code
stringlengths
1
2.08M
language
stringclasses
1 value
jQuery(document).ready(function($) { $('#the-list').on('click', '.delete-tag', function(e){ var t = $(this), tr = t.parents('tr'), r = true, data; if ( 'undefined' != showNotice ) r = showNotice.warn(); if ( r ) { data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag'); $.post(ajaxurl, data, function(r){ if ( '1' == r ) { $('#ajax-response').empty(); tr.fadeOut('normal', function(){ tr.remove(); }); // Remove the term from the parent box and tag cloud $('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove(); $('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove(); } else if ( '-1' == r ) { $('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>'); tr.children().css('backgroundColor', ''); } else { $('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>'); tr.children().css('backgroundColor', ''); } }); tr.children().css('backgroundColor', '#f33'); } return false; }); $('#submit').click(function(){ var form = $(this).parents('form'); if ( !validateForm( form ) ) return false; $.post(ajaxurl, $('#addtag').serialize(), function(r){ $('#ajax-response').empty(); var res = wpAjax.parseAjaxResponse(r, 'ajax-response'); if ( ! res || res.errors ) return; var parent = form.find('select#parent').val(); if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list. $('.tags #tag-' + parent).after( res.responses[0].supplemental['noparents'] ); // As the parent exists, Insert the version with - - - prefixed else $('.tags').prepend( res.responses[0].supplemental['parents'] ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm $('.tags .no-items').remove(); if ( form.find('select#parent') ) { // Parents field exists, Add new term to the list. var term = res.responses[1].supplemental; // Create an indent for the Parent field var indent = ''; for ( var i = 0; i < res.responses[1].position; i++ ) indent += '&nbsp;&nbsp;&nbsp;'; form.find('select#parent option:selected').after('<option value="' + term['term_id'] + '">' + indent + term['name'] + '</option>'); } $('input[type="text"]:visible, textarea:visible', form).val(''); }); return false; }); });
JavaScript
var switchEditors = { switchto: function(el) { var aid = el.id, l = aid.length, id = aid.substr(0, l - 5), mode = aid.substr(l - 4); this.go(id, mode); }, go: function(id, mode) { // mode can be 'html', 'tmce', or 'toggle'; 'html' is used for the "Text" editor tab. id = id || 'content'; mode = mode || 'toggle'; var t = this, ed = tinyMCE.get(id), wrap_id, txtarea_el, dom = tinymce.DOM; wrap_id = 'wp-'+id+'-wrap'; txtarea_el = dom.get(id); if ( 'toggle' == mode ) { if ( ed && !ed.isHidden() ) mode = 'html'; else mode = 'tmce'; } if ( 'tmce' == mode || 'tinymce' == mode ) { if ( ed && ! ed.isHidden() ) return false; if ( typeof(QTags) != 'undefined' ) QTags.closeAllTags(id); if ( tinyMCEPreInit.mceInit[id] && tinyMCEPreInit.mceInit[id].wpautop ) txtarea_el.value = t.wpautop( txtarea_el.value ); if ( ed ) { ed.show(); } else { ed = new tinymce.Editor(id, tinyMCEPreInit.mceInit[id]); ed.render(); } dom.removeClass(wrap_id, 'html-active'); dom.addClass(wrap_id, 'tmce-active'); setUserSetting('editor', 'tinymce'); } else if ( 'html' == mode ) { if ( ed && ed.isHidden() ) return false; if ( ed ) { ed.hide(); } else { // The TinyMCE instance doesn't exist, run the content through "pre_wpautop()" and show the textarea if ( tinyMCEPreInit.mceInit[id] && tinyMCEPreInit.mceInit[id].wpautop ) txtarea_el.value = t.pre_wpautop( txtarea_el.value ); dom.setStyles(txtarea_el, {'display': '', 'visibility': ''}); } dom.removeClass(wrap_id, 'tmce-active'); dom.addClass(wrap_id, 'html-active'); setUserSetting('editor', 'html'); } return false; }, _wp_Nop : function(content) { var blocklist1, blocklist2, preserve_linebreaks = false, preserve_br = false; // Protect pre|script tags if ( content.indexOf('<pre') != -1 || content.indexOf('<script') != -1 ) { preserve_linebreaks = true; content = content.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) { a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp-temp-lb>'); return a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-temp-lb>'); }); } // keep <br> tags inside captions and remove line breaks if ( content.indexOf('[caption') != -1 ) { preserve_br = true; content = content.replace(/\[caption[\s\S]+?\[\/caption\]/g, function(a) { return a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>').replace(/[\r\n\t]+/, ''); }); } // Pretty it up for the source editor blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|div|h[1-6]|p|fieldset'; content = content.replace(new RegExp('\\s*</('+blocklist1+')>\\s*', 'g'), '</$1>\n'); content = content.replace(new RegExp('\\s*<((?:'+blocklist1+')(?: [^>]*)?)>', 'g'), '\n<$1>'); // Mark </p> if it has any attributes. content = content.replace(/(<p [^>]+>.*?)<\/p>/g, '$1</p#>'); // Sepatate <div> containing <p> content = content.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n'); // Remove <p> and <br /> content = content.replace(/\s*<p>/gi, ''); content = content.replace(/\s*<\/p>\s*/gi, '\n\n'); content = content.replace(/\n[\s\u00a0]+\n/g, '\n\n'); content = content.replace(/\s*<br ?\/?>\s*/gi, '\n'); // Fix some block element newline issues content = content.replace(/\s*<div/g, '\n<div'); content = content.replace(/<\/div>\s*/g, '</div>\n'); content = content.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n'); content = content.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption'); blocklist2 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|h[1-6]|pre|fieldset'; content = content.replace(new RegExp('\\s*<((?:'+blocklist2+')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>'); content = content.replace(new RegExp('\\s*</('+blocklist2+')>\\s*', 'g'), '</$1>\n'); content = content.replace(/<li([^>]*)>/g, '\t<li$1>'); if ( content.indexOf('<hr') != -1 ) { content = content.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n'); } if ( content.indexOf('<object') != -1 ) { content = content.replace(/<object[\s\S]+?<\/object>/g, function(a){ return a.replace(/[\r\n]+/g, ''); }); } // Unmark special paragraph closing tags content = content.replace(/<\/p#>/g, '</p>\n'); content = content.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1'); // Trim whitespace content = content.replace(/^\s+/, ''); content = content.replace(/[\s\u00a0]+$/, ''); // put back the line breaks in pre|script if ( preserve_linebreaks ) content = content.replace(/<wp-temp-lb>/g, '\n'); // and the <br> tags in captions if ( preserve_br ) content = content.replace(/<wp-temp-br([^>]*)>/g, '<br$1>'); return content; }, _wp_Autop : function(pee) { var preserve_linebreaks = false, preserve_br = false, blocklist = 'table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary'; if ( pee.indexOf('<object') != -1 ) { pee = pee.replace(/<object[\s\S]+?<\/object>/g, function(a){ return a.replace(/[\r\n]+/g, ''); }); } pee = pee.replace(/<[^<>]+>/g, function(a){ return a.replace(/[\r\n]+/g, ' '); }); // Protect pre|script tags if ( pee.indexOf('<pre') != -1 || pee.indexOf('<script') != -1 ) { preserve_linebreaks = true; pee = pee.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) { return a.replace(/(\r\n|\n)/g, '<wp-temp-lb>'); }); } // keep <br> tags inside captions and convert line breaks if ( pee.indexOf('[caption') != -1 ) { preserve_br = true; pee = pee.replace(/\[caption[\s\S]+?\[\/caption\]/g, function(a) { // keep existing <br> a = a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>'); // no line breaks inside HTML tags a = a.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(b){ return b.replace(/[\r\n\t]+/, ' '); }); // convert remaining line breaks to <br> return a.replace(/\s*\n\s*/g, '<wp-temp-br />'); }); } pee = pee + '\n\n'; pee = pee.replace(/<br \/>\s*<br \/>/gi, '\n\n'); pee = pee.replace(new RegExp('(<(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), '\n$1'); pee = pee.replace(new RegExp('(</(?:'+blocklist+')>)', 'gi'), '$1\n\n'); pee = pee.replace(/<hr( [^>]*)?>/gi, '<hr$1>\n\n'); // hr is self closing block element pee = pee.replace(/\r\n|\r/g, '\n'); pee = pee.replace(/\n\s*\n+/g, '\n\n'); pee = pee.replace(/([\s\S]+?)\n\n/g, '<p>$1</p>\n'); pee = pee.replace(/<p>\s*?<\/p>/gi, ''); pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1"); pee = pee.replace(/<p>(<li.+?)<\/p>/gi, '$1'); pee = pee.replace(/<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>'); pee = pee.replace(/<\/blockquote>\s*<\/p>/gi, '</p></blockquote>'); pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), "$1"); pee = pee.replace(new RegExp('(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1"); pee = pee.replace(/\s*\n/gi, '<br />\n'); pee = pee.replace(new RegExp('(</?(?:'+blocklist+')[^>]*>)\\s*<br />', 'gi'), "$1"); pee = pee.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1'); pee = pee.replace(/(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]'); pee = pee.replace(/(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g, function(a, b, c) { if ( c.match(/<p( [^>]*)?>/) ) return a; return b + '<p>' + c + '</p>'; }); // put back the line breaks in pre|script if ( preserve_linebreaks ) pee = pee.replace(/<wp-temp-lb>/g, '\n'); if ( preserve_br ) pee = pee.replace(/<wp-temp-br([^>]*)>/g, '<br$1>'); return pee; }, pre_wpautop : function(content) { var t = this, o = { o: t, data: content, unfiltered: content }, q = typeof(jQuery) != 'undefined'; if ( q ) jQuery('body').trigger('beforePreWpautop', [o]); o.data = t._wp_Nop(o.data); if ( q ) jQuery('body').trigger('afterPreWpautop', [o]); return o.data; }, wpautop : function(pee) { var t = this, o = { o: t, data: pee, unfiltered: pee }, q = typeof(jQuery) != 'undefined'; if ( q ) jQuery('body').trigger('beforeWpautop', [o]); o.data = t._wp_Autop(o.data); if ( q ) jQuery('body').trigger('afterWpautop', [o]); return o.data; } }
JavaScript
var theList, theExtraList, toggleWithKeyboard = false; (function($) { var getCount, updateCount, updatePending, dashboardTotals; setCommentsList = function() { var totalInput, perPageInput, pageInput, lastConfidentTime = 0, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList; totalInput = $('input[name="_total"]', '#comments-form'); perPageInput = $('input[name="_per_page"]', '#comments-form'); pageInput = $('input[name="_page"]', '#comments-form'); dimAfter = function( r, settings ) { var c = $('#' + settings.element), editRow, replyID, replyButton; editRow = $('#replyrow'); replyID = $('#comment_ID', editRow).val(); replyButton = $('#replybtn', editRow); if ( c.is('.unapproved') ) { if ( settings.data.id == replyID ) replyButton.text(adminCommentsL10n.replyApprove); c.find('div.comment_status').html('0'); } else { if ( settings.data.id == replyID ) replyButton.text(adminCommentsL10n.reply); c.find('div.comment_status').html('1'); } var diff = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1; updatePending( diff ); }; // Send current total, page, per_page and url delBefore = function( settings, list ) { var wpListsData = $(settings.target).attr('data-wp-lists'), id, el, n, h, a, author, action = false; settings.data._total = totalInput.val() || 0; settings.data._per_page = perPageInput.val() || 0; settings.data._page = pageInput.val() || 0; settings.data._url = document.location.href; settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val(); if ( wpListsData.indexOf(':trash=1') != -1 ) action = 'trash'; else if ( wpListsData.indexOf(':spam=1') != -1 ) action = 'spam'; if ( action ) { id = wpListsData.replace(/.*?comment-([0-9]+).*/, '$1'); el = $('#comment-' + id); note = $('#' + action + '-undo-holder').html(); el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits. if ( el.siblings('#replyrow').length && commentReply.cid == id ) commentReply.close(); if ( el.is('tr') ) { n = el.children(':visible').length; author = $('.author strong', el).text(); h = $('<tr id="undo-' + id + '" class="undo un' + action + '" style="display:none;"><td colspan="' + n + '">' + note + '</td></tr>'); } else { author = $('.comment-author', el).text(); h = $('<div id="undo-' + id + '" style="display:none;" class="undo un' + action + '">' + note + '</div>'); } el.before(h); $('strong', '#undo-' + id).text(author); a = $('.undo a', '#undo-' + id); a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce); a.attr('data-wp-lists', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1'); a.attr('class', 'vim-z vim-destructive'); $('.avatar', el).clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside'); a.click(function(){ list.wpList.del(this); $('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){ $(this).remove(); $('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show() }); }); return false; }); } return settings; }; // Updates the current total (stored in the _total input) updateTotalCount = function( total, time, setConfidentTime ) { if ( time < lastConfidentTime ) return; if ( setConfidentTime ) lastConfidentTime = time; totalInput.val( total.toString() ); }; dashboardTotals = function(n) { var dash = $('#dashboard_right_now'), total, appr, totalN, apprN; n = n || 0; if ( isNaN(n) || !dash.length ) return; total = $('span.total-count', dash); appr = $('span.approved-count', dash); totalN = getCount(total); totalN = totalN + n; apprN = totalN - getCount( $('span.pending-count', dash) ) - getCount( $('span.spam-count', dash) ); updateCount(total, totalN); updateCount(appr, apprN); }; getCount = function(el) { var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 ); if ( isNaN(n) ) return 0; return n; }; updateCount = function(el, n) { var n1 = ''; if ( isNaN(n) ) return; n = n < 1 ? '0' : n.toString(); if ( n.length > 3 ) { while ( n.length > 3 ) { n1 = thousandsSeparator + n.substr(n.length - 3) + n1; n = n.substr(0, n.length - 3); } n = n + n1; } el.html(n); }; updatePending = function( diff ) { $('span.pending-count').each(function() { var a = $(this), n = getCount(a) + diff; if ( n < 1 ) n = 0; a.closest('.awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0'); updateCount( a, n ); }); dashboardTotals(); }; // In admin-ajax.php, we send back the unix time stamp instead of 1 on success delAfter = function( r, settings ) { var total, N, spam, trash, pending, untrash = $(settings.target).parent().is('span.untrash'), unspam = $(settings.target).parent().is('span.unspam'), unapproved = $('#' + settings.element).is('.unapproved'); function getUpdate(s) { if ( $(settings.target).parent().is('span.' + s) ) return 1; else if ( $('#' + settings.element).is('.' + s) ) return -1; return 0; } if ( untrash ) trash = -1; else trash = getUpdate('trash'); if ( unspam ) spam = -1; else spam = getUpdate('spam'); if ( $(settings.target).parent().is('span.unapprove') || ( ( untrash || unspam ) && unapproved ) ) { // a comment was 'deleted' from another list (e.g. approved, spam, trash) and moved to pending, // or a trash/spam of a pending comment was undone pending = 1; } else if ( unapproved ) { // a pending comment was trashed/spammed/approved pending = -1; } if ( pending ) updatePending(pending); $('span.spam-count').each( function() { var a = $(this), n = getCount(a) + spam; updateCount(a, n); }); $('span.trash-count').each( function() { var a = $(this), n = getCount(a) + trash; updateCount(a, n); }); if ( $('#dashboard_right_now').length ) { N = trash ? -1 * trash : 0; dashboardTotals(N); } else { total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0; if ( $(settings.target).parent().is('span.undo') ) total++; else total--; if ( total < 0 ) total = 0; if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) { total_items_i18n = settings.parsed.responses[0].supplemental.total_items_i18n || ''; if ( total_items_i18n ) { $('.displaying-num').text( total_items_i18n ); $('.total-pages').text( settings.parsed.responses[0].supplemental.total_pages_i18n ); $('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', settings.parsed.responses[0].supplemental.total_pages == $('.current-page').val()); } updateTotalCount( total, settings.parsed.responses[0].supplemental.time, true ); } else { updateTotalCount( total, r, false ); } } if ( ! theExtraList || theExtraList.size() == 0 || theExtraList.children().size() == 0 || untrash || unspam ) { return; } theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() ); refillTheExtraList(); }; refillTheExtraList = function(ev) { var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val(); if (! args.paged) args.paged = 1; if (args.paged > total_pages) { return; } if (ev) { theExtraList.empty(); args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php } else { args.number = 1; args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list } args.no_placeholder = true; args.paged ++; // $.query.get() needs some correction to be sent into an ajax request if ( true === args.comment_type ) args.comment_type = ''; args = $.extend(args, { 'action': 'fetch-list', 'list_args': list_args, '_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val() }); $.ajax({ url: ajaxurl, global: false, dataType: 'json', data: args, success: function(response) { theExtraList.get(0).wpList.add( response.rows ); } }); }; theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } ); theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } ) .bind('wpListDelEnd', function(e, s){ var wpListsData = $(s.target).attr('data-wp-lists'), id = s.element.replace(/[^0-9]+/g, ''); if ( wpListsData.indexOf(':trash=1') != -1 || wpListsData.indexOf(':spam=1') != -1 ) $('#undo-' + id).fadeIn(300, function(){ $(this).show() }); }); }; commentReply = { cid : '', act : '', init : function() { var row = $('#replyrow'); $('a.cancel', row).click(function() { return commentReply.revert(); }); $('a.save', row).click(function() { return commentReply.send(); }); $('input#author, input#author-email, input#author-url', row).keypress(function(e){ if ( e.which == 13 ) { commentReply.send(); e.preventDefault(); return false; } }); // add events $('#the-comment-list .column-comment > p').dblclick(function(){ commentReply.toggle($(this).parent()); }); $('#doaction, #doaction2, #post-query-submit').click(function(e){ if ( $('#the-comment-list #replyrow').length > 0 ) commentReply.close(); }); this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || ''; /* $(listTable).bind('beforeChangePage', function(){ commentReply.close(); }); */ }, addEvents : function(r) { r.each(function() { $(this).find('.column-comment > p').dblclick(function(){ commentReply.toggle($(this).parent()); }); }); }, toggle : function(el) { if ( $(el).css('display') != 'none' ) $(el).find('a.vim-q').click(); }, revert : function() { if ( $('#the-comment-list #replyrow').length < 1 ) return false; $('#replyrow').fadeOut('fast', function(){ commentReply.close(); }); return false; }, close : function() { var c, replyrow = $('#replyrow'); // replyrow is not showing? if ( replyrow.parent().is('#com-reply') ) return; if ( this.cid && this.act == 'edit-comment' ) { c = $('#comment-' + this.cid); c.fadeIn(300, function(){ c.show() }).css('backgroundColor', ''); } // reset the Quicktags buttons if ( typeof QTags != 'undefined' ) QTags.closeAllTags('replycontent'); $('#add-new-comment').css('display', ''); replyrow.hide(); $('#com-reply').append( replyrow ); $('#replycontent').css('height', '').val(''); $('#edithead input').val(''); $('.error', replyrow).html('').hide(); $('.spinner', replyrow).hide(); this.cid = ''; }, open : function(comment_id, post_id, action) { var t = this, editRow, rowData, act, c = $('#comment-' + comment_id), h = c.height(), replyButton; t.close(); t.cid = comment_id; editRow = $('#replyrow'); rowData = $('#inline-'+comment_id); action = action || 'replyto'; act = 'edit' == action ? 'edit' : 'replyto'; act = t.act = act + '-comment'; $('#action', editRow).val(act); $('#comment_post_ID', editRow).val(post_id); $('#comment_ID', editRow).val(comment_id); if ( h > 120 ) $('#replycontent', editRow).css('height', (35+h) + 'px'); if ( action == 'edit' ) { $('#author', editRow).val( $('div.author', rowData).text() ); $('#author-email', editRow).val( $('div.author-email', rowData).text() ); $('#author-url', editRow).val( $('div.author-url', rowData).text() ); $('#status', editRow).val( $('div.comment_status', rowData).text() ); $('#replycontent', editRow).val( $('textarea.comment', rowData).val() ); $('#edithead, #savebtn', editRow).show(); $('#replyhead, #replybtn, #addhead, #addbtn', editRow).hide(); c.after( editRow ).fadeOut('fast', function(){ $('#replyrow').fadeIn(300, function(){ $(this).show() }); }); } else if ( action == 'add' ) { $('#addhead, #addbtn', editRow).show(); $('#replyhead, #replybtn, #edithead, #editbtn', editRow).hide(); $('#the-comment-list').prepend(editRow); $('#replyrow').fadeIn(300); } else { replyButton = $('#replybtn', editRow); $('#edithead, #savebtn, #addhead, #addbtn', editRow).hide(); $('#replyhead, #replybtn', editRow).show(); c.after(editRow); if ( c.hasClass('unapproved') ) { replyButton.text(adminCommentsL10n.replyApprove); } else { replyButton.text(adminCommentsL10n.reply); } $('#replyrow').fadeIn(300, function(){ $(this).show() }); } setTimeout(function() { var rtop, rbottom, scrollTop, vp, scrollBottom; rtop = $('#replyrow').offset().top; rbottom = rtop + $('#replyrow').height(); scrollTop = window.pageYOffset || document.documentElement.scrollTop; vp = document.documentElement.clientHeight || self.innerHeight || 0; scrollBottom = scrollTop + vp; if ( scrollBottom - 20 < rbottom ) window.scroll(0, rbottom - vp + 35); else if ( rtop - 20 < scrollTop ) window.scroll(0, rtop - 35); $('#replycontent').focus().keyup(function(e){ if ( e.which == 27 ) commentReply.revert(); // close on Escape }); }, 600); return false; }, send : function() { var post = {}; $('#replysubmit .error').hide(); $('#replysubmit .spinner').show(); $('#replyrow input').not(':button').each(function() { var t = $(this); post[ t.attr('name') ] = t.val(); }); post.content = $('#replycontent').val(); post.id = post.comment_post_ID; post.comments_listing = this.comments_listing; post.p = $('[name="p"]').val(); if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') ) post.approve_parent = 1; $.ajax({ type : 'POST', url : ajaxurl, data : post, success : function(x) { commentReply.show(x); }, error : function(r) { commentReply.error(r); } }); return false; }, show : function(xml) { var t = this, r, c, id, bg, pid; if ( typeof(xml) == 'string' ) { t.error({'responseText': xml}); return false; } r = wpAjax.parseAjaxResponse(xml); if ( r.errors ) { t.error({'responseText': wpAjax.broken}); return false; } t.revert(); r = r.responses[0]; c = r.data; id = '#comment-' + r.id; if ( 'edit-comment' == t.act ) $(id).remove(); if ( r.supplemental.parent_approved ) { pid = $('#comment-' + r.supplemental.parent_approved); updatePending( -1 ); if ( this.comments_listing == 'moderated' ) { pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){ pid.fadeOut(); }); return; } } $(c).hide() $('#replyrow').after(c); id = $(id); t.addEvents(id); bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat, .postbox').css('backgroundColor'); id.animate( { 'backgroundColor':'#CCEEBB' }, 300 ) .animate( { 'backgroundColor': bg }, 300, function() { if ( pid && pid.length ) { pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 ) .animate( { 'backgroundColor': bg }, 300 ) .removeClass('unapproved').addClass('approved') .find('div.comment_status').html('1'); } }); }, error : function(r) { var er = r.statusText; $('#replysubmit .spinner').hide(); if ( r.responseText ) er = r.responseText.replace( /<.[^<>]*?>/g, '' ); if ( er ) $('#replysubmit .error').html(er).show(); }, addcomment: function(post_id) { var t = this; $('#add-new-comment').fadeOut(200, function(){ t.open(0, post_id, 'add'); $('table.comments-box').css('display', ''); $('#no-comments').remove(); }); } }; $(document).ready(function(){ var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk; setCommentsList(); commentReply.init(); $(document).delegate('span.delete a.delete', 'click', function(){return false;}); if ( typeof $.table_hotkeys != 'undefined' ) { make_hotkeys_redirect = function(which) { return function() { var first_last, l; first_last = 'next' == which? 'first' : 'last'; l = $('.tablenav-pages .'+which+'-page:not(.disabled)'); if (l.length) window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1'; } }; edit_comment = function(event, current_row) { window.location = $('span.edit a', current_row).attr('href'); }; toggle_all = function() { toggleWithKeyboard = true; $('input:checkbox', '#cb').click().prop('checked', false); toggleWithKeyboard = false; }; make_bulk = function(value) { return function() { var scope = $('select[name="action"]'); $('option[value="' + value + '"]', scope).prop('selected', true); $('#doaction').click(); } }; $.table_hotkeys( $('table.widefat'), ['a', 'u', 's', 'd', 'r', 'q', 'z', ['e', edit_comment], ['shift+x', toggle_all], ['shift+a', make_bulk('approve')], ['shift+s', make_bulk('spam')], ['shift+d', make_bulk('delete')], ['shift+t', make_bulk('trash')], ['shift+z', make_bulk('untrash')], ['shift+u', make_bulk('unapprove')]], { highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last, prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next') } ); } }); })(jQuery);
JavaScript
jQuery(document).ready( function($) { $('#link_rel').prop('readonly', true); $('#linkxfndiv input').bind('click keyup', function() { var isMe = $('#me').is(':checked'), inputs = ''; $('input.valinp').each( function() { if (isMe) { $(this).prop('disabled', true).parent().addClass('disabled'); } else { $(this).removeAttr('disabled').parent().removeClass('disabled'); if ( $(this).is(':checked') && $(this).val() != '') inputs += $(this).val() + ' '; } }); $('#link_rel').val( (isMe) ? 'me' : inputs.substr(0,inputs.length - 1) ); }); });
JavaScript
(function( exports, $ ){ var api = wp.customize; /* * @param options * - previewer - The Previewer instance to sync with. * - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'. */ api.Setting = api.Value.extend({ initialize: function( id, value, options ) { var element; api.Value.prototype.initialize.call( this, value, options ); this.id = id; this.transport = this.transport || 'refresh'; this.bind( this.preview ); }, preview: function() { switch ( this.transport ) { case 'refresh': return this.previewer.refresh(); case 'postMessage': return this.previewer.send( 'setting', [ this.id, this() ] ); } } }); api.Control = api.Class.extend({ initialize: function( id, options ) { var control = this, nodes, radios, settings; this.params = {}; $.extend( this, options || {} ); this.id = id; this.selector = '#customize-control-' + id.replace( ']', '' ).replace( '[', '-' ); this.container = $( this.selector ); settings = $.map( this.params.settings, function( value ) { return value; }); api.apply( api, settings.concat( function() { var key; control.settings = {}; for ( key in control.params.settings ) { control.settings[ key ] = api( control.params.settings[ key ] ); } control.setting = control.settings['default'] || null; control.ready(); }) ); control.elements = []; nodes = this.container.find('[data-customize-setting-link]'); radios = {}; nodes.each( function() { var node = $(this), name; if ( node.is(':radio') ) { name = node.prop('name'); if ( radios[ name ] ) return; radios[ name ] = true; node = nodes.filter( '[name="' + name + '"]' ); } api( node.data('customizeSettingLink'), function( setting ) { var element = new api.Element( node ); control.elements.push( element ); element.sync( setting ); element.set( setting() ); }); }); }, ready: function() {}, dropdownInit: function() { var control = this, statuses = this.container.find('.dropdown-status'), params = this.params, update = function( to ) { if ( typeof to === 'string' && params.statuses && params.statuses[ to ] ) statuses.html( params.statuses[ to ] ).show(); else statuses.hide(); }; var toggleFreeze = false; // Support the .dropdown class to open/close complex elements this.container.on( 'click keydown', '.dropdown', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; event.preventDefault(); if (!toggleFreeze) control.container.toggleClass('open'); if ( control.container.hasClass('open') ) control.container.parent().parent().find('li.library-selected').focus(); // Don't want to fire focus and click at same time toggleFreeze = true; setTimeout(function () { toggleFreeze = false; }, 400); }); this.setting.bind( update ); update( this.setting() ); } }); api.ColorControl = api.Control.extend({ ready: function() { var control = this, picker = this.container.find('.color-picker-hex'); picker.val( control.setting() ).wpColorPicker({ change: function( event, options ) { control.setting.set( picker.wpColorPicker('color') ); }, clear: function() { control.setting.set( false ); } }); } }); api.UploadControl = api.Control.extend({ ready: function() { var control = this; this.params.removed = this.params.removed || ''; this.success = $.proxy( this.success, this ); this.uploader = $.extend({ container: this.container, browser: this.container.find('.upload'), dropzone: this.container.find('.upload-dropzone'), success: this.success, plupload: {}, params: {} }, this.uploader || {} ); if ( control.params.extensions ) { control.uploader.plupload.filters = [{ title: api.l10n.allowedFiles, extensions: control.params.extensions }]; } if ( control.params.context ) control.uploader.params['post_data[context]'] = this.params.context; if ( api.settings.theme.stylesheet ) control.uploader.params['post_data[theme]'] = api.settings.theme.stylesheet; this.uploader = new wp.Uploader( this.uploader ); this.remover = this.container.find('.remove'); this.remover.on( 'click keydown', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; control.setting.set( control.params.removed ); event.preventDefault(); }); this.removerVisibility = $.proxy( this.removerVisibility, this ); this.setting.bind( this.removerVisibility ); this.removerVisibility( this.setting.get() ); }, success: function( attachment ) { this.setting.set( attachment.get('url') ); }, removerVisibility: function( to ) { this.remover.toggle( to != this.params.removed ); } }); api.ImageControl = api.UploadControl.extend({ ready: function() { var control = this, panels; this.uploader = { init: function( up ) { var fallback, button; if ( this.supports.dragdrop ) return; // Maintain references while wrapping the fallback button. fallback = control.container.find( '.upload-fallback' ); button = fallback.children().detach(); this.browser.detach().empty().append( button ); fallback.append( this.browser ).show(); } }; api.UploadControl.prototype.ready.call( this ); this.thumbnail = this.container.find('.preview-thumbnail img'); this.thumbnailSrc = $.proxy( this.thumbnailSrc, this ); this.setting.bind( this.thumbnailSrc ); this.library = this.container.find('.library'); // Generate tab objects this.tabs = {}; panels = this.library.find('.library-content'); this.library.children('ul').children('li').each( function() { var link = $(this), id = link.data('customizeTab'), panel = panels.filter('[data-customize-tab="' + id + '"]'); control.tabs[ id ] = { both: link.add( panel ), link: link, panel: panel }; }); // Bind tab switch events this.library.children('ul').on( 'click keydown', 'li', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; var id = $(this).data('customizeTab'), tab = control.tabs[ id ]; event.preventDefault(); if ( tab.link.hasClass('library-selected') ) return; control.selected.both.removeClass('library-selected'); control.selected = tab; control.selected.both.addClass('library-selected'); }); // Bind events to switch image urls. this.library.on( 'click keydown', 'a', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; var value = $(this).data('customizeImageValue'); if ( value ) { control.setting.set( value ); event.preventDefault(); } }); if ( this.tabs.uploaded ) { this.tabs.uploaded.target = this.library.find('.uploaded-target'); if ( ! this.tabs.uploaded.panel.find('.thumbnail').length ) this.tabs.uploaded.both.addClass('hidden'); } // Select a tab panels.each( function() { var tab = control.tabs[ $(this).data('customizeTab') ]; // Select the first visible tab. if ( ! tab.link.hasClass('hidden') ) { control.selected = tab; tab.both.addClass('library-selected'); return false; } }); this.dropdownInit(); }, success: function( attachment ) { api.UploadControl.prototype.success.call( this, attachment ); // Add the uploaded image to the uploaded tab. if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) { this.tabs.uploaded.both.removeClass('hidden'); // @todo: Do NOT store this on the attachment model. That is bad. attachment.element = $( '<a href="#" class="thumbnail"></a>' ) .data( 'customizeImageValue', attachment.get('url') ) .append( '<img src="' + attachment.get('url')+ '" />' ) .appendTo( this.tabs.uploaded.target ); } }, thumbnailSrc: function( to ) { if ( /^(https?:)?\/\//.test( to ) ) this.thumbnail.prop( 'src', to ).show(); else this.thumbnail.hide(); } }); // Change objects contained within the main customize object to Settings. api.defaultConstructor = api.Setting; // Create the collection of Control objects. api.control = new api.Values({ defaultConstructor: api.Control }); api.PreviewFrame = api.Messenger.extend({ sensitivity: 2000, initialize: function( params, options ) { var deferred = $.Deferred(), self = this; // This is the promise object. deferred.promise( this ); this.container = params.container; this.signature = params.signature; $.extend( params, { channel: api.PreviewFrame.uuid() }); api.Messenger.prototype.initialize.call( this, params, options ); this.add( 'previewUrl', params.previewUrl ); this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() }); this.run( deferred ); }, run: function( deferred ) { var self = this, loaded = false, ready = false; if ( this._ready ) this.unbind( 'ready', this._ready ); this._ready = function() { ready = true; if ( loaded ) deferred.resolveWith( self ); }; this.bind( 'ready', this._ready ); this.request = $.ajax( this.previewUrl(), { type: 'POST', data: this.query, xhrFields: { withCredentials: true } } ); this.request.fail( function() { deferred.rejectWith( self, [ 'request failure' ] ); }); this.request.done( function( response ) { var location = self.request.getResponseHeader('Location'), signature = self.signature, index; // Check if the location response header differs from the current URL. // If so, the request was redirected; try loading the requested page. if ( location && location != self.previewUrl() ) { deferred.rejectWith( self, [ 'redirect', location ] ); return; } // Check if the user is not logged in. if ( '0' === response ) { self.login( deferred ); return; } // Check for cheaters. if ( '-1' === response ) { deferred.rejectWith( self, [ 'cheatin' ] ); return; } // Check for a signature in the request. index = response.lastIndexOf( signature ); if ( -1 === index || index < response.lastIndexOf('</html>') ) { deferred.rejectWith( self, [ 'unsigned' ] ); return; } // Strip the signature from the request. response = response.slice( 0, index ) + response.slice( index + signature.length ); // Create the iframe and inject the html content. self.iframe = $('<iframe />').appendTo( self.container ); // Bind load event after the iframe has been added to the page; // otherwise it will fire when injected into the DOM. self.iframe.one( 'load', function() { loaded = true; if ( ready ) { deferred.resolveWith( self ); } else { setTimeout( function() { deferred.rejectWith( self, [ 'ready timeout' ] ); }, self.sensitivity ); } }); self.targetWindow( self.iframe[0].contentWindow ); self.targetWindow().document.open(); self.targetWindow().document.write( response ); self.targetWindow().document.close(); }); }, login: function( deferred ) { var self = this, reject; reject = function() { deferred.rejectWith( self, [ 'logged out' ] ); }; if ( this.triedLogin ) return reject(); // Check if we have an admin cookie. $.get( api.settings.url.ajax, { action: 'logged-in' }).fail( reject ).done( function( response ) { var iframe; if ( '1' !== response ) reject(); iframe = $('<iframe src="' + self.previewUrl() + '" />').hide(); iframe.appendTo( self.container ); iframe.load( function() { self.triedLogin = true; iframe.remove(); self.run( deferred ); }); }); }, destroy: function() { api.Messenger.prototype.destroy.call( this ); this.request.abort(); if ( this.iframe ) this.iframe.remove(); delete this.request; delete this.iframe; delete this.targetWindow; } }); (function(){ var uuid = 0; api.PreviewFrame.uuid = function() { return 'preview-' + uuid++; }; }()); api.Previewer = api.Messenger.extend({ refreshBuffer: 250, /** * Requires params: * - container - a selector or jQuery element * - previewUrl - the URL of preview frame */ initialize: function( params, options ) { var self = this, rscheme = /^https?/, url; $.extend( this, options || {} ); /* * Wrap this.refresh to prevent it from hammering the servers: * * If refresh is called once and no other refresh requests are * loading, trigger the request immediately. * * If refresh is called while another refresh request is loading, * debounce the refresh requests: * 1. Stop the loading request (as it is instantly outdated). * 2. Trigger the new request once refresh hasn't been called for * self.refreshBuffer milliseconds. */ this.refresh = (function( self ) { var refresh = self.refresh, callback = function() { timeout = null; refresh.call( self ); }, timeout; return function() { if ( typeof timeout !== 'number' ) { if ( self.loading ) { self.abort(); } else { return callback(); } } clearTimeout( timeout ); timeout = setTimeout( callback, self.refreshBuffer ); }; })( this ); this.container = api.ensure( params.container ); this.allowedUrls = params.allowedUrls; this.signature = params.signature; params.url = window.location.href; api.Messenger.prototype.initialize.call( this, params ); this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) { var match = to.match( rscheme ); return match ? match[0] : ''; }); // Limit the URL to internal, front-end links. // // If the frontend and the admin are served from the same domain, load the // preview over ssl if the customizer is being loaded over ssl. This avoids // insecure content warnings. This is not attempted if the admin and frontend // are on different domains to avoid the case where the frontend doesn't have // ssl certs. this.add( 'previewUrl', params.previewUrl ).setter( function( to ) { var result; // Check for URLs that include "/wp-admin/" or end in "/wp-admin". // Strip hashes and query strings before testing. if ( /\/wp-admin(\/|$)/.test( to.replace(/[#?].*$/, '') ) ) return null; // Attempt to match the URL to the control frame's scheme // and check if it's allowed. If not, try the original URL. $.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) { $.each( self.allowedUrls, function( i, allowed ) { if ( 0 === url.indexOf( allowed ) ) { result = url; return false; } }); if ( result ) return false; }); // If we found a matching result, return it. If not, bail. return result ? result : null; }); // Refresh the preview when the URL is changed (but not yet). this.previewUrl.bind( this.refresh ); this.scroll = 0; this.bind( 'scroll', function( distance ) { this.scroll = distance; }); // Update the URL when the iframe sends a URL message. this.bind( 'url', this.previewUrl ); }, query: function() {}, abort: function() { if ( this.loading ) { this.loading.destroy(); delete this.loading; } }, refresh: function() { var self = this; this.abort(); this.loading = new api.PreviewFrame({ url: this.url(), previewUrl: this.previewUrl(), query: this.query() || {}, container: this.container, signature: this.signature }); this.loading.done( function() { // 'this' is the loading frame this.bind( 'synced', function() { if ( self.preview ) self.preview.destroy(); self.preview = this; delete self.loading; self.targetWindow( this.targetWindow() ); self.channel( this.channel() ); self.send( 'active' ); }); this.send( 'sync', { scroll: self.scroll, settings: api.get() }); }); this.loading.fail( function( reason, location ) { if ( 'redirect' === reason && location ) self.previewUrl( location ); if ( 'logged out' === reason ) { if ( self.preview ) { self.preview.destroy(); delete self.preview; } self.login().done( self.refresh ); } if ( 'cheatin' === reason ) self.cheatin(); }); }, login: function() { var previewer = this, deferred, messenger, iframe; if ( this._login ) return this._login; deferred = $.Deferred(); this._login = deferred.promise(); messenger = new api.Messenger({ channel: 'login', url: api.settings.url.login }); iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container ); messenger.targetWindow( iframe[0].contentWindow ); messenger.bind( 'login', function() { iframe.remove(); messenger.destroy(); delete previewer._login; deferred.resolve(); }); return this._login; }, cheatin: function() { $( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' ); } }); /* ===================================================================== * Ready. * ===================================================================== */ api.controlConstructor = { color: api.ColorControl, upload: api.UploadControl, image: api.ImageControl }; $( function() { api.settings = window._wpCustomizeSettings; api.l10n = window._wpCustomizeControlsL10n; // Check if we can run the customizer. if ( ! api.settings ) return; // Redirect to the fallback preview if any incompatibilities are found. if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) ) return window.location = api.settings.url.fallback; var body = $( document.body ), overlay = body.children('.wp-full-overlay'), query, previewer, parent; // Prevent the form from saving when enter is pressed. $('#customize-controls').on( 'keydown', function( e ) { if ( $( e.target ).is('textarea') ) return; if ( 13 === e.which ) // Enter e.preventDefault(); }); // Initialize Previewer previewer = new api.Previewer({ container: '#customize-preview', form: '#customize-controls', previewUrl: api.settings.url.preview, allowedUrls: api.settings.url.allowed, signature: 'WP_CUSTOMIZER_SIGNATURE' }, { nonce: api.settings.nonce, query: function() { return { wp_customize: 'on', theme: api.settings.theme.stylesheet, customized: JSON.stringify( api.get() ), nonce: this.nonce.preview }; }, save: function() { var self = this, query = $.extend( this.query(), { action: 'customize_save', nonce: this.nonce.save }), request = $.post( api.settings.url.ajax, query ); api.trigger( 'save', request ); body.addClass('saving'); request.always( function() { body.removeClass('saving'); }); request.done( function( response ) { // Check if the user is logged out. if ( '0' === response ) { self.preview.iframe.hide(); self.login().done( function() { self.save(); self.preview.iframe.show(); }); return; } // Check for cheaters. if ( '-1' === response ) { self.cheatin(); return; } api.trigger( 'saved' ); }); } }); // Refresh the nonces if the preview sends updated nonces over. previewer.bind( 'nonce', function( nonce ) { $.extend( this.nonce, nonce ); }); $.each( api.settings.settings, function( id, data ) { api.create( id, id, data.value, { transport: data.transport, previewer: previewer } ); }); $.each( api.settings.controls, function( id, data ) { var constructor = api.controlConstructor[ data.type ] || api.Control, control; control = api.control.add( id, new constructor( id, { params: data, previewer: previewer } ) ); }); // Check if preview url is valid and load the preview frame. if ( previewer.previewUrl() ) previewer.refresh(); else previewer.previewUrl( api.settings.url.home ); // Save and activated states (function() { var state = new api.Values(), saved = state.create('saved'), activated = state.create('activated'); state.bind( 'change', function() { var save = $('#save'), back = $('.back'); if ( ! activated() ) { save.val( api.l10n.activate ).prop( 'disabled', false ); back.text( api.l10n.cancel ); } else if ( saved() ) { save.val( api.l10n.saved ).prop( 'disabled', true ); back.text( api.l10n.close ); } else { save.val( api.l10n.save ).prop( 'disabled', false ); back.text( api.l10n.cancel ); } }); // Set default states. saved( true ); activated( api.settings.theme.active ); api.bind( 'change', function() { state('saved').set( false ); }); api.bind( 'saved', function() { state('saved').set( true ); state('activated').set( true ); }); activated.bind( function( to ) { if ( to ) api.trigger( 'activated' ); }); // Expose states to the API. api.state = state; }()); // Button bindings. $('#save').click( function( event ) { previewer.save(); event.preventDefault(); }).keydown( function( event ) { if ( 9 === event.which ) // tab return; if ( 13 === event.which ) // enter previewer.save(); event.preventDefault(); }); $('.back').keydown( function( event ) { if ( 9 === event.which ) // tab return; if ( 13 === event.which ) // enter parent.send( 'close' ); event.preventDefault(); }); $('.upload-dropzone a.upload').keydown( function( event ) { if ( 13 === event.which ) // enter this.click(); }); $('.collapse-sidebar').on( 'click keydown', function( event ) { if ( event.type === 'keydown' && 13 !== event.which ) // enter return; overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' ); event.preventDefault(); }); // Create a potential postMessage connection with the parent frame. parent = new api.Messenger({ url: api.settings.url.parent, channel: 'loader' }); // If we receive a 'back' event, we're inside an iframe. // Send any clicks to the 'Return' link to the parent page. parent.bind( 'back', function() { $('.back').on( 'click.back', function( event ) { event.preventDefault(); parent.send( 'close' ); }); }); // Pass events through to the parent. api.bind( 'saved', function() { parent.send( 'saved' ); }); // When activated, let the loader handle redirecting the page. // If no loader exists, redirect the page ourselves (if a url exists). api.bind( 'activated', function() { if ( parent.targetWindow() ) parent.send( 'activated', api.settings.url.activated ); else if ( api.settings.url.activated ) window.location = api.settings.url.activated; }); // Initialize the connection with the parent frame. parent.send( 'ready' ); // Control visibility for default controls $.each({ 'background_image': { controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ], callback: function( to ) { return !! to } }, 'show_on_front': { controls: [ 'page_on_front', 'page_for_posts' ], callback: function( to ) { return 'page' === to } }, 'header_textcolor': { controls: [ 'header_textcolor' ], callback: function( to ) { return 'blank' !== to } } }, function( settingId, o ) { api( settingId, function( setting ) { $.each( o.controls, function( i, controlId ) { api.control( controlId, function( control ) { var visibility = function( to ) { control.container.toggle( o.callback( to ) ); }; visibility( setting.get() ); setting.bind( visibility ); }); }); }); }); // Juggle the two controls that use header_textcolor api.control( 'display_header_text', function( control ) { var last = ''; control.elements[0].unsync( api( 'header_textcolor' ) ); control.element = new api.Element( control.container.find('input') ); control.element.set( 'blank' !== control.setting() ); control.element.bind( function( to ) { if ( ! to ) last = api( 'header_textcolor' ).get(); control.setting.set( to ? last : 'blank' ); }); control.setting.bind( function( to ) { control.element.set( 'blank' !== to ); }); }); // Handle header image data api.control( 'header_image', function( control ) { control.setting.bind( function( to ) { if ( to === control.params.removed ) control.settings.data.set( false ); }); control.library.on( 'click', 'a', function( event ) { control.settings.data.set( $(this).data('customizeHeaderImageData') ); }); control.uploader.success = function( attachment ) { var data; api.ImageControl.prototype.success.call( control, attachment ); data = { attachment_id: attachment.get('id'), url: attachment.get('url'), thumbnail_url: attachment.get('url'), height: attachment.get('height'), width: attachment.get('width') }; attachment.element.data( 'customizeHeaderImageData', data ); control.settings.data.set( data ); }; }); api.trigger( 'ready' ); // Make sure left column gets focus var topFocus = $('.back'); topFocus.focus(); setTimeout(function () { topFocus.focus(); }, 200); }); })( wp, jQuery );
JavaScript
( function( $ ){ $( document ).ready( function () { // Expand/Collapse on click $( '.accordion-container' ).on( 'click keydown', '.accordion-section-title', function( e ) { if ( e.type === 'keydown' && 13 !== e.which ) // "return" key return; e.preventDefault(); // Keep this AFTER the key filter above accordionSwitch( $( this ) ); }); // Re-initialize accordion when screen options are toggled $( '.hide-postbox-tog' ).click( function () { accordionInit(); }); }); var accordionOptions = $( '.accordion-container li.accordion-section' ), sectionContent = $( '.accordion-section-content' ); function accordionInit () { // Rounded corners accordionOptions.removeClass( 'top bottom' ); accordionOptions.filter( ':visible' ).first().addClass( 'top' ); accordionOptions.filter( ':visible' ).last().addClass( 'bottom' ).find( sectionContent ).addClass( 'bottom' ); } function accordionSwitch ( el ) { var section = el.closest( '.accordion-section' ), siblings = section.closest( '.accordion-container' ).find( '.open' ), content = section.find( sectionContent ); if ( section.hasClass( 'cannot-expand' ) ) return; if ( section.hasClass( 'open' ) ) { section.toggleClass( 'open' ); content.toggle( true ).slideToggle( 150 ); } else { siblings.removeClass( 'open' ); siblings.find( sectionContent ).show().slideUp( 150 ); content.toggle( false ).slideToggle( 150 ); section.toggleClass( 'open' ); } accordionInit(); } // Initialize the accordion (currently just corner fixes) accordionInit(); })(jQuery);
JavaScript
var thickDims, tbWidth, tbHeight; jQuery(document).ready(function($) { thickDims = function() { var tbWindow = $('#TB_window'), H = $(window).height(), W = $(window).width(), w, h; w = (tbWidth && tbWidth < W - 90) ? tbWidth : W - 90; h = (tbHeight && tbHeight < H - 60) ? tbHeight : H - 60; if ( tbWindow.size() ) { tbWindow.width(w).height(h); $('#TB_iframeContent').width(w).height(h - 27); tbWindow.css({'margin-left': '-' + parseInt((w / 2),10) + 'px'}); if ( typeof document.body.style.maxWidth != 'undefined' ) tbWindow.css({'top':'30px','margin-top':'0'}); } }; thickDims(); $(window).resize( function() { thickDims() } ); $('a.thickbox-preview').click( function() { tb_click.call(this); var alink = $(this).parents('.available-theme').find('.activatelink'), link = '', href = $(this).attr('href'), url, text; if ( tbWidth = href.match(/&tbWidth=[0-9]+/) ) tbWidth = parseInt(tbWidth[0].replace(/[^0-9]+/g, ''), 10); else tbWidth = $(window).width() - 90; if ( tbHeight = href.match(/&tbHeight=[0-9]+/) ) tbHeight = parseInt(tbHeight[0].replace(/[^0-9]+/g, ''), 10); else tbHeight = $(window).height() - 60; if ( alink.length ) { url = alink.attr('href') || ''; text = alink.attr('title') || ''; link = '&nbsp; <a href="' + url + '" target="_top" class="tb-theme-preview-link">' + text + '</a>'; } else { text = $(this).attr('title') || ''; link = '&nbsp; <span class="tb-theme-preview-link">' + text + '</span>'; } $('#TB_title').css({'background-color':'#222','color':'#dfdfdf'}); $('#TB_closeAjaxWindow').css({'float':'left'}); $('#TB_ajaxWindowTitle').css({'float':'right'}).html(link); $('#TB_iframeContent').width('100%'); thickDims(); return false; } ); });
JavaScript
function WPSetAsThumbnail(id, nonce){ var $link = jQuery('a#wp-post-thumbnail-' + id); $link.text( setPostThumbnailL10n.saving ); jQuery.post(ajaxurl, { action:"set-post-thumbnail", post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie) }, function(str){ var win = window.dialogArguments || opener || parent || top; $link.text( setPostThumbnailL10n.setThumbnail ); if ( str == '0' ) { alert( setPostThumbnailL10n.error ); } else { jQuery('a.wp-post-thumbnail').show(); $link.text( setPostThumbnailL10n.done ); $link.fadeOut( 2000 ); win.WPSetThumbnailID(id); win.WPSetThumbnailHTML(str); } } ); }
JavaScript
(function($,undefined) { wpWordCount = { settings : { strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc. w : /\S\s+/g, // word-counting regexp c : /\S/g // char-counting regexp for asian languages }, block : 0, wc : function(tx, type) { var t = this, w = $('.word-count'), tc = 0; if ( type === undefined ) type = wordCountL10n.type; if ( type !== 'w' && type !== 'c' ) type = 'w'; if ( t.block ) return; t.block = 1; setTimeout( function() { if ( tx ) { tx = tx.replace( t.settings.strip, ' ' ).replace( /&nbsp;|&#160;/gi, ' ' ); tx = tx.replace( t.settings.clean, '' ); tx.replace( t.settings[type], function(){tc++;} ); } w.html(tc.toString()); setTimeout( function() { t.block = 0; }, 2000 ); }, 1 ); } } $(document).bind( 'wpcountwords', function(e, txt) { wpWordCount.wc(txt); }); }(jQuery));
JavaScript
( function( $, undef ){ // html stuff var _before = '<a tabindex="0" class="wp-color-result" />', _after = '<div class="wp-picker-holder" />', _wrap = '<div class="wp-picker-container" />', _button = '<input type="button" class="button button-small hidden" />'; // jQuery UI Widget constructor var ColorPicker = { options: { defaultColor: false, change: false, clear: false, hide: true, palettes: true }, _create: function() { // bail early for unsupported Iris. if ( ! $.support.iris ) return; var self = this; var el = self.element; $.extend( self.options, el.data() ); self.initialValue = el.val(); // Set up HTML structure, hide things el.addClass( 'wp-color-picker' ).hide().wrap( _wrap ); self.wrap = el.parent(); self.toggler = $( _before ).insertBefore( el ).css( { backgroundColor: self.initialValue } ).attr( "title", wpColorPickerL10n.pick ).attr( "data-current", wpColorPickerL10n.current ); self.pickerContainer = $( _after ).insertAfter( el ); self.button = $( _button ); if ( self.options.defaultColor ) self.button.addClass( 'wp-picker-default' ).val( wpColorPickerL10n.defaultString ); else self.button.addClass( 'wp-picker-clear' ).val( wpColorPickerL10n.clear ); el.wrap('<span class="wp-picker-input-wrap" />').after(self.button); el.iris( { target: self.pickerContainer, hide: true, width: 255, mode: 'hsv', palettes: self.options.palettes, change: function( event, ui ) { self.toggler.css( { backgroundColor: ui.color.toString() } ); // check for a custom cb if ( $.isFunction( self.options.change ) ) self.options.change.call( this, event, ui ); } } ); el.val( self.initialValue ); self._addListeners(); if ( ! self.options.hide ) self.toggler.click(); }, _addListeners: function() { var self = this; self.toggler.click( function( event ){ event.stopPropagation(); self.element.toggle().iris( 'toggle' ); self.button.toggleClass('hidden'); self.toggler.toggleClass( 'wp-picker-open' ); // close picker when you click outside it if ( self.toggler.hasClass( 'wp-picker-open' ) ) $( "body" ).on( 'click', { wrap: self.wrap, toggler: self.toggler }, self._bodyListener ); else $( "body" ).off( 'click', self._bodyListener ); }); self.element.change(function( event ) { var me = $(this), val = me.val(); // Empty = clear if ( val === '' || val === '#' ) { self.toggler.css('backgroundColor', ''); // fire clear callback if we have one if ( $.isFunction( self.options.clear ) ) self.options.clear.call( this, event ); } }); // open a keyboard-focused closed picker with space or enter self.toggler.on('keyup', function( e ) { if ( e.keyCode === 13 || e.keyCode === 32 ) { e.preventDefault(); self.toggler.trigger('click').next().focus(); } }); self.button.click( function( event ) { var me = $(this); if ( me.hasClass( 'wp-picker-clear' ) ) { self.element.val( '' ); self.toggler.css('backgroundColor', ''); if ( $.isFunction( self.options.clear ) ) self.options.clear.call( this, event ); } else if ( me.hasClass( 'wp-picker-default' ) ) { self.element.val( self.options.defaultColor ).change(); } }); }, _bodyListener: function( event ) { if ( ! event.data.wrap.find( event.target ).length ) event.data.toggler.click(); }, // $("#input").wpColorPicker('color') returns the current color // $("#input").wpColorPicker('color', '#bada55') to set color: function( newColor ) { if ( newColor === undef ) return this.element.iris( "option", "color" ); this.element.iris( "option", "color", newColor ); }, //$("#input").wpColorPicker('defaultColor') returns the current default color //$("#input").wpColorPicker('defaultColor', newDefaultColor) to set defaultColor: function( newDefaultColor ) { if ( newDefaultColor === undef ) return this.options.defaultColor; this.options.defaultColor = newDefaultColor; } } $.widget( 'wp.wpColorPicker', ColorPicker ); }( jQuery ) );
JavaScript
var imageEdit; (function($) { imageEdit = { iasapi : {}, hold : {}, postid : '', intval : function(f) { return f | 0; }, setDisabled : function(el, s) { if ( s ) { el.removeClass('disabled'); $('input', el).removeAttr('disabled'); } else { el.addClass('disabled'); $('input', el).prop('disabled', true); } }, init : function(postid, nonce) { var t = this, old = $('#image-editor-' + t.postid), x = t.intval( $('#imgedit-x-' + postid).val() ), y = t.intval( $('#imgedit-y-' + postid).val() ); if ( t.postid != postid && old.length ) t.close(t.postid); t.hold['w'] = t.hold['ow'] = x; t.hold['h'] = t.hold['oh'] = y; t.hold['xy_ratio'] = x / y; t.hold['sizer'] = parseFloat( $('#imgedit-sizer-' + postid).val() ); t.postid = postid; $('#imgedit-response-' + postid).empty(); $('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) { var k = e.keyCode; if ( 36 < k && k < 41 ) $(this).blur() if ( 13 == k ) { e.preventDefault(); e.stopPropagation(); return false; } }); }, toggleEditor : function(postid, toggle) { var wait = $('#imgedit-wait-' + postid); if ( toggle ) wait.height( $('#imgedit-panel-' + postid).height() ).fadeIn('fast'); else wait.fadeOut('fast'); }, toggleHelp : function(el) { $(el).siblings('.imgedit-help').slideToggle('fast'); return false; }, getTarget : function(postid) { return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full'; }, scaleChanged : function(postid, x) { var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid), warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = ''; if ( x ) { h1 = (w.val() != '') ? Math.round( w.val() / this.hold['xy_ratio'] ) : ''; h.val( h1 ); } else { w1 = (h.val() != '') ? Math.round( h.val() * this.hold['xy_ratio'] ) : ''; w.val( w1 ); } if ( ( h1 && h1 > this.hold['oh'] ) || ( w1 && w1 > this.hold['ow'] ) ) warn.css('visibility', 'visible'); else warn.css('visibility', 'hidden'); }, getSelRatio : function(postid) { var x = this.hold['w'], y = this.hold['h'], X = this.intval( $('#imgedit-crop-width-' + postid).val() ), Y = this.intval( $('#imgedit-crop-height-' + postid).val() ); if ( X && Y ) return X + ':' + Y; if ( x && y ) return x + ':' + y; return '1:1'; }, filterHistory : function(postid, setSize) { // apply undo state to history var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = []; if ( history != '' ) { history = JSON.parse(history); pop = this.intval( $('#imgedit-undone-' + postid).val() ); if ( pop > 0 ) { while ( pop > 0 ) { history.pop(); pop--; } } if ( setSize ) { if ( !history.length ) { this.hold['w'] = this.hold['ow']; this.hold['h'] = this.hold['oh']; return ''; } // restore o = history[history.length - 1]; o = o.c || o.r || o.f || false; if ( o ) { this.hold['w'] = o.fw; this.hold['h'] = o.fh; } } // filter the values for ( n in history ) { i = history[n]; if ( i.hasOwnProperty('c') ) { op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } }; } else if ( i.hasOwnProperty('r') ) { op[n] = { 'r': i.r.r }; } else if ( i.hasOwnProperty('f') ) { op[n] = { 'f': i.f.f }; } } return JSON.stringify(op); } return ''; }, refreshEditor : function(postid, nonce, callback) { var t = this, data, img; t.toggleEditor(postid, 1); data = { 'action': 'imgedit-preview', '_ajax_nonce': nonce, 'postid': postid, 'history': t.filterHistory(postid, 1), 'rand': t.intval(Math.random() * 1000000) }; img = $('<img id="image-preview-' + postid + '" />'); img.load( function() { var max1, max2, parent = $('#imgedit-crop-' + postid), t = imageEdit; parent.empty().append(img); // w, h are the new full size dims max1 = Math.max( t.hold.w, t.hold.h ); max2 = Math.max( $(img).width(), $(img).height() ); t.hold['sizer'] = max1 > max2 ? max2 / max1 : 1; t.initCrop(postid, img, parent); t.setCropSelection(postid, 0); if ( (typeof callback != "unknown") && callback != null ) callback(); if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() == 0 ) $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled'); else $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true); t.toggleEditor(postid, 0); }).error(function(){ $('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>'); t.toggleEditor(postid, 0); }).attr('src', ajaxurl + '?' + $.param(data)); }, action : function(postid, nonce, action) { var t = this, data, w, h, fw, fh; if ( t.notsaved(postid) ) return false; data = { 'action': 'image-editor', '_ajax_nonce': nonce, 'postid': postid }; if ( 'scale' == action ) { w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid), fw = t.intval(w.val()), fh = t.intval(h.val()); if ( fw < 1 ) { w.focus(); return false; } else if ( fh < 1 ) { h.focus(); return false; } if ( fw == t.hold.ow || fh == t.hold.oh ) return false; data['do'] = 'scale'; data['fwidth'] = fw; data['fheight'] = fh; } else if ( 'restore' == action ) { data['do'] = 'restore'; } else { return false; } t.toggleEditor(postid, 1); $.post(ajaxurl, data, function(r) { $('#image-editor-' + postid).empty().append(r); t.toggleEditor(postid, 0); }); }, save : function(postid, nonce) { var data, target = this.getTarget(postid), history = this.filterHistory(postid, 0); if ( '' == history ) return false; this.toggleEditor(postid, 1); data = { 'action': 'image-editor', '_ajax_nonce': nonce, 'postid': postid, 'history': history, 'target': target, 'context': $('#image-edit-context').length ? $('#image-edit-context').val() : null, 'do': 'save' }; $.post(ajaxurl, data, function(r) { var ret = JSON.parse(r); if ( ret.error ) { $('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p><div>'); imageEdit.close(postid); return; } if ( ret.fw && ret.fh ) $('#media-dims-' + postid).html( ret.fw + ' &times; ' + ret.fh ); if ( ret.thumbnail ) $('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail); if ( ret.msg ) $('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>'); imageEdit.close(postid); }); }, open : function(postid, nonce) { var data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid), btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('.spinner'); btn.prop('disabled', true); spin.show(); data = { 'action': 'image-editor', '_ajax_nonce': nonce, 'postid': postid, 'do': 'open' }; elem.load(ajaxurl, data, function() { elem.fadeIn('fast'); head.fadeOut('fast', function(){ btn.removeAttr('disabled'); spin.hide(); }); }); }, imgLoaded : function(postid) { var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid); this.initCrop(postid, img, parent); this.setCropSelection(postid, 0); this.toggleEditor(postid, 0); }, initCrop : function(postid, image, parent) { var t = this, selW = $('#imgedit-sel-width-' + postid), selH = $('#imgedit-sel-height-' + postid); t.iasapi = $(image).imgAreaSelect({ parent: parent, instance: true, handles: true, keys: true, minWidth: 3, minHeight: 3, onInit: function(img, c) { parent.children().mousedown(function(e){ var ratio = false, sel, defRatio; if ( e.shiftKey ) { sel = t.iasapi.getSelection(); defRatio = t.getSelRatio(postid); ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio; } t.iasapi.setOptions({ aspectRatio: ratio }); }); }, onSelectStart: function(img, c) { imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1); }, onSelectEnd: function(img, c) { imageEdit.setCropSelection(postid, c); }, onSelectChange: function(img, c) { var sizer = imageEdit.hold.sizer; selW.val( imageEdit.round(c.width / sizer) ); selH.val( imageEdit.round(c.height / sizer) ); } }); }, setCropSelection : function(postid, c) { var sel, min = $('#imgedit-minthumb-' + postid).val() || '128:128', sizer = this.hold['sizer']; min = min.split(':'); c = c || 0; if ( !c || ( c.width < 3 && c.height < 3 ) ) { this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0); this.setDisabled($('#imgedit-crop-sel-' + postid), 0); $('#imgedit-sel-width-' + postid).val(''); $('#imgedit-sel-height-' + postid).val(''); $('#imgedit-selection-' + postid).val(''); return false; } if ( c.width < (min[0] * sizer) && c.height < (min[1] * sizer) ) { this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0); $('#imgedit-selection-' + postid).val(''); return false; } sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height }; this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1); $('#imgedit-selection-' + postid).val( JSON.stringify(sel) ); }, close : function(postid, warn) { warn = warn || false; if ( warn && this.notsaved(postid) ) return false; this.iasapi = {}; this.hold = {}; $('#image-editor-' + postid).fadeOut('fast', function() { $('#media-head-' + postid).fadeIn('fast'); $(this).empty(); }); }, notsaved : function(postid) { var h = $('#imgedit-history-' + postid).val(), history = (h != '') ? JSON.parse(h) : new Array(), pop = this.intval( $('#imgedit-undone-' + postid).val() ); if ( pop < history.length ) { if ( confirm( $('#imgedit-leaving-' + postid).html() ) ) return false; return true; } return false; }, addStep : function(op, postid, nonce) { var t = this, elem = $('#imgedit-history-' + postid), history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array(), undone = $('#imgedit-undone-' + postid), pop = t.intval(undone.val()); while ( pop > 0 ) { history.pop(); pop--; } undone.val(0); // reset history.push(op); elem.val( JSON.stringify(history) ); t.refreshEditor(postid, nonce, function() { t.setDisabled($('#image-undo-' + postid), true); t.setDisabled($('#image-redo-' + postid), false); }); }, rotate : function(angle, postid, nonce, t) { if ( $(t).hasClass('disabled') ) return false; this.addStep({ 'r': { 'r': angle, 'fw': this.hold['h'], 'fh': this.hold['w'] }}, postid, nonce); }, flip : function (axis, postid, nonce, t) { if ( $(t).hasClass('disabled') ) return false; this.addStep({ 'f': { 'f': axis, 'fw': this.hold['w'], 'fh': this.hold['h'] }}, postid, nonce); }, crop : function (postid, nonce, t) { var sel = $('#imgedit-selection-' + postid).val(), w = this.intval( $('#imgedit-sel-width-' + postid).val() ), h = this.intval( $('#imgedit-sel-height-' + postid).val() ); if ( $(t).hasClass('disabled') || sel == '' ) return false; sel = JSON.parse(sel); if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) { sel['fw'] = w; sel['fh'] = h; this.addStep({ 'c': sel }, postid, nonce); } }, undo : function (postid, nonce) { var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid), pop = t.intval( elem.val() ) + 1; if ( button.hasClass('disabled') ) return; elem.val(pop); t.refreshEditor(postid, nonce, function() { var elem = $('#imgedit-history-' + postid), history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array(); t.setDisabled($('#image-redo-' + postid), true); t.setDisabled(button, pop < history.length); }); }, redo : function(postid, nonce) { var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid), pop = t.intval( elem.val() ) - 1; if ( button.hasClass('disabled') ) return; elem.val(pop); t.refreshEditor(postid, nonce, function() { t.setDisabled($('#image-undo-' + postid), true); t.setDisabled(button, pop > 0); }); }, setNumSelection : function(postid) { var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid), x = this.intval( elX.val() ), y = this.intval( elY.val() ), img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(), sizer = this.hold['sizer'], x1, y1, x2, y2, ias = this.iasapi; if ( x < 1 ) { elX.val(''); return false; } if ( y < 1 ) { elY.val(''); return false; } if ( x && y && ( sel = ias.getSelection() ) ) { x2 = sel.x1 + Math.round( x * sizer ); y2 = sel.y1 + Math.round( y * sizer ); x1 = sel.x1; y1 = sel.y1; if ( x2 > imgw ) { x1 = 0; x2 = imgw; elX.val( Math.round( x2 / sizer ) ); } if ( y2 > imgh ) { y1 = 0; y2 = imgh; elY.val( Math.round( y2 / sizer ) ); } ias.setSelection( x1, y1, x2, y2 ); ias.update(); this.setCropSelection(postid, ias.getSelection()); } }, round : function(num) { var s; num = Math.round(num); if ( this.hold.sizer > 0.6 ) return num; s = num.toString().slice(-1); if ( '1' == s ) return num - 1; else if ( '9' == s ) return num + 1; return num; }, setRatioSelection : function(postid, n, el) { var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ), y = this.intval( $('#imgedit-crop-height-' + postid).val() ), h = $('#image-preview-' + postid).height(); if ( !this.intval( $(el).val() ) ) { $(el).val(''); return; } if ( x && y ) { this.iasapi.setOptions({ aspectRatio: x + ':' + y }); if ( sel = this.iasapi.getSelection(true) ) { r = Math.ceil( sel.y1 + ((sel.x2 - sel.x1) / (x / y)) ); if ( r > h ) { r = h; if ( n ) $('#imgedit-crop-height-' + postid).val(''); else $('#imgedit-crop-width-' + postid).val(''); } this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r ); this.iasapi.update(); } } } } })(jQuery);
JavaScript
jQuery(function($){ $( 'body' ).bind( 'click.wp-gallery', function(e){ var target = $( e.target ), id, img_size; if ( target.hasClass( 'wp-set-header' ) ) { ( window.dialogArguments || opener || parent || top ).location.href = target.data( 'location' ); e.preventDefault(); } else if ( target.hasClass( 'wp-set-background' ) ) { id = target.data( 'attachment-id' ); img_size = $( 'input[name="attachments[' + id + '][image-size]"]:checked').val(); jQuery.post(ajaxurl, { action: 'set-background-image', attachment_id: id, size: img_size }, function(){ var win = window.dialogArguments || opener || parent || top; win.tb_remove(); win.location.reload(); }); e.preventDefault(); } }); });
JavaScript
(function($){ function check_pass_strength() { var pass1 = $('#pass1').val(), user = $('#user_login').val(), pass2 = $('#pass2').val(), strength; $('#pass-strength-result').removeClass('short bad good strong'); if ( ! pass1 ) { $('#pass-strength-result').html( pwsL10n.empty ); return; } strength = passwordStrength(pass1, user, pass2); switch ( strength ) { case 2: $('#pass-strength-result').addClass('bad').html( pwsL10n['bad'] ); break; case 3: $('#pass-strength-result').addClass('good').html( pwsL10n['good'] ); break; case 4: $('#pass-strength-result').addClass('strong').html( pwsL10n['strong'] ); break; case 5: $('#pass-strength-result').addClass('short').html( pwsL10n['mismatch'] ); break; default: $('#pass-strength-result').addClass('short').html( pwsL10n['short'] ); } } $(document).ready( function() { var select = $('#display_name'); $('#pass1').val('').keyup( check_pass_strength ); $('#pass2').val('').keyup( check_pass_strength ); $('#pass-strength-result').show(); $('.color-palette').click( function() { $(this).siblings('input[name="admin_color"]').prop('checked', true); }); if ( select.length ) { $('#first_name, #last_name, #nickname').bind( 'blur.user_profile', function() { var dub = [], inputs = { display_nickname : $('#nickname').val() || '', display_username : $('#user_login').val() || '', display_firstname : $('#first_name').val() || '', display_lastname : $('#last_name').val() || '' }; if ( inputs.display_firstname && inputs.display_lastname ) { inputs['display_firstlast'] = inputs.display_firstname + ' ' + inputs.display_lastname; inputs['display_lastfirst'] = inputs.display_lastname + ' ' + inputs.display_firstname; } $.each( $('option', select), function( i, el ){ dub.push( el.value ); }); $.each(inputs, function( id, value ) { if ( ! value ) return; var val = value.replace(/<\/?[a-z][^>]*>/gi, ''); if ( inputs[id].length && $.inArray( val, dub ) == -1 ) { dub.push(val); $('<option />', { 'text': val }).appendTo( select ); } }); }); } }); })(jQuery);
JavaScript
/* Plugin Browser Thickbox related JS*/ var tb_position; jQuery(document).ready(function($) { tb_position = function() { var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0; if ( $('body.admin-bar').length ) adminbar_height = 28; if ( tbWindow.size() ) { tbWindow.width( W - 50 ).height( H - 45 - adminbar_height ); $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height ); tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'}); if ( typeof document.body.style.maxWidth != 'undefined' ) tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'}); }; return $('a.thickbox').each( function() { var href = $(this).attr('href'); if ( ! href ) return; href = href.replace(/&width=[0-9]+/g, ''); href = href.replace(/&height=[0-9]+/g, ''); $(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) ); }); }; $(window).resize(function(){ tb_position(); }); $('#dashboard_plugins, .plugins').on( 'click', 'a.thickbox', function() { tb_click.call(this); $('#TB_title').css({'background-color':'#222','color':'#cfcfcf'}); $('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong>&nbsp;' + $(this).attr('title') ); return false; }); /* Plugin install related JS*/ $('#plugin-information #sidemenu a').click( function() { var tab = $(this).attr('name'); //Flip the tab $('#plugin-information-header a.current').removeClass('current'); $(this).addClass('current'); //Flip the content. $('#section-holder div.section').hide(); //Hide 'em all $('#section-' + tab).show(); return false; }); $('a.install-now').click( function() { return confirm( plugininstallL10n.ays ); }); });
JavaScript
/** * PubSub * * A lightweight publish/subscribe implementation. * Private use only! */ var PubSub, fullscreen, wptitlehint; PubSub = function() { this.topics = {}; }; PubSub.prototype.subscribe = function( topic, callback ) { if ( ! this.topics[ topic ] ) this.topics[ topic ] = []; this.topics[ topic ].push( callback ); return callback; }; PubSub.prototype.unsubscribe = function( topic, callback ) { var i, l, topics = this.topics[ topic ]; if ( ! topics ) return callback || []; // Clear matching callbacks if ( callback ) { for ( i = 0, l = topics.length; i < l; i++ ) { if ( callback == topics[i] ) topics.splice( i, 1 ); } return callback; // Clear all callbacks } else { this.topics[ topic ] = []; return topics; } }; PubSub.prototype.publish = function( topic, args ) { var i, l, broken, topics = this.topics[ topic ]; if ( ! topics ) return; args = args || []; for ( i = 0, l = topics.length; i < l; i++ ) { broken = ( topics[i].apply( null, args ) === false || broken ); } return ! broken; }; /** * Distraction Free Writing * (wp-fullscreen) * * Access the API globally using the fullscreen variable. */ (function($){ var api, ps, bounder, s; // Initialize the fullscreen/api object fullscreen = api = {}; // Create the PubSub (publish/subscribe) interface. ps = api.pubsub = new PubSub(); timer = 0; block = false; s = api.settings = { // Settings visible : false, mode : 'tinymce', editor_id : 'content', title_id : '', timer : 0, toolbar_shown : false } /** * Bounder * * Creates a function that publishes start/stop topics. * Used to throttle events. */ bounder = api.bounder = function( start, stop, delay, e ) { var y, top; delay = delay || 1250; if ( e ) { y = e.pageY || e.clientY || e.offsetY; top = $(document).scrollTop(); if ( !e.isDefaultPrevented ) // test if e ic jQuery normalized y = 135 + y; if ( y - top > 120 ) return; } if ( block ) return; block = true; setTimeout( function() { block = false; }, 400 ); if ( s.timer ) clearTimeout( s.timer ); else ps.publish( start ); function timed() { ps.publish( stop ); s.timer = 0; } s.timer = setTimeout( timed, delay ); }; /** * on() * * Turns fullscreen on. * * @param string mode Optional. Switch to the given mode before opening. */ api.on = function() { if ( s.visible ) return; // Settings can be added or changed by defining "wp_fullscreen_settings" JS object. if ( typeof(wp_fullscreen_settings) == 'object' ) $.extend( s, wp_fullscreen_settings ); s.editor_id = wpActiveEditor || 'content'; if ( $('input#title').length && s.editor_id == 'content' ) s.title_id = 'title'; else if ( $('input#' + s.editor_id + '-title').length ) // the title input field should have [editor_id]-title HTML ID to be auto detected s.title_id = s.editor_id + '-title'; else $('#wp-fullscreen-title, #wp-fullscreen-title-prompt-text').hide(); s.mode = $('#' + s.editor_id).is(':hidden') ? 'tinymce' : 'html'; s.qt_canvas = $('#' + s.editor_id).get(0); if ( ! s.element ) api.ui.init(); s.is_mce_on = s.has_tinymce && typeof( tinyMCE.get(s.editor_id) ) != 'undefined'; api.ui.fade( 'show', 'showing', 'shown' ); }; /** * off() * * Turns fullscreen off. */ api.off = function() { if ( ! s.visible ) return; api.ui.fade( 'hide', 'hiding', 'hidden' ); }; /** * switchmode() * * @return string - The current mode. * * @param string to - The fullscreen mode to switch to. * @event switchMode * @eventparam string to - The new mode. * @eventparam string from - The old mode. */ api.switchmode = function( to ) { var from = s.mode; if ( ! to || ! s.visible || ! s.has_tinymce ) return from; // Don't switch if the mode is the same. if ( from == to ) return from; ps.publish( 'switchMode', [ from, to ] ); s.mode = to; ps.publish( 'switchedMode', [ from, to ] ); return to; }; /** * General */ api.save = function() { var hidden = $('#hiddenaction'), old = hidden.val(), spinner = $('#wp-fullscreen-save .spinner'), message = $('#wp-fullscreen-save span'); spinner.show(); api.savecontent(); hidden.val('wp-fullscreen-save-post'); $.post( ajaxurl, $('form#post').serialize(), function(r){ spinner.hide(); message.show(); setTimeout( function(){ message.fadeOut(1000); }, 3000 ); if ( r.last_edited ) $('#wp-fullscreen-save input').attr( 'title', r.last_edited ); }, 'json'); hidden.val(old); } api.savecontent = function() { var ed, content; if ( s.title_id ) $('#' + s.title_id).val( $('#wp-fullscreen-title').val() ); if ( s.mode === 'tinymce' && (ed = tinyMCE.get('wp_mce_fullscreen')) ) { content = ed.save(); } else { content = $('#wp_mce_fullscreen').val(); } $('#' + s.editor_id).val( content ); $(document).triggerHandler('wpcountwords', [ content ]); } set_title_hint = function( title ) { if ( ! title.val().length ) title.siblings('label').css( 'visibility', '' ); else title.siblings('label').css( 'visibility', 'hidden' ); } api.dfw_width = function(n) { var el = $('#wp-fullscreen-wrap'), w = el.width(); if ( !n ) { // reset to theme width el.width( $('#wp-fullscreen-central-toolbar').width() ); deleteUserSetting('dfw_width'); return; } w = n + w; if ( w < 200 || w > 1200 ) // sanity check return; el.width( w ); setUserSetting('dfw_width', w); } ps.subscribe( 'showToolbar', function() { s.toolbars.removeClass('fade-1000').addClass('fade-300'); api.fade.In( s.toolbars, 300, function(){ ps.publish('toolbarShown'); }, true ); $('#wp-fullscreen-body').addClass('wp-fullscreen-focus'); s.toolbar_shown = true; }); ps.subscribe( 'hideToolbar', function() { s.toolbars.removeClass('fade-300').addClass('fade-1000'); api.fade.Out( s.toolbars, 1000, function(){ ps.publish('toolbarHidden'); }, true ); $('#wp-fullscreen-body').removeClass('wp-fullscreen-focus'); }); ps.subscribe( 'toolbarShown', function() { s.toolbars.removeClass('fade-300'); }); ps.subscribe( 'toolbarHidden', function() { s.toolbars.removeClass('fade-1000'); s.toolbar_shown = false; }); ps.subscribe( 'show', function() { // This event occurs before the overlay blocks the UI. var title; if ( s.title_id ) { title = $('#wp-fullscreen-title').val( $('#' + s.title_id).val() ); set_title_hint( title ); } $('#wp-fullscreen-save input').attr( 'title', $('#last-edit').text() ); s.textarea_obj.value = s.qt_canvas.value; if ( s.has_tinymce && s.mode === 'tinymce' ) tinyMCE.execCommand('wpFullScreenInit'); s.orig_y = $(window).scrollTop(); }); ps.subscribe( 'showing', function() { // This event occurs while the DFW overlay blocks the UI. $( document.body ).addClass( 'fullscreen-active' ); api.refresh_buttons(); $( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } ); bounder( 'showToolbar', 'hideToolbar', 2000 ); api.bind_resize(); setTimeout( api.resize_textarea, 200 ); // scroll to top so the user is not disoriented scrollTo(0, 0); // needed it for IE7 and compat mode $('#wpadminbar').hide(); }); ps.subscribe( 'shown', function() { // This event occurs after the DFW overlay is shown var interim_init; s.visible = true; // init the standard TinyMCE instance if missing if ( s.has_tinymce && ! s.is_mce_on ) { interim_init = function(mce, ed) { var el = ed.getElement(), old_val = el.value, settings = tinyMCEPreInit.mceInit[s.editor_id]; if ( settings && settings.wpautop && typeof(switchEditors) != 'undefined' ) el.value = switchEditors.wpautop( el.value ); ed.onInit.add(function(ed) { ed.hide(); ed.getElement().value = old_val; tinymce.onAddEditor.remove(interim_init); }); }; tinymce.onAddEditor.add(interim_init); tinyMCE.init(tinyMCEPreInit.mceInit[s.editor_id]); s.is_mce_on = true; } wpActiveEditor = 'wp_mce_fullscreen'; }); ps.subscribe( 'hide', function() { // This event occurs before the overlay blocks DFW. var htmled_is_hidden = $('#' + s.editor_id).is(':hidden'); // Make sure the correct editor is displaying. if ( s.has_tinymce && s.mode === 'tinymce' && !htmled_is_hidden ) { switchEditors.go(s.editor_id, 'tmce'); } else if ( s.mode === 'html' && htmled_is_hidden ) { switchEditors.go(s.editor_id, 'html'); } // Save content must be after switchEditors or content will be overwritten. See #17229. api.savecontent(); $( document ).unbind( '.fullscreen' ); $(s.textarea_obj).unbind('.grow'); if ( s.has_tinymce && s.mode === 'tinymce' ) tinyMCE.execCommand('wpFullScreenSave'); if ( s.title_id ) set_title_hint( $('#' + s.title_id) ); s.qt_canvas.value = s.textarea_obj.value; }); ps.subscribe( 'hiding', function() { // This event occurs while the overlay blocks the DFW UI. $( document.body ).removeClass( 'fullscreen-active' ); scrollTo(0, s.orig_y); $('#wpadminbar').show(); }); ps.subscribe( 'hidden', function() { // This event occurs after DFW is removed. s.visible = false; $('#wp_mce_fullscreen, #wp-fullscreen-title').removeAttr('style'); if ( s.has_tinymce && s.is_mce_on ) tinyMCE.execCommand('wpFullScreenClose'); s.textarea_obj.value = ''; api.oldheight = 0; wpActiveEditor = s.editor_id; }); ps.subscribe( 'switchMode', function( from, to ) { var ed; if ( !s.has_tinymce || !s.is_mce_on ) return; ed = tinyMCE.get('wp_mce_fullscreen'); if ( from === 'html' && to === 'tinymce' ) { if ( tinyMCE.get(s.editor_id).getParam('wpautop') && typeof(switchEditors) != 'undefined' ) s.textarea_obj.value = switchEditors.wpautop( s.textarea_obj.value ); if ( 'undefined' == typeof(ed) ) tinyMCE.execCommand('wpFullScreenInit'); else ed.show(); } else if ( from === 'tinymce' && to === 'html' ) { if ( ed ) ed.hide(); } }); ps.subscribe( 'switchedMode', function( from, to ) { api.refresh_buttons(true); if ( to === 'html' ) setTimeout( api.resize_textarea, 200 ); }); /** * Buttons */ api.b = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('Bold'); } api.i = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('Italic'); } api.ul = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('InsertUnorderedList'); } api.ol = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('InsertOrderedList'); } api.link = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('WP_Link'); else wpLink.open(); } api.unlink = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('unlink'); } api.atd = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('mceWritingImprovementTool'); } api.help = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('WP_Help'); } api.blockquote = function() { if ( s.has_tinymce && 'tinymce' === s.mode ) tinyMCE.execCommand('mceBlockQuote'); } api.medialib = function() { if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) wp.media.editor.open(s.editor_id); } api.refresh_buttons = function( fade ) { fade = fade || false; if ( s.mode === 'html' ) { $('#wp-fullscreen-mode-bar').removeClass('wp-tmce-mode').addClass('wp-html-mode'); if ( fade ) $('#wp-fullscreen-button-bar').fadeOut( 150, function(){ $(this).addClass('wp-html-mode').fadeIn( 150 ); }); else $('#wp-fullscreen-button-bar').addClass('wp-html-mode'); } else if ( s.mode === 'tinymce' ) { $('#wp-fullscreen-mode-bar').removeClass('wp-html-mode').addClass('wp-tmce-mode'); if ( fade ) $('#wp-fullscreen-button-bar').fadeOut( 150, function(){ $(this).removeClass('wp-html-mode').fadeIn( 150 ); }); else $('#wp-fullscreen-button-bar').removeClass('wp-html-mode'); } } /** * UI Elements * * Used for transitioning between states. */ api.ui = { init: function() { var topbar = $('#fullscreen-topbar'), txtarea = $('#wp_mce_fullscreen'), last = 0; s.toolbars = topbar.add( $('#wp-fullscreen-status') ); s.element = $('#fullscreen-fader'); s.textarea_obj = txtarea[0]; s.has_tinymce = typeof(tinymce) != 'undefined'; if ( !s.has_tinymce ) $('#wp-fullscreen-mode-bar').hide(); if ( wptitlehint && $('#wp-fullscreen-title').length ) wptitlehint('wp-fullscreen-title'); $(document).keyup(function(e){ var c = e.keyCode || e.charCode, a, data; if ( !fullscreen.settings.visible ) return true; if ( navigator.platform && navigator.platform.indexOf('Mac') != -1 ) a = e.ctrlKey; // Ctrl key for Mac else a = e.altKey; // Alt key for Win & Linux if ( 27 == c ) { // Esc data = { event: e, what: 'dfw', cb: fullscreen.off, condition: function(){ if ( $('#TB_window').is(':visible') || $('.wp-dialog').is(':visible') ) return false; return true; } }; if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [data] ) ) fullscreen.off(); } if ( a && (61 == c || 107 == c || 187 == c) ) // + api.dfw_width(25); if ( a && (45 == c || 109 == c || 189 == c) ) // - api.dfw_width(-25); if ( a && 48 == c ) // 0 api.dfw_width(0); return false; }); // word count in Text mode if ( typeof(wpWordCount) != 'undefined' ) { txtarea.keyup( function(e) { var k = e.keyCode || e.charCode; if ( k == last ) return true; if ( 13 == k || 8 == last || 46 == last ) $(document).triggerHandler('wpcountwords', [ txtarea.val() ]); last = k; return true; }); } topbar.mouseenter(function(e){ s.toolbars.addClass('fullscreen-make-sticky'); $( document ).unbind( '.fullscreen' ); clearTimeout( s.timer ); s.timer = 0; }).mouseleave(function(e){ s.toolbars.removeClass('fullscreen-make-sticky'); if ( s.visible ) $( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } ); }); }, fade: function( before, during, after ) { if ( ! s.element ) api.ui.init(); // If any callback bound to before returns false, bail. if ( before && ! ps.publish( before ) ) return; api.fade.In( s.element, 600, function() { if ( during ) ps.publish( during ); api.fade.Out( s.element, 600, function() { if ( after ) ps.publish( after ); }) }); } }; api.fade = { transitionend: 'transitionend webkitTransitionEnd oTransitionEnd', // Sensitivity to allow browsers to render the blank element before animating. sensitivity: 100, In: function( element, speed, callback, stop ) { callback = callback || $.noop; speed = speed || 400; stop = stop || false; if ( api.fade.transitions ) { if ( element.is(':visible') ) { element.addClass( 'fade-trigger' ); return element; } element.show(); element.first().one( this.transitionend, function() { callback(); }); setTimeout( function() { element.addClass( 'fade-trigger' ); }, this.sensitivity ); } else { if ( stop ) element.stop(); element.css( 'opacity', 1 ); element.first().fadeIn( speed, callback ); if ( element.length > 1 ) element.not(':first').fadeIn( speed ); } return element; }, Out: function( element, speed, callback, stop ) { callback = callback || $.noop; speed = speed || 400; stop = stop || false; if ( ! element.is(':visible') ) return element; if ( api.fade.transitions ) { element.first().one( api.fade.transitionend, function() { if ( element.hasClass('fade-trigger') ) return; element.hide(); callback(); }); setTimeout( function() { element.removeClass( 'fade-trigger' ); }, this.sensitivity ); } else { if ( stop ) element.stop(); element.first().fadeOut( speed, callback ); if ( element.length > 1 ) element.not(':first').fadeOut( speed ); } return element; }, transitions: (function() { // Check if the browser supports CSS 3.0 transitions var s = document.documentElement.style; return ( typeof ( s.WebkitTransition ) == 'string' || typeof ( s.MozTransition ) == 'string' || typeof ( s.OTransition ) == 'string' || typeof ( s.transition ) == 'string' ); })() }; /** * Resize API * * Automatically updates textarea height. */ api.bind_resize = function() { $(s.textarea_obj).bind('keypress.grow click.grow paste.grow', function(){ setTimeout( api.resize_textarea, 200 ); }); } api.oldheight = 0; api.resize_textarea = function() { var txt = s.textarea_obj, newheight; newheight = txt.scrollHeight > 300 ? txt.scrollHeight : 300; if ( newheight != api.oldheight ) { txt.style.height = newheight + 'px'; api.oldheight = newheight; } }; })(jQuery);
JavaScript
// send html to the post editor var wpActiveEditor; function send_to_editor(h) { var ed, mce = typeof(tinymce) != 'undefined', qt = typeof(QTags) != 'undefined'; if ( !wpActiveEditor ) { if ( mce && tinymce.activeEditor ) { ed = tinymce.activeEditor; wpActiveEditor = ed.id; } else if ( !qt ) { return false; } } else if ( mce ) { if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') ) ed = tinymce.activeEditor; else ed = tinymce.get(wpActiveEditor); } if ( ed && !ed.isHidden() ) { // restore caret position on IE if ( tinymce.isIE && ed.windowManager.insertimagebookmark ) ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark); if ( h.indexOf('[caption') !== -1 ) { if ( ed.wpSetImgCaption ) h = ed.wpSetImgCaption(h); } else if ( h.indexOf('[gallery') !== -1 ) { if ( ed.plugins.wpgallery ) h = ed.plugins.wpgallery._do_gallery(h); } else if ( h.indexOf('[embed') === 0 ) { if ( ed.plugins.wordpress ) h = ed.plugins.wordpress._setEmbed(h); } ed.execCommand('mceInsertContent', false, h); } else if ( qt ) { QTags.insertContent(h); } else { document.getElementById(wpActiveEditor).value += h; } try{tb_remove();}catch(e){}; } // thickbox settings var tb_position; (function($) { tb_position = function() { var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0; if ( $('body.admin-bar').length ) adminbar_height = 28; if ( tbWindow.size() ) { tbWindow.width( W - 50 ).height( H - 45 - adminbar_height ); $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height ); tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'}); if ( typeof document.body.style.maxWidth != 'undefined' ) tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'}); }; return $('a.thickbox').each( function() { var href = $(this).attr('href'); if ( ! href ) return; href = href.replace(/&width=[0-9]+/g, ''); href = href.replace(/&height=[0-9]+/g, ''); $(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) ); }); }; $(window).resize(function(){ tb_position(); }); // store caret position in IE $(document).ready(function($){ $('a.thickbox').click(function(){ var ed; if ( typeof(tinymce) != 'undefined' && tinymce.isIE && ( ed = tinymce.get(wpActiveEditor) ) && !ed.isHidden() ) { ed.focus(); ed.windowManager.insertimagebookmark = ed.selection.getBookmark(); } }); }); })(jQuery);
JavaScript
var showNotice, adminMenu, columns, validateForm, screenMeta; (function($){ // Removed in 3.3. // (perhaps) needed for back-compat adminMenu = { init : function() {}, fold : function() {}, restoreMenuState : function() {}, toggle : function() {}, favorites : function() {} }; // show/hide/save table columns columns = { init : function() { var that = this; $('.hide-column-tog', '#adv-settings').click( function() { var $t = $(this), column = $t.val(); if ( $t.prop('checked') ) that.checked(column); else that.unchecked(column); columns.saveManageColumnsState(); }); }, saveManageColumnsState : function() { var hidden = this.hidden(); $.post(ajaxurl, { action: 'hidden-columns', hidden: hidden, screenoptionnonce: $('#screenoptionnonce').val(), page: pagenow }); }, checked : function(column) { $('.column-' + column).show(); this.colSpanChange(+1); }, unchecked : function(column) { $('.column-' + column).hide(); this.colSpanChange(-1); }, hidden : function() { return $('.manage-column').filter(':hidden').map(function() { return this.id; }).get().join(','); }, useCheckboxesForHidden : function() { this.hidden = function(){ return $('.hide-column-tog').not(':checked').map(function() { var id = this.id; return id.substring( id, id.length - 5 ); }).get().join(','); }; }, colSpanChange : function(diff) { var $t = $('table').find('.colspanchange'), n; if ( !$t.length ) return; n = parseInt( $t.attr('colspan'), 10 ) + diff; $t.attr('colspan', n.toString()); } } $(document).ready(function(){columns.init();}); validateForm = function( form ) { return !$( form ).find('.form-required').filter( function() { return $('input:visible', this).val() == ''; } ).addClass( 'form-invalid' ).find('input:visible').change( function() { $(this).closest('.form-invalid').removeClass( 'form-invalid' ); } ).size(); } // stub for doing better warnings showNotice = { warn : function() { var msg = commonL10n.warnDelete || ''; if ( confirm(msg) ) { return true; } return false; }, note : function(text) { alert(text); } }; screenMeta = { element: null, // #screen-meta toggles: null, // .screen-meta-toggle page: null, // #wpcontent init: function() { this.element = $('#screen-meta'); this.toggles = $('.screen-meta-toggle a'); this.page = $('#wpcontent'); this.toggles.click( this.toggleEvent ); }, toggleEvent: function( e ) { var panel = $( this.href.replace(/.+#/, '#') ); e.preventDefault(); if ( !panel.length ) return; if ( panel.is(':visible') ) screenMeta.close( panel, $(this) ); else screenMeta.open( panel, $(this) ); }, open: function( panel, link ) { $('.screen-meta-toggle').not( link.parent() ).css('visibility', 'hidden'); panel.parent().show(); panel.slideDown( 'fast', function() { panel.focus(); link.addClass('screen-meta-active').attr('aria-expanded', true); }); }, close: function( panel, link ) { panel.slideUp( 'fast', function() { link.removeClass('screen-meta-active').attr('aria-expanded', false); $('.screen-meta-toggle').css('visibility', ''); panel.parent().hide(); }); } }; /** * Help tabs. */ $('.contextual-help-tabs').delegate('a', 'click focus', function(e) { var link = $(this), panel; e.preventDefault(); // Don't do anything if the click is for the tab already showing. if ( link.is('.active a') ) return false; // Links $('.contextual-help-tabs .active').removeClass('active'); link.parent('li').addClass('active'); panel = $( link.attr('href') ); // Panels $('.help-tab-content').not( panel ).removeClass('active').hide(); panel.addClass('active').show(); }); $(document).ready( function() { var lastClicked = false, checks, first, last, checked, menu = $('#adminmenu'), mobileEvent, pageInput = $('input.current-page'), currentPage = pageInput.val(); // when the menu is folded, make the fly-out submenu header clickable menu.on('click.wp-submenu-head', '.wp-submenu-head', function(e){ $(e.target).parent().siblings('a').get(0).click(); }); $('#collapse-menu').on('click.collapse-menu', function(e){ var body = $( document.body ), respWidth; // reset any compensation for submenus near the bottom of the screen $('#adminmenu div.wp-submenu').css('margin-top', ''); // WebKit excludes the width of the vertical scrollbar when applying the CSS "@media screen and (max-width: ...)" // and matches $(window).width(). // Firefox and IE > 8 include the scrollbar width, so after the jQuery normalization // $(window).width() is 884px but window.innerWidth is 900px. // (using window.innerWidth also excludes IE < 9) respWidth = navigator.userAgent.indexOf('AppleWebKit/') > -1 ? $(window).width() : window.innerWidth; if ( respWidth && respWidth < 900 ) { if ( body.hasClass('auto-fold') ) { body.removeClass('auto-fold').removeClass('folded'); setUserSetting('unfold', 1); setUserSetting('mfold', 'o'); } else { body.addClass('auto-fold'); setUserSetting('unfold', 0); } } else { if ( body.hasClass('folded') ) { body.removeClass('folded'); setUserSetting('mfold', 'o'); } else { body.addClass('folded'); setUserSetting('mfold', 'f'); } } }); if ( 'ontouchstart' in window || /IEMobile\/[1-9]/.test(navigator.userAgent) ) { // touch screen device // iOS Safari works with touchstart, the rest work with click mobileEvent = /Mobile\/.+Safari/.test(navigator.userAgent) ? 'touchstart' : 'click'; // close any open submenus when touch/click is not on the menu $(document.body).on( mobileEvent+'.wp-mobile-hover', function(e) { if ( !$(e.target).closest('#adminmenu').length ) menu.find('li.wp-has-submenu.opensub').removeClass('opensub'); }); menu.find('a.wp-has-submenu').on( mobileEvent+'.wp-mobile-hover', function(e) { var el = $(this), parent = el.parent(); // Show the sub instead of following the link if: // - the submenu is not open // - the submenu is not shown inline or the menu is not folded if ( !parent.hasClass('opensub') && ( !parent.hasClass('wp-menu-open') || parent.width() < 40 ) ) { e.preventDefault(); menu.find('li.opensub').removeClass('opensub'); parent.addClass('opensub'); } }); } menu.find('li.wp-has-submenu').hoverIntent({ over: function(e){ var b, h, o, f, m = $(this).find('.wp-submenu'), menutop, wintop, maxtop, top = parseInt( m.css('top'), 10 ); if ( isNaN(top) || top > -5 ) // meaning the submenu is visible return; menutop = $(this).offset().top; wintop = $(window).scrollTop(); maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar b = menutop + m.height() + 1; // Bottom offset of the menu h = $('#wpwrap').height(); // Height of the entire page o = 60 + b - h; f = $(window).height() + wintop - 15; // The fold if ( f < (b - o) ) o = b - f; if ( o > maxtop ) o = maxtop; if ( o > 1 ) m.css('margin-top', '-'+o+'px'); else m.css('margin-top', ''); menu.find('li.menu-top').removeClass('opensub'); $(this).addClass('opensub'); }, out: function(){ $(this).removeClass('opensub').find('.wp-submenu').css('margin-top', ''); }, timeout: 200, sensitivity: 7, interval: 90 }); menu.on('focus.adminmenu', '.wp-submenu a', function(e){ $(e.target).closest('li.menu-top').addClass('opensub'); }).on('blur.adminmenu', '.wp-submenu a', function(e){ $(e.target).closest('li.menu-top').removeClass('opensub'); }); // Move .updated and .error alert boxes. Don't move boxes designed to be inline. $('div.wrap h2:first').nextAll('div.updated, div.error').addClass('below-h2'); $('div.updated, div.error').not('.below-h2, .inline').insertAfter( $('div.wrap h2:first') ); // Init screen meta screenMeta.init(); // check all checkboxes $('tbody').children().children('.check-column').find(':checkbox').click( function(e) { if ( 'undefined' == e.shiftKey ) { return true; } if ( e.shiftKey ) { if ( !lastClicked ) { return true; } checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' ); first = checks.index( lastClicked ); last = checks.index( this ); checked = $(this).prop('checked'); if ( 0 < first && 0 < last && first != last ) { checks.slice( first, last ).prop( 'checked', function(){ if ( $(this).closest('tr').is(':visible') ) return checked; return false; }); } } lastClicked = this; // toggle "check all" checkboxes var unchecked = $(this).closest('tbody').find(':checkbox').filter(':visible').not(':checked'); $(this).closest('table').children('thead, tfoot').find(':checkbox').prop('checked', function() { return ( 0 == unchecked.length ); }); return true; }); $('thead, tfoot').find('.check-column :checkbox').click( function(e) { var c = $(this).prop('checked'), kbtoggle = 'undefined' == typeof toggleWithKeyboard ? false : toggleWithKeyboard, toggle = e.shiftKey || kbtoggle; $(this).closest( 'table' ).children( 'tbody' ).filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( $(this).is(':hidden') ) return false; if ( toggle ) return $(this).prop( 'checked' ); else if (c) return true; return false; }); $(this).closest('table').children('thead, tfoot').filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( toggle ) return false; else if (c) return true; return false; }); }); $('#default-password-nag-no').click( function() { setUserSetting('default_password_nag', 'hide'); $('div.default-password-nag').hide(); return false; }); // tab in textareas $('#newcontent').bind('keydown.wpevent_InsertTab', function(e) { var el = e.target, selStart, selEnd, val, scroll, sel; if ( e.keyCode == 27 ) { // escape key $(el).data('tab-out', true); return; } if ( e.keyCode != 9 || e.ctrlKey || e.altKey || e.shiftKey ) // tab key return; if ( $(el).data('tab-out') ) { $(el).data('tab-out', false); return; } selStart = el.selectionStart; selEnd = el.selectionEnd; val = el.value; try { this.lastKey = 9; // not a standard DOM property, lastKey is to help stop Opera tab event. See blur handler below. } catch(err) {} if ( document.selection ) { el.focus(); sel = document.selection.createRange(); sel.text = '\t'; } else if ( selStart >= 0 ) { scroll = this.scrollTop; el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) ); el.selectionStart = el.selectionEnd = selStart + 1; this.scrollTop = scroll; } if ( e.stopPropagation ) e.stopPropagation(); if ( e.preventDefault ) e.preventDefault(); }); $('#newcontent').bind('blur.wpevent_InsertTab', function(e) { if ( this.lastKey && 9 == this.lastKey ) this.focus(); }); if ( pageInput.length ) { pageInput.closest('form').submit( function(e){ // Reset paging var for new filters/searches but not for bulk actions. See #17685. if ( $('select[name="action"]').val() == -1 && $('select[name="action2"]').val() == -1 && pageInput.val() == currentPage ) pageInput.val('1'); }); } // Scroll into view when focused $('#contextual-help-link, #show-settings-link').on( 'focus.scroll-into-view', function(e){ if ( e.target.scrollIntoView ) e.target.scrollIntoView(false); }); // Disable upload buttons until files are selected (function(){ var button, input, form = $('form.wp-upload-form'); if ( ! form.length ) return; button = form.find('input[type="submit"]'); input = form.find('input[type="file"]'); function toggleUploadButton() { button.prop('disabled', '' === input.map( function() { return $(this).val(); }).get().join('')); } toggleUploadButton(); input.on('change', toggleUploadButton); })(); }); // internal use $(document).bind( 'wp_CloseOnEscape', function( e, data ) { if ( typeof(data.cb) != 'function' ) return; if ( typeof(data.condition) != 'function' || data.condition() ) data.cb(); return true; }); })(jQuery);
JavaScript
/*! * Farbtastic: jQuery color picker plug-in v1.3u * * Licensed under the GPL license: * http://www.gnu.org/licenses/gpl.html */ (function($) { $.fn.farbtastic = function (options) { $.farbtastic(this, options); return this; }; $.farbtastic = function (container, callback) { var container = $(container).get(0); return container.farbtastic || (container.farbtastic = new $._farbtastic(container, callback)); }; $._farbtastic = function (container, callback) { // Store farbtastic object var fb = this; // Insert markup $(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>'); var e = $('.farbtastic', container); fb.wheel = $('.wheel', container).get(0); // Dimensions fb.radius = 84; fb.square = 100; fb.width = 194; // Fix background PNGs in IE6 if (navigator.appVersion.match(/MSIE [0-6]\./)) { $('*', e).each(function () { if (this.currentStyle.backgroundImage != 'none') { var image = this.currentStyle.backgroundImage; image = this.currentStyle.backgroundImage.substring(5, image.length - 2); $(this).css({ 'backgroundImage': 'none', 'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" }); } }); } /** * Link to the given element(s) or callback. */ fb.linkTo = function (callback) { // Unbind previous nodes if (typeof fb.callback == 'object') { $(fb.callback).unbind('keyup', fb.updateValue); } // Reset color fb.color = null; // Bind callback or elements if (typeof callback == 'function') { fb.callback = callback; } else if (typeof callback == 'object' || typeof callback == 'string') { fb.callback = $(callback); fb.callback.bind('keyup', fb.updateValue); if (fb.callback.get(0).value) { fb.setColor(fb.callback.get(0).value); } } return this; }; fb.updateValue = function (event) { if (this.value && this.value != fb.color) { fb.setColor(this.value); } }; /** * Change color with HTML syntax #123456 */ fb.setColor = function (color) { var unpack = fb.unpack(color); if (fb.color != color && unpack) { fb.color = color; fb.rgb = unpack; fb.hsl = fb.RGBToHSL(fb.rgb); fb.updateDisplay(); } return this; }; /** * Change color with HSL triplet [0..1, 0..1, 0..1] */ fb.setHSL = function (hsl) { fb.hsl = hsl; fb.rgb = fb.HSLToRGB(hsl); fb.color = fb.pack(fb.rgb); fb.updateDisplay(); return this; }; ///////////////////////////////////////////////////// /** * Retrieve the coordinates of the given event relative to the center * of the widget. */ fb.widgetCoords = function (event) { var offset = $(fb.wheel).offset(); return { x: (event.pageX - offset.left) - fb.width / 2, y: (event.pageY - offset.top) - fb.width / 2 }; }; /** * Mousedown handler */ fb.mousedown = function (event) { // Capture mouse if (!document.dragging) { $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup); document.dragging = true; } // Check which area is being dragged var pos = fb.widgetCoords(event); fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; // Process fb.mousemove(event); return false; }; /** * Mousemove handler */ fb.mousemove = function (event) { // Get coordinates relative to color picker center var pos = fb.widgetCoords(event); // Set new HSL parameters if (fb.circleDrag) { var hue = Math.atan2(pos.x, -pos.y) / 6.28; if (hue < 0) hue += 1; fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); } else { var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); fb.setHSL([fb.hsl[0], sat, lum]); } return false; }; /** * Mouseup handler */ fb.mouseup = function () { // Uncapture mouse $(document).unbind('mousemove', fb.mousemove); $(document).unbind('mouseup', fb.mouseup); document.dragging = false; }; /** * Update the markers and styles */ fb.updateDisplay = function () { // Markers var angle = fb.hsl[0] * 6.28; $('.h-marker', e).css({ left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px', top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px' }); $('.sl-marker', e).css({ left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px', top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px' }); // Saturation/Luminance gradient $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); // Linked elements or callback if (typeof fb.callback == 'object') { // Set background/foreground color $(fb.callback).css({ backgroundColor: fb.color, color: fb.hsl[2] > 0.5 ? '#000' : '#fff' }); // Change linked value $(fb.callback).each(function() { if (this.value && this.value != fb.color) { this.value = fb.color; } }); } else if (typeof fb.callback == 'function') { fb.callback.call(fb, fb.color); } }; /* Various color utility functions */ fb.pack = function (rgb) { var r = Math.round(rgb[0] * 255); var g = Math.round(rgb[1] * 255); var b = Math.round(rgb[2] * 255); return '#' + (r < 16 ? '0' : '') + r.toString(16) + (g < 16 ? '0' : '') + g.toString(16) + (b < 16 ? '0' : '') + b.toString(16); }; fb.unpack = function (color) { if (color.length == 7) { return [parseInt('0x' + color.substring(1, 3)) / 255, parseInt('0x' + color.substring(3, 5)) / 255, parseInt('0x' + color.substring(5, 7)) / 255]; } else if (color.length == 4) { return [parseInt('0x' + color.substring(1, 2)) / 15, parseInt('0x' + color.substring(2, 3)) / 15, parseInt('0x' + color.substring(3, 4)) / 15]; } }; fb.HSLToRGB = function (hsl) { var m1, m2, r, g, b; var h = hsl[0], s = hsl[1], l = hsl[2]; m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s; m1 = l * 2 - m2; return [this.hueToRGB(m1, m2, h+0.33333), this.hueToRGB(m1, m2, h), this.hueToRGB(m1, m2, h-0.33333)]; }; fb.hueToRGB = function (m1, m2, h) { h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; if (h * 2 < 1) return m2; if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; return m1; }; fb.RGBToHSL = function (rgb) { var min, max, delta, h, s, l; var r = rgb[0], g = rgb[1], b = rgb[2]; min = Math.min(r, Math.min(g, b)); max = Math.max(r, Math.max(g, b)); delta = max - min; l = (min + max) / 2; s = 0; if (l > 0 && l < 1) { s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); } h = 0; if (delta > 0) { if (max == r && max != g) h += (g - b) / delta; if (max == g && max != b) h += (2 + (b - r) / delta); if (max == b && max != r) h += (4 + (r - g) / delta); h /= 6; } return [h, s, l]; }; // Install mousedown handler (the others are set on the document on-demand) $('*', e).mousedown(fb.mousedown); // Init color fb.setColor('#000000'); // Set linked elements/callback if (callback) { fb.linkTo(callback); } }; })(jQuery);
JavaScript
// Password strength meter function passwordStrength(password1, username, password2) { var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score; // password 1 != password 2 if ( (password1 != password2) && password2.length > 0) return mismatch //password < 4 if ( password1.length < 4 ) return shortPass //password1 == username if ( password1.toLowerCase() == username.toLowerCase() ) return badPass; if ( password1.match(/[0-9]/) ) symbolSize +=10; if ( password1.match(/[a-z]/) ) symbolSize +=26; if ( password1.match(/[A-Z]/) ) symbolSize +=26; if ( password1.match(/[^a-zA-Z0-9]/) ) symbolSize +=31; natLog = Math.log( Math.pow(symbolSize, password1.length) ); score = natLog / Math.LN2; if (score < 40 ) return badPass if (score < 56 ) return goodPass return strongPass; }
JavaScript
var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad; jQuery(document).ready( function($) { /* Dashboard Welcome Panel */ var welcomePanel = $('#welcome-panel'), welcomePanelHide = $('#wp_welcome_panel-hide'), updateWelcomePanel = function( visible ) { $.post( ajaxurl, { action: 'update-welcome-panel', visible: visible, welcomepanelnonce: $('#welcomepanelnonce').val() }); }; if ( welcomePanel.hasClass('hidden') && welcomePanelHide.prop('checked') ) welcomePanel.removeClass('hidden'); $('.welcome-panel-close, .welcome-panel-dismiss a', welcomePanel).click( function(e) { e.preventDefault(); welcomePanel.addClass('hidden'); updateWelcomePanel( 0 ); $('#wp_welcome_panel-hide').prop('checked', false); }); welcomePanelHide.click( function() { welcomePanel.toggleClass('hidden', ! this.checked ); updateWelcomePanel( this.checked ? 1 : 0 ); }); // These widgets are sometimes populated via ajax ajaxWidgets = [ 'dashboard_incoming_links', 'dashboard_primary', 'dashboard_secondary', 'dashboard_plugins' ]; ajaxPopulateWidgets = function(el) { function show(i, id) { var p, e = $('#' + id + ' div.inside:visible').find('.widget-loading'); if ( e.length ) { p = e.parent(); setTimeout( function(){ p.load( ajaxurl + '?action=dashboard-widgets&widget=' + id, '', function() { p.hide().slideDown('normal', function(){ $(this).css('display', ''); }); }); }, i * 500 ); } } if ( el ) { el = el.toString(); if ( $.inArray(el, ajaxWidgets) != -1 ) show(0, el); } else { $.each( ajaxWidgets, show ); } }; ajaxPopulateWidgets(); postboxes.add_postbox_toggles(pagenow, { pbshow: ajaxPopulateWidgets } ); /* QuickPress */ quickPressLoad = function() { var act = $('#quickpost-action'), t; t = $('#quick-press').submit( function() { $('#dashboard_quick_press #publishing-action .spinner').show(); $('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true); if ( 'post' == act.val() ) { act.val( 'post-quickpress-publish' ); } $('#dashboard_quick_press div.inside').load( t.attr( 'action' ), t.serializeArray(), function() { $('#dashboard_quick_press #publishing-action .spinner').hide(); $('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', false); $('#dashboard_quick_press ul').next('p').remove(); $('#dashboard_quick_press ul').find('li').each( function() { $('#dashboard_recent_drafts ul').prepend( this ); } ).end().remove(); quickPressLoad(); } ); return false; } ); $('#publish').click( function() { act.val( 'post-quickpress-publish' ); } ); $('#title, #tags-input').each( function() { var input = $(this), prompt = $('#' + this.id + '-prompt-text'); if ( '' === this.value ) prompt.removeClass('screen-reader-text'); prompt.click( function() { $(this).addClass('screen-reader-text'); input.focus(); }); input.blur( function() { if ( '' === this.value ) prompt.removeClass('screen-reader-text'); }); input.focus( function() { prompt.addClass('screen-reader-text'); }); }); $('#quick-press').on( 'click focusin', function() { wpActiveEditor = 'content'; }); }; quickPressLoad(); } );
JavaScript
(function($) { var id = 'undefined' !== typeof current_site_id ? '&site_id=' + current_site_id : ''; $(document).ready( function() { $( '.wp-suggest-user' ).autocomplete({ source: ajaxurl + '?action=autocomplete-user&autocomplete_type=add' + id, delay: 500, minLength: 2, position: ( 'undefined' !== typeof isRtl && isRtl ) ? { my: 'right top', at: 'right bottom', offset: '0, -1' } : { offset: '0, -1' }, open: function() { $(this).addClass('open'); }, close: function() { $(this).removeClass('open'); } }); }); })(jQuery);
JavaScript
window.wp = window.wp || {}; (function($) { var revisions; revisions = wp.revisions = { model: {}, view: {}, controller: {} }; // Link settings. revisions.settings = _.isUndefined( _wpRevisionsSettings ) ? {} : _wpRevisionsSettings; // For debugging revisions.debug = false; revisions.log = function() { if ( window.console && revisions.debug ) console.log.apply( console, arguments ); }; // Handy functions to help with positioning $.fn.allOffsets = function() { var offset = this.offset() || {top: 0, left: 0}, win = $(window); return _.extend( offset, { right: win.width() - offset.left - this.outerWidth(), bottom: win.height() - offset.top - this.outerHeight() }); }; $.fn.allPositions = function() { var position = this.position() || {top: 0, left: 0}, parent = this.parent(); return _.extend( position, { right: parent.outerWidth() - position.left - this.outerWidth(), bottom: parent.outerHeight() - position.top - this.outerHeight() }); }; // wp_localize_script transforms top-level numbers into strings. Undo that. if ( revisions.settings.to ) revisions.settings.to = parseInt( revisions.settings.to, 10 ); if ( revisions.settings.from ) revisions.settings.from = parseInt( revisions.settings.from, 10 ); // wp_localize_script does not allow for top-level booleans. Fix that. if ( revisions.settings.compareTwoMode ) revisions.settings.compareTwoMode = revisions.settings.compareTwoMode === '1'; /** * ======================================================================== * MODELS * ======================================================================== */ revisions.model.Slider = Backbone.Model.extend({ defaults: { value: null, values: null, min: 0, max: 1, step: 1, range: false, compareTwoMode: false }, initialize: function( options ) { this.frame = options.frame; this.revisions = options.revisions; // Listen for changes to the revisions or mode from outside this.listenTo( this.frame, 'update:revisions', this.receiveRevisions ); this.listenTo( this.frame, 'change:compareTwoMode', this.updateMode ); // Listen for internal changes this.listenTo( this, 'change:from', this.handleLocalChanges ); this.listenTo( this, 'change:to', this.handleLocalChanges ); this.listenTo( this, 'change:compareTwoMode', this.updateSliderSettings ); this.listenTo( this, 'update:revisions', this.updateSliderSettings ); // Listen for changes to the hovered revision this.listenTo( this, 'change:hoveredRevision', this.hoverRevision ); this.set({ max: this.revisions.length - 1, compareTwoMode: this.frame.get('compareTwoMode'), from: this.frame.get('from'), to: this.frame.get('to') }); this.updateSliderSettings(); }, getSliderValue: function( a, b ) { return isRtl ? this.revisions.length - this.revisions.indexOf( this.get(a) ) - 1 : this.revisions.indexOf( this.get(b) ); }, updateSliderSettings: function() { if ( this.get('compareTwoMode') ) { this.set({ values: [ this.getSliderValue( 'to', 'from' ), this.getSliderValue( 'from', 'to' ) ], value: null, range: true // ensures handles cannot cross }); } else { this.set({ value: this.getSliderValue( 'to', 'to' ), values: null, range: false }); } this.trigger( 'update:slider' ); }, // Called when a revision is hovered hoverRevision: function( model, value ) { this.trigger( 'hovered:revision', value ); }, // Called when `compareTwoMode` changes updateMode: function( model, value ) { this.set({ compareTwoMode: value }); }, // Called when `from` or `to` changes in the local model handleLocalChanges: function() { this.frame.set({ from: this.get('from'), to: this.get('to') }); }, // Receives revisions changes from outside the model receiveRevisions: function( from, to ) { // Bail if nothing changed if ( this.get('from') === from && this.get('to') === to ) return; this.set({ from: from, to: to }, { silent: true }); this.trigger( 'update:revisions', from, to ); } }); revisions.model.Tooltip = Backbone.Model.extend({ defaults: { revision: null, offset: {}, hovering: false, // Whether the mouse is hovering scrubbing: false // Whether the mouse is scrubbing }, initialize: function( options ) { this.frame = options.frame; this.revisions = options.revisions; this.slider = options.slider; this.listenTo( this.slider, 'hovered:revision', this.updateRevision ); this.listenTo( this.slider, 'change:hovering', this.setHovering ); this.listenTo( this.slider, 'change:scrubbing', this.setScrubbing ); }, updateRevision: function( revision ) { this.set({ revision: revision }); }, setHovering: function( model, value ) { this.set({ hovering: value }); }, setScrubbing: function( model, value ) { this.set({ scrubbing: value }); } }); revisions.model.Revision = Backbone.Model.extend({}); revisions.model.Revisions = Backbone.Collection.extend({ model: revisions.model.Revision, initialize: function() { _.bindAll( this, 'next', 'prev' ); }, next: function( revision ) { var index = this.indexOf( revision ); if ( index !== -1 && index !== this.length - 1 ) return this.at( index + 1 ); }, prev: function( revision ) { var index = this.indexOf( revision ); if ( index !== -1 && index !== 0 ) return this.at( index - 1 ); } }); revisions.model.Field = Backbone.Model.extend({}); revisions.model.Fields = Backbone.Collection.extend({ model: revisions.model.Field }); revisions.model.Diff = Backbone.Model.extend({ initialize: function( attributes, options ) { var fields = this.get('fields'); this.unset('fields'); this.fields = new revisions.model.Fields( fields ); } }); revisions.model.Diffs = Backbone.Collection.extend({ initialize: function( models, options ) { _.bindAll( this, 'getClosestUnloaded' ); this.loadAll = _.once( this._loadAll ); this.revisions = options.revisions; this.requests = {}; }, model: revisions.model.Diff, ensure: function( id, context ) { var diff = this.get( id ); var request = this.requests[ id ]; var deferred = $.Deferred(); var ids = {}; var from = id.split(':')[0]; var to = id.split(':')[1]; ids[id] = true; wp.revisions.log( 'ensure', id ); this.trigger( 'ensure', ids, from, to, deferred.promise() ); if ( diff ) { deferred.resolveWith( context, [ diff ] ); } else { this.trigger( 'ensure:load', ids, from, to, deferred.promise() ); _.each( ids, _.bind( function( id ) { // Remove anything that has an ongoing request if ( this.requests[ id ] ) delete ids[ id ]; // Remove anything we already have if ( this.get( id ) ) delete ids[ id ]; }, this ) ); if ( ! request ) { // Always include the ID that started this ensure ids[ id ] = true; request = this.load( _.keys( ids ) ); } request.done( _.bind( function() { deferred.resolveWith( context, [ this.get( id ) ] ); }, this ) ).fail( _.bind( function() { deferred.reject(); }) ); } return deferred.promise(); }, // Returns an array of proximal diffs getClosestUnloaded: function( ids, centerId ) { var self = this; return _.chain([0].concat( ids )).initial().zip( ids ).sortBy( function( pair ) { return Math.abs( centerId - pair[1] ); }).map( function( pair ) { return pair.join(':'); }).filter( function( diffId ) { return _.isUndefined( self.get( diffId ) ) && ! self.requests[ diffId ]; }).value(); }, _loadAll: function( allRevisionIds, centerId, num ) { var self = this, deferred = $.Deferred(); diffs = _.first( this.getClosestUnloaded( allRevisionIds, centerId ), num ); if ( _.size( diffs ) > 0 ) { this.load( diffs ).done( function() { self._loadAll( allRevisionIds, centerId, num ).done( function() { deferred.resolve(); }); }).fail( function() { if ( 1 === num ) { // Already tried 1. This just isn't working. Give up. deferred.reject(); } else { // Request fewer diffs this time self._loadAll( allRevisionIds, centerId, Math.ceil( num / 2 ) ).done( function() { deferred.resolve(); }); } }); } else { deferred.resolve(); } return deferred; }, load: function( comparisons ) { wp.revisions.log( 'load', comparisons ); // Our collection should only ever grow, never shrink, so remove: false return this.fetch({ data: { compare: comparisons }, remove: false }).done( function(){ wp.revisions.log( 'load:complete', comparisons ); }); }, sync: function( method, model, options ) { if ( 'read' === method ) { options = options || {}; options.context = this; options.data = _.extend( options.data || {}, { action: 'get-revision-diffs', post_id: revisions.settings.postId }); var deferred = wp.ajax.send( options ); var requests = this.requests; // Record that we're requesting each diff. if ( options.data.compare ) { _.each( options.data.compare, function( id ) { requests[ id ] = deferred; }); } // When the request completes, clear the stored request. deferred.always( function() { if ( options.data.compare ) { _.each( options.data.compare, function( id ) { delete requests[ id ]; }); } }); return deferred; // Otherwise, fall back to `Backbone.sync()`. } else { return Backbone.Model.prototype.sync.apply( this, arguments ); } } }); revisions.model.FrameState = Backbone.Model.extend({ defaults: { loading: false, error: false, compareTwoMode: false }, initialize: function( attributes, options ) { var properties = {}; _.bindAll( this, 'receiveDiff' ); this._debouncedEnsureDiff = _.debounce( this._ensureDiff, 200 ); this.revisions = options.revisions; this.diffs = new revisions.model.Diffs( [], { revisions: this.revisions }); // Set the initial diffs collection provided through the settings this.diffs.set( revisions.settings.diffData ); // Set up internal listeners this.listenTo( this, 'change:from', this.changeRevisionHandler ); this.listenTo( this, 'change:to', this.changeRevisionHandler ); this.listenTo( this, 'change:compareTwoMode', this.changeMode ); this.listenTo( this, 'update:revisions', this.updatedRevisions ); this.listenTo( this.diffs, 'ensure:load', this.updateLoadingStatus ); this.listenTo( this, 'update:diff', this.updateLoadingStatus ); // Set the initial revisions, baseUrl, and mode as provided through settings properties.to = this.revisions.get( revisions.settings.to ); properties.from = this.revisions.get( revisions.settings.from ); properties.compareTwoMode = revisions.settings.compareTwoMode; properties.baseUrl = revisions.settings.baseUrl; this.set( properties ); // Start the router if browser supports History API if ( window.history && window.history.pushState ) { this.router = new revisions.Router({ model: this }); Backbone.history.start({ pushState: true }); } }, updateLoadingStatus: function() { this.set( 'error', false ); this.set( 'loading', ! this.diff() ); }, changeMode: function( model, value ) { // If we were on the first revision before switching, we have to bump them over one if ( value && 0 === this.revisions.indexOf( this.get('to') ) ) { this.set({ from: this.revisions.at(0), to: this.revisions.at(1) }); } }, updatedRevisions: function( from, to ) { if ( this.get( 'compareTwoMode' ) ) { // TODO: compare-two loading strategy } else { this.diffs.loadAll( this.revisions.pluck('id'), to.id, 40 ); } }, // Fetch the currently loaded diff. diff: function() { return this.diffs.get( this._diffId ); }, // So long as `from` and `to` are changed at the same time, the diff // will only be updated once. This is because Backbone updates all of // the changed attributes in `set`, and then fires the `change` events. updateDiff: function( options ) { var from, to, diffId, diff; options = options || {}; from = this.get('from'); to = this.get('to'); diffId = ( from ? from.id : 0 ) + ':' + to.id; // Check if we're actually changing the diff id. if ( this._diffId === diffId ) return $.Deferred().reject().promise(); this._diffId = diffId; this.trigger( 'update:revisions', from, to ); diff = this.diffs.get( diffId ); // If we already have the diff, then immediately trigger the update. if ( diff ) { this.receiveDiff( diff ); return $.Deferred().resolve().promise(); // Otherwise, fetch the diff. } else { if ( options.immediate ) { return this._ensureDiff(); } else { this._debouncedEnsureDiff(); return $.Deferred().reject().promise(); } } }, // A simple wrapper around `updateDiff` to prevent the change event's // parameters from being passed through. changeRevisionHandler: function( model, value, options ) { this.updateDiff(); }, receiveDiff: function( diff ) { // Did we actually get a diff? if ( _.isUndefined( diff ) || _.isUndefined( diff.id ) ) { this.set({ loading: false, error: true }); } else if ( this._diffId === diff.id ) { // Make sure the current diff didn't change this.trigger( 'update:diff', diff ); } }, _ensureDiff: function() { return this.diffs.ensure( this._diffId, this ).always( this.receiveDiff ); } }); /** * ======================================================================== * VIEWS * ======================================================================== */ // The frame view. This contains the entire page. revisions.view.Frame = wp.Backbone.View.extend({ className: 'revisions', template: wp.template('revisions-frame'), initialize: function() { this.listenTo( this.model, 'update:diff', this.renderDiff ); this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode ); this.listenTo( this.model, 'change:loading', this.updateLoadingStatus ); this.listenTo( this.model, 'change:error', this.updateErrorStatus ); this.views.set( '.revisions-control-frame', new revisions.view.Controls({ model: this.model }) ); }, render: function() { wp.Backbone.View.prototype.render.apply( this, arguments ); $('html').css( 'overflow-y', 'scroll' ); $('#wpbody-content .wrap').append( this.el ); this.updateCompareTwoMode(); this.renderDiff( this.model.diff() ); this.views.ready(); return this; }, renderDiff: function( diff ) { this.views.set( '.revisions-diff-frame', new revisions.view.Diff({ model: diff }) ); }, updateLoadingStatus: function() { this.$el.toggleClass( 'loading', this.model.get('loading') ); }, updateErrorStatus: function() { this.$el.toggleClass( 'diff-error', this.model.get('error') ); }, updateCompareTwoMode: function() { this.$el.toggleClass( 'comparing-two-revisions', this.model.get('compareTwoMode') ); } }); // The control view. // This contains the revision slider, previous/next buttons, the meta info and the compare checkbox. revisions.view.Controls = wp.Backbone.View.extend({ className: 'revisions-controls', initialize: function() { _.bindAll( this, 'setWidth' ); // Add the button view this.views.add( new revisions.view.Buttons({ model: this.model }) ); // Add the checkbox view this.views.add( new revisions.view.Checkbox({ model: this.model }) ); // Prep the slider model var slider = new revisions.model.Slider({ frame: this.model, revisions: this.model.revisions }); // Prep the tooltip model var tooltip = new revisions.model.Tooltip({ frame: this.model, revisions: this.model.revisions, slider: slider }); // Add the tooltip view this.views.add( new revisions.view.Tooltip({ model: tooltip }) ); // Add the tickmarks view this.views.add( new revisions.view.Tickmarks({ model: tooltip }) ); // Add the slider view this.views.add( new revisions.view.Slider({ model: slider }) ); // Add the Metabox view this.views.add( new revisions.view.Metabox({ model: this.model }) ); }, ready: function() { this.top = this.$el.offset().top; this.window = $(window); this.window.on( 'scroll.wp.revisions', {controls: this}, function(e) { var controls = e.data.controls; var container = controls.$el.parent(); var scrolled = controls.window.scrollTop(); var frame = controls.views.parent; if ( scrolled >= controls.top ) { if ( ! frame.$el.hasClass('pinned') ) { controls.setWidth(); container.css('height', container.height() + 'px' ); controls.window.on('resize.wp.revisions.pinning click.wp.revisions.pinning', {controls: controls}, function(e) { e.data.controls.setWidth(); }); } frame.$el.addClass('pinned'); } else if ( frame.$el.hasClass('pinned') ) { controls.window.off('.wp.revisions.pinning'); controls.$el.css('width', 'auto'); frame.$el.removeClass('pinned'); container.css('height', 'auto'); controls.top = controls.$el.offset().top; } else { controls.top = controls.$el.offset().top; } }); }, setWidth: function() { this.$el.css('width', this.$el.parent().width() + 'px'); } }); // The tickmarks view revisions.view.Tickmarks = wp.Backbone.View.extend({ className: 'revisions-tickmarks', direction: isRtl ? 'right' : 'left', initialize: function() { this.listenTo( this.model, 'change:revision', this.reportTickPosition ); }, reportTickPosition: function( model, revision ) { var offset, thisOffset, parentOffset, tick, index = this.model.revisions.indexOf( revision ); thisOffset = this.$el.allOffsets(); parentOffset = this.$el.parent().allOffsets(); if ( index === this.model.revisions.length - 1 ) { // Last one offset = { rightPlusWidth: thisOffset.left - parentOffset.left + 1, leftPlusWidth: thisOffset.right - parentOffset.right + 1 }; } else { // Normal tick tick = this.$('div:nth-of-type(' + (index + 1) + ')'); offset = tick.allPositions(); _.extend( offset, { left: offset.left + thisOffset.left - parentOffset.left, right: offset.right + thisOffset.right - parentOffset.right }); _.extend( offset, { leftPlusWidth: offset.left + tick.outerWidth(), rightPlusWidth: offset.right + tick.outerWidth() }); } this.model.set({ offset: offset }); }, ready: function() { var tickCount, tickWidth; tickCount = this.model.revisions.length - 1; tickWidth = 1 / tickCount; this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px'); _(tickCount).times( function( index ){ this.$el.append( '<div style="' + this.direction + ': ' + ( 100 * tickWidth * index ) + '%"></div>' ); }, this ); } }); // The metabox view revisions.view.Metabox = wp.Backbone.View.extend({ className: 'revisions-meta', initialize: function() { // Add the 'from' view this.views.add( new revisions.view.MetaFrom({ model: this.model, className: 'diff-meta diff-meta-from' }) ); // Add the 'to' view this.views.add( new revisions.view.MetaTo({ model: this.model }) ); } }); // The revision meta view (to be extended) revisions.view.Meta = wp.Backbone.View.extend({ template: wp.template('revisions-meta'), events: { 'click .restore-revision': 'restoreRevision' }, initialize: function() { this.listenTo( this.model, 'update:revisions', this.render ); }, prepare: function() { return _.extend( this.model.toJSON()[this.type] || {}, { type: this.type }); }, restoreRevision: function() { document.location = this.model.get('to').attributes.restoreUrl; } }); // The revision meta 'from' view revisions.view.MetaFrom = revisions.view.Meta.extend({ className: 'diff-meta diff-meta-from', type: 'from' }); // The revision meta 'to' view revisions.view.MetaTo = revisions.view.Meta.extend({ className: 'diff-meta diff-meta-to', type: 'to' }); // The checkbox view. revisions.view.Checkbox = wp.Backbone.View.extend({ className: 'revisions-checkbox', template: wp.template('revisions-checkbox'), events: { 'click .compare-two-revisions': 'compareTwoToggle' }, initialize: function() { this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode ); }, ready: function() { if ( this.model.revisions.length < 3 ) $('.revision-toggle-compare-mode').hide(); }, updateCompareTwoMode: function() { this.$('.compare-two-revisions').prop( 'checked', this.model.get('compareTwoMode') ); }, // Toggle the compare two mode feature when the compare two checkbox is checked. compareTwoToggle: function( event ) { // Activate compare two mode? this.model.set({ compareTwoMode: $('.compare-two-revisions').prop('checked') }); } }); // The tooltip view. // Encapsulates the tooltip. revisions.view.Tooltip = wp.Backbone.View.extend({ className: 'revisions-tooltip', template: wp.template('revisions-meta'), initialize: function( options ) { this.listenTo( this.model, 'change:offset', this.render ); this.listenTo( this.model, 'change:hovering', this.toggleVisibility ); this.listenTo( this.model, 'change:scrubbing', this.toggleVisibility ); }, prepare: function() { if ( _.isNull( this.model.get('revision') ) ) return; else return _.extend( { type: 'tooltip' }, { attributes: this.model.get('revision').toJSON() }); }, render: function() { var direction, directionVal, flipped, css = {}, position = this.model.revisions.indexOf( this.model.get('revision') ) + 1; flipped = ( position / this.model.revisions.length ) > 0.5; if ( isRtl ) { direction = flipped ? 'left' : 'right'; directionVal = flipped ? 'leftPlusWidth' : direction; } else { direction = flipped ? 'right' : 'left'; directionVal = flipped ? 'rightPlusWidth' : direction; } otherDirection = 'right' === direction ? 'left': 'right'; wp.Backbone.View.prototype.render.apply( this, arguments ); css[direction] = this.model.get('offset')[directionVal] + 'px'; css[otherDirection] = ''; this.$el.toggleClass( 'flipped', flipped ).css( css ); }, visible: function() { return this.model.get( 'scrubbing' ) || this.model.get( 'hovering' ); }, toggleVisibility: function( options ) { if ( this.visible() ) this.$el.stop().show().fadeTo( 100 - this.el.style.opacity * 100, 1 ); else this.$el.stop().fadeTo( this.el.style.opacity * 300, 0, function(){ $(this).hide(); } ); return; } }); // The buttons view. // Encapsulates all of the configuration for the previous/next buttons. revisions.view.Buttons = wp.Backbone.View.extend({ className: 'revisions-buttons', template: wp.template('revisions-buttons'), events: { 'click .revisions-next .button': 'nextRevision', 'click .revisions-previous .button': 'previousRevision' }, initialize: function() { this.listenTo( this.model, 'update:revisions', this.disabledButtonCheck ); }, ready: function() { this.disabledButtonCheck(); }, // Go to a specific model index gotoModel: function( toIndex ) { var attributes = { to: this.model.revisions.at( toIndex ) }; // If we're at the first revision, unset 'from'. if ( toIndex ) attributes.from = this.model.revisions.at( toIndex - 1 ); else this.model.unset('from', { silent: true }); this.model.set( attributes ); }, // Go to the 'next' revision nextRevision: function() { var toIndex = this.model.revisions.indexOf( this.model.get('to') ) + 1; this.gotoModel( toIndex ); }, // Go to the 'previous' revision previousRevision: function() { var toIndex = this.model.revisions.indexOf( this.model.get('to') ) - 1; this.gotoModel( toIndex ); }, // Check to see if the Previous or Next buttons need to be disabled or enabled. disabledButtonCheck: function() { var maxVal = this.model.revisions.length - 1, minVal = 0, next = $('.revisions-next .button'), previous = $('.revisions-previous .button'), val = this.model.revisions.indexOf( this.model.get('to') ); // Disable "Next" button if you're on the last node. next.prop( 'disabled', ( maxVal === val ) ); // Disable "Previous" button if you're on the first node. previous.prop( 'disabled', ( minVal === val ) ); } }); // The slider view. revisions.view.Slider = wp.Backbone.View.extend({ className: 'wp-slider', direction: isRtl ? 'right' : 'left', events: { 'mousemove' : 'mouseMove' }, initialize: function() { _.bindAll( this, 'start', 'slide', 'stop', 'mouseMove', 'mouseEnter', 'mouseLeave' ); this.listenTo( this.model, 'update:slider', this.applySliderSettings ); }, ready: function() { this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px'); this.$el.slider( _.extend( this.model.toJSON(), { start: this.start, slide: this.slide, stop: this.stop }) ); this.$el.hoverIntent({ over: this.mouseEnter, out: this.mouseLeave, timeout: 800 }); this.applySliderSettings(); }, mouseMove: function( e ) { var zoneCount = this.model.revisions.length - 1, // One fewer zone than models sliderFrom = this.$el.allOffsets()[this.direction], // "From" edge of slider sliderWidth = this.$el.width(), // Width of slider tickWidth = sliderWidth / zoneCount, // Calculated width of zone actualX = isRtl? $(window).width() - e.pageX : e.pageX; // Flipped for RTL - sliderFrom; actualX = actualX - sliderFrom; // Offset of mouse position in slider var currentModelIndex = Math.floor( ( actualX + ( tickWidth / 2 ) ) / tickWidth ); // Calculate the model index // Ensure sane value for currentModelIndex. if ( currentModelIndex < 0 ) currentModelIndex = 0; else if ( currentModelIndex >= this.model.revisions.length ) currentModelIndex = this.model.revisions.length - 1; // Update the tooltip mode this.model.set({ hoveredRevision: this.model.revisions.at( currentModelIndex ) }); }, mouseLeave: function() { this.model.set({ hovering: false }); }, mouseEnter: function() { this.model.set({ hovering: true }); }, applySliderSettings: function() { this.$el.slider( _.pick( this.model.toJSON(), 'value', 'values', 'range' ) ); var handles = this.$('a.ui-slider-handle'); if ( this.model.get('compareTwoMode') ) { // in RTL mode the 'left handle' is the second in the slider, 'right' is first handles.first() .toggleClass( 'to-handle', !! isRtl ) .toggleClass( 'from-handle', ! isRtl ); handles.last() .toggleClass( 'from-handle', !! isRtl ) .toggleClass( 'to-handle', ! isRtl ); } else { handles.removeClass('from-handle to-handle'); } }, start: function( event, ui ) { this.model.set({ scrubbing: true }); // Track the mouse position to enable smooth dragging, // overrides default jQuery UI step behavior. $( window ).on( 'mousemove.wp.revisions', { view: this }, function( e ) { var view = e.data.view, leftDragBoundary = view.$el.offset().left, sliderOffset = leftDragBoundary, sliderRightEdge = leftDragBoundary + view.$el.width(), rightDragBoundary = sliderRightEdge, leftDragReset = '0', rightDragReset = '100%', handle = $( ui.handle ); // In two handle mode, ensure handles can't be dragged past each other. // Adjust left/right boundaries and reset points. if ( view.model.get('compareTwoMode') ) { var handles = handle.parent().find('.ui-slider-handle'); if ( handle.is( handles.first() ) ) { // We're the left handle rightDragBoundary = handles.last().offset().left; rightDragReset = rightDragBoundary - sliderOffset; } else { // We're the right handle leftDragBoundary = handles.first().offset().left + handles.first().width(); leftDragReset = leftDragBoundary - sliderOffset; } } // Follow mouse movements, as long as handle remains inside slider. if ( e.pageX < leftDragBoundary ) { handle.css( 'left', leftDragReset ); // Mouse to left of slider. } else if ( e.pageX > rightDragBoundary ) { handle.css( 'left', rightDragReset ); // Mouse to right of slider. } else { handle.css( 'left', e.pageX - sliderOffset ); // Mouse in slider. } } ); }, getPosition: function( position ) { return isRtl ? this.model.revisions.length - position - 1: position; }, // Responds to slide events slide: function( event, ui ) { var attributes, movedRevision; // Compare two revisions mode if ( this.model.get('compareTwoMode') ) { // Prevent sliders from occupying same spot if ( ui.values[1] === ui.values[0] ) return false; if ( isRtl ) ui.values.reverse(); attributes = { from: this.model.revisions.at( this.getPosition( ui.values[0] ) ), to: this.model.revisions.at( this.getPosition( ui.values[1] ) ) }; } else { attributes = { to: this.model.revisions.at( this.getPosition( ui.value ) ) }; // If we're at the first revision, unset 'from'. if ( this.getPosition( ui.value ) > 0 ) attributes.from = this.model.revisions.at( this.getPosition( ui.value ) - 1 ); else attributes.from = undefined; } movedRevision = this.model.revisions.at( this.getPosition( ui.value ) ); // If we are scrubbing, a scrub to a revision is considered a hover if ( this.model.get('scrubbing') ) attributes.hoveredRevision = movedRevision; this.model.set( attributes ); }, stop: function( event, ui ) { $( window ).off('mousemove.wp.revisions'); this.model.updateSliderSettings(); // To snap us back to a tick mark this.model.set({ scrubbing: false }); } }); // The diff view. // This is the view for the current active diff. revisions.view.Diff = wp.Backbone.View.extend({ className: 'revisions-diff', template: wp.template('revisions-diff'), // Generate the options to be passed to the template. prepare: function() { return _.extend({ fields: this.model.fields.toJSON() }, this.options ); } }); // The revisions router // takes URLs with #hash fragments and routes them revisions.Router = Backbone.Router.extend({ initialize: function( options ) { this.model = options.model; this.routes = _.object([ [ this.baseUrl( '?from=:from&to=:to' ), 'handleRoute' ], [ this.baseUrl( '?from=:from&to=:to' ), 'handleRoute' ] ]); // Maintain state and history when navigating this.listenTo( this.model, 'update:diff', _.debounce( this.updateUrl, 250 ) ); this.listenTo( this.model, 'change:compareTwoMode', this.updateUrl ); }, baseUrl: function( url ) { return this.model.get('baseUrl') + url; }, updateUrl: function() { var from = this.model.has('from') ? this.model.get('from').id : 0; var to = this.model.get('to').id; if ( this.model.get('compareTwoMode' ) ) this.navigate( this.baseUrl( '?from=' + from + '&to=' + to ) ); else this.navigate( this.baseUrl( '?revision=' + to ) ); }, handleRoute: function( a, b ) { var from, to, compareTwo = _.isUndefined( b ); if ( ! compareTwo ) { b = this.model.revisions.get( a ); a = this.model.revisions.prev( b ); b = b ? b.id : 0; a = a ? a.id : 0; } this.model.set({ from: this.model.revisions.get( parseInt( a, 10 ) ), to: this.model.revisions.get( parseInt( a, 10 ) ), compareTwoMode: compareTwo }); } }); // Initialize the revisions UI. revisions.init = function() { revisions.view.frame = new revisions.view.Frame({ model: new revisions.model.FrameState({}, { revisions: new revisions.model.Revisions( revisions.settings.revisionData ) }) }).render(); }; $( revisions.init ); }(jQuery));
JavaScript
var tagBox, commentsBox, editPermalink, makeSlugeditClickable, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint; // return an array with any duplicate, whitespace or values removed function array_unique_noempty(a) { var out = []; jQuery.each( a, function(key, val) { val = jQuery.trim(val); if ( val && jQuery.inArray(val, out) == -1 ) out.push(val); } ); return out; } (function($){ tagBox = { clean : function(tags) { var comma = postL10n.comma; if ( ',' !== comma ) tags = tags.replace(new RegExp(comma, 'g'), ','); tags = tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, ''); if ( ',' !== comma ) tags = tags.replace(/,/g, comma); return tags; }, parseTags : function(el) { var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'), thetags = taxbox.find('.the-tags'), comma = postL10n.comma, current_tags = thetags.val().split(comma), new_tags = []; delete current_tags[num]; $.each( current_tags, function(key, val) { val = $.trim(val); if ( val ) { new_tags.push(val); } }); thetags.val( this.clean( new_tags.join(comma) ) ); this.quickClicks(taxbox); return false; }, quickClicks : function(el) { var thetags = $('.the-tags', el), tagchecklist = $('.tagchecklist', el), id = $(el).attr('id'), current_tags, disabled; if ( !thetags.length ) return; disabled = thetags.prop('disabled'); current_tags = thetags.val().split(postL10n.comma); tagchecklist.empty(); $.each( current_tags, function( key, val ) { var span, xbutton; val = $.trim( val ); if ( ! val ) return; // Create a new span, and ensure the text is properly escaped. span = $('<span />').text( val ); // If tags editing isn't disabled, create the X button. if ( ! disabled ) { xbutton = $( '<a id="' + id + '-check-num-' + key + '" class="ntdelbutton">X</a>' ); xbutton.click( function(){ tagBox.parseTags(this); }); span.prepend('&nbsp;').prepend( xbutton ); } // Append the span to the tag list. tagchecklist.append( span ); }); }, flushTags : function(el, a, f) { a = a || false; var tags = $('.the-tags', el), newtag = $('input.newtag', el), comma = postL10n.comma, newtags, text; text = a ? $(a).text() : newtag.val(); tagsval = tags.val(); newtags = tagsval ? tagsval + comma + text : text; newtags = this.clean( newtags ); newtags = array_unique_noempty( newtags.split(comma) ).join(comma); tags.val(newtags); this.quickClicks(el); if ( !a ) newtag.val(''); if ( 'undefined' == typeof(f) ) newtag.focus(); return false; }, get : function(id) { var tax = id.substr(id.indexOf('-')+1); $.post(ajaxurl, {'action':'get-tagcloud', 'tax':tax}, function(r, stat) { if ( 0 == r || 'success' != stat ) r = wpAjax.broken; r = $('<p id="tagcloud-'+tax+'" class="the-tagcloud">'+r+'</p>'); $('a', r).click(function(){ tagBox.flushTags( $(this).closest('.inside').children('.tagsdiv'), this); return false; }); $('#'+id).after(r); }); }, init : function() { var t = this, ajaxtag = $('div.ajaxtag'); $('.tagsdiv').each( function() { tagBox.quickClicks(this); }); $('input.tagadd', ajaxtag).click(function(){ t.flushTags( $(this).closest('.tagsdiv') ); }); $('div.taghint', ajaxtag).click(function(){ $(this).css('visibility', 'hidden').parent().siblings('.newtag').focus(); }); $('input.newtag', ajaxtag).blur(function() { if ( this.value == '' ) $(this).parent().siblings('.taghint').css('visibility', ''); }).focus(function(){ $(this).parent().siblings('.taghint').css('visibility', 'hidden'); }).keyup(function(e){ if ( 13 == e.which ) { tagBox.flushTags( $(this).closest('.tagsdiv') ); return false; } }).keypress(function(e){ if ( 13 == e.which ) { e.preventDefault(); return false; } }).each(function(){ var tax = $(this).closest('div.tagsdiv').attr('id'); $(this).suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: postL10n.comma + ' ' } ); }); // save tags on post save/publish $('#post').submit(function(){ $('div.tagsdiv').each( function() { tagBox.flushTags(this, false, 1); }); }); // tag cloud $('a.tagcloud-link').click(function(){ tagBox.get( $(this).attr('id') ); $(this).unbind().click(function(){ $(this).siblings('.the-tagcloud').toggle(); return false; }); return false; }); } }; commentsBox = { st : 0, get : function(total, num) { var st = this.st, data; if ( ! num ) num = 20; this.st += num; this.total = total; $('#commentsdiv .spinner').show(); data = { 'action' : 'get-comments', 'mode' : 'single', '_ajax_nonce' : $('#add_comment_nonce').val(), 'p' : $('#post_ID').val(), 'start' : st, 'number' : num }; $.post(ajaxurl, data, function(r) { r = wpAjax.parseAjaxResponse(r); $('#commentsdiv .widefat').show(); $('#commentsdiv .spinner').hide(); if ( 'object' == typeof r && r.responses[0] ) { $('#the-comment-list').append( r.responses[0].data ); theList = theExtraList = null; $("a[className*=':']").unbind(); if ( commentsBox.st > commentsBox.total ) $('#show-comments').hide(); else $('#show-comments').show().children('a').html(postL10n.showcomm); return; } else if ( 1 == r ) { $('#show-comments').html(postL10n.endcomm); return; } $('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>'); } ); return false; } }; WPSetThumbnailHTML = function(html){ $('.inside', '#postimagediv').html(html); }; WPSetThumbnailID = function(id){ var field = $('input[value="_thumbnail_id"]', '#list-table'); if ( field.size() > 0 ) { $('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id); } }; WPRemoveThumbnail = function(nonce){ $.post(ajaxurl, { action:"set-post-thumbnail", post_id: $('#post_ID').val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie) }, function(str){ if ( str == '0' ) { alert( setPostThumbnailL10n.error ); } else { WPSetThumbnailHTML(str); } } ); }; $(document).on( 'heartbeat-send.refresh-lock', function( e, data ) { var lock = $('#active_post_lock').val(), post_id = $('#post_ID').val(), send = {}; if ( ! post_id || ! $('#post-lock-dialog').length ) return; send['post_id'] = post_id; if ( lock ) send['lock'] = lock; data['wp-refresh-post-lock'] = send; }); // Post locks: update the lock string or show the dialog if somebody has taken over editing $(document).on( 'heartbeat-tick.refresh-lock', function( e, data ) { var received, wrap, avatar; if ( data['wp-refresh-post-lock'] ) { received = data['wp-refresh-post-lock']; if ( received.lock_error ) { // show "editing taken over" message wrap = $('#post-lock-dialog'); if ( wrap.length && ! wrap.is(':visible') ) { if ( typeof autosave == 'function' ) { $(document).on('autosave-disable-buttons.post-lock', function() { wrap.addClass('saving'); }).on('autosave-enable-buttons.post-lock', function() { wrap.removeClass('saving').addClass('saved'); window.onbeforeunload = null; }); // Save the latest changes and disable if ( ! autosave() ) window.onbeforeunload = null; autosave = function(){}; } if ( received.lock_error.avatar_src ) { avatar = $('<img class="avatar avatar-64 photo" width="64" height="64" />').attr( 'src', received.lock_error.avatar_src.replace(/&amp;/g, '&') ); wrap.find('div.post-locked-avatar').empty().append( avatar ); } wrap.show().find('.currently-editing').text( received.lock_error.text ); wrap.find('.wp-tab-first').focus(); } } else if ( received.new_lock ) { $('#active_post_lock').val( received.new_lock ); } } }); }(jQuery)); (function($) { var check, timeout; function schedule() { check = false; window.clearTimeout( timeout ); timeout = window.setTimeout( function(){ check = true; }, 300000 ); } $(document).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) { var nonce, post_id; if ( check ) { if ( ( post_id = $('#post_ID').val() ) && ( nonce = $('#_wpnonce').val() ) ) { data['wp-refresh-post-nonces'] = { post_id: post_id, post_nonce: nonce }; } } }).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) { var nonces = data['wp-refresh-post-nonces']; if ( nonces ) { schedule(); if ( nonces.replace ) { $.each( nonces.replace, function( selector, value ) { $( '#' + selector ).val( value ); }); } if ( nonces.heartbeatNonce ) window.heartbeatSettings.nonce = nonces.heartbeatNonce; } }).ready( function() { schedule(); }); }(jQuery)); jQuery(document).ready( function($) { var stamp, visibility, sticky = '', last = 0, co = $('#content'); postboxes.add_postbox_toggles(pagenow); // Post locks: contain focus inside the dialog. If the dialog is shown, focus the first item. $('#post-lock-dialog .notification-dialog').on( 'keydown', function(e) { if ( e.which != 9 ) return; var target = $(e.target); if ( target.hasClass('wp-tab-first') && e.shiftKey ) { $(this).find('.wp-tab-last').focus(); e.preventDefault(); } else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) { $(this).find('.wp-tab-first').focus(); e.preventDefault(); } }).filter(':visible').find('.wp-tab-first').focus(); // multi-taxonomies if ( $('#tagsdiv-post_tag').length ) { tagBox.init(); } else { $('#side-sortables, #normal-sortables, #advanced-sortables').children('div.postbox').each(function(){ if ( this.id.indexOf('tagsdiv-') === 0 ) { tagBox.init(); return false; } }); } // categories $('.categorydiv').each( function(){ var this_id = $(this).attr('id'), catAddBefore, catAddAfter, taxonomyParts, taxonomy, settingName; taxonomyParts = this_id.split('-'); taxonomyParts.shift(); taxonomy = taxonomyParts.join('-'); settingName = taxonomy + '_tab'; if ( taxonomy == 'category' ) settingName = 'cats'; // TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.js $('a', '#' + taxonomy + '-tabs').click( function(){ var t = $(this).attr('href'); $(this).parent().addClass('tabs').siblings('li').removeClass('tabs'); $('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide(); $(t).show(); if ( '#' + taxonomy + '-all' == t ) deleteUserSetting(settingName); else setUserSetting(settingName, 'pop'); return false; }); if ( getUserSetting(settingName) ) $('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click(); // Ajax Cat $('#new' + taxonomy).one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } ); $('#new' + taxonomy).keypress( function(event){ if( 13 === event.keyCode ) { event.preventDefault(); $('#' + taxonomy + '-add-submit').click(); } }); $('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); }); catAddBefore = function( s ) { if ( !$('#new'+taxonomy).val() ) return false; s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize(); $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true ); return s; }; catAddAfter = function( r, s ) { var sup, drop = $('#new'+taxonomy+'_parent'); $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false ); if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) { drop.before(sup); drop.remove(); } }; $('#' + taxonomy + 'checklist').wpList({ alt: '', response: taxonomy + '-ajax-response', addBefore: catAddBefore, addAfter: catAddAfter }); $('#' + taxonomy + '-add-toggle').click( function() { $('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' ); $('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click(); $('#new'+taxonomy).focus(); return false; }); $('#' + taxonomy + 'checklist, #' + taxonomy + 'checklist-pop').on( 'click', 'li.popular-category > label input[type="checkbox"]', function() { var t = $(this), c = t.is(':checked'), id = t.val(); if ( id && t.parents('#taxonomy-'+taxonomy).length ) $('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c ); }); }); // end cats // Custom Fields if ( $('#postcustom').length ) { $('#the-list').wpList( { addAfter: function( xml, s ) { $('table#list-table').show(); }, addBefore: function( s ) { s.data += '&post_id=' + $('#post_ID').val(); return s; } }); } // submitdiv if ( $('#submitdiv').length ) { stamp = $('#timestamp').html(); visibility = $('#post-visibility-display').html(); function updateVisibility() { var pvSelect = $('#post-visibility-select'); if ( $('input:radio:checked', pvSelect).val() != 'public' ) { $('#sticky').prop('checked', false); $('#sticky-span').hide(); } else { $('#sticky-span').show(); } if ( $('input:radio:checked', pvSelect).val() != 'password' ) { $('#password-span').hide(); } else { $('#password-span').show(); } } function updateText() { if ( ! $('#timestampdiv').length ) return true; var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'), optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(); attemptedDate = new Date( aa, mm - 1, jj, hh, mn ); originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() ); currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() ); if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) { $('.timestamp-wrap', '#timestampdiv').addClass('form-invalid'); return false; } else { $('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid'); } if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) { publishOn = postL10n.publishOnFuture; $('#publish').val( postL10n.schedule ); } else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) { publishOn = postL10n.publishOn; $('#publish').val( postL10n.publish ); } else { publishOn = postL10n.publishOnPast; $('#publish').val( postL10n.update ); } if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack $('#timestamp').html(stamp); } else { $('#timestamp').html( publishOn + ' <b>' + postL10n.dateFormat.replace( '%1$s', $('option[value="' + $('#mm').val() + '"]', '#mm').text() ) .replace( '%2$s', jj ) .replace( '%3$s', aa ) .replace( '%4$s', hh ) .replace( '%5$s', mn ) + '</b> ' ); } if ( $('input:radio:checked', '#post-visibility-select').val() == 'private' ) { $('#publish').val( postL10n.update ); if ( optPublish.length == 0 ) { postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>'); } else { optPublish.html( postL10n.privatelyPublished ); } $('option[value="publish"]', postStatus).prop('selected', true); $('.edit-post-status', '#misc-publishing-actions').hide(); } else { if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) { if ( optPublish.length ) { optPublish.remove(); postStatus.val($('#hidden_post_status').val()); } } else { optPublish.html( postL10n.published ); } if ( postStatus.is(':hidden') ) $('.edit-post-status', '#misc-publishing-actions').show(); } $('#post-status-display').html($('option:selected', postStatus).text()); if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) { $('#save-post').hide(); } else { $('#save-post').show(); if ( $('option:selected', postStatus).val() == 'pending' ) { $('#save-post').show().val( postL10n.savePending ); } else { $('#save-post').show().val( postL10n.saveDraft ); } } return true; } $('.edit-visibility', '#visibility').click(function () { if ($('#post-visibility-select').is(":hidden")) { updateVisibility(); $('#post-visibility-select').slideDown('fast'); $(this).hide(); } return false; }); $('.cancel-post-visibility', '#post-visibility-select').click(function () { $('#post-visibility-select').slideUp('fast'); $('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true); $('#post_password').val($('#hidden-post-password').val()); $('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked')); $('#post-visibility-display').html(visibility); $('.edit-visibility', '#visibility').show(); updateText(); return false; }); $('.save-post-visibility', '#post-visibility-select').click(function () { // crazyhorse - multiple ok cancels var pvSelect = $('#post-visibility-select'); pvSelect.slideUp('fast'); $('.edit-visibility', '#visibility').show(); updateText(); if ( $('input:radio:checked', pvSelect).val() != 'public' ) { $('#sticky').prop('checked', false); } // WEAPON LOCKED if ( true == $('#sticky').prop('checked') ) { sticky = 'Sticky'; } else { sticky = ''; } $('#post-visibility-display').html( postL10n[$('input:radio:checked', pvSelect).val() + sticky] ); return false; }); $('input:radio', '#post-visibility-select').change(function() { updateVisibility(); }); $('#timestampdiv').siblings('a.edit-timestamp').click(function() { if ($('#timestampdiv').is(":hidden")) { $('#timestampdiv').slideDown('fast'); $('#mm').focus(); $(this).hide(); } return false; }); $('.cancel-timestamp', '#timestampdiv').click(function() { $('#timestampdiv').slideUp('fast'); $('#mm').val($('#hidden_mm').val()); $('#jj').val($('#hidden_jj').val()); $('#aa').val($('#hidden_aa').val()); $('#hh').val($('#hidden_hh').val()); $('#mn').val($('#hidden_mn').val()); $('#timestampdiv').siblings('a.edit-timestamp').show(); updateText(); return false; }); $('.save-timestamp', '#timestampdiv').click(function () { // crazyhorse - multiple ok cancels if ( updateText() ) { $('#timestampdiv').slideUp('fast'); $('#timestampdiv').siblings('a.edit-timestamp').show(); } return false; }); $('#post').on( 'submit', function(e){ if ( ! updateText() ) { e.preventDefault(); $('#timestampdiv').show(); $('#publishing-action .spinner').hide(); $('#publish').prop('disabled', false).removeClass('button-primary-disabled'); return false; } }); $('#post-status-select').siblings('a.edit-post-status').click(function() { if ($('#post-status-select').is(":hidden")) { $('#post-status-select').slideDown('fast'); $(this).hide(); } return false; }); $('.save-post-status', '#post-status-select').click(function() { $('#post-status-select').slideUp('fast'); $('#post-status-select').siblings('a.edit-post-status').show(); updateText(); return false; }); $('.cancel-post-status', '#post-status-select').click(function() { $('#post-status-select').slideUp('fast'); $('#post_status').val($('#hidden_post_status').val()); $('#post-status-select').siblings('a.edit-post-status').show(); updateText(); return false; }); } // end submitdiv // permalink if ( $('#edit-slug-box').length ) { editPermalink = function(post_id) { var i, c = 0, e = $('#editable-post-name'), revert_e = e.html(), real_slug = $('#post_name'), revert_slug = real_slug.val(), b = $('#edit-slug-buttons'), revert_b = b.html(), full = $('#editable-post-name-full').html(); $('#view-post-btn').hide(); b.html('<a href="#" class="save button button-small">'+postL10n.ok+'</a> <a class="cancel" href="#">'+postL10n.cancel+'</a>'); b.children('.save').click(function() { var new_slug = e.children('input').val(); if ( new_slug == $('#editable-post-name-full').text() ) { return $('.cancel', '#edit-slug-buttons').click(); } $.post(ajaxurl, { action: 'sample-permalink', post_id: post_id, new_slug: new_slug, new_title: $('#title').val(), samplepermalinknonce: $('#samplepermalinknonce').val() }, function(data) { var box = $('#edit-slug-box'); box.html(data); if (box.hasClass('hidden')) { box.fadeIn('fast', function () { box.removeClass('hidden'); }); } b.html(revert_b); real_slug.val(new_slug); makeSlugeditClickable(); $('#view-post-btn').show(); }); return false; }); $('.cancel', '#edit-slug-buttons').click(function() { $('#view-post-btn').show(); e.html(revert_e); b.html(revert_b); real_slug.val(revert_slug); return false; }); for ( i = 0; i < full.length; ++i ) { if ( '%' == full.charAt(i) ) c++; } slug_value = ( c > full.length / 4 ) ? '' : full; e.html('<input type="text" id="new-post-slug" value="'+slug_value+'" />').children('input').keypress(function(e) { var key = e.keyCode || 0; // on enter, just save the new slug, don't save the post if ( 13 == key ) { b.children('.save').click(); return false; } if ( 27 == key ) { b.children('.cancel').click(); return false; } }).keyup(function(e) { real_slug.val(this.value); }).focus(); } makeSlugeditClickable = function() { $('#editable-post-name').click(function() { $('#edit-slug-buttons').children('.edit-slug').click(); }); } makeSlugeditClickable(); } // word count if ( typeof(wpWordCount) != 'undefined' ) { $(document).triggerHandler('wpcountwords', [ co.val() ]); co.keyup( function(e) { var k = e.keyCode || e.charCode; if ( k == last ) return true; if ( 13 == k || 8 == last || 46 == last ) $(document).triggerHandler('wpcountwords', [ co.val() ]); last = k; return true; }); } wptitlehint = function(id) { id = id || 'title'; var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text'); if ( title.val() == '' ) titleprompt.removeClass('screen-reader-text'); titleprompt.click(function(){ $(this).addClass('screen-reader-text'); title.focus(); }); title.blur(function(){ if ( this.value == '' ) titleprompt.removeClass('screen-reader-text'); }).focus(function(){ titleprompt.addClass('screen-reader-text'); }).keydown(function(e){ titleprompt.addClass('screen-reader-text'); $(this).unbind(e); }); } wptitlehint(); // resizable textarea#content (function() { var textarea = $('textarea#content'), offset = null, el; // No point for touch devices if ( !textarea.length || 'ontouchstart' in window ) return; function dragging(e) { textarea.height( Math.max(50, offset + e.pageY) + 'px' ); return false; } function endDrag(e) { var height; textarea.focus(); $(document).unbind('mousemove', dragging).unbind('mouseup', endDrag); height = parseInt( textarea.css('height'), 10 ); // sanity check if ( height && height > 50 && height < 5000 ) setUserSetting( 'ed_size', height ); } textarea.css('resize', 'none'); el = $('<div id="content-resize-handle"><br></div>'); $('#wp-content-wrap').append(el); el.on('mousedown', function(e) { offset = textarea.height() - e.pageY; textarea.blur(); $(document).mousemove(dragging).mouseup(endDrag); return false; }); })(); if ( typeof(tinymce) != 'undefined' ) { tinymce.onAddEditor.add(function(mce, ed){ // iOS expands the iframe to full height and the user cannot adjust it. if ( ed.id != 'content' || tinymce.isIOS5 ) return; function getHeight() { var height, node = document.getElementById('content_ifr'), ifr_height = node ? parseInt( node.style.height, 10 ) : 0, tb_height = $('#content_tbl tr.mceFirst').height(); if ( !ifr_height || !tb_height ) return false; // total height including toolbar and statusbar height = ifr_height + tb_height + 21; // textarea height = total height - 33px toolbar height -= 33; return height; } // resize TinyMCE to match the textarea height when switching Text -> Visual ed.onLoadContent.add( function(ed, o) { var ifr_height, node = document.getElementById('content'), height = node ? parseInt( node.style.height, 10 ) : 0, tb_height = $('#content_tbl tr.mceFirst').height() || 33; // height cannot be under 50 or over 5000 if ( !height || height < 50 || height > 5000 ) height = 360; // default height for the main editor if ( getUserSetting( 'ed_size' ) > 5000 ) setUserSetting( 'ed_size', 360 ); // compensate for padding and toolbars ifr_height = ( height - tb_height ) + 12; // sanity check if ( ifr_height > 50 && ifr_height < 5000 ) { $('#content_tbl').css('height', '' ); $('#content_ifr').css('height', ifr_height + 'px' ); } }); // resize the textarea to match TinyMCE's height when switching Visual -> Text ed.onSaveContent.add( function(ed, o) { var height = getHeight(); if ( !height || height < 50 || height > 5000 ) return; $('textarea#content').css( 'height', height + 'px' ); }); // save on resizing TinyMCE ed.onPostRender.add(function() { $('#content_resize').on('mousedown.wp-mce-resize', function(e){ $(document).on('mouseup.wp-mce-resize', function(e){ var height; $(document).off('mouseup.wp-mce-resize'); height = getHeight(); // sanity check if ( height && height > 50 && height < 5000 ) setUserSetting( 'ed_size', height ); }); }); }); }); // When changing post formats, change the editor body class $('#post-formats-select input.post-format').on( 'change.set-editor-class', function( event ) { var editor, body, format = this.id; if ( format && $( this ).prop('checked') ) { editor = tinymce.get( 'content' ); if ( editor ) { body = editor.getBody(); body.className = body.className.replace( /\bpost-format-[^ ]+/, '' ); editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format ); } } }); } });
JavaScript
/** * WordPress Administration Navigation Menu * Interface JS functions * * @version 2.0.0 * * @package WordPress * @subpackage Administration */ var wpNavMenu; (function($) { var api = wpNavMenu = { options : { menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead. globalMaxDepth : 11 }, menuList : undefined, // Set in init. targetList : undefined, // Set in init. menusChanged : false, isRTL: !! ( 'undefined' != typeof isRtl && isRtl ), negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1, // Functions that run on init. init : function() { api.menuList = $('#menu-to-edit'); api.targetList = api.menuList; this.jQueryExtensions(); this.attachMenuEditListeners(); this.setupInputWithDefaultTitle(); this.attachQuickSearchListeners(); this.attachThemeLocationsListeners(); this.attachTabsPanelListeners(); this.attachUnsavedChangesListener(); if ( api.menuList.length ) this.initSortables(); if ( menus.oneThemeLocationNoMenus ) $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom ); this.initManageLocations(); this.initAccessibility(); this.initToggles(); }, jQueryExtensions : function() { // jQuery extensions $.fn.extend({ menuItemDepth : function() { var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left'); return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 ); }, updateDepthClass : function(current, prev) { return this.each(function(){ var t = $(this); prev = prev || t.menuItemDepth(); $(this).removeClass('menu-item-depth-'+ prev ) .addClass('menu-item-depth-'+ current ); }); }, shiftDepthClass : function(change) { return this.each(function(){ var t = $(this), depth = t.menuItemDepth(); $(this).removeClass('menu-item-depth-'+ depth ) .addClass('menu-item-depth-'+ (depth + change) ); }); }, childMenuItems : function() { var result = $(); this.each(function(){ var t = $(this), depth = t.menuItemDepth(), next = t.next(); while( next.length && next.menuItemDepth() > depth ) { result = result.add( next ); next = next.next(); } }); return result; }, shiftHorizontally : function( dir ) { return this.each(function(){ var t = $(this), depth = t.menuItemDepth(), newDepth = depth + dir; // Change .menu-item-depth-n class t.moveHorizontally( newDepth, depth ); }); }, moveHorizontally : function( newDepth, depth ) { return this.each(function(){ var t = $(this), children = t.childMenuItems(), diff = newDepth - depth, subItemText = t.find('.is-submenu'); // Change .menu-item-depth-n class t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId(); // If it has children, move those too if ( children ) { children.each(function( index ) { var t = $(this), thisDepth = t.menuItemDepth(), newDepth = thisDepth + diff; t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId(); }); } // Show "Sub item" helper text if (0 === newDepth) subItemText.hide(); else subItemText.show(); }); }, updateParentMenuItemDBId : function() { return this.each(function(){ var item = $(this), input = item.find( '.menu-item-data-parent-id' ), depth = parseInt( item.menuItemDepth() ), parentDepth = depth - 1, parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first(); if ( 0 == depth ) { // Item is on the top level, has no parent input.val(0); } else { // Find the parent item, and retrieve its object id. input.val( parent.find( '.menu-item-data-db-id' ).val() ); } }); }, hideAdvancedMenuItemFields : function() { return this.each(function(){ var that = $(this); $('.hide-column-tog').not(':checked').each(function(){ that.find('.field-' + $(this).val() ).addClass('hidden-field'); }); }); }, /** * Adds selected menu items to the menu. * * @param jQuery metabox The metabox jQuery object. */ addSelectedToMenu : function(processMethod) { if ( 0 == $('#menu-to-edit').length ) { return false; } return this.each(function() { var t = $(this), menuItems = {}, checkboxes = ( menus.oneThemeLocationNoMenus && 0 == t.find('.tabs-panel-active .categorychecklist li input:checked').length ) ? t.find('#page-all li input[type="checkbox"]') : t.find('.tabs-panel-active .categorychecklist li input:checked'), re = new RegExp('menu-item\\[(\[^\\]\]*)'); processMethod = processMethod || api.addMenuItemToBottom; // If no items are checked, bail. if ( !checkboxes.length ) return false; // Show the ajax spinner t.find('.spinner').show(); // Retrieve menu item data $(checkboxes).each(function(){ var t = $(this), listItemDBIDMatch = re.exec( t.attr('name') ), listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10); if ( this.className && -1 != this.className.indexOf('add-to-top') ) processMethod = api.addMenuItemToTop; menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID ); }); // Add the items api.addItemToMenu(menuItems, processMethod, function(){ // Deselect the items and hide the ajax spinner checkboxes.removeAttr('checked'); t.find('.spinner').hide(); }); }); }, getItemData : function( itemType, id ) { itemType = itemType || 'menu-item'; var itemData = {}, i, fields = [ 'menu-item-db-id', 'menu-item-object-id', 'menu-item-object', 'menu-item-parent-id', 'menu-item-position', 'menu-item-type', 'menu-item-title', 'menu-item-url', 'menu-item-description', 'menu-item-attr-title', 'menu-item-target', 'menu-item-classes', 'menu-item-xfn' ]; if( !id && itemType == 'menu-item' ) { id = this.find('.menu-item-data-db-id').val(); } if( !id ) return itemData; this.find('input').each(function() { var field; i = fields.length; while ( i-- ) { if( itemType == 'menu-item' ) field = fields[i] + '[' + id + ']'; else if( itemType == 'add-menu-item' ) field = 'menu-item[' + id + '][' + fields[i] + ']'; if ( this.name && field == this.name ) { itemData[fields[i]] = this.value; } } }); return itemData; }, setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id. itemType = itemType || 'menu-item'; if( !id && itemType == 'menu-item' ) { id = $('.menu-item-data-db-id', this).val(); } if( !id ) return this; this.find('input').each(function() { var t = $(this), field; $.each( itemData, function( attr, val ) { if( itemType == 'menu-item' ) field = attr + '[' + id + ']'; else if( itemType == 'add-menu-item' ) field = 'menu-item[' + id + '][' + attr + ']'; if ( field == t.attr('name') ) { t.val( val ); } }); }); return this; } }); }, countMenuItems : function( depth ) { return $( '.menu-item-depth-' + depth ).length; }, moveMenuItem : function( $this, dir ) { var menuItems = $('#menu-to-edit li'); menuItemsCount = menuItems.length, thisItem = $this.parents( 'li.menu-item' ), thisItemChildren = thisItem.childMenuItems(), thisItemData = thisItem.getItemData(), thisItemDepth = parseInt( thisItem.menuItemDepth() ), thisItemPosition = parseInt( thisItem.index() ), nextItem = thisItem.next(), nextItemChildren = nextItem.childMenuItems(), nextItemDepth = parseInt( nextItem.menuItemDepth() ) + 1, prevItem = thisItem.prev(), prevItemDepth = parseInt( prevItem.menuItemDepth() ), prevItemId = prevItem.getItemData()['menu-item-db-id']; switch ( dir ) { case 'up': var newItemPosition = thisItemPosition - 1; // Already at top if ( 0 === thisItemPosition ) break; // If a sub item is moved to top, shift it to 0 depth if ( 0 === newItemPosition && 0 !== thisItemDepth ) thisItem.moveHorizontally( 0, thisItemDepth ); // If prev item is sub item, shift to match depth if ( 0 !== prevItemDepth ) thisItem.moveHorizontally( prevItemDepth, thisItemDepth ); // Does this item have sub items? if ( thisItemChildren ) { var items = thisItem.add( thisItemChildren ); // Move the entire block items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId(); } else { thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId(); } break; case 'down': // Does this item have sub items? if ( thisItemChildren ) { var items = thisItem.add( thisItemChildren ), nextItem = menuItems.eq( items.length + thisItemPosition ), nextItemChildren = 0 !== nextItem.childMenuItems().length; if ( nextItemChildren ) { var newDepth = parseInt( nextItem.menuItemDepth() ) + 1; thisItem.moveHorizontally( newDepth, thisItemDepth ); } // Have we reached the bottom? if ( menuItemsCount === thisItemPosition + items.length ) break; items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId(); } else { // If next item has sub items, shift depth if ( 0 !== nextItemChildren.length ) thisItem.moveHorizontally( nextItemDepth, thisItemDepth ); // Have we reached the bottom if ( menuItemsCount === thisItemPosition + 1 ) break; thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId(); } break; case 'top': // Already at top if ( 0 === thisItemPosition ) break; // Does this item have sub items? if ( thisItemChildren ) { var items = thisItem.add( thisItemChildren ); // Move the entire block items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId(); } else { thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId(); } break; case 'left': // As far left as possible if ( 0 === thisItemDepth ) break; thisItem.shiftHorizontally( -1 ); break; case 'right': // Can't be sub item at top if ( 0 === thisItemPosition ) break; // Already sub item of prevItem if ( thisItemData['menu-item-parent-id'] === prevItemId ) break; thisItem.shiftHorizontally( 1 ); break; } $this.focus(); api.registerChange(); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, initAccessibility : function() { api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); // Events $( '.menus-move-up' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'up' ); e.preventDefault(); }); $( '.menus-move-down' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'down' ); e.preventDefault(); }); $( '.menus-move-top' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'top' ); e.preventDefault(); }); $( '.menus-move-left' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'left' ); e.preventDefault(); }); $( '.menus-move-right' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'right' ); e.preventDefault(); }); }, refreshAdvancedAccessibility : function() { // Hide all links by default $( '.menu-item-settings .field-move a' ).hide(); $( '.item-edit' ).each( function() { var $this = $(this), movement = [], availableMovement = '', menuItem = $this.parents( 'li.menu-item' ).first(), depth = menuItem.menuItemDepth(), isPrimaryMenuItem = ( 0 === depth ), itemName = $this.parents( '.menu-item-handle' ).find( '.menu-item-title' ).text(), position = parseInt( menuItem.index() ), prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1 ), prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(), prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(), totalMenuItems = $('#menu-to-edit li').length, hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length; // Where can they move this menu item? if ( 0 !== position ) { var thisLink = menuItem.find( '.menus-move-up' ); thisLink.prop( 'title', menus.moveUp ).show(); } if ( 0 !== position && isPrimaryMenuItem ) { var thisLink = menuItem.find( '.menus-move-top' ); thisLink.prop( 'title', menus.moveToTop ).show(); } if ( position + 1 !== totalMenuItems && 0 !== position ) { var thisLink = menuItem.find( '.menus-move-down' ); thisLink.prop( 'title', menus.moveDown ).show(); } if ( 0 === position && 0 !== hasSameDepthSibling ) { var thisLink = menuItem.find( '.menus-move-down' ); thisLink.prop( 'title', menus.moveDown ).show(); } if ( ! isPrimaryMenuItem ) { var thisLink = menuItem.find( '.menus-move-left' ), thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft ); thisLink.prop( 'title', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).html( thisLinkText ).show(); } if ( 0 !== position ) { if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) { var thisLink = menuItem.find( '.menus-move-right' ), thisLinkText = menus.under.replace( '%s', prevItemNameRight ); thisLink.prop( 'title', menus.moveUnder.replace( '%s', prevItemNameRight ) ).html( thisLinkText ).show(); } } if ( isPrimaryMenuItem ) { var primaryItems = $( '.menu-item-depth-0' ), itemPosition = primaryItems.index( menuItem ) + 1, totalMenuItems = primaryItems.length, // String together help text for primary menu items title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems ); } else { var parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1 ) ).first(), parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(), parentItemName = parentItem.find( '.menu-item-title' ).text(), subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ), itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1; // String together help text for sub menu items title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName ); } $this.prop('title', title).html( title ); }); }, refreshKeyboardAccessibility : function() { $( '.item-edit' ).off( 'focus' ).on( 'focus', function(){ $(this).off( 'keydown' ).on( 'keydown', function(e){ var $this = $(this); // Bail if it's not an arrow key if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which ) return; // Avoid multiple keydown events $this.off('keydown'); // Bail if there is only one menu item if ( 1 === $('#menu-to-edit li').length ) return; // If RTL, swap left/right arrows var arrows = { '38' : 'up', '40' : 'down', '37' : 'left', '39' : 'right' }; if ( $('body').hasClass('rtl') ) arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' }; switch ( arrows[e.which] ) { case 'up': api.moveMenuItem( $this, 'up' ); break; case 'down': api.moveMenuItem( $this, 'down' ); break; case 'left': api.moveMenuItem( $this, 'left' ); break; case 'right': api.moveMenuItem( $this, 'right' ); break; } // Put focus back on same menu item $( '#edit-' + thisItemData['menu-item-db-id'] ).focus(); return false; }); }); }, initToggles : function() { // init postboxes postboxes.add_postbox_toggles('nav-menus'); // adjust columns functions for menus UI columns.useCheckboxesForHidden(); columns.checked = function(field) { $('.field-' + field).removeClass('hidden-field'); } columns.unchecked = function(field) { $('.field-' + field).addClass('hidden-field'); } // hide fields api.menuList.hideAdvancedMenuItemFields(); $('.hide-postbox-tog').click(function () { var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(','); $.post(ajaxurl, { action: 'closed-postboxes', hidden: hidden, closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(), page: 'nav-menus' }); }); }, initSortables : function() { var currentDepth = 0, originalDepth, minDepth, maxDepth, prev, next, prevBottom, nextThreshold, helperHeight, transport, menuEdge = api.menuList.offset().left, body = $('body'), maxChildDepth, menuMaxDepth = initialMenuMaxDepth(); if( 0 != $( '#menu-to-edit li' ).length ) $( '.drag-instructions' ).show(); // Use the right edge if RTL. menuEdge += api.isRTL ? api.menuList.width() : 0; api.menuList.sortable({ handle: '.menu-item-handle', placeholder: 'sortable-placeholder', start: function(e, ui) { var height, width, parent, children, tempHolder; // handle placement for rtl orientation if ( api.isRTL ) ui.item[0].style.right = 'auto'; transport = ui.item.children('.menu-item-transport'); // Set depths. currentDepth must be set before children are located. originalDepth = ui.item.menuItemDepth(); updateCurrentDepth(ui, originalDepth); // Attach child elements to parent // Skip the placeholder parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item; children = parent.childMenuItems(); transport.append( children ); // Update the height of the placeholder to match the moving item. height = transport.outerHeight(); // If there are children, account for distance between top of children and parent height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0; height += ui.helper.outerHeight(); helperHeight = height; height -= 2; // Subtract 2 for borders ui.placeholder.height(height); // Update the width of the placeholder to match the moving item. maxChildDepth = originalDepth; children.each(function(){ var depth = $(this).menuItemDepth(); maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth; }); width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width width += api.depthToPx(maxChildDepth - originalDepth); // Account for children width -= 2; // Subtract 2 for borders ui.placeholder.width(width); // Update the list of menu items. tempHolder = ui.placeholder.next(); tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item $(this).sortable( "refresh" ); // The children aren't sortable. We should let jQ UI know. ui.item.after( ui.placeholder ); // reattach the placeholder. tempHolder.css('margin-top', 0); // reset the margin // Now that the element is complete, we can update... updateSharedVars(ui); }, stop: function(e, ui) { var children, depthChange = currentDepth - originalDepth; // Return child elements to the list children = transport.children().insertAfter(ui.item); // Add "sub menu" description var subMenuTitle = ui.item.find( '.item-title .is-submenu' ); if ( 0 < currentDepth ) subMenuTitle.show(); else subMenuTitle.hide(); // Update depth classes if( depthChange != 0 ) { ui.item.updateDepthClass( currentDepth ); children.shiftDepthClass( depthChange ); updateMenuMaxDepth( depthChange ); } // Register a change api.registerChange(); // Update the item data. ui.item.updateParentMenuItemDBId(); // address sortable's incorrectly-calculated top in opera ui.item[0].style.top = 0; // handle drop placement for rtl orientation if ( api.isRTL ) { ui.item[0].style.left = 'auto'; ui.item[0].style.right = 0; } api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, change: function(e, ui) { // Make sure the placeholder is inside the menu. // Otherwise fix it, or we're in trouble. if( ! ui.placeholder.parent().hasClass('menu') ) (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder ); updateSharedVars(ui); }, sort: function(e, ui) { var offset = ui.helper.offset(), edge = api.isRTL ? offset.left + ui.helper.width() : offset.left, depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge ); // Check and correct if depth is not within range. // Also, if the dragged element is dragged upwards over // an item, shift the placeholder to a child position. if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth; else if ( depth < minDepth ) depth = minDepth; if( depth != currentDepth ) updateCurrentDepth(ui, depth); // If we overlap the next element, manually shift downwards if( nextThreshold && offset.top + helperHeight > nextThreshold ) { next.after( ui.placeholder ); updateSharedVars( ui ); $(this).sortable( "refreshPositions" ); } } }); function updateSharedVars(ui) { var depth; prev = ui.placeholder.prev(); next = ui.placeholder.next(); // Make sure we don't select the moving item. if( prev[0] == ui.item[0] ) prev = prev.prev(); if( next[0] == ui.item[0] ) next = next.next(); prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0; nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0; minDepth = (next.length) ? next.menuItemDepth() : 0; if( prev.length ) maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth; else maxDepth = 0; } function updateCurrentDepth(ui, depth) { ui.placeholder.updateDepthClass( depth, currentDepth ); currentDepth = depth; } function initialMenuMaxDepth() { if( ! body[0].className ) return 0; var match = body[0].className.match(/menu-max-depth-(\d+)/); return match && match[1] ? parseInt(match[1]) : 0; } function updateMenuMaxDepth( depthChange ) { var depth, newDepth = menuMaxDepth; if ( depthChange === 0 ) { return; } else if ( depthChange > 0 ) { depth = maxChildDepth + depthChange; if( depth > menuMaxDepth ) newDepth = depth; } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) { while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 ) newDepth--; } // Update the depth class. body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth ); menuMaxDepth = newDepth; } }, initManageLocations : function () { $('#menu-locations-wrap form').submit(function(){ window.onbeforeunload = null; }); $('.menu-location-menus select').on('change', function () { var editLink = $(this).closest('tr').find('.locations-edit-menu-link'); if ($(this).find('option:selected').data('orig')) editLink.show(); else editLink.hide(); }); }, attachMenuEditListeners : function() { var that = this; $('#update-nav-menu').bind('click', function(e) { if ( e.target && e.target.className ) { if ( -1 != e.target.className.indexOf('item-edit') ) { return that.eventOnClickEditLink(e.target); } else if ( -1 != e.target.className.indexOf('menu-save') ) { return that.eventOnClickMenuSave(e.target); } else if ( -1 != e.target.className.indexOf('menu-delete') ) { return that.eventOnClickMenuDelete(e.target); } else if ( -1 != e.target.className.indexOf('item-delete') ) { return that.eventOnClickMenuItemDelete(e.target); } else if ( -1 != e.target.className.indexOf('item-cancel') ) { return that.eventOnClickCancelLink(e.target); } } }); $('#add-custom-links input[type="text"]').keypress(function(e){ if ( e.keyCode === 13 ) { e.preventDefault(); $("#submit-customlinkdiv").click(); } }); }, /** * An interface for managing default values for input elements * that is both JS and accessibility-friendly. * * Input elements that add the class 'input-with-default-title' * will have their values set to the provided HTML title when empty. */ setupInputWithDefaultTitle : function() { var name = 'input-with-default-title'; $('.' + name).each( function(){ var $t = $(this), title = $t.attr('title'), val = $t.val(); $t.data( name, title ); if( '' == val ) $t.val( title ); else if ( title == val ) return; else $t.removeClass( name ); }).focus( function(){ var $t = $(this); if( $t.val() == $t.data(name) ) $t.val('').removeClass( name ); }).blur( function(){ var $t = $(this); if( '' == $t.val() ) $t.addClass( name ).val( $t.data(name) ); }); $( '.blank-slate .input-with-default-title' ).focus(); }, attachThemeLocationsListeners : function() { var loc = $('#nav-menu-theme-locations'), params = {}; params['action'] = 'menu-locations-save'; params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val(); loc.find('input[type="submit"]').click(function() { loc.find('select').each(function() { params[this.name] = $(this).val(); }); loc.find('.spinner').show(); $.post( ajaxurl, params, function(r) { loc.find('.spinner').hide(); }); return false; }); }, attachQuickSearchListeners : function() { var searchTimer; $('.quick-search').keypress(function(e){ var t = $(this); if( 13 == e.which ) { api.updateQuickSearchResults( t ); return false; } if( searchTimer ) clearTimeout(searchTimer); searchTimer = setTimeout(function(){ api.updateQuickSearchResults( t ); }, 400); }).attr('autocomplete','off'); }, updateQuickSearchResults : function(input) { var panel, params, minSearchLength = 2, q = input.val(); if( q.length < minSearchLength ) return; panel = input.parents('.tabs-panel'); params = { 'action': 'menu-quick-search', 'response-format': 'markup', 'menu': $('#menu').val(), 'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(), 'q': q, 'type': input.attr('name') }; $('.spinner', panel).show(); $.post( ajaxurl, params, function(menuMarkup) { api.processQuickSearchQueryResponse(menuMarkup, params, panel); }); }, addCustomLink : function( processMethod ) { var url = $('#custom-menu-item-url').val(), label = $('#custom-menu-item-name').val(); processMethod = processMethod || api.addMenuItemToBottom; if ( '' == url || 'http://' == url ) return false; // Show the ajax spinner $('.customlinkdiv .spinner').show(); this.addLinkToMenu( url, label, processMethod, function() { // Remove the ajax spinner $('.customlinkdiv .spinner').hide(); // Set custom link form back to defaults $('#custom-menu-item-name').val('').blur(); $('#custom-menu-item-url').val('http://'); }); }, addLinkToMenu : function(url, label, processMethod, callback) { processMethod = processMethod || api.addMenuItemToBottom; callback = callback || function(){}; api.addItemToMenu({ '-1': { 'menu-item-type': 'custom', 'menu-item-url': url, 'menu-item-title': label } }, processMethod, callback); }, addItemToMenu : function(menuItem, processMethod, callback) { var menu = $('#menu').val(), nonce = $('#menu-settings-column-nonce').val(); processMethod = processMethod || function(){}; callback = callback || function(){}; params = { 'action': 'add-menu-item', 'menu': menu, 'menu-settings-column-nonce': nonce, 'menu-item': menuItem }; $.post( ajaxurl, params, function(menuMarkup) { var ins = $('#menu-instructions'); processMethod(menuMarkup, params); // Make it stand out a bit more visually, by adding a fadeIn $( 'li.pending' ).hide().fadeIn('slow'); $( '.drag-instructions' ).show(); if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length ) ins.addClass( 'menu-instructions-inactive' ); callback(); }); }, /** * Process the add menu item request response into menu list item. * * @param string menuMarkup The text server response of menu item markup. * @param object req The request arguments. */ addMenuItemToBottom : function( menuMarkup, req ) { $(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, addMenuItemToTop : function( menuMarkup, req ) { $(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, attachUnsavedChangesListener : function() { $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){ api.registerChange(); }); if ( 0 != $('#menu-to-edit').length || 0 != $('.menu-location-menus select').length ) { window.onbeforeunload = function(){ if ( api.menusChanged ) return navMenuL10n.saveAlert; }; } else { // Make the post boxes read-only, as they can't be used yet $( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' ); } }, registerChange : function() { api.menusChanged = true; }, attachTabsPanelListeners : function() { $('#menu-settings-column').bind('click', function(e) { var selectAreaMatch, panelId, wrapper, items, target = $(e.target); if ( target.hasClass('nav-tab-link') ) { panelId = target.data( 'type' ); wrapper = target.parents('.accordion-section-content').first(); // upon changing tabs, we want to uncheck all checkboxes $('input', wrapper).removeAttr('checked'); $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive'); $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active'); $('.tabs', wrapper).removeClass('tabs'); target.parent().addClass('tabs'); // select the search bar $('.quick-search', wrapper).focus(); e.preventDefault(); } else if ( target.hasClass('select-all') ) { selectAreaMatch = /#(.*)$/.exec(e.target.href); if ( selectAreaMatch && selectAreaMatch[1] ) { items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input'); if( items.length === items.filter(':checked').length ) items.removeAttr('checked'); else items.prop('checked', true); return false; } } else if ( target.hasClass('submit-add-to-menu') ) { api.registerChange(); if ( e.target.id && 'submit-customlinkdiv' == e.target.id ) api.addCustomLink( api.addMenuItemToBottom ); else if ( e.target.id && -1 != e.target.id.indexOf('submit-') ) $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom ); return false; } else if ( target.hasClass('page-numbers') ) { $.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox', function( resp ) { if ( -1 == resp.indexOf('replace-id') ) return; var metaBoxData = $.parseJSON(resp), toReplace = document.getElementById(metaBoxData['replace-id']), placeholder = document.createElement('div'), wrap = document.createElement('div'); if ( ! metaBoxData['markup'] || ! toReplace ) return; wrap.innerHTML = metaBoxData['markup'] ? metaBoxData['markup'] : ''; toReplace.parentNode.insertBefore( placeholder, toReplace ); placeholder.parentNode.removeChild( toReplace ); placeholder.parentNode.insertBefore( wrap, placeholder ); placeholder.parentNode.removeChild( placeholder ); } ); return false; } }); }, eventOnClickEditLink : function(clickedEl) { var settings, item, matchedSection = /#(.*)$/.exec(clickedEl.href); if ( matchedSection && matchedSection[1] ) { settings = $('#'+matchedSection[1]); item = settings.parent(); if( 0 != item.length ) { if( item.hasClass('menu-item-edit-inactive') ) { if( ! settings.data('menu-item-data') ) { settings.data( 'menu-item-data', settings.getItemData() ); } settings.slideDown('fast'); item.removeClass('menu-item-edit-inactive') .addClass('menu-item-edit-active'); } else { settings.slideUp('fast'); item.removeClass('menu-item-edit-active') .addClass('menu-item-edit-inactive'); } return false; } } }, eventOnClickCancelLink : function(clickedEl) { var settings = $( clickedEl ).closest( '.menu-item-settings' ), thisMenuItem = $( clickedEl ).closest( '.menu-item' ); thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive'); settings.setItemData( settings.data('menu-item-data') ).hide(); return false; }, eventOnClickMenuSave : function(clickedEl) { var locs = '', menuName = $('#menu-name'), menuNameVal = menuName.val(); // Cancel and warn if invalid menu name if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) { menuName.parent().addClass('form-invalid'); return false; } // Copy menu theme locations $('#nav-menu-theme-locations select').each(function() { locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />'; }); $('#update-nav-menu').append( locs ); // Update menu item position data api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } ); window.onbeforeunload = null; return true; }, eventOnClickMenuDelete : function(clickedEl) { // Delete warning AYS if ( confirm( navMenuL10n.warnDeleteMenu ) ) { window.onbeforeunload = null; return true; } return false; }, eventOnClickMenuItemDelete : function(clickedEl) { var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10); api.removeMenuItem( $('#menu-item-' + itemID) ); api.registerChange(); return false; }, /** * Process the quick search response into a search result * * @param string resp The server response to the query. * @param object req The request arguments. * @param jQuery panel The tabs panel we're searching in. */ processQuickSearchQueryResponse : function(resp, req, panel) { var matched, newID, takenIDs = {}, form = document.getElementById('nav-menu-meta'), pattern = new RegExp('menu-item\\[(\[^\\]\]*)', 'g'), $items = $('<div>').html(resp).find('li'), $item; if( ! $items.length ) { $('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' ); $('.spinner', panel).hide(); return; } $items.each(function(){ $item = $(this); // make a unique DB ID number matched = pattern.exec($item.html()); if ( matched && matched[1] ) { newID = matched[1]; while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) { newID--; } takenIDs[newID] = true; if ( newID != matched[1] ) { $item.html( $item.html().replace(new RegExp( 'menu-item\\[' + matched[1] + '\\]', 'g'), 'menu-item[' + newID + ']' ) ); } } }); $('.categorychecklist', panel).html( $items ); $('.spinner', panel).hide(); }, removeMenuItem : function(el) { var children = el.childMenuItems(); el.addClass('deleting').animate({ opacity : 0, height: 0 }, 350, function() { var ins = $('#menu-instructions'); el.remove(); children.shiftDepthClass( -1 ).updateParentMenuItemDBId(); if( 0 == $( '#menu-to-edit li' ).length ) { $( '.drag-instructions' ).hide(); ins.removeClass( 'menu-instructions-inactive' ); } }); }, depthToPx : function(depth) { return depth * api.options.menuItemDepthPerLevel; }, pxToDepth : function(px) { return Math.floor(px / api.options.menuItemDepthPerLevel); } }; $(document).ready(function(){ wpNavMenu.init(); }); })(jQuery);
JavaScript
var wpWidgets; (function($) { wpWidgets = { init : function() { var rem, sidebars = $('div.widgets-sortables'), isRTL = !! ( 'undefined' != typeof isRtl && isRtl ), margin = ( isRtl ? 'marginRight' : 'marginLeft' ), the_id; $('#widgets-right').children('.widgets-holder-wrap').children('.sidebar-name').click(function(){ var c = $(this).siblings('.widgets-sortables'), p = $(this).parent(); if ( !p.hasClass('closed') ) { c.sortable('disable'); p.addClass('closed'); } else { p.removeClass('closed'); c.sortable('enable').sortable('refresh'); } }); $('#widgets-left').children('.widgets-holder-wrap').children('.sidebar-name').click(function() { $(this).parent().toggleClass('closed'); }); sidebars.each(function(){ if ( $(this).parent().hasClass('inactive') ) return true; var h = 50, H = $(this).children('.widget').length; h = h + parseInt(H * 48, 10); $(this).css( 'minHeight', h + 'px' ); }); $(document.body).bind('click.widgets-toggle', function(e){ var target = $(e.target), css = {}, widget, inside, w; if ( target.parents('.widget-top').length && ! target.parents('#available-widgets').length ) { widget = target.closest('div.widget'); inside = widget.children('.widget-inside'); w = parseInt( widget.find('input.widget-width').val(), 10 ); if ( inside.is(':hidden') ) { if ( w > 250 && inside.closest('div.widgets-sortables').length ) { css['width'] = w + 30 + 'px'; if ( inside.closest('div.widget-liquid-right').length ) css[margin] = 235 - w + 'px'; widget.css(css); } wpWidgets.fixLabels(widget); inside.slideDown('fast'); } else { inside.slideUp('fast', function() { widget.css({'width':'', margin:''}); }); } e.preventDefault(); } else if ( target.hasClass('widget-control-save') ) { wpWidgets.save( target.closest('div.widget'), 0, 1, 0 ); e.preventDefault(); } else if ( target.hasClass('widget-control-remove') ) { wpWidgets.save( target.closest('div.widget'), 1, 1, 0 ); e.preventDefault(); } else if ( target.hasClass('widget-control-close') ) { wpWidgets.close( target.closest('div.widget') ); e.preventDefault(); } }); sidebars.children('.widget').each(function() { wpWidgets.appendTitle(this); if ( $('p.widget-error', this).length ) $('a.widget-action', this).click(); }); $('#widget-list').children('.widget').draggable({ connectToSortable: 'div.widgets-sortables', handle: '> .widget-top > .widget-title', distance: 2, helper: 'clone', zIndex: 100, containment: 'document', start: function(e,ui) { ui.helper.find('div.widget-description').hide(); the_id = this.id; }, stop: function(e,ui) { if ( rem ) $(rem).hide(); rem = ''; } }); sidebars.sortable({ placeholder: 'widget-placeholder', items: '> .widget', handle: '> .widget-top > .widget-title', cursor: 'move', distance: 2, containment: 'document', start: function(e,ui) { ui.item.children('.widget-inside').hide(); ui.item.css({margin:'', 'width':''}); }, stop: function(e,ui) { if ( ui.item.hasClass('ui-draggable') && ui.item.data('draggable') ) ui.item.draggable('destroy'); if ( ui.item.hasClass('deleting') ) { wpWidgets.save( ui.item, 1, 0, 1 ); // delete widget ui.item.remove(); return; } var add = ui.item.find('input.add_new').val(), n = ui.item.find('input.multi_number').val(), id = the_id, sb = $(this).attr('id'); ui.item.css({margin:'', 'width':''}); the_id = ''; if ( add ) { if ( 'multi' == add ) { ui.item.html( ui.item.html().replace(/<[^<>]+>/g, function(m){ return m.replace(/__i__|%i%/g, n); }) ); ui.item.attr( 'id', id.replace('__i__', n) ); n++; $('div#' + id).find('input.multi_number').val(n); } else if ( 'single' == add ) { ui.item.attr( 'id', 'new-' + id ); rem = 'div#' + id; } wpWidgets.save( ui.item, 0, 0, 1 ); ui.item.find('input.add_new').val(''); ui.item.find('a.widget-action').click(); return; } wpWidgets.saveOrder(sb); }, receive: function(e, ui) { var sender = $(ui.sender); if ( !$(this).is(':visible') || this.id.indexOf('orphaned_widgets') != -1 ) sender.sortable('cancel'); if ( sender.attr('id').indexOf('orphaned_widgets') != -1 && !sender.children('.widget').length ) { sender.parents('.orphan-sidebar').slideUp(400, function(){ $(this).remove(); }); } } }).sortable('option', 'connectWith', 'div.widgets-sortables').parent().filter('.closed').children('.widgets-sortables').sortable('disable'); $('#available-widgets').droppable({ tolerance: 'pointer', accept: function(o){ return $(o).parent().attr('id') != 'widget-list'; }, drop: function(e,ui) { ui.draggable.addClass('deleting'); $('#removing-widget').hide().children('span').html(''); }, over: function(e,ui) { ui.draggable.addClass('deleting'); $('div.widget-placeholder').hide(); if ( ui.draggable.hasClass('ui-sortable-helper') ) $('#removing-widget').show().children('span') .html( ui.draggable.find('div.widget-title').children('h4').html() ); }, out: function(e,ui) { ui.draggable.removeClass('deleting'); $('div.widget-placeholder').show(); $('#removing-widget').hide().children('span').html(''); } }); }, saveOrder : function(sb) { if ( sb ) $('#' + sb).closest('div.widgets-holder-wrap').find('.spinner').css('display', 'inline-block'); var a = { action: 'widgets-order', savewidgets: $('#_wpnonce_widgets').val(), sidebars: [] }; $('div.widgets-sortables').each( function() { if ( $(this).sortable ) a['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(','); }); $.post( ajaxurl, a, function() { $('.spinner').hide(); }); this.resize(); }, save : function(widget, del, animate, order) { var sb = widget.closest('div.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a; widget = $(widget); $('.spinner', widget).show(); a = { action: 'save-widget', savewidgets: $('#_wpnonce_widgets').val(), sidebar: sb }; if ( del ) a['delete_widget'] = 1; data += '&' + $.param(a); $.post( ajaxurl, data, function(r){ var id; if ( del ) { if ( !$('input.widget_number', widget).val() ) { id = $('input.widget-id', widget).val(); $('#available-widgets').find('input.widget-id').each(function(){ if ( $(this).val() == id ) $(this).closest('div.widget').show(); }); } if ( animate ) { order = 0; widget.slideUp('fast', function(){ $(this).remove(); wpWidgets.saveOrder(); }); } else { widget.remove(); wpWidgets.resize(); } } else { $('.spinner').hide(); if ( r && r.length > 2 ) { $('div.widget-content', widget).html(r); wpWidgets.appendTitle(widget); wpWidgets.fixLabels(widget); } } if ( order ) wpWidgets.saveOrder(); }); }, appendTitle : function(widget) { var title = $('input[id*="-title"]', widget).val() || ''; if ( title ) title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '&lt;').replace(/>/g, '&gt;'); $(widget).children('.widget-top').children('.widget-title').children() .children('.in-widget-title').html(title); }, resize : function() { $('div.widgets-sortables').each(function(){ if ( $(this).parent().hasClass('inactive') ) return true; var h = 50, H = $(this).children('.widget').length; h = h + parseInt(H * 48, 10); $(this).css( 'minHeight', h + 'px' ); }); }, fixLabels : function(widget) { widget.children('.widget-inside').find('label').each(function(){ var f = $(this).attr('for'); if ( f && f == $('input', this).attr('id') ) $(this).removeAttr('for'); }); }, close : function(widget) { widget.children('.widget-inside').slideUp('fast', function(){ widget.css({'width':'', margin:''}); }); } }; $(document).ready(function($){ wpWidgets.init(); }); })(jQuery);
JavaScript
(function($) { var frame; $( function() { // Fetch available headers and apply jQuery.masonry // once the images have loaded. var $headers = $('.available-headers'); $headers.imagesLoaded( function() { $headers.masonry({ itemSelector: '.default-header', isRTL: !! ( 'undefined' != typeof isRtl && isRtl ) }); }); // Build the choose from library frame. $('#choose-from-library-link').click( function( event ) { var $el = $(this); event.preventDefault(); // If the media frame already exists, reopen it. if ( frame ) { frame.open(); return; } // Create the media frame. frame = wp.media.frames.customHeader = wp.media({ // Set the title of the modal. title: $el.data('choose'), // Tell the modal to show only images. library: { type: 'image' }, // Customize the submit button. button: { // Set the text of the button. text: $el.data('update'), // Tell the button not to close the modal, since we're // going to refresh the page when the image is selected. close: false } }); // When an image is selected, run a callback. frame.on( 'select', function() { // Grab the selected attachment. var attachment = frame.state().get('selection').first(), link = $el.data('updateLink'); // Tell the browser to navigate to the crop step. window.location = link + '&file=' + attachment.id; }); frame.open(); }); }); }(jQuery));
JavaScript
var postboxes; (function($) { postboxes = { add_postbox_toggles : function(page, args) { var self = this; self.init(page, args); $('.postbox h3, .postbox .handlediv').bind('click.postboxes', function() { var p = $(this).parent('.postbox'), id = p.attr('id'); if ( 'dashboard_browser_nag' == id ) return; p.toggleClass('closed'); if ( page != 'press-this' ) self.save_state(page); if ( id ) { if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) ) self.pbshow(id); else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) ) self.pbhide(id); } }); $('.postbox h3 a').click( function(e) { e.stopPropagation(); }); $('.postbox a.dismiss').bind('click.postboxes', function(e) { var hide_id = $(this).parents('.postbox').attr('id') + '-hide'; $( '#' + hide_id ).prop('checked', false).triggerHandler('click'); return false; }); $('.hide-postbox-tog').bind('click.postboxes', function() { var box = $(this).val(); if ( $(this).prop('checked') ) { $('#' + box).show(); if ( $.isFunction( postboxes.pbshow ) ) self.pbshow( box ); } else { $('#' + box).hide(); if ( $.isFunction( postboxes.pbhide ) ) self.pbhide( box ); } self.save_state(page); self._mark_area(); }); $('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){ var n = parseInt($(this).val(), 10); if ( n ) { self._pb_edit(n); self.save_order(page); } }); }, init : function(page, args) { var isMobile = $(document.body).hasClass('mobile'); $.extend( this, args || {} ); $('#wpbody-content').css('overflow','hidden'); $('.meta-box-sortables').sortable({ placeholder: 'sortable-placeholder', connectWith: '.meta-box-sortables', items: '.postbox', handle: '.hndle', cursor: 'move', delay: ( isMobile ? 200 : 0 ), distance: 2, tolerance: 'pointer', forcePlaceholderSize: true, helper: 'clone', opacity: 0.65, stop: function(e,ui) { if ( $(this).find('#dashboard_browser_nag').is(':visible') && 'dashboard_browser_nag' != this.firstChild.id ) { $(this).sortable('cancel'); return; } postboxes.save_order(page); }, receive: function(e,ui) { if ( 'dashboard_browser_nag' == ui.item[0].id ) $(ui.sender).sortable('cancel'); postboxes._mark_area(); } }); if ( isMobile ) { $(document.body).bind('orientationchange.postboxes', function(){ postboxes._pb_change(); }); this._pb_change(); } this._mark_area(); }, save_state : function(page) { var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','), hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(','); $.post(ajaxurl, { action: 'closed-postboxes', closed: closed, hidden: hidden, closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(), page: page }); }, save_order : function(page) { var postVars, page_columns = $('.columns-prefs input:checked').val() || 0; postVars = { action: 'meta-box-order', _ajax_nonce: $('#meta-box-order-nonce').val(), page_columns: page_columns, page: page } $('.meta-box-sortables').each( function() { postVars["order[" + this.id.split('-')[0] + "]"] = $(this).sortable( 'toArray' ).join(','); } ); $.post( ajaxurl, postVars ); }, _mark_area : function() { var visible = $('div.postbox:visible').length, side = $('#post-body #side-sortables'); $('#dashboard-widgets .meta-box-sortables:visible').each(function(n, el){ var t = $(this); if ( visible == 1 || t.children('.postbox:visible').length ) t.removeClass('empty-container'); else t.addClass('empty-container'); }); if ( side.length ) { if ( side.children('.postbox:visible').length ) side.removeClass('empty-container'); else if ( $('#postbox-container-1').css('width') == '280px' ) side.addClass('empty-container'); } }, _pb_edit : function(n) { var el = $('.metabox-holder').get(0); el.className = el.className.replace(/columns-\d+/, 'columns-' + n); }, _pb_change : function() { var check = $( 'label.columns-prefs-1 input[type="radio"]' ); switch ( window.orientation ) { case 90: case -90: if ( !check.length || !check.is(':checked') ) this._pb_edit(2); break; case 0: case 180: if ( $('#poststuff').length ) { this._pb_edit(1); } else { if ( !check.length || !check.is(':checked') ) this._pb_edit(2); } break; } }, /* Callbacks */ pbshow : false, pbhide : false }; }(jQuery));
JavaScript
(function($) { inlineEditTax = { init : function() { var t = this, row = $('#inline-edit'); t.type = $('#the-list').attr('data-wp-lists').substr(5); t.what = '#'+t.type+'-'; $('#the-list').on('click', 'a.editinline', function(){ inlineEditTax.edit(this); return false; }); // prepare the edit row row.keyup(function(e) { if(e.which == 27) return inlineEditTax.revert(); }); $('a.cancel', row).click(function() { return inlineEditTax.revert(); }); $('a.save', row).click(function() { return inlineEditTax.save(this); }); $('input, select', row).keydown(function(e) { if(e.which == 13) return inlineEditTax.save(this); }); $('#posts-filter input[type="submit"]').mousedown(function(e){ t.revert(); }); }, toggle : function(el) { var t = this; $(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el); }, edit : function(id) { var t = this, editRow; t.revert(); if ( typeof(id) == 'object' ) id = t.getId(id); editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id); $('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length); if ( $(t.what+id).hasClass('alternate') ) $(editRow).addClass('alternate'); $(t.what+id).hide().after(editRow); $(':input[name="name"]', editRow).val( $('.name', rowData).text() ); $(':input[name="slug"]', editRow).val( $('.slug', rowData).text() ); $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show(); $('.ptitle', editRow).eq(0).focus(); return false; }, save : function(id) { var params, fields, tax = $('input[name="taxonomy"]').val() || ''; if( typeof(id) == 'object' ) id = this.getId(id); $('table.widefat .spinner').show(); params = { action: 'inline-save-tax', tax_type: this.type, tax_ID: id, taxonomy: tax }; fields = $('#edit-'+id+' :input').serialize(); params = fields + '&' + $.param(params); // make ajax request $.post( ajaxurl, params, function(r) { var row, new_id; $('table.widefat .spinner').hide(); if (r) { if ( -1 != r.indexOf('<tr') ) { $(inlineEditTax.what+id).remove(); new_id = $(r).attr('id'); $('#edit-'+id).before(r).remove(); row = new_id ? $('#'+new_id) : $(inlineEditTax.what+id); row.hide().fadeIn(); } else $('#edit-'+id+' .inline-edit-save .error').html(r).show(); } else $('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show(); } ); return false; }, revert : function() { var id = $('table.widefat tr.inline-editor').attr('id'); if ( id ) { $('table.widefat .spinner').hide(); $('#'+id).remove(); id = id.substr( id.lastIndexOf('-') + 1 ); $(this.what+id).show(); } return false; }, getId : function(o) { var id = o.tagName == 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-'); return parts[parts.length - 1]; } }; $(document).ready(function(){inlineEditTax.init();}); })(jQuery);
JavaScript
(function($) { var fs = {add:'ajaxAdd',del:'ajaxDel',dim:'ajaxDim',process:'process',recolor:'recolor'}, wpList; wpList = { settings: { url: ajaxurl, type: 'POST', response: 'ajax-response', what: '', alt: 'alternate', altOffset: 0, addColor: null, delColor: null, dimAddColor: null, dimDelColor: null, confirm: null, addBefore: null, addAfter: null, delBefore: null, delAfter: null, dimBefore: null, dimAfter: null }, nonce: function(e,s) { var url = wpAjax.unserialize(e.attr('href')); return s.nonce || url._ajax_nonce || $('#' + s.element + ' input[name="_ajax_nonce"]').val() || url._wpnonce || $('#' + s.element + ' input[name="_wpnonce"]').val() || 0; }, parseData: function(e,t) { var d = [], wpListsData; try { wpListsData = $(e).attr('data-wp-lists') || ''; wpListsData = wpListsData.match(new RegExp(t+':[\\S]+')); if ( wpListsData ) d = wpListsData[0].split(':'); } catch(r) {} return d; }, pre: function(e,s,a) { var bg, r; s = $.extend( {}, this.wpList.settings, { element: null, nonce: 0, target: e.get(0) }, s || {} ); if ( $.isFunction( s.confirm ) ) { if ( 'add' != a ) { bg = $('#' + s.element).css('backgroundColor'); $('#' + s.element).css('backgroundColor', '#FF9966'); } r = s.confirm.call(this, e, s, a, bg); if ( 'add' != a ) $('#' + s.element).css('backgroundColor', bg ); if ( !r ) return false; } return s; }, ajaxAdd: function( e, s ) { e = $(e); s = s || {}; var list = this, data = wpList.parseData(e,'add'), es, valid, formData, res, rres; s = wpList.pre.call( list, e, s, 'add' ); s.element = data[2] || e.attr( 'id' ) || s.element || null; if ( data[3] ) s.addColor = '#' + data[3]; else s.addColor = s.addColor || '#FFFF33'; if ( !s ) return false; if ( !e.is('[id="' + s.element + '-submit"]') ) return !wpList.add.call( list, e, s ); if ( !s.element ) return true; s.action = 'add-' + s.what; s.nonce = wpList.nonce(e,s); es = $('#' + s.element + ' :input').not('[name="_ajax_nonce"], [name="_wpnonce"], [name="action"]'); valid = wpAjax.validateForm( '#' + s.element ); if ( !valid ) return false; s.data = $.param( $.extend( { _ajax_nonce: s.nonce, action: s.action }, wpAjax.unserialize( data[4] || '' ) ) ); formData = $.isFunction(es.fieldSerialize) ? es.fieldSerialize() : es.serialize(); if ( formData ) s.data += '&' + formData; if ( $.isFunction(s.addBefore) ) { s = s.addBefore( s ); if ( !s ) return true; } if ( !s.data.match(/_ajax_nonce=[a-f0-9]+/) ) return true; s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) return false; if ( true === res ) return true; jQuery.each( res.responses, function() { wpList.add.call( list, this.data, $.extend( {}, s, { // this.firstChild.nodevalue pos: this.position || 0, id: this.id || 0, oldId: this.oldId || null } ) ); } ); list.wpList.recolor(); $(list).trigger( 'wpListAddEnd', [ s, list.wpList ] ); wpList.clear.call(list,'#' + s.element); }; s.complete = function(x, st) { if ( $.isFunction(s.addAfter) ) { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.addAfter( rres, _s ); } }; $.ajax( s ); return false; }, ajaxDel: function( e, s ) { e = $(e); s = s || {}; var list = this, data = wpList.parseData(e,'delete'), element, res, rres; s = wpList.pre.call( list, e, s, 'delete' ); s.element = data[2] || s.element || null; if ( data[3] ) s.delColor = '#' + data[3]; else s.delColor = s.delColor || '#faa'; if ( !s || !s.element ) return false; s.action = 'delete-' + s.what; s.nonce = wpList.nonce(e,s); s.data = $.extend( { action: s.action, id: s.element.split('-').pop(), _ajax_nonce: s.nonce }, wpAjax.unserialize( data[4] || '' ) ); if ( $.isFunction(s.delBefore) ) { s = s.delBefore( s, list ); if ( !s ) return true; } if ( !s.data._ajax_nonce ) return true; element = $('#' + s.element); if ( 'none' != s.delColor ) { element.css( 'backgroundColor', s.delColor ).fadeOut( 350, function(){ list.wpList.recolor(); $(list).trigger( 'wpListDelEnd', [ s, list.wpList ] ); }); } else { list.wpList.recolor(); $(list).trigger( 'wpListDelEnd', [ s, list.wpList ] ); } s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) { element.stop().stop().css( 'backgroundColor', '#faa' ).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } ); return false; } }; s.complete = function(x, st) { if ( $.isFunction(s.delAfter) ) { element.queue( function() { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.delAfter( rres, _s ); }).dequeue(); } } $.ajax( s ); return false; }, ajaxDim: function( e, s ) { if ( $(e).parent().css('display') == 'none' ) // Prevent hidden links from being clicked by hotkeys return false; e = $(e); s = s || {}; var list = this, data = wpList.parseData(e,'dim'), element, isClass, color, dimColor, res, rres; s = wpList.pre.call( list, e, s, 'dim' ); s.element = data[2] || s.element || null; s.dimClass = data[3] || s.dimClass || null; if ( data[4] ) s.dimAddColor = '#' + data[4]; else s.dimAddColor = s.dimAddColor || '#FFFF33'; if ( data[5] ) s.dimDelColor = '#' + data[5]; else s.dimDelColor = s.dimDelColor || '#FF3333'; if ( !s || !s.element || !s.dimClass ) return true; s.action = 'dim-' + s.what; s.nonce = wpList.nonce(e,s); s.data = $.extend( { action: s.action, id: s.element.split('-').pop(), dimClass: s.dimClass, _ajax_nonce : s.nonce }, wpAjax.unserialize( data[6] || '' ) ); if ( $.isFunction(s.dimBefore) ) { s = s.dimBefore( s ); if ( !s ) return true; } element = $('#' + s.element); isClass = element.toggleClass(s.dimClass).is('.' + s.dimClass); color = wpList.getColor( element ); element.toggleClass( s.dimClass ); dimColor = isClass ? s.dimAddColor : s.dimDelColor; if ( 'none' != dimColor ) { element .animate( { backgroundColor: dimColor }, 'fast' ) .queue( function() { element.toggleClass(s.dimClass); $(this).dequeue(); } ) .animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); $(list).trigger( 'wpListDimEnd', [ s, list.wpList ] ); } }); } else { $(list).trigger( 'wpListDimEnd', [ s, list.wpList ] ); } if ( !s.data._ajax_nonce ) return true; s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) { element.stop().stop().css( 'backgroundColor', '#FF3333' )[isClass?'removeClass':'addClass'](s.dimClass).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } ); return false; } }; s.complete = function(x, st) { if ( $.isFunction(s.dimAfter) ) { element.queue( function() { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.dimAfter( rres, _s ); }).dequeue(); } }; $.ajax( s ); return false; }, getColor: function( el ) { var color = jQuery(el).css('backgroundColor'); return color || '#ffffff'; }, add: function( e, s ) { e = $(e); var list = $(this), old = false, _s = { pos: 0, id: 0, oldId: null }, ba, ref, color; if ( 'string' == typeof s ) s = { what: s }; s = $.extend(_s, this.wpList.settings, s); if ( !e.size() || !s.what ) return false; if ( s.oldId ) old = $('#' + s.what + '-' + s.oldId); if ( s.id && ( s.id != s.oldId || !old || !old.size() ) ) $('#' + s.what + '-' + s.id).remove(); if ( old && old.size() ) { old.before(e); old.remove(); } else if ( isNaN(s.pos) ) { ba = 'after'; if ( '-' == s.pos.substr(0,1) ) { s.pos = s.pos.substr(1); ba = 'before'; } ref = list.find( '#' + s.pos ); if ( 1 === ref.size() ) ref[ba](e); else list.append(e); } else if ( 'comment' != s.what || 0 === $('#' + s.element).length ) { if ( s.pos < 0 ) { list.prepend(e); } else { list.append(e); } } if ( s.alt ) { if ( ( list.children(':visible').index( e[0] ) + s.altOffset ) % 2 ) { e.removeClass( s.alt ); } else { e.addClass( s.alt ); } } if ( 'none' != s.addColor ) { color = wpList.getColor( e ); e.css( 'backgroundColor', s.addColor ).animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); } } ); } list.each( function() { this.wpList.process( e ); } ); return e; }, clear: function(e) { var list = this, t, tag; e = $(e); if ( list.wpList && e.parents( '#' + list.id ).size() ) return; e.find(':input').each( function() { if ( $(this).parents('.form-no-clear').size() ) return; t = this.type.toLowerCase(); tag = this.tagName.toLowerCase(); if ( 'text' == t || 'password' == t || 'textarea' == tag ) this.value = ''; else if ( 'checkbox' == t || 'radio' == t ) this.checked = false; else if ( 'select' == tag ) this.selectedIndex = null; }); }, process: function(el) { var list = this, $el = $(el || document); $el.delegate( 'form[data-wp-lists^="add:' + list.id + ':"]', 'submit', function(){ return list.wpList.add(this); }); $el.delegate( 'a[data-wp-lists^="add:' + list.id + ':"], input[data-wp-lists^="add:' + list.id + ':"]', 'click', function(){ return list.wpList.add(this); }); $el.delegate( '[data-wp-lists^="delete:' + list.id + ':"]', 'click', function(){ return list.wpList.del(this); }); $el.delegate( '[data-wp-lists^="dim:' + list.id + ':"]', 'click', function(){ return list.wpList.dim(this); }); }, recolor: function() { var list = this, items, eo; if ( !list.wpList.settings.alt ) return; items = $('.list-item:visible', list); if ( !items.size() ) items = $(list).children(':visible'); eo = [':even',':odd']; if ( list.wpList.settings.altOffset % 2 ) eo.reverse(); items.filter(eo[0]).addClass(list.wpList.settings.alt).end().filter(eo[1]).removeClass(list.wpList.settings.alt); }, init: function() { var lists = this; lists.wpList.process = function(a) { lists.each( function() { this.wpList.process(a); } ); }; lists.wpList.recolor = function() { lists.each( function() { this.wpList.recolor(); } ); }; } }; $.fn.wpList = function( settings ) { this.each( function() { var _this = this; this.wpList = { settings: $.extend( {}, wpList.settings, { what: wpList.parseData(this,'list')[1] || '' }, settings ) }; $.each( fs, function(i,f) { _this.wpList[i] = function( e, s ) { return wpList[f].call( _this, e, s ); }; } ); } ); wpList.init.call(this); this.wpList.process(); return this; }; })(jQuery);
JavaScript
/*! * hoverIntent r7 // 2013.03.11 // jQuery 1.9.1+ * http://cherne.net/brian/resources/jquery.hoverIntent.html * * You may use hoverIntent under the terms of the MIT license. Basically that * means you are free to use hoverIntent as long as this header is left intact. * Copyright 2007, 2013 Brian Cherne */ /* hoverIntent is similar to jQuery's built-in "hover" method except that * instead of firing the handlerIn function immediately, hoverIntent checks * to see if the user's mouse has slowed down (beneath the sensitivity * threshold) before firing the event. The handlerOut function is only * called after a matching handlerIn. * * // basic usage ... just like .hover() * .hoverIntent( handlerIn, handlerOut ) * .hoverIntent( handlerInOut ) * * // basic usage ... with event delegation! * .hoverIntent( handlerIn, handlerOut, selector ) * .hoverIntent( handlerInOut, selector ) * * // using a basic configuration object * .hoverIntent( config ) * * @param handlerIn function OR configuration object * @param handlerOut function OR selector for delegation OR undefined * @param selector selector OR undefined * @author Brian Cherne <brian(at)cherne(dot)net> */ (function($) { $.fn.hoverIntent = function(handlerIn,handlerOut,selector) { // default configuration values var cfg = { interval: 100, sensitivity: 7, timeout: 0 }; if ( typeof handlerIn === "object" ) { cfg = $.extend(cfg, handlerIn ); } else if ($.isFunction(handlerOut)) { cfg = $.extend(cfg, { over: handlerIn, out: handlerOut, selector: selector } ); } else { cfg = $.extend(cfg, { over: handlerIn, out: handlerIn, selector: handlerOut } ); } // instantiate variables // cX, cY = current X and Y position of mouse, updated by mousemove event // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval var cX, cY, pX, pY; // A private function for getting mouse position var track = function(ev) { cX = ev.pageX; cY = ev.pageY; }; // A private function for comparing current and previous mouse position var compare = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); // compare mouse positions to see if they've crossed the threshold if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { $(ob).off("mousemove.hoverIntent",track); // set hoverIntent state to true (so mouseOut can be called) ob.hoverIntent_s = 1; return cfg.over.apply(ob,[ev]); } else { // set previous coordinates for next time pX = cX; pY = cY; // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); } }; // A private function for delaying the mouseOut function var delay = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob,[ev]); }; // A private function for handling mouse 'hovering' var handleHover = function(e) { // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); var ob = this; // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // if e.type == "mouseenter" if (e.type == "mouseenter") { // set "previous" X and Y position based on initial entry point pX = ev.pageX; pY = ev.pageY; // update "current" X and Y position based on mousemove $(ob).on("mousemove.hoverIntent",track); // start polling interval (self-calling timeout) to compare mouse coordinates over time if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} // else e.type == "mouseleave" } else { // unbind expensive mousemove event $(ob).off("mousemove.hoverIntent",track); // if hoverIntent state is true, then call the mouseOut function after the specified delay if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} } }; // listen for mouseenter and mouseleave return this.on({'mouseenter.hoverIntent':handleHover,'mouseleave.hoverIntent':handleHover}, cfg.selector); }; })(jQuery);
JavaScript
// Interim login dialog (function($){ var wrap, check, next; function show() { var parent = $('#wp-auth-check'), form = $('#wp-auth-check-form'), noframe = wrap.find('.wp-auth-fallback-expired'), frame, loaded = false; if ( form.length ) { // Add unload confirmation to counter (frame-busting) JS redirects $(window).on( 'beforeunload.wp-auth-check', function(e) { e.originalEvent.returnValue = window.authcheckL10n.beforeunload; }); frame = $('<iframe id="wp-auth-check-frame" frameborder="0">').attr( 'title', noframe.text() ); frame.load( function(e) { var height, body; loaded = true; try { body = $(this).contents().find('body'); height = body.height(); } catch(e) { wrap.addClass('fallback'); parent.css( 'max-height', '' ); form.remove(); noframe.focus(); return; } if ( height ) { if ( body && body.hasClass('interim-login-success') ) hide(); else parent.css( 'max-height', height + 40 + 'px' ); } else if ( ! body || ! body.length ) { // Catch "silent" iframe origin exceptions in WebKit after another page is loaded in the iframe wrap.addClass('fallback'); parent.css( 'max-height', '' ); form.remove(); noframe.focus(); } }).attr( 'src', form.data('src') ); $('#wp-auth-check-form').append( frame ); } wrap.removeClass('hidden'); if ( frame ) { frame.focus(); // WebKit doesn't throw an error if the iframe fails to load because of "X-Frame-Options: DENY" header. // Wait for 10 sec. and switch to the fallback text. setTimeout( function() { if ( ! loaded ) { wrap.addClass('fallback'); form.remove(); noframe.focus(); } }, 10000 ); } else { noframe.focus(); } } function hide() { $(window).off( 'beforeunload.wp-auth-check' ); // When on the Edit Post screen, speed up heartbeat after the user logs in to quickly refresh nonces if ( typeof adminpage != 'undefined' && ( adminpage == 'post-php' || adminpage == 'post-new-php' ) && typeof wp != 'undefined' && wp.heartbeat ) { wp.heartbeat.interval( 'fast', 1 ); } wrap.fadeOut( 200, function() { wrap.addClass('hidden').css('display', ''); $('#wp-auth-check-frame').remove(); }); } function schedule() { var interval = parseInt( window.authcheckL10n.interval, 10 ) || 180; // in seconds, default 3 min. next = ( new Date() ).getTime() + ( interval * 1000 ); } $( document ).on( 'heartbeat-tick.wp-auth-check', function( e, data ) { if ( 'wp-auth-check' in data ) { schedule(); if ( ! data['wp-auth-check'] && wrap.hasClass('hidden') ) show(); else if ( data['wp-auth-check'] && ! wrap.hasClass('hidden') ) hide(); } }).on( 'heartbeat-send.wp-auth-check', function( e, data ) { if ( ( new Date() ).getTime() > next ) data['wp-auth-check'] = true; }).ready( function() { schedule(); wrap = $('#wp-auth-check-wrap'); wrap.find('.wp-auth-check-close').on( 'click', function(e) { hide(); }); }); }(jQuery));
JavaScript
var autosave, autosaveLast = '', autosavePeriodical, autosaveDelayPreview = false, notSaved = true, blockSave = false, fullscreen, autosaveLockRelease = true; jQuery(document).ready( function($) { if ( $('#wp-content-wrap').hasClass('tmce-active') && typeof switchEditors != 'undefined' ) { autosaveLast = wp.autosave.getCompareString({ post_title : $('#title').val() || '', content : switchEditors.pre_wpautop( $('#content').val() ) || '', excerpt : $('#excerpt').val() || '' }); } else { autosaveLast = wp.autosave.getCompareString(); } autosavePeriodical = $.schedule({time: autosaveL10n.autosaveInterval * 1000, func: function() { autosave(); }, repeat: true, protect: true}); //Disable autosave after the form has been submitted $("#post").submit(function() { $.cancel(autosavePeriodical); autosaveLockRelease = false; }); $('input[type="submit"], a.submitdelete', '#submitpost').click(function(){ blockSave = true; window.onbeforeunload = null; $(':button, :submit', '#submitpost').each(function(){ var t = $(this); if ( t.hasClass('button-primary') ) t.addClass('button-primary-disabled'); else t.addClass('button-disabled'); }); if ( $(this).attr('id') == 'publish' ) $('#major-publishing-actions .spinner').show(); else $('#minor-publishing .spinner').show(); }); window.onbeforeunload = function(){ var editor = typeof(tinymce) != 'undefined' ? tinymce.activeEditor : false, compareString; if ( editor && ! editor.isHidden() ) { if ( editor.isDirty() ) return autosaveL10n.saveAlert; } else { if ( fullscreen && fullscreen.settings.visible ) { compareString = wp.autosave.getCompareString({ post_title: $('#wp-fullscreen-title').val() || '', content: $('#wp_mce_fullscreen').val() || '', excerpt: $('#excerpt').val() || '' }); } else { compareString = wp.autosave.getCompareString(); } if ( compareString != autosaveLast ) return autosaveL10n.saveAlert; } }; $(window).unload( function(e) { if ( ! autosaveLockRelease ) return; // unload fires (twice) on removing the Thickbox iframe. Make sure we process only the main document unload. if ( e.target && e.target.nodeName != '#document' ) return; $.ajax({ type: 'POST', url: ajaxurl, async: false, data: { action: 'wp-remove-post-lock', _wpnonce: $('#_wpnonce').val(), post_ID: $('#post_ID').val(), active_post_lock: $('#active_post_lock').val() } }); } ); // preview $('#post-preview').click(function(){ if ( $('#auto_draft').val() == '1' && notSaved ) { autosaveDelayPreview = true; autosave(); return false; } doPreview(); return false; }); doPreview = function() { $('input#wp-preview').val('dopreview'); $('form#post').attr('target', 'wp-preview').submit().attr('target', ''); /* * Workaround for WebKit bug preventing a form submitting twice to the same action. * https://bugs.webkit.org/show_bug.cgi?id=28633 */ var ua = navigator.userAgent.toLowerCase(); if ( ua.indexOf('safari') != -1 && ua.indexOf('chrome') == -1 ) { $('form#post').attr('action', function(index, value) { return value + '?t=' + new Date().getTime(); }); } $('input#wp-preview').val(''); } // This code is meant to allow tabbing from Title to Post content. $('#title').on('keydown.editor-focus', function(e) { var ed; if ( e.which != 9 ) return; if ( !e.ctrlKey && !e.altKey && !e.shiftKey ) { if ( typeof(tinymce) != 'undefined' ) ed = tinymce.get('content'); if ( ed && !ed.isHidden() ) { $(this).one('keyup', function(e){ $('#content_tbl td.mceToolbar > a').focus(); }); } else { $('#content').focus(); } e.preventDefault(); } }); // autosave new posts after a title is typed but not if Publish or Save Draft is clicked if ( '1' == $('#auto_draft').val() ) { $('#title').blur( function() { if ( !this.value || $('#auto_draft').val() != '1' ) return; delayed_autosave(); }); } // When connection is lost, keep user from submitting changes. $(document).on('heartbeat-connection-lost.autosave', function( e, error ) { if ( 'timeout' === error ) { var notice = $('#lost-connection-notice'); if ( ! wp.autosave.local.hasStorage ) { notice.find('.hide-if-no-sessionstorage').hide(); } notice.show(); autosave_disable_buttons(); } }).on('heartbeat-connection-restored.autosave', function() { $('#lost-connection-notice').hide(); autosave_enable_buttons(); }); }); function autosave_parse_response( response ) { var res = wpAjax.parseAjaxResponse(response, 'autosave'), post_id, sup; if ( res && res.responses && res.responses.length ) { if ( res.responses[0].supplemental ) { sup = res.responses[0].supplemental; jQuery.each( sup, function( selector, value ) { if ( selector.match(/^replace-/) ) jQuery( '#' + selector.replace('replace-', '') ).val( value ); }); } // if no errors: add slug UI and update autosave-message if ( !res.errors ) { if ( post_id = parseInt( res.responses[0].id, 10 ) ) autosave_update_slug( post_id ); if ( res.responses[0].data ) // update autosave message jQuery('.autosave-message').text( res.responses[0].data ); } } return res; } // called when autosaving pre-existing post function autosave_saved(response) { blockSave = false; autosave_parse_response(response); // parse the ajax response autosave_enable_buttons(); // re-enable disabled form buttons } // called when autosaving new post function autosave_saved_new(response) { blockSave = false; var res = autosave_parse_response(response), post_id; if ( res && res.responses.length && !res.errors ) { // An ID is sent only for real auto-saves, not for autosave=0 "keepalive" saves post_id = parseInt( res.responses[0].id, 10 ); if ( post_id ) { notSaved = false; jQuery('#auto_draft').val('0'); // No longer an auto-draft } autosave_enable_buttons(); if ( autosaveDelayPreview ) { autosaveDelayPreview = false; doPreview(); } } else { autosave_enable_buttons(); // re-enable disabled form buttons } } function autosave_update_slug(post_id) { // create slug area only if not already there if ( 'undefined' != makeSlugeditClickable && jQuery.isFunction(makeSlugeditClickable) && !jQuery('#edit-slug-box > *').size() ) { jQuery.post( ajaxurl, { action: 'sample-permalink', post_id: post_id, new_title: fullscreen && fullscreen.settings.visible ? jQuery('#wp-fullscreen-title').val() : jQuery('#title').val(), samplepermalinknonce: jQuery('#samplepermalinknonce').val() }, function(data) { if ( data !== '-1' ) { var box = jQuery('#edit-slug-box'); box.html(data); if (box.hasClass('hidden')) { box.fadeIn('fast', function () { box.removeClass('hidden'); }); } makeSlugeditClickable(); } } ); } } function autosave_loading() { jQuery('.autosave-message').html(autosaveL10n.savingText); } function autosave_enable_buttons() { jQuery(document).trigger('autosave-enable-buttons'); if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) { // delay that a bit to avoid some rare collisions while the DOM is being updated. setTimeout(function(){ var parent = jQuery('#submitpost'); parent.find(':button, :submit').removeAttr('disabled'); parent.find('.spinner').hide(); }, 500); } } function autosave_disable_buttons() { jQuery(document).trigger('autosave-disable-buttons'); jQuery('#submitpost').find(':button, :submit').prop('disabled', true); // Re-enable 5 sec later. Just gives autosave a head start to avoid collisions. setTimeout( autosave_enable_buttons, 5000 ); } function delayed_autosave() { setTimeout(function(){ if ( blockSave ) return; autosave(); }, 200); } autosave = function() { var post_data = wp.autosave.getPostData(), compareString, successCallback; blockSave = true; // post_data.content cannot be retrieved at the moment if ( ! post_data.autosave ) return false; // No autosave while thickbox is open (media buttons) if ( jQuery("#TB_window").css('display') == 'block' ) return false; compareString = wp.autosave.getCompareString( post_data ); // Nothing to save or no change. if ( compareString == autosaveLast ) return false; autosaveLast = compareString; jQuery(document).triggerHandler('wpcountwords', [ post_data["content"] ]); // Disable buttons until we know the save completed. autosave_disable_buttons(); if ( post_data["auto_draft"] == '1' ) { successCallback = autosave_saved_new; // new post } else { successCallback = autosave_saved; // pre-existing post } jQuery.ajax({ data: post_data, beforeSend: autosave_loading, type: "POST", url: ajaxurl, success: successCallback }); return true; } // Autosave in localStorage // set as simple object/mixin for now window.wp = window.wp || {}; wp.autosave = wp.autosave || {}; (function($){ // Returns the data for saving in both localStorage and autosaves to the server wp.autosave.getPostData = function() { var ed = typeof tinymce != 'undefined' ? tinymce.activeEditor : null, post_name, parent_id, cats = [], data = { action: 'autosave', autosave: true, post_id: $('#post_ID').val() || 0, autosavenonce: $('#autosavenonce').val() || '', post_type: $('#post_type').val() || '', post_author: $('#post_author').val() || '', excerpt: $('#excerpt').val() || '' }; if ( ed && !ed.isHidden() ) { // Don't run while the tinymce spellcheck is on. It resets all found words. if ( ed.plugins.spellchecker && ed.plugins.spellchecker.active ) { data.autosave = false; return data; } else { if ( 'mce_fullscreen' == ed.id ) tinymce.get('content').setContent(ed.getContent({format : 'raw'}), {format : 'raw'}); tinymce.triggerSave(); } } if ( typeof fullscreen != 'undefined' && fullscreen.settings.visible ) { data['post_title'] = $('#wp-fullscreen-title').val() || ''; data['content'] = $('#wp_mce_fullscreen').val() || ''; } else { data['post_title'] = $('#title').val() || ''; data['content'] = $('#content').val() || ''; } /* // We haven't been saving tags with autosave since 2.8... Start again? $('.the-tags').each( function() { data[this.name] = this.value; }); */ $('input[id^="in-category-"]:checked').each( function() { cats.push(this.value); }); data['catslist'] = cats.join(','); if ( post_name = $('#post_name').val() ) data['post_name'] = post_name; if ( parent_id = $('#parent_id').val() ) data['parent_id'] = parent_id; if ( $('#comment_status').prop('checked') ) data['comment_status'] = 'open'; if ( $('#ping_status').prop('checked') ) data['ping_status'] = 'open'; if ( $('#auto_draft').val() == '1' ) data['auto_draft'] = '1'; return data; }; // Concatenate title, content and excerpt. Used to track changes when auto-saving. wp.autosave.getCompareString = function( post_data ) { if ( typeof post_data === 'object' ) { return ( post_data.post_title || '' ) + '::' + ( post_data.content || '' ) + '::' + ( post_data.excerpt || '' ); } return ( $('#title').val() || '' ) + '::' + ( $('#content').val() || '' ) + '::' + ( $('#excerpt').val() || '' ); }; wp.autosave.local = { lastSavedData: '', blog_id: 0, hasStorage: false, // Check if the browser supports sessionStorage and it's not disabled checkStorage: function() { var test = Math.random(), result = false; try { sessionStorage.setItem('wp-test', test); result = sessionStorage.getItem('wp-test') == test; sessionStorage.removeItem('wp-test'); } catch(e) {} this.hasStorage = result; return result; }, /** * Initialize the local storage * * @return mixed False if no sessionStorage in the browser or an Object containing all post_data for this blog */ getStorage: function() { var stored_obj = false; // Separate local storage containers for each blog_id if ( this.hasStorage && this.blog_id ) { stored_obj = sessionStorage.getItem( 'wp-autosave-' + this.blog_id ); if ( stored_obj ) stored_obj = JSON.parse( stored_obj ); else stored_obj = {}; } return stored_obj; }, /** * Set the storage for this blog * * Confirms that the data was saved successfully. * * @return bool */ setStorage: function( stored_obj ) { var key; if ( this.hasStorage && this.blog_id ) { key = 'wp-autosave-' + this.blog_id; sessionStorage.setItem( key, JSON.stringify( stored_obj ) ); return sessionStorage.getItem( key ) !== null; } return false; }, /** * Get the saved post data for the current post * * @return mixed False if no storage or no data or the post_data as an Object */ getData: function() { var stored = this.getStorage(), post_id = $('#post_ID').val(); if ( !stored || !post_id ) return false; return stored[ 'post_' + post_id ] || false; }, /** * Set (save or delete) post data in the storage. * * If stored_data evaluates to 'false' the storage key for the current post will be removed * * $param stored_data The post data to store or null/false/empty to delete the key * @return bool */ setData: function( stored_data ) { var stored = this.getStorage(), post_id = $('#post_ID').val(); if ( !stored || !post_id ) return false; if ( stored_data ) stored[ 'post_' + post_id ] = stored_data; else if ( stored.hasOwnProperty( 'post_' + post_id ) ) delete stored[ 'post_' + post_id ]; else return false; return this.setStorage(stored); }, /** * Save post data for the current post * * Runs on a 15 sec. schedule, saves when there are differences in the post title or content. * When the optional data is provided, updates the last saved post data. * * $param data optional Object The post data for saving, minimum 'post_title' and 'content' * @return bool */ save: function( data ) { var result = false, post_data, compareString; if ( ! data ) { post_data = wp.autosave.getPostData(); } else { post_data = this.getData() || {}; $.extend( post_data, data ); post_data.autosave = true; } // Cannot get the post data at the moment if ( ! post_data.autosave ) return false; compareString = wp.autosave.getCompareString( post_data ); // If the content, title and excerpt did not change since the last save, don't save again if ( compareString == this.lastSavedData ) return false; post_data['save_time'] = (new Date()).getTime(); post_data['status'] = $('#post_status').val() || ''; result = this.setData( post_data ); if ( result ) this.lastSavedData = compareString; return result; }, // Initialize and run checkPost() on loading the script (before TinyMCE init) init: function( settings ) { var self = this; // Check if the browser supports sessionStorage and it's not disabled if ( ! this.checkStorage() ) return; // Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'. if ( ! $('#content').length && ! $('#excerpt').length ) return; if ( settings ) $.extend( this, settings ); if ( !this.blog_id ) this.blog_id = typeof window.autosaveL10n != 'undefined' ? window.autosaveL10n.blog_id : 0; $(document).ready( function(){ self.run(); } ); }, // Run on DOM ready run: function() { var self = this; // Check if the local post data is different than the loaded post data. this.checkPost(); // Set the schedule this.schedule = $.schedule({ time: 15 * 1000, func: function() { wp.autosave.local.save(); }, repeat: true, protect: true }); $('form#post').on('submit.autosave-local', function() { var editor = typeof tinymce != 'undefined' && tinymce.get('content'), post_id = $('#post_ID').val() || 0; if ( editor && ! editor.isHidden() ) { // Last onSubmit event in the editor, needs to run after the content has been moved to the textarea. editor.onSubmit.add( function() { wp.autosave.local.save({ post_title: $('#title').val() || '', content: $('#content').val() || '', excerpt: $('#excerpt').val() || '' }); }); } else { self.save({ post_title: $('#title').val() || '', content: $('#content').val() || '', excerpt: $('#excerpt').val() || '' }); } wpCookies.set( 'wp-saving-post-' + post_id, 'check' ); }); }, // Strip whitespace and compare two strings compare: function( str1, str2 ) { function remove( string ) { return string.toString().replace(/[\x20\t\r\n\f]+/g, ''); } return ( remove( str1 || '' ) == remove( str2 || '' ) ); }, /** * Check if the saved data for the current post (if any) is different than the loaded post data on the screen * * Shows a standard message letting the user restore the post data if different. * * @return void */ checkPost: function() { var self = this, post_data = this.getData(), content, post_title, excerpt, notice, post_id = $('#post_ID').val() || 0, cookie = wpCookies.get( 'wp-saving-post-' + post_id ); if ( ! post_data ) return; if ( cookie ) { wpCookies.remove( 'wp-saving-post-' + post_id ); if ( cookie == 'saved' ) { // The post was saved properly, remove old data and bail this.setData( false ); return; } } // There is a newer autosave. Don't show two "restore" notices at the same time. if ( $('#has-newer-autosave').length ) return; content = $('#content').val() || ''; post_title = $('#title').val() || ''; excerpt = $('#excerpt').val() || ''; if ( $('#wp-content-wrap').hasClass('tmce-active') && typeof switchEditors != 'undefined' ) content = switchEditors.pre_wpautop( content ); // cookie == 'check' means the post was not saved properly, always show #local-storage-notice if ( cookie != 'check' && this.compare( content, post_data.content ) && this.compare( post_title, post_data.post_title ) && this.compare( excerpt, post_data.excerpt ) ) { return; } this.restore_post_data = post_data; this.undo_post_data = { content: content, post_title: post_title, excerpt: excerpt }; notice = $('#local-storage-notice'); $('.wrap h2').first().after( notice.addClass('updated').show() ); notice.on( 'click', function(e) { var target = $( e.target ); if ( target.hasClass('restore-backup') ) { self.restorePost( self.restore_post_data ); target.parent().hide(); $(this).find('p.undo-restore').show(); } else if ( target.hasClass('undo-restore-backup') ) { self.restorePost( self.undo_post_data ); target.parent().hide(); $(this).find('p.local-restore').show(); } e.preventDefault(); }); }, // Restore the current title, content and excerpt from post_data. restorePost: function( post_data ) { var editor; if ( post_data ) { // Set the last saved data this.lastSavedData = wp.autosave.getCompareString( post_data ); if ( $('#title').val() != post_data.post_title ) $('#title').focus().val( post_data.post_title || '' ); $('#excerpt').val( post_data.excerpt || '' ); editor = typeof tinymce != 'undefined' && tinymce.get('content'); if ( editor && ! editor.isHidden() && typeof switchEditors != 'undefined' ) { // Make sure there's an undo level in the editor editor.undoManager.add(); editor.setContent( post_data.content ? switchEditors.wpautop( post_data.content ) : '' ); } else { // Make sure the Text editor is selected $('#content-html').click(); $('#content').val( post_data.content ); } return true; } return false; } }; wp.autosave.local.init(); }(jQuery));
JavaScript
/* * imgAreaSelect jQuery plugin * version 0.9.9 * * Copyright (c) 2008-2011 Michal Wojciechowski (odyniec.net) * * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://odyniec.net/projects/imgareaselect/ * */ (function($) { /* * Math functions will be used extensively, so it's convenient to make a few * shortcuts */ var abs = Math.abs, max = Math.max, min = Math.min, round = Math.round; /** * Create a new HTML div element * * @return A jQuery object representing the new element */ function div() { return $('<div/>'); } /** * imgAreaSelect initialization * * @param img * A HTML image element to attach the plugin to * @param options * An options object */ $.imgAreaSelect = function (img, options) { var /* jQuery object representing the image */ $img = $(img), /* Has the image finished loading? */ imgLoaded, /* Plugin elements */ /* Container box */ $box = div(), /* Selection area */ $area = div(), /* Border (four divs) */ $border = div().add(div()).add(div()).add(div()), /* Outer area (four divs) */ $outer = div().add(div()).add(div()).add(div()), /* Handles (empty by default, initialized in setOptions()) */ $handles = $([]), /* * Additional element to work around a cursor problem in Opera * (explained later) */ $areaOpera, /* Image position (relative to viewport) */ left, top, /* Image offset (as returned by .offset()) */ imgOfs = { left: 0, top: 0 }, /* Image dimensions (as returned by .width() and .height()) */ imgWidth, imgHeight, /* * jQuery object representing the parent element that the plugin * elements are appended to */ $parent, /* Parent element offset (as returned by .offset()) */ parOfs = { left: 0, top: 0 }, /* Base z-index for plugin elements */ zIndex = 0, /* Plugin elements position */ position = 'absolute', /* X/Y coordinates of the starting point for move/resize operations */ startX, startY, /* Horizontal and vertical scaling factors */ scaleX, scaleY, /* Current resize mode ("nw", "se", etc.) */ resize, /* Selection area constraints */ minWidth, minHeight, maxWidth, maxHeight, /* Aspect ratio to maintain (floating point number) */ aspectRatio, /* Are the plugin elements currently displayed? */ shown, /* Current selection (relative to parent element) */ x1, y1, x2, y2, /* Current selection (relative to scaled image) */ selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 }, /* Document element */ docElem = document.documentElement, /* Various helper variables used throughout the code */ $p, d, i, o, w, h, adjusted; /* * Translate selection coordinates (relative to scaled image) to viewport * coordinates (relative to parent element) */ /** * Translate selection X to viewport X * * @param x * Selection X * @return Viewport X */ function viewX(x) { return x + imgOfs.left - parOfs.left; } /** * Translate selection Y to viewport Y * * @param y * Selection Y * @return Viewport Y */ function viewY(y) { return y + imgOfs.top - parOfs.top; } /* * Translate viewport coordinates to selection coordinates */ /** * Translate viewport X to selection X * * @param x * Viewport X * @return Selection X */ function selX(x) { return x - imgOfs.left + parOfs.left; } /** * Translate viewport Y to selection Y * * @param y * Viewport Y * @return Selection Y */ function selY(y) { return y - imgOfs.top + parOfs.top; } /* * Translate event coordinates (relative to document) to viewport * coordinates */ /** * Get event X and translate it to viewport X * * @param event * The event object * @return Viewport X */ function evX(event) { return event.pageX - parOfs.left; } /** * Get event Y and translate it to viewport Y * * @param event * The event object * @return Viewport Y */ function evY(event) { return event.pageY - parOfs.top; } /** * Get the current selection * * @param noScale * If set to <code>true</code>, scaling is not applied to the * returned selection * @return Selection object */ function getSelection(noScale) { var sx = noScale || scaleX, sy = noScale || scaleY; return { x1: round(selection.x1 * sx), y1: round(selection.y1 * sy), x2: round(selection.x2 * sx), y2: round(selection.y2 * sy), width: round(selection.x2 * sx) - round(selection.x1 * sx), height: round(selection.y2 * sy) - round(selection.y1 * sy) }; } /** * Set the current selection * * @param x1 * X coordinate of the upper left corner of the selection area * @param y1 * Y coordinate of the upper left corner of the selection area * @param x2 * X coordinate of the lower right corner of the selection area * @param y2 * Y coordinate of the lower right corner of the selection area * @param noScale * If set to <code>true</code>, scaling is not applied to the * new selection */ function setSelection(x1, y1, x2, y2, noScale) { var sx = noScale || scaleX, sy = noScale || scaleY; selection = { x1: round(x1 / sx || 0), y1: round(y1 / sy || 0), x2: round(x2 / sx || 0), y2: round(y2 / sy || 0) }; selection.width = selection.x2 - selection.x1; selection.height = selection.y2 - selection.y1; } /** * Recalculate image and parent offsets */ function adjust() { /* * Do not adjust if image width is not a positive number. This might * happen when imgAreaSelect is put on a parent element which is then * hidden. */ if (!$img.width()) return; /* * Get image offset. The .offset() method returns float values, so they * need to be rounded. */ imgOfs = { left: round($img.offset().left), top: round($img.offset().top) }; /* Get image dimensions */ imgWidth = $img.innerWidth(); imgHeight = $img.innerHeight(); imgOfs.top += ($img.outerHeight() - imgHeight) >> 1; imgOfs.left += ($img.outerWidth() - imgWidth) >> 1; /* Set minimum and maximum selection area dimensions */ minWidth = round(options.minWidth / scaleX) || 0; minHeight = round(options.minHeight / scaleY) || 0; maxWidth = round(min(options.maxWidth / scaleX || 1<<24, imgWidth)); maxHeight = round(min(options.maxHeight / scaleY || 1<<24, imgHeight)); /* * Workaround for jQuery 1.3.2 incorrect offset calculation, originally * observed in Safari 3. Firefox 2 is also affected. */ if ($().jquery == '1.3.2' && position == 'fixed' && !docElem['getBoundingClientRect']) { imgOfs.top += max(document.body.scrollTop, docElem.scrollTop); imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft); } /* Determine parent element offset */ parOfs = /absolute|relative/.test($parent.css('position')) ? { left: round($parent.offset().left) - $parent.scrollLeft(), top: round($parent.offset().top) - $parent.scrollTop() } : position == 'fixed' ? { left: $(document).scrollLeft(), top: $(document).scrollTop() } : { left: 0, top: 0 }; left = viewX(0); top = viewY(0); /* * Check if selection area is within image boundaries, adjust if * necessary */ if (selection.x2 > imgWidth || selection.y2 > imgHeight) doResize(); } /** * Update plugin elements * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ function update(resetKeyPress) { /* If plugin elements are hidden, do nothing */ if (!shown) return; /* * Set the position and size of the container box and the selection area * inside it */ $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) }) .add($area).width(w = selection.width).height(h = selection.height); /* * Reset the position of selection area, borders, and handles (IE6/IE7 * position them incorrectly if we don't do this) */ $area.add($border).add($handles).css({ left: 0, top: 0 }); /* Set border dimensions */ $border .width(max(w - $border.outerWidth() + $border.innerWidth(), 0)) .height(max(h - $border.outerHeight() + $border.innerHeight(), 0)); /* Arrange the outer area elements */ $($outer[0]).css({ left: left, top: top, width: selection.x1, height: imgHeight }); $($outer[1]).css({ left: left + selection.x1, top: top, width: w, height: selection.y1 }); $($outer[2]).css({ left: left + selection.x2, top: top, width: imgWidth - selection.x2, height: imgHeight }); $($outer[3]).css({ left: left + selection.x1, top: top + selection.y2, width: w, height: imgHeight - selection.y2 }); w -= $handles.outerWidth(); h -= $handles.outerHeight(); /* Arrange handles */ switch ($handles.length) { case 8: $($handles[4]).css({ left: w >> 1 }); $($handles[5]).css({ left: w, top: h >> 1 }); $($handles[6]).css({ left: w >> 1, top: h }); $($handles[7]).css({ top: h >> 1 }); case 4: $handles.slice(1,3).css({ left: w }); $handles.slice(2,4).css({ top: h }); } if (resetKeyPress !== false) { /* * Need to reset the document keypress event handler -- unbind the * current handler */ if ($.imgAreaSelect.keyPress != docKeyPress) $(document).unbind($.imgAreaSelect.keyPress, $.imgAreaSelect.onKeyPress); if (options.keys) /* * Set the document keypress event handler to this instance's * docKeyPress() function */ $(document)[$.imgAreaSelect.keyPress]( $.imgAreaSelect.onKeyPress = docKeyPress); } /* * Internet Explorer displays 1px-wide dashed borders incorrectly by * filling the spaces between dashes with white. Toggling the margin * property between 0 and "auto" fixes this in IE6 and IE7 (IE8 is still * broken). This workaround is not perfect, as it requires setTimeout() * and thus causes the border to flicker a bit, but I haven't found a * better solution. * * Note: This only happens with CSS borders, set with the borderWidth, * borderOpacity, borderColor1, and borderColor2 options (which are now * deprecated). Borders created with GIF background images are fine. */ if ($.browser.msie && $border.outerWidth() - $border.innerWidth() == 2) { $border.css('margin', 0); setTimeout(function () { $border.css('margin', 'auto'); }, 0); } } /** * Do the complete update sequence: recalculate offsets, update the * elements, and set the correct values of x1, y1, x2, and y2. * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ function doUpdate(resetKeyPress) { adjust(); update(resetKeyPress); x1 = viewX(selection.x1); y1 = viewY(selection.y1); x2 = viewX(selection.x2); y2 = viewY(selection.y2); } /** * Hide or fade out an element (or multiple elements) * * @param $elem * A jQuery object containing the element(s) to hide/fade out * @param fn * Callback function to be called when fadeOut() completes */ function hide($elem, fn) { options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide(); } /** * Selection area mousemove event handler * * @param event * The event object */ function areaMouseMove(event) { var x = selX(evX(event)) - selection.x1, y = selY(evY(event)) - selection.y1; if (!adjusted) { adjust(); adjusted = true; $box.one('mouseout', function () { adjusted = false; }); } /* Clear the resize mode */ resize = ''; if (options.resizable) { /* * Check if the mouse pointer is over the resize margin area and set * the resize mode accordingly */ if (y <= options.resizeMargin) resize = 'n'; else if (y >= selection.height - options.resizeMargin) resize = 's'; if (x <= options.resizeMargin) resize += 'w'; else if (x >= selection.width - options.resizeMargin) resize += 'e'; } $box.css('cursor', resize ? resize + '-resize' : options.movable ? 'move' : ''); if ($areaOpera) $areaOpera.toggle(); } /** * Document mouseup event handler * * @param event * The event object */ function docMouseUp(event) { /* Set back the default cursor */ $('body').css('cursor', ''); /* * If autoHide is enabled, or if the selection has zero width/height, * hide the selection and the outer area */ if (options.autoHide || selection.width * selection.height == 0) hide($box.add($outer), function () { $(this).hide(); }); $(document).unbind('mousemove', selectingMouseMove); $box.mousemove(areaMouseMove); options.onSelectEnd(img, getSelection()); } /** * Selection area mousedown event handler * * @param event * The event object * @return false */ function areaMouseDown(event) { if (event.which != 1) return false; adjust(); if (resize) { /* Resize mode is in effect */ $('body').css('cursor', resize + '-resize'); x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']); y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']); $(document).mousemove(selectingMouseMove) .one('mouseup', docMouseUp); $box.unbind('mousemove', areaMouseMove); } else if (options.movable) { startX = left + selection.x1 - evX(event); startY = top + selection.y1 - evY(event); $box.unbind('mousemove', areaMouseMove); $(document).mousemove(movingMouseMove) .one('mouseup', function () { options.onSelectEnd(img, getSelection()); $(document).unbind('mousemove', movingMouseMove); $box.mousemove(areaMouseMove); }); } else $img.mousedown(event); return false; } /** * Adjust the x2/y2 coordinates to maintain aspect ratio (if defined) * * @param xFirst * If set to <code>true</code>, calculate x2 first. Otherwise, * calculate y2 first. */ function fixAspectRatio(xFirst) { if (aspectRatio) if (xFirst) { x2 = max(left, min(left + imgWidth, x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))); y2 = round(max(top, min(top + imgHeight, y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)))); x2 = round(x2); } else { y2 = max(top, min(top + imgHeight, y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))); x2 = round(max(left, min(left + imgWidth, x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)))); y2 = round(y2); } } /** * Resize the selection area respecting the minimum/maximum dimensions and * aspect ratio */ function doResize() { /* * Make sure the top left corner of the selection area stays within * image boundaries (it might not if the image source was dynamically * changed). */ x1 = min(x1, left + imgWidth); y1 = min(y1, top + imgHeight); if (abs(x2 - x1) < minWidth) { /* Selection width is smaller than minWidth */ x2 = x1 - minWidth * (x2 < x1 || -1); if (x2 < left) x1 = left + minWidth; else if (x2 > left + imgWidth) x1 = left + imgWidth - minWidth; } if (abs(y2 - y1) < minHeight) { /* Selection height is smaller than minHeight */ y2 = y1 - minHeight * (y2 < y1 || -1); if (y2 < top) y1 = top + minHeight; else if (y2 > top + imgHeight) y1 = top + imgHeight - minHeight; } x2 = max(left, min(x2, left + imgWidth)); y2 = max(top, min(y2, top + imgHeight)); fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio); if (abs(x2 - x1) > maxWidth) { /* Selection width is greater than maxWidth */ x2 = x1 - maxWidth * (x2 < x1 || -1); fixAspectRatio(); } if (abs(y2 - y1) > maxHeight) { /* Selection height is greater than maxHeight */ y2 = y1 - maxHeight * (y2 < y1 || -1); fixAspectRatio(true); } selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)), y1: selY(min(y1, y2)), y2: selY(max(y1, y2)), width: abs(x2 - x1), height: abs(y2 - y1) }; update(); options.onSelectChange(img, getSelection()); } /** * Mousemove event handler triggered when the user is selecting an area * * @param event * The event object * @return false */ function selectingMouseMove(event) { x2 = /w|e|^$/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2); y2 = /n|s|^$/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2); doResize(); return false; } /** * Move the selection area * * @param newX1 * New viewport X1 * @param newY1 * New viewport Y1 */ function doMove(newX1, newY1) { x2 = (x1 = newX1) + selection.width; y2 = (y1 = newY1) + selection.height; $.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2), y2: selY(y2) }); update(); options.onSelectChange(img, getSelection()); } /** * Mousemove event handler triggered when the selection area is being moved * * @param event * The event object * @return false */ function movingMouseMove(event) { x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width)); y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height)); doMove(x1, y1); event.preventDefault(); return false; } /** * Start selection */ function startSelection() { $(document).unbind('mousemove', startSelection); adjust(); x2 = x1; y2 = y1; doResize(); resize = ''; if (!$outer.is(':visible')) /* Show the plugin elements */ $box.add($outer).hide().fadeIn(options.fadeSpeed||0); shown = true; $(document).unbind('mouseup', cancelSelection) .mousemove(selectingMouseMove).one('mouseup', docMouseUp); $box.unbind('mousemove', areaMouseMove); options.onSelectStart(img, getSelection()); } /** * Cancel selection */ function cancelSelection() { $(document).unbind('mousemove', startSelection) .unbind('mouseup', cancelSelection); hide($box.add($outer)); setSelection(selX(x1), selY(y1), selX(x1), selY(y1)); /* If this is an API call, callback functions should not be triggered */ if (!(this instanceof $.imgAreaSelect)) { options.onSelectChange(img, getSelection()); options.onSelectEnd(img, getSelection()); } } /** * Image mousedown event handler * * @param event * The event object * @return false */ function imgMouseDown(event) { /* Ignore the event if animation is in progress */ if (event.which != 1 || $outer.is(':animated')) return false; adjust(); startX = x1 = evX(event); startY = y1 = evY(event); /* Selection will start when the mouse is moved */ $(document).mousemove(startSelection).mouseup(cancelSelection); return false; } /** * Window resize event handler */ function windowResize() { doUpdate(false); } /** * Image load event handler. This is the final part of the initialization * process. */ function imgLoad() { imgLoaded = true; /* Set options */ setOptions(options = $.extend({ classPrefix: 'imgareaselect', movable: true, parent: 'body', resizable: true, resizeMargin: 10, onInit: function () {}, onSelectStart: function () {}, onSelectChange: function () {}, onSelectEnd: function () {} }, options)); $box.add($outer).css({ visibility: '' }); if (options.show) { shown = true; adjust(); update(); $box.add($outer).hide().fadeIn(options.fadeSpeed||0); } /* * Call the onInit callback. The setTimeout() call is used to ensure * that the plugin has been fully initialized and the object instance is * available (so that it can be obtained in the callback). */ setTimeout(function () { options.onInit(img, getSelection()); }, 0); } /** * Document keypress event handler * * @param event * The event object * @return false */ var docKeyPress = function(event) { var k = options.keys, d, t, key = event.keyCode; d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt : !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl : !isNaN(k.shift) && event.shiftKey ? k.shift : !isNaN(k.arrows) ? k.arrows : 10; if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) || (k.ctrl == 'resize' && event.ctrlKey) || (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey))) { /* Resize selection */ switch (key) { case 37: /* Left */ d = -d; case 39: /* Right */ t = max(x1, x2); x1 = min(x1, x2); x2 = max(t + d, x1); fixAspectRatio(); break; case 38: /* Up */ d = -d; case 40: /* Down */ t = max(y1, y2); y1 = min(y1, y2); y2 = max(t + d, y1); fixAspectRatio(true); break; default: return; } doResize(); } else { /* Move selection */ x1 = min(x1, x2); y1 = min(y1, y2); switch (key) { case 37: /* Left */ doMove(max(x1 - d, left), y1); break; case 38: /* Up */ doMove(x1, max(y1 - d, top)); break; case 39: /* Right */ doMove(x1 + min(d, imgWidth - selX(x2)), y1); break; case 40: /* Down */ doMove(x1, y1 + min(d, imgHeight - selY(y2))); break; default: return; } } return false; }; /** * Apply style options to plugin element (or multiple elements) * * @param $elem * A jQuery object representing the element(s) to style * @param props * An object that maps option names to corresponding CSS * properties */ function styleOptions($elem, props) { for (var option in props) if (options[option] !== undefined) $elem.css(props[option], options[option]); } /** * Set plugin options * * @param newOptions * The new options object */ function setOptions(newOptions) { if (newOptions.parent) ($parent = $(newOptions.parent)).append($box.add($outer)); /* Merge the new options with the existing ones */ $.extend(options, newOptions); adjust(); if (newOptions.handles != null) { /* Recreate selection area handles */ $handles.remove(); $handles = $([]); i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0; while (i--) $handles = $handles.add(div()); /* Add a class to handles and set the CSS properties */ $handles.addClass(options.classPrefix + '-handle').css({ position: 'absolute', /* * The font-size property needs to be set to zero, otherwise * Internet Explorer makes the handles too large */ fontSize: 0, zIndex: zIndex + 1 || 1 }); /* * If handle width/height has not been set with CSS rules, set the * default 5px */ if (!parseInt($handles.css('width')) >= 0) $handles.width(5).height(5); /* * If the borderWidth option is in use, add a solid border to * handles */ if (o = options.borderWidth) $handles.css({ borderWidth: o, borderStyle: 'solid' }); /* Apply other style options */ styleOptions($handles, { borderColor1: 'border-color', borderColor2: 'background-color', borderOpacity: 'opacity' }); } /* Calculate scale factors */ scaleX = options.imageWidth / imgWidth || 1; scaleY = options.imageHeight / imgHeight || 1; /* Set selection */ if (newOptions.x1 != null) { setSelection(newOptions.x1, newOptions.y1, newOptions.x2, newOptions.y2); newOptions.show = !newOptions.hide; } if (newOptions.keys) /* Enable keyboard support */ options.keys = $.extend({ shift: 1, ctrl: 'resize' }, newOptions.keys); /* Add classes to plugin elements */ $outer.addClass(options.classPrefix + '-outer'); $area.addClass(options.classPrefix + '-selection'); for (i = 0; i++ < 4;) $($border[i-1]).addClass(options.classPrefix + '-border' + i); /* Apply style options */ styleOptions($area, { selectionColor: 'background-color', selectionOpacity: 'opacity' }); styleOptions($border, { borderOpacity: 'opacity', borderWidth: 'border-width' }); styleOptions($outer, { outerColor: 'background-color', outerOpacity: 'opacity' }); if (o = options.borderColor1) $($border[0]).css({ borderStyle: 'solid', borderColor: o }); if (o = options.borderColor2) $($border[1]).css({ borderStyle: 'dashed', borderColor: o }); /* Append all the selection area elements to the container box */ $box.append($area.add($border).add($areaOpera).add($handles)); if ($.browser.msie) { if (o = $outer.css('filter').match(/opacity=(\d+)/)) $outer.css('opacity', o[1]/100); if (o = $border.css('filter').match(/opacity=(\d+)/)) $border.css('opacity', o[1]/100); } if (newOptions.hide) hide($box.add($outer)); else if (newOptions.show && imgLoaded) { shown = true; $box.add($outer).fadeIn(options.fadeSpeed||0); doUpdate(); } /* Calculate the aspect ratio factor */ aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1]; $img.add($outer).unbind('mousedown', imgMouseDown); if (options.disable || options.enable === false) { /* Disable the plugin */ $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown); $(window).unbind('resize', windowResize); } else { if (options.enable || options.disable === false) { /* Enable the plugin */ if (options.resizable || options.movable) $box.mousemove(areaMouseMove).mousedown(areaMouseDown); $(window).resize(windowResize); } if (!options.persistent) $img.add($outer).mousedown(imgMouseDown); } options.enable = options.disable = undefined; } /** * Remove plugin completely */ this.remove = function () { /* * Call setOptions with { disable: true } to unbind the event handlers */ setOptions({ disable: true }); $box.add($outer).remove(); }; /* * Public API */ /** * Get current options * * @return An object containing the set of options currently in use */ this.getOptions = function () { return options; }; /** * Set plugin options * * @param newOptions * The new options object */ this.setOptions = setOptions; /** * Get the current selection * * @param noScale * If set to <code>true</code>, scaling is not applied to the * returned selection * @return Selection object */ this.getSelection = getSelection; /** * Set the current selection * * @param x1 * X coordinate of the upper left corner of the selection area * @param y1 * Y coordinate of the upper left corner of the selection area * @param x2 * X coordinate of the lower right corner of the selection area * @param y2 * Y coordinate of the lower right corner of the selection area * @param noScale * If set to <code>true</code>, scaling is not applied to the * new selection */ this.setSelection = setSelection; /** * Cancel selection */ this.cancelSelection = cancelSelection; /** * Update plugin elements * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ this.update = doUpdate; /* * Traverse the image's parent elements (up to <body>) and find the * highest z-index */ $p = $img; while ($p.length) { zIndex = max(zIndex, !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex); /* Also check if any of the ancestor elements has fixed position */ if ($p.css('position') == 'fixed') position = 'fixed'; $p = $p.parent(':not(body)'); } /* * If z-index is given as an option, it overrides the one found by the * above loop */ zIndex = options.zIndex || zIndex; if ($.browser.msie) $img.attr('unselectable', 'on'); /* * In MSIE and WebKit, we need to use the keydown event instead of keypress */ $.imgAreaSelect.keyPress = $.browser.msie || $.browser.safari ? 'keydown' : 'keypress'; /* * There is a bug affecting the CSS cursor property in Opera (observed in * versions up to 10.00) that prevents the cursor from being updated unless * the mouse leaves and enters the element again. To trigger the mouseover * event, we're adding an additional div to $box and we're going to toggle * it when mouse moves inside the selection area. */ if ($.browser.opera) $areaOpera = div().css({ width: '100%', height: '100%', position: 'absolute', zIndex: zIndex + 2 || 2 }); /* * We initially set visibility to "hidden" as a workaround for a weird * behaviour observed in Google Chrome 1.0.154.53 (on Windows XP). Normally * we would just set display to "none", but, for some reason, if we do so * then Chrome refuses to later display the element with .show() or * .fadeIn(). */ $box.add($outer).css({ visibility: 'hidden', position: position, overflow: 'hidden', zIndex: zIndex || '0' }); $box.css({ zIndex: zIndex + 2 || 2 }); $area.add($border).css({ position: 'absolute', fontSize: 0 }); /* * If the image has been fully loaded, or if it is not really an image (eg. * a div), call imgLoad() immediately; otherwise, bind it to be called once * on image load event. */ img.complete || img.readyState == 'complete' || !$img.is('img') ? imgLoad() : $img.one('load', imgLoad); /* * MSIE 9.0 doesn't always fire the image load event -- resetting the src * attribute seems to trigger it. The check is for version 7 and above to * accommodate for MSIE 9 running in compatibility mode. */ if (!imgLoaded && $.browser.msie && $.browser.version >= 7) img.src = img.src; }; /** * Invoke imgAreaSelect on a jQuery object containing the image(s) * * @param options * Options object * @return The jQuery object or a reference to imgAreaSelect instance (if the * <code>instance</code> option was specified) */ $.fn.imgAreaSelect = function (options) { options = options || {}; this.each(function () { /* Is there already an imgAreaSelect instance bound to this element? */ if ($(this).data('imgAreaSelect')) { /* Yes there is -- is it supposed to be removed? */ if (options.remove) { /* Remove the plugin */ $(this).data('imgAreaSelect').remove(); $(this).removeData('imgAreaSelect'); } else /* Reset options */ $(this).data('imgAreaSelect').setOptions(options); } else if (!options.remove) { /* No exising instance -- create a new one */ /* * If neither the "enable" nor the "disable" option is present, add * "enable" as the default */ if (options.enable === undefined && options.disable === undefined) options.enable = true; $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options)); } }); if (options.instance) /* * Return the imgAreaSelect instance bound to the first element in the * set */ return $(this).data('imgAreaSelect'); return this; }; })(jQuery);
JavaScript
// Utility functions for parsing and handling shortcodes in Javascript. // Ensure the global `wp` object exists. window.wp = window.wp || {}; (function(){ wp.shortcode = { // ### Find the next matching shortcode // // Given a shortcode `tag`, a block of `text`, and an optional starting // `index`, returns the next matching shortcode or `undefined`. // // Shortcodes are formatted as an object that contains the match // `content`, the matching `index`, and the parsed `shortcode` object. next: function( tag, text, index ) { var re = wp.shortcode.regexp( tag ), match, result; re.lastIndex = index || 0; match = re.exec( text ); if ( ! match ) return; // If we matched an escaped shortcode, try again. if ( match[1] === '[' && match[7] === ']' ) return wp.shortcode.next( tag, text, re.lastIndex ); result = { index: match.index, content: match[0], shortcode: wp.shortcode.fromMatch( match ) }; // If we matched a leading `[`, strip it from the match // and increment the index accordingly. if ( match[1] ) { result.match = result.match.slice( 1 ); result.index++; } // If we matched a trailing `]`, strip it from the match. if ( match[7] ) result.match = result.match.slice( 0, -1 ); return result; }, // ### Replace matching shortcodes in a block of text // // Accepts a shortcode `tag`, content `text` to scan, and a `callback` // to process the shortcode matches and return a replacement string. // Returns the `text` with all shortcodes replaced. // // Shortcode matches are objects that contain the shortcode `tag`, // a shortcode `attrs` object, the `content` between shortcode tags, // and a boolean flag to indicate if the match was a `single` tag. replace: function( tag, text, callback ) { return text.replace( wp.shortcode.regexp( tag ), function( match, left, tag, attrs, slash, content, closing, right, offset ) { // If both extra brackets exist, the shortcode has been // properly escaped. if ( left === '[' && right === ']' ) return match; // Create the match object and pass it through the callback. var result = callback( wp.shortcode.fromMatch( arguments ) ); // Make sure to return any of the extra brackets if they // weren't used to escape the shortcode. return result ? left + result + right : match; }); }, // ### Generate a string from shortcode parameters // // Creates a `wp.shortcode` instance and returns a string. // // Accepts the same `options` as the `wp.shortcode()` constructor, // containing a `tag` string, a string or object of `attrs`, a boolean // indicating whether to format the shortcode using a `single` tag, and a // `content` string. string: function( options ) { return new wp.shortcode( options ).string(); }, // ### Generate a RegExp to identify a shortcode // // The base regex is functionally equivalent to the one found in // `get_shortcode_regex()` in `wp-includes/shortcodes.php`. // // Capture groups: // // 1. An extra `[` to allow for escaping shortcodes with double `[[]]` // 2. The shortcode name // 3. The shortcode argument list // 4. The self closing `/` // 5. The content of a shortcode when it wraps some content. // 6. The closing tag. // 7. An extra `]` to allow for escaping shortcodes with double `[[]]` regexp: _.memoize( function( tag ) { return new RegExp( '\\[(\\[?)(' + tag + ')(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\[]*)*)(\\[\\/\\2\\]))?)(\\]?)', 'g' ); }), // ### Parse shortcode attributes // // Shortcodes accept many types of attributes. These can chiefly be // divided into named and numeric attributes: // // Named attributes are assigned on a key/value basis, while numeric // attributes are treated as an array. // // Named attributes can be formatted as either `name="value"`, // `name='value'`, or `name=value`. Numeric attributes can be formatted // as `"value"` or just `value`. attrs: _.memoize( function( text ) { var named = {}, numeric = [], pattern, match; // This regular expression is reused from `shortcode_parse_atts()` // in `wp-includes/shortcodes.php`. // // Capture groups: // // 1. An attribute name, that corresponds to... // 2. a value in double quotes. // 3. An attribute name, that corresponds to... // 4. a value in single quotes. // 5. An attribute name, that corresponds to... // 6. an unquoted value. // 7. A numeric attribute in double quotes. // 8. An unquoted numeric attribute. pattern = /(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/g; // Map zero-width spaces to actual spaces. text = text.replace( /[\u00a0\u200b]/g, ' ' ); // Match and normalize attributes. while ( (match = pattern.exec( text )) ) { if ( match[1] ) { named[ match[1].toLowerCase() ] = match[2]; } else if ( match[3] ) { named[ match[3].toLowerCase() ] = match[4]; } else if ( match[5] ) { named[ match[5].toLowerCase() ] = match[6]; } else if ( match[7] ) { numeric.push( match[7] ); } else if ( match[8] ) { numeric.push( match[8] ); } } return { named: named, numeric: numeric }; }), // ### Generate a Shortcode Object from a RegExp match // Accepts a `match` object from calling `regexp.exec()` on a `RegExp` // generated by `wp.shortcode.regexp()`. `match` can also be set to the // `arguments` from a callback passed to `regexp.replace()`. fromMatch: function( match ) { var type; if ( match[4] ) type = 'self-closing'; else if ( match[6] ) type = 'closed'; else type = 'single'; return new wp.shortcode({ tag: match[2], attrs: match[3], type: type, content: match[5] }); } }; // Shortcode Objects // ----------------- // // Shortcode objects are generated automatically when using the main // `wp.shortcode` methods: `next()`, `replace()`, and `string()`. // // To access a raw representation of a shortcode, pass an `options` object, // containing a `tag` string, a string or object of `attrs`, a string // indicating the `type` of the shortcode ('single', 'self-closing', or // 'closed'), and a `content` string. wp.shortcode = _.extend( function( options ) { _.extend( this, _.pick( options || {}, 'tag', 'attrs', 'type', 'content' ) ); var attrs = this.attrs; // Ensure we have a correctly formatted `attrs` object. this.attrs = { named: {}, numeric: [] }; if ( ! attrs ) return; // Parse a string of attributes. if ( _.isString( attrs ) ) { this.attrs = wp.shortcode.attrs( attrs ); // Identify a correctly formatted `attrs` object. } else if ( _.isEqual( _.keys( attrs ), [ 'named', 'numeric' ] ) ) { this.attrs = attrs; // Handle a flat object of attributes. } else { _.each( options.attrs, function( value, key ) { this.set( key, value ); }, this ); } }, wp.shortcode ); _.extend( wp.shortcode.prototype, { // ### Get a shortcode attribute // // Automatically detects whether `attr` is named or numeric and routes // it accordingly. get: function( attr ) { return this.attrs[ _.isNumber( attr ) ? 'numeric' : 'named' ][ attr ]; }, // ### Set a shortcode attribute // // Automatically detects whether `attr` is named or numeric and routes // it accordingly. set: function( attr, value ) { this.attrs[ _.isNumber( attr ) ? 'numeric' : 'named' ][ attr ] = value; return this; }, // ### Transform the shortcode match into a string string: function() { var text = '[' + this.tag; _.each( this.attrs.numeric, function( value ) { if ( /\s/.test( value ) ) text += ' "' + value + '"'; else text += ' ' + value; }); _.each( this.attrs.named, function( value, name ) { text += ' ' + name + '="' + value + '"'; }); // If the tag is marked as `single` or `self-closing`, close the // tag and ignore any additional content. if ( 'single' === this.type ) return text + ']'; else if ( 'self-closing' === this.type ) return text + ' /]'; // Complete the opening tag. text += ']'; if ( this.content ) text += this.content; // Add the closing tag. return text + '[/' + this.tag + ']'; } }); }()); // HTML utility functions // ---------------------- // // Experimental. These functions may change or be removed in the future. (function(){ wp.html = _.extend( wp.html || {}, { // ### Parse HTML attributes. // // Converts `content` to a set of parsed HTML attributes. // Utilizes `wp.shortcode.attrs( content )`, which is a valid superset of // the HTML attribute specification. Reformats the attributes into an // object that contains the `attrs` with `key:value` mapping, and a record // of the attributes that were entered using `empty` attribute syntax (i.e. // with no value). attrs: function( content ) { var result, attrs; // If `content` ends in a slash, strip it. if ( '/' === content[ content.length - 1 ] ) content = content.slice( 0, -1 ); result = wp.shortcode.attrs( content ); attrs = result.named; _.each( result.numeric, function( key ) { if ( /\s/.test( key ) ) return; attrs[ key ] = ''; }); return attrs; }, // ### Convert an HTML-representation of an object to a string. string: function( options ) { var text = '<' + options.tag, content = options.content || ''; _.each( options.attrs, function( value, attr ) { text += ' ' + attr; // Use empty attribute notation where possible. if ( '' === value ) return; // Convert boolean values to strings. if ( _.isBoolean( value ) ) value = value ? 'true' : 'false'; text += '="' + value + '"'; }); // Return the result if it is a self-closing tag. if ( options.single ) return text + ' />'; // Complete the opening tag. text += '>'; // If `content` is an object, recursively call this function. text += _.isObject( content ) ? wp.html.string( content ) : content; return text + '</' + options.tag + '>'; } }); }());
JavaScript
(function( exports, $ ){ var api = wp.customize, debounce; debounce = function( fn, delay, context ) { var timeout; return function() { var args = arguments; context = context || this; clearTimeout( timeout ); timeout = setTimeout( function() { timeout = null; fn.apply( context, args ); }, delay ); }; }; api.Preview = api.Messenger.extend({ /** * Requires params: * - url - the URL of preview frame */ initialize: function( params, options ) { var self = this; api.Messenger.prototype.initialize.call( this, params, options ); this.body = $( document.body ); this.body.on( 'click.preview', 'a', function( event ) { event.preventDefault(); self.send( 'scroll', 0 ); self.send( 'url', $(this).prop('href') ); }); // You cannot submit forms. // @todo: Allow form submissions by mixing $_POST data with the customize setting $_POST data. this.body.on( 'submit.preview', 'form', function( event ) { event.preventDefault(); }); this.window = $( window ); this.window.on( 'scroll.preview', debounce( function() { self.send( 'scroll', self.window.scrollTop() ); }, 200 )); this.bind( 'scroll', function( distance ) { self.window.scrollTop( distance ); }); } }); $( function() { api.settings = window._wpCustomizeSettings; if ( ! api.settings ) return; var preview, bg; preview = new api.Preview({ url: window.location.href, channel: api.settings.channel }); preview.bind( 'settings', function( values ) { $.each( values, function( id, value ) { if ( api.has( id ) ) api( id ).set( value ); else api.create( id, value ); }); }); preview.trigger( 'settings', api.settings.values ); preview.bind( 'setting', function( args ) { var value; args = args.slice(); if ( value = api( args.shift() ) ) value.set.apply( value, args ); }); preview.bind( 'sync', function( events ) { $.each( events, function( event, args ) { preview.trigger( event, args ); }); preview.send( 'synced' ); }); preview.bind( 'active', function() { if ( api.settings.nonce ) preview.send( 'nonce', api.settings.nonce ); }); preview.send( 'ready' ); /* Custom Backgrounds */ bg = $.map(['color', 'image', 'position_x', 'repeat', 'attachment'], function( prop ) { return 'background_' + prop; }); api.when.apply( api, bg ).done( function( color, image, position_x, repeat, attachment ) { var body = $(document.body), head = $('head'), style = $('#custom-background-css'), update; // If custom backgrounds are active and we can't find the // default output, bail. if ( body.hasClass('custom-background') && ! style.length ) return; update = function() { var css = ''; // The body will support custom backgrounds if either // the color or image are set. // // See get_body_class() in /wp-includes/post-template.php body.toggleClass( 'custom-background', !! ( color() || image() ) ); if ( color() ) css += 'background-color: ' + color() + ';'; if ( image() ) { css += 'background-image: url("' + image() + '");'; css += 'background-position: top ' + position_x() + ';'; css += 'background-repeat: ' + repeat() + ';'; css += 'background-attachment: ' + attachment() + ';'; } // Refresh the stylesheet by removing and recreating it. style.remove(); style = $('<style type="text/css" id="custom-background-css">body.custom-background { ' + css + ' }</style>').appendTo( head ); }; $.each( arguments, function() { this.bind( update ); }); }); }); })( wp, jQuery );
JavaScript
// utility functions var wpCookies = { // The following functions are from Cookie.js class in TinyMCE, Moxiecode, used under LGPL. each : function(obj, cb, scope) { var n, l; if ( !obj ) return 0; scope = scope || obj; if ( typeof(obj.length) != 'undefined' ) { for ( n = 0, l = obj.length; n < l; n++ ) { if ( cb.call(scope, obj[n], n, obj) === false ) return 0; } } else { for ( n in obj ) { if ( obj.hasOwnProperty(n) ) { if ( cb.call(scope, obj[n], n, obj) === false ) { return 0; } } } } return 1; }, /** * Get a multi-values cookie. * Returns a JS object with the name: 'value' pairs. */ getHash : function(name) { var all = this.get(name), ret; if ( all ) { this.each( all.split('&'), function(pair) { pair = pair.split('='); ret = ret || {}; ret[pair[0]] = pair[1]; }); } return ret; }, /** * Set a multi-values cookie. * * 'values_obj' is the JS object that is stored. It is encoded as URI in wpCookies.set(). */ setHash : function(name, values_obj, expires, path, domain, secure) { var str = ''; this.each(values_obj, function(val, key) { str += (!str ? '' : '&') + key + '=' + val; }); this.set(name, str, expires, path, domain, secure); }, /** * Get a cookie. */ get : function(name) { var cookie = document.cookie, e, p = name + "=", b; if ( !cookie ) return; b = cookie.indexOf("; " + p); if ( b == -1 ) { b = cookie.indexOf(p); if ( b != 0 ) return null; } else { b += 2; } e = cookie.indexOf(";", b); if ( e == -1 ) e = cookie.length; return decodeURIComponent( cookie.substring(b + p.length, e) ); }, /** * Set a cookie. * * The 'expires' arg can be either a JS Date() object set to the expiration date (back-compat) * or the number of seconds until expiration */ set : function(name, value, expires, path, domain, secure) { var d = new Date(); if ( typeof(expires) == 'object' && expires.toGMTString ) { expires = expires.toGMTString(); } else if ( parseInt(expires, 10) ) { d.setTime( d.getTime() + ( parseInt(expires, 10) * 1000 ) ); // time must be in miliseconds expires = d.toGMTString(); } else { expires = ''; } document.cookie = name + "=" + encodeURIComponent(value) + ((expires) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); }, /** * Remove a cookie. * * This is done by setting it to an empty value and setting the expiration time in the past. */ remove : function(name, path) { this.set(name, '', -1000, path); } }; // Returns the value as string. Second arg or empty string is returned when value is not set. function getUserSetting( name, def ) { var obj = getAllUserSettings(); if ( obj.hasOwnProperty(name) ) return obj[name]; if ( typeof def != 'undefined' ) return def; return ''; } // Both name and value must be only ASCII letters, numbers or underscore // and the shorter, the better (cookies can store maximum 4KB). Not suitable to store text. function setUserSetting( name, value, _del ) { if ( 'object' !== typeof userSettings ) return false; var cookie = 'wp-settings-' + userSettings.uid, all = wpCookies.getHash(cookie) || {}, path = userSettings.url, n = name.toString().replace(/[^A-Za-z0-9_]/, ''), v = value.toString().replace(/[^A-Za-z0-9_]/, ''); if ( _del ) { delete all[n]; } else { all[n] = v; } wpCookies.setHash(cookie, all, 31536000, path); wpCookies.set('wp-settings-time-'+userSettings.uid, userSettings.time, 31536000, path); return name; } function deleteUserSetting( name ) { return setUserSetting( name, '', 1 ); } // Returns all settings as js object. function getAllUserSettings() { if ( 'object' !== typeof userSettings ) return {}; return wpCookies.getHash('wp-settings-' + userSettings.uid) || {}; }
JavaScript
window.wp = window.wp || {}; (function($){ var Attachment, Attachments, Query, compare, l10n, media; /** * wp.media( attributes ) * * Handles the default media experience. Automatically creates * and opens a media frame, and returns the result. * Does nothing if the controllers do not exist. * * @param {object} attributes The properties passed to the main media controller. * @return {object} A media workflow. */ media = wp.media = function( attributes ) { var MediaFrame = media.view.MediaFrame, frame; if ( ! MediaFrame ) return; attributes = _.defaults( attributes || {}, { frame: 'select' }); if ( 'select' === attributes.frame && MediaFrame.Select ) frame = new MediaFrame.Select( attributes ); else if ( 'post' === attributes.frame && MediaFrame.Post ) frame = new MediaFrame.Post( attributes ); delete attributes.frame; return frame; }; _.extend( media, { model: {}, view: {}, controller: {}, frames: {} }); // Link any localized strings. l10n = media.model.l10n = typeof _wpMediaModelsL10n === 'undefined' ? {} : _wpMediaModelsL10n; // Link any settings. media.model.settings = l10n.settings || {}; delete l10n.settings; /** * ======================================================================== * UTILITIES * ======================================================================== */ /** * A basic comparator. * * @param {mixed} a The primary parameter to compare. * @param {mixed} b The primary parameter to compare. * @param {string} ac The fallback parameter to compare, a's cid. * @param {string} bc The fallback parameter to compare, b's cid. * @return {number} -1: a should come before b. * 0: a and b are of the same rank. * 1: b should come before a. */ compare = function( a, b, ac, bc ) { if ( _.isEqual( a, b ) ) return ac === bc ? 0 : (ac > bc ? -1 : 1); else return a > b ? -1 : 1; }; _.extend( media, { /** * media.template( id ) * * Fetches a template by id. * See wp.template() in `wp-includes/js/wp-util.js`. */ template: wp.template, /** * media.post( [action], [data] ) * * Sends a POST request to WordPress. * See wp.ajax.post() in `wp-includes/js/wp-util.js`. */ post: wp.ajax.post, /** * media.ajax( [action], [options] ) * * Sends an XHR request to WordPress. * See wp.ajax.send() in `wp-includes/js/wp-util.js`. */ ajax: wp.ajax.send, // Scales a set of dimensions to fit within bounding dimensions. fit: function( dimensions ) { var width = dimensions.width, height = dimensions.height, maxWidth = dimensions.maxWidth, maxHeight = dimensions.maxHeight, constraint; // Compare ratios between the two values to determine which // max to constrain by. If a max value doesn't exist, then the // opposite side is the constraint. if ( ! _.isUndefined( maxWidth ) && ! _.isUndefined( maxHeight ) ) { constraint = ( width / height > maxWidth / maxHeight ) ? 'width' : 'height'; } else if ( _.isUndefined( maxHeight ) ) { constraint = 'width'; } else if ( _.isUndefined( maxWidth ) && height > maxHeight ) { constraint = 'height'; } // If the value of the constrained side is larger than the max, // then scale the values. Otherwise return the originals; they fit. if ( 'width' === constraint && width > maxWidth ) { return { width : maxWidth, height: Math.round( maxWidth * height / width ) }; } else if ( 'height' === constraint && height > maxHeight ) { return { width : Math.round( maxHeight * width / height ), height: maxHeight }; } else { return { width : width, height: height }; } }, // Truncates a string by injecting an ellipsis into the middle. // Useful for filenames. truncate: function( string, length, replacement ) { length = length || 30; replacement = replacement || '&hellip;'; if ( string.length <= length ) return string; return string.substr( 0, length / 2 ) + replacement + string.substr( -1 * length / 2 ); } }); /** * ======================================================================== * MODELS * ======================================================================== */ /** * wp.media.attachment */ media.attachment = function( id ) { return Attachment.get( id ); }; /** * wp.media.model.Attachment */ Attachment = media.model.Attachment = Backbone.Model.extend({ sync: function( method, model, options ) { // If the attachment does not yet have an `id`, return an instantly // rejected promise. Otherwise, all of our requests will fail. if ( _.isUndefined( this.id ) ) return $.Deferred().rejectWith( this ).promise(); // Overload the `read` request so Attachment.fetch() functions correctly. if ( 'read' === method ) { options = options || {}; options.context = this; options.data = _.extend( options.data || {}, { action: 'get-attachment', id: this.id }); return media.ajax( options ); // Overload the `update` request so properties can be saved. } else if ( 'update' === method ) { // If we do not have the necessary nonce, fail immeditately. if ( ! this.get('nonces') || ! this.get('nonces').update ) return $.Deferred().rejectWith( this ).promise(); options = options || {}; options.context = this; // Set the action and ID. options.data = _.extend( options.data || {}, { action: 'save-attachment', id: this.id, nonce: this.get('nonces').update, post_id: media.model.settings.post.id }); // Record the values of the changed attributes. if ( model.hasChanged() ) { options.data.changes = {}; _.each( model.changed, function( value, key ) { options.data.changes[ key ] = this.get( key ); }, this ); } return media.ajax( options ); // Overload the `delete` request so attachments can be removed. // This will permanently delete an attachment. } else if ( 'delete' === method ) { options = options || {}; if ( ! options.wait ) this.destroyed = true; options.context = this; options.data = _.extend( options.data || {}, { action: 'delete-post', id: this.id, _wpnonce: this.get('nonces')['delete'] }); return media.ajax( options ).done( function() { this.destroyed = true; }).fail( function() { this.destroyed = false; }); // Otherwise, fall back to `Backbone.sync()`. } else { return Backbone.Model.prototype.sync.apply( this, arguments ); } }, parse: function( resp, xhr ) { if ( ! resp ) return resp; // Convert date strings into Date objects. resp.date = new Date( resp.date ); resp.modified = new Date( resp.modified ); return resp; }, saveCompat: function( data, options ) { var model = this; // If we do not have the necessary nonce, fail immeditately. if ( ! this.get('nonces') || ! this.get('nonces').update ) return $.Deferred().rejectWith( this ).promise(); return media.post( 'save-attachment-compat', _.defaults({ id: this.id, nonce: this.get('nonces').update, post_id: media.model.settings.post.id }, data ) ).done( function( resp, status, xhr ) { model.set( model.parse( resp, xhr ), options ); }); } }, { create: function( attrs ) { return Attachments.all.push( attrs ); }, get: _.memoize( function( id, attachment ) { return Attachments.all.push( attachment || { id: id } ); }) }); /** * wp.media.model.Attachments */ Attachments = media.model.Attachments = Backbone.Collection.extend({ model: Attachment, initialize: function( models, options ) { options = options || {}; this.props = new Backbone.Model(); this.filters = options.filters || {}; // Bind default `change` events to the `props` model. this.props.on( 'change', this._changeFilteredProps, this ); this.props.on( 'change:order', this._changeOrder, this ); this.props.on( 'change:orderby', this._changeOrderby, this ); this.props.on( 'change:query', this._changeQuery, this ); // Set the `props` model and fill the default property values. this.props.set( _.defaults( options.props || {} ) ); // Observe another `Attachments` collection if one is provided. if ( options.observe ) this.observe( options.observe ); }, // Automatically sort the collection when the order changes. _changeOrder: function( model, order ) { if ( this.comparator ) this.sort(); }, // Set the default comparator only when the `orderby` property is set. _changeOrderby: function( model, orderby ) { // If a different comparator is defined, bail. if ( this.comparator && this.comparator !== Attachments.comparator ) return; if ( orderby && 'post__in' !== orderby ) this.comparator = Attachments.comparator; else delete this.comparator; }, // If the `query` property is set to true, query the server using // the `props` values, and sync the results to this collection. _changeQuery: function( model, query ) { if ( query ) { this.props.on( 'change', this._requery, this ); this._requery(); } else { this.props.off( 'change', this._requery, this ); } }, _changeFilteredProps: function( model, options ) { // If this is a query, updating the collection will be handled by // `this._requery()`. if ( this.props.get('query') ) return; var changed = _.chain( model.changed ).map( function( t, prop ) { var filter = Attachments.filters[ prop ], term = model.get( prop ); if ( ! filter ) return; if ( term && ! this.filters[ prop ] ) this.filters[ prop ] = filter; else if ( ! term && this.filters[ prop ] === filter ) delete this.filters[ prop ]; else return; // Record the change. return true; }, this ).any().value(); if ( ! changed ) return; // If no `Attachments` model is provided to source the searches // from, then automatically generate a source from the existing // models. if ( ! this._source ) this._source = new Attachments( this.models ); this.reset( this._source.filter( this.validator, this ) ); }, validateDestroyed: false, validator: function( attachment ) { if ( ! this.validateDestroyed && attachment.destroyed ) return false; return _.all( this.filters, function( filter, key ) { return !! filter.call( this, attachment ); }, this ); }, validate: function( attachment, options ) { var valid = this.validator( attachment ), hasAttachment = !! this.get( attachment.cid ); if ( ! valid && hasAttachment ) this.remove( attachment, options ); else if ( valid && ! hasAttachment ) this.add( attachment, options ); return this; }, validateAll: function( attachments, options ) { options = options || {}; _.each( attachments.models, function( attachment ) { this.validate( attachment, { silent: true }); }, this ); if ( ! options.silent ) this.trigger( 'reset', this, options ); return this; }, observe: function( attachments ) { this.observers = this.observers || []; this.observers.push( attachments ); attachments.on( 'add change remove', this._validateHandler, this ); attachments.on( 'reset', this._validateAllHandler, this ); this.validateAll( attachments ); return this; }, unobserve: function( attachments ) { if ( attachments ) { attachments.off( null, null, this ); this.observers = _.without( this.observers, attachments ); } else { _.each( this.observers, function( attachments ) { attachments.off( null, null, this ); }, this ); delete this.observers; } return this; }, _validateHandler: function( attachment, attachments, options ) { // If we're not mirroring this `attachments` collection, // only retain the `silent` option. options = attachments === this.mirroring ? options : { silent: options && options.silent }; return this.validate( attachment, options ); }, _validateAllHandler: function( attachments, options ) { return this.validateAll( attachments, options ); }, mirror: function( attachments ) { if ( this.mirroring && this.mirroring === attachments ) return this; this.unmirror(); this.mirroring = attachments; // Clear the collection silently. A `reset` event will be fired // when `observe()` calls `validateAll()`. this.reset( [], { silent: true } ); this.observe( attachments ); return this; }, unmirror: function() { if ( ! this.mirroring ) return; this.unobserve( this.mirroring ); delete this.mirroring; }, more: function( options ) { var deferred = $.Deferred(), mirroring = this.mirroring, attachments = this; if ( ! mirroring || ! mirroring.more ) return deferred.resolveWith( this ).promise(); // If we're mirroring another collection, forward `more` to // the mirrored collection. Account for a race condition by // checking if we're still mirroring that collection when // the request resolves. mirroring.more( options ).done( function() { if ( this === attachments.mirroring ) deferred.resolveWith( this ); }); return deferred.promise(); }, hasMore: function() { return this.mirroring ? this.mirroring.hasMore() : false; }, parse: function( resp, xhr ) { if ( ! _.isArray( resp ) ) resp = [resp]; return _.map( resp, function( attrs ) { var id, attachment, newAttributes; if ( attrs instanceof Backbone.Model ) { id = attrs.get( 'id' ); attrs = attrs.attributes; } else { id = attrs.id; } attachment = Attachment.get( id ); newAttributes = attachment.parse( attrs, xhr ); if ( ! _.isEqual( attachment.attributes, newAttributes ) ) attachment.set( newAttributes ); return attachment; }); }, _requery: function() { if ( this.props.get('query') ) this.mirror( Query.get( this.props.toJSON() ) ); }, // If this collection is sorted by `menuOrder`, recalculates and saves // the menu order to the database. saveMenuOrder: function() { if ( 'menuOrder' !== this.props.get('orderby') ) return; // Removes any uploading attachments, updates each attachment's // menu order, and returns an object with an { id: menuOrder } // mapping to pass to the request. var attachments = this.chain().filter( function( attachment ) { return ! _.isUndefined( attachment.id ); }).map( function( attachment, index ) { // Indices start at 1. index = index + 1; attachment.set( 'menuOrder', index ); return [ attachment.id, index ]; }).object().value(); if ( _.isEmpty( attachments ) ) return; return media.post( 'save-attachment-order', { nonce: media.model.settings.post.nonce, post_id: media.model.settings.post.id, attachments: attachments }); } }, { comparator: function( a, b, options ) { var key = this.props.get('orderby'), order = this.props.get('order') || 'DESC', ac = a.cid, bc = b.cid; a = a.get( key ); b = b.get( key ); if ( 'date' === key || 'modified' === key ) { a = a || new Date(); b = b || new Date(); } // If `options.ties` is set, don't enforce the `cid` tiebreaker. if ( options && options.ties ) ac = bc = null; return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac ); }, filters: { // Note that this client-side searching is *not* equivalent // to our server-side searching. search: function( attachment ) { if ( ! this.props.get('search') ) return true; return _.any(['title','filename','description','caption','name'], function( key ) { var value = attachment.get( key ); return value && -1 !== value.search( this.props.get('search') ); }, this ); }, type: function( attachment ) { var type = this.props.get('type'); return ! type || -1 !== type.indexOf( attachment.get('type') ); }, uploadedTo: function( attachment ) { var uploadedTo = this.props.get('uploadedTo'); if ( _.isUndefined( uploadedTo ) ) return true; return uploadedTo === attachment.get('uploadedTo'); } } }); Attachments.all = new Attachments(); /** * wp.media.query */ media.query = function( props ) { return new Attachments( null, { props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } ) }); }; /** * wp.media.model.Query * * A set of attachments that corresponds to a set of consecutively paged * queries on the server. * * Note: Do NOT change this.args after the query has been initialized. * Things will break. */ Query = media.model.Query = Attachments.extend({ initialize: function( models, options ) { var allowed; options = options || {}; Attachments.prototype.initialize.apply( this, arguments ); this.args = options.args; this._hasMore = true; this.created = new Date(); this.filters.order = function( attachment ) { var orderby = this.props.get('orderby'), order = this.props.get('order'); if ( ! this.comparator ) return true; // We want any items that can be placed before the last // item in the set. If we add any items after the last // item, then we can't guarantee the set is complete. if ( this.length ) { return 1 !== this.comparator( attachment, this.last(), { ties: true }); // Handle the case where there are no items yet and // we're sorting for recent items. In that case, we want // changes that occurred after we created the query. } else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) { return attachment.get( orderby ) >= this.created; // If we're sorting by menu order and we have no items, // accept any items that have the default menu order (0). } else if ( 'ASC' === order && 'menuOrder' === orderby ) { return attachment.get( orderby ) === 0; } // Otherwise, we don't want any items yet. return false; }; // Observe the central `wp.Uploader.queue` collection to watch for // new matches for the query. // // Only observe when a limited number of query args are set. There // are no filters for other properties, so observing will result in // false positives in those queries. allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent' ]; if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() ) this.observe( wp.Uploader.queue ); }, hasMore: function() { return this._hasMore; }, more: function( options ) { var query = this; if ( this._more && 'pending' === this._more.state() ) return this._more; if ( ! this.hasMore() ) return $.Deferred().resolveWith( this ).promise(); options = options || {}; options.remove = false; return this._more = this.fetch( options ).done( function( resp ) { if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page ) query._hasMore = false; }); }, sync: function( method, model, options ) { var fallback; // Overload the read method so Attachment.fetch() functions correctly. if ( 'read' === method ) { options = options || {}; options.context = this; options.data = _.extend( options.data || {}, { action: 'query-attachments', post_id: media.model.settings.post.id }); // Clone the args so manipulation is non-destructive. args = _.clone( this.args ); // Determine which page to query. if ( -1 !== args.posts_per_page ) args.paged = Math.floor( this.length / args.posts_per_page ) + 1; options.data.query = args; return media.ajax( options ); // Otherwise, fall back to Backbone.sync() } else { fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone; return fallback.sync.apply( this, arguments ); } } }, { defaultProps: { orderby: 'date', order: 'DESC' }, defaultArgs: { posts_per_page: 40 }, orderby: { allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ], valuemap: { 'id': 'ID', 'uploadedTo': 'parent', 'menuOrder': 'menu_order ID' } }, propmap: { 'search': 's', 'type': 'post_mime_type', 'perPage': 'posts_per_page', 'menuOrder': 'menu_order', 'uploadedTo': 'post_parent' }, // Caches query objects so queries can be easily reused. get: (function(){ var queries = []; return function( props, options ) { var args = {}, orderby = Query.orderby, defaults = Query.defaultProps, query; // Remove the `query` property. This isn't linked to a query, // this *is* the query. delete props.query; // Fill default args. _.defaults( props, defaults ); // Normalize the order. props.order = props.order.toUpperCase(); if ( 'DESC' !== props.order && 'ASC' !== props.order ) props.order = defaults.order.toUpperCase(); // Ensure we have a valid orderby value. if ( ! _.contains( orderby.allowed, props.orderby ) ) props.orderby = defaults.orderby; // Generate the query `args` object. // Correct any differing property names. _.each( props, function( value, prop ) { if ( _.isNull( value ) ) return; args[ Query.propmap[ prop ] || prop ] = value; }); // Fill any other default query args. _.defaults( args, Query.defaultArgs ); // `props.orderby` does not always map directly to `args.orderby`. // Substitute exceptions specified in orderby.keymap. args.orderby = orderby.valuemap[ props.orderby ] || props.orderby; // Search the query cache for matches. query = _.find( queries, function( query ) { return _.isEqual( query.args, args ); }); // Otherwise, create a new query and add it to the cache. if ( ! query ) { query = new Query( [], _.extend( options || {}, { props: props, args: args } ) ); queries.push( query ); } return query; }; }()) }); /** * wp.media.model.Selection * * Used to manage a selection of attachments in the views. */ media.model.Selection = Attachments.extend({ initialize: function( models, options ) { Attachments.prototype.initialize.apply( this, arguments ); this.multiple = options && options.multiple; // Refresh the `single` model whenever the selection changes. // Binds `single` instead of using the context argument to ensure // it receives no parameters. this.on( 'add remove reset', _.bind( this.single, this, false ) ); }, // Override the selection's add method. // If the workflow does not support multiple // selected attachments, reset the selection. add: function( models, options ) { if ( ! this.multiple ) this.remove( this.models ); return Attachments.prototype.add.call( this, models, options ); }, single: function( model ) { var previous = this._single; // If a `model` is provided, use it as the single model. if ( model ) this._single = model; // If the single model isn't in the selection, remove it. if ( this._single && ! this.get( this._single.cid ) ) delete this._single; this._single = this._single || this.last(); // If single has changed, fire an event. if ( this._single !== previous ) { if ( previous ) { previous.trigger( 'selection:unsingle', previous, this ); // If the model was already removed, trigger the collection // event manually. if ( ! this.get( previous.cid ) ) this.trigger( 'selection:unsingle', previous, this ); } if ( this._single ) this._single.trigger( 'selection:single', this._single, this ); } // Return the single model, or the last model as a fallback. return this._single; } }); // Clean up. Prevents mobile browsers caching $(window).on('unload', function(){ window.wp = null; }); }(jQuery));
JavaScript
(function($){ var media = wp.media, Attachment = media.model.Attachment, Attachments = media.model.Attachments, Query = media.model.Query, l10n; // Link any localized strings. l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n; // Link any settings. media.view.settings = l10n.settings || {}; delete l10n.settings; // Copy the `post` setting over to the model settings. media.model.settings.post = media.view.settings.post; // Check if the browser supports CSS 3.0 transitions $.support.transition = (function(){ var style = document.documentElement.style, transitions = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' }, transition; transition = _.find( _.keys( transitions ), function( transition ) { return ! _.isUndefined( style[ transition ] ); }); return transition && { end: transitions[ transition ] }; }()); // Makes it easier to bind events using transitions. media.transition = function( selector, sensitivity ) { var deferred = $.Deferred(); sensitivity = sensitivity || 2000; if ( $.support.transition ) { if ( ! (selector instanceof $) ) selector = $( selector ); // Resolve the deferred when the first element finishes animating. selector.first().one( $.support.transition.end, deferred.resolve ); // Just in case the event doesn't trigger, fire a callback. _.delay( deferred.resolve, sensitivity ); // Otherwise, execute on the spot. } else { deferred.resolve(); } return deferred.promise(); }; /** * ======================================================================== * CONTROLLERS * ======================================================================== */ /** * wp.media.controller.Region */ media.controller.Region = function( options ) { _.extend( this, _.pick( options || {}, 'id', 'view', 'selector' ) ); }; // Use Backbone's self-propagating `extend` inheritance method. media.controller.Region.extend = Backbone.Model.extend; _.extend( media.controller.Region.prototype, { mode: function( mode ) { if ( ! mode ) return this._mode; // Bail if we're trying to change to the current mode. if ( mode === this._mode ) return this; this.trigger('deactivate'); this._mode = mode; this.render( mode ); this.trigger('activate'); return this; }, render: function( mode ) { // If no mode is provided, just re-render the current mode. // If the provided mode isn't active, perform a full switch. if ( mode && mode !== this._mode ) return this.mode( mode ); var set = { view: null }, view; this.trigger( 'create', set ); view = set.view; this.trigger( 'render', view ); if ( view ) this.set( view ); return this; }, get: function() { return this.view.views.first( this.selector ); }, set: function( views, options ) { if ( options ) options.add = false; return this.view.views.set( this.selector, views, options ); }, trigger: function( event ) { var base; if ( ! this._mode ) return; var args = _.toArray( arguments ); base = this.id + ':' + event; // Trigger `region:action:mode` event. args[0] = base + ':' + this._mode; this.view.trigger.apply( this.view, args ); // Trigger `region:action` event. args[0] = base; this.view.trigger.apply( this.view, args ); return this; } }); /** * wp.media.controller.StateMachine */ media.controller.StateMachine = function( states ) { this.states = new Backbone.Collection( states ); }; // Use Backbone's self-propagating `extend` inheritance method. media.controller.StateMachine.extend = Backbone.Model.extend; // Add events to the `StateMachine`. _.extend( media.controller.StateMachine.prototype, Backbone.Events, { // Fetch a state. // // If no `id` is provided, returns the active state. // // Implicitly creates states. state: function( id ) { // Ensure that the `states` collection exists so the `StateMachine` // can be used as a mixin. this.states = this.states || new Backbone.Collection(); // Default to the active state. id = id || this._state; if ( id && ! this.states.get( id ) ) this.states.add({ id: id }); return this.states.get( id ); }, // Sets the active state. setState: function( id ) { var previous = this.state(); // Bail if we're trying to select the current state, if we haven't // created the `states` collection, or are trying to select a state // that does not exist. if ( ( previous && id === previous.id ) || ! this.states || ! this.states.get( id ) ) return this; if ( previous ) { previous.trigger('deactivate'); this._lastState = previous.id; } this._state = id; this.state().trigger('activate'); return this; }, // Returns the previous active state. // // Call the `state()` method with no parameters to retrieve the current // active state. lastState: function() { if ( this._lastState ) return this.state( this._lastState ); } }); // Map methods from the `states` collection to the `StateMachine` itself. _.each([ 'on', 'off', 'trigger' ], function( method ) { media.controller.StateMachine.prototype[ method ] = function() { // Ensure that the `states` collection exists so the `StateMachine` // can be used as a mixin. this.states = this.states || new Backbone.Collection(); // Forward the method to the `states` collection. this.states[ method ].apply( this.states, arguments ); return this; }; }); // wp.media.controller.State // --------------------------- media.controller.State = Backbone.Model.extend({ constructor: function() { this.on( 'activate', this._preActivate, this ); this.on( 'activate', this.activate, this ); this.on( 'activate', this._postActivate, this ); this.on( 'deactivate', this._deactivate, this ); this.on( 'deactivate', this.deactivate, this ); this.on( 'reset', this.reset, this ); this.on( 'ready', this._ready, this ); this.on( 'ready', this.ready, this ); Backbone.Model.apply( this, arguments ); this.on( 'change:menu', this._updateMenu, this ); }, ready: function() {}, activate: function() {}, deactivate: function() {}, reset: function() {}, _ready: function() { this._updateMenu(); }, _preActivate: function() { this.active = true; }, _postActivate: function() { this.on( 'change:menu', this._menu, this ); this.on( 'change:titleMode', this._title, this ); this.on( 'change:content', this._content, this ); this.on( 'change:toolbar', this._toolbar, this ); this.frame.on( 'title:render:default', this._renderTitle, this ); this._title(); this._menu(); this._toolbar(); this._content(); this._router(); }, _deactivate: function() { this.active = false; this.frame.off( 'title:render:default', this._renderTitle, this ); this.off( 'change:menu', this._menu, this ); this.off( 'change:titleMode', this._title, this ); this.off( 'change:content', this._content, this ); this.off( 'change:toolbar', this._toolbar, this ); }, _title: function() { this.frame.title.render( this.get('titleMode') || 'default' ); }, _renderTitle: function( view ) { view.$el.text( this.get('title') || '' ); }, _router: function() { var router = this.frame.router, mode = this.get('router'), view; this.frame.$el.toggleClass( 'hide-router', ! mode ); if ( ! mode ) return; this.frame.router.render( mode ); view = router.get(); if ( view && view.select ) view.select( this.frame.content.mode() ); }, _menu: function() { var menu = this.frame.menu, mode = this.get('menu'), view; if ( ! mode ) return; menu.mode( mode ); view = menu.get(); if ( view && view.select ) view.select( this.id ); }, _updateMenu: function() { var previous = this.previous('menu'), menu = this.get('menu'); if ( previous ) this.frame.off( 'menu:render:' + previous, this._renderMenu, this ); if ( menu ) this.frame.on( 'menu:render:' + menu, this._renderMenu, this ); }, _renderMenu: function( view ) { var menuItem = this.get('menuItem'), title = this.get('title'), priority = this.get('priority'); if ( ! menuItem && title ) { menuItem = { text: title }; if ( priority ) menuItem.priority = priority; } if ( ! menuItem ) return; view.set( this.id, menuItem ); } }); _.each(['toolbar','content'], function( region ) { media.controller.State.prototype[ '_' + region ] = function() { var mode = this.get( region ); if ( mode ) this.frame[ region ].render( mode ); }; }); // wp.media.controller.Library // --------------------------- media.controller.Library = media.controller.State.extend({ defaults: { id: 'library', multiple: false, // false, 'add', 'reset' describe: false, toolbar: 'select', sidebar: 'settings', content: 'upload', router: 'browse', menu: 'default', searchable: true, filterable: false, sortable: true, title: l10n.mediaLibraryTitle, // Uses a user setting to override the content mode. contentUserSetting: true, // Sync the selection from the last state when 'multiple' matches. syncSelection: true }, initialize: function() { var selection = this.get('selection'), props; // If a library isn't provided, query all media items. if ( ! this.get('library') ) this.set( 'library', media.query() ); // If a selection instance isn't provided, create one. if ( ! (selection instanceof media.model.Selection) ) { props = selection; if ( ! props ) { props = this.get('library').props.toJSON(); props = _.omit( props, 'orderby', 'query' ); } // If the `selection` attribute is set to an object, // it will use those values as the selection instance's // `props` model. Otherwise, it will copy the library's // `props` model. this.set( 'selection', new media.model.Selection( null, { multiple: this.get('multiple'), props: props }) ); } if ( ! this.get('edge') ) this.set( 'edge', 120 ); if ( ! this.get('gutter') ) this.set( 'gutter', 8 ); this.resetDisplays(); }, activate: function() { this.syncSelection(); wp.Uploader.queue.on( 'add', this.uploading, this ); this.get('selection').on( 'add remove reset', this.refreshContent, this ); if ( this.get('contentUserSetting') ) { this.frame.on( 'content:activate', this.saveContentMode, this ); this.set( 'content', getUserSetting( 'libraryContent', this.get('content') ) ); } }, deactivate: function() { this.recordSelection(); this.frame.off( 'content:activate', this.saveContentMode, this ); // Unbind all event handlers that use this state as the context // from the selection. this.get('selection').off( null, null, this ); wp.Uploader.queue.off( null, null, this ); }, reset: function() { this.get('selection').reset(); this.resetDisplays(); this.refreshContent(); }, resetDisplays: function() { var defaultProps = media.view.settings.defaultProps; this._displays = []; this._defaultDisplaySettings = { align: defaultProps.align || getUserSetting( 'align', 'none' ), size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ), link: defaultProps.link || getUserSetting( 'urlbutton', 'file' ) }; }, display: function( attachment ) { var displays = this._displays; if ( ! displays[ attachment.cid ] ) displays[ attachment.cid ] = new Backbone.Model( this.defaultDisplaySettings( attachment ) ); return displays[ attachment.cid ]; }, defaultDisplaySettings: function( attachment ) { settings = this._defaultDisplaySettings; if ( settings.canEmbed = this.canEmbed( attachment ) ) settings.link = 'embed'; return settings; }, canEmbed: function( attachment ) { // If uploading, we know the filename but not the mime type. if ( ! attachment.get('uploading') ) { var type = attachment.get('type'); if ( type !== 'audio' && type !== 'video' ) return false; } return _.contains( media.view.settings.embedExts, attachment.get('filename').split('.').pop() ); }, syncSelection: function() { var selection = this.get('selection'), manager = this.frame._selection; if ( ! this.get('syncSelection') || ! manager || ! selection ) return; // If the selection supports multiple items, validate the stored // attachments based on the new selection's conditions. Record // the attachments that are not included; we'll maintain a // reference to those. Other attachments are considered in flux. if ( selection.multiple ) { selection.reset( [], { silent: true }); selection.validateAll( manager.attachments ); manager.difference = _.difference( manager.attachments.models, selection.models ); } // Sync the selection's single item with the master. selection.single( manager.single ); }, recordSelection: function() { var selection = this.get('selection'), manager = this.frame._selection, filtered; if ( ! this.get('syncSelection') || ! manager || ! selection ) return; // Record the currently active attachments, which is a combination // of the selection's attachments and the set of selected // attachments that this specific selection considered invalid. // Reset the difference and record the single attachment. if ( selection.multiple ) { manager.attachments.reset( selection.toArray().concat( manager.difference ) ); manager.difference = []; } else { manager.attachments.add( selection.toArray() ); } manager.single = selection._single; }, refreshContent: function() { var selection = this.get('selection'), frame = this.frame, router = frame.router.get(), mode = frame.content.mode(); // If the state is active, no items are selected, and the current // content mode is not an option in the state's router (provided // the state has a router), reset the content mode to the default. if ( this.active && ! selection.length && router && ! router.get( mode ) ) this.frame.content.render( this.get('content') ); }, uploading: function( attachment ) { var content = this.frame.content; // If the uploader was selected, navigate to the browser. if ( 'upload' === content.mode() ) this.frame.content.mode('browse'); // Automatically select any uploading attachments. // // Selections that don't support multiple attachments automatically // limit themselves to one attachment (in this case, the last // attachment in the upload queue). this.get('selection').add( attachment ); }, saveContentMode: function() { // Only track the browse router on library states. if ( 'browse' !== this.get('router') ) return; var mode = this.frame.content.mode(), view = this.frame.router.get(); if ( view && view.get( mode ) ) setUserSetting( 'libraryContent', mode ); } }); // wp.media.controller.GalleryEdit // ------------------------------- media.controller.GalleryEdit = media.controller.Library.extend({ defaults: { id: 'gallery-edit', multiple: false, describe: true, edge: 199, editing: false, sortable: true, searchable: false, toolbar: 'gallery-edit', content: 'browse', title: l10n.editGalleryTitle, priority: 60, dragInfo: true, // Don't sync the selection, as the Edit Gallery library // *is* the selection. syncSelection: false }, initialize: function() { // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', new media.model.Selection() ); // The single `Attachment` view to be used in the `Attachments` view. if ( ! this.get('AttachmentView') ) this.set( 'AttachmentView', media.view.Attachment.EditLibrary ); media.controller.Library.prototype.initialize.apply( this, arguments ); }, activate: function() { var library = this.get('library'); // Limit the library to images only. library.props.set( 'type', 'image' ); // Watch for uploaded attachments. this.get('library').observe( wp.Uploader.queue ); this.frame.on( 'content:render:browse', this.gallerySettings, this ); media.controller.Library.prototype.activate.apply( this, arguments ); }, deactivate: function() { // Stop watching for uploaded attachments. this.get('library').unobserve( wp.Uploader.queue ); this.frame.off( 'content:render:browse', this.gallerySettings, this ); media.controller.Library.prototype.deactivate.apply( this, arguments ); }, gallerySettings: function( browser ) { var library = this.get('library'); if ( ! library || ! browser ) return; library.gallery = library.gallery || new Backbone.Model(); browser.sidebar.set({ gallery: new media.view.Settings.Gallery({ controller: this, model: library.gallery, priority: 40 }) }); browser.toolbar.set( 'reverse', { text: l10n.reverseOrder, priority: 80, click: function() { library.reset( library.toArray().reverse() ); } }); } }); // wp.media.controller.GalleryAdd // --------------------------------- media.controller.GalleryAdd = media.controller.Library.extend({ defaults: _.defaults({ id: 'gallery-library', filterable: 'uploaded', multiple: 'add', menu: 'gallery', toolbar: 'gallery-add', title: l10n.addToGalleryTitle, priority: 100, // Don't sync the selection, as the Edit Gallery library // *is* the selection. syncSelection: false }, media.controller.Library.prototype.defaults ), initialize: function() { // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', media.query({ type: 'image' }) ); media.controller.Library.prototype.initialize.apply( this, arguments ); }, activate: function() { var library = this.get('library'), edit = this.frame.state('gallery-edit').get('library'); if ( this.editLibrary && this.editLibrary !== edit ) library.unobserve( this.editLibrary ); // Accepts attachments that exist in the original library and // that do not exist in gallery's library. library.validator = function( attachment ) { return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments ); }; // Reset the library to ensure that all attachments are re-added // to the collection. Do so silently, as calling `observe` will // trigger the `reset` event. library.reset( library.mirroring.models, { silent: true }); library.observe( edit ); this.editLibrary = edit; media.controller.Library.prototype.activate.apply( this, arguments ); } }); // wp.media.controller.FeaturedImage // --------------------------------- media.controller.FeaturedImage = media.controller.Library.extend({ defaults: _.defaults({ id: 'featured-image', filterable: 'uploaded', multiple: false, toolbar: 'featured-image', title: l10n.setFeaturedImageTitle, priority: 60, syncSelection: false }, media.controller.Library.prototype.defaults ), initialize: function() { var library, comparator; // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', media.query({ type: 'image' }) ); media.controller.Library.prototype.initialize.apply( this, arguments ); library = this.get('library'); comparator = library.comparator; // Overload the library's comparator to push items that are not in // the mirrored query to the front of the aggregate collection. library.comparator = function( a, b ) { var aInQuery = !! this.mirroring.get( a.cid ), bInQuery = !! this.mirroring.get( b.cid ); if ( ! aInQuery && bInQuery ) return -1; else if ( aInQuery && ! bInQuery ) return 1; else return comparator.apply( this, arguments ); }; // Add all items in the selection to the library, so any featured // images that are not initially loaded still appear. library.observe( this.get('selection') ); }, activate: function() { this.updateSelection(); this.frame.on( 'open', this.updateSelection, this ); media.controller.Library.prototype.activate.apply( this, arguments ); }, deactivate: function() { this.frame.off( 'open', this.updateSelection, this ); media.controller.Library.prototype.deactivate.apply( this, arguments ); }, updateSelection: function() { var selection = this.get('selection'), id = media.view.settings.post.featuredImageId, attachment; if ( '' !== id && -1 !== id ) { attachment = Attachment.get( id ); attachment.fetch(); } selection.reset( attachment ? [ attachment ] : [] ); } }); // wp.media.controller.Embed // ------------------------- media.controller.Embed = media.controller.State.extend({ defaults: { id: 'embed', url: '', menu: 'default', content: 'embed', toolbar: 'main-embed', type: 'link', title: l10n.insertFromUrlTitle, priority: 120 }, // The amount of time used when debouncing the scan. sensitivity: 200, initialize: function() { this.debouncedScan = _.debounce( _.bind( this.scan, this ), this.sensitivity ); this.props = new Backbone.Model({ url: '' }); this.props.on( 'change:url', this.debouncedScan, this ); this.props.on( 'change:url', this.refresh, this ); this.on( 'scan', this.scanImage, this ); }, scan: function() { var scanners, embed = this, attributes = { type: 'link', scanners: [] }; // Scan is triggered with the list of `attributes` to set on the // state, useful for the 'type' attribute and 'scanners' attribute, // an array of promise objects for asynchronous scan operations. if ( this.props.get('url') ) this.trigger( 'scan', attributes ); if ( attributes.scanners.length ) { scanners = attributes.scanners = $.when.apply( $, attributes.scanners ); scanners.always( function() { if ( embed.get('scanners') === scanners ) embed.set( 'loading', false ); }); } else { attributes.scanners = null; } attributes.loading = !! attributes.scanners; this.set( attributes ); }, scanImage: function( attributes ) { var frame = this.frame, state = this, url = this.props.get('url'), image = new Image(), deferred = $.Deferred(); attributes.scanners.push( deferred.promise() ); // Try to load the image and find its width/height. image.onload = function() { deferred.resolve(); if ( state !== frame.state() || url !== state.props.get('url') ) return; state.set({ type: 'image' }); state.props.set({ width: image.width, height: image.height }); }; image.onerror = deferred.reject; image.src = url; }, refresh: function() { this.frame.toolbar.get().refresh(); }, reset: function() { this.props.clear().set({ url: '' }); if ( this.active ) this.refresh(); } }); /** * ======================================================================== * VIEWS * ======================================================================== */ // wp.media.View // ------------- // // The base view class. // // Undelegating events, removing events from the model, and // removing events from the controller mirror the code for // `Backbone.View.dispose` in Backbone 0.9.8 development. // // This behavior has since been removed, and should not be used // outside of the media manager. media.View = wp.Backbone.View.extend({ constructor: function( options ) { if ( options && options.controller ) this.controller = options.controller; wp.Backbone.View.apply( this, arguments ); }, dispose: function() { // Undelegating events, removing events from the model, and // removing events from the controller mirror the code for // `Backbone.View.dispose` in Backbone 0.9.8 development. this.undelegateEvents(); if ( this.model && this.model.off ) this.model.off( null, null, this ); if ( this.collection && this.collection.off ) this.collection.off( null, null, this ); // Unbind controller events. if ( this.controller && this.controller.off ) this.controller.off( null, null, this ); return this; }, remove: function() { this.dispose(); return wp.Backbone.View.prototype.remove.apply( this, arguments ); } }); /** * wp.media.view.Frame */ media.view.Frame = media.View.extend({ initialize: function() { this._createRegions(); this._createStates(); }, _createRegions: function() { // Clone the regions array. this.regions = this.regions ? this.regions.slice() : []; // Initialize regions. _.each( this.regions, function( region ) { this[ region ] = new media.controller.Region({ view: this, id: region, selector: '.media-frame-' + region }); }, this ); }, _createStates: function() { // Create the default `states` collection. this.states = new Backbone.Collection( null, { model: media.controller.State }); // Ensure states have a reference to the frame. this.states.on( 'add', function( model ) { model.frame = this; model.trigger('ready'); }, this ); if ( this.options.states ) this.states.add( this.options.states ); }, reset: function() { this.states.invoke( 'trigger', 'reset' ); return this; } }); // Make the `Frame` a `StateMachine`. _.extend( media.view.Frame.prototype, media.controller.StateMachine.prototype ); /** * wp.media.view.MediaFrame */ media.view.MediaFrame = media.view.Frame.extend({ className: 'media-frame', template: media.template('media-frame'), regions: ['menu','title','content','toolbar','router'], initialize: function() { media.view.Frame.prototype.initialize.apply( this, arguments ); _.defaults( this.options, { title: '', modal: true, uploader: true }); // Ensure core UI is enabled. this.$el.addClass('wp-core-ui'); // Initialize modal container view. if ( this.options.modal ) { this.modal = new media.view.Modal({ controller: this, title: this.options.title }); this.modal.content( this ); } // Force the uploader off if the upload limit has been exceeded or // if the browser isn't supported. if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported ) this.options.uploader = false; // Initialize window-wide uploader. if ( this.options.uploader ) { this.uploader = new media.view.UploaderWindow({ controller: this, uploader: { dropzone: this.modal ? this.modal.$el : this.$el, container: this.$el } }); this.views.set( '.media-frame-uploader', this.uploader ); } this.on( 'attach', _.bind( this.views.ready, this.views ), this ); // Bind default title creation. this.on( 'title:create:default', this.createTitle, this ); this.title.mode('default'); // Bind default menu. this.on( 'menu:create:default', this.createMenu, this ); }, render: function() { // Activate the default state if no active state exists. if ( ! this.state() && this.options.state ) this.setState( this.options.state ); return media.view.Frame.prototype.render.apply( this, arguments ); }, createTitle: function( title ) { title.view = new media.View({ controller: this, tagName: 'h1' }); }, createMenu: function( menu ) { menu.view = new media.view.Menu({ controller: this }); }, createToolbar: function( toolbar ) { toolbar.view = new media.view.Toolbar({ controller: this }); }, createRouter: function( router ) { router.view = new media.view.Router({ controller: this }); }, createIframeStates: function( options ) { var settings = media.view.settings, tabs = settings.tabs, tabUrl = settings.tabUrl, $postId; if ( ! tabs || ! tabUrl ) return; // Add the post ID to the tab URL if it exists. $postId = $('#post_ID'); if ( $postId.length ) tabUrl += '&post_id=' + $postId.val(); // Generate the tab states. _.each( tabs, function( title, id ) { var frame = this.state( 'iframe:' + id ).set( _.defaults({ tab: id, src: tabUrl + '&tab=' + id, title: title, content: 'iframe', menu: 'default' }, options ) ); }, this ); this.on( 'content:create:iframe', this.iframeContent, this ); this.on( 'menu:render:default', this.iframeMenu, this ); this.on( 'open', this.hijackThickbox, this ); this.on( 'close', this.restoreThickbox, this ); }, iframeContent: function( content ) { this.$el.addClass('hide-toolbar'); content.view = new media.view.Iframe({ controller: this }); }, iframeMenu: function( view ) { var views = {}; if ( ! view ) return; _.each( media.view.settings.tabs, function( title, id ) { views[ 'iframe:' + id ] = { text: this.state( 'iframe:' + id ).get('title'), priority: 200 }; }, this ); view.set( views ); }, hijackThickbox: function() { var frame = this; if ( ! window.tb_remove || this._tb_remove ) return; this._tb_remove = window.tb_remove; window.tb_remove = function() { frame.close(); frame.reset(); frame.setState( frame.options.state ); frame._tb_remove.call( window ); }; }, restoreThickbox: function() { if ( ! this._tb_remove ) return; window.tb_remove = this._tb_remove; delete this._tb_remove; } }); // Map some of the modal's methods to the frame. _.each(['open','close','attach','detach','escape'], function( method ) { media.view.MediaFrame.prototype[ method ] = function( view ) { if ( this.modal ) this.modal[ method ].apply( this.modal, arguments ); return this; }; }); /** * wp.media.view.MediaFrame.Select */ media.view.MediaFrame.Select = media.view.MediaFrame.extend({ initialize: function() { media.view.MediaFrame.prototype.initialize.apply( this, arguments ); _.defaults( this.options, { selection: [], library: {}, multiple: false, state: 'library' }); this.createSelection(); this.createStates(); this.bindHandlers(); }, createSelection: function() { var controller = this, selection = this.options.selection; if ( ! (selection instanceof media.model.Selection) ) { this.options.selection = new media.model.Selection( selection, { multiple: this.options.multiple }); } this._selection = { attachments: new Attachments(), difference: [] }; }, createStates: function() { var options = this.options; if ( this.options.states ) return; // Add the default states. this.states.add([ // Main states. new media.controller.Library({ library: media.query( options.library ), multiple: options.multiple, title: options.title, priority: 20 }) ]); }, bindHandlers: function() { this.on( 'router:create:browse', this.createRouter, this ); this.on( 'router:render:browse', this.browseRouter, this ); this.on( 'content:create:browse', this.browseContent, this ); this.on( 'content:render:upload', this.uploadContent, this ); this.on( 'toolbar:create:select', this.createSelectToolbar, this ); }, // Routers browseRouter: function( view ) { view.set({ upload: { text: l10n.uploadFilesTitle, priority: 20 }, browse: { text: l10n.mediaLibraryTitle, priority: 40 } }); }, // Content browseContent: function( content ) { var state = this.state(); this.$el.removeClass('hide-toolbar'); // Browse our library of attachments. content.view = new media.view.AttachmentsBrowser({ controller: this, collection: state.get('library'), selection: state.get('selection'), model: state, sortable: state.get('sortable'), search: state.get('searchable'), filters: state.get('filterable'), display: state.get('displaySettings'), dragInfo: state.get('dragInfo'), AttachmentView: state.get('AttachmentView') }); }, uploadContent: function() { this.$el.removeClass('hide-toolbar'); this.content.set( new media.view.UploaderInline({ controller: this }) ); }, // Toolbars createSelectToolbar: function( toolbar, options ) { options = options || this.options.button || {}; options.controller = this; toolbar.view = new media.view.Toolbar.Select( options ); } }); /** * wp.media.view.MediaFrame.Post */ media.view.MediaFrame.Post = media.view.MediaFrame.Select.extend({ initialize: function() { _.defaults( this.options, { multiple: true, editing: false, state: 'insert' }); media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments ); this.createIframeStates(); }, createStates: function() { var options = this.options; // Add the default states. this.states.add([ // Main states. new media.controller.Library({ id: 'insert', title: l10n.insertMediaTitle, priority: 20, toolbar: 'main-insert', filterable: 'all', library: media.query( options.library ), multiple: options.multiple ? 'reset' : false, editable: true, // If the user isn't allowed to edit fields, // can they still edit it locally? allowLocalEdits: true, // Show the attachment display settings. displaySettings: true, // Update user settings when users adjust the // attachment display settings. displayUserSettings: true }), new media.controller.Library({ id: 'gallery', title: l10n.createGalleryTitle, priority: 40, toolbar: 'main-gallery', filterable: 'uploaded', multiple: 'add', editable: false, library: media.query( _.defaults({ type: 'image' }, options.library ) ) }), // Embed states. new media.controller.Embed(), // Gallery states. new media.controller.GalleryEdit({ library: options.selection, editing: options.editing, menu: 'gallery' }), new media.controller.GalleryAdd() ]); if ( media.view.settings.post.featuredImageId ) { this.states.add( new media.controller.FeaturedImage() ); } }, bindHandlers: function() { media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments ); this.on( 'menu:create:gallery', this.createMenu, this ); this.on( 'toolbar:create:main-insert', this.createToolbar, this ); this.on( 'toolbar:create:main-gallery', this.createToolbar, this ); this.on( 'toolbar:create:featured-image', this.featuredImageToolbar, this ); this.on( 'toolbar:create:main-embed', this.mainEmbedToolbar, this ); var handlers = { menu: { 'default': 'mainMenu', 'gallery': 'galleryMenu' }, content: { 'embed': 'embedContent', 'edit-selection': 'editSelectionContent' }, toolbar: { 'main-insert': 'mainInsertToolbar', 'main-gallery': 'mainGalleryToolbar', 'gallery-edit': 'galleryEditToolbar', 'gallery-add': 'galleryAddToolbar' } }; _.each( handlers, function( regionHandlers, region ) { _.each( regionHandlers, function( callback, handler ) { this.on( region + ':render:' + handler, this[ callback ], this ); }, this ); }, this ); }, // Menus mainMenu: function( view ) { view.set({ 'library-separator': new media.View({ className: 'separator', priority: 100 }) }); }, galleryMenu: function( view ) { var lastState = this.lastState(), previous = lastState && lastState.id, frame = this; view.set({ cancel: { text: l10n.cancelGalleryTitle, priority: 20, click: function() { if ( previous ) frame.setState( previous ); else frame.close(); } }, separateCancel: new media.View({ className: 'separator', priority: 40 }) }); }, // Content embedContent: function() { var view = new media.view.Embed({ controller: this, model: this.state() }).render(); this.content.set( view ); view.url.focus(); }, editSelectionContent: function() { var state = this.state(), selection = state.get('selection'), view; view = new media.view.AttachmentsBrowser({ controller: this, collection: selection, selection: selection, model: state, sortable: true, search: false, dragInfo: true, AttachmentView: media.view.Attachment.EditSelection }).render(); view.toolbar.set( 'backToLibrary', { text: l10n.returnToLibrary, priority: -100, click: function() { this.controller.content.mode('browse'); } }); // Browse our library of attachments. this.content.set( view ); }, // Toolbars selectionStatusToolbar: function( view ) { var editable = this.state().get('editable'); view.set( 'selection', new media.view.Selection({ controller: this, collection: this.state().get('selection'), priority: -40, // If the selection is editable, pass the callback to // switch the content mode. editable: editable && function() { this.controller.content.mode('edit-selection'); } }).render() ); }, mainInsertToolbar: function( view ) { var controller = this; this.selectionStatusToolbar( view ); view.set( 'insert', { style: 'primary', priority: 80, text: l10n.insertIntoPost, requires: { selection: true }, click: function() { var state = controller.state(), selection = state.get('selection'); controller.close(); state.trigger( 'insert', selection ).reset(); } }); }, mainGalleryToolbar: function( view ) { var controller = this; this.selectionStatusToolbar( view ); view.set( 'gallery', { style: 'primary', text: l10n.createNewGallery, priority: 60, requires: { selection: true }, click: function() { var selection = controller.state().get('selection'), edit = controller.state('gallery-edit'), models = selection.where({ type: 'image' }); edit.set( 'library', new media.model.Selection( models, { props: selection.props.toJSON(), multiple: true }) ); this.controller.setState('gallery-edit'); } }); }, featuredImageToolbar: function( toolbar ) { this.createSelectToolbar( toolbar, { text: l10n.setFeaturedImage, state: this.options.state }); }, mainEmbedToolbar: function( toolbar ) { toolbar.view = new media.view.Toolbar.Embed({ controller: this }); }, galleryEditToolbar: function() { var editing = this.state().get('editing'); this.toolbar.set( new media.view.Toolbar({ controller: this, items: { insert: { style: 'primary', text: editing ? l10n.updateGallery : l10n.insertGallery, priority: 80, requires: { library: true }, click: function() { var controller = this.controller, state = controller.state(); controller.close(); state.trigger( 'update', state.get('library') ); // Restore and reset the default state. controller.setState( controller.options.state ); controller.reset(); } } } }) ); }, galleryAddToolbar: function() { this.toolbar.set( new media.view.Toolbar({ controller: this, items: { insert: { style: 'primary', text: l10n.addToGallery, priority: 80, requires: { selection: true }, click: function() { var controller = this.controller, state = controller.state(), edit = controller.state('gallery-edit'); edit.get('library').add( state.get('selection').models ); state.trigger('reset'); controller.setState('gallery-edit'); } } } }) ); } }); /** * wp.media.view.Modal */ media.view.Modal = media.View.extend({ tagName: 'div', template: media.template('media-modal'), attributes: { tabindex: 0 }, events: { 'click .media-modal-backdrop, .media-modal-close': 'escapeHandler', 'keydown': 'keydown' }, initialize: function() { _.defaults( this.options, { container: document.body, title: '', propagate: true, freeze: true }); }, prepare: function() { return { title: this.options.title }; }, attach: function() { if ( this.views.attached ) return this; if ( ! this.views.rendered ) this.render(); this.$el.appendTo( this.options.container ); // Manually mark the view as attached and trigger ready. this.views.attached = true; this.views.ready(); return this.propagate('attach'); }, detach: function() { if ( this.$el.is(':visible') ) this.close(); this.$el.detach(); this.views.attached = false; return this.propagate('detach'); }, open: function() { var $el = this.$el, options = this.options; if ( $el.is(':visible') ) return this; if ( ! this.views.attached ) this.attach(); // If the `freeze` option is set, record the window's scroll position. if ( options.freeze ) { this._freeze = { scrollTop: $( window ).scrollTop() }; } $el.show().focus(); return this.propagate('open'); }, close: function( options ) { var freeze = this._freeze; if ( ! this.views.attached || ! this.$el.is(':visible') ) return this; this.$el.hide(); this.propagate('close'); // If the `freeze` option is set, restore the container's scroll position. if ( freeze ) { $( window ).scrollTop( freeze.scrollTop ); } if ( options && options.escape ) this.propagate('escape'); return this; }, escape: function() { return this.close({ escape: true }); }, escapeHandler: function( event ) { event.preventDefault(); this.escape(); }, content: function( content ) { this.views.set( '.media-modal-content', content ); return this; }, // Triggers a modal event and if the `propagate` option is set, // forwards events to the modal's controller. propagate: function( id ) { this.trigger( id ); if ( this.options.propagate ) this.controller.trigger( id ); return this; }, keydown: function( event ) { // Close the modal when escape is pressed. if ( 27 === event.which ) { event.preventDefault(); this.escape(); return; } } }); // wp.media.view.FocusManager // ---------------------------- media.view.FocusManager = media.View.extend({ events: { keydown: 'recordTab', focusin: 'updateIndex' }, focus: function() { if ( _.isUndefined( this.index ) ) return; // Update our collection of `$tabbables`. this.$tabbables = this.$(':tabbable'); // If tab is saved, focus it. this.$tabbables.eq( this.index ).focus(); }, recordTab: function( event ) { // Look for the tab key. if ( 9 !== event.keyCode ) return; // First try to update the index. if ( _.isUndefined( this.index ) ) this.updateIndex( event ); // If we still don't have an index, bail. if ( _.isUndefined( this.index ) ) return; var index = this.index + ( event.shiftKey ? -1 : 1 ); if ( index >= 0 && index < this.$tabbables.length ) this.index = index; else delete this.index; }, updateIndex: function( event ) { this.$tabbables = this.$(':tabbable'); var index = this.$tabbables.index( event.target ); if ( -1 === index ) delete this.index; else this.index = index; } }); // wp.media.view.UploaderWindow // ---------------------------- media.view.UploaderWindow = media.View.extend({ tagName: 'div', className: 'uploader-window', template: media.template('uploader-window'), initialize: function() { var uploader; this.$browser = $('<a href="#" class="browser" />').hide().appendTo('body'); uploader = this.options.uploader = _.defaults( this.options.uploader || {}, { dropzone: this.$el, browser: this.$browser, params: {} }); // Ensure the dropzone is a jQuery collection. if ( uploader.dropzone && ! (uploader.dropzone instanceof $) ) uploader.dropzone = $( uploader.dropzone ); this.controller.on( 'activate', this.refresh, this ); }, refresh: function() { if ( this.uploader ) this.uploader.refresh(); }, ready: function() { var postId = media.view.settings.post.id, dropzone; // If the uploader already exists, bail. if ( this.uploader ) return; if ( postId ) this.options.uploader.params.post_id = postId; this.uploader = new wp.Uploader( this.options.uploader ); dropzone = this.uploader.dropzone; dropzone.on( 'dropzone:enter', _.bind( this.show, this ) ); dropzone.on( 'dropzone:leave', _.bind( this.hide, this ) ); }, show: function() { var $el = this.$el.show(); // Ensure that the animation is triggered by waiting until // the transparent element is painted into the DOM. _.defer( function() { $el.css({ opacity: 1 }); }); }, hide: function() { var $el = this.$el.css({ opacity: 0 }); media.transition( $el ).done( function() { // Transition end events are subject to race conditions. // Make sure that the value is set as intended. if ( '0' === $el.css('opacity') ) $el.hide(); }); } }); media.view.UploaderInline = media.View.extend({ tagName: 'div', className: 'uploader-inline', template: media.template('uploader-inline'), initialize: function() { _.defaults( this.options, { message: '', status: true }); if ( ! this.options.$browser && this.controller.uploader ) this.options.$browser = this.controller.uploader.$browser; if ( _.isUndefined( this.options.postId ) ) this.options.postId = media.view.settings.post.id; if ( this.options.status ) { this.views.set( '.upload-inline-status', new media.view.UploaderStatus({ controller: this.controller }) ); } }, dispose: function() { if ( this.disposing ) return media.View.prototype.dispose.apply( this, arguments ); // Run remove on `dispose`, so we can be sure to refresh the // uploader with a view-less DOM. Track whether we're disposing // so we don't trigger an infinite loop. this.disposing = true; return this.remove(); }, remove: function() { var result = media.View.prototype.remove.apply( this, arguments ); _.defer( _.bind( this.refresh, this ) ); return result; }, refresh: function() { var uploader = this.controller.uploader; if ( uploader ) uploader.refresh(); }, ready: function() { var $browser = this.options.$browser, $placeholder; if ( this.controller.uploader ) { $placeholder = this.$('.browser'); // Check if we've already replaced the placeholder. if ( $placeholder[0] === $browser[0] ) return; $browser.detach().text( $placeholder.text() ); $browser[0].className = $placeholder[0].className; $placeholder.replaceWith( $browser.show() ); } this.refresh(); return this; } }); /** * wp.media.view.UploaderStatus */ media.view.UploaderStatus = media.View.extend({ className: 'media-uploader-status', template: media.template('uploader-status'), events: { 'click .upload-dismiss-errors': 'dismiss' }, initialize: function() { this.queue = wp.Uploader.queue; this.queue.on( 'add remove reset', this.visibility, this ); this.queue.on( 'add remove reset change:percent', this.progress, this ); this.queue.on( 'add remove reset change:uploading', this.info, this ); this.errors = wp.Uploader.errors; this.errors.reset(); this.errors.on( 'add remove reset', this.visibility, this ); this.errors.on( 'add', this.error, this ); }, dispose: function() { wp.Uploader.queue.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, visibility: function() { this.$el.toggleClass( 'uploading', !! this.queue.length ); this.$el.toggleClass( 'errors', !! this.errors.length ); this.$el.toggle( !! this.queue.length || !! this.errors.length ); }, ready: function() { _.each({ '$bar': '.media-progress-bar div', '$index': '.upload-index', '$total': '.upload-total', '$filename': '.upload-filename' }, function( selector, key ) { this[ key ] = this.$( selector ); }, this ); this.visibility(); this.progress(); this.info(); }, progress: function() { var queue = this.queue, $bar = this.$bar, memo = 0; if ( ! $bar || ! queue.length ) return; $bar.width( ( queue.reduce( function( memo, attachment ) { if ( ! attachment.get('uploading') ) return memo + 100; var percent = attachment.get('percent'); return memo + ( _.isNumber( percent ) ? percent : 100 ); }, 0 ) / queue.length ) + '%' ); }, info: function() { var queue = this.queue, index = 0, active; if ( ! queue.length ) return; active = this.queue.find( function( attachment, i ) { index = i; return attachment.get('uploading'); }); this.$index.text( index + 1 ); this.$total.text( queue.length ); this.$filename.html( active ? this.filename( active.get('filename') ) : '' ); }, filename: function( filename ) { return media.truncate( _.escape( filename ), 24 ); }, error: function( error ) { this.views.add( '.upload-errors', new media.view.UploaderStatusError({ filename: this.filename( error.get('file').name ), message: error.get('message') }), { at: 0 }); }, dismiss: function( event ) { var errors = this.views.get('.upload-errors'); event.preventDefault(); if ( errors ) _.invoke( errors, 'remove' ); wp.Uploader.errors.reset(); } }); media.view.UploaderStatusError = media.View.extend({ className: 'upload-error', template: media.template('uploader-status-error') }); /** * wp.media.view.Toolbar */ media.view.Toolbar = media.View.extend({ tagName: 'div', className: 'media-toolbar', initialize: function() { var state = this.controller.state(), selection = this.selection = state.get('selection'), library = this.library = state.get('library'); this._views = {}; // The toolbar is composed of two `PriorityList` views. this.primary = new media.view.PriorityList(); this.secondary = new media.view.PriorityList(); this.primary.$el.addClass('media-toolbar-primary'); this.secondary.$el.addClass('media-toolbar-secondary'); this.views.set([ this.secondary, this.primary ]); if ( this.options.items ) this.set( this.options.items, { silent: true }); if ( ! this.options.silent ) this.render(); if ( selection ) selection.on( 'add remove reset', this.refresh, this ); if ( library ) library.on( 'add remove reset', this.refresh, this ); }, dispose: function() { if ( this.selection ) this.selection.off( null, null, this ); if ( this.library ) this.library.off( null, null, this ); return media.View.prototype.dispose.apply( this, arguments ); }, ready: function() { this.refresh(); }, set: function( id, view, options ) { var list; options = options || {}; // Accept an object with an `id` : `view` mapping. if ( _.isObject( id ) ) { _.each( id, function( view, id ) { this.set( id, view, { silent: true }); }, this ); } else { if ( ! ( view instanceof Backbone.View ) ) { view.classes = [ 'media-button-' + id ].concat( view.classes || [] ); view = new media.view.Button( view ).render(); } view.controller = view.controller || this.controller; this._views[ id ] = view; list = view.options.priority < 0 ? 'secondary' : 'primary'; this[ list ].set( id, view, options ); } if ( ! options.silent ) this.refresh(); return this; }, get: function( id ) { return this._views[ id ]; }, unset: function( id, options ) { delete this._views[ id ]; this.primary.unset( id, options ); this.secondary.unset( id, options ); if ( ! options || ! options.silent ) this.refresh(); return this; }, refresh: function() { var state = this.controller.state(), library = state.get('library'), selection = state.get('selection'); _.each( this._views, function( button ) { if ( ! button.model || ! button.options || ! button.options.requires ) return; var requires = button.options.requires, disabled = false; // Prevent insertion of attachments if any of them are still uploading disabled = _.some( selection.models, function( attachment ) { return attachment.get('uploading') === true; }); if ( requires.selection && selection && ! selection.length ) disabled = true; else if ( requires.library && library && ! library.length ) disabled = true; button.model.set( 'disabled', disabled ); }); } }); // wp.media.view.Toolbar.Select // ---------------------------- media.view.Toolbar.Select = media.view.Toolbar.extend({ initialize: function() { var options = this.options, controller = options.controller, selection = controller.state().get('selection'); _.bindAll( this, 'clickSelect' ); _.defaults( options, { event: 'select', state: false, reset: true, close: true, text: l10n.select, // Does the button rely on the selection? requires: { selection: true } }); options.items = _.defaults( options.items || {}, { select: { style: 'primary', text: options.text, priority: 80, click: this.clickSelect, requires: options.requires } }); media.view.Toolbar.prototype.initialize.apply( this, arguments ); }, clickSelect: function() { var options = this.options, controller = this.controller; if ( options.close ) controller.close(); if ( options.event ) controller.state().trigger( options.event ); if ( options.state ) controller.setState( options.state ); if ( options.reset ) controller.reset(); } }); // wp.media.view.Toolbar.Embed // --------------------------- media.view.Toolbar.Embed = media.view.Toolbar.Select.extend({ initialize: function() { _.defaults( this.options, { text: l10n.insertIntoPost, requires: false }); media.view.Toolbar.Select.prototype.initialize.apply( this, arguments ); }, refresh: function() { var url = this.controller.state().props.get('url'); this.get('select').model.set( 'disabled', ! url || url === 'http://' ); media.view.Toolbar.Select.prototype.refresh.apply( this, arguments ); } }); /** * wp.media.view.Button */ media.view.Button = media.View.extend({ tagName: 'a', className: 'media-button', attributes: { href: '#' }, events: { 'click': 'click' }, defaults: { text: '', style: '', size: 'large', disabled: false }, initialize: function() { // Create a model with the provided `defaults`. this.model = new Backbone.Model( this.defaults ); // If any of the `options` have a key from `defaults`, apply its // value to the `model` and remove it from the `options object. _.each( this.defaults, function( def, key ) { var value = this.options[ key ]; if ( _.isUndefined( value ) ) return; this.model.set( key, value ); delete this.options[ key ]; }, this ); this.model.on( 'change', this.render, this ); }, render: function() { var classes = [ 'button', this.className ], model = this.model.toJSON(); if ( model.style ) classes.push( 'button-' + model.style ); if ( model.size ) classes.push( 'button-' + model.size ); classes = _.uniq( classes.concat( this.options.classes ) ); this.el.className = classes.join(' '); this.$el.attr( 'disabled', model.disabled ); this.$el.text( this.model.get('text') ); return this; }, click: function( event ) { if ( '#' === this.attributes.href ) event.preventDefault(); if ( this.options.click && ! this.model.get('disabled') ) this.options.click.apply( this, arguments ); } }); /** * wp.media.view.ButtonGroup */ media.view.ButtonGroup = media.View.extend({ tagName: 'div', className: 'button-group button-large media-button-group', initialize: function() { this.buttons = _.map( this.options.buttons || [], function( button ) { if ( button instanceof Backbone.View ) return button; else return new media.view.Button( button ).render(); }); delete this.options.buttons; if ( this.options.classes ) this.$el.addClass( this.options.classes ); }, render: function() { this.$el.html( $( _.pluck( this.buttons, 'el' ) ).detach() ); return this; } }); /** * wp.media.view.PriorityList */ media.view.PriorityList = media.View.extend({ tagName: 'div', initialize: function() { this._views = {}; this.set( _.extend( {}, this._views, this.options.views ), { silent: true }); delete this.options.views; if ( ! this.options.silent ) this.render(); }, set: function( id, view, options ) { var priority, views, index; options = options || {}; // Accept an object with an `id` : `view` mapping. if ( _.isObject( id ) ) { _.each( id, function( view, id ) { this.set( id, view ); }, this ); return this; } if ( ! (view instanceof Backbone.View) ) view = this.toView( view, id, options ); view.controller = view.controller || this.controller; this.unset( id ); priority = view.options.priority || 10; views = this.views.get() || []; _.find( views, function( existing, i ) { if ( existing.options.priority > priority ) { index = i; return true; } }); this._views[ id ] = view; this.views.add( view, { at: _.isNumber( index ) ? index : views.length || 0 }); return this; }, get: function( id ) { return this._views[ id ]; }, unset: function( id ) { var view = this.get( id ); if ( view ) view.remove(); delete this._views[ id ]; return this; }, toView: function( options ) { return new media.View( options ); } }); /** * wp.media.view.MenuItem */ media.view.MenuItem = media.View.extend({ tagName: 'a', className: 'media-menu-item', attributes: { href: '#' }, events: { 'click': '_click' }, _click: function( event ) { var clickOverride = this.options.click; if ( event ) event.preventDefault(); if ( clickOverride ) clickOverride.call( this ); else this.click(); }, click: function() { var state = this.options.state; if ( state ) this.controller.setState( state ); }, render: function() { var options = this.options; if ( options.text ) this.$el.text( options.text ); else if ( options.html ) this.$el.html( options.html ); return this; } }); /** * wp.media.view.Menu */ media.view.Menu = media.view.PriorityList.extend({ tagName: 'div', className: 'media-menu', property: 'state', ItemView: media.view.MenuItem, region: 'menu', toView: function( options, id ) { options = options || {}; options[ this.property ] = options[ this.property ] || id; return new this.ItemView( options ).render(); }, ready: function() { media.view.PriorityList.prototype.ready.apply( this, arguments ); this.visibility(); }, set: function() { media.view.PriorityList.prototype.set.apply( this, arguments ); this.visibility(); }, unset: function() { media.view.PriorityList.prototype.unset.apply( this, arguments ); this.visibility(); }, visibility: function() { var region = this.region, view = this.controller[ region ].get(), views = this.views.get(), hide = ! views || views.length < 2; if ( this === view ) this.controller.$el.toggleClass( 'hide-' + region, hide ); }, select: function( id ) { var view = this.get( id ); if ( ! view ) return; this.deselect(); view.$el.addClass('active'); }, deselect: function() { this.$el.children().removeClass('active'); } }); /** * wp.media.view.RouterItem */ media.view.RouterItem = media.view.MenuItem.extend({ click: function() { var contentMode = this.options.contentMode; if ( contentMode ) this.controller.content.mode( contentMode ); } }); /** * wp.media.view.Router */ media.view.Router = media.view.Menu.extend({ tagName: 'div', className: 'media-router', property: 'contentMode', ItemView: media.view.RouterItem, region: 'router', initialize: function() { this.controller.on( 'content:render', this.update, this ); media.view.Menu.prototype.initialize.apply( this, arguments ); }, update: function() { var mode = this.controller.content.mode(); if ( mode ) this.select( mode ); } }); /** * wp.media.view.Sidebar */ media.view.Sidebar = media.view.PriorityList.extend({ className: 'media-sidebar' }); /** * wp.media.view.Attachment */ media.view.Attachment = media.View.extend({ tagName: 'li', className: 'attachment', template: media.template('attachment'), events: { 'click .attachment-preview': 'toggleSelectionHandler', 'change [data-setting]': 'updateSetting', 'change [data-setting] input': 'updateSetting', 'change [data-setting] select': 'updateSetting', 'change [data-setting] textarea': 'updateSetting', 'click .close': 'removeFromLibrary', 'click .check': 'removeFromSelection', 'click a': 'preventDefault' }, buttons: {}, initialize: function() { var selection = this.options.selection; this.model.on( 'change:sizes change:uploading', this.render, this ); this.model.on( 'change:title', this._syncTitle, this ); this.model.on( 'change:caption', this._syncCaption, this ); this.model.on( 'change:percent', this.progress, this ); // Update the selection. this.model.on( 'add', this.select, this ); this.model.on( 'remove', this.deselect, this ); if ( selection ) selection.on( 'reset', this.updateSelect, this ); // Update the model's details view. this.model.on( 'selection:single selection:unsingle', this.details, this ); this.details( this.model, this.controller.state().get('selection') ); }, dispose: function() { var selection = this.options.selection; // Make sure all settings are saved before removing the view. this.updateAll(); if ( selection ) selection.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, render: function() { var options = _.defaults( this.model.toJSON(), { orientation: 'landscape', uploading: false, type: '', subtype: '', icon: '', filename: '', caption: '', title: '', dateFormatted: '', width: '', height: '', compat: false, alt: '', description: '' }); options.buttons = this.buttons; options.describe = this.controller.state().get('describe'); if ( 'image' === options.type ) options.size = this.imageSize(); options.can = {}; if ( options.nonces ) { options.can.remove = !! options.nonces['delete']; options.can.save = !! options.nonces.update; } if ( this.controller.state().get('allowLocalEdits') ) options.allowLocalEdits = true; this.views.detach(); this.$el.html( this.template( options ) ); this.$el.toggleClass( 'uploading', options.uploading ); if ( options.uploading ) this.$bar = this.$('.media-progress-bar div'); else delete this.$bar; // Check if the model is selected. this.updateSelect(); // Update the save status. this.updateSave(); this.views.render(); return this; }, progress: function() { if ( this.$bar && this.$bar.length ) this.$bar.width( this.model.get('percent') + '%' ); }, toggleSelectionHandler: function( event ) { var method; if ( event.shiftKey ) method = 'between'; else if ( event.ctrlKey || event.metaKey ) method = 'toggle'; this.toggleSelection({ method: method }); }, toggleSelection: function( options ) { var collection = this.collection, selection = this.options.selection, model = this.model, method = options && options.method, single, between, models, singleIndex, modelIndex; if ( ! selection ) return; single = selection.single(); method = _.isUndefined( method ) ? selection.multiple : method; // If the `method` is set to `between`, select all models that // exist between the current and the selected model. if ( 'between' === method && single && selection.multiple ) { // If the models are the same, short-circuit. if ( single === model ) return; singleIndex = collection.indexOf( single ); modelIndex = collection.indexOf( this.model ); if ( singleIndex < modelIndex ) models = collection.models.slice( singleIndex, modelIndex + 1 ); else models = collection.models.slice( modelIndex, singleIndex + 1 ); selection.add( models ).single( model ); return; // If the `method` is set to `toggle`, just flip the selection // status, regardless of whether the model is the single model. } else if ( 'toggle' === method ) { selection[ this.selected() ? 'remove' : 'add' ]( model ).single( model ); return; } if ( method !== 'add' ) method = 'reset'; if ( this.selected() ) { // If the model is the single model, remove it. // If it is not the same as the single model, // it now becomes the single model. selection[ single === model ? 'remove' : 'single' ]( model ); } else { // If the model is not selected, run the `method` on the // selection. By default, we `reset` the selection, but the // `method` can be set to `add` the model to the selection. selection[ method ]( model ).single( model ); } }, updateSelect: function() { this[ this.selected() ? 'select' : 'deselect' ](); }, selected: function() { var selection = this.options.selection; if ( selection ) return !! selection.get( this.model.cid ); }, select: function( model, collection ) { var selection = this.options.selection; // Check if a selection exists and if it's the collection provided. // If they're not the same collection, bail; we're in another // selection's event loop. if ( ! selection || ( collection && collection !== selection ) ) return; this.$el.addClass('selected'); }, deselect: function( model, collection ) { var selection = this.options.selection; // Check if a selection exists and if it's the collection provided. // If they're not the same collection, bail; we're in another // selection's event loop. if ( ! selection || ( collection && collection !== selection ) ) return; this.$el.removeClass('selected'); }, details: function( model, collection ) { var selection = this.options.selection, details; if ( selection !== collection ) return; details = selection.single(); this.$el.toggleClass( 'details', details === this.model ); }, preventDefault: function( event ) { event.preventDefault(); }, imageSize: function( size ) { var sizes = this.model.get('sizes'); size = size || 'medium'; // Use the provided image size if possible. if ( sizes && sizes[ size ] ) { return _.clone( sizes[ size ] ); } else { return { url: this.model.get('url'), width: this.model.get('width'), height: this.model.get('height'), orientation: this.model.get('orientation') }; } }, updateSetting: function( event ) { var $setting = $( event.target ).closest('[data-setting]'), setting, value; if ( ! $setting.length ) return; setting = $setting.data('setting'); value = event.target.value; if ( this.model.get( setting ) !== value ) this.save( setting, value ); }, // Pass all the arguments to the model's save method. // // Records the aggregate status of all save requests and updates the // view's classes accordingly. save: function() { var view = this, save = this._save = this._save || { status: 'ready' }, request = this.model.save.apply( this.model, arguments ), requests = save.requests ? $.when( request, save.requests ) : request; // If we're waiting to remove 'Saved.', stop. if ( save.savedTimer ) clearTimeout( save.savedTimer ); this.updateSave('waiting'); save.requests = requests; requests.always( function() { // If we've performed another request since this one, bail. if ( save.requests !== requests ) return; view.updateSave( requests.state() === 'resolved' ? 'complete' : 'error' ); save.savedTimer = setTimeout( function() { view.updateSave('ready'); delete save.savedTimer; }, 2000 ); }); }, updateSave: function( status ) { var save = this._save = this._save || { status: 'ready' }; if ( status && status !== save.status ) { this.$el.removeClass( 'save-' + save.status ); save.status = status; } this.$el.addClass( 'save-' + save.status ); return this; }, updateAll: function() { var $settings = this.$('[data-setting]'), model = this.model, changed; changed = _.chain( $settings ).map( function( el ) { var $input = $('input, textarea, select, [value]', el ), setting, value; if ( ! $input.length ) return; setting = $(el).data('setting'); value = $input.val(); // Record the value if it changed. if ( model.get( setting ) !== value ) return [ setting, value ]; }).compact().object().value(); if ( ! _.isEmpty( changed ) ) model.save( changed ); }, removeFromLibrary: function( event ) { // Stop propagation so the model isn't selected. event.stopPropagation(); this.collection.remove( this.model ); }, removeFromSelection: function( event ) { var selection = this.options.selection; if ( ! selection ) return; // Stop propagation so the model isn't selected. event.stopPropagation(); selection.remove( this.model ); } }); // Ensure settings remain in sync between attachment views. _.each({ caption: '_syncCaption', title: '_syncTitle' }, function( method, setting ) { media.view.Attachment.prototype[ method ] = function( model, value ) { var $setting = this.$('[data-setting="' + setting + '"]'); if ( ! $setting.length ) return this; // If the updated value is in sync with the value in the DOM, there // is no need to re-render. If we're currently editing the value, // it will automatically be in sync, suppressing the re-render for // the view we're editing, while updating any others. if ( value === $setting.find('input, textarea, select, [value]').val() ) return this; return this.render(); }; }); /** * wp.media.view.Attachment.Library */ media.view.Attachment.Library = media.view.Attachment.extend({ buttons: { check: true } }); /** * wp.media.view.Attachment.EditLibrary */ media.view.Attachment.EditLibrary = media.view.Attachment.extend({ buttons: { close: true } }); /** * wp.media.view.Attachments */ media.view.Attachments = media.View.extend({ tagName: 'ul', className: 'attachments', cssTemplate: media.template('attachments-css'), events: { 'scroll': 'scroll' }, initialize: function() { this.el.id = _.uniqueId('__attachments-view-'); _.defaults( this.options, { refreshSensitivity: 200, refreshThreshold: 3, AttachmentView: media.view.Attachment, sortable: false, resize: true }); this._viewsByCid = {}; this.collection.on( 'add', function( attachment, attachments, options ) { this.views.add( this.createAttachmentView( attachment ), { at: this.collection.indexOf( attachment ) }); }, this ); this.collection.on( 'remove', function( attachment, attachments, options ) { var view = this._viewsByCid[ attachment.cid ]; delete this._viewsByCid[ attachment.cid ]; if ( view ) view.remove(); }, this ); this.collection.on( 'reset', this.render, this ); // Throttle the scroll handler. this.scroll = _.chain( this.scroll ).bind( this ).throttle( this.options.refreshSensitivity ).value(); this.initSortable(); _.bindAll( this, 'css' ); this.model.on( 'change:edge change:gutter', this.css, this ); this._resizeCss = _.debounce( _.bind( this.css, this ), this.refreshSensitivity ); if ( this.options.resize ) $(window).on( 'resize.attachments', this._resizeCss ); this.css(); }, dispose: function() { this.collection.props.off( null, null, this ); $(window).off( 'resize.attachments', this._resizeCss ); media.View.prototype.dispose.apply( this, arguments ); }, css: function() { var $css = $( '#' + this.el.id + '-css' ); if ( $css.length ) $css.remove(); media.view.Attachments.$head().append( this.cssTemplate({ id: this.el.id, edge: this.edge(), gutter: this.model.get('gutter') }) ); }, edge: function() { var edge = this.model.get('edge'), gutter, width, columns; if ( ! this.$el.is(':visible') ) return edge; gutter = this.model.get('gutter') * 2; width = this.$el.width() - gutter; columns = Math.ceil( width / ( edge + gutter ) ); edge = Math.floor( ( width - ( columns * gutter ) ) / columns ); return edge; }, initSortable: function() { var collection = this.collection; if ( ! this.options.sortable || ! $.fn.sortable ) return; this.$el.sortable( _.extend({ // If the `collection` has a `comparator`, disable sorting. disabled: !! collection.comparator, // Prevent attachments from being dragged outside the bounding // box of the list. containment: this.$el, // Change the position of the attachment as soon as the // mouse pointer overlaps a thumbnail. tolerance: 'pointer', // Record the initial `index` of the dragged model. start: function( event, ui ) { ui.item.data('sortableIndexStart', ui.item.index()); }, // Update the model's index in the collection. // Do so silently, as the view is already accurate. update: function( event, ui ) { var model = collection.at( ui.item.data('sortableIndexStart') ), comparator = collection.comparator; // Temporarily disable the comparator to prevent `add` // from re-sorting. delete collection.comparator; // Silently shift the model to its new index. collection.remove( model, { silent: true }).add( model, { silent: true, at: ui.item.index() }); // Restore the comparator. collection.comparator = comparator; // Fire the `reset` event to ensure other collections sync. collection.trigger( 'reset', collection ); // If the collection is sorted by menu order, // update the menu order. collection.saveMenuOrder(); } }, this.options.sortable ) ); // If the `orderby` property is changed on the `collection`, // check to see if we have a `comparator`. If so, disable sorting. collection.props.on( 'change:orderby', function() { this.$el.sortable( 'option', 'disabled', !! collection.comparator ); }, this ); this.collection.props.on( 'change:orderby', this.refreshSortable, this ); this.refreshSortable(); }, refreshSortable: function() { if ( ! this.options.sortable || ! $.fn.sortable ) return; // If the `collection` has a `comparator`, disable sorting. var collection = this.collection, orderby = collection.props.get('orderby'), enabled = 'menuOrder' === orderby || ! collection.comparator; this.$el.sortable( 'option', 'disabled', ! enabled ); }, createAttachmentView: function( attachment ) { var view = new this.options.AttachmentView({ controller: this.controller, model: attachment, collection: this.collection, selection: this.options.selection }); return this._viewsByCid[ attachment.cid ] = view; }, prepare: function() { // Create all of the Attachment views, and replace // the list in a single DOM operation. if ( this.collection.length ) { this.views.set( this.collection.map( this.createAttachmentView, this ) ); // If there are no elements, clear the views and load some. } else { this.views.unset(); this.collection.more().done( this.scroll ); } }, ready: function() { // Trigger the scroll event to check if we're within the // threshold to query for additional attachments. this.scroll(); }, scroll: function( event ) { // @todo: is this still necessary? if ( ! this.$el.is(':visible') ) return; if ( this.collection.hasMore() && this.el.scrollHeight < this.el.scrollTop + ( this.el.clientHeight * this.options.refreshThreshold ) ) { this.collection.more().done( this.scroll ); } } }, { $head: (function() { var $head; return function() { return $head = $head || $('head'); }; }()) }); /** * wp.media.view.Search */ media.view.Search = media.View.extend({ tagName: 'input', className: 'search', attributes: { type: 'search', placeholder: l10n.search }, events: { 'input': 'search', 'keyup': 'search', 'change': 'search', 'search': 'search' }, render: function() { this.el.value = this.model.escape('search'); return this; }, search: function( event ) { if ( event.target.value ) this.model.set( 'search', event.target.value ); else this.model.unset('search'); } }); /** * wp.media.view.AttachmentFilters */ media.view.AttachmentFilters = media.View.extend({ tagName: 'select', className: 'attachment-filters', events: { change: 'change' }, keys: [], initialize: function() { this.createFilters(); _.extend( this.filters, this.options.filters ); // Build `<option>` elements. this.$el.html( _.chain( this.filters ).map( function( filter, value ) { return { el: $('<option></option>').val(value).text(filter.text)[0], priority: filter.priority || 50 }; }, this ).sortBy('priority').pluck('el').value() ); this.model.on( 'change', this.select, this ); this.select(); }, createFilters: function() { this.filters = {}; }, change: function( event ) { var filter = this.filters[ this.el.value ]; if ( filter ) this.model.set( filter.props ); }, select: function() { var model = this.model, value = 'all', props = model.toJSON(); _.find( this.filters, function( filter, id ) { var equal = _.all( filter.props, function( prop, key ) { return prop === ( _.isUndefined( props[ key ] ) ? null : props[ key ] ); }); if ( equal ) return value = id; }); this.$el.val( value ); } }); media.view.AttachmentFilters.Uploaded = media.view.AttachmentFilters.extend({ createFilters: function() { var type = this.model.get('type'), types = media.view.settings.mimeTypes, text; if ( types && type ) text = types[ type ]; this.filters = { all: { text: text || l10n.allMediaItems, props: { uploadedTo: null, orderby: 'date', order: 'DESC' }, priority: 10 }, uploaded: { text: l10n.uploadedToThisPost, props: { uploadedTo: media.view.settings.post.id, orderby: 'menuOrder', order: 'ASC' }, priority: 20 } }; } }); media.view.AttachmentFilters.All = media.view.AttachmentFilters.extend({ createFilters: function() { var filters = {}; _.each( media.view.settings.mimeTypes || {}, function( text, key ) { filters[ key ] = { text: text, props: { type: key, uploadedTo: null, orderby: 'date', order: 'DESC' } }; }); filters.all = { text: l10n.allMediaItems, props: { type: null, uploadedTo: null, orderby: 'date', order: 'DESC' }, priority: 10 }; filters.uploaded = { text: l10n.uploadedToThisPost, props: { type: null, uploadedTo: media.view.settings.post.id, orderby: 'menuOrder', order: 'ASC' }, priority: 20 }; this.filters = filters; } }); /** * wp.media.view.AttachmentsBrowser */ media.view.AttachmentsBrowser = media.View.extend({ tagName: 'div', className: 'attachments-browser', initialize: function() { _.defaults( this.options, { filters: false, search: true, display: false, AttachmentView: media.view.Attachment.Library }); this.createToolbar(); this.updateContent(); this.createSidebar(); this.collection.on( 'add remove reset', this.updateContent, this ); }, dispose: function() { this.options.selection.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, createToolbar: function() { var filters, FiltersConstructor; this.toolbar = new media.view.Toolbar({ controller: this.controller }); this.views.add( this.toolbar ); filters = this.options.filters; if ( 'uploaded' === filters ) FiltersConstructor = media.view.AttachmentFilters.Uploaded; else if ( 'all' === filters ) FiltersConstructor = media.view.AttachmentFilters.All; if ( FiltersConstructor ) { this.toolbar.set( 'filters', new FiltersConstructor({ controller: this.controller, model: this.collection.props, priority: -80 }).render() ); } if ( this.options.search ) { this.toolbar.set( 'search', new media.view.Search({ controller: this.controller, model: this.collection.props, priority: 60 }).render() ); } if ( this.options.dragInfo ) { this.toolbar.set( 'dragInfo', new media.View({ el: $( '<div class="instructions">' + l10n.dragInfo + '</div>' )[0], priority: -40 }) ); } }, updateContent: function() { var view = this; if( ! this.attachments ) this.createAttachments(); if ( ! this.collection.length ) { this.collection.more().done( function() { if ( ! view.collection.length ) view.createUploader(); }); } }, removeContent: function() { _.each(['attachments','uploader'], function( key ) { if ( this[ key ] ) { this[ key ].remove(); delete this[ key ]; } }, this ); }, createUploader: function() { this.removeContent(); this.uploader = new media.view.UploaderInline({ controller: this.controller, status: false, message: l10n.noItemsFound }); this.views.add( this.uploader ); }, createAttachments: function() { this.removeContent(); this.attachments = new media.view.Attachments({ controller: this.controller, collection: this.collection, selection: this.options.selection, model: this.model, sortable: this.options.sortable, // The single `Attachment` view to be used in the `Attachments` view. AttachmentView: this.options.AttachmentView }); this.views.add( this.attachments ); }, createSidebar: function() { var options = this.options, selection = options.selection, sidebar = this.sidebar = new media.view.Sidebar({ controller: this.controller }); this.views.add( sidebar ); if ( this.controller.uploader ) { sidebar.set( 'uploads', new media.view.UploaderStatus({ controller: this.controller, priority: 40 }) ); } selection.on( 'selection:single', this.createSingle, this ); selection.on( 'selection:unsingle', this.disposeSingle, this ); if ( selection.single() ) this.createSingle(); }, createSingle: function() { var sidebar = this.sidebar, single = this.options.selection.single(), views = {}; sidebar.set( 'details', new media.view.Attachment.Details({ controller: this.controller, model: single, priority: 80 }) ); sidebar.set( 'compat', new media.view.AttachmentCompat({ controller: this.controller, model: single, priority: 120 }) ); if ( this.options.display ) { sidebar.set( 'display', new media.view.Settings.AttachmentDisplay({ controller: this.controller, model: this.model.display( single ), attachment: single, priority: 160, userSettings: this.model.get('displayUserSettings') }) ); } }, disposeSingle: function() { var sidebar = this.sidebar; sidebar.unset('details'); sidebar.unset('compat'); sidebar.unset('display'); } }); /** * wp.media.view.Selection */ media.view.Selection = media.View.extend({ tagName: 'div', className: 'media-selection', template: media.template('media-selection'), events: { 'click .edit-selection': 'edit', 'click .clear-selection': 'clear' }, initialize: function() { _.defaults( this.options, { editable: false, clearable: true }); this.attachments = new media.view.Attachments.Selection({ controller: this.controller, collection: this.collection, selection: this.collection, model: new Backbone.Model({ edge: 40, gutter: 5 }) }); this.views.set( '.selection-view', this.attachments ); this.collection.on( 'add remove reset', this.refresh, this ); this.controller.on( 'content:activate', this.refresh, this ); }, ready: function() { this.refresh(); }, refresh: function() { // If the selection hasn't been rendered, bail. if ( ! this.$el.children().length ) return; var collection = this.collection, editing = 'edit-selection' === this.controller.content.mode(); // If nothing is selected, display nothing. this.$el.toggleClass( 'empty', ! collection.length ); this.$el.toggleClass( 'one', 1 === collection.length ); this.$el.toggleClass( 'editing', editing ); this.$('.count').text( l10n.selected.replace('%d', collection.length) ); }, edit: function( event ) { event.preventDefault(); if ( this.options.editable ) this.options.editable.call( this, this.collection ); }, clear: function( event ) { event.preventDefault(); this.collection.reset(); } }); /** * wp.media.view.Attachment.Selection */ media.view.Attachment.Selection = media.view.Attachment.extend({ className: 'attachment selection', // On click, just select the model, instead of removing the model from // the selection. toggleSelection: function() { this.options.selection.single( this.model ); } }); /** * wp.media.view.Attachments.Selection */ media.view.Attachments.Selection = media.view.Attachments.extend({ events: {}, initialize: function() { _.defaults( this.options, { sortable: true, resize: false, // The single `Attachment` view to be used in the `Attachments` view. AttachmentView: media.view.Attachment.Selection }); return media.view.Attachments.prototype.initialize.apply( this, arguments ); } }); /** * wp.media.view.Attachments.EditSelection */ media.view.Attachment.EditSelection = media.view.Attachment.Selection.extend({ buttons: { close: true } }); /** * wp.media.view.Settings */ media.view.Settings = media.View.extend({ events: { 'click button': 'updateHandler', 'change input': 'updateHandler', 'change select': 'updateHandler', 'change textarea': 'updateHandler' }, initialize: function() { this.model = this.model || new Backbone.Model(); this.model.on( 'change', this.updateChanges, this ); }, prepare: function() { return _.defaults({ model: this.model.toJSON() }, this.options ); }, render: function() { media.View.prototype.render.apply( this, arguments ); // Select the correct values. _( this.model.attributes ).chain().keys().each( this.update, this ); return this; }, update: function( key ) { var value = this.model.get( key ), $setting = this.$('[data-setting="' + key + '"]'), $buttons, $value; // Bail if we didn't find a matching setting. if ( ! $setting.length ) return; // Attempt to determine how the setting is rendered and update // the selected value. // Handle dropdowns. if ( $setting.is('select') ) { $value = $setting.find('[value="' + value + '"]'); if ( $value.length ) { $setting.find('option').prop( 'selected', false ); $value.prop( 'selected', true ); } else { // If we can't find the desired value, record what *is* selected. this.model.set( key, $setting.find(':selected').val() ); } // Handle button groups. } else if ( $setting.hasClass('button-group') ) { $buttons = $setting.find('button').removeClass('active'); $buttons.filter( '[value="' + value + '"]' ).addClass('active'); // Handle text inputs and textareas. } else if ( $setting.is('input[type="text"], textarea') ) { if ( ! $setting.is(':focus') ) $setting.val( value ); // Handle checkboxes. } else if ( $setting.is('input[type="checkbox"]') ) { $setting.attr( 'checked', !! value ); } }, updateHandler: function( event ) { var $setting = $( event.target ).closest('[data-setting]'), value = event.target.value, userSetting; event.preventDefault(); if ( ! $setting.length ) return; // Use the correct value for checkboxes. if ( $setting.is('input[type="checkbox"]') ) value = $setting[0].checked; // Update the corresponding setting. this.model.set( $setting.data('setting'), value ); // If the setting has a corresponding user setting, // update that as well. if ( userSetting = $setting.data('userSetting') ) setUserSetting( userSetting, value ); }, updateChanges: function( model, options ) { if ( model.hasChanged() ) _( model.changed ).chain().keys().each( this.update, this ); } }); /** * wp.media.view.Settings.AttachmentDisplay */ media.view.Settings.AttachmentDisplay = media.view.Settings.extend({ className: 'attachment-display-settings', template: media.template('attachment-display-settings'), initialize: function() { var attachment = this.options.attachment; _.defaults( this.options, { userSettings: false }); media.view.Settings.prototype.initialize.apply( this, arguments ); this.model.on( 'change:link', this.updateLinkTo, this ); if ( attachment ) attachment.on( 'change:uploading', this.render, this ); }, dispose: function() { var attachment = this.options.attachment; if ( attachment ) attachment.off( null, null, this ); media.view.Settings.prototype.dispose.apply( this, arguments ); }, render: function() { var attachment = this.options.attachment; if ( attachment ) { _.extend( this.options, { sizes: attachment.get('sizes'), type: attachment.get('type') }); } media.view.Settings.prototype.render.call( this ); this.updateLinkTo(); return this; }, updateLinkTo: function() { var linkTo = this.model.get('link'), $input = this.$('.link-to-custom'), attachment = this.options.attachment; if ( 'none' === linkTo || 'embed' === linkTo || ( ! attachment && 'custom' !== linkTo ) ) { $input.hide(); return; } if ( attachment ) { if ( 'post' === linkTo ) { $input.val( attachment.get('link') ); } else if ( 'file' === linkTo ) { $input.val( attachment.get('url') ); } else if ( ! this.model.get('linkUrl') ) { $input.val('http://'); } $input.prop( 'readonly', 'custom' !== linkTo ); } $input.show(); // If the input is visible, focus and select its contents. if ( $input.is(':visible') ) $input.focus()[0].select(); } }); /** * wp.media.view.Settings.Gallery */ media.view.Settings.Gallery = media.view.Settings.extend({ className: 'gallery-settings', template: media.template('gallery-settings') }); /** * wp.media.view.Attachment.Details */ media.view.Attachment.Details = media.view.Attachment.extend({ tagName: 'div', className: 'attachment-details', template: media.template('attachment-details'), events: { 'change [data-setting]': 'updateSetting', 'change [data-setting] input': 'updateSetting', 'change [data-setting] select': 'updateSetting', 'change [data-setting] textarea': 'updateSetting', 'click .delete-attachment': 'deleteAttachment', 'click .edit-attachment': 'editAttachment', 'click .refresh-attachment': 'refreshAttachment' }, initialize: function() { this.focusManager = new media.view.FocusManager({ el: this.el }); media.view.Attachment.prototype.initialize.apply( this, arguments ); }, render: function() { media.view.Attachment.prototype.render.apply( this, arguments ); this.focusManager.focus(); return this; }, deleteAttachment: function( event ) { event.preventDefault(); if ( confirm( l10n.warnDelete ) ) this.model.destroy(); }, editAttachment: function( event ) { this.$el.addClass('needs-refresh'); }, refreshAttachment: function( event ) { this.$el.removeClass('needs-refresh'); event.preventDefault(); this.model.fetch(); } }); /** * wp.media.view.AttachmentCompat */ media.view.AttachmentCompat = media.View.extend({ tagName: 'form', className: 'compat-item', events: { 'submit': 'preventDefault', 'change input': 'save', 'change select': 'save', 'change textarea': 'save' }, initialize: function() { this.focusManager = new media.view.FocusManager({ el: this.el }); this.model.on( 'change:compat', this.render, this ); }, dispose: function() { if ( this.$(':focus').length ) this.save(); return media.View.prototype.dispose.apply( this, arguments ); }, render: function() { var compat = this.model.get('compat'); if ( ! compat || ! compat.item ) return; this.views.detach(); this.$el.html( compat.item ); this.views.render(); this.focusManager.focus(); return this; }, preventDefault: function( event ) { event.preventDefault(); }, save: function( event ) { var data = {}; if ( event ) event.preventDefault(); _.each( this.$el.serializeArray(), function( pair ) { data[ pair.name ] = pair.value; }); this.model.saveCompat( data ); } }); /** * wp.media.view.Iframe */ media.view.Iframe = media.View.extend({ className: 'media-iframe', render: function() { this.views.detach(); this.$el.html( '<iframe src="' + this.controller.state().get('src') + '" />' ); this.views.render(); return this; } }); /** * wp.media.view.Embed */ media.view.Embed = media.View.extend({ className: 'media-embed', initialize: function() { this.url = new media.view.EmbedUrl({ controller: this.controller, model: this.model.props }).render(); this.views.set([ this.url ]); this.refresh(); this.model.on( 'change:type', this.refresh, this ); this.model.on( 'change:loading', this.loading, this ); }, settings: function( view ) { if ( this._settings ) this._settings.remove(); this._settings = view; this.views.add( view ); }, refresh: function() { var type = this.model.get('type'), constructor; if ( 'image' === type ) constructor = media.view.EmbedImage; else if ( 'link' === type ) constructor = media.view.EmbedLink; else return; this.settings( new constructor({ controller: this.controller, model: this.model.props, priority: 40 }) ); }, loading: function() { this.$el.toggleClass( 'embed-loading', this.model.get('loading') ); } }); /** * wp.media.view.EmbedUrl */ media.view.EmbedUrl = media.View.extend({ tagName: 'label', className: 'embed-url', events: { 'input': 'url', 'keyup': 'url', 'change': 'url' }, initialize: function() { this.$input = $('<input/>').attr( 'type', 'text' ).val( this.model.get('url') ); this.input = this.$input[0]; this.spinner = $('<span class="spinner" />')[0]; this.$el.append([ this.input, this.spinner ]); this.model.on( 'change:url', this.render, this ); }, render: function() { var $input = this.$input; if ( $input.is(':focus') ) return; this.input.value = this.model.get('url') || 'http://'; media.View.prototype.render.apply( this, arguments ); return this; }, ready: function() { this.focus(); }, url: function( event ) { this.model.set( 'url', event.target.value ); }, focus: function() { var $input = this.$input; // If the input is visible, focus and select its contents. if ( $input.is(':visible') ) $input.focus()[0].select(); } }); /** * wp.media.view.EmbedLink */ media.view.EmbedLink = media.view.Settings.extend({ className: 'embed-link-settings', template: media.template('embed-link-settings') }); /** * wp.media.view.EmbedImage */ media.view.EmbedImage = media.view.Settings.AttachmentDisplay.extend({ className: 'embed-image-settings', template: media.template('embed-image-settings'), initialize: function() { media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments ); this.model.on( 'change:url', this.updateImage, this ); }, updateImage: function() { this.$('img').attr( 'src', this.model.get('url') ); } }); }(jQuery));
JavaScript
/** * Heartbeat API * * Note: this API is "experimental" meaning it will likely change a lot * in the next few releases based on feedback from 3.6.0. If you intend * to use it, please follow the development closely. * * Heartbeat is a simple server polling API that sends XHR requests to * the server every 15 seconds and triggers events (or callbacks) upon * receiving data. Currently these 'ticks' handle transports for post locking, * login-expiration warnings, and related tasks while a user is logged in. * * Available filters in ajax-actions.php: * - heartbeat_received * - heartbeat_send * - heartbeat_tick * - heartbeat_nopriv_received * - heartbeat_nopriv_send * - heartbeat_nopriv_tick * @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat() * * @since 3.6.0 */ // Ensure the global `wp` object exists. window.wp = window.wp || {}; (function($){ var Heartbeat = function() { var self = this, running, beat, screenId = typeof pagenow != 'undefined' ? pagenow : '', url = typeof ajaxurl != 'undefined' ? ajaxurl : '', settings, tick = 0, queue = {}, interval, connecting, countdown = 0, errorcount = 0, tempInterval, hasFocus = true, isUserActive, userActiveEvents, winBlurTimeout, frameBlurTimeout = -1, hasConnectionError = false; /** * Returns a boolean that's indicative of whether or not there is a connection error * * @returns boolean */ this.hasConnectionError = function() { return hasConnectionError; }; if ( typeof( window.heartbeatSettings ) == 'object' ) { settings = $.extend( {}, window.heartbeatSettings ); // Add private vars url = settings.ajaxurl || url; delete settings.ajaxurl; delete settings.nonce; interval = settings.interval || 15; // default interval delete settings.interval; // The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec. if ( interval < 15 ) interval = 15; else if ( interval > 60 ) interval = 60; interval = interval * 1000; // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set screenId = screenId || settings.screenId || 'front'; delete settings.screenId; // Add or overwrite public vars $.extend( this, settings ); } function time(s) { if ( s ) return parseInt( (new Date()).getTime() / 1000 ); return (new Date()).getTime(); } function isLocalFrame( frame ) { var origin, src = frame.src; if ( src && /^https?:\/\//.test( src ) ) { origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host; if ( src.indexOf( origin ) !== 0 ) return false; } try { if ( frame.contentWindow.document ) return true; } catch(e) {} return false; } // Set error state and fire an event on XHR errors or timeout function errorstate( error ) { var trigger; if ( error ) { switch ( error ) { case 'abort': // do nothing break; case 'timeout': // no response for 30 sec. trigger = true; break; case 'parsererror': case 'error': case 'empty': case 'unknown': errorcount++; if ( errorcount > 2 ) trigger = true; break; } if ( trigger && ! self.hasConnectionError() ) { hasConnectionError = true; $(document).trigger( 'heartbeat-connection-lost', [error] ); } } else if ( self.hasConnectionError() ) { errorcount = 0; hasConnectionError = false; $(document).trigger( 'heartbeat-connection-restored' ); } } function connect() { var send = {}, data, i, empty = true, nonce = typeof window.heartbeatSettings == 'object' ? window.heartbeatSettings.nonce : ''; tick = time(); data = $.extend( {}, queue ); // Clear the data queue, anything added after this point will be send on the next tick queue = {}; $(document).trigger( 'heartbeat-send', [data] ); for ( i in data ) { if ( data.hasOwnProperty( i ) ) { empty = false; break; } } // If nothing to send (nothing is expecting a response), // schedule the next tick and bail if ( empty && ! self.hasConnectionError() ) { connecting = false; next(); return; } send.data = data; send.interval = interval / 1000; send._nonce = nonce; send.action = 'heartbeat'; send.screen_id = screenId; send.has_focus = hasFocus; connecting = true; self.xhr = $.ajax({ url: url, type: 'post', timeout: 30000, // throw an error if not completed after 30 sec. data: send, dataType: 'json' }).done( function( response, textStatus, jqXHR ) { var new_interval; if ( ! response ) return errorstate( 'empty' ); // Clear error state if ( self.hasConnectionError() ) errorstate(); if ( response.nonces_expired ) { $(document).trigger( 'heartbeat-nonces-expired' ); return; } // Change the interval from PHP if ( response.heartbeat_interval ) { new_interval = response.heartbeat_interval; delete response.heartbeat_interval; } self.tick( response, textStatus, jqXHR ); // do this last, can trigger the next XHR if connection time > 5 sec. and new_interval == 'fast' if ( new_interval ) self.interval.call( self, new_interval ); }).always( function() { connecting = false; next(); }).fail( function( jqXHR, textStatus, error ) { errorstate( textStatus || 'unknown' ); self.error( jqXHR, textStatus, error ); }); } function next() { var delta = time() - tick, t = interval; if ( ! running ) return; if ( ! hasFocus ) { t = 100000; // 100 sec. Post locks expire after 120 sec. } else if ( countdown > 0 && tempInterval ) { t = tempInterval; countdown--; } window.clearTimeout(beat); if ( delta < t ) { beat = window.setTimeout( function(){ if ( running ) connect(); }, t - delta ); } else { connect(); } } function blurred() { window.clearTimeout(winBlurTimeout); window.clearTimeout(frameBlurTimeout); winBlurTimeout = frameBlurTimeout = 0; hasFocus = false; } function focused() { window.clearTimeout(winBlurTimeout); window.clearTimeout(frameBlurTimeout); winBlurTimeout = frameBlurTimeout = 0; isUserActive = time(); if ( hasFocus ) return; hasFocus = true; window.clearTimeout(beat); if ( ! connecting ) next(); } function setFrameEvents() { $('iframe').each( function( i, frame ){ if ( ! isLocalFrame( frame ) ) return; if ( $.data( frame, 'wp-heartbeat-focus' ) ) return; $.data( frame, 'wp-heartbeat-focus', 1 ); $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function(e) { focused(); }).on('blur.wp-heartbeat-focus', function(e) { setFrameEvents(); frameBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 ); }); }); } $(window).on( 'blur.wp-heartbeat-focus', function(e) { setFrameEvents(); winBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 ); }).on( 'focus.wp-heartbeat-focus', function() { $('iframe').each( function( i, frame ) { if ( !isLocalFrame( frame ) ) return; $.removeData( frame, 'wp-heartbeat-focus' ); $( frame.contentWindow ).off( '.wp-heartbeat-focus' ); }); focused(); }); function userIsActive() { userActiveEvents = false; $(document).off( '.wp-heartbeat-active' ); $('iframe').each( function( i, frame ) { if ( ! isLocalFrame( frame ) ) return; $( frame.contentWindow ).off( '.wp-heartbeat-active' ); }); focused(); } // Set 'hasFocus = true' if user is active and the window is in the background. // Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity) for 5 min. even when the window has focus. function checkUserActive() { var lastActive = isUserActive ? time() - isUserActive : 0; // Throttle down when no mouse or keyboard activity for 5 min if ( lastActive > 300000 && hasFocus ) blurred(); if ( ! userActiveEvents ) { $(document).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } ); $('iframe').each( function( i, frame ) { if ( ! isLocalFrame( frame ) ) return; $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } ); }); userActiveEvents = true; } } // Check for user activity every 30 seconds. window.setInterval( function(){ checkUserActive(); }, 30000 ); $(document).ready( function() { // Start one tick (15 sec) after DOM ready running = true; tick = time(); next(); }); this.hasFocus = function() { return hasFocus; }; /** * Get/Set the interval * * When setting to 'fast', the interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec). * If the window doesn't have focus, the interval slows down to 2 min. * * @param string speed Interval speed: 'fast' (5sec), 'standard' (15sec) default, 'slow' (60sec) * @param string ticks Used with speed = 'fast', how many ticks before the speed reverts back * @return int Current interval in seconds */ this.interval = function( speed, ticks ) { var reset, seconds; ticks = parseInt( ticks, 10 ) || 30; ticks = ticks < 1 || ticks > 30 ? 30 : ticks; if ( speed ) { switch ( speed ) { case 'fast': seconds = 5; countdown = ticks; break; case 'slow': seconds = 60; countdown = 0; break; case 'long-polling': // Allow long polling, (experimental) interval = 0; return 0; break; default: seconds = 15; countdown = 0; } // Reset when the new interval value is lower than the current one reset = seconds * 1000 < interval; if ( countdown > 0 ) { tempInterval = seconds * 1000; } else { interval = seconds * 1000; tempInterval = 0; } if ( reset ) next(); } if ( ! hasFocus ) return 120; return tempInterval ? tempInterval / 1000 : interval / 1000; }; /** * Enqueue data to send with the next XHR * * As the data is sent later, this function doesn't return the XHR response. * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example: * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) { * // code * }); * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'. * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle. * * $param string handle Unique handle for the data. The handle is used in PHP to receive the data. * $param mixed data The data to send. * $param bool dont_overwrite Whether to overwrite existing data in the queue. * $return bool Whether the data was queued or not. */ this.enqueue = function( handle, data, dont_overwrite ) { if ( handle ) { if ( queue.hasOwnProperty( handle ) && dont_overwrite ) return false; queue[handle] = data; return true; } return false; }; /** * Check if data with a particular handle is queued * * $param string handle The handle for the data * $return mixed The data queued with that handle or null */ this.isQueued = function( handle ) { return queue[handle]; }; }; $.extend( Heartbeat.prototype, { tick: function( data, textStatus, jqXHR ) { $(document).trigger( 'heartbeat-tick', [data, textStatus, jqXHR] ); }, error: function( jqXHR, textStatus, error ) { $(document).trigger( 'heartbeat-error', [jqXHR, textStatus, error] ); } }); wp.heartbeat = new Heartbeat(); }(jQuery));
JavaScript
// WordPress, TinyMCE, and Media // ----------------------------- (function($){ // Stores the editors' `wp.media.controller.Frame` instances. var workflows = {}; wp.media.string = { // Joins the `props` and `attachment` objects, // outputting the proper object format based on the // attachment's type. props: function( props, attachment ) { var link, linkUrl, size, sizes, fallbacks, defaultProps = wp.media.view.settings.defaultProps; // Final fallbacks run after all processing has been completed. fallbacks = function( props ) { // Generate alt fallbacks and strip tags. if ( 'image' === props.type && ! props.alt ) { props.alt = props.caption || props.title || ''; props.alt = props.alt.replace( /<\/?[^>]+>/g, '' ); props.alt = props.alt.replace( /[\r\n]+/g, ' ' ); } return props; }; props = props ? _.clone( props ) : {}; if ( attachment && attachment.type ) props.type = attachment.type; if ( 'image' === props.type ) { props = _.defaults( props || {}, { align: defaultProps.align || getUserSetting( 'align', 'none' ), size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ), url: '', classes: [] }); } // All attachment-specific settings follow. if ( ! attachment ) return fallbacks( props ); props.title = props.title || attachment.title; link = props.link || defaultProps.link || getUserSetting( 'urlbutton', 'file' ); if ( 'file' === link || 'embed' === link ) linkUrl = attachment.url; else if ( 'post' === link ) linkUrl = attachment.link; else if ( 'custom' === link ) linkUrl = props.linkUrl; props.linkUrl = linkUrl || ''; // Format properties for images. if ( 'image' === attachment.type ) { props.classes.push( 'wp-image-' + attachment.id ); sizes = attachment.sizes; size = sizes && sizes[ props.size ] ? sizes[ props.size ] : attachment; _.extend( props, _.pick( attachment, 'align', 'caption', 'alt' ), { width: size.width, height: size.height, src: size.url, captionId: 'attachment_' + attachment.id }); } else if ( 'video' === attachment.type || 'audio' === attachment.type ) { _.extend( props, _.pick( attachment, 'title', 'type', 'icon', 'mime' ) ); // Format properties for non-images. } else { props.title = props.title || attachment.filename; props.rel = props.rel || 'attachment wp-att-' + attachment.id; } return fallbacks( props ); }, link: function( props, attachment ) { var options; props = wp.media.string.props( props, attachment ); options = { tag: 'a', content: props.title, attrs: { href: props.linkUrl } }; if ( props.rel ) options.attrs.rel = props.rel; return wp.html.string( options ); }, audio: function( props, attachment ) { return wp.media.string._audioVideo( 'audio', props, attachment ); }, video: function( props, attachment ) { return wp.media.string._audioVideo( 'video', props, attachment ); }, _audioVideo: function( type, props, attachment ) { var shortcode, html, extension; props = wp.media.string.props( props, attachment ); if ( props.link !== 'embed' ) return wp.media.string.link( props ); shortcode = {}; if ( 'video' === type ) { if ( attachment.width ) shortcode.width = attachment.width; if ( attachment.height ) shortcode.height = attachment.height; } extension = attachment.filename.split('.').pop(); if ( _.contains( wp.media.view.settings.embedExts, extension ) ) { shortcode[extension] = attachment.url; } else { // Render unsupported audio and video files as links. return wp.media.string.link( props ); } html = wp.shortcode.string({ tag: type, attrs: shortcode }); return html; }, image: function( props, attachment ) { var img = {}, options, classes, shortcode, html; props = wp.media.string.props( props, attachment ); classes = props.classes || []; img.src = typeof attachment !== 'undefined' ? attachment.url : props.url; _.extend( img, _.pick( props, 'width', 'height', 'alt' ) ); // Only assign the align class to the image if we're not printing // a caption, since the alignment is sent to the shortcode. if ( props.align && ! props.caption ) classes.push( 'align' + props.align ); if ( props.size ) classes.push( 'size-' + props.size ); img['class'] = _.compact( classes ).join(' '); // Generate `img` tag options. options = { tag: 'img', attrs: img, single: true }; // Generate the `a` element options, if they exist. if ( props.linkUrl ) { options = { tag: 'a', attrs: { href: props.linkUrl }, content: options }; } html = wp.html.string( options ); // Generate the caption shortcode. if ( props.caption ) { shortcode = {}; if ( img.width ) shortcode.width = img.width; if ( props.captionId ) shortcode.id = props.captionId; if ( props.align ) shortcode.align = 'align' + props.align; html = wp.shortcode.string({ tag: 'caption', attrs: shortcode, content: html + ' ' + props.caption }); } return html; } }; wp.media.gallery = (function() { var galleries = {}; return { defaults: { order: 'ASC', id: wp.media.view.settings.post.id, itemtag: 'dl', icontag: 'dt', captiontag: 'dd', columns: '3', link: 'post', size: 'thumbnail', orderby: 'menu_order ID' }, attachments: function( shortcode ) { var shortcodeString = shortcode.string(), result = galleries[ shortcodeString ], attrs, args, query, others; delete galleries[ shortcodeString ]; if ( result ) return result; // Fill the default shortcode attributes. attrs = _.defaults( shortcode.attrs.named, wp.media.gallery.defaults ); args = _.pick( attrs, 'orderby', 'order' ); args.type = 'image'; args.perPage = -1; // Mark the `orderby` override attribute. if ( 'rand' === attrs.orderby ) attrs._orderbyRandom = true; // Map the `orderby` attribute to the corresponding model property. if ( ! attrs.orderby || /^menu_order(?: ID)?$/i.test( attrs.orderby ) ) args.orderby = 'menuOrder'; // Map the `ids` param to the correct query args. if ( attrs.ids ) { args.post__in = attrs.ids.split(','); args.orderby = 'post__in'; } else if ( attrs.include ) { args.post__in = attrs.include.split(','); } if ( attrs.exclude ) args.post__not_in = attrs.exclude.split(','); if ( ! args.post__in ) args.uploadedTo = attrs.id; // Collect the attributes that were not included in `args`. others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' ); query = wp.media.query( args ); query.gallery = new Backbone.Model( others ); return query; }, shortcode: function( attachments ) { var props = attachments.props.toJSON(), attrs = _.pick( props, 'orderby', 'order' ), shortcode, clone; if ( attachments.gallery ) _.extend( attrs, attachments.gallery.toJSON() ); // Convert all gallery shortcodes to use the `ids` property. // Ignore `post__in` and `post__not_in`; the attachments in // the collection will already reflect those properties. attrs.ids = attachments.pluck('id'); // Copy the `uploadedTo` post ID. if ( props.uploadedTo ) attrs.id = props.uploadedTo; // Check if the gallery is randomly ordered. if ( attrs._orderbyRandom ) attrs.orderby = 'rand'; delete attrs._orderbyRandom; // If the `ids` attribute is set and `orderby` attribute // is the default value, clear it for cleaner output. if ( attrs.ids && 'post__in' === attrs.orderby ) delete attrs.orderby; // Remove default attributes from the shortcode. _.each( wp.media.gallery.defaults, function( value, key ) { if ( value === attrs[ key ] ) delete attrs[ key ]; }); shortcode = new wp.shortcode({ tag: 'gallery', attrs: attrs, type: 'single' }); // Use a cloned version of the gallery. clone = new wp.media.model.Attachments( attachments.models, { props: props }); clone.gallery = attachments.gallery; galleries[ shortcode.string() ] = clone; return shortcode; }, edit: function( content ) { var shortcode = wp.shortcode.next( 'gallery', content ), defaultPostId = wp.media.gallery.defaults.id, attachments, selection; // Bail if we didn't match the shortcode or all of the content. if ( ! shortcode || shortcode.content !== content ) return; // Ignore the rest of the match object. shortcode = shortcode.shortcode; if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) ) shortcode.set( 'id', defaultPostId ); attachments = wp.media.gallery.attachments( shortcode ); selection = new wp.media.model.Selection( attachments.models, { props: attachments.props.toJSON(), multiple: true }); selection.gallery = attachments.gallery; // Fetch the query's attachments, and then break ties from the // query to allow for sorting. selection.more().done( function() { // Break ties with the query. selection.props.set({ query: false }); selection.unmirror(); selection.props.unset('orderby'); }); // Destroy the previous gallery frame. if ( this.frame ) this.frame.dispose(); // Store the current gallery frame. this.frame = wp.media({ frame: 'post', state: 'gallery-edit', title: wp.media.view.l10n.editGalleryTitle, editing: true, multiple: true, selection: selection }).open(); return this.frame; } }; }()); wp.media.featuredImage = { get: function() { return wp.media.view.settings.post.featuredImageId; }, set: function( id ) { var settings = wp.media.view.settings; settings.post.featuredImageId = id; wp.media.post( 'set-post-thumbnail', { json: true, post_id: settings.post.id, thumbnail_id: settings.post.featuredImageId, _wpnonce: settings.post.nonce }).done( function( html ) { $( '.inside', '#postimagediv' ).html( html ); }); }, frame: function() { if ( this._frame ) return this._frame; this._frame = wp.media({ state: 'featured-image', states: [ new wp.media.controller.FeaturedImage() ] }); this._frame.on( 'toolbar:create:featured-image', function( toolbar ) { this.createSelectToolbar( toolbar, { text: wp.media.view.l10n.setFeaturedImage }); }, this._frame ); this._frame.state('featured-image').on( 'select', this.select ); return this._frame; }, select: function() { var settings = wp.media.view.settings, selection = this.get('selection').single(); if ( ! settings.post.featuredImageId ) return; wp.media.featuredImage.set( selection ? selection.id : -1 ); }, init: function() { // Open the content media manager to the 'featured image' tab when // the post thumbnail is clicked. $('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) { event.preventDefault(); // Stop propagation to prevent thickbox from activating. event.stopPropagation(); wp.media.featuredImage.frame().open(); // Update the featured image id when the 'remove' link is clicked. }).on( 'click', '#remove-post-thumbnail', function() { wp.media.view.settings.post.featuredImageId = -1; }); } }; $( wp.media.featuredImage.init ); wp.media.editor = { insert: function( h ) { var mce = typeof(tinymce) != 'undefined', qt = typeof(QTags) != 'undefined', wpActiveEditor = window.wpActiveEditor, ed; // Delegate to the global `send_to_editor` if it exists. // This attempts to play nice with any themes/plugins that have // overridden the insert functionality. if ( window.send_to_editor ) return window.send_to_editor.apply( this, arguments ); if ( ! wpActiveEditor ) { if ( mce && tinymce.activeEditor ) { ed = tinymce.activeEditor; wpActiveEditor = window.wpActiveEditor = ed.id; } else if ( !qt ) { return false; } } else if ( mce ) { if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') ) ed = tinymce.activeEditor; else ed = tinymce.get(wpActiveEditor); } if ( ed && !ed.isHidden() ) { // restore caret position on IE if ( tinymce.isIE && ed.windowManager.insertimagebookmark ) ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark); if ( h.indexOf('[caption') !== -1 ) { if ( ed.wpSetImgCaption ) h = ed.wpSetImgCaption(h); } else if ( h.indexOf('[gallery') !== -1 ) { if ( ed.plugins.wpgallery ) h = ed.plugins.wpgallery._do_gallery(h); } else if ( h.indexOf('[embed') === 0 ) { if ( ed.plugins.wordpress ) h = ed.plugins.wordpress._setEmbed(h); } ed.execCommand('mceInsertContent', false, h); } else if ( qt ) { QTags.insertContent(h); } else { document.getElementById(wpActiveEditor).value += h; } // If the old thickbox remove function exists, call it in case // a theme/plugin overloaded it. if ( window.tb_remove ) try { window.tb_remove(); } catch( e ) {} }, add: function( id, options ) { var workflow = this.get( id ); if ( workflow ) // only add once: if exists return existing return workflow; workflow = workflows[ id ] = wp.media( _.defaults( options || {}, { frame: 'post', state: 'insert', title: wp.media.view.l10n.addMedia, multiple: true } ) ); workflow.on( 'insert', function( selection ) { var state = workflow.state(); selection = selection || state.get('selection'); if ( ! selection ) return; $.when.apply( $, selection.map( function( attachment ) { var display = state.display( attachment ).toJSON(); return this.send.attachment( display, attachment.toJSON() ); }, this ) ).done( function() { wp.media.editor.insert( _.toArray( arguments ).join("\n\n") ); }); }, this ); workflow.state('gallery-edit').on( 'update', function( selection ) { this.insert( wp.media.gallery.shortcode( selection ).string() ); }, this ); workflow.state('embed').on( 'select', function() { var state = workflow.state(), type = state.get('type'), embed = state.props.toJSON(); embed.url = embed.url || ''; if ( 'link' === type ) { _.defaults( embed, { title: embed.url, linkUrl: embed.url }); this.send.link( embed ).done( function( resp ) { wp.media.editor.insert( resp ); }); } else if ( 'image' === type ) { _.defaults( embed, { title: embed.url, linkUrl: '', align: 'none', link: 'none' }); if ( 'none' === embed.link ) embed.linkUrl = ''; else if ( 'file' === embed.link ) embed.linkUrl = embed.url; this.insert( wp.media.string.image( embed ) ); } }, this ); workflow.state('featured-image').on( 'select', wp.media.featuredImage.select ); workflow.setState( workflow.options.state ); return workflow; }, id: function( id ) { if ( id ) return id; // If an empty `id` is provided, default to `wpActiveEditor`. id = wpActiveEditor; // If that doesn't work, fall back to `tinymce.activeEditor.id`. if ( ! id && typeof tinymce !== 'undefined' && tinymce.activeEditor ) id = tinymce.activeEditor.id; // Last but not least, fall back to the empty string. id = id || ''; return id; }, get: function( id ) { id = this.id( id ); return workflows[ id ]; }, remove: function( id ) { id = this.id( id ); delete workflows[ id ]; }, send: { attachment: function( props, attachment ) { var caption = attachment.caption, options, html; // If captions are disabled, clear the caption. if ( ! wp.media.view.settings.captions ) delete attachment.caption; props = wp.media.string.props( props, attachment ); options = { id: attachment.id, post_content: attachment.description, post_excerpt: caption }; if ( props.linkUrl ) options.url = props.linkUrl; if ( 'image' === attachment.type ) { html = wp.media.string.image( props ); _.each({ align: 'align', size: 'image-size', alt: 'image_alt' }, function( option, prop ) { if ( props[ prop ] ) options[ option ] = props[ prop ]; }); } else if ( 'video' === attachment.type ) { html = wp.media.string.video( props, attachment ); } else if ( 'audio' === attachment.type ) { html = wp.media.string.audio( props, attachment ); } else { html = wp.media.string.link( props ); options.post_title = props.title; } return wp.media.post( 'send-attachment-to-editor', { nonce: wp.media.view.settings.nonce.sendToEditor, attachment: options, html: html, post_id: wp.media.view.settings.post.id }); }, link: function( embed ) { return wp.media.post( 'send-link-to-editor', { nonce: wp.media.view.settings.nonce.sendToEditor, src: embed.linkUrl, title: embed.title, html: wp.media.string.link( embed ), post_id: wp.media.view.settings.post.id }); } }, open: function( id, options ) { var workflow, editor; options = options || {}; id = this.id( id ); // Save a bookmark of the caret position in IE. if ( typeof tinymce !== 'undefined' ) { editor = tinymce.get( id ); if ( tinymce.isIE && editor && ! editor.isHidden() ) { editor.focus(); editor.windowManager.insertimagebookmark = editor.selection.getBookmark(); } } workflow = this.get( id ); // Redo workflow if state has changed if ( ! workflow || ( workflow.options && options.state !== workflow.options.state ) ) workflow = this.add( id, options ); return workflow.open(); }, init: function() { $(document.body).on( 'click', '.insert-media', function( event ) { var $this = $(this), editor = $this.data('editor'), options = { frame: 'post', state: 'insert', title: wp.media.view.l10n.addMedia, multiple: true }; event.preventDefault(); // Remove focus from the `.insert-media` button. // Prevents Opera from showing the outline of the button // above the modal. // // See: http://core.trac.wordpress.org/ticket/22445 $this.blur(); if ( $this.hasClass( 'gallery' ) ) { options.state = 'gallery'; options.title = wp.media.view.l10n.createGalleryTitle; } wp.media.editor.open( editor, options ); }); } }; _.bindAll( wp.media.editor, 'open' ); $( wp.media.editor.init ); }(jQuery));
JavaScript
addComment = { moveForm : function(commId, parentId, respondId, postId) { var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID'); if ( ! comm || ! respond || ! cancel || ! parent ) return; t.respondId = respondId; postId = postId || false; if ( ! t.I('wp-temp-form-div') ) { div = document.createElement('div'); div.id = 'wp-temp-form-div'; div.style.display = 'none'; respond.parentNode.insertBefore(div, respond); } comm.parentNode.insertBefore(respond, comm.nextSibling); if ( post && postId ) post.value = postId; parent.value = parentId; cancel.style.display = ''; cancel.onclick = function() { var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId); if ( ! temp || ! respond ) return; t.I('comment_parent').value = '0'; temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp); this.style.display = 'none'; this.onclick = null; return false; } try { t.I('comment').focus(); } catch(e) {} return false; }, I : function(e) { return document.getElementById(e); } }
JavaScript
/* http://www.JSON.org/json2.js 2011-02-23 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false, regexp: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON; if (!JSON) { JSON = {}; } (function () { "use strict"; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());
JavaScript
// =================================================================== // Author: Matt Kruse <matt@mattkruse.com> // WWW: http://www.mattkruse.com/ // // NOTICE: You may use this code for any purpose, commercial or // private, without any further permission from the author. You may // remove this notice from your final code if you wish, however it is // appreciated by the author if at least my web site address is kept. // // You may *NOT* re-distribute this code in any way except through its // use. That means, you can include it in your product, or your web // site, or any other form where the code is actually being used. You // may not put the plain javascript up on your site for download or // include it in your javascript libraries for download. // If you wish to share this code with others, please just point them // to the URL instead. // Please DO NOT link directly to my .js files from your site. Copy // the files to your server and use them there. Thank you. // =================================================================== /* SOURCE FILE: AnchorPosition.js */ /* AnchorPosition.js Author: Matt Kruse Last modified: 10/11/02 DESCRIPTION: These functions find the position of an <A> tag in a document, so other elements can be positioned relative to it. COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small positioning errors - usually with Window positioning - occur on the Macintosh platform. FUNCTIONS: getAnchorPosition(anchorname) Returns an Object() having .x and .y properties of the pixel coordinates of the upper-left corner of the anchor. Position is relative to the PAGE. getAnchorWindowPosition(anchorname) Returns an Object() having .x and .y properties of the pixel coordinates of the upper-left corner of the anchor, relative to the WHOLE SCREEN. NOTES: 1) For popping up separate browser windows, use getAnchorWindowPosition. Otherwise, use getAnchorPosition 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. */ // getAnchorPosition(anchorname) // This function returns an object having .x and .y properties which are the coordinates // of the named anchor, relative to the page. function getAnchorPosition(anchorname) { // This function will return an Object with x and y properties var useWindow=false; var coordinates=new Object(); var x=0,y=0; // Browser capability sniffing var use_gebi=false, use_css=false, use_layers=false; if (document.getElementById) { use_gebi=true; } else if (document.all) { use_css=true; } else if (document.layers) { use_layers=true; } // Logic to find position if (use_gebi && document.all) { x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); } else if (use_gebi) { var o=document.getElementById(anchorname); x=AnchorPosition_getPageOffsetLeft(o); y=AnchorPosition_getPageOffsetTop(o); } else if (use_css) { x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); } else if (use_layers) { var found=0; for (var i=0; i<document.anchors.length; i++) { if (document.anchors[i].name==anchorname) { found=1; break; } } if (found==0) { coordinates.x=0; coordinates.y=0; return coordinates; } x=document.anchors[i].x; y=document.anchors[i].y; } else { coordinates.x=0; coordinates.y=0; return coordinates; } coordinates.x=x; coordinates.y=y; return coordinates; } // getAnchorWindowPosition(anchorname) // This function returns an object having .x and .y properties which are the coordinates // of the named anchor, relative to the window function getAnchorWindowPosition(anchorname) { var coordinates=getAnchorPosition(anchorname); var x=0; var y=0; if (document.getElementById) { if (isNaN(window.screenX)) { x=coordinates.x-document.body.scrollLeft+window.screenLeft; y=coordinates.y-document.body.scrollTop+window.screenTop; } else { x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset; y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset; } } else if (document.all) { x=coordinates.x-document.body.scrollLeft+window.screenLeft; y=coordinates.y-document.body.scrollTop+window.screenTop; } else if (document.layers) { x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset; y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset; } coordinates.x=x; coordinates.y=y; return coordinates; } // Functions for IE to get position of an object function AnchorPosition_getPageOffsetLeft (el) { var ol=el.offsetLeft; while ((el=el.offsetParent) != null) { ol += el.offsetLeft; } return ol; } function AnchorPosition_getWindowOffsetLeft (el) { return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft; } function AnchorPosition_getPageOffsetTop (el) { var ot=el.offsetTop; while((el=el.offsetParent) != null) { ot += el.offsetTop; } return ot; } function AnchorPosition_getWindowOffsetTop (el) { return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop; } /* SOURCE FILE: PopupWindow.js */ /* PopupWindow.js Author: Matt Kruse Last modified: 02/16/04 DESCRIPTION: This object allows you to easily and quickly popup a window in a certain place. The window can either be a DIV or a separate browser window. COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small positioning errors - usually with Window positioning - occur on the Macintosh platform. Due to bugs in Netscape 4.x, populating the popup window with <STYLE> tags may cause errors. USAGE: // Create an object for a WINDOW popup var win = new PopupWindow(); // Create an object for a DIV window using the DIV named 'mydiv' var win = new PopupWindow('mydiv'); // Set the window to automatically hide itself when the user clicks // anywhere else on the page except the popup win.autoHide(); // Show the window relative to the anchor name passed in win.showPopup(anchorname); // Hide the popup win.hidePopup(); // Set the size of the popup window (only applies to WINDOW popups win.setSize(width,height); // Populate the contents of the popup window that will be shown. If you // change the contents while it is displayed, you will need to refresh() win.populate(string); // set the URL of the window, rather than populating its contents // manually win.setUrl("http://www.site.com/"); // Refresh the contents of the popup win.refresh(); // Specify how many pixels to the right of the anchor the popup will appear win.offsetX = 50; // Specify how many pixels below the anchor the popup will appear win.offsetY = 100; NOTES: 1) Requires the functions in AnchorPosition.js 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. 4) When a PopupWindow object is created, a handler for 'onmouseup' is attached to any event handler you may have already defined. Do NOT define an event handler for 'onmouseup' after you define a PopupWindow object or the autoHide() will not work correctly. */ // Set the position of the popup window based on the anchor function PopupWindow_getXYPosition(anchorname) { var coordinates; if (this.type == "WINDOW") { coordinates = getAnchorWindowPosition(anchorname); } else { coordinates = getAnchorPosition(anchorname); } this.x = coordinates.x; this.y = coordinates.y; } // Set width/height of DIV/popup window function PopupWindow_setSize(width,height) { this.width = width; this.height = height; } // Fill the window with contents function PopupWindow_populate(contents) { this.contents = contents; this.populated = false; } // Set the URL to go to function PopupWindow_setUrl(url) { this.url = url; } // Set the window popup properties function PopupWindow_setWindowProperties(props) { this.windowProperties = props; } // Refresh the displayed contents of the popup function PopupWindow_refresh() { if (this.divName != null) { // refresh the DIV object if (this.use_gebi) { document.getElementById(this.divName).innerHTML = this.contents; } else if (this.use_css) { document.all[this.divName].innerHTML = this.contents; } else if (this.use_layers) { var d = document.layers[this.divName]; d.document.open(); d.document.writeln(this.contents); d.document.close(); } } else { if (this.popupWindow != null && !this.popupWindow.closed) { if (this.url!="") { this.popupWindow.location.href=this.url; } else { this.popupWindow.document.open(); this.popupWindow.document.writeln(this.contents); this.popupWindow.document.close(); } this.popupWindow.focus(); } } } // Position and show the popup, relative to an anchor object function PopupWindow_showPopup(anchorname) { this.getXYPosition(anchorname); this.x += this.offsetX; this.y += this.offsetY; if (!this.populated && (this.contents != "")) { this.populated = true; this.refresh(); } if (this.divName != null) { // Show the DIV object if (this.use_gebi) { document.getElementById(this.divName).style.left = this.x + "px"; document.getElementById(this.divName).style.top = this.y; document.getElementById(this.divName).style.visibility = "visible"; } else if (this.use_css) { document.all[this.divName].style.left = this.x; document.all[this.divName].style.top = this.y; document.all[this.divName].style.visibility = "visible"; } else if (this.use_layers) { document.layers[this.divName].left = this.x; document.layers[this.divName].top = this.y; document.layers[this.divName].visibility = "visible"; } } else { if (this.popupWindow == null || this.popupWindow.closed) { // If the popup window will go off-screen, move it so it doesn't if (this.x<0) { this.x=0; } if (this.y<0) { this.y=0; } if (screen && screen.availHeight) { if ((this.y + this.height) > screen.availHeight) { this.y = screen.availHeight - this.height; } } if (screen && screen.availWidth) { if ((this.x + this.width) > screen.availWidth) { this.x = screen.availWidth - this.width; } } var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ); this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+""); } this.refresh(); } } // Hide the popup function PopupWindow_hidePopup() { if (this.divName != null) { if (this.use_gebi) { document.getElementById(this.divName).style.visibility = "hidden"; } else if (this.use_css) { document.all[this.divName].style.visibility = "hidden"; } else if (this.use_layers) { document.layers[this.divName].visibility = "hidden"; } } else { if (this.popupWindow && !this.popupWindow.closed) { this.popupWindow.close(); this.popupWindow = null; } } } // Pass an event and return whether or not it was the popup DIV that was clicked function PopupWindow_isClicked(e) { if (this.divName != null) { if (this.use_layers) { var clickX = e.pageX; var clickY = e.pageY; var t = document.layers[this.divName]; if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) { return true; } else { return false; } } else if (document.all) { // Need to hard-code this to trap IE for error-handling var t = window.event.srcElement; while (t.parentElement != null) { if (t.id==this.divName) { return true; } t = t.parentElement; } return false; } else if (this.use_gebi && e) { var t = e.originalTarget; while (t.parentNode != null) { if (t.id==this.divName) { return true; } t = t.parentNode; } return false; } return false; } return false; } // Check an onMouseDown event to see if we should hide function PopupWindow_hideIfNotClicked(e) { if (this.autoHideEnabled && !this.isClicked(e)) { this.hidePopup(); } } // Call this to make the DIV disable automatically when mouse is clicked outside it function PopupWindow_autoHide() { this.autoHideEnabled = true; } // This global function checks all PopupWindow objects onmouseup to see if they should be hidden function PopupWindow_hidePopupWindows(e) { for (var i=0; i<popupWindowObjects.length; i++) { if (popupWindowObjects[i] != null) { var p = popupWindowObjects[i]; p.hideIfNotClicked(e); } } } // Run this immediately to attach the event listener function PopupWindow_attachListener() { if (document.layers) { document.captureEvents(Event.MOUSEUP); } window.popupWindowOldEventListener = document.onmouseup; if (window.popupWindowOldEventListener != null) { document.onmouseup = new Function("window.popupWindowOldEventListener(); PopupWindow_hidePopupWindows();"); } else { document.onmouseup = PopupWindow_hidePopupWindows; } } // CONSTRUCTOR for the PopupWindow object // Pass it a DIV name to use a DHTML popup, otherwise will default to window popup function PopupWindow() { if (!window.popupWindowIndex) { window.popupWindowIndex = 0; } if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); } if (!window.listenerAttached) { window.listenerAttached = true; PopupWindow_attachListener(); } this.index = popupWindowIndex++; popupWindowObjects[this.index] = this; this.divName = null; this.popupWindow = null; this.width=0; this.height=0; this.populated = false; this.visible = false; this.autoHideEnabled = false; this.contents = ""; this.url=""; this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no"; if (arguments.length>0) { this.type="DIV"; this.divName = arguments[0]; } else { this.type="WINDOW"; } this.use_gebi = false; this.use_css = false; this.use_layers = false; if (document.getElementById) { this.use_gebi = true; } else if (document.all) { this.use_css = true; } else if (document.layers) { this.use_layers = true; } else { this.type = "WINDOW"; } this.offsetX = 0; this.offsetY = 0; // Method mappings this.getXYPosition = PopupWindow_getXYPosition; this.populate = PopupWindow_populate; this.setUrl = PopupWindow_setUrl; this.setWindowProperties = PopupWindow_setWindowProperties; this.refresh = PopupWindow_refresh; this.showPopup = PopupWindow_showPopup; this.hidePopup = PopupWindow_hidePopup; this.setSize = PopupWindow_setSize; this.isClicked = PopupWindow_isClicked; this.autoHide = PopupWindow_autoHide; this.hideIfNotClicked = PopupWindow_hideIfNotClicked; } /* SOURCE FILE: ColorPicker2.js */ /* Last modified: 02/24/2003 DESCRIPTION: This widget is used to select a color, in hexadecimal #RRGGBB form. It uses a color "swatch" to display the standard 216-color web-safe palette. The user can then click on a color to select it. COMPATABILITY: See notes in AnchorPosition.js and PopupWindow.js. Only the latest DHTML-capable browsers will show the color and hex values at the bottom as your mouse goes over them. USAGE: // Create a new ColorPicker object using DHTML popup var cp = new ColorPicker(); // Create a new ColorPicker object using Window Popup var cp = new ColorPicker('window'); // Add a link in your page to trigger the popup. For example: <A HREF="#" onClick="cp.show('pick');return false;" NAME="pick" ID="pick">Pick</A> // Or use the built-in "select" function to do the dirty work for you: <A HREF="#" onClick="cp.select(document.forms[0].color,'pick');return false;" NAME="pick" ID="pick">Pick</A> // If using DHTML popup, write out the required DIV tag near the bottom // of your page. <SCRIPT LANGUAGE="JavaScript">cp.writeDiv()</SCRIPT> // Write the 'pickColor' function that will be called when the user clicks // a color and do something with the value. This is only required if you // want to do something other than simply populate a form field, which is // what the 'select' function will give you. function pickColor(color) { field.value = color; } NOTES: 1) Requires the functions in AnchorPosition.js and PopupWindow.js 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. 4) When a ColorPicker object is created, a handler for 'onmouseup' is attached to any event handler you may have already defined. Do NOT define an event handler for 'onmouseup' after you define a ColorPicker object or the color picker will not hide itself correctly. */ ColorPicker_targetInput = null; function ColorPicker_writeDiv() { document.writeln("<DIV ID=\"colorPickerDiv\" STYLE=\"position:absolute;visibility:hidden;\"> </DIV>"); } function ColorPicker_show(anchorname) { this.showPopup(anchorname); } function ColorPicker_pickColor(color,obj) { obj.hidePopup(); pickColor(color); } // A Default "pickColor" function to accept the color passed back from popup. // User can over-ride this with their own function. function pickColor(color) { if (ColorPicker_targetInput==null) { alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!"); return; } ColorPicker_targetInput.value = color; } // This function is the easiest way to popup the window, select a color, and // have the value populate a form field, which is what most people want to do. function ColorPicker_select(inputobj,linkname) { if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") { alert("colorpicker.select: Input object passed is not a valid form input object"); window.ColorPicker_targetInput=null; return; } window.ColorPicker_targetInput = inputobj; this.show(linkname); } // This function runs when you move your mouse over a color block, if you have a newer browser function ColorPicker_highlightColor(c) { var thedoc = (arguments.length>1)?arguments[1]:window.document; var d = thedoc.getElementById("colorPickerSelectedColor"); d.style.backgroundColor = c; d = thedoc.getElementById("colorPickerSelectedColorValue"); d.innerHTML = c; } function ColorPicker() { var windowMode = false; // Create a new PopupWindow object if (arguments.length==0) { var divname = "colorPickerDiv"; } else if (arguments[0] == "window") { var divname = ''; windowMode = true; } else { var divname = arguments[0]; } if (divname != "") { var cp = new PopupWindow(divname); } else { var cp = new PopupWindow(); cp.setSize(225,250); } // Object variables cp.currentValue = "#FFFFFF"; // Method Mappings cp.writeDiv = ColorPicker_writeDiv; cp.highlightColor = ColorPicker_highlightColor; cp.show = ColorPicker_show; cp.select = ColorPicker_select; // Code to populate color picker window var colors = new Array( "#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099", "#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099", "#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099", "#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF", "#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F", "#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000", "#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399", "#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399", "#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399", "#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF", "#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F", "#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00", "#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699", "#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699", "#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699", "#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F", "#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F", "#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F", "#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999", "#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999", "#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999", "#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF", "#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F", "#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000", "#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99", "#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99", "#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99", "#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF", "#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F", "#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00", "#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99", "#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99", "#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99", "#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F", "#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F", "#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F", "#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666", "#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000", "#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000", "#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999", "#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF", "#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66", "#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00", "#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000", "#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099", "#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF", "#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF", "#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC", "#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000", "#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900", "#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33", "#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF", "#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF", "#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F", "#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F", "#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F", "#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000"); var total = colors.length; var width = 72; var cp_contents = ""; var windowRef = (windowMode)?"window.opener.":""; if (windowMode) { cp_contents += "<html><head><title>Select Color</title></head>"; cp_contents += "<body marginwidth=0 marginheight=0 leftmargin=0 topmargin=0><span style='text-align: center;'>"; } cp_contents += "<table style='border: none;' cellspacing=0 cellpadding=0>"; var use_highlight = (document.getElementById || document.all)?true:false; for (var i=0; i<total; i++) { if ((i % width) == 0) { cp_contents += "<tr>"; } if (use_highlight) { var mo = 'onMouseOver="'+windowRef+'ColorPicker_highlightColor(\''+colors[i]+'\',window.document)"'; } else { mo = ""; } cp_contents += '<td style="background-color: '+colors[i]+';"><a href="javascript:void()" onclick="'+windowRef+'ColorPicker_pickColor(\''+colors[i]+'\','+windowRef+'window.popupWindowObjects['+cp.index+']);return false;" '+mo+'>&nbsp;</a></td>'; if ( ((i+1)>=total) || (((i+1) % width) == 0)) { cp_contents += "</tr>"; } } // If the browser supports dynamically changing TD cells, add the fancy stuff if (document.getElementById) { var width1 = Math.floor(width/2); var width2 = width = width1; cp_contents += "<tr><td colspan='"+width1+"' style='background-color: #FFF;' ID='colorPickerSelectedColor'>&nbsp;</td><td colspan='"+width2+"' style='text-align: center;' id='colorPickerSelectedColorValue'>#FFFFFF</td></tr>"; } cp_contents += "</table>"; if (windowMode) { cp_contents += "</span></body></html>"; } // end populate code // Write the contents to the popup object cp.populate(cp_contents+"\n"); // Move the table down a bit so you can see it cp.offsetY = 25; cp.autoHide(); return cp; }
JavaScript
window.wp = window.wp || {}; (function( exports, $ ){ var api = wp.customize, Loader; $.extend( $.support, { history: !! ( window.history && history.pushState ), hashchange: ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7) }); Loader = $.extend( {}, api.Events, { initialize: function() { this.body = $( document.body ); // Ensure the loader is supported. // Check for settings, postMessage support, and whether we require CORS support. if ( ! Loader.settings || ! $.support.postMessage || ( ! $.support.cors && Loader.settings.isCrossDomain ) ) { return; } this.window = $( window ); this.element = $( '<div id="customize-container" />' ).appendTo( this.body ); this.bind( 'open', this.overlay.show ); this.bind( 'close', this.overlay.hide ); $('#wpbody').on( 'click', '.load-customize', function( event ) { event.preventDefault(); // Store a reference to the link that opened the customizer. Loader.link = $(this); // Load the theme. Loader.open( Loader.link.attr('href') ); }); // Add navigation listeners. if ( $.support.history ) this.window.on( 'popstate', Loader.popstate ); if ( $.support.hashchange ) { this.window.on( 'hashchange', Loader.hashchange ); this.window.triggerHandler( 'hashchange' ); } }, popstate: function( e ) { var state = e.originalEvent.state; if ( state && state.customize ) Loader.open( state.customize ); else if ( Loader.active ) Loader.close(); }, hashchange: function( e ) { var hash = window.location.toString().split('#')[1]; if ( hash && 0 === hash.indexOf( 'wp_customize=on' ) ) Loader.open( Loader.settings.url + '?' + hash ); if ( ! hash && ! $.support.history ) Loader.close(); }, open: function( src ) { var hash; if ( this.active ) return; // Load the full page on mobile devices. if ( Loader.settings.browser.mobile ) return window.location = src; this.active = true; this.body.addClass('customize-loading'); this.iframe = $( '<iframe />', { src: src }).appendTo( this.element ); this.iframe.one( 'load', this.loaded ); // Create a postMessage connection with the iframe. this.messenger = new api.Messenger({ url: src, channel: 'loader', targetWindow: this.iframe[0].contentWindow }); // Wait for the connection from the iframe before sending any postMessage events. this.messenger.bind( 'ready', function() { Loader.messenger.send( 'back' ); }); this.messenger.bind( 'close', function() { if ( $.support.history ) history.back(); else if ( $.support.hashchange ) window.location.hash = ''; else Loader.close(); }); this.messenger.bind( 'activated', function( location ) { if ( location ) window.location = location; }); hash = src.split('?')[1]; // Ensure we don't call pushState if the user hit the forward button. if ( $.support.history && window.location.href !== src ) history.pushState( { customize: src }, '', src ); else if ( ! $.support.history && $.support.hashchange && hash ) window.location.hash = 'wp_customize=on&' + hash; this.trigger( 'open' ); }, opened: function() { Loader.body.addClass( 'customize-active full-overlay-active' ); }, close: function() { if ( ! this.active ) return; this.active = false; this.trigger( 'close' ); // Return focus to link that was originally clicked. if ( this.link ) this.link.focus(); }, closed: function() { Loader.iframe.remove(); Loader.messenger.destroy(); Loader.iframe = null; Loader.messenger = null; Loader.body.removeClass( 'customize-active full-overlay-active' ).removeClass( 'customize-loading' ); }, loaded: function() { Loader.body.removeClass('customize-loading'); }, overlay: { show: function() { this.element.fadeIn( 200, Loader.opened ); }, hide: function() { this.element.fadeOut( 200, Loader.closed ); } } }); $( function() { Loader.settings = _wpCustomizeLoaderSettings; Loader.initialize(); }); // Expose the API to the world. api.Loader = Loader; })( wp, jQuery );
JavaScript
window.wp = window.wp || {}; (function ($) { // Create the WordPress Backbone namespace. wp.Backbone = {}; // wp.Backbone.Subviews // -------------------- // // A subview manager. wp.Backbone.Subviews = function( view, views ) { this.view = view; this._views = _.isArray( views ) ? { '': views } : views || {}; }; wp.Backbone.Subviews.extend = Backbone.Model.extend; _.extend( wp.Backbone.Subviews.prototype, { // ### Fetch all of the subviews // // Returns an array of all subviews. all: function() { return _.flatten( this._views ); }, // ### Get a selector's subviews // // Fetches all subviews that match a given `selector`. // // If no `selector` is provided, it will grab all subviews attached // to the view's root. get: function( selector ) { selector = selector || ''; return this._views[ selector ]; }, // ### Get a selector's first subview // // Fetches the first subview that matches a given `selector`. // // If no `selector` is provided, it will grab the first subview // attached to the view's root. // // Useful when a selector only has one subview at a time. first: function( selector ) { var views = this.get( selector ); return views && views.length ? views[0] : null; }, // ### Register subview(s) // // Registers any number of `views` to a `selector`. // // When no `selector` is provided, the root selector (the empty string) // is used. `views` accepts a `Backbone.View` instance or an array of // `Backbone.View` instances. // // --- // // Accepts an `options` object, which has a significant effect on the // resulting behavior. // // `options.silent` &ndash; *boolean, `false`* // > If `options.silent` is true, no DOM modifications will be made. // // `options.add` &ndash; *boolean, `false`* // > Use `Views.add()` as a shortcut for setting `options.add` to true. // // > By default, the provided `views` will replace // any existing views associated with the selector. If `options.add` // is true, the provided `views` will be added to the existing views. // // `options.at` &ndash; *integer, `undefined`* // > When adding, to insert `views` at a specific index, use // `options.at`. By default, `views` are added to the end of the array. set: function( selector, views, options ) { var existing, next; if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } options = options || {}; views = _.isArray( views ) ? views : [ views ]; existing = this.get( selector ); next = views; if ( existing ) { if ( options.add ) { if ( _.isUndefined( options.at ) ) { next = existing.concat( views ); } else { next = existing; next.splice.apply( next, [ options.at, 0 ].concat( views ) ); } } else { _.each( next, function( view ) { view.__detach = true; }); _.each( existing, function( view ) { if ( view.__detach ) view.$el.detach(); else view.remove(); }); _.each( next, function( view ) { delete view.__detach; }); } } this._views[ selector ] = next; _.each( views, function( subview ) { var constructor = subview.Views || wp.Backbone.Subviews, subviews = subview.views = subview.views || new constructor( subview ); subviews.parent = this.view; subviews.selector = selector; }, this ); if ( ! options.silent ) this._attach( selector, views, _.extend({ ready: this._isReady() }, options ) ); return this; }, // ### Add subview(s) to existing subviews // // An alias to `Views.set()`, which defaults `options.add` to true. // // Adds any number of `views` to a `selector`. // // When no `selector` is provided, the root selector (the empty string) // is used. `views` accepts a `Backbone.View` instance or an array of // `Backbone.View` instances. // // Use `Views.set()` when setting `options.add` to `false`. // // Accepts an `options` object. By default, provided `views` will be // inserted at the end of the array of existing views. To insert // `views` at a specific index, use `options.at`. If `options.silent` // is true, no DOM modifications will be made. // // For more information on the `options` object, see `Views.set()`. add: function( selector, views, options ) { if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } return this.set( selector, views, _.extend({ add: true }, options ) ); }, // ### Stop tracking subviews // // Stops tracking `views` registered to a `selector`. If no `views` are // set, then all of the `selector`'s subviews will be unregistered and // removed. // // Accepts an `options` object. If `options.silent` is set, `remove` // will *not* be triggered on the unregistered views. unset: function( selector, views, options ) { var existing; if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } views = views || []; if ( existing = this.get( selector ) ) { views = _.isArray( views ) ? views : [ views ]; this._views[ selector ] = views.length ? _.difference( existing, views ) : []; } if ( ! options || ! options.silent ) _.invoke( views, 'remove' ); return this; }, // ### Detach all subviews // // Detaches all subviews from the DOM. // // Helps to preserve all subview events when re-rendering the master // view. Used in conjunction with `Views.render()`. detach: function() { $( _.pluck( this.all(), 'el' ) ).detach(); return this; }, // ### Render all subviews // // Renders all subviews. Used in conjunction with `Views.detach()`. render: function() { var options = { ready: this._isReady() }; _.each( this._views, function( views, selector ) { this._attach( selector, views, options ); }, this ); this.rendered = true; return this; }, // ### Remove all subviews // // Triggers the `remove()` method on all subviews. Detaches the master // view from its parent. Resets the internals of the views manager. // // Accepts an `options` object. If `options.silent` is set, `unset` // will *not* be triggered on the master view's parent. remove: function( options ) { if ( ! options || ! options.silent ) { if ( this.parent && this.parent.views ) this.parent.views.unset( this.selector, this.view, { silent: true }); delete this.parent; delete this.selector; } _.invoke( this.all(), 'remove' ); this._views = []; return this; }, // ### Replace a selector's subviews // // By default, sets the `$target` selector's html to the subview `els`. // // Can be overridden in subclasses. replace: function( $target, els ) { $target.html( els ); return this; }, // ### Insert subviews into a selector // // By default, appends the subview `els` to the end of the `$target` // selector. If `options.at` is set, inserts the subview `els` at the // provided index. // // Can be overridden in subclasses. insert: function( $target, els, options ) { var at = options && options.at, $children; if ( _.isNumber( at ) && ($children = $target.children()).length > at ) $children.eq( at ).before( els ); else $target.append( els ); return this; }, // ### Trigger the ready event // // **Only use this method if you know what you're doing.** // For performance reasons, this method does not check if the view is // actually attached to the DOM. It's taking your word for it. // // Fires the ready event on the current view and all attached subviews. ready: function() { this.view.trigger('ready'); // Find all attached subviews, and call ready on them. _.chain( this.all() ).map( function( view ) { return view.views; }).flatten().where({ attached: true }).invoke('ready'); }, // #### Internal. Attaches a series of views to a selector. // // Checks to see if a matching selector exists, renders the views, // performs the proper DOM operation, and then checks if the view is // attached to the document. _attach: function( selector, views, options ) { var $selector = selector ? this.view.$( selector ) : this.view.$el, managers; // Check if we found a location to attach the views. if ( ! $selector.length ) return this; managers = _.chain( views ).pluck('views').flatten().value(); // Render the views if necessary. _.each( managers, function( manager ) { if ( manager.rendered ) return; manager.view.render(); manager.rendered = true; }, this ); // Insert or replace the views. this[ options.add ? 'insert' : 'replace' ]( $selector, _.pluck( views, 'el' ), options ); // Set attached and trigger ready if the current view is already // attached to the DOM. _.each( managers, function( manager ) { manager.attached = true; if ( options.ready ) manager.ready(); }, this ); return this; }, // #### Internal. Checks if the current view is in the DOM. _isReady: function() { var node = this.view.el; while ( node ) { if ( node === document.body ) return true; node = node.parentNode; } return false; } }); // wp.Backbone.View // ---------------- // // The base view class. wp.Backbone.View = Backbone.View.extend({ // The constructor for the `Views` manager. Subviews: wp.Backbone.Subviews, constructor: function() { this.views = new this.Subviews( this, this.views ); this.on( 'ready', this.ready, this ); Backbone.View.apply( this, arguments ); }, remove: function() { var result = Backbone.View.prototype.remove.apply( this, arguments ); // Recursively remove child views. if ( this.views ) this.views.remove(); return result; }, render: function() { var options; if ( this.prepare ) options = this.prepare(); this.views.detach(); if ( this.template ) { options = options || {}; this.trigger( 'prepare', options ); this.$el.html( this.template( options ) ); } this.views.render(); return this; }, prepare: function() { return this.options; }, ready: function() {} }); }(jQuery));
JavaScript
/** * Pointer jQuery widget. */ (function($){ var identifier = 0, zindex = 9999; $.widget("wp.pointer", { options: { pointerClass: 'wp-pointer', pointerWidth: 320, content: function( respond, event, t ) { return $(this).text(); }, buttons: function( event, t ) { var close = ( wpPointerL10n ) ? wpPointerL10n.dismiss : 'Dismiss', button = $('<a class="close" href="#">' + close + '</a>'); return button.bind( 'click.pointer', function(e) { e.preventDefault(); t.element.pointer('close'); }); }, position: 'top', show: function( event, t ) { t.pointer.show(); t.opened(); }, hide: function( event, t ) { t.pointer.hide(); t.closed(); }, document: document }, _create: function() { var positioning, family; this.content = $('<div class="wp-pointer-content"></div>'); this.arrow = $('<div class="wp-pointer-arrow"><div class="wp-pointer-arrow-inner"></div></div>'); family = this.element.parents().add( this.element ); positioning = 'absolute'; if ( family.filter(function(){ return 'fixed' === $(this).css('position'); }).length ) positioning = 'fixed'; this.pointer = $('<div />') .append( this.content ) .append( this.arrow ) .attr('id', 'wp-pointer-' + identifier++) .addClass( this.options.pointerClass ) .css({'position': positioning, 'width': this.options.pointerWidth+'px', 'display': 'none'}) .appendTo( this.options.document.body ); }, _setOption: function( key, value ) { var o = this.options, tip = this.pointer; // Handle document transfer if ( key === "document" && value !== o.document ) { tip.detach().appendTo( value.body ); // Handle class change } else if ( key === "pointerClass" ) { tip.removeClass( o.pointerClass ).addClass( value ); } // Call super method. $.Widget.prototype._setOption.apply( this, arguments ); // Reposition automatically if ( key === "position" ) { this.reposition(); // Update content automatically if pointer is open } else if ( key === "content" && this.active ) { this.update(); } }, destroy: function() { this.pointer.remove(); $.Widget.prototype.destroy.call( this ); }, widget: function() { return this.pointer; }, update: function( event ) { var self = this, o = this.options, dfd = $.Deferred(), content; if ( o.disabled ) return; dfd.done( function( content ) { self._update( event, content ); }) // Either o.content is a string... if ( typeof o.content === 'string' ) { content = o.content; // ...or o.content is a callback. } else { content = o.content.call( this.element[0], dfd.resolve, event, this._handoff() ); } // If content is set, then complete the update. if ( content ) dfd.resolve( content ); return dfd.promise(); }, /** * Update is separated into two functions to allow events to defer * updating the pointer (e.g. fetch content with ajax, etc). */ _update: function( event, content ) { var buttons, o = this.options; if ( ! content ) return; this.pointer.stop(); // Kill any animations on the pointer. this.content.html( content ); buttons = o.buttons.call( this.element[0], event, this._handoff() ); if ( buttons ) { buttons.wrap('<div class="wp-pointer-buttons" />').parent().appendTo( this.content ); } this.reposition(); }, reposition: function() { var position; if ( this.options.disabled ) return; position = this._processPosition( this.options.position ); // Reposition pointer. this.pointer.css({ top: 0, left: 0, zIndex: zindex++ // Increment the z-index so that it shows above other opened pointers. }).show().position($.extend({ of: this.element, collision: 'fit none' }, position )); // the object comes before this.options.position so the user can override position.of. this.repoint(); }, repoint: function() { var o = this.options, edge; if ( o.disabled ) return; edge = ( typeof o.position == 'string' ) ? o.position : o.position.edge; // Remove arrow classes. this.pointer[0].className = this.pointer[0].className.replace( /wp-pointer-[^\s'"]*/, '' ); // Add arrow class. this.pointer.addClass( 'wp-pointer-' + edge ); }, _processPosition: function( position ) { var opposite = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }, result; // If the position object is a string, it is shorthand for position.edge. if ( typeof position == 'string' ) { result = { edge: position + '' }; } else { result = $.extend( {}, position ); } if ( ! result.edge ) return result; if ( result.edge == 'top' || result.edge == 'bottom' ) { result.align = result.align || 'left'; result.at = result.at || result.align + ' ' + opposite[ result.edge ]; result.my = result.my || result.align + ' ' + result.edge; } else { result.align = result.align || 'top'; result.at = result.at || opposite[ result.edge ] + ' ' + result.align; result.my = result.my || result.edge + ' ' + result.align; } return result; }, open: function( event ) { var self = this, o = this.options; if ( this.active || o.disabled || this.element.is(':hidden') ) return; this.update().done( function() { self._open( event ); }); }, _open: function( event ) { var self = this, o = this.options; if ( this.active || o.disabled || this.element.is(':hidden') ) return; this.active = true; this._trigger( "open", event, this._handoff() ); this._trigger( "show", event, this._handoff({ opened: function() { self._trigger( "opened", event, self._handoff() ); } })); }, close: function( event ) { if ( !this.active || this.options.disabled ) return; var self = this; this.active = false; this._trigger( "close", event, this._handoff() ); this._trigger( "hide", event, this._handoff({ closed: function() { self._trigger( "closed", event, self._handoff() ); } })); }, sendToTop: function( event ) { if ( this.active ) this.pointer.css( 'z-index', zindex++ ); }, toggle: function( event ) { if ( this.pointer.is(':hidden') ) this.open( event ); else this.close( event ); }, _handoff: function( extend ) { return $.extend({ pointer: this.pointer, element: this.element }, extend); } }); })(jQuery);
JavaScript
var wpLink; (function($){ var inputs = {}, rivers = {}, ed, River, Query; wpLink = { timeToTriggerRiver: 150, minRiverAJAXDuration: 200, riverBottomThreshold: 5, keySensitivity: 100, lastSearch: '', textarea: '', init : function() { inputs.dialog = $('#wp-link'); inputs.submit = $('#wp-link-submit'); // URL inputs.url = $('#url-field'); inputs.nonce = $('#_ajax_linking_nonce'); // Secondary options inputs.title = $('#link-title-field'); // Advanced Options inputs.openInNewTab = $('#link-target-checkbox'); inputs.search = $('#search-field'); // Build Rivers rivers.search = new River( $('#search-results') ); rivers.recent = new River( $('#most-recent-results') ); rivers.elements = $('.query-results', inputs.dialog); // Bind event handlers inputs.dialog.keydown( wpLink.keydown ); inputs.dialog.keyup( wpLink.keyup ); inputs.submit.click( function(e){ e.preventDefault(); wpLink.update(); }); $('#wp-link-cancel').click( function(e){ e.preventDefault(); wpLink.close(); }); $('#internal-toggle').click( wpLink.toggleInternalLinking ); rivers.elements.bind('river-select', wpLink.updateFields ); inputs.search.keyup( wpLink.searchInternalLinks ); inputs.dialog.bind('wpdialogrefresh', wpLink.refresh); inputs.dialog.bind('wpdialogbeforeopen', wpLink.beforeOpen); inputs.dialog.bind('wpdialogclose', wpLink.onClose); }, beforeOpen : function() { wpLink.range = null; if ( ! wpLink.isMCE() && document.selection ) { wpLink.textarea.focus(); wpLink.range = document.selection.createRange(); } }, open : function() { if ( !wpActiveEditor ) return; this.textarea = $('#'+wpActiveEditor).get(0); // Initialize the dialog if necessary (html mode). if ( ! inputs.dialog.data('wpdialog') ) { inputs.dialog.wpdialog({ title: wpLinkL10n.title, width: 480, height: 'auto', modal: true, dialogClass: 'wp-dialog' }); } inputs.dialog.wpdialog('open'); }, isMCE : function() { return tinyMCEPopup && ( ed = tinyMCEPopup.editor ) && ! ed.isHidden(); }, refresh : function() { // Refresh rivers (clear links, check visibility) rivers.search.refresh(); rivers.recent.refresh(); if ( wpLink.isMCE() ) wpLink.mceRefresh(); else wpLink.setDefaultValues(); // Focus the URL field and highlight its contents. // If this is moved above the selection changes, // IE will show a flashing cursor over the dialog. inputs.url.focus()[0].select(); // Load the most recent results if this is the first time opening the panel. if ( ! rivers.recent.ul.children().length ) rivers.recent.ajax(); }, mceRefresh : function() { var e; ed = tinyMCEPopup.editor; tinyMCEPopup.restoreSelection(); // If link exists, select proper values. if ( e = ed.dom.getParent(ed.selection.getNode(), 'A') ) { // Set URL and description. inputs.url.val( ed.dom.getAttrib(e, 'href') ); inputs.title.val( ed.dom.getAttrib(e, 'title') ); // Set open in new tab. inputs.openInNewTab.prop('checked', ( "_blank" == ed.dom.getAttrib( e, 'target' ) ) ); // Update save prompt. inputs.submit.val( wpLinkL10n.update ); // If there's no link, set the default values. } else { wpLink.setDefaultValues(); } tinyMCEPopup.storeSelection(); }, close : function() { if ( wpLink.isMCE() ) tinyMCEPopup.close(); else inputs.dialog.wpdialog('close'); }, onClose: function() { if ( ! wpLink.isMCE() ) { wpLink.textarea.focus(); if ( wpLink.range ) { wpLink.range.moveToBookmark( wpLink.range.getBookmark() ); wpLink.range.select(); } } }, getAttrs : function() { return { href : inputs.url.val(), title : inputs.title.val(), target : inputs.openInNewTab.prop('checked') ? '_blank' : '' }; }, update : function() { if ( wpLink.isMCE() ) wpLink.mceUpdate(); else wpLink.htmlUpdate(); }, htmlUpdate : function() { var attrs, html, begin, end, cursor, textarea = wpLink.textarea; if ( ! textarea ) return; attrs = wpLink.getAttrs(); // If there's no href, return. if ( ! attrs.href || attrs.href == 'http://' ) return; // Build HTML html = '<a href="' + attrs.href + '"'; if ( attrs.title ) html += ' title="' + attrs.title + '"'; if ( attrs.target ) html += ' target="' + attrs.target + '"'; html += '>'; // Insert HTML if ( document.selection && wpLink.range ) { // IE // Note: If no text is selected, IE will not place the cursor // inside the closing tag. textarea.focus(); wpLink.range.text = html + wpLink.range.text + '</a>'; wpLink.range.moveToBookmark( wpLink.range.getBookmark() ); wpLink.range.select(); wpLink.range = null; } else if ( typeof textarea.selectionStart !== 'undefined' ) { // W3C begin = textarea.selectionStart; end = textarea.selectionEnd; selection = textarea.value.substring( begin, end ); html = html + selection + '</a>'; cursor = begin + html.length; // If no next is selected, place the cursor inside the closing tag. if ( begin == end ) cursor -= '</a>'.length; textarea.value = textarea.value.substring( 0, begin ) + html + textarea.value.substring( end, textarea.value.length ); // Update cursor position textarea.selectionStart = textarea.selectionEnd = cursor; } wpLink.close(); textarea.focus(); }, mceUpdate : function() { var ed = tinyMCEPopup.editor, attrs = wpLink.getAttrs(), e, b; tinyMCEPopup.restoreSelection(); e = ed.dom.getParent(ed.selection.getNode(), 'A'); // If the values are empty, unlink and return if ( ! attrs.href || attrs.href == 'http://' ) { if ( e ) { tinyMCEPopup.execCommand("mceBeginUndoLevel"); b = ed.selection.getBookmark(); ed.dom.remove(e, 1); ed.selection.moveToBookmark(b); tinyMCEPopup.execCommand("mceEndUndoLevel"); wpLink.close(); } return; } tinyMCEPopup.execCommand("mceBeginUndoLevel"); if (e == null) { ed.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); tinymce.each(ed.dom.select("a"), function(n) { if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { e = n; ed.dom.setAttribs(e, attrs); } }); // Sometimes WebKit lets a user create a link where // they shouldn't be able to. In this case, CreateLink // injects "#mce_temp_url#" into their content. Fix it. if ( $(e).text() == '#mce_temp_url#' ) { ed.dom.remove(e); e = null; } } else { ed.dom.setAttribs(e, attrs); } // Don't move caret if selection was image if ( e && (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') ) { ed.focus(); ed.selection.select(e); ed.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); wpLink.close(); }, updateFields : function( e, li, originalEvent ) { inputs.url.val( li.children('.item-permalink').val() ); inputs.title.val( li.hasClass('no-title') ? '' : li.children('.item-title').text() ); if ( originalEvent && originalEvent.type == "click" ) inputs.url.focus(); }, setDefaultValues : function() { // Set URL and description to defaults. // Leave the new tab setting as-is. inputs.url.val('http://'); inputs.title.val(''); // Update save prompt. inputs.submit.val( wpLinkL10n.save ); }, searchInternalLinks : function() { var t = $(this), waiting, search = t.val(); if ( search.length > 2 ) { rivers.recent.hide(); rivers.search.show(); // Don't search if the keypress didn't change the title. if ( wpLink.lastSearch == search ) return; wpLink.lastSearch = search; waiting = t.parent().find('.spinner').show(); rivers.search.change( search ); rivers.search.ajax( function(){ waiting.hide(); }); } else { rivers.search.hide(); rivers.recent.show(); } }, next : function() { rivers.search.next(); rivers.recent.next(); }, prev : function() { rivers.search.prev(); rivers.recent.prev(); }, keydown : function( event ) { var fn, key = $.ui.keyCode; switch( event.which ) { case key.UP: fn = 'prev'; case key.DOWN: fn = fn || 'next'; clearInterval( wpLink.keyInterval ); wpLink[ fn ](); wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity ); break; default: return; } event.preventDefault(); }, keyup: function( event ) { var key = $.ui.keyCode; switch( event.which ) { case key.ESCAPE: event.stopImmediatePropagation(); if ( ! $(document).triggerHandler( 'wp_CloseOnEscape', [{ event: event, what: 'wplink', cb: wpLink.close }] ) ) wpLink.close(); return false; break; case key.UP: case key.DOWN: clearInterval( wpLink.keyInterval ); break; default: return; } event.preventDefault(); }, delayedCallback : function( func, delay ) { var timeoutTriggered, funcTriggered, funcArgs, funcContext; if ( ! delay ) return func; setTimeout( function() { if ( funcTriggered ) return func.apply( funcContext, funcArgs ); // Otherwise, wait. timeoutTriggered = true; }, delay); return function() { if ( timeoutTriggered ) return func.apply( this, arguments ); // Otherwise, wait. funcArgs = arguments; funcContext = this; funcTriggered = true; }; }, toggleInternalLinking : function( event ) { var panel = $('#search-panel'), widget = inputs.dialog.wpdialog('widget'), // We're about to toggle visibility; it's currently the opposite visible = !panel.is(':visible'), win = $(window); $(this).toggleClass('toggle-arrow-active', visible); inputs.dialog.height('auto'); panel.slideToggle( 300, function() { setUserSetting('wplink', visible ? '1' : '0'); inputs[ visible ? 'search' : 'url' ].focus(); // Move the box if the box is now expanded, was opened in a collapsed state, // and if it needs to be moved. (Judged by bottom not being positive or // bottom being smaller than top.) var scroll = win.scrollTop(), top = widget.offset().top, bottom = top + widget.outerHeight(), diff = bottom - win.height(); if ( diff > scroll ) { widget.animate({'top': diff < top ? top - diff : scroll }, 200); } }); event.preventDefault(); } } River = function( element, search ) { var self = this; this.element = element; this.ul = element.children('ul'); this.waiting = element.find('.river-waiting'); this.change( search ); this.refresh(); element.scroll( function(){ self.maybeLoad(); }); element.delegate('li', 'click', function(e){ self.select( $(this), e ); }); }; $.extend( River.prototype, { refresh: function() { this.deselect(); this.visible = this.element.is(':visible'); }, show: function() { if ( ! this.visible ) { this.deselect(); this.element.show(); this.visible = true; } }, hide: function() { this.element.hide(); this.visible = false; }, // Selects a list item and triggers the river-select event. select: function( li, event ) { var liHeight, elHeight, liTop, elTop; if ( li.hasClass('unselectable') || li == this.selected ) return; this.deselect(); this.selected = li.addClass('selected'); // Make sure the element is visible liHeight = li.outerHeight(); elHeight = this.element.height(); liTop = li.position().top; elTop = this.element.scrollTop(); if ( liTop < 0 ) // Make first visible element this.element.scrollTop( elTop + liTop ); else if ( liTop + liHeight > elHeight ) // Make last visible element this.element.scrollTop( elTop + liTop - elHeight + liHeight ); // Trigger the river-select event this.element.trigger('river-select', [ li, event, this ]); }, deselect: function() { if ( this.selected ) this.selected.removeClass('selected'); this.selected = false; }, prev: function() { if ( ! this.visible ) return; var to; if ( this.selected ) { to = this.selected.prev('li'); if ( to.length ) this.select( to ); } }, next: function() { if ( ! this.visible ) return; var to = this.selected ? this.selected.next('li') : $('li:not(.unselectable):first', this.element); if ( to.length ) this.select( to ); }, ajax: function( callback ) { var self = this, delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration, response = wpLink.delayedCallback( function( results, params ) { self.process( results, params ); if ( callback ) callback( results, params ); }, delay ); this.query.ajax( response ); }, change: function( search ) { if ( this.query && this._search == search ) return; this._search = search; this.query = new Query( search ); this.element.scrollTop(0); }, process: function( results, params ) { var list = '', alt = true, classes = '', firstPage = params.page == 1; if ( !results ) { if ( firstPage ) { list += '<li class="unselectable"><span class="item-title"><em>' + wpLinkL10n.noMatchesFound + '</em></span></li>'; } } else { $.each( results, function() { classes = alt ? 'alternate' : ''; classes += this['title'] ? '' : ' no-title'; list += classes ? '<li class="' + classes + '">' : '<li>'; list += '<input type="hidden" class="item-permalink" value="' + this['permalink'] + '" />'; list += '<span class="item-title">'; list += this['title'] ? this['title'] : wpLinkL10n.noTitle; list += '</span><span class="item-info">' + this['info'] + '</span></li>'; alt = ! alt; }); } this.ul[ firstPage ? 'html' : 'append' ]( list ); }, maybeLoad: function() { var self = this, el = this.element, bottom = el.scrollTop() + el.height(); if ( ! this.query.ready() || bottom < this.ul.height() - wpLink.riverBottomThreshold ) return; setTimeout(function() { var newTop = el.scrollTop(), newBottom = newTop + el.height(); if ( ! self.query.ready() || newBottom < self.ul.height() - wpLink.riverBottomThreshold ) return; self.waiting.show(); el.scrollTop( newTop + self.waiting.outerHeight() ); self.ajax( function() { self.waiting.hide(); }); }, wpLink.timeToTriggerRiver ); } }); Query = function( search ) { this.page = 1; this.allLoaded = false; this.querying = false; this.search = search; }; $.extend( Query.prototype, { ready: function() { return !( this.querying || this.allLoaded ); }, ajax: function( callback ) { var self = this, query = { action : 'wp-link-ajax', page : this.page, '_ajax_linking_nonce' : inputs.nonce.val() }; if ( this.search ) query.search = this.search; this.querying = true; $.post( ajaxurl, query, function(r) { self.page++; self.querying = false; self.allLoaded = !r; callback( r, query ); }, "json" ); } }); $(document).ready( wpLink.init ); })(jQuery);
JavaScript
var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init; function fileDialogStart() { jQuery("#media-upload-error").empty(); } // progress and success handlers for media multi uploads function fileQueued(fileObj) { // Get rid of unused form jQuery('.media-blank').remove(); var items = jQuery('#media-items').children(), postid = post_id || 0; // Collapse a single item if ( items.length == 1 ) { items.removeClass('open').find('.slidetoggle').slideUp(200); } // Create a progress bar containing the filename jQuery('<div class="media-item">') .attr( 'id', 'media-item-' + fileObj.id ) .addClass('child-of-' + postid) .append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>', jQuery('<div class="filename original">').text( ' ' + fileObj.name )) .appendTo( jQuery('#media-items' ) ); // Disable submit jQuery('#insert-gallery').prop('disabled', true); } function uploadStart() { try { if ( typeof topWin.tb_remove != 'undefined' ) topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove); } catch(e){} return true; } function uploadProgress(up, file) { var item = jQuery('#media-item-' + file.id); jQuery('.bar', item).width( (200 * file.loaded) / file.size ); jQuery('.percent', item).html( file.percent + '%' ); } // check to see if a large file failed to upload function fileUploading(up, file) { var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10); if ( max > hundredmb && file.size > hundredmb ) { setTimeout(function(){ var done; if ( file.status < 3 && file.loaded == 0 ) { // not uploading wpFileError(file, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>')); up.stop(); // stops the whole queue up.removeFile(file); up.start(); // restart the queue } }, 10000); // wait for 10 sec. for the file to start uploading } } function updateMediaForm() { var items = jQuery('#media-items').children(); // Just one file, no need for collapsible part if ( items.length == 1 ) { items.addClass('open').find('.slidetoggle').show(); jQuery('.insert-gallery').hide(); } else if ( items.length > 1 ) { items.removeClass('open'); // Only show Gallery button when there are at least two files. jQuery('.insert-gallery').show(); } // Only show Save buttons when there is at least one file. if ( items.not('.media-blank').length > 0 ) jQuery('.savebutton').show(); else jQuery('.savebutton').hide(); } function uploadSuccess(fileObj, serverData) { var item = jQuery('#media-item-' + fileObj.id); // on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1'); // if async-upload returned an error message, place it in the media item div and return if ( serverData.match(/media-upload-error|error-div/) ) { item.html(serverData); return; } else { jQuery('.percent', item).html( pluploadL10n.crunching ); } prepareMediaItem(fileObj, serverData); updateMediaForm(); // Increment the counter. if ( post_id && item.hasClass('child-of-' + post_id) ) jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1); } function setResize(arg) { if ( arg ) { if ( uploader.features.jpgresize ) uploader.settings['resize'] = { width: resize_width, height: resize_height, quality: 100 }; else uploader.settings.multipart_params.image_resize = true; } else { delete(uploader.settings.resize); delete(uploader.settings.multipart_params.image_resize); } } function prepareMediaItem(fileObj, serverData) { var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id); if ( f == 2 && shortform > 2 ) f = shortform; try { if ( typeof topWin.tb_remove != 'undefined' ) topWin.jQuery('#TB_overlay').click(topWin.tb_remove); } catch(e){} if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs item.append(serverData); prepareMediaItemInit(fileObj); } else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()}); } } function prepareMediaItemInit(fileObj) { var item = jQuery('#media-item-' + fileObj.id); // Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item); // Replace the original filename with the new (unique) one assigned during upload jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) ); // Bind AJAX to the new Delete button jQuery('a.delete', item).click(function(){ // Tell the server to delete it. TODO: handle exceptions jQuery.ajax({ url: ajaxurl, type: 'post', success: deleteSuccess, error: deleteError, id: fileObj.id, data: { id : this.id.replace(/[^0-9]/g, ''), action : 'trash-post', _ajax_nonce : this.href.replace(/^.*wpnonce=/,'') } }); return false; }); // Bind AJAX to the new Undo button jQuery('a.undo', item).click(function(){ // Tell the server to untrash it. TODO: handle exceptions jQuery.ajax({ url: ajaxurl, type: 'post', id: fileObj.id, data: { id : this.id.replace(/[^0-9]/g,''), action: 'untrash-post', _ajax_nonce: this.href.replace(/^.*wpnonce=/,'') }, success: function(data, textStatus){ var item = jQuery('#media-item-' + fileObj.id); if ( type = jQuery('#type-of-' + fileObj.id).val() ) jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1); if ( post_id && item.hasClass('child-of-'+post_id) ) jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1); jQuery('.filename .trashnotice', item).remove(); jQuery('.filename .title', item).css('font-weight','normal'); jQuery('a.undo', item).addClass('hidden'); jQuery('.menu_order_input', item).show(); item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo'); } }); return false; }); // Open this item if it says to start open (e.g. to display an error) jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').addClass('open').find('slidetoggle').fadeIn(); } // generic error message function wpQueueError(message) { jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' ); } // file-specific error messages function wpFileError(fileObj, message) { itemAjaxError(fileObj.id, message); } function itemAjaxError(id, message) { var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err'); if ( last_err == id ) // prevent firing an error for the same file twice return; item.html('<div class="error-div">' + '<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>' + '<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> ' + message + '</div>').data('last-err', id); } function deleteSuccess(data, textStatus) { if ( data == '-1' ) return itemAjaxError(this.id, 'You do not have permission. Has your session expired?'); if ( data == '0' ) return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?'); var id = this.id, item = jQuery('#media-item-' + id); // Decrement the counters. if ( type = jQuery('#type-of-' + id).val() ) jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 ); if ( post_id && item.hasClass('child-of-'+post_id) ) jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 ); if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) { jQuery('.toggle').toggle(); jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden'); } // Vanish it. jQuery('.toggle', item).toggle(); jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden'); item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo'); jQuery('.filename:empty', item).remove(); jQuery('.filename .title', item).css('font-weight','bold'); jQuery('.filename', item).append('<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>').siblings('a.toggle').hide(); jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') ); jQuery('.menu_order_input', item).hide(); return; } function deleteError(X, textStatus, errorThrown) { // TODO } function uploadComplete() { jQuery('#insert-gallery').prop('disabled', false); } function switchUploader(s) { if ( s ) { deleteUserSetting('uploader'); jQuery('.media-upload-form').removeClass('html-uploader'); if ( typeof(uploader) == 'object' ) uploader.refresh(); } else { setUserSetting('uploader', '1'); // 1 == html uploader jQuery('.media-upload-form').addClass('html-uploader'); } } function dndHelper(s) { var d = document.getElementById('dnd-helper'); if ( s ) { d.style.display = 'block'; } else { d.style.display = 'none'; } } function uploadError(fileObj, errorCode, message, uploader) { var hundredmb = 100 * 1024 * 1024, max; switch (errorCode) { case plupload.FAILED: wpFileError(fileObj, pluploadL10n.upload_failed); break; case plupload.FILE_EXTENSION_ERROR: wpFileError(fileObj, pluploadL10n.invalid_filetype); break; case plupload.FILE_SIZE_ERROR: uploadSizeError(uploader, fileObj); break; case plupload.IMAGE_FORMAT_ERROR: wpFileError(fileObj, pluploadL10n.not_an_image); break; case plupload.IMAGE_MEMORY_ERROR: wpFileError(fileObj, pluploadL10n.image_memory_exceeded); break; case plupload.IMAGE_DIMENSIONS_ERROR: wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded); break; case plupload.GENERIC_ERROR: wpQueueError(pluploadL10n.upload_failed); break; case plupload.IO_ERROR: max = parseInt(uploader.settings.max_file_size, 10); if ( max > hundredmb && fileObj.size > hundredmb ) wpFileError(fileObj, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>')); else wpQueueError(pluploadL10n.io_error); break; case plupload.HTTP_ERROR: wpQueueError(pluploadL10n.http_error); break; case plupload.INIT_ERROR: jQuery('.media-upload-form').addClass('html-uploader'); break; case plupload.SECURITY_ERROR: wpQueueError(pluploadL10n.security_error); break; /* case plupload.UPLOAD_ERROR.UPLOAD_STOPPED: case plupload.UPLOAD_ERROR.FILE_CANCELLED: jQuery('#media-item-' + fileObj.id).remove(); break;*/ default: wpFileError(fileObj, pluploadL10n.default_error); } } function uploadSizeError( up, file, over100mb ) { var message; if ( over100mb ) message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'); else message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name); jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>'); up.removeFile(file); } jQuery(document).ready(function($){ $('.media-upload-form').bind('click.uploader', function(e) { var target = $(e.target), tr, c; if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment tr = target.closest('tr'); if ( tr.hasClass('align') ) setUserSetting('align', target.val()); else if ( tr.hasClass('image-size') ) setUserSetting('imgsize', target.val()); } else if ( target.is('button.button') ) { // remember the last used image link url c = e.target.className || ''; c = c.match(/url([^ '"]+)/); if ( c && c[1] ) { setUserSetting('urlbutton', c[1]); target.siblings('.urlfield').val( target.data('link-url') ); } } else if ( target.is('a.dismiss') ) { target.parents('.media-item').fadeOut(200, function(){ $(this).remove(); }); } else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4 $('#media-items, p.submit, span.big-file-warning').css('display', 'none'); switchUploader(0); e.preventDefault(); } else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file $('#media-items, p.submit, span.big-file-warning').css('display', ''); switchUploader(1); e.preventDefault(); } else if ( target.is('a.describe-toggle-on') ) { // Show target.parent().addClass('open'); target.siblings('.slidetoggle').fadeIn(250, function(){ var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B; if ( H && top && h ) { b = top + h; B = S + H; if ( b > B ) { if ( b - B < top - S ) window.scrollBy(0, (b - B) + 10); else window.scrollBy(0, top - S - 40); } } }); e.preventDefault(); } else if ( target.is('a.describe-toggle-off') ) { // Hide target.siblings('.slidetoggle').fadeOut(250, function(){ target.parent().removeClass('open'); }); e.preventDefault(); } }); // init and set the uploader uploader_init = function() { uploader = new plupload.Uploader(wpUploaderInit); $('#image_resize').bind('change', function() { var arg = $(this).prop('checked'); setResize( arg ); if ( arg ) setUserSetting('upload_resize', '1'); else deleteUserSetting('upload_resize'); }); uploader.bind('Init', function(up) { var uploaddiv = $('#plupload-upload-ui'); setResize( getUserSetting('upload_resize', false) ); if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) { uploaddiv.addClass('drag-drop'); $('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :( uploaddiv.addClass('drag-over'); }).bind('dragleave.wp-uploader, drop.wp-uploader', function(){ uploaddiv.removeClass('drag-over'); }); } else { uploaddiv.removeClass('drag-drop'); $('#drag-drop-area').unbind('.wp-uploader'); } if ( up.runtime == 'html4' ) $('.upload-flash-bypass').hide(); }); uploader.init(); uploader.bind('FilesAdded', function(up, files) { var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10); $('#media-upload-error').html(''); uploadStart(); plupload.each(files, function(file){ if ( max > hundredmb && file.size > hundredmb && up.runtime != 'html5' ) uploadSizeError( up, file, true ); else fileQueued(file); }); up.refresh(); up.start(); }); uploader.bind('BeforeUpload', function(up, file) { // something }); uploader.bind('UploadFile', function(up, file) { fileUploading(up, file); }); uploader.bind('UploadProgress', function(up, file) { uploadProgress(up, file); }); uploader.bind('Error', function(up, err) { uploadError(err.file, err.code, err.message, up); up.refresh(); }); uploader.bind('FileUploaded', function(up, file, response) { uploadSuccess(file, response.response); }); uploader.bind('UploadComplete', function(up, files) { uploadComplete(); }); } if ( typeof(wpUploaderInit) == 'object' ) uploader_init(); });
JavaScript
window.wp = window.wp || {}; (function( exports, $ ) { var Uploader; if ( typeof _wpPluploadSettings === 'undefined' ) return; /* * An object that helps create a WordPress uploader using plupload. * * @param options - object - The options passed to the new plupload instance. * Accepts the following parameters: * - container - The id of uploader container. * - browser - The id of button to trigger the file select. * - dropzone - The id of file drop target. * - plupload - An object of parameters to pass to the plupload instance. * - params - An object of parameters to pass to $_POST when uploading the file. * Extends this.plupload.multipart_params under the hood. * * @param attributes - object - Attributes and methods for this specific instance. */ Uploader = function( options ) { var self = this, elements = { container: 'container', browser: 'browse_button', dropzone: 'drop_element' }, key, error; this.supports = { upload: Uploader.browser.supported }; this.supported = this.supports.upload; if ( ! this.supported ) return; // Use deep extend to ensure that multipart_params and other objects are cloned. this.plupload = $.extend( true, { multipart_params: {} }, Uploader.defaults ); this.container = document.body; // Set default container. // Extend the instance with options // // Use deep extend to allow options.plupload to override individual // default plupload keys. $.extend( true, this, options ); // Proxy all methods so this always refers to the current instance. for ( key in this ) { if ( $.isFunction( this[ key ] ) ) this[ key ] = $.proxy( this[ key ], this ); } // Ensure all elements are jQuery elements and have id attributes // Then set the proper plupload arguments to the ids. for ( key in elements ) { if ( ! this[ key ] ) continue; this[ key ] = $( this[ key ] ).first(); if ( ! this[ key ].length ) { delete this[ key ]; continue; } if ( ! this[ key ].prop('id') ) this[ key ].prop( 'id', '__wp-uploader-id-' + Uploader.uuid++ ); this.plupload[ elements[ key ] ] = this[ key ].prop('id'); } // If the uploader has neither a browse button nor a dropzone, bail. if ( ! ( this.browser && this.browser.length ) && ! ( this.dropzone && this.dropzone.length ) ) return; this.uploader = new plupload.Uploader( this.plupload ); delete this.plupload; // Set default params and remove this.params alias. this.param( this.params || {} ); delete this.params; error = function( message, data, file ) { if ( file.attachment ) file.attachment.destroy(); Uploader.errors.unshift({ message: message || pluploadL10n.default_error, data: data, file: file }); self.error( message, data, file ); }; this.uploader.init(); this.supports.dragdrop = this.uploader.features.dragdrop && ! Uploader.browser.mobile; // Generate drag/drop helper classes. (function( dropzone, supported ) { var timer, active; if ( ! dropzone ) return; dropzone.toggleClass( 'supports-drag-drop', !! supported ); if ( ! supported ) return dropzone.unbind('.wp-uploader'); // 'dragenter' doesn't fire correctly, // simulate it with a limited 'dragover' dropzone.bind( 'dragover.wp-uploader', function(){ if ( timer ) clearTimeout( timer ); if ( active ) return; dropzone.trigger('dropzone:enter').addClass('drag-over'); active = true; }); dropzone.bind('dragleave.wp-uploader, drop.wp-uploader', function(){ // Using an instant timer prevents the drag-over class from // being quickly removed and re-added when elements inside the // dropzone are repositioned. // // See http://core.trac.wordpress.org/ticket/21705 timer = setTimeout( function() { active = false; dropzone.trigger('dropzone:leave').removeClass('drag-over'); }, 0 ); }); }( this.dropzone, this.supports.dragdrop )); if ( this.browser ) { this.browser.on( 'mouseenter', this.refresh ); } else { this.uploader.disableBrowse( true ); // If HTML5 mode, hide the auto-created file container. $('#' + this.uploader.id + '_html5_container').hide(); } this.uploader.bind( 'FilesAdded', function( up, files ) { _.each( files, function( file ) { var attributes, image; // Ignore failed uploads. if ( plupload.FAILED === file.status ) return; // Generate attributes for a new `Attachment` model. attributes = _.extend({ file: file, uploading: true, date: new Date(), filename: file.name, menuOrder: 0, uploadedTo: wp.media.model.settings.post.id }, _.pick( file, 'loaded', 'size', 'percent' ) ); // Handle early mime type scanning for images. image = /(?:jpe?g|png|gif)$/i.exec( file.name ); // Did we find an image? if ( image ) { attributes.type = 'image'; // `jpeg`, `png` and `gif` are valid subtypes. // `jpg` is not, so map it to `jpeg`. attributes.subtype = ( 'jpg' === image[0] ) ? 'jpeg' : image[0]; } // Create the `Attachment`. file.attachment = wp.media.model.Attachment.create( attributes ); Uploader.queue.add( file.attachment ); self.added( file.attachment ); }); up.refresh(); up.start(); }); this.uploader.bind( 'UploadProgress', function( up, file ) { file.attachment.set( _.pick( file, 'loaded', 'percent' ) ); self.progress( file.attachment ); }); this.uploader.bind( 'FileUploaded', function( up, file, response ) { var complete; try { response = JSON.parse( response.response ); } catch ( e ) { return error( pluploadL10n.default_error, e, file ); } if ( ! _.isObject( response ) || _.isUndefined( response.success ) ) return error( pluploadL10n.default_error, null, file ); else if ( ! response.success ) return error( response.data && response.data.message, response.data, file ); _.each(['file','loaded','size','percent'], function( key ) { file.attachment.unset( key ); }); file.attachment.set( _.extend( response.data, { uploading: false }) ); wp.media.model.Attachment.get( response.data.id, file.attachment ); complete = Uploader.queue.all( function( attachment ) { return ! attachment.get('uploading'); }); if ( complete ) Uploader.queue.reset(); self.success( file.attachment ); }); this.uploader.bind( 'Error', function( up, pluploadError ) { var message = pluploadL10n.default_error, key; // Check for plupload errors. for ( key in Uploader.errorMap ) { if ( pluploadError.code === plupload[ key ] ) { message = Uploader.errorMap[ key ]; if ( _.isFunction( message ) ) message = message( pluploadError.file, pluploadError ); break; } } error( message, pluploadError, pluploadError.file ); up.refresh(); }); this.init(); }; // Adds the 'defaults' and 'browser' properties. $.extend( Uploader, _wpPluploadSettings ); Uploader.uuid = 0; Uploader.errorMap = { 'FAILED': pluploadL10n.upload_failed, 'FILE_EXTENSION_ERROR': pluploadL10n.invalid_filetype, 'IMAGE_FORMAT_ERROR': pluploadL10n.not_an_image, 'IMAGE_MEMORY_ERROR': pluploadL10n.image_memory_exceeded, 'IMAGE_DIMENSIONS_ERROR': pluploadL10n.image_dimensions_exceeded, 'GENERIC_ERROR': pluploadL10n.upload_failed, 'IO_ERROR': pluploadL10n.io_error, 'HTTP_ERROR': pluploadL10n.http_error, 'SECURITY_ERROR': pluploadL10n.security_error, 'FILE_SIZE_ERROR': function( file ) { return pluploadL10n.file_exceeds_size_limit.replace('%s', file.name); } }; $.extend( Uploader.prototype, { /** * Acts as a shortcut to extending the uploader's multipart_params object. * * param( key ) * Returns the value of the key. * * param( key, value ) * Sets the value of a key. * * param( map ) * Sets values for a map of data. */ param: function( key, value ) { if ( arguments.length === 1 && typeof key === 'string' ) return this.uploader.settings.multipart_params[ key ]; if ( arguments.length > 1 ) { this.uploader.settings.multipart_params[ key ] = value; } else { $.extend( this.uploader.settings.multipart_params, key ); } }, init: function() {}, error: function() {}, success: function() {}, added: function() {}, progress: function() {}, complete: function() {}, refresh: function() { var node, attached, container, id; if ( this.browser ) { node = this.browser[0]; // Check if the browser node is in the DOM. while ( node ) { if ( node === document.body ) { attached = true; break; } node = node.parentNode; } // If the browser node is not attached to the DOM, use a // temporary container to house it, as the browser button // shims require the button to exist in the DOM at all times. if ( ! attached ) { id = 'wp-uploader-browser-' + this.uploader.id; container = $( '#' + id ); if ( ! container.length ) { container = $('<div class="wp-uploader-browser" />').css({ position: 'fixed', top: '-1000px', left: '-1000px', height: 0, width: 0 }).attr( 'id', 'wp-uploader-browser-' + this.uploader.id ).appendTo('body'); } container.append( this.browser ); } } this.uploader.refresh(); } }); Uploader.queue = new wp.media.model.Attachments( [], { query: false }); Uploader.errors = new Backbone.Collection(); exports.Uploader = Uploader; })( wp, jQuery );
JavaScript
(function($){ $.fn.filter_visible = function(depth) { depth = depth || 3; var is_visible = function() { var p = $(this), i; for(i=0; i<depth-1; ++i) { if (!p.is(':visible')) return false; p = p.parent(); } return true; } return this.filter(is_visible); }; $.table_hotkeys = function(table, keys, opts) { opts = $.extend($.table_hotkeys.defaults, opts); var selected_class, destructive_class, set_current_row, adjacent_row_callback, get_adjacent_row, adjacent_row, prev_row, next_row, check, get_first_row, get_last_row, make_key_callback, first_row; selected_class = opts.class_prefix + opts.selected_suffix; destructive_class = opts.class_prefix + opts.destructive_suffix set_current_row = function (tr) { if ($.table_hotkeys.current_row) $.table_hotkeys.current_row.removeClass(selected_class); tr.addClass(selected_class); tr[0].scrollIntoView(false); $.table_hotkeys.current_row = tr; }; adjacent_row_callback = function(which) { if (!adjacent_row(which) && $.isFunction(opts[which+'_page_link_cb'])) { opts[which+'_page_link_cb'](); } }; get_adjacent_row = function(which) { var first_row, method; if (!$.table_hotkeys.current_row) { first_row = get_first_row(); $.table_hotkeys.current_row = first_row; return first_row[0]; } method = 'prev' == which? $.fn.prevAll : $.fn.nextAll; return method.call($.table_hotkeys.current_row, opts.cycle_expr).filter_visible()[0]; }; adjacent_row = function(which) { var adj = get_adjacent_row(which); if (!adj) return false; set_current_row($(adj)); return true; }; prev_row = function() { return adjacent_row('prev'); }; next_row = function() { return adjacent_row('next'); }; check = function() { $(opts.checkbox_expr, $.table_hotkeys.current_row).each(function() { this.checked = !this.checked; }); }; get_first_row = function() { return $(opts.cycle_expr, table).filter_visible().eq(opts.start_row_index); }; get_last_row = function() { var rows = $(opts.cycle_expr, table).filter_visible(); return rows.eq(rows.length-1); }; make_key_callback = function(expr) { return function() { if ( null == $.table_hotkeys.current_row ) return false; var clickable = $(expr, $.table_hotkeys.current_row); if (!clickable.length) return false; if (clickable.is('.'+destructive_class)) next_row() || prev_row(); clickable.click(); } }; first_row = get_first_row(); if (!first_row.length) return; if (opts.highlight_first) set_current_row(first_row); else if (opts.highlight_last) set_current_row(get_last_row()); $.hotkeys.add(opts.prev_key, opts.hotkeys_opts, function() {return adjacent_row_callback('prev')}); $.hotkeys.add(opts.next_key, opts.hotkeys_opts, function() {return adjacent_row_callback('next')}); $.hotkeys.add(opts.mark_key, opts.hotkeys_opts, check); $.each(keys, function() { var callback, key; if ($.isFunction(this[1])) { callback = this[1]; key = this[0]; $.hotkeys.add(key, opts.hotkeys_opts, function(event) { return callback(event, $.table_hotkeys.current_row); }); } else { key = this; $.hotkeys.add(key, opts.hotkeys_opts, make_key_callback('.'+opts.class_prefix+key)); } }); }; $.table_hotkeys.current_row = null; $.table_hotkeys.defaults = {cycle_expr: 'tr', class_prefix: 'vim-', selected_suffix: 'current', destructive_suffix: 'destructive', hotkeys_opts: {disableInInput: true, type: 'keypress'}, checkbox_expr: ':checkbox', next_key: 'j', prev_key: 'k', mark_key: 'x', start_row_index: 2, highlight_first: false, highlight_last: false, next_page_link_cb: false, prev_page_link_cb: false}; })(jQuery);
JavaScript
(function($){$.scheduler=function(){this.bucket={};return;};$.scheduler.prototype={schedule:function(){var ctx={"id":null,"time":1000,"repeat":false,"protect":false,"obj":null,"func":function(){},"args":[]};function _isfn(fn){return(!!fn&&typeof fn!="string"&&typeof fn[0]=="undefined"&&RegExp("function","i").test(fn+""));};var i=0;var override=false;if(typeof arguments[i]=="object"&&arguments.length>1){override=true;i++;} if(typeof arguments[i]=="object"){for(var option in arguments[i]) if(typeof ctx[option]!="undefined") ctx[option]=arguments[i][option];i++;} if(typeof arguments[i]=="number"||(typeof arguments[i]=="string"&&arguments[i].match(RegExp("^[0-9]+[smhdw]$")))) ctx["time"]=arguments[i++];if(typeof arguments[i]=="boolean") ctx["repeat"]=arguments[i++];if(typeof arguments[i]=="boolean") ctx["protect"]=arguments[i++];if(typeof arguments[i]=="object"&&typeof arguments[i+1]=="string"&&_isfn(arguments[i][arguments[i+1]])){ctx["obj"]=arguments[i++];ctx["func"]=arguments[i++];} else if(typeof arguments[i]!="undefined"&&(_isfn(arguments[i])||typeof arguments[i]=="string")) ctx["func"]=arguments[i++];while(typeof arguments[i]!="undefined") ctx["args"].push(arguments[i++]);if(override){if(typeof arguments[1]=="object"){for(var option in arguments[0]) if(typeof ctx[option]!="undefined"&&typeof arguments[1][option]=="undefined") ctx[option]=arguments[0][option];} else{for(var option in arguments[0]) if(typeof ctx[option]!="undefined") ctx[option]=arguments[0][option];} i++;} ctx["_scheduler"]=this;ctx["_handle"]=null;var match=String(ctx["time"]).match(RegExp("^([0-9]+)([smhdw])$"));if(match&&match[0]!="undefined"&&match[1]!="undefined") ctx["time"]=String(parseInt(match[1])*{s:1000,m:1000*60,h:1000*60*60,d:1000*60*60*24,w:1000*60*60*24*7}[match[2]]);if(ctx["id"]==null) ctx["id"]=(String(ctx["repeat"])+":" +String(ctx["protect"])+":" +String(ctx["time"])+":" +String(ctx["obj"])+":" +String(ctx["func"])+":" +String(ctx["args"]));if(ctx["protect"]) if(typeof this.bucket[ctx["id"]]!="undefined") return this.bucket[ctx["id"]];if(!_isfn(ctx["func"])){if(ctx["obj"]!=null&&typeof ctx["obj"]=="object"&&typeof ctx["func"]=="string"&&_isfn(ctx["obj"][ctx["func"]])) ctx["func"]=ctx["obj"][ctx["func"]];else ctx["func"]=eval("function () { "+ctx["func"]+" }");} ctx["_handle"]=this._schedule(ctx);this.bucket[ctx["id"]]=ctx;return ctx;},reschedule:function(ctx){if(typeof ctx=="string") ctx=this.bucket[ctx];ctx["_handle"]=this._schedule(ctx);return ctx;},_schedule:function(ctx){var trampoline=function(){var obj=(ctx["obj"]!=null?ctx["obj"]:ctx);(ctx["func"]).apply(obj,ctx["args"]);if(typeof(ctx["_scheduler"]).bucket[ctx["id"]]!="undefined"&&ctx["repeat"]) (ctx["_scheduler"])._schedule(ctx);else delete(ctx["_scheduler"]).bucket[ctx["id"]];};return setTimeout(trampoline,ctx["time"]);},cancel:function(ctx){if(typeof ctx=="string") ctx=this.bucket[ctx];if(typeof ctx=="object"){clearTimeout(ctx["_handle"]);delete this.bucket[ctx["id"]];}}};$.extend({scheduler$:new $.scheduler(),schedule:function(){return $.scheduler$.schedule.apply($.scheduler$,arguments)},reschedule:function(){return $.scheduler$.reschedule.apply($.scheduler$,arguments)},cancel:function(){return $.scheduler$.cancel.apply($.scheduler$,arguments)}});$.fn.extend({schedule:function(){var a=[{}];for(var i=0;i<arguments.length;i++) a.push(arguments[i]);return this.each(function(){a[0]={"id":this,"obj":this};return $.schedule.apply($,a);});}});})(jQuery);
JavaScript
/*! * jQuery serializeObject - v0.2 - 1/20/2010 * http://benalman.com/projects/jquery-misc-plugins/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Whereas .serializeArray() serializes a form into an array, .serializeObject() // serializes a form into an (arguably more useful) object. (function($,undefined){ '$:nomunge'; // Used by YUI compressor. $.fn.serializeObject = function(){ var obj = {}; $.each( this.serializeArray(), function(i,o){ var n = o.name, v = o.value; obj[n] = obj[n] === undefined ? v : $.isArray( obj[n] ) ? obj[n].concat( v ) : [ obj[n], v ]; }); return obj; }; })(jQuery);
JavaScript
/*! * jQuery Form Plugin * version: 2.73 (03-MAY-2011) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') { options = { success: options }; } var action = this.attr('action'); var url = (typeof action === 'string') ? $.trim(action) : ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } url = url || window.location.href || ''; options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57) iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (n in options.data) { if(options.data[n] instanceof Array) { for (var k in options.data[n]) { a.push( { name: n, value: options.data[n][k] } ); } } else { v = options.data[n]; v = $.isFunction(v) ? v() : v; // if value is fn, invoke it a.push( { name: n, value: v } ); } } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var $form = this, callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file', this).length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (fileInputs || options.iframe || multipart)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, fileUpload); } else { fileUpload(); } } else { $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } var s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id; var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />'); var io = $io[0]; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, e, e); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, e); } }; var g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } var timedOut = 0, timeoutHandle; // add submitting element to data if we know it var sub = form.clk; if (sub) { var n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (form.getAttribute('method') != 'POST') { form.setAttribute('method', 'POST'); } if (form.getAttribute('action') != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(true); }, s.timeout); } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />') .appendTo(form)[0]); } } // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } if (e === true && xhr) { xhr.abort('timeout'); return; } var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var ok = true; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; var scr = /(json|script|text)/.test(s.dataType); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = httpData(xhr, s.dataType, s); } catch(e){ log('error caught:',e); ok = false; xhr.error = e; s.error && s.error.call(s.context, xhr, 'error', e); g && $.event.trigger("ajaxError", [xhr, s, e]); } if (xhr.aborted) { log('upload aborted'); ok = false; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error'); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { $io.removeData('form-plugin-onload'); $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { // in jQuery 1.3+ we can fix mistakes with the ready state if (this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug) { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } }; })(jQuery);
JavaScript
/****************************************************************************************************************************** * @ Original idea by by Binny V A, Original version: 2.00.A * @ http://www.openjs.com/scripts/events/keyboard_shortcuts/ * @ Original License : BSD * @ jQuery Plugin by Tzury Bar Yochay mail: tzury.by@gmail.com blog: evalinux.wordpress.com face: facebook.com/profile.php?id=513676303 (c) Copyrights 2007 * @ jQuery Plugin version Beta (0.0.2) * @ License: jQuery-License. TODO: add queue support (as in gmail) e.g. 'x' then 'y', etc. add mouse + mouse wheel events. USAGE: $.hotkeys.add('Ctrl+c', function(){ alert('copy anyone?');}); $.hotkeys.add('Ctrl+c', {target:'div#editor', type:'keyup', propagate: true},function(){ alert('copy anyone?');});> $.hotkeys.remove('Ctrl+c'); $.hotkeys.remove('Ctrl+c', {target:'div#editor', type:'keypress'}); ******************************************************************************************************************************/ (function (jQuery){ this.version = '(beta)(0.0.3)'; this.all = {}; this.special_keys = { 27: 'esc', 9: 'tab', 32:'space', 13: 'return', 8:'backspace', 145: 'scroll', 20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down', 112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12'}; this.shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&", "8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<", ".":">", "/":"?", "\\":"|" }; this.add = function(combi, options, callback) { if (jQuery.isFunction(options)){ callback = options; options = {}; } var opt = {}, defaults = {type: 'keydown', propagate: false, disableInInput: false, target: jQuery('html')[0]}, that = this; opt = jQuery.extend( opt , defaults, options || {} ); combi = combi.toLowerCase(); // inspect if keystroke matches var inspector = function(event) { // WP: not needed with newer jQuery // event = jQuery.event.fix(event); // jQuery event normalization. var element = event.target; // @ TextNode -> nodeType == 3 // WP: not needed with newer jQuery // element = (element.nodeType==3) ? element.parentNode : element; if(opt['disableInInput']) { // Disable shortcut keys in Input, Textarea fields var target = jQuery(element); if( target.is("input") || target.is("textarea")){ return; } } var code = event.which, type = event.type, character = String.fromCharCode(code).toLowerCase(), special = that.special_keys[code], shift = event.shiftKey, ctrl = event.ctrlKey, alt= event.altKey, meta = event.metaKey, propagate = true, // default behaivour mapPoint = null; // in opera + safari, the event.target is unpredictable. // for example: 'keydown' might be associated with HtmlBodyElement // or the element where you last clicked with your mouse. // WP: needed for all browsers // if (jQuery.browser.opera || jQuery.browser.safari){ while (!that.all[element] && element.parentNode){ element = element.parentNode; } // } var cbMap = that.all[element].events[type].callbackMap; if(!shift && !ctrl && !alt && !meta) { // No Modifiers mapPoint = cbMap[special] || cbMap[character] } // deals with combinaitons (alt|ctrl|shift+anything) else{ var modif = ''; if(alt) modif +='alt+'; if(ctrl) modif+= 'ctrl+'; if(shift) modif += 'shift+'; if(meta) modif += 'meta+'; // modifiers + special keys or modifiers + characters or modifiers + shift characters mapPoint = cbMap[modif+special] || cbMap[modif+character] || cbMap[modif+that.shift_nums[character]] } if (mapPoint){ mapPoint.cb(event); if(!mapPoint.propagate) { event.stopPropagation(); event.preventDefault(); return false; } } }; // first hook for this element if (!this.all[opt.target]){ this.all[opt.target] = {events:{}}; } if (!this.all[opt.target].events[opt.type]){ this.all[opt.target].events[opt.type] = {callbackMap: {}} jQuery.event.add(opt.target, opt.type, inspector); } this.all[opt.target].events[opt.type].callbackMap[combi] = {cb: callback, propagate:opt.propagate}; return jQuery; }; this.remove = function(exp, opt) { opt = opt || {}; target = opt.target || jQuery('html')[0]; type = opt.type || 'keydown'; exp = exp.toLowerCase(); delete this.all[target].events[type].callbackMap[exp] return jQuery; }; jQuery.hotkeys = this; return jQuery; })(jQuery);
JavaScript
/** * mctabs.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function MCTabs() { this.settings = []; this.onChange = tinyMCEPopup.editor.windowManager.createInstance('tinymce.util.Dispatcher'); }; MCTabs.prototype.init = function(settings) { this.settings = settings; }; MCTabs.prototype.getParam = function(name, default_value) { var value = null; value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name]; // Fix bool values if (value == "true" || value == "false") return (value == "true"); return value; }; MCTabs.prototype.showTab =function(tab){ tab.className = 'current'; tab.setAttribute("aria-selected", true); tab.setAttribute("aria-expanded", true); tab.tabIndex = 0; }; MCTabs.prototype.hideTab =function(tab){ var t=this; tab.className = ''; tab.setAttribute("aria-selected", false); tab.setAttribute("aria-expanded", false); tab.tabIndex = -1; }; MCTabs.prototype.showPanel = function(panel) { panel.className = 'current'; panel.setAttribute("aria-hidden", false); }; MCTabs.prototype.hidePanel = function(panel) { panel.className = 'panel'; panel.setAttribute("aria-hidden", true); }; MCTabs.prototype.getPanelForTab = function(tabElm) { return tinyMCEPopup.dom.getAttrib(tabElm, "aria-controls"); }; MCTabs.prototype.displayTab = function(tab_id, panel_id, avoid_focus) { var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i, t = this; tabElm = document.getElementById(tab_id); if (panel_id === undefined) { panel_id = t.getPanelForTab(tabElm); } panelElm= document.getElementById(panel_id); panelContainerElm = panelElm ? panelElm.parentNode : null; tabContainerElm = tabElm ? tabElm.parentNode : null; selectionClass = t.getParam('selection_class', 'current'); if (tabElm && tabContainerElm) { nodes = tabContainerElm.childNodes; // Hide all other tabs for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "LI") { t.hideTab(nodes[i]); } } // Show selected tab t.showTab(tabElm); } if (panelElm && panelContainerElm) { nodes = panelContainerElm.childNodes; // Hide all other panels for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "DIV") t.hidePanel(nodes[i]); } if (!avoid_focus) { tabElm.focus(); } // Show selected panel t.showPanel(panelElm); } }; MCTabs.prototype.getAnchor = function() { var pos, url = document.location.href; if ((pos = url.lastIndexOf('#')) != -1) return url.substring(pos + 1); return ""; }; //Global instance var mcTabs = new MCTabs(); tinyMCEPopup.onInit.add(function() { var tinymce = tinyMCEPopup.getWin().tinymce, dom = tinyMCEPopup.dom, each = tinymce.each; each(dom.select('div.tabs'), function(tabContainerElm) { var keyNav; dom.setAttrib(tabContainerElm, "role", "tablist"); var items = tinyMCEPopup.dom.select('li', tabContainerElm); var action = function(id) { mcTabs.displayTab(id, mcTabs.getPanelForTab(id)); mcTabs.onChange.dispatch(id); }; each(items, function(item) { dom.setAttrib(item, 'role', 'tab'); dom.bind(item, 'click', function(evt) { action(item.id); }); }); dom.bind(dom.getRoot(), 'keydown', function(evt) { if (evt.keyCode === 9 && evt.ctrlKey && !evt.altKey) { // Tab keyNav.moveFocus(evt.shiftKey ? -1 : 1); tinymce.dom.Event.cancel(evt); } }); each(dom.select('a', tabContainerElm), function(a) { dom.setAttrib(a, 'tabindex', '-1'); }); keyNav = tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', { root: tabContainerElm, items: items, onAction: action, actOnFocus: true, enableLeftRight: true, enableUpDown: true }, tinyMCEPopup.dom); }); });
JavaScript
/** * validate.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ /** // String validation: if (!Validator.isEmail('myemail')) alert('Invalid email.'); // Form validation: var f = document.forms['myform']; if (!Validator.isEmail(f.myemail)) alert('Invalid email.'); */ var Validator = { isEmail : function(s) { return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'); }, isAbsUrl : function(s) { return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$'); }, isSize : function(s) { return this.test(s, '^[0-9.]+(%|in|cm|mm|em|ex|pt|pc|px)?$'); }, isId : function(s) { return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$'); }, isEmpty : function(s) { var nl, i; if (s.nodeName == 'SELECT' && s.selectedIndex < 1) return true; if (s.type == 'checkbox' && !s.checked) return true; if (s.type == 'radio') { for (i=0, nl = s.form.elements; i<nl.length; i++) { if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked) return false; } return true; } return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s); }, isNumber : function(s, d) { return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$')); }, test : function(s, p) { s = s.nodeType == 1 ? s.value : s; return s == '' || new RegExp(p).test(s); } }; var AutoValidator = { settings : { id_cls : 'id', int_cls : 'int', url_cls : 'url', number_cls : 'number', email_cls : 'email', size_cls : 'size', required_cls : 'required', invalid_cls : 'invalid', min_cls : 'min', max_cls : 'max' }, init : function(s) { var n; for (n in s) this.settings[n] = s[n]; }, validate : function(f) { var i, nl, s = this.settings, c = 0; nl = this.tags(f, 'label'); for (i=0; i<nl.length; i++) { this.removeClass(nl[i], s.invalid_cls); nl[i].setAttribute('aria-invalid', false); } c += this.validateElms(f, 'input'); c += this.validateElms(f, 'select'); c += this.validateElms(f, 'textarea'); return c == 3; }, invalidate : function(n) { this.mark(n.form, n); }, getErrorMessages : function(f) { var nl, i, s = this.settings, field, msg, values, messages = [], ed = tinyMCEPopup.editor; nl = this.tags(f, "label"); for (i=0; i<nl.length; i++) { if (this.hasClass(nl[i], s.invalid_cls)) { field = document.getElementById(nl[i].getAttribute("for")); values = { field: nl[i].textContent }; if (this.hasClass(field, s.min_cls, true)) { message = ed.getLang('invalid_data_min'); values.min = this.getNum(field, s.min_cls); } else if (this.hasClass(field, s.number_cls)) { message = ed.getLang('invalid_data_number'); } else if (this.hasClass(field, s.size_cls)) { message = ed.getLang('invalid_data_size'); } else { message = ed.getLang('invalid_data'); } message = message.replace(/{\#([^}]+)\}/g, function(a, b) { return values[b] || '{#' + b + '}'; }); messages.push(message); } } return messages; }, reset : function(e) { var t = ['label', 'input', 'select', 'textarea']; var i, j, nl, s = this.settings; if (e == null) return; for (i=0; i<t.length; i++) { nl = this.tags(e.form ? e.form : e, t[i]); for (j=0; j<nl.length; j++) { this.removeClass(nl[j], s.invalid_cls); nl[j].setAttribute('aria-invalid', false); } } }, validateElms : function(f, e) { var nl, i, n, s = this.settings, st = true, va = Validator, v; nl = this.tags(f, e); for (i=0; i<nl.length; i++) { n = nl[i]; this.removeClass(n, s.invalid_cls); if (this.hasClass(n, s.required_cls) && va.isEmpty(n)) st = this.mark(f, n); if (this.hasClass(n, s.number_cls) && !va.isNumber(n)) st = this.mark(f, n); if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true)) st = this.mark(f, n); if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n)) st = this.mark(f, n); if (this.hasClass(n, s.email_cls) && !va.isEmail(n)) st = this.mark(f, n); if (this.hasClass(n, s.size_cls) && !va.isSize(n)) st = this.mark(f, n); if (this.hasClass(n, s.id_cls) && !va.isId(n)) st = this.mark(f, n); if (this.hasClass(n, s.min_cls, true)) { v = this.getNum(n, s.min_cls); if (isNaN(v) || parseInt(n.value) < parseInt(v)) st = this.mark(f, n); } if (this.hasClass(n, s.max_cls, true)) { v = this.getNum(n, s.max_cls); if (isNaN(v) || parseInt(n.value) > parseInt(v)) st = this.mark(f, n); } } return st; }, hasClass : function(n, c, d) { return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className); }, getNum : function(n, c) { c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0]; c = c.replace(/[^0-9]/g, ''); return c; }, addClass : function(n, c, b) { var o = this.removeClass(n, c); n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c; }, removeClass : function(n, c) { c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' '); return n.className = c != ' ' ? c : ''; }, tags : function(f, s) { return f.getElementsByTagName(s); }, mark : function(f, n) { var s = this.settings; this.addClass(n, s.invalid_cls); n.setAttribute('aria-invalid', 'true'); this.markLabels(f, n, s.invalid_cls); return false; }, markLabels : function(f, n, ic) { var nl, i; nl = this.tags(f, "label"); for (i=0; i<nl.length; i++) { if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id) this.addClass(nl[i], ic); } return null; } };
JavaScript
/** * form_utils.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme")); function getColorPickerHTML(id, target_form_element) { var h = "", dom = tinyMCEPopup.dom; if (label = dom.select('label[for=' + target_form_element + ']')[0]) { label.id = label.id || dom.uniqueId(); } h += '<a role="button" aria-labelledby="' + id + '_label" id="' + id + '_link" href="javascript:;" onclick="tinyMCEPopup.pickColor(event,\'' + target_form_element +'\');" onmousedown="return false;" class="pickcolor">'; h += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '">&nbsp;<span id="' + id + '_label" class="mceVoiceLabel mceIconOnly" style="display:none;">' + tinyMCEPopup.getLang('browse') + '</span></span></a>'; return h; } function updateColor(img_id, form_element_id) { document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value; } function setBrowserDisabled(id, state) { var img = document.getElementById(id); var lnk = document.getElementById(id + "_link"); if (lnk) { if (state) { lnk.setAttribute("realhref", lnk.getAttribute("href")); lnk.removeAttribute("href"); tinyMCEPopup.dom.addClass(img, 'disabled'); } else { if (lnk.getAttribute("realhref")) lnk.setAttribute("href", lnk.getAttribute("realhref")); tinyMCEPopup.dom.removeClass(img, 'disabled'); } } } function getBrowserHTML(id, target_form_element, type, prefix) { var option = prefix + "_" + type + "_browser_callback", cb, html; cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback")); if (!cb) return ""; html = ""; html += '<a id="' + id + '_link" href="javascript:openBrowser(\'' + id + '\',\'' + target_form_element + '\', \'' + type + '\',\'' + option + '\');" onmousedown="return false;" class="browse">'; html += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '">&nbsp;</span></a>'; return html; } function openBrowser(img_id, target_form_element, type, option) { var img = document.getElementById(img_id); if (img.className != "mceButtonDisabled") tinyMCEPopup.openBrowser(target_form_element, type, option); } function selectByValue(form_obj, field_name, value, add_custom, ignore_case) { if (!form_obj || !form_obj.elements[field_name]) return; if (!value) value = ""; var sel = form_obj.elements[field_name]; var found = false; for (var i=0; i<sel.options.length; i++) { var option = sel.options[i]; if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) { option.selected = true; found = true; } else option.selected = false; } if (!found && add_custom && value != '') { var option = new Option(value, value); option.selected = true; sel.options[sel.options.length] = option; sel.selectedIndex = sel.options.length - 1; } return found; } function getSelectValue(form_obj, field_name) { var elm = form_obj.elements[field_name]; if (elm == null || elm.options == null || elm.selectedIndex === -1) return ""; return elm.options[elm.selectedIndex].value; } function addSelectValue(form_obj, field_name, name, value) { var s = form_obj.elements[field_name]; var o = new Option(name, value); s.options[s.options.length] = o; } function addClassesToList(list_id, specific_option) { // Setup class droplist var styleSelectElm = document.getElementById(list_id); var styles = tinyMCEPopup.getParam('theme_advanced_styles', false); styles = tinyMCEPopup.getParam(specific_option, styles); if (styles) { var stylesAr = styles.split(';'); for (var i=0; i<stylesAr.length; i++) { if (stylesAr != "") { var key, value; key = stylesAr[i].split('=')[0]; value = stylesAr[i].split('=')[1]; styleSelectElm.options[styleSelectElm.length] = new Option(key, value); } } } else { tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) { styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']); }); } } function isVisible(element_id) { var elm = document.getElementById(element_id); return elm && elm.style.display != "none"; } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return "rgb(" + r + "," + g + "," + b + ")"; } return col; } function trimSize(size) { return size.replace(/([0-9\.]+)(px|%|in|cm|mm|em|ex|pt|pc)/i, '$1$2'); } function getCSSSize(size) { size = trimSize(size); if (size == "") return ""; // Add px if (/^[0-9]+$/.test(size)) size += 'px'; // Sanity check, IE doesn't like broken values else if (!(/^[0-9\.]+(px|%|in|cm|mm|em|ex|pt|pc)$/i.test(size))) return ""; return size; } function getStyle(elm, attrib, style) { var val = tinyMCEPopup.dom.getAttrib(elm, attrib); if (val != '') return '' + val; if (typeof(style) == 'undefined') style = attrib; return tinyMCEPopup.dom.getStyle(elm, style); }
JavaScript
/** * editable_selects.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ var TinyMCE_EditableSelects = { editSelectElm : null, init : function() { var nl = document.getElementsByTagName("select"), i, d = document, o; for (i=0; i<nl.length; i++) { if (nl[i].className.indexOf('mceEditableSelect') != -1) { o = new Option(tinyMCEPopup.editor.translate('value'), '__mce_add_custom__'); o.className = 'mceAddSelectValue'; nl[i].options[nl[i].options.length] = o; nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect; } } }, onChangeEditableSelect : function(e) { var d = document, ne, se = window.event ? window.event.srcElement : e.target; if (se.options[se.selectedIndex].value == '__mce_add_custom__') { ne = d.createElement("input"); ne.id = se.id + "_custom"; ne.name = se.name + "_custom"; ne.type = "text"; ne.style.width = se.offsetWidth + 'px'; se.parentNode.insertBefore(ne, se); se.style.display = 'none'; ne.focus(); ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput; ne.onkeydown = TinyMCE_EditableSelects.onKeyDown; TinyMCE_EditableSelects.editSelectElm = se; } }, onBlurEditableSelectInput : function() { var se = TinyMCE_EditableSelects.editSelectElm; if (se) { if (se.previousSibling.value != '') { addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value); selectByValue(document.forms[0], se.id, se.previousSibling.value); } else selectByValue(document.forms[0], se.id, ''); se.style.display = 'inline'; se.parentNode.removeChild(se.previousSibling); TinyMCE_EditableSelects.editSelectElm = null; } }, onKeyDown : function(e) { e = e || window.event; if (e.keyCode == 13) TinyMCE_EditableSelects.onBlurEditableSelectInput(); } };
JavaScript
/** * TinyMCE Schema.js * * Duck-punched by WordPress core to support a sane schema superset. * * Copyright, Moxiecode Systems AB * Released under LGPL * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ (function(tinymce) { var mapCache = {}, makeMap = tinymce.makeMap, each = tinymce.each; function split(str, delim) { return str.split(delim || ','); }; /** * Unpacks the specified lookup and string data it will also parse it into an object * map with sub object for it's children. This will later also include the attributes. */ function unpack(lookup, data) { var key, elements = {}; function replace(value) { return value.replace(/[A-Z]+/g, function(key) { return replace(lookup[key]); }); }; // Unpack lookup for (key in lookup) { if (lookup.hasOwnProperty(key)) lookup[key] = replace(lookup[key]); } // Unpack and parse data into object map replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) { attributes = split(attributes, '|'); elements[name] = { attributes : makeMap(attributes), attributesOrder : attributes, children : makeMap(children, '|', {'#comment' : {}}) } }); return elements; }; /** * Returns the HTML5 schema and caches it in the mapCache. */ function getHTML5() { var html5 = mapCache.html5; if (!html5) { html5 = mapCache.html5 = unpack({ A : 'accesskey|class|contextmenu|dir|draggable|dropzone|hidden|id|inert|itemid|itemprop|itemref|itemscope|itemtype|lang|spellcheck|style|tabindex|title|translate|item|role|subject|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup', B : '#|a|abbr|area|audio|b|bdi|bdo|br|button|canvas|cite|code|command|data|datalist|del|dfn|em|embed|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|math|meta|meter|noscript|object|output|progress|q|ruby|s|samp|script|select|small|span|strong|sub|sup|svg|textarea|time|u|var|video|wbr', C : '#|a|abbr|area|address|article|aside|audio|b|bdi|bdo|blockquote|br|button|canvas|cite|code|command|data|datalist|del|details|dfn|dialog|div|dl|em|embed|fieldset|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|math|menu|meta|meter|nav|noscript|ol|object|output|p|pre|progress|q|ruby|s|samp|script|section|select|small|span|strong|style|sub|sup|svg|table|textarea|time|u|ul|var|video|wbr' }, 'html[A|manifest][body|head]' + 'head[A][base|command|link|meta|noscript|script|style|title]' + 'title[A][#]' + 'base[A|href|target][]' + 'link[A|href|rel|media|type|sizes|crossorigin|hreflang][]' + 'meta[A|http-equiv|name|content|charset][]' + 'style[A|type|media|scoped][#]' + 'script[A|charset|type|src|defer|async|crossorigin][#]' + 'noscript[A][C]' + 'body[A|onafterprint|onbeforeprint|onbeforeunload|onblur|onerror|onfocus|onfullscreenchange|onfullscreenerror|onhashchange|onload|onmessage|onoffline|ononline|onpagehide|onpageshow|onpopstate|onresize|onscroll|onstorage|onunload][C]' + 'section[A][C]' + 'nav[A][C]' + 'article[A][C]' + 'aside[A][C]' + 'h1[A][B]' + 'h2[A][B]' + 'h3[A][B]' + 'h4[A][B]' + 'h5[A][B]' + 'h6[A][B]' + 'hgroup[A][h1|h2|h3|h4|h5|h6]' + 'header[A][C]' + 'footer[A][C]' + 'address[A][C]' + 'p[A][B]' + 'br[A][]' + 'pre[A][B]' + 'dialog[A|open][C|dd|dt]' + 'blockquote[A|cite][C]' + 'ol[A|start|reversed][li]' + 'ul[A][li]' + 'li[A|value][C]' + 'dl[A][dd|dt]' + 'dt[A][C|B]' + 'dd[A][C]' + 'a[A|href|target|download|ping|rel|media|type][B]' + 'em[A][B]' + 'strong[A][B]' + 'small[A][B]' + 's[A][B]' + 'cite[A][B]' + 'q[A|cite][B]' + 'dfn[A][B]' + 'abbr[A][B]' + 'code[A][B]' + 'var[A][B]' + 'samp[A][B]' + 'kbd[A][B]' + 'sub[A][B]' + 'sup[A][B]' + 'i[A][B]' + 'b[A][B]' + 'u[A][B]' + 'mark[A][B]' + 'progress[A|value|max][B]' + 'meter[A|value|min|max|low|high|optimum][B]' + 'time[A|datetime][B]' + 'ruby[A][B|rt|rp]' + 'rt[A][B]' + 'rp[A][B]' + 'bdi[A][B]' + 'bdo[A][B]' + 'span[A][B]' + 'ins[A|cite|datetime][C|B]' + 'del[A|cite|datetime][C|B]' + 'figure[A][C|legend|figcaption]' + 'figcaption[A][C]' + 'img[A|alt|src|srcset|crossorigin|usemap|ismap|width|height][]' + 'iframe[A|name|src|srcdoc|height|width|sandbox|seamless|allowfullscreen][C|B]' + 'embed[A|src|height|width|type][]' + 'object[A|data|type|typemustmatch|name|usemap|form|width|height][C|B|param]' + 'param[A|name|value][]' + 'summary[A][B]' + 'details[A|open][C|legend|summary]' + 'command[A|type|label|icon|disabled|checked|radiogroup|command][]' + 'menu[A|type|label][C|li]' + 'legend[A][C|B]' + 'div[A][C]' + 'source[A|src|type|media][]' + 'track[A|kind|src|srclang|label|default][]' + 'audio[A|src|autobuffer|autoplay|loop|controls|crossorigin|preload|mediagroup|muted][C|source|track]' + 'video[A|src|autobuffer|autoplay|loop|controls|width|height|poster|crossorigin|preload|mediagroup|muted][C|source|track]' + 'hr[A][]' + 'form[A|accept-charset|action|autocomplete|enctype|method|name|novalidate|target][C]' + 'fieldset[A|disabled|form|name][C|legend]' + 'label[A|form|for][B]' + 'input[A|type|accept|alt|autocomplete|autofocus|checked|dirname|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|inputmode|list|max|maxlength|min|multiple|name|pattern|placeholder|readonly|required|size|src|step|value|width|files][]' + 'button[A|autofocus|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|name|type|value][B]' + 'select[A|autofocus|disabled|form|multiple|name|required|size][option|optgroup]' + 'data[A|value][B]' + 'datalist[A][B|option]' + 'optgroup[A|disabled|label][option]' + 'option[A|disabled|selected|label|value][#]' + 'textarea[A|autocomplete|autofocus|cols|dirname|disabled|form|inputmode|maxlength|name|placeholder|readonly|required|rows|wrap][#]' + 'keygen[A|autofocus|challenge|disabled|form|keytype|name][]' + 'output[A|for|form|name][B]' + 'canvas[A|width|height][a|button|input]' + 'map[A|name][C|B]' + 'area[A|alt|coords|shape|href|target|download|ping|rel|media|hreflang|type][]' + 'math[A][]' + 'svg[A][]' + 'table[A][caption|colgroup|thead|tfoot|tbody|tr]' + 'caption[A][C]' + 'colgroup[A|span][col]' + 'col[A|span][]' + 'thead[A][tr]' + 'tfoot[A][tr]' + 'tbody[A][tr]' + 'tr[A][th|td]' + 'th[A|headers|rowspan|colspan|scope][C]' + 'td[A|headers|rowspan|colspan][C]' + 'wbr[A][]' ); } return html5; }; /** * Returns the HTML4 schema and caches it in the mapCache. */ function getHTML4() { var html4 = mapCache.html4; if (!html4) { // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size html4 = mapCache.html4 = unpack({ Z : 'H|K|N|O|P', Y : 'X|form|R|Q', ZG : 'E|span|width|align|char|charoff|valign', X : 'p|T|div|U|W|isindex|fieldset|table', ZF : 'E|align|char|charoff|valign', W : 'pre|hr|blockquote|address|center|noframes', ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height', ZD : '[E][S]', U : 'ul|ol|dl|menu|dir', ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q', T : 'h1|h2|h3|h4|h5|h6', ZB : 'X|S|Q', S : 'R|P', ZA : 'a|G|J|M|O|P', R : 'a|H|K|N|O', Q : 'noscript|P', P : 'ins|del|script', O : 'input|select|textarea|label|button', N : 'M|L', M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym', L : 'sub|sup', K : 'J|I', J : 'tt|i|b|u|s|strike', I : 'big|small|font|basefont', H : 'G|F', G : 'br|span|bdo', F : 'object|applet|img|map|iframe', E : 'A|B|C', D : 'accesskey|tabindex|onfocus|onblur', C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup', B : 'lang|xml:lang|dir', A : 'id|class|style|title' }, 'script[id|charset|type|language|src|defer|xml:space][]' + 'style[B|id|type|media|title|xml:space][]' + 'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + 'param[id|name|value|valuetype|type][]' + 'p[E|align][#|S]' + 'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + 'br[A|clear][]' + 'span[E][#|S]' + 'bdo[A|C|B][#|S]' + 'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + 'h1[E|align][#|S]' + 'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + 'map[B|C|A|name][X|form|Q|area]' + 'h2[E|align][#|S]' + 'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + 'h3[E|align][#|S]' + 'tt[E][#|S]' + 'i[E][#|S]' + 'b[E][#|S]' + 'u[E][#|S]' + 's[E][#|S]' + 'strike[E][#|S]' + 'big[E][#|S]' + 'small[E][#|S]' + 'font[A|B|size|color|face][#|S]' + 'basefont[id|size|color|face][]' + 'em[E][#|S]' + 'strong[E][#|S]' + 'dfn[E][#|S]' + 'code[E][#|S]' + 'q[E|cite][#|S]' + 'samp[E][#|S]' + 'kbd[E][#|S]' + 'var[E][#|S]' + 'cite[E][#|S]' + 'abbr[E][#|S]' + 'acronym[E][#|S]' + 'sub[E][#|S]' + 'sup[E][#|S]' + 'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + 'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + 'optgroup[E|disabled|label][option]' + 'option[E|selected|disabled|label|value][]' + 'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + 'label[E|for|accesskey|onfocus|onblur][#|S]' + 'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + 'h4[E|align][#|S]' + 'ins[E|cite|datetime][#|Y]' + 'h5[E|align][#|S]' + 'del[E|cite|datetime][#|Y]' + 'h6[E|align][#|S]' + 'div[E|align][#|Y]' + 'ul[E|type|compact][li]' + 'li[E|type|value][#|Y]' + 'ol[E|type|compact|start][li]' + 'dl[E|compact][dt|dd]' + 'dt[E][#|S]' + 'dd[E][#|Y]' + 'menu[E|compact][li]' + 'dir[E|compact][li]' + 'pre[E|width|xml:space][#|ZA]' + 'hr[E|align|noshade|size|width][]' + 'blockquote[E|cite][#|Y]' + 'address[E][#|S|p]' + 'center[E][#|Y]' + 'noframes[E][#|Y]' + 'isindex[A|B|prompt][]' + 'fieldset[E][#|legend|Y]' + 'legend[E|accesskey|align][#|S]' + 'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + 'caption[E|align][#|S]' + 'col[ZG][]' + 'colgroup[ZG][col]' + 'thead[ZF][tr]' + 'tr[ZF|bgcolor][th|td]' + 'th[E|ZE][#|Y]' + 'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + 'noscript[E][#|Y]' + 'td[E|ZE][#|Y]' + 'tfoot[ZF][tr]' + 'tbody[ZF][tr]' + 'area[E|D|shape|coords|href|nohref|alt|target][]' + 'base[id|href|target][]' + 'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]' ); } return html4; }; /** * WordPress Core * * Returns a schema that is the result of a deep merge between the HTML5 * and HTML4 schemas. */ function getSaneSchema() { var cachedMapCache = mapCache, html5, html4; if ( mapCache.sane ) return mapCache.sane; // Bust the mapCache so we're not dealing with the other schema objects. mapCache = {}; html5 = getHTML5(); html4 = getHTML4(); mapCache = cachedMapCache; each( html4, function( html4settings, tag ) { var html5settings = html5[ tag ], difference = []; // Merge tags missing in HTML5 mode. if ( ! html5settings ) { html5[ tag ] = html4settings; return; } // Merge attributes missing from this HTML5 tag. each( html4settings.attributes, function( attribute, key ) { if ( ! html5settings.attributes[ key ] ) html5settings.attributes[ key ] = attribute; }); // Merge any missing attributes into the attributes order. each( html4settings.attributesOrder, function( key ) { if ( -1 === tinymce.inArray( html5settings.attributesOrder, key ) ) difference.push( key ); }); html5settings.attributesOrder = html5settings.attributesOrder.concat( difference ); // Merge children missing from this HTML5 tag. each( html4settings.children, function( child, key ) { if ( ! html5settings.children[ key ] ) html5settings.children[ key ] = child; }); }); return mapCache.sane = html5; } /** * Schema validator class. * * @class tinymce.html.Schema * @example * if (tinymce.activeEditor.schema.isValidChild('p', 'span')) * alert('span is valid child of p.'); * * if (tinymce.activeEditor.schema.getElementRule('p')) * alert('P is a valid element.'); * * @class tinymce.html.Schema * @version 3.4 */ /** * Constructs a new Schema instance. * * @constructor * @method Schema * @param {Object} settings Name/value settings object. */ tinymce.html.Schema = function(settings) { var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems; var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap, blockElementsMap, nonEmptyElementsMap, customElementsMap = {}; // Creates an lookup table map object for the specified option or the default value function createLookupTable(option, default_value, extend) { var value = settings[option]; if (!value) { // Get cached default map or make it if needed value = mapCache[option]; if (!value) { value = makeMap(default_value, ' ', makeMap(default_value.toUpperCase(), ' ')); value = tinymce.extend(value, extend); mapCache[option] = value; } } else { // Create custom map value = makeMap(value, ',', makeMap(value.toUpperCase(), ' ')); } return value; }; settings = settings || {}; /** * WordPress core uses a sane schema in place of the default "HTML5" schema. */ schemaItems = settings.schema == "html5" ? getSaneSchema() : getHTML4(); // Allow all elements and attributes if verify_html is set to false if (settings.verify_html === false) settings.valid_elements = '*[*]'; // Build styles list if (settings.valid_styles) { validStyles = {}; // Convert styles into a rule list each(settings.valid_styles, function(value, key) { validStyles[key] = tinymce.explode(value); }); } // Setup map objects whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea'); selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr'); shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link meta param embed source wbr'); boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls'); nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap); textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + 'blockquote center dir fieldset header footer article section hgroup aside nav figure'); blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + 'th tr td li ol ul caption dl dt dd noscript menu isindex option datalist select optgroup', textBlockElementsMap); // Converts a wildcard expression string to a regexp for example *a will become /.*a/. function patternToRegExp(str) { return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$'); }; // Parses the specified valid_elements string and adds to the current rules // This function is a bit hard to read since it's heavily optimized for speed function addValidElements(valid_elements) { var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value, elementRuleRegExp = /^([#+\-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/, attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/; if (valid_elements) { // Split valid elements into an array with rules valid_elements = split(valid_elements); if (elements['@']) { globalAttributes = elements['@'].attributes; globalAttributesOrder = elements['@'].attributesOrder; } // Loop all rules for (ei = 0, el = valid_elements.length; ei < el; ei++) { // Parse element rule matches = elementRuleRegExp.exec(valid_elements[ei]); if (matches) { // Setup local names for matches prefix = matches[1]; elementName = matches[2]; outputName = matches[3]; attrData = matches[4]; // Create new attributes and attributesOrder attributes = {}; attributesOrder = []; // Create the new element element = { attributes : attributes, attributesOrder : attributesOrder }; // Padd empty elements prefix if (prefix === '#') element.paddEmpty = true; // Remove empty elements prefix if (prefix === '-') element.removeEmpty = true; // Copy attributes from global rule into current rule if (globalAttributes) { for (key in globalAttributes) attributes[key] = globalAttributes[key]; attributesOrder.push.apply(attributesOrder, globalAttributesOrder); } // Attributes defined if (attrData) { attrData = split(attrData, '|'); for (ai = 0, al = attrData.length; ai < al; ai++) { matches = attrRuleRegExp.exec(attrData[ai]); if (matches) { attr = {}; attrType = matches[1]; attrName = matches[2].replace(/::/g, ':'); prefix = matches[3]; value = matches[4]; // Required if (attrType === '!') { element.attributesRequired = element.attributesRequired || []; element.attributesRequired.push(attrName); attr.required = true; } // Denied from global if (attrType === '-') { delete attributes[attrName]; attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1); continue; } // Default value if (prefix) { // Default value if (prefix === '=') { element.attributesDefault = element.attributesDefault || []; element.attributesDefault.push({name: attrName, value: value}); attr.defaultValue = value; } // Forced value if (prefix === ':') { element.attributesForced = element.attributesForced || []; element.attributesForced.push({name: attrName, value: value}); attr.forcedValue = value; } // Required values if (prefix === '<') attr.validValues = makeMap(value, '?'); } // Check for attribute patterns if (hasPatternsRegExp.test(attrName)) { element.attributePatterns = element.attributePatterns || []; attr.pattern = patternToRegExp(attrName); element.attributePatterns.push(attr); } else { // Add attribute to order list if it doesn't already exist if (!attributes[attrName]) attributesOrder.push(attrName); attributes[attrName] = attr; } } } } // Global rule, store away these for later usage if (!globalAttributes && elementName == '@') { globalAttributes = attributes; globalAttributesOrder = attributesOrder; } // Handle substitute elements such as b/strong if (outputName) { element.outputName = elementName; elements[outputName] = element; } // Add pattern or exact element if (hasPatternsRegExp.test(elementName)) { element.pattern = patternToRegExp(elementName); patternElements.push(element); } else elements[elementName] = element; } } } }; function setValidElements(valid_elements) { elements = {}; patternElements = []; addValidElements(valid_elements); each(schemaItems, function(element, name) { children[name] = element.children; }); }; // Adds custom non HTML elements to the schema function addCustomElements(custom_elements) { var customElementRegExp = /^(~)?(.+)$/; if (custom_elements) { each(split(custom_elements), function(rule) { var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2]; children[name] = children[cloneName]; customElementsMap[name] = cloneName; // If it's not marked as inline then add it to valid block elements if (!inline) { blockElementsMap[name.toUpperCase()] = {}; blockElementsMap[name] = {}; } // Add elements clone if needed if (!elements[name]) { elements[name] = elements[cloneName]; } // Add custom elements at span/div positions each(children, function(element, child) { if (element[cloneName]) element[name] = element[cloneName]; }); }); } }; // Adds valid children to the schema object function addValidChildren(valid_children) { var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/; if (valid_children) { each(split(valid_children), function(rule) { var matches = childRuleRegExp.exec(rule), parent, prefix; if (matches) { prefix = matches[1]; // Add/remove items from default if (prefix) parent = children[matches[2]]; else parent = children[matches[2]] = {'#comment' : {}}; parent = children[matches[2]]; each(split(matches[3], '|'), function(child) { if (prefix === '-') delete parent[child]; else parent[child] = {}; }); } }); } }; function getElementRule(name) { var element = elements[name], i; // Exact match found if (element) return element; // No exact match then try the patterns i = patternElements.length; while (i--) { element = patternElements[i]; if (element.pattern.test(name)) return element; } }; if (!settings.valid_elements) { // No valid elements defined then clone the elements from the schema spec each(schemaItems, function(element, name) { elements[name] = { attributes : element.attributes, attributesOrder : element.attributesOrder }; children[name] = element.children; }); // Switch these on HTML4 if (settings.schema != "html5") { each(split('strong/b,em/i'), function(item) { item = split(item, '/'); elements[item[1]].outputName = item[0]; }); } // Add default alt attribute for images elements.img.attributesDefault = [{name: 'alt', value: ''}]; // Remove these if they are empty by default each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr'), function(name) { if (elements[name]) { elements[name].removeEmpty = true; } }); // Padd these by default each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) { elements[name].paddEmpty = true; }); } else setValidElements(settings.valid_elements); addCustomElements(settings.custom_elements); addValidChildren(settings.valid_children); addValidElements(settings.extended_valid_elements); // Todo: Remove this when we fix list handling to be valid addValidChildren('+ol[ul|ol],+ul[ul|ol]'); // Delete invalid elements if (settings.invalid_elements) { tinymce.each(tinymce.explode(settings.invalid_elements), function(item) { if (elements[item]) delete elements[item]; }); } // If the user didn't allow span only allow internal spans if (!getElementRule('span')) addValidElements('span[!data-mce-type|*]'); /** * Name/value map object with valid parents and children to those parents. * * @example * children = { * div:{p:{}, h1:{}} * }; * @field children * @type {Object} */ self.children = children; /** * Name/value map object with valid styles for each element. * * @field styles * @type {Object} */ self.styles = validStyles; /** * Returns a map with boolean attributes. * * @method getBoolAttrs * @return {Object} Name/value lookup map for boolean attributes. */ self.getBoolAttrs = function() { return boolAttrMap; }; /** * Returns a map with block elements. * * @method getBlockElements * @return {Object} Name/value lookup map for block elements. */ self.getBlockElements = function() { return blockElementsMap; }; /** * Returns a map with text block elements. Such as: p,h1-h6,div,address * * @method getTextBlockElements * @return {Object} Name/value lookup map for block elements. */ self.getTextBlockElements = function() { return textBlockElementsMap; }; /** * Returns a map with short ended elements such as BR or IMG. * * @method getShortEndedElements * @return {Object} Name/value lookup map for short ended elements. */ self.getShortEndedElements = function() { return shortEndedElementsMap; }; /** * Returns a map with self closing tags such as <li>. * * @method getSelfClosingElements * @return {Object} Name/value lookup map for self closing tags elements. */ self.getSelfClosingElements = function() { return selfClosingElementsMap; }; /** * Returns a map with elements that should be treated as contents regardless if it has text * content in them or not such as TD, VIDEO or IMG. * * @method getNonEmptyElements * @return {Object} Name/value lookup map for non empty elements. */ self.getNonEmptyElements = function() { return nonEmptyElementsMap; }; /** * Returns a map with elements where white space is to be preserved like PRE or SCRIPT. * * @method getWhiteSpaceElements * @return {Object} Name/value lookup map for white space elements. */ self.getWhiteSpaceElements = function() { return whiteSpaceElementsMap; }; /** * Returns true/false if the specified element and it's child is valid or not * according to the schema. * * @method isValidChild * @param {String} name Element name to check for. * @param {String} child Element child to verify. * @return {Boolean} True/false if the element is a valid child of the specified parent. */ self.isValidChild = function(name, child) { var parent = children[name]; return !!(parent && parent[child]); }; /** * Returns true/false if the specified element name and optional attribute is * valid according to the schema. * * @method isValid * @param {String} name Name of element to check. * @param {String} attr Optional attribute name to check for. * @return {Boolean} True/false if the element and attribute is valid. */ self.isValid = function(name, attr) { var attrPatterns, i, rule = getElementRule(name); // Check if it's a valid element if (rule) { if (attr) { // Check if attribute name exists if (rule.attributes[attr]) { return true; } // Check if attribute matches a regexp pattern attrPatterns = rule.attributePatterns; if (attrPatterns) { i = attrPatterns.length; while (i--) { if (attrPatterns[i].pattern.test(name)) { return true; } } } } else { return true; } } // No match return false; }; /** * Returns true/false if the specified element is valid or not * according to the schema. * * @method getElementRule * @param {String} name Element name to check for. * @return {Object} Element object or undefined if the element isn't valid. */ self.getElementRule = getElementRule; /** * Returns an map object of all custom elements. * * @method getCustomElements * @return {Object} Name/value map object of all custom elements. */ self.getCustomElements = function() { return customElementsMap; }; /** * Parses a valid elements string and adds it to the schema. The valid elements format is for example "element[attr=default|otherattr]". * Existing rules will be replaced with the ones specified, so this extends the schema. * * @method addValidElements * @param {String} valid_elements String in the valid elements format to be parsed. */ self.addValidElements = addValidElements; /** * Parses a valid elements string and sets it to the schema. The valid elements format is for example "element[attr=default|otherattr]". * Existing rules will be replaced with the ones specified, so this extends the schema. * * @method setValidElements * @param {String} valid_elements String in the valid elements format to be parsed. */ self.setValidElements = setValidElements; /** * Adds custom non HTML elements to the schema. * * @method addCustomElements * @param {String} custom_elements Comma separated list of custom elements to add. */ self.addCustomElements = addCustomElements; /** * Parses a valid children string and adds them to the schema structure. The valid children format is for example: "element[child1|child2]". * * @method addValidChildren * @param {String} valid_children Valid children elements string to parse */ self.addValidChildren = addValidChildren; self.elements = elements; }; })(tinymce);
JavaScript
tinyMCEPopup.requireLangPack(); var LinkDialog = { preInit : function() { var url; if (url = tinyMCEPopup.getParam("external_link_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function() { var f = document.forms[0], ed = tinyMCEPopup.editor; // Setup browse button document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser', 'href', 'file', 'theme_advanced_link'); if (isVisible('hrefbrowser')) document.getElementById('href').style.width = '180px'; this.fillClassList('class_list'); this.fillFileList('link_list', 'tinyMCELinkList'); this.fillTargetList('target_list'); if (e = ed.dom.getParent(ed.selection.getNode(), 'A')) { f.href.value = ed.dom.getAttrib(e, 'href'); f.linktitle.value = ed.dom.getAttrib(e, 'title'); f.insert.value = ed.getLang('update'); selectByValue(f, 'link_list', f.href.value); selectByValue(f, 'target_list', ed.dom.getAttrib(e, 'target')); selectByValue(f, 'class_list', ed.dom.getAttrib(e, 'class')); } }, update : function() { var f = document.forms[0], ed = tinyMCEPopup.editor, e, b, href = f.href.value.replace(/ /g, '%20'); tinyMCEPopup.restoreSelection(); e = ed.dom.getParent(ed.selection.getNode(), 'A'); // Remove element if there is no href if (!f.href.value) { if (e) { b = ed.selection.getBookmark(); ed.dom.remove(e, 1); ed.selection.moveToBookmark(b); tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); return; } } // Create new anchor elements if (e == null) { ed.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); tinymce.each(ed.dom.select("a"), function(n) { if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { e = n; ed.dom.setAttribs(e, { href : href, title : f.linktitle.value, target : f.target_list ? getSelectValue(f, "target_list") : null, 'class' : f.class_list ? getSelectValue(f, "class_list") : null }); } }); } else { ed.dom.setAttribs(e, { href : href, title : f.linktitle.value }); if (f.target_list) { ed.dom.setAttrib(e, 'target', getSelectValue(f, "target_list")); } if (f.class_list) { ed.dom.setAttrib(e, 'class', getSelectValue(f, "class_list")); } } // Don't move caret if selection was image if (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') { ed.focus(); ed.selection.select(e); ed.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); }, checkPrefix : function(n) { if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_email'))) n.value = 'mailto:' + n.value; if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_external'))) n.value = 'http://' + n.value; }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillTargetList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v; lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_same'), '_self'); lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_blank'), '_blank'); if (v = tinyMCEPopup.getParam('theme_advanced_link_targets')) { tinymce.each(v.split(','), function(v) { v = v.split('='); lst.options[lst.options.length] = new Option(v[0], v[1]); }); } } }; LinkDialog.preInit(); tinyMCEPopup.onInit.add(LinkDialog.init, LinkDialog);
JavaScript
tinyMCEPopup.requireLangPack(); function init() { var ed, tcont; tinyMCEPopup.resizeToInnerSize(); ed = tinyMCEPopup.editor; // Give FF some time window.setTimeout(insertHelpIFrame, 10); tcont = document.getElementById('plugintablecontainer'); document.getElementById('plugins_tab').style.display = 'none'; var html = ""; html += '<table id="plugintable">'; html += '<thead>'; html += '<tr>'; html += '<td>' + ed.getLang('advanced_dlg.about_plugin') + '</td>'; html += '<td>' + ed.getLang('advanced_dlg.about_author') + '</td>'; html += '<td>' + ed.getLang('advanced_dlg.about_version') + '</td>'; html += '</tr>'; html += '</thead>'; html += '<tbody>'; tinymce.each(ed.plugins, function(p, n) { var info; if (!p.getInfo) return; html += '<tr>'; info = p.getInfo(); if (info.infourl != null && info.infourl != '') html += '<td width="50%" title="' + n + '"><a href="' + info.infourl + '" target="_blank">' + info.longname + '</a></td>'; else html += '<td width="50%" title="' + n + '">' + info.longname + '</td>'; if (info.authorurl != null && info.authorurl != '') html += '<td width="35%"><a href="' + info.authorurl + '" target="_blank">' + info.author + '</a></td>'; else html += '<td width="35%">' + info.author + '</td>'; html += '<td width="15%">' + info.version + '</td>'; html += '</tr>'; document.getElementById('plugins_tab').style.display = ''; }); html += '</tbody>'; html += '</table>'; tcont.innerHTML = html; tinyMCEPopup.dom.get('version').innerHTML = tinymce.majorVersion + "." + tinymce.minorVersion; tinyMCEPopup.dom.get('date').innerHTML = tinymce.releaseDate; } function insertHelpIFrame() { var html; if (tinyMCEPopup.getParam('docs_url')) { html = '<iframe width="100%" height="300" src="' + tinyMCEPopup.editor.baseURI.toAbsolute(tinyMCEPopup.getParam('docs_url')) + '"></iframe>'; document.getElementById('iframecontainer').innerHTML = html; document.getElementById('help_tab').style.display = 'block'; document.getElementById('help_tab').setAttribute("aria-hidden", "false"); } } tinyMCEPopup.onInit.add(init);
JavaScript
tinyMCEPopup.requireLangPack(); var detail = 50, strhex = "0123456789abcdef", i, isMouseDown = false, isMouseOver = false; var colors = [ "#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033", "#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099", "#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff", "#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033", "#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399", "#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff", "#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333", "#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399", "#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff", "#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633", "#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699", "#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff", "#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633", "#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999", "#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff", "#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933", "#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999", "#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff", "#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33", "#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99", "#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff", "#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33", "#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99", "#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff", "#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33", "#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99", "#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff" ]; var named = { '#F0F8FF':'Alice Blue','#FAEBD7':'Antique White','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige', '#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'Blanched Almond','#0000FF':'Blue','#8A2BE2':'Blue Violet','#A52A2A':'Brown', '#DEB887':'Burly Wood','#5F9EA0':'Cadet Blue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'Cornflower Blue', '#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'Dark Blue','#008B8B':'Dark Cyan','#B8860B':'Dark Golden Rod', '#A9A9A9':'Dark Gray','#A9A9A9':'Dark Grey','#006400':'Dark Green','#BDB76B':'Dark Khaki','#8B008B':'Dark Magenta','#556B2F':'Dark Olive Green', '#FF8C00':'Darkorange','#9932CC':'Dark Orchid','#8B0000':'Dark Red','#E9967A':'Dark Salmon','#8FBC8F':'Dark Sea Green','#483D8B':'Dark Slate Blue', '#2F4F4F':'Dark Slate Gray','#2F4F4F':'Dark Slate Grey','#00CED1':'Dark Turquoise','#9400D3':'Dark Violet','#FF1493':'Deep Pink','#00BFFF':'Deep Sky Blue', '#696969':'Dim Gray','#696969':'Dim Grey','#1E90FF':'Dodger Blue','#B22222':'Fire Brick','#FFFAF0':'Floral White','#228B22':'Forest Green', '#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'Ghost White','#FFD700':'Gold','#DAA520':'Golden Rod','#808080':'Gray','#808080':'Grey', '#008000':'Green','#ADFF2F':'Green Yellow','#F0FFF0':'Honey Dew','#FF69B4':'Hot Pink','#CD5C5C':'Indian Red','#4B0082':'Indigo','#FFFFF0':'Ivory', '#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'Lavender Blush','#7CFC00':'Lawn Green','#FFFACD':'Lemon Chiffon','#ADD8E6':'Light Blue', '#F08080':'Light Coral','#E0FFFF':'Light Cyan','#FAFAD2':'Light Golden Rod Yellow','#D3D3D3':'Light Gray','#D3D3D3':'Light Grey','#90EE90':'Light Green', '#FFB6C1':'Light Pink','#FFA07A':'Light Salmon','#20B2AA':'Light Sea Green','#87CEFA':'Light Sky Blue','#778899':'Light Slate Gray','#778899':'Light Slate Grey', '#B0C4DE':'Light Steel Blue','#FFFFE0':'Light Yellow','#00FF00':'Lime','#32CD32':'Lime Green','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon', '#66CDAA':'Medium Aqua Marine','#0000CD':'Medium Blue','#BA55D3':'Medium Orchid','#9370D8':'Medium Purple','#3CB371':'Medium Sea Green','#7B68EE':'Medium Slate Blue', '#00FA9A':'Medium Spring Green','#48D1CC':'Medium Turquoise','#C71585':'Medium Violet Red','#191970':'Midnight Blue','#F5FFFA':'Mint Cream','#FFE4E1':'Misty Rose','#FFE4B5':'Moccasin', '#FFDEAD':'Navajo White','#000080':'Navy','#FDF5E6':'Old Lace','#808000':'Olive','#6B8E23':'Olive Drab','#FFA500':'Orange','#FF4500':'Orange Red','#DA70D6':'Orchid', '#EEE8AA':'Pale Golden Rod','#98FB98':'Pale Green','#AFEEEE':'Pale Turquoise','#D87093':'Pale Violet Red','#FFEFD5':'Papaya Whip','#FFDAB9':'Peach Puff', '#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'Powder Blue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'Rosy Brown','#4169E1':'Royal Blue', '#8B4513':'Saddle Brown','#FA8072':'Salmon','#F4A460':'Sandy Brown','#2E8B57':'Sea Green','#FFF5EE':'Sea Shell','#A0522D':'Sienna','#C0C0C0':'Silver', '#87CEEB':'Sky Blue','#6A5ACD':'Slate Blue','#708090':'Slate Gray','#708090':'Slate Grey','#FFFAFA':'Snow','#00FF7F':'Spring Green', '#4682B4':'Steel Blue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet', '#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'White Smoke','#FFFF00':'Yellow','#9ACD32':'Yellow Green' }; var namedLookup = {}; function init() { var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color')), key, value; tinyMCEPopup.resizeToInnerSize(); generatePicker(); generateWebColors(); generateNamedColors(); if (inputColor) { changeFinalColor(inputColor); col = convertHexToRGB(inputColor); if (col) updateLight(col.r, col.g, col.b); } for (key in named) { value = named[key]; namedLookup[value.replace(/\s+/, '').toLowerCase()] = key.replace(/#/, '').toLowerCase(); } } function toHexColor(color) { var matches, red, green, blue, toInt = parseInt; function hex(value) { value = parseInt(value).toString(16); return value.length > 1 ? value : '0' + value; // Padd with leading zero }; color = tinymce.trim(color); color = color.replace(/^[#]/, '').toLowerCase(); // remove leading '#' color = namedLookup[color] || color; matches = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/.exec(color); if (matches) { red = toInt(matches[1]); green = toInt(matches[2]); blue = toInt(matches[3]); } else { matches = /^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(color); if (matches) { red = toInt(matches[1], 16); green = toInt(matches[2], 16); blue = toInt(matches[3], 16); } else { matches = /^([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(color); if (matches) { red = toInt(matches[1] + matches[1], 16); green = toInt(matches[2] + matches[2], 16); blue = toInt(matches[3] + matches[3], 16); } else { return ''; } } } return '#' + hex(red) + hex(green) + hex(blue); } function insertAction() { var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func'); var hexColor = toHexColor(color); if (hexColor === '') { var text = tinyMCEPopup.editor.getLang('advanced_dlg.invalid_color_value'); tinyMCEPopup.alert(text + ': ' + color); } else { tinyMCEPopup.restoreSelection(); if (f) f(hexColor); tinyMCEPopup.close(); } } function showColor(color, name) { if (name) document.getElementById("colorname").innerHTML = name; document.getElementById("preview").style.backgroundColor = color; document.getElementById("color").value = color.toUpperCase(); } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); if (!col) return col; var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return {r : r, g : g, b : b}; } return null; } function generatePicker() { var el = document.getElementById('light'), h = '', i; for (i = 0; i < detail; i++){ h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"' + ' onclick="changeFinalColor(this.style.backgroundColor)"' + ' onmousedown="isMouseDown = true; return false;"' + ' onmouseup="isMouseDown = false;"' + ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"' + ' onmouseover="isMouseOver = true;"' + ' onmouseout="isMouseOver = false;"' + '></div>'; } el.innerHTML = h; } function generateWebColors() { var el = document.getElementById('webcolors'), h = '', i; if (el.className == 'generated') return; // TODO: VoiceOver doesn't seem to support legend as a label referenced by labelledby. h += '<div role="listbox" aria-labelledby="webcolors_title" tabindex="0"><table role="presentation" border="0" cellspacing="1" cellpadding="0">' + '<tr>'; for (i=0; i<colors.length; i++) { h += '<td bgcolor="' + colors[i] + '" width="10" height="10">' + '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="web_colors_' + i + '" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');" style="display:block;width:10px;height:10px;overflow:hidden;">'; if (tinyMCEPopup.editor.forcedHighContrastMode) { h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>'; } h += '<span class="mceVoiceLabel" style="display:none;" id="web_colors_' + i + '">' + colors[i].toUpperCase() + '</span>'; h += '</a></td>'; if ((i+1) % 18 == 0) h += '</tr><tr>'; } h += '</table></div>'; el.innerHTML = h; el.className = 'generated'; paintCanvas(el); enableKeyboardNavigation(el.firstChild); } function paintCanvas(el) { tinyMCEPopup.getWin().tinymce.each(tinyMCEPopup.dom.select('canvas.mceColorSwatch', el), function(canvas) { var context; if (canvas.getContext && (context = canvas.getContext("2d"))) { context.fillStyle = canvas.getAttribute('data-color'); context.fillRect(0, 0, 10, 10); } }); } function generateNamedColors() { var el = document.getElementById('namedcolors'), h = '', n, v, i = 0; if (el.className == 'generated') return; for (n in named) { v = named[n]; h += '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="named_colors_' + i + '" onfocus="showColor(\'' + n + '\',\'' + v + '\');" onmouseover="showColor(\'' + n + '\',\'' + v + '\');" style="background-color: ' + n + '">'; if (tinyMCEPopup.editor.forcedHighContrastMode) { h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>'; } h += '<span class="mceVoiceLabel" style="display:none;" id="named_colors_' + i + '">' + v + '</span>'; h += '</a>'; i++; } el.innerHTML = h; el.className = 'generated'; paintCanvas(el); enableKeyboardNavigation(el); } function enableKeyboardNavigation(el) { tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', { root: el, items: tinyMCEPopup.dom.select('a', el) }, tinyMCEPopup.dom); } function dechex(n) { return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16); } function computeColor(e) { var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB, pos = tinyMCEPopup.dom.getPos(e.target); x = e.offsetX ? e.offsetX : (e.target ? e.clientX - pos.x : 0); y = e.offsetY ? e.offsetY : (e.target ? e.clientY - pos.y : 0); partWidth = document.getElementById('colors').width / 6; partDetail = detail / 2; imHeight = document.getElementById('colors').height; r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255; g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth); b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth); coef = (imHeight - y) / imHeight; r = 128 + (r - 128) * coef; g = 128 + (g - 128) * coef; b = 128 + (b - 128) * coef; changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b)); updateLight(r, g, b); } function updateLight(r, g, b) { var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color; for (i=0; i<detail; i++) { if ((i>=0) && (i<partDetail)) { finalCoef = i / partDetail; finalR = dechex(255 - (255 - r) * finalCoef); finalG = dechex(255 - (255 - g) * finalCoef); finalB = dechex(255 - (255 - b) * finalCoef); } else { finalCoef = 2 - i / partDetail; finalR = dechex(r * finalCoef); finalG = dechex(g * finalCoef); finalB = dechex(b * finalCoef); } color = finalR + finalG + finalB; setCol('gs' + i, '#'+color); } } function changeFinalColor(color) { if (color.indexOf('#') == -1) color = convertRGBToHex(color); setCol('preview', color); document.getElementById('color').value = color; } function setCol(e, c) { try { document.getElementById(e).style.backgroundColor = c; } catch (ex) { // Ignore IE warning } } tinyMCEPopup.onInit.add(init);
JavaScript
tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(onLoadInit); function saveContent() { tinyMCEPopup.editor.setContent(document.getElementById('htmlSource').value, {source_view : true}); tinyMCEPopup.close(); } function onLoadInit() { tinyMCEPopup.resizeToInnerSize(); // Remove Gecko spellchecking if (tinymce.isGecko) document.body.spellcheck = tinyMCEPopup.editor.getParam("gecko_spellcheck"); document.getElementById('htmlSource').value = tinyMCEPopup.editor.getContent({source_view : true}); if (tinyMCEPopup.editor.getParam("theme_advanced_source_editor_wrap", true)) { turnWrapOn(); document.getElementById('wraped').checked = true; } resizeInputs(); } function setWrap(val) { var v, n, s = document.getElementById('htmlSource'); s.wrap = val; if (!tinymce.isIE) { v = s.value; n = s.cloneNode(false); n.setAttribute("wrap", val); s.parentNode.replaceChild(n, s); n.value = v; } } function setWhiteSpaceCss(value) { var el = document.getElementById('htmlSource'); tinymce.DOM.setStyle(el, 'white-space', value); } function turnWrapOff() { if (tinymce.isWebKit) { setWhiteSpaceCss('pre'); } else { setWrap('off'); } } function turnWrapOn() { if (tinymce.isWebKit) { setWhiteSpaceCss('pre-wrap'); } else { setWrap('soft'); } } function toggleWordWrap(elm) { if (elm.checked) { turnWrapOn(); } else { turnWrapOff(); } } function resizeInputs() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('htmlSource'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 65) + 'px'; } }
JavaScript
var ImageDialog = { preInit : function() { var url; tinyMCEPopup.requireLangPack(); if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function() { var f = document.forms[0], ed = tinyMCEPopup.editor; // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '180px'; e = ed.selection.getNode(); this.fillFileList('image_list', tinyMCEPopup.getParam('external_image_list', 'tinyMCEImageList')); if (e.nodeName == 'IMG') { f.src.value = ed.dom.getAttrib(e, 'src'); f.alt.value = ed.dom.getAttrib(e, 'alt'); f.border.value = this.getAttrib(e, 'border'); f.vspace.value = this.getAttrib(e, 'vspace'); f.hspace.value = this.getAttrib(e, 'hspace'); f.width.value = ed.dom.getAttrib(e, 'width'); f.height.value = ed.dom.getAttrib(e, 'height'); f.insert.value = ed.getLang('update'); this.styleVal = ed.dom.getAttrib(e, 'style'); selectByValue(f, 'image_list', f.src.value); selectByValue(f, 'align', this.getAttrib(e, 'align')); this.updateStyle(); } }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = typeof(l) === 'function' ? l() : window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, update : function() { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el; tinyMCEPopup.restoreSelection(); if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (!ed.settings.inline_styles) { args = tinymce.extend(args, { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }); } else args.style = this.styleVal; tinymce.extend(args, { src : f.src.value.replace(/ /g, '%20'), alt : f.alt.value, width : f.width.value, height : f.height.value }); el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); tinyMCEPopup.editor.execCommand('mceRepaint'); tinyMCEPopup.editor.focus(); } else { tinymce.each(args, function(value, name) { if (value === "") { delete args[name]; } }); ed.execCommand('mceInsertContent', false, tinyMCEPopup.editor.dom.createHTML('img', args), {skip_undo : 1}); ed.undoManager.add(); } tinyMCEPopup.close(); }, updateStyle : function() { var dom = tinyMCEPopup.dom, st = {}, v, f = document.forms[0]; if (tinyMCEPopup.editor.settings.inline_styles) { tinymce.each(tinyMCEPopup.dom.parseStyle(this.styleVal), function(value, key) { st[key] = value; }); // Handle align v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') { st['float'] = v; delete st['vertical-align']; } else { st['vertical-align'] = v; delete st['float']; } } else { delete st['float']; delete st['vertical-align']; } // Handle border v = f.border.value; if (v || v == '0') { if (v == '0') st['border'] = '0'; else st['border'] = v + 'px solid black'; } else delete st['border']; // Handle hspace v = f.hspace.value; if (v) { delete st['margin']; st['margin-left'] = v + 'px'; st['margin-right'] = v + 'px'; } else { delete st['margin-left']; delete st['margin-right']; } // Handle vspace v = f.vspace.value; if (v) { delete st['margin']; st['margin-top'] = v + 'px'; st['margin-bottom'] = v + 'px'; } else { delete st['margin-top']; delete st['margin-bottom']; } // Merge st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st), 'img'); this.styleVal = dom.serializeStyle(st, 'img'); } }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, resetImageData : function() { var f = document.forms[0]; f.width.value = f.height.value = ""; }, updateImageData : function() { var f = document.forms[0], t = ImageDialog; if (f.width.value == "") f.width.value = t.preloadImg.width; if (f.height.value == "") f.height.value = t.preloadImg.height; }, getImageData : function() { var f = document.forms[0]; this.preloadImg = new Image(); this.preloadImg.onload = this.updateImageData; this.preloadImg.onerror = this.resetImageData; this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value); } }; ImageDialog.preInit(); tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
JavaScript
tinyMCEPopup.requireLangPack(); var AnchorDialog = { init : function(ed) { var action, elm, f = document.forms[0]; this.editor = ed; elm = ed.dom.getParent(ed.selection.getNode(), 'A'); v = ed.dom.getAttrib(elm, 'name') || ed.dom.getAttrib(elm, 'id'); if (v) { this.action = 'update'; f.anchorName.value = v; } f.insert.value = ed.getLang(elm ? 'update' : 'insert'); }, update : function() { var ed = this.editor, elm, name = document.forms[0].anchorName.value, attribName; if (!name || !/^[a-z][a-z0-9\-\_:\.]*$/i.test(name)) { tinyMCEPopup.alert('advanced_dlg.anchor_invalid'); return; } tinyMCEPopup.restoreSelection(); if (this.action != 'update') ed.selection.collapse(1); var aRule = ed.schema.getElementRule('a'); if (!aRule || aRule.attributes.name) { attribName = 'name'; } else { attribName = 'id'; } elm = ed.dom.getParent(ed.selection.getNode(), 'A'); if (elm) { elm.setAttribute(attribName, name); elm[attribName] = name; ed.undoManager.add(); } else { // create with zero-sized nbsp so that in Webkit where anchor is on last line by itself caret cannot be placed after it var attrs = {'class' : 'mceItemAnchor'}; attrs[attribName] = name; ed.execCommand('mceInsertContent', 0, ed.dom.createHTML('a', attrs, '\uFEFF')); ed.nodeChanged(); } tinyMCEPopup.close(); } }; tinyMCEPopup.onInit.add(AnchorDialog.init, AnchorDialog);
JavaScript
/** * charmap.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ tinyMCEPopup.requireLangPack(); var charmap = [ ['&nbsp;', '&#160;', true, 'no-break space'], ['&amp;', '&#38;', true, 'ampersand'], ['&quot;', '&#34;', true, 'quotation mark'], // finance ['&cent;', '&#162;', true, 'cent sign'], ['&euro;', '&#8364;', true, 'euro sign'], ['&pound;', '&#163;', true, 'pound sign'], ['&yen;', '&#165;', true, 'yen sign'], // signs ['&copy;', '&#169;', true, 'copyright sign'], ['&reg;', '&#174;', true, 'registered sign'], ['&trade;', '&#8482;', true, 'trade mark sign'], ['&permil;', '&#8240;', true, 'per mille sign'], ['&micro;', '&#181;', true, 'micro sign'], ['&middot;', '&#183;', true, 'middle dot'], ['&bull;', '&#8226;', true, 'bullet'], ['&hellip;', '&#8230;', true, 'three dot leader'], ['&prime;', '&#8242;', true, 'minutes / feet'], ['&Prime;', '&#8243;', true, 'seconds / inches'], ['&sect;', '&#167;', true, 'section sign'], ['&para;', '&#182;', true, 'paragraph sign'], ['&szlig;', '&#223;', true, 'sharp s / ess-zed'], // quotations ['&lsaquo;', '&#8249;', true, 'single left-pointing angle quotation mark'], ['&rsaquo;', '&#8250;', true, 'single right-pointing angle quotation mark'], ['&laquo;', '&#171;', true, 'left pointing guillemet'], ['&raquo;', '&#187;', true, 'right pointing guillemet'], ['&lsquo;', '&#8216;', true, 'left single quotation mark'], ['&rsquo;', '&#8217;', true, 'right single quotation mark'], ['&ldquo;', '&#8220;', true, 'left double quotation mark'], ['&rdquo;', '&#8221;', true, 'right double quotation mark'], ['&sbquo;', '&#8218;', true, 'single low-9 quotation mark'], ['&bdquo;', '&#8222;', true, 'double low-9 quotation mark'], ['&lt;', '&#60;', true, 'less-than sign'], ['&gt;', '&#62;', true, 'greater-than sign'], ['&le;', '&#8804;', true, 'less-than or equal to'], ['&ge;', '&#8805;', true, 'greater-than or equal to'], ['&ndash;', '&#8211;', true, 'en dash'], ['&mdash;', '&#8212;', true, 'em dash'], ['&macr;', '&#175;', true, 'macron'], ['&oline;', '&#8254;', true, 'overline'], ['&curren;', '&#164;', true, 'currency sign'], ['&brvbar;', '&#166;', true, 'broken bar'], ['&uml;', '&#168;', true, 'diaeresis'], ['&iexcl;', '&#161;', true, 'inverted exclamation mark'], ['&iquest;', '&#191;', true, 'turned question mark'], ['&circ;', '&#710;', true, 'circumflex accent'], ['&tilde;', '&#732;', true, 'small tilde'], ['&deg;', '&#176;', true, 'degree sign'], ['&minus;', '&#8722;', true, 'minus sign'], ['&plusmn;', '&#177;', true, 'plus-minus sign'], ['&divide;', '&#247;', true, 'division sign'], ['&frasl;', '&#8260;', true, 'fraction slash'], ['&times;', '&#215;', true, 'multiplication sign'], ['&sup1;', '&#185;', true, 'superscript one'], ['&sup2;', '&#178;', true, 'superscript two'], ['&sup3;', '&#179;', true, 'superscript three'], ['&frac14;', '&#188;', true, 'fraction one quarter'], ['&frac12;', '&#189;', true, 'fraction one half'], ['&frac34;', '&#190;', true, 'fraction three quarters'], // math / logical ['&fnof;', '&#402;', true, 'function / florin'], ['&int;', '&#8747;', true, 'integral'], ['&sum;', '&#8721;', true, 'n-ary sumation'], ['&infin;', '&#8734;', true, 'infinity'], ['&radic;', '&#8730;', true, 'square root'], ['&sim;', '&#8764;', false,'similar to'], ['&cong;', '&#8773;', false,'approximately equal to'], ['&asymp;', '&#8776;', true, 'almost equal to'], ['&ne;', '&#8800;', true, 'not equal to'], ['&equiv;', '&#8801;', true, 'identical to'], ['&isin;', '&#8712;', false,'element of'], ['&notin;', '&#8713;', false,'not an element of'], ['&ni;', '&#8715;', false,'contains as member'], ['&prod;', '&#8719;', true, 'n-ary product'], ['&and;', '&#8743;', false,'logical and'], ['&or;', '&#8744;', false,'logical or'], ['&not;', '&#172;', true, 'not sign'], ['&cap;', '&#8745;', true, 'intersection'], ['&cup;', '&#8746;', false,'union'], ['&part;', '&#8706;', true, 'partial differential'], ['&forall;', '&#8704;', false,'for all'], ['&exist;', '&#8707;', false,'there exists'], ['&empty;', '&#8709;', false,'diameter'], ['&nabla;', '&#8711;', false,'backward difference'], ['&lowast;', '&#8727;', false,'asterisk operator'], ['&prop;', '&#8733;', false,'proportional to'], ['&ang;', '&#8736;', false,'angle'], // undefined ['&acute;', '&#180;', true, 'acute accent'], ['&cedil;', '&#184;', true, 'cedilla'], ['&ordf;', '&#170;', true, 'feminine ordinal indicator'], ['&ordm;', '&#186;', true, 'masculine ordinal indicator'], ['&dagger;', '&#8224;', true, 'dagger'], ['&Dagger;', '&#8225;', true, 'double dagger'], // alphabetical special chars ['&Agrave;', '&#192;', true, 'A - grave'], ['&Aacute;', '&#193;', true, 'A - acute'], ['&Acirc;', '&#194;', true, 'A - circumflex'], ['&Atilde;', '&#195;', true, 'A - tilde'], ['&Auml;', '&#196;', true, 'A - diaeresis'], ['&Aring;', '&#197;', true, 'A - ring above'], ['&AElig;', '&#198;', true, 'ligature AE'], ['&Ccedil;', '&#199;', true, 'C - cedilla'], ['&Egrave;', '&#200;', true, 'E - grave'], ['&Eacute;', '&#201;', true, 'E - acute'], ['&Ecirc;', '&#202;', true, 'E - circumflex'], ['&Euml;', '&#203;', true, 'E - diaeresis'], ['&Igrave;', '&#204;', true, 'I - grave'], ['&Iacute;', '&#205;', true, 'I - acute'], ['&Icirc;', '&#206;', true, 'I - circumflex'], ['&Iuml;', '&#207;', true, 'I - diaeresis'], ['&ETH;', '&#208;', true, 'ETH'], ['&Ntilde;', '&#209;', true, 'N - tilde'], ['&Ograve;', '&#210;', true, 'O - grave'], ['&Oacute;', '&#211;', true, 'O - acute'], ['&Ocirc;', '&#212;', true, 'O - circumflex'], ['&Otilde;', '&#213;', true, 'O - tilde'], ['&Ouml;', '&#214;', true, 'O - diaeresis'], ['&Oslash;', '&#216;', true, 'O - slash'], ['&OElig;', '&#338;', true, 'ligature OE'], ['&Scaron;', '&#352;', true, 'S - caron'], ['&Ugrave;', '&#217;', true, 'U - grave'], ['&Uacute;', '&#218;', true, 'U - acute'], ['&Ucirc;', '&#219;', true, 'U - circumflex'], ['&Uuml;', '&#220;', true, 'U - diaeresis'], ['&Yacute;', '&#221;', true, 'Y - acute'], ['&Yuml;', '&#376;', true, 'Y - diaeresis'], ['&THORN;', '&#222;', true, 'THORN'], ['&agrave;', '&#224;', true, 'a - grave'], ['&aacute;', '&#225;', true, 'a - acute'], ['&acirc;', '&#226;', true, 'a - circumflex'], ['&atilde;', '&#227;', true, 'a - tilde'], ['&auml;', '&#228;', true, 'a - diaeresis'], ['&aring;', '&#229;', true, 'a - ring above'], ['&aelig;', '&#230;', true, 'ligature ae'], ['&ccedil;', '&#231;', true, 'c - cedilla'], ['&egrave;', '&#232;', true, 'e - grave'], ['&eacute;', '&#233;', true, 'e - acute'], ['&ecirc;', '&#234;', true, 'e - circumflex'], ['&euml;', '&#235;', true, 'e - diaeresis'], ['&igrave;', '&#236;', true, 'i - grave'], ['&iacute;', '&#237;', true, 'i - acute'], ['&icirc;', '&#238;', true, 'i - circumflex'], ['&iuml;', '&#239;', true, 'i - diaeresis'], ['&eth;', '&#240;', true, 'eth'], ['&ntilde;', '&#241;', true, 'n - tilde'], ['&ograve;', '&#242;', true, 'o - grave'], ['&oacute;', '&#243;', true, 'o - acute'], ['&ocirc;', '&#244;', true, 'o - circumflex'], ['&otilde;', '&#245;', true, 'o - tilde'], ['&ouml;', '&#246;', true, 'o - diaeresis'], ['&oslash;', '&#248;', true, 'o slash'], ['&oelig;', '&#339;', true, 'ligature oe'], ['&scaron;', '&#353;', true, 's - caron'], ['&ugrave;', '&#249;', true, 'u - grave'], ['&uacute;', '&#250;', true, 'u - acute'], ['&ucirc;', '&#251;', true, 'u - circumflex'], ['&uuml;', '&#252;', true, 'u - diaeresis'], ['&yacute;', '&#253;', true, 'y - acute'], ['&thorn;', '&#254;', true, 'thorn'], ['&yuml;', '&#255;', true, 'y - diaeresis'], ['&Alpha;', '&#913;', true, 'Alpha'], ['&Beta;', '&#914;', true, 'Beta'], ['&Gamma;', '&#915;', true, 'Gamma'], ['&Delta;', '&#916;', true, 'Delta'], ['&Epsilon;', '&#917;', true, 'Epsilon'], ['&Zeta;', '&#918;', true, 'Zeta'], ['&Eta;', '&#919;', true, 'Eta'], ['&Theta;', '&#920;', true, 'Theta'], ['&Iota;', '&#921;', true, 'Iota'], ['&Kappa;', '&#922;', true, 'Kappa'], ['&Lambda;', '&#923;', true, 'Lambda'], ['&Mu;', '&#924;', true, 'Mu'], ['&Nu;', '&#925;', true, 'Nu'], ['&Xi;', '&#926;', true, 'Xi'], ['&Omicron;', '&#927;', true, 'Omicron'], ['&Pi;', '&#928;', true, 'Pi'], ['&Rho;', '&#929;', true, 'Rho'], ['&Sigma;', '&#931;', true, 'Sigma'], ['&Tau;', '&#932;', true, 'Tau'], ['&Upsilon;', '&#933;', true, 'Upsilon'], ['&Phi;', '&#934;', true, 'Phi'], ['&Chi;', '&#935;', true, 'Chi'], ['&Psi;', '&#936;', true, 'Psi'], ['&Omega;', '&#937;', true, 'Omega'], ['&alpha;', '&#945;', true, 'alpha'], ['&beta;', '&#946;', true, 'beta'], ['&gamma;', '&#947;', true, 'gamma'], ['&delta;', '&#948;', true, 'delta'], ['&epsilon;', '&#949;', true, 'epsilon'], ['&zeta;', '&#950;', true, 'zeta'], ['&eta;', '&#951;', true, 'eta'], ['&theta;', '&#952;', true, 'theta'], ['&iota;', '&#953;', true, 'iota'], ['&kappa;', '&#954;', true, 'kappa'], ['&lambda;', '&#955;', true, 'lambda'], ['&mu;', '&#956;', true, 'mu'], ['&nu;', '&#957;', true, 'nu'], ['&xi;', '&#958;', true, 'xi'], ['&omicron;', '&#959;', true, 'omicron'], ['&pi;', '&#960;', true, 'pi'], ['&rho;', '&#961;', true, 'rho'], ['&sigmaf;', '&#962;', true, 'final sigma'], ['&sigma;', '&#963;', true, 'sigma'], ['&tau;', '&#964;', true, 'tau'], ['&upsilon;', '&#965;', true, 'upsilon'], ['&phi;', '&#966;', true, 'phi'], ['&chi;', '&#967;', true, 'chi'], ['&psi;', '&#968;', true, 'psi'], ['&omega;', '&#969;', true, 'omega'], // symbols ['&alefsym;', '&#8501;', false,'alef symbol'], ['&piv;', '&#982;', false,'pi symbol'], ['&real;', '&#8476;', false,'real part symbol'], ['&thetasym;','&#977;', false,'theta symbol'], ['&upsih;', '&#978;', false,'upsilon - hook symbol'], ['&weierp;', '&#8472;', false,'Weierstrass p'], ['&image;', '&#8465;', false,'imaginary part'], // arrows ['&larr;', '&#8592;', true, 'leftwards arrow'], ['&uarr;', '&#8593;', true, 'upwards arrow'], ['&rarr;', '&#8594;', true, 'rightwards arrow'], ['&darr;', '&#8595;', true, 'downwards arrow'], ['&harr;', '&#8596;', true, 'left right arrow'], ['&crarr;', '&#8629;', false,'carriage return'], ['&lArr;', '&#8656;', false,'leftwards double arrow'], ['&uArr;', '&#8657;', false,'upwards double arrow'], ['&rArr;', '&#8658;', false,'rightwards double arrow'], ['&dArr;', '&#8659;', false,'downwards double arrow'], ['&hArr;', '&#8660;', false,'left right double arrow'], ['&there4;', '&#8756;', false,'therefore'], ['&sub;', '&#8834;', false,'subset of'], ['&sup;', '&#8835;', false,'superset of'], ['&nsub;', '&#8836;', false,'not a subset of'], ['&sube;', '&#8838;', false,'subset of or equal to'], ['&supe;', '&#8839;', false,'superset of or equal to'], ['&oplus;', '&#8853;', false,'circled plus'], ['&otimes;', '&#8855;', false,'circled times'], ['&perp;', '&#8869;', false,'perpendicular'], ['&sdot;', '&#8901;', false,'dot operator'], ['&lceil;', '&#8968;', false,'left ceiling'], ['&rceil;', '&#8969;', false,'right ceiling'], ['&lfloor;', '&#8970;', false,'left floor'], ['&rfloor;', '&#8971;', false,'right floor'], ['&lang;', '&#9001;', false,'left-pointing angle bracket'], ['&rang;', '&#9002;', false,'right-pointing angle bracket'], ['&loz;', '&#9674;', true, 'lozenge'], ['&spades;', '&#9824;', true, 'black spade suit'], ['&clubs;', '&#9827;', true, 'black club suit'], ['&hearts;', '&#9829;', true, 'black heart suit'], ['&diams;', '&#9830;', true, 'black diamond suit'], ['&ensp;', '&#8194;', false,'en space'], ['&emsp;', '&#8195;', false,'em space'], ['&thinsp;', '&#8201;', false,'thin space'], ['&zwnj;', '&#8204;', false,'zero width non-joiner'], ['&zwj;', '&#8205;', false,'zero width joiner'], ['&lrm;', '&#8206;', false,'left-to-right mark'], ['&rlm;', '&#8207;', false,'right-to-left mark'], ['&shy;', '&#173;', false,'soft hyphen'] ]; tinyMCEPopup.onInit.add(function() { tinyMCEPopup.dom.setHTML('charmapView', renderCharMapHTML()); addKeyboardNavigation(); }); function addKeyboardNavigation(){ var tableElm, cells, settings; cells = tinyMCEPopup.dom.select("a.charmaplink", "charmapgroup"); settings ={ root: "charmapgroup", items: cells }; cells[0].tabindex=0; tinyMCEPopup.dom.addClass(cells[0], "mceFocus"); if (tinymce.isGecko) { cells[0].focus(); } else { setTimeout(function(){ cells[0].focus(); }, 100); } tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', settings, tinyMCEPopup.dom); } function renderCharMapHTML() { var charsPerRow = 20, tdWidth=20, tdHeight=20, i; var html = '<div id="charmapgroup" aria-labelledby="charmap_label" tabindex="0" role="listbox">'+ '<table role="presentation" border="0" cellspacing="1" cellpadding="0" width="' + (tdWidth*charsPerRow) + '"><tr height="' + tdHeight + '">'; var cols=-1; for (i=0; i<charmap.length; i++) { var previewCharFn; if (charmap[i][2]==true) { cols++; previewCharFn = 'previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');'; html += '' + '<td class="charmap">' + '<a class="charmaplink" role="button" onmouseover="'+previewCharFn+'" onfocus="'+previewCharFn+'" href="javascript:void(0)" onclick="insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');" onclick="return false;" onmousedown="return false;" title="' + charmap[i][3] + ' '+ tinyMCEPopup.editor.translate("advanced_dlg.charmap_usage")+'">' + charmap[i][1] + '</a></td>'; if ((cols+1) % charsPerRow == 0) html += '</tr><tr height="' + tdHeight + '">'; } } if (cols % charsPerRow > 0) { var padd = charsPerRow - (cols % charsPerRow); for (var i=0; i<padd-1; i++) html += '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap">&nbsp;</td>'; } html += '</tr></table></div>'; html = html.replace(/<tr height="20"><\/tr>/g, ''); return html; } function insertChar(chr) { tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';'); // Refocus in window if (tinyMCEPopup.isWindow) window.focus(); tinyMCEPopup.editor.focus(); tinyMCEPopup.close(); } function previewChar(codeA, codeB, codeN) { var elmA = document.getElementById('codeA'); var elmB = document.getElementById('codeB'); var elmV = document.getElementById('codeV'); var elmN = document.getElementById('codeN'); if (codeA=='#160;') { elmV.innerHTML = '__'; } else { elmV.innerHTML = '&' + codeA; } elmB.innerHTML = '&amp;' + codeA; elmA.innerHTML = '&amp;' + codeB; elmN.innerHTML = codeN; }
JavaScript
/** * editor_template_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, Cookie = tinymce.util.Cookie, lastExtID, explode = tinymce.explode; // Generates a preview for a format function getPreviewCss(ed, fmt) { var name, previewElm, dom = ed.dom, previewCss = '', parentFontSize, previewStylesName; previewStyles = ed.settings.preview_styles; // No preview forced if (previewStyles === false) return ''; // Default preview if (!previewStyles) previewStyles = 'font-family font-size font-weight text-decoration text-transform color background-color'; // Removes any variables since these can't be previewed function removeVars(val) { return val.replace(/%(\w+)/g, ''); }; // Create block/inline element to use for preview name = fmt.block || fmt.inline || 'span'; previewElm = dom.create(name); // Add format styles to preview element each(fmt.styles, function(value, name) { value = removeVars(value); if (value) dom.setStyle(previewElm, name, value); }); // Add attributes to preview element each(fmt.attributes, function(value, name) { value = removeVars(value); if (value) dom.setAttrib(previewElm, name, value); }); // Add classes to preview element each(fmt.classes, function(value) { value = removeVars(value); if (!dom.hasClass(previewElm, value)) dom.addClass(previewElm, value); }); // Add the previewElm outside the visual area dom.setStyles(previewElm, {position: 'absolute', left: -0xFFFF}); ed.getBody().appendChild(previewElm); // Get parent container font size so we can compute px values out of em/% for older IE:s parentFontSize = dom.getStyle(ed.getBody(), 'fontSize', true); parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0; each(previewStyles.split(' '), function(name) { var value = dom.getStyle(previewElm, name, true); // If background is transparent then check if the body has a background color we can use if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) { value = dom.getStyle(ed.getBody(), name, true); // Ignore white since it's the default color, not the nicest fix if (dom.toHex(value).toLowerCase() == '#ffffff') { return; } } // Old IE won't calculate the font size so we need to do that manually if (name == 'font-size') { if (/em|%$/.test(value)) { if (parentFontSize === 0) { return; } // Convert font size from em/% to px value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1); value = (value * parentFontSize) + 'px'; } } previewCss += name + ':' + value + ';'; }); dom.remove(previewElm); return previewCss; }; // Tell it to load theme specific language pack(s) tinymce.ThemeManager.requireLangPack('advanced'); tinymce.create('tinymce.themes.AdvancedTheme', { sizes : [8, 10, 12, 14, 18, 24, 36], // Control name lookup, format: title, command controls : { bold : ['bold_desc', 'Bold'], italic : ['italic_desc', 'Italic'], underline : ['underline_desc', 'Underline'], strikethrough : ['striketrough_desc', 'Strikethrough'], justifyleft : ['justifyleft_desc', 'JustifyLeft'], justifycenter : ['justifycenter_desc', 'JustifyCenter'], justifyright : ['justifyright_desc', 'JustifyRight'], justifyfull : ['justifyfull_desc', 'JustifyFull'], bullist : ['bullist_desc', 'InsertUnorderedList'], numlist : ['numlist_desc', 'InsertOrderedList'], outdent : ['outdent_desc', 'Outdent'], indent : ['indent_desc', 'Indent'], cut : ['cut_desc', 'Cut'], copy : ['copy_desc', 'Copy'], paste : ['paste_desc', 'Paste'], undo : ['undo_desc', 'Undo'], redo : ['redo_desc', 'Redo'], link : ['link_desc', 'mceLink'], unlink : ['unlink_desc', 'unlink'], image : ['image_desc', 'mceImage'], cleanup : ['cleanup_desc', 'mceCleanup'], help : ['help_desc', 'mceHelp'], code : ['code_desc', 'mceCodeEditor'], hr : ['hr_desc', 'InsertHorizontalRule'], removeformat : ['removeformat_desc', 'RemoveFormat'], sub : ['sub_desc', 'subscript'], sup : ['sup_desc', 'superscript'], forecolor : ['forecolor_desc', 'ForeColor'], forecolorpicker : ['forecolor_desc', 'mceForeColor'], backcolor : ['backcolor_desc', 'HiliteColor'], backcolorpicker : ['backcolor_desc', 'mceBackColor'], charmap : ['charmap_desc', 'mceCharMap'], visualaid : ['visualaid_desc', 'mceToggleVisualAid'], anchor : ['anchor_desc', 'mceInsertAnchor'], newdocument : ['newdocument_desc', 'mceNewDocument'], blockquote : ['blockquote_desc', 'mceBlockQuote'] }, stateControls : ['bold', 'italic', 'underline', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'sub', 'sup', 'blockquote'], init : function(ed, url) { var t = this, s, v, o; t.editor = ed; t.url = url; t.onResolveName = new tinymce.util.Dispatcher(this); s = ed.settings; ed.forcedHighContrastMode = ed.settings.detect_highcontrast && t._isHighContrast(); ed.settings.skin = ed.forcedHighContrastMode ? 'highcontrast' : ed.settings.skin; // Setup default buttons if (!s.theme_advanced_buttons1) { s = extend({ theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect", theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code", theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap" }, s); } // Default settings t.settings = s = extend({ theme_advanced_path : true, theme_advanced_toolbar_location : 'top', theme_advanced_blockformats : "p,address,pre,h1,h2,h3,h4,h5,h6", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats", theme_advanced_more_colors : 1, theme_advanced_row_height : 23, theme_advanced_resize_horizontal : 1, theme_advanced_resizing_use_cookie : 1, theme_advanced_font_sizes : "1,2,3,4,5,6,7", theme_advanced_font_selector : "span", theme_advanced_show_current_color: 0, readonly : ed.settings.readonly }, s); // Setup default font_size_style_values if (!s.font_size_style_values) s.font_size_style_values = "8pt,10pt,12pt,14pt,18pt,24pt,36pt"; if (tinymce.is(s.theme_advanced_font_sizes, 'string')) { s.font_size_style_values = tinymce.explode(s.font_size_style_values); s.font_size_classes = tinymce.explode(s.font_size_classes || ''); // Parse string value o = {}; ed.settings.theme_advanced_font_sizes = s.theme_advanced_font_sizes; each(ed.getParam('theme_advanced_font_sizes', '', 'hash'), function(v, k) { var cl; if (k == v && v >= 1 && v <= 7) { k = v + ' (' + t.sizes[v - 1] + 'pt)'; cl = s.font_size_classes[v - 1]; v = s.font_size_style_values[v - 1] || (t.sizes[v - 1] + 'pt'); } if (/^\s*\./.test(v)) cl = v.replace(/\./g, ''); o[k] = cl ? {'class' : cl} : {fontSize : v}; }); s.theme_advanced_font_sizes = o; } if ((v = s.theme_advanced_path_location) && v != 'none') s.theme_advanced_statusbar_location = s.theme_advanced_path_location; if (s.theme_advanced_statusbar_location == 'none') s.theme_advanced_statusbar_location = 0; if (ed.settings.content_css !== false) ed.contentCSS.push(ed.baseURI.toAbsolute(url + "/skins/" + ed.settings.skin + "/content.css")); // Init editor ed.onInit.add(function() { if (!ed.settings.readonly) { ed.onNodeChange.add(t._nodeChanged, t); ed.onKeyUp.add(t._updateUndoStatus, t); ed.onMouseUp.add(t._updateUndoStatus, t); ed.dom.bind(ed.dom.getRoot(), 'dragend', function() { t._updateUndoStatus(ed); }); } }); ed.onSetProgressState.add(function(ed, b, ti) { var co, id = ed.id, tb; if (b) { t.progressTimer = setTimeout(function() { co = ed.getContainer(); co = co.insertBefore(DOM.create('DIV', {style : 'position:relative'}), co.firstChild); tb = DOM.get(ed.id + '_tbl'); DOM.add(co, 'div', {id : id + '_blocker', 'class' : 'mceBlocker', style : {width : tb.clientWidth + 2, height : tb.clientHeight + 2}}); DOM.add(co, 'div', {id : id + '_progress', 'class' : 'mceProgress', style : {left : tb.clientWidth / 2, top : tb.clientHeight / 2}}); }, ti || 0); } else { DOM.remove(id + '_blocker'); DOM.remove(id + '_progress'); clearTimeout(t.progressTimer); } }); DOM.loadCSS(s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : url + "/skins/" + ed.settings.skin + "/ui.css"); if (s.skin_variant) DOM.loadCSS(url + "/skins/" + ed.settings.skin + "/ui_" + s.skin_variant + ".css"); }, _isHighContrast : function() { var actualColor, div = DOM.add(DOM.getRoot(), 'div', {'style': 'background-color: rgb(171,239,86);'}); actualColor = (DOM.getStyle(div, 'background-color', true) + '').toLowerCase().replace(/ /g, ''); DOM.remove(div); return actualColor != 'rgb(171,239,86)' && actualColor != '#abef56'; }, createControl : function(n, cf) { var cd, c; if (c = cf.createControl(n)) return c; switch (n) { case "styleselect": return this._createStyleSelect(); case "formatselect": return this._createBlockFormats(); case "fontselect": return this._createFontSelect(); case "fontsizeselect": return this._createFontSizeSelect(); case "forecolor": return this._createForeColorMenu(); case "backcolor": return this._createBackColorMenu(); } if ((cd = this.controls[n])) return cf.createButton(n, {title : "advanced." + cd[0], cmd : cd[1], ui : cd[2], value : cd[3]}); }, execCommand : function(cmd, ui, val) { var f = this['_' + cmd]; if (f) { f.call(this, ui, val); return true; } return false; }, _importClasses : function(e) { var ed = this.editor, ctrl = ed.controlManager.get('styleselect'); if (ctrl.getLength() == 0) { each(ed.dom.getClasses(), function(o, idx) { var name = 'style_' + idx, fmt; fmt = { inline : 'span', attributes : {'class' : o['class']}, selector : '*' }; ed.formatter.register(name, fmt); ctrl.add(o['class'], name, { style: function() { return getPreviewCss(ed, fmt); } }); }); } }, _createStyleSelect : function(n) { var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl; // Setup style select box ctrl = ctrlMan.createListBox('styleselect', { title : 'advanced.style_select', onselect : function(name) { var matches, formatNames = [], removedFormat; each(ctrl.items, function(item) { formatNames.push(item.value); }); ed.focus(); ed.undoManager.add(); // Toggle off the current format(s) matches = ed.formatter.matchAll(formatNames); tinymce.each(matches, function(match) { if (!name || match == name) { if (match) ed.formatter.remove(match); removedFormat = true; } }); if (!removedFormat) ed.formatter.apply(name); ed.undoManager.add(); ed.nodeChanged(); return false; // No auto select } }); // Handle specified format ed.onPreInit.add(function() { var counter = 0, formats = ed.getParam('style_formats'); if (formats) { each(formats, function(fmt) { var name, keys = 0; each(fmt, function() {keys++;}); if (keys > 1) { name = fmt.name = fmt.name || 'style_' + (counter++); ed.formatter.register(name, fmt); ctrl.add(fmt.title, name, { style: function() { return getPreviewCss(ed, fmt); } }); } else ctrl.add(fmt.title); }); } else { each(ed.getParam('theme_advanced_styles', '', 'hash'), function(val, key) { var name, fmt; if (val) { name = 'style_' + (counter++); fmt = { inline : 'span', classes : val, selector : '*' }; ed.formatter.register(name, fmt); ctrl.add(t.editor.translate(key), name, { style: function() { return getPreviewCss(ed, fmt); } }); } }); } }); // Auto import classes if the ctrl box is empty if (ctrl.getLength() == 0) { ctrl.onPostRender.add(function(ed, n) { if (!ctrl.NativeListBox) { Event.add(n.id + '_text', 'focus', t._importClasses, t); Event.add(n.id + '_text', 'mousedown', t._importClasses, t); Event.add(n.id + '_open', 'focus', t._importClasses, t); Event.add(n.id + '_open', 'mousedown', t._importClasses, t); } else Event.add(n.id, 'focus', t._importClasses, t); }); } return ctrl; }, _createFontSelect : function() { var c, t = this, ed = t.editor; c = ed.controlManager.createListBox('fontselect', { title : 'advanced.fontdefault', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { ed.execCommand('FontName', false, cur.value); return; } ed.execCommand('FontName', false, v); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && cur.value == v) { c.select(null); } return false; // No auto select } }); if (c) { each(ed.getParam('theme_advanced_fonts', t.settings.theme_advanced_fonts, 'hash'), function(v, k) { c.add(ed.translate(k), v, {style : v.indexOf('dings') == -1 ? 'font-family:' + v : ''}); }); } return c; }, _createFontSizeSelect : function() { var t = this, ed = t.editor, c, i = 0, cl = []; c = ed.controlManager.createListBox('fontsizeselect', {title : 'advanced.font_size', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { cur = cur.value; if (cur['class']) { ed.formatter.toggle('fontsize_class', {value : cur['class']}); ed.undoManager.add(); ed.nodeChanged(); } else { ed.execCommand('FontSize', false, cur.fontSize); } return; } if (v['class']) { ed.focus(); ed.undoManager.add(); ed.formatter.toggle('fontsize_class', {value : v['class']}); ed.undoManager.add(); ed.nodeChanged(); } else ed.execCommand('FontSize', false, v.fontSize); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && (cur.value.fontSize == v.fontSize || cur.value['class'] && cur.value['class'] == v['class'])) { c.select(null); } return false; // No auto select }}); if (c) { each(t.settings.theme_advanced_font_sizes, function(v, k) { var fz = v.fontSize; if (fz >= 1 && fz <= 7) fz = t.sizes[parseInt(fz) - 1] + 'pt'; c.add(k, v, {'style' : 'font-size:' + fz, 'class' : 'mceFontSize' + (i++) + (' ' + (v['class'] || ''))}); }); } return c; }, _createBlockFormats : function() { var c, fmts = { p : 'advanced.paragraph', address : 'advanced.address', pre : 'advanced.pre', h1 : 'advanced.h1', h2 : 'advanced.h2', h3 : 'advanced.h3', h4 : 'advanced.h4', h5 : 'advanced.h5', h6 : 'advanced.h6', div : 'advanced.div', blockquote : 'advanced.blockquote', code : 'advanced.code', dt : 'advanced.dt', dd : 'advanced.dd', samp : 'advanced.samp' }, t = this; c = t.editor.controlManager.createListBox('formatselect', {title : 'advanced.block', onselect : function(v) { t.editor.execCommand('FormatBlock', false, v); return false; }}); if (c) { each(t.editor.getParam('theme_advanced_blockformats', t.settings.theme_advanced_blockformats, 'hash'), function(v, k) { c.add(t.editor.translate(k != v ? k : fmts[v]), v, {'class' : 'mce_formatPreview mce_' + v, style: function() { return getPreviewCss(t.editor, {block: v}); }}); }); } return c; }, _createForeColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_text_colors) o.colors = v; if (s.theme_advanced_default_foreground_color) o.default_color = s.theme_advanced_default_foreground_color; o.title = 'advanced.forecolor_desc'; o.cmd = 'ForeColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('forecolor', o); return c; }, _createBackColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_background_colors) o.colors = v; if (s.theme_advanced_default_background_color) o.default_color = s.theme_advanced_default_background_color; o.title = 'advanced.backcolor_desc'; o.cmd = 'HiliteColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('backcolor', o); return c; }, renderUI : function(o) { var n, ic, tb, t = this, ed = t.editor, s = t.settings, sc, p, nl; if (ed.settings) { ed.settings.aria_label = s.aria_label + ed.getLang('advanced.help_shortcut'); } // TODO: ACC Should have an aria-describedby attribute which is user-configurable to describe what this field is actually for. // Maybe actually inherit it from the original textara? n = p = DOM.create('span', {role : 'application', 'aria-labelledby' : ed.id + '_voice', id : ed.id + '_parent', 'class' : 'mceEditor ' + ed.settings.skin + 'Skin' + (s.skin_variant ? ' ' + ed.settings.skin + 'Skin' + t._ufirst(s.skin_variant) : '') + (ed.settings.directionality == "rtl" ? ' mceRtl' : '')}); DOM.add(n, 'span', {'class': 'mceVoiceLabel', 'style': 'display:none;', id: ed.id + '_voice'}, s.aria_label); if (!DOM.boxModel) n = DOM.add(n, 'div', {'class' : 'mceOldBoxModel'}); n = sc = DOM.add(n, 'table', {role : "presentation", id : ed.id + '_tbl', 'class' : 'mceLayout', cellSpacing : 0, cellPadding : 0}); n = tb = DOM.add(n, 'tbody'); switch ((s.theme_advanced_layout_manager || '').toLowerCase()) { case "rowlayout": ic = t._rowLayout(s, tb, o); break; case "customlayout": ic = ed.execCallback("theme_advanced_custom_layout", s, tb, o, p); break; default: ic = t._simpleLayout(s, tb, o, p); } n = o.targetNode; // Add classes to first and last TRs nl = sc.rows; DOM.addClass(nl[0], 'mceFirst'); DOM.addClass(nl[nl.length - 1], 'mceLast'); // Add classes to first and last TDs each(DOM.select('tr', tb), function(n) { DOM.addClass(n.firstChild, 'mceFirst'); DOM.addClass(n.childNodes[n.childNodes.length - 1], 'mceLast'); }); if (DOM.get(s.theme_advanced_toolbar_container)) DOM.get(s.theme_advanced_toolbar_container).appendChild(p); else DOM.insertAfter(p, n); Event.add(ed.id + '_path_row', 'click', function(e) { e = e.target; if (e.nodeName == 'A') { t._sel(e.className.replace(/^.*mcePath_([0-9]+).*$/, '$1')); return false; } }); /* if (DOM.get(ed.id + '_path_row')) { Event.add(ed.id + '_tbl', 'mouseover', function(e) { var re; e = e.target; if (e.nodeName == 'SPAN' && DOM.hasClass(e.parentNode, 'mceButton')) { re = DOM.get(ed.id + '_path_row'); t.lastPath = re.innerHTML; DOM.setHTML(re, e.parentNode.title); } }); Event.add(ed.id + '_tbl', 'mouseout', function(e) { if (t.lastPath) { DOM.setHTML(ed.id + '_path_row', t.lastPath); t.lastPath = 0; } }); } */ if (!ed.getParam('accessibility_focus')) Event.add(DOM.add(p, 'a', {href : '#'}, '<!-- IE -->'), 'focus', function() {tinyMCE.get(ed.id).focus();}); if (s.theme_advanced_toolbar_location == 'external') o.deltaHeight = 0; t.deltaHeight = o.deltaHeight; o.targetNode = null; ed.onKeyDown.add(function(ed, evt) { var DOM_VK_F10 = 121, DOM_VK_F11 = 122; if (evt.altKey) { if (evt.keyCode === DOM_VK_F10) { // Make sure focus is given to toolbar in Safari. // We can't do this in IE as it prevents giving focus to toolbar when editor is in a frame if (tinymce.isWebKit) { window.focus(); } t.toolbarGroup.focus(); return Event.cancel(evt); } else if (evt.keyCode === DOM_VK_F11) { DOM.get(ed.id + '_path_row').focus(); return Event.cancel(evt); } } }); // alt+0 is the UK recommended shortcut for accessing the list of access controls. ed.addShortcut('alt+0', '', 'mceShortcuts', t); return { iframeContainer : ic, editorContainer : ed.id + '_parent', sizeContainer : sc, deltaHeight : o.deltaHeight }; }, getInfo : function() { return { longname : 'Advanced theme', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', version : tinymce.majorVersion + "." + tinymce.minorVersion } }, resizeBy : function(dw, dh) { var e = DOM.get(this.editor.id + '_ifr'); this.resizeTo(e.clientWidth + dw, e.clientHeight + dh); }, resizeTo : function(w, h, store) { var ed = this.editor, s = this.settings, e = DOM.get(ed.id + '_tbl'), ifr = DOM.get(ed.id + '_ifr'); // Boundery fix box w = Math.max(s.theme_advanced_resizing_min_width || 100, w); h = Math.max(s.theme_advanced_resizing_min_height || 100, h); w = Math.min(s.theme_advanced_resizing_max_width || 0xFFFF, w); h = Math.min(s.theme_advanced_resizing_max_height || 0xFFFF, h); // Resize iframe and container DOM.setStyle(e, 'height', ''); DOM.setStyle(ifr, 'height', h); if (s.theme_advanced_resize_horizontal) { DOM.setStyle(e, 'width', ''); DOM.setStyle(ifr, 'width', w); // Make sure that the size is never smaller than the over all ui if (w < e.clientWidth) { w = e.clientWidth; DOM.setStyle(ifr, 'width', e.clientWidth); } } // Store away the size if (store && s.theme_advanced_resizing_use_cookie) { Cookie.setHash("TinyMCE_" + ed.id + "_size", { cw : w, ch : h }); } }, destroy : function() { var id = this.editor.id; Event.clear(id + '_resize'); Event.clear(id + '_path_row'); Event.clear(id + '_external_close'); }, // Internal functions _simpleLayout : function(s, tb, o, p) { var t = this, ed = t.editor, lo = s.theme_advanced_toolbar_location, sl = s.theme_advanced_statusbar_location, n, ic, etb, c; if (s.readonly) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); return ic; } // Create toolbar container at top if (lo == 'top') t._addToolbars(tb, o); // Create external toolbar if (lo == 'external') { n = c = DOM.create('div', {style : 'position:relative'}); n = DOM.add(n, 'div', {id : ed.id + '_external', 'class' : 'mceExternalToolbar'}); DOM.add(n, 'a', {id : ed.id + '_external_close', href : 'javascript:;', 'class' : 'mceExternalClose'}); n = DOM.add(n, 'table', {id : ed.id + '_tblext', cellSpacing : 0, cellPadding : 0}); etb = DOM.add(n, 'tbody'); if (p.firstChild.className == 'mceOldBoxModel') p.firstChild.appendChild(c); else p.insertBefore(c, p.firstChild); t._addToolbars(etb, o); ed.onMouseUp.add(function() { var e = DOM.get(ed.id + '_external'); DOM.show(e); DOM.hide(lastExtID); var f = Event.add(ed.id + '_external_close', 'click', function() { DOM.hide(ed.id + '_external'); Event.remove(ed.id + '_external_close', 'click', f); return false; }); DOM.show(e); DOM.setStyle(e, 'top', 0 - DOM.getRect(ed.id + '_tblext').h - 1); // Fixes IE rendering bug DOM.hide(e); DOM.show(e); e.style.filter = ''; lastExtID = ed.id + '_external'; e = null; }); } if (sl == 'top') t._addStatusBar(tb, o); // Create iframe container if (!s.theme_advanced_toolbar_container) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); } // Create toolbar container at bottom if (lo == 'bottom') t._addToolbars(tb, o); if (sl == 'bottom') t._addStatusBar(tb, o); return ic; }, _rowLayout : function(s, tb, o) { var t = this, ed = t.editor, dc, da, cf = ed.controlManager, n, ic, to, a; dc = s.theme_advanced_containers_default_class || ''; da = s.theme_advanced_containers_default_align || 'center'; each(explode(s.theme_advanced_containers || ''), function(c, i) { var v = s['theme_advanced_container_' + c] || ''; switch (c.toLowerCase()) { case 'mceeditor': n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); break; case 'mceelementpath': t._addStatusBar(tb, o); break; default: a = (s['theme_advanced_container_' + c + '_align'] || da).toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(tb, 'tr'), 'td', { 'class' : 'mceToolbar ' + (s['theme_advanced_container_' + c + '_class'] || dc) + ' ' + a || da }); to = cf.createToolbar("toolbar" + i); t._addControls(v, to); DOM.setHTML(n, to.renderHTML()); o.deltaHeight -= s.theme_advanced_row_height; } }); return ic; }, _addControls : function(v, tb) { var t = this, s = t.settings, di, cf = t.editor.controlManager; if (s.theme_advanced_disable && !t._disabled) { di = {}; each(explode(s.theme_advanced_disable), function(v) { di[v] = 1; }); t._disabled = di; } else di = t._disabled; each(explode(v), function(n) { var c; if (di && di[n]) return; // Compatiblity with 2.x if (n == 'tablecontrols') { each(["table","|","row_props","cell_props","|","row_before","row_after","delete_row","|","col_before","col_after","delete_col","|","split_cells","merge_cells"], function(n) { n = t.createControl(n, cf); if (n) tb.add(n); }); return; } c = t.createControl(n, cf); if (c) tb.add(c); }); }, _addToolbars : function(c, o) { var t = this, i, tb, ed = t.editor, s = t.settings, v, cf = ed.controlManager, di, n, h = [], a, toolbarGroup, toolbarsExist = false; toolbarGroup = cf.createToolbarGroup('toolbargroup', { 'name': ed.getLang('advanced.toolbar'), 'tab_focus_toolbar':ed.getParam('theme_advanced_tab_focus_toolbar') }); t.toolbarGroup = toolbarGroup; a = s.theme_advanced_toolbar_align.toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(c, 'tr', {role: 'presentation'}), 'td', {'class' : 'mceToolbar ' + a, "role":"toolbar"}); // Create toolbar and add the controls for (i=1; (v = s['theme_advanced_buttons' + i]); i++) { toolbarsExist = true; tb = cf.createToolbar("toolbar" + i, {'class' : 'mceToolbarRow' + i}); if (s['theme_advanced_buttons' + i + '_add']) v += ',' + s['theme_advanced_buttons' + i + '_add']; if (s['theme_advanced_buttons' + i + '_add_before']) v = s['theme_advanced_buttons' + i + '_add_before'] + ',' + v; t._addControls(v, tb); toolbarGroup.add(tb); o.deltaHeight -= s.theme_advanced_row_height; } // Handle case when there are no toolbar buttons and ensure editor height is adjusted accordingly if (!toolbarsExist) o.deltaHeight -= s.theme_advanced_row_height; h.push(toolbarGroup.renderHTML()); h.push(DOM.createHTML('a', {href : '#', accesskey : 'z', title : ed.getLang("advanced.toolbar_focus"), onfocus : 'tinyMCE.getInstanceById(\'' + ed.id + '\').focus();'}, '<!-- IE -->')); DOM.setHTML(n, h.join('')); }, _addStatusBar : function(tb, o) { var n, t = this, ed = t.editor, s = t.settings, r, mf, me, td; n = DOM.add(tb, 'tr'); n = td = DOM.add(n, 'td', {'class' : 'mceStatusbar'}); n = DOM.add(n, 'div', {id : ed.id + '_path_row', 'role': 'group', 'aria-labelledby': ed.id + '_path_voice'}); if (s.theme_advanced_path) { DOM.add(n, 'span', {id: ed.id + '_path_voice'}, ed.translate('advanced.path')); DOM.add(n, 'span', {}, ': '); } else { DOM.add(n, 'span', {}, '&#160;'); } if (s.theme_advanced_resizing) { DOM.add(td, 'a', {id : ed.id + '_resize', href : 'javascript:;', onclick : "return false;", 'class' : 'mceResize', tabIndex:"-1"}); if (s.theme_advanced_resizing_use_cookie) { ed.onPostRender.add(function() { var o = Cookie.getHash("TinyMCE_" + ed.id + "_size"), c = DOM.get(ed.id + '_tbl'); if (!o) return; t.resizeTo(o.cw, o.ch); }); } ed.onPostRender.add(function() { Event.add(ed.id + '_resize', 'click', function(e) { e.preventDefault(); }); Event.add(ed.id + '_resize', 'mousedown', function(e) { var mouseMoveHandler1, mouseMoveHandler2, mouseUpHandler1, mouseUpHandler2, startX, startY, startWidth, startHeight, width, height, ifrElm; function resizeOnMove(e) { e.preventDefault(); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height); }; function endResize(e) { // Stop listening Event.remove(DOM.doc, 'mousemove', mouseMoveHandler1); Event.remove(ed.getDoc(), 'mousemove', mouseMoveHandler2); Event.remove(DOM.doc, 'mouseup', mouseUpHandler1); Event.remove(ed.getDoc(), 'mouseup', mouseUpHandler2); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height, true); ed.nodeChanged(); }; e.preventDefault(); // Get the current rect size startX = e.screenX; startY = e.screenY; ifrElm = DOM.get(t.editor.id + '_ifr'); startWidth = width = ifrElm.clientWidth; startHeight = height = ifrElm.clientHeight; // Register envent handlers mouseMoveHandler1 = Event.add(DOM.doc, 'mousemove', resizeOnMove); mouseMoveHandler2 = Event.add(ed.getDoc(), 'mousemove', resizeOnMove); mouseUpHandler1 = Event.add(DOM.doc, 'mouseup', endResize); mouseUpHandler2 = Event.add(ed.getDoc(), 'mouseup', endResize); }); }); } o.deltaHeight -= 21; n = tb = null; }, _updateUndoStatus : function(ed) { var cm = ed.controlManager, um = ed.undoManager; cm.setDisabled('undo', !um.hasUndo() && !um.typing); cm.setDisabled('redo', !um.hasRedo()); }, _nodeChanged : function(ed, cm, n, co, ob) { var t = this, p, de = 0, v, c, s = t.settings, cl, fz, fn, fc, bc, formatNames, matches; tinymce.each(t.stateControls, function(c) { cm.setActive(c, ed.queryCommandState(t.controls[c][1])); }); function getParent(name) { var i, parents = ob.parents, func = name; if (typeof(name) == 'string') { func = function(node) { return node.nodeName == name; }; } for (i = 0; i < parents.length; i++) { if (func(parents[i])) return parents[i]; } }; cm.setActive('visualaid', ed.hasVisual); t._updateUndoStatus(ed); cm.setDisabled('outdent', !ed.queryCommandState('Outdent')); p = getParent('A'); if (c = cm.get('link')) { c.setDisabled((!p && co) || (p && !p.href)); c.setActive(!!p && (!p.name && !p.id)); } if (c = cm.get('unlink')) { c.setDisabled(!p && co); c.setActive(!!p && !p.name && !p.id); } if (c = cm.get('anchor')) { c.setActive(!co && !!p && (p.name || (p.id && !p.href))); } p = getParent('IMG'); if (c = cm.get('image')) c.setActive(!co && !!p && n.className.indexOf('mceItem') == -1); if (c = cm.get('styleselect')) { t._importClasses(); formatNames = []; each(c.items, function(item) { formatNames.push(item.value); }); matches = ed.formatter.matchAll(formatNames); c.select(matches[0]); tinymce.each(matches, function(match, index) { if (index > 0) { c.mark(match); } }); } if (c = cm.get('formatselect')) { p = getParent(ed.dom.isBlock); if (p) c.select(p.nodeName.toLowerCase()); } // Find out current fontSize, fontFamily and fontClass getParent(function(n) { if (n.nodeName === 'SPAN') { if (!cl && n.className) cl = n.className; } if (ed.dom.is(n, s.theme_advanced_font_selector)) { if (!fz && n.style.fontSize) fz = n.style.fontSize; if (!fn && n.style.fontFamily) fn = n.style.fontFamily.replace(/[\"\']+/g, '').replace(/^([^,]+).*/, '$1').toLowerCase(); if (!fc && n.style.color) fc = n.style.color; if (!bc && n.style.backgroundColor) bc = n.style.backgroundColor; } return false; }); if (c = cm.get('fontselect')) { c.select(function(v) { return v.replace(/^([^,]+).*/, '$1').toLowerCase() == fn; }); } // Select font size if (c = cm.get('fontsizeselect')) { // Use computed style if (s.theme_advanced_runtime_fontsize && !fz && !cl) fz = ed.dom.getStyle(n, 'fontSize', true); c.select(function(v) { if (v.fontSize && v.fontSize === fz) return true; if (v['class'] && v['class'] === cl) return true; }); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } } updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } }; updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_path && s.theme_advanced_statusbar_location) { p = DOM.get(ed.id + '_path') || DOM.add(ed.id + '_path_row', 'span', {id : ed.id + '_path'}); if (t.statusKeyboardNavigation) { t.statusKeyboardNavigation.destroy(); t.statusKeyboardNavigation = null; } DOM.setHTML(p, ''); getParent(function(n) { var na = n.nodeName.toLowerCase(), u, pi, ti = ''; // Ignore non element and bogus/hidden elements if (n.nodeType != 1 || na === 'br' || n.getAttribute('data-mce-bogus') || DOM.hasClass(n, 'mceItemHidden') || DOM.hasClass(n, 'mceItemRemoved')) return; // Handle prefix if (tinymce.isIE && n.scopeName !== 'HTML' && n.scopeName) na = n.scopeName + ':' + na; // Remove internal prefix na = na.replace(/mce\:/g, ''); // Handle node name switch (na) { case 'b': na = 'strong'; break; case 'i': na = 'em'; break; case 'img': if (v = DOM.getAttrib(n, 'src')) ti += 'src: ' + v + ' '; break; case 'a': if (v = DOM.getAttrib(n, 'name')) { ti += 'name: ' + v + ' '; na += '#' + v; } if (v = DOM.getAttrib(n, 'href')) ti += 'href: ' + v + ' '; break; case 'font': if (v = DOM.getAttrib(n, 'face')) ti += 'font: ' + v + ' '; if (v = DOM.getAttrib(n, 'size')) ti += 'size: ' + v + ' '; if (v = DOM.getAttrib(n, 'color')) ti += 'color: ' + v + ' '; break; case 'span': if (v = DOM.getAttrib(n, 'style')) ti += 'style: ' + v + ' '; break; } if (v = DOM.getAttrib(n, 'id')) ti += 'id: ' + v + ' '; if (v = n.className) { v = v.replace(/\b\s*(webkit|mce|Apple-)\w+\s*\b/g, ''); if (v) { ti += 'class: ' + v + ' '; if (ed.dom.isBlock(n) || na == 'img' || na == 'span') na += '.' + v; } } na = na.replace(/(html:)/g, ''); na = {name : na, node : n, title : ti}; t.onResolveName.dispatch(t, na); ti = na.title; na = na.name; //u = "javascript:tinymce.EditorManager.get('" + ed.id + "').theme._sel('" + (de++) + "');"; pi = DOM.create('a', {'href' : "javascript:;", role: 'button', onmousedown : "return false;", title : ti, 'class' : 'mcePath_' + (de++)}, na); if (p.hasChildNodes()) { p.insertBefore(DOM.create('span', {'aria-hidden': 'true'}, '\u00a0\u00bb '), p.firstChild); p.insertBefore(pi, p.firstChild); } else p.appendChild(pi); }, ed.getBody()); if (DOM.select('a', p).length > 0) { t.statusKeyboardNavigation = new tinymce.ui.KeyboardNavigation({ root: ed.id + "_path_row", items: DOM.select('a', p), excludeFromTabOrder: true, onCancel: function() { ed.focus(); } }, DOM); } } }, // Commands gets called by execCommand _sel : function(v) { this.editor.execCommand('mceSelectNodeDepth', false, v); }, _mceInsertAnchor : function(ui, v) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/anchor.htm', width : 320 + parseInt(ed.getLang('advanced.anchor_delta_width', 0)), height : 90 + parseInt(ed.getLang('advanced.anchor_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceCharMap : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/charmap.htm', width : 550 + parseInt(ed.getLang('advanced.charmap_delta_width', 0)), height : 265 + parseInt(ed.getLang('advanced.charmap_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceHelp : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/about.htm', width : 480, height : 380, inline : true }, { theme_url : this.url }); }, _mceShortcuts : function() { var ed = this.editor; ed.windowManager.open({ url: this.url + '/shortcuts.htm', width: 480, height: 380, inline: true }, { theme_url: this.url }); }, _mceColorPicker : function(u, v) { var ed = this.editor; v = v || {}; ed.windowManager.open({ url : this.url + '/color_picker.htm', width : 375 + parseInt(ed.getLang('advanced.colorpicker_delta_width', 0)), height : 250 + parseInt(ed.getLang('advanced.colorpicker_delta_height', 0)), close_previous : false, inline : true }, { input_color : v.color, func : v.func, theme_url : this.url }); }, _mceCodeEditor : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/source_editor.htm', width : parseInt(ed.getParam("theme_advanced_source_editor_width", 720)), height : parseInt(ed.getParam("theme_advanced_source_editor_height", 580)), inline : true, resizable : true, maximizable : true }, { theme_url : this.url }); }, _mceImage : function(ui, val) { var ed = this.editor; // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class', '').indexOf('mceItem') != -1) return; ed.windowManager.open({ url : this.url + '/image.htm', width : 355 + parseInt(ed.getLang('advanced.image_delta_width', 0)), height : 275 + parseInt(ed.getLang('advanced.image_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceLink : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/link.htm', width : 310 + parseInt(ed.getLang('advanced.link_delta_width', 0)), height : 200 + parseInt(ed.getLang('advanced.link_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceNewDocument : function() { var ed = this.editor; ed.windowManager.confirm('advanced.newdocument', function(s) { if (s) ed.execCommand('mceSetContent', false, ''); }); }, _mceForeColor : function() { var t = this; this._mceColorPicker(0, { color: t.fgColor, func : function(co) { t.fgColor = co; t.editor.execCommand('ForeColor', false, co); } }); }, _mceBackColor : function() { var t = this; this._mceColorPicker(0, { color: t.bgColor, func : function(co) { t.bgColor = co; t.editor.execCommand('HiliteColor', false, co); } }); }, _ufirst : function(s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }); tinymce.ThemeManager.add('advanced', tinymce.themes.AdvancedTheme); }(tinymce));
JavaScript
(function() { tinymce.create('tinymce.plugins.wpEditImage', { url: '', editor: {}, init: function(ed, url) { var t = this, mouse = {}; t.url = url; t.editor = ed; t._createButtons(); ed.addCommand('WP_EditImage', t._editImage); ed.onInit.add(function(ed) { ed.dom.events.add(ed.getBody(), 'mousedown', function(e) { var parent; if ( e.target.nodeName == 'IMG' && ( parent = ed.dom.getParent(e.target, 'div.mceTemp') ) ) { if ( tinymce.isGecko ) ed.selection.select(parent); else if ( tinymce.isWebKit ) ed.dom.events.prevent(e); } }); // when pressing Return inside a caption move the caret to a new parapraph under it ed.dom.events.add(ed.getBody(), 'keydown', function(e) { var n, DL, DIV, P, content; if ( e.keyCode == 13 ) { n = ed.selection.getNode(); DL = ed.dom.getParent(n, 'dl.wp-caption'); if ( DL ) DIV = ed.dom.getParent(DL, 'div.mceTemp'); if ( DIV ) { ed.dom.events.cancel(e); P = ed.dom.create('p', {}, '\uFEFF'); ed.dom.insertAfter( P, DIV ); ed.selection.setCursorLocation(P, 0); return false; } } }); // iOS6 doesn't show the buttons properly on click, show them on 'touchstart' if ( 'ontouchstart' in window ) { ed.dom.events.add(ed.getBody(), 'touchstart', function(e){ t._showButtons(e); }); } }); // resize the caption <dl> when the image is soft-resized by the user ed.onMouseUp.add(function(ed, e) { if ( tinymce.isWebKit || tinymce.isOpera ) return; if ( mouse.x && (e.clientX != mouse.x || e.clientY != mouse.y) ) { var n = ed.selection.getNode(); if ( 'IMG' == n.nodeName ) { window.setTimeout(function(){ var DL = ed.dom.getParent(n, 'dl.wp-caption'), width; if ( n.width != mouse.img_w || n.height != mouse.img_h ) n.className = n.className.replace(/size-[^ "']+/, ''); if ( DL ) { width = ed.dom.getAttrib(n, 'width') || n.width; width = parseInt(width, 10); ed.dom.setStyle(DL, 'width', 10 + width); ed.execCommand('mceRepaint'); } }, 100); } } mouse = {}; }); // show editimage buttons ed.onMouseDown.add(function(ed, e){ t._showButtons(e); }); ed.onBeforeSetContent.add(function(ed, o) { o.content = ed.wpSetImgCaption(o.content); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = ed.wpGetImgCaption(o.content); }); ed.wpSetImgCaption = function(content) { return t._do_shcode(content); }; ed.wpGetImgCaption = function(content) { return t._get_shcode(content); }; // When inserting content, if the caret is inside a caption create new paragraph under // and move the caret there ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { var node, p; if ( cmd == 'mceInsertContent' ) { node = ed.dom.getParent(ed.selection.getNode(), 'div.mceTemp'); if ( !node ) return; p = ed.dom.create('p'); ed.dom.insertAfter( p, node ); ed.selection.setCursorLocation(p, 0); } }); }, _do_shcode : function(content) { return content.replace(/(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?/g, function(a,b,c){ var id, cls, w, cap, div_cls, img, trim = tinymce.trim; id = b.match(/id=['"]([^'"]*)['"] ?/); if ( id ) b = b.replace(id[0], ''); cls = b.match(/align=['"]([^'"]*)['"] ?/); if ( cls ) b = b.replace(cls[0], ''); w = b.match(/width=['"]([0-9]*)['"] ?/); if ( w ) b = b.replace(w[0], ''); c = trim(c); img = c.match(/((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)([\s\S]*)/i); if ( img && img[2] ) { cap = trim( img[2] ); img = trim( img[1] ); } else { // old captions shortcode style cap = trim(b).replace(/caption=['"]/, '').replace(/['"]$/, ''); img = c; } id = ( id && id[1] ) ? id[1] : ''; cls = ( cls && cls[1] ) ? cls[1] : 'alignnone'; w = ( w && w[1] ) ? w[1] : ''; if ( !w || !cap ) return c; div_cls = 'mceTemp'; if ( cls == 'aligncenter' ) div_cls += ' mceIEcenter'; return '<div class="'+div_cls+'"><dl id="'+id+'" class="wp-caption '+cls+'" style="width: '+( 10 + parseInt(w) )+ 'px"><dt class="wp-caption-dt">'+img+'</dt><dd class="wp-caption-dd">'+cap+'</dd></dl></div>'; }); }, _get_shcode : function(content) { return content.replace(/<div (?:id="attachment_|class="mceTemp)[^>]*>([\s\S]+?)<\/div>/g, function(a, b){ var ret = b.replace(/<dl ([^>]+)>\s*<dt [^>]+>([\s\S]+?)<\/dt>\s*<dd [^>]+>([\s\S]*?)<\/dd>\s*<\/dl>/gi, function(a,b,c,cap){ var id, cls, w; w = c.match(/width="([0-9]*)"/); w = ( w && w[1] ) ? w[1] : ''; if ( !w || !cap ) return c; id = b.match(/id="([^"]*)"/); id = ( id && id[1] ) ? id[1] : ''; cls = b.match(/class="([^"]*)"/); cls = ( cls && cls[1] ) ? cls[1] : ''; cls = cls.match(/align[a-z]+/) || 'alignnone'; cap = cap.replace(/\r\n|\r/g, '\n').replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){ // no line breaks inside HTML tags return a.replace(/[\r\n\t]+/, ' '); }); // convert remaining line breaks to <br> cap = cap.replace(/\s*\n\s*/g, '<br />'); return '[caption id="'+id+'" align="'+cls+'" width="'+w+'"]'+c+' '+cap+'[/caption]'; }); if ( ret.indexOf('[caption') !== 0 ) { // the caption html seems brocken, try to find the image that may be wrapped in a link // and may be followed by <p> with the caption text. ret = b.replace(/[\s\S]*?((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)(<p>[\s\S]*<\/p>)?[\s\S]*/gi, '<p>$1</p>$2'); } return ret; }); }, _createButtons : function() { var t = this, ed = tinymce.activeEditor, DOM = tinymce.DOM, editButton, dellButton, isRetina; if ( DOM.get('wp_editbtns') ) return; isRetina = ( window.devicePixelRatio && window.devicePixelRatio > 1 ) || // WebKit, Opera ( window.matchMedia && window.matchMedia('(min-resolution:130dpi)').matches ); // Firefox, IE10, Opera DOM.add(document.body, 'div', { id : 'wp_editbtns', style : 'display:none;' }); editButton = DOM.add('wp_editbtns', 'img', { src : isRetina ? t.url+'/img/image-2x.png' : t.url+'/img/image.png', id : 'wp_editimgbtn', width : '24', height : '24', title : ed.getLang('wpeditimage.edit_img') }); tinymce.dom.Event.add(editButton, 'mousedown', function(e) { t._editImage(); ed.plugins.wordpress._hideButtons(); }); dellButton = DOM.add('wp_editbtns', 'img', { src : isRetina ? t.url+'/img/delete-2x.png' : t.url+'/img/delete.png', id : 'wp_delimgbtn', width : '24', height : '24', title : ed.getLang('wpeditimage.del_img') }); tinymce.dom.Event.add(dellButton, 'mousedown', function(e) { var ed = tinymce.activeEditor, el = ed.selection.getNode(), parent; if ( el.nodeName == 'IMG' && ed.dom.getAttrib(el, 'class').indexOf('mceItem') == -1 ) { if ( (parent = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(parent, 'mceTemp') ) { ed.dom.remove(parent); } else { if ( el.parentNode.nodeName == 'A' && el.parentNode.childNodes.length == 1 ) el = el.parentNode; if ( el.parentNode.nodeName == 'P' && el.parentNode.childNodes.length == 1 ) el = el.parentNode; ed.dom.remove(el); } ed.execCommand('mceRepaint'); return false; } ed.plugins.wordpress._hideButtons(); }); }, _editImage : function() { var ed = tinymce.activeEditor, url = this.url, el = ed.selection.getNode(), vp, H, W, cls = el.className; if ( cls.indexOf('mceItem') != -1 || cls.indexOf('wpGallery') != -1 || el.nodeName != 'IMG' ) return; vp = tinymce.DOM.getViewPort(); H = 680 < (vp.h - 70) ? 680 : vp.h - 70; W = 650 < vp.w ? 650 : vp.w; ed.windowManager.open({ file: url + '/editimage.html', width: W+'px', height: H+'px', inline: true }); }, _showButtons : function(e) { var ed = this.editor, target = e.target; if ( target.nodeName != 'IMG' ) { if ( target.firstChild && target.firstChild.nodeName == 'IMG' && target.childNodes.length == 1 ) { target = target.firstChild; } else { ed.plugins.wordpress._hideButtons(); return; } } if ( ed.dom.getAttrib(target, 'class').indexOf('mceItem') == -1 ) { mouse = { x: e.clientX, y: e.clientY, img_w: target.clientWidth, img_h: target.clientHeight }; if ( e.type == 'touchstart' ) { ed.selection.select(target); ed.dom.events.cancel(e); } ed.plugins.wordpress._hideButtons(); ed.plugins.wordpress._showButtons(target, 'wp_editbtns'); } }, getInfo : function() { return { longname : 'Edit Image', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); tinymce.PluginManager.add('wpeditimage', tinymce.plugins.wpEditImage); })();
JavaScript
var tinymce = null, tinyMCEPopup, tinyMCE, wpImage; tinyMCEPopup = { init: function() { var t = this, w, ti; // Find window & API w = t.getWin(); tinymce = w.tinymce; tinyMCE = w.tinyMCE; t.editor = tinymce.EditorManager.activeEditor; t.params = t.editor.windowManager.params; t.features = t.editor.windowManager.features; // Setup local DOM t.dom = t.editor.windowManager.createInstance('tinymce.dom.DOMUtils', document); t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window); }, getWin : function() { return (!window.frameElement && window.dialogArguments) || opener || parent || top; }, getParam : function(n, dv) { return this.editor.getParam(n, dv); }, close : function() { var t = this; // To avoid domain relaxing issue in Opera function close() { t.editor.windowManager.close(window); tinymce = tinyMCE = t.editor = t.params = t.dom = t.dom.doc = null; // Cleanup }; if (tinymce.isOpera) t.getWin().setTimeout(close, 0); else close(); }, execCommand : function(cmd, ui, val, a) { a = a || {}; a.skip_focus = 1; this.restoreSelection(); return this.editor.execCommand(cmd, ui, val, a); }, storeSelection : function() { this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark(1); }, restoreSelection : function() { var t = tinyMCEPopup; if ( tinymce.isIE ) t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark); } } tinyMCEPopup.init(); wpImage = { preInit : function() { // import colors stylesheet from parent var ed = tinyMCEPopup.editor, win = tinyMCEPopup.getWin(), styles = win.document.styleSheets, url, i; for ( i = 0; i < styles.length; i++ ) { url = styles.item(i).href; if ( url && url.indexOf('colors') != -1 ) { document.getElementsByTagName('head')[0].appendChild( ed.dom.create('link', {rel:'stylesheet', href: url}) ); break; } } }, I : function(e) { return document.getElementById(e); }, current : '', link : '', link_rel : '', target_value : '', current_size_sel : 's100', width : '', height : '', align : '', img_alt : '', setTabs : function(tab) { var t = this; if ( 'current' == tab.className ) return false; t.I('div_advanced').style.display = ( 'tab_advanced' == tab.id ) ? 'block' : 'none'; t.I('div_basic').style.display = ( 'tab_basic' == tab.id ) ? 'block' : 'none'; t.I('tab_basic').className = t.I('tab_advanced').className = ''; tab.className = 'current'; return false; }, img_seturl : function(u) { var t = this, rel = t.I('link_rel').value; if ( 'current' == u ) { t.I('link_href').value = t.current; t.I('link_rel').value = t.link_rel; } else { t.I('link_href').value = t.link; if ( rel ) { rel = rel.replace( /attachment|wp-att-[0-9]+/gi, '' ); t.I('link_rel').value = tinymce.trim(rel); } } }, imgAlignCls : function(v) { var t = this, cls = t.I('img_classes').value; t.I('img_demo').className = t.align = v; cls = cls.replace( /align[^ "']+/gi, '' ); cls += (' ' + v); cls = cls.replace( /\s+/g, ' ' ).replace( /^\s/, '' ); if ( 'aligncenter' == v ) { t.I('hspace').value = ''; t.updateStyle('hspace'); } t.I('img_classes').value = cls; }, showSize : function(el) { var t = this, demo = t.I('img_demo'), w = t.width, h = t.height, id = el.id || 's100', size; size = parseInt(id.substring(1)) / 200; demo.width = Math.round(w * size); demo.height = Math.round(h * size); t.showSizeClear(); el.style.borderColor = '#A3A3A3'; el.style.backgroundColor = '#E5E5E5'; }, showSizeSet : function() { var t = this, s130, s120, s110; if ( (t.width * 1.3) > parseInt(t.preloadImg.width) ) { s130 = t.I('s130'), s120 = t.I('s120'), s110 = t.I('s110'); s130.onclick = s120.onclick = s110.onclick = null; s130.onmouseover = s120.onmouseover = s110.onmouseover = null; s130.style.color = s120.style.color = s110.style.color = '#aaa'; } }, showSizeRem : function() { var t = this, demo = t.I('img_demo'), f = document.forms[0]; demo.width = Math.round(f.width.value * 0.5); demo.height = Math.round(f.height.value * 0.5); t.showSizeClear(); t.I(t.current_size_sel).style.borderColor = '#A3A3A3'; t.I(t.current_size_sel).style.backgroundColor = '#E5E5E5'; return false; }, showSizeClear : function() { var divs = this.I('img_size').getElementsByTagName('div'), i; for ( i = 0; i < divs.length; i++ ) { divs[i].style.borderColor = '#f1f1f1'; divs[i].style.backgroundColor = '#f1f1f1'; } }, imgEditSize : function(el) { var t = this, f = document.forms[0], W, H, w, h, id; if ( ! t.preloadImg || ! t.preloadImg.width || ! t.preloadImg.height ) return; W = parseInt(t.preloadImg.width), H = parseInt(t.preloadImg.height), w = t.width || W, h = t.height || H, id = el.id || 's100'; size = parseInt(id.substring(1)) / 100; w = Math.round(w * size); h = Math.round(h * size); f.width.value = Math.min(W, w); f.height.value = Math.min(H, h); t.current_size_sel = id; t.demoSetSize(); }, demoSetSize : function(img) { var demo = this.I('img_demo'), f = document.forms[0]; demo.width = f.width.value ? Math.round(f.width.value * 0.5) : ''; demo.height = f.height.value ? Math.round(f.height.value * 0.5) : ''; }, demoSetStyle : function() { var f = document.forms[0], demo = this.I('img_demo'), dom = tinyMCEPopup.editor.dom; if (demo) { dom.setAttrib(demo, 'style', f.img_style.value); dom.setStyle(demo, 'width', ''); dom.setStyle(demo, 'height', ''); } }, origSize : function() { var t = this, f = document.forms[0], el = t.I('s100'); f.width.value = t.width = t.preloadImg.width; f.height.value = t.height = t.preloadImg.height; t.showSizeSet(); t.demoSetSize(); t.showSize(el); }, init : function() { var ed = tinyMCEPopup.editor, h; h = document.body.innerHTML; document.body.innerHTML = ed.translate(h); window.setTimeout( function(){wpImage.setup();}, 500 ); }, setup : function() { var t = this, c, el, link, fname, f = document.forms[0], ed = tinyMCEPopup.editor, d = t.I('img_demo'), dom = tinyMCEPopup.dom, DL, DD, caption = '', dlc, pa; document.dir = tinyMCEPopup.editor.getParam('directionality',''); if ( tinyMCEPopup.editor.getParam('wpeditimage_disable_captions', false) ) t.I('cap_field').style.display = 'none'; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; f.img_src.value = d.src = link = ed.dom.getAttrib(el, 'src'); ed.dom.setStyle(el, 'float', ''); t.getImageData(); c = ed.dom.getAttrib(el, 'class'); if ( DL = dom.getParent(el, 'dl') ) { dlc = ed.dom.getAttrib(DL, 'class'); dlc = dlc.match(/align[^ "']+/i); if ( dlc && ! dom.hasClass(el, dlc) ) { c += ' '+dlc; tinymce.trim(c); } DD = ed.dom.select('dd.wp-caption-dd', DL); if ( DD && DD[0] ) caption = ed.serializer.serialize(DD[0]).replace(/^<p>/, '').replace(/<\/p>$/, ''); } f.img_cap_text.value = caption; f.img_title.value = ed.dom.getAttrib(el, 'title'); f.img_alt.value = ed.dom.getAttrib(el, 'alt'); f.border.value = ed.dom.getAttrib(el, 'border'); f.vspace.value = ed.dom.getAttrib(el, 'vspace'); f.hspace.value = ed.dom.getAttrib(el, 'hspace'); f.align.value = ed.dom.getAttrib(el, 'align'); f.width.value = t.width = ed.dom.getAttrib(el, 'width'); f.height.value = t.height = ed.dom.getAttrib(el, 'height'); f.img_classes.value = c; f.img_style.value = ed.dom.getAttrib(el, 'style'); // Move attribs to styles if ( dom.getAttrib(el, 'hspace') ) t.updateStyle('hspace'); if ( dom.getAttrib(el, 'border') ) t.updateStyle('border'); if ( dom.getAttrib(el, 'vspace') ) t.updateStyle('vspace'); if ( pa = ed.dom.getParent(el, 'A') ) { f.link_href.value = t.current = ed.dom.getAttrib(pa, 'href'); f.link_title.value = ed.dom.getAttrib(pa, 'title'); f.link_rel.value = t.link_rel = ed.dom.getAttrib(pa, 'rel'); f.link_style.value = ed.dom.getAttrib(pa, 'style'); t.target_value = ed.dom.getAttrib(pa, 'target'); f.link_classes.value = ed.dom.getAttrib(pa, 'class'); } f.link_target.checked = ( t.target_value && t.target_value == '_blank' ) ? 'checked' : ''; fname = link.substring( link.lastIndexOf('/') ); fname = fname.replace(/-[0-9]{2,4}x[0-9]{2,4}/, '' ); t.link = link.substring( 0, link.lastIndexOf('/') ) + fname; if ( c.indexOf('alignleft') != -1 ) { t.I('alignleft').checked = "checked"; d.className = t.align = "alignleft"; } else if ( c.indexOf('aligncenter') != -1 ) { t.I('aligncenter').checked = "checked"; d.className = t.align = "aligncenter"; } else if ( c.indexOf('alignright') != -1 ) { t.I('alignright').checked = "checked"; d.className = t.align = "alignright"; } else if ( c.indexOf('alignnone') != -1 ) { t.I('alignnone').checked = "checked"; d.className = t.align = "alignnone"; } if ( t.width && t.preloadImg.width ) t.showSizeSet(); document.body.style.display = ''; }, remove : function() { var ed = tinyMCEPopup.editor, p, el; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') ) ed.dom.remove(p); else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 ) ed.dom.remove(p); else ed.dom.remove(el); ed.execCommand('mceRepaint'); tinyMCEPopup.close(); return; }, update : function() { var t = this, f = document.forms[0], ed = tinyMCEPopup.editor, el, b, fixSafari = null, DL, P, A, DIV, do_caption = null, img_class = f.img_classes.value, html, id, cap_id = '', cap, DT, DD, cap_width, div_cls, lnk = '', pa, aa, caption; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; if (f.img_src.value === '') { t.remove(); return; } if ( f.img_cap_text.value != '' && f.width.value != '' ) { do_caption = 1; img_class = img_class.replace( /align[^ "']+\s?/gi, '' ); } A = ed.dom.getParent(el, 'a'); P = ed.dom.getParent(el, 'p'); DL = ed.dom.getParent(el, 'dl'); DIV = ed.dom.getParent(el, 'div'); tinyMCEPopup.execCommand("mceBeginUndoLevel"); if ( f.width.value != el.width || f.height.value != el.height ) img_class = img_class.replace(/size-[^ "']+/, ''); ed.dom.setAttribs(el, { src : f.img_src.value, title : f.img_title.value, alt : f.img_alt.value, width : f.width.value, height : f.height.value, style : f.img_style.value, 'class' : img_class }); if ( f.link_href.value ) { // Create new anchor elements if ( A == null ) { if ( ! f.link_href.value.match(/https?:\/\//i) ) f.link_href.value = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.link_href.value); ed.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); tinymce.each(ed.dom.select("a"), function(n) { if ( ed.dom.getAttrib(n, 'href') == '#mce_temp_url#' ) { ed.dom.setAttribs(n, { href : f.link_href.value, title : f.link_title.value, rel : f.link_rel.value, target : (f.link_target.checked == true) ? '_blank' : '', 'class' : f.link_classes.value, style : f.link_style.value }); } }); } else { ed.dom.setAttribs(A, { href : f.link_href.value, title : f.link_title.value, rel : f.link_rel.value, target : (f.link_target.checked == true) ? '_blank' : '', 'class' : f.link_classes.value, style : f.link_style.value }); } } if ( do_caption ) { cap_width = 10 + parseInt(f.width.value); div_cls = (t.align == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp'; caption = f.img_cap_text.value; caption = caption.replace(/\r\n|\r/g, '\n').replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){ return a.replace(/[\r\n\t]+/, ' '); }); caption = caption.replace(/\s*\n\s*/g, '<br />'); if ( DL ) { ed.dom.setAttribs(DL, { 'class' : 'wp-caption '+t.align, style : 'width: '+cap_width+'px;' }); if ( DIV ) ed.dom.setAttrib(DIV, 'class', div_cls); if ( (DT = ed.dom.getParent(el, 'dt')) && (DD = DT.nextSibling) && ed.dom.hasClass(DD, 'wp-caption-dd') ) ed.dom.setHTML(DD, caption); } else { if ( (id = f.img_classes.value.match( /wp-image-([0-9]{1,6})/ )) && id[1] ) cap_id = 'attachment_'+id[1]; if ( f.link_href.value && (lnk = ed.dom.getParent(el, 'a')) ) { if ( lnk.childNodes.length == 1 ) { html = ed.dom.getOuterHTML(lnk); } else { html = ed.dom.getOuterHTML(lnk); html = html.match(/<a [^>]+>/i); html = html+ed.dom.getOuterHTML(el)+'</a>'; } } else { html = ed.dom.getOuterHTML(el); } html = '<dl id="'+cap_id+'" class="wp-caption '+t.align+'" style="width: '+cap_width+ 'px"><dt class="wp-caption-dt">'+html+'</dt><dd class="wp-caption-dd">'+caption+'</dd></dl>'; cap = ed.dom.create('div', {'class': div_cls}, html); if ( P ) { P.parentNode.insertBefore(cap, P); if ( P.childNodes.length == 1 ) ed.dom.remove(P); else if ( lnk && lnk.childNodes.length == 1 ) ed.dom.remove(lnk); else ed.dom.remove(el); } else if ( pa = ed.dom.getParent(el, 'TD,TH,LI') ) { pa.appendChild(cap); if ( lnk && lnk.childNodes.length == 1 ) ed.dom.remove(lnk); else ed.dom.remove(el); } } } else { if ( DL && DIV ) { if ( f.link_href.value && (aa = ed.dom.getParent(el, 'a')) ) html = ed.dom.getOuterHTML(aa); else html = ed.dom.getOuterHTML(el); P = ed.dom.create('p', {}, html); DIV.parentNode.insertBefore(P, DIV); ed.dom.remove(DIV); } } if ( f.img_classes.value.indexOf('aligncenter') != -1 ) { if ( P && ( ! P.style || P.style.textAlign != 'center' ) ) ed.dom.setStyle(P, 'textAlign', 'center'); } else { if ( P && P.style && P.style.textAlign == 'center' ) ed.dom.setStyle(P, 'textAlign', ''); } if ( ! f.link_href.value && A ) { b = ed.selection.getBookmark(); ed.dom.remove(A, 1); ed.selection.moveToBookmark(b); } tinyMCEPopup.execCommand("mceEndUndoLevel"); ed.execCommand('mceRepaint'); tinyMCEPopup.close(); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, v, f = document.forms[0], img = dom.create('img', {style : f.img_style.value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = f.align.value; if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = '0'; else img.style.border = v + 'px solid black'; } } // Handle hspace if (ty == 'hspace') { dom.setStyle(img, 'marginLeft', ''); dom.setStyle(img, 'marginRight', ''); v = f.hspace.value; if (v) { img.style.marginLeft = v + 'px'; img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vspace') { dom.setStyle(img, 'marginTop', ''); dom.setStyle(img, 'marginBottom', ''); v = f.vspace.value; if (v) { img.style.marginTop = v + 'px'; img.style.marginBottom = v + 'px'; } } // Merge f.img_style.value = dom.serializeStyle(dom.parseStyle(img.style.cssText)); this.demoSetStyle(); } }, checkVal : function(f) { if ( f.value == '' ) { // if ( f.id == 'width' ) f.value = this.width || this.preloadImg.width; // if ( f.id == 'height' ) f.value = this.height || this.preloadImg.height; if ( f.id == 'img_src' ) f.value = this.I('img_demo').src || this.preloadImg.src; } }, resetImageData : function() { var f = document.forms[0]; f.width.value = f.height.value = ''; }, updateImageData : function() { var f = document.forms[0], t = wpImage, w = f.width.value, h = f.height.value; if ( !w && h ) w = f.width.value = t.width = Math.round( t.preloadImg.width / (t.preloadImg.height / h) ); else if ( w && !h ) h = f.height.value = t.height = Math.round( t.preloadImg.height / (t.preloadImg.width / w) ); if ( !w ) f.width.value = t.width = t.preloadImg.width; if ( !h ) f.height.value = t.height = t.preloadImg.height; t.showSizeSet(); t.demoSetSize(); if ( f.img_style.value ) t.demoSetStyle(); }, getImageData : function() { var t = wpImage, f = document.forms[0]; t.preloadImg = new Image(); t.preloadImg.onload = t.updateImageData; t.preloadImg.onerror = t.resetImageData; t.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.img_src.value); } }; window.onload = function(){wpImage.init();} wpImage.preInit();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.FullScreenPlugin', { init : function(ed, url) { var t = this, s = {}, vp, posCss; t.editor = ed; // Register commands ed.addCommand('mceFullScreen', function() { var win, de = DOM.doc.documentElement; if (ed.getParam('fullscreen_is_enabled')) { if (ed.getParam('fullscreen_new_window')) closeFullscreen(); // Call to close in new window else { DOM.win.setTimeout(function() { tinymce.dom.Event.remove(DOM.win, 'resize', t.resizeFunc); tinyMCE.get(ed.getParam('fullscreen_editor_id')).setContent(ed.getContent()); tinyMCE.remove(ed); DOM.remove('mce_fullscreen_container'); de.style.overflow = ed.getParam('fullscreen_html_overflow'); DOM.setStyle(DOM.doc.body, 'overflow', ed.getParam('fullscreen_overflow')); DOM.win.scrollTo(ed.getParam('fullscreen_scrollx'), ed.getParam('fullscreen_scrolly')); tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings }, 10); } return; } if (ed.getParam('fullscreen_new_window')) { win = DOM.win.open(url + "/fullscreen.htm", "mceFullScreenPopup", "fullscreen=yes,menubar=no,toolbar=no,scrollbars=no,resizable=yes,left=0,top=0,width=" + screen.availWidth + ",height=" + screen.availHeight); try { win.resizeTo(screen.availWidth, screen.availHeight); } catch (e) { // Ignore } } else { tinyMCE.oldSettings = tinyMCE.settings; // Store old settings s.fullscreen_overflow = DOM.getStyle(DOM.doc.body, 'overflow', 1) || 'auto'; s.fullscreen_html_overflow = DOM.getStyle(de, 'overflow', 1); vp = DOM.getViewPort(); s.fullscreen_scrollx = vp.x; s.fullscreen_scrolly = vp.y; // Fixes an Opera bug where the scrollbars doesn't reappear if (tinymce.isOpera && s.fullscreen_overflow == 'visible') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where horizontal scrollbars would appear if (tinymce.isIE && s.fullscreen_overflow == 'scroll') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where the scrollbars doesn't reappear if (tinymce.isIE && (s.fullscreen_html_overflow == 'visible' || s.fullscreen_html_overflow == 'scroll')) s.fullscreen_html_overflow = 'auto'; if (s.fullscreen_overflow == '0px') s.fullscreen_overflow = ''; DOM.setStyle(DOM.doc.body, 'overflow', 'hidden'); de.style.overflow = 'hidden'; //Fix for IE6/7 vp = DOM.getViewPort(); DOM.win.scrollTo(0, 0); if (tinymce.isIE) vp.h -= 1; // Use fixed position if it exists if (tinymce.isIE6 || document.compatMode == 'BackCompat') posCss = 'absolute;top:' + vp.y; else posCss = 'fixed;top:0'; n = DOM.add(DOM.doc.body, 'div', { id : 'mce_fullscreen_container', style : 'position:' + posCss + ';left:0;width:' + vp.w + 'px;height:' + vp.h + 'px;z-index:200000;'}); DOM.add(n, 'div', {id : 'mce_fullscreen'}); tinymce.each(ed.settings, function(v, n) { s[n] = v; }); s.id = 'mce_fullscreen'; s.width = n.clientWidth; s.height = n.clientHeight - 15; s.fullscreen_is_enabled = true; s.fullscreen_editor_id = ed.id; s.theme_advanced_resizing = false; s.save_onsavecallback = function() { ed.setContent(tinyMCE.get(s.id).getContent()); ed.execCommand('mceSave'); }; tinymce.each(ed.getParam('fullscreen_settings'), function(v, k) { s[k] = v; }); if (s.theme_advanced_toolbar_location === 'external') s.theme_advanced_toolbar_location = 'top'; t.fullscreenEditor = new tinymce.Editor('mce_fullscreen', s); t.fullscreenEditor.onInit.add(function() { t.fullscreenEditor.setContent(ed.getContent()); t.fullscreenEditor.focus(); }); t.fullscreenEditor.render(); t.fullscreenElement = new tinymce.dom.Element('mce_fullscreen_container'); t.fullscreenElement.update(); //document.body.overflow = 'hidden'; t.resizeFunc = tinymce.dom.Event.add(DOM.win, 'resize', function() { var vp = tinymce.DOM.getViewPort(), fed = t.fullscreenEditor, outerSize, innerSize; // Get outer/inner size to get a delta size that can be used to calc the new iframe size outerSize = fed.dom.getSize(fed.getContainer().getElementsByTagName('table')[0]); innerSize = fed.dom.getSize(fed.getContainer().getElementsByTagName('iframe')[0]); fed.theme.resizeTo(vp.w - outerSize.w + innerSize.w, vp.h - outerSize.h + innerSize.h); }); } }); // Register buttons ed.addButton('fullscreen', {title : 'fullscreen.desc', cmd : 'mceFullScreen'}); ed.onNodeChange.add(function(ed, cm) { cm.setActive('fullscreen', ed.getParam('fullscreen_is_enabled')); }); }, getInfo : function() { return { longname : 'Fullscreen', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullscreen', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('fullscreen', tinymce.plugins.FullScreenPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var rootAttributes = tinymce.explode('id,name,width,height,style,align,class,hspace,vspace,bgcolor,type'), excludedAttrs = tinymce.makeMap(rootAttributes.join(',')), Node = tinymce.html.Node, mediaTypes, scriptRegExp, JSON = tinymce.util.JSON, mimeTypes; // Media types supported by this plugin mediaTypes = [ // Type, clsid:s, mime types, codebase ["Flash", "d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash", "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"], ["ShockWave", "166b1bca-3f9c-11cf-8075-444553540000", "application/x-director", "http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0"], ["WindowsMedia", "6bf52a52-394a-11d3-b153-00c04f79faa6,22d6f312-b0f6-11d0-94ab-0080c74c7e95,05589fa1-c356-11ce-bf01-00aa0055595a", "application/x-mplayer2", "http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"], ["QuickTime", "02bf25d5-8c17-4b23-bc80-d3488abddc6b", "video/quicktime", "http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0"], ["RealMedia", "cfcdaa03-8be4-11cf-b84b-0020afbbccfa", "audio/x-pn-realaudio-plugin", "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"], ["Java", "8ad9c840-044e-11d1-b3e9-00805f499d93", "application/x-java-applet", "http://java.sun.com/products/plugin/autodl/jinstall-1_5_0-windows-i586.cab#Version=1,5,0,0"], ["Silverlight", "dfeaf541-f3e1-4c24-acac-99c30715084a", "application/x-silverlight-2"], ["Iframe"], ["Video"], ["EmbeddedAudio"], ["Audio"] ]; function normalizeSize(size) { return typeof(size) == "string" ? size.replace(/[^0-9%]/g, '') : size; } function toArray(obj) { var undef, out, i; if (obj && !obj.splice) { out = []; for (i = 0; true; i++) { if (obj[i]) out[i] = obj[i]; else break; } return out; } return obj; }; tinymce.create('tinymce.plugins.MediaPlugin', { init : function(ed, url) { var self = this, lookup = {}, i, y, item, name; function isMediaImg(node) { return node && node.nodeName === 'IMG' && ed.dom.hasClass(node, 'mceItemMedia'); }; self.editor = ed; self.url = url; // Parse media types into a lookup table scriptRegExp = ''; for (i = 0; i < mediaTypes.length; i++) { name = mediaTypes[i][0]; item = { name : name, clsids : tinymce.explode(mediaTypes[i][1] || ''), mimes : tinymce.explode(mediaTypes[i][2] || ''), codebase : mediaTypes[i][3] }; for (y = 0; y < item.clsids.length; y++) lookup['clsid:' + item.clsids[y]] = item; for (y = 0; y < item.mimes.length; y++) lookup[item.mimes[y]] = item; lookup['mceItem' + name] = item; lookup[name.toLowerCase()] = item; scriptRegExp += (scriptRegExp ? '|' : '') + name; } // Handle the media_types setting tinymce.each(ed.getParam("media_types", "video=mp4,m4v,ogv,webm;" + "silverlight=xap;" + "flash=swf,flv;" + "shockwave=dcr;" + "quicktime=mov,qt,mpg,mpeg;" + "shockwave=dcr;" + "windowsmedia=avi,wmv,wm,asf,asx,wmx,wvx;" + "realmedia=rm,ra,ram;" + "java=jar;" + "audio=mp3,ogg" ).split(';'), function(item) { var i, extensions, type; item = item.split(/=/); extensions = tinymce.explode(item[1].toLowerCase()); for (i = 0; i < extensions.length; i++) { type = lookup[item[0].toLowerCase()]; if (type) lookup[extensions[i]] = type; } }); scriptRegExp = new RegExp('write(' + scriptRegExp + ')\\(([^)]+)\\)'); self.lookup = lookup; ed.onPreInit.add(function() { // Allow video elements ed.schema.addValidElements('object[id|style|width|height|classid|codebase|*],param[name|value],embed[id|style|width|height|type|src|*],video[*],audio[*],source[*]'); // Convert video elements to image placeholder ed.parser.addNodeFilter('object,embed,video,audio,script,iframe', function(nodes) { var i = nodes.length; while (i--) self.objectToImg(nodes[i]); }); // Convert image placeholders to video elements ed.serializer.addNodeFilter('img', function(nodes, name, args) { var i = nodes.length, node; while (i--) { node = nodes[i]; if ((node.attr('class') || '').indexOf('mceItemMedia') !== -1) self.imgToObject(node, args); } }); }); ed.onInit.add(function() { // Display "media" instead of "img" in element path if (ed.theme && ed.theme.onResolveName) { ed.theme.onResolveName.add(function(theme, path_object) { if (path_object.name === 'img' && ed.dom.hasClass(path_object.node, 'mceItemMedia')) path_object.name = 'media'; }); } // Add contect menu if it's loaded if (ed && ed.plugins.contextmenu) { ed.plugins.contextmenu.onContextMenu.add(function(plugin, menu, element) { if (element.nodeName === 'IMG' && element.className.indexOf('mceItemMedia') !== -1) menu.add({title : 'media.edit', icon : 'media', cmd : 'mceMedia'}); }); } }); // Register commands ed.addCommand('mceMedia', function() { var data, img; img = ed.selection.getNode(); if (isMediaImg(img)) { data = ed.dom.getAttrib(img, 'data-mce-json'); if (data) { data = JSON.parse(data); // Add some extra properties to the data object tinymce.each(rootAttributes, function(name) { var value = ed.dom.getAttrib(img, name); if (value) data[name] = value; }); data.type = self.getType(img.className).name.toLowerCase(); } } if (!data) { data = { type : 'flash', video: {sources:[]}, params: {} }; } ed.windowManager.open({ file : url + '/media.htm', width : 430 + parseInt(ed.getLang('media.delta_width', 0)), height : 500 + parseInt(ed.getLang('media.delta_height', 0)), inline : 1 }, { plugin_url : url, data : data }); }); // Register buttons ed.addButton('media', {title : 'media.desc', cmd : 'mceMedia'}); // Update media selection status ed.onNodeChange.add(function(ed, cm, node) { cm.setActive('media', isMediaImg(node)); }); }, convertUrl : function(url, force_absolute) { var self = this, editor = self.editor, settings = editor.settings, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || self; if (!url) return url; if (force_absolute) return editor.documentBaseURI.toAbsolute(url); return urlConverter.call(urlConverterScope, url, 'src', 'object'); }, getInfo : function() { return { longname : 'Media', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/media', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, /** * Converts the JSON data object to an img node. */ dataToImg : function(data, force_absolute) { var self = this, editor = self.editor, baseUri = editor.documentBaseURI, sources, attrs, img, i; data.params.src = self.convertUrl(data.params.src, force_absolute); attrs = data.video.attrs; if (attrs) attrs.src = self.convertUrl(attrs.src, force_absolute); if (attrs) attrs.poster = self.convertUrl(attrs.poster, force_absolute); sources = toArray(data.video.sources); if (sources) { for (i = 0; i < sources.length; i++) sources[i].src = self.convertUrl(sources[i].src, force_absolute); } img = self.editor.dom.create('img', { id : data.id, style : data.style, align : data.align, hspace : data.hspace, vspace : data.vspace, src : self.editor.theme.url + '/img/trans.gif', 'class' : 'mceItemMedia mceItem' + self.getType(data.type).name, 'data-mce-json' : JSON.serialize(data, "'") }); img.width = data.width = normalizeSize(data.width || (data.type == 'audio' ? "300" : "320")); img.height = data.height = normalizeSize(data.height || (data.type == 'audio' ? "32" : "240")); return img; }, /** * Converts the JSON data object to a HTML string. */ dataToHtml : function(data, force_absolute) { return this.editor.serializer.serialize(this.dataToImg(data, force_absolute), {forced_root_block : '', force_absolute : force_absolute}); }, /** * Converts the JSON data object to a HTML string. */ htmlToData : function(html) { var fragment, img, data; data = { type : 'flash', video: {sources:[]}, params: {} }; fragment = this.editor.parser.parse(html); img = fragment.getAll('img')[0]; if (img) { data = JSON.parse(img.attr('data-mce-json')); data.type = this.getType(img.attr('class')).name.toLowerCase(); // Add some extra properties to the data object tinymce.each(rootAttributes, function(name) { var value = img.attr(name); if (value) data[name] = value; }); } return data; }, /** * Get type item by extension, class, clsid or mime type. * * @method getType * @param {String} value Value to get type item by. * @return {Object} Type item object or undefined. */ getType : function(value) { var i, values, typeItem; // Find type by checking the classes values = tinymce.explode(value, ' '); for (i = 0; i < values.length; i++) { typeItem = this.lookup[values[i]]; if (typeItem) return typeItem; } }, /** * Converts a tinymce.html.Node image element to video/object/embed. */ imgToObject : function(node, args) { var self = this, editor = self.editor, video, object, embed, iframe, name, value, data, source, sources, params, param, typeItem, i, item, mp4Source, replacement, posterSrc, style, audio; // Adds the flash player function addPlayer(video_src, poster_src) { var baseUri, flashVars, flashVarsOutput, params, flashPlayer; flashPlayer = editor.getParam('flash_video_player_url', self.convertUrl(self.url + '/moxieplayer.swf')); if (flashPlayer) { baseUri = editor.documentBaseURI; data.params.src = flashPlayer; // Convert the movie url to absolute urls if (editor.getParam('flash_video_player_absvideourl', true)) { video_src = baseUri.toAbsolute(video_src || '', true); poster_src = baseUri.toAbsolute(poster_src || '', true); } // Generate flash vars flashVarsOutput = ''; flashVars = editor.getParam('flash_video_player_flashvars', {url : '$url', poster : '$poster'}); tinymce.each(flashVars, function(value, name) { // Replace $url and $poster variables in flashvars value value = value.replace(/\$url/, video_src || ''); value = value.replace(/\$poster/, poster_src || ''); if (value.length > 0) flashVarsOutput += (flashVarsOutput ? '&' : '') + name + '=' + escape(value); }); if (flashVarsOutput.length) data.params.flashvars = flashVarsOutput; params = editor.getParam('flash_video_player_params', { allowfullscreen: true, allowscriptaccess: true }); tinymce.each(params, function(value, name) { data.params[name] = "" + value; }); } }; data = node.attr('data-mce-json'); if (!data) return; data = JSON.parse(data); typeItem = this.getType(node.attr('class')); style = node.attr('data-mce-style'); if (!style) { style = node.attr('style'); if (style) style = editor.dom.serializeStyle(editor.dom.parseStyle(style, 'img')); } // Use node width/height to override the data width/height when the placeholder is resized data.width = node.attr('width') || data.width; data.height = node.attr('height') || data.height; // Handle iframe if (typeItem.name === 'Iframe') { replacement = new Node('iframe', 1); tinymce.each(rootAttributes, function(name) { var value = node.attr(name); if (name == 'class' && value) value = value.replace(/mceItem.+ ?/g, ''); if (value && value.length > 0) replacement.attr(name, value); }); for (name in data.params) replacement.attr(name, data.params[name]); replacement.attr({ style: style, src: data.params.src }); node.replace(replacement); return; } // Handle scripts if (this.editor.settings.media_use_script) { replacement = new Node('script', 1).attr('type', 'text/javascript'); value = new Node('#text', 3); value.value = 'write' + typeItem.name + '(' + JSON.serialize(tinymce.extend(data.params, { width: node.attr('width'), height: node.attr('height') })) + ');'; replacement.append(value); node.replace(replacement); return; } // Add HTML5 video element if (typeItem.name === 'Video' && data.video.sources && data.video.sources[0]) { // Create new object element video = new Node('video', 1).attr(tinymce.extend({ id : node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style }, data.video.attrs)); // Get poster source and use that for flash fallback if (data.video.attrs) posterSrc = data.video.attrs.poster; sources = data.video.sources = toArray(data.video.sources); for (i = 0; i < sources.length; i++) { if (/\.mp4$/.test(sources[i].src)) mp4Source = sources[i].src; } if (!sources[0].type) { video.attr('src', sources[0].src); sources.splice(0, 1); } for (i = 0; i < sources.length; i++) { source = new Node('source', 1).attr(sources[i]); source.shortEnded = true; video.append(source); } // Create flash fallback for video if we have a mp4 source if (mp4Source) { addPlayer(mp4Source, posterSrc); typeItem = self.getType('flash'); } else data.params.src = ''; } // Add HTML5 audio element if (typeItem.name === 'Audio' && data.video.sources && data.video.sources[0]) { // Create new object element audio = new Node('audio', 1).attr(tinymce.extend({ id : node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style }, data.video.attrs)); // Get poster source and use that for flash fallback if (data.video.attrs) posterSrc = data.video.attrs.poster; sources = data.video.sources = toArray(data.video.sources); if (!sources[0].type) { audio.attr('src', sources[0].src); sources.splice(0, 1); } for (i = 0; i < sources.length; i++) { source = new Node('source', 1).attr(sources[i]); source.shortEnded = true; audio.append(source); } data.params.src = ''; } if (typeItem.name === 'EmbeddedAudio') { embed = new Node('embed', 1); embed.shortEnded = true; embed.attr({ id: node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style, type: node.attr('type') }); for (name in data.params) embed.attr(name, data.params[name]); tinymce.each(rootAttributes, function(name) { if (data[name] && name != 'type') embed.attr(name, data[name]); }); data.params.src = ''; } // Do we have a params src then we can generate object if (data.params.src) { // Is flv movie add player for it if (/\.flv$/i.test(data.params.src)) addPlayer(data.params.src, ''); if (args && args.force_absolute) data.params.src = editor.documentBaseURI.toAbsolute(data.params.src); // Create new object element object = new Node('object', 1).attr({ id : node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style }); tinymce.each(rootAttributes, function(name) { var value = data[name]; if (name == 'class' && value) value = value.replace(/mceItem.+ ?/g, ''); if (value && name != 'type') object.attr(name, value); }); // Add params for (name in data.params) { param = new Node('param', 1); param.shortEnded = true; value = data.params[name]; // Windows media needs to use url instead of src for the media URL if (name === 'src' && typeItem.name === 'WindowsMedia') name = 'url'; param.attr({name: name, value: value}); object.append(param); } // Setup add type and classid if strict is disabled if (this.editor.getParam('media_strict', true)) { object.attr({ data: data.params.src, type: typeItem.mimes[0] }); } else { if ( typeItem.clsids ) object.attr('clsid', typeItem.clsids[0]); object.attr('codebase', typeItem.codebase); embed = new Node('embed', 1); embed.shortEnded = true; embed.attr({ id: node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style, type: typeItem.mimes[0] }); for (name in data.params) embed.attr(name, data.params[name]); tinymce.each(rootAttributes, function(name) { if (data[name] && name != 'type') embed.attr(name, data[name]); }); object.append(embed); } // Insert raw HTML if (data.object_html) { value = new Node('#text', 3); value.raw = true; value.value = data.object_html; object.append(value); } // Append object to video element if it exists if (video) video.append(object); } if (video) { // Insert raw HTML if (data.video_html) { value = new Node('#text', 3); value.raw = true; value.value = data.video_html; video.append(value); } } if (audio) { // Insert raw HTML if (data.video_html) { value = new Node('#text', 3); value.raw = true; value.value = data.video_html; audio.append(value); } } var n = video || audio || object || embed; if (n) node.replace(n); else node.remove(); }, /** * Converts a tinymce.html.Node video/object/embed to an img element. * * The video/object/embed will be converted into an image placeholder with a JSON data attribute like this: * <img class="mceItemMedia mceItemFlash" width="100" height="100" data-mce-json="{..}" /> * * The JSON structure will be like this: * {'params':{'flashvars':'something','quality':'high','src':'someurl'}, 'video':{'sources':[{src: 'someurl', type: 'video/mp4'}]}} */ objectToImg : function(node) { var object, embed, video, iframe, img, name, id, width, height, style, i, html, param, params, source, sources, data, type, lookup = this.lookup, matches, attrs, urlConverter = this.editor.settings.url_converter, urlConverterScope = this.editor.settings.url_converter_scope, hspace, vspace, align, bgcolor; function getInnerHTML(node) { return new tinymce.html.Serializer({ inner: true, validate: false }).serialize(node); }; function lookupAttribute(o, attr) { return lookup[(o.attr(attr) || '').toLowerCase()]; } function lookupExtension(src) { var ext = src.replace(/^.*\.([^.]+)$/, '$1'); return lookup[ext.toLowerCase() || '']; } // If node isn't in document if (!node.parent) return; // Handle media scripts if (node.name === 'script') { if (node.firstChild) matches = scriptRegExp.exec(node.firstChild.value); if (!matches) return; type = matches[1]; data = {video : {}, params : JSON.parse(matches[2])}; width = data.params.width; height = data.params.height; } // Setup data objects data = data || { video : {}, params : {} }; // Setup new image object img = new Node('img', 1); img.attr({ src : this.editor.theme.url + '/img/trans.gif' }); // Video element name = node.name; if (name === 'video' || name == 'audio') { video = node; object = node.getAll('object')[0]; embed = node.getAll('embed')[0]; width = video.attr('width'); height = video.attr('height'); id = video.attr('id'); data.video = {attrs : {}, sources : []}; // Get all video attributes attrs = data.video.attrs; for (name in video.attributes.map) attrs[name] = video.attributes.map[name]; source = node.attr('src'); if (source) data.video.sources.push({src : urlConverter.call(urlConverterScope, source, 'src', node.name)}); // Get all sources sources = video.getAll("source"); for (i = 0; i < sources.length; i++) { source = sources[i].remove(); data.video.sources.push({ src: urlConverter.call(urlConverterScope, source.attr('src'), 'src', 'source'), type: source.attr('type'), media: source.attr('media') }); } // Convert the poster URL if (attrs.poster) attrs.poster = urlConverter.call(urlConverterScope, attrs.poster, 'poster', node.name); } // Object element if (node.name === 'object') { object = node; embed = node.getAll('embed')[0]; } // Embed element if (node.name === 'embed') embed = node; // Iframe element if (node.name === 'iframe') { iframe = node; type = 'Iframe'; } if (object) { // Get width/height width = width || object.attr('width'); height = height || object.attr('height'); style = style || object.attr('style'); id = id || object.attr('id'); hspace = hspace || object.attr('hspace'); vspace = vspace || object.attr('vspace'); align = align || object.attr('align'); bgcolor = bgcolor || object.attr('bgcolor'); data.name = object.attr('name'); // Get all object params params = object.getAll("param"); for (i = 0; i < params.length; i++) { param = params[i]; name = param.remove().attr('name'); if (!excludedAttrs[name]) data.params[name] = param.attr('value'); } data.params.src = data.params.src || object.attr('data'); } if (embed) { // Get width/height width = width || embed.attr('width'); height = height || embed.attr('height'); style = style || embed.attr('style'); id = id || embed.attr('id'); hspace = hspace || embed.attr('hspace'); vspace = vspace || embed.attr('vspace'); align = align || embed.attr('align'); bgcolor = bgcolor || embed.attr('bgcolor'); // Get all embed attributes for (name in embed.attributes.map) { if (!excludedAttrs[name] && !data.params[name]) data.params[name] = embed.attributes.map[name]; } } if (iframe) { // Get width/height width = normalizeSize(iframe.attr('width')); height = normalizeSize(iframe.attr('height')); style = style || iframe.attr('style'); id = iframe.attr('id'); hspace = iframe.attr('hspace'); vspace = iframe.attr('vspace'); align = iframe.attr('align'); bgcolor = iframe.attr('bgcolor'); tinymce.each(rootAttributes, function(name) { img.attr(name, iframe.attr(name)); }); // Get all iframe attributes for (name in iframe.attributes.map) { if (!excludedAttrs[name] && !data.params[name]) data.params[name] = iframe.attributes.map[name]; } } // Use src not movie if (data.params.movie) { data.params.src = data.params.src || data.params.movie; delete data.params.movie; } // Convert the URL to relative/absolute depending on configuration if (data.params.src) data.params.src = urlConverter.call(urlConverterScope, data.params.src, 'src', 'object'); if (video) { if (node.name === 'video') type = lookup.video.name; else if (node.name === 'audio') type = lookup.audio.name; } if (object && !type) type = (lookupAttribute(object, 'clsid') || lookupAttribute(object, 'classid') || lookupAttribute(object, 'type') || {}).name; if (embed && !type) type = (lookupAttribute(embed, 'type') || lookupExtension(data.params.src) || {}).name; // for embedded audio we preserve the original specified type if (embed && type == 'EmbeddedAudio') { data.params.type = embed.attr('type'); } // Replace the video/object/embed element with a placeholder image containing the data node.replace(img); // Remove embed if (embed) embed.remove(); // Serialize the inner HTML of the object element if (object) { html = getInnerHTML(object.remove()); if (html) data.object_html = html; } // Serialize the inner HTML of the video element if (video) { html = getInnerHTML(video.remove()); if (html) data.video_html = html; } data.hspace = hspace; data.vspace = vspace; data.align = align; data.bgcolor = bgcolor; // Set width/height of placeholder img.attr({ id : id, 'class' : 'mceItemMedia mceItem' + (type || 'Flash'), style : style, width : width || (node.name == 'audio' ? "300" : "320"), height : height || (node.name == 'audio' ? "32" : "240"), hspace : hspace, vspace : vspace, align : align, bgcolor : bgcolor, "data-mce-json" : JSON.serialize(data, "'") }); } }); // Register plugin tinymce.PluginManager.add('media', tinymce.plugins.MediaPlugin); })();
JavaScript
(function() { var url; if (url = tinyMCEPopup.getParam("media_external_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); function get(id) { return document.getElementById(id); } function clone(obj) { var i, len, copy, attr; if (null == obj || "object" != typeof obj) return obj; // Handle Array if ('length' in obj) { copy = []; for (i = 0, len = obj.length; i < len; ++i) { copy[i] = clone(obj[i]); } return copy; } // Handle Object copy = {}; for (attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } function getVal(id) { var elm = get(id); if (elm.nodeName == "SELECT") return elm.options[elm.selectedIndex].value; if (elm.type == "checkbox") return elm.checked; return elm.value; } function setVal(id, value, name) { if (typeof(value) != 'undefined' && value != null) { var elm = get(id); if (elm.nodeName == "SELECT") selectByValue(document.forms[0], id, value); else if (elm.type == "checkbox") { if (typeof(value) == 'string') { value = value.toLowerCase(); value = (!name && value === 'true') || (name && value === name.toLowerCase()); } elm.checked = !!value; } else elm.value = value; } } window.Media = { init : function() { var html, editor, self = this; self.editor = editor = tinyMCEPopup.editor; // Setup file browsers and color pickers get('filebrowsercontainer').innerHTML = getBrowserHTML('filebrowser','src','media','media'); get('qtsrcfilebrowsercontainer').innerHTML = getBrowserHTML('qtsrcfilebrowser','quicktime_qtsrc','media','media'); get('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); get('video_altsource1_filebrowser').innerHTML = getBrowserHTML('video_filebrowser_altsource1','video_altsource1','media','media'); get('video_altsource2_filebrowser').innerHTML = getBrowserHTML('video_filebrowser_altsource2','video_altsource2','media','media'); get('audio_altsource1_filebrowser').innerHTML = getBrowserHTML('audio_filebrowser_altsource1','audio_altsource1','media','media'); get('audio_altsource2_filebrowser').innerHTML = getBrowserHTML('audio_filebrowser_altsource2','audio_altsource2','media','media'); get('video_poster_filebrowser').innerHTML = getBrowserHTML('filebrowser_poster','video_poster','image','media'); html = self.getMediaListHTML('medialist', 'src', 'media', 'media'); if (html == "") get("linklistrow").style.display = 'none'; else get("linklistcontainer").innerHTML = html; if (isVisible('filebrowser')) get('src').style.width = '230px'; if (isVisible('video_filebrowser_altsource1')) get('video_altsource1').style.width = '220px'; if (isVisible('video_filebrowser_altsource2')) get('video_altsource2').style.width = '220px'; if (isVisible('audio_filebrowser_altsource1')) get('audio_altsource1').style.width = '220px'; if (isVisible('audio_filebrowser_altsource2')) get('audio_altsource2').style.width = '220px'; if (isVisible('filebrowser_poster')) get('video_poster').style.width = '220px'; editor.dom.setOuterHTML(get('media_type'), self.getMediaTypeHTML(editor)); self.setDefaultDialogSettings(editor); self.data = clone(tinyMCEPopup.getWindowArg('data')); self.dataToForm(); self.preview(); updateColor('bgcolor_pick', 'bgcolor'); }, insert : function() { var editor = tinyMCEPopup.editor; this.formToData(); editor.execCommand('mceRepaint'); tinyMCEPopup.restoreSelection(); editor.selection.setNode(editor.plugins.media.dataToImg(this.data)); tinyMCEPopup.close(); }, preview : function() { get('prev').innerHTML = this.editor.plugins.media.dataToHtml(this.data, true); }, moveStates : function(to_form, field) { var data = this.data, editor = this.editor, mediaPlugin = editor.plugins.media, ext, src, typeInfo, defaultStates, src; defaultStates = { // QuickTime quicktime_autoplay : true, quicktime_controller : true, // Flash flash_play : true, flash_loop : true, flash_menu : true, // WindowsMedia windowsmedia_autostart : true, windowsmedia_enablecontextmenu : true, windowsmedia_invokeurls : true, // RealMedia realmedia_autogotourl : true, realmedia_imagestatus : true }; function parseQueryParams(str) { var out = {}; if (str) { tinymce.each(str.split('&'), function(item) { var parts = item.split('='); out[unescape(parts[0])] = unescape(parts[1]); }); } return out; }; function setOptions(type, names) { var i, name, formItemName, value, list; if (type == data.type || type == 'global') { names = tinymce.explode(names); for (i = 0; i < names.length; i++) { name = names[i]; formItemName = type == 'global' ? name : type + '_' + name; if (type == 'global') list = data; else if (type == 'video' || type == 'audio') { list = data.video.attrs; if (!list && !to_form) data.video.attrs = list = {}; } else list = data.params; if (list) { if (to_form) { setVal(formItemName, list[name], type == 'video' || type == 'audio' ? name : ''); } else { delete list[name]; value = getVal(formItemName); if ((type == 'video' || type == 'audio') && value === true) value = name; if (defaultStates[formItemName]) { if (value !== defaultStates[formItemName]) { value = "" + value; list[name] = value; } } else if (value) { value = "" + value; list[name] = value; } } } } } } if (!to_form) { data.type = get('media_type').options[get('media_type').selectedIndex].value; data.width = getVal('width'); data.height = getVal('height'); // Switch type based on extension src = getVal('src'); if (field == 'src') { ext = src.replace(/^.*\.([^.]+)$/, '$1'); if (typeInfo = mediaPlugin.getType(ext)) data.type = typeInfo.name.toLowerCase(); setVal('media_type', data.type); } if (data.type == "video" || data.type == "audio") { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src: getVal('src')}; } } // Hide all fieldsets and show the one active get('video_options').style.display = 'none'; get('audio_options').style.display = 'none'; get('flash_options').style.display = 'none'; get('quicktime_options').style.display = 'none'; get('shockwave_options').style.display = 'none'; get('windowsmedia_options').style.display = 'none'; get('realmedia_options').style.display = 'none'; get('embeddedaudio_options').style.display = 'none'; if (get(data.type + '_options')) get(data.type + '_options').style.display = 'block'; setVal('media_type', data.type); setOptions('flash', 'play,loop,menu,swliveconnect,quality,scale,salign,wmode,base,flashvars'); setOptions('quicktime', 'loop,autoplay,cache,controller,correction,enablejavascript,kioskmode,autohref,playeveryframe,targetcache,scale,starttime,endtime,target,qtsrcchokespeed,volume,qtsrc'); setOptions('shockwave', 'sound,progress,autostart,swliveconnect,swvolume,swstretchstyle,swstretchhalign,swstretchvalign'); setOptions('windowsmedia', 'autostart,enabled,enablecontextmenu,fullscreen,invokeurls,mute,stretchtofit,windowlessvideo,balance,baseurl,captioningid,currentmarker,currentposition,defaultframe,playcount,rate,uimode,volume'); setOptions('realmedia', 'autostart,loop,autogotourl,center,imagestatus,maintainaspect,nojava,prefetch,shuffle,console,controls,numloop,scriptcallbacks'); setOptions('video', 'poster,autoplay,loop,muted,preload,controls'); setOptions('audio', 'autoplay,loop,preload,controls'); setOptions('embeddedaudio', 'autoplay,loop,controls'); setOptions('global', 'id,name,vspace,hspace,bgcolor,align,width,height'); if (to_form) { if (data.type == 'video') { if (data.video.sources[0]) setVal('src', data.video.sources[0].src); src = data.video.sources[1]; if (src) setVal('video_altsource1', src.src); src = data.video.sources[2]; if (src) setVal('video_altsource2', src.src); } else if (data.type == 'audio') { if (data.video.sources[0]) setVal('src', data.video.sources[0].src); src = data.video.sources[1]; if (src) setVal('audio_altsource1', src.src); src = data.video.sources[2]; if (src) setVal('audio_altsource2', src.src); } else { // Check flash vars if (data.type == 'flash') { tinymce.each(editor.getParam('flash_video_player_flashvars', {url : '$url', poster : '$poster'}), function(value, name) { if (value == '$url') data.params.src = parseQueryParams(data.params.flashvars)[name] || data.params.src || ''; }); } setVal('src', data.params.src); } } else { src = getVal("src"); // YouTube Embed if (src.match(/youtube\.com\/embed\/\w+/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; setVal('src', src); setVal('media_type', data.type); } else { // YouTube *NEW* if (src.match(/youtu\.be\/[a-z1-9.-_]+/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://www.youtube.com/embed/' + src.match(/youtu.be\/([a-z1-9.-_]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } // YouTube if (src.match(/youtube\.com(.+)v=([^&]+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://www.youtube.com/embed/' + src.match(/v=([^&]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } } // Google video if (src.match(/video\.google\.com(.+)docid=([^&]+)/)) { data.width = 425; data.height = 326; data.type = 'flash'; src = 'http://video.google.com/googleplayer.swf?docId=' + src.match(/docid=([^&]+)/)[1] + '&hl=en'; setVal('src', src); setVal('media_type', data.type); } // Vimeo if (src.match(/vimeo\.com\/([0-9]+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://player.vimeo.com/video/' + src.match(/vimeo.com\/([0-9]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } // stream.cz if (src.match(/stream\.cz\/((?!object).)*\/([0-9]+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://www.stream.cz/object/' + src.match(/stream.cz\/[^/]+\/([0-9]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } // Google maps if (src.match(/maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://maps.google.com/maps/ms?msid=' + src.match(/msid=(.+)/)[1] + "&output=embed"; setVal('src', src); setVal('media_type', data.type); } if (data.type == 'video') { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src : src}; src = getVal("video_altsource1"); if (src) data.video.sources[1] = {src : src}; src = getVal("video_altsource2"); if (src) data.video.sources[2] = {src : src}; } else if (data.type == 'audio') { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src : src}; src = getVal("audio_altsource1"); if (src) data.video.sources[1] = {src : src}; src = getVal("audio_altsource2"); if (src) data.video.sources[2] = {src : src}; } else data.params.src = src; // Set default size setVal('width', data.width || (data.type == 'audio' ? 300 : 320)); setVal('height', data.height || (data.type == 'audio' ? 32 : 240)); } }, dataToForm : function() { this.moveStates(true); }, formToData : function(field) { if (field == "width" || field == "height") this.changeSize(field); if (field == 'source') { this.moveStates(false, field); setVal('source', this.editor.plugins.media.dataToHtml(this.data)); this.panel = 'source'; } else { if (this.panel == 'source') { this.data = clone(this.editor.plugins.media.htmlToData(getVal('source'))); this.dataToForm(); this.panel = ''; } this.moveStates(false, field); this.preview(); } }, beforeResize : function() { this.width = parseInt(getVal('width') || (this.data.type == 'audio' ? "300" : "320"), 10); this.height = parseInt(getVal('height') || (this.data.type == 'audio' ? "32" : "240"), 10); }, changeSize : function(type) { var width, height, scale, size; if (get('constrain').checked) { width = parseInt(getVal('width') || (this.data.type == 'audio' ? "300" : "320"), 10); height = parseInt(getVal('height') || (this.data.type == 'audio' ? "32" : "240"), 10); if (type == 'width') { this.height = Math.round((width / this.width) * height); setVal('height', this.height); } else { this.width = Math.round((height / this.height) * width); setVal('width', this.width); } } }, getMediaListHTML : function() { if (typeof(tinyMCEMediaList) != "undefined" && tinyMCEMediaList.length > 0) { var html = ""; html += '<select id="linklist" name="linklist" style="width: 250px" onchange="this.form.src.value=this.options[this.selectedIndex].value;Media.formToData(\'src\');">'; html += '<option value="">---</option>'; for (var i=0; i<tinyMCEMediaList.length; i++) html += '<option value="' + tinyMCEMediaList[i][1] + '">' + tinyMCEMediaList[i][0] + '</option>'; html += '</select>'; return html; } return ""; }, getMediaTypeHTML : function(editor) { function option(media_type, element) { if (!editor.schema.getElementRule(element || media_type)) { return ''; } return '<option value="'+media_type+'">'+tinyMCEPopup.editor.translate("media_dlg."+media_type)+'</option>' } var html = ""; html += '<select id="media_type" name="media_type" onchange="Media.formToData(\'type\');">'; html += option("video"); html += option("audio"); html += option("flash", "object"); html += option("quicktime", "object"); html += option("shockwave", "object"); html += option("windowsmedia", "object"); html += option("realmedia", "object"); html += option("iframe"); if (editor.getParam('media_embedded_audio', false)) { html += option('embeddedaudio', "object"); } html += '</select>'; return html; }, setDefaultDialogSettings : function(editor) { var defaultDialogSettings = editor.getParam("media_dialog_defaults", {}); tinymce.each(defaultDialogSettings, function(v, k) { setVal(k, v); }); } }; tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(function() { Media.init(); }); })();
JavaScript
/** * This script contains embed functions for common plugins. This scripts are complety free to use for any purpose. */ function writeFlash(p) { writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); } function writeShockWave(p) { writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); } function writeQuickTime(p) { writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); } function writeRealMedia(p) { writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); } function writeWindowsMedia(p) { p.url = p.src; writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); } function writeEmbed(cls, cb, mt, p) { var h = '', n; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; document.write(h); }
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.WPDialogs', { init : function(ed, url) { tinymce.create('tinymce.WPWindowManager:tinymce.InlineWindowManager', { WPWindowManager : function(ed) { this.parent(ed); }, open : function(f, p) { var t = this, element; if ( ! f.wpDialog ) return this.parent( f, p ); else if ( ! f.id ) return; element = jQuery('#' + f.id); if ( ! element.length ) return; t.features = f; t.params = p; t.onOpen.dispatch(t, f, p); t.element = t.windows[ f.id ] = element; // Store selection t.bookmark = t.editor.selection.getBookmark(1); // Create the dialog if necessary if ( ! element.data('wpdialog') ) { element.wpdialog({ title: f.title, width: f.width, height: f.height, modal: true, dialogClass: 'wp-dialog', zIndex: 300000 }); } element.wpdialog('open'); }, close : function() { if ( ! this.features.wpDialog ) return this.parent.apply( this, arguments ); this.element.wpdialog('close'); } }); // Replace window manager ed.onBeforeRenderUI.add(function() { ed.windowManager = new tinymce.WPWindowManager(ed); }); }, getInfo : function() { return { longname : 'WPDialogs', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '0.1' }; } }); // Register plugin tinymce.PluginManager.add('wpdialogs', tinymce.plugins.WPDialogs); })();
JavaScript
/** * popup.js * * An altered version of tinyMCEPopup to work in the same window as tinymce. * * ------------------------------------------------------------------ * * Copyright 2009, Moxiecode Systems AB * Released under LGPL * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ // Some global instances /** * TinyMCE popup/dialog helper class. This gives you easy access to the * parent editor instance and a bunch of other things. It's higly recommended * that you load this script into your dialogs. * * @static * @class tinyMCEPopup */ var tinyMCEPopup = { /** * Initializes the popup this will be called automatically. * * @method init */ init : function() { var t = this, w, ti; // Find window & API w = t.getWin(); tinymce = w.tinymce; tinyMCE = w.tinyMCE; t.editor = tinymce.EditorManager.activeEditor; t.params = t.editor.windowManager.params; t.features = t.editor.windowManager.features; t.dom = tinymce.dom; // Setup on init listeners t.listeners = []; t.onInit = { add : function(f, s) { t.listeners.push({func : f, scope : s}); } }; t.isWindow = false; t.id = t.features.id; t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window); }, /** * Returns the reference to the parent window that opened the dialog. * * @method getWin * @return {Window} Reference to the parent window that opened the dialog. */ getWin : function() { return window; }, /** * Returns a window argument/parameter by name. * * @method getWindowArg * @param {String} n Name of the window argument to retrieve. * @param {String} dv Optional default value to return. * @return {String} Argument value or default value if it wasn't found. */ getWindowArg : function(n, dv) { var v = this.params[n]; return tinymce.is(v) ? v : dv; }, /** * Returns a editor parameter/config option value. * * @method getParam * @param {String} n Name of the editor config option to retrieve. * @param {String} dv Optional default value to return. * @return {String} Parameter value or default value if it wasn't found. */ getParam : function(n, dv) { return this.editor.getParam(n, dv); }, /** * Returns a language item by key. * * @method getLang * @param {String} n Language item like mydialog.something. * @param {String} dv Optional default value to return. * @return {String} Language value for the item like "my string" or the default value if it wasn't found. */ getLang : function(n, dv) { return this.editor.getLang(n, dv); }, /** * Executed a command on editor that opened the dialog/popup. * * @method execCommand * @param {String} cmd Command to execute. * @param {Boolean} ui Optional boolean value if the UI for the command should be presented or not. * @param {Object} val Optional value to pass with the comman like an URL. * @param {Object} a Optional arguments object. */ execCommand : function(cmd, ui, val, a) { a = a || {}; a.skip_focus = 1; this.restoreSelection(); return this.editor.execCommand(cmd, ui, val, a); }, /** * Resizes the dialog to the inner size of the window. This is needed since various browsers * have different border sizes on windows. * * @method resizeToInnerSize */ resizeToInnerSize : function() { var t = this; // Detach it to workaround a Chrome specific bug // https://sourceforge.net/tracker/?func=detail&atid=635682&aid=2926339&group_id=103281 setTimeout(function() { var vp = t.dom.getViewPort(window); t.editor.windowManager.resizeBy( t.getWindowArg('mce_width') - vp.w, t.getWindowArg('mce_height') - vp.h, t.id || window ); }, 0); }, /** * Will executed the specified string when the page has been loaded. This function * was added for compatibility with the 2.x branch. * * @method executeOnLoad * @param {String} s String to evalutate on init. */ executeOnLoad : function(s) { this.onInit.add(function() { eval(s); }); }, /** * Stores the current editor selection for later restoration. This can be useful since some browsers * loses its selection if a control element is selected/focused inside the dialogs. * * @method storeSelection */ storeSelection : function() { this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark(1); }, /** * Restores any stored selection. This can be useful since some browsers * loses its selection if a control element is selected/focused inside the dialogs. * * @method restoreSelection */ restoreSelection : function() { var t = tinyMCEPopup; if (!t.isWindow && tinymce.isIE) t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark); }, /** * Loads a specific dialog language pack. If you pass in plugin_url as a arugment * when you open the window it will load the <plugin url>/langs/<code>_dlg.js lang pack file. * * @method requireLangPack */ requireLangPack : function() { var t = this, u = t.getWindowArg('plugin_url') || t.getWindowArg('theme_url'); if (u && t.editor.settings.language && t.features.translate_i18n !== false) { u += '/langs/' + t.editor.settings.language + '_dlg.js'; if (!tinymce.ScriptLoader.isDone(u)) { document.write('<script type="text/javascript" src="' + tinymce._addVer(u) + '"></script>'); tinymce.ScriptLoader.markDone(u); } } }, /** * Executes a color picker on the specified element id. When the user * then selects a color it will be set as the value of the specified element. * * @method pickColor * @param {DOMEvent} e DOM event object. * @param {string} element_id Element id to be filled with the color value from the picker. */ pickColor : function(e, element_id) { this.execCommand('mceColorPicker', true, { color : document.getElementById(element_id).value, func : function(c) { document.getElementById(element_id).value = c; try { document.getElementById(element_id).onchange(); } catch (ex) { // Try fire event, ignore errors } } }); }, /** * Opens a filebrowser/imagebrowser this will set the output value from * the browser as a value on the specified element. * * @method openBrowser * @param {string} element_id Id of the element to set value in. * @param {string} type Type of browser to open image/file/flash. * @param {string} option Option name to get the file_broswer_callback function name from. */ openBrowser : function(element_id, type, option) { tinyMCEPopup.restoreSelection(); this.editor.execCallback('file_browser_callback', element_id, document.getElementById(element_id).value, type, window); }, /** * Creates a confirm dialog. Please don't use the blocking behavior of this * native version use the callback method instead then it can be extended. * * @method confirm * @param {String} t Title for the new confirm dialog. * @param {function} cb Callback function to be executed after the user has selected ok or cancel. * @param {Object} s Optional scope to execute the callback in. */ confirm : function(t, cb, s) { this.editor.windowManager.confirm(t, cb, s, window); }, /** * Creates an alert dialog. Please don't use the blocking behavior of this * native version use the callback method instead then it can be extended. * * @method alert * @param {String} t Title for the new alert dialog. * @param {function} cb Callback function to be executed after the user has selected ok. * @param {Object} s Optional scope to execute the callback in. */ alert : function(tx, cb, s) { this.editor.windowManager.alert(tx, cb, s, window); }, /** * Closes the current window. * * @method close */ close : function() { var t = this; // To avoid domain relaxing issue in Opera function close() { t.editor.windowManager.close(window); t.editor = null; }; if (tinymce.isOpera) t.getWin().setTimeout(close, 0); else close(); }, // Internal functions _restoreSelection : function() { var e = window.event.srcElement; if (e.nodeName == 'INPUT' && (e.type == 'submit' || e.type == 'button')) tinyMCEPopup.restoreSelection(); }, /* _restoreSelection : function() { var e = window.event.srcElement; // If user focus a non text input or textarea if ((e.nodeName != 'INPUT' && e.nodeName != 'TEXTAREA') || e.type != 'text') tinyMCEPopup.restoreSelection(); },*/ _onDOMLoaded : function() { var t = tinyMCEPopup, ti = document.title, bm, h, nv; if (t.domLoaded) return; t.domLoaded = 1; tinyMCEPopup.init(); // Translate page if (t.features.translate_i18n !== false) { h = document.body.innerHTML; // Replace a=x with a="x" in IE if (tinymce.isIE) h = h.replace(/ (value|title|alt)=([^"][^\s>]+)/gi, ' $1="$2"') document.dir = t.editor.getParam('directionality',''); if ((nv = t.editor.translate(h)) && nv != h) document.body.innerHTML = nv; if ((nv = t.editor.translate(ti)) && nv != ti) document.title = ti = nv; } document.body.style.display = ''; // Restore selection in IE when focus is placed on a non textarea or input element of the type text if (tinymce.isIE) { document.attachEvent('onmouseup', tinyMCEPopup._restoreSelection); // Add base target element for it since it would fail with modal dialogs t.dom.add(t.dom.select('head')[0], 'base', {target : '_self'}); } t.restoreSelection(); // Set inline title if (!t.isWindow) t.editor.windowManager.setTitle(window, ti); else window.focus(); if (!tinymce.isIE && !t.isWindow) { tinymce.dom.Event._add(document, 'focus', function() { t.editor.windowManager.focus(t.id); }); } // Patch for accessibility tinymce.each(t.dom.select('select'), function(e) { e.onkeydown = tinyMCEPopup._accessHandler; }); // Call onInit // Init must be called before focus so the selection won't get lost by the focus call tinymce.each(t.listeners, function(o) { o.func.call(o.scope, t.editor); }); // Move focus to window if (t.getWindowArg('mce_auto_focus', true)) { window.focus(); // Focus element with mceFocus class tinymce.each(document.forms, function(f) { tinymce.each(f.elements, function(e) { if (t.dom.hasClass(e, 'mceFocus') && !e.disabled) { e.focus(); return false; // Break loop } }); }); } document.onkeyup = tinyMCEPopup._closeWinKeyHandler; }, _accessHandler : function(e) { e = e || window.event; if (e.keyCode == 13 || e.keyCode == 32) { e = e.target || e.srcElement; if (e.onchange) e.onchange(); return tinymce.dom.Event.cancel(e); } }, _closeWinKeyHandler : function(e) { e = e || window.event; if (e.keyCode == 27) tinyMCEPopup.close(); }, _wait : function() { // Use IE method if (document.attachEvent) { document.attachEvent("onreadystatechange", function() { if (document.readyState === "complete") { document.detachEvent("onreadystatechange", arguments.callee); tinyMCEPopup._onDOMLoaded(); } }); if (document.documentElement.doScroll && window == window.top) { (function() { if (tinyMCEPopup.domLoaded) return; try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch (ex) { setTimeout(arguments.callee, 0); return; } tinyMCEPopup._onDOMLoaded(); })(); } document.attachEvent('onload', tinyMCEPopup._onDOMLoaded); } else if (document.addEventListener) { window.addEventListener('DOMContentLoaded', tinyMCEPopup._onDOMLoaded, false); window.addEventListener('load', tinyMCEPopup._onDOMLoaded, false); } } };
JavaScript
(function($){ $.ui.dialog.prototype.options.closeOnEscape = false; $.widget('wp.wpdialog', $.ui.dialog, { // Work around a bug in jQuery UI 1.9.1. // http://bugs.jqueryui.com/ticket/8805 widgetEventPrefix: 'wpdialog', open: function() { var ed; // Initialize tinyMCEPopup if it exists and the editor is active. if ( tinyMCEPopup && typeof tinyMCE != 'undefined' && ( ed = tinyMCE.activeEditor ) && !ed.isHidden() ) { tinyMCEPopup.init(); } // Add beforeOpen event. if ( this.isOpen() || false === this._trigger('beforeOpen') ) { return; } // Open the dialog. this._super(); // WebKit leaves focus in the TinyMCE editor unless we shift focus. this.element.focus(); this._trigger('refresh'); } }); })(jQuery);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Directionality', { init : function(ed, url) { var t = this; t.editor = ed; function setDir(dir) { var dom = ed.dom, curDir, blocks = ed.selection.getSelectedBlocks(); if (blocks.length) { curDir = dom.getAttrib(blocks[0], "dir"); tinymce.each(blocks, function(block) { // Add dir to block if the parent block doesn't already have that dir if (!dom.getParent(block.parentNode, "*[dir='" + dir + "']", dom.getRoot())) { if (curDir != dir) { dom.setAttrib(block, "dir", dir); } else { dom.setAttrib(block, "dir", null); } } }); ed.nodeChanged(); } } ed.addCommand('mceDirectionLTR', function() { setDir("ltr"); }); ed.addCommand('mceDirectionRTL', function() { setDir("rtl"); }); ed.addButton('ltr', {title : 'directionality.ltr_desc', cmd : 'mceDirectionLTR'}); ed.addButton('rtl', {title : 'directionality.rtl_desc', cmd : 'mceDirectionRTL'}); ed.onNodeChange.add(t._nodeChange, t); }, getInfo : function() { return { longname : 'Directionality', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/directionality', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var dom = ed.dom, dir; n = dom.getParent(n, dom.isBlock); if (!n) { cm.setDisabled('ltr', 1); cm.setDisabled('rtl', 1); return; } dir = dom.getAttrib(n, 'dir'); cm.setActive('ltr', dir == "ltr"); cm.setDisabled('ltr', 0); cm.setActive('rtl', dir == "rtl"); cm.setDisabled('rtl', 0); } }); // Register plugin tinymce.PluginManager.add('directionality', tinymce.plugins.Directionality); })();
JavaScript
/** * WP Fullscreen TinyMCE plugin * * Contains code from Moxiecode Systems AB released under LGPL http://tinymce.moxiecode.com/license */ (function() { tinymce.create('tinymce.plugins.wpFullscreenPlugin', { resize_timeout: false, init : function(ed, url) { var t = this, oldHeight = 0, s = {}, DOM = tinymce.DOM; // Register commands ed.addCommand('wpFullScreenClose', function() { // this removes the editor, content has to be saved first with tinyMCE.execCommand('wpFullScreenSave'); if ( ed.getParam('wp_fullscreen_is_enabled') ) { DOM.win.setTimeout(function() { tinyMCE.remove(ed); DOM.remove('wp_mce_fullscreen_parent'); tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings }, 10); } }); ed.addCommand('wpFullScreenSave', function() { var ed = tinyMCE.get('wp_mce_fullscreen'), edd; ed.focus(); edd = tinyMCE.get( ed.getParam('wp_fullscreen_editor_id') ); edd.setContent( ed.getContent({format : 'raw'}), {format : 'raw'} ); }); ed.addCommand('wpFullScreenInit', function() { var d, b, fsed; ed = tinyMCE.activeEditor; d = ed.getDoc(); b = d.body; tinyMCE.oldSettings = tinyMCE.settings; // Store old settings tinymce.each(ed.settings, function(v, n) { s[n] = v; }); s.id = 'wp_mce_fullscreen'; s.wp_fullscreen_is_enabled = true; s.wp_fullscreen_editor_id = ed.id; s.theme_advanced_resizing = false; s.theme_advanced_statusbar_location = 'none'; s.content_css = s.content_css ? s.content_css + ',' + s.wp_fullscreen_content_css : s.wp_fullscreen_content_css; s.height = tinymce.isIE ? b.scrollHeight : b.offsetHeight; tinymce.each(ed.getParam('wp_fullscreen_settings'), function(v, k) { s[k] = v; }); fsed = new tinymce.Editor('wp_mce_fullscreen', s); fsed.onInit.add(function(edd) { var DOM = tinymce.DOM, buttons = DOM.select('a.mceButton', DOM.get('wp-fullscreen-buttons')); if ( !ed.isHidden() ) edd.setContent( ed.getContent() ); else edd.setContent( switchEditors.wpautop( edd.getElement().value ) ); setTimeout(function(){ // add last edd.onNodeChange.add(function(ed, cm, e){ tinymce.each(buttons, function(c) { var btn, cls; if ( btn = DOM.get( 'wp_mce_fullscreen_' + c.id.substr(6) ) ) { cls = btn.className; if ( cls ) c.className = cls; } }); }); }, 1000); edd.dom.addClass(edd.getBody(), 'wp-fullscreen-editor'); edd.focus(); }); fsed.render(); if ( 'undefined' != fullscreen ) { fsed.dom.bind( fsed.dom.doc, 'mousemove', function(e){ fullscreen.bounder( 'showToolbar', 'hideToolbar', 2000, e ); }); } }); ed.addCommand('wpFullScreen', function() { if ( typeof(fullscreen) == 'undefined' ) return; if ( 'wp_mce_fullscreen' == ed.id ) fullscreen.off(); else fullscreen.on(); }); // Register buttons ed.addButton('wp_fullscreen', { title : 'wordpress.wp_fullscreen_desc', cmd : 'wpFullScreen' }); // END fullscreen //---------------------------------------------------------------- // START autoresize if ( ed.getParam('fullscreen_is_enabled') || !ed.getParam('wp_fullscreen_is_enabled') ) return; /** * This method gets executed each time the editor needs to resize. */ function resize(editor, e) { var DOM = tinymce.DOM, body = ed.getBody(), ifr = DOM.get(ed.id + '_ifr'), height, y = ed.dom.win.scrollY; if ( t.resize_timeout ) return; // sometimes several events are fired few ms apart, trottle down resizing a little t.resize_timeout = true; setTimeout(function(){ t.resize_timeout = false; }, 500); height = body.scrollHeight > 300 ? body.scrollHeight : 300; if ( height != ifr.scrollHeight ) { DOM.setStyle(ifr, 'height', height + 'px'); ed.getWin().scrollTo(0, 0); // iframe window object, make sure there's no scrolling } // WebKit scrolls to top on paste... if ( e && e.type == 'paste' && tinymce.isWebKit ) { setTimeout(function(){ ed.dom.win.scrollTo(0, y); }, 40); } }; // Add appropriate listeners for resizing content area ed.onInit.add(function(ed, l) { ed.onChange.add(resize); ed.onSetContent.add(resize); ed.onPaste.add(resize); ed.onKeyUp.add(resize); ed.onPostRender.add(resize); ed.getBody().style.overflowY = "hidden"; }); if ( ed.getParam('autoresize_on_init', true) ) { ed.onLoadContent.add(function(ed, l) { // Because the content area resizes when its content CSS loads, // and we can't easily add a listener to its onload event, // we'll just trigger a resize after a short loading period setTimeout(function() { resize(); }, 1200); }); } // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('wpAutoResize', resize); }, getInfo : function() { return { longname : 'WP Fullscreen', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : '1.0' }; } }); // Register plugin tinymce.PluginManager.add('wpfullscreen', tinymce.plugins.wpFullscreenPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, explode = tinymce.explode; tinymce.create('tinymce.plugins.TabFocusPlugin', { init : function(ed, url) { function tabCancel(ed, e) { if (e.keyCode === 9) return Event.cancel(e); } function tabHandler(ed, e) { var x, i, f, el, v; function find(d) { el = DOM.select(':input:enabled,*[tabindex]:not(iframe)'); function canSelectRecursive(e) { return e.nodeName==="BODY" || (e.type != 'hidden' && !(e.style.display == "none") && !(e.style.visibility == "hidden") && canSelectRecursive(e.parentNode)); } function canSelectInOldIe(el) { return el.attributes["tabIndex"].specified || el.nodeName == "INPUT" || el.nodeName == "TEXTAREA"; } function isOldIe() { return tinymce.isIE6 || tinymce.isIE7; } function canSelect(el) { return ((!isOldIe() || canSelectInOldIe(el))) && el.getAttribute("tabindex") != '-1' && canSelectRecursive(el); } each(el, function(e, i) { if (e.id == ed.id) { x = i; return false; } }); if (d > 0) { for (i = x + 1; i < el.length; i++) { if (canSelect(el[i])) return el[i]; } } else { for (i = x - 1; i >= 0; i--) { if (canSelect(el[i])) return el[i]; } } return null; } if (e.keyCode === 9) { v = explode(ed.getParam('tab_focus', ed.getParam('tabfocus_elements', ':prev,:next'))); if (v.length == 1) { v[1] = v[0]; v[0] = ':prev'; } // Find element to focus if (e.shiftKey) { if (v[0] == ':prev') el = find(-1); else el = DOM.get(v[0]); } else { if (v[1] == ':next') el = find(1); else el = DOM.get(v[1]); } if (el) { if (el.id && (ed = tinymce.get(el.id || el.name))) ed.focus(); else window.setTimeout(function() { if (!tinymce.isWebKit) window.focus(); el.focus(); }, 10); return Event.cancel(e); } } } ed.onKeyUp.add(tabCancel); if (tinymce.isGecko) { ed.onKeyPress.add(tabHandler); ed.onKeyDown.add(tabCancel); } else ed.onKeyDown.add(tabHandler); }, getInfo : function() { return { longname : 'Tabfocus', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/tabfocus', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('tabfocus', tinymce.plugins.TabFocusPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Element = tinymce.dom.Element, Event = tinymce.dom.Event, each = tinymce.each, is = tinymce.is; tinymce.create('tinymce.plugins.InlinePopups', { init : function(ed, url) { // Replace window manager ed.onBeforeRenderUI.add(function() { ed.windowManager = new tinymce.InlineWindowManager(ed); DOM.loadCSS(url + '/skins/' + (ed.settings.inlinepopups_skin || 'clearlooks2') + "/window.css"); }); }, getInfo : function() { return { longname : 'InlinePopups', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.create('tinymce.InlineWindowManager:tinymce.WindowManager', { InlineWindowManager : function(ed) { var t = this; t.parent(ed); t.zIndex = 300000; t.count = 0; t.windows = {}; }, open : function(f, p) { var t = this, id, opt = '', ed = t.editor, dw = 0, dh = 0, vp, po, mdf, clf, we, w, u, parentWindow; f = f || {}; p = p || {}; // Run native windows if (!f.inline) return t.parent(f, p); parentWindow = t._frontWindow(); if (parentWindow && DOM.get(parentWindow.id + '_ifr')) { parentWindow.focussedElement = DOM.get(parentWindow.id + '_ifr').contentWindow.document.activeElement; } // Only store selection if the type is a normal window if (!f.type) t.bookmark = ed.selection.getBookmark(1); id = DOM.uniqueId(); vp = DOM.getViewPort(); f.width = parseInt(f.width || 320); f.height = parseInt(f.height || 240) + (tinymce.isIE ? 8 : 0); f.min_width = parseInt(f.min_width || 150); f.min_height = parseInt(f.min_height || 100); f.max_width = parseInt(f.max_width || 2000); f.max_height = parseInt(f.max_height || 2000); f.left = f.left || Math.round(Math.max(vp.x, vp.x + (vp.w / 2.0) - (f.width / 2.0))); f.top = f.top || Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (f.height / 2.0))); f.movable = f.resizable = true; p.mce_width = f.width; p.mce_height = f.height; p.mce_inline = true; p.mce_window_id = id; p.mce_auto_focus = f.auto_focus; // Transpose // po = DOM.getPos(ed.getContainer()); // f.left -= po.x; // f.top -= po.y; t.features = f; t.params = p; t.onOpen.dispatch(t, f, p); if (f.type) { opt += ' mceModal'; if (f.type) opt += ' mce' + f.type.substring(0, 1).toUpperCase() + f.type.substring(1); f.resizable = false; } if (f.statusbar) opt += ' mceStatusbar'; if (f.resizable) opt += ' mceResizable'; if (f.minimizable) opt += ' mceMinimizable'; if (f.maximizable) opt += ' mceMaximizable'; if (f.movable) opt += ' mceMovable'; // Create DOM objects t._addAll(DOM.doc.body, ['div', {id : id, role : 'dialog', 'aria-labelledby': f.type ? id + '_content' : id + '_title', 'class' : (ed.settings.inlinepopups_skin || 'clearlooks2') + (tinymce.isIE && window.getSelection ? ' ie9' : ''), style : 'width:100px;height:100px'}, ['div', {id : id + '_wrapper', 'class' : 'mceWrapper' + opt}, ['div', {id : id + '_top', 'class' : 'mceTop'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_title'}, f.title || ''] ], ['div', {id : id + '_middle', 'class' : 'mceMiddle'}, ['div', {id : id + '_left', 'class' : 'mceLeft', tabindex : '0'}], ['span', {id : id + '_content'}], ['div', {id : id + '_right', 'class' : 'mceRight', tabindex : '0'}] ], ['div', {id : id + '_bottom', 'class' : 'mceBottom'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_status'}, 'Content'] ], ['a', {'class' : 'mceMove', tabindex : '-1', href : 'javascript:;'}], ['a', {'class' : 'mceMin', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMax', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMed', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceClose', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {id : id + '_resize_n', 'class' : 'mceResize mceResizeN', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_s', 'class' : 'mceResize mceResizeS', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_w', 'class' : 'mceResize mceResizeW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_e', 'class' : 'mceResize mceResizeE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_nw', 'class' : 'mceResize mceResizeNW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_ne', 'class' : 'mceResize mceResizeNE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_sw', 'class' : 'mceResize mceResizeSW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_se', 'class' : 'mceResize mceResizeSE', tabindex : '-1', href : 'javascript:;'}] ] ] ); DOM.setStyles(id, {top : -10000, left : -10000}); // Fix gecko rendering bug, where the editors iframe messed with window contents if (tinymce.isGecko) DOM.setStyle(id, 'overflow', 'auto'); // Measure borders if (!f.type) { dw += DOM.get(id + '_left').clientWidth; dw += DOM.get(id + '_right').clientWidth; dh += DOM.get(id + '_top').clientHeight; dh += DOM.get(id + '_bottom').clientHeight; } // Resize window DOM.setStyles(id, {top : f.top, left : f.left, width : f.width + dw, height : f.height + dh}); u = f.url || f.file; if (u) { if (tinymce.relaxedDomain) u += (u.indexOf('?') == -1 ? '?' : '&') + 'mce_rdomain=' + tinymce.relaxedDomain; u = tinymce._addVer(u); } if (!f.type) { DOM.add(id + '_content', 'iframe', {id : id + '_ifr', src : 'javascript:""', frameBorder : 0, style : 'border:0;width:10px;height:10px'}); DOM.setStyles(id + '_ifr', {width : f.width, height : f.height}); DOM.setAttrib(id + '_ifr', 'src', u); } else { DOM.add(id + '_wrapper', 'a', {id : id + '_ok', 'class' : 'mceButton mceOk', href : 'javascript:;', onmousedown : 'return false;'}, 'Ok'); if (f.type == 'confirm') DOM.add(id + '_wrapper', 'a', {'class' : 'mceButton mceCancel', href : 'javascript:;', onmousedown : 'return false;'}, 'Cancel'); DOM.add(id + '_middle', 'div', {'class' : 'mceIcon'}); DOM.setHTML(id + '_content', f.content.replace('\n', '<br />')); Event.add(id, 'keyup', function(evt) { var VK_ESCAPE = 27; if (evt.keyCode === VK_ESCAPE) { f.button_func(false); return Event.cancel(evt); } }); Event.add(id, 'keydown', function(evt) { var cancelButton, VK_TAB = 9; if (evt.keyCode === VK_TAB) { cancelButton = DOM.select('a.mceCancel', id + '_wrapper')[0]; if (cancelButton && cancelButton !== evt.target) { cancelButton.focus(); } else { DOM.get(id + '_ok').focus(); } return Event.cancel(evt); } }); } // Register events mdf = Event.add(id, 'mousedown', function(e) { var n = e.target, w, vp; w = t.windows[id]; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { if (n.className == 'mceClose') { t.close(null, id); return Event.cancel(e); } else if (n.className == 'mceMax') { w.oldPos = w.element.getXY(); w.oldSize = w.element.getSize(); vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars vp.w -= 2; vp.h -= 2; w.element.moveTo(vp.x, vp.y); w.element.resizeTo(vp.w, vp.h); DOM.setStyles(id + '_ifr', {width : vp.w - w.deltaWidth, height : vp.h - w.deltaHeight}); DOM.addClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMed') { // Reset to old size w.element.moveTo(w.oldPos.x, w.oldPos.y); w.element.resizeTo(w.oldSize.w, w.oldSize.h); w.iframeElement.resizeTo(w.oldSize.w - w.deltaWidth, w.oldSize.h - w.deltaHeight); DOM.removeClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMove') return t._startDrag(id, e, n.className); else if (DOM.hasClass(n, 'mceResize')) return t._startDrag(id, e, n.className.substring(13)); } }); clf = Event.add(id, 'click', function(e) { var n = e.target; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { switch (n.className) { case 'mceClose': t.close(null, id); return Event.cancel(e); case 'mceButton mceOk': case 'mceButton mceCancel': f.button_func(n.className == 'mceButton mceOk'); return Event.cancel(e); } } }); // Make sure the tab order loops within the dialog. Event.add([id + '_left', id + '_right'], 'focus', function(evt) { var iframe = DOM.get(id + '_ifr'); if (iframe) { var body = iframe.contentWindow.document.body; var focusable = DOM.select(':input:enabled,*[tabindex=0]', body); if (evt.target.id === (id + '_left')) { focusable[focusable.length - 1].focus(); } else { focusable[0].focus(); } } else { DOM.get(id + '_ok').focus(); } }); // Add window w = t.windows[id] = { id : id, mousedown_func : mdf, click_func : clf, element : new Element(id, {blocker : 1, container : ed.getContainer()}), iframeElement : new Element(id + '_ifr'), features : f, deltaWidth : dw, deltaHeight : dh }; w.iframeElement.on('focus', function() { t.focus(id); }); // Setup blocker if (t.count == 0 && t.editor.getParam('dialog_type', 'modal') == 'modal') { DOM.add(DOM.doc.body, 'div', { id : 'mceModalBlocker', 'class' : (t.editor.settings.inlinepopups_skin || 'clearlooks2') + '_modalBlocker', style : {zIndex : t.zIndex - 1} }); DOM.show('mceModalBlocker'); // Reduces flicker in IE DOM.setAttrib(DOM.doc.body, 'aria-hidden', 'true'); } else DOM.setStyle('mceModalBlocker', 'z-index', t.zIndex - 1); if (tinymce.isIE6 || /Firefox\/2\./.test(navigator.userAgent) || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceModalBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); DOM.setAttrib(id, 'aria-hidden', 'false'); t.focus(id); t._fixIELayout(id, 1); // Focus ok button if (DOM.get(id + '_ok')) DOM.get(id + '_ok').focus(); t.count++; return w; }, focus : function(id) { var t = this, w; if (w = t.windows[id]) { w.zIndex = this.zIndex++; w.element.setStyle('zIndex', w.zIndex); w.element.update(); id = id + '_wrapper'; DOM.removeClass(t.lastId, 'mceFocus'); DOM.addClass(id, 'mceFocus'); t.lastId = id; if (w.focussedElement) { w.focussedElement.focus(); } else if (DOM.get(id + '_ok')) { DOM.get(w.id + '_ok').focus(); } else if (DOM.get(w.id + '_ifr')) { DOM.get(w.id + '_ifr').focus(); } } }, _addAll : function(te, ne) { var i, n, t = this, dom = tinymce.DOM; if (is(ne, 'string')) te.appendChild(dom.doc.createTextNode(ne)); else if (ne.length) { te = te.appendChild(dom.create(ne[0], ne[1])); for (i=2; i<ne.length; i++) t._addAll(te, ne[i]); } }, _startDrag : function(id, se, ac) { var t = this, mu, mm, d = DOM.doc, eb, w = t.windows[id], we = w.element, sp = we.getXY(), p, sz, ph, cp, vp, sx, sy, sex, sey, dx, dy, dw, dh; // Get positons and sizes // cp = DOM.getPos(t.editor.getContainer()); cp = {x : 0, y : 0}; vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars while dragging vp.w -= 2; vp.h -= 2; sex = se.screenX; sey = se.screenY; dx = dy = dw = dh = 0; // Handle mouse up mu = Event.add(d, 'mouseup', function(e) { Event.remove(d, 'mouseup', mu); Event.remove(d, 'mousemove', mm); if (eb) eb.remove(); we.moveBy(dx, dy); we.resizeBy(dw, dh); sz = we.getSize(); DOM.setStyles(id + '_ifr', {width : sz.w - w.deltaWidth, height : sz.h - w.deltaHeight}); t._fixIELayout(id, 1); return Event.cancel(e); }); if (ac != 'Move') startMove(); function startMove() { if (eb) return; t._fixIELayout(id, 0); // Setup event blocker DOM.add(d.body, 'div', { id : 'mceEventBlocker', 'class' : 'mceEventBlocker ' + (t.editor.settings.inlinepopups_skin || 'clearlooks2'), style : {zIndex : t.zIndex + 1} }); if (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceEventBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); eb = new Element('mceEventBlocker'); eb.update(); // Setup placeholder p = we.getXY(); sz = we.getSize(); sx = cp.x + p.x - vp.x; sy = cp.y + p.y - vp.y; DOM.add(eb.get(), 'div', {id : 'mcePlaceHolder', 'class' : 'mcePlaceHolder', style : {left : sx, top : sy, width : sz.w, height : sz.h}}); ph = new Element('mcePlaceHolder'); }; // Handle mouse move/drag mm = Event.add(d, 'mousemove', function(e) { var x, y, v; startMove(); x = e.screenX - sex; y = e.screenY - sey; switch (ac) { case 'ResizeW': dx = x; dw = 0 - x; break; case 'ResizeE': dw = x; break; case 'ResizeN': case 'ResizeNW': case 'ResizeNE': if (ac == "ResizeNW") { dx = x; dw = 0 - x; } else if (ac == "ResizeNE") dw = x; dy = y; dh = 0 - y; break; case 'ResizeS': case 'ResizeSW': case 'ResizeSE': if (ac == "ResizeSW") { dx = x; dw = 0 - x; } else if (ac == "ResizeSE") dw = x; dh = y; break; case 'mceMove': dx = x; dy = y; break; } // Boundary check if (dw < (v = w.features.min_width - sz.w)) { if (dx !== 0) dx += dw - v; dw = v; } if (dh < (v = w.features.min_height - sz.h)) { if (dy !== 0) dy += dh - v; dh = v; } dw = Math.min(dw, w.features.max_width - sz.w); dh = Math.min(dh, w.features.max_height - sz.h); dx = Math.max(dx, vp.x - (sx + vp.x)); dy = Math.max(dy, vp.y - (sy + vp.y)); dx = Math.min(dx, (vp.w + vp.x) - (sx + sz.w + vp.x)); dy = Math.min(dy, (vp.h + vp.y) - (sy + sz.h + vp.y)); // Move if needed if (dx + dy !== 0) { if (sx + dx < 0) dx = 0; if (sy + dy < 0) dy = 0; ph.moveTo(sx + dx, sy + dy); } // Resize if needed if (dw + dh !== 0) ph.resizeTo(sz.w + dw, sz.h + dh); return Event.cancel(e); }); return Event.cancel(se); }, resizeBy : function(dw, dh, id) { var w = this.windows[id]; if (w) { w.element.resizeBy(dw, dh); w.iframeElement.resizeBy(dw, dh); } }, close : function(win, id) { var t = this, w, d = DOM.doc, fw, id; id = t._findId(id || win); // Probably not inline if (!t.windows[id]) { t.parent(win); return; } t.count--; if (t.count == 0) { DOM.remove('mceModalBlocker'); DOM.setAttrib(DOM.doc.body, 'aria-hidden', 'false'); t.editor.focus(); } if (w = t.windows[id]) { t.onClose.dispatch(t); Event.remove(d, 'mousedown', w.mousedownFunc); Event.remove(d, 'click', w.clickFunc); Event.clear(id); Event.clear(id + '_ifr'); DOM.setAttrib(id + '_ifr', 'src', 'javascript:""'); // Prevent leak w.element.remove(); delete t.windows[id]; fw = t._frontWindow(); if (fw) t.focus(fw.id); } }, // Find front most window _frontWindow : function() { var fw, ix = 0; // Find front most window and focus that each (this.windows, function(w) { if (w.zIndex > ix) { fw = w; ix = w.zIndex; } }); return fw; }, setTitle : function(w, ti) { var e; w = this._findId(w); if (e = DOM.get(w + '_title')) e.innerHTML = DOM.encode(ti); }, alert : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'alert', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, confirm : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'confirm', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, // Internal functions _findId : function(w) { var t = this; if (typeof(w) == 'string') return w; each(t.windows, function(wo) { var ifr = DOM.get(wo.id + '_ifr'); if (ifr && w == ifr.contentWindow) { w = wo.id; return false; } }); return w; }, _fixIELayout : function(id, s) { var w, img; if (!tinymce.isIE6) return; // Fixes the bug where hover flickers and does odd things in IE6 each(['n','s','w','e','nw','ne','sw','se'], function(v) { var e = DOM.get(id + '_resize_' + v); DOM.setStyles(e, { width : s ? e.clientWidth : '', height : s ? e.clientHeight : '', cursor : DOM.getStyle(e, 'cursor', 1) }); DOM.setStyle(id + "_bottom", 'bottom', '-1px'); e = 0; }); // Fixes graphics glitch if (w = this.windows[id]) { // Fixes rendering bug after resize w.element.hide(); w.element.show(); // Forced a repaint of the window //DOM.get(id).style.filter = ''; // IE has a bug where images used in CSS won't get loaded // sometimes when the cache in the browser is disabled // This fix tries to solve it by loading the images using the image object each(DOM.select('div,a', id), function(e, i) { if (e.currentStyle.backgroundImage != 'none') { img = new Image(); img.src = e.currentStyle.backgroundImage.replace(/url\(\"(.+)\"\)/, '$1'); } }); DOM.get(id).style.filter = ''; } } }); // Register plugin tinymce.PluginManager.add('inlinepopups', tinymce.plugins.InlinePopups); })();
JavaScript
(function() { tinymce.create('tinymce.plugins.wpGallery', { init : function(ed, url) { var t = this; t.url = url; t.editor = ed; t._createButtons(); // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...'); ed.addCommand('WP_Gallery', function() { if ( tinymce.isIE ) ed.selection.moveToBookmark( ed.wpGalleryBookmark ); var el = ed.selection.getNode(), gallery = wp.media.gallery, frame; // Check if the `wp.media.gallery` API exists. if ( typeof wp === 'undefined' || ! wp.media || ! wp.media.gallery ) return; // Make sure we've selected a gallery node. if ( el.nodeName != 'IMG' || ed.dom.getAttrib(el, 'class').indexOf('wp-gallery') == -1 ) return; frame = gallery.edit( '[' + ed.dom.getAttrib( el, 'title' ) + ']' ); frame.state('gallery-edit').on( 'update', function( selection ) { var shortcode = gallery.shortcode( selection ).string().slice( 1, -1 ); ed.dom.setAttrib( el, 'title', shortcode ); }); }); ed.onInit.add(function(ed) { // iOS6 doesn't show the buttons properly on click, show them on 'touchstart' if ( 'ontouchstart' in window ) { ed.dom.events.add(ed.getBody(), 'touchstart', function(e){ var target = e.target; if ( target.nodeName == 'IMG' && ed.dom.hasClass(target, 'wp-gallery') ) { ed.selection.select(target); ed.dom.events.cancel(e); ed.plugins.wordpress._hideButtons(); ed.plugins.wordpress._showButtons(target, 'wp_gallerybtns'); } }); } }); ed.onMouseDown.add(function(ed, e) { if ( e.target.nodeName == 'IMG' && ed.dom.hasClass(e.target, 'wp-gallery') ) { ed.plugins.wordpress._hideButtons(); ed.plugins.wordpress._showButtons(e.target, 'wp_gallerybtns'); } }); ed.onBeforeSetContent.add(function(ed, o) { o.content = t._do_gallery(o.content); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = t._get_gallery(o.content); }); }, _do_gallery : function(co) { return co.replace(/\[gallery([^\]]*)\]/g, function(a,b){ return '<img src="'+tinymce.baseURL+'/plugins/wpgallery/img/t.gif" class="wp-gallery mceItem" title="gallery'+tinymce.DOM.encode(b)+'" />'; }); }, _get_gallery : function(co) { function getAttr(s, n) { n = new RegExp(n + '=\"([^\"]+)\"', 'g').exec(s); return n ? tinymce.DOM.decode(n[1]) : ''; }; return co.replace(/(?:<p[^>]*>)*(<img[^>]+>)(?:<\/p>)*/g, function(a,im) { var cls = getAttr(im, 'class'); if ( cls.indexOf('wp-gallery') != -1 ) return '<p>['+tinymce.trim(getAttr(im, 'title'))+']</p>'; return a; }); }, _createButtons : function() { var t = this, ed = tinymce.activeEditor, DOM = tinymce.DOM, editButton, dellButton, isRetina; if ( DOM.get('wp_gallerybtns') ) return; isRetina = ( window.devicePixelRatio && window.devicePixelRatio > 1 ) || // WebKit, Opera ( window.matchMedia && window.matchMedia('(min-resolution:130dpi)').matches ); // Firefox, IE10, Opera DOM.add(document.body, 'div', { id : 'wp_gallerybtns', style : 'display:none;' }); editButton = DOM.add('wp_gallerybtns', 'img', { src : isRetina ? t.url+'/img/edit-2x.png' : t.url+'/img/edit.png', id : 'wp_editgallery', width : '24', height : '24', title : ed.getLang('wordpress.editgallery') }); tinymce.dom.Event.add(editButton, 'mousedown', function(e) { var ed = tinymce.activeEditor; ed.wpGalleryBookmark = ed.selection.getBookmark('simple'); ed.execCommand("WP_Gallery"); ed.plugins.wordpress._hideButtons(); }); dellButton = DOM.add('wp_gallerybtns', 'img', { src : isRetina ? t.url+'/img/delete-2x.png' : t.url+'/img/delete.png', id : 'wp_delgallery', width : '24', height : '24', title : ed.getLang('wordpress.delgallery') }); tinymce.dom.Event.add(dellButton, 'mousedown', function(e) { var ed = tinymce.activeEditor, el = ed.selection.getNode(); if ( el.nodeName == 'IMG' && ed.dom.hasClass(el, 'wp-gallery') ) { ed.dom.remove(el); ed.execCommand('mceRepaint'); ed.dom.events.cancel(e); } ed.plugins.wordpress._hideButtons(); }); }, getInfo : function() { return { longname : 'Gallery Settings', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); tinymce.PluginManager.add('wpgallery', tinymce.plugins.wpGallery); })();
JavaScript
/** * WordPress plugin. */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.WordPress', { init : function(ed, url) { var t = this, tbId = ed.getParam('wordpress_adv_toolbar', 'toolbar2'), last = 0, moreHTML, nextpageHTML, closeOnClick, mod_key, style; moreHTML = '<img src="' + url + '/img/trans.gif" class="mce-wp-more mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />'; nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mce-wp-nextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />'; if ( getUserSetting('hidetb', '0') == '1' ) ed.settings.wordpress_adv_hidden = 0; // Hides the specified toolbar and resizes the iframe ed.onPostRender.add(function() { var adv_toolbar = ed.controlManager.get(tbId); if ( ed.getParam('wordpress_adv_hidden', 1) && adv_toolbar ) { DOM.hide(adv_toolbar.id); t._resizeIframe(ed, tbId, 28); } }); // Register commands ed.addCommand('WP_More', function() { ed.execCommand('mceInsertContent', 0, moreHTML); }); ed.addCommand('WP_Page', function() { ed.execCommand('mceInsertContent', 0, nextpageHTML); }); ed.addCommand('WP_Help', function() { ed.windowManager.open({ url : tinymce.baseURL + '/wp-mce-help.php', width : 450, height : 420, inline : 1 }); }); ed.addCommand('WP_Adv', function() { var cm = ed.controlManager, id = cm.get(tbId).id; if ( 'undefined' == id ) return; if ( DOM.isHidden(id) ) { cm.setActive('wp_adv', 1); DOM.show(id); t._resizeIframe(ed, tbId, -28); ed.settings.wordpress_adv_hidden = 0; setUserSetting('hidetb', '1'); } else { cm.setActive('wp_adv', 0); DOM.hide(id); t._resizeIframe(ed, tbId, 28); ed.settings.wordpress_adv_hidden = 1; setUserSetting('hidetb', '0'); } }); ed.addCommand('WP_Medialib', function() { if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) wp.media.editor.open( ed.id ); }); // Register buttons ed.addButton('wp_more', { title : 'wordpress.wp_more_desc', cmd : 'WP_More' }); ed.addButton('wp_page', { title : 'wordpress.wp_page_desc', image : url + '/img/page.gif', cmd : 'WP_Page' }); ed.addButton('wp_help', { title : 'wordpress.wp_help_desc', cmd : 'WP_Help' }); ed.addButton('wp_adv', { title : 'wordpress.wp_adv_desc', cmd : 'WP_Adv' }); // Add Media button ed.addButton('add_media', { title : 'wordpress.add_media', image : url + '/img/image.gif', cmd : 'WP_Medialib' }); // Add Media buttons to fullscreen and handle align buttons for image captions ed.onBeforeExecCommand.add(function(ed, cmd, ui, val, o) { var DOM = tinymce.DOM, n, DL, DIV, cls, a, align; if ( 'mceFullScreen' == cmd ) { if ( 'mce_fullscreen' != ed.id && DOM.select('a.thickbox').length ) ed.settings.theme_advanced_buttons1 += ',|,add_media'; } if ( 'JustifyLeft' == cmd || 'JustifyRight' == cmd || 'JustifyCenter' == cmd ) { n = ed.selection.getNode(); if ( n.nodeName == 'IMG' ) { align = cmd.substr(7).toLowerCase(); a = 'align' + align; DL = ed.dom.getParent(n, 'dl.wp-caption'); DIV = ed.dom.getParent(n, 'div.mceTemp'); if ( DL && DIV ) { cls = ed.dom.hasClass(DL, a) ? 'alignnone' : a; DL.className = DL.className.replace(/align[^ '"]+\s?/g, ''); ed.dom.addClass(DL, cls); if (cls == 'aligncenter') ed.dom.addClass(DIV, 'mceIEcenter'); else ed.dom.removeClass(DIV, 'mceIEcenter'); o.terminate = true; ed.execCommand('mceRepaint'); } else { if ( ed.dom.hasClass(n, a) ) ed.dom.addClass(n, 'alignnone'); else ed.dom.removeClass(n, 'alignnone'); } } } if ( tinymce.isWebKit && ( 'InsertUnorderedList' == cmd || 'InsertOrderedList' == cmd ) ) { if ( !style ) style = ed.dom.create('style', {'type': 'text/css'}, '#tinymce,#tinymce span,#tinymce li,#tinymce li>span,#tinymce p,#tinymce p>span{font:medium sans-serif;color:#000;line-height:normal;}'); ed.getDoc().head.appendChild( style ); } }); ed.onExecCommand.add( function( ed, cmd, ui, val ) { if ( tinymce.isWebKit && style && ( 'InsertUnorderedList' == cmd || 'InsertOrderedList' == cmd ) ) ed.dom.remove( style ); }); ed.onInit.add(function(ed) { var bodyClass = ed.getParam('body_class', ''), body = ed.getBody(); // add body classes if ( bodyClass ) bodyClass = bodyClass.split(' '); else bodyClass = []; if ( ed.getParam('directionality', '') == 'rtl' ) bodyClass.push('rtl'); if ( tinymce.isIE9 ) bodyClass.push('ie9'); else if ( tinymce.isIE8 ) bodyClass.push('ie8'); else if ( tinymce.isIE7 ) bodyClass.push('ie7'); if ( ed.id != 'wp_mce_fullscreen' && ed.id != 'mce_fullscreen' ) bodyClass.push('wp-editor'); else if ( ed.id == 'mce_fullscreen' ) bodyClass.push('mce-fullscreen'); tinymce.each( bodyClass, function(cls){ if ( cls ) ed.dom.addClass(body, cls); }); // make sure these run last ed.onNodeChange.add( function(ed, cm, e) { var DL; if ( e.nodeName == 'IMG' ) { DL = ed.dom.getParent(e, 'dl.wp-caption'); } else if ( e.nodeName == 'DIV' && ed.dom.hasClass(e, 'mceTemp') ) { DL = e.firstChild; if ( ! ed.dom.hasClass(DL, 'wp-caption') ) DL = false; } if ( DL ) { if ( ed.dom.hasClass(DL, 'alignleft') ) cm.setActive('justifyleft', 1); else if ( ed.dom.hasClass(DL, 'alignright') ) cm.setActive('justifyright', 1); else if ( ed.dom.hasClass(DL, 'aligncenter') ) cm.setActive('justifycenter', 1); } }); // remove invalid parent paragraphs when pasting HTML and/or switching to the HTML editor and back ed.onBeforeSetContent.add(function(ed, o) { if ( o.content ) { o.content = o.content.replace(/<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)( [^>]*)?>/gi, '<$1$2>'); o.content = o.content.replace(/<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)>\s*<\/p>/gi, '</$1>'); } }); }); // Word count if ( 'undefined' != typeof(jQuery) ) { ed.onKeyUp.add(function(ed, e) { var k = e.keyCode || e.charCode; if ( k == last ) return; if ( 13 == k || 8 == last || 46 == last ) jQuery(document).triggerHandler('wpcountwords', [ ed.getContent({format : 'raw'}) ]); last = k; }); }; // keep empty paragraphs :( ed.onSaveContent.addToTop(function(ed, o) { o.content = o.content.replace(/<p>(<br ?\/?>|\u00a0|\uFEFF)?<\/p>/g, '<p>&nbsp;</p>'); }); // Fix bug in iOS Safari where it's impossible to type after a touchstart event on the parent document. // Happens after zooming in or out while the keyboard is open. See #25131. if ( tinymce.isIOS5 ) { ed.onKeyDown.add( function() { if ( document.activeElement == document.body ) { ed.getWin().focus(); } }); } ed.onSaveContent.add(function(ed, o) { // If editor is hidden, we just want the textarea's value to be saved if ( ed.isHidden() ) o.content = o.element.value; else if ( ed.getParam('wpautop', true) && typeof(switchEditors) == 'object' ) o.content = switchEditors.pre_wpautop(o.content); }); /* disable for now ed.onBeforeSetContent.add(function(ed, o) { o.content = t._setEmbed(o.content); }); ed.onPostProcess.add(function(ed, o) { if ( o.get ) o.content = t._getEmbed(o.content); }); */ // Add listeners to handle more break t._handleMoreBreak(ed, url); // Add custom shortcuts mod_key = 'alt+shift'; // if ( tinymce.isGecko ) // disable for mow, too many shortcuts conflicts // mod_key = 'ctrl+alt'; ed.addShortcut(mod_key + '+c', 'justifycenter_desc', 'JustifyCenter'); ed.addShortcut(mod_key + '+r', 'justifyright_desc', 'JustifyRight'); ed.addShortcut(mod_key + '+l', 'justifyleft_desc', 'JustifyLeft'); ed.addShortcut(mod_key + '+j', 'justifyfull_desc', 'JustifyFull'); ed.addShortcut(mod_key + '+q', 'blockquote_desc', 'mceBlockQuote'); ed.addShortcut(mod_key + '+u', 'bullist_desc', 'InsertUnorderedList'); ed.addShortcut(mod_key + '+o', 'numlist_desc', 'InsertOrderedList'); ed.addShortcut(mod_key + '+n', 'spellchecker.desc', 'mceSpellCheck'); ed.addShortcut(mod_key + '+a', 'link_desc', 'WP_Link'); ed.addShortcut(mod_key + '+s', 'unlink_desc', 'unlink'); ed.addShortcut(mod_key + '+m', 'image_desc', 'WP_Medialib'); ed.addShortcut(mod_key + '+z', 'wordpress.wp_adv_desc', 'WP_Adv'); ed.addShortcut(mod_key + '+t', 'wordpress.wp_more_desc', 'WP_More'); ed.addShortcut(mod_key + '+d', 'striketrough_desc', 'Strikethrough'); ed.addShortcut(mod_key + '+h', 'help_desc', 'WP_Help'); ed.addShortcut(mod_key + '+p', 'wordpress.wp_page_desc', 'WP_Page'); ed.addShortcut('ctrl+s', 'save_desc', function(){if('function'==typeof autosave)autosave();}); if ( /\bwpfullscreen\b/.test(ed.settings.plugins) ) ed.addShortcut(mod_key + '+w', 'wordpress.wp_fullscreen_desc', 'wpFullScreen'); else if ( /\bfullscreen\b/.test(ed.settings.plugins) ) ed.addShortcut(mod_key + '+g', 'fullscreen.desc', 'mceFullScreen'); // popup buttons for images and the gallery ed.onInit.add(function(ed) { tinymce.dom.Event.add(ed.getWin(), 'scroll', function(e) { ed.plugins.wordpress._hideButtons(); }); tinymce.dom.Event.add(ed.getBody(), 'dragstart', function(e) { ed.plugins.wordpress._hideButtons(); }); }); ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { ed.plugins.wordpress._hideButtons(); }); ed.onSaveContent.add(function(ed, o) { ed.plugins.wordpress._hideButtons(); }); ed.onMouseDown.add(function(ed, e) { if ( e.target.nodeName != 'IMG' ) ed.plugins.wordpress._hideButtons(); }); ed.onKeyDown.add(function(ed, e){ if ( e.which == tinymce.VK.DELETE || e.which == tinymce.VK.BACKSPACE ) ed.plugins.wordpress._hideButtons(); }); closeOnClick = function(e){ var id; if ( e.target.id == 'mceModalBlocker' || e.target.className == 'ui-widget-overlay' ) { for ( id in ed.windowManager.windows ) { ed.windowManager.close(null, id); } } } // close popups when clicking on the background tinymce.dom.Event.remove(document.body, 'click', closeOnClick); tinymce.dom.Event.add(document.body, 'click', closeOnClick); }, getInfo : function() { return { longname : 'WordPress Plugin', author : 'WordPress', // add Moxiecode? authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '3.0' }; }, // Internal functions _setEmbed : function(c) { return c.replace(/\[embed\]([\s\S]+?)\[\/embed\][\s\u00a0]*/g, function(a,b){ return '<img width="300" height="200" src="' + tinymce.baseURL + '/plugins/wordpress/img/trans.gif" class="wp-oembed mceItemNoResize" alt="'+b+'" title="'+b+'" />'; }); }, _getEmbed : function(c) { return c.replace(/<img[^>]+>/g, function(a) { if ( a.indexOf('class="wp-oembed') != -1 ) { var u = a.match(/alt="([^\"]+)"/); if ( u[1] ) a = '[embed]' + u[1] + '[/embed]'; } return a; }); }, _showButtons : function(n, id) { var ed = tinyMCE.activeEditor, p1, p2, vp, DOM = tinymce.DOM, X, Y; vp = ed.dom.getViewPort(ed.getWin()); p1 = DOM.getPos(ed.getContentAreaContainer()); p2 = ed.dom.getPos(n); X = Math.max(p2.x - vp.x, 0) + p1.x; Y = Math.max(p2.y - vp.y, 0) + p1.y; DOM.setStyles(id, { 'top' : Y+5+'px', 'left' : X+5+'px', 'display' : 'block' }); }, _hideButtons : function() { var DOM = tinymce.DOM; DOM.hide( DOM.select('#wp_editbtns, #wp_gallerybtns') ); }, // Resizes the iframe by a relative height value _resizeIframe : function(ed, tb_id, dy) { var ifr = ed.getContentAreaContainer().firstChild; DOM.setStyle(ifr, 'height', ifr.clientHeight + dy); // Resize iframe ed.theme.deltaHeight += dy; // For resize cookie }, _handleMoreBreak : function(ed, url) { var moreHTML, nextpageHTML; moreHTML = '<img src="' + url + '/img/trans.gif" alt="$1" class="mce-wp-more mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />'; nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mce-wp-nextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />'; // Display morebreak instead if img in element path ed.onPostRender.add(function() { if (ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.node.nodeName == 'IMG') { if ( ed.dom.hasClass(o.node, 'mce-wp-more') ) o.name = 'wpmore'; if ( ed.dom.hasClass(o.node, 'mce-wp-nextpage') ) o.name = 'wppage'; } }); } }); // Replace morebreak with images ed.onBeforeSetContent.add(function(ed, o) { if ( o.content ) { o.content = o.content.replace(/<!--more(.*?)-->/g, moreHTML); o.content = o.content.replace(/<!--nextpage-->/g, nextpageHTML); } }); // Replace images with morebreak ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = o.content.replace(/<img[^>]+>/g, function(im) { if (im.indexOf('class="mce-wp-more') !== -1) { var m, moretext = (m = im.match(/alt="(.*?)"/)) ? m[1] : ''; im = '<!--more'+moretext+'-->'; } if (im.indexOf('class="mce-wp-nextpage') !== -1) im = '<!--nextpage-->'; return im; }); }); // Set active buttons if user selected pagebreak or more break ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('wp_page', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mce-wp-nextpage')); cm.setActive('wp_more', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mce-wp-more')); }); } }); // Register plugin tinymce.PluginManager.add('wordpress', tinymce.plugins.WordPress); })();
JavaScript
/** * WordPress View plugin. */ (function() { var VK = tinymce.VK, TreeWalker = tinymce.dom.TreeWalker, selected; tinymce.create('tinymce.plugins.wpView', { init : function( editor, url ) { var wpView = this; // Check if the `wp.mce` API exists. if ( typeof wp === 'undefined' || ! wp.mce ) return; editor.onPreInit.add( function( editor ) { // Add elements so we can set `contenteditable` to false. editor.schema.addValidElements('div[*],span[*]'); }); // When the editor's content changes, scan the new content for // matching view patterns, and transform the matches into // view wrappers. Since the editor's DOM is outdated at this point, // we'll wait to render the views. editor.onBeforeSetContent.add( function( editor, o ) { if ( ! o.content ) return; o.content = wp.mce.view.toViews( o.content ); }); // When the editor's content has been updated and the DOM has been // processed, render the views in the document. editor.onSetContent.add( function( editor, o ) { wp.mce.view.render( editor.getDoc() ); }); editor.onInit.add( function( editor ) { // When a view is selected, ensure content that is being pasted // or inserted is added to a text node (instead of the view). editor.selection.onBeforeSetContent.add( function( selection, o ) { var view = wpView.getParentView( selection.getNode() ), walker, target; // If the selection is not within a view, bail. if ( ! view ) return; // If there are no additional nodes or the next node is a // view, create a text node after the current view. if ( ! view.nextSibling || wpView.isView( view.nextSibling ) ) { target = editor.getDoc().createTextNode(''); editor.dom.insertAfter( target, view ); // Otherwise, find the next text node. } else { walker = new TreeWalker( view.nextSibling, view.nextSibling ); target = walker.next(); } // Select the `target` text node. selection.select( target ); selection.collapse( true ); }); // When the selection's content changes, scan any new content // for matching views and immediately render them. // // Runs on paste and on inserting nodes/html. editor.selection.onSetContent.add( function( selection, o ) { if ( ! o.context ) return; var node = selection.getNode(); if ( ! node.innerHTML ) return; node.innerHTML = wp.mce.view.toViews( node.innerHTML ); wp.mce.view.render( node ); }); }); // When the editor's contents are being accessed as a string, // transform any views back to their text representations. editor.onPostProcess.add( function( editor, o ) { if ( ( ! o.get && ! o.save ) || ! o.content ) return; o.content = wp.mce.view.toText( o.content ); }); // Triggers when the selection is changed. // Add the event handler to the top of the stack. editor.onNodeChange.addToTop( function( editor, controlManager, node, collapsed, o ) { var view = wpView.getParentView( node ); // Update the selected view. if ( view ) { wpView.select( view ); // Prevent the selection from propagating to other plugins. return false; // If we've clicked off of the selected view, deselect it. } else { wpView.deselect(); } }); editor.onKeyDown.addToTop( function( editor, event ) { var keyCode = event.keyCode, view, instance; // If a view isn't selected, let the event go on its merry way. if ( ! selected ) return; // If the caret is not within the selected view, deselect the // view and bail. view = wpView.getParentView( editor.selection.getNode() ); if ( view !== selected ) { wpView.deselect(); return; } // If delete or backspace is pressed, delete the view. if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) { if ( (instance = wp.mce.view.instance( selected )) ) { instance.remove(); wpView.deselect(); } } // Let keypresses that involve the command or control keys through. // Also, let any of the F# keys through. if ( event.metaKey || event.ctrlKey || ( keyCode >= 112 && keyCode <= 123 ) ) return; event.preventDefault(); }); }, getParentView : function( node ) { while ( node ) { if ( this.isView( node ) ) return node; node = node.parentNode; } }, isView : function( node ) { return (/(?:^|\s)wp-view-wrap(?:\s|$)/).test( node.className ); }, select : function( view ) { if ( view === selected ) return; this.deselect(); selected = view; wp.mce.view.select( selected ); }, deselect : function() { if ( selected ) wp.mce.view.deselect( selected ); selected = null; }, getInfo : function() { return { longname : 'WordPress Views', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '1.0' }; } }); // Register plugin tinymce.PluginManager.add( 'wpview', tinymce.plugins.wpView ); })();
JavaScript
(function() { tinymce.create('tinymce.plugins.wpLink', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished its initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var disabled = true; // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('WP_Link', function() { if ( disabled ) return; ed.windowManager.open({ id : 'wp-link', width : 480, height : "auto", wpDialog : true, title : ed.getLang('advlink.link_desc') }, { plugin_url : url // Plugin absolute URL }); }); // Register example button ed.addButton('link', { title : 'advanced.link_desc', cmd : 'WP_Link' }); ed.onNodeChange.add(function(ed, cm, n, co) { disabled = co && n.nodeName != 'A'; }); }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'WordPress Link Dialog', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); // Register plugin tinymce.PluginManager.add('wplink', tinymce.plugins.wpLink); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each, defs = { paste_auto_cleanup_on_paste : true, paste_enable_default_filters : true, paste_block_drop : false, paste_retain_style_properties : "none", paste_strip_class_attributes : "mso", paste_remove_spans : false, paste_remove_styles : false, paste_remove_styles_if_webkit : true, paste_convert_middot_lists : true, paste_convert_headers_to_strong : false, paste_dialog_width : "450", paste_dialog_height : "400", paste_max_consecutive_linebreaks: 2, paste_text_use_dialog : false, paste_text_sticky : false, paste_text_sticky_default : false, paste_text_notifyalways : false, paste_text_linebreaktype : "combined", paste_text_replacements : [ [/\u2026/g, "..."], [/[\x93\x94\u201c\u201d]/g, '"'], [/[\x60\x91\x92\u2018\u2019]/g, "'"] ] }; function getParam(ed, name) { return ed.getParam(name, defs[name]); } tinymce.create('tinymce.plugins.PastePlugin', { init : function(ed, url) { var t = this; t.editor = ed; t.url = url; // Setup plugin events t.onPreProcess = new tinymce.util.Dispatcher(t); t.onPostProcess = new tinymce.util.Dispatcher(t); // Register default handlers t.onPreProcess.add(t._preProcess); t.onPostProcess.add(t._postProcess); // Register optional preprocess handler t.onPreProcess.add(function(pl, o) { ed.execCallback('paste_preprocess', pl, o); }); // Register optional postprocess t.onPostProcess.add(function(pl, o) { ed.execCallback('paste_postprocess', pl, o); }); ed.onKeyDown.addToTop(function(ed, e) { // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) return false; // Stop other listeners }); // Initialize plain text flag ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default'); // This function executes the process handlers and inserts the contents // force_rich overrides plain text mode set by user, important for pasting with execCommand function process(o, force_rich) { var dom = ed.dom, rng; // Execute pre process handlers t.onPreProcess.dispatch(t, o); // Create DOM structure o.node = dom.create('div', 0, o.content); // If pasting inside the same element and the contents is only one block // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element if (tinymce.isGecko) { rng = ed.selection.getRng(true); if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) { // Is only one block node and it doesn't contain word stuff if (o.node.childNodes.length === 1 && /^(p|h[1-6]|pre)$/i.test(o.node.firstChild.nodeName) && o.content.indexOf('__MCE_ITEM__') === -1) dom.remove(o.node.firstChild, true); } } // Execute post process handlers t.onPostProcess.dispatch(t, o); // Serialize content o.content = ed.serializer.serialize(o.node, {getInner : 1, forced_root_block : ''}); // Plain text option active? if ((!force_rich) && (ed.pasteAsPlainText)) { t._insertPlainText(o.content); if (!getParam(ed, "paste_text_sticky")) { ed.pasteAsPlainText = false; ed.controlManager.setActive("pastetext", false); } } else { t._insert(o.content); } } // Add command for external usage ed.addCommand('mceInsertClipboardContent', function(u, o) { process(o, true); }); if (!getParam(ed, "paste_text_use_dialog")) { ed.addCommand('mcePasteText', function(u, v) { var cookie = tinymce.util.Cookie; ed.pasteAsPlainText = !ed.pasteAsPlainText; ed.controlManager.setActive('pastetext', ed.pasteAsPlainText); if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) { if (getParam(ed, "paste_text_sticky")) { ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky')); } else { ed.windowManager.alert(ed.translate('paste.plaintext_mode')); } if (!getParam(ed, "paste_text_notifyalways")) { cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31)) } } }); } ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'}); ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'}); // This function grabs the contents from the clipboard by adding a // hidden div and placing the caret inside it and after the browser paste // is done it grabs that contents and processes that function grabContent(e) { var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent; // Check if browser supports direct plaintext access if (e.clipboardData || dom.doc.dataTransfer) { textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text'); if (ed.pasteAsPlainText) { e.preventDefault(); process({content : dom.encode(textContent).replace(/\r?\n/g, '<br />')}); return; } } if (dom.get('_mcePaste')) return; // Create container to paste into n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF'); // If contentEditable mode we need to find out the position of the closest element if (body != ed.getDoc().body) posY = dom.getPos(ed.selection.getStart(), body).y; else posY = body.scrollTop + dom.getViewPort(ed.getWin()).y; // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles // If also needs to be in view on IE or the paste would fail dom.setStyles(n, { position : 'absolute', left : tinymce.isGecko ? -40 : 0, // Need to move it out of site on Gecko since it will othewise display a ghost resize rect for the div top : posY - 25, width : 1, height : 1, overflow : 'hidden' }); if (tinymce.isIE) { // Store away the old range oldRng = sel.getRng(); // Select the container rng = dom.doc.body.createTextRange(); rng.moveToElementText(n); rng.execCommand('Paste'); // Remove container dom.remove(n); // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due // to IE security settings so we pass the junk though better than nothing right if (n.innerHTML === '\uFEFF\uFEFF') { ed.execCommand('mcePasteWord'); e.preventDefault(); return; } // Restore the old range and clear the contents before pasting sel.setRng(oldRng); sel.setContent(''); // For some odd reason we need to detach the the mceInsertContent call from the paste event // It's like IE has a reference to the parent element that you paste in and the selection gets messed up // when it tries to restore the selection setTimeout(function() { // Process contents process({content : n.innerHTML}); }, 0); // Block the real paste event return tinymce.dom.Event.cancel(e); } else { function block(e) { e.preventDefault(); }; // Block mousedown and click to prevent selection change dom.bind(ed.getDoc(), 'mousedown', block); dom.bind(ed.getDoc(), 'keydown', block); or = ed.selection.getRng(); // Move select contents inside DIV n = n.firstChild; rng = ed.getDoc().createRange(); rng.setStart(n, 0); rng.setEnd(n, 2); sel.setRng(rng); // Wait a while and grab the pasted contents window.setTimeout(function() { var h = '', nl; // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit if (!dom.select('div.mcePaste > div.mcePaste').length) { nl = dom.select('div.mcePaste'); // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string each(nl, function(n) { var child = n.firstChild; // WebKit inserts a DIV container with lots of odd styles if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) { dom.remove(child, 1); } // Remove apply style spans each(dom.select('span.Apple-style-span', n), function(n) { dom.remove(n, 1); }); // Remove bogus br elements each(dom.select('br[data-mce-bogus]', n), function(n) { dom.remove(n); }); // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV if (n.parentNode.className != 'mcePaste') h += n.innerHTML; }); } else { // Found WebKit weirdness so force the content into paragraphs this seems to happen when you paste plain text from Nodepad etc // So this logic will replace double enter with paragraphs and single enter with br so it kind of looks the same h = '<p>' + dom.encode(textContent).replace(/\r?\n\r?\n/g, '</p><p>').replace(/\r?\n/g, '<br />') + '</p>'; } // Remove the nodes each(dom.select('div.mcePaste'), function(n) { dom.remove(n); }); // Restore the old selection if (or) sel.setRng(or); process({content : h}); // Unblock events ones we got the contents dom.unbind(ed.getDoc(), 'mousedown', block); dom.unbind(ed.getDoc(), 'keydown', block); }, 0); } } // Check if we should use the new auto process method if (getParam(ed, "paste_auto_cleanup_on_paste")) { // Is it's Opera or older FF use key handler if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) { ed.onKeyDown.addToTop(function(ed, e) { if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) grabContent(e); }); } else { // Grab contents on paste event on Gecko and WebKit ed.onPaste.addToTop(function(ed, e) { return grabContent(e); }); } } ed.onInit.add(function() { ed.controlManager.setActive("pastetext", ed.pasteAsPlainText); // Block all drag/drop events if (getParam(ed, "paste_block_drop")) { ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) { e.preventDefault(); e.stopPropagation(); return false; }); } }); // Add legacy support t._legacySupport(); }, getInfo : function() { return { longname : 'Paste text/word', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _preProcess : function(pl, o) { var ed = this.editor, h = o.content, grep = tinymce.grep, explode = tinymce.explode, trim = tinymce.trim, len, stripClass; //console.log('Before preprocess:' + o.content); function process(items) { each(items, function(v) { // Remove or replace if (v.constructor == RegExp) h = h.replace(v, ''); else h = h.replace(v[0], v[1]); }); } if (ed.settings.paste_enable_default_filters == false) { return; } // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser if (tinymce.isIE && document.documentMode >= 9 && /<(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)/.test(o.content)) { // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser process([[/(?:<br>&nbsp;[\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br>&nbsp;[\s\r\n]+|<br>)*/g, '$1']]); // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break process([ [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s [/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR ]); } // Detect Word content and process it more aggressive if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) { o.wordContent = true; // Mark the pasted contents as word specific content //console.log('Word contents detected.'); // Process away some basic content process([ /^\s*(&nbsp;)+/gi, // &nbsp; entities at the start of contents /(&nbsp;|<br[^>]*>)+\s*$/gi // &nbsp; entities at the end of contents ]); if (getParam(ed, "paste_convert_headers_to_strong")) { h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>"); } if (getParam(ed, "paste_convert_middot_lists")) { process([ [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'], // Convert mso-list and symbol spans to item markers [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol paragraphs to item markers (FF) ]); } process([ // Word comments like conditional comments etc /<!--[\s\S]+?-->/gi, // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, // Convert <s> into <strike> for line-though [/<(\/?)s>/gi, "<$1strike>"], // Replace nsbp entites to char since it's easier to handle [/&nbsp;/gi, "\u00a0"] ]); // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag. // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot. do { len = h.length; h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1"); } while (len != h.length); // Remove all spans if no styles is to be retained if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) { h = h.replace(/<\/?span[^>]*>/gi, ""); } else { // We're keeping styles, so at least clean them up. // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx process([ // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function(str, spaces) { return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ""; } ], // Examine all styles: delete junk, transform some, and keep the rest [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi, function(str, tag, style) { var n = [], i = 0, s = explode(trim(style).replace(/&quot;/gi, "'"), ";"); // Examine each style definition within the tag's style attribute each(s, function(v) { var name, value, parts = explode(v, ":"); function ensureUnits(v) { return v + ((v !== "0") && (/\d$/.test(v)))? "px" : ""; } if (parts.length == 2) { name = parts[0].toLowerCase(); value = parts[1].toLowerCase(); // Translate certain MS Office styles into their CSS equivalents switch (name) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value); return; case "horiz-align": n[i++] = "text-align:" + value; return; case "vert-align": n[i++] = "vertical-align:" + value; return; case "font-color": case "mso-foreground": n[i++] = "color:" + value; return; case "mso-background": case "mso-highlight": n[i++] = "background:" + value; return; case "mso-default-height": n[i++] = "min-height:" + ensureUnits(value); return; case "mso-default-width": n[i++] = "min-width:" + ensureUnits(value); return; case "mso-padding-between-alt": n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value); return; case "text-line-through": if ((value == "single") || (value == "double")) { n[i++] = "text-decoration:line-through"; } return; case "mso-zero-height": if (value == "yes") { n[i++] = "display:none"; } return; } // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) { return; } // If it reached this point, it must be a valid CSS style n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case } }); // If style attribute contained any valid styles the re-write it; otherwise delete style attribute. if (i > 0) { return tag + ' style="' + n.join(';') + '"'; } else { return tag; } } ] ]); } } // Replace headers with <strong> if (getParam(ed, "paste_convert_headers_to_strong")) { process([ [/<h[1-6][^>]*>/gi, "<p><strong>"], [/<\/h[1-6][^>]*>/gi, "</strong></p>"] ]); } process([ // Copy paste from Java like Open Office will produce this junk on FF [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, ''] ]); // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso"). // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation. stripClass = getParam(ed, "paste_strip_class_attributes"); if (stripClass !== "none") { function removeClasses(match, g1) { if (stripClass === "all") return ''; var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "), function(v) { return (/^(?!mso)/i.test(v)); } ); return cls.length ? ' class="' + cls.join(" ") + '"' : ''; }; h = h.replace(/ class="([^"]+)"/gi, removeClasses); h = h.replace(/ class=([\-\w]+)/gi, removeClasses); } // Remove spans option if (getParam(ed, "paste_remove_spans")) { h = h.replace(/<\/?span[^>]*>/gi, ""); } //console.log('After preprocess:' + h); o.content = h; }, /** * Various post process items. */ _postProcess : function(pl, o) { var t = this, ed = t.editor, dom = ed.dom, styleProps; if (ed.settings.paste_enable_default_filters == false) { return; } if (o.wordContent) { // Remove named anchors or TOC links each(dom.select('a', o.node), function(a) { if (!a.href || a.href.indexOf('#_Toc') != -1) dom.remove(a, 1); }); if (getParam(ed, "paste_convert_middot_lists")) { t._convertLists(pl, o); } // Process styles styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties // Process only if a string was specified and not equal to "all" or "*" if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) { styleProps = tinymce.explode(styleProps.replace(/^none$/i, "")); // Retains some style properties each(dom.select('*', o.node), function(el) { var newStyle = {}, npc = 0, i, sp, sv; // Store a subset of the existing styles if (styleProps) { for (i = 0; i < styleProps.length; i++) { sp = styleProps[i]; sv = dom.getStyle(el, sp); if (sv) { newStyle[sp] = sv; npc++; } } } // Remove all of the existing styles dom.setAttrib(el, 'style', ''); if (styleProps && npc > 0) dom.setStyles(el, newStyle); // Add back the stored subset of styles else // Remove empty span tags that do not have class attributes if (el.nodeName == 'SPAN' && !el.className) dom.remove(el, true); }); } } // Remove all style information or only specifically on WebKit to avoid the style bug on that browser if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) { each(dom.select('*[style]', o.node), function(el) { el.removeAttribute('style'); el.removeAttribute('data-mce-style'); }); } else { if (tinymce.isWebKit) { // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." /> // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles each(dom.select('*', o.node), function(el) { el.removeAttribute('data-mce-style'); }); } } }, /** * Converts the most common bullet and number formats in Office into a real semantic UL/LI list. */ _convertLists : function(pl, o) { var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html; // Convert middot lists into real semantic lists each(dom.select('p', o.node), function(p) { var sib, val = '', type, html, idx, parents; // Get text node value at beginning of paragraph for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling) val += sib.nodeValue; val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0'); // Detect unordered lists look for bullets if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val)) type = 'ul'; // Detect ordered lists 1., a. or ixv. if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val)) type = 'ol'; // Check if node value matches the list pattern: o&nbsp;&nbsp; if (type) { margin = parseFloat(p.style.marginLeft || 0); if (margin > lastMargin) levels.push(margin); if (!listElm || type != lastType) { listElm = dom.create(type); dom.insertAfter(listElm, p); } else { // Nested list element if (margin > lastMargin) { listElm = li.appendChild(dom.create(type)); } else if (margin < lastMargin) { // Find parent level based on margin value idx = tinymce.inArray(levels, margin); parents = dom.getParents(listElm.parentNode, type); listElm = parents[parents.length - 1 - idx] || listElm; } } // Remove middot or number spans if they exists each(dom.select('span', p), function(span) { var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, ''); // Remove span with the middot or the number if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html)) dom.remove(span); else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html)) dom.remove(span); }); html = p.innerHTML; // Remove middot/list items if (type == 'ul') html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, ''); else html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, ''); // Create li and add paragraph data into the new li li = listElm.appendChild(dom.create('li', 0, html)); dom.remove(p); lastMargin = margin; lastType = type; } else listElm = lastMargin = 0; // End list element }); // Remove any left over makers html = o.node.innerHTML; if (html.indexOf('__MCE_ITEM__') != -1) o.node.innerHTML = html.replace(/__MCE_ITEM__/g, ''); }, /** * Inserts the specified contents at the caret position. */ _insert : function(h, skip_undo) { var ed = this.editor, r = ed.selection.getRng(); // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells. if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer) ed.getDoc().execCommand('Delete', false, null); ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo}); }, /** * Instead of the old plain text method which tried to re-create a paste operation, the * new approach adds a plain text mode toggle switch that changes the behavior of paste. * This function is passed the same input that the regular paste plugin produces. * It performs additional scrubbing and produces (and inserts) the plain text. * This approach leverages all of the great existing functionality in the paste * plugin, and requires minimal changes to add the new functionality. * Speednet - June 2009 */ _insertPlainText : function(content) { var ed = this.editor, linebr = getParam(ed, "paste_text_linebreaktype"), rl = getParam(ed, "paste_text_replacements"), is = tinymce.is; function process(items) { each(items, function(v) { if (v.constructor == RegExp) content = content.replace(v, ""); else content = content.replace(v[0], v[1]); }); }; if ((typeof(content) === "string") && (content.length > 0)) { // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(content)) { process([ /[\n\r]+/g ]); } else { // Otherwise just get rid of carriage returns (only need linefeeds) process([ /\r+/g ]); } process([ [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"], // Block tags get a blank line after them [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags [/&nbsp;/gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*) [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"] // Cool little RegExp deletes whitespace around linebreak chars. ]); var maxLinebreaks = Number(getParam(ed, "paste_max_consecutive_linebreaks")); if (maxLinebreaks > -1) { var maxLinebreaksRegex = new RegExp("\n{" + (maxLinebreaks + 1) + ",}", "g"); var linebreakReplacement = ""; while (linebreakReplacement.length < maxLinebreaks) { linebreakReplacement += "\n"; } process([ [maxLinebreaksRegex, linebreakReplacement] // Limit max consecutive linebreaks ]); } content = ed.dom.decode(tinymce.html.Entities.encodeRaw(content)); // Perform default or custom replacements if (is(rl, "array")) { process(rl); } else if (is(rl, "string")) { process(new RegExp(rl, "gi")); } // Treat paragraphs as specified in the config if (linebr == "none") { // Convert all line breaks to space process([ [/\n+/g, " "] ]); } else if (linebr == "br") { // Convert all line breaks to <br /> process([ [/\n/g, "<br />"] ]); } else if (linebr == "p") { // Convert all line breaks to <p>...</p> process([ [/\n+/g, "</p><p>"], [/^(.*<\/p>)(<p>)$/, '<p>$1'] ]); } else { // defaults to "combined" // Convert single line breaks to <br /> and double line breaks to <p>...</p> process([ [/\n\n/g, "</p><p>"], [/^(.*<\/p>)(<p>)$/, '<p>$1'], [/\n/g, "<br />"] ]); } ed.execCommand('mceInsertContent', false, content); } }, /** * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine. */ _legacySupport : function() { var t = this, ed = t.editor; // Register command(s) for backwards compatibility ed.addCommand("mcePasteWord", function() { ed.windowManager.open({ file: t.url + "/pasteword.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline: 1 }); }); if (getParam(ed, "paste_text_use_dialog")) { ed.addCommand("mcePasteText", function() { ed.windowManager.open({ file : t.url + "/pastetext.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline : 1 }); }); } // Register button for backwards compatibility ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"}); } }); // Register plugin tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin); })();
JavaScript
tinyMCEPopup.requireLangPack(); var PasteTextDialog = { init : function() { this.resize(); }, insert : function() { var h = tinyMCEPopup.dom.encode(document.getElementById('content').value), lines; // Convert linebreaks into paragraphs if (document.getElementById('linebreaks').checked) { lines = h.split(/\r?\n/); if (lines.length > 1) { h = ''; tinymce.each(lines, function(row) { h += '<p>' + row + '</p>'; }); } } tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('content'); el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } }; tinyMCEPopup.onInit.add(PasteTextDialog.init, PasteTextDialog);
JavaScript
tinyMCEPopup.requireLangPack(); var PasteWordDialog = { init : function() { var ed = tinyMCEPopup.editor, el = document.getElementById('iframecontainer'), ifr, doc, css, cssHTML = ''; // Create iframe el.innerHTML = '<iframe id="iframe" src="javascript:\'\';" frameBorder="0" style="border: 1px solid gray"></iframe>'; ifr = document.getElementById('iframe'); doc = ifr.contentWindow.document; // Force absolute CSS urls css = [ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css")]; css = css.concat(tinymce.explode(ed.settings.content_css) || []); tinymce.each(css, function(u) { cssHTML += '<link href="' + ed.documentBaseURI.toAbsolute('' + u) + '" rel="stylesheet" type="text/css" />'; }); // Write content into iframe doc.open(); doc.write('<html><head>' + cssHTML + '</head><body class="mceContentBody" spellcheck="false"></body></html>'); doc.close(); doc.designMode = 'on'; this.resize(); window.setTimeout(function() { ifr.contentWindow.focus(); }, 10); }, insert : function() { var h = document.getElementById('iframe').contentWindow.document.body.innerHTML; tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h, wordContent : true}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('iframe'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } } }; tinyMCEPopup.onInit.add(PasteWordDialog.init, PasteWordDialog);
JavaScript
(function(){ if ( typeof tinyMCEPreInit === 'undefined' ) return; var t = tinyMCEPreInit, baseurl = t.base, markDone = tinymce.ScriptLoader.markDone, lang = t.ref.language, theme = t.ref.theme, plugins = t.ref.plugins, suffix = t.suffix; markDone( baseurl+'/langs/'+lang+'.js' ); markDone( baseurl+'/themes/'+theme+'/editor_template'+suffix+'.js' ); markDone( baseurl+'/themes/'+theme+'/langs/'+lang+'.js' ); markDone( baseurl+'/themes/'+theme+'/langs/'+lang+'_dlg.js' ); tinymce.each( plugins.split(','), function(plugin){ if ( plugin && plugin.charAt(0) != '-' ) { markDone( baseurl+'/plugins/'+plugin+'/editor_plugin'+suffix+'.js' ); markDone( baseurl+'/plugins/'+plugin+'/langs/'+lang+'.js' ); markDone( baseurl+'/plugins/'+plugin+'/langs/'+lang+'_dlg.js' ) } }); })();
JavaScript
tinyMCE.addI18n({en:{ common:{ edit_confirm:"Do you want to use the WYSIWYG mode for this textarea?", apply:"Apply", insert:"Insert", update:"Update", cancel:"Cancel", close:"Close", browse:"Browse", class_name:"Class", not_set:"-- Not set --", clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.", clipboard_no_support:"Currently not supported by your browser, use keyboard shortcuts instead.", popup_blocked:"Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.", invalid_data:"ERROR: Invalid values entered, these are marked in red.", invalid_data_number:"{#field} must be a number", invalid_data_min:"{#field} must be a number greater than {#min}", invalid_data_size:"{#field} must be a number or percentage", more_colors:"More colors" }, colors:{ "000000":"Black", "993300":"Burnt orange", "333300":"Dark olive", "003300":"Dark green", "003366":"Dark azure", "000080":"Navy Blue", "333399":"Indigo", "333333":"Very dark gray", "800000":"Maroon", "FF6600":"Orange", "808000":"Olive", "008000":"Green", "008080":"Teal", "0000FF":"Blue", "666699":"Grayish blue", "808080":"Gray", "FF0000":"Red", "FF9900":"Amber", "99CC00":"Yellow green", "339966":"Sea green", "33CCCC":"Turquoise", "3366FF":"Royal blue", "800080":"Purple", "999999":"Medium gray", "FF00FF":"Magenta", "FFCC00":"Gold", "FFFF00":"Yellow", "00FF00":"Lime", "00FFFF":"Aqua", "00CCFF":"Sky blue", "993366":"Brown", "C0C0C0":"Silver", "FF99CC":"Pink", "FFCC99":"Peach", "FFFF99":"Light yellow", "CCFFCC":"Pale green", "CCFFFF":"Pale cyan", "99CCFF":"Light sky blue", "CC99FF":"Plum", "FFFFFF":"White" }, contextmenu:{ align:"Alignment", left:"Left", center:"Center", right:"Right", full:"Full" }, insertdatetime:{ date_fmt:"%Y-%m-%d", time_fmt:"%H:%M:%S", insertdate_desc:"Insert date", inserttime_desc:"Insert time", months_long:"January,February,March,April,May,June,July,August,September,October,November,December", months_short:"Jan_January_abbreviation,Feb_February_abbreviation,Mar_March_abbreviation,Apr_April_abbreviation,May_May_abbreviation,Jun_June_abbreviation,Jul_July_abbreviation,Aug_August_abbreviation,Sep_September_abbreviation,Oct_October_abbreviation,Nov_November_abbreviation,Dec_December_abbreviation", day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday", day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat" }, print:{ print_desc:"Print" }, preview:{ preview_desc:"Preview" }, directionality:{ ltr_desc:"Direction left to right", rtl_desc:"Direction right to left" }, layer:{ insertlayer_desc:"Insert new layer", forward_desc:"Move forward", backward_desc:"Move backward", absolute_desc:"Toggle absolute positioning", content:"New layer..." }, save:{ save_desc:"Save", cancel_desc:"Cancel all changes" }, nonbreaking:{ nonbreaking_desc:"Insert non-breaking space character" }, iespell:{ iespell_desc:"Run spell checking", download:"ieSpell not detected. Do you want to install it now?" }, advhr:{ advhr_desc:"Horizontal rule" }, emotions:{ emotions_desc:"Emotions" }, searchreplace:{ search_desc:"Find", replace_desc:"Find/Replace" }, advimage:{ image_desc:"Insert/edit image" }, advlink:{ link_desc:"Insert/edit link" }, xhtmlxtras:{ cite_desc:"Citation", abbr_desc:"Abbreviation", acronym_desc:"Acronym", del_desc:"Deletion", ins_desc:"Insertion", attribs_desc:"Insert/Edit Attributes" }, style:{ desc:"Edit CSS Style" }, paste:{ paste_text_desc:"Paste as Plain Text", paste_word_desc:"Paste from Word", selectall_desc:"Select All", plaintext_mode_sticky:"Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.", plaintext_mode:"Paste is now in plain text mode. Click again to toggle back to regular paste mode." }, paste_dlg:{ text_title:"Use CTRL + V on your keyboard to paste the text into the window.", text_linebreaks:"Keep linebreaks", word_title:"Use CTRL + V on your keyboard to paste the text into the window." }, table:{ desc:"Inserts a new table", row_before_desc:"Insert row before", row_after_desc:"Insert row after", delete_row_desc:"Delete row", col_before_desc:"Insert column before", col_after_desc:"Insert column after", delete_col_desc:"Remove column", split_cells_desc:"Split merged table cells", merge_cells_desc:"Merge table cells", row_desc:"Table row properties", cell_desc:"Table cell properties", props_desc:"Table properties", paste_row_before_desc:"Paste table row before", paste_row_after_desc:"Paste table row after", cut_row_desc:"Cut table row", copy_row_desc:"Copy table row", del:"Delete table", row:"Row", col:"Column", cell:"Cell" }, autosave:{ unload_msg:"The changes you made will be lost if you navigate away from this page." }, fullscreen:{ desc:"Toggle fullscreen mode (Alt + Shift + G)" }, media:{ desc:"Insert / edit embedded media", edit:"Edit embedded media" }, fullpage:{ desc:"Document properties" }, template:{ desc:"Insert predefined template content" }, visualchars:{ desc:"Visual control characters on/off." }, spellchecker:{ desc:"Toggle spellchecker (Alt + Shift + N)", menu:"Spellchecker settings", ignore_word:"Ignore word", ignore_words:"Ignore all", langs:"Languages", wait:"Please wait...", sug:"Suggestions", no_sug:"No suggestions", no_mpell:"No misspellings found.", learn_word:"Learn word" }, pagebreak:{ desc:"Insert Page Break" }, advlist:{ types:"Types", def:"Default", lower_alpha:"Lower alpha", lower_greek:"Lower greek", lower_roman:"Lower roman", upper_alpha:"Upper alpha", upper_roman:"Upper roman", circle:"Circle", disc:"Disc", square:"Square" }, aria:{ rich_text_area:"Rich Text Area" }, wordcount:{ words:"Words: " } }}); tinyMCE.addI18n("en.advanced",{ style_select:"Styles", font_size:"Font size", fontdefault:"Font family", block:"Format", paragraph:"Paragraph", div:"Div", address:"Address", pre:"Preformatted", h1:"Heading 1", h2:"Heading 2", h3:"Heading 3", h4:"Heading 4", h5:"Heading 5", h6:"Heading 6", blockquote:"Blockquote", code:"Code", samp:"Code sample", dt:"Definition term ", dd:"Definition description", bold_desc:"Bold (Ctrl + B)", italic_desc:"Italic (Ctrl + I)", underline_desc:"Underline", striketrough_desc:"Strikethrough (Alt + Shift + D)", justifyleft_desc:"Align Left (Alt + Shift + L)", justifycenter_desc:"Align Center (Alt + Shift + C)", justifyright_desc:"Align Right (Alt + Shift + R)", justifyfull_desc:"Align Full (Alt + Shift + J)", bullist_desc:"Unordered list (Alt + Shift + U)", numlist_desc:"Ordered list (Alt + Shift + O)", outdent_desc:"Outdent", indent_desc:"Indent", undo_desc:"Undo (Ctrl + Z)", redo_desc:"Redo (Ctrl + Y)", link_desc:"Insert/edit link (Alt + Shift + A)", unlink_desc:"Unlink (Alt + Shift + S)", image_desc:"Insert/edit image (Alt + Shift + M)", cleanup_desc:"Cleanup messy code", code_desc:"Edit HTML Source", sub_desc:"Subscript", sup_desc:"Superscript", hr_desc:"Insert horizontal ruler", removeformat_desc:"Remove formatting", forecolor_desc:"Select text color", backcolor_desc:"Select background color", charmap_desc:"Insert custom character", visualaid_desc:"Toggle guidelines/invisible elements", anchor_desc:"Insert/edit anchor", cut_desc:"Cut", copy_desc:"Copy", paste_desc:"Paste", image_props_desc:"Image properties", newdocument_desc:"New document", help_desc:"Help", blockquote_desc:"Blockquote (Alt + Shift + Q)", clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.", path:"Path", newdocument:"Are you sure you want to clear all contents?", toolbar_focus:"Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X", more_colors:"More colors", shortcuts_desc:"Accessibility Help", help_shortcut:" Press ALT F10 for toolbar. Press ALT 0 for help.", rich_text_area:"Rich Text Area", toolbar:"Toolbar" }); tinyMCE.addI18n("en.advanced_dlg",{ about_title:"About TinyMCE", about_general:"About", about_help:"Help", about_license:"License", about_plugins:"Plugins", about_plugin:"Plugin", about_author:"Author", about_version:"Version", about_loaded:"Loaded plugins", anchor_title:"Insert/edit anchor", anchor_name:"Anchor name", code_title:"HTML Source Editor", code_wordwrap:"Word wrap", colorpicker_title:"Select a color", colorpicker_picker_tab:"Picker", colorpicker_picker_title:"Color picker", colorpicker_palette_tab:"Palette", colorpicker_palette_title:"Palette colors", colorpicker_named_tab:"Named", colorpicker_named_title:"Named colors", colorpicker_color:"Color:", colorpicker_name:"Name:", charmap_title:"Select custom character", charmap_usage:"Use left and right arrows to navigate.", image_title:"Insert/edit image", image_src:"Image URL", image_alt:"Image description", image_list:"Image list", image_border:"Border", image_dimensions:"Dimensions", image_vspace:"Vertical space", image_hspace:"Horizontal space", image_align:"Alignment", image_align_baseline:"Baseline", image_align_top:"Top", image_align_middle:"Middle", image_align_bottom:"Bottom", image_align_texttop:"Text top", image_align_textbottom:"Text bottom", image_align_left:"Left", image_align_right:"Right", link_title:"Insert/edit link", link_url:"Link URL", link_target:"Target", link_target_same:"Open link in the same window", link_target_blank:"Open link in a new window", link_titlefield:"Title", link_is_email:"The URL you entered seems to be an email address, do you want to add the required mailto: prefix?", link_is_external:"The URL you entered seems to external link, do you want to add the required http:// prefix?", link_list:"Link list", accessibility_help:"Accessibility Help", accessibility_usage_title:"General Usage" }); tinyMCE.addI18n("en.media_dlg",{ title:"Insert / edit embedded media", general:"General", advanced:"Advanced", file:"File/URL", list:"List", size:"Dimensions", preview:"Preview", constrain_proportions:"Constrain proportions", type:"Type", id:"Id", name:"Name", class_name:"Class", vspace:"V-Space", hspace:"H-Space", play:"Auto play", loop:"Loop", menu:"Show menu", quality:"Quality", scale:"Scale", align:"Align", salign:"SAlign", wmode:"WMode", bgcolor:"Background", base:"Base", flashvars:"Flashvars", liveconnect:"SWLiveConnect", autohref:"AutoHREF", cache:"Cache", hidden:"Hidden", controller:"Controller", kioskmode:"Kiosk mode", playeveryframe:"Play every frame", targetcache:"Target cache", correction:"No correction", enablejavascript:"Enable JavaScript", starttime:"Start time", endtime:"End time", href:"href", qtsrcchokespeed:"Choke speed", target:"Target", volume:"Volume", autostart:"Auto start", enabled:"Enabled", fullscreen:"Fullscreen", invokeurls:"Invoke URLs", mute:"Mute", stretchtofit:"Stretch to fit", windowlessvideo:"Windowless video", balance:"Balance", baseurl:"Base URL", captioningid:"Captioning id", currentmarker:"Current marker", currentposition:"Current position", defaultframe:"Default frame", playcount:"Play count", rate:"Rate", uimode:"UI Mode", flash_options:"Flash options", qt_options:"QuickTime options", wmp_options:"Windows media player options", rmp_options:"Real media player options", shockwave_options:"Shockwave options", autogotourl:"Auto goto URL", center:"Center", imagestatus:"Image status", maintainaspect:"Maintain aspect", nojava:"No java", prefetch:"Prefetch", shuffle:"Shuffle", console:"Console", numloop:"Num loops", controls:"Controls", scriptcallbacks:"Script callbacks", swstretchstyle:"Stretch style", swstretchhalign:"Stretch H-Align", swstretchvalign:"Stretch V-Align", sound:"Sound", progress:"Progress", qtsrc:"QT Src", qt_stream_warn:"Streamed rtsp resources should be added to the QT Src field under the advanced tab.", align_top:"Top", align_right:"Right", align_bottom:"Bottom", align_left:"Left", align_center:"Center", align_top_left:"Top left", align_top_right:"Top right", align_bottom_left:"Bottom left", align_bottom_right:"Bottom right", flv_options:"Flash video options", flv_scalemode:"Scale mode", flv_buffer:"Buffer", flv_startimage:"Start image", flv_starttime:"Start time", flv_defaultvolume:"Default volume", flv_hiddengui:"Hidden GUI", flv_autostart:"Auto start", flv_loop:"Loop", flv_showscalemodes:"Show scale modes", flv_smoothvideo:"Smooth video", flv_jscallback:"JS Callback", html5_video_options:"HTML5 Video Options", altsource1:"Alternative source 1", altsource2:"Alternative source 2", preload:"Preload", poster:"Poster", source:"Source" }); tinyMCE.addI18n("en.wordpress",{ wp_adv_desc:"Show/Hide Kitchen Sink (Alt + Shift + Z)", wp_more_desc:"Insert More Tag (Alt + Shift + T)", wp_page_desc:"Insert Page break (Alt + Shift + P)", wp_help_desc:"Help (Alt + Shift + H)", wp_more_alt:"More...", wp_page_alt:"Next page...", add_media:"Add Media", add_image:"Add an Image", add_video:"Add Video", add_audio:"Add Audio", editgallery:"Edit Gallery", delgallery:"Delete Gallery", wp_fullscreen_desc:"Distraction Free Writing mode (Alt + Shift + W)" }); tinyMCE.addI18n("en.wpeditimage",{ edit_img:"Edit Image", del_img:"Delete Image", adv_settings:"Advanced Settings", none:"None", size:"Size", thumbnail:"Thumbnail", medium:"Medium", full_size:"Full Size", current_link:"Current Link", link_to_img:"Link to Image", link_help:"Enter a link URL or click above for presets.", adv_img_settings:"Advanced Image Settings", source:"Source", width:"Width", height:"Height", orig_size:"Original Size", css:"CSS Class", adv_link_settings:"Advanced Link Settings", link_rel:"Link Rel", height:"Height", orig_size:"Original Size", css:"CSS Class", s60:"60%", s70:"70%", s80:"80%", s90:"90%", s100:"100%", s110:"110%", s120:"120%", s130:"130%", img_title:"Title", caption:"Caption", alt:"Alternative Text" });
JavaScript
// Ensure the global `wp` object exists. window.wp = window.wp || {}; (function($){ var views = {}, instances = {}; // Create the `wp.mce` object if necessary. wp.mce = wp.mce || {}; // wp.mce.view // ----------- // A set of utilities that simplifies adding custom UI within a TinyMCE editor. // At its core, it serves as a series of converters, transforming text to a // custom UI, and back again. wp.mce.view = { // ### defaults defaults: { // The default properties used for objects with the `pattern` key in // `wp.mce.view.add()`. pattern: { view: Backbone.View, text: function( instance ) { return instance.options.original; }, toView: function( content ) { if ( ! this.pattern ) return; this.pattern.lastIndex = 0; var match = this.pattern.exec( content ); if ( ! match ) return; return { index: match.index, content: match[0], options: { original: match[0], results: match } }; } }, // The default properties used for objects with the `shortcode` key in // `wp.mce.view.add()`. shortcode: { view: Backbone.View, text: function( instance ) { return instance.options.shortcode.string(); }, toView: function( content ) { var match = wp.shortcode.next( this.shortcode, content ); if ( ! match ) return; return { index: match.index, content: match.content, options: { shortcode: match.shortcode } }; } } }, // ### add( id, options ) // Registers a new TinyMCE view. // // Accepts a unique `id` and an `options` object. // // `options` accepts the following properties: // // * `pattern` is the regular expression used to scan the content and // detect matching views. // // * `view` is a `Backbone.View` constructor. If a plain object is // provided, it will automatically extend the parent constructor // (usually `Backbone.View`). Views are instantiated when the `pattern` // is successfully matched. The instance's `options` object is provided // with the `original` matched value, the match `results` including // capture groups, and the `viewType`, which is the constructor's `id`. // // * `extend` an existing view by passing in its `id`. The current // view will inherit all properties from the parent view, and if // `view` is set to a plain object, it will extend the parent `view` // constructor. // // * `text` is a method that accepts an instance of the `view` // constructor and transforms it into a text representation. add: function( id, options ) { var parent, remove, base, properties; // Fetch the parent view or the default options. if ( options.extend ) parent = wp.mce.view.get( options.extend ); else if ( options.shortcode ) parent = wp.mce.view.defaults.shortcode; else parent = wp.mce.view.defaults.pattern; // Extend the `options` object with the parent's properties. _.defaults( options, parent ); options.id = id; // Create properties used to enhance the view for use in TinyMCE. properties = { // Ensure the wrapper element and references to the view are // removed. Otherwise, removed views could randomly restore. remove: function() { delete instances[ this.el.id ]; this.$el.parent().remove(); // Trigger the inherited `remove` method. if ( remove ) remove.apply( this, arguments ); return this; } }; // If the `view` provided was an object, use the parent's // `view` constructor as a base. If a `view` constructor // was provided, treat that as the base. if ( _.isFunction( options.view ) ) { base = options.view; } else { base = parent.view; remove = options.view.remove; _.defaults( properties, options.view ); } // If there's a `remove` method on the `base` view that wasn't // created by this method, inherit it. if ( ! remove && ! base._mceview ) remove = base.prototype.remove; // Automatically create the new `Backbone.View` constructor. options.view = base.extend( properties, { // Flag that the new view has been created by `wp.mce.view`. _mceview: true }); views[ id ] = options; }, // ### get( id ) // Returns a TinyMCE view options object. get: function( id ) { return views[ id ]; }, // ### remove( id ) // Unregisters a TinyMCE view. remove: function( id ) { delete views[ id ]; }, // ### toViews( content ) // Scans a `content` string for each view's pattern, replacing any // matches with wrapper elements, and creates a new view instance for // every match. // // To render the views, call `wp.mce.view.render( scope )`. toViews: function( content ) { var pieces = [ { content: content } ], current; _.each( views, function( view, viewType ) { current = pieces.slice(); pieces = []; _.each( current, function( piece ) { var remaining = piece.content, result; // Ignore processed pieces, but retain their location. if ( piece.processed ) { pieces.push( piece ); return; } // Iterate through the string progressively matching views // and slicing the string as we go. while ( remaining && (result = view.toView( remaining )) ) { // Any text before the match becomes an unprocessed piece. if ( result.index ) pieces.push({ content: remaining.substring( 0, result.index ) }); // Add the processed piece for the match. pieces.push({ content: wp.mce.view.toView( viewType, result.options ), processed: true }); // Update the remaining content. remaining = remaining.slice( result.index + result.content.length ); } // There are no additional matches. If any content remains, // add it as an unprocessed piece. if ( remaining ) pieces.push({ content: remaining }); }); }); return _.pluck( pieces, 'content' ).join(''); }, toView: function( viewType, options ) { var view = wp.mce.view.get( viewType ), instance, id; if ( ! view ) return ''; // Create a new view instance. instance = new view.view( _.extend( options || {}, { viewType: viewType }) ); // Use the view's `id` if it already exists. Otherwise, // create a new `id`. id = instance.el.id = instance.el.id || _.uniqueId('__wpmce-'); instances[ id ] = instance; // Create a dummy `$wrapper` property to allow `$wrapper` to be // called in the view's `render` method without a conditional. instance.$wrapper = $(); return wp.html.string({ // If the view is a span, wrap it in a span. tag: 'span' === instance.tagName ? 'span' : 'div', attrs: { 'class': 'wp-view-wrap wp-view-type-' + viewType, 'data-wp-view': id, 'contenteditable': false } }); }, // ### render( scope ) // Renders any view instances inside a DOM node `scope`. // // View instances are detected by the presence of wrapper elements. // To generate wrapper elements, pass your content through // `wp.mce.view.toViews( content )`. render: function( scope ) { $( '.wp-view-wrap', scope ).each( function() { var wrapper = $(this), view = wp.mce.view.instance( this ); if ( ! view ) return; // Link the real wrapper to the view. view.$wrapper = wrapper; // Render the view. view.render(); // Detach the view element to ensure events are not unbound. view.$el.detach(); // Empty the wrapper, attach the view element to the wrapper, // and add an ending marker to the wrapper to help regexes // scan the HTML string. wrapper.empty().append( view.el ).append('<span data-wp-view-end class="wp-view-end"></span>'); }); }, // ### toText( content ) // Scans an HTML `content` string and replaces any view instances with // their respective text representations. toText: function( content ) { return content.replace( /<(?:div|span)[^>]+data-wp-view="([^"]+)"[^>]*>.*?<span[^>]+data-wp-view-end[^>]*><\/span><\/(?:div|span)>/g, function( match, id ) { var instance = instances[ id ], view; if ( instance ) view = wp.mce.view.get( instance.options.viewType ); return instance && view ? view.text( instance ) : ''; }); }, // ### Remove internal TinyMCE attributes. removeInternalAttrs: function( attrs ) { var result = {}; _.each( attrs, function( value, attr ) { if ( -1 === attr.indexOf('data-mce') ) result[ attr ] = value; }); return result; }, // ### Parse an attribute string and removes internal TinyMCE attributes. attrs: function( content ) { return wp.mce.view.removeInternalAttrs( wp.html.attrs( content ) ); }, // ### instance( scope ) // // Accepts a MCE view wrapper `node` (i.e. a node with the // `wp-view-wrap` class). instance: function( node ) { var id = $( node ).data('wp-view'); if ( id ) return instances[ id ]; }, // ### Select a view. // // Accepts a MCE view wrapper `node` (i.e. a node with the // `wp-view-wrap` class). select: function( node ) { var $node = $(node); // Bail if node is already selected. if ( $node.hasClass('selected') ) return; $node.addClass('selected'); $( node.firstChild ).trigger('select'); }, // ### Deselect a view. // // Accepts a MCE view wrapper `node` (i.e. a node with the // `wp-view-wrap` class). deselect: function( node ) { var $node = $(node); // Bail if node is already selected. if ( ! $node.hasClass('selected') ) return; $node.removeClass('selected'); $( node.firstChild ).trigger('deselect'); } }; }(jQuery));
JavaScript
(function ($) { // add mime-type aliases to MediaElement plugin support mejs.plugins.silverlight[0].types.push('video/x-ms-wmv'); mejs.plugins.silverlight[0].types.push('audio/x-ms-wma'); $(function () { var settings = {}; if ( typeof _wpmejsSettings !== 'undefined' ) settings.pluginPath = _wpmejsSettings.pluginPath; $('.wp-audio-shortcode, .wp-video-shortcode').mediaelementplayer( settings ); }); }(jQuery));
JavaScript
window.wp = window.wp || {}; (function( exports, $ ){ var api, extend, ctor, inherits, slice = Array.prototype.slice; /* ===================================================================== * Micro-inheritance - thank you, backbone.js. * ===================================================================== */ extend = function( protoProps, classProps ) { var child = inherits( this, protoProps, classProps ); child.extend = this.extend; return child; }; // Shared empty constructor function to aid in prototype-chain creation. ctor = function() {}; // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. inherits = function( parent, protoProps, staticProps ) { var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call `super()`. if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) { child = protoProps.constructor; } else { child = function() { // Storing the result `super()` before returning the value // prevents a bug in Opera where, if the constructor returns // a function, Opera will reject the return value in favor of // the original object. This causes all sorts of trouble. var result = parent.apply( this, arguments ); return result; }; } // Inherit class (static) properties from parent. $.extend( child, parent ); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. ctor.prototype = parent.prototype; child.prototype = new ctor(); // Add prototype properties (instance properties) to the subclass, // if supplied. if ( protoProps ) $.extend( child.prototype, protoProps ); // Add static properties to the constructor function, if supplied. if ( staticProps ) $.extend( child, staticProps ); // Correctly set child's `prototype.constructor`. child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed later. child.__super__ = parent.prototype; return child; }; api = {}; /* ===================================================================== * Base class. * ===================================================================== */ api.Class = function( applicator, argsArray, options ) { var magic, args = arguments; if ( applicator && argsArray && api.Class.applicator === applicator ) { args = argsArray; $.extend( this, options || {} ); } magic = this; if ( this.instance ) { magic = function() { return magic.instance.apply( magic, arguments ); }; $.extend( magic, this ); } magic.initialize.apply( magic, args ); return magic; }; api.Class.applicator = {}; api.Class.prototype.initialize = function() {}; /* * Checks whether a given instance extended a constructor. * * The magic surrounding the instance parameter causes the instanceof * keyword to return inaccurate results; it defaults to the function's * prototype instead of the constructor chain. Hence this function. */ api.Class.prototype.extended = function( constructor ) { var proto = this; while ( typeof proto.constructor !== 'undefined' ) { if ( proto.constructor === constructor ) return true; if ( typeof proto.constructor.__super__ === 'undefined' ) return false; proto = proto.constructor.__super__; } return false; }; api.Class.extend = extend; /* ===================================================================== * Events mixin. * ===================================================================== */ api.Events = { trigger: function( id ) { if ( this.topics && this.topics[ id ] ) this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) ); return this; }, bind: function( id, callback ) { this.topics = this.topics || {}; this.topics[ id ] = this.topics[ id ] || $.Callbacks(); this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) ); return this; }, unbind: function( id, callback ) { if ( this.topics && this.topics[ id ] ) this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) ); return this; } }; /* ===================================================================== * Observable values that support two-way binding. * ===================================================================== */ api.Value = api.Class.extend({ initialize: function( initial, options ) { this._value = initial; // @todo: potentially change this to a this.set() call. this.callbacks = $.Callbacks(); $.extend( this, options || {} ); this.set = $.proxy( this.set, this ); }, /* * Magic. Returns a function that will become the instance. * Set to null to prevent the instance from extending a function. */ instance: function() { return arguments.length ? this.set.apply( this, arguments ) : this.get(); }, get: function() { return this._value; }, set: function( to ) { var from = this._value; to = this._setter.apply( this, arguments ); to = this.validate( to ); // Bail if the sanitized value is null or unchanged. if ( null === to || this._value === to ) return this; this._value = to; this.callbacks.fireWith( this, [ to, from ] ); return this; }, _setter: function( to ) { return to; }, setter: function( callback ) { var from = this.get(); this._setter = callback; // Temporarily clear value so setter can decide if it's valid. this._value = null; this.set( from ); return this; }, resetSetter: function() { this._setter = this.constructor.prototype._setter; this.set( this.get() ); return this; }, validate: function( value ) { return value; }, bind: function( callback ) { this.callbacks.add.apply( this.callbacks, arguments ); return this; }, unbind: function( callback ) { this.callbacks.remove.apply( this.callbacks, arguments ); return this; }, link: function() { // values* var set = this.set; $.each( arguments, function() { this.bind( set ); }); return this; }, unlink: function() { // values* var set = this.set; $.each( arguments, function() { this.unbind( set ); }); return this; }, sync: function() { // values* var that = this; $.each( arguments, function() { that.link( this ); this.link( that ); }); return this; }, unsync: function() { // values* var that = this; $.each( arguments, function() { that.unlink( this ); this.unlink( that ); }); return this; } }); /* ===================================================================== * A collection of observable values. * ===================================================================== */ api.Values = api.Class.extend({ defaultConstructor: api.Value, initialize: function( options ) { $.extend( this, options || {} ); this._value = {}; this._deferreds = {}; }, instance: function( id ) { if ( arguments.length === 1 ) return this.value( id ); return this.when.apply( this, arguments ); }, value: function( id ) { return this._value[ id ]; }, has: function( id ) { return typeof this._value[ id ] !== 'undefined'; }, add: function( id, value ) { if ( this.has( id ) ) return this.value( id ); this._value[ id ] = value; value.parent = this; if ( value.extended( api.Value ) ) value.bind( this._change ); this.trigger( 'add', value ); if ( this._deferreds[ id ] ) this._deferreds[ id ].resolve(); return this._value[ id ]; }, create: function( id ) { return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) ); }, each: function( callback, context ) { context = typeof context === 'undefined' ? this : context; $.each( this._value, function( key, obj ) { callback.call( context, obj, key ); }); }, remove: function( id ) { var value; if ( this.has( id ) ) { value = this.value( id ); this.trigger( 'remove', value ); if ( value.extended( api.Value ) ) value.unbind( this._change ); delete value.parent; } delete this._value[ id ]; delete this._deferreds[ id ]; }, /** * Runs a callback once all requested values exist. * * when( ids*, [callback] ); * * For example: * when( id1, id2, id3, function( value1, value2, value3 ) {} ); * * @returns $.Deferred.promise(); */ when: function() { var self = this, ids = slice.call( arguments ), dfd = $.Deferred(); // If the last argument is a callback, bind it to .done() if ( $.isFunction( ids[ ids.length - 1 ] ) ) dfd.done( ids.pop() ); $.when.apply( $, $.map( ids, function( id ) { if ( self.has( id ) ) return; return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred(); })).done( function() { var values = $.map( ids, function( id ) { return self( id ); }); // If a value is missing, we've used at least one expired deferred. // Call Values.when again to generate a new deferred. if ( values.length !== ids.length ) { // ids.push( callback ); self.when.apply( self, ids ).done( function() { dfd.resolveWith( self, values ); }); return; } dfd.resolveWith( self, values ); }); return dfd.promise(); }, _change: function() { this.parent.trigger( 'change', this ); } }); $.extend( api.Values.prototype, api.Events ); /* ===================================================================== * An observable value that syncs with an element. * * Handles inputs, selects, and textareas by default. * ===================================================================== */ api.ensure = function( element ) { return typeof element == 'string' ? $( element ) : element; }; api.Element = api.Value.extend({ initialize: function( element, options ) { var self = this, synchronizer = api.Element.synchronizer.html, type, update, refresh; this.element = api.ensure( element ); this.events = ''; if ( this.element.is('input, select, textarea') ) { this.events += 'change'; synchronizer = api.Element.synchronizer.val; if ( this.element.is('input') ) { type = this.element.prop('type'); if ( api.Element.synchronizer[ type ] ) synchronizer = api.Element.synchronizer[ type ]; if ( 'text' === type || 'password' === type ) this.events += ' keyup'; } else if ( this.element.is('textarea') ) { this.events += ' keyup'; } } api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) ); this._value = this.get(); update = this.update; refresh = this.refresh; this.update = function( to ) { if ( to !== refresh.call( self ) ) update.apply( this, arguments ); }; this.refresh = function() { self.set( refresh.call( self ) ); }; this.bind( this.update ); this.element.bind( this.events, this.refresh ); }, find: function( selector ) { return $( selector, this.element ); }, refresh: function() {}, update: function() {} }); api.Element.synchronizer = {}; $.each( [ 'html', 'val' ], function( i, method ) { api.Element.synchronizer[ method ] = { update: function( to ) { this.element[ method ]( to ); }, refresh: function() { return this.element[ method ](); } }; }); api.Element.synchronizer.checkbox = { update: function( to ) { this.element.prop( 'checked', to ); }, refresh: function() { return this.element.prop( 'checked' ); } }; api.Element.synchronizer.radio = { update: function( to ) { this.element.filter( function() { return this.value === to; }).prop( 'checked', true ); }, refresh: function() { return this.element.filter( ':checked' ).val(); } }; /* ===================================================================== * Messenger for postMessage. * ===================================================================== */ $.support.postMessage = !! window.postMessage; api.Messenger = api.Class.extend({ add: function( key, initial, options ) { return this[ key ] = new api.Value( initial, options ); }, /** * Initialize Messenger. * * @param {object} params Parameters to configure the messenger. * {string} .url The URL to communicate with. * {window} .targetWindow The window instance to communicate with. Default window.parent. * {string} .channel If provided, will send the channel with each message and only accept messages a matching channel. * @param {object} options Extend any instance parameter or method with this object. */ initialize: function( params, options ) { // Target the parent frame by default, but only if a parent frame exists. var defaultTarget = window.parent == window ? null : window.parent; $.extend( this, options || {} ); this.add( 'channel', params.channel ); this.add( 'url', params.url || '' ); this.add( 'targetWindow', params.targetWindow || defaultTarget ); this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) { return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' ); }); // Since we want jQuery to treat the receive function as unique // to this instance, we give the function a new guid. // // This will prevent every Messenger's receive function from being // unbound when calling $.off( 'message', this.receive ); this.receive = $.proxy( this.receive, this ); this.receive.guid = $.guid++; $( window ).on( 'message', this.receive ); }, destroy: function() { $( window ).off( 'message', this.receive ); }, receive: function( event ) { var message; event = event.originalEvent; if ( ! this.targetWindow() ) return; // Check to make sure the origin is valid. if ( this.origin() && event.origin !== this.origin() ) return; message = JSON.parse( event.data ); // Check required message properties. if ( ! message || ! message.id || typeof message.data === 'undefined' ) return; // Check if channel names match. if ( ( message.channel || this.channel() ) && this.channel() !== message.channel ) return; this.trigger( message.id, message.data ); }, send: function( id, data ) { var message; data = typeof data === 'undefined' ? null : data; if ( ! this.url() || ! this.targetWindow() ) return; message = { id: id, data: data }; if ( this.channel() ) message.channel = this.channel(); this.targetWindow().postMessage( JSON.stringify( message ), this.origin() ); } }); // Add the Events mixin to api.Messenger. $.extend( api.Messenger.prototype, api.Events ); /* ===================================================================== * Core customize object. * ===================================================================== */ api = $.extend( new api.Values(), api ); api.get = function() { var result = {}; this.each( function( obj, key ) { result[ key ] = obj.get(); }); return result; }; // Expose the API to the world. exports.customize = api; })( wp, jQuery );
JavaScript
var topWin = window.dialogArguments || opener || parent || top; function fileDialogStart() { jQuery("#media-upload-error").empty(); } // progress and success handlers for media multi uploads function fileQueued(fileObj) { // Get rid of unused form jQuery('.media-blank').remove(); // Collapse a single item if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) { jQuery('.describe-toggle-on').show(); jQuery('.describe-toggle-off').hide(); jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden'); } // Create a progress bar containing the filename jQuery('<div class="media-item">') .attr( 'id', 'media-item-' + fileObj.id ) .addClass('child-of-' + post_id) .append('<div class="progress"><div class="bar"></div></div>', jQuery('<div class="filename original"><span class="percent"></span>').text( ' ' + fileObj.name )) .appendTo( jQuery('#media-items' ) ); // Display the progress div jQuery('.progress', '#media-item-' + fileObj.id).show(); // Disable submit and enable cancel jQuery('#insert-gallery').prop('disabled', true); jQuery('#cancel-upload').prop('disabled', false); } function uploadStart(fileObj) { try { if ( typeof topWin.tb_remove != 'undefined' ) topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove); } catch(e){} return true; } function uploadProgress(fileObj, bytesDone, bytesTotal) { // Lengthen the progress bar var w = jQuery('#media-items').width() - 2, item = jQuery('#media-item-' + fileObj.id); jQuery('.bar', item).width( w * bytesDone / bytesTotal ); jQuery('.percent', item).html( Math.ceil(bytesDone / bytesTotal * 100) + '%' ); if ( bytesDone == bytesTotal ) jQuery('.bar', item).html('<strong class="crunching">' + swfuploadL10n.crunching + '</strong>'); } function prepareMediaItem(fileObj, serverData) { var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id); // Move the progress bar to 100% jQuery('.bar', item).remove(); jQuery('.progress', item).hide(); try { if ( typeof topWin.tb_remove != 'undefined' ) topWin.jQuery('#TB_overlay').click(topWin.tb_remove); } catch(e){} // Old style: Append the HTML returned by the server -- thumbnail and form inputs if ( isNaN(serverData) || !serverData ) { item.append(serverData); prepareMediaItemInit(fileObj); } // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server else { item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()}); } } function prepareMediaItemInit(fileObj) { var item = jQuery('#media-item-' + fileObj.id); // Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item); // Replace the original filename with the new (unique) one assigned during upload jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) ); // Also bind toggle to the links jQuery('a.toggle', item).click(function(){ jQuery(this).siblings('.slidetoggle').slideToggle(350, function(){ var w = jQuery(window).height(), t = jQuery(this).offset().top, h = jQuery(this).height(), b; if ( w && t && h ) { b = t + h; if ( b > w && (h + 48) < w ) window.scrollBy(0, b - w + 13); else if ( b > w ) window.scrollTo(0, t - 36); } }); jQuery(this).siblings('.toggle').andSelf().toggle(); jQuery(this).siblings('a.toggle').focus(); return false; }); // Bind AJAX to the new Delete button jQuery('a.delete', item).click(function(){ // Tell the server to delete it. TODO: handle exceptions jQuery.ajax({ url: ajaxurl, type: 'post', success: deleteSuccess, error: deleteError, id: fileObj.id, data: { id : this.id.replace(/[^0-9]/g, ''), action : 'trash-post', _ajax_nonce : this.href.replace(/^.*wpnonce=/,'') } }); return false; }); // Bind AJAX to the new Undo button jQuery('a.undo', item).click(function(){ // Tell the server to untrash it. TODO: handle exceptions jQuery.ajax({ url: ajaxurl, type: 'post', id: fileObj.id, data: { id : this.id.replace(/[^0-9]/g,''), action: 'untrash-post', _ajax_nonce: this.href.replace(/^.*wpnonce=/,'') }, success: function(data, textStatus){ var item = jQuery('#media-item-' + fileObj.id); if ( type = jQuery('#type-of-' + fileObj.id).val() ) jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1); if ( item.hasClass('child-of-'+post_id) ) jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1); jQuery('.filename .trashnotice', item).remove(); jQuery('.filename .title', item).css('font-weight','normal'); jQuery('a.undo', item).addClass('hidden'); jQuery('a.describe-toggle-on, .menu_order_input', item).show(); item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo'); } }); return false; }); // Open this item if it says to start open (e.g. to display an error) jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').slideToggle(500).siblings('.toggle').toggle(); } function itemAjaxError(id, html) { var item = jQuery('#media-item-' + id); var filename = jQuery('.filename', item).text(); item.html('<div class="error-div">' + '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>' + '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />' + html + '</div>'); item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})}); } function deleteSuccess(data, textStatus) { if ( data == '-1' ) return itemAjaxError(this.id, 'You do not have permission. Has your session expired?'); if ( data == '0' ) return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?'); var id = this.id, item = jQuery('#media-item-' + id); // Decrement the counters. if ( type = jQuery('#type-of-' + id).val() ) jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 ); if ( item.hasClass('child-of-'+post_id) ) jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 ); if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) { jQuery('.toggle').toggle(); jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden'); } // Vanish it. jQuery('.toggle', item).toggle(); jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden'); item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo'); jQuery('.filename:empty', item).remove(); jQuery('.filename .title', item).css('font-weight','bold'); jQuery('.filename', item).append('<span class="trashnotice"> ' + swfuploadL10n.deleted + ' </span>').siblings('a.toggle').hide(); jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') ); jQuery('.menu_order_input', item).hide(); return; } function deleteError(X, textStatus, errorThrown) { // TODO } function updateMediaForm() { var one = jQuery('form.type-form #media-items').children(), items = jQuery('#media-items').children(); // Just one file, no need for collapsible part if ( one.length == 1 ) { jQuery('.slidetoggle', one).slideDown(500).siblings().addClass('hidden').filter('.toggle').toggle(); } // Only show Save buttons when there is at least one file. if ( items.not('.media-blank').length > 0 ) jQuery('.savebutton').show(); else jQuery('.savebutton').hide(); // Only show Gallery button when there are at least two files. if ( items.length > 1 ) jQuery('.insert-gallery').show(); else jQuery('.insert-gallery').hide(); } function uploadSuccess(fileObj, serverData) { // if async-upload returned an error message, place it in the media item div and return if ( serverData.match('media-upload-error') ) { jQuery('#media-item-' + fileObj.id).html(serverData); return; } prepareMediaItem(fileObj, serverData); updateMediaForm(); // Increment the counter. if ( jQuery('#media-item-' + fileObj.id).hasClass('child-of-' + post_id) ) jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1); } function uploadComplete(fileObj) { // If no more uploads queued, enable the submit button if ( swfu.getStats().files_queued == 0 ) { jQuery('#cancel-upload').prop('disabled', true); jQuery('#insert-gallery').prop('disabled', false); } } // wp-specific error handlers // generic message function wpQueueError(message) { jQuery('#media-upload-error').show().text(message); } // file-specific message function wpFileError(fileObj, message) { var item = jQuery('#media-item-' + fileObj.id); var filename = jQuery('.filename', item).text(); item.html('<div class="error-div">' + '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>' + '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />' + message + '</div>'); item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})}); } function fileQueueError(fileObj, error_code, message) { // Handle this error separately because we don't want to create a FileProgress element for it. if ( error_code == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED ) { wpQueueError(swfuploadL10n.queue_limit_exceeded); } else if ( error_code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.file_exceeds_size_limit); } else if ( error_code == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.zero_byte_file); } else if ( error_code == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.invalid_filetype); } else { wpQueueError(swfuploadL10n.default_error); } } function fileDialogComplete(num_files_queued) { try { if (num_files_queued > 0) { this.startUpload(); } } catch (ex) { this.debug(ex); } } function switchUploader(s) { var f = document.getElementById(swfu.customSettings.swfupload_element_id), h = document.getElementById(swfu.customSettings.degraded_element_id); if ( s ) { f.style.display = 'block'; h.style.display = 'none'; } else { f.style.display = 'none'; h.style.display = 'block'; } } function swfuploadPreLoad() { if ( !uploaderMode ) { switchUploader(1); } else { switchUploader(0); } } function swfuploadLoadFailed() { switchUploader(0); jQuery('.upload-html-bypass').hide(); } function uploadError(fileObj, errorCode, message) { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: wpFileError(fileObj, swfuploadL10n.missing_upload_url); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: wpFileError(fileObj, swfuploadL10n.upload_limit_exceeded); break; case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: wpQueueError(swfuploadL10n.http_error); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: wpQueueError(swfuploadL10n.upload_failed); break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: wpQueueError(swfuploadL10n.io_error); break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: wpQueueError(swfuploadL10n.security_error); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: jQuery('#media-item-' + fileObj.id).remove(); break; default: wpFileError(fileObj, swfuploadL10n.default_error); } } function cancelUpload() { swfu.cancelQueue(); } // remember the last used image size, alignment and url jQuery(document).ready(function($){ $('input[type="radio"]', '#media-items').live('click', function(){ var tr = $(this).closest('tr'); if ( $(tr).hasClass('align') ) setUserSetting('align', $(this).val()); else if ( $(tr).hasClass('image-size') ) setUserSetting('imgsize', $(this).val()); }); $('button.button', '#media-items').live('click', function(){ var c = this.className || ''; c = c.match(/url([^ '"]+)/); if ( c && c[1] ) { setUserSetting('urlbutton', c[1]); $(this).siblings('.urlfield').val( $(this).attr('title') ); } }); });
JavaScript
/* Speed Plug-in Features: *Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc. - currentSpeed -- String indicating the upload speed, bytes per second - averageSpeed -- Overall average upload speed, bytes per second - movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second - timeRemaining -- Estimated remaining upload time in seconds - timeElapsed -- Number of seconds passed for this upload - percentUploaded -- Percentage of the file uploaded (0 to 100) - sizeUploaded -- Formatted size uploaded so far, bytes *Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed. *Adds several Formatting functions for formatting that values provided on the file object. - SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps) - SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S) - SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B ) - SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %) - SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean) - Formats a number using the division array to determine how to apply the labels in the Label Array - factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed) or as several numbers labeled with units (time) */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.speed = {}; SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // List used to keep the speed stats for the files we are tracking this.fileSpeedStats = {}; this.speedSettings = {}; this.ensureDefault("moving_average_history_size", "10"); this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler; this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler; this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler; this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler; this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler; this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler; this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler; this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler; this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler; this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler; this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler; this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler; this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler; delete this.ensureDefault; }; })(SWFUpload.prototype.initSettings); SWFUpload.speed.fileQueuedHandler = function (file) { if (typeof this.speedSettings.user_file_queued_handler === "function") { file = SWFUpload.speed.extendFile(file); return this.speedSettings.user_file_queued_handler.call(this, file); } }; SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) { if (typeof this.speedSettings.user_file_queue_error_handler === "function") { file = SWFUpload.speed.extendFile(file); return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message); } }; SWFUpload.speed.uploadStartHandler = function (file) { if (typeof this.speedSettings.user_upload_start_handler === "function") { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); return this.speedSettings.user_upload_start_handler.call(this, file); } }; SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); SWFUpload.speed.removeTracking(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_error_handler === "function") { return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message); } }; SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) { this.updateTracking(file, bytesComplete); file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_progress_handler === "function") { return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal); } }; SWFUpload.speed.uploadSuccessHandler = function (file, serverData) { if (typeof this.speedSettings.user_upload_success_handler === "function") { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); return this.speedSettings.user_upload_success_handler.call(this, file, serverData); } }; SWFUpload.speed.uploadCompleteHandler = function (file) { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); SWFUpload.speed.removeTracking(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_complete_handler === "function") { return this.speedSettings.user_upload_complete_handler.call(this, file); } }; // Private: extends the file object with the speed plugin values SWFUpload.speed.extendFile = function (file, trackingList) { var tracking; if (trackingList) { tracking = trackingList[file.id]; } if (tracking) { file.currentSpeed = tracking.currentSpeed; file.averageSpeed = tracking.averageSpeed; file.movingAverageSpeed = tracking.movingAverageSpeed; file.timeRemaining = tracking.timeRemaining; file.timeElapsed = tracking.timeElapsed; file.percentUploaded = tracking.percentUploaded; file.sizeUploaded = tracking.bytesUploaded; } else { file.currentSpeed = 0; file.averageSpeed = 0; file.movingAverageSpeed = 0; file.timeRemaining = 0; file.timeElapsed = 0; file.percentUploaded = 0; file.sizeUploaded = 0; } return file; }; // Private: Updates the speed tracking object, or creates it if necessary SWFUpload.prototype.updateTracking = function (file, bytesUploaded) { var tracking = this.fileSpeedStats[file.id]; if (!tracking) { this.fileSpeedStats[file.id] = tracking = {}; } // Sanity check inputs bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0; if (bytesUploaded < 0) { bytesUploaded = 0; } if (bytesUploaded > file.size) { bytesUploaded = file.size; } var tickTime = (new Date()).getTime(); if (!tracking.startTime) { tracking.startTime = (new Date()).getTime(); tracking.lastTime = tracking.startTime; tracking.currentSpeed = 0; tracking.averageSpeed = 0; tracking.movingAverageSpeed = 0; tracking.movingAverageHistory = []; tracking.timeRemaining = 0; tracking.timeElapsed = 0; tracking.percentUploaded = bytesUploaded / file.size; tracking.bytesUploaded = bytesUploaded; } else if (tracking.startTime > tickTime) { this.debug("When backwards in time"); } else { // Get time and deltas var now = (new Date()).getTime(); var lastTime = tracking.lastTime; var deltaTime = now - lastTime; var deltaBytes = bytesUploaded - tracking.bytesUploaded; if (deltaBytes === 0 || deltaTime === 0) { return tracking; } // Update tracking object tracking.lastTime = now; tracking.bytesUploaded = bytesUploaded; // Calculate speeds tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000); tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000); // Calculate moving average tracking.movingAverageHistory.push(tracking.currentSpeed); if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) { tracking.movingAverageHistory.shift(); } tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory); // Update times tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed; tracking.timeElapsed = (now - tracking.startTime) / 1000; // Update percent tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100); } return tracking; }; SWFUpload.speed.removeTracking = function (file, trackingList) { try { trackingList[file.id] = null; delete trackingList[file.id]; } catch (ex) { } }; SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) { var i, unit, unitDivisor, unitLabel; if (baseNumber === 0) { return "0 " + unitLabels[unitLabels.length - 1]; } if (singleFractional) { unit = baseNumber; unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : ""; for (i = 0; i < unitDivisors.length; i++) { if (baseNumber >= unitDivisors[i]) { unit = (baseNumber / unitDivisors[i]).toFixed(2); unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : ""; break; } } return unit + unitLabel; } else { var formattedStrings = []; var remainder = baseNumber; for (i = 0; i < unitDivisors.length; i++) { unitDivisor = unitDivisors[i]; unitLabel = unitLabels.length > i ? " " + unitLabels[i] : ""; unit = remainder / unitDivisor; if (i < unitDivisors.length -1) { unit = Math.floor(unit); } else { unit = unit.toFixed(2); } if (unit > 0) { remainder = remainder % unitDivisor; formattedStrings.push(unit + unitLabel); } } return formattedStrings.join(" "); } }; SWFUpload.speed.formatBPS = function (baseNumber) { var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"]; return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true); }; SWFUpload.speed.formatTime = function (baseNumber) { var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"]; return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false); }; SWFUpload.speed.formatBytes = function (baseNumber) { var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"]; return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true); }; SWFUpload.speed.formatPercent = function (baseNumber) { return baseNumber.toFixed(2) + " %"; }; SWFUpload.speed.calculateMovingAverage = function (history) { var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0; var i; var mSum = 0, mCount = 0; size = history.length; // Check for sufficient data if (size >= 8) { // Clone the array and Calculate sum of the values for (i = 0; i < size; i++) { vals[i] = history[i]; sum += vals[i]; } mean = sum / size; // Calculate variance for the set for (i = 0; i < size; i++) { varianceTemp += Math.pow((vals[i] - mean), 2); } variance = varianceTemp / size; standardDev = Math.sqrt(variance); //Standardize the Data for (i = 0; i < size; i++) { vals[i] = (vals[i] - mean) / standardDev; } // Calculate the average excluding outliers var deviationRange = 2.0; for (i = 0; i < size; i++) { if (vals[i] <= deviationRange && vals[i] >= -deviationRange) { mCount++; mSum += history[i]; } } } else { // Calculate the average (not enough data points to remove outliers) mCount = size; for (i = 0; i < size; i++) { mSum += history[i]; } } return mSum / mCount; }; }
JavaScript
/* Cookie Plug-in This plug in automatically gets all the cookies for this site and adds them to the post_params. Cookies are loaded only on initialization. The refreshCookies function can be called to update the post_params. The cookies will override any other post params with the same name. */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.prototype.initSettings = function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.refreshCookies(false); // The false parameter must be sent since SWFUpload has not initialzed at this point }; }(SWFUpload.prototype.initSettings); // refreshes the post_params and updates SWFUpload. The sendToFlash parameters is optional and defaults to True SWFUpload.prototype.refreshCookies = function (sendToFlash) { if (sendToFlash === undefined) { sendToFlash = true; } sendToFlash = !!sendToFlash; // Get the post_params object var postParams = this.settings.post_params; // Get the cookies var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value; for (i = 0; i < caLength; i++) { c = cookieArray[i]; // Left Trim spaces while (c.charAt(0) === " ") { c = c.substring(1, c.length); } eqIndex = c.indexOf("="); if (eqIndex > 0) { name = c.substring(0, eqIndex); value = c.substring(eqIndex + 1); postParams[name] = value; } } if (sendToFlash) { this.setPostParams(postParams); } }; }
JavaScript
/* Queue Plug-in Features: *Adds a cancelQueue() method for cancelling the entire queue. *All queued files are uploaded when startUpload() is called. *If false is returned from uploadComplete then the queue upload is stopped. If false is not returned (strict comparison) then the queue upload is continued. *Adds a QueueComplete event that is fired when all the queued files have finished uploading. Set the event handler with the queue_complete_handler setting. */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.queue = {}; SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.queueSettings = {}; this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler; this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler; this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler; this.settings.queue_complete_handler = this.settings.queue_complete_handler || null; }; })(SWFUpload.prototype.initSettings); SWFUpload.prototype.startUpload = function (fileID) { this.queueSettings.queue_cancelled_flag = false; this.callFlash("StartUpload", [fileID]); }; SWFUpload.prototype.cancelQueue = function () { this.queueSettings.queue_cancelled_flag = true; this.stopUpload(); var stats = this.getStats(); while (stats.files_queued > 0) { this.cancelUpload(); stats = this.getStats(); } }; SWFUpload.queue.uploadStartHandler = function (file) { var returnValue; if (typeof(this.queueSettings.user_upload_start_handler) === "function") { returnValue = this.queueSettings.user_upload_start_handler.call(this, file); } // To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value. returnValue = (returnValue === false) ? false : true; this.queueSettings.queue_cancelled_flag = !returnValue; return returnValue; }; SWFUpload.queue.uploadCompleteHandler = function (file) { var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler; var continueUpload; if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) { this.queueSettings.queue_upload_count++; } if (typeof(user_upload_complete_handler) === "function") { continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true; } else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) { // If the file was stopped and re-queued don't restart the upload continueUpload = false; } else { continueUpload = true; } if (continueUpload) { var stats = this.getStats(); if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) { this.startUpload(); } else if (this.queueSettings.queue_cancelled_flag === false) { this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]); this.queueSettings.queue_upload_count = 0; } else { this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; } } }; }
JavaScript
/* SWFUpload.SWFObject Plugin Summary: This plugin uses SWFObject to embed SWFUpload dynamically in the page. SWFObject provides accurate Flash Player detection and DOM Ready loading. This plugin replaces the Graceful Degradation plugin. Features: * swfupload_load_failed_hander event * swfupload_pre_load_handler event * minimum_flash_version setting (default: "9.0.28") * SWFUpload.onload event for early loading Usage: Provide handlers and settings as needed. When using the SWFUpload.SWFObject plugin you should initialize SWFUploading in SWFUpload.onload rather than in window.onload. When initialized this way SWFUpload can load earlier preventing the UI flicker that was seen using the Graceful Degradation plugin. <script type="text/javascript"> var swfu; SWFUpload.onload = function () { swfu = new SWFUpload({ minimum_flash_version: "9.0.28", swfupload_pre_load_handler: swfuploadPreLoad, swfupload_load_failed_handler: swfuploadLoadFailed }); }; </script> Notes: You must provide set minimum_flash_version setting to "8" if you are using SWFUpload for Flash Player 8. The swfuploadLoadFailed event is only fired if the minimum version of Flash Player is not met. Other issues such as missing SWF files, browser bugs or corrupt Flash Player installations will not trigger this event. The swfuploadPreLoad event is fired as soon as the minimum version of Flash Player is found. It does not wait for SWFUpload to load and can be used to prepare the SWFUploadUI and hide alternate content. swfobject's onDomReady event is cross-browser safe but will default to the window.onload event when DOMReady is not supported by the browser. Early DOM Loading is supported in major modern browsers but cannot be guaranteed for every browser ever made. */ // SWFObject v2.1 must be loaded var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.onload = function () {}; swfobject.addDomLoadEvent(function () { if (typeof(SWFUpload.onload) === "function") { setTimeout(function(){SWFUpload.onload.call(window);}, 200); } }); SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; this.ensureDefault("minimum_flash_version", "9.0.28"); this.ensureDefault("swfupload_pre_load_handler", null); this.ensureDefault("swfupload_load_failed_handler", null); delete this.ensureDefault; }; })(SWFUpload.prototype.initSettings); SWFUpload.prototype.loadFlash = function (oldLoadFlash) { return function () { var hasFlash = swfobject.hasFlashPlayerVersion(this.settings.minimum_flash_version); if (hasFlash) { this.queueEvent("swfupload_pre_load_handler"); if (typeof(oldLoadFlash) === "function") { oldLoadFlash.call(this); } } else { this.queueEvent("swfupload_load_failed_handler"); } }; }(SWFUpload.prototype.loadFlash); SWFUpload.prototype.displayDebugInfo = function (oldDisplayDebugInfo) { return function () { if (typeof(oldDisplayDebugInfo) === "function") { oldDisplayDebugInfo.call(this); } this.debug( [ "SWFUpload.SWFObject Plugin settings:", "\n", "\t", "minimum_flash_version: ", this.settings.minimum_flash_version, "\n", "\t", "swfupload_pre_load_handler assigned: ", (typeof(this.settings.swfupload_pre_load_handler) === "function").toString(), "\n", "\t", "swfupload_load_failed_handler assigned: ", (typeof(this.settings.swfupload_load_failed_handler) === "function").toString(), "\n", ].join("") ); }; }(SWFUpload.prototype.displayDebugInfo); }
JavaScript
(function(w) { var init = function() { var pr = document.getElementById('post-revisions'), inputs = pr ? pr.getElementsByTagName('input') : []; pr.onclick = function() { var i, checkCount = 0, side; for ( i = 0; i < inputs.length; i++ ) { checkCount += inputs[i].checked ? 1 : 0; side = inputs[i].getAttribute('name'); if ( ! inputs[i].checked && ( 'left' == side && 1 > checkCount || 'right' == side && 1 < checkCount && ( ! inputs[i-1] || ! inputs[i-1].checked ) ) && ! ( inputs[i+1] && inputs[i+1].checked && 'right' == inputs[i+1].getAttribute('name') ) ) inputs[i].style.visibility = 'hidden'; else if ( 'left' == side || 'right' == side ) inputs[i].style.visibility = 'visible'; } } pr.onclick(); } if ( w && w.addEventListener ) w.addEventListener('load', init, false); else if ( w && w.attachEvent ) w.attachEvent('onload', init); })(window);
JavaScript
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ if ( typeof tb_pathToImage != 'string' ) { var tb_pathToImage = thickboxL10n.loadingAnimation; } /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init jQuery(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ jQuery('body').on('click', domChunk, tb_click); } function tb_click(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 jQuery("body","html").css({height: "100%", width: "100%"}); jQuery("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 jQuery("body").append("<iframe id='TB_HideSelect'>"+thickboxL10n.noiframes+"</iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' width='208' /></div>");//add loader to the page jQuery('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = jQuery("a[rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.next+"</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.prev+"</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = thickboxL10n.image + ' ' + (TB_Counter + 1) + ' ' + thickboxL10n.of + ' ' + (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='"+thickboxL10n.close+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><div class='tb-close-icon'></div></a></div>"); jQuery("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);} jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } jQuery("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } jQuery("#TB_next").click(goNext); } jQuery(document).bind('keydown.thickbox', function(e){ e.stopImmediatePropagation(); if ( e.which == 27 ){ // close if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); } else if ( e.which == 190 ){ // display previous image if(!(TB_NextHTML == "")){ jQuery(document).unbind('thickbox'); goNext(); } } else if ( e.which == 188 ){ // display next image if(!(TB_PrevHTML == "")){ jQuery(document).unbind('thickbox'); goPrev(); } } return false; }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_ImageOff").click(tb_remove); jQuery("#TB_window").css({'visibility':'visible'}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); jQuery("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><div class='tb-close-icon'></div></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' >"+thickboxL10n.noiframes+"</iframe>"); }else{//iframe modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'>"+thickboxL10n.noiframes+"</iframe>"); } }else{// not an iframe, ajax if(jQuery("#TB_window").css("visibility") != "visible"){ if(params['modal'] != "true"){//ajax no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><div class='tb-close-icon'></div></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; jQuery("#TB_ajaxContent")[0].scrollTop = 0; jQuery("#TB_ajaxWindowTitle").html(caption); } } jQuery("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children()); jQuery("#TB_window").bind('tb_unload', function () { jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); }else{ jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); jQuery("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); jQuery("#TB_window").css({'visibility':'visible'}); }); } } if(!params['modal']){ jQuery(document).bind('keyup.thickbox', function(e){ if ( e.which == 27 ){ // close e.stopImmediatePropagation(); if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); return false; } }); } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); } function tb_remove() { jQuery("#TB_imageOff").unbind("click"); jQuery("#TB_closeWindowButton").unbind("click"); jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("tb_unload").unbind().remove();}); jQuery("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 jQuery("body","html").css({height: "auto", width: "auto"}); jQuery("html").css("overflow",""); } jQuery(document).unbind('.thickbox'); return false; } function tb_position() { var isIE6 = typeof document.body.style.maxHeight === "undefined"; jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( ! isIE6 ) { // take away IE6 jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
JavaScript
var wpAjax = jQuery.extend( { unserialize: function( s ) { var r = {}, q, pp, i, p; if ( !s ) { return r; } q = s.split('?'); if ( q[1] ) { s = q[1]; } pp = s.split('&'); for ( i in pp ) { if ( jQuery.isFunction(pp.hasOwnProperty) && !pp.hasOwnProperty(i) ) { continue; } p = pp[i].split('='); r[p[0]] = p[1]; } return r; }, parseAjaxResponse: function( x, r, e ) { // 1 = good, 0 = strange (bad data?), -1 = you lack permission var parsed = {}, re = jQuery('#' + r).html(''), err = ''; if ( x && typeof x == 'object' && x.getElementsByTagName('wp_ajax') ) { parsed.responses = []; parsed.errors = false; jQuery('response', x).each( function() { var th = jQuery(this), child = jQuery(this.firstChild), response; response = { action: th.attr('action'), what: child.get(0).nodeName, id: child.attr('id'), oldId: child.attr('old_id'), position: child.attr('position') }; response.data = jQuery( 'response_data', child ).text(); response.supplemental = {}; if ( !jQuery( 'supplemental', child ).children().each( function() { response.supplemental[this.nodeName] = jQuery(this).text(); } ).size() ) { response.supplemental = false } response.errors = []; if ( !jQuery('wp_error', child).each( function() { var code = jQuery(this).attr('code'), anError, errorData, formField; anError = { code: code, message: this.firstChild.nodeValue, data: false }; errorData = jQuery('wp_error_data[code="' + code + '"]', x); if ( errorData ) { anError.data = errorData.get(); } formField = jQuery( 'form-field', errorData ).text(); if ( formField ) { code = formField; } if ( e ) { wpAjax.invalidateForm( jQuery('#' + e + ' :input[name="' + code + '"]' ).parents('.form-field:first') ); } err += '<p>' + anError.message + '</p>'; response.errors.push( anError ); parsed.errors = true; } ).size() ) { response.errors = false; } parsed.responses.push( response ); } ); if ( err.length ) { re.html( '<div class="error">' + err + '</div>' ); } return parsed; } if ( isNaN(x) ) { return !re.html('<div class="error"><p>' + x + '</p></div>'); } x = parseInt(x,10); if ( -1 == x ) { return !re.html('<div class="error"><p>' + wpAjax.noPerm + '</p></div>'); } else if ( 0 === x ) { return !re.html('<div class="error"><p>' + wpAjax.broken + '</p></div>'); } return true; }, invalidateForm: function ( selector ) { return jQuery( selector ).addClass( 'form-invalid' ).find('input:visible').change( function() { jQuery(this).closest('.form-invalid').removeClass( 'form-invalid' ); } ); }, validateForm: function( selector ) { selector = jQuery( selector ); return !wpAjax.invalidateForm( selector.find('.form-required').filter( function() { return jQuery('input:visible', this).val() == ''; } ) ).size(); } }, wpAjax || { noPerm: 'You do not have permission to do that.', broken: 'An unidentified error has occurred.' } ); // Basic form validation jQuery(document).ready( function($){ $('form.validate').submit( function() { return wpAjax.validateForm( $(this) ); } ); });
JavaScript