dvadf
File manager - Edit - /home/theblueo/tv/fb4e3b/js.tar
Back
astra-admin-menu-settings.js 0000666 00000017120 15210400130 0012071 0 ustar 00 /** * Install Starter Templates * * * @since 1.2.4 */ (function($){ AstraThemeAdmin = { init: function() { this._bind(); }, /** * Binds events for the Astra Theme. * * @since 1.0.0 * @access private * @method _bind */ _bind: function() { $( document ).on('ast-after-plugin-active', AstraThemeAdmin._disableActivcationNotice ); $( document ).on('click' , '.astra-install-recommended-plugin', AstraThemeAdmin._installNow ); $( document ).on('click' , '.astra-activate-recommended-plugin', AstraThemeAdmin._activatePlugin); $( document ).on('click' , '.astra-deactivate-recommended-plugin', AstraThemeAdmin._deactivatePlugin); $( document ).on('wp-plugin-install-success' , AstraThemeAdmin._activatePlugin); $( document ).on('wp-plugin-install-error' , AstraThemeAdmin._installError); $( document ).on('wp-plugin-installing' , AstraThemeAdmin._pluginInstalling); }, /** * Plugin Installation Error. */ _installError: function( event, response ) { var $card = jQuery( '.astra-install-recommended-plugin' ); $card .removeClass( 'button-primary' ) .addClass( 'disabled' ) .html( wp.updates.l10n.installFailedShort ); }, /** * Installing Plugin */ _pluginInstalling: function(event, args) { event.preventDefault(); var slug = args.slug; var $card = jQuery( '.astra-install-recommended-plugin' ); var activatingText = astra.recommendedPluiginActivatingText; $card.each(function( index, element ) { element = jQuery( element ); if ( element.data('slug') === slug ) { element.addClass('updating-message'); element.html( activatingText ); } }); }, /** * Activate Success */ _activatePlugin: function( event, response ) { event.preventDefault(); var $message = jQuery(event.target); var $init = $message.data('init'); var activatedSlug; if (typeof $init === 'undefined') { var $message = jQuery('.astra-install-recommended-plugin[data-slug=' + response.slug + ']'); activatedSlug = response.slug; } else { activatedSlug = $init; } // Transform the 'Install' button into an 'Activate' button. var $init = $message.data('init'); var activatingText = astra.recommendedPluiginActivatingText; var settingsLink = $message.data('settings-link'); var settingsLinkText = astra.recommendedPluiginSettingsText; var deactivateText = astra.recommendedPluiginDeactivateText; var astraSitesLink = astra.astraSitesLink; $message.removeClass( 'install-now installed button-disabled updated-message' ) .addClass('updating-message') .html( activatingText ); // WordPress adds "Activate" button after waiting for 1000ms. So we will run our activation after that. setTimeout( function() { $.ajax({ url: astra.ajaxUrl, type: 'POST', data: { 'action' : 'astra-sites-plugin-activate', 'init' : $init, }, }) .done(function (result) { if( result.success ) { var output = '<a href="#" class="astra-deactivate-recommended-plugin" data-init="'+ $init +'" data-settings-link="'+ settingsLink +'" data-settings-link-text="'+ deactivateText +'" aria-label="'+ deactivateText +'">'+ deactivateText +'</a>'; output += ( typeof settingsLink === 'string' && settingsLink != 'undefined' ) ? '<a href="' + settingsLink +'" aria-label="'+ settingsLinkText +'">' + settingsLinkText +' </a>' : ''; output += ( typeof settingsLink === undefined && settingsLink != undefined ) ? '<a href="' + settingsLink +'" aria-label="'+ settingsLinkText +'">' + settingsLinkText +' </a>' : ''; $message.removeClass( 'astra-activate-recommended-plugin astra-install-recommended-plugin button button-primary install-now activate-now updating-message' ); $message.parent('.ast-addon-link-wrapper').parent('.astra-recommended-plugin').addClass('active'); $message.parents('.ast-addon-link-wrapper').html( output ); var starterSitesRedirectionUrl = astraSitesLink + result.data.starter_template_slug; jQuery(document).trigger( 'ast-after-plugin-active', [starterSitesRedirectionUrl, activatedSlug] ); } else { $message.removeClass( 'updating-message' ); } }); }, 1200 ); }, /** * Activate Success */ _deactivatePlugin: function( event, response ) { event.preventDefault(); var $message = jQuery(event.target); var $init = $message.data('init'); if (typeof $init === 'undefined') { var $message = jQuery('.astra-install-recommended-plugin[data-slug=' + response.slug + ']'); } // Transform the 'Install' button into an 'Activate' button. var $init = $message.data('init'); var deactivatingText = $message.data('deactivating-text') || astra.recommendedPluiginDeactivatingText; var settingsLink = $message.data('settings-link'); var settingsLinkText = astra.recommendedPluiginSettingsText; var activateText = astra.recommendedPluiginActivateText; $message.removeClass( 'install-now installed button-disabled updated-message' ) .addClass('updating-message') .html( deactivatingText ); // WordPress adds "Activate" button after waiting for 1000ms. So we will run our activation after that. setTimeout( function() { $.ajax({ url: astra.ajaxUrl, type: 'POST', data: { 'action' : 'astra-sites-plugin-deactivate', 'init' : $init, }, }) .done(function (result) { if( result.success ) { var output = '<a href="#" class="astra-activate-recommended-plugin" data-init="'+ $init +'" data-settings-link="'+ settingsLink +'" data-settings-link-text="'+ activateText +'" aria-label="'+ activateText +'">'+ activateText +'</a>'; $message.removeClass( 'astra-activate-recommended-plugin astra-install-recommended-plugin button button-primary install-now activate-now updating-message' ); $message.parent('.ast-addon-link-wrapper').parent('.astra-recommended-plugin').removeClass('active'); $message.parents('.ast-addon-link-wrapper').html( output ); } else { $message.removeClass( 'updating-message' ); } }); }, 1200 ); }, /** * Install Now */ _installNow: function(event) { event.preventDefault(); var $button = jQuery( event.target ), $document = jQuery(document); if ( $button.hasClass( 'updating-message' ) || $button.hasClass( 'button-disabled' ) ) { return; } if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) { wp.updates.requestFilesystemCredentials( event ); $document.on( 'credential-modal-cancel', function() { var $message = $( '.astra-install-recommended-plugin.updating-message' ); $message .addClass('astra-activate-recommended-plugin') .removeClass( 'updating-message astra-install-recommended-plugin' ) .text( wp.updates.l10n.installNow ); wp.a11y.speak( wp.updates.l10n.updateCancel, 'polite' ); } ); } wp.updates.installPlugin( { slug: $button.data( 'slug' ) }); }, /** * After plugin active redirect and deactivate activation notice */ _disableActivcationNotice: function( event, astraSitesLink, activatedSlug ) { event.preventDefault(); if ( activatedSlug.indexOf( 'astra-sites' ) >= 0 || activatedSlug.indexOf( 'astra-pro-sites' ) >= 0 ) { if ( 'undefined' != typeof AstraNotices ) { AstraNotices._ajax( 'astra-sites-on-active', '' ); } window.location.href = astraSitesLink + '&ast-disable-activation-notice'; } }, }; /** * Initialize AstraThemeAdmin */ $(function(){ AstraThemeAdmin.init(); }); })(jQuery); poinit.js 0000666 00000013465 15213303106 0006413 0 ustar 00 /** * Script for PO file initializing page */ !function( window, document, $ ){ var path, loco = window.locoScope, fsHook = document.getElementById('loco-fs'), elForm = document.getElementById('loco-poinit'), fsConn = loco.fs.init( fsHook ) ; /** * Abstract selection of twin mode (Select/Custom) locale input */ var localeSelector = function( elForm ){ function isSelectMode(){ return elMode[0].checked; } function setSelectMode(){ elMode[0].checked = true; redrawMode( true ); } function setCustomMode(){ if( ! elCode.value ){ elCode.value = getValue(); } elMode[1].checked = true; //elOpts.selectedIndex = 0; redrawMode( false ); } function getValue(){ var data = $( isSelectMode() ? elOpts : elCode ).serializeArray(); return data[0] && data[0].value || ''; } function getLocale(){ var value = getValue(); return value ? loco.locale.parse(value) : loco.locale.cast( {lang:'zxx'} ); } function onModeChange(){ redrawMode( isSelectMode() ); return true; } function redrawMode( selectMode ){ elCode.disabled = selectMode; elOpts.disabled = ! selectMode; fsCode.className = selectMode ? 'disabled' : 'active'; fsOpts.className = selectMode ? 'active' : 'disabled'; validate(); } var elOpts = elForm['select-locale'], elCode = elForm['custom-locale'], elMode = elForm['use-selector'], fsOpts = $(elOpts).focus( setSelectMode ).closest('fieldset').click( setSelectMode )[0], fsCode = $(elCode).focus( setCustomMode ).closest('fieldset').click( setCustomMode )[0]; $(elMode).change( onModeChange ); onModeChange(); loco.watchtext( elCode, function(v){ $(elCode.form).triggerHandler('change'); } ); return { val: getLocale }; }( elForm ); /** * Abstract selection of target directory */ var pathSelector = function(){ var elOpts = elForm['select-path']; function getIndex(){ var pairs = $(elOpts).serializeArray(), pair = pairs[0]; return pair && pair.value || null; } function getSelected(){ var index = getIndex(); return index && elForm['path['+index+']']; } function getValue(){ var elField = getSelected(); return elField && elField.value; } function getLabel(){ var elField = getSelected(); return elField && $(elField.parentNode).find('code.path').text(); } /*$(elForm['path[0]']).focus( function(){ elOpts[0].checked = true; } );*/ return { val: getValue, txt: getLabel }; }( elForm ); // enable disable form submission function setFormDisabled( disabled ){ $(elForm).find('button.button-primary').each( function( i, button ){ button.disabled = disabled; } ); } // Recalculate form submission when any data changes function validate(){ var locale = localeSelector && localeSelector.val(), hasloc = locale && locale.isValid() && 'zxx' !== locale.lang, hasdir = pathSelector && pathSelector.val(), valid = hasloc && hasdir ; redrawLocale( locale ); // disabled until back end validates file path setFormDisabled( true ); // check calculated path against back end if( valid ){ var newPath = pathSelector.txt(); if( newPath !== path ){ path = newPath; fsHook.path.value = path; fsConn.listen(onFsConnect).connect(); } else { setFormDisabled( false ); } } } // callback after file system connect has returned function onFsConnect( valid ){ setFormDisabled( ! valid ); } // show locale in all file paths (or place holder if empty) function redrawLocale( locale ){ var $form = $(elForm), loctag = locale && locale.toString('_') || '', suffix = loctag ? ( 'zxx' === loctag ? '<locale>' : loctag ) : '<invalid>' ; $form.find('code.path span').each( function( i, el ){ el.textContent = suffix; } ); $form.find('span.lang').each( function( i, icon ){ setLocaleIcon( icon, locale ); } ); } function setLocaleIcon( icon, locale ){ if( locale && 'zxx' !== locale.lang ){ icon.setAttribute('lang',locale.lang); icon.setAttribute('class',locale.getIcon()); } else { icon.setAttribute('lang',''); icon.setAttribute('class','lang nolang'); } } // Submit form to Ajax end point when ..erm.. submitted function onMsginitSuccess( data ){ var href = data && data.redirect; if( href ){ // TODO show success panel and hide form instead of redirect? // loco.notices.success('YES'); location.assign( href ); } } function process( event ){ event.preventDefault(); fsConn.applyCreds( elForm ); loco.ajax.submit( event.target, onMsginitSuccess ); // TODO some kind of loader? return false; } $(elForm) .change( validate ) .submit( process ); redrawLocale( localeSelector.val() ); }( window, document, jQuery ); config.js 0000666 00000004532 15213303106 0006351 0 ustar 00 /** * Script for bundle configuration screen */ !function( window, document, $ ){ // utility for scrolling function elementTop( el, ancestor ){ var y = el.offsetTop; while( ( el = el.offsetParent ) && el !== ancestor ){ y += el.offsetTop; } return y; } // form duplicator for adding another project function addProject(){ var $divs = $('#loco-conf > div'), $copy = $divs.eq(0).clone(), index = $divs.length, id = 'loco-conf-'+index, ns = '['+index+']' ; function clearField( i, input ){ var name = input.name.replace('[0]',ns); $(input).attr('name', name ).val(''); } $copy.attr('id', 'loco-conf-'+index ); $copy.find('input').each( clearField ); $copy.find('textarea').each( clearField ); //$copy.find('div.notice').remove(); // TODO translations of this: $copy.find('h2').eq(0).html('New set <span>(untitled)</span>'); $copy.insertBefore('#loco-form-foot'); createClickRemove( $copy.find('a.icon-del'), index ); // scroll to $copy $copy.hide().slideDown( 500 ); $('html, body').animate( { scrollTop: elementTop($copy[0]) }, 500 ); } function createClickRemove( $el, index ){ return $el.click( function(event){ event.preventDefault(); delProject( index ); return false; } ); } // remove whole set from form function delProject( index ){ var $div = $('#loco-conf-'+index), $fld = $div.find('input[name="conf['+index+'][removed]"]') ; // setting removed flag saves having to re-index all sets. back end will ignore it. $fld.val('1'); $div.slideUp( 500, function(){ $(this).hide().find('table').remove(); } ); } // enable project removal from initial blocks $('#loco-conf > div').each( function( index, div ){ createClickRemove( $(div).find('a.icon-del'), index ); } ); // enable project addition via button in footer $('#loco-add-butt').attr('disabled',false).click( function(event){ event.preventDefault(); addProject(); return false; } ); }( window, document, jQuery ); editor.js 0000666 00000027634 15213303106 0006402 0 ustar 00 ( function( $ ) { function SwitchEditors() { var tinymce, $$, exports = {}; function init() { if ( ! tinymce && window.tinymce ) { tinymce = window.tinymce; $$ = tinymce.$; $$( document ).on( 'click', function( event ) { var id, mode, target = $$( event.target ); if ( target.hasClass( 'wp-switch-editor' ) ) { id = target.attr( 'data-wp-editor-id' ); mode = target.hasClass( 'switch-tmce' ) ? 'tmce' : 'html'; switchEditor( id, mode ); } }); } } function getToolbarHeight( editor ) { var node = $$( '.mce-toolbar-grp', editor.getContainer() )[0], height = node && node.clientHeight; if ( height && height > 10 && height < 200 ) { return parseInt( height, 10 ); } return 30; } function switchEditor( id, mode ) { id = id || 'content'; mode = mode || 'toggle'; var editorHeight, toolbarHeight, iframe, editor = tinymce.get( id ), wrap = $$( '#wp-' + id + '-wrap' ), $textarea = $$( '#' + id ), textarea = $textarea[0]; if ( 'toggle' === mode ) { if ( editor && ! editor.isHidden() ) { mode = 'html'; } else { mode = 'tmce'; } } if ( 'tmce' === mode || 'tinymce' === mode ) { if ( editor && ! editor.isHidden() ) { return false; } if ( typeof( window.QTags ) !== 'undefined' ) { window.QTags.closeAllTags( id ); } editorHeight = parseInt( textarea.style.height, 10 ) || 0; if ( editor ) { editor.show(); // No point resizing the iframe in iOS if ( ! tinymce.Env.iOS && editorHeight ) { toolbarHeight = getToolbarHeight( editor ); editorHeight = editorHeight - toolbarHeight + 14; // height cannot be under 50 or over 5000 if ( editorHeight > 50 && editorHeight < 5000 ) { editor.theme.resizeTo( null, editorHeight ); } } } else { tinymce.init( window.tinyMCEPreInit.mceInit[id] ); } wrap.removeClass( 'html-active' ).addClass( 'tmce-active' ); $textarea.attr( 'aria-hidden', true ); window.setUserSetting( 'editor', 'tinymce' ); } else if ( 'html' === mode ) { if ( editor && editor.isHidden() ) { return false; } if ( editor ) { if ( ! tinymce.Env.iOS ) { iframe = editor.iframeElement; editorHeight = iframe ? parseInt( iframe.style.height, 10 ) : 0; if ( editorHeight ) { toolbarHeight = getToolbarHeight( editor ); editorHeight = editorHeight + toolbarHeight - 14; // height cannot be under 50 or over 5000 if ( editorHeight > 50 && editorHeight < 5000 ) { textarea.style.height = editorHeight + 'px'; } } } editor.hide(); } else { // The TinyMCE instance doesn't exist, show the textarea $textarea.css({ 'display': '', 'visibility': '' }); } wrap.removeClass( 'tmce-active' ).addClass( 'html-active' ); $textarea.attr( 'aria-hidden', false ); window.setUserSetting( 'editor', 'html' ); } } // Replace paragraphs with double line breaks function removep( html ) { var blocklist = 'blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure', blocklist1 = blocklist + '|div|p', blocklist2 = blocklist + '|pre', preserve_linebreaks = false, preserve_br = false, preserve = []; if ( ! html ) { return ''; } // Preserve script and style tags. if ( html.indexOf( '<script' ) !== -1 || html.indexOf( '<style' ) !== -1 ) { html = html.replace( /<(script|style)[^>]*>[\s\S]*?<\/\1>/g, function( match ) { preserve.push( match ); return '<wp-preserve>'; } ); } // Protect pre tags. if ( html.indexOf( '<pre' ) !== -1 ) { preserve_linebreaks = true; html = html.replace( /<pre[^>]*>[\s\S]+?<\/pre>/g, function( a ) { a = a.replace( /<br ?\/?>(\r\n|\n)?/g, '<wp-line-break>' ); a = a.replace( /<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-line-break>' ); return a.replace( /\r?\n/g, '<wp-line-break>' ); }); } // keep <br> tags inside captions and remove line breaks if ( html.indexOf( '[caption' ) !== -1 ) { preserve_br = true; html = html.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 html = html.replace( new RegExp( '\\s*</(' + blocklist1 + ')>\\s*', 'g' ), '</$1>\n' ); html = html.replace( new RegExp( '\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g' ), '\n<$1>' ); // Mark </p> if it has any attributes. html = html.replace( /(<p [^>]+>.*?)<\/p>/g, '$1</p#>' ); // Separate <div> containing <p> html = html.replace( /<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n' ); // Remove <p> and <br /> html = html.replace( /\s*<p>/gi, '' ); html = html.replace( /\s*<\/p>\s*/gi, '\n\n' ); html = html.replace( /\n[\s\u00a0]+\n/g, '\n\n' ); html = html.replace( /\s*<br ?\/?>\s*/gi, '\n' ); // Fix some block element newline issues html = html.replace( /\s*<div/g, '\n<div' ); html = html.replace( /<\/div>\s*/g, '</div>\n' ); html = html.replace( /\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n' ); html = html.replace( /caption\]\n\n+\[caption/g, 'caption]\n\n[caption' ); html = html.replace( new RegExp('\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g' ), '\n<$1>' ); html = html.replace( new RegExp('\\s*</(' + blocklist2 + ')>\\s*', 'g' ), '</$1>\n' ); html = html.replace( /<((li|dt|dd)[^>]*)>/g, ' \t<$1>' ); if ( html.indexOf( '<option' ) !== -1 ) { html = html.replace( /\s*<option/g, '\n<option' ); html = html.replace( /\s*<\/select>/g, '\n</select>' ); } if ( html.indexOf( '<hr' ) !== -1 ) { html = html.replace( /\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n' ); } if ( html.indexOf( '<object' ) !== -1 ) { html = html.replace( /<object[\s\S]+?<\/object>/g, function( a ) { return a.replace( /[\r\n]+/g, '' ); }); } // Unmark special paragraph closing tags html = html.replace( /<\/p#>/g, '</p>\n' ); html = html.replace( /\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1' ); // Trim whitespace html = html.replace( /^\s+/, '' ); html = html.replace( /[\s\u00a0]+$/, '' ); // put back the line breaks in pre|script if ( preserve_linebreaks ) { html = html.replace( /<wp-line-break>/g, '\n' ); } // and the <br> tags in captions if ( preserve_br ) { html = html.replace( /<wp-temp-br([^>]*)>/g, '<br$1>' ); } // Put back preserved tags. if ( preserve.length ) { html = html.replace( /<wp-preserve>/g, function() { return preserve.shift(); } ); } return html; } // Similar to `wpautop()` in formatting.php function autop( text ) { 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' + '|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section' + '|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary'; // Normalize line breaks text = text.replace( /\r\n|\r/g, '\n' ); if ( text.indexOf( '\n' ) === -1 ) { return text; } if ( text.indexOf( '<object' ) !== -1 ) { text = text.replace( /<object[\s\S]+?<\/object>/g, function( a ) { return a.replace( /\n+/g, '' ); }); } text = text.replace( /<[^<>]+>/g, function( a ) { return a.replace( /[\n\t ]+/g, ' ' ); }); // Protect pre|script tags if ( text.indexOf( '<pre' ) !== -1 || text.indexOf( '<script' ) !== -1 ) { preserve_linebreaks = true; text = text.replace( /<(pre|script)[^>]*>[\s\S]*?<\/\1>/g, function( a ) { return a.replace( /\n/g, '<wp-line-break>' ); }); } if ( text.indexOf( '<figcaption' ) !== -1 ) { text = text.replace( /\s*(<figcaption[^>]*>)/g, '$1' ); text = text.replace( /<\/figcaption>\s*/g, '</figcaption>' ); } // keep <br> tags inside captions and convert line breaks if ( text.indexOf( '[caption' ) !== -1 ) { preserve_br = true; text = text.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( /<[^<>]+>/g, function( b ) { return b.replace( /[\n\t ]+/, ' ' ); }); // convert remaining line breaks to <br> return a.replace( /\s*\n\s*/g, '<wp-temp-br />' ); }); } text = text + '\n\n'; text = text.replace( /<br \/>\s*<br \/>/gi, '\n\n' ); text = text.replace( new RegExp( '(<(?:' + blocklist + ')(?: [^>]*)?>)', 'gi' ), '\n\n$1' ); text = text.replace( new RegExp( '(</(?:' + blocklist + ')>)', 'gi' ), '$1\n\n' ); text = text.replace( /<hr( [^>]*)?>/gi, '<hr$1>\n\n' ); // hr is self closing block element text = text.replace( /\s*<option/gi, '<option' ); // No <p> or <br> around <option> text = text.replace( /<\/option>\s*/gi, '</option>' ); text = text.replace( /\n\s*\n+/g, '\n\n' ); text = text.replace( /([\s\S]+?)\n\n/g, '<p>$1</p>\n' ); text = text.replace( /<p>\s*?<\/p>/gi, ''); text = text.replace( new RegExp( '<p>\\s*(</?(?:' + blocklist + ')(?: [^>]*)?>)\\s*</p>', 'gi' ), '$1' ); text = text.replace( /<p>(<li.+?)<\/p>/gi, '$1'); text = text.replace( /<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>'); text = text.replace( /<\/blockquote>\s*<\/p>/gi, '</p></blockquote>'); text = text.replace( new RegExp( '<p>\\s*(</?(?:' + blocklist + ')(?: [^>]*)?>)', 'gi' ), '$1' ); text = text.replace( new RegExp( '(</?(?:' + blocklist + ')(?: [^>]*)?>)\\s*</p>', 'gi' ), '$1' ); // Remove redundant spaces and line breaks after existing <br /> tags text = text.replace( /(<br[^>]*>)\s*\n/gi, '$1' ); // Create <br /> from the remaining line breaks text = text.replace( /\s*\n/g, '<br />\n'); text = text.replace( new RegExp( '(</?(?:' + blocklist + ')[^>]*>)\\s*<br />', 'gi' ), '$1' ); text = text.replace( /<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1' ); text = text.replace( /(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]' ); text = text.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 ) { text = text.replace( /<wp-line-break>/g, '\n' ); } if ( preserve_br ) { text = text.replace( /<wp-temp-br([^>]*)>/g, '<br$1>' ); } return text; } // Add old events function pre_wpautop( html ) { var obj = { o: exports, data: html, unfiltered: html }; if ( $ ) { $( 'body' ).trigger( 'beforePreWpautop', [ obj ] ); } obj.data = removep( obj.data ); if ( $ ) { $( 'body' ).trigger( 'afterPreWpautop', [ obj ] ); } return obj.data; } function wpautop( text ) { var obj = { o: exports, data: text, unfiltered: text }; if ( $ ) { $( 'body' ).trigger( 'beforeWpautop', [ obj ] ); } obj.data = autop( obj.data ); if ( $ ) { $( 'body' ).trigger( 'afterWpautop', [ obj ] ); } return obj.data; } if ( $ ) { $( document ).ready( init ); } else if ( document.addEventListener ) { document.addEventListener( 'DOMContentLoaded', init, false ); window.addEventListener( 'load', init, false ); } else if ( window.attachEvent ) { window.attachEvent( 'onload', init ); document.attachEvent( 'onreadystatechange', function() { if ( 'complete' === document.readyState ) { init(); } } ); } window.wp = window.wp || {}; window.wp.editor = window.wp.editor || {}; window.wp.editor.autop = wpautop; window.wp.editor.removep = pre_wpautop; exports = { go: switchEditor, wpautop: wpautop, pre_wpautop: pre_wpautop, _wp_Autop: autop, _wp_Nop: removep }; return exports; } window.switchEditors = new SwitchEditors(); }( window.jQuery )); potinit.js 0000666 00000002017 15213303106 0006566 0 ustar 00 /** * Script for POT file initializing page */ !function( window, document, $ ){ var loco = window.locoScope, fsHook = document.getElementById('loco-fs'), elForm = document.getElementById('loco-potinit') ; // enable disable form submission function setFormDisabled( disabled ){ $(elForm).find('button.button-primary').each( function( i, button ){ button.disabled = disabled; } ); } // Submit form to Ajax end point when ..erm.. submitted function onXgettextSuccess( data ){ var href = data && data.redirect; if( href ){ location.assign( href ); } } function process( event ){ event.preventDefault(); loco.ajax.submit( event.target, onXgettextSuccess ); return false; } $(elForm) .submit( process ); setFormDisabled( false ); if( fsHook ){ loco.fs.init(fsHook).setForm( elForm ); } }( window, document, jQuery ); delete.js 0000666 00000000534 15213303106 0006344 0 ustar 00 /** * Script for file delete operation */ !function( window, document, $ ){ var fsHook = document.getElementById('loco-fs'), elForm = document.getElementById('loco-del'); if( fsHook && elForm ){ window.locoScope.fs .init( fsHook ) .setForm( elForm ); } }( window, document, jQuery ); min/admin.js 0000666 00000312205 15213303106 0006756 0 ustar 00 (function(q,y,h,T){var n=function(){var f={};return{register:function(c,h){f[c]=h},require:function(c,h){var l=f[c];if(!l)throw Error('CommonJS error: failed to require("'+h+'")');return l}}}();n.register("$1",function(f,c,h){function l(b){var g=typeof b;if("string"===g)if(/[^ <>!=()%^&|?:n0-9]/.test(b))console.error("Invalid plural: "+b);else return new Function("n","return "+b);"function"!==g&&(b=function(a){return 1!=a});return b}f.init=function(b){function g(d,e,k){return(d=a[d])&&d[k]?d[k]:e|| ""}b=l(b);var a={};return{_:function(a){return g(a,a,0)},_x:function(a,e){return g(e+"\u0004"+a,a,0)},_n:function(a,e,k){k=Number(b(k));isNaN(k)&&(k=0);return g(a,i?e:a,k)},load:function(d){a=d||{};return this},pluraleq:function(a){b=l(a);return this}}};return f}({},q,y));n.register("$2",function(f,c,h){Array.prototype.indexOf||(Array.prototype.indexOf=function(c){if(null==this)throw new TypeError;var b,g=Object(this),a=g.length>>>0;if(0===a)return-1;b=0;1<arguments.length&&(b=Number(arguments[1]), b!=b?b=0:0!=b&&Infinity!=b&&-Infinity!=b&&(b=(0<b||-1)*Math.floor(Math.abs(b))));if(b>=a)return-1;for(b=0<=b?b:Math.max(a-Math.abs(b),0);b<a;b++)if(b in g&&g[b]===c)return b;return-1});return f}({},q,y));n.register("$3",function(f,c,h){f.trim=function(c,b){for(b||(b=" \n");c&&-1!==b.indexOf(c.substr(0,1));)c=c.substr(1);for(;c&&-1!==b.indexOf(c.substr(-1));)c=c.substr(0,c.length-1);return c};f.sprintf=function(c){var b=0,g,a=[].slice.call(arguments,1);return c.replace(/%(s|u|%)/g,function(d,e){if("%"=== e)return"%";g=a[b++];return String(g)||""})};return f}({},q,y));n.register("$34",function(f,c,h){function l(d){a||c._gat&&(a=_gat._createTracker(b,"loco"));if(a){var e=d.shift();a[e].apply(a,d)}else g&&g.push(d);return f}var b,g,a;f._init=function(a){if(b=a.code){g=c._gaq||(c._gaq=[]);g.push(["_setAccount",b]);g.push(["_trackPageview"]);g.push(["_setDomainName",a.host]);a=h.createElement("script");a.type="text/javascript";a.async=!0;a.src=("https:"==h.location.protocol?"https://ssl":"http://www")+ ".google-analytics.com/ga.js";var e=h.getElementsByTagName("script")[0];e.parentNode.insertBefore(a,e)}return f};f.event=function(a,e,k,b){return l(["_trackEvent",a||"",e||"",k||"",b||0])};f.page=function(a,e){return l(["_trackPageview",{page:a||location.pathname+location.hash,title:e||h.title}])};return f}({},q,y));n.register("$35",function(f,c,h){function l(a,d){if(b)b[a](d);else c.ga&&ga(a,d);return f}var b,g;f._init=function(a){a.code&&(function(a,e,k,b,g,m,p){a.GoogleAnalyticsObject=g;a[g]=a[g]|| function(){(a[g].q=a[g].q||[]).push(arguments)};a[g].l=1*new Date;m=e.createElement(k);p=e.getElementsByTagName(k)[0];m.async=1;m.src=b;p.parentNode.insertBefore(m,p)}(c,h,"script","//www.google-analytics.com/analytics.js","ga"),ga("create",a.code,{alwaysSendReferrer:!0,userId:a.user}),a.custom&&l("set",a.custom),f.page(),ga(function(a){b=a}));return f};f.event=function(a,d,e,k){return l("send",{hitType:"event",eventCategory:a||"",eventAction:d||"",eventLabel:e||"",eventValue:Number(k||0)})};f.page= function(a,d){var e={hitType:"pageview",page:a||location.pathname+location.hash,title:d||h.title};e.location=location.protocol+"//"+location.hostname+e.page;g&&l("set",{referrer:g});g=e.location;return l("send",e)};f.reset=function(){g=location.href;l("set",{page:location.pathname+location.hash,title:h.title,location:g});return f};return f}({},q,y));n.register("$28",function(f,c,I){function l(a,e){h(a).click(function(a){b&&b.event(e,"click",this.getAttribute("href")||"");return!0});a=null;return f} var b,g=location.hostname,a="/help"===location.pathname.substr(0,5);f.init=function(a){!b&&a&&(g=a.host||(a.host=g),b=a.legacy?n.require("$34","legacy.js"):n.require("$35","universal.js"),b._init(a));return f};f.link=function(d){for(var e=d.getAttribute("href");e&&"#"!==e;){if(0===e.indexOf("#"))return l(d,"anchor");if("/help"===e.substr(0,5)&&!a)d.setAttribute("target","_blank");else if(0===e.indexOf("http")||0===e.indexOf("//")){if(-1!==e.indexOf(g)&&/^(https?:)*\/\/([^\/]+)/.exec(e)&&g===RegExp.$2)break; d.setAttribute("target","_blank");l(d,"external")}break}return f};f.page=function(){b&&b.page.apply(b,arguments);return f};f.event=function(){b&&b.event.apply(b,arguments);return f};f.reset=function(){b&&b.reset&&b.reset();return f};return f}({},q,y));n.register("$31",function(f,c,n){function l(a,d,e,k,b){function s(){c&&clearTimeout(c);r&&r.fadeOut(400,function(){h(this).remove();r=null});return!1}function m(){p();-1!==k&&(c=setTimeout(s,k||2E3));r.off("mouseleave").on("mouseenter",p)}function p(){c&& clearTimeout(c);c=null;r.off("mouseenter").on("mouseleave",m)}var c;g||(g=n.createElement("div"),g.id="growls",n.body.appendChild(g));var r=h('<div class="growl growl-'+e+'"><div><a class="close" href="#"><span>X</span></a><span class="badge"></span><p class="message"></p><small class="caption"></small></div></div>');r.find("p").text(a||"Empty message");d?r.find("small").text(d):r.find("small").remove();if(b.length){b.push({label:"Cancel",callback:s,css:"cancel"});var f,t=h('<form action="#" class="dialog"></form>'); d=function(a,d){f=h('<input type="button" value="'+d.label+'" class="butt '+(d.css||"")+'" />');f.click(function(a){"function"===typeof d.callback&&d.callback(a,{close:s})});t.append(f);return f};for(a=0;a<b.length;a++)d(a,b[a]);r.append(t)}h(g).prepend(r.hide().fadeIn(400));r.find("a").click(s);m()}var b,g;f.init=function(){if(!b)return b=c.alert,c.alert=function(a){a=String(a).split("\n");var d=a[1]&&a.slice(1).join("\n");f.alert(a[0],d)},f};f.debug=function(a){b(a);return f};f.alert=function(a, d,e,k,g){try{return l(a,d||"",e||"alert",k||4E3,g||[]),!0}catch(s){return a+="\n\n--\n"+(s.message||s),b.call(c,a),!1}};f.success=function(a,d,e){return f.alert(a,d,"success",e||2E3)};f.dialog=function(a,d,e,b){return f.alert(a,d,b||"alert",-1,e)};f.login=function(a,d,e,b){f.dialog(d||"You're not logged in",e||"Please log in to continue",[{label:b||"Log in",callback:function(d,e){location.assign(a||"/session/auth/login?r="+encodeURIComponent(location.href))}}])};return f}({},q,y));n.register("$36", function(f,c,n){function l(a){return 27===a.keyCode&&r&&B?(H(),a.preventDefault(),!1):!0}function b(a){if(r){a=c.innerWidth;var d=c.innerHeight;a!==C&&(C=a,G(w));d!==v&&(v=d,A&&g())}return!0}function g(){var a=e.outerHeight(!0)-A.clientHeight;A.style.maxHeight=String(v-a)+"px"}function a(a){a?(s.show(),k.addClass("has-title")):(s.hide(),k.removeClass("has-title"))}var d,e,k,u,s,m,p,A,r=!1,B=!1,t=!1,E,z,C,w,v,D=f.init=function(){if(!d){d=h('<div id="overlay"></div>');e=h('<div class="overlay-frame"></div>'); k=h('<div class="overlay-container"></div>');s=h('<div class="overlay-title"><span class="icon"></span><span class="title">Untitled</span></div>');m=h("<nav></nav>");p=h('<a class="overlay-close" href="#"><span>x</span></a>');u=h('<div class="overlay-bg"></div>');d.append(e.append(k)).append(u).prependTo(n.body);h(n).on("keydown",l);h(c).resize(b);C=c.innerWidth;v=c.innerHeight;z=k.outerWidth(!0)-k.width()+(e.innerWidth()-e.width());E=parseInt(k.css("width"));if(!E||isNaN(E))E=k.width();m.hide().prependTo(e); s.append(p.hide()).hide().prependTo(e);d.hide()}return d},G=f.width=function(a){var d=D();if(null===a)e.css("width",""),k.css("width","");else{a=a||E||640;x=a+z;w=a;var b=C;x>b?(x=b,a=x-z,d.addClass("spill")):d.removeClass("spill");e.css("width",x+"px");k.css("width",a+"px")}return f};f.autoSize=function(){var a=D(),d=E||0;k.children().each(function(a,e){d=Math.max(d,h(e).outerWidth(!0))});G(d);if(A=a.find("div.overlay-scroll")[0])v=c.innerHeight,g();return f};f.css=function(a){D().attr("class",a); return f};f.html=function(a){D();c.innerShiv&&(a=innerShiv(a,!1));return k.html(a)};f.append=function(a){D();a instanceof jQuery||(a=h(a));k.append(a);return f};var H=f.close=function(a){if(r){var e=function(){D().hide();h(n.body).removeClass("has-overlay");r=!1;k.html("");r=null;d.trigger("overlayClosed",[f])};null==a&&(a=300);d.trigger("overlayClosing",[f]);a?d.fadeOut(a,e):e()}return f};f.title=function(d,e){D();var b="",k=s.find("span");e&&/^lang lang-(\w+)/.exec(e)&&(b=RegExp.$1);k.eq(0).attr("class", e||"icon").attr("lang",b);t=d||"";k.eq(1).text(t);null!=d?a(!0):B||a(!1);return f};f.enableClose=function(){D();B=!0;p.off("click").on("click",function(a){H();return!1});a(!0);p.show();return f};f.disableClose=function(){D();B=!1;p.hide();r&&t||a(!1);return f};f.enableNav=function(a){m.append(a);m.show();return f};f.disableNav=function(){m.html("").hide();return f};f.open=function(){D();k.html("");G(E);d.attr("class","");h(n.body).addClass("has-overlay");D().show();r=!0;f.title(null);B&&a(!0);d.trigger("overlayOpened", [f]);return f};f.listen=function(a){D().on("overlayClosed",a);return f};f.unlisten=function(a){D().off("overlayClosed",a);return f};return f}({},q,y));n.register("$11",function(f,c,n){function l(a,d){this.$element=h(a);this.options=d;this.enabled=!0;this.fixTitle()}f.init=function(a,d){var e={fade:!0,offset:5,delayIn:b,delayOut:g,anchor:a.attr("data-anchor"),gravity:a.attr("data-gravity")||"s"};d&&(e=h.extend({},e,d));a.tipsy(e)};f.delays=function(a,d){b=a||150;g=d||100};f.kill=function(){h("div.tipsy").remove()}; f.text=function(a,d){d.data("tipsy").setTitle(a)};var b,g;f.delays();h(n.body).on("overlayOpened overlayClosing",function(a){f.kill();return!0});l.prototype={show:function(){var a=this.getTitle();if(a&&this.enabled){var d=this.tip();d.find(".tipsy-inner")[this.options.html?"html":"text"](a);d[0].className="tipsy";d.remove().css({top:0,left:0}).prependTo(n.body);var a=(a=this.options.anchor)?this.$element.find(a):this.$element,a=h.extend({},a.offset(),{width:a[0].offsetWidth,height:a[0].offsetHeight}), e=d[0].offsetWidth,b=d[0].offsetHeight,g="function"==typeof this.options.gravity?this.options.gravity.call(this.$element[0]):this.options.gravity,c;switch(g.charAt(0)){case "n":c={top:a.top+a.height+this.options.offset,left:a.left+a.width/2-e/2};break;case "s":c={top:a.top-b-this.options.offset,left:a.left+a.width/2-e/2};break;case "e":c={top:a.top+a.height/2-b/2,left:a.left-e-this.options.offset};break;case "w":c={top:a.top+a.height/2-b/2,left:a.left+a.width+this.options.offset}}2==g.length&&("w"== g.charAt(1)?c.left=a.left+a.width/2-15:c.left=a.left+a.width/2-e+15);d.css(c).addClass("tipsy-"+g);d.find(".tipsy-arrow")[0].className="tipsy-arrow tipsy-arrow-"+g.charAt(0);this.options.className&&d.addClass("function"==typeof this.options.className?this.options.className.call(this.$element[0]):this.options.className);d.addClass("in")}},hide:function(){this.tip().remove()},fixTitle:function(){var a=this.$element,d=a.attr("title")||"";(d||"string"!==typeof a.attr("original-title"))&&a.attr("original-title", d).removeAttr("title")},getTitle:function(){var a,d=this.$element,e=this.options;this.fixTitle();"string"==typeof e.title?a=d.attr("title"==e.title?"original-title":e.title):"function"==typeof e.title&&(a=e.title.call(d[0]));return(a=(""+a).replace(/(^\s*|\s*$)/,""))||e.fallback},setTitle:function(a){var d=this.$element;d.attr("default-title")||d.attr("default-title",this.getTitle());null==a&&(a=d.attr("default-title")||this.getTitle());d.attr("original-title",a);if(this.$tip)this.$tip.find(".tipsy-inner")[this.options.html? "html":"text"](a)},tip:function(){this.$tip||(this.$tip=h('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>'),this.$tip.data("tipsy-pointee",this.$element[0]));return this.$tip},validate:function(){this.$element[0].parentNode||(this.hide(),this.options=this.$element=null)},enable:function(){this.enabled=!0},disable:function(){this.hide();this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled}};h.fn.tipsy=function(a){function d(d){var e= h.data(d,"tipsy");e||(e=new l(d,h.fn.tipsy.elementOptions(d,a)),h.data(d,"tipsy",e));return e}function e(){var e=d(this),b=a.delayIn;e.hoverState="in";0==b?e.show():(e.fixTitle(),setTimeout(function(){"in"==e.hoverState&&e.show()},b))}function b(){var e=d(this),k=a.delayOut;e.hoverState="out";0==k?e.hide():(e.tip().removeClass("in"),setTimeout(function(){"out"==e.hoverState&&e.hide()},k))}a=h.extend({},h.fn.tipsy.defaults,a);a.live||this.each(function(){d(this)});if("manual"!=a.trigger){var g=a.live? "live":"bind",c="hover"==a.trigger?"mouseleave":"blur";this[g]("hover"==a.trigger?"mouseenter":"focus",e)[g](c,b)}return this};h.fn.tipsy.defaults={className:null,delayIn:0,delayOut:0,fade:!1,fallback:"",gravity:"n",html:!1,live:!1,offset:0,opacity:0.8,title:"title",trigger:"hover",anchor:null};h.fn.tipsy.revalidate=function(){h(".tipsy").each(function(){var a=h.data(this,"tipsy-pointee"),d;if(!(d=!a)){a:{for(;a=a.parentNode;)if(a==n){a=!0;break a}a=!1}d=!a}d&&h(this).remove()})};h.fn.tipsy.elementOptions= function(a,d){return h.metadata?h.extend({},d,h(a).metadata()):d};h.fn.tipsy.autoNS=function(){return h(this).offset().top>h(n).scrollTop()+h(c).height()/2?"s":"n"};h.fn.tipsy.autoWE=function(){return h(this).offset().left>h(n).scrollLeft()+h(c).width()/2?"e":"w"};h.fn.tipsy.autoBounds=function(a,d){return function(){var e=d[0],b=1<d.length?d[1]:!1,g=h(n).scrollTop()+a,s=h(n).scrollLeft()+a,m=h(this);m.offset().top<g&&(e="n");m.offset().left<s&&(b="w");h(c).width()+h(n).scrollLeft()-m.offset().left< a&&(b="e");h(c).height()+h(n).scrollTop()-m.offset().top<a&&(e="s");return e+(b?b:"")}};return f}({},q,y));n.register("$21",function(f,c,I){var l={401:"You've been logged out",422:"Invalid data sent to server",404:"Not Found",500:"Server Error",502:"Bad Gateway",503:"Service unavailable",504:"Gateway timeout"};f.getErrors=function(){return l};f.jsonLink=function(b){if(!b)return"";b=b.split("?");b[0]=b[0].replace(/(\.[a-z0-9]{1,4})?$/i,".json");return b.join("?")};f.errorData=function(b,g,a){var d, e;a=b.responseText;g=b.status;if(!a&&0===g)return null;try{d=h.parseJSON(a)||{}}catch(k){d={},e=l[b.status]||k.message||k}d.error=e||d.error||d.statusText||b.statusText||l[g]||"Unknown Error";return d};f.ajax=function(b,g,a,d){function e(){a&&a()}function k(a){a.alert&&alert(a.alert);var b=a.success;b&&n.require("$31","growl.js").success.apply(this,b.push?b:[b]);b=d||h(I.body);b.trigger("locoAjaxSuccess",[a]);var k=a.events;if(k&&k.length)for(var g,r=n.require("$28","ga.js");g=k.shift();)b.trigger(g, [a]),r.event("ajax",g);if(b=a.download)c.location.assign(b);else if(b=a.redirect)if(0===b.indexOf("/modal/"))a.modal={url:b};else return c.location.assign(b),!1;else if(a.reload)return c.location.reload(),!1;(b=a.modal)&&n.require("$29","modal.js").replace(b);e();return!0}function u(a,d,b){if("abort"!==d){var u=a.status,r;if(401===u)n.require("$31","growl.js").login(),g&&!1===g(null,l[u],u,a)&&e();else{if("parsererror"===d)c.console&&console.error&&console.error(u,a.responseText),r=404===u?"Ajax service not found": /^\s+Fatal error/.test(a.responseText)?"Fatal server error from Ajax request":"Bad Ajax response";else{var h=f.errorData(a,d,b);h&&h.error&&(r=h.error)}"function"===typeof g&&!1===g(null,r,u,a)?e():h&&h.data&&!k(h.data)||(alert(r||"Unknown Ajax error"),e())}}}(b.headers||(b.headers={}))["X-Loco-Csrf"]=c.loco&&F.csrf||"";b.error=u;b.success=function(a,d,b){if(!a||"object"!==typeof a)return u(b,"unknown");(a.status||a.error)&&alert(a.error||a.statusText||b.statusText||l[a.status]||"Unknown Error"); "function"===typeof g&&!1===g(a&&a.data?a.data:a,null,d,b)?e():a&&a.data?k(a.data):e()};-1!==b.url.indexOf(".json")&&(b.dataType="json");return h.ajax(b)};return f}({},q,y));n.register("$29",function(f,c,I){function l(a){a.stopPropagation();a.preventDefault();return!1}function b(){k||(k=n.require("$36","overlay.js"),k.listen(d));return k}function g(){var a=m.length-1,d=m[a],e=h('<a class="has-icon icon-back" data-gravity="w">Back</a>').attr("href",d[0]).attr("title",d[1]).click(function(e){if(m[a]=== d&&B())return l(e)});k.enableNav(e);n.require("$11","tooltip.js").init(e)}function a(a,d){b().autoSize();var e=k.init();n.require("$17","html.js").init(e);m.length&&g();e.find("[data-script]").each(function(a,e){e=h(e);for(var b=-1,k,g=e.attr("data-script").split(" ");++b<g.length;)k=g[b],s[k]?s[k](e,d||{}):alert("Unknown script "+k)});e.trigger("locoModalLoaded",[k,a||"",d||{}]);var c,p=e.find("form")[0],v;if(p)a:for(e=0;e<p.elements.length;e++)switch(c=p.elements[e],c.type){case "text":case "email":case "textarea":v= Number(c.getAttribute("tabindex"));if(isNaN(v)||100>v)continue a;h(c).focus();break a}}function d(){p=null;m=[];return!0}function e(a){var d=h(a.currentTarget),e=d.attr("data-modal");if("back"===e){if(B())return l(a);e="close"}if("close"===e){r();var b=d.attr("href");if(b&&-1!==b.indexOf("#!"))return!0}else{var k="submit"===a.type,g=d.attr("title")||d.attr("data-title"),b=d.attr("href")||d.attr("action"),c=k?d.serialize():"",d=k?d.attr("method"):"get";e||(e=b.split("/").slice(1,4).join("-"));A(b, g,d,c,"modal "+e)}return l(a)}var k,u=n.require("$28","ga.js"),s={},m=[],p,A=f.load=function(d,e,g,c,r){var v=p;p=[].slice.call(arguments);v&&d!==v[0]&&(m.push(v),d+=-1===d.indexOf("?")?"?":"&",d+="r="+encodeURIComponent(v[0]));b().open().title("Loading ..").disableClose().disableNav().css("modal").html('<div class="loading"></div>');r&&k.width(null).css(r).autoSize();var v=d.split("#"),s=v[1];s&&(d=v[0]);var v=n.require("$21","http.js"),B={type:g||"get",data:c||"",url:v.jsonLink(d)};v.ajax(B,function(b, v,f){var B=b&&b.html;if(!B)return b&&b.redirect?(p=m.pop()||null,A(b.redirect,e,g,c,r)):(b=h('<h3 class="error"></h3>').text(v||"Unknown error"),k.enableClose().title("Error "+f||"?").html("").append(b)),!1;e=b.title||e||"Untitled";p&&(p[1]=e);k.enableClose().title(e,b.icon).html(B);f=b.js||{};s&&(f["#"]=s);a(d,f);u.page(d,e);k.init().one("overlayClosed",function(){u.reset()});return!0});return f},r=f.close=function(){b().close();return f},B=f.back=function(){if(previous=m.pop())return p=m[m.length- 2],A.apply(null,previous),!0};f.reload=function(){p&&A.apply(null,p)};f.initLink=function(a){a.click(e)};f.initForm=function(a){h(a).submit(e)};f.replace=function(d){b();var e=d&&d.html,g=d&&d.url,c=d&&d.title,p=d&&d.action;if(g)d=d&&d.css||g.split("/").slice(1,4).join("-"),A(g,c,"","",d);else if(e)k.open().html(e),c&&k.enableClose().title(c),a("",d&&d.js);else if("function"===typeof f[p])f[p]()};f.find=function(a){return b().init().find(a)};f.script=function(a,d){if(d){if("function"!==typeof d.run)throw Error(a+ " macro has no run function");s[a]=d.run;return f}return s[a]};return f}({},q,y));n.register("$8",function(f,c,n){f.listen=function(f,b){function g(){A[k?"show":"hide"]()}function a(a){p&&f.setAttribute("size",a.length||1);k=a;g();return a}function d(){u=null;b(k)}function e(){var e=f.value;m&&e===m&&(e="");e!==k&&(u&&clearTimeout(u),a(e),s?u=setTimeout(d,s):d())}var k,u;f=f instanceof jQuery?f[0]:f;var s=150,m=c.attachEvent&&f.getAttribute("placeholder"),p=1===Number(f.size),A=h('<a href="#clear" tabindex="-1" class="icon clear"><span>clear</span></a>').click(function(a){f.value= "";e();return!1});a(f.value);h(f).on("input blur focus",function(){e();return!0}).after(A);g();return{delay:function(a){s=a},ping:function(b){b?(u&&clearTimeout(u),b=f.value,m&&b===m&&(b=""),a(b),d(),b=void 0):b=e();return b},val:function(d){if(null==d)return k;u&&clearTimeout(u);f.value=a(d);g()},el:function(){return f},blur:function(a){return h(f).on("blur",a)}}};return f}({},q,y));n.register("$20",{"\u00e1":"a","\u00e0":"a","\u0103":"a","\u1eaf":"a","\u1eb1":"a","\u1eb5":"a","\u1eb3":"a","\u00e2":"a", "\u1ea5":"a","\u1ea7":"a","\u1eab":"a","\u1ea9":"a","\u01ce":"a","\u00e5":"a","\u01fb":"a","\u00e4":"a","\u01df":"a","\u00e3":"a","\u0227":"a","\u01e1":"a","\u0105":"a","\u0101":"a","\u1ea3":"a","\u0201":"a","\u0203":"a","\u1ea1":"a","\u1eb7":"a","\u1ead":"a","\u1e01":"a","\u01fd":"\u00e6","\u01e3":"\u00e6","\u1e03":"b","\u1e05":"b","\u1e07":"b","\u0107":"c","\u0109":"c","\u010d":"c","\u010b":"c","\u00e7":"c","\u1e09":"c","\u010f":"d","\u1e0b":"d","\u1e11":"d","\u0111":"d","\u1e0d":"d","\u1e13":"d", "\u1e0f":"d","\u00f0":"d","\ua77a":"d","\u01c6":"\u01f3","\u00e9":"e","\u00e8":"e","\u0115":"e","\u00ea":"e","\u1ebf":"e","\u1ec1":"e","\u1ec5":"e","\u1ec3":"e","\u011b":"e","\u00eb":"e","\u1ebd":"e","\u0117":"e","\u0229":"e","\u1e1d":"e","\u0119":"e","\u0113":"e","\u1e17":"e","\u1e15":"e","\u1ebb":"e","\u0205":"e","\u0207":"e","\u1eb9":"e","\u1ec7":"e","\u1e19":"e","\u1e1b":"e","\u1e1f":"f","\ua77c":"f","\u01f5":"g","\u011f":"g","\u011d":"g","\u01e7":"g","\u0121":"g","\u0123":"g","\u1e21":"g","\ua7a1":"g", "\u1d79":"g","\u0125":"h","\u021f":"h","\u1e27":"h","\u1e23":"h","\u1e29":"h","\u0127":"h","\u210f":"h","\u1e25":"h","\u1e2b":"h","\u1e96":"h","\u00ed":"i","\u00ec":"i","\u012d":"i","\u00ee":"i","\u01d0":"i","\u00ef":"i","\u1e2f":"i","\u0129":"i","\u012f":"i","\u012b":"i","\u1ec9":"i","\u0209":"i","\u020b":"i","\u1ecb":"i","\u1e2d":"i","\u0135":"j","\u01f0":"j","\u1e31":"k","\u01e9":"k","\u0137":"k","\ua7a3":"k","\u1e33":"k","\u1e35":"k","\u013a":"l","\u013e":"l","\u013c":"l","\u0142":"l","\u1e37":"l", "\u1e39":"l","\u1e3d":"l","\u1e3b":"l","\u0140":"l","\u1e3f":"m","\u1e41":"m","\u1e43":"m","\u0144":"n","\u01f9":"n","\u0148":"n","\u00f1":"n","\u1e45":"n","\u0146":"n","\ua7a5":"n","\u1e47":"n","\u1e4b":"n","\u1e49":"n","\u00f3":"o","\u00f2":"o","\u014f":"o","\u00f4":"o","\u1ed1":"o","\u1ed3":"o","\u1ed7":"o","\u1ed5":"o","\u01d2":"o","\u00f6":"o","\u022b":"o","\u0151":"o","\u00f5":"o","\u1e4d":"o","\u1e4f":"o","\u022d":"o","\u022f":"o","\u0231":"o","\u00f8":"o","\u01ff":"o","\u01eb":"o","\u01ed":"o", "\u014d":"o","\u1e53":"o","\u1e51":"o","\u1ecf":"o","\u020d":"o","\u020f":"o","\u01a1":"o","\u1edb":"o","\u1edd":"o","\u1ee1":"o","\u1edf":"o","\u1ee3":"o","\u1ecd":"o","\u1ed9":"o","\u1e55":"p","\u1e57":"p","\u0155":"r","\u0159":"r","\u1e59":"r","\u0157":"r","\ua7a7":"r","\u0211":"r","\u0213":"r","\u1e5b":"r","\u1e5d":"r","\u1e5f":"r","\ua783":"r","\u015b":"s","\u1e65":"s","\u015d":"s","\u0161":"s","\u1e67":"s","\u1e61":"s","\u015f":"s","\ua7a9":"s","\u1e63":"s","\u1e69":"s","\u0219":"s","\u017f":"s", "\ua785":"s","\u1e9b":"s","\u0165":"t","\u1e97":"t","\u1e6b":"t","\u0163":"t","\u1e6d":"t","\u021b":"t","\u1e71":"t","\u1e6f":"t","\ua787":"t","\u00fa":"u","\u00f9":"u","\u016d":"u","\u00fb":"u","\u01d4":"u","\u016f":"u","\u00fc":"u","\u01d8":"u","\u01dc":"u","\u01da":"u","\u01d6":"u","\u0171":"u","\u0169":"u","\u1e79":"u","\u0173":"u","\u016b":"u","\u1e7b":"u","\u1ee7":"u","\u0215":"u","\u0217":"u","\u01b0":"u","\u1ee9":"u","\u1eeb":"u","\u1eef":"u","\u1eed":"u","\u1ef1":"u","\u1ee5":"u","\u1e73":"u", "\u1e77":"u","\u1e75":"u","\u1e7d":"v","\u1e7f":"v","\u1e83":"w","\u1e81":"w","\u0175":"w","\u1e98":"w","\u1e85":"w","\u1e87":"w","\u1e89":"w","\u1e8d":"x","\u1e8b":"x","\u00fd":"y","\u1ef3":"y","\u0177":"y","\u1e99":"y","\u00ff":"y","\u1ef9":"y","\u1e8f":"y","\u0233":"y","\u1ef7":"y","\u1ef5":"y","\u017a":"z","\u1e91":"z","\u017e":"z","\u017c":"z","\u1e93":"z","\u1e95":"z","\u01ef":"\u0292","\u1f00":"\u03b1","\u1f04":"\u03b1","\u1f84":"\u03b1","\u1f02":"\u03b1","\u1f82":"\u03b1","\u1f06":"\u03b1", "\u1f86":"\u03b1","\u1f80":"\u03b1","\u1f01":"\u03b1","\u1f05":"\u03b1","\u1f85":"\u03b1","\u1f03":"\u03b1","\u1f83":"\u03b1","\u1f07":"\u03b1","\u1f87":"\u03b1","\u1f81":"\u03b1","\u03ac":"\u03b1","\u1f71":"\u03b1","\u1fb4":"\u03b1","\u1f70":"\u03b1","\u1fb2":"\u03b1","\u1fb0":"\u03b1","\u1fb6":"\u03b1","\u1fb7":"\u03b1","\u1fb1":"\u03b1","\u1fb3":"\u03b1","\u1f10":"\u03b5","\u1f14":"\u03b5","\u1f12":"\u03b5","\u1f11":"\u03b5","\u1f15":"\u03b5","\u1f13":"\u03b5","\u03ad":"\u03b5","\u1f73":"\u03b5", "\u1f72":"\u03b5","\u1f20":"\u03b7","\u1f24":"\u03b7","\u1f94":"\u03b7","\u1f22":"\u03b7","\u1f92":"\u03b7","\u1f26":"\u03b7","\u1f96":"\u03b7","\u1f90":"\u03b7","\u1f21":"\u03b7","\u1f25":"\u03b7","\u1f95":"\u03b7","\u1f23":"\u03b7","\u1f93":"\u03b7","\u1f27":"\u03b7","\u1f97":"\u03b7","\u1f91":"\u03b7","\u03ae":"\u03b7","\u1f75":"\u03b7","\u1fc4":"\u03b7","\u1f74":"\u03b7","\u1fc2":"\u03b7","\u1fc6":"\u03b7","\u1fc7":"\u03b7","\u1fc3":"\u03b7","\u1f30":"\u03b9","\u1f34":"\u03b9","\u1f32":"\u03b9", "\u1f36":"\u03b9","\u1f31":"\u03b9","\u1f35":"\u03b9","\u1f33":"\u03b9","\u1f37":"\u03b9","\u03af":"\u03b9","\u1f77":"\u03b9","\u1f76":"\u03b9","\u1fd0":"\u03b9","\u1fd6":"\u03b9","\u03ca":"\u03b9","\u0390":"\u03b9","\u1fd3":"\u03b9","\u1fd2":"\u03b9","\u1fd7":"\u03b9","\u1fd1":"\u03b9","\u1f40":"\u03bf","\u1f44":"\u03bf","\u1f42":"\u03bf","\u1f41":"\u03bf","\u1f45":"\u03bf","\u1f43":"\u03bf","\u03cc":"\u03bf","\u1f79":"\u03bf","\u1f78":"\u03bf","\u1fe4":"\u03c1","\u1fe5":"\u03c1","\u1f50":"\u03c5", "\u1f54":"\u03c5","\u1f52":"\u03c5","\u1f56":"\u03c5","\u1f51":"\u03c5","\u1f55":"\u03c5","\u1f53":"\u03c5","\u1f57":"\u03c5","\u03cd":"\u03c5","\u1f7b":"\u03c5","\u1f7a":"\u03c5","\u1fe0":"\u03c5","\u1fe6":"\u03c5","\u03cb":"\u03c5","\u03b0":"\u03c5","\u1fe3":"\u03c5","\u1fe2":"\u03c5","\u1fe7":"\u03c5","\u1fe1":"\u03c5","\u1f60":"\u03c9","\u1f64":"\u03c9","\u1fa4":"\u03c9","\u1f62":"\u03c9","\u1fa2":"\u03c9","\u1f66":"\u03c9","\u1fa6":"\u03c9","\u1fa0":"\u03c9","\u1f61":"\u03c9","\u1f65":"\u03c9", "\u1fa5":"\u03c9","\u1f63":"\u03c9","\u1fa3":"\u03c9","\u1f67":"\u03c9","\u1fa7":"\u03c9","\u1fa1":"\u03c9","\u03ce":"\u03c9","\u1f7d":"\u03c9","\u1ff4":"\u03c9","\u1f7c":"\u03c9","\u1ff2":"\u03c9","\u1ff6":"\u03c9","\u1ff7":"\u03c9","\u1ff3":"\u03c9","\u0491":"\u0433","\u0450":"\u0435","\u0451":"\u0435","\u04c2":"\u0436","\u045d":"\u0438","\u04e3":"\u0438","\u04ef":"\u0443"});n.register("$7",function(f,c,h){f.init=function(){function c(a){return f[a]||a}function b(a){return String(a||"").toLowerCase().replace(e, c)}function g(a,d,e){for(var b=a.split(k),g=b.length;0!==g--;)(a=b[g])&&null==e[a]&&(d.push(a),e[a]=!0);return d}function a(a,e){for(var k=[],c={},f,u=e.length;0!==u--;)(f=e[u])&&g(b(f),k,c);d[a]=k}var d=[],e=/[^a-z0-9]/g,k=/[\-_\s.?!;:,*^+=~`"(){}<>\[\]\/\\\u00a0\u1680\u180e\u2000-\u206f\u2e00-\u2e7f\u3000-\u303f]+/,f=n.require("$20","flatten.json");return{find:function(a,e){var k=[],c=-1,f=d,u=f.length,t,h,z,C,l,v,D=g(b(a),[],{}),G=D.length,n=e?!0:!1;a:for(;++c<u;)if(z=f[c],null!=z&&(C=z.length)){l= 0;b:for(;l<G;l++){v=D[l];for(t=0;t<C;t++)if(h=z[t],0===h.indexOf(v))continue b;continue a}k.push(n?e[c]:c)}return k},add:function(a,e){d[a]=g(b(e),[],{})},push:function(e){a(d.length,e)},index:function(d,e){a(d,e)},size:function(){return d.length},clear:function(){d=[]},remove:function(a){d[a]=null}}};return f}({},q,y));n.register("$22",function(f,c,h){f.create=function(){var c=[],b=n.require("$7","fulltext.js").init();return{add:function(g,a){b.add(c.length,a);c.push(g);return this},find:function(g){return b.find(g, c)},clear:function(){c=[];b.clear();return this}}};return f}({},q,y));n.register("$10",function(f,c,q){function l(b){-1===b.indexOf("?")&&(b="/auto/"+b+".json?q=");this.url=b;this.dead={}}function b(){this.dict=n.require("$22","dict.js").create()}f.init=function(g){function a(){if("hint"!==G){var a=v.val()&&!(J&&J.val())&&null==C&&!t;U[a?"addClass":"removeClass"]("error")}}function d(a){J&&J.val(a)}function e(){q.show();var a=v.outerWidth(!1),d=v.outerHeight(!1),e=v.css("margin-top");e&&(e=parseInt(e), isNaN(e)||(d+=e));a-=2;q.css("top",d+"px").css("width",a+"px");t=!0}function k(){q.hide();t=!1}function c(){q.html("");k();B=0;w=C=null}function f(d){c();var b;for(b=0;b<d.length;b++){var k=b,g=d[b],v=g.value,t=g.lang||v.lang,r=h('<span class="label"></span>').text(g.label),A=h('<div class="auto-comp-result"></div>'),s=void 0,z=void 0;if(z=g.icon)s=h("<span></span>").attr("class",z).appendTo(A),t?(s.attr("lang",t),g.lang=t):-1!==z.indexOf("lang-"+v)&&(s.attr("lang",v),g.lang=v);for(z in g)A.data(z, g[z]);A.append(r);m(k,A)}(B=d.length)?(E&&e(),p(0)):(p(null),a(),U.trigger("locoAutonone",[]))}function m(a,d){q.append(d);d.click(function(e){e.stopPropagation();p(a,d);r();return!1});return d}function p(a,e){w&&(w.removeClass("selected"),w=null);C=null;null==a?d(""):(e||(e=q.find("div.auto-comp-result").eq(a)),e.length&&(e.addClass("selected"),C=a,w=e))}function A(a){if(B){var d=B-1;null==C?a=0<a?0:d:(a=C+a,0>a?a=d:a>d&&(a=0));return p(a)}}function r(){if(null==C)I.val(""),d("");else{var e=q.find("div.auto-comp-result").eq(C), b=e.data()||{label:"Error"},g=b.value,f=b.label;d(g);I.val(f);k();e=e.clone();e.data(b);c();m(0,e);B=1;p(0,e);a();e.trigger("locoAutocomp",[g,f,e])}}var B=0,t=!1,E=!1,z=g.form,C=null,w=null,v=h(g),D=v.attr("name"),G=v.attr("data-mode"),H=v.attr("data-provider"),J="hint"!==G&&h('<input type="hidden" value="" name="'+D+'" />').appendTo(z),U=h('<div class="auto-comp-wrap"></div>').replaceAll(v),q=h('<div class="auto-comp-drop"></div>');H&&(H=new l(H));J&&v.attr("name","_"+D);v.attr("autocomplete")|| v.attr("autocomplete","off");U.append(v).append(q);k();v.focus(function(a){E=!0;1<B&&e()}).blur(function(d){E=!1;a()}).keydown(function(a){function d(){a.preventDefault();a.stopPropagation();return!1}switch(a.keyCode){case 27:t&&(a.stopPropagation(),k(),v.blur());break;case 40:B&&(t?A(1):e());break;case 38:t&&A(-1);break;case 13:if(t)return r(),d();if(!C&&"hint"!==G)return d()}return!0});var I=n.require("$8","LocoTextListener.js").listen(v,function(a){H&&H.fetch(a,f)});(z=v.attr("data-pre"))&&(z= h.parseJSON(z))&&z.value&&z.label?(f([z]),r()):!g.value||J&&J.val()||!H||H.fetch(g.value,function(a){f(a);r()});return{$:v,val:function(){return J&&J.val()},clear:c,reset:function(){c();v.val("");d("");I.ping()},force:function(a,e){c();d(e||"");I.val(a)},preload:function(a){B&&c();H=new b;var d,e;for(d in a)e=a[d],H.add(e)},mode:function(a){G=a},provide:function(a){H=new l(a)}}};l.prototype.fetch=function(b,a){if(!b)return a&&a([]),this.dead={},this;var d,e=this.dead;for(d in e)if(0===b.indexOf(d))return a&& a([]),this;d={dataType:"json",url:this.url+encodeURIComponent(b)};n.require("$21","http.js").ajax(d,function(d){var c=d&&d.results;c&&(a&&d.query&&d.query===b&&a(d.results),c.length||(e[b]=0));return!0});return this};b.prototype.add=function(b){var a=b.fulltext||b.label||b.value;a&&this.dict.add(b,a)};b.prototype.fetch=function(b,a){var d=b?this.dict.find(b):[];a&&a(d);return this};return f}({},q,y));n.register("$9",function(f,c,q){function l(a){a.stopPropagation();a.preventDefault();return!1}function b(a, d,e){if(e=e||a.getElement(d))e.off().mouseup(function(e){e.stopPropagation();a.selectIndex(d,!0);return!1}).mouseover(function(){h(this).addClass("over");a.hover=d;return!0}).mouseout(function(){h(this).removeClass("over");a.hover=-1;return!0}),e=null;return a}function g(a){if(a){var d,e=a[0],b=e.id,g=e.title,c=[],f=[],p=-1,A=e.options.length,r,B=this.selectedIcon||"";this.id=b||"";this.name=e.name||"";this.prefix=e.getAttribute("data-prefix");for(this.defaultIcon=e.getAttribute("data-icon")||"icon no-icon";++p< A;)d=e.options[p],r=d.disabled,d.selected&&c.push(p),d=h(d),f.push([d.val(),d.text(),d.attr("data-icon")||B,r,d.attr("lang")]);this.hidden||(this.hidden=h('<input type="hidden" name="'+this.name+'" value="" />').appendTo(e.form));this.list=h('<ul class="clearfix"></ul>');this.icon=h('<span class="icon"> </span>');this.selection=h('<span class="label"></span>');this.handle=h('<a class="handle" href="#"></a>').attr("tabindex",a.attr("tabindex")||"").append(this.icon).append(this.selection);d=h('<div class="selector"></div>').addClass(e.className).append(this.handle).append(this.list).replaceAll(e); b&&d.attr("id",b);g&&a.hasClass("hastip")&&(d.attr("title",g),n.require("$11","tooltip.js").init(d,{gravity:a.attr("data-gravity")||"s",anchor:a.attr("data-anchor")}));this.wrapper=d;this.up=d.hasClass("up");for(this.clearOptions();d=f.shift();)this.addOption.apply(this,d);this.enable();this.close();if(A=c.length)for(p=0;p<A;p++)this.selectIndex(c[p]);else p=e.selectedIndex,null!=p&&0<=p&&this.selectIndex(p)}}f.create=function(a){return new g(a)};f.extend=function(a){a.parent=g;a.prototype=new g}; c=g.prototype;c.enable=function(){var a=this;a.handle.click(function(a){a.preventDefault();return!1}).mouseover(function(d){return a.onRollover(d)}).mouseout(function(d){return a.onRollout(d)}).mousedown(function(d){return a.onPress(d)}).keydown(function(d){return a.onKeydown(d)});h(q).mouseup(function(d){return a.onRelease(d)}).keydown(function(d){return a.onGlobalKeydown(d)})};c.onRollover=function(a){return this.over=!0};c.onRollout=function(a){this.over=!1;return!0};c.onPress=function(a){return this.active? this.over?(this.close(),a.stopPropagation(),a.preventDefault(),!1):!0:(this.open(),a.stopPropagation(),a.preventDefault(),this.handle.focus(),!1)};c.onRelease=function(a){this.active&&!this.over&&this.close();return!0};c.onGlobalKeydown=function(a){if(this.active)switch(a.keyCode){case 27:return this.close(),l(a);case 40:return this.hoverNext(1),l(a);case 38:return this.hoverNext(-1),l(a);case 13:if(-1!=this.hover)return this.selectIndex(this.hover,!0),this.hoverItem(-1),this.close(),l(a)}return!0}; c.onKeydown=function(a){return this.active||40!==a.keyCode?!0:(this.open(),l(a))};c.open=function(){var a=this.list,d=this.handle,e=this.wrapper,b=e.data("tipsy"),g=d.outerWidth()||0,c=a.outerWidth()||0;this.active=!0;this.hover=-1;e.addClass("active");a.show();this.up?a.css("top","-"+a.outerHeight()+"px"):a.css("top",d.outerHeight()+"px");b&&b.disable();g>c&&(g-=c-a.width(),a.css("min-width",String(g)+"px"))};c.close=function(){var a=this.wrapper,d=a.data("tipsy");this.list.hide();this.active=!1; -1!==this.hover&&(this.getElement(this.hover).removeClass("over"),this.hover=-1);a.removeClass("active");d&&d.enable()};c.hoverItem=function(a,d){-1!==this.hover&&this.getElement(this.hover).removeClass("over");this.hover=a;-1!==a&&(d=d||this.getElement(a),d.addClass("over"))};c.hoverNext=function(a){var d=this.options.length;if(d){d-=1;if(-1==this.hover)a=0<a?0:d;else{a=this.hover+a;if(0>a){this.close();return}a>d&&(a=0)}this.hoverItem(a)}};c.enableChange=function(a){this.eventName=a;this.eventData= [].slice.call(arguments,1);return this};c.enableConfirm=function(a){this.confirm=a;return this};c.clearOptions=function(){this.index={};this.length=0;this.options=[];this.list.html("");this.hidden.val("");this.idx=this.hover=-1;return this};c.destroy=function(){this.clearOptions();this.hidden.remove()};c.addOption=function(a,d,e,k,g){var c=this.options.length,f=h("<span></span>").addClass(e||"icon no-icon"),p=h('<span class="label"></span>').text(d||a),p=h("<li></li>").append(f).append(p).appendTo(this.list); g?g=g.split("-").shift():e&&-1!==e.indexOf("lang-"+a)&&(g=a);g&&f.attr("lang",g);p.attr("data-option",c);this.options[c]={value:a,text:d,lang:g||"",icon:e};this.index[a]=c;this.length=c+1;k?this.disableIndex(c):b(this,c,p);return c};c.disableOption=function(a){return this.disableIndex(this.index[a])};c.disableIndex=function(a){(a=this.getElement(a))&&a.addClass("disabled").off();return this};c.enableOption=function(a){return this.enableIndex(this.index[a])};c.enableIndex=function(a){return b(this, a)};c.reIndex=function(){this.index={};this.length=0;for(var a=this.options.length;0!==a--;)this.index[this.options[a].value]=a,this.length++};c.selectValue=function(a,d){return this.selectIndex(this.index[a],d)};c.selectIndex=function(a,d){var e=this.options[a];if(e){var b=this,g=b.idx,c=e.value,f=e.icon||b.defaultIcon,p=function(){null!=g&&b.getElement(g).removeClass("active");b.getElement(a).addClass("active");b.setLabel(e.text).setIcon(f,e.lang);b.hidden.val(c);b.idx=a;d&&b.change()};g===a?b.hidden.val(c): d?"function"===typeof b.confirm?b.confirm.call(null,e,function(a){a&&p()}):b.beforeChange(c)&&p():p();b.active&&b.close()}return this};c.setLabel=function(a){this.selection.text(a);this.prefix&&this.selection.prepend(h('<span class="prefix"></span>').text(this.prefix));return this};c.setIcon=function(a,d){this.icon.attr("class",a).attr("lang",d||"");return this};c.val=function(){var a=this.options[this.idx];return a&&a.value};c.change=function(){var a=this.val(),d=this.save,e=this.eventName||"change", b=[a].concat(this.eventData||[]);this.wrapper.trigger(e,b);d&&d(a);return this};c.beforeChange=function(a){var d=h.Event("locoBeforeSelect");this.wrapper.trigger(d,[a]);return!d.isDefaultPrevented()};c.renameOption=function(a,d){var e=this.index[a],b=this.options[e];b&&(b.text=d,this.getElement(e).find("span.label").text(d),e===this.idx&&this.setLabel(d));return this};c.removeOption=function(a){var d=this.index[a],e=this.options[d];e&&(a=this.val(),this.getElement(d).remove(),this.options.splice(d, 1),this.reIndex(),a===e.value?this.selectIndex(0,!0):this.selectValue(a,!1))};c.getElement=function(a){return this.list.find("li").eq(a)};c.getWrapper=function(){return this.wrapper};c.persist=function(a){var d=this.id||this.name,e=a.fetch(d);null!=e&&this.selectValue(e,!0);this.save=function(e){a.store(d,e)};return this};c.listen=function(a){return this.on(this.eventName||"change",a)};c.on=function(a,d){this.wrapper.on(a,d);return this};c=null;return f}({},q,y));n.register("$30",function(f,c,q){function l(b){var g= [],a=h([]);this.hidden=a;this.selected=g;this.selectedIcon="icon icon-checkbox";this.constructor.call(this,b);this.wrapper.addClass("multi");for(var d,e,k,c=h('<input type="checkbox" name="'+this.name+'[]" />')[0],f=this.options,m=f.length,p=-1;++p<m;)d=this.getElement(p)[0],k=c.cloneNode(!0),g[p]&&(k.checked=!0),k.setAttribute("value",f[p].value),a.push(d.appendChild(k));(e=this.defaultIcon)&&this.setIcon(e);(e=b.attr("title"))?this.setLabel(e):this.wrapper.addClass("no-title")}f.create=function(b){return new l(b)}; n.require("$9","LocoSelector.js").extend(l);c=l.prototype;c.selectIndex=function(b,g){return this.setIndexState(b,!this.selected[b],g)};c.setIndexState=function(b,g,a){var d=this.options[b],e=this.getElement(b),k=this.hidden[b],c=this.selected;d&&g!==c[b]&&(c[b]=g,e[g?"addClass":"removeClass"]("checked"),k&&(k.checked=g),a&&this.change());return this};c.selectValue=function(b,g){if(null==b.pop)return l.parent.prototype.selectValue.call(this,b,g);for(var a=this.selected.slice(),d=this.options.length, e=!1,k=-1,c=-1;++k<d;)a[k]&&(e=!0),a[k]=!1;if(d=b.length)for(;++c<d;)k=this.index[b[c]],!1===a[k]&&(e=a[k]=!0);if(e){for(k in a)this.setIndexState(k,a[k]);g&&this.change()}return this};c.val=function(){for(var b=[],c=this.options,a=this.selected,d=a.length,e=-1;++e<d;)a[e]&&b.push(c[e].value);return b};c=null;return f}({},q,y));n.register("$17",function(f,c,q){var l=c.ieVersion;f.ie=function(b){return b?l<=b:l};var b=f.init=function(c){c?c instanceof jQuery||(c=h(c)):c=h(q.body);var a=n.require("$28", "ga.js"),d=n.require("$18","forms.js"),e=n.require("$29","modal.js"),k=n.require("$10","LocoAutoComplete.js"),u=n.require("$9","LocoSelector.js"),s=n.require("$30","LocoMultiSelector.js"),m=n.require("$11","tooltip.js");c.find("form").each(function(a,b){var c=h(b);l&&10>l&&d.placeholders(c);b.getAttribute("data-modal")?e.initForm(b):b.action&&0!==c.attr("action").indexOf("#")&&!b.target&&d.jsonify(b);c.hasClass("hasreveal")&&d.revealify(c);c.find("input.auto-comp").each(function(a,d){k.init(d)}); c.find("select.selector").each(function(a,d){d.hasAttribute("multiple")?s.create(h(d)):u.create(h(d))});c.find("button.hastip").each(function(a,d){m.init(h(d))})});c.find("a").each(function(d,k){-1!==k.className.indexOf("hastip")&&m.init(h(k));if(-1!==k.href.indexOf("/modal/")||k.getAttribute("data-modal"))e.initLink(h(k));else{a.link(k);var c=k.getAttribute("data-ajax-target");c&&(c=h("#"+c),h(k).click(function(a){a.preventDefault();c.addClass("loading");h.get(k.href,function(a){a=f.$(a).replaceAll(c); b(a);a.trigger("locoAhah")});return!1}))}});d=e=k=c=null;return f};f.$=function(b){return h(c.innerShiv?innerShiv(b,!1):b)};h.fn._html=function(g){return null!=g?(g=this.html(c.innerShiv?innerShiv(g,!1):g),b(this),g):j.html()};h.fn.macro=function(b,a){if("function"!==typeof b.run)throw Error("macro has no run function");b.run(this,a||{});return this};f.el=function(b,a){var d=q.createElement(b||"div");a&&(d.className=a);return d};f.txt=function(b){return q.createTextNode(b||"")};f.h=function(){function b(){e= /[<>&]/g;k=/(\r\n|\n|\r)/g;c=/(?:https?):\/\/([a-zA-Z0-9\-_\.\?%~&;=\/]+(?:#.*)?)/g;b=null}function a(a){return"&#"+a.charCodeAt(0)+";"}function d(a,d){return'<a href="'+a+'">'+d+"</a>"}var e,k,c;return function(f,m){b&&b();var p=f.replace(e,a);m&&(p=p.replace(k,"<br />").replace(c,d));return p}}();f.noop=function(b){b&&(b.preventDefault(),b.stopPropagation(),h(b.target).blur());return!1};return f}({},q,y));n.register("$18",function(f,c,q){function l(a){function d(){a.value===c&&(a.value="",b.removeClass("placeheld")); return!0}function e(){""===a.value&&(a.value=c,b.addClass("placeheld"));return!0}var b=h(a);if(!b.hasClass("auto-comp")){var c=b.attr("placeholder");if(c)return b.focus(d).blur(e),e(),{kill:function(){d();b.off("focus",d).off("blur",e)}}}}var b=f.enable=function(a){function d(a,d){d.getAttribute("data-was-disabled")||(d.disabled=!1)}a.find(".button").removeClass("loading");a.find("button").each(d);a.find("input").each(d);a.find("select").each(d);a.find("textarea").each(d);c.attachEvent&&a.hasClass("has-placeholders")&& f.placeholders(a);delete a._disabled},g=f.disable=function(a){function d(a,d){d.disabled?d.setAttribute("data-was-disabled","true"):d.disabled=!0}a._disabled||(a.find(".button").addClass("loading"),a.find("button").each(d),a.find("input").each(d),a.find("select").each(d),a.find("textarea").each(d),a._disabled=!0)};f.jsonify=function(a,d,e){a instanceof jQuery||(a=h(a));a.disable||(h.fn.disable=function(){g(this);return this},h.fn.enable=function(){b(this);this.placehold&&this.placehold();return this}); var c="";a.find('[type="submit"]').click(function(a){a&&a.target&&a.target.name&&(c=encodeURIComponent(a.target.name)+"="+encodeURIComponent(a.target.value));return!0});a.submit(function(b){if(b&&b.isDefaultPrevented&&b.isDefaultPrevented()||e&&!1===e(b))return!1;var g=a.serialize(),g=g.replace(/%0D%0A/g,"%0A");c&&(g&&(g+="&"),g+=c,c="");a.disable();var f=n.require("$21","http.js"),g={url:f.jsonLink(a.attr("action")),type:a.attr("method"),data:g};f.ajax(g,d,function(){a.enable()},a);b.preventDefault(); b.stopPropagation();return!1})};f.revealify=function(a){a=a.closest("form");a.find("div[data-reveal-if]").each(function(d,b){function c(a){var d;t=t||a.target;if("."===r)d=Boolean(t&&t[B]),p&&(d=!d);else{var b,e=h(t.form).serializeArray();for(b in e)e[b].name===A&&(d=e[b].value);d=p?B!==d:B===d}if(d!==m)if(m=d,a)g[m?"slideDown":"slideUp"](200);else g[m?"show":"hide"]();return!0}var g=h(b),f=/^(\!?)([_\w\-\[\]]+)(\.|!?=)(.*)$/.exec(g.attr("data-reveal-if"));if(f){var m,p=f[1],A=f[2],r=f[3],B=f[4], f=a[0][A];if(f.type||null==f.length)f=[f];d=f.length;for(var t;0!==d--;)t=f[d],c(),h(t).change(c).removeClass("jshide");f=f=t=null}});a=null};f.linkify=function(a){var d=a.getAttribute("data-icon");if(d){var b=h(a),c=h("<a> </a>");c.attr("href",a.form.action);c.attr("class",b.attr("class"));c.attr("tabindex",b.attr("tabindex"));b.attr("tabindex","-1");c.text(b.val());d&&h("<span></span>").prependTo(c).addClass(d);b.hide().after(c);c.click(function(a){b.click();return!1})}};f.placeholders=function(a){var d, b=[];a.find("input[placeholder]").each(function(a,c){"password"!==c.type&&(d=l(c))&&b.push(d)});b.length&&(a.submit(function(){for(var a in b)b[a].kill()}),a.addClass("has-placeholders"),d=i=null)};return f}({},q,y));n.register("$4",function(f,c,q){function l(a,d,b){function e(){c();k=setTimeout(d,b)}function c(){k&&clearTimeout(k);k=null}var k;e();h(a).mouseenter(c).mouseleave(e);return{die:function(){c();h(a).off("mouseenter mouseleave")}}}function b(a,d){a.fadeTo(d,0,function(){a.slideUp(d,function(){a.remove(); h(c).triggerHandler("resize")})})}function g(a,d){function e(d){k[f]=null;b(h(a),250);g&&g.die();var c;if(c=d)d.stopPropagation(),d.preventDefault(),c=!1;return c}var g,f;h('<button type="button" class="notice-dismiss" href="#"> </a>').prependTo(a).click(e);h(c).triggerHandler("resize");u();f=k.length;k.push(e);d&&(g=l(a,e,d))}function a(a,d,b){var e=n.require("$17","html.js");a=h('<div class="notice notice-'+a+'" loco-notice inline></div>').prependTo(h("#loco-notices"));var c=h(e.el("p"));b=h(e.el("span")).text(b); d=h(e.el("strong","has-icon")).text(d+": ");c.append(d).append(b).appendTo(a);return a}function d(d,b,e,k){d=a(e,b,d).hide().fadeIn(500);h(c).triggerHandler("resize");g(d,k);return f}function e(){h("#loco-notices").find("div.notice").each(function(a,d){g(d,!1)})}var k=[],u=Date.now||function(){return(new Date).getTime()},s,m,p,A;f.error=function(a){return d(a,s,"error")};f.warning=function(a){return d(a,m,"warning")};f.info=function(a){return d(a,p,"info")};f.success=function(a){return d(a,A,"success", 5E3)};f.log=function(){c.console&&console.log&&console.log.apply(console,arguments)};f.debug=function(a,d){c.console&&console.error&&(console.error("Loco Error: "+a),d&&console.debug&&console.debug(d))};f.clear=function(){for(var a=-1,d,b=k,e=b.length;++a<e;)(d=b[a])&&d();k=[];return f};f.create=a;f.raise=function(a){var d=f;(d[a.type]||d.error).call(d,a.message)};f.init=function(a){s=a._("Error");m=a._("Warning");p=a._("Notice");A=a._("OK");setTimeout(e,1E3);return f};return f}({},q,y));n.register("$5", function(f,c,q){function l(d,b,c,f){function m(a,b,k){var f=g||{_:function(a){return a}},m=a.responseText,z=h("<pre>"+m+"</pre>").text();z&&(z=z.replace(/(^\s+|\s+$)/g,""));z||(z=m);p.debug("Ajax failure for "+d,{status:a.status,error:b,message:k,output:m});p.log(f._("Provide the following text when reporting a problem")+":\n--8<--\n",z,"\n------");"parsererror"===b?(m=f._("Check console output for debugging information"),(z=z.split(/[\r\n]/)[0])?(z=z.replace(/ +in +\S+ on line \d+/,""),z=z.replace(/^[()! ]+Fatal error:\s*/, ""),p.error(z+".\n"+m)):p.error(f._("Server returned invalid data")+". "+m)):p.error(k||f._("Unknown error"));c&&c(a,b,k)}f.url=a;f.dataType="json";f.error=m;f.success=function(a,d,e){var c=a&&a.data,f=a&&a.notices,g=f&&f.length;for(!c||a.error?m(e,d,a&&a.error&&a.error.message):b&&b(c,d,e);g--;)p.raise(f[g])};var p=n.require("$4","notices.js").clear();return h.ajax(f)}var b={},g,a=c.ajaxurl||"/wp-admin/admin-ajax.php",d=c.encodeURIComponent;f.init=function(a){b=a.nonces||b;return f};f.localise=function(a){g= a;return f};f.submit=function(a,d,b){function c(){f.removeClass("loading");n.require("$18","forms.js").enable(f)}var f=h(a),g=f.serialize();f.addClass("loading");n.require("$18","forms.js").disable(f);return l(a.route.value,function(a,b,e){c();d&&d(a,b,e)},function(a,d,e){c();b&&b(a,d,e)},{type:a.method,data:g})};f.post=function(a,k,f,g){var m;(m=b[a])||(c.console&&console.debug&&console.debug('No nonce for "'+a+'"'),m="");m="action=loco_json&route="+d(a)+"&loco-nonce="+d(m);(k=k?h.param(k):"")&& (m+="&"+k);return l(a,f,g,{type:"post",data:m})};f.setNonce=function(a,d){b[a]=d;return f};return f}({},q,y));n.register("$19",{arab:1,aran:1,hebr:1,nkoo:1,syrc:1,syrn:1,syrj:1,syre:1,samr:1,mand:1,mend:1,thaa:1,adlm:1,cprt:1,phnx:1,armi:1,prti:1,phli:1,phlp:1,phlv:1,avst:1,mani:1,khar:1,orkh:1,ital:1,lydi:1,ar:1,ary:1,ckb:1,dv:1,fa:1,he:1,nqo:1,ps:1,ur:1,yi:1});n.register("$6",function(f,c,h){function l(){}var b,g,a=n.require("$19","rtl.json");f.init=function(){return new l};f.cast=function(a){return a instanceof l?a:"string"===typeof a?f.parse(a):f.clone(a)};f.clone=function(a){var b,c=new l;for(b in a)c[b]=a[b];return c};f.parse=function(a){b||(g=/[-_+]/,b=/^([a-z]{2,3})(?:-([a-z]{4}))?(?:-([a-z]{2}|[0-9]{3}))?(?:-([0-9][a-z0-9]{3,8}|[a-z0-9]{5,8}))?(?:-([a-z]-[-a-z]+))?$/i);a=String(a).split(g).join("-");if(!b.exec(a))return null;var e=new l;e.lang=RegExp.$1.toLowerCase();if(a=RegExp.$2)e.script=a.charAt(0).toUpperCase()+a.substr(1).toLowerCase();if(a=RegExp.$3)e.region=a.toUpperCase();if(a=RegExp.$4)e.variant= a.toLowerCase();if(a=RegExp.$5)e.extension=a;return e};c=l.prototype;c.isValid=function(){return!!this.lang};c.isKnown=function(){var a=this.lang;return!(!a||"zxx"===a)};c.toString=function(a){a=a||"-";var b,c=this.lang||"zxx";if(b=this.script)c+=a+b;if(b=this.region)c+=a+b;if(b=this.variant)c+=a+b;if(b=this.extension)c+=a+b;return c};c.getIcon=function(){for(var a=4,b,c,f=["variant","region","script","lang"],g=[];0!==a--;)if(b=f[a],c=this[b])1===a&&3===c.length?g.push("region-m49"):g=g.concat([b, b+"-"+c.toLowerCase()]);return g.join(" ")};c.isRTL=function(){return!!a[String(this.script||this.lang).toLowerCase()]};c=null;return f}({},q,y));n.register("$32",function(f,c,h){function l(a){c.console&&console.error&&console.error(a)}function b(){l("Method not implemented")}function g(){}function a(a){}g.prototype.toString=function(){return"[Undefined]"};a.prototype._validate=function(a){var e,c,f=!0;for(e in this)c=this[e],c===b?(l(a+"."+e+"() must be implemented"),f=!1):c instanceof g&&(l(a+"."+ e+" must be defined"),f=!1);return f};f.init=function(d,e){var c,f=new a;if(d)for(c=d.length;0!==c--;)f[d[c]]=b;if(e)for(c=e.length;0!==c--;)f[e[c]]=new g;return f};f.validate=function(a){var b=/function (\w+)\(/.exec(a.toString())?RegExp.$1:"";a.prototype._validate(b||"Object")};return f}({},q,y));n.register("$40",function(f,c,h){var l=c.requestAnimationFrame,b=c.cancelAnimationFrame,g=0;if(!l||!b)for(var a in{ms:1,moz:1,webkit:1,o:1})if(l=c[a+"RequestAnimationFrame"])if(b=c[a+"CancelAnimationFrame"]|| c[a+"CancelRequestAnimationFrame"])break;l&&b||(l=function(a){var b=d();timeToCall=Math.max(0,16-(b-g));nextTime=b+timeToCall;timerId=c.setTimeout(function(){a(nextTime)},timeToCall);g=nextTime;return timerId},b=function(a){clearTimeout(a)});var d=Date.now||function(){return(new Date).getTime()};f.loop=function(a,d){function c(){g=l(c,d);a(f++)}var f=0,g;c();return{stop:function(){g&&b(g);g=null}}};return f}({},q,y));n.register("$37",function(f,c,h){function l(b,d,e,c){if(a){var f=e;e=function(a){if((a.MSPOINTER_TYPE_TOUCH|| "touch")===a.pointerType)return f(a)}}b.addEventListener(d,e,c);return{unbind:function(){b.removeEventListener(d,e,c)}}}function b(a){a.preventDefault();a.stopPropagation();return!1}var g,a=!!c.navigator.msPointerEnabled,d=a?"MSPointerDown":"touchstart",e=a?"MSPointerMove":"touchmove",k=a?"MSPointerUp":"touchend";f.ok=function(a){null==g&&(g="function"===typeof h.body.addEventListener);g&&a&&a(f);return g};f.ms=function(){return a};f.dragger=function(a,c){function f(b){a.addEventListener(b,h[b],!1)} function g(b){a.removeEventListener(b,h[b],!1)}var h={};h[d]=function(a){u(a,function(b,e){e.type=d;c(a,e,t)});f(e);f(k);return!0};h[k]=function(a){g(e);g(k);u(a,function(b,d){d.type=k;c(a,d,t)});return!0};h[e]=function(a){u(a,function(b,d){d.type=e;c(a,d,t)});return b(a)};f(d);var t={kill:function(){g(d);g(e);g(k);a=t=c=null}};return t};f.swiper=function(c,f,g){function h(a){c.addEventListener(a,w[a],!1)}function l(a){c.removeEventListener(a,w[a],!1)}function t(){E&&E.stop();E=null}var E,z,C,w={}, v=[],D=[],G=[];w[d]=function(a){z=!1;t();var b=s();u(a,function(a,d){v[a]=b;D[a]=d.clientX;G[a]=d.clientY});C=c.scrollLeft;return!0};w[k]=function(a){u(a,function(a,b){var d=s()-v[a],e=D[a]-b.clientX,d=Math.abs(e)/d;f(d,e?0>e?-1:1:0)});C=null;return!0};w[e]=function(a){var d,e;null==C||u(a,function(a,b){d=D[a]-b.clientX;e=G[a]-b.clientY});if(e&&Math.abs(e)>Math.abs(d))return z=!0;d&&(z=!0,c.scrollLeft=Math.max(0,C+d));return b(a)};if(!a||g)h(d),h(e),h(k),a&&(c.className+=" mstouch");return{kill:function(){l(d); l(e);l(k);t()},swiped:function(){return z},ms:function(){return a},snap:function(b){a&&!g&&(c.style["-ms-scroll-snap-points-x"]="snapInterval(0px,"+b+"px)",c.style["-ms-scroll-snap-type"]="mandatory",c.style["-ms-scroll-chaining"]="none")},scroll:function(a,b,d){t();var e=c.scrollLeft,f=a>e?1:-1,g=Math[1===f?"min":"max"],k=Math.round(16*b*f);return E=n.require("$40","fps.js").loop(function(b){b&&(e=Math.max(0,g(a,e+k)),c.scrollLeft=e,a===e&&(t(),d&&d(e)))},c)}}};f.start=function(a,b){return l(a,d, b,!1)};f.move=function(a,b){return l(a,e,b,!1)};f.end=function(a,b){return l(a,k,b,!1)};var u=f.each=function(b,d){if(a)(b.MSPOINTER_TYPE_TOUCH||"touch")===b.pointerType&&d(0,b);else for(var e=-1,c=(b.originalEvent||b).changedTouches||[];++e<c.length;)d(e,c[e])},s=Date.now||function(){return(new Date).getTime()};return f}({},q,y));n.register("$41",function(f,c,n){f.init=function(c){function b(){e.style.top=String(-c.scrollTop)+"px";return!0}function f(){var b=e;b.textContent=c.value;b.innerHTML=b.innerHTML.replace(/[ \t]/g, a).split(/(?:\r\n|\r|\n)/).join('<span class="eol crlf"></span>\r\n')+'<span class="eol eof"></span>';return!0}function a(a,b){return'<span class="x'+a.charCodeAt(0).toString(16)+'">'+a+"</span>"}var d=c.parentNode,e=d.insertBefore(n.createElement("div"),c);h(c).on("input",f).on("scroll",b);h(d).addClass("has-mirror");e.className="ta-mirror";var k=c.offsetWidth-c.clientWidth;2<k&&(e.style.marginRight=String(k-2)+"px");f();b();return{kill:function(){h(c).off("input",f).off("scroll",b);d.removeChild(e); e=null;h(d).removeClass("has-mirror")}}};return f}({},q,y));n.register("$44",function(f,c,h){function l(a,d){for(var e=0,f=-1,g=d&&c[d],h=b[a]||[],m=h.length;++f<m;)callback=h[f],"function"===typeof callback&&(callback(g),e++);return e}var b={},g;f.load=function(a,d,e){function f(){m&&(clearTimeout(m),m=null);p&&(p.onreadystatechange=null,p=p=p.onload=null);a&&(delete b[a],a=null)}function g(b,d){var c=p&&p.readyState;if(d||!c||"loaded"===c||"complete"===c)d||l(a,e),f()}function s(){if(0===l(a))throw Error('Failed to load "'+ (e||a)+'"');f()}if(e&&c[e])"function"===typeof d&&d(c[e]);else if(null!=b[a])b[a].push(d);else{b[a]=[d];var m=setTimeout(s,4E3),p=h.createElement("script");p.setAttribute("src",a);p.setAttribute("async","true");p.onreadystatechange=g;p.onload=g;p.onerror=s;p.onabort=f;h.getElementsByTagName("head")[0].appendChild(p)}};f.stat=function(a){var b;if(!(b=g)){for(var e,c,f=h.getElementsByTagName("script"),s=-1,m=f.length;++s<m;)if(b=f[s].getAttribute("src"))if(e=b.indexOf("/lib/vendor"),-1!==e){c=b.substr(0, e);break}b=g=c||"/static"}return b+a};return f}({},q,y));n.register("$42",function(f,c,q){function l(a,b){a.setReadOnly(!1);a.on("change",function(a,d){return b.val(d.getValue())});a.on("focus",function(a,d){return b.focus()});a.on("blur",function(a,d){return b.blur()})}function b(a){a.off("change");a.off("focus");a.off("blur")}function g(a){b(a);a.setReadOnly(!0);a.setHighlightGutterLine(!1);a.setHighlightActiveLine(!1)}function a(a){function b(){this.$rules={start:[{token:"empty_line",regex:"^$"}, {token:"constant.language",regex:"(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"},{token:"printf",regex:"%(?:\\d+\\$)?[-+]?(?:'.)?[ 0]*-?\\d*(?:\\.d+)?[bcdeEfFgGosuxX%]"},{token:"printf",regex:"%(?:\\d+\\$)?[-,'+#0 (]*\\d*(?:\\.\\d+|\\.\\*)?[sScCuidoxXfFeEgGaAbBpn%@]"},{defaultToken:"text"}]}}function c(){this.HighlightRules=b}a=a.require;var f=a("ace/lib/oop");f.inherits(b,a("ace/mode/text_highlight_rules").TextHighlightRules);f.inherits(c,a("ace/mode/text").Mode);return new c}f.init= function(d,e){var c,f=!1,s=d.parentNode,m=s.appendChild(q.createElement("div"));h(s).addClass("has-proxy has-ace");n.require("$44","remote.js").load("https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.5/ace.js",function(b){if(m){if(!b)throw Error("Failed to load code editor");c=b.edit(m);var h=c.session,r=c.renderer;c.$blockScrolling=Infinity;c.setShowInvisibles(f);c.setWrapBehavioursEnabled(!1);c.setBehavioursEnabled(!1);c.setHighlightActiveLine(!1);h.setUseSoftTabs(!1);r.setShowGutter(!0);r.setPadding(10); r.setScrollMargin(8);h.setMode(a(b));c.setValue(d.value,-1);h.setUseWrapMode(!0);e?l(c,e):g(c)}},"ace");return{kill:function(){c&&(b(c),c.destroy(),c=null);m&&(s.removeChild(m),h(s).removeClass("has-proxy has-ace"),m=null);return this},disable:function(){c&&g(c);e=null;return this},enable:function(a){e=a;c&&l(c,a);return this},resize:function(){c&&c.resize();return this},val:function(a){c&&a!==c.getValue()&&c.setValue(a,-1);return this},invs:function(a){a=a||!1;f!==a&&(f=a,c&&c.setShowInvisibles(a)); return this},focus:function(){return this}}};return f}({},q,y));n.register("$43",function(f,c,q){function l(a,b){function e(){return b.val(a.getContent())}a.on("input",e);a.on("change",e);a.on("focus",function(a){return b.focus()});a.on("blur",function(a){return b.blur()});a.setMode("design")}function b(a){a.off("input");a.off("change");a.off("focus");a.off("blur")}var g=0;f.load=function(a){var b=n.require("$44","remote.js");b.load(b.stat("/lib/tinymce.min.js"),a,"tinymce");return f};f.init=function(a, d){function e(a){c=a;d?l(a,d):(b(a),a.setMode("readonly"));h(p).removeClass("loading")}var c,u=!1,s=a.parentNode,m=s.parentNode,p=s.appendChild(q.createElement("div")),A=m.insertBefore(q.createElement("nav"),s);h(s).addClass("has-proxy has-mce");h(p).html(a.value).addClass("mce-content-body loading");A.id="_tb"+String(++g);f.load(function(a){if(!a)throw Error("Failed to load HTML editor");p&&a.init({inline:!0,target:p,hidden_input:!1,theme:"modern",skin:!1,plugins:"link",browser_spellcheck:!0,menubar:!1, fixed_toolbar_container:"#"+A.id,toolbar:"formatselect | bold italic link unlink | bullist numlist outdent indent",block_formats:"Paragraph=p;Heading 1=h1;Heading 2=h2;Heading 3=h4;Heading 4=h4;Heading 5=h5;Heading 6=h6;",forced_root_block:"p",relative_urls:!1,convert_urls:!1,remove_script_host:!1,document_base_url:"",allow_script_urls:!1,formats:{alignleft:{classes:"alignleft"},alignright:{selector:"p,h1,h2,h3,h4,span,strong,em,a",classes:"alignright"},aligncenter:{selector:"p,h1,h2,h3,h4,span,strong,em,a", classes:"aligncenter"},strikethrough:{inline:"del"}},fix_list_elements:!0,entities:"38,amp,60,lt,62,gt,160,nbsp",entity_encoding:"named",keep_styles:!1,init_instance_callback:e})});return{val:function(a){null==c?h(p).html(a):c.getContent()!==a&&c.setContent(a);return this},kill:function(){c&&(b(c),c.destroy(),c=null);p&&(s.removeChild(p),h(s).removeClass("has-proxy has-mce"),p=null);A&&(m.removeChild(A),A=null);return this},enable:function(a){d=a;c&&l(c,a);return this},disable:function(){if(c){var a= c;b(a);a.setMode("readonly")}d=null;return this},focus:function(){c&&d&&c.focus();return this},invs:function(a){a=a||!1;u!==a&&(u=a,h(s)[a?"addClass":"removeClass"]("show-invs"));return this}}};return f}({},q,y));n.register("$38",function(f,c,q){function l(a){function b(){s&&m.off("input",e);s=!1;return!0}function e(){var b=a.value;b!==A&&(m.trigger("changing",[b,A]),A=b)}function c(){g=a;r=A;s||m.on("input",e);s=!0;m.trigger("editFocus");p.addClass("has-focus");return!0}function f(){g===a&&(g=null); m.trigger("editBlur");p.removeClass("has-focus");b();e();r!==A&&m.trigger("changed",[A]);return!0}var s=!1,m=h(a),p=h(a.parentNode),A=a.value,r;m.blur(f).focus(c);return{val:function(b){A!==b&&(a.value=b,s?(m.triggerHandler("input"),A=b):e());return!0},kill:function(){b();m.off("blur",f).off("focus",c)},fire:function(){A=null;e()},ping:e,blur:f,focus:c}}function b(a){this.e=a}var g;f._new=function(a){return new b(a)};f.init=function(a){var d=new b(a);a.disabled?(a.removeAttribute("disabled"),d.disable()): a.readOnly?d.disable():d.enable();return d};TextAreaPrototype=b.prototype;TextAreaPrototype.destroy=function(){this.unlisten();this.e=null};TextAreaPrototype.reload=function(a,b){b?this.l||this.enable():this.l&&this.disable();return this.val(a||"")};TextAreaPrototype.val=function(a){var b=this.e;if(null==a)return b.value;var e=this.p||this.l;e?e.val(a):b.value!==a&&(b.value=a,h(b).triggerHandler("input"));return this};TextAreaPrototype.fire=function(){this.l&&this.l.fire();return this};TextAreaPrototype.focus= function(){var a=this.p;a?a.focus():h(this.e).focus()};TextAreaPrototype.focused=function(){return g&&g===this.el};TextAreaPrototype.parent=function(){return this.e.parentNode};TextAreaPrototype.attr=function(a,b){var e=this.e;if(1===arguments.length)return e.getAttribute(a);null==b?e.removeAttribute(a):e.setAttribute(a,b);return this};TextAreaPrototype.editable=function(){return!!this.l};TextAreaPrototype.enable=function(){var a=this.p;this.e.removeAttribute("readonly");this.listen();a&&a.enable&& a.enable(this.l);return this};TextAreaPrototype.disable=function(){var a=this.p;this.e.setAttribute("readonly",!0);this.unlisten();a&&a.disable&&a.disable();return this};TextAreaPrototype.listen=function(){var a=this.l;a&&a.kill();this.l=l(this.e);return this};TextAreaPrototype.unlisten=function(){this.l&&this.l.kill();this.l=null;return this};TextAreaPrototype.setInvs=function(a,b){var e=this.i||!1;if(b||e!==a)this._i&&(this._i.kill(),delete this._i),(e=this.p)?e.invs&&e.invs(a):a&&(this._i=n.require("$41", "mirror.js").init(this.e)),this.i=a;return this};TextAreaPrototype.getInvs=function(){return this.i||!1};TextAreaPrototype.setMode=function(a){var b=this.p;a!==(this.m||"")&&(this.m=a,b&&b.kill(),this.p=b="code"===a?n.require("$42","ace.js").init(this.e,this.l):"html"===a?n.require("$43","mce.js").init(this.e,this.l):null,this.setInvs(this.i,!0),g&&this.focus());return this};TextAreaPrototype.name=function(a){this.e.setAttribute("name",a);return this};TextAreaPrototype.placeholder=function(a){this.e.setAttribute("placeholder", a);return this};TextAreaPrototype.redraw=function(a){var b=this.p;b&&b.resize&&!a&&b.resize()};TextAreaPrototype=null;return f}({},q,y));n.register("$39",function(f,c,n){function l(a){var b=c.console;b&&b.error&&b.error(a)}function b(a){var b=n.createElement("div");a&&b.setAttribute("class",a);return b}function g(a){return function(){a.resize();return this}}function a(a){return function(b){var d=b.target.$r;if(null==d)return!0;a.select(d);b.stopPropagation();b.preventDefault();return!1}}function d(a){return function(){a.redrawDirty()&& a.redraw();return!0}}function e(a){return function(b){var d;d=b.keyCode;if(40===d)d=1;else if(38===d)d=-1;else return!0;if(b.shiftKey||b.ctrlKey||b.metaKey||b.altKey)return!0;a.selectNext(d);b.stopPropagation();b.preventDefault();return!1}}function k(a){this.w=a}function u(a,b,d){var e=n.createElement("div");e.className=d||"";this._=e;this.d=b;this.i=a;this.length=b.length}function s(a){this.live=a;this.rows=[]}f.create=function(a){return new k(a)};var m=k.prototype;m.init=function(c){var f=this.w, k=f.id,m=f.splity(k+"-thead",k+"-tbody"),t=m[0],m=m[1],E=[],z=[];t.css.push("wg-thead");m.css.push("wg-tbody");c.eachCol(function(a,b){E.push(k+"-col"+a);z.push(b)});for(var s=b(),l=-1,v=E.length,D=b("wg-cols"),G=t.splitx.apply(t,E);++l<v;)G[l].header(z[l]),D.appendChild(s.cloneNode(!1));var n=[];c.eachRow(function(a,b,d){n[a]=new u(a,b,d)});c=m.body;this.rows=n;this.cols=D;this.root=c;t.redraw=g(this);t=m.fixed=G[0].bodyY()||20;f.lock().resize(t,m);f.css.push("is-table");f.restyle();this.redrawDirty(); this.render();h(c).attr("tabindex","-1").on("keydown",e(this)).on("mousedown",a(this)).on("scroll",d(this));return this};m.clear=function(){for(var a=this.pages||[],b=a.length;0!==b--;)a[b].destroy();this.pages=[];this.sy=this.mx=this.mn=this.vh=null;void 0;return this};m.render=function(){for(var a,b,d=[],e=-1,c=this.rows||[],f=this.f,g=f?!0:!1,k=g?f.length:c.length,h=this.r,v=this._r,m=this.root,u=this.cols;++e<k;)0===e%100&&(b=u.cloneNode(!0),b=new s(b),b.h=2200,b.insert(m),d.push(b)),a=g?f[e]: e,a=c[a],a.page=b,b.rows.push(a);b&&100!==b.size()&&b.sleepH(22);this.pages=d;this.mx=this.mn=null;this.redrawDirty();this.redraw();null==h?null!=v&&(a=c[v])&&a.page&&(delete this._r,this.select(v,!0)):(a=c[h])&&a.page?this.select(h,!0):(this.deselect(),this._r=h);return this};m.resize=function(){var a=-1,b=this.ww||(this.ww=[]),d=this.w,e=d.cells[0],c=e.body.childNodes,f=c.length,g=this.pages||[],k=g.length;for(d.redraw.call(e);++a<f;)b[a]=c[a].style.width;if(k){d=this.mx;for(a=this.mn;a<=d;a++)g[a].widths(b); this.redrawDirty()&&this.redraw()}};m.redrawDirty=function(){var a=!1,b=this.root,d=b.scrollTop,b=b.clientHeight;this.sy!==d&&(a=!0,this.sy=d);this.vh!==b&&(a=!0,this.vh=b);return a};m.redraw=function(){for(var a=0,b=-1,d=null,e=null,c=this.ww,f=this.sy,g=this.vh,k=this.mn,h=this.mx,v=Math.max(0,f-100),f=g+f+100,m=this.pages||[],u=m.length;++b<u&&!(a>f);)g=m[b],a+=g.height(),a<v||(null===d&&(d=b),e=b,g.rendered||g.render(c));if(k!==d){if(null!==k&&d>k)for(b=k;b<d;b++){g=m[b];if(!g)throw Error("Shit!"); g.rendered&&g.sleep()}this.mn=d}if(h!==e){if(null!==h&&e<h)for(b=h;b>e;b--)g=m[b],g.rendered&&g.sleep();this.mx=e}};m.selected=function(){return this.r};m.thead=function(){return this.w.cells[0]};m.tbody=function(){return this.w.cells[1]};m.tr=function(a){return(a=this.rows[a])?a.cells():[]};m.td=function(a,b){return this.tr(a)[b]};m.next=function(a,b,d){null==d&&(d=this.r);for(var e,c=this.rows,f=d,g=c.length;d!==(f+=a);)if(0<=f&&g>f){if(e=c[f],e.page)break}else if(b&&g)f=1===a?-1:g,b=!1;else{f= null;break}return f};m.selectNext=function(a,b,d){a=this.next(a,b);null!=a&&this.r!==a&&this.select(a,d);return this};m.deselect=function(a){var b=this.r;null!=b&&(this.r=null,h(this.tr(b)).removeClass("selected"),this.w.fire("wgRowDeselect",[b,a]));return this};m.select=function(a,b){var d=this.rows[a],e=d&&d.page;if(!e)return this.deselect(!1),l("Row is filtered out"),this;this.deselect(!0);var c,f=this.w.cells[1];e.rendered||(c=e.top(),f.scrollY(c),this.redrawDirty()&&this.redraw());if(!d.rendered)return e.rendered|| l("Failed to render page"),l("Row ["+a+"] not rendered"),this;e=d.cells();h(e).addClass("selected");this.r=a;b||(c=f.scrollY(),h(this.root).focus(),c!==f.scrollY()&&f.scrollY(c));f.scrollTo(e[0],!0);this.w.fire("wgRowSelect",[a,d.data()]);return this};m.unfilter=function(){this.f&&(this.f=null,this.clear().render());return this};m.filter=function(a){this.f=a;return this.clear().render()};m=null;m=u.prototype;m.render=function(a){var b,d=[],e=this._,c=this.d,f=this.length,g=this.i;if(e){for(;0!==f--;)d[f]= b=e.cloneNode(!1),b.textContent=c[f]||"\u00a0",b.$r=g,a[f].appendChild(b);this._=null;this.c=d}else for(d=this.c;0!==f--;)a[f].appendChild(d[f]);this.rendered=!0;return this};m.cells=function(){return this.c||[]};m.data=function(){return this.d||[]};m.destroy=function(){this.page=null;this.rendered=!1};m=null;m=s.prototype;m.size=function(){return this.rows.length};m.insert=function(a){var d=this.h,e=b("wg-dead");e.style.height=String(d)+"px";a.appendChild(e);return this.dead=e};m.top=function(){return(this.rendered? this.live:this.dead).offsetTop};m.height=function(){var a=this.h;null==a&&(this.h=a=this.rendered?this.live.firstChild.offsetHeight:this.dead.offsetHight);a||l("row has zero height");return a};m.render=function(a){for(var b,d=-1,e=this.rows,c=e.length,f=this.dead,g=this.live,k=g.childNodes;++d<c;)b=e[d],b.rendered||b.render(k);c=a.length;for(d=0;d<c;d++)k[d].style.width=a[d];f.parentNode.replaceChild(g,f);this.rendered=!0;this.h=null;return this};m.sleep=function(){var a=this.height(),b=this.live, d=this.dead;d.style.height=String(a)+"px";b.parentNode.replaceChild(d,b);this.rendered=!1;this.h=a;return this};m.sleepH=function(a){a*=this.rows.length;var b=this.dead;b&&(b.style.height=String(a)+"px");this.rendered||(this.h=a);return this};m.widths=function(a){for(var b=this.live.childNodes,d=a.length;0!==d--;)b[d].style.width=a[d];return this};m.destroy=function(){var a=this.rendered?this.live:this.dead,b=this.rows,d=b.length;for(a.parentNode.removeChild(a);0!==d--;)b[d].destroy()};m=null;return f}({}, q,y));n.register("$33",function(f,c,q){function l(a,b){var c=a.id,f=c&&A[c],g=f&&f.parent();if(!f||!g)return null;var v=g.dir===p,c=v?"X":"Y",k="page"+c,v=v?d:e,h=v(g.el),c=b["offset"+c],m=g.el,u=m.className;null==c&&(c=b[k]-v(a));c&&(h+=c);m.className=u+" is-resizing";return{done:function(){m.className=u},move:function(a){g.resize(a[k]-h,f);return!0}}}function b(b,d){function e(){h(q).off("mousemove",c);B&&(B.done(),B=null);return!0}function c(a){B?B.move(a):e();return!0}if(B)return!0;B=l(b.target, b);if(!B)return!0;h(q).one("mouseup",e).on("mousemove",c);return a(b)}function g(a,b){var d=b.type;"touchmove"===d?B&&B.move(b):"touchstart"===d?B=l(a.target,b):"touchend"===d&&B&&(B.done(),B=null)}function a(a){a.stopPropagation();a.preventDefault();return!1}function d(a,b){b||(b=q.body);for(var d=a.offsetLeft||0;(a=a.offsetParent)&&a!==b;)d+=a.offsetLeft||0;return d}function e(a,b){b||(b=q.body);for(var d=a.offsetTop||0;(a=a.offsetParent)&&a!==b;)d+=a.offsetTop||0;return d}function k(a){var b=r; b&&b.redraw();a&&a.redraw();return r=a}function u(a,b){var d=h(b).on("editFocus",function(){d.trigger("wgFocus",[k(a)])}).on("editBlur",function(){d.trigger("wgBlur",[k(null)])})}function s(a){var b=a.id,d=a.className;this.id=b;this.el=a;this.pos=this.index=0;this.css=[d||"wg-root","wg-cell"];this._cn=d;A[b]=this;this.clear()}var m=n.require("$17","html.js"),p=1,A={},r,B=!1;f.init=function(a){var d=new s(a);d.redraw();n.require("$37","touch.js").ok(function(b){b.dragger(a,g)});h(a).mousedown(b);return d}; c=s.prototype;c.fire=function(a,b){var d=h.Event(a);d.cell=this;h(this.el).trigger(d,b);return this};c.each=function(a){for(var b=-1,d=this.cells,e=d.length;++b<e;)a(d[b],b);return this};c.on=function(){return this.$("on",arguments)};c.off=function(){return this.$("off",arguments)};c.find=function(a){return h(this.el).find(a)};c.$=function(a,b){h.fn[a].apply(h(this.el),b);return this};c.parent=function(){return this.pid&&A[this.pid]};c.splitx=function(){return this._split(p,arguments)};c.splity=function(){return this._split(2, arguments)};c._split=function(a,b){(this.length||this.field)&&this.clear();for(var d=-1,e,c=b.length,f=1/c,g=0;++d<c;){e=m.el();this.body.appendChild(e);for(var k=e,h=b[d],u=h,l=1;A[h];)h=u+"-"+ ++l;k.id=h;e=new s(e);e.index=d;e.pid=this.id;e.pos=g;g+=f;this.cells.push(e);this.length++}this.dir=a;this.redraw();return this.cells};c.destroy=function(){this.clear();delete A[this.id];var a=this.el;a.innerHTML="";a.className=this._cn||"";h(a).off();return this};c.exists=function(){return this===A[this.id]}; c.clear=function(){for(var a=this.el,b=this.cells,d=this.field,e=this.body,c=this.nav,f=this.length||0;0!==f--;)delete A[b[f].destroy().id];this.cells=[];this.length=0;c&&(a.removeChild(c),this.nav=null);e&&(d&&(m.ie()&&h(e).triggerHandler("blur"),d.destroy(),this.field=null),this.table&&(this.table=null),a.removeChild(e));this.body=a.appendChild(m.el("","wg-body"));this._h=null;return this};c.resize=function(a,b){if(!b&&(b=this.cells[1],!b))return;var d=b.index,e=this.cells;this.parent();var c=h(this.el)[this.dir=== p?"width":"height"](),f=e[d+1],d=e[d-1];pad=(b.body||b.el.firstChild).offsetTop||0;max=(f?f.pos*c:c)-pad;min=d?d.pos*c:0;b.pos=Math.min(max,Math.max(min,a))/c;this.redraw();return this};c.distribute=function(a){for(var b,d=0,e=this.cells,c=a.length;d<c;)b=a[d],e[++d].pos=Math.max(0,Math.min(1,b));this.redraw();return this};c.distribution=function(){for(var a=[],b=0,d=this.cells,e=d.length-1;b<e;)a[b]=d[++b].pos;return a};c.restyle=function(){var a=this.css.concat();0===this.index?a.push("first"): a.push("not-first");this.dir&&(a.push("wg-split"),2===this.dir?a.push("wg-split-y"):a.push("wg-split-x"));this.t&&a.push("has-title");this.nav&&a.push("has-nav");this.field&&(a.push("is-field"),this.field.editable()?a.push("is-editable"):a.push("is-readonly"));a=a.join(" ");a!==this._css&&(this._css=a,this.el.className=a);return this};c.redraw=function(a){this.restyle();var b=this.el,d=this.body,e=this.field;if(d){var c=b.clientHeight||0,f=d.offsetTop||0,c=f>c?0:c-f;this._h!==c&&(this._h=c,d.style.height= String(c)+"px",e&&e.redraw(a))}for(var d=this.length,f=1,g=this.nav,k=2===this.dir?"height":"width";0!==d--;)e=this.cells[d],g?c=1:(e.fixed&&(e.pos=e.fixed/h(b)[k]()),c=f-e.pos,f=e.pos),e.el.style[k]=String(100*c)+"%",e.redraw(a);return this};c.contents=function(a,b){var d=this.el,e=this.body;if(null==a)return e.innerHTML;this.length?this.clear():e&&(d.removeChild(e),e=null);e||(this.body=e=d.appendChild(m.el("",b||"wg-content")),this._h=null,(d=this.lang)&&this._locale(d,this.rtl,!0));"string"=== typeof a?h(e)._html(a):a&&this.append(a);this.redraw();return this};c.textarea=function(a,b){var d=this.field;if(d){var e=d.editable();d.reload(a,b);e!==b&&this.restyle()}else this.length&&this.clear(),e=m.el("textarea"),e.setAttribute("wrap","virtual"),e.value=a,this.contents(e),d=n.require("$38","field.js")._new(e)[b?"enable":"disable"](),u(this,e),this.field=d,this.restyle();this.lang||this.locale("en");return d};c.locale=function(a){a=n.require("$6","locale.js").cast(a);return this._locale(String(a), a.isRTL())};c._locale=function(a,b,d){var e=this.body;if(d||a!==this.lang)this.lang=a,e&&e.setAttribute("lang",a);if(d||b!==this.rtl)this.rtl=b,e&&e.setAttribute("dir",b?"RTL":"LTR");return this};c.editable=function(){var a=this.field;if(!a||!a.editable())for(var b=-1,d=this.length;++b<d&&!(a=this.cells[b].editable()););return a};c.eachTextarea=function(a){var b=this.field;b?a(b):this.each(function(b){b.eachTextarea(a)});return this};c.append=function(a){a&&(a.nodeType?m.init(this.body.appendChild(a)): m.init(h(a).appendTo(this.body)));return this};c.prepend=function(a){var b=this.body;if(a.nodeType){var d=b.firstChild;m.init(d?b.insertBefore(a,d):b.appendChild(a))}else m.init(h(a).prependTo(b));return this};c.before=function(a){var b=this.body;a.nodeType?m.init(this.el.insertBefore(a,b)):m.init(h(a).insertBefore(b));return this};c.header=function(a,b){if(null==a&&null==b)return this.el.getElementsByTagName("header")[0];this.t=m.txt(a||"");this.el.insertBefore(m.el("header",b),this.body).appendChild(this.t); this.redraw();return this};c.title=function(a){var b=this.t;if(b)return b.nodeValue=a||"",b;this.header(a);return this.t};c.titled=function(){var a=this.t;return a&&a.nodeValue};c.bodyY=function(){return e(this.body,this.el)};c.scrollY=function(a){if(T===a)return this.body.scrollTop;this.body.scrollTop=a};c.tabulate=function(a){return this.table=n.require("$39","wgtable.js").create(this).init(a)};c.lock=function(){this.body.className+=" locked";return this};c.scrollTo=function(a,b){var d,c=this.body; d=c.scrollTop;var f=e(a,c);if(d>f)d=f;else{var g=c.clientHeight,f=f+h(a).outerHeight();if(g+d<f)d=f-g;else return}b?c.scrollTop=d:h(c).stop(!0).animate({scrollTop:d},250)};c.navigize=function(b,d){function e(a){var b=f[a],d=u[a],c=h(b.el).show();d.addClass("active");k=a;l.data("idx",a);b.fire("wgTabSelect",[a]);return c}var c=this,f=c.cells,g=c.nav,k,u=[];g&&c.el.removeChild(g);var g=c.nav=c.el.insertBefore(m.el("nav","wg-tabs"),c.body),l=h(g).on("click",function(b){var d=h(b.target).data("idx"); if(null==d)return!0;if(null!=k){var g=u[k];h(f[k].el).hide();g.removeClass("active")}e(d);c.redraw();return a(b)});null==d&&(d=l.data("idx")||0);c.each(function(a,d){u[d]=h('<a href="#'+a.id+'"></a>').data("idx",d).text(b[d]).appendTo(l);a.pos=0;h(a.el).hide()});e(f[d]?d:0);c.lock();c.redraw();return c};c.navigated=function(){var a=this.nav;if(a)return h(a).data("idx")};c=null;return f}({},q,y));n.register("$24",function(f,c,h){function l(b){this.reIndex([]);if(b)for(var c in b)this.add(c,b[c])}f.init= function(b){return new l(b)};c=l.prototype;c.reIndex=function(b){for(var c={},a=-1,d=b.length;++a<d;)c[b[a]]=a;this.keys=b;this.length=a;this.ords=c};c.key=function(b,c){if(null==c)return this.keys[b];var a=this.keys[b],d=this.ords[c];if(c!==a){if(null!=d)throw Error("Clash with item at ["+d+"]");this.keys[b]=c;delete this.ords[a];this.ords[c]=b}return b};c.indexOf=function(b){b=this.ords[b];return null==b?-1:b};c.add=function(b,c){var a=this.ords[b];null==a&&(this.keys[this.length]=b,a=this.ords[b]= this.length++);this[a]=c;return a};c.get=function(b){return this[this.ords[b]]};c.has=function(b){return null!=this.ords[b]};c.del=function(b){this.cut(this.ords[b],1)};c.cut=function(b,c){c=c||1;var a=[].splice.call(this,b,c);this.keys.splice(b,c);this.reIndex(this.keys);return a};c.each=function(b){for(var c=-1,a=this.keys,d=this.length;++c<d;)b(a[c],this[c],c);return this};c.sort=function(b){for(var c=-1,a=this.length,d,e=this.keys,f=this.ords,h=[];++c<a;)h[c]=[this[c],e[c]];h.sort(function(a, d){return b(a[0],d[0])});for(c=0;c<a;c++)d=h[c],this[c]=d[0],d=d[1],e[c]=d,f[d]=c;return this};c=null;return f}({},q,y));n.register("$23",function(f,c,q){function l(a){var b=[];a&&(a.saved()||b.push("po-unsaved"),a.fuzzy()?b.push("po-fuzzy"):a.flagged()&&(b.push("po-flagged"),b.push("po-flag-"+a.flags().join(" po-flag-"))),a.translation()||b.push("po-empty"),a.comment()&&b.push("po-comment"));return b.join(" ")}function b(a,b,d){b=h(a.title(b).parentNode);var c=b.find("span.lang");d?(d=n.require("$6", "locale.js").cast(d),c.length||(c=h("<span></span>").prependTo(b)),c.attr("lang",d.lang).attr("class",d.getIcon()||"lang region region-"+(d.region||"zz").toLowerCase())):(c.remove(),d="en");a.locale(d);return b}function g(){this.dirty=0}var a="poUpdate",d="changing",e="changed",k=0,u=1,s=2,m=3,p=4,A=5,r=/^\s+/,B,t,y=n.require("$3","string.js").sprintf,z=n.require("$17","html.js");f.extend=function(a){return a.prototype=new g};f.localise=function(a){t=a;return f};var C=function(){var a=q.createElement("p"); return function(b){a.innerHTML=b;return a.textContent}}(),w=g.prototype=n.require("$32","abstract.js").init(["getListColumns","getListHeadings","getListEntry"],["editable","t"]);w.init=function(){this.localise();this.editable={source:!0,target:!0};this.mode="";this.html=!1;return this};w.localise=function(a){a||(a=t||n.require("$1","t.js").init());var b=[];b[k]=a._x("Source text","Editor")+":";b[m]=a._x("%s translation","Editor")+":";b[p]=a._x("Context","Editor")+":";b[A]=a._x("Comments","Editor")+ ":";b[u]=a._x("Single","Editor")+":";b[s]=a._x("Plural","Editor")+":";this.labels=b;this.t=a;return this};w.setRootCell=function(a){function b(a){d.redraw(!0,a);return!0}var d=n.require("$33","wingrid.js").init(a);h(c).on("resize",b);this.redraw=b;h(a).on("wgFocus wgBlur",function(a,b){B=b});this.destroy=function(){d.destroy();h(c).off("resize",b)};this.rootDiv=a;return d};g.prototype.$=function(){return h(this.rootDiv)};w.on=function(a,b){return h(this.rootDiv).on(a,b)};w.setListCell=function(a){var b= this;b.listCell=a;a.on("wgRowSelect",function(a,d){b.loadMessage(b.po.row(d));return!0}).on("wgRowDeselect",function(a,d,c){c||b.loadNothing();return!0})};w.setSourceCell=function(a){this.sourceCell=a;var b=a.find("p.notes");b.length||(b=h('<p class="notes"></p>').insertAfter(a.header()).hide());this.notesPara=b};w.setTargetCell=function(a){this.targetCell=a};w.next=function(a,b,d){for(var c=this.listTable,e=c.selected(),f=e,g,k=this.po;null!=(e=c.next(a,d,e));){if(f===e){e=null;break}if(b&&(g=k.row(e), g.translated(0)))continue;break}null!=e&&c.select(e,!0);return e};w.current=function(a){var b=this.active;if("undefined"===typeof a)return b;a?a.is(b)?this.pasteMessage(a):this.loadMessage(a):this.unloadActive();return this};w.getTargetEditable=function(){return this.editable.target&&this.targetCell&&this.targetCell.editable()};w.getSourceEditable=function(){return this.editable.source&&this.sourceCell&&this.sourceCell.editable()};w.getContextEditable=function(){return this.editable.context&&this.contextCell&& this.contextCell.editable()};w.getFirstEditable=function(){return this.getTargetEditable()||this.getSourceEditable()||this.getContextEditable()};w.searchable=function(a){a&&(this.dict=a,this.po&&this.rebuildSearch());return this.dict&&!0};w.rebuildSearch=function(){var a=-1,b=this.po.rows,d=b.length,c=this.dict;for(c.clear();++a<d;)c.add(a,b[a].toText());this.lastSearch="";this.lastFound=d};w.filtered=function(){return this.lastSearch||""};w.filter=function(a,b){var d,c=this.listTable,e=this.lastFound, f=this.lastSearch;if(a){if(f===a)return e||0;if(f&&!e&&0===a.indexOf(f))return 0;d=this.dict.find(a)}f=this.lastSearch=a;e=this.lastFound=d?d.length:this.po.length;d?c.filter(d):c.unfilter();b||this.fire("poFilter",[f,e]);return e};w.unsave=function(a,b){var d=!1;if(a=a||self.active){if(d=a.saved(b))this.dirty++,a.unsave(b),this.fire("poUnsaved",[a,b]);this.markUnsaved(a)}return d};w.markUnsaved=function(a){var b=this.po.indexOf(a),b=this.listTable.tr(b),d=b[0].className;changedStyle=d.replace(/(?:^| +)po-[a-z]+/g, "")+" "+l(a);changedStyle!==d&&h(b).attr("class",changedStyle)};w.save=function(a){var b=this.po;if(this.dirty||a)b.each(function(a,b){b.save()}),this.listCell.find("div.po-unsaved").removeClass("po-unsaved"),this.dirty=0,this.fire("poSave");return b};w.fire=function(a,b){var d=this.on;if(d&&d[a]&&(d=d[a].apply(this,b||[]),!1===d))return!1;d=h.Event(a);h(this.rootDiv).trigger(d,b);return!d.isDefaultPrevented()};w.reload=function(){var a=this,b,d=a.listCell,c=a.listTable,e=a.po,f=e&&e.locale(),g=f&& f.isRTL(),k=e&&e.length||0;if(e&&e.row)return a.lastSearch&&(a.lastSearch="",a.lastFound=k,a.fire("poFilter",[a.lastSearch,a.lastFound])),c&&(b=c.thead().distribution()),c=a.listTable=d.tabulate({length:k,getRow:function(b){return a.getListEntry(e.row(b))},getCss:function(b){return a.getListEntry(e.row(b))},eachCol:function(b){for(var d=-1,e=a.getListHeadings(),c=e.length;++d<c;)b(d,e[d])},eachRow:function(b){var d=0;e.each(function(e,c){b(d++,a.getListEntry(c),l(c))})}}),b&&c.thead().distribute(b), c.tbody().$(g?"addClass":"removeClass",["is-rtl"]),a.targetLocale=f,a.fire("poLoad"),!!e.length;d&&d.clear().header("Error").contents("Invalid messages list")};w.load=function(a,b){this.po=a;this.dict&&this.rebuildSearch();this.reload()&&(-1!==b?this.listTable.select(b||0):this.active&&this.unloadActive())};w.pasteMessage=function(a){var b,d=0;if(b=this.sourceCell)b.eachTextarea(function(b){b.val(a.source(null,d++))}),this.updateListCell(a,"source");(b=this.contextCell)&&b.eachTextarea(function(b){b.val(a.context())}); if(b=this.targetCell)d=0,b.eachTextarea(function(b){b.val(a.translation(d++))}),this.updateListCell(a,"target");return this};w.loadMessage=function(c){function f(g){var h,m=g,l=g.id,m=!1;h=K[k];g.off();N&&(P?(P=z.h(P,!0),N.html(P).show(),z.init(N),m=!0):N.text()&&(m=!0,N.text("").hide()));g.titled()!==h&&b(g,h,r.sourceLocale||"en");m&&g.clear();Q?(h=g.splity(l+"-singular",l+"-plural"),m=h[0],h=h[1],m.header(K[u]).textarea(Z,R).setMode(t).setInvs(C),h.header(K[s]).textarea(Q,R).setMode(t).setInvs(C), g.lock()):g.textarea(Z,R).setMode(t).setInvs(C);R&&g.on(d,function(a,b){Q&&a.target.name===l+"-plural"?c.plural(b):(c.source(b),r.updateListCell(c,"source"));r.unsave(c,M)}).on(e,function(b){Q&&b.target.name===l+"-plural"||r.po.reIndex(c);r.dict&&r.rebuildSearch();r.fire(a,[c])})}function g(f,k,h){f.off();var u=k.isKnown()&&k.label||"Target",u=y(K[m],u);f.titled()!==u&&b(f,u,k);if(c.pluralized()){var l=[],p=k.plurals||["One","Other"],s=n.require("$24","collection.js").init();for(c.each(function(a, b,d){if(d||p[a])l.push(p[a]||"Form "+a),s.add("plural-"+a,d)});(u=l.length)<k.nplurals;)l.push(p[u]||"Form "+s.length),s.add("plural-"+u,c.translation(u));children=f.splitx.apply(f,s.keys);f.each(function(a,b){var d=L&&!c.disabled(b);a.textarea(s[b],d).setMode(t).setInvs(C)});f.navigize(l,h||null).on("wgTabSelect",function(a,b){var d=L&&a.cell.editable();d&&d.focus();h=b;r.fire("poTab",[b])})}else h=0,L=L&&!c.disabled(0),f.textarea(c.translation(),L).setMode(t).setInvs(C);L&&f.on(d,function(a,b,d){c.translate(b, h);0===h&&r.updateListCell(c,"target");c.fuzzy(h)?r.fuzzy(!1,c,h):r.unsave(c,h);""===b?r.fire("poEmpty",[!0,c,h]):""===d&&r.fire("poEmpty",[!1,c,h])}).on(e,function(b){r.dict&&r.rebuildSearch();r.fire(a,[c])})}function l(f){f.off();b(f,K[p]);f.textarea(c.context(),!0).setMode(t).setInvs(C);T&&f.on(d,function(a,b){c.context(b);r.updateListCell(c,"source");r.unsave(c,M)}).on(e,function(){r.po.reIndex(c);r.dict&&r.rebuildSearch();r.fire(a,[c])})}function q(a){var e=K[A];a.titled()!==e&&b(a,e);a.off().on(d, function(a,b){c.comment(b);r.fire("poComment",[c,b]);r.unsave(c,M)}).textarea(c.comment(),!0)}var r=this,t=r.mode,w=c.isHTML(),C=r.inv||!1,I=this.fmt||null,F=c.format()||null,S=c.is(r.active),M=0,W=r.sourceCell,V=r.targetCell,X=r.contextCell,Y=r.commentCell,N=r.notesPara,L=r.editable.target,R=r.editable.source,T=r.editable.context,Z=c.source()||"",Q=c.plural()||"",P=c.notes(),O=B,$=r.targetLocale,K=r.labels;r.html!==w&&(r.html=w,"code"!==r.mode&&(t=w?"html":"",r.setMode(t)));r.active=c;W&&f(W);X&& l(X);V&&$&&(M=V.navigated()||0,g(V,$,M));Y&&q(Y);O&&(O.exists()||(O=O.parent()),(w=O.editable())&&w.focus());I!==F&&(w=h(r.rootDiv),F&&w.addClass(F+"-format"),I&&w.removeClass(I+"-format"),this.fmt=F);S||r.fire("poSelected",[c])};w.unloadActive=function(){var a;(a=this.notesPara)&&a.text("").hide();(a=this.sourceCell)&&a.off().clear();(a=this.contextCell)&&a.off().clear();(a=this.targetCell)&&a.off().clear();(a=this.commentCell)&&a.off();this.active&&(this.fire("poDeselected",[this.active]),this.active= null);return this};w.loadNothing=function(){var a,b=this.t,d=this.mode||"",c=this.inv||!1;this.unloadActive();(a=this.commentCell)&&a.textarea("",!1);if(a=this.sourceCell)a.textarea("",!1).setMode(d).setMode(d).setInvs(c),a.title(b._x("Source text not loaded","Editor")+":");if(a=this.contextCell)a.textarea("",!1).setMode(d).setMode(d).setInvs(c),a.title(b._x("Context not loaded","Editor")+":");if(a=this.targetCell)a.textarea("",!1).setMode(d).setMode(d).setInvs(c),a.title(b._x("Translation not loaded", "Editor")+":");this.fire("poSelected",[null])};w.updateListCell=function(a,b){var d=this.getListColumns()[b],c=this.getListEntry(a)[d||0],e=this.po.indexOf(a);if(d=this.listTable.td(e,d))d.textContent=c};w.cellText=function(a){if(-1!==a.indexOf("<")||-1!==a.indexOf("&"))a=C(a);return a.replace(r,"")||"\u00a0"};w.fuzzy=function(b,d,c){if(!d){d=this.active;if(!d)return null;null==c&&(c=this.targetCell&&this.targetCell.navigated()||0)}var e=d.fuzzy(c);null==b||e==b||b&&!d.translated(c)||!this.fire("poFuzzy", [d,b,c])||(d.fuzzy(c,b),this.fire(a,[d])&&this.unsave(d,c));return e};w.add=function(b,d){var c,e=this.po.get(b,d);e?c=this.po.indexOf(e):(c=this.po.length,e=this.po.add(b,d),this.load(this.po,-1),this.fire("poAdd",[e]),this.fire(a,[e]));this.lastSearch&&this.filter("");this.listTable.select(c);return e};w.del=function(b){if(b=b||this.active){var d=this.lastSearch,c=this.po.del(b);null!=c&&(this.unsave(b),this.fire("poDel",[b]),this.fire(a,[b]),this.reload(),this.dict&&this.rebuildSearch(),this.active&& this.active.equals(b)&&this.unloadActive(),this.po.length&&(d&&this.filter(d),this.active||(c=Math.min(c,this.po.length-1),this.listTable.select(c))))}};w.setMono=function(a){return this.setMode(a?"code":this.html?"html":"")};w.setMode=function(a){this.mode!==a&&(this.mode=a,this.callTextareas(function(b){b.setMode(a)}));return this};w.getMono=function(){return"code"===this.mode};w.setInvs=function(a){(this.inv||!1)!==a&&(this.inv=a,this.callTextareas(function(b){b.setInvs(a)}),this.fire("poInvs", [a]));return this};w.getInvs=function(){return this.inv||!1};w.callTextareas=function(a){var b=this.targetCell;b&&b.eachTextarea(a);(b=this.contextCell)&&b.eachTextarea(a);(b=this.sourceCell)&&b.eachTextarea(a);return this};w=null;return f}({},q,y));n.register("$12",function(f,c,h){function l(){this.init()._validate();this.sourceLocale={lang:"en",label:"English",plurals:["One","Other"]}}c=n.require("$23","base.js");f.init=function(b){var c=new l;b=c.setRootCell(b);var a=b.splity("po-list","po-edit"), d=a[0],e=a[1],a=e.splitx("po-trans","po-comment"),f=a[0],h=a[1].header("Loading.."),a=f.splity("po-source","po-target"),f=a[0].header("Loading.."),a=a[1].header("Loading..");b.distribute([0.34]);e.distribute([0.8]);c.setListCell(d);c.setSourceCell(f);c.setTargetCell(a);c.commentCell=h;c.editable.source=!1;return c};c=l.prototype=c.extend(l);c.getListHeadings=function(){var b=this.t||{_x:function(b){return b}};return[b._x("Source text","Editor"),b._x("Translation","Editor")]};c.getListColumns=function(){return{source:0, target:1}};c.getListEntry=function(b){if(!b)return["",""];var c=this.cellText,a=[c(b.id||b.source()||""),c(b.translation()||"")];if(b=b.context())a[0]+=" [ "+c(b)+" ]";return a};c.stats=function(){var b=this.po.length,c=0,a=0,d=0;this.po.each(function(b,f){f.translation()?f.fuzzy()?d++:c++:a++});return{t:b,p:String(c?Math.round(100*(c/b)):0)+"%",f:d,u:a}};c.unlock=function(){this._unlocked||(this._unlocked=this.targetLocale,delete this.targetLocale,this.po&&this.po.unlock(),this.editable={source:!0, context:!0,target:!1},this.contextCell=this.targetCell,delete this.targetCell,this.fire("poLock",[!1]),this.active&&this.loadMessage(this.active))};c.lock=function(){var b;this._unlocked&&(b=this.targetLocale=this._unlocked,delete this._unlocked,this.po&&this.po.lock(b),this.editable={source:!1,context:!1,target:!0},this.targetCell=this.contextCell,delete this.contextCell,this.fire("poLock",[!0,b]),this.active&&this.loadMessage(this.active))};c.locked=function(){return!this._unlocked};return f}({}, q,y));n.register("$13",function(f,c,n){var l={copy:66,clear:75,save:83,fuzzy:85,next:40,prev:38,enter:13,invis:73},b={38:!0,40:!0,73:!0},g={66:function(a,b){var c=b.current();c&&(c.normalize(),b.pasteMessage(c))},75:function(a,b){var c=b.current();c&&(c.untranslate(),b.pasteMessage(c))},85:function(a,b){b.fuzzy(!b.fuzzy())},13:function(a,b){b.getFirstEditable()&&b.next(1,!0,!0)},40:function(a,b){var c=a.shiftKey;b.next(1,c,c)},38:function(a,b){var c=a.shiftKey;b.next(-1,c,c)},73:function(a,b){if(!a.shiftKey)return!1; b.setInvs(!b.getInvs())}};f.init=function(a,d){function e(d){if(d.isDefaultPrevented()||!d.metaKey&&!d.ctrlKey)return!0;var c=d.which;if(!f[c])return!0;var e=g[c];if(!e)throw Error("command undefined #"+c);if(d.altKey||d.shiftKey&&!b[c]||!1===e(d,a))return!0;d.stopPropagation();d.preventDefault();return!1}var f={};h(d||c).on("keydown",e);return{add:function(a,b){g[l[a]]=b;return this},enable:function(){var a,b;for(b in arguments)a=l[arguments[b]],f[a]=!0;return this},disable:function(){h(d||c).off("keydown", e);a=d=f=null}}};return f}({},q,y));n.register("$25",function(f,c,h){function l(b,c){var a=RegExp("^.{0,"+(b-1)+"}["+c+"]"),d=RegExp("^[^"+c+"]+");return function(c,f){for(var g=c.length,h;g>b;){h=a.exec(c)||d.exec(c);if(null==h)break;h=h[0];f.push(h);h=h.length;g-=h;c=c.substr(h)}0!==g&&f.push(c);return f}}f.create=function(b){function c(a){return n[a]||"\\"+a}var a,d,e=/(?:\r\n|[\r\n\v\f\u2028\u2029])/g,f=/[ \r\n]+/g,h=/[\t\v\f\x07\x08\\\"]/g,n={"\t":"\\t","\v":"\\v","\f":"\\f","\u0007":"\\a","\b":"\\b"}; null==b&&(b=79);0!==b&&(a=l(b-3," "),d=l(b-2,"-\u2013 \\.,:;\\?!\\)\\]\\}\\>"));return{pair:function(a,f){if(!f)return a+' ""';f=f.replace(h,c);var k=0;f=f.replace(e,function(){k++;return"\\n\n"});if(!(k||b&&b<f.length+a.length+3))return a+' "'+f+'"';var l=[a+' "'],n=f.split("\n");if(d)for(var s=-1,q=n.length;++s<q;)d(n[s],l);else l=l.concat(n);return l.join('"\n"')+'"'},prefix:function(a,b){var d=a.split(e);return b+d.join("\n"+b)},refs:function(b){b=b.replace(f," ",b);a&&(b=a(b,[]).join("\n#: ")); return"#: "+b}}};return f}({},q,y));n.register("$26",function(f,c,h){function l(){}f.extend=function(b){return b.prototype=new l};c=l.prototype=n.require("$32","abstract.js").init(["add","load"]);c.row=function(b){return this.rows[b]};c.lock=function(b){return this.locale(b||{lang:"zxx",label:"Unknown",nplurals:1,pluraleq:"n!=1"})};c.unlock=function(){var b=this.loc;this.loc=null;return b};c.locale=function(b){var c=n.require("$6","locale.js");null==b?b=this.loc:this.loc=b=c.cast(b);return b};c.each= function(b){this.rows.each(b);return this};c.indexOf=function(b){"object"!==typeof b&&(b=this.get(b));if(!b)return-1;null==b.idx&&(b.idx=this.rows.indexOf(b.hash()));return b.idx};c.get=function(b){return this.rows&&this.rows.get(b)};c.del=function(b){b=this.indexOf(b);if(-1!==b){var c=this.rows.cut(b,1);if(c&&c.length)return this.length=this.rows.length,this.rows.each(function(a,b,c){b.idx=c}),b}};c.reIndex=function(b,c){var a=this.indexOf(b),d=b.hash(),e=this.rows.indexOf(d);return e===a?a:-1!== e?(c=(c||0)+1,b.source("Error, duplicate "+String(c)+": "+b.source()),this.reIndex(b,c)):this.rows.key(a,d)};c=null;return f}({},q,y));n.register("$27",function(f,c,h){function l(){this.id=this._id=this.ref=this.cmt=this.xcmt=""}f.extend=function(b){return b.prototype=new l};c=l.prototype;c.flag=function(b,c){var a=this.flg||(this.flg=[]);if(null!=c)a[c]=b;else for(var d=Math.max(a.length,this.src.length,this.msg.length);0!==d--;)a[d]=b;return this};c.flagged=function(b){var c=this.flg||[];if(null!= b)return c[b]||0;for(b=c.length;0!==b--;)if(c[b])return!0;return!1};c.flags=function(){for(var b,c={},a=[],d=this.flg||[],e=d.length;0!==e--;)b=d[e],c[b]||(c[b]=!0,a.push(b));return a};c.flaggedAs=function(b,c){var a=this.flg||[];if(null!=c)return b===a[c]||0;for(var d=a.length;0!==d--;)if(a[d]===b)return!0;return!1};c.fuzzy=function(b,c){var a=this.flaggedAs(4,b);null!=c&&this.flag(c?4:0,b);return a};c.source=function(b,c){if(null==b)return this.src[c||0]||"";this.src[c||0]=b;return this};c.plural= function(b,c){if(null==b)return this.src[c||1]||"";this.src[c||1]=b||"";return this};c.each=function(b){for(var c=-1,a=this.src,d=this.msg,e=Math.max(a.length,d.length);++c<e;)b(c,a[c],d[c]);return this};c.pluralized=function(){return 1<this.src.length||1<this.msg.length};c.translate=function(b,c){this.msg[c||0]=b||"";return this};c.untranslate=function(b){null!=b&&(this.msg[b]="");for(b=0;b<this.msg.length;b++)this.msg[b]="";return this};c.translation=function(b){return this.msg[b||0]||""};c.translated= function(b){if(null!=b)return!!this.translation(b);var c=this.msg.length;for(b=0;b<c;b++)if(!this.msg[b])return!1;return!0};c.comment=function(b){if(null==b)return this.cmt;this.cmt=b||"";return this};c.notes=function(b){if(null==b)return this.xcmt;this.xcmt=b||"";return this};c.refs=function(b){if(null==b)return this.ref;this.ref=b||"";return this};c.format=function(b){if(null==b)return this.fmt;this.fmt=b;return this};c.context=function(b){if(null==b)return this.ctx||"";this.ctx=b||"";return this}; c.toString=c.toText=function(){return this.src.concat(this.msg,[this.id,this.ctx]).join(" ")};c.weight=function(){var b=0;this.translation()||(b+=2);this.fuzzy()&&(b+=1);return b};c.equals=function(b){return this===b||this.hash()===b.hash()};c.hash=function(){return this.id};c.normalize=function(){for(var b=this.msg.length;0!==b--;)this.msg[b]=this.src[b]||""};c.disabled=function(b){return!!(this.lck||[])[b||0]};c.disable=function(b){(this.lck||(this.lck=[]))[b||0]=!0;return this};c.saved=function(b){var c= this.drt;if(!c)return!0;if(null!=b)return!c[b];for(b=c.length;0!==b--;)if(c[b])return!1;return!0};c.unsave=function(b){(this.drt||(this.drt=[]))[b||0]=!0;return this};c.save=function(b){var c=this.drt;null==b?this.drt=null:c[b]=!1;return this};c.is=function(b){return b&&(b===this||b.idx===this.idx)};c.isHTML=function(b){if(null==b)return this.htm||!1;this.htm=b};c=null;return f}({},q,y));n.register("$14",function(f,c,h){function l(a){return{"Project-Id-Version":"PACKAGE VERSION","Report-Msgid-Bugs-To":"", "POT-Creation-Date":a||"","PO-Revision-Date":a||"","Last-Translator":"","Language-Team":"",Language:"","Plural-Forms":"","MIME-Version":"1.0","Content-Type":"text/plain; charset=UTF-8","Content-Transfer-Encoding":"8bit"}}function b(a,b){var c=a||"";b&&(c+="\x00"+b);return c}function g(){return n.require("$24","collection.js").init()}function a(a){this.locale(a);this.length=0;this.rows=g();this.head=l(this.now())}function d(a,b){this.src=[a||""];this.msg=[b||""]}f.create=function(b){return new a(b)}; c=n.require("$26","messages.js").extend(a);c.now=function(){function a(b,c){for(var d=String(b);d.length<c;)d="0"+d;return d}var b=new Date,c=b.getUTCFullYear(),d=b.getUTCMonth()+1,f=b.getUTCDate(),g=b.getUTCHours(),b=b.getUTCMinutes();return a(c,4)+"-"+a(d,2)+"-"+a(f,2)+" "+a(g,2)+":"+a(b,2)+"+0000"};c.header=function(a,b){var c=this.head||(this.head={});if(null==b)return this.headers()[a]||"";c[a]=b||"";return this};c.headers=function(a){var b,c=this.now(),d=this.head||(this.head=l(c));if(null!= a){for(b in a)d[b]=a[b];return this}var f=this.locale();a={};for(b in d)a[b]=String(d[b]);f?(a.Language=String(f)||"zxx",a["Language-Team"]=f.label||a.Language,a["Plural-Forms"]="nplurals="+(f.nplurals||"2")+"; plural="+(f.pluraleq||"n!=1"),a["PO-Revision-Date"]=c):(a.Language="",a["Plural-Forms"]="nplurals=INTEGER; plural=EXPRESSION",a["POT-Creation-Date"]=c,a["PO-Revision-Date"]="YEAR-MO-DA HO:MI+ZONE");a["X-Generator"]="Loco - https://localise.biz/";return a};c.get=function(a,c){var d=b(a,c);return this.rows.get(d)}; c.add=function(a,b){a instanceof d||(a=new d(a));b&&a.context(b);var c=a.hash();if(this.rows.get(c))throw Error("Duplicate message at index "+this.indexOf(a));a.idx=this.rows.add(c,a);this.length=this.rows.length;return a};c.load=function(a){for(var b=-1,c,f,g,h,l,n,q=[],t=[],y=[],z=[];++b<a.length;)c=a[b],null==c.parent?(f=c.source||c.id,g=c.target||"",h=c.context,f||h?(l=new d(f,g),l._id=c._id,h&&l.context(h),c.flag&&l.flag(c.flag,0),c.comment&&l.comment(c.comment),c.notes&&l.notes(c.notes),c.refs&& l.refs(c.refs),null!==c.format&&l.format(c.format),c.message=l,l.translation()?l.fuzzy()?y.push(l):t.push(l):z.push(l)):0===b&&"object"===typeof g&&(this.head=g)):q.push(c);for(b=-1;++b<q.length;)try{c=q[b];f=c.source||c.id;l=a[c.parent]&&a[c.parent].message;if(!l)throw Error("parent missing for plural "+f);n=c.plural;1===n&&l.plural(f);c.flag&&l.flag(c.flag,n);l.translate(c.target||"",n);c.format&&!l.format()&&l.format(c.format)}catch(C){}return this._add(z,y,t)};c._add=function(a,b,c){c=[a,b,c]; for(i=0;3>i;i++)for(b=c[i],a=-1;++a<b.length;)try{this.add(b[a])}catch(d){}return this};c.merge=function(a){var b,c=a.header("POT-Creation-Date"),d=this.rows,f=[],h=[],l=[],n=[],q=[];a=a.rows;this.rows.each(function(b,c){null==a.get(b)&&q.push(c)});a.each(function(a,c){try{(b=d.get(a))?(b.ref=c.ref,b.fmt=c.fmt):(b=c,n.push(b)),b.translation()?b.fuzzy()?h.push(b):l.push(b):f.push(b)}catch(e){}});this.rows=g();this._add(f,h,l);c&&this.header("POT-Creation-Date",c);return{add:n,del:q}};c.toString=function(){var a, b=[],c=[],f=this.headers(),g=!this.loc,h=n.require("$25","format.js").create(void 0);for(a in f)c.push(a+": "+f[a]);c=new d("",c.join("\n"));g&&c.fuzzy(0,!0);b.push(c.toString());b.push("");this.rows.each(function(a,c){a&&(b.push(c.cat(h,g)),b.push(""))});return b.join("\n")};c=n.require("$27","message.js").extend(d);c.hash=function(){return b(this.source(),this.context())};c.source=function(a,b){if(null==a)return this.src[0];this.src[0]=a;null!=b&&this.plural(b);return this};c.toString=function(){return this.cat(n.require("$25", "format.js").create(void 0))};c.cat=function(a,b){var c,d=[],f;(f=this.cmt)&&d.push(a.prefix(f,"# "));(f=this.xcmt)&&d.push(a.prefix(f,"#. "));c=this.ref;if(f=this._id)c+=(c?" ":"")+"loco:"+f;c&&/\S/.test(c)&&d.push(a.refs(c));!b&&this.fuzzy()&&d.push("#, fuzzy");(f=this.fmt)?d.push("#, "+f+"-format"):null!=f&&d.push("#, no-c-format");(f=this.ctx)&&d.push(a.pair("msgctxt",f));d.push(a.pair("msgid",this.src[0]));if(null==this.src[1])d.push(a.pair("msgstr",b?"":this.msg[0]));else for(c=-1,d.push(a.pair("msgid_plural", this.src[1]));++c<this.msg.length;)d.push(a.pair("msgstr["+c+"]",b?"":this.msg[c]));return d.join("\n")};c.compare=function(a,b){var c=this.weight(),d=a.weight();if(c>d)return 1;if(c<d)return-1;if(b){c=this.hash().toLowerCase();d=a.hash().toLowerCase();if(c<d)return 1;if(c>d)return-1}return 0};c=c=null;return f}({},q,y));n.register("$15",function(f,c,n){f.init=function(f){function b(){D&&D.dialog("close");h(f).find('input[type="submit"]').attr("disabled",!1);h(r).addClass("jshide");q&&q(!0)}function g(){h(f).find('input[type="submit"]').attr("disabled", !0);q&&q(!1)}function a(a){var b,c;for(b in p)c=p[b],a[b]?a[b].value=c:h('<input type="hidden" />').attr("name",b).appendTo(a).val(c)}function d(a){a.preventDefault();a=h(a.target).serializeArray();m(a);t=!0;return!1}function e(a){a.preventDefault();D.dialog("close");return!1}function k(a){a.preventDefault();D.dialog("open");return!1}function n(c){p=c.authed&&c.creds;B=c.method;if(p)"direct"!==B&&(a(f),t&&c.success&&z.notices.success(c.success)),y=!0,b();else if(y=!1,c.reason)z.notices.info(c.reason); else if(c=c.prompt){var g;D||(h(r).find("button.button-small").click(k),D=h('<div id="loco-fs-creds"></div>').dialog({dialogClass:"request-filesystem-credentials-dialog loco-modal",minWidth:480,modal:!0,autoOpen:!1,closeOnEscape:!0}));g=D;g.html(c).find("form").submit(d);g.dialog("option","title",g.find("h2").remove().text());g.find("button.cancel-button").show().click(e);g.find('input[type="submit"]').addClass("button-primary");h(r).removeClass("jshide")}else z.notices.error("Server didn't return credentials, nor a prompt for credentials")} function s(){b()}function m(a){t=!1;a.path=C;a.auth=w;z.ajax.setNonce("fsConnect",v).post("fsConnect",a,n,s);return a}var p,q,r=f,B=null,t=!1,y=!1,z=c.locoScope,C=f.path.value,w=f.auth.value,v=f["loco-nonce"].value,D;f.connection_type?(p={},p.connection_type=f.connection_type.value,y=!0):C&&w&&(g(),m({}));return{applyCreds:function(b){if(b.nodeType)a(b);else{var c,d=p||{};for(c in d)b[c]=d[c]}return this},setForm:function(b){f=b;y||g();a(b);return this},connect:function(){var a=h(f).serializeArray(); C=a.path;w=a.auth;m(a);return this},listen:function(a){q=a;y&&a(!0);return this}}};return f}({},q,y));n.register("$16",function(f,c,q){function l(c,f,h,l){f="n"===h?g(f):a(f);l&&(f=d(f));return b([].sort,[f])(c)}function b(a,b){return function(c){a.apply(c,b);return c}}function g(a){return function(b,c){var d=b&&b[a]||0,f=c&&c[a]||0;return d===f?0:d>f?1:-1}}function a(a){return function(b,c){return(b&&b[a]||"").localeCompare(c&&c[a]||"")}}function d(a){return function(b,c){return-1*a(b,c)}}f.init= function(a){function b(a){var c=-1,d=a.length;for(h("tr",t).remove();++c<d;)t.appendChild(a[c].$)}function c(a){q=a?z.find(a,d):d.slice(0);y&&(a=f[y],q=l(q,y,a.type,a.desc));b(q)}var d=[],f=[],g=0,q,r,y,t=a.getElementsByTagName("tbody")[0],E=a.getElementsByTagName("thead")[0],z=n.require("$7","fulltext.js").init();E&&t&&(h("th",E).each(function(a,c){var e=c.getAttribute("data-sort-type");e&&(a=g,h(c).addClass("loco-sort").click(function(c){c.preventDefault();c=a;var e=f[c],g=e.type,n=!(e.desc=!e.desc); q=l(q||d.slice(0),c,g,n);b(q);r&&r.removeClass("loco-desc loco-asc");r=h(e.$).addClass(n?"loco-desc":"loco-asc").removeClass(n?"loco-asc":"loco-desc");y=c;return!1}),f[g]={$:c,type:e});c.hasAttribute("colspan")?g+=Number(c.getAttribute("colspan")):g++}),h("tr",t).each(function(a,b){var c,e,g,h=[],k={_:a,$:b},l=b.getElementsByTagName("td");for(e in f){c=l[e];(g=c.textContent.replace(/(^\s+|\s+$)/g,""))&&h.push(g);c.hasAttribute("data-sort-value")&&(g=c.getAttribute("data-sort-value"));switch(f[e].type){case "n":g= Number(g)}k[e]=g}d[a]=k;z.index(a,h)}),a=h('form.loco-filter input[type="text"]',a.parentNode),a.length&&(a=a[0],E=h(a.form),1<d.length?n.require("$8","LocoTextListener.js").listen(a,c):E.hide(),E.on("submit",function(a){a.preventDefault();return!1})))};return f}({},q,y));var F=q.locoScope||(q.locoScope={});q=q.locoConf||(q.locoConf={});y=n.require("$1","t.js").init();var S=q.wplang;n.require("$2","array.js");F.l10n=y;y.load(q.wpl10n);S&&y.pluraleq(S.pluraleq);F.string=n.require("$3","string.js"); F.notices=n.require("$4","notices.js").init(y);F.ajax=n.require("$5","ajax.js").init(q).localise(y);F.locale=n.require("$6","locale.js");F.fulltext=n.require("$7","fulltext.js");F.watchtext=n.require("$8","LocoTextListener.js").listen;F.selector=n.require("$9","LocoSelector.js").create;F.autocomp=n.require("$10","LocoAutoComplete.js").init;F.tooltip=n.require("$11","tooltip.js");F.po={ed:n.require("$12","poedit.js"),kbd:n.require("$13","hotkeys.js"),init:n.require("$14","po.js").create};F.fs=n.require("$15", "fsconn.js");h("#loco.wrap table.wp-list-table").each(function(f,c){n.require("$16","tables.js").init(c)})})(window,document,window.jQuery); poview.js 0000666 00000007530 15213303106 0006416 0 ustar 00 /** * Script for PO/POT source view screen */ !function( window, document, $ ){ var loco = window.locoScope, conf = window.locoConf, view = document.getElementById('loco-po'), $modal; // OK to show view now. mat have taken long to render $(view).removeClass('loading'); // resize function fits scrollable viewport, accounting for headroom and touching bottom of screen. var resize = function(){ function top( el, ancestor ){ var y = el.offsetTop||0; while( ( el = el.offsetParent ) && el !== ancestor ){ y += el.offsetTop||0; } return y; } var fixHeight, maxHeight = view.clientHeight - 2 ; return function(){ var topBanner = top( view, document.body ), winHeight = window.innerHeight, setHeight = winHeight - topBanner - 20 ; if( fixHeight !== setHeight ){ if( setHeight < maxHeight ){ view.style.height = String(setHeight)+'px'; } else { view.style.height = ''; } fixHeight = setHeight; } }; }(); resize(); $(window).resize( resize ); // enable file reference links to open modal to ajax service $('ol.msgcat').click( function(event){ var link = event.target; if( link.hasAttribute('href') ){ event.preventDefault(); getModal().html('<div class="loading"></div>').dialog('option','title','Loading..').off('dialogopen').dialog('open').on('dialogopen',onModalOpen); var postdata = $.extend( { ref:link.textContent, path:conf.popath }, conf.project||{} ); loco.ajax.post( 'fsReference', postdata, onRefSource, onRefError ); return false; } } ); // http://api.jqueryui.com/dialog/ function getModal(){ return $modal || ( $modal = $('<div id="loco-po-ref"></div>').dialog( { dialogClass : 'loco-modal', modal : true, autoOpen : false, closeOnEscape : true, resizable : false, height : 500 } ) ); } // when reference pulling fails (e.g. file not found, or line nonexistant) function onRefError( xhr, error, message ){ $error = $('<p></p>').text( message ); getModal().dialog('close').html('').dialog('option','title','Error').append($error).dialog('open'); } // display reference source when received via ajax response function onRefSource( result ){ var code = result && result.code; if( ! code ){ return; } var i = -1, length = code.length, $ol = $('<ol></ol>').attr('class',result.type); while( ++i < length ){ $('<li></li>').html( code[i] ).appendTo($ol); } // Highlight referenced line $ol.find('li').eq( result.line - 1 ).attr('class','highlighted'); // TODO enable highlight toggling of other lines via click/drag etc.. getModal().dialog('close').html('').dialog('option','title', result.path+':'+result.line).append($ol).dialog('open'); } // scroll to first highlighted line of code once modal open function onModalOpen( event, ui ){ var div = event.target, line = $(div).find('li.highlighted')[0], yAbs = line.offsetTop, // <- position of line relative to container yVis = Math.floor( div.clientHeight / 2 ), // <- target position of line relative to view port yAdj = Math.max( 0, yAbs - yVis ) // scroll required to move line to visual position ; div.scrollTop = yAdj; } }( window, document, jQuery ); setup.js 0000666 00000006511 15213303106 0006243 0 ustar 00 /** * Script for bundle setup page * TODO translations */ !function( window, document, $ ){ /** * Look up bundle configuration on remote server */ function find( vendor, slug, version ){ function onFailure(){ if( timer ){ destroy(); onTimeout(); } }; function onResponse( data, status, obj ){ if( timer ){ destroy(); var match = data && data.exact, status = data && data.status ; if( match ){ setJson( match ); } else if( 404 === status ){ unsetJson("Sorry, we don't know a bundle by this name"); } else { loco.notices.debug( data.error || 'Unknown server error' ); onTimeout(); } } }; function onTimeout(){ unsetJson('Failed to contact remote API'); timer = null; } function destroy(){ if( timer ){ clearTimeout( timer ); timer = null; } } var timer = setTimeout( onTimeout, 3000 ); unsetJson(''); $.ajax( { url: conf.apiUrl+'/'+vendor+'/'+slug+'.jsonp?version='+encodeURIComponent(version), dataType: 'jsonp', success: onResponse, error: onFailure, cache: true } ); return { abort: destroy }; } function setJson( json ){ elForm['json-content'].value = json; $('#loco-remote-empty').hide(); //$('#loco-remote-query').hide(); $('#loco-remote-found').show(); } function unsetJson( message ){ elForm['json-content'].value = ''; //$('#loco-remote-query').show(); $('#loco-remote-empty').show().find('span').text( message ); $('#loco-remote-found').hide().removeClass('jshide'); } function onFindClick( event ){ event.preventDefault(); finder && finder.abort(); finder = find( elForm.vendor.value, elForm.slug.value, elForm.version.value ); return false; } function onCancelClick( event ){ event.preventDefault(); unsetJson(''); return false; } function setVendors( list ){ var i = -1, value, label, length = list.length, $select = $(elForm.vendor).html('') ; while( ++i < length ){ value = list[i][0]; label = list[i][1]; $select.append( $('<option></option>').attr('value',value).text(label) ); } } var loco = window.locoScope, conf = window.locoConf, finder, elForm = document.getElementById('loco-remote'), $findButt = $(elForm).find('button[type="button"]').click( onFindClick ), $resetButt = $(elForm).find('input[type="reset"]').click( onCancelClick ); // pull vendor list $.ajax( { url: conf.apiUrl+'/vendors.jsonp', dataType: 'jsonp', success: setVendors, cache: true } ); }( window, document, jQuery ); link.min.js 0000666 00000003143 15213733063 0006631 0 ustar 00 jQuery(document).ready(function(c){var t,i,e,a=!1;c("#link_name").focus(),postboxes.add_postbox_toggles("link"),c("#category-tabs a").click(function(){var t=c(this).attr("href");return c(this).parent().addClass("tabs").siblings("li").removeClass("tabs"),c(".tabs-panel").hide(),c(t).show(),"#categories-all"==t?deleteUserSetting("cats"):setUserSetting("cats","pop"),!1}),getUserSetting("cats")&&c('#category-tabs a[href="#categories-pop"]').click(),t=c("#newcat").one("focus",function(){c(this).val("").removeClass("form-input-tip")}),c("#link-category-add-submit").click(function(){t.focus()}),i=function(){var t,e;a||(a=!0,t=(e=c(this)).is(":checked"),e=e.val().toString(),c("#in-link-category-"+e+", #in-popular-link_category-"+e).prop("checked",t),a=!1)},e=function(t,e){c(e.what+" response_data",t).each(function(){c(c(this).text()).find("label").each(function(){var t=c(this),e=t.find("input").val(),a=t.find("input")[0].id,t=c.trim(t.text());c("#"+a).change(i),c('<option value="'+parseInt(e,10)+'"></option>').text(t)})})},c("#categorychecklist").wpList({alt:"",what:"link-category",response:"category-ajax-response",addAfter:e}),c('a[href="#categories-all"]').click(function(){deleteUserSetting("cats")}),c('a[href="#categories-pop"]').click(function(){setUserSetting("cats","pop")}),"pop"==getUserSetting("cats")&&c('a[href="#categories-pop"]').click(),c("#category-add-toggle").click(function(){return c(this).parents("div:first").toggleClass("wp-hidden-children"),c('#category-tabs a[href="#categories-all"]').click(),c("#newcategory").focus(),!1}),c(".categorychecklist :checkbox").change(i).filter(":checked").change()}); editor.min.js 0000666 00000014625 15213733063 0007171 0 ustar 00 !function(d){window.switchEditors=new function(){var c,o,n={};function e(){!c&&window.tinymce&&(c=window.tinymce,(o=c.$)(document).on("click",function(e){e=o(e.target);e.hasClass("wp-switch-editor")&&t(e.attr("data-wp-editor-id"),e.hasClass("switch-tmce")?"tmce":"html")}))}function l(e){e=o(".mce-toolbar-grp",e.getContainer())[0],e=e&&e.clientHeight;return e&&10<e&&e<200?parseInt(e,10):30}function t(e,n){e=e||"content",n=n||"toggle";var t,r=c.get(e),p=o("#wp-"+e+"-wrap"),i=o("#"+e),a=i[0];if("tmce"===(n="toggle"===n?r&&!r.isHidden()?"html":"tmce":n)||"tinymce"===n){if(r&&!r.isHidden())return!1;void 0!==window.QTags&&window.QTags.closeAllTags(e),t=parseInt(a.style.height,10)||0,r?(r.show(),!c.Env.iOS&&t&&50<(t=t-l(r)+14)&&t<5e3&&r.theme.resizeTo(null,t)):c.init(window.tinyMCEPreInit.mceInit[e]),p.removeClass("html-active").addClass("tmce-active"),i.attr("aria-hidden",!0),window.setUserSetting("editor","tinymce")}else if("html"===n){if(r&&r.isHidden())return!1;r?(c.Env.iOS||(t=(n=r.iframeElement)?parseInt(n.style.height,10):0)&&50<(t=t+l(r)-14)&&t<5e3&&(a.style.height=t+"px"),r.hide()):i.css({display:"",visibility:""}),p.removeClass("tmce-active").addClass("html-active"),i.attr("aria-hidden",!1),window.setUserSetting("editor","html")}}function r(e){var n="blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure",t=n+"|div|p",r=n+"|pre",p=!1,n=!1,i=[];return e?(-1!==(e=-1!==e.indexOf("<script")||-1!==e.indexOf("<style")?e.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/g,function(e){return i.push(e),"<wp-preserve>"}):e).indexOf("<pre")&&(p=!0,e=e.replace(/<pre[^>]*>[\s\S]+?<\/pre>/g,function(e){return(e=(e=e.replace(/<br ?\/?>(\r\n|\n)?/g,"<wp-line-break>")).replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g,"<wp-line-break>")).replace(/\r?\n/g,"<wp-line-break>")})),-1!==e.indexOf("[caption")&&(n=!0,e=e.replace(/\[caption[\s\S]+?\[\/caption\]/g,function(e){return e.replace(/<br([^>]*)>/g,"<wp-temp-br$1>").replace(/[\r\n\t]+/,"")})),e=(e=(e=(e=(e=-1!==(e=-1!==(e=-1!==(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=e.replace(new RegExp("\\s*</("+t+")>\\s*","g"),"</$1>\n")).replace(new RegExp("\\s*<((?:"+t+")(?: [^>]*)?)>","g"),"\n<$1>")).replace(/(<p [^>]+>.*?)<\/p>/g,"$1</p#>")).replace(/<div( [^>]*)?>\s*<p>/gi,"<div$1>\n\n")).replace(/\s*<p>/gi,"")).replace(/\s*<\/p>\s*/gi,"\n\n")).replace(/\n[\s\u00a0]+\n/g,"\n\n")).replace(/\s*<br ?\/?>\s*/gi,"\n")).replace(/\s*<div/g,"\n<div")).replace(/<\/div>\s*/g,"</div>\n")).replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi,"\n\n[caption$1[/caption]\n\n")).replace(/caption\]\n\n+\[caption/g,"caption]\n\n[caption")).replace(new RegExp("\\s*<((?:"+r+")(?: [^>]*)?)\\s*>","g"),"\n<$1>")).replace(new RegExp("\\s*</("+r+")>\\s*","g"),"</$1>\n")).replace(/<((li|dt|dd)[^>]*)>/g," \t<$1>")).indexOf("<option")?(e=e.replace(/\s*<option/g,"\n<option")).replace(/\s*<\/select>/g,"\n</select>"):e).indexOf("<hr")?e.replace(/\s*<hr( [^>]*)?>\s*/g,"\n\n<hr$1>\n\n"):e).indexOf("<object")?e.replace(/<object[\s\S]+?<\/object>/g,function(e){return e.replace(/[\r\n]+/g,"")}):e).replace(/<\/p#>/g,"</p>\n")).replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g,"\n$1")).replace(/^\s+/,"")).replace(/[\s\u00a0]+$/,""),p&&(e=e.replace(/<wp-line-break>/g,"\n")),n&&(e=e.replace(/<wp-temp-br([^>]*)>/g,"<br$1>")),e=i.length?e.replace(/<wp-preserve>/g,function(){return i.shift()}):e):""}function p(e){var n=!1,t=!1,r="table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary";return-1===(e=e.replace(/\r\n|\r/g,"\n")).indexOf("\n")?e:(-1===(e=(e=-1!==e.indexOf("<object")?e.replace(/<object[\s\S]+?<\/object>/g,function(e){return e.replace(/\n+/g,"")}):e).replace(/<[^<>]+>/g,function(e){return e.replace(/[\n\t ]+/g," ")})).indexOf("<pre")&&-1===e.indexOf("<script")||(n=!0,e=e.replace(/<(pre|script)[^>]*>[\s\S]*?<\/\1>/g,function(e){return e.replace(/\n/g,"<wp-line-break>")})),-1!==(e=-1!==e.indexOf("<figcaption")?(e=e.replace(/\s*(<figcaption[^>]*>)/g,"$1")).replace(/<\/figcaption>\s*/g,"</figcaption>"):e).indexOf("[caption")&&(t=!0,e=e.replace(/\[caption[\s\S]+?\[\/caption\]/g,function(e){return(e=(e=e.replace(/<br([^>]*)>/g,"<wp-temp-br$1>")).replace(/<[^<>]+>/g,function(e){return e.replace(/[\n\t ]+/," ")})).replace(/\s*\n\s*/g,"<wp-temp-br />")})),e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e+="\n\n").replace(/<br \/>\s*<br \/>/gi,"\n\n")).replace(new RegExp("(<(?:"+r+")(?: [^>]*)?>)","gi"),"\n\n$1")).replace(new RegExp("(</(?:"+r+")>)","gi"),"$1\n\n")).replace(/<hr( [^>]*)?>/gi,"<hr$1>\n\n")).replace(/\s*<option/gi,"<option")).replace(/<\/option>\s*/gi,"</option>")).replace(/\n\s*\n+/g,"\n\n")).replace(/([\s\S]+?)\n\n/g,"<p>$1</p>\n")).replace(/<p>\s*?<\/p>/gi,"")).replace(new RegExp("<p>\\s*(</?(?:"+r+")(?: [^>]*)?>)\\s*</p>","gi"),"$1")).replace(/<p>(<li.+?)<\/p>/gi,"$1")).replace(/<p>\s*<blockquote([^>]*)>/gi,"<blockquote$1><p>")).replace(/<\/blockquote>\s*<\/p>/gi,"</p></blockquote>")).replace(new RegExp("<p>\\s*(</?(?:"+r+")(?: [^>]*)?>)","gi"),"$1")).replace(new RegExp("(</?(?:"+r+")(?: [^>]*)?>)\\s*</p>","gi"),"$1")).replace(/(<br[^>]*>)\s*\n/gi,"$1")).replace(/\s*\n/g,"<br />\n")).replace(new RegExp("(</?(?:"+r+")[^>]*>)\\s*<br />","gi"),"$1")).replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi,"$1")).replace(/(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi,"[caption$1[/caption]")).replace(/(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g,function(e,n,t){return t.match(/<p( [^>]*)?>/)?e:n+"<p>"+t+"</p>"}),n&&(e=e.replace(/<wp-line-break>/g,"\n")),e=t?e.replace(/<wp-temp-br([^>]*)>/g,"<br$1>"):e)}function i(e){e={o:n,data:e,unfiltered:e};return d&&d("body").trigger("beforePreWpautop",[e]),e.data=r(e.data),d&&d("body").trigger("afterPreWpautop",[e]),e.data}function a(e){e={o:n,data:e,unfiltered:e};return d&&d("body").trigger("beforeWpautop",[e]),e.data=p(e.data),d&&d("body").trigger("afterWpautop",[e]),e.data}return d?d(document).ready(e):document.addEventListener?(document.addEventListener("DOMContentLoaded",e,!1),window.addEventListener("load",e,!1)):window.attachEvent&&(window.attachEvent("onload",e),document.attachEvent("onreadystatechange",function(){"complete"===document.readyState&&e()})),window.wp=window.wp||{},window.wp.editor=window.wp.editor||{},window.wp.editor.autop=a,window.wp.editor.removep=i,n={go:t,wpautop:a,pre_wpautop:i,_wp_Autop:p,_wp_Nop:r}}}(window.jQuery); inline-edit-tax.js 0000666 00000016466 15213733063 0010121 0 ustar 00 /* global inlineEditL10n, ajaxurl */ /** * This file is used on the term overview page to power quick-editing terms. */ window.wp = window.wp || {}; /** * Consists of functions relevant to the inline taxonomy editor. * * @namespace inlineEditTax * * @property {string} type The type of inline edit we are currently on. * @property {string} what The type property with a hash prefixed and a dash * suffixed. */ var inlineEditTax; ( function( $, wp ) { inlineEditTax = { /** * @summary Initializes the inline taxonomy editor. * * Adds event handlers to be able to quick edit. * * @since 2.7.0 * * @this inlineEditTax * @memberof inlineEditTax * @returns {void} */ 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; }); /* * @summary Cancels inline editing when pressing escape inside the inline editor. * * @param {Object} e The keyup event that has been triggered. */ row.keyup( function( e ) { // 27 = [escape] if ( e.which === 27 ) { return inlineEditTax.revert(); } }); /** * @summary Cancels inline editing when clicking the cancel button. */ $( '.cancel', row ).click( function() { return inlineEditTax.revert(); }); /** * @summary Saves the inline edits when clicking the save button. */ $( '.save', row ).click( function() { return inlineEditTax.save(this); }); /** * @summary Saves the inline edits when pressing enter inside the inline editor. */ $( 'input, select', row ).keydown( function( e ) { // 13 = [enter] if ( e.which === 13 ) { return inlineEditTax.save( this ); } }); /** * @summary Saves the inline edits on submitting the inline edit form. */ $( '#posts-filter input[type="submit"]' ).mousedown( function() { t.revert(); }); }, /** * Toggles the quick edit based on if it is currently shown or hidden. * * @since 2.7.0 * * @this inlineEditTax * @memberof inlineEditTax * * @param {HTMLElement} el An element within the table row or the table row * itself that we want to quick edit. * @returns {void} */ toggle : function(el) { var t = this; $(t.what+t.getId(el)).css('display') === 'none' ? t.revert() : t.edit(el); }, /** * Shows the quick editor * * @since 2.7.0 * * @this inlineEditTax * @memberof inlineEditTax * * @param {string|HTMLElement} id The ID of the term we want to quick edit or an * element within the table row or the * table row itself. * @returns {boolean} Always returns false. */ edit : function(id) { var editRow, rowData, val, t = this; t.revert(); // Makes sure we can pass an HTMLElement as the ID. if ( typeof(id) === 'object' ) { id = t.getId(id); } editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id); $( 'td', editRow ).attr( 'colspan', $( 'th:visible, td:visible', '.wp-list-table.widefat:first thead' ).length ); $(t.what+id).hide().after(editRow).after('<tr class="hidden"></tr>'); val = $('.name', rowData); val.find( 'img' ).replaceWith( function() { return this.alt; } ); val = val.text(); $(':input[name="name"]', editRow).val( val ); val = $('.slug', rowData); val.find( 'img' ).replaceWith( function() { return this.alt; } ); val = val.text(); $(':input[name="slug"]', editRow).val( val ); $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show(); $('.ptitle', editRow).eq(0).focus(); return false; }, /** * @summary Saves the quick edit data. * * Saves the quick edit data to the server and replaces the table row with the * HTML retrieved from the server. * * @since 2.7.0 * * @this inlineEditTax * @memberof inlineEditTax * * @param {string|HTMLElement} id The ID of the term we want to quick edit or an * element within the table row or the * table row itself. * @returns {boolean} Always returns false. */ save : function(id) { var params, fields, tax = $('input[name="taxonomy"]').val() || ''; // Makes sure we can pass an HTMLElement as the ID. if( typeof(id) === 'object' ) { id = this.getId(id); } $( 'table.widefat .spinner' ).addClass( 'is-active' ); params = { action: 'inline-save-tax', tax_type: this.type, tax_ID: id, taxonomy: tax }; fields = $('#edit-'+id).find(':input').serialize(); params = fields + '&' + $.param(params); // Do the ajax request to save the data to the server. $.post( ajaxurl, params, /** * @summary Handles the response from the server. * * Handles the response from the server, replaces the table row with the response * from the server. * * @param {string} r The string with which to replace the table row. */ function(r) { var row, new_id, option_value, $errorSpan = $( '#edit-' + id + ' .inline-edit-save .error' ); $( 'table.widefat .spinner' ).removeClass( 'is-active' ); if (r) { if ( -1 !== r.indexOf( '<tr' ) ) { $(inlineEditTax.what+id).siblings('tr.hidden').addBack().remove(); new_id = $(r).attr('id'); $('#edit-'+id).before(r).remove(); if ( new_id ) { option_value = new_id.replace( inlineEditTax.type + '-', '' ); row = $( '#' + new_id ); } else { option_value = id; row = $( inlineEditTax.what + id ); } // Update the value in the Parent dropdown. $( '#parent' ).find( 'option[value=' + option_value + ']' ).text( row.find( '.row-title' ).text() ); row.hide().fadeIn( 400, function() { // Move focus back to the Quick Edit link. row.find( '.editinline' ).focus(); wp.a11y.speak( inlineEditL10n.saved ); }); } else { $errorSpan.html( r ).show(); /* * Some error strings may contain HTML entities (e.g. `“`), let's use * the HTML element's text. */ wp.a11y.speak( $errorSpan.text() ); } } else { $errorSpan.html( inlineEditL10n.error ).show(); wp.a11y.speak( inlineEditL10n.error ); } } ); // Prevent submitting the form when pressing Enter on a focused field. return false; }, /** * Closes the quick edit form. * * @since 2.7.0 * * @this inlineEditTax * @memberof inlineEditTax * @returns {void} */ revert : function() { var id = $('table.widefat tr.inline-editor').attr('id'); if ( id ) { $( 'table.widefat .spinner' ).removeClass( 'is-active' ); $('#'+id).siblings('tr.hidden').addBack().remove(); id = id.substr( id.lastIndexOf('-') + 1 ); // Show the taxonomy row and move focus back to the Quick Edit link. $( this.what + id ).show().find( '.editinline' ).focus(); } }, /** * Retrieves the ID of the term of the element inside the table row. * * @since 2.7.0 * * @memberof inlineEditTax * * @param {HTMLElement} o An element within the table row or the table row itself. * @returns {string} The ID of the term based on the element. */ 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, window.wp ); svg-painter.js 0000666 00000012554 15213733063 0007357 0 ustar 00 /** * Attempt to re-color SVG icons used in the admin menu or the toolbar * */ window.wp = window.wp || {}; wp.svgPainter = ( function( $, window, document, undefined ) { 'use strict'; var selector, base64, painter, colorscheme = {}, elements = []; $(document).ready( function() { // detection for browser SVG capability if ( document.implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#Image', '1.1' ) ) { $( document.body ).removeClass( 'no-svg' ).addClass( 'svg' ); wp.svgPainter.init(); } }); /** * Needed only for IE9 * * Based on jquery.base64.js 0.0.3 - https://github.com/yckart/jquery.base64.js * * Based on: https://gist.github.com/Yaffle/1284012 * * Copyright (c) 2012 Yannick Albert (http://yckart.com) * Licensed under the MIT license * http://www.opensource.org/licenses/mit-license.php */ base64 = ( function() { var c, b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', a256 = '', r64 = [256], r256 = [256], i = 0; function init() { while( i < 256 ) { c = String.fromCharCode(i); a256 += c; r256[i] = i; r64[i] = b64.indexOf(c); ++i; } } function code( s, discard, alpha, beta, w1, w2 ) { var tmp, length, buffer = 0, i = 0, result = '', bitsInBuffer = 0; s = String(s); length = s.length; while( i < length ) { c = s.charCodeAt(i); c = c < 256 ? alpha[c] : -1; buffer = ( buffer << w1 ) + c; bitsInBuffer += w1; while( bitsInBuffer >= w2 ) { bitsInBuffer -= w2; tmp = buffer >> bitsInBuffer; result += beta.charAt(tmp); buffer ^= tmp << bitsInBuffer; } ++i; } if ( ! discard && bitsInBuffer > 0 ) { result += beta.charAt( buffer << ( w2 - bitsInBuffer ) ); } return result; } function btoa( plain ) { if ( ! c ) { init(); } plain = code( plain, false, r256, b64, 8, 6 ); return plain + '===='.slice( ( plain.length % 4 ) || 4 ); } function atob( coded ) { var i; if ( ! c ) { init(); } coded = coded.replace( /[^A-Za-z0-9\+\/\=]/g, '' ); coded = String(coded).split('='); i = coded.length; do { --i; coded[i] = code( coded[i], true, r64, a256, 6, 8 ); } while ( i > 0 ); coded = coded.join(''); return coded; } return { atob: atob, btoa: btoa }; })(); return { init: function() { painter = this; selector = $( '#adminmenu .wp-menu-image, #wpadminbar .ab-item' ); this.setColors(); this.findElements(); this.paint(); }, setColors: function( colors ) { if ( typeof colors === 'undefined' && typeof window._wpColorScheme !== 'undefined' ) { colors = window._wpColorScheme; } if ( colors && colors.icons && colors.icons.base && colors.icons.current && colors.icons.focus ) { colorscheme = colors.icons; } }, findElements: function() { selector.each( function() { var $this = $(this), bgImage = $this.css( 'background-image' ); if ( bgImage && bgImage.indexOf( 'data:image/svg+xml;base64' ) != -1 ) { elements.push( $this ); } }); }, paint: function() { // loop through all elements $.each( elements, function( index, $element ) { var $menuitem = $element.parent().parent(); if ( $menuitem.hasClass( 'current' ) || $menuitem.hasClass( 'wp-has-current-submenu' ) ) { // paint icon in 'current' color painter.paintElement( $element, 'current' ); } else { // paint icon in base color painter.paintElement( $element, 'base' ); // set hover callbacks $menuitem.hover( function() { painter.paintElement( $element, 'focus' ); }, function() { // Match the delay from hoverIntent window.setTimeout( function() { painter.paintElement( $element, 'base' ); }, 100 ); } ); } }); }, paintElement: function( $element, colorType ) { var xml, encoded, color; if ( ! colorType || ! colorscheme.hasOwnProperty( colorType ) ) { return; } color = colorscheme[ colorType ]; // only accept hex colors: #101 or #101010 if ( ! color.match( /^(#[0-9a-f]{3}|#[0-9a-f]{6})$/i ) ) { return; } xml = $element.data( 'wp-ui-svg-' + color ); if ( xml === 'none' ) { return; } if ( ! xml ) { encoded = $element.css( 'background-image' ).match( /.+data:image\/svg\+xml;base64,([A-Za-z0-9\+\/\=]+)/ ); if ( ! encoded || ! encoded[1] ) { $element.data( 'wp-ui-svg-' + color, 'none' ); return; } try { if ( 'atob' in window ) { xml = window.atob( encoded[1] ); } else { xml = base64.atob( encoded[1] ); } } catch ( error ) {} if ( xml ) { // replace `fill` attributes xml = xml.replace( /fill="(.+?)"/g, 'fill="' + color + '"'); // replace `style` attributes xml = xml.replace( /style="(.+?)"/g, 'style="fill:' + color + '"'); // replace `fill` properties in `<style>` tags xml = xml.replace( /fill:.*?;/g, 'fill: ' + color + ';'); if ( 'btoa' in window ) { xml = window.btoa( xml ); } else { xml = base64.btoa( xml ); } $element.data( 'wp-ui-svg-' + color, xml ); } else { $element.data( 'wp-ui-svg-' + color, 'none' ); return; } } $element.attr( 'style', 'background-image: url("data:image/svg+xml;base64,' + xml + '") !important;' ); } }; })( jQuery, window, document ); dashboard.js 0000666 00000013236 15213733063 0007045 0 ustar 00 /* global pagenow, ajaxurl, postboxes, wpActiveEditor:true */ var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad; jQuery(document).ready( function($) { var welcomePanel = $( '#welcome-panel' ), welcomePanelHide = $('#wp_welcome_panel-hide'), updateWelcomePanel; 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_primary']; 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 + '&pagenow=' + pagenow, '', 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; $( '#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]' ).prop( 'disabled' , false ); t = $('#quick-press').submit( function( e ) { e.preventDefault(); $('#dashboard_quick_press #publishing-action .spinner').show(); $('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true); $.post( t.attr( 'action' ), t.serializeArray(), function( data ) { // Replace the form, and prepend the published post. $('#dashboard_quick_press .inside').html( data ); $('#quick-press').removeClass('initial-form'); quickPressLoad(); highlightLatestPost(); $('#title').focus(); }); function highlightLatestPost () { var latestPost = $('.drafts ul li').first(); latestPost.css('background', '#fffbe5'); setTimeout(function () { latestPost.css('background', 'none'); }, 1000); } } ); $('#publish').click( function() { act.val( 'post-quickpress-publish' ); } ); $('#title, #tags-input, #content').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'; }); autoResizeTextarea(); }; quickPressLoad(); $( '.meta-box-sortables' ).sortable( 'option', 'containment', '#wpwrap' ); function autoResizeTextarea() { if ( document.documentMode && document.documentMode < 9 ) { return; } // Add a hidden div. We'll copy over the text from the textarea to measure its height. $('body').append( '<div class="quick-draft-textarea-clone" style="display: none;"></div>' ); var clone = $('.quick-draft-textarea-clone'), editor = $('#content'), editorHeight = editor.height(), // 100px roughly accounts for browser chrome and allows the // save draft button to show on-screen at the same time. editorMaxHeight = $(window).height() - 100; // Match up textarea and clone div as much as possible. // Padding cannot be reliably retrieved using shorthand in all browsers. clone.css({ 'font-family': editor.css('font-family'), 'font-size': editor.css('font-size'), 'line-height': editor.css('line-height'), 'padding-bottom': editor.css('paddingBottom'), 'padding-left': editor.css('paddingLeft'), 'padding-right': editor.css('paddingRight'), 'padding-top': editor.css('paddingTop'), 'white-space': 'pre-wrap', 'word-wrap': 'break-word', 'display': 'none' }); // propertychange is for IE < 9 editor.on('focus input propertychange', function() { var $this = $(this), // is to ensure that the height of a final trailing newline is included. textareaContent = $this.val() + ' ', // 2px is for border-top & border-bottom cloneHeight = clone.css('width', $this.css('width')).text(textareaContent).outerHeight() + 2; // Default to having scrollbars editor.css('overflow-y', 'auto'); // Only change the height if it has indeed changed and both heights are below the max. if ( cloneHeight === editorHeight || ( cloneHeight >= editorMaxHeight && editorHeight >= editorMaxHeight ) ) { return; } // Don't allow editor to exceed height of window. // This is also bound in CSS to a max-height of 1300px to be extra safe. if ( cloneHeight > editorMaxHeight ) { editorHeight = editorMaxHeight; } else { editorHeight = cloneHeight; } // No scrollbars as we change height, not for IE < 9 editor.css('overflow', 'hidden'); $this.css('height', editorHeight + 'px'); }); } } ); tags-suggest.js 0000666 00000012112 15213733063 0007523 0 ustar 00 /** * Default settings for jQuery UI Autocomplete for use with non-hierarchical taxonomies. */ ( function( $ ) { if ( typeof window.tagsSuggestL10n === 'undefined' || typeof window.uiAutocompleteL10n === 'undefined' ) { return; } var tempID = 0; var separator = window.tagsSuggestL10n.tagDelimiter || ','; function split( val ) { return val.split( new RegExp( separator + '\\s*' ) ); } function getLast( term ) { return split( term ).pop(); } /** * Add UI Autocomplete to an input or textarea element with presets for use * with non-hierarchical taxonomies. * * Example: `$( element ).wpTagsSuggest( options )`. * * The taxonomy can be passed in a `data-wp-taxonomy` attribute on the element or * can be in `options.taxonomy`. * * @since 4.7.0 * * @param {object} options Options that are passed to UI Autocomplete. Can be used to override the default settings. * @returns {object} jQuery instance. */ $.fn.wpTagsSuggest = function( options ) { var cache; var last; var $element = $( this ); options = options || {}; var taxonomy = options.taxonomy || $element.attr( 'data-wp-taxonomy' ) || 'post_tag'; delete( options.taxonomy ); options = $.extend( { source: function( request, response ) { var term; if ( last === request.term ) { response( cache ); return; } term = getLast( request.term ); $.get( window.ajaxurl, { action: 'ajax-tag-search', tax: taxonomy, q: term } ).always( function() { $element.removeClass( 'ui-autocomplete-loading' ); // UI fails to remove this sometimes? } ).done( function( data ) { var tagName; var tags = []; if ( data ) { data = data.split( '\n' ); for ( tagName in data ) { var id = ++tempID; tags.push({ id: id, name: data[tagName] }); } cache = tags; response( tags ); } else { response( tags ); } } ); last = request.term; }, focus: function( event, ui ) { $element.attr( 'aria-activedescendant', 'wp-tags-autocomplete-' + ui.item.id ); // Don't empty the input field when using the arrow keys to // highlight items. See api.jqueryui.com/autocomplete/#event-focus event.preventDefault(); }, select: function( event, ui ) { var tags = split( $element.val() ); // Remove the last user input. tags.pop(); // Append the new tag and an empty element to get one more separator at the end. tags.push( ui.item.name, '' ); $element.val( tags.join( separator + ' ' ) ); if ( $.ui.keyCode.TAB === event.keyCode ) { // Audible confirmation message when a tag has been selected. window.wp.a11y.speak( window.tagsSuggestL10n.termSelected, 'assertive' ); event.preventDefault(); } else if ( $.ui.keyCode.ENTER === event.keyCode ) { // Do not close Quick Edit / Bulk Edit event.preventDefault(); event.stopPropagation(); } return false; }, open: function() { $element.attr( 'aria-expanded', 'true' ); }, close: function() { $element.attr( 'aria-expanded', 'false' ); }, minLength: 2, position: { my: 'left top+2', at: 'left bottom', collision: 'none' }, messages: { noResults: window.uiAutocompleteL10n.noResults, results: function( number ) { if ( number > 1 ) { return window.uiAutocompleteL10n.manyResults.replace( '%d', number ); } return window.uiAutocompleteL10n.oneResult; } } }, options ); $element.on( 'keydown', function() { $element.removeAttr( 'aria-activedescendant' ); } ) .autocomplete( options ) .autocomplete( 'instance' )._renderItem = function( ul, item ) { return $( '<li role="option" id="wp-tags-autocomplete-' + item.id + '">' ) .text( item.name ) .appendTo( ul ); }; $element.attr( { 'role': 'combobox', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'aria-owns': $element.autocomplete( 'widget' ).attr( 'id' ) } ) .on( 'focus', function() { var inputValue = split( $element.val() ).pop(); // Don't trigger a search if the field is empty. // Also, avoids screen readers announce `No search results`. if ( inputValue ) { $element.autocomplete( 'search' ); } } ) // Returns a jQuery object containing the menu element. .autocomplete( 'widget' ) .addClass( 'wp-tags-autocomplete' ) .attr( 'role', 'listbox' ) .removeAttr( 'tabindex' ) // Remove the `tabindex=0` attribute added by jQuery UI. // Looks like Safari and VoiceOver need an `aria-selected` attribute. See ticket #33301. // The `menufocus` and `menublur` events are the same events used to add and remove // the `ui-state-focus` CSS class on the menu items. See jQuery UI Menu Widget. .on( 'menufocus', function( event, ui ) { ui.item.attr( 'aria-selected', 'true' ); }) .on( 'menublur', function() { // The `menublur` event returns an object where the item is `null` // so we need to find the active item with other means. $( this ).find( '[aria-selected="true"]' ).removeAttr( 'aria-selected' ); }); return this; }; }( jQuery ) ); tags-box.js 0000666 00000015302 15213733063 0006636 0 ustar 00 /* jshint curly: false, eqeqeq: false */ /* global ajaxurl */ var tagBox, array_unique_noempty; ( function( $ ) { var tagDelimiter = ( window.tagsSuggestL10n && window.tagsSuggestL10n.tagDelimiter ) || ','; // Return an array with any duplicate, whitespace or empty values removed array_unique_noempty = function( array ) { var out = []; $.each( array, function( key, val ) { val = $.trim( val ); if ( val && $.inArray( val, out ) === -1 ) { out.push( val ); } } ); return out; }; tagBox = { clean : function( tags ) { if ( ',' !== tagDelimiter ) { tags = tags.replace( new RegExp( tagDelimiter, 'g' ), ',' ); } tags = tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, ''); if ( ',' !== tagDelimiter ) { tags = tags.replace( /,/g, tagDelimiter ); } return tags; }, parseTags : function(el) { var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'), thetags = taxbox.find('.the-tags'), current_tags = thetags.val().split( tagDelimiter ), 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( tagDelimiter ) ) ); 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( tagDelimiter ); 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 ) { /* * Build the X buttons, hide the X icon with aria-hidden and * use visually hidden text for screen readers. */ xbutton = $( '<button type="button" id="' + id + '-check-num-' + key + '" class="ntdelbutton">' + '<span class="remove-tag-icon" aria-hidden="true"></span>' + '<span class="screen-reader-text">' + window.tagsSuggestL10n.removeTerm + ' ' + span.html() + '</span>' + '</button>' ); xbutton.on( 'click keypress', function( e ) { // On click or when using the Enter/Spacebar keys. if ( 'click' === e.type || 13 === e.keyCode || 32 === e.keyCode ) { /* * When using the keyboard, move focus back to the * add new tag field. Note: when releasing the pressed * key this will fire the `keyup` event on the input. */ if ( 13 === e.keyCode || 32 === e.keyCode ) { $( this ).closest( '.tagsdiv' ).find( 'input.newtag' ).focus(); } tagBox.userAction = 'remove'; tagBox.parseTags( this ); } }); span.prepend( ' ' ).prepend( xbutton ); } // Append the span to the tag list. tagchecklist.append( span ); }); // The buttons list is built now, give feedback to screen reader users. tagBox.screenReadersMessage(); }, flushTags : function( el, a, f ) { var tagsval, newtags, text, tags = $( '.the-tags', el ), newtag = $( 'input.newtag', el ); a = a || false; text = a ? $(a).text() : newtag.val(); /* * Return if there's no new tag or if the input field is empty. * Note: when using the keyboard to add tags, focus is moved back to * the input field and the `keyup` event attached on this field will * fire when releasing the pressed key. Checking also for the field * emptiness avoids to set the tags and call quickClicks() again. */ if ( 'undefined' == typeof( text ) || '' === text ) { return false; } tagsval = tags.val(); newtags = tagsval ? tagsval + tagDelimiter + text : text; newtags = this.clean( newtags ); newtags = array_unique_noempty( newtags.split( tagDelimiter ) ).join( tagDelimiter ); 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 ) { return; } r = $( '<p id="tagcloud-' + tax + '" class="the-tagcloud">' + r + '</p>' ); $( 'a', r ).click( function() { tagBox.userAction = 'add'; tagBox.flushTags( $( '#' + tax ), this ); return false; }); $( '#' + id ).after( r ); }); }, /** * Track the user's last action. * * @since 4.7.0 */ userAction: '', /** * Dispatch an audible message to screen readers. * * @since 4.7.0 */ screenReadersMessage: function() { var message; switch ( this.userAction ) { case 'remove': message = window.tagsSuggestL10n.termRemoved; break; case 'add': message = window.tagsSuggestL10n.termAdded; break; default: return; } window.wp.a11y.speak( message, 'assertive' ); }, init : function() { var ajaxtag = $('div.ajaxtag'); $('.tagsdiv').each( function() { tagBox.quickClicks( this ); }); $( '.tagadd', ajaxtag ).click( function() { tagBox.userAction = 'add'; tagBox.flushTags( $( this ).closest( '.tagsdiv' ) ); }); $( 'input.newtag', ajaxtag ).keyup( function( event ) { if ( 13 == event.which ) { tagBox.userAction = 'add'; tagBox.flushTags( $( this ).closest( '.tagsdiv' ) ); event.preventDefault(); event.stopPropagation(); } }).keypress( function( event ) { if ( 13 == event.which ) { event.preventDefault(); event.stopPropagation(); } }).each( function( i, element ) { $( element ).wpTagsSuggest(); }); // save tags on post save/publish $('#post').submit(function(){ $('div.tagsdiv').each( function() { tagBox.flushTags(this, false, 1); }); }); // Fetch and toggle the Tag cloud. $('.tagcloud-link').click(function(){ // On the first click, fetch the tag cloud and insert it in the DOM. tagBox.get( $( this ).attr( 'id' ) ); // Update button state, remove previous click event and attach a new one to toggle the cloud. $( this ) .attr( 'aria-expanded', 'true' ) .unbind() .click( function() { $( this ) .attr( 'aria-expanded', 'false' === $( this ).attr( 'aria-expanded' ) ? 'true' : 'false' ) .siblings( '.the-tagcloud' ).toggle(); }); }); } }; }( jQuery )); common.min.js 0000666 00000032536 15213733063 0007174 0 ustar 00 var showNotice,adminMenu,columns,validateForm,screenMeta;!function(V,q){var e,n,B=V(document),H=V(q),Q=V(document.body);function t(){B.trigger("wp-window-resized")}adminMenu={init:function(){},fold:function(){},restoreMenuState:function(){},toggle:function(){},favorites:function(){}},columns={init:function(){var t=this;V(".hide-column-tog","#adv-settings").click(function(){var e=V(this),n=e.val();e.prop("checked")?t.checked(n):t.unchecked(n),columns.saveManageColumnsState()})},saveManageColumnsState:function(){var e=this.hidden();V.post(ajaxurl,{action:"hidden-columns",hidden:e,screenoptionnonce:V("#screenoptionnonce").val(),page:pagenow})},checked:function(e){V(".column-"+e).removeClass("hidden"),this.colSpanChange(1)},unchecked:function(e){V(".column-"+e).addClass("hidden"),this.colSpanChange(-1)},hidden:function(){return V(".manage-column[id]").filter(":hidden").map(function(){return this.id}).get().join(",")},useCheckboxesForHidden:function(){this.hidden=function(){return V(".hide-column-tog").not(":checked").map(function(){var e=this.id;return e.substring(e,e.length-5)}).get().join(",")}},colSpanChange:function(e){var n=V("table").find(".colspanchange");n.length&&(e=parseInt(n.attr("colspan"),10)+e,n.attr("colspan",e.toString()))}},B.ready(function(){columns.init()}),validateForm=function(e){return!V(e).find(".form-required").filter(function(){return""===V("input:visible",this).val()}).addClass("form-invalid").find("input:visible").change(function(){V(this).closest(".form-invalid").removeClass("form-invalid")}).length},showNotice={warn:function(){var e=commonL10n.warnDelete||"";return!!confirm(e)},note:function(e){alert(e)}},screenMeta={element:null,toggles:null,page:null,init:function(){this.element=V("#screen-meta"),this.toggles=V("#screen-meta-links").find(".show-settings"),this.page=V("#wpcontent"),this.toggles.click(this.toggleEvent)},toggleEvent:function(){var e=V("#"+V(this).attr("aria-controls"));e.length&&(e.is(":visible")?screenMeta.close(e,V(this)):screenMeta.open(e,V(this)))},open:function(e,n){V("#screen-meta-links").find(".screen-meta-toggle").not(n.parent()).css("visibility","hidden"),e.parent().show(),e.slideDown("fast",function(){e.focus(),n.addClass("screen-meta-active").attr("aria-expanded",!0)}),B.trigger("screen:options:open")},close:function(e,n){e.slideUp("fast",function(){n.removeClass("screen-meta-active").attr("aria-expanded",!1),V(".screen-meta-toggle").css("visibility",""),e.parent().hide()}),B.trigger("screen:options:close")}},V(".contextual-help-tabs").delegate("a","click",function(e){var n=V(this);if(e.preventDefault(),n.is(".active a"))return!1;V(".contextual-help-tabs .active").removeClass("active"),n.parent("li").addClass("active"),n=V(n.attr("href")),V(".help-tab-content").not(n).removeClass("active").hide(),n.addClass("active").show()}),B.ready(function(){var t,i,o,s,e,n,a,r,c,l,d=!1,u=V("input.current-page"),p=u.val(),f=/iPhone|iPad|iPod/.test(navigator.userAgent),h=-1!==navigator.userAgent.indexOf("Android"),m=V(document.documentElement).hasClass("ie8"),v=V("#adminmenuwrap"),w=V("#wpwrap"),g=V("#adminmenu"),b=V("#wp-responsive-overlay"),k=V("#wp-toolbar"),C=k.find('a[aria-haspopup="true"]'),x=V(".meta-box-sortables"),y=!1,S=V("#wpadminbar"),M=0,T=!1,D=!1,E=0,A=!1,I={window:H.height(),wpwrap:w.height(),adminbar:S.height(),menu:v.height()},U=V(".wp-header-end");function j(){var e=V("a.wp-has-current-submenu");"folded"===r?e.attr("aria-haspopup","true"):e.attr("aria-haspopup","false")}function K(e){var n=e.find(".wp-submenu"),t=e.offset().top,i=H.scrollTop(),o=t-i-30,e=t+n.height()+1,t=60+e-w.height(),i=H.height()+i-50;1<(t=o<(t=i<e-t?e-i:t)?o:t)?n.css("margin-top","-"+t+"px"):n.css("margin-top","")}function z(){V(".notice.is-dismissible").each(function(){var n=V(this),e=V('<button type="button" class="notice-dismiss"><span class="screen-reader-text"></span></button>'),t=commonL10n.dismiss||"";e.find(".screen-reader-text").text(t),e.on("click.wp-dismiss-notice",function(e){e.preventDefault(),n.fadeTo(100,0,function(){n.slideUp(100,function(){n.remove()})})}),n.append(e)})}function N(){c.prop("disabled",""===l.map(function(){return V(this).val()}).get().join(""))}function O(e){var n=H.scrollTop(),e=!e||"scroll"!==e.type;if(!(f||m||g.data("wp-responsive")))if(I.menu+I.adminbar<I.window||I.menu+I.adminbar+20>I.wpwrap)W();else{if(A=!0,I.menu+I.adminbar>I.window){if(n<0)return void(T||(D=!(T=!0),v.css({position:"fixed",top:"",bottom:""})));if(n+I.window>B.height()-1)return void(D||(T=!(D=!0),v.css({position:"fixed",top:"",bottom:0})));M<n?T?(T=!1,(E=v.offset().top-I.adminbar-(n-M))+I.menu+I.adminbar<n+I.window&&(E=n+I.window-I.menu-I.adminbar),v.css({position:"absolute",top:E,bottom:""})):!D&&v.offset().top+I.menu<n+I.window&&(D=!0,v.css({position:"fixed",top:"",bottom:0})):n<M?D?(D=!1,(E=v.offset().top-I.adminbar+(M-n))+I.menu>n+I.window&&(E=n),v.css({position:"absolute",top:E,bottom:""})):!T&&v.offset().top>=n+I.adminbar&&(T=!0,v.css({position:"fixed",top:"",bottom:""})):e&&(T=D=!1,0<(E=n+I.window-I.menu-I.adminbar-1)?v.css({position:"absolute",top:E,bottom:""}):W())}M=n}}function P(){I={window:H.height(),wpwrap:w.height(),adminbar:S.height(),menu:v.height()}}function W(){!f&&A&&(T=D=A=!1,v.css({position:"",top:"",bottom:""}))}function L(){P(),g.data("wp-responsive")?(Q.removeClass("sticky-menu"),W()):I.menu+I.adminbar>I.window?(O(),Q.removeClass("sticky-menu")):(Q.addClass("sticky-menu"),W())}function F(){V(".aria-button-if-js").attr("role","button")}function R(){var e=!1;return e=q.innerWidth?Math.max(q.innerWidth,document.documentElement.clientWidth):e}function _(){var e=R()||961;r=e<=782?"responsive":Q.hasClass("folded")||Q.hasClass("auto-fold")&&e<=960&&782<e?"folded":"open",B.trigger("wp-menu-state-set",{state:r})}g.on("click.wp-submenu-head",".wp-submenu-head",function(e){V(e.target).parent().siblings("a").get(0).click()}),V("#collapse-button").on("click.collapse-menu",function(){var e=R()||961;V("#adminmenu div.wp-submenu").css("margin-top",""),r=e<960?Q.hasClass("auto-fold")?(Q.removeClass("auto-fold").removeClass("folded"),setUserSetting("unfold",1),setUserSetting("mfold","o"),"open"):(Q.addClass("auto-fold"),setUserSetting("unfold",0),"folded"):Q.hasClass("folded")?(Q.removeClass("folded"),setUserSetting("mfold","o"),"open"):(Q.addClass("folded"),setUserSetting("mfold","f"),"folded"),B.trigger("wp-collapse-menu",{state:r})}),B.on("wp-menu-state-set wp-collapse-menu wp-responsive-activate wp-responsive-deactivate",j),("ontouchstart"in q||/IEMobile\/[1-9]/.test(navigator.userAgent))&&(e=f?"touchstart":"click",Q.on(e+".wp-mobile-hover",function(e){g.data("wp-responsive")||V(e.target).closest("#adminmenu").length||g.find("li.opensub").removeClass("opensub")}),g.find("a.wp-has-submenu").on(e+".wp-mobile-hover",function(e){var n=V(this).parent();g.data("wp-responsive")||n.hasClass("opensub")||n.hasClass("wp-menu-open")&&!(n.width()<40)||(e.preventDefault(),K(n),g.find("li.opensub").removeClass("opensub"),n.addClass("opensub"))})),f||h||(g.find("li.wp-has-submenu").hoverIntent({over:function(){var e=V(this),n=e.find(".wp-submenu"),n=parseInt(n.css("top"),10);isNaN(n)||-5<n||g.data("wp-responsive")||(K(e),g.find("li.opensub").removeClass("opensub"),e.addClass("opensub"))},out:function(){g.data("wp-responsive")||V(this).removeClass("opensub").find(".wp-submenu").css("margin-top","")},timeout:200,sensitivity:7,interval:90}),g.on("focus.adminmenu",".wp-submenu a",function(e){g.data("wp-responsive")||V(e.target).closest("li.menu-top").addClass("opensub")}).on("blur.adminmenu",".wp-submenu a",function(e){g.data("wp-responsive")||V(e.target).closest("li.menu-top").removeClass("opensub")}).find("li.wp-has-submenu.wp-not-current-submenu").on("focusin.adminmenu",function(){K(V(this))})),U.length||(U=V(".wrap h1, .wrap h2").first()),V("div.updated, div.error, div.notice").not(".inline, .below-h2").insertAfter(U),B.on("wp-updates-notice-added wp-plugin-install-error wp-plugin-update-error wp-plugin-delete-error wp-theme-install-error wp-theme-delete-error",z),screenMeta.init(),Q.on("click","tbody > tr > .check-column :checkbox",function(e){if("undefined"==e.shiftKey)return!0;if(e.shiftKey){if(!d)return!0;t=V(d).closest("form").find(":checkbox").filter(":visible:enabled"),i=t.index(d),o=t.index(this),s=V(this).prop("checked"),0<i&&0<o&&i!=o&&(i<o?t.slice(i,o):t.slice(o,i)).prop("checked",function(){return!!V(this).closest("tr").is(":visible")&&s})}var n=V(d=this).closest("tbody").find(":checkbox").filter(":visible:enabled").not(":checked");return V(this).closest("table").children("thead, tfoot").find(":checkbox").prop("checked",function(){return 0===n.length}),!0}),Q.on("click.wp-toggle-checkboxes","thead .check-column :checkbox, tfoot .check-column :checkbox",function(e){var n=V(this),t=n.closest("table"),i=n.prop("checked"),o=e.shiftKey||n.data("wp-toggle");t.children("tbody").filter(":visible").children().children(".check-column").find(":checkbox").prop("checked",function(){return!V(this).is(":hidden,:disabled")&&(o?!V(this).prop("checked"):!!i)}),t.children("thead, tfoot").filter(":visible").children().children(".check-column").find(":checkbox").prop("checked",function(){return!o&&!!i})}),V("#wpbody-content").on({focusin:function(){clearTimeout(n),a=V(this).find(".row-actions"),V(".row-actions").not(this).removeClass("visible"),a.addClass("visible")},focusout:function(){n=setTimeout(function(){a.removeClass("visible")},30)}},".has-row-actions"),V("tbody").on("click",".toggle-row",function(){V(this).closest("tr").toggleClass("is-expanded")}),V("#default-password-nag-no").click(function(){return setUserSetting("default_password_nag","hide"),V("div.default-password-nag").hide(),!1}),V("#newcontent").bind("keydown.wpevent_InsertTab",function(e){var n,t,i,o,s=e.target;if(27==e.keyCode)return e.preventDefault(),void V(s).data("tab-out",!0);9!=e.keyCode||e.ctrlKey||e.altKey||e.shiftKey||(V(s).data("tab-out")?V(s).data("tab-out",!1):(n=s.selectionStart,t=s.selectionEnd,i=s.value,document.selection?(s.focus(),document.selection.createRange().text="\t"):0<=n&&(o=this.scrollTop,s.value=i.substring(0,n).concat("\t",i.substring(t)),s.selectionStart=s.selectionEnd=n+1,this.scrollTop=o),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()))}),u.length&&u.closest("form").submit(function(){-1==V('select[name="action"]').val()&&-1==V('select[name="action2"]').val()&&u.val()==p&&u.val("1")}),V('.search-box input[type="search"], .search-box input[type="submit"]').mousedown(function(){V('select[name^="action"]').val("-1")}),V("#contextual-help-link, #show-settings-link").on("focus.scroll-into-view",function(e){e.target.scrollIntoView&&e.target.scrollIntoView(!1)}),(U=V("form.wp-upload-form")).length&&(c=U.find('input[type="submit"]'),l=U.find('input[type="file"]'),N(),l.on("change",N)),f||(H.on("scroll.pin-menu",O),B.on("tinymce-editor-init.pin-menu",function(e,n){n.on("wp-autoresize",P)})),q.wpResponsive={init:function(){var e=this;B.on("wp-responsive-activate.wp-responsive",function(){e.activate()}).on("wp-responsive-deactivate.wp-responsive",function(){e.deactivate()}),V("#wp-admin-bar-menu-toggle a").attr("aria-expanded","false"),V("#wp-admin-bar-menu-toggle").on("click.wp-responsive",function(e){e.preventDefault(),S.find(".hover").removeClass("hover"),w.toggleClass("wp-responsive-open"),w.hasClass("wp-responsive-open")?(V(this).find("a").attr("aria-expanded","true"),V("#adminmenu a:first").focus()):V(this).find("a").attr("aria-expanded","false")}),g.on("click.wp-responsive","li.wp-has-submenu > a",function(e){g.data("wp-responsive")&&(V(this).parent("li").toggleClass("selected"),e.preventDefault())}),e.trigger(),B.on("wp-window-resized.wp-responsive",V.proxy(this.trigger,this)),H.on("load.wp-responsive",function(){(-1<navigator.userAgent.indexOf("AppleWebKit/")?H.width():q.innerWidth)<=782&&e.disableSortables()})},activate:function(){L(),Q.hasClass("auto-fold")||Q.addClass("auto-fold"),g.data("wp-responsive",1),this.disableSortables()},deactivate:function(){L(),g.removeData("wp-responsive"),this.enableSortables()},trigger:function(){var e=R();e&&(e<=782?y||(B.trigger("wp-responsive-activate"),y=!0):y&&(B.trigger("wp-responsive-deactivate"),y=!1),e<=480?this.enableOverlay():this.disableOverlay())},enableOverlay:function(){0===b.length&&(b=V('<div id="wp-responsive-overlay"></div>').insertAfter("#wpcontent").hide().on("click.wp-responsive",function(){k.find(".menupop.hover").removeClass("hover"),V(this).hide()})),C.on("click.wp-responsive",function(){b.show()})},disableOverlay:function(){C.off("click.wp-responsive"),b.hide()},disableSortables:function(){if(x.length)try{x.sortable("disable")}catch(e){}},enableSortables:function(){if(x.length)try{x.sortable("enable")}catch(e){}}},V(document).ajaxComplete(function(){F()}),B.on("wp-window-resized.set-menu-state",_),B.on("wp-menu-state-set wp-collapse-menu",function(e,n){var t=V("#collapse-button"),i="true",o=commonL10n.collapseMenu;"folded"===n.state&&(i="false",o=commonL10n.expandMenu),t.attr({"aria-expanded":i,"aria-label":o})}),q.wpResponsive.init(),L(),_(),j(),z(),F(),B.on("wp-pin-menu wp-window-resized.pin-menu postboxes-columnchange.pin-menu postbox-toggled.pin-menu wp-collapse-menu.pin-menu wp-scroll-start.pin-menu",L),V(".wp-initial-focus").focus()}),H.on("resize.wp-fire-once",function(){q.clearTimeout(e),e=q.setTimeout(t,200)}),"-ms-user-select"in document.documentElement.style&&navigator.userAgent.match(/IEMobile\/10\.0/)&&((n=document.createElement("style")).appendChild(document.createTextNode("@-ms-viewport{width:auto!important}")),document.getElementsByTagName("head")[0].appendChild(n))}(jQuery,window); media.js 0000666 00000005637 15213733063 0006203 0 ustar 00 /* global ajaxurl, attachMediaBoxL10n, _wpMediaGridSettings, showNotice */ var findPosts; ( function( $ ){ findPosts = { open: function( af_name, af_val ) { var overlay = $( '.ui-find-overlay' ); if ( overlay.length === 0 ) { $( 'body' ).append( '<div class="ui-find-overlay"></div>' ); findPosts.overlay(); } overlay.show(); if ( af_name && af_val ) { $( '#affected' ).attr( 'name', af_name ).val( af_val ); } $( '#find-posts' ).show(); $('#find-posts-input').focus().keyup( function( event ){ if ( event.which == 27 ) { findPosts.close(); } // close on Escape }); // Pull some results up by default findPosts.send(); return false; }, close: function() { $('#find-posts-response').empty(); $('#find-posts').hide(); $( '.ui-find-overlay' ).hide(); }, overlay: function() { $( '.ui-find-overlay' ).on( 'click', function () { findPosts.close(); }); }, send: function() { var post = { ps: $( '#find-posts-input' ).val(), action: 'find_posts', _ajax_nonce: $('#_ajax_nonce').val() }, spinner = $( '.find-box-search .spinner' ); spinner.addClass( 'is-active' ); $.ajax( ajaxurl, { type: 'POST', data: post, dataType: 'json' }).always( function() { spinner.removeClass( 'is-active' ); }).done( function( x ) { if ( ! x.success ) { $( '#find-posts-response' ).text( attachMediaBoxL10n.error ); } $( '#find-posts-response' ).html( x.data ); }).fail( function() { $( '#find-posts-response' ).text( attachMediaBoxL10n.error ); }); } }; $( document ).ready( function() { var settings, $mediaGridWrap = $( '#wp-media-grid' ); // Open up a manage media frame into the grid. if ( $mediaGridWrap.length && window.wp && window.wp.media ) { settings = _wpMediaGridSettings; window.wp.media({ frame: 'manage', container: $mediaGridWrap, library: settings.queryVars }).open(); } $( '#find-posts-submit' ).click( function( event ) { if ( ! $( '#find-posts-response input[type="radio"]:checked' ).length ) event.preventDefault(); }); $( '#find-posts .find-box-search :input' ).keypress( function( event ) { if ( 13 == event.which ) { findPosts.send(); return false; } }); $( '#find-posts-search' ).click( findPosts.send ); $( '#find-posts-close' ).click( findPosts.close ); $( '#doaction, #doaction2' ).click( function( event ) { $( 'select[name^="action"]' ).each( function() { var optionValue = $( this ).val(); if ( 'attach' === optionValue ) { event.preventDefault(); findPosts.open(); } else if ( 'delete' === optionValue ) { if ( ! showNotice.warn() ) { event.preventDefault(); } } }); }); // Enable whole row to be clicked $( '.find-box-inside' ).on( 'click', 'tr', function() { $( this ).find( '.found-radio input' ).prop( 'checked', true ); }); }); })( jQuery ); gallery.min.js 0000666 00000007264 15213733063 0007343 0 ustar 00 jQuery(document).ready(function(n){var l=!1,e=function(){n("#media-items").sortable({items:"div.media-item",placeholder:"sorthelper",axis:"y",distance:2,handle:"div.filename",stop:function(){var e=n("#media-items").sortable("toArray"),i=e.length;n.each(e,function(e,t){e=l?i-e:1+e;n("#"+t+" .menu_order input").val(e)})}})},t=function(){var e=n(".menu_order_input"),t=e.length;e.each(function(e){e=l?t-e:1+e;n(this).val(e)})},i=function(e){e=e||0,n(".menu_order_input").each(function(){"0"!==this.value&&!e||(this.value="")})};n("#asc").click(function(e){e.preventDefault(),l=!1,t()}),n("#desc").click(function(e){e.preventDefault(),l=!0,t()}),n("#clear").click(function(e){e.preventDefault(),i(1)}),n("#showall").click(function(e){e.preventDefault(),n("#sort-buttons span a").toggle(),n("a.describe-toggle-on").hide(),n("a.describe-toggle-off, table.slidetoggle").show(),n("img.pinkynail").toggle(!1)}),n("#hideall").click(function(e){e.preventDefault(),n("#sort-buttons span a").toggle(),n("a.describe-toggle-on").show(),n("a.describe-toggle-off, table.slidetoggle").hide(),n("img.pinkynail").toggle(!0)}),e(),i(),1<n("#media-items>*").length&&(e=wpgallery.getWin(),n("#save-all, #gallery-settings").show(),void 0!==e.tinyMCE&&e.tinyMCE.activeEditor&&!e.tinyMCE.activeEditor.isHidden()?(wpgallery.mcemode=!0,wpgallery.init()):n("#insert-gallery").show())}),jQuery(window).unload(function(){tinymce=tinyMCE=wpgallery=null});var tinyMCE,tinymce=null,wpgallery={mcemode:!1,editor:{},dom:{},is_update:!1,el:{},I:function(e){return document.getElementById(e)},init:function(){var e,t,i,n,l=this,o=l.getWin();if(l.mcemode){for(e=(""+document.location.search).replace(/^\?/,"").split("&"),t={},i=0;i<e.length;i++)n=e[i].split("="),t[unescape(n[0])]=unescape(n[1]);t.mce_rdomain&&(document.domain=t.mce_rdomain),tinymce=o.tinymce,tinyMCE=o.tinyMCE,l.editor=tinymce.EditorManager.activeEditor,l.setup()}},getWin:function(){return window.dialogArguments||opener||parent||top},setup:function(){var e,t,i,n=this,l=n.editor;if(n.mcemode){if(n.el=l.selection.getNode(),"IMG"!==n.el.nodeName||!l.dom.hasClass(n.el,"wpGallery")){if(!(t=l.dom.select("img.wpGallery"))||!t[0])return"1"===getUserSetting("galfile")&&(n.I("linkto-file").checked="checked"),"1"===getUserSetting("galdesc")&&(n.I("order-desc").checked="checked"),getUserSetting("galcols")&&(n.I("columns").value=getUserSetting("galcols")),getUserSetting("galord")&&(n.I("orderby").value=getUserSetting("galord")),void jQuery("#insert-gallery").show();n.el=t[0]}i=l.dom.getAttrib(n.el,"title"),(i=l.dom.decode(i))?(jQuery("#update-gallery").show(),n.is_update=!0,e=i.match(/columns=['"]([0-9]+)['"]/),t=i.match(/link=['"]([^'"]+)['"]/i),l=i.match(/order=['"]([^'"]+)['"]/i),i=i.match(/orderby=['"]([^'"]+)['"]/i),t&&t[1]&&(n.I("linkto-file").checked="checked"),l&&l[1]&&(n.I("order-desc").checked="checked"),e&&e[1]&&(n.I("columns").value=""+e[1]),i&&i[1]&&(n.I("orderby").value=i[1])):jQuery("#insert-gallery").show()}},update:function(){var e,t=this,i=t.editor,n="";if(!t.mcemode||!t.is_update)return e="[gallery"+t.getSettings()+"]",void t.getWin().send_to_editor(e);"IMG"===t.el.nodeName&&(n=(n=i.dom.decode(i.dom.getAttrib(t.el,"title"))).replace(/\s*(order|link|columns|orderby)=['"]([^'"]+)['"]/gi,""),n+=t.getSettings(),i.dom.setAttrib(t.el,"title",n),t.getWin().tb_remove())},getSettings:function(){var e=this.I,t="";return e("linkto-file").checked&&(t+=' link="file"',setUserSetting("galfile","1")),e("order-desc").checked&&(t+=' order="DESC"',setUserSetting("galdesc","1")),3!==e("columns").value&&(t+=' columns="'+e("columns").value+'"',setUserSetting("galcols",e("columns").value)),"menu_order"!==e("orderby").value&&(t+=' orderby="'+e("orderby").value+'"',setUserSetting("galord",e("orderby").value)),t}}; postbox.min.js 0000666 00000010067 15213733063 0007375 0 ustar 00 var postboxes;!function(a){var n=a(document);postboxes={handle_click:function(){var e,o=a(this),s=o.parent(".postbox"),t=s.attr("id");"dashboard_browser_nag"!==t&&(s.toggleClass("closed"),e=!s.hasClass("closed"),(o.hasClass("handlediv")?o:o.closest(".postbox").find("button.handlediv")).attr("aria-expanded",e),"press-this"!==postboxes.page&&postboxes.save_state(postboxes.page),t&&(!s.hasClass("closed")&&a.isFunction(postboxes.pbshow)?postboxes.pbshow(t):s.hasClass("closed")&&a.isFunction(postboxes.pbhide)&&postboxes.pbhide(t)),n.trigger("postbox-toggled",s))},add_postbox_toggles:function(t,e){var o=a(".postbox .hndle, .postbox .handlediv");this.page=t,this.init(t,e),o.on("click.postboxes",this.handle_click),a(".postbox .hndle a").click(function(e){e.stopPropagation()}),a(".postbox a.dismiss").on("click.postboxes",function(e){var o=a(this).parents(".postbox").attr("id")+"-hide";e.preventDefault(),a("#"+o).prop("checked",!1).triggerHandler("click")}),a(".hide-postbox-tog").bind("click.postboxes",function(){var e=a(this),o=e.val(),s=a("#"+o);e.prop("checked")?(s.show(),a.isFunction(postboxes.pbshow)&&postboxes.pbshow(o)):(s.hide(),a.isFunction(postboxes.pbhide)&&postboxes.pbhide(o)),postboxes.save_state(t),postboxes._mark_area(),n.trigger("postbox-toggled",s)}),a('.columns-prefs input[type="radio"]').bind("click.postboxes",function(){var e=parseInt(a(this).val(),10);e&&(postboxes._pb_edit(e),postboxes.save_order(t))})},init:function(o,e){var s=a(document.body).hasClass("mobile"),t=a(".postbox .handlediv");a.extend(this,e||{}),a("#wpbody-content").css("overflow","hidden"),a(".meta-box-sortables").sortable({placeholder:"sortable-placeholder",connectWith:".meta-box-sortables",items:".postbox",handle:".hndle",cursor:"move",delay:s?200:0,distance:2,tolerance:"pointer",forcePlaceholderSize:!0,helper:function(e,o){return o.clone().find(":input").attr("name",function(e,o){return"sort_"+parseInt(1e5*Math.random(),10).toString()+"_"+o}).end()},opacity:.65,stop:function(){var e=a(this);e.find("#dashboard_browser_nag").is(":visible")&&"dashboard_browser_nag"!=this.firstChild.id?e.sortable("cancel"):postboxes.save_order(o)},receive:function(e,o){"dashboard_browser_nag"==o.item[0].id&&a(o.sender).sortable("cancel"),postboxes._mark_area(),n.trigger("postbox-moved",o.item)}}),s&&(a(document.body).bind("orientationchange.postboxes",function(){postboxes._pb_change()}),this._pb_change()),this._mark_area(),t.each(function(){var e=a(this);e.attr("aria-expanded",!e.parent(".postbox").hasClass("closed"))})},save_state:function(e){var o,s;"nav-menus"!==e&&(o=a(".postbox").filter(".closed").map(function(){return this.id}).get().join(","),s=a(".postbox").filter(":hidden").map(function(){return this.id}).get().join(","),a.post(ajaxurl,{action:"closed-postboxes",closed:o,hidden:s,closedpostboxesnonce:jQuery("#closedpostboxesnonce").val(),page:e}))},save_order:function(e){var o=a(".columns-prefs input:checked").val()||0,s={action:"meta-box-order",_ajax_nonce:a("#meta-box-order-nonce").val(),page_columns:o,page:e};a(".meta-box-sortables").each(function(){s["order["+this.id.split("-")[0]+"]"]=a(this).sortable("toArray").join(",")}),a.post(ajaxurl,s)},_mark_area:function(){var o=a("div.postbox:visible").length,e=a("#post-body #side-sortables");a("#dashboard-widgets .meta-box-sortables:visible").each(function(){var e=a(this);1==o||e.children(".postbox:visible").length?e.removeClass("empty-container"):(e.addClass("empty-container"),e.attr("data-emptyString",postBoxL10n.postBoxEmptyString))}),e.length&&(e.children(".postbox:visible").length?e.removeClass("empty-container"):"280px"==a("#postbox-container-1").css("width")&&e.addClass("empty-container"))},_pb_edit:function(e){var o=a(".metabox-holder").get(0);o&&(o.className=o.className.replace(/columns-\d+/,"columns-"+e)),a(document).trigger("postboxes-columnchange")},_pb_change:function(){var e=a('label.columns-prefs-1 input[type="radio"]');switch(window.orientation){case 90:case-90:e.length&&e.is(":checked")||this._pb_edit(2);break;case 0:case 180:a("#poststuff").length?this._pb_edit(1):e.length&&e.is(":checked")||this._pb_edit(2)}},pbshow:!1,pbhide:!1}}(jQuery); customize-nav-menus.min.js 0000666 00000124770 15213733063 0011637 0 ustar 00 !function(u,c,l){"use strict";function m(e){return e=e||"",e=l("<div>").text(e).html(),(e=l.trim(e))||u.Menus.data.l10n.unnamed}wpNavMenu.originalInit=wpNavMenu.init,wpNavMenu.options.menuItemDepthPerLevel=20,wpNavMenu.options.sortableItems="> .customize-control-nav_menu_item",wpNavMenu.options.targetTolerance=10,wpNavMenu.init=function(){this.jQueryExtensions()},u.Menus=u.Menus||{},u.Menus.data={itemTypes:[],l10n:{},settingTransport:"refresh",phpIntMax:0,defaultSettingValues:{nav_menu:{},nav_menu_item:{}},locationSlugMappedToName:{}},"undefined"!=typeof _wpCustomizeNavMenusSettings&&l.extend(u.Menus.data,_wpCustomizeNavMenusSettings),u.Menus.generatePlaceholderAutoIncrementId=function(){return-Math.ceil(u.Menus.data.phpIntMax*Math.random())},u.Menus.AvailableItemModel=Backbone.Model.extend(l.extend({id:null},u.Menus.data.defaultSettingValues.nav_menu_item)),u.Menus.AvailableItemCollection=Backbone.Collection.extend({model:u.Menus.AvailableItemModel,sort_key:"order",comparator:function(e){return-e.get(this.sort_key)},sortByField:function(e){this.sort_key=e,this.sort()}}),u.Menus.availableMenuItems=new u.Menus.AvailableItemCollection(u.Menus.data.availableMenuItems),u.Menus.insertAutoDraftPost=function(n){var i=l.Deferred(),e=c.ajax.post("customize-nav-menus-insert-auto-draft",{"customize-menus-nonce":u.settings.nonce["customize-menus"],wp_customize:"on",params:n});return e.done(function(t){t.post_id&&(u("nav_menus_created_posts").set(u("nav_menus_created_posts").get().concat([t.post_id])),"page"===n.post_type&&(u.section.has("static_front_page")&&u.section("static_front_page").activate(),u.control.each(function(e){"dropdown-pages"===e.params.type&&e.container.find('select[name^="_customize-dropdown-pages-"]').append(new Option(n.post_title,t.post_id))})),i.resolve(t))}),e.fail(function(e){var t=e||"";void 0!==e.message&&(t=e.message),console.error(t),i.rejectWith(t)}),i.promise()},u.Menus.AvailableMenuItemsPanelView=c.Backbone.View.extend({el:"#available-menu-items",events:{"input #menu-items-search":"debounceSearch","keyup #menu-items-search":"debounceSearch","focus .menu-item-tpl":"focus","click .menu-item-tpl":"_submit","click #custom-menu-item-submit":"_submitLink","keypress #custom-menu-item-name":"_submitLink","click .new-content-item .add-content":"_submitNew","keypress .create-item-input":"_submitNew",keydown:"keyboardAccessible"},selected:null,currentMenuControl:null,debounceSearch:null,$search:null,$clearResults:null,searchTerm:"",rendered:!1,pages:{},sectionContent:"",loading:!1,addingNew:!1,initialize:function(){var n=this;u.panel.has("nav_menus")&&(this.$search=l("#menu-items-search"),this.$clearResults=this.$el.find(".clear-results"),this.sectionContent=this.$el.find(".available-menu-items-list"),this.debounceSearch=_.debounce(n.search,500),_.bindAll(this,"close"),l("#customize-controls, .customize-section-back").on("click keydown",function(e){var t=l(e.target).is(".item-delete, .item-delete *"),e=l(e.target).is(".add-new-menu-item, .add-new-menu-item *");!l("body").hasClass("adding-menu-items")||t||e||n.close()}),this.$clearResults.on("click",function(){n.$search.val("").focus().trigger("keyup")}),this.$el.on("input","#custom-menu-item-name.invalid, #custom-menu-item-url.invalid",function(){l(this).removeClass("invalid")}),u.panel("nav_menus").container.bind("expanded",function(){n.rendered||(n.initList(),n.rendered=!0)}),this.sectionContent.scroll(function(){var e=n.$el.find(".accordion-section.open .available-menu-items-list").prop("scrollHeight"),t=n.$el.find(".accordion-section.open").height();!n.loading&&l(this).scrollTop()>.75*e-t&&(e=l(this).data("type"),t=l(this).data("object"),"search"===e?n.searchTerm&&n.doSearch(n.pages.search):n.loadItems([{type:e,object:t}]))}),u.previewer.bind("url",this.close),n.delegateEvents())},search:function(e){var t=l("#available-menu-items-search"),n=l("#available-menu-items .accordion-section").not(t);e&&this.searchTerm!==e.target.value&&(""===e.target.value||t.hasClass("open")?""===e.target.value&&(t.removeClass("open"),n.show(),this.$clearResults.removeClass("is-visible")):(n.fadeOut(100),t.find(".accordion-section-content").slideDown("fast"),t.addClass("open"),this.$clearResults.addClass("is-visible")),this.searchTerm=e.target.value,this.pages.search=1,this.doSearch(1))},doSearch:function(t){var e,n=this,i=l("#available-menu-items-search"),a=i.find(".accordion-section-content"),o=c.template("available-menu-item");if(n.currentRequest&&n.currentRequest.abort(),!(t<0)){if(1<t)i.addClass("loading-more"),a.attr("aria-busy","true"),c.a11y.speak(u.Menus.data.l10n.itemsLoadingMore);else if(""===n.searchTerm)return a.html(""),void c.a11y.speak("");i.addClass("loading"),n.loading=!0,e=u.previewer.query({excludeCustomizedSaved:!0}),_.extend(e,{"customize-menus-nonce":u.settings.nonce["customize-menus"],wp_customize:"on",search:n.searchTerm,page:t}),n.currentRequest=c.ajax.post("search-available-menu-items-customizer",e),n.currentRequest.done(function(e){1===t&&a.empty(),i.removeClass("loading loading-more"),a.attr("aria-busy","false"),i.addClass("open"),n.loading=!1,e=new u.Menus.AvailableItemCollection(e.items),n.collection.add(e.models),e.each(function(e){a.append(o(e.attributes))}),e.length<20?n.pages.search=-1:n.pages.search=n.pages.search+1,e&&1<t?c.a11y.speak(u.Menus.data.l10n.itemsFoundMore.replace("%d",e.length)):e&&1===t&&c.a11y.speak(u.Menus.data.l10n.itemsFound.replace("%d",e.length))}),n.currentRequest.fail(function(e){e.message&&(a.empty().append(l('<li class="nothing-found"></li>').text(e.message)),c.a11y.speak(e.message)),n.pages.search=-1}),n.currentRequest.always(function(){i.removeClass("loading loading-more"),a.attr("aria-busy","false"),n.loading=!1,n.currentRequest=null})}},initList:function(){var t=this;_.each(u.Menus.data.itemTypes,function(e){t.pages[e.type+":"+e.object]=0}),t.loadItems(u.Menus.data.itemTypes)},loadItems:function(e,t){var i=this,a=[],o={},s=c.template("available-menu-item"),e=_.isString(e)&&_.isString(t)?[{type:e,object:t}]:e;_.each(e,function(e){var t,n=e.type+":"+e.object;-1!==i.pages[n]&&((t=l("#available-menu-items-"+e.type+"-"+e.object)).find(".accordion-section-title").addClass("loading"),o[n]=t,a.push({object:e.object,type:e.type,page:i.pages[n]}))}),0!==a.length&&(i.loading=!0,e=u.previewer.query({excludeCustomizedSaved:!0}),_.extend(e,{"customize-menus-nonce":u.settings.nonce["customize-menus"],wp_customize:"on",item_types:a}),(e=c.ajax.post("load-available-menu-items-customizer",e)).done(function(e){var n;_.each(e.items,function(e,t){return 0===e.length?(0===i.pages[t]&&o[t].find(".accordion-section-title").addClass("cannot-expand").removeClass("loading").find(".accordion-section-title > button").prop("tabIndex",-1),void(i.pages[t]=-1)):("post_type:page"!==t||o[t].hasClass("open")||o[t].find(".accordion-section-title > button").click(),e=new u.Menus.AvailableItemCollection(e),i.collection.add(e.models),n=o[t].find(".available-menu-items-list"),e.each(function(e){n.append(s(e.attributes))}),void(i.pages[t]+=1))})}),e.fail(function(e){"undefined"!=typeof console&&console.error&&console.error(e)}),e.always(function(){_.each(o,function(e){e.find(".accordion-section-title").removeClass("loading")}),i.loading=!1}))},itemSectionHeight:function(){var e=window.innerHeight,t=this.$el.find(".accordion-section:not( #available-menu-items-search ) .accordion-section-content"),n=this.$el.find('.accordion-section:not( #available-menu-items-search ) .available-menu-items-list:not(":only-child")'),e=e-(46*(1+t.length)+14);120<e&&e<290&&(t.css("max-height",e),n.css("max-height",e-60))},select:function(e){this.selected=l(e),this.selected.siblings(".menu-item-tpl").removeClass("selected"),this.selected.addClass("selected")},focus:function(e){this.select(l(e.currentTarget))},_submit:function(e){"keypress"===e.type&&13!==e.which&&32!==e.which||this.submit(l(e.currentTarget))},submit:function(e){var t;(e=e||this.selected)&&this.currentMenuControl&&(this.select(e),t=l(this.selected).data("menu-item-id"),(t=this.collection.findWhere({id:t}))&&((t=Object.assign({},t.attributes)).title===t.original_title&&(t.title=""),this.currentMenuControl.addItemToMenu(t),l(e).find(".menu-item-handle").addClass("item-added")))},_submitLink:function(e){"keypress"===e.type&&13!==e.which||this.submitLink()},submitLink:function(){var e,t=l("#custom-menu-item-name"),n=l("#custom-menu-item-url");this.currentMenuControl&&(""!==t.val()?""!==n.val()&&"http://"!==n.val()?(e={title:t.val(),url:n.val(),type:"custom",type_label:u.Menus.data.l10n.custom_label,object:"custom"},this.currentMenuControl.addItemToMenu(e),n.val("http://"),t.val("")):n.addClass("invalid"):t.addClass("invalid"))},_submitNew:function(e){"keypress"===e.type&&13!==e.which||this.addingNew||(e=l(e.target).closest(".accordion-section"),this.submitNew(e))},submitNew:function(n){var i=this,a=n.find(".create-item-input"),e=a.val(),t=n.find(".available-menu-items-list"),o=t.data("type"),s=t.data("object"),r=t.data("type_label");if(this.currentMenuControl&&"post_type"===o){if(""===l.trim(a.val()))return a.addClass("invalid"),void a.focus();a.removeClass("invalid"),n.find(".accordion-section-title").addClass("loading"),i.addingNew=!0,a.attr("disabled","disabled"),u.Menus.insertAutoDraftPost({post_title:e,post_type:s}).done(function(e){var t=new u.Menus.AvailableItemModel({id:"post-"+e.post_id,title:a.val(),type:o,type_label:r,object:s,object_id:e.post_id,url:e.url});i.currentMenuControl.addItemToMenu(t.attributes),u.Menus.availableMenuItemsPanel.collection.add(t),e=n.find(".available-menu-items-list"),(t=l(c.template("available-menu-item")(t.attributes))).find(".menu-item-handle:first").addClass("item-added"),e.prepend(t),e.scrollTop(),a.val("").removeAttr("disabled"),i.addingNew=!1,n.find(".accordion-section-title").removeClass("loading")})}},open:function(e){this.currentMenuControl=e,this.itemSectionHeight(),l("body").addClass("adding-menu-items"),_(this.currentMenuControl.getMenuItemControls()).each(function(e){e.collapseForm()}),this.$el.find(".selected").removeClass("selected"),this.$search.focus()},close:function(e){(e=e||{}).returnFocus&&this.currentMenuControl&&this.currentMenuControl.container.find(".add-new-menu-item").focus(),this.currentMenuControl=null,this.selected=null,l("body").removeClass("adding-menu-items"),l("#available-menu-items .menu-item-handle.item-added").removeClass("item-added"),this.$search.val("")},keyboardAccessible:function(e){var t=13===e.which,n=27===e.which,i=9===e.which&&e.shiftKey,a=l(e.target).is(this.$search);t&&!this.$search.val()||(a&&i?(this.currentMenuControl.container.find(".add-new-menu-item").focus(),e.preventDefault()):n&&this.close({returnFocus:!0}))}}),u.Menus.MenusPanel=u.Panel.extend({attachEvents:function(){u.Panel.prototype.attachEvents.call(this);var t=this.container.find(".panel-meta"),n=t.find(".customize-help-toggle"),i=t.find(".customize-panel-description"),a=l("#screen-options-wrap"),o=t.find(".customize-screen-options-toggle");o.on("click keydown",function(e){if(!u.utils.isKeydownButNotEnterEvent(e))return e.preventDefault(),i.not(":hidden")&&(i.slideUp("fast"),n.attr("aria-expanded","false")),"true"===o.attr("aria-expanded")?(o.attr("aria-expanded","false"),t.removeClass("open"),t.removeClass("active-menu-screen-options"),a.slideUp("fast")):(o.attr("aria-expanded","true"),t.addClass("open"),t.addClass("active-menu-screen-options"),a.slideDown("fast")),!1}),n.on("click keydown",function(e){u.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),"true"===o.attr("aria-expanded")&&(o.attr("aria-expanded","false"),n.attr("aria-expanded","true"),t.addClass("open"),t.removeClass("active-menu-screen-options"),a.slideUp("fast"),i.slideDown("fast")))})},ready:function(){var e=this;e.container.find(".hide-column-tog").click(function(){e.saveManageColumnsState()})},saveManageColumnsState:_.debounce(function(){var e=this;e._updateHiddenColumnsRequest&&e._updateHiddenColumnsRequest.abort(),e._updateHiddenColumnsRequest=c.ajax.post("hidden-columns",{hidden:e.hidden(),screenoptionnonce:l("#screenoptionnonce").val(),page:"nav-menus"}),e._updateHiddenColumnsRequest.always(function(){e._updateHiddenColumnsRequest=null})},2e3),checked:function(){},unchecked:function(){},hidden:function(){return l(".hide-column-tog").not(":checked").map(function(){var e=this.id;return e.substring(0,e.length-5)}).get().join(",")}}),u.Menus.MenuSection=u.Section.extend({initialize:function(e,t){u.Section.prototype.initialize.call(this,e,t),this.deferred.initSortables=l.Deferred()},ready:function(){var e,t,n=this;if(void 0===n.params.menu_id)throw new Error("params.menu_id was not defined");n.active.validate=function(){return!!u.has(n.id)&&!!u(n.id).get()},n.populateControls(),n.navMenuLocationSettings={},n.assignedLocations=new u.Value([]),u.each(function(e,t){t=t.match(/^nav_menu_locations\[(.+?)]/);t&&(n.navMenuLocationSettings[t[1]]=e).bind(function(){n.refreshAssignedLocations()})}),n.assignedLocations.bind(function(e){n.updateAssignedLocationsInSectionTitle(e)}),n.refreshAssignedLocations(),u.bind("pane-contents-reflowed",function(){n.contentContainer.parent().length&&(n.container.find(".menu-item .menu-item-reorder-nav button").attr({tabindex:"0","aria-hidden":"false"}),n.container.find(".menu-item.move-up-disabled .menus-move-up").attr({tabindex:"-1","aria-hidden":"true"}),n.container.find(".menu-item.move-down-disabled .menus-move-down").attr({tabindex:"-1","aria-hidden":"true"}),n.container.find(".menu-item.move-left-disabled .menus-move-left").attr({tabindex:"-1","aria-hidden":"true"}),n.container.find(".menu-item.move-right-disabled .menus-move-right").attr({tabindex:"-1","aria-hidden":"true"}))}),t=function(){var e="field-"+l(this).val()+"-active";n.contentContainer.toggleClass(e,l(this).prop("checked"))},(e=u.panel("nav_menus").contentContainer.find(".metabox-prefs:first").find(".hide-column-tog")).each(t),e.on("click",t)},populateControls:function(){var e=this,t=e.id+"[name]",n=u.control(t);n||(n=new u.controlConstructor.nav_menu_name(t,{params:{type:"nav_menu_name",content:'<li id="customize-control-'+e.id.replace("[","-").replace("]","")+'-name" class="customize-control customize-control-nav_menu_name"></li>',label:u.Menus.data.l10n.menuNameLabel,active:!0,section:e.id,priority:0,settings:{"default":e.id}}}),u.control.add(n.id,n),n.active.set(!0)),(t=u.control(e.id))||(t=new u.controlConstructor.nav_menu(e.id,{params:{type:"nav_menu",content:'<li id="customize-control-'+e.id.replace("[","-").replace("]","")+'" class="customize-control customize-control-nav_menu"></li>',section:e.id,priority:998,active:!0,settings:{"default":e.id},menu_id:e.params.menu_id}}),u.control.add(t.id,t),t.active.set(!0)),n=e.id+"[auto_add]",(t=u.control(n))||(t=new u.controlConstructor.nav_menu_auto_add(n,{params:{type:"nav_menu_auto_add",content:'<li id="customize-control-'+e.id.replace("[","-").replace("]","")+'-auto-add" class="customize-control customize-control-nav_menu_auto_add"></li>',label:"",active:!0,section:e.id,priority:999,settings:{"default":e.id}}}),u.control.add(t.id,t),t.active.set(!0))},refreshAssignedLocations:function(){var n=this.params.menu_id,i=[];_.each(this.navMenuLocationSettings,function(e,t){e()===n&&i.push(t)}),this.assignedLocations.set(i)},updateAssignedLocationsInSectionTitle:function(e){var n=this.container.find(".accordion-section-title:first");n.find(".menu-in-location").remove(),_.each(e,function(e){var t=l('<span class="menu-in-location"></span>'),e=u.Menus.data.locationSlugMappedToName[e];t.text(u.Menus.data.l10n.menuLocation.replace("%s",e)),n.append(t)}),this.container.toggleClass("assigned-to-menu-location",0!==e.length)},onChangeExpanded:function(e,t){var n,i=this;e&&(wpNavMenu.menuList=i.contentContainer,wpNavMenu.targetList=wpNavMenu.menuList,l("#menu-to-edit").removeAttr("id"),wpNavMenu.menuList.attr("id","menu-to-edit").addClass("menu"),_.each(u.section(i.id).controls(),function(e){"nav_menu_item"===e.params.type&&e.actuallyEmbed()}),t.completeCallback&&(n=t.completeCallback),t.completeCallback=function(){"resolved"!==i.deferred.initSortables.state()&&(wpNavMenu.initSortables(),i.deferred.initSortables.resolve(wpNavMenu.menuList),u.control("nav_menu["+String(i.params.menu_id)+"]").reflowMenuItems()),_.isFunction(n)&&n()}),u.Section.prototype.onChangeExpanded.call(i,e,t)}}),u.Menus.NewMenuSection=u.Section.extend({attachEvents:function(){var e=this;this.container.on("click",".add-menu-toggle",function(){e.expanded()?e.collapse():e.expand()})},onChangeExpanded:function(e){var t=this.container.find(".add-menu-toggle"),n=this.contentContainer,i=this.headContainer.closest(".wp-full-overlay-sidebar-content");e?(t.addClass("open"),t.attr("aria-expanded","true"),n.slideDown("fast",function(){i.scrollTop(i.height())})):(t.removeClass("open"),t.attr("aria-expanded","false"),n.slideUp("fast"),n.find(".menu-name-field").removeClass("invalid"))},getContent:function(){return this.container.find("ul:first")}}),u.Menus.MenuLocationControl=u.Control.extend({initialize:function(e,t){var n=e.match(/^nav_menu_locations\[(.+?)]/);this.themeLocation=n[1],u.Control.prototype.initialize.call(this,e,t)},ready:function(){var n=this,i=/^nav_menu\[(-?\d+)]/;n.setting.validate=function(e){return""===e?0:parseInt(e,10)},n.container.find(".edit-menu").on("click",function(){var e=n.setting();u.section("nav_menu["+e+"]").focus()}),n.setting.bind("change",function(){0===n.setting()?n.container.find(".edit-menu").addClass("hidden"):n.container.find(".edit-menu").removeClass("hidden")}),u.bind("add",function(e){var t=e.id.match(i);t&&!1!==e()&&(t=t[1],t=new Option(m(e().name),t),n.container.find("select").append(t))}),u.bind("remove",function(e){var e=e.id.match(i);e&&(e=parseInt(e[1],10),n.setting()===e&&n.setting.set(""),n.container.find("option[value="+e+"]").remove())}),u.bind("change",function(e){var t=e.id.match(i);t&&(t=parseInt(t[1],10),!1===e()?(n.setting()===t&&n.setting.set(""),n.container.find("option[value="+t+"]").remove()):n.container.find("option[value="+t+"]").text(m(e().name)))})}}),u.Menus.MenuItemControl=u.Control.extend({initialize:function(e,t){var n=this;n.expanded=new u.Value(!1),n.expandedArgumentsQueue=[],n.expanded.bind(function(e){var t=n.expandedArgumentsQueue.shift(),t=l.extend({},n.defaultExpandedArguments,t);n.onChangeExpanded(e,t)}),u.Control.prototype.initialize.call(n,e,t),n.active.validate=function(){var e=u.section(n.section()),e=!!e&&e.active();return e}},embed:function(){var e=this.section();e&&((e=u.section(e))&&e.expanded()||u.settings.autofocus.control===this.id)&&this.actuallyEmbed()},actuallyEmbed:function(){"resolved"!==this.deferred.embedded.state()&&(this.renderContent(),this.deferred.embedded.resolve())},ready:function(){if(void 0===this.params.menu_item_id)throw new Error("params.menu_item_id was not defined");this._setupControlToggle(),this._setupReorderUI(),this._setupUpdateUI(),this._setupRemoveUI(),this._setupLinksUI(),this._setupTitleUI()},_setupControlToggle:function(){var i=this;this.container.find(".menu-item-handle").on("click",function(e){e.preventDefault(),e.stopPropagation();var t=i.getMenuControl(),n=l(e.target).is(".item-delete, .item-delete *"),e=l(e.target).is(".add-new-menu-item, .add-new-menu-item *");!l("body").hasClass("adding-menu-items")||n||e||u.Menus.availableMenuItemsPanel.close(),t.isReordering||t.isSorting||i.toggleForm()})},_setupReorderUI:function(){var o=this,e=c.template("menu-item-reorder-nav");o.container.find(".item-controls").after(e),o.container.find(".menu-item-reorder-nav").find(".menus-move-up, .menus-move-down, .menus-move-left, .menus-move-right").on("click",function(){var e=l(this);e.focus();var t=e.is(".menus-move-up"),n=e.is(".menus-move-down"),i=e.is(".menus-move-left"),a=e.is(".menus-move-right");t?o.moveUp():n?o.moveDown():i?o.moveLeft():a&&o.moveRight(),e.focus()})},_setupUpdateUI:function(){var s=this,e=s.setting();s.elements={},s.elements.url=new u.Element(s.container.find(".edit-menu-item-url")),s.elements.title=new u.Element(s.container.find(".edit-menu-item-title")),s.elements.attr_title=new u.Element(s.container.find(".edit-menu-item-attr-title")),s.elements.target=new u.Element(s.container.find(".edit-menu-item-target")),s.elements.classes=new u.Element(s.container.find(".edit-menu-item-classes")),s.elements.xfn=new u.Element(s.container.find(".edit-menu-item-xfn")),s.elements.description=new u.Element(s.container.find(".edit-menu-item-description")),_.each(s.elements,function(n,i){n.bind(function(e){n.element.is("input[type=checkbox]")&&(e=e?n.element.val():"");var t=s.setting();t&&t[i]!==e&&((t=_.clone(t))[i]=e,s.setting.set(t))}),e&&("classes"!==i&&"xfn"!==i||!_.isArray(e[i])?n.set(e[i]):n.set(e[i].join(" ")))}),s.setting.bind(function(n,i){var e,t=s.params.menu_item_id,a=[],o=[];!1===n?(e=u.control("nav_menu["+String(i.nav_menu_term_id)+"]"),s.container.remove(),_.each(e.getMenuItemControls(),function(e){i.menu_item_parent===e.setting().menu_item_parent&&e.setting().position>i.position?a.push(e):e.setting().menu_item_parent===t&&o.push(e)}),_.each(a,function(e){var t=_.clone(e.setting());t.position+=o.length,e.setting.set(t)}),_.each(o,function(e,t){var n=_.clone(e.setting());n.position=i.position+t,n.menu_item_parent=i.menu_item_parent,e.setting.set(n)}),e.debouncedReflowMenuItems()):(_.each(n,function(e,t){s.elements[t]&&s.elements[t].set(n[t])}),s.container.find(".menu-item-data-parent-id").val(n.menu_item_parent),n.position===i.position&&n.menu_item_parent===i.menu_item_parent||s.getMenuControl().debouncedReflowMenuItems())})},_setupRemoveUI:function(){var a=this;a.container.find(".item-delete").on("click",function(){var e,t,n,i=!0;l("body").hasClass("adding-menu-items")||(i=!1),t=a.container.nextAll(".customize-control-nav_menu_item:visible").first(),n=a.container.prevAll(".customize-control-nav_menu_item:visible").first(),e=(t.length?t.find(!1===i?".item-edit":".item-delete"):n.length?n.find(!1===i?".item-edit":".item-delete"):a.container.nextAll(".customize-control-nav_menu").find(".add-new-menu-item")).first(),a.container.slideUp(function(){a.setting.set(!1),c.a11y.speak(u.Menus.data.l10n.itemDeleted),e.focus()})})},_setupLinksUI:function(){this.container.find("a.original-link").on("click",function(e){e.preventDefault(),u.previewer.previewUrl(e.target.toString())})},_setupTitleUI:function(){var i;this.container.find(".edit-menu-item-title").on("blur",function(){l(this).val(l.trim(l(this).val()))}),i=this.container.find(".menu-item-title"),this.setting.bind(function(e){var t,n;e&&(n=(t=l.trim(e.title))||e.original_title||u.Menus.data.l10n.untitled,e._invalid&&(n=u.Menus.data.l10n.invalidTitleTpl.replace("%s",n)),t||e.original_title?i.text(n).removeClass("no-title"):i.text(n).addClass("no-title"))})},getDepth:function(){var e=this,t=e.setting(),n=0;if(!t)return 0;for(;t&&t.menu_item_parent&&(n+=1,e=u.control("nav_menu_item["+t.menu_item_parent+"]"));)t=e.setting();return n},renderContent:function(){var e,t=this,n=t.setting();t.params.title=n.title||"",t.params.depth=t.getDepth(),t.container.data("item-depth",t.params.depth),e=["menu-item","menu-item-depth-"+String(t.params.depth),"menu-item-"+n.object,"menu-item-edit-inactive"],n._invalid?(e.push("menu-item-invalid"),t.params.title=u.Menus.data.l10n.invalidTitleTpl.replace("%s",t.params.title)):"draft"===n.status&&(e.push("pending"),t.params.title=u.Menus.data.pendingTitleTpl.replace("%s",t.params.title)),t.params.el_classes=e.join(" "),t.params.item_type_label=n.type_label,t.params.item_type=n.type,t.params.url=n.url,t.params.target=n.target,t.params.attr_title=n.attr_title,t.params.classes=_.isArray(n.classes)?n.classes.join(" "):n.classes,t.params.attr_title=n.attr_title,t.params.xfn=n.xfn,t.params.description=n.description,t.params.parent=n.menu_item_parent,t.params.original_title=n.original_title||"",t.container.addClass(t.params.el_classes),u.Control.prototype.renderContent.call(t)},getMenuControl:function(){var e=this.setting();return e&&e.nav_menu_term_id?u.control("nav_menu["+e.nav_menu_term_id+"]"):null},expandControlSection:function(){var e=this.container.closest(".accordion-section");e.hasClass("open")||e.find(".accordion-section-title:first").trigger("click")},_toggleExpanded:u.Section.prototype._toggleExpanded,expand:u.Section.prototype.expand,expandForm:function(e){this.expand(e)},collapse:u.Section.prototype.collapse,collapseForm:function(e){this.collapse(e)},toggleForm:function(e,t){(e=void 0===e?!this.expanded():e)?this.expand(t):this.collapse(t)},onChangeExpanded:function(e,t){var n,i=this,a=this.container,o=a.find(".menu-item-settings:first");void 0===e&&(e=!o.is(":visible")),o.is(":visible")!==e?e?(u.control.each(function(e){i.params.type===e.params.type&&i!==e&&e.collapseForm()}),n=function(){a.removeClass("menu-item-edit-inactive").addClass("menu-item-edit-active"),i.container.trigger("expanded"),t&&t.completeCallback&&t.completeCallback()},a.find(".item-edit").attr("aria-expanded","true"),o.slideDown("fast",n),i.container.trigger("expand")):(n=function(){a.addClass("menu-item-edit-inactive").removeClass("menu-item-edit-active"),i.container.trigger("collapsed"),t&&t.completeCallback&&t.completeCallback()},i.container.trigger("collapse"),a.find(".item-edit").attr("aria-expanded","false"),o.slideUp("fast",n)):t&&t.completeCallback&&t.completeCallback()},focus:function(e){var t=this,n=(e=e||{}).completeCallback,i=function(){t.expandControlSection(),e.completeCallback=function(){t.container.find(".menu-item-settings").find("input, select, textarea, button, object, a[href], [tabindex]").filter(":visible").first().focus(),n&&n()},t.expandForm(e)};u.section.has(t.section())?u.section(t.section()).expand({completeCallback:i}):i()},moveUp:function(){this._changePosition(-1),c.a11y.speak(u.Menus.data.l10n.movedUp)},moveDown:function(){this._changePosition(1),c.a11y.speak(u.Menus.data.l10n.movedDown)},moveLeft:function(){this._changeDepth(-1),c.a11y.speak(u.Menus.data.l10n.movedLeft)},moveRight:function(){this._changeDepth(1),c.a11y.speak(u.Menus.data.l10n.movedRight)},_changePosition:function(e){var t,n=this,i=_.clone(n.setting()),a=[];if(1!==e&&-1!==e)throw new Error("Offset changes by 1 are only supported.");if(n.setting()){if(_(n.getMenuControl().getMenuItemControls()).each(function(e){e.setting().menu_item_parent===i.menu_item_parent&&a.push(e.setting)}),a.sort(function(e,t){return e().position-t().position}),-1===(t=_.indexOf(a,n.setting)))throw new Error("Expected setting to be among siblings.");0===t&&e<0||t===a.length-1&&0<e||((t=a[t+e])&&t.set(l.extend(_.clone(t()),{position:i.position})),i.position+=e,n.setting.set(i))}},_changeDepth:function(e){if(1!==e&&-1!==e)throw new Error("Offset changes by 1 are only supported.");var t,n,i=this,a=_.clone(i.setting()),o=[];if(_(i.getMenuControl().getMenuItemControls()).each(function(e){e.setting().menu_item_parent===a.menu_item_parent&&o.push(e)}),o.sort(function(e,t){return e.setting().position-t.setting().position}),-1===(t=_.indexOf(o,i)))throw new Error("Expected control to be among siblings.");-1===e?a.menu_item_parent&&(n=u.control("nav_menu_item["+a.menu_item_parent+"]"),_(o).chain().slice(t).each(function(e,t){e.setting.set(l.extend({},e.setting(),{menu_item_parent:i.params.menu_item_id,position:t}))}),_(i.getMenuControl().getMenuItemControls()).each(function(e){var t;e.setting().menu_item_parent===n.setting().menu_item_parent&&e.setting().position>n.setting().position&&(t=_.clone(e.setting()),e.setting.set(l.extend(t,{position:t.position+1})))}),a.position=n.setting().position+1,a.menu_item_parent=n.setting().menu_item_parent,i.setting.set(a)):1===e&&0!==t&&(t=o[t-1],a.menu_item_parent=t.params.menu_item_id,a.position=0,_(i.getMenuControl().getMenuItemControls()).each(function(e){e.setting().menu_item_parent===a.menu_item_parent&&(a.position=Math.max(a.position,e.setting().position))}),a.position+=1,i.setting.set(a))}}),u.Menus.MenuNameControl=u.Control.extend({ready:function(){var n=this,e=n.setting();n.active.validate=function(){var e=u.section(n.section()),e=!!e&&e.active();return e},n.nameElement=new u.Element(n.container.find(".menu-name-field")),n.nameElement.bind(function(e){var t=n.setting();t&&t.name!==e&&((t=_.clone(t)).name=e,n.setting.set(t))}),e&&n.nameElement.set(e.name),n.setting.bind(function(e){e&&n.nameElement.set(e.name)})}}),u.Menus.MenuAutoAddControl=u.Control.extend({ready:function(){var n=this,e=n.setting();n.active.validate=function(){var e=u.section(n.section()),e=!!e&&e.active();return e},n.autoAddElement=new u.Element(n.container.find("input[type=checkbox].auto_add")),n.autoAddElement.bind(function(e){var t=n.setting();t&&t.name!==e&&((t=_.clone(t)).auto_add=e,n.setting.set(t))}),e&&n.autoAddElement.set(e.auto_add),n.setting.bind(function(e){e&&n.autoAddElement.set(e.auto_add)})}}),u.Menus.MenuControl=u.Control.extend({ready:function(){var t,n,i=this,a=u.section(i.section()),o=i.params.menu_id,e=i.setting();if(void 0===this.params.menu_id)throw new Error("params.menu_id was not defined");i.active.validate=function(){var e=!!a&&a.active();return e},i.$controlSection=a.headContainer,i.$sectionContent=i.container.closest(".accordion-section-content"),this._setupModel(),u.section(i.section(),function(e){e.deferred.initSortables.done(function(e){i._setupSortable(e)})}),this._setupAddition(),this._setupLocations(),this._setupTitle(),e&&(t=m(e.name),u.control.each(function(e){e.extended(u.controlConstructor.widget_form)&&"nav_menu"===e.params.widget_id_base&&(e.container.find(".nav-menu-widget-form-controls:first").show(),e.container.find(".nav-menu-widget-no-menus-message:first").hide(),0===(n=e.container.find("select")).find("option[value="+String(o)+"]").length&&n.append(new Option(t,o)))}),(e=l("#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )")).find(".nav-menu-widget-form-controls:first").show(),e.find(".nav-menu-widget-no-menus-message:first").hide(),0===(n=e.find(".widget-inside select:first")).find("option[value="+String(o)+"]").length&&n.append(new Option(t,o)))},_setupModel:function(){var n=this,i=n.params.menu_id;n.setting.bind(function(e){var t;!1===e?n._handleDeletion():(t=m(e.name),u.control.each(function(e){e.extended(u.controlConstructor.widget_form)&&"nav_menu"===e.params.widget_id_base&&e.container.find("select").find("option[value="+String(i)+"]").text(t)}))}),n.container.find(".menu-delete-item").on("click",function(e){e.stopPropagation(),e.preventDefault(),n.setting.set(!1)})},_setupSortable:function(e){var a=this;if(!e.is(a.$sectionContent))throw new Error("Unexpected menuList.");e.on("sortstart",function(){a.isSorting=!0}),e.on("sortstop",function(){setTimeout(function(){var e=a.$sectionContent.sortable("toArray"),t=[],n=0,i=10;a.isSorting=!1,a.$sectionContent.scrollLeft(0),_.each(e,function(e){var e=e.match(/^customize-control-nav_menu_item-(-?\d+)$/,"");e&&(e=parseInt(e[1],10),(e=u.control("nav_menu_item["+String(e)+"]"))&&t.push(e))}),_.each(t,function(e){var t;!1!==e.setting()&&(t=_.clone(e.setting()),n+=1,i+=1,t.position=n,e.priority(i),t.menu_item_parent=parseInt(e.container.find(".menu-item-data-parent-id").val(),10),t.menu_item_parent||(t.menu_item_parent=0),e.setting.set(t))})})}),a.isReordering=!1,this.container.find(".reorder-toggle").on("click",function(){a.toggleReordering(!a.isReordering)})},_setupAddition:function(){var t=this;this.container.find(".add-new-menu-item").on("click",function(e){t.$sectionContent.hasClass("reordering")||(l("body").hasClass("adding-menu-items")?(l(this).attr("aria-expanded","false"),u.Menus.availableMenuItemsPanel.close(),e.stopPropagation()):(l(this).attr("aria-expanded","true"),u.Menus.availableMenuItemsPanel.open(t)))})},_handleDeletion:function(){var e,n=this.params.menu_id,i=0,t=u.section(this.section()),a=function(){t.container.remove(),u.section.remove(t.id)};t&&t.expanded()?t.collapse({completeCallback:function(){a(),c.a11y.speak(u.Menus.data.l10n.menuDeleted),u.panel("nav_menus").focus()}}):a(),u.each(function(e){/^nav_menu\[/.test(e.id)&&!1!==e()&&(i+=1)}),u.control.each(function(e){var t;e.extended(u.controlConstructor.widget_form)&&"nav_menu"===e.params.widget_id_base&&((t=e.container.find("select")).val()===String(n)&&t.prop("selectedIndex",0).trigger("change"),e.container.find(".nav-menu-widget-form-controls:first").toggle(0!==i),e.container.find(".nav-menu-widget-no-menus-message:first").toggle(0===i),e.container.find("option[value="+String(n)+"]").remove())}),(e=l("#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )")).find(".nav-menu-widget-form-controls:first").toggle(0!==i),e.find(".nav-menu-widget-no-menus-message:first").toggle(0===i),e.find("option[value="+String(n)+"]").remove()},_setupLocations:function(){var o=this;o.container.find(".assigned-menu-location").each(function(){var n=l(this),e=n.find("input[type=checkbox]"),t=u("nav_menu_locations["+e.data("location-id")+"]"),i=function(e){var t=u("nav_menu["+String(e)+"]");e&&t&&t()?n.find(".theme-location-set").show().find("span").text(m(t().name)):n.find(".theme-location-set").hide()},a=new u.Element(e);a.set(t.get()===o.params.menu_id),e.on("change",function(){t.set(this.checked?o.params.menu_id:0)}),t.bind(function(e){a.set(e===o.params.menu_id),i(e)}),i(t.get())})},_setupTitle:function(){var d=this;d.setting.bind(function(e){var t,n,i,a,o,s,r;e&&(t=u.section(d.section()),n=d.params.menu_id,i=t.headContainer.find(".accordion-section-title"),a=t.contentContainer.find(".customize-section-title h3"),o=t.headContainer.find(".menu-in-location"),s=a.find(".customize-action"),r=m(e.name),i.text(r),o.length&&o.appendTo(i),a.text(r),s.length&&s.prependTo(a),u.control.each(function(e){/^nav_menu_locations\[/.test(e.id)&&e.container.find("option[value="+n+"]").text(r)}),t.contentContainer.find(".customize-control-checkbox input").each(function(){l(this).prop("checked")&&l(".current-menu-location-name-"+l(this).data("location-id")).text(r)}))})},toggleReordering:function(e){var t=this.container.find(".add-new-menu-item"),n=this.container.find(".reorder-toggle"),i=this.$sectionContent.find(".item-title");(e=Boolean(e))!==this.$sectionContent.hasClass("reordering")&&(this.isReordering=e,this.$sectionContent.toggleClass("reordering",e),this.$sectionContent.sortable(this.isReordering?"disable":"enable"),this.isReordering?(t.attr({tabindex:"-1","aria-hidden":"true"}),n.attr("aria-label",u.Menus.data.l10n.reorderLabelOff),c.a11y.speak(u.Menus.data.l10n.reorderModeOn),i.attr("aria-hidden","false")):(t.removeAttr("tabindex aria-hidden"),n.attr("aria-label",u.Menus.data.l10n.reorderLabelOn),c.a11y.speak(u.Menus.data.l10n.reorderModeOff),i.attr("aria-hidden","true")),e&&_(this.getMenuItemControls()).each(function(e){e.collapseForm()}))},getMenuItemControls:function(){var t=[],n=this.params.menu_id;return u.control.each(function(e){"nav_menu_item"===e.params.type&&e.setting()&&n===e.setting().nav_menu_term_id&&t.push(e)}),t},reflowMenuItems:function(){var e=this.getMenuItemControls(),a=function(n){var t=[],i=n.currentParent;_.each(n.menuItemControls,function(e){i===e.setting().menu_item_parent&&t.push(e)}),t.sort(function(e,t){return e.setting().position-t.setting().position}),_.each(t,function(t){n.currentAbsolutePosition+=1,t.priority.set(n.currentAbsolutePosition),t.container.hasClass("menu-item-depth-"+String(n.currentDepth))||(_.each(t.container.prop("className").match(/menu-item-depth-\d+/g),function(e){t.container.removeClass(e)}),t.container.addClass("menu-item-depth-"+String(n.currentDepth))),t.container.data("item-depth",n.currentDepth),n.currentDepth+=1,n.currentParent=t.params.menu_item_id,a(n),--n.currentDepth,n.currentParent=i}),t.length&&(_(t).each(function(e){e.container.removeClass("move-up-disabled move-down-disabled move-left-disabled move-right-disabled"),0===n.currentDepth?e.container.addClass("move-left-disabled"):10===n.currentDepth&&e.container.addClass("move-right-disabled")}),t[0].container.addClass("move-up-disabled").addClass("move-right-disabled").toggleClass("move-down-disabled",1===t.length),t[t.length-1].container.addClass("move-down-disabled").toggleClass("move-up-disabled",1===t.length))};a({menuItemControls:e,currentParent:0,currentDepth:0,currentAbsolutePosition:0}),this.container.find(".reorder-toggle").toggle(1<e.length)},debouncedReflowMenuItems:_.debounce(function(){this.reflowMenuItems.apply(this,arguments)},0),addItemToMenu:function(e){var t,n,i,a=0,o=10;return _.each(this.getMenuItemControls(),function(e){!1!==e.setting()&&(o=Math.max(o,e.priority()),0===e.setting().menu_item_parent&&(a=Math.max(a,e.setting().position)))}),a+=1,o+=1,delete(e=l.extend({},u.Menus.data.defaultSettingValues.nav_menu_item,e,{nav_menu_term_id:this.params.menu_id,position:a})).id,i=u.Menus.generatePlaceholderAutoIncrementId(),t="nav_menu_item["+String(i)+"]",n={type:"nav_menu_item",transport:u.Menus.data.settingTransport,previewer:u.previewer},(n=u.create(t,t,{},n)).set(e),i=new u.controlConstructor.nav_menu_item(t,{params:{type:"nav_menu_item",content:'<li id="customize-control-nav_menu_item-'+String(i)+'" class="customize-control customize-control-nav_menu_item"></li>',section:this.id,priority:o,active:!0,settings:{"default":t},menu_item_id:i},previewer:u.previewer}),u.control.add(t,i),n.preview(),this.debouncedReflowMenuItems(),c.a11y.speak(u.Menus.data.l10n.itemAdded),i}}),u.Menus.NewMenuControl=u.Control.extend({ready:function(){this._bindHandlers()},_bindHandlers:function(){var t=this,e=l("#customize-control-new_menu_name input"),n=l("#create-new-menu-submit");e.on("keydown",function(e){13===e.which&&t.submit()}),n.on("click",function(e){t.submit(),e.stopPropagation(),e.preventDefault()})},submit:function(){var e,t=this.container.closest(".accordion-section-new-menu").find(".menu-name-field").first(),n=t.val(),i=u.Menus.generatePlaceholderAutoIncrementId();if(!n)return t.addClass("invalid"),void t.focus();e="nav_menu["+String(i)+"]",u.create(e,e,{},{type:"nav_menu",transport:u.Menus.data.settingTransport,previewer:u.previewer}),u(e).set(l.extend({},u.Menus.data.defaultSettingValues.nav_menu,{name:n})),i=new u.Menus.MenuSection(e,{params:{id:e,panel:"nav_menus",title:m(n),customizeAction:u.Menus.data.l10n.customizingMenus,type:"nav_menu",priority:10,menu_id:i}}),u.section.add(e,i),t.val(""),t.removeClass("invalid"),c.a11y.speak(u.Menus.data.l10n.menuAdded),u.section(e).focus()}}),l.extend(u.controlConstructor,{nav_menu_location:u.Menus.MenuLocationControl,nav_menu_item:u.Menus.MenuItemControl,nav_menu:u.Menus.MenuControl,nav_menu_name:u.Menus.MenuNameControl,nav_menu_auto_add:u.Menus.MenuAutoAddControl,new_menu:u.Menus.NewMenuControl}),l.extend(u.panelConstructor,{nav_menus:u.Menus.MenusPanel}),l.extend(u.sectionConstructor,{nav_menu:u.Menus.MenuSection,new_menu:u.Menus.NewMenuSection}),u.bind("ready",function(){u.Menus.availableMenuItemsPanel=new u.Menus.AvailableMenuItemsPanelView({collection:u.Menus.availableMenuItems}),u.bind("saved",function(e){(e.nav_menu_updates||e.nav_menu_item_updates)&&u.Menus.applySavedData(e)}),u.state("changesetStatus").bind(function(e){"publish"===e&&(u("nav_menus_created_posts")._value=[])}),u.previewer.bind("focus-nav-menu-item-control",u.Menus.focusMenuItemControl)}),u.Menus.applySavedData=function(e){var d={},r={};_(e.nav_menu_updates).each(function(n){var e,t,i,a,o,s,r;if("inserted"===n.status){if(!n.previous_term_id)throw new Error("Expected previous_term_id");if(!n.term_id)throw new Error("Expected term_id");if(s="nav_menu["+String(n.previous_term_id)+"]",!u.has(s))throw new Error("Expected setting to exist: "+s);if(t=u(s),!u.section.has(s))throw new Error("Expected control to exist: "+s);if(o=u.section(s),!(a=t.get()))throw new Error("Did not expect setting to be empty (deleted).");a=l.extend(_.clone(a),n.saved_value),d[n.previous_term_id]=n.term_id,e="nav_menu["+String(n.term_id)+"]",i=u.create(e,e,a,{type:"nav_menu",transport:u.Menus.data.settingTransport,previewer:u.previewer}),o.expanded()&&o.collapse(),a=new u.Menus.MenuSection(e,{params:{id:e,panel:"nav_menus",title:a.name,customizeAction:u.Menus.data.l10n.customizingMenus,type:"nav_menu",priority:o.priority.get(),active:!0,menu_id:n.term_id}}),u.section.add(e,a),u.control.each(function(e){var t;e.extended(u.controlConstructor.widget_form)&&"nav_menu"===e.params.widget_id_base&&(e=(t=e.container.find("select")).find("option[value="+String(n.previous_term_id)+"]"),t.find("option[value="+String(n.term_id)+"]").prop("selected",e.prop("selected")),e.remove())}),t.callbacks.disable(),t.set(!1),t.preview(),i.preview(),t._dirty=!1,o.container.remove(),u.section.remove(s),r=0,u.each(function(e){/^nav_menu\[/.test(e.id)&&!1!==e()&&(r+=1)}),(s=l("#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )")).find(".nav-menu-widget-form-controls:first").toggle(0!==r),s.find(".nav-menu-widget-no-menus-message:first").toggle(0===r),s.find("option[value="+String(n.previous_term_id)+"]").remove(),c.customize.control.each(function(e){/^nav_menu_locations\[/.test(e.id)&&e.container.find("option[value="+String(n.previous_term_id)+"]").remove()}),u.each(function(e){var t=u.state("saved").get();/^nav_menu_locations\[/.test(e.id)&&e.get()===n.previous_term_id&&(e.set(n.term_id),e._dirty=!1,u.state("saved").set(t),e.preview())}),o.expanded.get()&&a.expand()}else if("updated"===n.status){if(o="nav_menu["+String(n.term_id)+"]",!u.has(o))throw new Error("Expected setting to exist: "+o);a=u(o),_.isEqual(n.saved_value,a.get())||(o=u.state("saved").get(),a.set(n.saved_value),a._dirty=!1,u.state("saved").set(o))}}),_(e.nav_menu_item_updates).each(function(e){e.previous_post_id&&(r[e.previous_post_id]=e.post_id)}),_(e.nav_menu_item_updates).each(function(e){var t,n,i,a,o,s;if("inserted"===e.status){if(!e.previous_post_id)throw new Error("Expected previous_post_id");if(!e.post_id)throw new Error("Expected post_id");if(t="nav_menu_item["+String(e.previous_post_id)+"]",!u.has(t))throw new Error("Expected setting to exist: "+t);if(i=u(t),!u.control.has(t))throw new Error("Expected control to exist: "+t);if(s=u.control(t),!(o=i.get()))throw new Error("Did not expect setting to be empty (deleted).");if((o=_.clone(o)).menu_item_parent<0){if(!r[o.menu_item_parent])throw new Error("inserted ID for menu_item_parent not available");o.menu_item_parent=r[o.menu_item_parent]}d[o.nav_menu_term_id]&&(o.nav_menu_term_id=d[o.nav_menu_term_id]),n="nav_menu_item["+String(e.post_id)+"]",a=u.create(n,n,o,{type:"nav_menu_item",transport:u.Menus.data.settingTransport,previewer:u.previewer}),e=new u.controlConstructor.nav_menu_item(n,{params:{type:"nav_menu_item",content:'<li id="customize-control-nav_menu_item-'+String(e.post_id)+'" class="customize-control customize-control-nav_menu_item"></li>',menu_id:e.post_id,section:"nav_menu["+String(o.nav_menu_term_id)+"]",priority:s.priority.get(),active:!0,settings:{"default":n},menu_item_id:e.post_id},previewer:u.previewer}),s.container.remove(),u.control.remove(t),u.control.add(n,e),i.callbacks.disable(),i.set(!1),i.preview(),a.preview(),i._dirty=!1,e.container.toggleClass("menu-item-edit-inactive",s.container.hasClass("menu-item-edit-inactive"))}}),_.each(e.widget_nav_menu_updates,function(e,t){t=u(t);t&&(t._value=e,t.preview())})},u.Menus.focusMenuItemControl=function(e){e=u.Menus.getMenuItemControl(e);e&&e.focus()},u.Menus.getMenuControl=function(e){return u.control("nav_menu["+e+"]")},u.Menus.getMenuItemControl=function(e){return u.control("nav_menu_item["+e+"]")}}(wp.customize,wp,jQuery); updates.min.js 0000666 00000102764 15213733063 0007352 0 ustar 00 !function(r,p,d){var o=r(document);(p=p||{}).updates={},p.updates.ajaxNonce=d.ajax_nonce,p.updates.l10n=d.l10n,p.updates.searchTerm="",p.updates.shouldRequestFilesystemCredentials=!1,p.updates.filesystemCredentials={ftp:{host:"",username:"",password:"",connectionType:""},ssh:{publicKey:"",privateKey:""},fsNonce:"",available:!1},p.updates.ajaxLocked=!1,p.updates.adminNotice=p.template("wp-updates-admin-notice"),p.updates.queue=[],p.updates.$elToReturnFocusToFromCredentialsModal=void 0,p.updates.addAdminNotice=function(e){var t,a=r(e.selector);delete e.selector,t=p.updates.adminNotice(e),(a=!a.length?r("#"+e.id):a).length?a.replaceWith(t):r(".wrap").find("> h1").after(t),o.trigger("wp-updates-notice-added")},p.updates.ajax=function(e,t){var a={};return p.updates.ajaxLocked?(p.updates.queue.push({action:e,data:t}),r.Deferred()):(p.updates.ajaxLocked=!0,t.success&&(a.success=t.success,delete t.success),t.error&&(a.error=t.error,delete t.error),a.data=_.extend(t,{action:e,_ajax_nonce:p.updates.ajaxNonce,_fs_nonce:p.updates.filesystemCredentials.fsNonce,username:p.updates.filesystemCredentials.ftp.username,password:p.updates.filesystemCredentials.ftp.password,hostname:p.updates.filesystemCredentials.ftp.hostname,connection_type:p.updates.filesystemCredentials.ftp.connectionType,public_key:p.updates.filesystemCredentials.ssh.publicKey,private_key:p.updates.filesystemCredentials.ssh.privateKey}),p.ajax.send(a).always(p.updates.ajaxAlways))},p.updates.ajaxAlways=function(e){e.errorCode&&"unable_to_connect_to_filesystem"===e.errorCode||(p.updates.ajaxLocked=!1,p.updates.queueChecker()),void 0!==e.debug&&window.console&&window.console.log&&_.map(e.debug,function(e){window.console.log(r("<p />").html(e).text())})},p.updates.refreshCount=function(){var e,t=r("#wp-admin-bar-updates"),a=r('a[href="update-core.php"] .update-plugins'),s=r('a[href="plugins.php"] .update-plugins'),n=r('a[href="themes.php"] .update-plugins');t.find(".ab-item").removeAttr("title"),t.find(".ab-label").text(d.totals.counts.total),0===d.totals.counts.total&&t.find(".ab-label").parents("li").remove(),a.each(function(e,t){t.className=t.className.replace(/count-\d+/,"count-"+d.totals.counts.total)}),0<d.totals.counts.total?a.find(".update-count").text(d.totals.counts.total):a.remove(),s.each(function(e,t){t.className=t.className.replace(/count-\d+/,"count-"+d.totals.counts.plugins)}),0<d.totals.counts.total?s.find(".plugin-count").text(d.totals.counts.plugins):s.remove(),n.each(function(e,t){t.className=t.className.replace(/count-\d+/,"count-"+d.totals.counts.themes)}),0<d.totals.counts.total?n.find(".theme-count").text(d.totals.counts.themes):n.remove(),"plugins"===pagenow||"plugins-network"===pagenow?e=d.totals.counts.plugins:"themes"!==pagenow&&"themes-network"!==pagenow||(e=d.totals.counts.themes),0<e?r(".subsubsub .upgrade .count").text("("+e+")"):r(".subsubsub .upgrade").remove()},p.updates.decrementCount=function(e){d.totals.counts.total=Math.max(--d.totals.counts.total,0),"plugin"===e?d.totals.counts.plugins=Math.max(--d.totals.counts.plugins,0):"theme"===e&&(d.totals.counts.themes=Math.max(--d.totals.counts.themes,0)),p.updates.refreshCount(e)},p.updates.updatePlugin=function(e){var t,a,s;return e=_.extend({success:p.updates.updatePluginSuccess,error:p.updates.updatePluginError},e),"plugins"===pagenow||"plugins-network"===pagenow?(a=(t=r('tr[data-plugin="'+e.plugin+'"]')).find(".update-message").removeClass("notice-error").addClass("updating-message notice-warning").find("p"),s=p.updates.l10n.updatingLabel.replace("%s",t.find(".plugin-title strong").text())):"plugin-install"!==pagenow&&"plugin-install-network"!==pagenow||(a=(t=r(".plugin-card-"+e.slug)).find(".update-now").addClass("updating-message"),s=p.updates.l10n.updatingLabel.replace("%s",a.data("name")),t.removeClass("plugin-card-update-failed").find(".notice.notice-error").remove()),a.html()!==p.updates.l10n.updating&&a.data("originaltext",a.html()),a.attr("aria-label",s).text(p.updates.l10n.updating),o.trigger("wp-plugin-updating",e),p.updates.ajax("update-plugin",e)},p.updates.updatePluginSuccess=function(e){var t,a,s;"plugins"===pagenow||"plugins-network"===pagenow?(a=(t=r('tr[data-plugin="'+e.plugin+'"]').removeClass("update").addClass("updated")).find(".update-message").removeClass("updating-message notice-warning").addClass("updated-message notice-success").find("p"),s=t.find(".plugin-version-author-uri").html().replace(e.oldVersion,e.newVersion),t.find(".plugin-version-author-uri").html(s)):"plugin-install"!==pagenow&&"plugin-install-network"!==pagenow||(a=r(".plugin-card-"+e.slug).find(".update-now").removeClass("updating-message").addClass("button-disabled updated-message")),a.attr("aria-label",p.updates.l10n.updatedLabel.replace("%s",e.pluginName)).text(p.updates.l10n.updated),p.a11y.speak(p.updates.l10n.updatedMsg,"polite"),p.updates.decrementCount("plugin"),o.trigger("wp-plugin-update-success",e)},p.updates.updatePluginError=function(e){var t,a,s;p.updates.isValidResponse(e,"update")&&(p.updates.maybeHandleCredentialError(e,"update-plugin")||(s=p.updates.l10n.updateFailed.replace("%s",e.errorMessage),"plugins"===pagenow||"plugins-network"===pagenow?((a=(e.plugin?r('tr[data-plugin="'+e.plugin+'"]'):r('tr[data-slug="'+e.slug+'"]')).find(".update-message")).removeClass("updating-message notice-warning").addClass("notice-error").find("p").html(s),e.pluginName?a.find("p").attr("aria-label",p.updates.l10n.updateFailedLabel.replace("%s",e.pluginName)):a.find("p").removeAttr("aria-label")):"plugin-install"!==pagenow&&"plugin-install-network"!==pagenow||((t=r(".plugin-card-"+e.slug).addClass("plugin-card-update-failed").append(p.updates.adminNotice({className:"update-message notice-error notice-alt is-dismissible",message:s}))).find(".update-now").text(p.updates.l10n.updateFailedShort).removeClass("updating-message"),e.pluginName?t.find(".update-now").attr("aria-label",p.updates.l10n.updateFailedLabel.replace("%s",e.pluginName)):t.find(".update-now").removeAttr("aria-label"),t.on("click",".notice.is-dismissible .notice-dismiss",function(){setTimeout(function(){t.removeClass("plugin-card-update-failed").find(".column-name a").focus(),t.find(".update-now").attr("aria-label",!1).text(p.updates.l10n.updateNow)},200)})),p.a11y.speak(s,"assertive"),o.trigger("wp-plugin-update-error",e)))},p.updates.installPlugin=function(e){var t=r(".plugin-card-"+e.slug),a=t.find(".install-now");return e=_.extend({success:p.updates.installPluginSuccess,error:p.updates.installPluginError},e),(a="import"===pagenow?r('[data-slug="'+e.slug+'"]'):a).html()!==p.updates.l10n.installing&&a.data("originaltext",a.html()),a.addClass("updating-message").attr("aria-label",p.updates.l10n.pluginInstallingLabel.replace("%s",a.data("name"))).text(p.updates.l10n.installing),p.a11y.speak(p.updates.l10n.installingMsg,"polite"),t.removeClass("plugin-card-install-failed").find(".notice.notice-error").remove(),o.trigger("wp-plugin-installing",e),p.updates.ajax("install-plugin",e)},p.updates.installPluginSuccess=function(e){var t=r(".plugin-card-"+e.slug).find(".install-now");t.removeClass("updating-message").addClass("updated-message installed button-disabled").attr("aria-label",p.updates.l10n.pluginInstalledLabel.replace("%s",e.pluginName)).text(p.updates.l10n.installed),p.a11y.speak(p.updates.l10n.installedMsg,"polite"),o.trigger("wp-plugin-install-success",e),e.activateUrl&&setTimeout(function(){t.removeClass("install-now installed button-disabled updated-message").addClass("activate-now button-primary").attr("href",e.activateUrl).attr("aria-label",p.updates.l10n.activatePluginLabel.replace("%s",e.pluginName)).text(p.updates.l10n.activatePlugin)},1e3)},p.updates.installPluginError=function(e){var t,a=r(".plugin-card-"+e.slug),s=a.find(".install-now");p.updates.isValidResponse(e,"install")&&(p.updates.maybeHandleCredentialError(e,"install-plugin")||(t=p.updates.l10n.installFailed.replace("%s",e.errorMessage),a.addClass("plugin-card-update-failed").append('<div class="notice notice-error notice-alt is-dismissible"><p>'+t+"</p></div>"),a.on("click",".notice.is-dismissible .notice-dismiss",function(){setTimeout(function(){a.removeClass("plugin-card-update-failed").find(".column-name a").focus()},200)}),s.removeClass("updating-message").addClass("button-disabled").attr("aria-label",p.updates.l10n.pluginInstallFailedLabel.replace("%s",s.data("name"))).text(p.updates.l10n.installFailedShort),p.a11y.speak(t,"assertive"),o.trigger("wp-plugin-install-error",e)))},p.updates.installImporterSuccess=function(e){p.updates.addAdminNotice({id:"install-success",className:"notice-success is-dismissible",message:p.updates.l10n.importerInstalledMsg.replace("%s",e.activateUrl+"&from=import")}),r('[data-slug="'+e.slug+'"]').removeClass("install-now updating-message").addClass("activate-now").attr({href:e.activateUrl+"&from=import","aria-label":p.updates.l10n.activateImporterLabel.replace("%s",e.pluginName)}).text(p.updates.l10n.activateImporter),p.a11y.speak(p.updates.l10n.installedMsg,"polite"),o.trigger("wp-importer-install-success",e)},p.updates.installImporterError=function(e){var t=p.updates.l10n.installFailed.replace("%s",e.errorMessage),a=r('[data-slug="'+e.slug+'"]'),s=a.data("name");p.updates.isValidResponse(e,"install")&&(p.updates.maybeHandleCredentialError(e,"install-plugin")||(p.updates.addAdminNotice({id:e.errorCode,className:"notice-error is-dismissible",message:t}),a.removeClass("updating-message").text(p.updates.l10n.installNow).attr("aria-label",p.updates.l10n.installNowLabel.replace("%s",s)),p.a11y.speak(t,"assertive"),o.trigger("wp-importer-install-error",e)))},p.updates.deletePlugin=function(e){var t=r('[data-plugin="'+e.plugin+'"]').find(".row-actions a.delete");return e=_.extend({success:p.updates.deletePluginSuccess,error:p.updates.deletePluginError},e),t.html()!==p.updates.l10n.deleting&&t.data("originaltext",t.html()).text(p.updates.l10n.deleting),p.a11y.speak(p.updates.l10n.deleting,"polite"),o.trigger("wp-plugin-deleting",e),p.updates.ajax("delete-plugin",e)},p.updates.deletePluginSuccess=function(i){r('[data-plugin="'+i.plugin+'"]').css({backgroundColor:"#faafaa"}).fadeOut(350,function(){var e=r("#bulk-action-form"),t=r(".subsubsub"),a=r(this),s=e.find("thead th:not(.hidden), thead td").length,n=p.template("item-deleted-row"),l=d.plugins;a.hasClass("plugin-update-tr")||a.after(n({slug:i.slug,plugin:i.plugin,colspan:s,name:i.pluginName})),a.remove(),-1!==_.indexOf(l.upgrade,i.plugin)&&(l.upgrade=_.without(l.upgrade,i.plugin),p.updates.decrementCount("plugin")),-1!==_.indexOf(l.inactive,i.plugin)&&(l.inactive=_.without(l.inactive,i.plugin),l.inactive.length?t.find(".inactive .count").text("("+l.inactive.length+")"):t.find(".inactive").remove()),-1!==_.indexOf(l.active,i.plugin)&&(l.active=_.without(l.active,i.plugin),l.active.length?t.find(".active .count").text("("+l.active.length+")"):t.find(".active").remove()),-1!==_.indexOf(l.recently_activated,i.plugin)&&(l.recently_activated=_.without(l.recently_activated,i.plugin),l.recently_activated.length?t.find(".recently_activated .count").text("("+l.recently_activated.length+")"):t.find(".recently_activated").remove()),l.all=_.without(l.all,i.plugin),l.all.length?t.find(".all .count").text("("+l.all.length+")"):(e.find(".tablenav").css({visibility:"hidden"}),t.find(".all").remove(),e.find("tr.no-items").length||e.find("#the-list").append('<tr class="no-items"><td class="colspanchange" colspan="'+s+'">'+p.updates.l10n.noPlugins+"</td></tr>"))}),p.a11y.speak(p.updates.l10n.deleted,"polite"),o.trigger("wp-plugin-delete-success",i)},p.updates.deletePluginError=function(e){var t,a=p.template("item-update-row"),s=p.updates.adminNotice({className:"update-message notice-error notice-alt",message:e.errorMessage}),n=e.plugin?(t=r('tr.inactive[data-plugin="'+e.plugin+'"]')).siblings('[data-plugin="'+e.plugin+'"]'):(t=r('tr.inactive[data-slug="'+e.slug+'"]')).siblings('[data-slug="'+e.slug+'"]');p.updates.isValidResponse(e,"delete")&&(p.updates.maybeHandleCredentialError(e,"delete-plugin")||(n.length?(n.find(".notice-error").remove(),n.find(".plugin-update").append(s)):t.addClass("update").after(a({slug:e.slug,plugin:e.plugin||e.slug,colspan:r("#bulk-action-form").find("thead th:not(.hidden), thead td").length,content:s})),o.trigger("wp-plugin-delete-error",e)))},p.updates.updateTheme=function(e){var t;return e=_.extend({success:p.updates.updateThemeSuccess,error:p.updates.updateThemeError},e),(t="themes-network"===pagenow?r('[data-slug="'+e.slug+'"]').find(".update-message").removeClass("notice-error").addClass("updating-message notice-warning").find("p"):((t=r("#update-theme").closest(".notice").removeClass("notice-large")).find("h3").remove(),(t=t.add(r('[data-slug="'+e.slug+'"]').find(".update-message"))).addClass("updating-message").find("p"))).html()!==p.updates.l10n.updating&&t.data("originaltext",t.html()),p.a11y.speak(p.updates.l10n.updatingMsg,"polite"),t.text(p.updates.l10n.updating),o.trigger("wp-theme-updating",e),p.updates.ajax("update-theme",e)},p.updates.updateThemeSuccess=function(e){var t,a,s=r("body.modal-open").length,n=r('[data-slug="'+e.slug+'"]'),l={className:"updated-message notice-success notice-alt",message:p.updates.l10n.updated};"themes-network"===pagenow?(t=n.find(".update-message"),a=n.find(".theme-version-author-uri").html().replace(e.oldVersion,e.newVersion),n.find(".theme-version-author-uri").html(a)):(t=r(".theme-info .notice").add(n.find(".update-message")),(s?r(".load-customize:visible"):n.find(".load-customize")).focus()),p.updates.addAdminNotice(_.extend({selector:t},l)),p.a11y.speak(p.updates.l10n.updatedMsg,"polite"),p.updates.decrementCount("theme"),o.trigger("wp-theme-update-success",e),s&&r(".theme-info .theme-author").after(p.updates.adminNotice(l))},p.updates.updateThemeError=function(e){var t,a=r('[data-slug="'+e.slug+'"]'),s=p.updates.l10n.updateFailed.replace("%s",e.errorMessage);p.updates.isValidResponse(e,"update")&&(p.updates.maybeHandleCredentialError(e,"update-theme")||("themes-network"===pagenow?t=a.find(".update-message "):(t=r(".theme-info .notice").add(a.find(".notice")),(r("body.modal-open").length?r(".load-customize:visible"):a.find(".load-customize")).focus()),p.updates.addAdminNotice({selector:t,className:"update-message notice-error notice-alt is-dismissible",message:s}),p.a11y.speak(s,"polite"),o.trigger("wp-theme-update-error",e)))},p.updates.installTheme=function(e){var t=r('.theme-install[data-slug="'+e.slug+'"]');return e=_.extend({success:p.updates.installThemeSuccess,error:p.updates.installThemeError},e),t.addClass("updating-message"),t.parents(".theme").addClass("focus"),t.html()!==p.updates.l10n.installing&&t.data("originaltext",t.html()),t.text(p.updates.l10n.installing).attr("aria-label",p.updates.l10n.themeInstallingLabel.replace("%s",t.data("name"))),p.a11y.speak(p.updates.l10n.installingMsg,"polite"),r('.install-theme-info, [data-slug="'+e.slug+'"]').removeClass("theme-install-failed").find(".notice.notice-error").remove(),o.trigger("wp-theme-installing",e),p.updates.ajax("install-theme",e)},p.updates.installThemeSuccess=function(e){var t,a=r(".wp-full-overlay-header, [data-slug="+e.slug+"]");o.trigger("wp-theme-install-success",e),t=a.find(".button-primary").removeClass("updating-message").addClass("updated-message disabled").attr("aria-label",p.updates.l10n.themeInstalledLabel.replace("%s",e.themeName)).text(p.updates.l10n.installed),p.a11y.speak(p.updates.l10n.installedMsg,"polite"),setTimeout(function(){e.activateUrl&&t.attr("href",e.activateUrl).removeClass("theme-install updated-message disabled").addClass("activate").attr("aria-label",p.updates.l10n.activateThemeLabel.replace("%s",e.themeName)).text(p.updates.l10n.activateTheme),e.customizeUrl&&t.siblings(".preview").replaceWith(function(){return r("<a>").attr("href",e.customizeUrl).addClass("button load-customize").text(p.updates.l10n.livePreview)})},1e3)},p.updates.installThemeError=function(e){var t,a=p.updates.l10n.installFailed.replace("%s",e.errorMessage),s=p.updates.adminNotice({className:"update-message notice-error notice-alt",message:a});p.updates.isValidResponse(e,"install")&&(p.updates.maybeHandleCredentialError(e,"install-theme")||(o.find("body").hasClass("full-overlay-active")?(t=r('.theme-install[data-slug="'+e.slug+'"]'),r(".install-theme-info").prepend(s)):t=r('[data-slug="'+e.slug+'"]').removeClass("focus").addClass("theme-install-failed").append(s).find(".theme-install"),t.removeClass("updating-message").attr("aria-label",p.updates.l10n.themeInstallFailedLabel.replace("%s",t.data("name"))).text(p.updates.l10n.installFailedShort),p.a11y.speak(a,"assertive"),o.trigger("wp-theme-install-error",e)))},p.updates.deleteTheme=function(e){var t;return"themes"===pagenow?t=r(".theme-actions .delete-theme"):"themes-network"===pagenow&&(t=r('[data-slug="'+e.slug+'"]').find(".row-actions a.delete")),e=_.extend({success:p.updates.deleteThemeSuccess,error:p.updates.deleteThemeError},e),t&&t.html()!==p.updates.l10n.deleting&&t.data("originaltext",t.html()).text(p.updates.l10n.deleting),p.a11y.speak(p.updates.l10n.deleting,"polite"),r(".theme-info .update-message").remove(),o.trigger("wp-theme-deleting",e),p.updates.ajax("delete-theme",e)},p.updates.deleteThemeSuccess=function(n){var e=r('[data-slug="'+n.slug+'"]');"themes-network"===pagenow&&e.css({backgroundColor:"#faafaa"}).fadeOut(350,function(){var e=r(".subsubsub"),t=r(this),a=d.themes,s=p.template("item-deleted-row");t.hasClass("plugin-update-tr")||t.after(s({slug:n.slug,colspan:r("#bulk-action-form").find("thead th:not(.hidden), thead td").length,name:t.find(".theme-title strong").text()})),t.remove(),t.hasClass("update")&&(a.upgrade--,p.updates.decrementCount("theme")),t.hasClass("inactive")&&(a.disabled--,a.disabled?e.find(".disabled .count").text("("+a.disabled+")"):e.find(".disabled").remove()),e.find(".all .count").text("("+--a.all+")")}),p.a11y.speak(p.updates.l10n.deleted,"polite"),o.trigger("wp-theme-delete-success",n)},p.updates.deleteThemeError=function(e){var t=r('tr.inactive[data-slug="'+e.slug+'"]'),a=r(".theme-actions .delete-theme"),s=p.template("item-update-row"),n=t.siblings("#"+e.slug+"-update"),l=p.updates.l10n.deleteFailed.replace("%s",e.errorMessage),i=p.updates.adminNotice({className:"update-message notice-error notice-alt",message:l});p.updates.maybeHandleCredentialError(e,"delete-theme")||("themes-network"===pagenow?n.length?(n.find(".notice-error").remove(),n.find(".plugin-update").append(i)):t.addClass("update").after(s({slug:e.slug,colspan:r("#bulk-action-form").find("thead th:not(.hidden), thead td").length,content:i})):r(".theme-info .theme-description").before(i),a.html(a.data("originaltext")),p.a11y.speak(l,"assertive"),o.trigger("wp-theme-delete-error",e))},p.updates._addCallbacks=function(e,t){return"import"===pagenow&&"install-plugin"===t&&(e.success=p.updates.installImporterSuccess,e.error=p.updates.installImporterError),e},p.updates.queueChecker=function(){var e;if(!p.updates.ajaxLocked&&p.updates.queue.length)switch((e=p.updates.queue.shift()).action){case"install-plugin":p.updates.installPlugin(e.data);break;case"update-plugin":p.updates.updatePlugin(e.data);break;case"delete-plugin":p.updates.deletePlugin(e.data);break;case"install-theme":p.updates.installTheme(e.data);break;case"update-theme":p.updates.updateTheme(e.data);break;case"delete-theme":p.updates.deleteTheme(e.data)}},p.updates.requestFilesystemCredentials=function(e){!1===p.updates.filesystemCredentials.available&&(e&&!p.updates.$elToReturnFocusToFromCredentialsModal&&(p.updates.$elToReturnFocusToFromCredentialsModal=r(e.target)),p.updates.ajaxLocked=!0,p.updates.requestForCredentialsModalOpen())},p.updates.maybeRequestFilesystemCredentials=function(e){p.updates.shouldRequestFilesystemCredentials&&!p.updates.ajaxLocked&&p.updates.requestFilesystemCredentials(e)},p.updates.keydown=function(e){27===e.keyCode?p.updates.requestForCredentialsModalCancel():9===e.keyCode&&("upgrade"!==e.target.id||e.shiftKey?"hostname"===e.target.id&&e.shiftKey&&(r("#upgrade").focus(),e.preventDefault()):(r("#hostname").focus(),e.preventDefault()))},p.updates.requestForCredentialsModalOpen=function(){var e=r("#request-filesystem-credentials-dialog");r("body").addClass("modal-open"),e.show(),e.find("input:enabled:first").focus(),e.on("keydown",p.updates.keydown)},p.updates.requestForCredentialsModalClose=function(){r("#request-filesystem-credentials-dialog").hide(),r("body").removeClass("modal-open"),p.updates.$elToReturnFocusToFromCredentialsModal&&p.updates.$elToReturnFocusToFromCredentialsModal.focus()},p.updates.requestForCredentialsModalCancel=function(){(p.updates.ajaxLocked||p.updates.queue.length)&&(_.each(p.updates.queue,function(e){o.trigger("credential-modal-cancel",e)}),p.updates.ajaxLocked=!1,p.updates.queue=[],p.updates.requestForCredentialsModalClose())},p.updates.showErrorInCredentialsForm=function(e){var t=r("#request-filesystem-credentials-form");t.find(".notice").remove(),t.find("#request-filesystem-credentials-title").after('<div class="notice notice-alt notice-error"><p>'+e+"</p></div>")},p.updates.credentialError=function(e,t){e=p.updates._addCallbacks(e,t),p.updates.queue.unshift({action:t,data:e}),p.updates.filesystemCredentials.available=!1,p.updates.showErrorInCredentialsForm(e.errorMessage),p.updates.requestFilesystemCredentials()},p.updates.maybeHandleCredentialError=function(e,t){return!(!p.updates.shouldRequestFilesystemCredentials||!e.errorCode||"unable_to_connect_to_filesystem"!==e.errorCode)&&(p.updates.credentialError(e,t),!0)},p.updates.isValidResponse=function(e,t){var a,s=p.updates.l10n.unknownError;if(_.isObject(e)&&!_.isFunction(e.always))return!0;switch(_.isString(e)&&"-1"===e?s=p.updates.l10n.nonceError:_.isString(e)?s=e:void 0!==e.readyState&&0===e.readyState?s=p.updates.l10n.connectionError:_.isString(e.responseText)&&""!==e.responseText?s=e.responseText:_.isString(e.statusText)&&(s=e.statusText),t){case"update":a=p.updates.l10n.updateFailed;break;case"install":a=p.updates.l10n.installFailed;break;case"delete":a=p.updates.l10n.deleteFailed}return s=s.replace(/<[\/a-z][^<>]*>/gi,""),a=a.replace("%s",s),p.updates.addAdminNotice({id:"unknown_error",className:"notice-error is-dismissible",message:_.escape(a)}),p.updates.ajaxLocked=!1,p.updates.queue=[],r(".button.updating-message").removeClass("updating-message").removeAttr("aria-label").prop("disabled",!0).text(p.updates.l10n.updateFailedShort),r(".updating-message:not(.button):not(.thickbox)").removeClass("updating-message notice-warning").addClass("notice-error").find("p").removeAttr("aria-label").text(a),p.a11y.speak(a,"assertive"),!1},p.updates.beforeunload=function(){if(p.updates.ajaxLocked)return p.updates.l10n.beforeunload},r(function(){var l=r("#plugin-filter"),u=r("#bulk-action-form"),e=r("#request-filesystem-credentials-form"),t=r("#request-filesystem-credentials-dialog"),a=r(".plugins-php .wp-filter-search"),s=r(".plugin-install-php .wp-filter-search");(d=_.extend(d,window._wpUpdatesItemCounts||{})).totals&&p.updates.refreshCount(),p.updates.shouldRequestFilesystemCredentials=0<t.length,t.on("submit","form",function(e){e.preventDefault(),p.updates.filesystemCredentials.ftp.hostname=r("#hostname").val(),p.updates.filesystemCredentials.ftp.username=r("#username").val(),p.updates.filesystemCredentials.ftp.password=r("#password").val(),p.updates.filesystemCredentials.ftp.connectionType=r('input[name="connection_type"]:checked').val(),p.updates.filesystemCredentials.ssh.publicKey=r("#public_key").val(),p.updates.filesystemCredentials.ssh.privateKey=r("#private_key").val(),p.updates.filesystemCredentials.fsNonce=r("#_fs_nonce").val(),p.updates.filesystemCredentials.available=!0,p.updates.ajaxLocked=!1,p.updates.queueChecker(),p.updates.requestForCredentialsModalClose()}),t.on("click",'[data-js-action="close"], .notification-dialog-background',p.updates.requestForCredentialsModalCancel),e.on("change",'input[name="connection_type"]',function(){r("#ssh-keys").toggleClass("hidden","ssh"!==r(this).val())}).change(),o.on("credential-modal-cancel",function(e,t){var a,s=r(".updating-message");"import"===pagenow?s.removeClass("updating-message"):"plugins"===pagenow||"plugins-network"===pagenow?"update-plugin"===t.action?a=r('tr[data-plugin="'+t.data.plugin+'"]').find(".update-message"):"delete-plugin"===t.action&&(a=r('[data-plugin="'+t.data.plugin+'"]').find(".row-actions a.delete")):"themes"===pagenow||"themes-network"===pagenow?"update-theme"===t.action?a=r('[data-slug="'+t.data.slug+'"]').find(".update-message"):"delete-theme"===t.action&&"themes-network"===pagenow?a=r('[data-slug="'+t.data.slug+'"]').find(".row-actions a.delete"):"delete-theme"===t.action&&"themes"===pagenow&&(a=r(".theme-actions .delete-theme")):a=s,a&&a.hasClass("updating-message")&&(void 0===(s=a.data("originaltext"))&&(s=r("<p>").html(a.find("p").data("originaltext"))),a.removeClass("updating-message").html(s),"plugin-install"!==pagenow&&"plugin-install-network"!==pagenow||("update-plugin"===t.action?a.attr("aria-label",p.updates.l10n.updateNowLabel.replace("%s",a.data("name"))):"install-plugin"===t.action&&a.attr("aria-label",p.updates.l10n.installNowLabel.replace("%s",a.data("name"))))),p.a11y.speak(p.updates.l10n.updateCancel,"polite")}),u.on("click","[data-plugin] .update-link",function(e){var t=r(e.target),a=t.parents("tr");e.preventDefault(),t.hasClass("updating-message")||t.hasClass("button-disabled")||(p.updates.maybeRequestFilesystemCredentials(e),p.updates.$elToReturnFocusToFromCredentialsModal=a.find(".check-column input"),p.updates.updatePlugin({plugin:a.data("plugin"),slug:a.data("slug")}))}),l.on("click",".update-now",function(e){var t=r(e.target);e.preventDefault(),t.hasClass("updating-message")||t.hasClass("button-disabled")||(p.updates.maybeRequestFilesystemCredentials(e),p.updates.updatePlugin({plugin:t.data("plugin"),slug:t.data("slug")}))}),l.on("click",".install-now",function(e){var t=r(e.target);e.preventDefault(),t.hasClass("updating-message")||t.hasClass("button-disabled")||(p.updates.shouldRequestFilesystemCredentials&&!p.updates.ajaxLocked&&(p.updates.requestFilesystemCredentials(e),o.on("credential-modal-cancel",function(){r(".install-now.updating-message").removeClass("updating-message").text(p.updates.l10n.installNow),p.a11y.speak(p.updates.l10n.updateCancel,"polite")})),p.updates.installPlugin({slug:t.data("slug")}))}),o.on("click",".importer-item .install-now",function(e){var t=r(e.target),a=r(this).data("name");e.preventDefault(),t.hasClass("updating-message")||(p.updates.shouldRequestFilesystemCredentials&&!p.updates.ajaxLocked&&(p.updates.requestFilesystemCredentials(e),o.on("credential-modal-cancel",function(){t.removeClass("updating-message").text(p.updates.l10n.installNow).attr("aria-label",p.updates.l10n.installNowLabel.replace("%s",a)),p.a11y.speak(p.updates.l10n.updateCancel,"polite")})),p.updates.installPlugin({slug:t.data("slug"),pagenow:pagenow,success:p.updates.installImporterSuccess,error:p.updates.installImporterError}))}),u.on("click","[data-plugin] a.delete",function(e){var t=r(e.target).parents("tr");e.preventDefault(),window.confirm(p.updates.l10n.aysDeleteUninstall.replace("%s",t.find(".plugin-title strong").text()))&&(p.updates.maybeRequestFilesystemCredentials(e),p.updates.deletePlugin({plugin:t.data("plugin"),slug:t.data("slug")}))}),o.on("click",".themes-php.network-admin .update-link",function(e){var t=r(e.target),a=t.parents("tr");e.preventDefault(),t.hasClass("updating-message")||t.hasClass("button-disabled")||(p.updates.maybeRequestFilesystemCredentials(e),p.updates.$elToReturnFocusToFromCredentialsModal=a.find(".check-column input"),p.updates.updateTheme({slug:a.data("slug")}))}),o.on("click",".themes-php.network-admin a.delete",function(e){var t=r(e.target).parents("tr");e.preventDefault(),window.confirm(p.updates.l10n.aysDelete.replace("%s",t.find(".theme-title strong").text()))&&(p.updates.maybeRequestFilesystemCredentials(e),p.updates.deleteTheme({slug:t.data("slug")}))}),u.on("click",'[type="submit"]',function(e){var t,s,n=r(e.target).siblings("select").val(),a=u.find('input[name="checked[]"]:checked'),l=0,i=0,d=[];switch(pagenow){case"plugins":case"plugins-network":t="plugin";break;case"themes-network":t="theme";break;default:return}if(!a.length)return e.preventDefault(),r("html, body").animate({scrollTop:0}),p.updates.addAdminNotice({id:"no-items-selected",className:"notice-error is-dismissible",message:p.updates.l10n.noItemsSelected});switch(n){case"update-selected":s=n.replace("selected",t);break;case"delete-selected":if(!window.confirm("plugin"===t?p.updates.l10n.aysBulkDelete:p.updates.l10n.aysBulkDeleteThemes))return void e.preventDefault();s=n.replace("selected",t);break;default:return}p.updates.maybeRequestFilesystemCredentials(e),e.preventDefault(),u.find('.manage-column [type="checkbox"]').prop("checked",!1),o.trigger("wp-"+t+"-bulk-"+n,a),a.each(function(e,t){var a=r(t),t=a.parents("tr");"update-selected"!==n||t.hasClass("update")&&!t.find("notice-error").length?p.updates.queue.push({action:s,data:{plugin:t.data("plugin"),slug:t.data("slug")}}):a.prop("checked",!1)}),o.on("wp-plugin-update-success wp-plugin-update-error wp-theme-update-success wp-theme-update-error",function(e,t){var a,s=r('[data-slug="'+t.slug+'"]');"wp-"+t.update+"-update-success"===e.type?l++:(e=t.pluginName||s.find(".column-primary strong").text(),i++,d.push(e+": "+t.errorMessage)),s.find('input[name="checked[]"]:checked').prop("checked",!1),p.updates.adminNotice=p.template("wp-bulk-updates-admin-notice"),p.updates.addAdminNotice({id:"bulk-action-notice",className:"bulk-action-notice",successes:l,errors:i,errorMessages:d,type:t.update}),a=r("#bulk-action-notice").on("click","button",function(){r(this).toggleClass("bulk-action-errors-collapsed").attr("aria-expanded",!r(this).hasClass("bulk-action-errors-collapsed")),a.find(".bulk-action-errors").toggleClass("hidden")}),0<i&&!p.updates.queue.length&&r("html, body").animate({scrollTop:0})}),o.on("wp-updates-notice-added",function(){p.updates.adminNotice=p.template("wp-updates-admin-notice")}),p.updates.queueChecker()}),s.length&&s.attr("aria-describedby","live-search-desc"),s.on("keyup input",_.debounce(function(e,t){var a=r(".plugin-install-search"),s={_ajax_nonce:p.updates.ajaxNonce,s:e.target.value,tab:"search",type:r("#typeselector").val(),pagenow:pagenow},n=location.href.split("?")[0]+"?"+r.param(_.omit(s,["_ajax_nonce","pagenow"]));"keyup"===e.type&&27===e.which&&(e.target.value=""),p.updates.searchTerm===s.s&&"typechange"!==t||(l.empty(),p.updates.searchTerm=s.s,window.history&&window.history.replaceState&&window.history.replaceState(null,"",n),a.length||(a=r('<li class="plugin-install-search" />').append(r("<a />",{"class":"current",href:n,text:p.updates.l10n.searchResultsLabel})),r(".wp-filter .filter-links .current").removeClass("current").parents(".filter-links").prepend(a),l.prev("p").remove(),r(".plugins-popular-tags-wrapper").remove()),void 0!==p.updates.searchRequest&&p.updates.searchRequest.abort(),r("body").addClass("loading-content"),p.updates.searchRequest=p.ajax.post("search-install-plugins",s).done(function(e){r("body").removeClass("loading-content"),l.append(e.items),delete p.updates.searchRequest,0===e.count?p.a11y.speak(p.updates.l10n.noPluginsFound):p.a11y.speak(p.updates.l10n.pluginsFound.replace("%d",e.count))}))},500)),a.length&&a.attr("aria-describedby","live-search-desc"),a.on("keyup input",_.debounce(function(e){var s={_ajax_nonce:p.updates.ajaxNonce,s:e.target.value,pagenow:pagenow,plugin_status:"all"};"keyup"===e.type&&27===e.which&&(e.target.value=""),p.updates.searchTerm!==s.s&&(p.updates.searchTerm=s.s,e=_.object(_.compact(_.map(location.search.slice(1).split("&"),function(e){if(e)return e.split("=")}))),s.plugin_status=e.plugin_status||"all",window.history&&window.history.replaceState&&window.history.replaceState(null,"",location.href.split("?")[0]+"?s="+s.s+"&plugin_status="+s.plugin_status),void 0!==p.updates.searchRequest&&p.updates.searchRequest.abort(),u.empty(),r("body").addClass("loading-content"),r(".subsubsub .current").removeClass("current"),p.updates.searchRequest=p.ajax.post("search-plugins",s).done(function(e){var t=r("<span />").addClass("subtitle").html(p.updates.l10n.searchResults.replace("%s",_.escape(s.s))),a=r(".wrap .subtitle");s.s.length?a.length?a.replaceWith(t):r(".wrap h1").append(t):(a.remove(),r(".subsubsub ."+s.plugin_status+" a").addClass("current")),r("body").removeClass("loading-content"),u.append(e.items),delete p.updates.searchRequest,0===e.count?p.a11y.speak(p.updates.l10n.noPluginsFound):p.a11y.speak(p.updates.l10n.pluginsFound.replace("%d",e.count))}))},500)),o.on("submit",".search-plugins",function(e){e.preventDefault(),r("input.wp-filter-search").trigger("input")}),r("#typeselector").on("change",function(){var e=r('input[name="s"]');e.val().length&&e.trigger("input","typechange")}),r("#plugin_update_from_iframe").on("click",function(e){var t=window.parent===window?null:window.parent;r.support.postMessage=!!window.postMessage,!1!==r.support.postMessage&&null!==t&&-1===window.parent.location.pathname.indexOf("update-core.php")&&(e.preventDefault(),e={action:"update-plugin",data:{plugin:r(this).data("plugin"),slug:r(this).data("slug")}},t.postMessage(JSON.stringify(e),window.location.origin))}),r("#plugin_install_from_iframe").on("click",function(e){var t=window.parent===window?null:window.parent;r.support.postMessage=!!window.postMessage,!1!==r.support.postMessage&&null!==t&&-1===window.parent.location.pathname.indexOf("index.php")&&(e.preventDefault(),e={action:"install-plugin",data:{slug:r(this).data("slug")}},t.postMessage(JSON.stringify(e),window.location.origin))}),r(window).on("message",function(e){var t,a=e.originalEvent,e=document.location.protocol+"//"+document.location.hostname;if(a.origin===e){try{t=r.parseJSON(a.data)}catch(e){return}if(void 0!==t.action)switch(t.action){case"decrementUpdateCount":p.updates.decrementCount(t.upgradeType);break;case"install-plugin":case"update-plugin":window.tb_remove(),t.data=p.updates._addCallbacks(t.data,t.action),p.updates.queue.push(t),p.updates.queueChecker()}}}),r(window).on("beforeunload",p.updates.beforeunload)})}(jQuery,window.wp,window._wpUpdatesSettings); theme.js 0000666 00000145164 15213733063 0006226 0 ustar 00 /* global _wpThemeSettings, confirm */ window.wp = window.wp || {}; ( function($) { // Set up our namespace... var themes, l10n; themes = wp.themes = wp.themes || {}; // Store the theme data and settings for organized and quick access // themes.data.settings, themes.data.themes, themes.data.l10n themes.data = _wpThemeSettings; l10n = themes.data.l10n; // Shortcut for isInstall check themes.isInstall = !! themes.data.settings.isInstall; // Setup app structure _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template }); themes.Model = Backbone.Model.extend({ // Adds attributes to the default data coming through the .org themes api // Map `id` to `slug` for shared code initialize: function() { var description; // If theme is already installed, set an attribute. if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) { this.set({ installed: true }); } // Set the attributes this.set({ // slug is for installation, id is for existing. id: this.get( 'slug' ) || this.get( 'id' ) }); // Map `section.description` to `description` // as the API sometimes returns it differently if ( this.has( 'sections' ) ) { description = this.get( 'sections' ).description; this.set({ description: description }); } } }); // Main view controller for themes.php // Unifies and renders all available views themes.view.Appearance = wp.Backbone.View.extend({ el: '#wpbody-content .wrap .theme-browser', window: $( window ), // Pagination instance page: 0, // Sets up a throttler for binding to 'scroll' initialize: function( options ) { // Scroller checks how far the scroll position is _.bindAll( this, 'scroller' ); this.SearchView = options.SearchView ? options.SearchView : themes.view.Search; // Bind to the scroll event and throttle // the results from this.scroller this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) ); }, // Main render control render: function() { // Setup the main theme view // with the current theme collection this.view = new themes.view.Themes({ collection: this.collection, parent: this }); // Render search form. this.search(); // Render and append this.view.render(); this.$el.empty().append( this.view.el ).addClass( 'rendered' ); }, // Defines search element container searchContainer: $( '#wpbody h1:first' ), // Search input and view // for current theme collection search: function() { var view, self = this; // Don't render the search if there is only one theme if ( themes.data.themes.length === 1 ) { return; } view = new this.SearchView({ collection: self.collection, parent: this }); // Render and append after screen title view.render(); this.searchContainer .append( $.parseHTML( '<label class="screen-reader-text" for="wp-filter-search-input">' + l10n.search + '</label>' ) ) .append( view.el ); }, // Checks when the user gets close to the bottom // of the mage and triggers a theme:scroll event scroller: function() { var self = this, bottom, threshold; bottom = this.window.scrollTop() + self.window.height(); threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height(); threshold = Math.round( threshold * 0.9 ); if ( bottom > threshold ) { this.trigger( 'theme:scroll' ); } } }); // Set up the Collection for our theme data // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ... themes.Collection = Backbone.Collection.extend({ model: themes.Model, // Search terms terms: '', // Controls searching on the current theme collection // and triggers an update event doSearch: function( value ) { // Don't do anything if we've already done this search // Useful because the Search handler fires multiple times per keystroke if ( this.terms === value ) { return; } // Updates terms with the value passed this.terms = value; // If we have terms, run a search... if ( this.terms.length > 0 ) { this.search( this.terms ); } // If search is blank, show all themes // Useful for resetting the views when you clean the input if ( this.terms === '' ) { this.reset( themes.data.themes ); $( 'body' ).removeClass( 'no-results' ); } // Trigger a 'themes:update' event this.trigger( 'themes:update' ); }, // Performs a search within the collection // @uses RegExp search: function( term ) { var match, results, haystack, name, description, author; // Start with a full collection this.reset( themes.data.themes, { silent: true } ); // Escape the term string for RegExp meta characters term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' ); // Consider spaces as word delimiters and match the whole string // so matching terms can be combined term = term.replace( / /g, ')(?=.*' ); match = new RegExp( '^(?=.*' + term + ').+', 'i' ); // Find results // _.filter and .test results = this.filter( function( data ) { name = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' ); description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' ); author = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' ); haystack = _.union( [ name, data.get( 'id' ), description, author, data.get( 'tags' ) ] ); if ( match.test( data.get( 'author' ) ) && term.length > 2 ) { data.set( 'displayAuthor', true ); } return match.test( haystack ); }); if ( results.length === 0 ) { this.trigger( 'query:empty' ); } else { $( 'body' ).removeClass( 'no-results' ); } this.reset( results ); }, // Paginates the collection with a helper method // that slices the collection paginate: function( instance ) { var collection = this; instance = instance || 0; // Themes per instance are set at 20 collection = _( collection.rest( 20 * instance ) ); collection = _( collection.first( 20 ) ); return collection; }, count: false, // Handles requests for more themes // and caches results // // When we are missing a cache object we fire an apiCall() // which triggers events of `query:success` or `query:fail` query: function( request ) { /** * @static * @type Array */ var queries = this.queries, self = this, query, isPaginated, count; // Store current query request args // for later use with the event `theme:end` this.currentQuery.request = request; // Search the query cache for matches. query = _.find( queries, function( query ) { return _.isEqual( query.request, request ); }); // If the request matches the stored currentQuery.request // it means we have a paginated request. isPaginated = _.has( request, 'page' ); // Reset the internal api page counter for non paginated queries. if ( ! isPaginated ) { this.currentQuery.page = 1; } // Otherwise, send a new API call and add it to the cache. if ( ! query && ! isPaginated ) { query = this.apiCall( request ).done( function( data ) { // Update the collection with the queried data. if ( data.themes ) { self.reset( data.themes ); count = data.info.results; // Store the results and the query request queries.push( { themes: data.themes, request: request, total: count } ); } // Trigger a collection refresh event // and a `query:success` event with a `count` argument. self.trigger( 'themes:update' ); self.trigger( 'query:success', count ); if ( data.themes && data.themes.length === 0 ) { self.trigger( 'query:empty' ); } }).fail( function() { self.trigger( 'query:fail' ); }); } else { // If it's a paginated request we need to fetch more themes... if ( isPaginated ) { return this.apiCall( request, isPaginated ).done( function( data ) { // Add the new themes to the current collection // @todo update counter self.add( data.themes ); self.trigger( 'query:success' ); // We are done loading themes for now. self.loadingThemes = false; }).fail( function() { self.trigger( 'query:fail' ); }); } if ( query.themes.length === 0 ) { self.trigger( 'query:empty' ); } else { $( 'body' ).removeClass( 'no-results' ); } // Only trigger an update event since we already have the themes // on our cached object if ( _.isNumber( query.total ) ) { this.count = query.total; } this.reset( query.themes ); if ( ! query.total ) { this.count = this.length; } this.trigger( 'themes:update' ); this.trigger( 'query:success', this.count ); } }, // Local cache array for API queries queries: [], // Keep track of current query so we can handle pagination currentQuery: { page: 1, request: {} }, // Send request to api.wordpress.org/themes apiCall: function( request, paginated ) { return wp.ajax.send( 'query-themes', { data: { // Request data request: _.extend({ per_page: 100, fields: { description: true, tested: true, requires: true, rating: true, downloaded: true, downloadLink: true, last_updated: true, homepage: true, num_ratings: true } }, request) }, beforeSend: function() { if ( ! paginated ) { // Spin it $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' ); } } }); }, // Static status controller for when we are loading themes. loadingThemes: false }); // This is the view that controls each theme item // that will be displayed on the screen themes.view.Theme = wp.Backbone.View.extend({ // Wrap theme data on a div.theme element className: 'theme', // Reflects which theme view we have // 'grid' (default) or 'detail' state: 'grid', // The HTML template for each element to be rendered html: themes.template( 'theme' ), events: { 'click': themes.isInstall ? 'preview': 'expand', 'keydown': themes.isInstall ? 'preview': 'expand', 'touchend': themes.isInstall ? 'preview': 'expand', 'keyup': 'addFocus', 'touchmove': 'preventExpand', 'click .theme-install': 'installTheme', 'click .update-message': 'updateTheme' }, touchDrag: false, initialize: function() { this.model.on( 'change', this.render, this ); }, render: function() { var data = this.model.toJSON(); // Render themes using the html template this.$el.html( this.html( data ) ).attr({ tabindex: 0, 'aria-describedby' : data.id + '-action ' + data.id + '-name', 'data-slug': data.id }); // Renders active theme styles this.activeTheme(); if ( this.model.get( 'displayAuthor' ) ) { this.$el.addClass( 'display-author' ); } }, // Adds a class to the currently active theme // and to the overlay in detailed view mode activeTheme: function() { if ( this.model.get( 'active' ) ) { this.$el.addClass( 'active' ); } }, // Add class of focus to the theme we are focused on. addFocus: function() { var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme'); $('.theme.focus').removeClass('focus'); $themeToFocus.addClass('focus'); }, // Single theme overlay screen // It's shown when clicking a theme expand: function( event ) { var self = this; event = event || window.event; // 'enter' and 'space' keys expand the details view when a theme is :focused if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) { return; } // Bail if the user scrolled on a touch device if ( this.touchDrag === true ) { return this.touchDrag = false; } // Prevent the modal from showing when the user clicks // one of the direct action buttons if ( $( event.target ).is( '.theme-actions a' ) ) { return; } // Prevent the modal from showing when the user clicks one of the direct action buttons. if ( $( event.target ).is( '.theme-actions a, .update-message, .button-link, .notice-dismiss' ) ) { return; } // Set focused theme to current element themes.focusedTheme = this.$el; this.trigger( 'theme:expand', self.model.cid ); }, preventExpand: function() { this.touchDrag = true; }, preview: function( event ) { var self = this, current, preview; event = event || window.event; // Bail if the user scrolled on a touch device if ( this.touchDrag === true ) { return this.touchDrag = false; } // Allow direct link path to installing a theme. if ( $( event.target ).not( '.install-theme-preview' ).parents( '.theme-actions' ).length ) { return; } // 'enter' and 'space' keys expand the details view when a theme is :focused if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) { return; } // pressing enter while focused on the buttons shouldn't open the preview if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) { return; } event.preventDefault(); event = event || window.event; // Set focus to current theme. themes.focusedTheme = this.$el; // Construct a new Preview view. preview = new themes.view.Preview({ model: this.model }); // Render the view and append it. preview.render(); this.setNavButtonsState(); // Hide previous/next navigation if there is only one theme if ( this.model.collection.length === 1 ) { preview.$el.addClass( 'no-navigation' ); } else { preview.$el.removeClass( 'no-navigation' ); } // Append preview $( 'div.wrap' ).append( preview.el ); // Listen to our preview object // for `theme:next` and `theme:previous` events. this.listenTo( preview, 'theme:next', function() { // Keep local track of current theme model. current = self.model; // If we have ventured away from current model update the current model position. if ( ! _.isUndefined( self.current ) ) { current = self.current; } // Get next theme model. self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 ); // If we have no more themes, bail. if ( _.isUndefined( self.current ) ) { self.options.parent.parent.trigger( 'theme:end' ); return self.current = current; } preview.model = self.current; // Render and append. preview.render(); this.setNavButtonsState(); $( '.next-theme' ).focus(); }) .listenTo( preview, 'theme:previous', function() { // Keep track of current theme model. current = self.model; // Bail early if we are at the beginning of the collection if ( self.model.collection.indexOf( self.current ) === 0 ) { return; } // If we have ventured away from current model update the current model position. if ( ! _.isUndefined( self.current ) ) { current = self.current; } // Get previous theme model. self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 ); // If we have no more themes, bail. if ( _.isUndefined( self.current ) ) { return; } preview.model = self.current; // Render and append. preview.render(); this.setNavButtonsState(); $( '.previous-theme' ).focus(); }); this.listenTo( preview, 'preview:close', function() { self.current = self.model; }); }, // Handles .disabled classes for previous/next buttons in theme installer preview setNavButtonsState: function() { var $themeInstaller = $( '.theme-install-overlay' ), current = _.isUndefined( this.current ) ? this.model : this.current; // Disable previous at the zero position if ( 0 === this.model.collection.indexOf( current ) ) { $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' ); } // Disable next if the next model is undefined if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) { $themeInstaller.find( '.next-theme' ).addClass( 'disabled' ); } }, installTheme: function( event ) { var _this = this; event.preventDefault(); wp.updates.maybeRequestFilesystemCredentials( event ); $( document ).on( 'wp-theme-install-success', function( event, response ) { if ( _this.model.get( 'id' ) === response.slug ) { _this.model.set( { 'installed': true } ); } } ); wp.updates.installTheme( { slug: $( event.target ).data( 'slug' ) } ); }, updateTheme: function( event ) { var _this = this; if ( ! this.model.get( 'hasPackage' ) ) { return; } event.preventDefault(); wp.updates.maybeRequestFilesystemCredentials( event ); $( document ).on( 'wp-theme-update-success', function( event, response ) { _this.model.off( 'change', _this.render, _this ); if ( _this.model.get( 'id' ) === response.slug ) { _this.model.set( { hasUpdate: false, version: response.newVersion } ); } _this.model.on( 'change', _this.render, _this ); } ); wp.updates.updateTheme( { slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' ) } ); } }); // Theme Details view // Set ups a modal overlay with the expanded theme data themes.view.Details = wp.Backbone.View.extend({ // Wrap theme data on a div.theme element className: 'theme-overlay', events: { 'click': 'collapse', 'click .delete-theme': 'deleteTheme', 'click .left': 'previousTheme', 'click .right': 'nextTheme', 'click #update-theme': 'updateTheme' }, // The HTML template for the theme overlay html: themes.template( 'theme-single' ), render: function() { var data = this.model.toJSON(); this.$el.html( this.html( data ) ); // Renders active theme styles this.activeTheme(); // Set up navigation events this.navigation(); // Checks screenshot size this.screenshotCheck( this.$el ); // Contain "tabbing" inside the overlay this.containFocus( this.$el ); }, // Adds a class to the currently active theme // and to the overlay in detailed view mode activeTheme: function() { // Check the model has the active property this.$el.toggleClass( 'active', this.model.get( 'active' ) ); }, // Set initial focus and constrain tabbing within the theme browser modal. containFocus: function( $el ) { // Set initial focus on the primary action control. _.delay( function() { $( '.theme-wrap a.button-primary:visible' ).focus(); }, 100 ); // Constrain tabbing within the modal. $el.on( 'keydown.wp-themes', function( event ) { var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(), $lastFocusable = $el.find( '.theme-actions a:visible' ).last(); // Check for the Tab key. if ( 9 === event.which ) { if ( $firstFocusable[0] === event.target && event.shiftKey ) { $lastFocusable.focus(); event.preventDefault(); } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) { $firstFocusable.focus(); event.preventDefault(); } } }); }, // Single theme overlay screen // It's shown when clicking a theme collapse: function( event ) { var self = this, scroll; event = event || window.event; // Prevent collapsing detailed view when there is only one theme available if ( themes.data.themes.length === 1 ) { return; } // Detect if the click is inside the overlay // and don't close it unless the target was // the div.back button if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) { // Add a temporary closing class while overlay fades out $( 'body' ).addClass( 'closing-overlay' ); // With a quick fade out animation this.$el.fadeOut( 130, function() { // Clicking outside the modal box closes the overlay $( 'body' ).removeClass( 'closing-overlay' ); // Handle event cleanup self.closeOverlay(); // Get scroll position to avoid jumping to the top scroll = document.body.scrollTop; // Clean the url structure themes.router.navigate( themes.router.baseUrl( '' ) ); // Restore scroll position document.body.scrollTop = scroll; // Return focus to the theme div if ( themes.focusedTheme ) { themes.focusedTheme.focus(); } }); } }, // Handles .disabled classes for next/previous buttons navigation: function() { // Disable Left/Right when at the start or end of the collection if ( this.model.cid === this.model.collection.at(0).cid ) { this.$el.find( '.left' ) .addClass( 'disabled' ) .prop( 'disabled', true ); } if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) { this.$el.find( '.right' ) .addClass( 'disabled' ) .prop( 'disabled', true ); } }, // Performs the actions to effectively close // the theme details overlay closeOverlay: function() { $( 'body' ).removeClass( 'modal-open' ); this.remove(); this.unbind(); this.trigger( 'theme:collapse' ); }, updateTheme: function( event ) { var _this = this; event.preventDefault(); wp.updates.maybeRequestFilesystemCredentials( event ); $( document ).on( 'wp-theme-update-success', function( event, response ) { if ( _this.model.get( 'id' ) === response.slug ) { _this.model.set( { hasUpdate: false, version: response.newVersion } ); } _this.render(); } ); wp.updates.updateTheme( { slug: $( event.target ).data( 'slug' ) } ); }, deleteTheme: function( event ) { var _this = this, _collection = _this.model.collection, _themes = themes; event.preventDefault(); // Confirmation dialog for deleting a theme. if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) { return; } wp.updates.maybeRequestFilesystemCredentials( event ); $( document ).one( 'wp-theme-delete-success', function( event, response ) { _this.$el.find( '.close' ).trigger( 'click' ); $( '[data-slug="' + response.slug + '"]' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() { $( this ).remove(); _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) ); $( '.wp-filter-search' ).val( '' ); _collection.doSearch( '' ); _collection.remove( _this.model ); _collection.trigger( 'themes:update' ); } ); } ); wp.updates.deleteTheme( { slug: this.model.get( 'id' ) } ); }, nextTheme: function() { var self = this; self.trigger( 'theme:next', self.model.cid ); return false; }, previousTheme: function() { var self = this; self.trigger( 'theme:previous', self.model.cid ); return false; }, // Checks if the theme screenshot is the old 300px width version // and adds a corresponding class if it's true screenshotCheck: function( el ) { var screenshot, image; screenshot = el.find( '.screenshot img' ); image = new Image(); image.src = screenshot.attr( 'src' ); // Width check if ( image.width && image.width <= 300 ) { el.addClass( 'small-screenshot' ); } } }); // Theme Preview view // Set ups a modal overlay with the expanded theme data themes.view.Preview = themes.view.Details.extend({ className: 'wp-full-overlay expanded', el: '.theme-install-overlay', events: { 'click .close-full-overlay': 'close', 'click .collapse-sidebar': 'collapse', 'click .devices button': 'previewDevice', 'click .previous-theme': 'previousTheme', 'click .next-theme': 'nextTheme', 'keyup': 'keyEvent', 'click .theme-install': 'installTheme' }, // The HTML template for the theme preview html: themes.template( 'theme-preview' ), render: function() { var self = this, currentPreviewDevice, data = this.model.toJSON(), $body = $( document.body ); $body.attr( 'aria-busy', 'true' ); this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) ); currentPreviewDevice = this.$el.data( 'current-preview-device' ); if ( currentPreviewDevice ) { self.tooglePreviewDeviceButtons( currentPreviewDevice ); } themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } ); this.$el.fadeIn( 200, function() { $body.addClass( 'theme-installer-active full-overlay-active' ); }); this.$el.find( 'iframe' ).one( 'load', function() { self.iframeLoaded(); }); }, iframeLoaded: function() { this.$el.addClass( 'iframe-ready' ); $( document.body ).attr( 'aria-busy', 'false' ); }, close: function() { this.$el.fadeOut( 200, function() { $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' ); // Return focus to the theme div if ( themes.focusedTheme ) { themes.focusedTheme.focus(); } }).removeClass( 'iframe-ready' ); themes.router.navigate( themes.router.baseUrl( '' ) ); this.trigger( 'preview:close' ); this.undelegateEvents(); this.unbind(); return false; }, collapse: function( event ) { var $button = $( event.currentTarget ); if ( 'true' === $button.attr( 'aria-expanded' ) ) { $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar }); } else { $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar }); } this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' ); return false; }, previewDevice: function( event ) { var device = $( event.currentTarget ).data( 'device' ); this.$el .removeClass( 'preview-desktop preview-tablet preview-mobile' ) .addClass( 'preview-' + device ) .data( 'current-preview-device', device ); this.tooglePreviewDeviceButtons( device ); }, tooglePreviewDeviceButtons: function( newDevice ) { var $devices = $( '.wp-full-overlay-footer .devices' ); $devices.find( 'button' ) .removeClass( 'active' ) .attr( 'aria-pressed', false ); $devices.find( 'button.preview-' + newDevice ) .addClass( 'active' ) .attr( 'aria-pressed', true ); }, keyEvent: function( event ) { // The escape key closes the preview if ( event.keyCode === 27 ) { this.undelegateEvents(); this.close(); } // The right arrow key, next theme if ( event.keyCode === 39 ) { _.once( this.nextTheme() ); } // The left arrow key, previous theme if ( event.keyCode === 37 ) { this.previousTheme(); } }, installTheme: function( event ) { var _this = this, $target = $( event.target ); event.preventDefault(); if ( $target.hasClass( 'disabled' ) ) { return; } wp.updates.maybeRequestFilesystemCredentials( event ); $( document ).on( 'wp-theme-install-success', function() { _this.model.set( { 'installed': true } ); } ); wp.updates.installTheme( { slug: $target.data( 'slug' ) } ); } }); // Controls the rendering of div.themes, // a wrapper that will hold all the theme elements themes.view.Themes = wp.Backbone.View.extend({ className: 'themes wp-clearfix', $overlay: $( 'div.theme-overlay' ), // Number to keep track of scroll position // while in theme-overlay mode index: 0, // The theme count element count: $( '.wrap .theme-count' ), // The live themes count liveThemeCount: 0, initialize: function( options ) { var self = this; // Set up parent this.parent = options.parent; // Set current view to [grid] this.setView( 'grid' ); // Move the active theme to the beginning of the collection self.currentTheme(); // When the collection is updated by user input... this.listenTo( self.collection, 'themes:update', function() { self.parent.page = 0; self.currentTheme(); self.render( this ); } ); // Update theme count to full result set when available. this.listenTo( self.collection, 'query:success', function( count ) { if ( _.isNumber( count ) ) { self.count.text( count ); self.announceSearchResults( count ); } else { self.count.text( self.collection.length ); self.announceSearchResults( self.collection.length ); } }); this.listenTo( self.collection, 'query:empty', function() { $( 'body' ).addClass( 'no-results' ); }); this.listenTo( this.parent, 'theme:scroll', function() { self.renderThemes( self.parent.page ); }); this.listenTo( this.parent, 'theme:close', function() { if ( self.overlay ) { self.overlay.closeOverlay(); } } ); // Bind keyboard events. $( 'body' ).on( 'keyup', function( event ) { if ( ! self.overlay ) { return; } // Bail if the filesystem credentials dialog is shown. if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) { return; } // Pressing the right arrow key fires a theme:next event if ( event.keyCode === 39 ) { self.overlay.nextTheme(); } // Pressing the left arrow key fires a theme:previous event if ( event.keyCode === 37 ) { self.overlay.previousTheme(); } // Pressing the escape key fires a theme:collapse event if ( event.keyCode === 27 ) { self.overlay.collapse( event ); } }); }, // Manages rendering of theme pages // and keeping theme count in sync render: function() { // Clear the DOM, please this.$el.empty(); // If the user doesn't have switch capabilities // or there is only one theme in the collection // render the detailed view of the active theme if ( themes.data.themes.length === 1 ) { // Constructs the view this.singleTheme = new themes.view.Details({ model: this.collection.models[0] }); // Render and apply a 'single-theme' class to our container this.singleTheme.render(); this.$el.addClass( 'single-theme' ); this.$el.append( this.singleTheme.el ); } // Generate the themes // Using page instance // While checking the collection has items if ( this.options.collection.size() > 0 ) { this.renderThemes( this.parent.page ); } // Display a live theme count for the collection this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length; this.count.text( this.liveThemeCount ); /* * In the theme installer the themes count is already announced * because `announceSearchResults` is called on `query:success`. */ if ( ! themes.isInstall ) { this.announceSearchResults( this.liveThemeCount ); } }, // Iterates through each instance of the collection // and renders each theme module renderThemes: function( page ) { var self = this; self.instance = self.collection.paginate( page ); // If we have no more themes bail if ( self.instance.size() === 0 ) { // Fire a no-more-themes event. this.parent.trigger( 'theme:end' ); return; } // Make sure the add-new stays at the end if ( ! themes.isInstall && page >= 1 ) { $( '.add-new-theme' ).remove(); } // Loop through the themes and setup each theme view self.instance.each( function( theme ) { self.theme = new themes.view.Theme({ model: theme, parent: self }); // Render the views... self.theme.render(); // and append them to div.themes self.$el.append( self.theme.el ); // Binds to theme:expand to show the modal box // with the theme details self.listenTo( self.theme, 'theme:expand', self.expand, self ); }); // 'Add new theme' element shown at the end of the grid if ( ! themes.isInstall && themes.data.settings.canInstall ) { this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h2 class="theme-name">' + l10n.addNew + '</h2></a></div>' ); } this.parent.page++; }, // Grabs current theme and puts it at the beginning of the collection currentTheme: function() { var self = this, current; current = self.collection.findWhere({ active: true }); // Move the active theme to the beginning of the collection if ( current ) { self.collection.remove( current ); self.collection.add( current, { at:0 } ); } }, // Sets current view setView: function( view ) { return view; }, // Renders the overlay with the ThemeDetails view // Uses the current model data expand: function( id ) { var self = this, $card, $modal; // Set the current theme model this.model = self.collection.get( id ); // Trigger a route update for the current model themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) ); // Sets this.view to 'detail' this.setView( 'detail' ); $( 'body' ).addClass( 'modal-open' ); // Set up the theme details view this.overlay = new themes.view.Details({ model: self.model }); this.overlay.render(); if ( this.model.get( 'hasUpdate' ) ) { $card = $( '[data-slug="' + this.model.id + '"]' ); $modal = $( this.overlay.el ); if ( $card.find( '.updating-message' ).length ) { $modal.find( '.notice-warning h3' ).remove(); $modal.find( '.notice-warning' ) .removeClass( 'notice-large' ) .addClass( 'updating-message' ) .find( 'p' ).text( wp.updates.l10n.updating ); } else if ( $card.find( '.notice-error' ).length ) { $modal.find( '.notice-warning' ).remove(); } } this.$overlay.html( this.overlay.el ); // Bind to theme:next and theme:previous // triggered by the arrow keys // // Keep track of the current model so we // can infer an index position this.listenTo( this.overlay, 'theme:next', function() { // Renders the next theme on the overlay self.next( [ self.model.cid ] ); }) .listenTo( this.overlay, 'theme:previous', function() { // Renders the previous theme on the overlay self.previous( [ self.model.cid ] ); }); }, // This method renders the next theme on the overlay modal // based on the current position in the collection // @params [model cid] next: function( args ) { var self = this, model, nextModel; // Get the current theme model = self.collection.get( args[0] ); // Find the next model within the collection nextModel = self.collection.at( self.collection.indexOf( model ) + 1 ); // Sanity check which also serves as a boundary test if ( nextModel !== undefined ) { // We have a new theme... // Close the overlay this.overlay.closeOverlay(); // Trigger a route update for the current model self.theme.trigger( 'theme:expand', nextModel.cid ); } }, // This method renders the previous theme on the overlay modal // based on the current position in the collection // @params [model cid] previous: function( args ) { var self = this, model, previousModel; // Get the current theme model = self.collection.get( args[0] ); // Find the previous model within the collection previousModel = self.collection.at( self.collection.indexOf( model ) - 1 ); if ( previousModel !== undefined ) { // We have a new theme... // Close the overlay this.overlay.closeOverlay(); // Trigger a route update for the current model self.theme.trigger( 'theme:expand', previousModel.cid ); } }, // Dispatch audible search results feedback message announceSearchResults: function( count ) { if ( 0 === count ) { wp.a11y.speak( l10n.noThemesFound ); } else { wp.a11y.speak( l10n.themesFound.replace( '%d', count ) ); } } }); // Search input view controller. themes.view.Search = wp.Backbone.View.extend({ tagName: 'input', className: 'wp-filter-search', id: 'wp-filter-search-input', searching: false, attributes: { placeholder: l10n.searchPlaceholder, type: 'search', 'aria-describedby': 'live-search-desc' }, events: { 'input': 'search', 'keyup': 'search', 'blur': 'pushState' }, initialize: function( options ) { this.parent = options.parent; this.listenTo( this.parent, 'theme:close', function() { this.searching = false; } ); }, search: function( event ) { // Clear on escape. if ( event.type === 'keyup' && event.which === 27 ) { event.target.value = ''; } /** * Since doSearch is debounced, it will only run when user input comes to a rest */ this.doSearch( event ); }, // Runs a search on the theme collection. doSearch: _.debounce( function( event ) { var options = {}; this.collection.doSearch( event.target.value ); // if search is initiated and key is not return if ( this.searching && event.which !== 13 ) { options.replace = true; } else { this.searching = true; } // Update the URL hash if ( event.target.value ) { themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options ); } else { themes.router.navigate( themes.router.baseUrl( '' ) ); } }, 500 ), pushState: function( event ) { var url = themes.router.baseUrl( '' ); if ( event.target.value ) { url = themes.router.baseUrl( themes.router.searchPath + event.target.value ); } this.searching = false; themes.router.navigate( url ); } }); // Sets up the routes events for relevant url queries // Listens to [theme] and [search] params themes.Router = Backbone.Router.extend({ routes: { 'themes.php?theme=:slug': 'theme', 'themes.php?search=:query': 'search', 'themes.php?s=:query': 'search', 'themes.php': 'themes', '': 'themes' }, baseUrl: function( url ) { return 'themes.php' + url; }, themePath: '?theme=', searchPath: '?search=', search: function( query ) { $( '.wp-filter-search' ).val( query ); }, themes: function() { $( '.wp-filter-search' ).val( '' ); }, navigate: function() { if ( Backbone.history._hasPushState ) { Backbone.Router.prototype.navigate.apply( this, arguments ); } } }); // Execute and setup the application themes.Run = { init: function() { // Initializes the blog's theme library view // Create a new collection with data this.themes = new themes.Collection( themes.data.themes ); // Set up the view this.view = new themes.view.Appearance({ collection: this.themes }); this.render(); }, render: function() { // Render results this.view.render(); this.routes(); Backbone.history.start({ root: themes.data.settings.adminUrl, pushState: true, hashChange: false }); }, routes: function() { var self = this; // Bind to our global thx object // so that the object is available to sub-views themes.router = new themes.Router(); // Handles theme details route event themes.router.on( 'route:theme', function( slug ) { self.view.view.expand( slug ); }); themes.router.on( 'route:themes', function() { self.themes.doSearch( '' ); self.view.trigger( 'theme:close' ); }); // Handles search route event themes.router.on( 'route:search', function() { $( '.wp-filter-search' ).trigger( 'keyup' ); }); this.extraRoutes(); }, extraRoutes: function() { return false; } }; // Extend the main Search view themes.view.InstallerSearch = themes.view.Search.extend({ events: { 'input': 'search', 'keyup': 'search' }, terms: '', // Handles Ajax request for searching through themes in public repo search: function( event ) { // Tabbing or reverse tabbing into the search input shouldn't trigger a search if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) { return; } this.collection = this.options.parent.view.collection; // Clear on escape. if ( event.type === 'keyup' && event.which === 27 ) { event.target.value = ''; } this.doSearch( event.target.value ); }, doSearch: _.debounce( function( value ) { var request = {}; // Don't do anything if the search terms haven't changed. if ( this.terms === value ) { return; } // Updates terms with the value passed. this.terms = value; request.search = value; // Intercept an [author] search. // // If input value starts with `author:` send a request // for `author` instead of a regular `search` if ( value.substring( 0, 7 ) === 'author:' ) { request.search = ''; request.author = value.slice( 7 ); } // Intercept a [tag] search. // // If input value starts with `tag:` send a request // for `tag` instead of a regular `search` if ( value.substring( 0, 4 ) === 'tag:' ) { request.search = ''; request.tag = [ value.slice( 4 ) ]; } $( '.filter-links li > a.current' ).removeClass( 'current' ); $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' ); $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' ); // Get the themes by sending Ajax POST request to api.wordpress.org/themes // or searching the local cache this.collection.query( request ); // Set route themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } ); }, 500 ) }); themes.view.Installer = themes.view.Appearance.extend({ el: '#wpbody-content .wrap', // Register events for sorting and filters in theme-navigation events: { 'click .filter-links li > a': 'onSort', 'click .theme-filter': 'onFilter', 'click .drawer-toggle': 'moreFilters', 'click .filter-drawer .apply-filters': 'applyFilters', 'click .filter-group [type="checkbox"]': 'addFilter', 'click .filter-drawer .clear-filters': 'clearFilters', 'click .edit-filters': 'backToFilters', 'click .favorites-form-submit' : 'saveUsername', 'keyup #wporg-username-input': 'saveUsername' }, // Initial render method render: function() { var self = this; this.search(); this.uploader(); this.collection = new themes.Collection(); // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page. this.listenTo( this, 'theme:end', function() { // Make sure we are not already loading if ( self.collection.loadingThemes ) { return; } // Set loadingThemes to true and bump page instance of currentQuery. self.collection.loadingThemes = true; self.collection.currentQuery.page++; // Use currentQuery.page to build the themes request. _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } ); self.collection.query( self.collection.currentQuery.request ); }); this.listenTo( this.collection, 'query:success', function() { $( 'body' ).removeClass( 'loading-content' ); $( '.theme-browser' ).find( 'div.error' ).remove(); }); this.listenTo( this.collection, 'query:fail', function() { $( 'body' ).removeClass( 'loading-content' ); $( '.theme-browser' ).find( 'div.error' ).remove(); $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' ); }); if ( this.view ) { this.view.remove(); } // Set ups the view and passes the section argument this.view = new themes.view.Themes({ collection: this.collection, parent: this }); // Reset pagination every time the install view handler is run this.page = 0; // Render and append this.$el.find( '.themes' ).remove(); this.view.render(); this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' ); }, // Handles all the rendering of the public theme directory browse: function( section ) { // Create a new collection with the proper theme data // for each section this.collection.query( { browse: section } ); }, // Sorting navigation onSort: function( event ) { var $el = $( event.target ), sort = $el.data( 'sort' ); event.preventDefault(); $( 'body' ).removeClass( 'filters-applied show-filters' ); $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' ); // Bail if this is already active if ( $el.hasClass( this.activeClass ) ) { return; } this.sort( sort ); // Trigger a router.naviagte update themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) ); }, sort: function( sort ) { this.clearSearch(); $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass ); $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass ); if ( 'favorites' === sort ) { $( 'body' ).addClass( 'show-favorites-form' ); } else { $( 'body' ).removeClass( 'show-favorites-form' ); } this.browse( sort ); }, // Filters and Tags onFilter: function( event ) { var request, $el = $( event.target ), filter = $el.data( 'filter' ); // Bail if this is already active if ( $el.hasClass( this.activeClass ) ) { return; } $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass ); $el.addClass( this.activeClass ); if ( ! filter ) { return; } // Construct the filter request // using the default values filter = _.union( [ filter, this.filtersChecked() ] ); request = { tag: [ filter ] }; // Get the themes by sending Ajax POST request to api.wordpress.org/themes // or searching the local cache this.collection.query( request ); }, // Clicking on a checkbox to add another filter to the request addFilter: function() { this.filtersChecked(); }, // Applying filters triggers a tag request applyFilters: function( event ) { var name, tags = this.filtersChecked(), request = { tag: tags }, filteringBy = $( '.filtered-by .tags' ); if ( event ) { event.preventDefault(); } if ( ! tags ) { wp.a11y.speak( l10n.selectFeatureFilter ); return; } $( 'body' ).addClass( 'filters-applied' ); $( '.filter-links li > a.current' ).removeClass( 'current' ); filteringBy.empty(); _.each( tags, function( tag ) { name = $( 'label[for="filter-id-' + tag + '"]' ).text(); filteringBy.append( '<span class="tag">' + name + '</span>' ); }); // Get the themes by sending Ajax POST request to api.wordpress.org/themes // or searching the local cache this.collection.query( request ); }, // Save the user's WordPress.org username and get his favorite themes. saveUsername: function ( event ) { var username = $( '#wporg-username-input' ).val(), nonce = $( '#wporg-username-nonce' ).val(), request = { browse: 'favorites', user: username }, that = this; if ( event ) { event.preventDefault(); } // save username on enter if ( event.type === 'keyup' && event.which !== 13 ) { return; } return wp.ajax.send( 'save-wporg-username', { data: { _wpnonce: nonce, username: username }, success: function () { // Get the themes by sending Ajax POST request to api.wordpress.org/themes // or searching the local cache that.collection.query( request ); } } ); }, // Get the checked filters // @return {array} of tags or false filtersChecked: function() { var items = $( '.filter-group' ).find( ':checkbox' ), tags = []; _.each( items.filter( ':checked' ), function( item ) { tags.push( $( item ).prop( 'value' ) ); }); // When no filters are checked, restore initial state and return if ( tags.length === 0 ) { $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' ); $( '.filter-drawer .clear-filters' ).hide(); $( 'body' ).removeClass( 'filters-applied' ); return false; } $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length ); $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' ); return tags; }, activeClass: 'current', // Overwrite search container class to append search // in new location searchContainer: $( '.wp-filter .search-form' ), /* * When users press the "Upload Theme" button, show the upload form in place. */ uploader: function() { var uploadViewToggle = $( '.upload-view-toggle' ), $body = $( document.body ); uploadViewToggle.on( 'click', function() { // Toggle the upload view. $body.toggleClass( 'show-upload-view' ); // Toggle the `aria-expanded` button attribute. uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) ); }); }, // Toggle the full filters navigation moreFilters: function( event ) { var $body = $( 'body' ), $toggleButton = $( '.drawer-toggle' ); event.preventDefault(); if ( $body.hasClass( 'filters-applied' ) ) { return this.backToFilters(); } this.clearSearch(); themes.router.navigate( themes.router.baseUrl( '' ) ); // Toggle the feature filters view. $body.toggleClass( 'show-filters' ); // Toggle the `aria-expanded` button attribute. $toggleButton.attr( 'aria-expanded', $body.hasClass( 'show-filters' ) ); }, // Clears all the checked filters // @uses filtersChecked() clearFilters: function( event ) { var items = $( '.filter-group' ).find( ':checkbox' ), self = this; event.preventDefault(); _.each( items.filter( ':checked' ), function( item ) { $( item ).prop( 'checked', false ); return self.filtersChecked(); }); }, backToFilters: function( event ) { if ( event ) { event.preventDefault(); } $( 'body' ).removeClass( 'filters-applied' ); }, clearSearch: function() { $( '#wp-filter-search-input').val( '' ); } }); themes.InstallerRouter = Backbone.Router.extend({ routes: { 'theme-install.php?theme=:slug': 'preview', 'theme-install.php?browse=:sort': 'sort', 'theme-install.php?search=:query': 'search', 'theme-install.php': 'sort' }, baseUrl: function( url ) { return 'theme-install.php' + url; }, themePath: '?theme=', browsePath: '?browse=', searchPath: '?search=', search: function( query ) { $( '.wp-filter-search' ).val( query ); }, navigate: function() { if ( Backbone.history._hasPushState ) { Backbone.Router.prototype.navigate.apply( this, arguments ); } } }); themes.RunInstaller = { init: function() { // Set up the view // Passes the default 'section' as an option this.view = new themes.view.Installer({ section: 'featured', SearchView: themes.view.InstallerSearch }); // Render results this.render(); }, render: function() { // Render results this.view.render(); this.routes(); Backbone.history.start({ root: themes.data.settings.adminUrl, pushState: true, hashChange: false }); }, routes: function() { var self = this, request = {}; // Bind to our global `wp.themes` object // so that the router is available to sub-views themes.router = new themes.InstallerRouter(); // Handles `theme` route event // Queries the API for the passed theme slug themes.router.on( 'route:preview', function( slug ) { request.theme = slug; self.view.collection.query( request ); self.view.collection.once( 'update', function() { self.view.view.theme.preview(); }); }); // Handles sorting / browsing routes // Also handles the root URL triggering a sort request // for `featured`, the default view themes.router.on( 'route:sort', function( sort ) { if ( ! sort ) { sort = 'featured'; } self.view.sort( sort ); self.view.trigger( 'theme:close' ); }); // The `search` route event. The router populates the input field. themes.router.on( 'route:search', function() { $( '.wp-filter-search' ).focus().trigger( 'keyup' ); }); this.extraRoutes(); }, extraRoutes: function() { return false; } }; // Ready... $( document ).ready(function() { if ( themes.isInstall ) { themes.RunInstaller.init(); } else { themes.Run.init(); } $( '.broken-themes .delete-theme' ).on( 'click', function() { return confirm( _wpThemeSettings.settings.confirmDelete ); }); }); })( jQuery ); // Align theme browser thickbox var tb_position; jQuery(document).ready( function($) { tb_position = function() { var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 1040 < width ) ? 1040 : width, adminbar_height = 0; if ( $('#wpadminbar').length ) { adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 ); } 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'}); } } }; $(window).resize(function(){ tb_position(); }); }); widgets.js 0000666 00000041362 15213733063 0006565 0 ustar 00 /*global ajaxurl, isRtl */ var wpWidgets; (function($) { var $document = $( document ); wpWidgets = { /** * A closed Sidebar that gets a Widget dragged over it. * * @var element|null */ hoveredSidebar: null, init : function() { var rem, the_id, self = this, chooser = $('.widgets-chooser'), selectSidebar = chooser.find('.widgets-chooser-sidebars'), sidebars = $('div.widgets-sortables'), isRTL = !! ( 'undefined' !== typeof isRtl && isRtl ); $('#widgets-right .sidebar-name').click( function() { var $this = $(this), $wrap = $this.closest('.widgets-holder-wrap'); if ( $wrap.hasClass('closed') ) { $wrap.removeClass('closed'); $this.parent().sortable('refresh'); } else { $wrap.addClass('closed'); } $document.triggerHandler( 'wp-pin-menu' ); }); $('#widgets-left .sidebar-name').click( function() { $(this).closest('.widgets-holder-wrap').toggleClass('closed'); $document.triggerHandler( 'wp-pin-menu' ); }); $(document.body).bind('click.widgets-toggle', function(e) { var target = $(e.target), css = { 'z-index': 100 }, widget, inside, targetWidth, widgetWidth, margin; if ( target.parents('.widget-top').length && ! target.parents('#available-widgets').length ) { widget = target.closest('div.widget'); inside = widget.children('.widget-inside'); targetWidth = parseInt( widget.find('input.widget-width').val(), 10 ), widgetWidth = widget.parent().width(); if ( inside.is(':hidden') ) { if ( targetWidth > 250 && ( targetWidth + 30 > widgetWidth ) && widget.closest('div.widgets-sortables').length ) { if ( widget.closest('div.widget-liquid-right').length ) { margin = isRTL ? 'margin-right' : 'margin-left'; } else { margin = isRTL ? 'margin-left' : 'margin-right'; } css[ margin ] = widgetWidth - ( targetWidth + 30 ) + 'px'; widget.css( css ); } widget.addClass( 'open' ); inside.slideDown('fast'); } else { inside.slideUp('fast', function() { widget.attr( 'style', '' ); widget.removeClass( 'open' ); }); } 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') ) { widget = target.closest('div.widget'); widget.removeClass( 'open' ); wpWidgets.close( widget ); e.preventDefault(); } else if ( target.attr( 'id' ) === 'inactive-widgets-control-remove' ) { wpWidgets.removeInactiveWidgets(); e.preventDefault(); } }); sidebars.children('.widget').each( function() { var $this = $(this); wpWidgets.appendTitle( this ); if ( $this.find( 'p.widget-error' ).length ) { $this.find( 'a.widget-action' ).trigger('click'); } }); $('#widget-list').children('.widget').draggable({ connectToSortable: 'div.widgets-sortables', handle: '> .widget-top > .widget-title', distance: 2, helper: 'clone', zIndex: 100, containment: '#wpwrap', refreshPositions: true, start: function( event, ui ) { var chooser = $(this).find('.widgets-chooser'); ui.helper.find('div.widget-description').hide(); the_id = this.id; if ( chooser.length ) { // Hide the chooser and move it out of the widget $( '#wpbody-content' ).append( chooser.hide() ); // Delete the cloned chooser from the drag helper ui.helper.find('.widgets-chooser').remove(); self.clearWidgetSelection(); } }, stop: function() { if ( rem ) { $(rem).hide(); } rem = ''; } }); /** * Opens and closes previously closed Sidebars when Widgets are dragged over/out of them. */ sidebars.droppable( { tolerance: 'intersect', /** * Open Sidebar when a Widget gets dragged over it. * * @param event */ over: function( event ) { var $wrap = $( event.target ).parent(); if ( wpWidgets.hoveredSidebar && ! $wrap.is( wpWidgets.hoveredSidebar ) ) { // Close the previous Sidebar as the Widget has been dragged onto another Sidebar. wpWidgets.closeSidebar( event ); } if ( $wrap.hasClass( 'closed' ) ) { wpWidgets.hoveredSidebar = $wrap; $wrap.removeClass( 'closed' ); } $( this ).sortable( 'refresh' ); }, /** * Close Sidebar when the Widget gets dragged out of it. * * @param event */ out: function( event ) { if ( wpWidgets.hoveredSidebar ) { wpWidgets.closeSidebar( event ); } } } ); sidebars.sortable({ placeholder: 'widget-placeholder', items: '> .widget', handle: '> .widget-top > .widget-title', cursor: 'move', distance: 2, containment: '#wpwrap', tolerance: 'pointer', refreshPositions: true, start: function( event, ui ) { var height, $this = $(this), $wrap = $this.parent(), inside = ui.item.children('.widget-inside'); if ( inside.css('display') === 'block' ) { ui.item.removeClass('open'); inside.hide(); $(this).sortable('refreshPositions'); } if ( ! $wrap.hasClass('closed') ) { // Lock all open sidebars min-height when starting to drag. // Prevents jumping when dragging a widget from an open sidebar to a closed sidebar below. height = ui.item.hasClass('ui-draggable') ? $this.height() : 1 + $this.height(); $this.css( 'min-height', height + 'px' ); } }, stop: function( event, ui ) { var addNew, widgetNumber, $sidebar, $children, child, item, $widget = ui.item, id = the_id; // Reset the var to hold a previously closed sidebar. wpWidgets.hoveredSidebar = null; if ( $widget.hasClass('deleting') ) { wpWidgets.save( $widget, 1, 0, 1 ); // delete widget $widget.remove(); return; } addNew = $widget.find('input.add_new').val(); widgetNumber = $widget.find('input.multi_number').val(); $widget.attr( 'style', '' ).removeClass('ui-draggable'); the_id = ''; if ( addNew ) { if ( 'multi' === addNew ) { $widget.html( $widget.html().replace( /<[^<>]+>/g, function( tag ) { return tag.replace( /__i__|%i%/g, widgetNumber ); }) ); $widget.attr( 'id', id.replace( '__i__', widgetNumber ) ); widgetNumber++; $( 'div#' + id ).find( 'input.multi_number' ).val( widgetNumber ); } else if ( 'single' === addNew ) { $widget.attr( 'id', 'new-' + id ); rem = 'div#' + id; } wpWidgets.save( $widget, 0, 0, 1 ); $widget.find('input.add_new').val(''); $document.trigger( 'widget-added', [ $widget ] ); } $sidebar = $widget.parent(); if ( $sidebar.parent().hasClass('closed') ) { $sidebar.parent().removeClass('closed'); $children = $sidebar.children('.widget'); // Make sure the dropped widget is at the top if ( $children.length > 1 ) { child = $children.get(0); item = $widget.get(0); if ( child.id && item.id && child.id !== item.id ) { $( child ).before( $widget ); } } } if ( addNew ) { $widget.find( 'a.widget-action' ).trigger('click'); } else { wpWidgets.saveOrder( $sidebar.attr('id') ); } }, activate: function() { $(this).parent().addClass( 'widget-hover' ); }, deactivate: function() { // Remove all min-height added on "start" $(this).css( 'min-height', '' ).parent().removeClass( 'widget-hover' ); }, receive: function( event, ui ) { var $sender = $( ui.sender ); // Don't add more widgets to orphaned sidebars if ( this.id.indexOf('orphaned_widgets') > -1 ) { $sender.sortable('cancel'); return; } // If the last widget was moved out of an orphaned sidebar, close and remove it. 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' ); $('#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').empty(); }, 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( 'h3' ).html() ); } }, out: function(e,ui) { ui.draggable.removeClass('deleting'); $('div.widget-placeholder').show(); $('#removing-widget').hide().children('span').empty(); } }); // Area Chooser $( '#widgets-right .widgets-holder-wrap' ).each( function( index, element ) { var $element = $( element ), name = $element.find( '.sidebar-name h2' ).text(), id = $element.find( '.widgets-sortables' ).attr( 'id' ), li = $('<li tabindex="0">').text( $.trim( name ) ); if ( index === 0 ) { li.addClass( 'widgets-chooser-selected' ); } selectSidebar.append( li ); li.data( 'sidebarId', id ); }); $( '#available-widgets .widget .widget-title' ).on( 'click.widgets-chooser', function() { var $widget = $(this).closest( '.widget' ); if ( $widget.hasClass( 'widget-in-question' ) || $( '#widgets-left' ).hasClass( 'chooser' ) ) { self.closeChooser(); } else { // Open the chooser self.clearWidgetSelection(); $( '#widgets-left' ).addClass( 'chooser' ); $widget.addClass( 'widget-in-question' ).children( '.widget-description' ).after( chooser ); chooser.slideDown( 300, function() { selectSidebar.find('.widgets-chooser-selected').focus(); }); selectSidebar.find( 'li' ).on( 'focusin.widgets-chooser', function() { selectSidebar.find('.widgets-chooser-selected').removeClass( 'widgets-chooser-selected' ); $(this).addClass( 'widgets-chooser-selected' ); } ); } }); // Add event handlers chooser.on( 'click.widgets-chooser', function( event ) { var $target = $( event.target ); if ( $target.hasClass('button-primary') ) { self.addWidget( chooser ); self.closeChooser(); } else if ( $target.hasClass( 'widgets-chooser-cancel' ) ) { self.closeChooser(); } }).on( 'keyup.widgets-chooser', function( event ) { if ( event.which === $.ui.keyCode.ENTER ) { if ( $( event.target ).hasClass( 'widgets-chooser-cancel' ) ) { // Close instead of adding when pressing Enter on the Cancel button self.closeChooser(); } else { self.addWidget( chooser ); self.closeChooser(); } } else if ( event.which === $.ui.keyCode.ESCAPE ) { self.closeChooser(); } }); }, saveOrder : function( sidebarId ) { var data = { action: 'widgets-order', savewidgets: $('#_wpnonce_widgets').val(), sidebars: [] }; if ( sidebarId ) { $( '#' + sidebarId ).find( '.spinner:first' ).addClass( 'is-active' ); } $('div.widgets-sortables').each( function() { if ( $(this).sortable ) { data['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(','); } }); $.post( ajaxurl, data, function() { $( '#inactive-widgets-control-remove' ).prop( 'disabled' , ! $( '#wp_inactive_widgets .widget' ).length ); $( '.spinner' ).removeClass( 'is-active' ); }); }, save : function( widget, del, animate, order ) { var sidebarId = widget.closest('div.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a; widget = $(widget); $( '.spinner', widget ).addClass( 'is-active' ); a = { action: 'save-widget', savewidgets: $('#_wpnonce_widgets').val(), sidebar: sidebarId }; 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(); if ( sidebarId === 'wp_inactive_widgets' ) { $( '#inactive-widgets-control-remove' ).prop( 'disabled' , ! $( '#wp_inactive_widgets .widget' ).length ); } } } else { $( '.spinner' ).removeClass( 'is-active' ); if ( r && r.length > 2 ) { $( 'div.widget-content', widget ).html( r ); wpWidgets.appendTitle( widget ); $document.trigger( 'widget-updated', [ widget ] ); if ( sidebarId === 'wp_inactive_widgets' ) { $( '#inactive-widgets-control-remove' ).prop( 'disabled' , ! $( '#wp_inactive_widgets .widget' ).length ); } } } if ( order ) { wpWidgets.saveOrder(); } }); }, removeInactiveWidgets : function() { var $element = $( '.remove-inactive-widgets' ), a, data; $( '.spinner', $element ).addClass( 'is-active' ); a = { action : 'delete-inactive-widgets', removeinactivewidgets : $( '#_wpnonce_remove_inactive_widgets' ).val() }; data = $.param( a ); $.post( ajaxurl, data, function() { $( '#wp_inactive_widgets .widget' ).remove(); $( '#inactive-widgets-control-remove' ).prop( 'disabled' , true ); $( '.spinner', $element ).removeClass( 'is-active' ); } ); }, appendTitle : function(widget) { var title = $('input[id*="-title"]', widget).val() || ''; if ( title ) { title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '<').replace(/>/g, '>'); } $(widget).children('.widget-top').children('.widget-title').children() .children('.in-widget-title').html(title); }, close : function(widget) { widget.children('.widget-inside').slideUp('fast', function() { widget.attr( 'style', '' ); }); }, addWidget: function( chooser ) { var widget, widgetId, add, n, viewportTop, viewportBottom, sidebarBounds, sidebarId = chooser.find( '.widgets-chooser-selected' ).data('sidebarId'), sidebar = $( '#' + sidebarId ); widget = $('#available-widgets').find('.widget-in-question').clone(); widgetId = widget.attr('id'); add = widget.find( 'input.add_new' ).val(); n = widget.find( 'input.multi_number' ).val(); // Remove the cloned chooser from the widget widget.find('.widgets-chooser').remove(); if ( 'multi' === add ) { widget.html( widget.html().replace( /<[^<>]+>/g, function(m) { return m.replace( /__i__|%i%/g, n ); }) ); widget.attr( 'id', widgetId.replace( '__i__', n ) ); n++; $( '#' + widgetId ).find('input.multi_number').val(n); } else if ( 'single' === add ) { widget.attr( 'id', 'new-' + widgetId ); $( '#' + widgetId ).hide(); } // Open the widgets container sidebar.closest( '.widgets-holder-wrap' ).removeClass('closed'); sidebar.append( widget ); sidebar.sortable('refresh'); wpWidgets.save( widget, 0, 0, 1 ); // No longer "new" widget widget.find( 'input.add_new' ).val(''); $document.trigger( 'widget-added', [ widget ] ); /* * Check if any part of the sidebar is visible in the viewport. If it is, don't scroll. * Otherwise, scroll up to so the sidebar is in view. * * We do this by comparing the top and bottom, of the sidebar so see if they are within * the bounds of the viewport. */ viewportTop = $(window).scrollTop(); viewportBottom = viewportTop + $(window).height(); sidebarBounds = sidebar.offset(); sidebarBounds.bottom = sidebarBounds.top + sidebar.outerHeight(); if ( viewportTop > sidebarBounds.bottom || viewportBottom < sidebarBounds.top ) { $( 'html, body' ).animate({ scrollTop: sidebarBounds.top - 130 }, 200 ); } window.setTimeout( function() { // Cannot use a callback in the animation above as it fires twice, // have to queue this "by hand". widget.find( '.widget-title' ).trigger('click'); }, 250 ); }, closeChooser: function() { var self = this; $( '.widgets-chooser' ).slideUp( 200, function() { $( '#wpbody-content' ).append( this ); self.clearWidgetSelection(); }); }, clearWidgetSelection: function() { $( '#widgets-left' ).removeClass( 'chooser' ); $( '.widget-in-question' ).removeClass( 'widget-in-question' ); }, /** * Closes a Sidebar that was previously closed, but opened by dragging a Widget over it. * * Used when a Widget gets dragged in/out of the Sidebar and never dropped. * * @param sidebar */ closeSidebar: function( sidebar ) { this.hoveredSidebar.addClass( 'closed' ); $( sidebar.target ).css( 'min-height', '' ); this.hoveredSidebar = null; } }; $document.ready( function(){ wpWidgets.init(); } ); })(jQuery); accordion.min.js 0000666 00000001476 15213733063 0007644 0 ustar 00 !function(s){s(document).ready(function(){s(".accordion-container").on("click keydown",".accordion-section-title",function(e){var n,o,a,i,t;"keydown"===e.type&&13!==e.which||(e.preventDefault(),n=s(this),o=n.closest(".accordion-section"),a=o.find("[aria-expanded]").first(),i=o.closest(".accordion-container"),t=i.find(".open"),e=t.find("[aria-expanded]").first(),n=o.find(".accordion-section-content"),o.hasClass("cannot-expand")||(i.addClass("opening"),o.hasClass("open")?(o.toggleClass("open"),n.toggle(!0).slideToggle(150)):(e.attr("aria-expanded","false"),t.removeClass("open"),t.find(".accordion-section-content").show().slideUp(150),n.toggle(!1).slideToggle(150),o.toggleClass("open")),setTimeout(function(){i.removeClass("opening")},150),a&&a.attr("aria-expanded",String("false"===a.attr("aria-expanded")))))})})}(jQuery); dashboard.min.js 0000666 00000006122 15213733063 0007623 0 ustar 00 var ajaxWidgets,ajaxPopulateWidgets,quickPressLoad;jQuery(document).ready(function(o){var t,s=o("#welcome-panel"),e=o("#wp_welcome_panel-hide");t=function(e){o.post(ajaxurl,{action:"update-welcome-panel",visible:e,welcomepanelnonce:o("#welcomepanelnonce").val()})},s.hasClass("hidden")&&e.prop("checked")&&s.removeClass("hidden"),o(".welcome-panel-close, .welcome-panel-dismiss a",s).click(function(e){e.preventDefault(),s.addClass("hidden"),t(0),o("#wp_welcome_panel-hide").prop("checked",!1)}),e.click(function(){s.toggleClass("hidden",!this.checked),t(this.checked?1:0)}),ajaxWidgets=["dashboard_primary"],(ajaxPopulateWidgets=function(e){function t(e,t){var s,i=o("#"+t+" div.inside:visible").find(".widget-loading");i.length&&(s=i.parent(),setTimeout(function(){s.load(ajaxurl+"?action=dashboard-widgets&widget="+t+"&pagenow="+pagenow,"",function(){s.hide().slideDown("normal",function(){o(this).css("display","")})})},500*e))}e?(e=e.toString(),-1!==o.inArray(e,ajaxWidgets)&&t(0,e)):o.each(ajaxWidgets,t)})(),postboxes.add_postbox_toggles(pagenow,{pbshow:ajaxPopulateWidgets}),(quickPressLoad=function(){var t,s,i,n,a,e=o("#quickpost-action");o('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop("disabled",!1),t=o("#quick-press").submit(function(e){e.preventDefault(),o("#dashboard_quick_press #publishing-action .spinner").show(),o('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop("disabled",!0),o.post(t.attr("action"),t.serializeArray(),function(e){var t;o("#dashboard_quick_press .inside").html(e),o("#quick-press").removeClass("initial-form"),quickPressLoad(),(t=o(".drafts ul li").first()).css("background","#fffbe5"),setTimeout(function(){t.css("background","none")},1e3),o("#title").focus()})}),o("#publish").click(function(){e.val("post-quickpress-publish")}),o("#title, #tags-input, #content").each(function(){var e=o(this),t=o("#"+this.id+"-prompt-text");""===this.value&&t.removeClass("screen-reader-text"),t.click(function(){o(this).addClass("screen-reader-text"),e.focus()}),e.blur(function(){""===this.value&&t.removeClass("screen-reader-text")}),e.focus(function(){t.addClass("screen-reader-text")})}),o("#quick-press").on("click focusin",function(){wpActiveEditor="content"}),document.documentMode&&document.documentMode<9||(o("body").append('<div class="quick-draft-textarea-clone" style="display: none;"></div>'),s=o(".quick-draft-textarea-clone"),i=o("#content"),n=i.height(),a=o(window).height()-100,s.css({"font-family":i.css("font-family"),"font-size":i.css("font-size"),"line-height":i.css("line-height"),"padding-bottom":i.css("paddingBottom"),"padding-left":i.css("paddingLeft"),"padding-right":i.css("paddingRight"),"padding-top":i.css("paddingTop"),"white-space":"pre-wrap","word-wrap":"break-word",display:"none"}),i.on("focus input propertychange",function(){var e=o(this),t=e.val()+" ",t=s.css("width",e.css("width")).text(t).outerHeight()+2;i.css("overflow-y","auto"),t===n||a<=t&&a<=n||(n=a<t?a:t,i.css("overflow","hidden"),e.css("height",n+"px"))}))})(),o(".meta-box-sortables").sortable("option","containment","#wpwrap")}); comment.min.js 0000666 00000002316 15213733063 0007337 0 ustar 00 jQuery(document).ready(function(m){postboxes.add_postbox_toggles("comment");var d=m("#timestampdiv"),c=m("#timestamp"),a=c.html(),o=d.find(".timestamp-wrap"),v=d.siblings("a.edit-timestamp");v.click(function(e){d.is(":hidden")&&(d.slideDown("fast",function(){m("input, select",o).first().focus()}),m(this).hide()),e.preventDefault()}),d.find(".cancel-timestamp").click(function(e){v.show().focus(),d.slideUp("fast"),m("#mm").val(m("#hidden_mm").val()),m("#jj").val(m("#hidden_jj").val()),m("#aa").val(m("#hidden_aa").val()),m("#hh").val(m("#hidden_hh").val()),m("#mn").val(m("#hidden_mn").val()),c.html(a),e.preventDefault()}),d.find(".save-timestamp").click(function(e){var a=m("#aa").val(),t=m("#mm").val(),l=m("#jj").val(),i=m("#hh").val(),n=m("#mn").val(),s=new Date(a,t-1,l,i,n);e.preventDefault(),s.getFullYear()==a&&1+s.getMonth()==t&&s.getDate()==l&&s.getMinutes()==n?(o.removeClass("form-invalid"),c.html(commentL10n.submittedOn+" <b>"+commentL10n.dateFormat.replace("%1$s",m('option[value="'+t+'"]',"#mm").attr("data-text")).replace("%2$s",parseInt(l,10)).replace("%3$s",a).replace("%4$s",("00"+i).slice(-2)).replace("%5$s",("00"+n).slice(-2))+"</b> "),v.show().focus(),d.slideUp("fast")):o.addClass("form-invalid")})}); set-post-thumbnail.js 0000666 00000001411 15213733063 0010645 0 ustar 00 /* global setPostThumbnailL10n, ajaxurl, post_id, alert */ /* exported WPSetAsThumbnail */ 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); } } ); } post.js 0000666 00000111041 15213733063 0006074 0 ustar 00 /* global postL10n, ajaxurl, wpAjax, setPostThumbnailL10n, postboxes, pagenow, tinymce, alert, deleteUserSetting */ /* global theList:true, theExtraList:true, getUserSetting, setUserSetting, commentReply */ /** * Contains all dynamic functionality needed on post and term pages. * * @summary Control page and term functionality. */ var commentsBox, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint, makeSlugeditClickable, editPermalink; // Backwards compatibility: prevent fatal errors. makeSlugeditClickable = editPermalink = function(){}; // Make sure the wp object exists. window.wp = window.wp || {}; ( function( $ ) { var titleHasFocus = false; /** * Control loading of comments on the post and term edit pages. * * @type {{st: number, get: commentsBox.get, load: commentsBox.load}} * * @namespace commentsBox */ commentsBox = { // Comment offset to use when fetching new comments. st : 0, /** * Fetch comments using AJAX and display them in the box. * * @param {int} total Total number of comments for this post. * @param {int} num Optional. Number of comments to fetch, defaults to 20. * @returns {boolean} Always returns false. * * @memberof commentsBox */ get : function(total, num) { var st = this.st, data; if ( ! num ) num = 20; this.st += num; this.total = total; $( '#commentsdiv .spinner' ).addClass( 'is-active' ); 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' ).removeClass( 'is-active' ); if ( 'object' == typeof r && r.responses[0] ) { $('#the-comment-list').append( r.responses[0].data ); theList = theExtraList = null; $( 'a[className*=\':\']' ).unbind(); // If the offset is over the total number of comments we cannot fetch any more, so hide the button. 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; }, /** * Load the next batch of comments. * * @param {int} total Total number of comments to load. * * @memberof commentsBox */ load: function(total){ this.st = jQuery('#the-comment-list tr.comment:visible').length; this.get(total); } }; /** * Overwrite the content of the Featured Image postbox * * @param {string} html New HTML to be displayed in the content area of the postbox. * * @global */ WPSetThumbnailHTML = function(html){ $('.inside', '#postimagediv').html(html); }; /** * Set the Image ID of the Featured Image * * @param {int} id The post_id of the image to use as Featured Image. * * @global */ WPSetThumbnailID = function(id){ var field = $('input[value="_thumbnail_id"]', '#list-table'); if ( field.length > 0 ) { $('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id); } }; /** * Remove the Featured Image * * @param {string} nonce Nonce to use in the request. * * @global */ WPRemoveThumbnail = function(nonce){ $.post(ajaxurl, { action: 'set-post-thumbnail', post_id: $( '#post_ID' ).val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent( document.cookie ) }, /** * Handle server response * * @param {string} str Response, will be '0' when an error occurred otherwise contains link to add Featured Image. */ function(str){ if ( str == '0' ) { alert( setPostThumbnailL10n.error ); } else { WPSetThumbnailHTML(str); } } ); }; /** * Heartbeat locks. * * Used to lock editing of an object by only one user at a time. * * When the user does not send a heartbeat in a heartbeat-time * the user is no longer editing and another user can start editing. */ $(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; }).on( 'heartbeat-tick.refresh-lock', function( e, data ) { // Post locks: update the lock string or show the dialog if somebody has taken over editing. 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 ( wp.autosave ) { // Save the latest changes and disable. $(document).one( 'heartbeat-tick', function() { wp.autosave.server.suspend(); wrap.removeClass('saving').addClass('saved'); $(window).off( 'beforeunload.edit-post' ); }); wrap.addClass('saving'); wp.autosave.server.triggerSave(); } if ( received.lock_error.avatar_src ) { avatar = $( '<img class="avatar avatar-64 photo" width="64" height="64" alt="" />' ).attr( 'src', received.lock_error.avatar_src.replace( /&/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 ); } } }).on( 'before-autosave.update-post-slug', function() { titleHasFocus = document.activeElement && document.activeElement.id === 'title'; }).on( 'after-autosave.update-post-slug', function() { /* * Create slug area only if not already there * and the title field was not focused (user was not typing a title) when autosave ran. */ if ( ! $('#edit-slug-box > *').length && ! titleHasFocus ) { $.post( ajaxurl, { action: 'sample-permalink', post_id: $('#post_ID').val(), new_title: $('#title').val(), samplepermalinknonce: $('#samplepermalinknonce').val() }, function( data ) { if ( data != '-1' ) { $('#edit-slug-box').html(data); } } ); } }); }(jQuery)); /** * Heartbeat refresh nonces. */ (function($) { var check, timeout; /** * Only allow to check for nonce refresh every 30 seconds. */ 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 post_id, $authCheck = $('#wp-auth-check-wrap'); if ( check || ( $authCheck.length && ! $authCheck.hasClass( 'hidden' ) ) ) { if ( ( post_id = $('#post_ID').val() ) && $('#_wpnonce').val() ) { data['wp-refresh-post-nonces'] = { post_id: post_id }; } } }).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)); /** * All post and postbox controls and functionality. */ jQuery(document).ready( function($) { var stamp, visibility, $submitButtons, updateVisibility, updateText, sticky = '', $textarea = $('#content'), $document = $(document), postId = $('#post_ID').val() || 0, $submitpost = $('#submitpost'), releaseLock = true, $postVisibilitySelect = $('#post-visibility-select'), $timestampdiv = $('#timestampdiv'), $postStatusSelect = $('#post-status-select'), isMac = window.navigator.platform ? window.navigator.platform.indexOf( 'Mac' ) !== -1 : false; postboxes.add_postbox_toggles(pagenow); /* * Clear the window name. Otherwise if this is a former preview window where the user navigated to edit another post, * and the first post is still being edited, clicking Preview there will use this window to show the preview. */ window.name = ''; // 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) { // Don't do anything when [tab] is pressed. if ( e.which != 9 ) return; var target = $(e.target); // [shift] + [tab] on first tab cycles back to last tab. if ( target.hasClass('wp-tab-first') && e.shiftKey ) { $(this).find('.wp-tab-last').focus(); e.preventDefault(); // [tab] on last tab cycles back to first tab. } else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) { $(this).find('.wp-tab-first').focus(); e.preventDefault(); } }).filter(':visible').find('.wp-tab-first').focus(); // Set the heartbeat interval to 15 sec. if post lock dialogs are enabled. if ( wp.heartbeat && $('#post-lock-dialog').length ) { wp.heartbeat.interval( 15 ); } // The form is being submitted by the user. $submitButtons = $submitpost.find( ':submit, a.submitdelete, #post-preview' ).on( 'click.edit-post', function( event ) { var $button = $(this); if ( $button.hasClass('disabled') ) { event.preventDefault(); return; } if ( $button.hasClass('submitdelete') || $button.is( '#post-preview' ) ) { return; } // The form submission can be blocked from JS or by using HTML 5.0 validation on some fields. // Run this only on an actual 'submit'. $('form#post').off( 'submit.edit-post' ).on( 'submit.edit-post', function( event ) { if ( event.isDefaultPrevented() ) { return; } // Stop auto save. if ( wp.autosave ) { wp.autosave.server.suspend(); } if ( typeof commentReply !== 'undefined' ) { /* * Warn the user they have an unsaved comment before submitting * the post data for update. */ if ( ! commentReply.discardCommentChanges() ) { return false; } /* * Close the comment edit/reply form if open to stop the form * action from interfering with the post's form action. */ commentReply.close(); } releaseLock = false; $(window).off( 'beforeunload.edit-post' ); $submitButtons.addClass( 'disabled' ); if ( $button.attr('id') === 'publish' ) { $submitpost.find( '#major-publishing-actions .spinner' ).addClass( 'is-active' ); } else { $submitpost.find( '#minor-publishing .spinner' ).addClass( 'is-active' ); } }); }); // Submit the form saving a draft or an autosave, and show a preview in a new tab $('#post-preview').on( 'click.post-preview', function( event ) { var $this = $(this), $form = $('form#post'), $previewField = $('input#wp-preview'), target = $this.attr('target') || 'wp-preview', ua = navigator.userAgent.toLowerCase(); event.preventDefault(); if ( $this.hasClass('disabled') ) { return; } if ( wp.autosave ) { wp.autosave.server.tempBlockSave(); } $previewField.val('dopreview'); $form.attr( 'target', target ).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 if ( ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1 ) { $form.attr( 'action', function( index, value ) { return value + '?t=' + ( new Date() ).getTime(); }); } $previewField.val(''); }); // This code is meant to allow tabbing from Title to Post content. $('#title').on( 'keydown.editor-focus', function( event ) { var editor; if ( event.keyCode === 9 && ! event.ctrlKey && ! event.altKey && ! event.shiftKey ) { editor = typeof tinymce != 'undefined' && tinymce.get('content'); if ( editor && ! editor.isHidden() ) { editor.focus(); } else if ( $textarea.length ) { $textarea.focus(); } else { return; } event.preventDefault(); } }); // Auto save new posts after a title is typed. if ( $( '#auto_draft' ).val() ) { $( '#title' ).blur( function() { var cancel; if ( ! this.value || $('#edit-slug-box > *').length ) { return; } // Cancel the auto save when the blur was triggered by the user submitting the form. $('form#post').one( 'submit', function() { cancel = true; }); window.setTimeout( function() { if ( ! cancel && wp.autosave ) { wp.autosave.server.triggerSave(); } }, 200 ); }); } $document.on( 'autosave-disable-buttons.edit-post', function() { $submitButtons.addClass( 'disabled' ); }).on( 'autosave-enable-buttons.edit-post', function() { if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) { $submitButtons.removeClass( 'disabled' ); } }).on( 'before-autosave.edit-post', function() { $( '.autosave-message' ).text( postL10n.savingText ); }).on( 'after-autosave.edit-post', function( event, data ) { $( '.autosave-message' ).text( data.message ); if ( $( document.body ).hasClass( 'post-new-php' ) ) { $( '.submitbox .submitdelete' ).show(); } }); /* * When the user is trying to load another page, or reloads current page * show a confirmation dialog when there are unsaved changes. */ $(window).on( 'beforeunload.edit-post', function() { var editor = typeof tinymce !== 'undefined' && tinymce.get('content'); if ( ( editor && ! editor.isHidden() && editor.isDirty() ) || ( wp.autosave && wp.autosave.server.postChanged() ) ) { return postL10n.saveAlert; } }).on( 'unload.edit-post', function( event ) { if ( ! releaseLock ) { return; } /* * Unload is triggered (by hand) on removing the Thickbox iframe. * Make sure we process only the main document unload. */ if ( event.target && event.target.nodeName != '#document' ) { return; } var postID = $('#post_ID').val(); var postLock = $('#active_post_lock').val(); if ( ! postID || ! postLock ) { return; } var data = { action: 'wp-remove-post-lock', _wpnonce: $('#_wpnonce').val(), post_ID: postID, active_post_lock: postLock }; if ( window.FormData && window.navigator.sendBeacon ) { var formData = new window.FormData(); $.each( data, function( key, value ) { formData.append( key, value ); }); if ( window.navigator.sendBeacon( ajaxurl, formData ) ) { return; } } // Fall back to a synchronous POST request. // See https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon $.post({ async: false, data: data, url: ajaxurl }); }); // Multiple Taxonomies. if ( $('#tagsdiv-post_tag').length ) { window.tagBox && window.tagBox.init(); } else { $('.meta-box-sortables').children('div.postbox').each(function(){ if ( this.id.indexOf('tagsdiv-') === 0 ) { window.tagBox && window.tagBox.init(); return false; } }); } // Handle 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( e ) { e.preventDefault(); 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' ); } }); if ( getUserSetting( settingName ) ) $('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click(); // Add category button controls. $('#new' + taxonomy).one( 'focus', function() { $( this ).val( '' ).removeClass( 'form-input-tip' ); }); // On [enter] submit the taxonomy. $('#new' + taxonomy).keypress( function(event){ if( 13 === event.keyCode ) { event.preventDefault(); $('#' + taxonomy + '-add-submit').click(); } }); // After submitting a new taxonomy, re-focus the input field. $('#' + taxonomy + '-add-submit').click( function() { $('#new' + taxonomy).focus(); }); /** * Before adding a new taxonomy, disable submit button. * * @param {Object} s Taxonomy object which will be added. * * @returns {Object} */ catAddBefore = function( s ) { if ( !$('#new'+taxonomy).val() ) { return false; } s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize(); $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true ); return s; }; /** * Re-enable submit button after a taxonomy has been added. * * Re-enable submit button. * If the taxonomy has a parent place the taxonomy underneath the parent. * * @param {Object} r Response. * @param {Object} s Taxonomy data. * * @returns void */ 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 }); // Add new taxonomy button toggles input form visibility. $('#' + taxonomy + '-add-toggle').click( function( e ) { e.preventDefault(); $('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' ); $('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click(); $('#new'+taxonomy).focus(); }); // Sync checked items between "All {taxonomy}" and "Most used" lists. $('#' + 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 postbox. if ( $('#postcustom').length ) { $( '#the-list' ).wpList( { /** * Add current post_ID to request to fetch custom fields * * @param {Object} s Request object. * * @returns {Object} Data modified with post_ID attached. */ addBefore: function( s ) { s.data += '&post_id=' + $('#post_ID').val(); return s; }, /** * Show the listing of custom fields after fetching. */ addAfter: function() { $('table#list-table').show(); } }); } /* * Publish Post box (#submitdiv) */ if ( $('#submitdiv').length ) { stamp = $('#timestamp').html(); visibility = $('#post-visibility-display').html(); /** * When the visibility of a post changes sub-options should be shown or hidden. * * @returns void */ updateVisibility = function() { // Show sticky for public posts. if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) { $('#sticky').prop('checked', false); $('#sticky-span').hide(); } else { $('#sticky-span').show(); } // Show password input field for password protected post. if ( $postVisibilitySelect.find('input:radio:checked').val() != 'password' ) { $('#password-span').hide(); } else { $('#password-span').show(); } }; /** * Make sure all labels represent the current settings. * * @returns {boolean} False when an invalid timestamp has been selected, otherwise True. */ updateText = function() { 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() ); // Catch unexpected date problems. if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) { $timestampdiv.find('.timestamp-wrap').addClass('form-invalid'); return false; } else { $timestampdiv.find('.timestamp-wrap').removeClass('form-invalid'); } // Determine what the publish should be depending on the date and post status. 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 the date is the same, set it to trigger update events. if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { // Re-set to the current value. $('#timestamp').html(stamp); } else { $('#timestamp').html( '\n' + publishOn + ' <b>' + postL10n.dateFormat .replace( '%1$s', $( 'option[value="' + mm + '"]', '#mm' ).attr( 'data-text' ) ) .replace( '%2$s', parseInt( jj, 10 ) ) .replace( '%3$s', aa ) .replace( '%4$s', ( '00' + hh ).slice( -2 ) ) .replace( '%5$s', ( '00' + mn ).slice( -2 ) ) + '</b> ' ); } // Add "privately published" to post status when applies. if ( $postVisibilitySelect.find('input:radio:checked').val() == 'private' ) { $('#publish').val( postL10n.update ); if ( 0 === optPublish.length ) { postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>'); } else { optPublish.html( postL10n.privatelyPublished ); } $('option[value="publish"]', postStatus).prop('selected', true); $('#misc-publishing-actions .edit-post-status').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') ) $('#misc-publishing-actions .edit-post-status').show(); } // Update "Status:" to currently selected status. $('#post-status-display').html($('option:selected', postStatus).text()); // Show or hide the "Save Draft" button. 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; }; // Show the visibility options and hide the toggle button when opened. $( '#visibility .edit-visibility').click( function( e ) { e.preventDefault(); if ( $postVisibilitySelect.is(':hidden') ) { updateVisibility(); $postVisibilitySelect.slideDown( 'fast', function() { $postVisibilitySelect.find( 'input[type="radio"]' ).first().focus(); } ); $(this).hide(); } }); // Cancel visibility selection area and hide it from view. $postVisibilitySelect.find('.cancel-post-visibility').click( function( event ) { $postVisibilitySelect.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); $('#visibility .edit-visibility').show().focus(); updateText(); event.preventDefault(); }); // Set the selected visibility as current. $postVisibilitySelect.find('.save-post-visibility').click( function( event ) { // crazyhorse - multiple ok cancels $postVisibilitySelect.slideUp('fast'); $('#visibility .edit-visibility').show().focus(); updateText(); if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) { $('#sticky').prop('checked', false); } if ( $('#sticky').prop('checked') ) { sticky = 'Sticky'; } else { sticky = ''; } $('#post-visibility-display').html( postL10n[ $postVisibilitySelect.find('input:radio:checked').val() + sticky ] ); event.preventDefault(); }); // When the selection changes, update labels. $postVisibilitySelect.find('input:radio').change( function() { updateVisibility(); }); // Edit publish time click. $timestampdiv.siblings('a.edit-timestamp').click( function( event ) { if ( $timestampdiv.is( ':hidden' ) ) { $timestampdiv.slideDown( 'fast', function() { $( 'input, select', $timestampdiv.find( '.timestamp-wrap' ) ).first().focus(); } ); $(this).hide(); } event.preventDefault(); }); // Cancel editing the publish time and hide the settings. $timestampdiv.find('.cancel-timestamp').click( function( event ) { $timestampdiv.slideUp('fast').siblings('a.edit-timestamp').show().focus(); $('#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()); updateText(); event.preventDefault(); }); // Save the changed timestamp. $timestampdiv.find('.save-timestamp').click( function( event ) { // crazyhorse - multiple ok cancels if ( updateText() ) { $timestampdiv.slideUp('fast'); $timestampdiv.siblings('a.edit-timestamp').show().focus(); } event.preventDefault(); }); // Cancel submit when an invalid timestamp has been selected. $('#post').on( 'submit', function( event ) { if ( ! updateText() ) { event.preventDefault(); $timestampdiv.show(); if ( wp.autosave ) { wp.autosave.enableButtons(); } $( '#publishing-action .spinner' ).removeClass( 'is-active' ); } }); // Post Status edit click. $postStatusSelect.siblings('a.edit-post-status').click( function( event ) { if ( $postStatusSelect.is( ':hidden' ) ) { $postStatusSelect.slideDown( 'fast', function() { $postStatusSelect.find('select').focus(); } ); $(this).hide(); } event.preventDefault(); }); // Save the Post Status changes and hide the options. $postStatusSelect.find('.save-post-status').click( function( event ) { $postStatusSelect.slideUp( 'fast' ).siblings( 'a.edit-post-status' ).show().focus(); updateText(); event.preventDefault(); }); // Cancel Post Status editing and hide the options. $postStatusSelect.find('.cancel-post-status').click( function( event ) { $postStatusSelect.slideUp( 'fast' ).siblings( 'a.edit-post-status' ).show().focus(); $('#post_status').val( $('#hidden_post_status').val() ); updateText(); event.preventDefault(); }); } /** * Handle the editing of the post_name. Create the required HTML elements and update the changes via AJAX. * * @summary Permalink aka slug aka post_name editing * * @global * * @returns void */ function editPermalink() { var i, slug_value, $el, revert_e, c = 0, real_slug = $('#post_name'), revert_slug = real_slug.val(), permalink = $( '#sample-permalink' ), permalinkOrig = permalink.html(), permalinkInner = $( '#sample-permalink a' ).html(), buttons = $('#edit-slug-buttons'), buttonsOrig = buttons.html(), full = $('#editable-post-name-full'); // Deal with Twemoji in the post-name. full.find( 'img' ).replaceWith( function() { return this.alt; } ); full = full.html(); permalink.html( permalinkInner ); // Save current content to revert to when cancelling. $el = $( '#editable-post-name' ); revert_e = $el.html(); buttons.html( '<button type="button" class="save button button-small">' + postL10n.ok + '</button> <button type="button" class="cancel button-link">' + postL10n.cancel + '</button>' ); // Save permalink changes. buttons.children( '.save' ).click( function() { var new_slug = $el.children( 'input' ).val(); if ( new_slug == $('#editable-post-name-full').text() ) { buttons.children('.cancel').click(); return; } $.post( ajaxurl, { action: 'sample-permalink', post_id: postId, 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'); }); } buttons.html(buttonsOrig); permalink.html(permalinkOrig); real_slug.val(new_slug); $( '.edit-slug' ).focus(); wp.a11y.speak( postL10n.permalinkSaved ); } ); }); // Cancel editing of permalink. buttons.children( '.cancel' ).click( function() { $('#view-post-btn').show(); $el.html(revert_e); buttons.html(buttonsOrig); permalink.html(permalinkOrig); real_slug.val(revert_slug); $( '.edit-slug' ).focus(); }); // If more than 1/4th of 'full' is '%', make it empty. for ( i = 0; i < full.length; ++i ) { if ( '%' == full.charAt(i) ) c++; } slug_value = ( c > full.length / 4 ) ? '' : full; $el.html( '<input type="text" id="new-post-slug" value="' + slug_value + '" autocomplete="off" />' ).children( 'input' ).keydown( function( e ) { var key = e.which; // On [enter], just save the new slug, don't save the post. if ( 13 === key ) { e.preventDefault(); buttons.children( '.save' ).click(); } // On [esc] cancel the editing. if ( 27 === key ) { buttons.children( '.cancel' ).click(); } } ).keyup( function() { real_slug.val( this.value ); }).focus(); } $( '#titlediv' ).on( 'click', '.edit-slug', function() { editPermalink(); }); /** * Add screen reader text to the title prompt when needed. * * @summary Title screen reader text handler. * * @param {string} id Optional. HTML ID to add the screen reader helper text to. * * @global * * @returns void */ 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(); // Resize the WYSIWYG and plain text editors. ( function() { var editor, offset, mce, $handle = $('#post-status-info'), $postdivrich = $('#postdivrich'); // If there are no textareas or we are on a touch device, we can't do anything. if ( ! $textarea.length || 'ontouchstart' in window ) { // Hide the resize handle. $('#content-resize-handle').hide(); return; } /** * Handle drag event. * * @param {Object} event Event containing details about the drag. */ function dragging( event ) { if ( $postdivrich.hasClass( 'wp-editor-expand' ) ) { return; } if ( mce ) { editor.theme.resizeTo( null, offset + event.pageY ); } else { $textarea.height( Math.max( 50, offset + event.pageY ) ); } event.preventDefault(); } /** * When the dragging stopped make sure we return focus and do a sanity check on the height. */ function endDrag() { var height, toolbarHeight; if ( $postdivrich.hasClass( 'wp-editor-expand' ) ) { return; } if ( mce ) { editor.focus(); toolbarHeight = parseInt( $( '#wp-content-editor-container .mce-toolbar-grp' ).height(), 10 ); if ( toolbarHeight < 10 || toolbarHeight > 200 ) { toolbarHeight = 30; } height = parseInt( $('#content_ifr').css('height'), 10 ) + toolbarHeight - 28; } else { $textarea.focus(); height = parseInt( $textarea.css('height'), 10 ); } $document.off( '.wp-editor-resize' ); // Sanity check: normalize height to stay within acceptable ranges. if ( height && height > 50 && height < 5000 ) { setUserSetting( 'ed_size', height ); } } $handle.on( 'mousedown.wp-editor-resize', function( event ) { if ( typeof tinymce !== 'undefined' ) { editor = tinymce.get('content'); } if ( editor && ! editor.isHidden() ) { mce = true; offset = $('#content_ifr').height() - event.pageY; } else { mce = false; offset = $textarea.height() - event.pageY; $textarea.blur(); } $document.on( 'mousemove.wp-editor-resize', dragging ) .on( 'mouseup.wp-editor-resize mouseleave.wp-editor-resize', endDrag ); event.preventDefault(); }).on( 'mouseup.wp-editor-resize', endDrag ); })(); // TinyMCE specific handling of Post Format changes to reflect in the editor. if ( typeof tinymce !== 'undefined' ) { // When changing post formats, change the editor body class. $( '#post-formats-select input.post-format' ).on( 'change.set-editor-class', function() { var editor, body, format = this.id; if ( format && $( this ).prop( 'checked' ) && ( editor = tinymce.get( 'content' ) ) ) { body = editor.getBody(); body.className = body.className.replace( /\bpost-format-[^ ]+/, '' ); editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format ); $( document ).trigger( 'editor-classchange' ); } }); // When changing page template, change the editor body class $( '#page_template' ).on( 'change.set-editor-class', function() { var editor, body, pageTemplate = $( this ).val() || ''; pageTemplate = pageTemplate.substr( pageTemplate.lastIndexOf( '/' ) + 1, pageTemplate.length ) .replace( /\.php$/, '' ) .replace( /\./g, '-' ); if ( pageTemplate && ( editor = tinymce.get( 'content' ) ) ) { body = editor.getBody(); body.className = body.className.replace( /\bpage-template-[^ ]+/, '' ); editor.dom.addClass( body, 'page-template-' + pageTemplate ); $( document ).trigger( 'editor-classchange' ); } }); } // Save on pressing [ctrl]/[command] + [s] in the Text editor. $textarea.on( 'keydown.wp-autosave', function( event ) { // Key [s] has code 83. if ( event.which === 83 ) { if ( event.shiftKey || event.altKey || ( isMac && ( ! event.metaKey || event.ctrlKey ) ) || ( ! isMac && ! event.ctrlKey ) ) { return; } wp.autosave && wp.autosave.server.triggerSave(); event.preventDefault(); } }); // If the last status was auto-draft and the save is triggered, edit the current URL. if ( $( '#original_post_status' ).val() === 'auto-draft' && window.history.replaceState ) { var location; $( '#publish' ).on( 'click', function() { location = window.location.href; location += ( location.indexOf( '?' ) !== -1 ) ? '&' : '?'; location += 'wp-post-new-reload=true'; window.history.replaceState( null, null, location ); }); } }); /** * TinyMCE word count display */ ( function( $, counter ) { $( function() { var $content = $( '#content' ), $count = $( '#wp-word-count' ).find( '.word-count' ), prevCount = 0, contentEditor; /** * Get the word count from TinyMCE and display it */ function update() { var text, count; if ( ! contentEditor || contentEditor.isHidden() ) { text = $content.val(); } else { text = contentEditor.getContent( { format: 'raw' } ); } count = counter.count( text ); if ( count !== prevCount ) { $count.text( count ); } prevCount = count; } /** * Bind the word count update triggers. * * When a node change in the main TinyMCE editor has been triggered. * When a key has been released in the plain text content editor. */ $( document ).on( 'tinymce-editor-init', function( event, editor ) { if ( editor.id !== 'content' ) { return; } contentEditor = editor; editor.on( 'nodechange keyup', _.debounce( update, 1000 ) ); } ); $content.on( 'input keyup', _.debounce( update, 1000 ) ); update(); } ); } )( jQuery, new wp.utils.WordCounter() ); customize-nav-menus.js 0000666 00000300477 15213733063 0011055 0 ustar 00 /* global _wpCustomizeNavMenusSettings, wpNavMenu, console */ ( function( api, wp, $ ) { 'use strict'; /** * Set up wpNavMenu for drag and drop. */ wpNavMenu.originalInit = wpNavMenu.init; wpNavMenu.options.menuItemDepthPerLevel = 20; wpNavMenu.options.sortableItems = '> .customize-control-nav_menu_item'; wpNavMenu.options.targetTolerance = 10; wpNavMenu.init = function() { this.jQueryExtensions(); }; api.Menus = api.Menus || {}; // Link settings. api.Menus.data = { itemTypes: [], l10n: {}, settingTransport: 'refresh', phpIntMax: 0, defaultSettingValues: { nav_menu: {}, nav_menu_item: {} }, locationSlugMappedToName: {} }; if ( 'undefined' !== typeof _wpCustomizeNavMenusSettings ) { $.extend( api.Menus.data, _wpCustomizeNavMenusSettings ); } /** * Newly-created Nav Menus and Nav Menu Items have negative integer IDs which * serve as placeholders until Save & Publish happens. * * @return {number} */ api.Menus.generatePlaceholderAutoIncrementId = function() { return -Math.ceil( api.Menus.data.phpIntMax * Math.random() ); }; /** * wp.customize.Menus.AvailableItemModel * * A single available menu item model. See PHP's WP_Customize_Nav_Menu_Item_Setting class. * * @constructor * @augments Backbone.Model */ api.Menus.AvailableItemModel = Backbone.Model.extend( $.extend( { id: null // This is only used by Backbone. }, api.Menus.data.defaultSettingValues.nav_menu_item ) ); /** * wp.customize.Menus.AvailableItemCollection * * Collection for available menu item models. * * @constructor * @augments Backbone.Model */ api.Menus.AvailableItemCollection = Backbone.Collection.extend({ model: api.Menus.AvailableItemModel, sort_key: 'order', comparator: function( item ) { return -item.get( this.sort_key ); }, sortByField: function( fieldName ) { this.sort_key = fieldName; this.sort(); } }); api.Menus.availableMenuItems = new api.Menus.AvailableItemCollection( api.Menus.data.availableMenuItems ); /** * Insert a new `auto-draft` post. * * @since 4.7.0 * @access public * * @param {object} params - Parameters for the draft post to create. * @param {string} params.post_type - Post type to add. * @param {string} params.post_title - Post title to use. * @return {jQuery.promise} Promise resolved with the added post. */ api.Menus.insertAutoDraftPost = function insertAutoDraftPost( params ) { var request, deferred = $.Deferred(); request = wp.ajax.post( 'customize-nav-menus-insert-auto-draft', { 'customize-menus-nonce': api.settings.nonce['customize-menus'], 'wp_customize': 'on', 'params': params } ); request.done( function( response ) { if ( response.post_id ) { api( 'nav_menus_created_posts' ).set( api( 'nav_menus_created_posts' ).get().concat( [ response.post_id ] ) ); if ( 'page' === params.post_type ) { // Activate static front page controls as this could be the first page created. if ( api.section.has( 'static_front_page' ) ) { api.section( 'static_front_page' ).activate(); } // Add new page to dropdown-pages controls. api.control.each( function( control ) { var select; if ( 'dropdown-pages' === control.params.type ) { select = control.container.find( 'select[name^="_customize-dropdown-pages-"]' ); select.append( new Option( params.post_title, response.post_id ) ); } } ); } deferred.resolve( response ); } } ); request.fail( function( response ) { var error = response || ''; if ( 'undefined' !== typeof response.message ) { error = response.message; } console.error( error ); deferred.rejectWith( error ); } ); return deferred.promise(); }; /** * wp.customize.Menus.AvailableMenuItemsPanelView * * View class for the available menu items panel. * * @constructor * @augments wp.Backbone.View * @augments Backbone.View */ api.Menus.AvailableMenuItemsPanelView = wp.Backbone.View.extend({ el: '#available-menu-items', events: { 'input #menu-items-search': 'debounceSearch', 'keyup #menu-items-search': 'debounceSearch', 'focus .menu-item-tpl': 'focus', 'click .menu-item-tpl': '_submit', 'click #custom-menu-item-submit': '_submitLink', 'keypress #custom-menu-item-name': '_submitLink', 'click .new-content-item .add-content': '_submitNew', 'keypress .create-item-input': '_submitNew', 'keydown': 'keyboardAccessible' }, // Cache current selected menu item. selected: null, // Cache menu control that opened the panel. currentMenuControl: null, debounceSearch: null, $search: null, $clearResults: null, searchTerm: '', rendered: false, pages: {}, sectionContent: '', loading: false, addingNew: false, initialize: function() { var self = this; if ( ! api.panel.has( 'nav_menus' ) ) { return; } this.$search = $( '#menu-items-search' ); this.$clearResults = this.$el.find( '.clear-results' ); this.sectionContent = this.$el.find( '.available-menu-items-list' ); this.debounceSearch = _.debounce( self.search, 500 ); _.bindAll( this, 'close' ); // If the available menu items panel is open and the customize controls are // interacted with (other than an item being deleted), then close the // available menu items panel. Also close on back button click. $( '#customize-controls, .customize-section-back' ).on( 'click keydown', function( e ) { var isDeleteBtn = $( e.target ).is( '.item-delete, .item-delete *' ), isAddNewBtn = $( e.target ).is( '.add-new-menu-item, .add-new-menu-item *' ); if ( $( 'body' ).hasClass( 'adding-menu-items' ) && ! isDeleteBtn && ! isAddNewBtn ) { self.close(); } } ); // Clear the search results and trigger a `keyup` event to fire a new search. this.$clearResults.on( 'click', function() { self.$search.val( '' ).focus().trigger( 'keyup' ); } ); this.$el.on( 'input', '#custom-menu-item-name.invalid, #custom-menu-item-url.invalid', function() { $( this ).removeClass( 'invalid' ); }); // Load available items if it looks like we'll need them. api.panel( 'nav_menus' ).container.bind( 'expanded', function() { if ( ! self.rendered ) { self.initList(); self.rendered = true; } }); // Load more items. this.sectionContent.scroll( function() { var totalHeight = self.$el.find( '.accordion-section.open .available-menu-items-list' ).prop( 'scrollHeight' ), visibleHeight = self.$el.find( '.accordion-section.open' ).height(); if ( ! self.loading && $( this ).scrollTop() > 3 / 4 * totalHeight - visibleHeight ) { var type = $( this ).data( 'type' ), object = $( this ).data( 'object' ); if ( 'search' === type ) { if ( self.searchTerm ) { self.doSearch( self.pages.search ); } } else { self.loadItems( [ { type: type, object: object } ] ); } } }); // Close the panel if the URL in the preview changes api.previewer.bind( 'url', this.close ); self.delegateEvents(); }, // Search input change handler. search: function( event ) { var $searchSection = $( '#available-menu-items-search' ), $otherSections = $( '#available-menu-items .accordion-section' ).not( $searchSection ); if ( ! event ) { return; } if ( this.searchTerm === event.target.value ) { return; } if ( '' !== event.target.value && ! $searchSection.hasClass( 'open' ) ) { $otherSections.fadeOut( 100 ); $searchSection.find( '.accordion-section-content' ).slideDown( 'fast' ); $searchSection.addClass( 'open' ); this.$clearResults.addClass( 'is-visible' ); } else if ( '' === event.target.value ) { $searchSection.removeClass( 'open' ); $otherSections.show(); this.$clearResults.removeClass( 'is-visible' ); } this.searchTerm = event.target.value; this.pages.search = 1; this.doSearch( 1 ); }, // Get search results. doSearch: function( page ) { var self = this, params, $section = $( '#available-menu-items-search' ), $content = $section.find( '.accordion-section-content' ), itemTemplate = wp.template( 'available-menu-item' ); if ( self.currentRequest ) { self.currentRequest.abort(); } if ( page < 0 ) { return; } else if ( page > 1 ) { $section.addClass( 'loading-more' ); $content.attr( 'aria-busy', 'true' ); wp.a11y.speak( api.Menus.data.l10n.itemsLoadingMore ); } else if ( '' === self.searchTerm ) { $content.html( '' ); wp.a11y.speak( '' ); return; } $section.addClass( 'loading' ); self.loading = true; params = api.previewer.query( { excludeCustomizedSaved: true } ); _.extend( params, { 'customize-menus-nonce': api.settings.nonce['customize-menus'], 'wp_customize': 'on', 'search': self.searchTerm, 'page': page } ); self.currentRequest = wp.ajax.post( 'search-available-menu-items-customizer', params ); self.currentRequest.done(function( data ) { var items; if ( 1 === page ) { // Clear previous results as it's a new search. $content.empty(); } $section.removeClass( 'loading loading-more' ); $content.attr( 'aria-busy', 'false' ); $section.addClass( 'open' ); self.loading = false; items = new api.Menus.AvailableItemCollection( data.items ); self.collection.add( items.models ); items.each( function( menuItem ) { $content.append( itemTemplate( menuItem.attributes ) ); } ); if ( 20 > items.length ) { self.pages.search = -1; // Up to 20 posts and 20 terms in results, if <20, no more results for either. } else { self.pages.search = self.pages.search + 1; } if ( items && page > 1 ) { wp.a11y.speak( api.Menus.data.l10n.itemsFoundMore.replace( '%d', items.length ) ); } else if ( items && page === 1 ) { wp.a11y.speak( api.Menus.data.l10n.itemsFound.replace( '%d', items.length ) ); } }); self.currentRequest.fail(function( data ) { // data.message may be undefined, for example when typing slow and the request is aborted. if ( data.message ) { $content.empty().append( $( '<li class="nothing-found"></li>' ).text( data.message ) ); wp.a11y.speak( data.message ); } self.pages.search = -1; }); self.currentRequest.always(function() { $section.removeClass( 'loading loading-more' ); $content.attr( 'aria-busy', 'false' ); self.loading = false; self.currentRequest = null; }); }, // Render the individual items. initList: function() { var self = this; // Render the template for each item by type. _.each( api.Menus.data.itemTypes, function( itemType ) { self.pages[ itemType.type + ':' + itemType.object ] = 0; } ); self.loadItems( api.Menus.data.itemTypes ); }, /** * Load available nav menu items. * * @since 4.3.0 * @since 4.7.0 Changed function signature to take list of item types instead of single type/object. * @access private * * @param {Array.<object>} itemTypes List of objects containing type and key. * @param {string} deprecated Formerly the object parameter. * @returns {void} */ loadItems: function( itemTypes, deprecated ) { var self = this, _itemTypes, requestItemTypes = [], params, request, itemTemplate, availableMenuItemContainers = {}; itemTemplate = wp.template( 'available-menu-item' ); if ( _.isString( itemTypes ) && _.isString( deprecated ) ) { _itemTypes = [ { type: itemTypes, object: deprecated } ]; } else { _itemTypes = itemTypes; } _.each( _itemTypes, function( itemType ) { var container, name = itemType.type + ':' + itemType.object; if ( -1 === self.pages[ name ] ) { return; // Skip types for which there are no more results. } container = $( '#available-menu-items-' + itemType.type + '-' + itemType.object ); container.find( '.accordion-section-title' ).addClass( 'loading' ); availableMenuItemContainers[ name ] = container; requestItemTypes.push( { object: itemType.object, type: itemType.type, page: self.pages[ name ] } ); } ); if ( 0 === requestItemTypes.length ) { return; } self.loading = true; params = api.previewer.query( { excludeCustomizedSaved: true } ); _.extend( params, { 'customize-menus-nonce': api.settings.nonce['customize-menus'], 'wp_customize': 'on', 'item_types': requestItemTypes } ); request = wp.ajax.post( 'load-available-menu-items-customizer', params ); request.done(function( data ) { var typeInner; _.each( data.items, function( typeItems, name ) { if ( 0 === typeItems.length ) { if ( 0 === self.pages[ name ] ) { availableMenuItemContainers[ name ].find( '.accordion-section-title' ) .addClass( 'cannot-expand' ) .removeClass( 'loading' ) .find( '.accordion-section-title > button' ) .prop( 'tabIndex', -1 ); } self.pages[ name ] = -1; return; } else if ( ( 'post_type:page' === name ) && ( ! availableMenuItemContainers[ name ].hasClass( 'open' ) ) ) { availableMenuItemContainers[ name ].find( '.accordion-section-title > button' ).click(); } typeItems = new api.Menus.AvailableItemCollection( typeItems ); // @todo Why is this collection created and then thrown away? self.collection.add( typeItems.models ); typeInner = availableMenuItemContainers[ name ].find( '.available-menu-items-list' ); typeItems.each( function( menuItem ) { typeInner.append( itemTemplate( menuItem.attributes ) ); } ); self.pages[ name ] += 1; }); }); request.fail(function( data ) { if ( typeof console !== 'undefined' && console.error ) { console.error( data ); } }); request.always(function() { _.each( availableMenuItemContainers, function( container ) { container.find( '.accordion-section-title' ).removeClass( 'loading' ); } ); self.loading = false; }); }, // Adjust the height of each section of items to fit the screen. itemSectionHeight: function() { var sections, lists, totalHeight, accordionHeight, diff; totalHeight = window.innerHeight; sections = this.$el.find( '.accordion-section:not( #available-menu-items-search ) .accordion-section-content' ); lists = this.$el.find( '.accordion-section:not( #available-menu-items-search ) .available-menu-items-list:not(":only-child")' ); accordionHeight = 46 * ( 1 + sections.length ) + 14; // Magic numbers. diff = totalHeight - accordionHeight; if ( 120 < diff && 290 > diff ) { sections.css( 'max-height', diff ); lists.css( 'max-height', ( diff - 60 ) ); } }, // Highlights a menu item. select: function( menuitemTpl ) { this.selected = $( menuitemTpl ); this.selected.siblings( '.menu-item-tpl' ).removeClass( 'selected' ); this.selected.addClass( 'selected' ); }, // Highlights a menu item on focus. focus: function( event ) { this.select( $( event.currentTarget ) ); }, // Submit handler for keypress and click on menu item. _submit: function( event ) { // Only proceed with keypress if it is Enter or Spacebar if ( 'keypress' === event.type && ( 13 !== event.which && 32 !== event.which ) ) { return; } this.submit( $( event.currentTarget ) ); }, // Adds a selected menu item to the menu. submit: function( menuitemTpl ) { var menuitemId, menu_item; if ( ! menuitemTpl ) { menuitemTpl = this.selected; } if ( ! menuitemTpl || ! this.currentMenuControl ) { return; } this.select( menuitemTpl ); menuitemId = $( this.selected ).data( 'menu-item-id' ); menu_item = this.collection.findWhere( { id: menuitemId } ); if ( ! menu_item ) { return; } // Leave the title as empty to reuse the original title as a placeholder if set. var nav_menu_item = Object.assign( {}, menu_item.attributes ); if ( nav_menu_item.title === nav_menu_item.original_title ) { nav_menu_item.title = ''; } this.currentMenuControl.addItemToMenu( nav_menu_item ); $( menuitemTpl ).find( '.menu-item-handle' ).addClass( 'item-added' ); }, // Submit handler for keypress and click on custom menu item. _submitLink: function( event ) { // Only proceed with keypress if it is Enter. if ( 'keypress' === event.type && 13 !== event.which ) { return; } this.submitLink(); }, // Adds the custom menu item to the menu. submitLink: function() { var menuItem, itemName = $( '#custom-menu-item-name' ), itemUrl = $( '#custom-menu-item-url' ); if ( ! this.currentMenuControl ) { return; } if ( '' === itemName.val() ) { itemName.addClass( 'invalid' ); return; } else if ( '' === itemUrl.val() || 'http://' === itemUrl.val() ) { itemUrl.addClass( 'invalid' ); return; } menuItem = { 'title': itemName.val(), 'url': itemUrl.val(), 'type': 'custom', 'type_label': api.Menus.data.l10n.custom_label, 'object': 'custom' }; this.currentMenuControl.addItemToMenu( menuItem ); // Reset the custom link form. itemUrl.val( 'http://' ); itemName.val( '' ); }, /** * Submit handler for keypress (enter) on field and click on button. * * @since 4.7.0 * @private * * @param {jQuery.Event} event Event. * @returns {void} */ _submitNew: function( event ) { var container; // Only proceed with keypress if it is Enter. if ( 'keypress' === event.type && 13 !== event.which ) { return; } if ( this.addingNew ) { return; } container = $( event.target ).closest( '.accordion-section' ); this.submitNew( container ); }, /** * Creates a new object and adds an associated menu item to the menu. * * @since 4.7.0 * @private * * @param {jQuery} container * @returns {void} */ submitNew: function( container ) { var panel = this, itemName = container.find( '.create-item-input' ), title = itemName.val(), dataContainer = container.find( '.available-menu-items-list' ), itemType = dataContainer.data( 'type' ), itemObject = dataContainer.data( 'object' ), itemTypeLabel = dataContainer.data( 'type_label' ), promise; if ( ! this.currentMenuControl ) { return; } // Only posts are supported currently. if ( 'post_type' !== itemType ) { return; } if ( '' === $.trim( itemName.val() ) ) { itemName.addClass( 'invalid' ); itemName.focus(); return; } else { itemName.removeClass( 'invalid' ); container.find( '.accordion-section-title' ).addClass( 'loading' ); } panel.addingNew = true; itemName.attr( 'disabled', 'disabled' ); promise = api.Menus.insertAutoDraftPost( { post_title: title, post_type: itemObject } ); promise.done( function( data ) { var availableItem, $content, itemElement; availableItem = new api.Menus.AvailableItemModel( { 'id': 'post-' + data.post_id, // Used for available menu item Backbone models. 'title': itemName.val(), 'type': itemType, 'type_label': itemTypeLabel, 'object': itemObject, 'object_id': data.post_id, 'url': data.url } ); // Add new item to menu. panel.currentMenuControl.addItemToMenu( availableItem.attributes ); // Add the new item to the list of available items. api.Menus.availableMenuItemsPanel.collection.add( availableItem ); $content = container.find( '.available-menu-items-list' ); itemElement = $( wp.template( 'available-menu-item' )( availableItem.attributes ) ); itemElement.find( '.menu-item-handle:first' ).addClass( 'item-added' ); $content.prepend( itemElement ); $content.scrollTop(); // Reset the create content form. itemName.val( '' ).removeAttr( 'disabled' ); panel.addingNew = false; container.find( '.accordion-section-title' ).removeClass( 'loading' ); } ); }, // Opens the panel. open: function( menuControl ) { this.currentMenuControl = menuControl; this.itemSectionHeight(); $( 'body' ).addClass( 'adding-menu-items' ); // Collapse all controls. _( this.currentMenuControl.getMenuItemControls() ).each( function( control ) { control.collapseForm(); } ); this.$el.find( '.selected' ).removeClass( 'selected' ); this.$search.focus(); }, // Closes the panel close: function( options ) { options = options || {}; if ( options.returnFocus && this.currentMenuControl ) { this.currentMenuControl.container.find( '.add-new-menu-item' ).focus(); } this.currentMenuControl = null; this.selected = null; $( 'body' ).removeClass( 'adding-menu-items' ); $( '#available-menu-items .menu-item-handle.item-added' ).removeClass( 'item-added' ); this.$search.val( '' ); }, // Add a few keyboard enhancements to the panel. keyboardAccessible: function( event ) { var isEnter = ( 13 === event.which ), isEsc = ( 27 === event.which ), isBackTab = ( 9 === event.which && event.shiftKey ), isSearchFocused = $( event.target ).is( this.$search ); // If enter pressed but nothing entered, don't do anything if ( isEnter && ! this.$search.val() ) { return; } if ( isSearchFocused && isBackTab ) { this.currentMenuControl.container.find( '.add-new-menu-item' ).focus(); event.preventDefault(); // Avoid additional back-tab. } else if ( isEsc ) { this.close( { returnFocus: true } ); } } }); /** * wp.customize.Menus.MenusPanel * * Customizer panel for menus. This is used only for screen options management. * Note that 'menus' must match the WP_Customize_Menu_Panel::$type. * * @constructor * @augments wp.customize.Panel */ api.Menus.MenusPanel = api.Panel.extend({ attachEvents: function() { api.Panel.prototype.attachEvents.call( this ); var panel = this, panelMeta = panel.container.find( '.panel-meta' ), help = panelMeta.find( '.customize-help-toggle' ), content = panelMeta.find( '.customize-panel-description' ), options = $( '#screen-options-wrap' ), button = panelMeta.find( '.customize-screen-options-toggle' ); button.on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Hide description if ( content.not( ':hidden' ) ) { content.slideUp( 'fast' ); help.attr( 'aria-expanded', 'false' ); } if ( 'true' === button.attr( 'aria-expanded' ) ) { button.attr( 'aria-expanded', 'false' ); panelMeta.removeClass( 'open' ); panelMeta.removeClass( 'active-menu-screen-options' ); options.slideUp( 'fast' ); } else { button.attr( 'aria-expanded', 'true' ); panelMeta.addClass( 'open' ); panelMeta.addClass( 'active-menu-screen-options' ); options.slideDown( 'fast' ); } return false; } ); // Help toggle help.on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); if ( 'true' === button.attr( 'aria-expanded' ) ) { button.attr( 'aria-expanded', 'false' ); help.attr( 'aria-expanded', 'true' ); panelMeta.addClass( 'open' ); panelMeta.removeClass( 'active-menu-screen-options' ); options.slideUp( 'fast' ); content.slideDown( 'fast' ); } } ); }, /** * Update field visibility when clicking on the field toggles. */ ready: function() { var panel = this; panel.container.find( '.hide-column-tog' ).click( function() { panel.saveManageColumnsState(); }); }, /** * Save hidden column states. * * @since 4.3.0 * @private * * @returns {void} */ saveManageColumnsState: _.debounce( function() { var panel = this; if ( panel._updateHiddenColumnsRequest ) { panel._updateHiddenColumnsRequest.abort(); } panel._updateHiddenColumnsRequest = wp.ajax.post( 'hidden-columns', { hidden: panel.hidden(), screenoptionnonce: $( '#screenoptionnonce' ).val(), page: 'nav-menus' } ); panel._updateHiddenColumnsRequest.always( function() { panel._updateHiddenColumnsRequest = null; } ); }, 2000 ), /** * @deprecated Since 4.7.0 now that the nav_menu sections are responsible for toggling the classes on their own containers. */ checked: function() {}, /** * @deprecated Since 4.7.0 now that the nav_menu sections are responsible for toggling the classes on their own containers. */ unchecked: function() {}, /** * Get hidden fields. * * @since 4.3.0 * @private * * @returns {Array} Fields (columns) that are hidden. */ hidden: function() { return $( '.hide-column-tog' ).not( ':checked' ).map( function() { var id = this.id; return id.substring( 0, id.length - 5 ); }).get().join( ',' ); } } ); /** * wp.customize.Menus.MenuSection * * Customizer section for menus. This is used only for lazy-loading child controls. * Note that 'nav_menu' must match the WP_Customize_Menu_Section::$type. * * @constructor * @augments wp.customize.Section */ api.Menus.MenuSection = api.Section.extend({ /** * Initialize. * * @since 4.3.0 * * @param {String} id * @param {Object} options */ initialize: function( id, options ) { var section = this; api.Section.prototype.initialize.call( section, id, options ); section.deferred.initSortables = $.Deferred(); }, /** * Ready. */ ready: function() { var section = this, fieldActiveToggles, handleFieldActiveToggle; if ( 'undefined' === typeof section.params.menu_id ) { throw new Error( 'params.menu_id was not defined' ); } /* * Since newly created sections won't be registered in PHP, we need to prevent the * preview's sending of the activeSections to result in this control * being deactivated when the preview refreshes. So we can hook onto * the setting that has the same ID and its presence can dictate * whether the section is active. */ section.active.validate = function() { if ( ! api.has( section.id ) ) { return false; } return !! api( section.id ).get(); }; section.populateControls(); section.navMenuLocationSettings = {}; section.assignedLocations = new api.Value( [] ); api.each(function( setting, id ) { var matches = id.match( /^nav_menu_locations\[(.+?)]/ ); if ( matches ) { section.navMenuLocationSettings[ matches[1] ] = setting; setting.bind( function() { section.refreshAssignedLocations(); }); } }); section.assignedLocations.bind(function( to ) { section.updateAssignedLocationsInSectionTitle( to ); }); section.refreshAssignedLocations(); api.bind( 'pane-contents-reflowed', function() { // Skip menus that have been removed. if ( ! section.contentContainer.parent().length ) { return; } section.container.find( '.menu-item .menu-item-reorder-nav button' ).attr({ 'tabindex': '0', 'aria-hidden': 'false' }); section.container.find( '.menu-item.move-up-disabled .menus-move-up' ).attr({ 'tabindex': '-1', 'aria-hidden': 'true' }); section.container.find( '.menu-item.move-down-disabled .menus-move-down' ).attr({ 'tabindex': '-1', 'aria-hidden': 'true' }); section.container.find( '.menu-item.move-left-disabled .menus-move-left' ).attr({ 'tabindex': '-1', 'aria-hidden': 'true' }); section.container.find( '.menu-item.move-right-disabled .menus-move-right' ).attr({ 'tabindex': '-1', 'aria-hidden': 'true' }); } ); /** * Update the active field class for the content container for a given checkbox toggle. * * @this {jQuery} * @returns {void} */ handleFieldActiveToggle = function() { var className = 'field-' + $( this ).val() + '-active'; section.contentContainer.toggleClass( className, $( this ).prop( 'checked' ) ); }; fieldActiveToggles = api.panel( 'nav_menus' ).contentContainer.find( '.metabox-prefs:first' ).find( '.hide-column-tog' ); fieldActiveToggles.each( handleFieldActiveToggle ); fieldActiveToggles.on( 'click', handleFieldActiveToggle ); }, populateControls: function() { var section = this, menuNameControlId, menuAutoAddControlId, menuControl, menuNameControl, menuAutoAddControl; // Add the control for managing the menu name. menuNameControlId = section.id + '[name]'; menuNameControl = api.control( menuNameControlId ); if ( ! menuNameControl ) { menuNameControl = new api.controlConstructor.nav_menu_name( menuNameControlId, { params: { type: 'nav_menu_name', content: '<li id="customize-control-' + section.id.replace( '[', '-' ).replace( ']', '' ) + '-name" class="customize-control customize-control-nav_menu_name"></li>', // @todo core should do this for us; see #30741 label: api.Menus.data.l10n.menuNameLabel, active: true, section: section.id, priority: 0, settings: { 'default': section.id } } } ); api.control.add( menuNameControl.id, menuNameControl ); menuNameControl.active.set( true ); } // Add the menu control. menuControl = api.control( section.id ); if ( ! menuControl ) { menuControl = new api.controlConstructor.nav_menu( section.id, { params: { type: 'nav_menu', content: '<li id="customize-control-' + section.id.replace( '[', '-' ).replace( ']', '' ) + '" class="customize-control customize-control-nav_menu"></li>', // @todo core should do this for us; see #30741 section: section.id, priority: 998, active: true, settings: { 'default': section.id }, menu_id: section.params.menu_id } } ); api.control.add( menuControl.id, menuControl ); menuControl.active.set( true ); } // Add the control for managing the menu auto_add. menuAutoAddControlId = section.id + '[auto_add]'; menuAutoAddControl = api.control( menuAutoAddControlId ); if ( ! menuAutoAddControl ) { menuAutoAddControl = new api.controlConstructor.nav_menu_auto_add( menuAutoAddControlId, { params: { type: 'nav_menu_auto_add', content: '<li id="customize-control-' + section.id.replace( '[', '-' ).replace( ']', '' ) + '-auto-add" class="customize-control customize-control-nav_menu_auto_add"></li>', // @todo core should do this for us label: '', active: true, section: section.id, priority: 999, settings: { 'default': section.id } } } ); api.control.add( menuAutoAddControl.id, menuAutoAddControl ); menuAutoAddControl.active.set( true ); } }, /** * */ refreshAssignedLocations: function() { var section = this, menuTermId = section.params.menu_id, currentAssignedLocations = []; _.each( section.navMenuLocationSettings, function( setting, themeLocation ) { if ( setting() === menuTermId ) { currentAssignedLocations.push( themeLocation ); } }); section.assignedLocations.set( currentAssignedLocations ); }, /** * @param {Array} themeLocationSlugs Theme location slugs. */ updateAssignedLocationsInSectionTitle: function( themeLocationSlugs ) { var section = this, $title; $title = section.container.find( '.accordion-section-title:first' ); $title.find( '.menu-in-location' ).remove(); _.each( themeLocationSlugs, function( themeLocationSlug ) { var $label, locationName; $label = $( '<span class="menu-in-location"></span>' ); locationName = api.Menus.data.locationSlugMappedToName[ themeLocationSlug ]; $label.text( api.Menus.data.l10n.menuLocation.replace( '%s', locationName ) ); $title.append( $label ); }); section.container.toggleClass( 'assigned-to-menu-location', 0 !== themeLocationSlugs.length ); }, onChangeExpanded: function( expanded, args ) { var section = this, completeCallback; if ( expanded ) { wpNavMenu.menuList = section.contentContainer; wpNavMenu.targetList = wpNavMenu.menuList; // Add attributes needed by wpNavMenu $( '#menu-to-edit' ).removeAttr( 'id' ); wpNavMenu.menuList.attr( 'id', 'menu-to-edit' ).addClass( 'menu' ); _.each( api.section( section.id ).controls(), function( control ) { if ( 'nav_menu_item' === control.params.type ) { control.actuallyEmbed(); } } ); // Make sure Sortables is initialized after the section has been expanded to prevent `offset` issues. if ( args.completeCallback ) { completeCallback = args.completeCallback; } args.completeCallback = function() { if ( 'resolved' !== section.deferred.initSortables.state() ) { wpNavMenu.initSortables(); // Depends on menu-to-edit ID being set above. section.deferred.initSortables.resolve( wpNavMenu.menuList ); // Now MenuControl can extend the sortable. // @todo Note that wp.customize.reflowPaneContents() is debounced, so this immediate change will show a slight flicker while priorities get updated. api.control( 'nav_menu[' + String( section.params.menu_id ) + ']' ).reflowMenuItems(); } if ( _.isFunction( completeCallback ) ) { completeCallback(); } }; } api.Section.prototype.onChangeExpanded.call( section, expanded, args ); } }); /** * wp.customize.Menus.NewMenuSection * * Customizer section for new menus. * Note that 'new_menu' must match the WP_Customize_New_Menu_Section::$type. * * @constructor * @augments wp.customize.Section */ api.Menus.NewMenuSection = api.Section.extend({ /** * Add behaviors for the accordion section. * * @since 4.3.0 */ attachEvents: function() { var section = this; this.container.on( 'click', '.add-menu-toggle', function() { if ( section.expanded() ) { section.collapse(); } else { section.expand(); } }); }, /** * Update UI to reflect expanded state. * * @since 4.1.0 * * @param {Boolean} expanded */ onChangeExpanded: function( expanded ) { var section = this, button = section.container.find( '.add-menu-toggle' ), content = section.contentContainer, customizer = section.headContainer.closest( '.wp-full-overlay-sidebar-content' ); if ( expanded ) { button.addClass( 'open' ); button.attr( 'aria-expanded', 'true' ); content.slideDown( 'fast', function() { customizer.scrollTop( customizer.height() ); }); } else { button.removeClass( 'open' ); button.attr( 'aria-expanded', 'false' ); content.slideUp( 'fast' ); content.find( '.menu-name-field' ).removeClass( 'invalid' ); } }, /** * Find the content element. * * @since 4.7.0 * * @returns {jQuery} Content UL element. */ getContent: function() { return this.container.find( 'ul:first' ); } }); /** * wp.customize.Menus.MenuLocationControl * * Customizer control for menu locations (rendered as a <select>). * Note that 'nav_menu_location' must match the WP_Customize_Nav_Menu_Location_Control::$type. * * @constructor * @augments wp.customize.Control */ api.Menus.MenuLocationControl = api.Control.extend({ initialize: function( id, options ) { var control = this, matches = id.match( /^nav_menu_locations\[(.+?)]/ ); control.themeLocation = matches[1]; api.Control.prototype.initialize.call( control, id, options ); }, ready: function() { var control = this, navMenuIdRegex = /^nav_menu\[(-?\d+)]/; // @todo It would be better if this was added directly on the setting itself, as opposed to the control. control.setting.validate = function( value ) { if ( '' === value ) { return 0; } else { return parseInt( value, 10 ); } }; // Edit menu button. control.container.find( '.edit-menu' ).on( 'click', function() { var menuId = control.setting(); api.section( 'nav_menu[' + menuId + ']' ).focus(); }); control.setting.bind( 'change', function() { if ( 0 === control.setting() ) { control.container.find( '.edit-menu' ).addClass( 'hidden' ); } else { control.container.find( '.edit-menu' ).removeClass( 'hidden' ); } }); // Add/remove menus from the available options when they are added and removed. api.bind( 'add', function( setting ) { var option, menuId, matches = setting.id.match( navMenuIdRegex ); if ( ! matches || false === setting() ) { return; } menuId = matches[1]; option = new Option( displayNavMenuName( setting().name ), menuId ); control.container.find( 'select' ).append( option ); }); api.bind( 'remove', function( setting ) { var menuId, matches = setting.id.match( navMenuIdRegex ); if ( ! matches ) { return; } menuId = parseInt( matches[1], 10 ); if ( control.setting() === menuId ) { control.setting.set( '' ); } control.container.find( 'option[value=' + menuId + ']' ).remove(); }); api.bind( 'change', function( setting ) { var menuId, matches = setting.id.match( navMenuIdRegex ); if ( ! matches ) { return; } menuId = parseInt( matches[1], 10 ); if ( false === setting() ) { if ( control.setting() === menuId ) { control.setting.set( '' ); } control.container.find( 'option[value=' + menuId + ']' ).remove(); } else { control.container.find( 'option[value=' + menuId + ']' ).text( displayNavMenuName( setting().name ) ); } }); } }); /** * wp.customize.Menus.MenuItemControl * * Customizer control for menu items. * Note that 'menu_item' must match the WP_Customize_Menu_Item_Control::$type. * * @constructor * @augments wp.customize.Control */ api.Menus.MenuItemControl = api.Control.extend({ /** * @inheritdoc */ initialize: function( id, options ) { var control = this; control.expanded = new api.Value( false ); control.expandedArgumentsQueue = []; control.expanded.bind( function( expanded ) { var args = control.expandedArgumentsQueue.shift(); args = $.extend( {}, control.defaultExpandedArguments, args ); control.onChangeExpanded( expanded, args ); }); api.Control.prototype.initialize.call( control, id, options ); control.active.validate = function() { var value, section = api.section( control.section() ); if ( section ) { value = section.active(); } else { value = false; } return value; }; }, /** * Override the embed() method to do nothing, * so that the control isn't embedded on load, * unless the containing section is already expanded. * * @since 4.3.0 */ embed: function() { var control = this, sectionId = control.section(), section; if ( ! sectionId ) { return; } section = api.section( sectionId ); if ( ( section && section.expanded() ) || api.settings.autofocus.control === control.id ) { control.actuallyEmbed(); } }, /** * This function is called in Section.onChangeExpanded() so the control * will only get embedded when the Section is first expanded. * * @since 4.3.0 */ actuallyEmbed: function() { var control = this; if ( 'resolved' === control.deferred.embedded.state() ) { return; } control.renderContent(); control.deferred.embedded.resolve(); // This triggers control.ready(). }, /** * Set up the control. */ ready: function() { if ( 'undefined' === typeof this.params.menu_item_id ) { throw new Error( 'params.menu_item_id was not defined' ); } this._setupControlToggle(); this._setupReorderUI(); this._setupUpdateUI(); this._setupRemoveUI(); this._setupLinksUI(); this._setupTitleUI(); }, /** * Show/hide the settings when clicking on the menu item handle. */ _setupControlToggle: function() { var control = this; this.container.find( '.menu-item-handle' ).on( 'click', function( e ) { e.preventDefault(); e.stopPropagation(); var menuControl = control.getMenuControl(), isDeleteBtn = $( e.target ).is( '.item-delete, .item-delete *' ), isAddNewBtn = $( e.target ).is( '.add-new-menu-item, .add-new-menu-item *' ); if ( $( 'body' ).hasClass( 'adding-menu-items' ) && ! isDeleteBtn && ! isAddNewBtn ) { api.Menus.availableMenuItemsPanel.close(); } if ( menuControl.isReordering || menuControl.isSorting ) { return; } control.toggleForm(); } ); }, /** * Set up the menu-item-reorder-nav */ _setupReorderUI: function() { var control = this, template, $reorderNav; template = wp.template( 'menu-item-reorder-nav' ); // Add the menu item reordering elements to the menu item control. control.container.find( '.item-controls' ).after( template ); // Handle clicks for up/down/left-right on the reorder nav. $reorderNav = control.container.find( '.menu-item-reorder-nav' ); $reorderNav.find( '.menus-move-up, .menus-move-down, .menus-move-left, .menus-move-right' ).on( 'click', function() { var moveBtn = $( this ); moveBtn.focus(); var isMoveUp = moveBtn.is( '.menus-move-up' ), isMoveDown = moveBtn.is( '.menus-move-down' ), isMoveLeft = moveBtn.is( '.menus-move-left' ), isMoveRight = moveBtn.is( '.menus-move-right' ); if ( isMoveUp ) { control.moveUp(); } else if ( isMoveDown ) { control.moveDown(); } else if ( isMoveLeft ) { control.moveLeft(); } else if ( isMoveRight ) { control.moveRight(); } moveBtn.focus(); // Re-focus after the container was moved. } ); }, /** * Set up event handlers for menu item updating. */ _setupUpdateUI: function() { var control = this, settingValue = control.setting(); control.elements = {}; control.elements.url = new api.Element( control.container.find( '.edit-menu-item-url' ) ); control.elements.title = new api.Element( control.container.find( '.edit-menu-item-title' ) ); control.elements.attr_title = new api.Element( control.container.find( '.edit-menu-item-attr-title' ) ); control.elements.target = new api.Element( control.container.find( '.edit-menu-item-target' ) ); control.elements.classes = new api.Element( control.container.find( '.edit-menu-item-classes' ) ); control.elements.xfn = new api.Element( control.container.find( '.edit-menu-item-xfn' ) ); control.elements.description = new api.Element( control.container.find( '.edit-menu-item-description' ) ); // @todo allow other elements, added by plugins, to be automatically picked up here; allow additional values to be added to setting array. _.each( control.elements, function( element, property ) { element.bind(function( value ) { if ( element.element.is( 'input[type=checkbox]' ) ) { value = ( value ) ? element.element.val() : ''; } var settingValue = control.setting(); if ( settingValue && settingValue[ property ] !== value ) { settingValue = _.clone( settingValue ); settingValue[ property ] = value; control.setting.set( settingValue ); } }); if ( settingValue ) { if ( ( property === 'classes' || property === 'xfn' ) && _.isArray( settingValue[ property ] ) ) { element.set( settingValue[ property ].join( ' ' ) ); } else { element.set( settingValue[ property ] ); } } }); control.setting.bind(function( to, from ) { var itemId = control.params.menu_item_id, followingSiblingItemControls = [], childrenItemControls = [], menuControl; if ( false === to ) { menuControl = api.control( 'nav_menu[' + String( from.nav_menu_term_id ) + ']' ); control.container.remove(); _.each( menuControl.getMenuItemControls(), function( otherControl ) { if ( from.menu_item_parent === otherControl.setting().menu_item_parent && otherControl.setting().position > from.position ) { followingSiblingItemControls.push( otherControl ); } else if ( otherControl.setting().menu_item_parent === itemId ) { childrenItemControls.push( otherControl ); } }); // Shift all following siblings by the number of children this item has. _.each( followingSiblingItemControls, function( followingSiblingItemControl ) { var value = _.clone( followingSiblingItemControl.setting() ); value.position += childrenItemControls.length; followingSiblingItemControl.setting.set( value ); }); // Now move the children up to be the new subsequent siblings. _.each( childrenItemControls, function( childrenItemControl, i ) { var value = _.clone( childrenItemControl.setting() ); value.position = from.position + i; value.menu_item_parent = from.menu_item_parent; childrenItemControl.setting.set( value ); }); menuControl.debouncedReflowMenuItems(); } else { // Update the elements' values to match the new setting properties. _.each( to, function( value, key ) { if ( control.elements[ key] ) { control.elements[ key ].set( to[ key ] ); } } ); control.container.find( '.menu-item-data-parent-id' ).val( to.menu_item_parent ); // Handle UI updates when the position or depth (parent) change. if ( to.position !== from.position || to.menu_item_parent !== from.menu_item_parent ) { control.getMenuControl().debouncedReflowMenuItems(); } } }); }, /** * Set up event handlers for menu item deletion. */ _setupRemoveUI: function() { var control = this, $removeBtn; // Configure delete button. $removeBtn = control.container.find( '.item-delete' ); $removeBtn.on( 'click', function() { // Find an adjacent element to add focus to when this menu item goes away var addingItems = true, $adjacentFocusTarget, $next, $prev; if ( ! $( 'body' ).hasClass( 'adding-menu-items' ) ) { addingItems = false; } $next = control.container.nextAll( '.customize-control-nav_menu_item:visible' ).first(); $prev = control.container.prevAll( '.customize-control-nav_menu_item:visible' ).first(); if ( $next.length ) { $adjacentFocusTarget = $next.find( false === addingItems ? '.item-edit' : '.item-delete' ).first(); } else if ( $prev.length ) { $adjacentFocusTarget = $prev.find( false === addingItems ? '.item-edit' : '.item-delete' ).first(); } else { $adjacentFocusTarget = control.container.nextAll( '.customize-control-nav_menu' ).find( '.add-new-menu-item' ).first(); } control.container.slideUp( function() { control.setting.set( false ); wp.a11y.speak( api.Menus.data.l10n.itemDeleted ); $adjacentFocusTarget.focus(); // keyboard accessibility } ); } ); }, _setupLinksUI: function() { var $origBtn; // Configure original link. $origBtn = this.container.find( 'a.original-link' ); $origBtn.on( 'click', function( e ) { e.preventDefault(); api.previewer.previewUrl( e.target.toString() ); } ); }, /** * Update item handle title when changed. */ _setupTitleUI: function() { var control = this, titleEl; // Ensure that whitespace is trimmed on blur so placeholder can be shown. control.container.find( '.edit-menu-item-title' ).on( 'blur', function() { $( this ).val( $.trim( $( this ).val() ) ); } ); titleEl = control.container.find( '.menu-item-title' ); control.setting.bind( function( item ) { var trimmedTitle, titleText; if ( ! item ) { return; } trimmedTitle = $.trim( item.title ); titleText = trimmedTitle || item.original_title || api.Menus.data.l10n.untitled; if ( item._invalid ) { titleText = api.Menus.data.l10n.invalidTitleTpl.replace( '%s', titleText ); } // Don't update to an empty title. if ( trimmedTitle || item.original_title ) { titleEl .text( titleText ) .removeClass( 'no-title' ); } else { titleEl .text( titleText ) .addClass( 'no-title' ); } } ); }, /** * * @returns {number} */ getDepth: function() { var control = this, setting = control.setting(), depth = 0; if ( ! setting ) { return 0; } while ( setting && setting.menu_item_parent ) { depth += 1; control = api.control( 'nav_menu_item[' + setting.menu_item_parent + ']' ); if ( ! control ) { break; } setting = control.setting(); } return depth; }, /** * Amend the control's params with the data necessary for the JS template just in time. */ renderContent: function() { var control = this, settingValue = control.setting(), containerClasses; control.params.title = settingValue.title || ''; control.params.depth = control.getDepth(); control.container.data( 'item-depth', control.params.depth ); containerClasses = [ 'menu-item', 'menu-item-depth-' + String( control.params.depth ), 'menu-item-' + settingValue.object, 'menu-item-edit-inactive' ]; if ( settingValue._invalid ) { containerClasses.push( 'menu-item-invalid' ); control.params.title = api.Menus.data.l10n.invalidTitleTpl.replace( '%s', control.params.title ); } else if ( 'draft' === settingValue.status ) { containerClasses.push( 'pending' ); control.params.title = api.Menus.data.pendingTitleTpl.replace( '%s', control.params.title ); } control.params.el_classes = containerClasses.join( ' ' ); control.params.item_type_label = settingValue.type_label; control.params.item_type = settingValue.type; control.params.url = settingValue.url; control.params.target = settingValue.target; control.params.attr_title = settingValue.attr_title; control.params.classes = _.isArray( settingValue.classes ) ? settingValue.classes.join( ' ' ) : settingValue.classes; control.params.attr_title = settingValue.attr_title; control.params.xfn = settingValue.xfn; control.params.description = settingValue.description; control.params.parent = settingValue.menu_item_parent; control.params.original_title = settingValue.original_title || ''; control.container.addClass( control.params.el_classes ); api.Control.prototype.renderContent.call( control ); }, /*********************************************************************** * Begin public API methods **********************************************************************/ /** * @return {wp.customize.controlConstructor.nav_menu|null} */ getMenuControl: function() { var control = this, settingValue = control.setting(); if ( settingValue && settingValue.nav_menu_term_id ) { return api.control( 'nav_menu[' + settingValue.nav_menu_term_id + ']' ); } else { return null; } }, /** * Expand the accordion section containing a control */ expandControlSection: function() { var $section = this.container.closest( '.accordion-section' ); if ( ! $section.hasClass( 'open' ) ) { $section.find( '.accordion-section-title:first' ).trigger( 'click' ); } }, /** * @since 4.6.0 * * @param {Boolean} expanded * @param {Object} [params] * @returns {Boolean} false if state already applied */ _toggleExpanded: api.Section.prototype._toggleExpanded, /** * @since 4.6.0 * * @param {Object} [params] * @returns {Boolean} false if already expanded */ expand: api.Section.prototype.expand, /** * Expand the menu item form control. * * @since 4.5.0 Added params.completeCallback. * * @param {Object} [params] - Optional params. * @param {Function} [params.completeCallback] - Function to call when the form toggle has finished animating. */ expandForm: function( params ) { this.expand( params ); }, /** * @since 4.6.0 * * @param {Object} [params] * @returns {Boolean} false if already collapsed */ collapse: api.Section.prototype.collapse, /** * Collapse the menu item form control. * * @since 4.5.0 Added params.completeCallback. * * @param {Object} [params] - Optional params. * @param {Function} [params.completeCallback] - Function to call when the form toggle has finished animating. */ collapseForm: function( params ) { this.collapse( params ); }, /** * Expand or collapse the menu item control. * * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide ) * @since 4.5.0 Added params.completeCallback. * * @param {boolean} [showOrHide] - If not supplied, will be inverse of current visibility * @param {Object} [params] - Optional params. * @param {Function} [params.completeCallback] - Function to call when the form toggle has finished animating. */ toggleForm: function( showOrHide, params ) { if ( typeof showOrHide === 'undefined' ) { showOrHide = ! this.expanded(); } if ( showOrHide ) { this.expand( params ); } else { this.collapse( params ); } }, /** * Expand or collapse the menu item control. * * @since 4.6.0 * @param {boolean} [showOrHide] - If not supplied, will be inverse of current visibility * @param {Object} [params] - Optional params. * @param {Function} [params.completeCallback] - Function to call when the form toggle has finished animating. */ onChangeExpanded: function( showOrHide, params ) { var self = this, $menuitem, $inside, complete; $menuitem = this.container; $inside = $menuitem.find( '.menu-item-settings:first' ); if ( 'undefined' === typeof showOrHide ) { showOrHide = ! $inside.is( ':visible' ); } // Already expanded or collapsed. if ( $inside.is( ':visible' ) === showOrHide ) { if ( params && params.completeCallback ) { params.completeCallback(); } return; } if ( showOrHide ) { // Close all other menu item controls before expanding this one. api.control.each( function( otherControl ) { if ( self.params.type === otherControl.params.type && self !== otherControl ) { otherControl.collapseForm(); } } ); complete = function() { $menuitem .removeClass( 'menu-item-edit-inactive' ) .addClass( 'menu-item-edit-active' ); self.container.trigger( 'expanded' ); if ( params && params.completeCallback ) { params.completeCallback(); } }; $menuitem.find( '.item-edit' ).attr( 'aria-expanded', 'true' ); $inside.slideDown( 'fast', complete ); self.container.trigger( 'expand' ); } else { complete = function() { $menuitem .addClass( 'menu-item-edit-inactive' ) .removeClass( 'menu-item-edit-active' ); self.container.trigger( 'collapsed' ); if ( params && params.completeCallback ) { params.completeCallback(); } }; self.container.trigger( 'collapse' ); $menuitem.find( '.item-edit' ).attr( 'aria-expanded', 'false' ); $inside.slideUp( 'fast', complete ); } }, /** * Expand the containing menu section, expand the form, and focus on * the first input in the control. * * @since 4.5.0 Added params.completeCallback. * * @param {Object} [params] - Params object. * @param {Function} [params.completeCallback] - Optional callback function when focus has completed. */ focus: function( params ) { params = params || {}; var control = this, originalCompleteCallback = params.completeCallback, focusControl; focusControl = function() { control.expandControlSection(); params.completeCallback = function() { var focusable; // Note that we can't use :focusable due to a jQuery UI issue. See: https://github.com/jquery/jquery-ui/pull/1583 focusable = control.container.find( '.menu-item-settings' ).find( 'input, select, textarea, button, object, a[href], [tabindex]' ).filter( ':visible' ); focusable.first().focus(); if ( originalCompleteCallback ) { originalCompleteCallback(); } }; control.expandForm( params ); }; if ( api.section.has( control.section() ) ) { api.section( control.section() ).expand( { completeCallback: focusControl } ); } else { focusControl(); } }, /** * Move menu item up one in the menu. */ moveUp: function() { this._changePosition( -1 ); wp.a11y.speak( api.Menus.data.l10n.movedUp ); }, /** * Move menu item up one in the menu. */ moveDown: function() { this._changePosition( 1 ); wp.a11y.speak( api.Menus.data.l10n.movedDown ); }, /** * Move menu item and all children up one level of depth. */ moveLeft: function() { this._changeDepth( -1 ); wp.a11y.speak( api.Menus.data.l10n.movedLeft ); }, /** * Move menu item and children one level deeper, as a submenu of the previous item. */ moveRight: function() { this._changeDepth( 1 ); wp.a11y.speak( api.Menus.data.l10n.movedRight ); }, /** * Note that this will trigger a UI update, causing child items to * move as well and cardinal order class names to be updated. * * @private * * @param {Number} offset 1|-1 */ _changePosition: function( offset ) { var control = this, adjacentSetting, settingValue = _.clone( control.setting() ), siblingSettings = [], realPosition; if ( 1 !== offset && -1 !== offset ) { throw new Error( 'Offset changes by 1 are only supported.' ); } // Skip moving deleted items. if ( ! control.setting() ) { return; } // Locate the other items under the same parent (siblings). _( control.getMenuControl().getMenuItemControls() ).each(function( otherControl ) { if ( otherControl.setting().menu_item_parent === settingValue.menu_item_parent ) { siblingSettings.push( otherControl.setting ); } }); siblingSettings.sort(function( a, b ) { return a().position - b().position; }); realPosition = _.indexOf( siblingSettings, control.setting ); if ( -1 === realPosition ) { throw new Error( 'Expected setting to be among siblings.' ); } // Skip doing anything if the item is already at the edge in the desired direction. if ( ( realPosition === 0 && offset < 0 ) || ( realPosition === siblingSettings.length - 1 && offset > 0 ) ) { // @todo Should we allow a menu item to be moved up to break it out of a parent? Adopt with previous or following parent? return; } // Update any adjacent menu item setting to take on this item's position. adjacentSetting = siblingSettings[ realPosition + offset ]; if ( adjacentSetting ) { adjacentSetting.set( $.extend( _.clone( adjacentSetting() ), { position: settingValue.position } ) ); } settingValue.position += offset; control.setting.set( settingValue ); }, /** * Note that this will trigger a UI update, causing child items to * move as well and cardinal order class names to be updated. * * @private * * @param {Number} offset 1|-1 */ _changeDepth: function( offset ) { if ( 1 !== offset && -1 !== offset ) { throw new Error( 'Offset changes by 1 are only supported.' ); } var control = this, settingValue = _.clone( control.setting() ), siblingControls = [], realPosition, siblingControl, parentControl; // Locate the other items under the same parent (siblings). _( control.getMenuControl().getMenuItemControls() ).each(function( otherControl ) { if ( otherControl.setting().menu_item_parent === settingValue.menu_item_parent ) { siblingControls.push( otherControl ); } }); siblingControls.sort(function( a, b ) { return a.setting().position - b.setting().position; }); realPosition = _.indexOf( siblingControls, control ); if ( -1 === realPosition ) { throw new Error( 'Expected control to be among siblings.' ); } if ( -1 === offset ) { // Skip moving left an item that is already at the top level. if ( ! settingValue.menu_item_parent ) { return; } parentControl = api.control( 'nav_menu_item[' + settingValue.menu_item_parent + ']' ); // Make this control the parent of all the following siblings. _( siblingControls ).chain().slice( realPosition ).each(function( siblingControl, i ) { siblingControl.setting.set( $.extend( {}, siblingControl.setting(), { menu_item_parent: control.params.menu_item_id, position: i } ) ); }); // Increase the positions of the parent item's subsequent children to make room for this one. _( control.getMenuControl().getMenuItemControls() ).each(function( otherControl ) { var otherControlSettingValue, isControlToBeShifted; isControlToBeShifted = ( otherControl.setting().menu_item_parent === parentControl.setting().menu_item_parent && otherControl.setting().position > parentControl.setting().position ); if ( isControlToBeShifted ) { otherControlSettingValue = _.clone( otherControl.setting() ); otherControl.setting.set( $.extend( otherControlSettingValue, { position: otherControlSettingValue.position + 1 } ) ); } }); // Make this control the following sibling of its parent item. settingValue.position = parentControl.setting().position + 1; settingValue.menu_item_parent = parentControl.setting().menu_item_parent; control.setting.set( settingValue ); } else if ( 1 === offset ) { // Skip moving right an item that doesn't have a previous sibling. if ( realPosition === 0 ) { return; } // Make the control the last child of the previous sibling. siblingControl = siblingControls[ realPosition - 1 ]; settingValue.menu_item_parent = siblingControl.params.menu_item_id; settingValue.position = 0; _( control.getMenuControl().getMenuItemControls() ).each(function( otherControl ) { if ( otherControl.setting().menu_item_parent === settingValue.menu_item_parent ) { settingValue.position = Math.max( settingValue.position, otherControl.setting().position ); } }); settingValue.position += 1; control.setting.set( settingValue ); } } } ); /** * wp.customize.Menus.MenuNameControl * * Customizer control for a nav menu's name. * * @constructor * @augments wp.customize.Control */ api.Menus.MenuNameControl = api.Control.extend({ ready: function() { var control = this, settingValue = control.setting(); /* * Since the control is not registered in PHP, we need to prevent the * preview's sending of the activeControls to result in this control * being deactivated. */ control.active.validate = function() { var value, section = api.section( control.section() ); if ( section ) { value = section.active(); } else { value = false; } return value; }; control.nameElement = new api.Element( control.container.find( '.menu-name-field' ) ); control.nameElement.bind(function( value ) { var settingValue = control.setting(); if ( settingValue && settingValue.name !== value ) { settingValue = _.clone( settingValue ); settingValue.name = value; control.setting.set( settingValue ); } }); if ( settingValue ) { control.nameElement.set( settingValue.name ); } control.setting.bind(function( object ) { if ( object ) { control.nameElement.set( object.name ); } }); } }); /** * wp.customize.Menus.MenuAutoAddControl * * Customizer control for a nav menu's auto add. * * @constructor * @augments wp.customize.Control */ api.Menus.MenuAutoAddControl = api.Control.extend({ ready: function() { var control = this, settingValue = control.setting(); /* * Since the control is not registered in PHP, we need to prevent the * preview's sending of the activeControls to result in this control * being deactivated. */ control.active.validate = function() { var value, section = api.section( control.section() ); if ( section ) { value = section.active(); } else { value = false; } return value; }; control.autoAddElement = new api.Element( control.container.find( 'input[type=checkbox].auto_add' ) ); control.autoAddElement.bind(function( value ) { var settingValue = control.setting(); if ( settingValue && settingValue.name !== value ) { settingValue = _.clone( settingValue ); settingValue.auto_add = value; control.setting.set( settingValue ); } }); if ( settingValue ) { control.autoAddElement.set( settingValue.auto_add ); } control.setting.bind(function( object ) { if ( object ) { control.autoAddElement.set( object.auto_add ); } }); } }); /** * wp.customize.Menus.MenuControl * * Customizer control for menus. * Note that 'nav_menu' must match the WP_Menu_Customize_Control::$type * * @constructor * @augments wp.customize.Control */ api.Menus.MenuControl = api.Control.extend({ /** * Set up the control. */ ready: function() { var control = this, section = api.section( control.section() ), menuId = control.params.menu_id, menu = control.setting(), name, widgetTemplate, select; if ( 'undefined' === typeof this.params.menu_id ) { throw new Error( 'params.menu_id was not defined' ); } /* * Since the control is not registered in PHP, we need to prevent the * preview's sending of the activeControls to result in this control * being deactivated. */ control.active.validate = function() { var value; if ( section ) { value = section.active(); } else { value = false; } return value; }; control.$controlSection = section.headContainer; control.$sectionContent = control.container.closest( '.accordion-section-content' ); this._setupModel(); api.section( control.section(), function( section ) { section.deferred.initSortables.done(function( menuList ) { control._setupSortable( menuList ); }); } ); this._setupAddition(); this._setupLocations(); this._setupTitle(); // Add menu to Custom Menu widgets. if ( menu ) { name = displayNavMenuName( menu.name ); // Add the menu to the existing controls. api.control.each( function( widgetControl ) { if ( ! widgetControl.extended( api.controlConstructor.widget_form ) || 'nav_menu' !== widgetControl.params.widget_id_base ) { return; } widgetControl.container.find( '.nav-menu-widget-form-controls:first' ).show(); widgetControl.container.find( '.nav-menu-widget-no-menus-message:first' ).hide(); select = widgetControl.container.find( 'select' ); if ( 0 === select.find( 'option[value=' + String( menuId ) + ']' ).length ) { select.append( new Option( name, menuId ) ); } } ); // Add the menu to the widget template. widgetTemplate = $( '#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )' ); widgetTemplate.find( '.nav-menu-widget-form-controls:first' ).show(); widgetTemplate.find( '.nav-menu-widget-no-menus-message:first' ).hide(); select = widgetTemplate.find( '.widget-inside select:first' ); if ( 0 === select.find( 'option[value=' + String( menuId ) + ']' ).length ) { select.append( new Option( name, menuId ) ); } } }, /** * Update ordering of menu item controls when the setting is updated. */ _setupModel: function() { var control = this, menuId = control.params.menu_id; control.setting.bind( function( to ) { var name; if ( false === to ) { control._handleDeletion(); } else { // Update names in the Custom Menu widgets. name = displayNavMenuName( to.name ); api.control.each( function( widgetControl ) { if ( ! widgetControl.extended( api.controlConstructor.widget_form ) || 'nav_menu' !== widgetControl.params.widget_id_base ) { return; } var select = widgetControl.container.find( 'select' ); select.find( 'option[value=' + String( menuId ) + ']' ).text( name ); }); } } ); control.container.find( '.menu-delete-item' ).on( 'click', function( event ) { event.stopPropagation(); event.preventDefault(); control.setting.set( false ); }); }, /** * Allow items in each menu to be re-ordered, and for the order to be previewed. * * Notice that the UI aspects here are handled by wpNavMenu.initSortables() * which is called in MenuSection.onChangeExpanded() * * @param {object} menuList - The element that has sortable(). */ _setupSortable: function( menuList ) { var control = this; if ( ! menuList.is( control.$sectionContent ) ) { throw new Error( 'Unexpected menuList.' ); } menuList.on( 'sortstart', function() { control.isSorting = true; }); menuList.on( 'sortstop', function() { setTimeout( function() { // Next tick. var menuItemContainerIds = control.$sectionContent.sortable( 'toArray' ), menuItemControls = [], position = 0, priority = 10; control.isSorting = false; // Reset horizontal scroll position when done dragging. control.$sectionContent.scrollLeft( 0 ); _.each( menuItemContainerIds, function( menuItemContainerId ) { var menuItemId, menuItemControl, matches; matches = menuItemContainerId.match( /^customize-control-nav_menu_item-(-?\d+)$/, '' ); if ( ! matches ) { return; } menuItemId = parseInt( matches[1], 10 ); menuItemControl = api.control( 'nav_menu_item[' + String( menuItemId ) + ']' ); if ( menuItemControl ) { menuItemControls.push( menuItemControl ); } } ); _.each( menuItemControls, function( menuItemControl ) { if ( false === menuItemControl.setting() ) { // Skip deleted items. return; } var setting = _.clone( menuItemControl.setting() ); position += 1; priority += 1; setting.position = position; menuItemControl.priority( priority ); // Note that wpNavMenu will be setting this .menu-item-data-parent-id input's value. setting.menu_item_parent = parseInt( menuItemControl.container.find( '.menu-item-data-parent-id' ).val(), 10 ); if ( ! setting.menu_item_parent ) { setting.menu_item_parent = 0; } menuItemControl.setting.set( setting ); }); }); }); control.isReordering = false; /** * Keyboard-accessible reordering. */ this.container.find( '.reorder-toggle' ).on( 'click', function() { control.toggleReordering( ! control.isReordering ); } ); }, /** * Set up UI for adding a new menu item. */ _setupAddition: function() { var self = this; this.container.find( '.add-new-menu-item' ).on( 'click', function( event ) { if ( self.$sectionContent.hasClass( 'reordering' ) ) { return; } if ( ! $( 'body' ).hasClass( 'adding-menu-items' ) ) { $( this ).attr( 'aria-expanded', 'true' ); api.Menus.availableMenuItemsPanel.open( self ); } else { $( this ).attr( 'aria-expanded', 'false' ); api.Menus.availableMenuItemsPanel.close(); event.stopPropagation(); } } ); }, _handleDeletion: function() { var control = this, section, menuId = control.params.menu_id, removeSection, widgetTemplate, navMenuCount = 0; section = api.section( control.section() ); removeSection = function() { section.container.remove(); api.section.remove( section.id ); }; if ( section && section.expanded() ) { section.collapse({ completeCallback: function() { removeSection(); wp.a11y.speak( api.Menus.data.l10n.menuDeleted ); api.panel( 'nav_menus' ).focus(); } }); } else { removeSection(); } api.each(function( setting ) { if ( /^nav_menu\[/.test( setting.id ) && false !== setting() ) { navMenuCount += 1; } }); // Remove the menu from any Custom Menu widgets. api.control.each(function( widgetControl ) { if ( ! widgetControl.extended( api.controlConstructor.widget_form ) || 'nav_menu' !== widgetControl.params.widget_id_base ) { return; } var select = widgetControl.container.find( 'select' ); if ( select.val() === String( menuId ) ) { select.prop( 'selectedIndex', 0 ).trigger( 'change' ); } widgetControl.container.find( '.nav-menu-widget-form-controls:first' ).toggle( 0 !== navMenuCount ); widgetControl.container.find( '.nav-menu-widget-no-menus-message:first' ).toggle( 0 === navMenuCount ); widgetControl.container.find( 'option[value=' + String( menuId ) + ']' ).remove(); }); // Remove the menu to the nav menu widget template. widgetTemplate = $( '#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )' ); widgetTemplate.find( '.nav-menu-widget-form-controls:first' ).toggle( 0 !== navMenuCount ); widgetTemplate.find( '.nav-menu-widget-no-menus-message:first' ).toggle( 0 === navMenuCount ); widgetTemplate.find( 'option[value=' + String( menuId ) + ']' ).remove(); }, // Setup theme location checkboxes. _setupLocations: function() { var control = this; control.container.find( '.assigned-menu-location' ).each(function() { var container = $( this ), checkbox = container.find( 'input[type=checkbox]' ), element, updateSelectedMenuLabel, navMenuLocationSetting = api( 'nav_menu_locations[' + checkbox.data( 'location-id' ) + ']' ); updateSelectedMenuLabel = function( selectedMenuId ) { var menuSetting = api( 'nav_menu[' + String( selectedMenuId ) + ']' ); if ( ! selectedMenuId || ! menuSetting || ! menuSetting() ) { container.find( '.theme-location-set' ).hide(); } else { container.find( '.theme-location-set' ).show().find( 'span' ).text( displayNavMenuName( menuSetting().name ) ); } }; element = new api.Element( checkbox ); element.set( navMenuLocationSetting.get() === control.params.menu_id ); checkbox.on( 'change', function() { // Note: We can't use element.bind( function( checked ){ ... } ) here because it will trigger a change as well. navMenuLocationSetting.set( this.checked ? control.params.menu_id : 0 ); } ); navMenuLocationSetting.bind(function( selectedMenuId ) { element.set( selectedMenuId === control.params.menu_id ); updateSelectedMenuLabel( selectedMenuId ); }); updateSelectedMenuLabel( navMenuLocationSetting.get() ); }); }, /** * Update Section Title as menu name is changed. */ _setupTitle: function() { var control = this; control.setting.bind( function( menu ) { if ( ! menu ) { return; } var section = api.section( control.section() ), menuId = control.params.menu_id, controlTitle = section.headContainer.find( '.accordion-section-title' ), sectionTitle = section.contentContainer.find( '.customize-section-title h3' ), location = section.headContainer.find( '.menu-in-location' ), action = sectionTitle.find( '.customize-action' ), name = displayNavMenuName( menu.name ); // Update the control title controlTitle.text( name ); if ( location.length ) { location.appendTo( controlTitle ); } // Update the section title sectionTitle.text( name ); if ( action.length ) { action.prependTo( sectionTitle ); } // Update the nav menu name in location selects. api.control.each( function( control ) { if ( /^nav_menu_locations\[/.test( control.id ) ) { control.container.find( 'option[value=' + menuId + ']' ).text( name ); } } ); // Update the nav menu name in all location checkboxes. section.contentContainer.find( '.customize-control-checkbox input' ).each( function() { if ( $( this ).prop( 'checked' ) ) { $( '.current-menu-location-name-' + $( this ).data( 'location-id' ) ).text( name ); } } ); } ); }, /*********************************************************************** * Begin public API methods **********************************************************************/ /** * Enable/disable the reordering UI * * @param {Boolean} showOrHide to enable/disable reordering */ toggleReordering: function( showOrHide ) { var addNewItemBtn = this.container.find( '.add-new-menu-item' ), reorderBtn = this.container.find( '.reorder-toggle' ), itemsTitle = this.$sectionContent.find( '.item-title' ); showOrHide = Boolean( showOrHide ); if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) { return; } this.isReordering = showOrHide; this.$sectionContent.toggleClass( 'reordering', showOrHide ); this.$sectionContent.sortable( this.isReordering ? 'disable' : 'enable' ); if ( this.isReordering ) { addNewItemBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' }); reorderBtn.attr( 'aria-label', api.Menus.data.l10n.reorderLabelOff ); wp.a11y.speak( api.Menus.data.l10n.reorderModeOn ); itemsTitle.attr( 'aria-hidden', 'false' ); } else { addNewItemBtn.removeAttr( 'tabindex aria-hidden' ); reorderBtn.attr( 'aria-label', api.Menus.data.l10n.reorderLabelOn ); wp.a11y.speak( api.Menus.data.l10n.reorderModeOff ); itemsTitle.attr( 'aria-hidden', 'true' ); } if ( showOrHide ) { _( this.getMenuItemControls() ).each( function( formControl ) { formControl.collapseForm(); } ); } }, /** * @return {wp.customize.controlConstructor.nav_menu_item[]} */ getMenuItemControls: function() { var menuControl = this, menuItemControls = [], menuTermId = menuControl.params.menu_id; api.control.each(function( control ) { if ( 'nav_menu_item' === control.params.type && control.setting() && menuTermId === control.setting().nav_menu_term_id ) { menuItemControls.push( control ); } }); return menuItemControls; }, /** * Make sure that each menu item control has the proper depth. */ reflowMenuItems: function() { var menuControl = this, menuItemControls = menuControl.getMenuItemControls(), reflowRecursively; reflowRecursively = function( context ) { var currentMenuItemControls = [], thisParent = context.currentParent; _.each( context.menuItemControls, function( menuItemControl ) { if ( thisParent === menuItemControl.setting().menu_item_parent ) { currentMenuItemControls.push( menuItemControl ); // @todo We could remove this item from menuItemControls now, for efficiency. } }); currentMenuItemControls.sort( function( a, b ) { return a.setting().position - b.setting().position; }); _.each( currentMenuItemControls, function( menuItemControl ) { // Update position. context.currentAbsolutePosition += 1; menuItemControl.priority.set( context.currentAbsolutePosition ); // This will change the sort order. // Update depth. if ( ! menuItemControl.container.hasClass( 'menu-item-depth-' + String( context.currentDepth ) ) ) { _.each( menuItemControl.container.prop( 'className' ).match( /menu-item-depth-\d+/g ), function( className ) { menuItemControl.container.removeClass( className ); }); menuItemControl.container.addClass( 'menu-item-depth-' + String( context.currentDepth ) ); } menuItemControl.container.data( 'item-depth', context.currentDepth ); // Process any children items. context.currentDepth += 1; context.currentParent = menuItemControl.params.menu_item_id; reflowRecursively( context ); context.currentDepth -= 1; context.currentParent = thisParent; }); // Update class names for reordering controls. if ( currentMenuItemControls.length ) { _( currentMenuItemControls ).each(function( menuItemControl ) { menuItemControl.container.removeClass( 'move-up-disabled move-down-disabled move-left-disabled move-right-disabled' ); if ( 0 === context.currentDepth ) { menuItemControl.container.addClass( 'move-left-disabled' ); } else if ( 10 === context.currentDepth ) { menuItemControl.container.addClass( 'move-right-disabled' ); } }); currentMenuItemControls[0].container .addClass( 'move-up-disabled' ) .addClass( 'move-right-disabled' ) .toggleClass( 'move-down-disabled', 1 === currentMenuItemControls.length ); currentMenuItemControls[ currentMenuItemControls.length - 1 ].container .addClass( 'move-down-disabled' ) .toggleClass( 'move-up-disabled', 1 === currentMenuItemControls.length ); } }; reflowRecursively( { menuItemControls: menuItemControls, currentParent: 0, currentDepth: 0, currentAbsolutePosition: 0 } ); menuControl.container.find( '.reorder-toggle' ).toggle( menuItemControls.length > 1 ); }, /** * Note that this function gets debounced so that when a lot of setting * changes are made at once, for instance when moving a menu item that * has child items, this function will only be called once all of the * settings have been updated. */ debouncedReflowMenuItems: _.debounce( function() { this.reflowMenuItems.apply( this, arguments ); }, 0 ), /** * Add a new item to this menu. * * @param {object} item - Value for the nav_menu_item setting to be created. * @returns {wp.customize.Menus.controlConstructor.nav_menu_item} The newly-created nav_menu_item control instance. */ addItemToMenu: function( item ) { var menuControl = this, customizeId, settingArgs, setting, menuItemControl, placeholderId, position = 0, priority = 10; _.each( menuControl.getMenuItemControls(), function( control ) { if ( false === control.setting() ) { return; } priority = Math.max( priority, control.priority() ); if ( 0 === control.setting().menu_item_parent ) { position = Math.max( position, control.setting().position ); } }); position += 1; priority += 1; item = $.extend( {}, api.Menus.data.defaultSettingValues.nav_menu_item, item, { nav_menu_term_id: menuControl.params.menu_id, position: position } ); delete item.id; // only used by Backbone placeholderId = api.Menus.generatePlaceholderAutoIncrementId(); customizeId = 'nav_menu_item[' + String( placeholderId ) + ']'; settingArgs = { type: 'nav_menu_item', transport: api.Menus.data.settingTransport, previewer: api.previewer }; setting = api.create( customizeId, customizeId, {}, settingArgs ); setting.set( item ); // Change from initial empty object to actual item to mark as dirty. // Add the menu item control. menuItemControl = new api.controlConstructor.nav_menu_item( customizeId, { params: { type: 'nav_menu_item', content: '<li id="customize-control-nav_menu_item-' + String( placeholderId ) + '" class="customize-control customize-control-nav_menu_item"></li>', section: menuControl.id, priority: priority, active: true, settings: { 'default': customizeId }, menu_item_id: placeholderId }, previewer: api.previewer } ); api.control.add( customizeId, menuItemControl ); setting.preview(); menuControl.debouncedReflowMenuItems(); wp.a11y.speak( api.Menus.data.l10n.itemAdded ); return menuItemControl; } } ); /** * wp.customize.Menus.NewMenuControl * * Customizer control for creating new menus and handling deletion of existing menus. * Note that 'new_menu' must match the WP_Customize_New_Menu_Control::$type. * * @constructor * @augments wp.customize.Control */ api.Menus.NewMenuControl = api.Control.extend({ /** * Set up the control. */ ready: function() { this._bindHandlers(); }, _bindHandlers: function() { var self = this, name = $( '#customize-control-new_menu_name input' ), submit = $( '#create-new-menu-submit' ); name.on( 'keydown', function( event ) { if ( 13 === event.which ) { // Enter. self.submit(); } } ); submit.on( 'click', function( event ) { self.submit(); event.stopPropagation(); event.preventDefault(); } ); }, /** * Create the new menu with the name supplied. */ submit: function() { var control = this, container = control.container.closest( '.accordion-section-new-menu' ), nameInput = container.find( '.menu-name-field' ).first(), name = nameInput.val(), menuSection, customizeId, placeholderId = api.Menus.generatePlaceholderAutoIncrementId(); if ( ! name ) { nameInput.addClass( 'invalid' ); nameInput.focus(); return; } customizeId = 'nav_menu[' + String( placeholderId ) + ']'; // Register the menu control setting. api.create( customizeId, customizeId, {}, { type: 'nav_menu', transport: api.Menus.data.settingTransport, previewer: api.previewer } ); api( customizeId ).set( $.extend( {}, api.Menus.data.defaultSettingValues.nav_menu, { name: name } ) ); /* * Add the menu section (and its controls). * Note that this will automatically create the required controls * inside via the Section's ready method. */ menuSection = new api.Menus.MenuSection( customizeId, { params: { id: customizeId, panel: 'nav_menus', title: displayNavMenuName( name ), customizeAction: api.Menus.data.l10n.customizingMenus, type: 'nav_menu', priority: 10, menu_id: placeholderId } } ); api.section.add( customizeId, menuSection ); // Clear name field. nameInput.val( '' ); nameInput.removeClass( 'invalid' ); wp.a11y.speak( api.Menus.data.l10n.menuAdded ); // Focus on the new menu section. api.section( customizeId ).focus(); // @todo should we focus on the new menu's control and open the add-items panel? Thinking user flow... } }); /** * Extends wp.customize.controlConstructor with control constructor for * menu_location, menu_item, nav_menu, and new_menu. */ $.extend( api.controlConstructor, { nav_menu_location: api.Menus.MenuLocationControl, nav_menu_item: api.Menus.MenuItemControl, nav_menu: api.Menus.MenuControl, nav_menu_name: api.Menus.MenuNameControl, nav_menu_auto_add: api.Menus.MenuAutoAddControl, new_menu: api.Menus.NewMenuControl }); /** * Extends wp.customize.panelConstructor with section constructor for menus. */ $.extend( api.panelConstructor, { nav_menus: api.Menus.MenusPanel }); /** * Extends wp.customize.sectionConstructor with section constructor for menu. */ $.extend( api.sectionConstructor, { nav_menu: api.Menus.MenuSection, new_menu: api.Menus.NewMenuSection }); /** * Init Customizer for menus. */ api.bind( 'ready', function() { // Set up the menu items panel. api.Menus.availableMenuItemsPanel = new api.Menus.AvailableMenuItemsPanelView({ collection: api.Menus.availableMenuItems }); api.bind( 'saved', function( data ) { if ( data.nav_menu_updates || data.nav_menu_item_updates ) { api.Menus.applySavedData( data ); } } ); /* * Reset the list of posts created in the customizer once published. * The setting is updated quietly (bypassing events being triggered) * so that the customized state doesn't become immediately dirty. */ api.state( 'changesetStatus' ).bind( function( status ) { if ( 'publish' === status ) { api( 'nav_menus_created_posts' )._value = []; } } ); // Open and focus menu control. api.previewer.bind( 'focus-nav-menu-item-control', api.Menus.focusMenuItemControl ); } ); /** * When customize_save comes back with a success, make sure any inserted * nav menus and items are properly re-added with their newly-assigned IDs. * * @param {object} data * @param {array} data.nav_menu_updates * @param {array} data.nav_menu_item_updates */ api.Menus.applySavedData = function( data ) { var insertedMenuIdMapping = {}, insertedMenuItemIdMapping = {}; _( data.nav_menu_updates ).each(function( update ) { var oldCustomizeId, newCustomizeId, customizeId, oldSetting, newSetting, setting, settingValue, oldSection, newSection, wasSaved, widgetTemplate, navMenuCount; if ( 'inserted' === update.status ) { if ( ! update.previous_term_id ) { throw new Error( 'Expected previous_term_id' ); } if ( ! update.term_id ) { throw new Error( 'Expected term_id' ); } oldCustomizeId = 'nav_menu[' + String( update.previous_term_id ) + ']'; if ( ! api.has( oldCustomizeId ) ) { throw new Error( 'Expected setting to exist: ' + oldCustomizeId ); } oldSetting = api( oldCustomizeId ); if ( ! api.section.has( oldCustomizeId ) ) { throw new Error( 'Expected control to exist: ' + oldCustomizeId ); } oldSection = api.section( oldCustomizeId ); settingValue = oldSetting.get(); if ( ! settingValue ) { throw new Error( 'Did not expect setting to be empty (deleted).' ); } settingValue = $.extend( _.clone( settingValue ), update.saved_value ); insertedMenuIdMapping[ update.previous_term_id ] = update.term_id; newCustomizeId = 'nav_menu[' + String( update.term_id ) + ']'; newSetting = api.create( newCustomizeId, newCustomizeId, settingValue, { type: 'nav_menu', transport: api.Menus.data.settingTransport, previewer: api.previewer } ); if ( oldSection.expanded() ) { oldSection.collapse(); } // Add the menu section. newSection = new api.Menus.MenuSection( newCustomizeId, { params: { id: newCustomizeId, panel: 'nav_menus', title: settingValue.name, customizeAction: api.Menus.data.l10n.customizingMenus, type: 'nav_menu', priority: oldSection.priority.get(), active: true, menu_id: update.term_id } } ); // Add new control for the new menu. api.section.add( newCustomizeId, newSection ); // Update the values for nav menus in Custom Menu controls. api.control.each( function( setting ) { if ( ! setting.extended( api.controlConstructor.widget_form ) || 'nav_menu' !== setting.params.widget_id_base ) { return; } var select, oldMenuOption, newMenuOption; select = setting.container.find( 'select' ); oldMenuOption = select.find( 'option[value=' + String( update.previous_term_id ) + ']' ); newMenuOption = select.find( 'option[value=' + String( update.term_id ) + ']' ); newMenuOption.prop( 'selected', oldMenuOption.prop( 'selected' ) ); oldMenuOption.remove(); } ); // Delete the old placeholder nav_menu. oldSetting.callbacks.disable(); // Prevent setting triggering Customizer dirty state when set. oldSetting.set( false ); oldSetting.preview(); newSetting.preview(); oldSetting._dirty = false; // Remove nav_menu section. oldSection.container.remove(); api.section.remove( oldCustomizeId ); // Update the nav_menu widget to reflect removed placeholder menu. navMenuCount = 0; api.each(function( setting ) { if ( /^nav_menu\[/.test( setting.id ) && false !== setting() ) { navMenuCount += 1; } }); widgetTemplate = $( '#available-widgets-list .widget-tpl:has( input.id_base[ value=nav_menu ] )' ); widgetTemplate.find( '.nav-menu-widget-form-controls:first' ).toggle( 0 !== navMenuCount ); widgetTemplate.find( '.nav-menu-widget-no-menus-message:first' ).toggle( 0 === navMenuCount ); widgetTemplate.find( 'option[value=' + String( update.previous_term_id ) + ']' ).remove(); // Update the nav_menu_locations[...] controls to remove the placeholder menus from the dropdown options. wp.customize.control.each(function( control ){ if ( /^nav_menu_locations\[/.test( control.id ) ) { control.container.find( 'option[value=' + String( update.previous_term_id ) + ']' ).remove(); } }); // Update nav_menu_locations to reference the new ID. api.each( function( setting ) { var wasSaved = api.state( 'saved' ).get(); if ( /^nav_menu_locations\[/.test( setting.id ) && setting.get() === update.previous_term_id ) { setting.set( update.term_id ); setting._dirty = false; // Not dirty because this is has also just been done on server in WP_Customize_Nav_Menu_Setting::update(). api.state( 'saved' ).set( wasSaved ); setting.preview(); } } ); if ( oldSection.expanded.get() ) { // @todo This doesn't seem to be working. newSection.expand(); } } else if ( 'updated' === update.status ) { customizeId = 'nav_menu[' + String( update.term_id ) + ']'; if ( ! api.has( customizeId ) ) { throw new Error( 'Expected setting to exist: ' + customizeId ); } // Make sure the setting gets updated with its sanitized server value (specifically the conflict-resolved name). setting = api( customizeId ); if ( ! _.isEqual( update.saved_value, setting.get() ) ) { wasSaved = api.state( 'saved' ).get(); setting.set( update.saved_value ); setting._dirty = false; api.state( 'saved' ).set( wasSaved ); } } } ); // Build up mapping of nav_menu_item placeholder IDs to inserted IDs. _( data.nav_menu_item_updates ).each(function( update ) { if ( update.previous_post_id ) { insertedMenuItemIdMapping[ update.previous_post_id ] = update.post_id; } }); _( data.nav_menu_item_updates ).each(function( update ) { var oldCustomizeId, newCustomizeId, oldSetting, newSetting, settingValue, oldControl, newControl; if ( 'inserted' === update.status ) { if ( ! update.previous_post_id ) { throw new Error( 'Expected previous_post_id' ); } if ( ! update.post_id ) { throw new Error( 'Expected post_id' ); } oldCustomizeId = 'nav_menu_item[' + String( update.previous_post_id ) + ']'; if ( ! api.has( oldCustomizeId ) ) { throw new Error( 'Expected setting to exist: ' + oldCustomizeId ); } oldSetting = api( oldCustomizeId ); if ( ! api.control.has( oldCustomizeId ) ) { throw new Error( 'Expected control to exist: ' + oldCustomizeId ); } oldControl = api.control( oldCustomizeId ); settingValue = oldSetting.get(); if ( ! settingValue ) { throw new Error( 'Did not expect setting to be empty (deleted).' ); } settingValue = _.clone( settingValue ); // If the parent menu item was also inserted, update the menu_item_parent to the new ID. if ( settingValue.menu_item_parent < 0 ) { if ( ! insertedMenuItemIdMapping[ settingValue.menu_item_parent ] ) { throw new Error( 'inserted ID for menu_item_parent not available' ); } settingValue.menu_item_parent = insertedMenuItemIdMapping[ settingValue.menu_item_parent ]; } // If the menu was also inserted, then make sure it uses the new menu ID for nav_menu_term_id. if ( insertedMenuIdMapping[ settingValue.nav_menu_term_id ] ) { settingValue.nav_menu_term_id = insertedMenuIdMapping[ settingValue.nav_menu_term_id ]; } newCustomizeId = 'nav_menu_item[' + String( update.post_id ) + ']'; newSetting = api.create( newCustomizeId, newCustomizeId, settingValue, { type: 'nav_menu_item', transport: api.Menus.data.settingTransport, previewer: api.previewer } ); // Add the menu control. newControl = new api.controlConstructor.nav_menu_item( newCustomizeId, { params: { type: 'nav_menu_item', content: '<li id="customize-control-nav_menu_item-' + String( update.post_id ) + '" class="customize-control customize-control-nav_menu_item"></li>', menu_id: update.post_id, section: 'nav_menu[' + String( settingValue.nav_menu_term_id ) + ']', priority: oldControl.priority.get(), active: true, settings: { 'default': newCustomizeId }, menu_item_id: update.post_id }, previewer: api.previewer } ); // Remove old control. oldControl.container.remove(); api.control.remove( oldCustomizeId ); // Add new control to take its place. api.control.add( newCustomizeId, newControl ); // Delete the placeholder and preview the new setting. oldSetting.callbacks.disable(); // Prevent setting triggering Customizer dirty state when set. oldSetting.set( false ); oldSetting.preview(); newSetting.preview(); oldSetting._dirty = false; newControl.container.toggleClass( 'menu-item-edit-inactive', oldControl.container.hasClass( 'menu-item-edit-inactive' ) ); } }); /* * Update the settings for any nav_menu widgets that had selected a placeholder ID. */ _.each( data.widget_nav_menu_updates, function( widgetSettingValue, widgetSettingId ) { var setting = api( widgetSettingId ); if ( setting ) { setting._value = widgetSettingValue; setting.preview(); // Send to the preview now so that menu refresh will use the inserted menu. } }); }; /** * Focus a menu item control. * * @param {string} menuItemId */ api.Menus.focusMenuItemControl = function( menuItemId ) { var control = api.Menus.getMenuItemControl( menuItemId ); if ( control ) { control.focus(); } }; /** * Get the control for a given menu. * * @param menuId * @return {wp.customize.controlConstructor.menus[]} */ api.Menus.getMenuControl = function( menuId ) { return api.control( 'nav_menu[' + menuId + ']' ); }; /** * Given a menu item ID, get the control associated with it. * * @param {string} menuItemId * @return {object|null} */ api.Menus.getMenuItemControl = function( menuItemId ) { return api.control( menuItemIdToSettingId( menuItemId ) ); }; /** * @param {String} menuItemId */ function menuItemIdToSettingId( menuItemId ) { return 'nav_menu_item[' + menuItemId + ']'; } /** * Apply sanitize_text_field()-like logic to the supplied name, returning a * "unnammed" fallback string if the name is then empty. * * @param {string} name * @returns {string} */ function displayNavMenuName( name ) { name = name || ''; name = $( '<div>' ).text( name ).html(); // Emulate esc_html() which is used in wp-admin/nav-menus.php. name = $.trim( name ); return name || api.Menus.data.l10n.unnamed; } })( wp.customize, wp, jQuery ); iris.min.js 0000666 00000056070 15213733063 0006651 0 ustar 00 /*! Iris Color Picker - v1.1.0-beta - 2016-10-25 * https://github.com/Automattic/Iris * Copyright (c) 2016 Matt Wiebe; Licensed GPLv2 */ !function(a,b){function c(){var b,c,d="backgroundImage";j?k="filter":(b=a('<div id="iris-gradtest" />'),c="linear-gradient(top,#fff,#000)",a.each(l,function(a,e){if(b.css(d,e+c),b.css(d).match("gradient"))return k=a,!1}),k===!1&&(b.css("background","-webkit-gradient(linear,0% 0%,0% 100%,from(#fff),to(#000))"),b.css(d).match("gradient")&&(k="webkit")),b.remove())}function d(b,c){return b="top"===b?"top":"left",c=a.isArray(c)?c:Array.prototype.slice.call(arguments,1),"webkit"===k?f(b,c):l[k]+"linear-gradient("+b+", "+c.join(", ")+")"}function e(b,c){var d,e,f,h,i,j,k,l,m;b="top"===b?"top":"left",c=a.isArray(c)?c:Array.prototype.slice.call(arguments,1),d="top"===b?0:1,e=a(this),f=c.length-1,h="filter",i=1===d?"left":"top",j=1===d?"right":"bottom",k=1===d?"height":"width",l='<div class="iris-ie-gradient-shim" style="position:absolute;'+k+":100%;"+i+":%start%;"+j+":%end%;"+h+':%filter%;" data-color:"%color%"></div>',m="","static"===e.css("position")&&e.css({position:"relative"}),c=g(c),a.each(c,function(a,b){var e,g,h;return a!==f&&(e=c[a+1],void(b.stop!==e.stop&&(g=100-parseFloat(e.stop)+"%",b.octoHex=new Color(b.color).toIEOctoHex(),e.octoHex=new Color(e.color).toIEOctoHex(),h="progid:DXImageTransform.Microsoft.Gradient(GradientType="+d+", StartColorStr='"+b.octoHex+"', EndColorStr='"+e.octoHex+"')",m+=l.replace("%start%",b.stop).replace("%end%",g).replace("%filter%",h))))}),e.find(".iris-ie-gradient-shim").remove(),a(m).prependTo(e)}function f(b,c){var d=[];return b="top"===b?"0% 0%,0% 100%,":"0% 100%,100% 100%,",c=g(c),a.each(c,function(a,b){d.push("color-stop("+parseFloat(b.stop)/100+", "+b.color+")")}),"-webkit-gradient(linear,"+b+d.join(",")+")"}function g(b){var c=[],d=[],e=[],f=b.length-1;return a.each(b,function(a,b){var e=b,f=!1,g=b.match(/1?[0-9]{1,2}%$/);g&&(e=b.replace(/\s?1?[0-9]{1,2}%$/,""),f=g.shift()),c.push(e),d.push(f)}),d[0]===!1&&(d[0]="0%"),d[f]===!1&&(d[f]="100%"),d=h(d),a.each(d,function(a){e[a]={color:c[a],stop:d[a]}}),e}function h(b){var c,d,e,f,g=0,i=b.length-1,j=0,k=!1;if(b.length<=2||a.inArray(!1,b)<0)return b;for(;j<b.length-1;)k||b[j]!==!1?k&&b[j]!==!1&&(i=j,j=b.length):(g=j-1,k=!0),j++;for(d=i-g,f=parseInt(b[g].replace("%"),10),c=(parseFloat(b[i].replace("%"))-f)/d,j=g+1,e=1;j<i;)b[j]=f+e*c+"%",e++,j++;return h(b)}var i,j,k,l,m,n,o,p,q;return i='<div class="iris-picker"><div class="iris-picker-inner"><div class="iris-square"><a class="iris-square-value" href="#"><span class="iris-square-handle ui-slider-handle"></span></a><div class="iris-square-inner iris-square-horiz"></div><div class="iris-square-inner iris-square-vert"></div></div><div class="iris-slider iris-strip"><div class="iris-slider-offset"></div></div></div></div>',m='.iris-picker{display:block;position:relative}.iris-picker,.iris-picker *{-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input+.iris-picker{margin-top:4px}.iris-error{background-color:#ffafaf}.iris-border{border-radius:3px;border:1px solid #aaa;width:200px;background-color:#fff}.iris-picker-inner{position:absolute;top:0;right:0;left:0;bottom:0}.iris-border .iris-picker-inner{top:10px;right:10px;left:10px;bottom:10px}.iris-picker .iris-square-inner{position:absolute;left:0;right:0;top:0;bottom:0}.iris-picker .iris-square,.iris-picker .iris-slider,.iris-picker .iris-square-inner,.iris-picker .iris-palette{border-radius:3px;box-shadow:inset 0 0 5px rgba(0,0,0,.4);height:100%;width:12.5%;float:left;margin-right:5%}.iris-only-strip .iris-slider{width:100%}.iris-picker .iris-square{width:76%;margin-right:10%;position:relative}.iris-only-strip .iris-square{display:none}.iris-picker .iris-square-inner{width:auto;margin:0}.iris-ie-9 .iris-square,.iris-ie-9 .iris-slider,.iris-ie-9 .iris-square-inner,.iris-ie-9 .iris-palette{box-shadow:none;border-radius:0}.iris-ie-9 .iris-square,.iris-ie-9 .iris-slider,.iris-ie-9 .iris-palette{outline:1px solid rgba(0,0,0,.1)}.iris-ie-lt9 .iris-square,.iris-ie-lt9 .iris-slider,.iris-ie-lt9 .iris-square-inner,.iris-ie-lt9 .iris-palette{outline:1px solid #aaa}.iris-ie-lt9 .iris-square .ui-slider-handle{outline:1px solid #aaa;background-color:#fff;-ms-filter:"alpha(Opacity=30)"}.iris-ie-lt9 .iris-square .iris-square-handle{background:0 0;border:3px solid #fff;-ms-filter:"alpha(Opacity=50)"}.iris-picker .iris-strip{margin-right:0;position:relative}.iris-picker .iris-strip .ui-slider-handle{position:absolute;background:0 0;margin:0;right:-3px;left:-3px;border:4px solid #aaa;border-width:4px 3px;width:auto;height:6px;border-radius:4px;box-shadow:0 1px 2px rgba(0,0,0,.2);opacity:.9;z-index:5;cursor:ns-resize}.iris-strip-horiz .iris-strip .ui-slider-handle{right:auto;left:auto;bottom:-3px;top:-3px;height:auto;width:6px;cursor:ew-resize}.iris-strip .ui-slider-handle:before{content:" ";position:absolute;left:-2px;right:-2px;top:-3px;bottom:-3px;border:2px solid #fff;border-radius:3px}.iris-picker .iris-slider-offset{position:absolute;top:11px;left:0;right:0;bottom:-3px;width:auto;height:auto;background:transparent;border:0;border-radius:0}.iris-strip-horiz .iris-slider-offset{top:0;bottom:0;right:11px;left:-3px}.iris-picker .iris-square-handle{background:transparent;border:5px solid #aaa;border-radius:50%;border-color:rgba(128,128,128,.5);box-shadow:none;width:12px;height:12px;position:absolute;left:-10px;top:-10px;cursor:move;opacity:1;z-index:10}.iris-picker .ui-state-focus .iris-square-handle{opacity:.8}.iris-picker .iris-square-handle:hover{border-color:#999}.iris-picker .iris-square-value:focus .iris-square-handle{box-shadow:0 0 2px rgba(0,0,0,.75);opacity:.8}.iris-picker .iris-square-handle:hover::after{border-color:#fff}.iris-picker .iris-square-handle::after{position:absolute;bottom:-4px;right:-4px;left:-4px;top:-4px;border:3px solid #f9f9f9;border-color:rgba(255,255,255,.8);border-radius:50%;content:" "}.iris-picker .iris-square-value{width:8px;height:8px;position:absolute}.iris-ie-lt9 .iris-square-value,.iris-mozilla .iris-square-value{width:1px;height:1px}.iris-palette-container{position:absolute;bottom:0;left:0;margin:0;padding:0}.iris-border .iris-palette-container{left:10px;bottom:10px}.iris-picker .iris-palette{margin:0;cursor:pointer}.iris-square-handle,.ui-slider-handle{border:0;outline:0}',o=navigator.userAgent.toLowerCase(),p="Microsoft Internet Explorer"===navigator.appName,q=p?parseFloat(o.match(/msie ([0-9]{1,}[\.0-9]{0,})/)[1]):0,j=p&&q<10,k=!1,l=["-moz-","-webkit-","-o-","-ms-"],j&&q<=7?(a.fn.iris=a.noop,void(a.support.iris=!1)):(a.support.iris=!0,a.fn.gradient=function(){var b=arguments;return this.each(function(){j?e.apply(this,b):a(this).css("backgroundImage",d.apply(this,b))})},a.fn.rainbowGradient=function(b,c){var d,e,f,g;for(b=b||"top",d=a.extend({},{s:100,l:50},c),e="hsl(%h%,"+d.s+"%,"+d.l+"%)",f=0,g=[];f<=360;)g.push(e.replace("%h%",f)),f+=30;return this.each(function(){a(this).gradient(b,g)})},n={options:{color:!1,mode:"hsl",controls:{horiz:"s",vert:"l",strip:"h"},hide:!0,border:!0,target:!1,width:200,palettes:!1,type:"full",slider:"horizontal"},_color:"",_palettes:["#000","#fff","#d33","#d93","#ee2","#81d742","#1e73be","#8224e3"],_inited:!1,_defaultHSLControls:{horiz:"s",vert:"l",strip:"h"},_defaultHSVControls:{horiz:"h",vert:"v",strip:"s"},_scale:{h:360,s:100,l:100,v:100},_create:function(){var b=this,d=b.element,e=b.options.color||d.val();k===!1&&c(),d.is("input")?(b.options.target?b.picker=a(i).appendTo(b.options.target):b.picker=a(i).insertAfter(d),b._addInputListeners(d)):(d.append(i),b.picker=d.find(".iris-picker")),p?9===q?b.picker.addClass("iris-ie-9"):q<=8&&b.picker.addClass("iris-ie-lt9"):o.indexOf("compatible")<0&&o.indexOf("khtml")<0&&o.match(/mozilla/)&&b.picker.addClass("iris-mozilla"),b.options.palettes&&b._addPalettes(),b.onlySlider="hue"===b.options.type,b.horizontalSlider=b.onlySlider&&"horizontal"===b.options.slider,b.onlySlider&&(b.options.controls.strip="h",e||(e="hsl(10,100,50)")),b._color=new Color(e).setHSpace(b.options.mode),b.options.color=b._color.toString(),b.controls={square:b.picker.find(".iris-square"),squareDrag:b.picker.find(".iris-square-value"),horiz:b.picker.find(".iris-square-horiz"),vert:b.picker.find(".iris-square-vert"),strip:b.picker.find(".iris-strip"),stripSlider:b.picker.find(".iris-strip .iris-slider-offset")},"hsv"===b.options.mode&&b._has("l",b.options.controls)?b.options.controls=b._defaultHSVControls:"hsl"===b.options.mode&&b._has("v",b.options.controls)&&(b.options.controls=b._defaultHSLControls),b.hue=b._color.h(),b.options.hide&&b.picker.hide(),b.options.border&&!b.onlySlider&&b.picker.addClass("iris-border"),b._initControls(),b.active="external",b._dimensions(),b._change()},_has:function(b,c){var d=!1;return a.each(c,function(a,c){if(b===c)return d=!0,!1}),d},_addPalettes:function(){var b=a('<div class="iris-palette-container" />'),c=a('<a class="iris-palette" tabindex="0" />'),d=a.isArray(this.options.palettes)?this.options.palettes:this._palettes;this.picker.find(".iris-palette-container").length&&(b=this.picker.find(".iris-palette-container").detach().html("")),a.each(d,function(a,d){c.clone().data("color",d).css("backgroundColor",d).appendTo(b).height(10).width(10)}),this.picker.append(b)},_paint:function(){var a=this;a.horizontalSlider?a._paintDimension("left","strip"):a._paintDimension("top","strip"),a._paintDimension("top","vert"),a._paintDimension("left","horiz")},_paintDimension:function(a,b){var c,d=this,e=d._color,f=d.options.mode,g=d._getHSpaceColor(),h=d.controls[b],i=d.options.controls;if(b!==d.active&&("square"!==d.active||"strip"===b))switch(i[b]){case"h":if("hsv"===f){switch(g=e.clone(),b){case"horiz":g[i.vert](100);break;case"vert":g[i.horiz](100);break;case"strip":g.setHSpace("hsl")}c=g.toHsl()}else c="strip"===b?{s:g.s,l:g.l}:{s:100,l:g.l};h.rainbowGradient(a,c);break;case"s":"hsv"===f?"vert"===b?c=[e.clone().a(0).s(0).toCSS("rgba"),e.clone().a(1).s(0).toCSS("rgba")]:"strip"===b?c=[e.clone().s(100).toCSS("hsl"),e.clone().s(0).toCSS("hsl")]:"horiz"===b&&(c=["#fff","hsl("+g.h+",100%,50%)"]):c="vert"===b&&"h"===d.options.controls.horiz?["hsla(0, 0%, "+g.l+"%, 0)","hsla(0, 0%, "+g.l+"%, 1)"]:["hsl("+g.h+",0%,50%)","hsl("+g.h+",100%,50%)"],h.gradient(a,c);break;case"l":c="strip"===b?["hsl("+g.h+",100%,100%)","hsl("+g.h+", "+g.s+"%,50%)","hsl("+g.h+",100%,0%)"]:["#fff","rgba(255,255,255,0) 50%","rgba(0,0,0,0) 50%","rgba(0,0,0,1)"],h.gradient(a,c);break;case"v":c="strip"===b?[e.clone().v(100).toCSS(),e.clone().v(0).toCSS()]:["rgba(0,0,0,0)","#000"],h.gradient(a,c)}},_getHSpaceColor:function(){return"hsv"===this.options.mode?this._color.toHsv():this._color.toHsl()},_stripOnlyDimensions:function(){var a=this,b=this.options.width,c=.12*b;a.horizontalSlider?a.picker.css({width:b,height:c}).addClass("iris-only-strip iris-strip-horiz"):a.picker.css({width:c,height:b}).addClass("iris-only-strip iris-strip-vert")},_dimensions:function(b){if("hue"===this.options.type)return this._stripOnlyDimensions();var c,d,e,f,g=this,h=g.options,i=g.controls,j=i.square,k=g.picker.find(".iris-strip"),l="77.5%",m="12%",n=20,o=h.border?h.width-n:h.width,p=a.isArray(h.palettes)?h.palettes.length:g._palettes.length;return b&&(j.css("width",""),k.css("width",""),g.picker.css({width:"",height:""})),l=o*(parseFloat(l)/100),m=o*(parseFloat(m)/100),c=h.border?l+n:l,j.width(l).height(l),k.height(l).width(m),g.picker.css({width:h.width,height:c}),h.palettes?(d=2*l/100,f=l-(p-1)*d,e=f/p,g.picker.find(".iris-palette").each(function(b){var c=0===b?0:d;a(this).css({width:e,height:e,marginLeft:c})}),g.picker.css("paddingBottom",e+d),void k.height(e+d+l)):g.picker.css("paddingBottom","")},_addInputListeners:function(a){var b=this,c=100,d=function(c){var d=new Color(a.val()),e=a.val().replace(/^#/,"");a.removeClass("iris-error"),d.error?""!==e&&a.addClass("iris-error"):d.toString()!==b._color.toString()&&("keyup"===c.type&&e.match(/^[0-9a-fA-F]{3}$/)||b._setOption("color",d.toString()))};a.on("change",d).on("keyup",b._debounce(d,c)),b.options.hide&&a.one("focus",function(){b.show()})},_initControls:function(){var b=this,c=b.controls,d=c.square,e=b.options.controls,f=b._scale[e.strip],g=b.horizontalSlider?"horizontal":"vertical";c.stripSlider.slider({orientation:g,max:f,slide:function(a,c){b.active="strip","h"===e.strip&&"vertical"===g&&(c.value=f-c.value),b._color[e.strip](c.value),b._change.apply(b,arguments)}}),c.squareDrag.draggable({containment:c.square.find(".iris-square-inner"),zIndex:1e3,cursor:"move",drag:function(a,c){b._squareDrag(a,c)},start:function(){d.addClass("iris-dragging"),a(this).addClass("ui-state-focus")},stop:function(){d.removeClass("iris-dragging"),a(this).removeClass("ui-state-focus")}}).on("mousedown mouseup",function(c){var d="ui-state-focus";c.preventDefault(),"mousedown"===c.type?(b.picker.find("."+d).removeClass(d).blur(),a(this).addClass(d).focus()):a(this).removeClass(d)}).on("keydown",function(a){var d=c.square,e=c.squareDrag,f=e.position(),g=b.options.width/100;switch(a.altKey&&(g*=10),a.keyCode){case 37:f.left-=g;break;case 38:f.top-=g;break;case 39:f.left+=g;break;case 40:f.top+=g;break;default:return!0}f.left=Math.max(0,Math.min(f.left,d.width())),f.top=Math.max(0,Math.min(f.top,d.height())),e.css(f),b._squareDrag(a,{position:f}),a.preventDefault()}),d.mousedown(function(c){var d,e;1===c.which&&a(c.target).is("div")&&(d=b.controls.square.offset(),e={top:c.pageY-d.top,left:c.pageX-d.left},c.preventDefault(),b._squareDrag(c,{position:e}),c.target=b.controls.squareDrag.get(0),b.controls.squareDrag.css(e).trigger(c))}),b.options.palettes&&b._paletteListeners()},_paletteListeners:function(){var b=this;b.picker.find(".iris-palette-container").on("click.palette",".iris-palette",function(){b._color.fromCSS(a(this).data("color")),b.active="external",b._change()}).on("keydown.palette",".iris-palette",function(b){return 13!==b.keyCode&&32!==b.keyCode||(b.stopPropagation(),void a(this).click())})},_squareDrag:function(a,b){var c=this,d=c.options.controls,e=c._squareDimensions(),f=Math.round((e.h-b.position.top)/e.h*c._scale[d.vert]),g=c._scale[d.horiz]-Math.round((e.w-b.position.left)/e.w*c._scale[d.horiz]);c._color[d.horiz](g)[d.vert](f),c.active="square",c._change.apply(c,arguments)},_setOption:function(b,c){var d,e,f,g=this,h=g.options[b],i=!1;switch(g.options[b]=c,b){case"color":g.onlySlider?(c=parseInt(c,10),c=isNaN(c)||c<0||c>359?h:"hsl("+c+",100,50)",g.options.color=g.options[b]=c,g._color=new Color(c).setHSpace(g.options.mode),g.active="external",g._change()):(c=""+c,d=c.replace(/^#/,""),e=new Color(c).setHSpace(g.options.mode),e.error?g.options[b]=h:(g._color=e,g.options.color=g.options[b]=g._color.toString(),g.active="external",g._change()));break;case"palettes":i=!0,c?g._addPalettes():g.picker.find(".iris-palette-container").remove(),h||g._paletteListeners();break;case"width":i=!0;break;case"border":i=!0,f=c?"addClass":"removeClass",g.picker[f]("iris-border");break;case"mode":case"controls":if(h===c)return;return f=g.element,h=g.options,h.hide=!g.picker.is(":visible"),g.destroy(),g.picker.remove(),a(g.element).iris(h)}i&&g._dimensions(!0)},_squareDimensions:function(a){var c,d,e=this.controls.square;return a!==b&&e.data("dimensions")?e.data("dimensions"):(d=this.controls.squareDrag,c={w:e.width(),h:e.height()},e.data("dimensions",c),c)},_isNonHueControl:function(a,b){return"square"===a&&"h"===this.options.controls.strip||"external"!==b&&("h"!==b||"strip"!==a)},_change:function(){var b=this,c=b.controls,d=b._getHSpaceColor(),e=["square","strip"],f=b.options.controls,g=f[b.active]||"external",h=b.hue;"strip"===b.active?e=[]:"external"!==b.active&&e.pop(),a.each(e,function(a,e){var g,h,i;if(e!==b.active)switch(e){case"strip":g="h"!==f.strip||b.horizontalSlider?d[f.strip]:b._scale[f.strip]-d[f.strip],c.stripSlider.slider("value",g);break;case"square":h=b._squareDimensions(),i={left:d[f.horiz]/b._scale[f.horiz]*h.w,top:h.h-d[f.vert]/b._scale[f.vert]*h.h},b.controls.squareDrag.css(i)}}),d.h!==h&&b._isNonHueControl(b.active,g)&&b._color.h(h),b.hue=b._color.h(),b.options.color=b._color.toString(),b._inited&&b._trigger("change",{type:b.active},{color:b._color}),b.element.is(":input")&&!b._color.error&&(b.element.removeClass("iris-error"),b.onlySlider?b.element.val()!==b.hue&&b.element.val(b.hue):b.element.val()!==b._color.toString()&&b.element.val(b._color.toString())),b._paint(),b._inited=!0,b.active=!1},_debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},show:function(){this.picker.show()},hide:function(){this.picker.hide()},toggle:function(){this.picker.toggle()},color:function(a){return a===!0?this._color.clone():a===b?this._color.toString():void this.option("color",a)}},a.widget("a8c.iris",n),void a('<style id="iris-css">'+m+"</style>").appendTo("head"))}(jQuery),function(a,b){var c=function(a,b){return this instanceof c?this._init(a,b):new c(a,b)};c.fn=c.prototype={_color:0,_alpha:1,error:!1,_hsl:{h:0,s:0,l:0},_hsv:{h:0,s:0,v:0},_hSpace:"hsl",_init:function(a){var c="noop";switch(typeof a){case"object":return a.a!==b&&this.a(a.a),c=a.r!==b?"fromRgb":a.l!==b?"fromHsl":a.v!==b?"fromHsv":c,this[c](a);case"string":return this.fromCSS(a);case"number":return this.fromInt(parseInt(a,10))}return this},_error:function(){return this.error=!0,this},clone:function(){for(var a=new c(this.toInt()),b=["_alpha","_hSpace","_hsl","_hsv","error"],d=b.length-1;d>=0;d--)a[b[d]]=this[b[d]];return a},setHSpace:function(a){return this._hSpace="hsv"===a?a:"hsl",this},noop:function(){return this},fromCSS:function(a){var b,c=/^(rgb|hs(l|v))a?\(/;if(this.error=!1,a=a.replace(/^\s+/,"").replace(/\s+$/,"").replace(/;$/,""),a.match(c)&&a.match(/\)$/)){if(b=a.replace(/(\s|%)/g,"").replace(c,"").replace(/,?\);?$/,"").split(","),b.length<3)return this._error();if(4===b.length&&(this.a(parseFloat(b.pop())),this.error))return this;for(var d=b.length-1;d>=0;d--)if(b[d]=parseInt(b[d],10),isNaN(b[d]))return this._error();return a.match(/^rgb/)?this.fromRgb({r:b[0],g:b[1],b:b[2]}):a.match(/^hsv/)?this.fromHsv({h:b[0],s:b[1],v:b[2]}):this.fromHsl({h:b[0],s:b[1],l:b[2]})}return this.fromHex(a)},fromRgb:function(a,c){return"object"!=typeof a||a.r===b||a.g===b||a.b===b?this._error():(this.error=!1,this.fromInt(parseInt((a.r<<16)+(a.g<<8)+a.b,10),c))},fromHex:function(a){return a=a.replace(/^#/,"").replace(/^0x/,""),3===a.length&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]),this.error=!/^[0-9A-F]{6}$/i.test(a),this.fromInt(parseInt(a,16))},fromHsl:function(a){var c,d,e,f,g,h,i,j;return"object"!=typeof a||a.h===b||a.s===b||a.l===b?this._error():(this._hsl=a,this._hSpace="hsl",h=a.h/360,i=a.s/100,j=a.l/100,0===i?c=d=e=j:(f=j<.5?j*(1+i):j+i-j*i,g=2*j-f,c=this.hue2rgb(g,f,h+1/3),d=this.hue2rgb(g,f,h),e=this.hue2rgb(g,f,h-1/3)),this.fromRgb({r:255*c,g:255*d,b:255*e},!0))},fromHsv:function(a){var c,d,e,f,g,h,i,j,k,l,m;if("object"!=typeof a||a.h===b||a.s===b||a.v===b)return this._error();switch(this._hsv=a,this._hSpace="hsv",c=a.h/360,d=a.s/100,e=a.v/100,i=Math.floor(6*c),j=6*c-i,k=e*(1-d),l=e*(1-j*d),m=e*(1-(1-j)*d),i%6){case 0:f=e,g=m,h=k;break;case 1:f=l,g=e,h=k;break;case 2:f=k,g=e,h=m;break;case 3:f=k,g=l,h=e;break;case 4:f=m,g=k,h=e;break;case 5:f=e,g=k,h=l}return this.fromRgb({r:255*f,g:255*g,b:255*h},!0)},fromInt:function(a,c){return this._color=parseInt(a,10),isNaN(this._color)&&(this._color=0),this._color>16777215?this._color=16777215:this._color<0&&(this._color=0),c===b&&(this._hsv.h=this._hsv.s=this._hsl.h=this._hsl.s=0),this},hue2rgb:function(a,b,c){return c<0&&(c+=1),c>1&&(c-=1),c<1/6?a+6*(b-a)*c:c<.5?b:c<2/3?a+(b-a)*(2/3-c)*6:a},toString:function(){var a=parseInt(this._color,10).toString(16);if(this.error)return"";if(a.length<6)for(var b=6-a.length-1;b>=0;b--)a="0"+a;return"#"+a},toCSS:function(a,b){switch(a=a||"hex",b=parseFloat(b||this._alpha),a){case"rgb":case"rgba":var c=this.toRgb();return b<1?"rgba( "+c.r+", "+c.g+", "+c.b+", "+b+" )":"rgb( "+c.r+", "+c.g+", "+c.b+" )";case"hsl":case"hsla":var d=this.toHsl();return b<1?"hsla( "+d.h+", "+d.s+"%, "+d.l+"%, "+b+" )":"hsl( "+d.h+", "+d.s+"%, "+d.l+"% )";default:return this.toString()}},toRgb:function(){return{r:255&this._color>>16,g:255&this._color>>8,b:255&this._color}},toHsl:function(){var a,b,c=this.toRgb(),d=c.r/255,e=c.g/255,f=c.b/255,g=Math.max(d,e,f),h=Math.min(d,e,f),i=(g+h)/2;if(g===h)a=b=0;else{var j=g-h;switch(b=i>.5?j/(2-g-h):j/(g+h),g){case d:a=(e-f)/j+(e<f?6:0);break;case e:a=(f-d)/j+2;break;case f:a=(d-e)/j+4}a/=6}return a=Math.round(360*a),0===a&&this._hsl.h!==a&&(a=this._hsl.h),b=Math.round(100*b),0===b&&this._hsl.s&&(b=this._hsl.s),{h:a,s:b,l:Math.round(100*i)}},toHsv:function(){var a,b,c=this.toRgb(),d=c.r/255,e=c.g/255,f=c.b/255,g=Math.max(d,e,f),h=Math.min(d,e,f),i=g,j=g-h;if(b=0===g?0:j/g,g===h)a=b=0;else{switch(g){case d:a=(e-f)/j+(e<f?6:0);break;case e:a=(f-d)/j+2;break;case f:a=(d-e)/j+4}a/=6}return a=Math.round(360*a),0===a&&this._hsv.h!==a&&(a=this._hsv.h),b=Math.round(100*b),0===b&&this._hsv.s&&(b=this._hsv.s),{h:a,s:b,v:Math.round(100*i)}},toInt:function(){return this._color},toIEOctoHex:function(){var a=this.toString(),b=parseInt(255*this._alpha,10).toString(16);return 1===b.length&&(b="0"+b),"#"+b+a.replace(/^#/,"")},toLuminosity:function(){var a=this.toRgb(),b={};for(var c in a)if(a.hasOwnProperty(c)){var d=a[c]/255;b[c]=d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)}return.2126*b.r+.7152*b.g+.0722*b.b},getDistanceLuminosityFrom:function(a){if(!(a instanceof c))throw"getDistanceLuminosityFrom requires a Color object";var b=this.toLuminosity(),d=a.toLuminosity();return b>d?(b+.05)/(d+.05):(d+.05)/(b+.05)},getMaxContrastColor:function(){var a=this.getDistanceLuminosityFrom(new c("#000")),b=this.getDistanceLuminosityFrom(new c("#fff")),d=a>=b?"#000":"#fff";return new c(d)},getReadableContrastingColor:function(a,d){if(!(a instanceof c))return this;var e,f,g,h=d===b?5:d,i=a.getDistanceLuminosityFrom(this);if(i>=h)return this;if(e=a.getMaxContrastColor(),f=e.getDistanceLuminosityFrom(a),f<=h)return e;for(g=0===e.toInt()?-1:1;i<h&&(this.l(g,!0),i=this.getDistanceLuminosityFrom(a),0!==this._color&&16777215!==this._color););return this},a:function(a){if(a===b)return this._alpha;var c=parseFloat(a);return isNaN(c)?this._error():(this._alpha=c,this)},darken:function(a){return a=a||5,this.l(-a,!0)},lighten:function(a){return a=a||5,this.l(a,!0)},saturate:function(a){return a=a||15,this.s(a,!0)},desaturate:function(a){return a=a||15,this.s(-a,!0)},toGrayscale:function(){return this.setHSpace("hsl").s(0)},getComplement:function(){return this.h(180,!0)},getSplitComplement:function(a){a=a||1;var b=180+30*a;return this.h(b,!0)},getAnalog:function(a){a=a||1;var b=30*a;return this.h(b,!0)},getTetrad:function(a){a=a||1;var b=60*a;return this.h(b,!0)},getTriad:function(a){a=a||1;var b=120*a;return this.h(b,!0)},_partial:function(a){var c=d[a];return function(d,e){var f=this._spaceFunc("to",c.space);return d===b?f[a]:(e===!0&&(d=f[a]+d),c.mod&&(d%=c.mod),c.range&&(d=d<c.range[0]?c.range[0]:d>c.range[1]?c.range[1]:d),f[a]=d,this._spaceFunc("from",c.space,f))}},_spaceFunc:function(a,b,c){var d=b||this._hSpace,e=a+d.charAt(0).toUpperCase()+d.substr(1);return this[e](c)}};var d={h:{mod:360},s:{range:[0,100]},l:{space:"hsl",range:[0,100]},v:{space:"hsv",range:[0,100]},r:{space:"rgb",range:[0,255]},g:{space:"rgb",range:[0,255]},b:{space:"rgb",range:[0,255]}};for(var e in d)d.hasOwnProperty(e)&&(c.fn[e]=c.fn._partial(e));"object"==typeof exports?module.exports=c:a.Color=c}(this); custom-header.js 0000666 00000002736 15213733063 0007661 0 ustar 00 /* global isRtl */ (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)); inline-edit-post.min.js 0000666 00000015770 15213733063 0011071 0 ustar 00 var inlineEditPost;window.wp=window.wp||{},function(u,n){inlineEditPost={init:function(){var i=this,t=u("#inline-edit"),e=u("#bulk-edit");i.type=u("table.widefat").hasClass("pages")?"page":"post",i.what="#post-",t.keyup(function(t){if(27===t.which)return inlineEditPost.revert()}),e.keyup(function(t){if(27===t.which)return inlineEditPost.revert()}),u(".cancel",t).click(function(){return inlineEditPost.revert()}),u(".save",t).click(function(){return inlineEditPost.save(this)}),u("td",t).keydown(function(t){if(13===t.which&&!u(t.target).hasClass("cancel"))return inlineEditPost.save(this)}),u(".cancel",e).click(function(){return inlineEditPost.revert()}),u('#inline-edit .inline-edit-private input[value="private"]').click(function(){var t=u("input.inline-edit-password-input");u(this).prop("checked")?t.val("").prop("disabled",!0):t.prop("disabled",!1)}),u("#the-list").on("click","a.editinline",function(t){t.preventDefault(),inlineEditPost.edit(this)}),u("#bulk-edit").find("fieldset:first").after(u("#inline-edit fieldset.inline-edit-categories").clone()).siblings("fieldset:last").prepend(u("#inline-edit label.inline-edit-tags").clone()),u('select[name="_status"] option[value="future"]',e).remove(),u("#doaction, #doaction2").click(function(t){var e;i.whichBulkButtonId=u(this).attr("id"),e=i.whichBulkButtonId.substr(2),"edit"===u('select[name="'+e+'"]').val()?(t.preventDefault(),i.setBulk()):0<u("form#posts-filter tr.inline-editor").length&&i.revert()})},toggle:function(t){var e=this;"none"===u(e.what+e.getId(t)).css("display")?e.revert():e.edit(t)},setBulk:function(){var i="",t=this.type,n=!0;if(this.revert(),u("#bulk-edit td").attr("colspan",u("th:visible, td:visible",".widefat:first thead").length),u("table.widefat tbody").prepend(u("#bulk-edit")).prepend('<tr class="hidden"></tr>'),u("#bulk-edit").addClass("inline-editor").show(),u('tbody th.check-column input[type="checkbox"]').each(function(){var t,e;u(this).prop("checked")&&(n=!1,t=u(this).val(),e=u("#inline_"+t+" .post_title").html()||inlineEditL10n.notitle,i+='<div id="ttle'+t+'"><a id="_'+t+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+e+"</div>")}),n)return this.revert();u("#bulk-titles").html(i),u("#bulk-titles a").click(function(){var t=u(this).attr("id").substr(1);u('table.widefat input[value="'+t+'"]').prop("checked",!1),u("#ttle"+t).remove()}),"post"===t&&u("tr.inline-editor textarea[data-wp-taxonomy]").each(function(t,e){u(e).autocomplete("instance")||u(e).wpTagsSuggest()}),u("html, body").animate({scrollTop:0},"fast")},edit:function(n){var t,a,e,i,s,l,o,r,d,c=this,p=!0;for(c.revert(),"object"==typeof n&&(n=c.getId(n)),t=["post_title","post_name","post_author","_status","jj","mm","aa","hh","mn","ss","post_password","post_format","menu_order","page_template"],"page"===c.type&&t.push("post_parent"),a=u("#inline-edit").clone(!0),u("td",a).attr("colspan",u("th:visible, td:visible",".widefat:first thead").length),u(c.what+n).removeClass("is-expanded").hide().after(a).after('<tr class="hidden"></tr>'),e=u("#inline_"+n),u(':input[name="post_author"] option[value="'+u(".post_author",e).text()+'"]',a).val()||u(':input[name="post_author"]',a).prepend('<option value="'+u(".post_author",e).text()+'">'+u("#"+c.type+"-"+n+" .author").text()+"</option>"),1===u(':input[name="post_author"] option',a).length&&u("label.inline-edit-author",a).hide(),r=0;r<t.length;r++)(d=u("."+t[r],e)).find("img").replaceWith(function(){return this.alt}),d=d.text(),u(':input[name="'+t[r]+'"]',a).val(d);if("open"===u(".comment_status",e).text()&&u('input[name="comment_status"]',a).prop("checked",!0),"open"===u(".ping_status",e).text()&&u('input[name="ping_status"]',a).prop("checked",!0),"sticky"===u(".sticky",e).text()&&u('input[name="sticky"]',a).prop("checked",!0),u(".post_category",e).each(function(){var t,e=u(this).text();e&&(t=u(this).attr("id").replace("_"+n,""),u("ul."+t+"-checklist :checkbox",a).val(e.split(",")))}),u(".tags_input",e).each(function(){var t=u(this),e=u(this).attr("id").replace("_"+n,""),i=u("textarea.tax_input_"+e,a),e=inlineEditL10n.comma;t.find("img").replaceWith(function(){return this.alt}),(t=t.text())&&(","!==e&&(t=t.replace(/,/g,e)),i.val(t)),i.wpTagsSuggest()}),"future"!==(i=u("._status",e).text())&&u('select[name="_status"] option[value="future"]',a).remove(),c=u(".inline-edit-password-input").prop("disabled",!1),"private"===i&&(u('input[name="keep_private"]',a).prop("checked",!0),c.val("").prop("disabled",!0)),0<(s=u('select[name="post_parent"] option[value="'+n+'"]',a)).length){for(l=s[0].className.split("-")[1],o=s;p&&0!==(o=o.next("option")).length;)o[0].className.split("-")[1]<=l?p=!1:(o.remove(),o=s);s.remove()}return u(a).attr("id","edit-"+n).addClass("inline-editor").show(),u(".ptitle",a).focus(),!1},save:function(i){var t=u(".post_status_page").val()||"";return"object"==typeof i&&(i=this.getId(i)),u("table.widefat .spinner").addClass("is-active"),t={action:"inline-save",post_type:typenow,post_ID:i,edit_date:"true",post_status:t},t=u("#edit-"+i).find(":input").serialize()+"&"+u.param(t),u.post(ajaxurl,t,function(t){var e=u("#edit-"+i+" .inline-edit-save .error");u("table.widefat .spinner").removeClass("is-active"),u(".ac_results").hide(),t?-1!==t.indexOf("<tr")?(u(inlineEditPost.what+i).siblings("tr.hidden").addBack().remove(),u("#edit-"+i).before(t).remove(),u(inlineEditPost.what+i).hide().fadeIn(400,function(){u(this).find(".editinline").focus(),n.a11y.speak(inlineEditL10n.saved)})):(t=t.replace(/<.[^<>]*?>/g,""),e.html(t).show(),n.a11y.speak(e.text())):(e.html(inlineEditL10n.error).show(),n.a11y.speak(inlineEditL10n.error))},"html"),!1},revert:function(){var t=u(".widefat"),e=u(".inline-editor",t).attr("id");return e&&(u(".spinner",t).removeClass("is-active"),u(".ac_results").hide(),"bulk-edit"===e?(u("#bulk-edit",t).removeClass("inline-editor").hide().siblings(".hidden").remove(),u("#bulk-titles").empty(),u("#inlineedit").append(u("#bulk-edit")),u("#"+inlineEditPost.whichBulkButtonId).focus()):(u("#"+e).siblings("tr.hidden").addBack().remove(),e=e.substr(e.lastIndexOf("-")+1),u(this.what+e).show().find(".editinline").focus())),!1},getId:function(t){t=u(t).closest("tr").attr("id").split("-");return t[t.length-1]}},u(document).ready(function(){inlineEditPost.init()}),u(document).on("heartbeat-tick.wp-check-locked-posts",function(t,e){var n=e["wp-check-locked-posts"]||{};u("#the-list tr").each(function(t,e){var i=e.id,e=u(e);n.hasOwnProperty(i)?e.hasClass("wp-locked")||(i=n[i],e.find(".column-title .locked-text").text(i.text),e.find(".check-column checkbox").prop("checked",!1),i.avatar_src&&(i=u('<img class="avatar avatar-18 photo" width="18" height="18" alt="" />').attr("src",i.avatar_src.replace(/&/g,"&")),e.find(".column-title .locked-avatar").empty().append(i)),e.addClass("wp-locked")):e.hasClass("wp-locked")&&e.removeClass("wp-locked").delay(1e3).find(".locked-info span").empty()})}).on("heartbeat-send.wp-check-locked-posts",function(t,e){var i=[];u("#the-list tr").each(function(t,e){e.id&&i.push(e.id)}),i.length&&(e["wp-check-locked-posts"]=i)}).ready(function(){void 0!==n&&n.heartbeat&&n.heartbeat.interval(15)})}(jQuery,window.wp); media-gallery.js 0000666 00000002362 15213733063 0007630 0 ustar 00 /* global ajaxurl */ /** * This file is used on media-upload.php which has been replaced by media-new.php and upload.php * Deprecated since 3.5.0 */ jQuery(function($) { /** * Adds a click event handler to the element with a 'wp-gallery' class. */ $( 'body' ).bind( 'click.wp-gallery', function(e) { var target = $( e.target ), id, img_size, nonceValue; if ( target.hasClass( 'wp-set-header' ) ) { // Opens the image to preview it full size. ( window.dialogArguments || opener || parent || top ).location.href = target.data( 'location' ); e.preventDefault(); } else if ( target.hasClass( 'wp-set-background' ) ) { // Sets the image as background of the theme. id = target.data( 'attachment-id' ); img_size = $( 'input[name="attachments[' + id + '][image-size]"]:checked').val(); nonceValue = $( '#_wpnonce' ).val() && ''; /** * This AJAX action has been deprecated since 3.5.0, see custom-background.php */ jQuery.post(ajaxurl, { action: 'set-background-image', attachment_id: id, _ajax_nonce: nonceValue, size: img_size }, function() { var win = window.dialogArguments || opener || parent || top; win.tb_remove(); win.location.reload(); }); e.preventDefault(); } }); }); password-strength-meter.min.js 0000666 00000001351 15213733063 0012503 0 ustar 00 var passwordStrength;window.wp=window.wp||{},function(s){wp.passwordStrength={meter:function(n,t,e){return s.isArray(t)||(t=[t.toString()]),n!=e&&e&&0<e.length?5:void 0===window.zxcvbn?-1:zxcvbn(n,t).score},userInputBlacklist:function(){var n,t,e,r,i=[],a=[],o=["user_login","first_name","last_name","nickname","display_name","email","url","description","weblog_title","admin_email"];for(i.push(document.title),i.push(document.URL),t=o.length,n=0;n<t;n++)0!==(r=s("#"+o[n])).length&&(i.push(r[0].defaultValue),i.push(r.val()));for(e=i.length,n=0;n<e;n++)i[n]&&(a=a.concat(i[n].replace(/\W/g," ").split(" ")));return a=s.grep(a,function(n,t){return!(""===n||n.length<4)&&s.inArray(n,a)===t})}},passwordStrength=wp.passwordStrength.meter}(jQuery); edit-comments.min.js 0000666 00000034244 15213733063 0010452 0 ustar 00 var setCommentsList,theList,theExtraList,commentReply;!function(_){var o,s,i=document.title,w=_("#dashboard_right_now").length,r=function(t){t=parseInt(t.html().replace(/[^0-9]+/g,""),10);return isNaN(t)?0:t},l=function(t,e){var n="";if(!isNaN(e)){if(3<(e=e<1?"0":e.toString()).length){for(;3<e.length;)n=thousandsSeparator+e.substr(e.length-3)+n,e=e.substr(0,e.length-3);e+=n}t.html(e)}},x=function(n,t){var e=".post-com-count-"+t,a="comment-count-no-comments",o="comment-count-approved";b("span.approved-count",n),t&&(t=_("span."+o,e),e=_("span."+a,e),t.each(function(){var t=_(this),e=r(t)+n;0===(e=e<1?0:e)?t.removeClass(o).addClass(a):t.addClass(o).removeClass(a),l(t,e)}),e.each(function(){var t=_(this);0<n?t.removeClass(a).addClass(o):t.addClass(a).removeClass(o),l(t,n)}))},b=function(t,n){_(t).each(function(){var t=_(this),e=r(t)+n;l(t,e=e<1?0:e)})},k=function(t){var e;w&&t&&t.i18n_comments_text&&(e=_("#dashboard_right_now"),_(".comment-count a",e).text(t.i18n_comments_text),_(".comment-mod-count a",e).text(t.i18n_moderation_text).parent()[0<t.in_moderation?"removeClass":"addClass"]("hidden"))},m=function(t){var e,n,a;s=s||new RegExp(adminCommentsL10n.docTitleCommentsCount.replace("%s","\\([0-9"+thousandsSeparator+"]+\\)")+"?"),o=o||_("<div />"),e=i,1<=(t=(a=s.exec(document.title))?(a=a[0],o.html(a),r(o)+t):(o.html(0),t))?(l(o,t),(n=s.exec(document.title))&&(e=document.title.replace(n[0],adminCommentsL10n.docTitleCommentsCount.replace("%s",o.text())+" "))):(n=s.exec(e))&&(e=e.replace(n[0],adminCommentsL10n.docTitleComments)),document.title=e},L=function(n,t){var e=".post-com-count-"+t,a="comment-count-no-pending",o="post-com-count-no-pending",s="comment-count-pending";w||m(n),_("span.pending-count").each(function(){var t=_(this),e=r(t)+n;e<1&&(e=0),t.closest(".awaiting-mod")[0===e?"addClass":"removeClass"]("count-0"),l(t,e)}),t&&(t=_("span."+s,e),e=_("span."+a,e),t.each(function(){var t=_(this),e=r(t)+n;0===(e=e<1?0:e)?(t.parent().addClass(o),t.removeClass(s).addClass(a)):(t.parent().removeClass(o),t.addClass(s).removeClass(a)),l(t,e)}),e.each(function(){var t=_(this);0<n?(t.parent().removeClass(o),t.removeClass(a).addClass(s)):(t.parent().addClass(o),t.addClass(a).removeClass(s)),l(t,n)}))};setCommentsList=function(){var i,f=0,g=_('input[name="_total"]',"#comments-form"),l=_('input[name="_per_page"]',"#comments-form"),m=_('input[name="_page"]',"#comments-form"),y=function(t,e,n){e<f||(n&&(f=e),g.val(t.toString()))},t=function(t,e){var n,a,o,s=_("#"+e.element);!0!==e.parsed&&(o=e.parsed.responses[0]),a=_("#replyrow"),n=_("#comment_ID",a).val(),a=_("#replybtn",a),s.is(".unapproved")?(e.data.id==n&&a.text(adminCommentsL10n.replyApprove),s.find(".row-actions span.view").addClass("hidden").end().find("div.comment_status").html("0")):(e.data.id==n&&a.text(adminCommentsL10n.reply),s.find(".row-actions span.view").removeClass("hidden").end().find("div.comment_status").html("1")),i=_("#"+e.element).is("."+e.dimClass)?1:-1,o?(k(o.supplemental),L(i,o.supplemental.postId),x(-1*i,o.supplemental.postId)):(L(i),x(-1*i))},e=function(t,e){var n,a,o,s,i=!1,r=_(t.target).attr("data-wp-lists");return t.data._total=g.val()||0,t.data._per_page=l.val()||0,t.data._page=m.val()||0,t.data._url=document.location.href,t.data.comment_status=_('input[name="comment_status"]',"#comments-form").val(),-1!=r.indexOf(":trash=1")?i="trash":-1!=r.indexOf(":spam=1")&&(i="spam"),i&&(n=r.replace(/.*?comment-([0-9]+).*/,"$1"),a=_("#comment-"+n),o=_("#"+i+"-undo-holder").html(),a.find(".check-column :checkbox").prop("checked",!1),a.siblings("#replyrow").length&&commentReply.cid==n&&commentReply.close(),o=a.is("tr")?(r=a.children(":visible").length,s=_(".author strong",a).text(),_('<tr id="undo-'+n+'" class="undo un'+i+'" style="display:none;"><td colspan="'+r+'">'+o+"</td></tr>")):(s=_(".comment-author",a).text(),_('<div id="undo-'+n+'" style="display:none;" class="undo un'+i+'">'+o+"</div>")),a.before(o),_("strong","#undo-"+n).text(s),(s=_(".undo a","#undo-"+n)).attr("href","comment.php?action=un"+i+"comment&c="+n+"&_wpnonce="+t.data._ajax_nonce),s.attr("data-wp-lists","delete:the-comment-list:comment-"+n+"::un"+i+"=1"),s.attr("class","vim-z vim-destructive"),_(".avatar",a).first().clone().prependTo("#undo-"+n+" ."+i+"-undo-inside"),s.click(function(t){t.preventDefault(),t.stopPropagation(),e.wpList.del(this),_("#undo-"+n).css({backgroundColor:"#ceb"}).fadeOut(350,function(){_(this).remove(),_("#comment-"+n).css("backgroundColor","").fadeIn(300,function(){_(this).show()})})})),t},n=function(t,e){var n,a,o,s,i=!0===e.parsed?{}:e.parsed.responses[0],r=!0===e.parsed?"":i.supplemental.status,l=!0===e.parsed?"":i.supplemental.postId,m=!0===e.parsed?"":i.supplemental,p=_(e.target).parent(),c=_("#"+e.element),d=c.hasClass("approved"),u=c.hasClass("unapproved"),h=c.hasClass("spam"),v=c.hasClass("trash"),c=!1;k(m),p.is("span.undo")?(p.hasClass("unspam")?(n=-1,"trash"===r?a=1:"1"===r?s=1:"0"===r&&(o=1)):p.hasClass("untrash")&&(a=-1,"spam"===r?n=1:"1"===r?s=1:"0"===r&&(o=1)),c=!0):p.is("span.spam")?(d?s=-1:u?o=-1:v&&(a=-1),n=1):p.is("span.unspam")?(d?o=1:u?s=1:(v||h)&&(p.hasClass("approve")?s=1:p.hasClass("unapprove")&&(o=1)),n=-1):p.is("span.trash")?(d?s=-1:u?o=-1:h&&(n=-1),a=1):p.is("span.untrash")?(d?o=1:u?s=1:v&&(p.hasClass("approve")?s=1:p.hasClass("unapprove")&&(o=1)),a=-1):p.is("span.approve:not(.unspam):not(.untrash)")?o=-(s=1):p.is("span.unapprove:not(.unspam):not(.untrash)")?(s=-1,o=1):p.is("span.delete")&&(h?n=-1:v&&(a=-1)),o&&(L(o,l),b("span.all-count",o)),s&&(x(s,l),b("span.all-count",s)),n&&b("span.spam-count",n),a&&b("span.trash-count",a),w||(a=g.val()?parseInt(g.val(),10):0,_(e.target).parent().is("span.undo")?a++:a--,a<0&&(a=0),"object"==typeof t?i.supplemental.total_items_i18n&&f<i.supplemental.time?((e=i.supplemental.total_items_i18n||"")&&(_(".displaying-num").text(e),_(".total-pages").text(i.supplemental.total_pages_i18n),_(".tablenav-pages").find(".next-page, .last-page").toggleClass("disabled",i.supplemental.total_pages==_(".current-page").val())),y(a,i.supplemental.time,!0)):i.supplemental.time&&y(a,i.supplemental.time,!1):y(a,t,!1)),theExtraList&&0!==theExtraList.length&&0!==theExtraList.children().length&&!c&&(theList.get(0).wpList.add(theExtraList.children(":eq(0):not(.no-items)").remove().clone()),C(),t=function(){_("#the-comment-list tr:visible").length||theList.get(0).wpList.add(theExtraList.find(".no-items").clone())},(c=_(":animated","#the-comment-list")).length?c.promise().done(t):t())},C=function(t){var e=_.query.get(),n=_(".total-pages").text(),a=_('input[name="_per_page"]',"#comments-form").val();e.paged||(e.paged=1),e.paged>n||(t?(theExtraList.empty(),e.number=Math.min(8,a)):(e.number=1,e.offset=Math.min(8,a)-1),e.no_placeholder=!0,e.paged++,!0===e.comment_type&&(e.comment_type=""),e=_.extend(e,{action:"fetch-list",list_args:list_args,_ajax_fetch_list_nonce:_("#_ajax_fetch_list_nonce").val()}),_.ajax({url:ajaxurl,global:!1,dataType:"json",data:e,success:function(t){theExtraList.get(0).wpList.add(t.rows)}}))};theExtraList=_("#the-extra-comment-list").wpList({alt:"",delColor:"none",addColor:"none"}),theList=_("#the-comment-list").wpList({alt:"",delBefore:e,dimAfter:t,delAfter:n,addColor:"none"}).bind("wpListDelEnd",function(t,e){var n=_(e.target).attr("data-wp-lists"),e=e.element.replace(/[^0-9]+/g,"");-1==n.indexOf(":trash=1")&&-1==n.indexOf(":spam=1")||_("#undo-"+e).fadeIn(300,function(){_(this).show()})})},commentReply={cid:"",act:"",originalContent:"",init:function(){var t=_("#replyrow");_("a.cancel",t).click(function(){return commentReply.revert()}),_("a.save",t).click(function(){return commentReply.send()}),_("input#author-name, input#author-email, input#author-url",t).keypress(function(t){if(13==t.which)return commentReply.send(),t.preventDefault(),!1}),_("#the-comment-list .column-comment > p").dblclick(function(){commentReply.toggle(_(this).parent())}),_("#doaction, #doaction2, #post-query-submit").click(function(){0<_("#the-comment-list #replyrow").length&&commentReply.close()}),this.comments_listing=_('#comments-form > input[name="comment_status"]').val()||""},addEvents:function(t){t.each(function(){_(this).find(".column-comment > p").dblclick(function(){commentReply.toggle(_(this).parent())})})},toggle:function(t){"none"!==_(t).css("display")&&(_("#replyrow").parent().is("#com-reply")||window.confirm(adminCommentsL10n.warnQuickEdit))&&_(t).find("a.vim-q").click()},revert:function(){return _("#the-comment-list #replyrow").length<1||_("#replyrow").fadeOut("fast",function(){commentReply.close()}),!1},close:function(){var t,e=_("#replyrow");e.parent().is("#com-reply")||(this.cid&&"edit-comment"==this.act&&(t=_("#comment-"+this.cid)).fadeIn(300,function(){t.show()}).css("backgroundColor",""),"undefined"!=typeof QTags&&QTags.closeAllTags("replycontent"),_("#add-new-comment").css("display",""),e.hide(),_("#com-reply").append(e),_("#replycontent").css("height","").val(""),_("#edithead input").val(""),_(".error",e).empty().hide(),_(".spinner",e).removeClass("is-active"),this.cid="",this.originalContent="")},open:function(t,e,n){var a,o,s,i,r=_("#comment-"+t),l=r.height();return this.discardCommentChanges()&&(this.close(),this.cid=t,a=_("#replyrow"),o=_("#inline-"+t),s="edit"==(n=n||"replyto")?"edit":"replyto",s=this.act=s+"-comment",this.originalContent=_("textarea.comment",o).val(),i=_("> th:visible, > td:visible",r).length,a.hasClass("inline-edit-row")&&0!==i&&_("td",a).attr("colspan",i),_("#action",a).val(s),_("#comment_post_ID",a).val(e),_("#comment_ID",a).val(t),"edit"==n?(_("#author-name",a).val(_("div.author",o).text()),_("#author-email",a).val(_("div.author-email",o).text()),_("#author-url",a).val(_("div.author-url",o).text()),_("#status",a).val(_("div.comment_status",o).text()),_("#replycontent",a).val(_("textarea.comment",o).val()),_("#edithead, #editlegend, #savebtn",a).show(),_("#replyhead, #replybtn, #addhead, #addbtn",a).hide(),120<l&&(l=500<l?500:l,_("#replycontent",a).css("height",l+"px")),r.after(a).fadeOut("fast",function(){_("#replyrow").fadeIn(300,function(){_(this).show()})})):"add"==n?(_("#addhead, #addbtn",a).show(),_("#replyhead, #replybtn, #edithead, #editlegend, #savebtn",a).hide(),_("#the-comment-list").prepend(a),_("#replyrow").fadeIn(300)):(n=_("#replybtn",a),_("#edithead, #editlegend, #savebtn, #addhead, #addbtn",a).hide(),_("#replyhead, #replybtn",a).show(),r.after(a),r.hasClass("unapproved")?n.text(adminCommentsL10n.replyApprove):n.text(adminCommentsL10n.reply),_("#replyrow").fadeIn(300,function(){_(this).show()})),setTimeout(function(){var t=_("#replyrow").offset().top,e=t+_("#replyrow").height(),n=window.pageYOffset||document.documentElement.scrollTop,a=document.documentElement.clientHeight||window.innerHeight||0;n+a-20<e?window.scroll(0,e-a+35):t-20<n&&window.scroll(0,t-35),_("#replycontent").focus().keyup(function(t){27==t.which&&commentReply.revert()})},600)),!1},send:function(){var e={};return _("#replysubmit .error").hide(),_("#replysubmit .spinner").addClass("is-active"),_("#replyrow input").not(":button").each(function(){var t=_(this);e[t.attr("name")]=t.val()}),e.content=_("#replycontent").val(),e.id=e.comment_post_ID,e.comments_listing=this.comments_listing,e.p=_('[name="p"]').val(),_("#comment-"+_("#comment_ID").val()).hasClass("unapproved")&&(e.approve_parent=1),_.ajax({type:"POST",url:ajaxurl,data:e,success:function(t){commentReply.show(t)},error:function(t){commentReply.error(t)}}),!1},show:function(t){var e,n,a,o=this;return"string"==typeof t?(o.error({responseText:t}),!1):(e=wpAjax.parseAjaxResponse(t)).errors?(o.error({responseText:wpAjax.broken}),!1):(o.revert(),t="#comment-"+(e=e.responses[0]).id,"edit-comment"==o.act&&_(t).remove(),void(e.supplemental.parent_approved&&(a=_("#comment-"+e.supplemental.parent_approved),L(-1,e.supplemental.parent_post_id),"moderated"==this.comments_listing)?a.animate({backgroundColor:"#CCEEBB"},400,function(){a.fadeOut()}):(e.supplemental.i18n_comments_text&&(w?k(e.supplemental):(x(1,e.supplemental.parent_post_id),b("span.all-count",1))),e=_.trim(e.data),_(e).hide(),_("#replyrow").after(e),t=_(t),o.addEvents(t),n=t.hasClass("unapproved")?"#FFFFE0":t.closest(".widefat, .postbox").css("backgroundColor"),t.animate({backgroundColor:"#CCEEBB"},300).animate({backgroundColor:n},300,function(){a&&a.length&&a.animate({backgroundColor:"#CCEEBB"},300).animate({backgroundColor:n},300).removeClass("unapproved").addClass("approved").find("div.comment_status").html("1")}))))},error:function(t){var e=t.statusText;_("#replysubmit .spinner").removeClass("is-active"),(e=t.responseText?t.responseText.replace(/<.[^<>]*?>/g,""):e)&&_("#replysubmit .error").html(e).show()},addcomment:function(t){var e=this;_("#add-new-comment").fadeOut(200,function(){e.open(0,t,"add"),_("table.comments-box").css("display",""),_("#no-comments").remove()})},discardCommentChanges:function(){var t=_("#replyrow");return this.originalContent===_("#replycontent",t).val()||window.confirm(adminCommentsL10n.warnCommentChanges)}},_(document).ready(function(){var t,e,n,a;setCommentsList(),commentReply.init(),_(document).on("click","span.delete a.delete",function(t){t.preventDefault()}),void 0!==_.table_hotkeys&&(t=function(n){return function(){var t="next"==n?"first":"last",e=_(".tablenav-pages ."+n+"-page:not(.disabled)");e.length&&(window.location=e[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g,"")+"&hotkeys_highlight_"+t+"=1")}},e=function(t,e){window.location=_("span.edit a",e).attr("href")},n=function(){_("#cb-select-all-1").data("wp-toggle",1).trigger("click").removeData("wp-toggle")},a=function(e){return function(){var t=_('select[name="action"]');_('option[value="'+e+'"]',t).prop("selected",!0),_("#doaction").click()}},_.table_hotkeys(_("table.widefat"),["a","u","s","d","r","q","z",["e",e],["shift+x",n],["shift+a",a("approve")],["shift+s",a("spam")],["shift+d",a("delete")],["shift+t",a("trash")],["shift+z",a("untrash")],["shift+u",a("unapprove")]],{highlight_first:adminCommentsL10n.hotkeys_highlight_first,highlight_last:adminCommentsL10n.hotkeys_highlight_last,prev_page_link_cb:t("prev"),next_page_link_cb:t("next"),hotkeys_opts:{disableInInput:!0,type:"keypress",noDisable:'.check-column input[type="checkbox"]'},cycle_expr:"#the-comment-list tr",start_row_index:0})),_("#the-comment-list").on("click",".comment-inline",function(t){t.preventDefault();var e=_(this),t="replyto";void 0!==e.data("action")&&(t=e.data("action")),commentReply.open(e.data("commentId"),e.data("postId"),t)})})}(jQuery); inline-edit-tax.min.js 0000666 00000005260 15213733063 0010671 0 ustar 00 var inlineEditTax;window.wp=window.wp||{},function(d,s){inlineEditTax={init:function(){var t=this,i=d("#inline-edit");t.type=d("#the-list").attr("data-wp-lists").substr(5),t.what="#"+t.type+"-",d("#the-list").on("click","a.editinline",function(){return inlineEditTax.edit(this),!1}),i.keyup(function(t){if(27===t.which)return inlineEditTax.revert()}),d(".cancel",i).click(function(){return inlineEditTax.revert()}),d(".save",i).click(function(){return inlineEditTax.save(this)}),d("input, select",i).keydown(function(t){if(13===t.which)return inlineEditTax.save(this)}),d('#posts-filter input[type="submit"]').mousedown(function(){t.revert()})},toggle:function(t){var i=this;"none"===d(i.what+i.getId(t)).css("display")?i.revert():i.edit(t)},edit:function(t){var i,e,n=this;return n.revert(),"object"==typeof t&&(t=n.getId(t)),i=d("#inline-edit").clone(!0),e=d("#inline_"+t),d("td",i).attr("colspan",d("th:visible, td:visible",".wp-list-table.widefat:first thead").length),d(n.what+t).hide().after(i).after('<tr class="hidden"></tr>'),(n=d(".name",e)).find("img").replaceWith(function(){return this.alt}),n=n.text(),d(':input[name="name"]',i).val(n),(n=d(".slug",e)).find("img").replaceWith(function(){return this.alt}),n=n.text(),d(':input[name="slug"]',i).val(n),d(i).attr("id","edit-"+t).addClass("inline-editor").show(),d(".ptitle",i).eq(0).focus(),!1},save:function(r){var t=d('input[name="taxonomy"]').val()||"";return"object"==typeof r&&(r=this.getId(r)),d("table.widefat .spinner").addClass("is-active"),t={action:"inline-save-tax",tax_type:this.type,tax_ID:r,taxonomy:t},t=d("#edit-"+r).find(":input").serialize()+"&"+d.param(t),d.post(ajaxurl,t,function(t){var i,e,n,a=d("#edit-"+r+" .inline-edit-save .error");d("table.widefat .spinner").removeClass("is-active"),t?-1!==t.indexOf("<tr")?(d(inlineEditTax.what+r).siblings("tr.hidden").addBack().remove(),e=d(t).attr("id"),d("#edit-"+r).before(t).remove(),i=e?(n=e.replace(inlineEditTax.type+"-",""),d("#"+e)):(n=r,d(inlineEditTax.what+r)),d("#parent").find("option[value="+n+"]").text(i.find(".row-title").text()),i.hide().fadeIn(400,function(){i.find(".editinline").focus(),s.a11y.speak(inlineEditL10n.saved)})):(a.html(t).show(),s.a11y.speak(a.text())):(a.html(inlineEditL10n.error).show(),s.a11y.speak(inlineEditL10n.error))}),!1},revert:function(){var t=d("table.widefat tr.inline-editor").attr("id");t&&(d("table.widefat .spinner").removeClass("is-active"),d("#"+t).siblings("tr.hidden").addBack().remove(),t=t.substr(t.lastIndexOf("-")+1),d(this.what+t).show().find(".editinline").focus())},getId:function(t){t=("TR"===t.tagName?t.id:d(t).parents("tr").attr("id")).split("-");return t[t.length-1]}},d(document).ready(function(){inlineEditTax.init()})}(jQuery,window.wp); postbox.js 0000666 00000027204 15213733063 0006614 0 ustar 00 /** * Contains the postboxes logic, opening and closing postboxes, reordering and saving * the state and ordering to the database. * * @summary Contains postboxes logic * * @since 2.5.0 * @requires jQuery */ /* global ajaxurl, postBoxL10n */ /** * This object contains all function to handle the behaviour of the post boxes. The post boxes are the boxes you see * around the content on the edit page. * * @since 2.7.0 * * @namespace postboxes * * @type {Object} */ var postboxes; (function($) { var $document = $( document ); postboxes = { /** * @summary Handles a click on either the postbox heading or the postbox open/close icon. * * Opens or closes the postbox. Expects `this` to equal the clicked element. * Calls postboxes.pbshow if the postbox has been opened, calls postboxes.pbhide * if the postbox has been closed. * * @since 4.4.0 * @memberof postboxes * @fires postboxes#postbox-toggled * * @returns {void} */ handle_click : function () { var $el = $( this ), p = $el.parent( '.postbox' ), id = p.attr( 'id' ), ariaExpandedValue; if ( 'dashboard_browser_nag' === id ) { return; } p.toggleClass( 'closed' ); ariaExpandedValue = ! p.hasClass( 'closed' ); if ( $el.hasClass( 'handlediv' ) ) { // The handle button was clicked. $el.attr( 'aria-expanded', ariaExpandedValue ); } else { // The handle heading was clicked. $el.closest( '.postbox' ).find( 'button.handlediv' ) .attr( 'aria-expanded', ariaExpandedValue ); } if ( postboxes.page !== 'press-this' ) { postboxes.save_state( postboxes.page ); } if ( id ) { if ( !p.hasClass('closed') && $.isFunction( postboxes.pbshow ) ) { postboxes.pbshow( id ); } else if ( p.hasClass('closed') && $.isFunction( postboxes.pbhide ) ) { postboxes.pbhide( id ); } } /** * @summary Fires when a postbox has been opened or closed. * * Contains a jQuery object with the relevant postbox element. * * @since 4.0.0 * @event postboxes#postbox-toggled * @type {Object} */ $document.trigger( 'postbox-toggled', p ); }, /** * Adds event handlers to all postboxes and screen option on the current page. * * @since 2.7.0 * @memberof postboxes * * @param {string} page The page we are currently on. * @param {Object} [args] * @param {Function} args.pbshow A callback that is called when a postbox opens. * @param {Function} args.pbhide A callback that is called when a postbox closes. * @returns {void} */ add_postbox_toggles : function (page, args) { var $handles = $( '.postbox .hndle, .postbox .handlediv' ); this.page = page; this.init( page, args ); $handles.on( 'click.postboxes', this.handle_click ); /** * @since 2.7.0 */ $('.postbox .hndle a').click( function(e) { e.stopPropagation(); }); /** * @summary Hides a postbox. * * Event handler for the postbox dismiss button. After clicking the button * the postbox will be hidden. * * @since 3.2.0 * * @returns {void} */ $( '.postbox a.dismiss' ).on( 'click.postboxes', function( e ) { var hide_id = $(this).parents('.postbox').attr('id') + '-hide'; e.preventDefault(); $( '#' + hide_id ).prop('checked', false).triggerHandler('click'); }); /** * @summary Hides the postbox element * * Event handler for the screen options checkboxes. When a checkbox is * clicked this function will hide or show the relevant postboxes. * * @since 2.7.0 * @fires postboxes#postbox-toggled * * @returns {void} */ $('.hide-postbox-tog').bind('click.postboxes', function() { var $el = $(this), boxId = $el.val(), $postbox = $( '#' + boxId ); if ( $el.prop( 'checked' ) ) { $postbox.show(); if ( $.isFunction( postboxes.pbshow ) ) { postboxes.pbshow( boxId ); } } else { $postbox.hide(); if ( $.isFunction( postboxes.pbhide ) ) { postboxes.pbhide( boxId ); } } postboxes.save_state( page ); postboxes._mark_area(); /** * @since 4.0.0 * @see postboxes.handle_click */ $document.trigger( 'postbox-toggled', $postbox ); }); /** * @summary Changes the amount of columns based on the layout preferences. * * @since 2.8.0 * * @returns {void} */ $('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){ var n = parseInt($(this).val(), 10); if ( n ) { postboxes._pb_edit(n); postboxes.save_order( page ); } }); }, /** * @summary Initializes all the postboxes, mainly their sortable behaviour. * * @since 2.7.0 * @memberof postboxes * * @param {string} page The page we are currently on. * @param {Object} [args={}] The arguments for the postbox initializer. * @param {Function} args.pbshow A callback that is called when a postbox opens. * @param {Function} args.pbhide A callback that is called when a postbox * closes. * * @returns {void} */ init : function(page, args) { var isMobile = $( document.body ).hasClass( 'mobile' ), $handleButtons = $( '.postbox .handlediv' ); $.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: function( event, element ) { /* `helper: 'clone'` is equivalent to `return element.clone();` * Cloning a checked radio and then inserting that clone next to the original * radio unchecks the original radio (since only one of the two can be checked). * We get around this by renaming the helper's inputs' name attributes so that, * when the helper is inserted into the DOM for the sortable, no radios are * duplicated, and no original radio gets unchecked. */ return element.clone() .find( ':input' ) .attr( 'name', function( i, currentName ) { return 'sort_' + parseInt( Math.random() * 100000, 10 ).toString() + '_' + currentName; } ) .end(); }, opacity: 0.65, stop: function() { var $el = $( this ); if ( $el.find( '#dashboard_browser_nag' ).is( ':visible' ) && 'dashboard_browser_nag' != this.firstChild.id ) { $el.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(); $document.trigger( 'postbox-moved', ui.item ); } }); if ( isMobile ) { $(document.body).bind('orientationchange.postboxes', function(){ postboxes._pb_change(); }); this._pb_change(); } this._mark_area(); // Set the handle buttons `aria-expanded` attribute initial value on page load. $handleButtons.each( function () { var $el = $( this ); $el.attr( 'aria-expanded', ! $el.parent( '.postbox' ).hasClass( 'closed' ) ); }); }, /** * @summary Saves the state of the postboxes to the server. * * Saves the state of the postboxes to the server. It sends two lists, one with * all the closed postboxes, one with all the hidden postboxes. * * @since 2.7.0 * @memberof postboxes * * @param {string} page The page we are currently on. * @returns {void} */ save_state : function(page) { var closed, hidden; // Return on the nav-menus.php screen, see #35112. if ( 'nav-menus' === page ) { return; } 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 }); }, /** * @summary Saves the order of the postboxes to the server. * * Saves the order of the postboxes to the server. Sends a list of all postboxes * inside a sortable area to the server. * * @since 2.8.0 * @memberof postboxes * * @param {string} page The page we are currently on. * @returns {void} */ 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 ); }, /** * @summary Marks empty postbox areas. * * Adds a message to empty sortable areas on the dashboard page. Also adds a * border around the side area on the post edit screen if there are no postboxes * present. * * @since 3.3.0 * @memberof postboxes * @access private * * @returns {void} */ _mark_area : function() { var visible = $('div.postbox:visible').length, side = $('#post-body #side-sortables'); $( '#dashboard-widgets .meta-box-sortables:visible' ).each( function() { var t = $(this); if ( visible == 1 || t.children('.postbox:visible').length ) { t.removeClass('empty-container'); } else { t.addClass('empty-container'); t.attr('data-emptyString', postBoxL10n.postBoxEmptyString); } }); 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'); } }, /** * @summary Changes the amount of columns on the post edit page. * * @since 3.3.0 * @memberof postboxes * @fires postboxes#postboxes-columnchange * @access private * * @param {number} n The amount of columns to divide the post edit page in. * @returns {void} */ _pb_edit : function(n) { var el = $('.metabox-holder').get(0); if ( el ) { el.className = el.className.replace(/columns-\d+/, 'columns-' + n); } /** * Fires when the amount of columns on the post edit page has been changed. * * @since 4.0.0 * @event postboxes#postboxes-columnchange */ $( document ).trigger( 'postboxes-columnchange' ); }, /** * @summary Changes the amount of columns the postboxes are in based on the * current orientation of the browser. * * @since 3.3.0 * @memberof postboxes * @access private * * @returns {void} */ _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 */ /** * @since 2.7.0 * @memberof postboxes * @access public * @property {Function|boolean} pbshow A callback that is called when a postbox * is opened. */ pbshow : false, /** * @since 2.7.0 * @memberof postboxes * @access public * @property {Function|boolean} pbhide A callback that is called when a postbox * is closed. */ pbhide : false }; }(jQuery)); nav-menu.js 0000666 00000121511 15213733063 0006640 0 ustar 00 /** * WordPress Administration Navigation Menu * Interface JS functions * * @version 2.0.0 * * @package WordPress * @subpackage Administration */ /* global menus, postboxes, columns, isRtl, navMenuL10n, ajaxurl */ var wpNavMenu; (function($) { var api; api = wpNavMenu = { options : { menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead. globalMaxDepth: 11, sortableItems: '> *', targetTolerance: 0 }, menuList : undefined, // Set in init. targetList : undefined, // Set in init. menusChanged : false, isRTL: !! ( 'undefined' != typeof isRtl && isRtl ), negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1, lastSearch: '', // Functions that run on init. init : function() { api.menuList = $('#menu-to-edit'); api.targetList = api.menuList; this.jQueryExtensions(); this.attachMenuEditListeners(); this.attachQuickSearchListeners(); this.attachThemeLocationsListeners(); this.attachMenuSaveSubmitListeners(); this.attachTabsPanelListeners(); this.attachUnsavedChangesListener(); if ( api.menuList.length ) this.initSortables(); if ( menus.oneThemeLocationNoMenus ) $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom ); this.initManageLocations(); this.initAccessibility(); this.initToggles(); this.initPreviewing(); }, 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(), newDepth = depth + change; t.removeClass( 'menu-item-depth-'+ depth ) .addClass( 'menu-item-depth-'+ ( newDepth ) ); if ( 0 === newDepth ) { t.find( '.is-submenu' ).hide(); } }); }, childMenuItems : function() { var result = $(); this.each(function(){ var t = $(this), depth = t.menuItemDepth(), next = t.next( '.menu-item' ); while( next.length && next.menuItemDepth() > depth ) { result = result.add( next ); next = next.next( '.menu-item' ); } }); 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() { 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(), 10 ), 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 = /menu-item\[([^\]]*)/; processMethod = processMethod || api.addMenuItemToBottom; // If no items are checked, bail. if ( !checkboxes.length ) return false; // Show the ajax spinner t.find( '.button-controls .spinner' ).addClass( 'is-active' ); // 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( '.button-controls .spinner' ).removeClass( 'is-active' ); }); }); }, 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 items, newItemPosition, newDepth, menuItems = $( '#menu-to-edit li' ), menuItemsCount = menuItems.length, thisItem = $this.parents( 'li.menu-item' ), thisItemChildren = thisItem.childMenuItems(), thisItemData = thisItem.getItemData(), thisItemDepth = parseInt( thisItem.menuItemDepth(), 10 ), thisItemPosition = parseInt( thisItem.index(), 10 ), nextItem = thisItem.next(), nextItemChildren = nextItem.childMenuItems(), nextItemDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1, prevItem = thisItem.prev(), prevItemDepth = parseInt( prevItem.menuItemDepth(), 10 ), prevItemId = prevItem.getItemData()['menu-item-db-id']; switch ( dir ) { case 'up': 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 ) { 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 ) { items = thisItem.add( thisItemChildren ), nextItem = menuItems.eq( items.length + thisItemPosition ), nextItemChildren = 0 !== nextItem.childMenuItems().length; if ( nextItemChildren ) { newDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 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 ) { 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() { var menu = $( '#menu-to-edit' ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); // Refresh the accessibility when the user comes close to the item in any way menu.on( 'mouseenter.refreshAccessibility focus.refreshAccessibility touchstart.refreshAccessibility' , '.menu-item' , function(){ api.refreshAdvancedAccessibilityOfItem( $( this ).find( 'a.item-edit' ) ); } ); // We have to update on click as well because we might hover first, change the item, and then click. menu.on( 'click', 'a.item-edit', function() { api.refreshAdvancedAccessibilityOfItem( $( this ) ); } ); // Links for moving items menu.on( 'click', '.menus-move', function () { var $this = $( this ), dir = $this.data( 'dir' ); if ( 'undefined' !== typeof dir ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), dir ); } }); }, /** * refreshAdvancedAccessibilityOfItem( [itemToRefresh] ) * * Refreshes advanced accessibility buttons for one menu item. * Shows or hides buttons based on the location of the menu item. * * @param {object} itemToRefresh The menu item that might need its advanced accessibility buttons refreshed */ refreshAdvancedAccessibilityOfItem : function( itemToRefresh ) { // Only refresh accessibility when necessary if ( true !== $( itemToRefresh ).data( 'needs_accessibility_refresh' ) ) { return; } var thisLink, thisLinkText, primaryItems, itemPosition, title, parentItem, parentItemId, parentItemName, subItems, $this = $( itemToRefresh ), menuItem = $this.closest( 'li.menu-item' ).first(), depth = menuItem.menuItemDepth(), isPrimaryMenuItem = ( 0 === depth ), itemName = $this.closest( '.menu-item-handle' ).find( '.menu-item-title' ).text(), position = parseInt( menuItem.index(), 10 ), prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1, 10 ), 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; menuItem.find( '.field-move' ).toggle( totalMenuItems > 1 ); // Where can they move this menu item? if ( 0 !== position ) { thisLink = menuItem.find( '.menus-move-up' ); thisLink.attr( 'aria-label', menus.moveUp ).css( 'display', 'inline' ); } if ( 0 !== position && isPrimaryMenuItem ) { thisLink = menuItem.find( '.menus-move-top' ); thisLink.attr( 'aria-label', menus.moveToTop ).css( 'display', 'inline' ); } if ( position + 1 !== totalMenuItems && 0 !== position ) { thisLink = menuItem.find( '.menus-move-down' ); thisLink.attr( 'aria-label', menus.moveDown ).css( 'display', 'inline' ); } if ( 0 === position && 0 !== hasSameDepthSibling ) { thisLink = menuItem.find( '.menus-move-down' ); thisLink.attr( 'aria-label', menus.moveDown ).css( 'display', 'inline' ); } if ( ! isPrimaryMenuItem ) { thisLink = menuItem.find( '.menus-move-left' ), thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft ); thisLink.attr( 'aria-label', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).text( thisLinkText ).css( 'display', 'inline' ); } if ( 0 !== position ) { if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) { thisLink = menuItem.find( '.menus-move-right' ), thisLinkText = menus.under.replace( '%s', prevItemNameRight ); thisLink.attr( 'aria-label', menus.moveUnder.replace( '%s', prevItemNameRight ) ).text( thisLinkText ).css( 'display', 'inline' ); } } if ( isPrimaryMenuItem ) { 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 { parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).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 ); } // @todo Consider to update just the `aria-label` attribute. $this.attr( 'aria-label', title ).text( title ); // Mark this item's accessibility as refreshed $this.data( 'needs_accessibility_refresh', false ); }, /** * refreshAdvancedAccessibility * * Hides all advanced accessibility buttons and marks them for refreshing. */ refreshAdvancedAccessibility : function() { // Hide all the move buttons by default. $( '.menu-item-settings .field-move .menus-move' ).hide(); // Mark all menu items as unprocessed $( 'a.item-edit' ).data( 'needs_accessibility_refresh', true ); // All open items have to be refreshed or they will show no links $( '.menu-item-edit-active a.item-edit' ).each( function() { api.refreshAdvancedAccessibilityOfItem( this ); } ); }, refreshKeyboardAccessibility : function() { $( 'a.item-edit' ).off( 'focus' ).on( 'focus', function(){ $(this).off( 'keydown' ).on( 'keydown', function(e){ var arrows, $this = $( this ), thisItem = $this.parents( 'li.menu-item' ), thisItemData = thisItem.getItemData(); // 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 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; }); }); }, initPreviewing : function() { // Update the item handle title when the navigation label is changed. $( '#menu-to-edit' ).on( 'change input', '.edit-menu-item-title', function(e) { var input = $( e.currentTarget ), title, titleEl; title = input.val(); titleEl = input.closest( '.menu-item' ).find( '.menu-item-title' ); // Don't update to empty title. if ( title ) { titleEl.text( title ).removeClass( 'no-title' ); } else { titleEl.text( navMenuL10n.untitled ).addClass( 'no-title' ); } } ); }, 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', items: api.options.sortableItems, 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( '.menu-item' ); 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, subMenuTitle, depthChange = currentDepth - originalDepth; // Return child elements to the list children = transport.children().insertAfter(ui.item); // Add "sub menu" description subMenuTitle = ui.item.find( '.item-title .is-submenu' ); if ( 0 < currentDepth ) subMenuTitle.show(); else subMenuTitle.hide(); // Update depth classes if ( 0 !== depthChange ) { 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 - api.options.targetTolerance ) ) { 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( '.menu-item' ); next = ui.placeholder.next( '.menu-item' ); // Make sure we don't select the moving item. if( prev[0] == ui.item[0] ) prev = prev.prev( '.menu-item' ); if( next[0] == ui.item[0] ) next = next.next( '.menu-item' ); 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], 10 ) : 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){ $('#customlinkdiv').removeClass('form-invalid'); if ( e.keyCode === 13 ) { e.preventDefault(); $( '#submit-customlinkdiv' ).click(); } }); }, attachMenuSaveSubmitListeners : function() { /* * When a navigation menu is saved, store a JSON representation of all form data * in a single input to avoid PHP `max_input_vars` limitations. See #14134. */ $( '#update-nav-menu' ).submit( function() { var navMenuData = $( '#update-nav-menu' ).serializeArray(); $( '[name="nav-menu-data"]' ).val( JSON.stringify( navMenuData ) ); }); }, 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' ).addClass( 'is-active' ); $.post( ajaxurl, params, function() { loc.find( '.spinner' ).removeClass( 'is-active' ); }); return false; }); }, attachQuickSearchListeners : function() { var searchTimer, inputEvent; // Prevent form submission. $( '#nav-menu-meta' ).on( 'submit', function( event ) { event.preventDefault(); }); /* * Use feature detection to determine whether inputs should use * the `keyup` or `input` event. Input is preferred but lacks support * in legacy browsers. See changeset 34078, see also ticket #26600#comment:59 */ if ( 'oninput' in document.createElement( 'input' ) ) { inputEvent = 'input'; } else { inputEvent = 'keyup'; } $( '#nav-menu-meta' ).on( inputEvent, '.quick-search', function() { var $this = $( this ); $this.attr( 'autocomplete', 'off' ); if ( searchTimer ) { clearTimeout( searchTimer ); } searchTimer = setTimeout( function() { api.updateQuickSearchResults( $this ); }, 500 ); }).on( 'blur', '.quick-search', function() { api.lastSearch = ''; }); }, updateQuickSearchResults : function(input) { var panel, params, minSearchLength = 2, q = input.val(); /* * Minimum characters for a search. Also avoid a new AJAX search when * the pressed key (e.g. arrows) doesn't change the searched term. */ if ( q.length < minSearchLength || api.lastSearch == q ) { return; } api.lastSearch = q; 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 ).addClass( 'is-active' ); $.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 ) { $('#customlinkdiv').addClass('form-invalid'); return false; } // Show the ajax spinner $( '.customlinkdiv .spinner' ).addClass( 'is-active' ); this.addLinkToMenu( url, label, processMethod, function() { // Remove the ajax spinner $( '.customlinkdiv .spinner' ).removeClass( 'is-active' ); // 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(), params; 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'); menuMarkup = $.trim( menuMarkup ); // Trim leading whitespaces 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 ) { $(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, addMenuItemToTop : function( menuMarkup ) { $(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(); // Hide controls in the search tab if no items found. if ( ! wrapper.find( '.tabs-panel-active .menu-item-title' ).length ) { wrapper.addClass( 'has-no-menu-item' ); } else { wrapper.removeClass( 'has-no-menu-item' ); } 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; } }); /* * Delegate the `click` event and attach it just to the pagination * links thus excluding the current page `<span>`. See ticket #35577. */ $( '#nav-menu-meta' ).on( 'click', 'a.page-numbers', function() { var $container = $( this ).closest( '.inside' ); $.post( ajaxurl, this.href.replace( /.*\?/, '' ).replace( /action=([^&]*)/, '' ) + '&action=menu-get-metabox', function( resp ) { var metaBoxData = $.parseJSON( resp ), toReplace; if ( -1 === resp.indexOf( 'replace-id' ) ) { return; } // Get the post type menu meta box to update. toReplace = document.getElementById( metaBoxData['replace-id'] ); if ( ! metaBoxData.markup || ! toReplace ) { return; } // Update the post type menu meta box with new content from the response. $container.html( metaBoxData.markup ); } ); 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() { var 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. // Note: This appears to be dead code since #nav-menu-theme-locations no longer exists, perhaps removed in r32842. var $updateNavMenu = $('#update-nav-menu'); $('#nav-menu-theme-locations select').each(function() { $updateNavMenu.append( $( '<input>', { type: 'hidden', name: this.name, value: $( this ).val() } ) ); }); // 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() { // Delete warning AYS if ( window.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 = /menu-item[(\[^]\]*/, $items = $('<div>').html(resp).find('li'), wrapper = panel.closest( '.accordion-section-content' ), $item; if( ! $items.length ) { var li = $( '<li>' ); var p = $( '<p>', { text: navMenuL10n.noResultsFound } ); li.append( p ); $('.categorychecklist', panel).empty().append( li ); $( '.spinner', panel ).removeClass( 'is-active' ); wrapper.addClass( 'has-no-menu-item' ); 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 ).removeClass( 'is-active' ); wrapper.removeClass( 'has-no-menu-item' ); }, 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' ); } api.refreshAdvancedAccessibility(); }); }, depthToPx : function(depth) { return depth * api.options.menuItemDepthPerLevel; }, pxToDepth : function(px) { return Math.floor(px / api.options.menuItemDepthPerLevel); } }; $(document).ready(function(){ wpNavMenu.init(); }); })(jQuery); image-edit.min.js 0000666 00000022525 15213733063 0007706 0 ustar 00 !function(g){var d=window.imageEdit={iasapi:{},hold:{},postid:"",_view:!1,intval:function(i){return 0|i},setDisabled:function(i,t){t?i.removeClass("disabled").prop("disabled",!1):i.addClass("disabled").prop("disabled",!0)},init:function(i){var t=this,e=g("#image-editor-"+t.postid),a=t.intval(g("#imgedit-x-"+i).val()),o=t.intval(g("#imgedit-y-"+i).val());t.postid!==i&&e.length&&t.close(t.postid),t.hold.w=t.hold.ow=a,t.hold.h=t.hold.oh=o,t.hold.xy_ratio=a/o,t.hold.sizer=parseFloat(g("#imgedit-sizer-"+i).val()),t.postid=i,g("#imgedit-response-"+i).empty(),g('input[type="text"]',"#imgedit-panel-"+i).keypress(function(i){var t=i.keyCode;if(36<t&&t<41&&g(this).blur(),13===t)return i.preventDefault(),i.stopPropagation(),!1})},toggleEditor:function(i,t){i=g("#imgedit-wait-"+i);t?i.fadeIn("fast"):i.fadeOut("fast")},toggleHelp:function(i){i=g(i);return i.attr("aria-expanded","false"===i.attr("aria-expanded")?"true":"false").parents(".imgedit-group-top").toggleClass("imgedit-help-toggled").find(".imgedit-help").slideToggle("fast"),!1},getTarget:function(i){return g('input[name="imgedit-target-'+i+'"]:checked',"#imgedit-save-target-"+i).val()||"full"},scaleChanged:function(i,t,e){var a=g("#imgedit-scale-width-"+i),o=g("#imgedit-scale-height-"+i),s=g("#imgedit-scale-warn-"+i),n="",i="";!1!==this.validateNumeric(e)&&(t?(i=""!==a.val()?Math.round(a.val()/this.hold.xy_ratio):"",o.val(i)):(n=""!==o.val()?Math.round(o.val()*this.hold.xy_ratio):"",a.val(n)),i&&i>this.hold.oh||n&&n>this.hold.ow?s.css("visibility","visible"):s.css("visibility","hidden"))},getSelRatio:function(i){var t=this.hold.w,e=this.hold.h,a=this.intval(g("#imgedit-crop-width-"+i).val()),i=this.intval(g("#imgedit-crop-height-"+i).val());return a&&i?a+":"+i:t&&e?t+":"+e:"1:1"},filterHistory:function(i,t){var e,a,o,s=g("#imgedit-history-"+i).val(),n=[];if(""===s)return"";if(s=JSON.parse(s),0<(e=this.intval(g("#imgedit-undone-"+i).val())))for(;0<e;)s.pop(),e--;if(t){if(!s.length)return this.hold.w=this.hold.ow,this.hold.h=this.hold.oh,"";(t=(t=s[s.length-1]).c||t.r||t.f||!1)&&(this.hold.w=t.fw,this.hold.h=t.fh)}for(a in s)(o=s[a]).hasOwnProperty("c")?n[a]={c:{x:o.c.x,y:o.c.y,w:o.c.w,h:o.c.h}}:o.hasOwnProperty("r")?n[a]={r:o.r.r}:o.hasOwnProperty("f")&&(n[a]={f:o.f.f});return JSON.stringify(n)},refreshEditor:function(o,i,s){var n,t=this;t.toggleEditor(o,1),i={action:"imgedit-preview",_ajax_nonce:i,postid:o,history:t.filterHistory(o,1),rand:t.intval(1e6*Math.random())},n=g('<img id="image-preview-'+o+'" alt="" />').on("load",{history:i.history},function(i){var t,e=g("#imgedit-crop-"+o),a=d;""!==i.data.history&&(t=JSON.parse(i.data.history))[t.length-1].hasOwnProperty("c")&&(a.setDisabled(g("#image-undo-"+o),!0),g("#image-undo-"+o).focus()),e.empty().append(n),i=Math.max(a.hold.w,a.hold.h),t=Math.max(g(n).width(),g(n).height()),a.hold.sizer=t<i?t/i:1,a.initCrop(o,n,e),a.setCropSelection(o,0),null!=s&&s(),g("#imgedit-history-"+o).val()&&"0"===g("#imgedit-undone-"+o).val()?g("input.imgedit-submit-btn","#imgedit-panel-"+o).removeAttr("disabled"):g("input.imgedit-submit-btn","#imgedit-panel-"+o).prop("disabled",!0),a.toggleEditor(o,0)}).on("error",function(){g("#imgedit-crop-"+o).empty().append('<div class="error"><p>'+imageEditL10n.error+"</p></div>"),t.toggleEditor(o,0)}).attr("src",ajaxurl+"?"+g.param(i))},action:function(t,i,e){var a,o,s,n,d=this;if(d.notsaved(t))return!1;if(a={action:"image-editor",_ajax_nonce:i,postid:t},"scale"===e){if(o=g("#imgedit-scale-width-"+t),s=g("#imgedit-scale-height-"+t),n=d.intval(o.val()),i=d.intval(s.val()),n<1)return o.focus(),!1;if(i<1)return s.focus(),!1;if(n===d.hold.ow||i===d.hold.oh)return!1;a["do"]="scale",a.fwidth=n,a.fheight=i}else{if("restore"!==e)return!1;a["do"]="restore"}d.toggleEditor(t,1),g.post(ajaxurl,a,function(i){g("#image-editor-"+t).empty().append(i),d.toggleEditor(t,0),d._view&&d._view.refresh()})},save:function(t,i){var e=this.getTarget(t),a=this.filterHistory(t,0),o=this;if(""===a)return!1;this.toggleEditor(t,1),e={action:"image-editor",_ajax_nonce:i,postid:t,history:a,target:e,context:g("#image-edit-context").length?g("#image-edit-context").val():null,"do":"save"},g.post(ajaxurl,e,function(i){i=JSON.parse(i);if(i.error)return g("#imgedit-response-"+t).html('<div class="error"><p>'+i.error+"</p></div>"),void d.close(t);i.fw&&i.fh&&g("#media-dims-"+t).html(i.fw+" × "+i.fh),i.thumbnail&&g(".thumbnail","#thumbnail-head-"+t).attr("src",""+i.thumbnail),i.msg&&g("#imgedit-response-"+t).html('<div class="updated"><p>'+i.msg+"</p></div>"),o._view?o._view.save():d.close(t)})},open:function(t,i,e){this._view=e;var a=g("#image-editor-"+t),o=g("#media-head-"+t),s=g("#imgedit-open-btn-"+t),n=s.siblings(".spinner");if(!s.hasClass("button-activated"))return n.addClass("is-active"),i={action:"image-editor",_ajax_nonce:i,postid:t,"do":"open"},g.ajax({url:ajaxurl,type:"post",data:i,beforeSend:function(){s.addClass("button-activated")}}).done(function(i){a.html(i),o.fadeOut("fast",function(){a.fadeIn("fast"),s.removeClass("button-activated"),n.removeClass("is-active")}),d.init(t)})},imgLoaded:function(i){var t=g("#image-preview-"+i),e=g("#imgedit-crop-"+i);this.initCrop(i,t,e),this.setCropSelection(i,0),this.toggleEditor(i,0),g(".imgedit-wrap .imgedit-help-toggle").eq(0).focus()},initCrop:function(a,i,t){var o=this,s=g("#imgedit-sel-width-"+a),n=g("#imgedit-sel-height-"+a);o.iasapi=g(i).imgAreaSelect({parent:t,instance:!0,handles:!0,keys:!0,minWidth:3,minHeight:3,onInit:function(i){g(i).next().css("position","absolute").nextAll(".imgareaselect-outer").css("position","absolute"),t.children().mousedown(function(i){var t,e=!1;i.shiftKey&&(t=o.iasapi.getSelection(),i=o.getSelRatio(a),e=t&&t.width&&t.height?t.width+":"+t.height:i),o.iasapi.setOptions({aspectRatio:e})})},onSelectStart:function(){d.setDisabled(g("#imgedit-crop-sel-"+a),1)},onSelectEnd:function(i,t){d.setCropSelection(a,t)},onSelectChange:function(i,t){var e=d.hold.sizer;s.val(d.round(t.width/e)),n.val(d.round(t.height/e))}})},setCropSelection:function(i,t){if(!(t=t||0)||t.width<3&&t.height<3)return this.setDisabled(g(".imgedit-crop","#imgedit-panel-"+i),0),this.setDisabled(g("#imgedit-crop-sel-"+i),0),g("#imgedit-sel-width-"+i).val(""),g("#imgedit-sel-height-"+i).val(""),g("#imgedit-selection-"+i).val(""),!1;t={x:t.x1,y:t.y1,w:t.width,h:t.height},this.setDisabled(g(".imgedit-crop","#imgedit-panel-"+i),1),g("#imgedit-selection-"+i).val(JSON.stringify(t))},close:function(i,t){if((t=t||!1)&&this.notsaved(i))return!1;this.iasapi={},this.hold={},this._view?this._view.back():g("#image-editor-"+i).fadeOut("fast",function(){g("#media-head-"+i).fadeIn("fast",function(){g("#imgedit-open-btn-"+i).focus()}),g(this).empty()})},notsaved:function(i){var t=g("#imgedit-history-"+i).val(),t=""!==t?JSON.parse(t):[];return this.intval(g("#imgedit-undone-"+i).val())<t.length&&!confirm(g("#imgedit-leaving-"+i).html())},addStep:function(i,t,e){for(var a=this,o=g("#imgedit-history-"+t),s=""!==o.val()?JSON.parse(o.val()):[],n=g("#imgedit-undone-"+t),d=a.intval(n.val());0<d;)s.pop(),d--;n.val(0),s.push(i),o.val(JSON.stringify(s)),a.refreshEditor(t,e,function(){a.setDisabled(g("#image-undo-"+t),!0),a.setDisabled(g("#image-redo-"+t),!1)})},rotate:function(i,t,e,a){if(g(a).hasClass("disabled"))return!1;this.addStep({r:{r:i,fw:this.hold.h,fh:this.hold.w}},t,e)},flip:function(i,t,e,a){if(g(a).hasClass("disabled"))return!1;this.addStep({f:{f:i,fw:this.hold.w,fh:this.hold.h}},t,e)},crop:function(i,t,e){var a=g("#imgedit-selection-"+i).val(),o=this.intval(g("#imgedit-sel-width-"+i).val()),s=this.intval(g("#imgedit-sel-height-"+i).val());if(g(e).hasClass("disabled")||""===a)return!1;0<(a=JSON.parse(a)).w&&0<a.h&&0<o&&0<s&&(a.fw=o,a.fh=s,this.addStep({c:a},i,t))},undo:function(t,i){var e=this,a=g("#image-undo-"+t),o=g("#imgedit-undone-"+t),s=e.intval(o.val())+1;a.hasClass("disabled")||(o.val(s),e.refreshEditor(t,i,function(){var i=g("#imgedit-history-"+t),i=""!==i.val()?JSON.parse(i.val()):[];e.setDisabled(g("#image-redo-"+t),!0),e.setDisabled(a,s<i.length),i.length===s&&g("#image-redo-"+t).focus()}))},redo:function(i,t){var e=this,a=g("#image-redo-"+i),o=g("#imgedit-undone-"+i),s=e.intval(o.val())-1;a.hasClass("disabled")||(o.val(s),e.refreshEditor(i,t,function(){e.setDisabled(g("#image-undo-"+i),!0),e.setDisabled(a,0<s),0==s&&g("#image-undo-"+i).focus()}))},setNumSelection:function(i,t){var e,a=g("#imgedit-sel-width-"+i),o=g("#imgedit-sel-height-"+i),s=this.intval(a.val()),n=this.intval(o.val()),d=g("#image-preview-"+i),r=d.height(),l=d.width(),h=this.hold.sizer,d=this.iasapi;if(!1!==this.validateNumeric(t))return s<1?(a.val(""),!1):n<1?(o.val(""),!1):void(s&&n&&(e=d.getSelection())&&(t=e.x1+Math.round(s*h),s=e.y1+Math.round(n*h),n=e.x1,e=e.y1,l<t&&(n=0,t=l,a.val(Math.round(t/h))),r<s&&(e=0,s=r,o.val(Math.round(s/h))),d.setSelection(n,e,t,s),d.update(),this.setCropSelection(i,d.getSelection())))},round:function(i){var t;return i=Math.round(i),.6<this.hold.sizer?i:"1"===(t=i.toString().slice(-1))?i-1:"9"===t?i+1:i},setRatioSelection:function(i,t,e){var a=this.intval(g("#imgedit-crop-width-"+i).val()),o=this.intval(g("#imgedit-crop-height-"+i).val()),s=g("#image-preview-"+i).height();!1!==this.validateNumeric(e)&&a&&o&&(this.iasapi.setOptions({aspectRatio:a+":"+o}),(e=this.iasapi.getSelection(!0))&&(s<(o=Math.ceil(e.y1+(e.x2-e.x1)/(a/o)))&&(o=s,g(t?"#imgedit-crop-height-"+i:"#imgedit-crop-width-"+i).val("")),this.iasapi.setSelection(e.x1,e.y1,e.x2,o),this.iasapi.update()))},validateNumeric:function(i){if(!this.intval(g(i).val()))return g(i).val(""),!1}}}(jQuery); language-chooser.js 0000666 00000001161 15213733063 0010333 0 ustar 00 jQuery( function($) { var select = $( '#language' ), submit = $( '#language-continue' ); if ( ! $( 'body' ).hasClass( 'language-chooser' ) ) { return; } select.focus().on( 'change', function() { var option = select.children( 'option:selected' ); submit.attr({ value: option.data( 'continue' ), lang: option.attr( 'lang' ) }); }); $( 'form' ).submit( function() { // Don't show a spinner for English and installed languages, // as there is nothing to download. if ( ! select.children( 'option:selected' ).data( 'installed' ) ) { $( this ).find( '.step .spinner' ).css( 'visibility', 'visible' ); } }); }); customize-widgets.js 0000666 00000205435 15213733063 0010610 0 ustar 00 /* global _wpCustomizeWidgetsSettings */ (function( wp, $ ){ if ( ! wp || ! wp.customize ) { return; } // Set up our namespace... var api = wp.customize, l10n; api.Widgets = api.Widgets || {}; api.Widgets.savedWidgetIds = {}; // Link settings api.Widgets.data = _wpCustomizeWidgetsSettings || {}; l10n = api.Widgets.data.l10n; delete api.Widgets.data.l10n; /** * wp.customize.Widgets.WidgetModel * * A single widget model. * * @constructor * @augments Backbone.Model */ api.Widgets.WidgetModel = Backbone.Model.extend({ id: null, temp_id: null, classname: null, control_tpl: null, description: null, is_disabled: null, is_multi: null, multi_number: null, name: null, id_base: null, transport: null, params: [], width: null, height: null, search_matched: true }); /** * wp.customize.Widgets.WidgetCollection * * Collection for widget models. * * @constructor * @augments Backbone.Model */ api.Widgets.WidgetCollection = Backbone.Collection.extend({ model: api.Widgets.WidgetModel, // Controls searching on the current widget collection // and triggers an update event doSearch: function( value ) { // Don't do anything if we've already done this search // Useful because the search handler fires multiple times per keystroke if ( this.terms === value ) { return; } // Updates terms with the value passed this.terms = value; // If we have terms, run a search... if ( this.terms.length > 0 ) { this.search( this.terms ); } // If search is blank, set all the widgets as they matched the search to reset the views. if ( this.terms === '' ) { this.each( function ( widget ) { widget.set( 'search_matched', true ); } ); } }, // Performs a search within the collection // @uses RegExp search: function( term ) { var match, haystack; // Escape the term string for RegExp meta characters term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' ); // Consider spaces as word delimiters and match the whole string // so matching terms can be combined term = term.replace( / /g, ')(?=.*' ); match = new RegExp( '^(?=.*' + term + ').+', 'i' ); this.each( function ( data ) { haystack = [ data.get( 'name' ), data.get( 'id' ), data.get( 'description' ) ].join( ' ' ); data.set( 'search_matched', match.test( haystack ) ); } ); } }); api.Widgets.availableWidgets = new api.Widgets.WidgetCollection( api.Widgets.data.availableWidgets ); /** * wp.customize.Widgets.SidebarModel * * A single sidebar model. * * @constructor * @augments Backbone.Model */ api.Widgets.SidebarModel = Backbone.Model.extend({ after_title: null, after_widget: null, before_title: null, before_widget: null, 'class': null, description: null, id: null, name: null, is_rendered: false }); /** * wp.customize.Widgets.SidebarCollection * * Collection for sidebar models. * * @constructor * @augments Backbone.Collection */ api.Widgets.SidebarCollection = Backbone.Collection.extend({ model: api.Widgets.SidebarModel }); api.Widgets.registeredSidebars = new api.Widgets.SidebarCollection( api.Widgets.data.registeredSidebars ); /** * wp.customize.Widgets.AvailableWidgetsPanelView * * View class for the available widgets panel. * * @constructor * @augments wp.Backbone.View * @augments Backbone.View */ api.Widgets.AvailableWidgetsPanelView = wp.Backbone.View.extend({ el: '#available-widgets', events: { 'input #widgets-search': 'search', 'keyup #widgets-search': 'search', 'focus .widget-tpl' : 'focus', 'click .widget-tpl' : '_submit', 'keypress .widget-tpl' : '_submit', 'keydown' : 'keyboardAccessible' }, // Cache current selected widget selected: null, // Cache sidebar control which has opened panel currentSidebarControl: null, $search: null, $clearResults: null, searchMatchesCount: null, initialize: function() { var self = this; this.$search = $( '#widgets-search' ); this.$clearResults = this.$el.find( '.clear-results' ); _.bindAll( this, 'close' ); this.listenTo( this.collection, 'change', this.updateList ); this.updateList(); // Set the initial search count to the number of available widgets. this.searchMatchesCount = this.collection.length; // If the available widgets panel is open and the customize controls are // interacted with (i.e. available widgets panel is blurred) then close the // available widgets panel. Also close on back button click. $( '#customize-controls, #available-widgets .customize-section-title' ).on( 'click keydown', function( e ) { var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' ); if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) { self.close(); } } ); // Clear the search results and trigger a `keyup` event to fire a new search. this.$clearResults.on( 'click', function() { self.$search.val( '' ).focus().trigger( 'keyup' ); } ); // Close the panel if the URL in the preview changes api.previewer.bind( 'url', this.close ); }, // Performs a search and handles selected widget search: function( event ) { var firstVisible; this.collection.doSearch( event.target.value ); // Update the search matches count. this.updateSearchMatchesCount(); // Announce how many search results. this.announceSearchMatches(); // Remove a widget from being selected if it is no longer visible if ( this.selected && ! this.selected.is( ':visible' ) ) { this.selected.removeClass( 'selected' ); this.selected = null; } // If a widget was selected but the filter value has been cleared out, clear selection if ( this.selected && ! event.target.value ) { this.selected.removeClass( 'selected' ); this.selected = null; } // If a filter has been entered and a widget hasn't been selected, select the first one shown if ( ! this.selected && event.target.value ) { firstVisible = this.$el.find( '> .widget-tpl:visible:first' ); if ( firstVisible.length ) { this.select( firstVisible ); } } // Toggle the clear search results button. if ( '' !== event.target.value ) { this.$clearResults.addClass( 'is-visible' ); } else if ( '' === event.target.value ) { this.$clearResults.removeClass( 'is-visible' ); } // Set a CSS class on the search container when there are no search results. if ( ! this.searchMatchesCount ) { this.$el.addClass( 'no-widgets-found' ); } else { this.$el.removeClass( 'no-widgets-found' ); } }, // Update the count of the available widgets that have the `search_matched` attribute. updateSearchMatchesCount: function() { this.searchMatchesCount = this.collection.where({ search_matched: true }).length; }, // Send a message to the aria-live region to announce how many search results. announceSearchMatches: _.debounce( function() { var message = l10n.widgetsFound.replace( '%d', this.searchMatchesCount ) ; if ( ! this.searchMatchesCount ) { message = l10n.noWidgetsFound; } wp.a11y.speak( message ); }, 500 ), // Changes visibility of available widgets updateList: function() { this.collection.each( function( widget ) { var widgetTpl = $( '#widget-tpl-' + widget.id ); widgetTpl.toggle( widget.get( 'search_matched' ) && ! widget.get( 'is_disabled' ) ); if ( widget.get( 'is_disabled' ) && widgetTpl.is( this.selected ) ) { this.selected = null; } } ); }, // Highlights a widget select: function( widgetTpl ) { this.selected = $( widgetTpl ); this.selected.siblings( '.widget-tpl' ).removeClass( 'selected' ); this.selected.addClass( 'selected' ); }, // Highlights a widget on focus focus: function( event ) { this.select( $( event.currentTarget ) ); }, // Submit handler for keypress and click on widget _submit: function( event ) { // Only proceed with keypress if it is Enter or Spacebar if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) { return; } this.submit( $( event.currentTarget ) ); }, // Adds a selected widget to the sidebar submit: function( widgetTpl ) { var widgetId, widget, widgetFormControl; if ( ! widgetTpl ) { widgetTpl = this.selected; } if ( ! widgetTpl || ! this.currentSidebarControl ) { return; } this.select( widgetTpl ); widgetId = $( this.selected ).data( 'widget-id' ); widget = this.collection.findWhere( { id: widgetId } ); if ( ! widget ) { return; } widgetFormControl = this.currentSidebarControl.addWidget( widget.get( 'id_base' ) ); if ( widgetFormControl ) { widgetFormControl.focus(); } this.close(); }, // Opens the panel open: function( sidebarControl ) { this.currentSidebarControl = sidebarControl; // Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens _( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) { if ( control.params.is_wide ) { control.collapseForm(); } } ); $( 'body' ).addClass( 'adding-widget' ); this.$el.find( '.selected' ).removeClass( 'selected' ); // Reset search this.collection.doSearch( '' ); if ( ! api.settings.browser.mobile ) { this.$search.focus(); } }, // Closes the panel close: function( options ) { options = options || {}; if ( options.returnFocus && this.currentSidebarControl ) { this.currentSidebarControl.container.find( '.add-new-widget' ).focus(); } this.currentSidebarControl = null; this.selected = null; $( 'body' ).removeClass( 'adding-widget' ); this.$search.val( '' ); }, // Add keyboard accessiblity to the panel keyboardAccessible: function( event ) { var isEnter = ( event.which === 13 ), isEsc = ( event.which === 27 ), isDown = ( event.which === 40 ), isUp = ( event.which === 38 ), isTab = ( event.which === 9 ), isShift = ( event.shiftKey ), selected = null, firstVisible = this.$el.find( '> .widget-tpl:visible:first' ), lastVisible = this.$el.find( '> .widget-tpl:visible:last' ), isSearchFocused = $( event.target ).is( this.$search ), isLastWidgetFocused = $( event.target ).is( '.widget-tpl:visible:last' ); if ( isDown || isUp ) { if ( isDown ) { if ( isSearchFocused ) { selected = firstVisible; } else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) { selected = this.selected.nextAll( '.widget-tpl:visible:first' ); } } else if ( isUp ) { if ( isSearchFocused ) { selected = lastVisible; } else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) { selected = this.selected.prevAll( '.widget-tpl:visible:first' ); } } this.select( selected ); if ( selected ) { selected.focus(); } else { this.$search.focus(); } return; } // If enter pressed but nothing entered, don't do anything if ( isEnter && ! this.$search.val() ) { return; } if ( isEnter ) { this.submit(); } else if ( isEsc ) { this.close( { returnFocus: true } ); } if ( this.currentSidebarControl && isTab && ( isShift && isSearchFocused || ! isShift && isLastWidgetFocused ) ) { this.currentSidebarControl.container.find( '.add-new-widget' ).focus(); event.preventDefault(); } } }); /** * Handlers for the widget-synced event, organized by widget ID base. * Other widgets may provide their own update handlers by adding * listeners for the widget-synced event. */ api.Widgets.formSyncHandlers = { /** * @param {jQuery.Event} e * @param {jQuery} widget * @param {String} newForm */ rss: function( e, widget, newForm ) { var oldWidgetError = widget.find( '.widget-error:first' ), newWidgetError = $( '<div>' + newForm + '</div>' ).find( '.widget-error:first' ); if ( oldWidgetError.length && newWidgetError.length ) { oldWidgetError.replaceWith( newWidgetError ); } else if ( oldWidgetError.length ) { oldWidgetError.remove(); } else if ( newWidgetError.length ) { widget.find( '.widget-content:first' ).prepend( newWidgetError ); } } }; /** * wp.customize.Widgets.WidgetControl * * Customizer control for widgets. * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type * * @constructor * @augments wp.customize.Control */ api.Widgets.WidgetControl = api.Control.extend({ defaultExpandedArguments: { duration: 'fast', completeCallback: $.noop }, /** * @since 4.1.0 */ initialize: function( id, options ) { var control = this; control.widgetControlEmbedded = false; control.widgetContentEmbedded = false; control.expanded = new api.Value( false ); control.expandedArgumentsQueue = []; control.expanded.bind( function( expanded ) { var args = control.expandedArgumentsQueue.shift(); args = $.extend( {}, control.defaultExpandedArguments, args ); control.onChangeExpanded( expanded, args ); }); control.altNotice = true; api.Control.prototype.initialize.call( control, id, options ); }, /** * Set up the control. * * @since 3.9.0 */ ready: function() { var control = this; /* * Embed a placeholder once the section is expanded. The full widget * form content will be embedded once the control itself is expanded, * and at this point the widget-added event will be triggered. */ if ( ! control.section() ) { control.embedWidgetControl(); } else { api.section( control.section(), function( section ) { var onExpanded = function( isExpanded ) { if ( isExpanded ) { control.embedWidgetControl(); section.expanded.unbind( onExpanded ); } }; if ( section.expanded() ) { onExpanded( true ); } else { section.expanded.bind( onExpanded ); } } ); } }, /** * Embed the .widget element inside the li container. * * @since 4.4.0 */ embedWidgetControl: function() { var control = this, widgetControl; if ( control.widgetControlEmbedded ) { return; } control.widgetControlEmbedded = true; widgetControl = $( control.params.widget_control ); control.container.append( widgetControl ); control._setupModel(); control._setupWideWidget(); control._setupControlToggle(); control._setupWidgetTitle(); control._setupReorderUI(); control._setupHighlightEffects(); control._setupUpdateUI(); control._setupRemoveUI(); }, /** * Embed the actual widget form inside of .widget-content and finally trigger the widget-added event. * * @since 4.4.0 */ embedWidgetContent: function() { var control = this, widgetContent; control.embedWidgetControl(); if ( control.widgetContentEmbedded ) { return; } control.widgetContentEmbedded = true; widgetContent = $( control.params.widget_content ); control.container.find( '.widget-content:first' ).append( widgetContent ); /* * Trigger widget-added event so that plugins can attach any event * listeners and dynamic UI elements. */ $( document ).trigger( 'widget-added', [ control.container.find( '.widget:first' ) ] ); }, /** * Handle changes to the setting */ _setupModel: function() { var self = this, rememberSavedWidgetId; // Remember saved widgets so we know which to trash (move to inactive widgets sidebar) rememberSavedWidgetId = function() { api.Widgets.savedWidgetIds[self.params.widget_id] = true; }; api.bind( 'ready', rememberSavedWidgetId ); api.bind( 'saved', rememberSavedWidgetId ); this._updateCount = 0; this.isWidgetUpdating = false; this.liveUpdateMode = true; // Update widget whenever model changes this.setting.bind( function( to, from ) { if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) { self.updateWidget( { instance: to } ); } } ); }, /** * Add special behaviors for wide widget controls */ _setupWideWidget: function() { var self = this, $widgetInside, $widgetForm, $customizeSidebar, $themeControlsContainer, positionWidget; if ( ! this.params.is_wide ) { return; } $widgetInside = this.container.find( '.widget-inside' ); $widgetForm = $widgetInside.find( '> .form' ); $customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' ); this.container.addClass( 'wide-widget-control' ); this.container.find( '.widget-content:first' ).css( { 'max-width': this.params.width, 'min-height': this.params.height } ); /** * Keep the widget-inside positioned so the top of fixed-positioned * element is at the same top position as the widget-top. When the * widget-top is scrolled out of view, keep the widget-top in view; * likewise, don't allow the widget to drop off the bottom of the window. * If a widget is too tall to fit in the window, don't let the height * exceed the window height so that the contents of the widget control * will become scrollable (overflow:auto). */ positionWidget = function() { var offsetTop = self.container.offset().top, windowHeight = $( window ).height(), formHeight = $widgetForm.outerHeight(), top; $widgetInside.css( 'max-height', windowHeight ); top = Math.max( 0, // prevent top from going off screen Math.min( Math.max( offsetTop, 0 ), // distance widget in panel is from top of screen windowHeight - formHeight // flush up against bottom of screen ) ); $widgetInside.css( 'top', top ); }; $themeControlsContainer = $( '#customize-theme-controls' ); this.container.on( 'expand', function() { positionWidget(); $customizeSidebar.on( 'scroll', positionWidget ); $( window ).on( 'resize', positionWidget ); $themeControlsContainer.on( 'expanded collapsed', positionWidget ); } ); this.container.on( 'collapsed', function() { $customizeSidebar.off( 'scroll', positionWidget ); $( window ).off( 'resize', positionWidget ); $themeControlsContainer.off( 'expanded collapsed', positionWidget ); } ); // Reposition whenever a sidebar's widgets are changed api.each( function( setting ) { if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) { setting.bind( function() { if ( self.container.hasClass( 'expanded' ) ) { positionWidget(); } } ); } } ); }, /** * Show/hide the control when clicking on the form title, when clicking * the close button */ _setupControlToggle: function() { var self = this, $closeBtn; this.container.find( '.widget-top' ).on( 'click', function( e ) { e.preventDefault(); var sidebarWidgetsControl = self.getSidebarWidgetsControl(); if ( sidebarWidgetsControl.isReordering ) { return; } self.expanded( ! self.expanded() ); } ); $closeBtn = this.container.find( '.widget-control-close' ); $closeBtn.on( 'click', function( e ) { e.preventDefault(); self.collapse(); self.container.find( '.widget-top .widget-action:first' ).focus(); // keyboard accessibility } ); }, /** * Update the title of the form if a title field is entered */ _setupWidgetTitle: function() { var self = this, updateTitle; updateTitle = function() { var title = self.setting().title, inWidgetTitle = self.container.find( '.in-widget-title' ); if ( title ) { inWidgetTitle.text( ': ' + title ); } else { inWidgetTitle.text( '' ); } }; this.setting.bind( updateTitle ); updateTitle(); }, /** * Set up the widget-reorder-nav */ _setupReorderUI: function() { var self = this, selectSidebarItem, $moveWidgetArea, $reorderNav, updateAvailableSidebars, template; /** * select the provided sidebar list item in the move widget area * * @param {jQuery} li */ selectSidebarItem = function( li ) { li.siblings( '.selected' ).removeClass( 'selected' ); li.addClass( 'selected' ); var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id ); self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar ); }; /** * Add the widget reordering elements to the widget control */ this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) ); template = _.template( api.Widgets.data.tpl.moveWidgetArea ); $moveWidgetArea = $( template( { sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' ) } ) ); this.container.find( '.widget-top' ).after( $moveWidgetArea ); /** * Update available sidebars when their rendered state changes */ updateAvailableSidebars = function() { var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem, renderedSidebarCount = 0; selfSidebarItem = $sidebarItems.filter( function(){ return $( this ).data( 'id' ) === self.params.sidebar_id; } ); $sidebarItems.each( function() { var li = $( this ), sidebarId, sidebar, sidebarIsRendered; sidebarId = li.data( 'id' ); sidebar = api.Widgets.registeredSidebars.get( sidebarId ); sidebarIsRendered = sidebar.get( 'is_rendered' ); li.toggle( sidebarIsRendered ); if ( sidebarIsRendered ) { renderedSidebarCount += 1; } if ( li.hasClass( 'selected' ) && ! sidebarIsRendered ) { selectSidebarItem( selfSidebarItem ); } } ); if ( renderedSidebarCount > 1 ) { self.container.find( '.move-widget' ).show(); } else { self.container.find( '.move-widget' ).hide(); } }; updateAvailableSidebars(); api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars ); /** * Handle clicks for up/down/move on the reorder nav */ $reorderNav = this.container.find( '.widget-reorder-nav' ); $reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() { $( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' ); } ).on( 'click keypress', function( event ) { if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) { return; } $( this ).focus(); if ( $( this ).is( '.move-widget' ) ) { self.toggleWidgetMoveArea(); } else { var isMoveDown = $( this ).is( '.move-widget-down' ), isMoveUp = $( this ).is( '.move-widget-up' ), i = self.getWidgetSidebarPosition(); if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) { return; } if ( isMoveUp ) { self.moveUp(); wp.a11y.speak( l10n.widgetMovedUp ); } else { self.moveDown(); wp.a11y.speak( l10n.widgetMovedDown ); } $( this ).focus(); // re-focus after the container was moved } } ); /** * Handle selecting a sidebar to move to */ this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( event ) { if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) { return; } event.preventDefault(); selectSidebarItem( $( this ) ); } ); /** * Move widget to another sidebar */ this.container.find( '.move-widget-btn' ).click( function() { self.getSidebarWidgetsControl().toggleReordering( false ); var oldSidebarId = self.params.sidebar_id, newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ), oldSidebarWidgetsSetting, newSidebarWidgetsSetting, oldSidebarWidgetIds, newSidebarWidgetIds, i; oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' ); newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' ); oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() ); newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() ); i = self.getWidgetSidebarPosition(); oldSidebarWidgetIds.splice( i, 1 ); newSidebarWidgetIds.push( self.params.widget_id ); oldSidebarWidgetsSetting( oldSidebarWidgetIds ); newSidebarWidgetsSetting( newSidebarWidgetIds ); self.focus(); } ); }, /** * Highlight widgets in preview when interacted with in the Customizer */ _setupHighlightEffects: function() { var self = this; // Highlight whenever hovering or clicking over the form this.container.on( 'mouseenter click', function() { self.setting.previewer.send( 'highlight-widget', self.params.widget_id ); } ); // Highlight when the setting is updated this.setting.bind( function() { self.setting.previewer.send( 'highlight-widget', self.params.widget_id ); } ); }, /** * Set up event handlers for widget updating */ _setupUpdateUI: function() { var self = this, $widgetRoot, $widgetContent, $saveBtn, updateWidgetDebounced, formSyncHandler; $widgetRoot = this.container.find( '.widget:first' ); $widgetContent = $widgetRoot.find( '.widget-content:first' ); // Configure update button $saveBtn = this.container.find( '.widget-control-save' ); $saveBtn.val( l10n.saveBtnLabel ); $saveBtn.attr( 'title', l10n.saveBtnTooltip ); $saveBtn.removeClass( 'button-primary' ); $saveBtn.on( 'click', function( e ) { e.preventDefault(); self.updateWidget( { disable_form: true } ); // @todo disable_form is unused? } ); updateWidgetDebounced = _.debounce( function() { self.updateWidget(); }, 250 ); // Trigger widget form update when hitting Enter within an input $widgetContent.on( 'keydown', 'input', function( e ) { if ( 13 === e.which ) { // Enter e.preventDefault(); self.updateWidget( { ignoreActiveElement: true } ); } } ); // Handle widgets that support live previews $widgetContent.on( 'change input propertychange', ':input', function( e ) { if ( ! self.liveUpdateMode ) { return; } if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) { updateWidgetDebounced(); } } ); // Remove loading indicators when the setting is saved and the preview updates this.setting.previewer.channel.bind( 'synced', function() { self.container.removeClass( 'previewer-loading' ); } ); api.previewer.bind( 'widget-updated', function( updatedWidgetId ) { if ( updatedWidgetId === self.params.widget_id ) { self.container.removeClass( 'previewer-loading' ); } } ); formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ]; if ( formSyncHandler ) { $( document ).on( 'widget-synced', function( e, widget ) { if ( $widgetRoot.is( widget ) ) { formSyncHandler.apply( document, arguments ); } } ); } }, /** * Update widget control to indicate whether it is currently rendered. * * Overrides api.Control.toggle() * * @since 4.1.0 * * @param {Boolean} active * @param {Object} args * @param {Callback} args.completeCallback */ onChangeActive: function ( active, args ) { // Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments this.container.toggleClass( 'widget-rendered', active ); if ( args.completeCallback ) { args.completeCallback(); } }, /** * Set up event handlers for widget removal */ _setupRemoveUI: function() { var self = this, $removeBtn, replaceDeleteWithRemove; // Configure remove button $removeBtn = this.container.find( 'a.widget-control-remove' ); $removeBtn.on( 'click', function( e ) { e.preventDefault(); // Find an adjacent element to add focus to when this widget goes away var $adjacentFocusTarget; if ( self.container.next().is( '.customize-control-widget_form' ) ) { $adjacentFocusTarget = self.container.next().find( '.widget-action:first' ); } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) { $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' ); } else { $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' ); } self.container.slideUp( function() { var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ), sidebarWidgetIds, i; if ( ! sidebarsWidgetsControl ) { return; } sidebarWidgetIds = sidebarsWidgetsControl.setting().slice(); i = _.indexOf( sidebarWidgetIds, self.params.widget_id ); if ( -1 === i ) { return; } sidebarWidgetIds.splice( i, 1 ); sidebarsWidgetsControl.setting( sidebarWidgetIds ); $adjacentFocusTarget.focus(); // keyboard accessibility } ); } ); replaceDeleteWithRemove = function() { $removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the link as "Delete" $removeBtn.attr( 'title', l10n.removeBtnTooltip ); }; if ( this.params.is_new ) { api.bind( 'saved', replaceDeleteWithRemove ); } else { replaceDeleteWithRemove(); } }, /** * Find all inputs in a widget container that should be considered when * comparing the loaded form with the sanitized form, whose fields will * be aligned to copy the sanitized over. The elements returned by this * are passed into this._getInputsSignature(), and they are iterated * over when copying sanitized values over to the form loaded. * * @param {jQuery} container element in which to look for inputs * @returns {jQuery} inputs * @private */ _getInputs: function( container ) { return $( container ).find( ':input[name]' ); }, /** * Iterate over supplied inputs and create a signature string for all of them together. * This string can be used to compare whether or not the form has all of the same fields. * * @param {jQuery} inputs * @returns {string} * @private */ _getInputsSignature: function( inputs ) { var inputsSignatures = _( inputs ).map( function( input ) { var $input = $( input ), signatureParts; if ( $input.is( ':checkbox, :radio' ) ) { signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ]; } else { signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ]; } return signatureParts.join( ',' ); } ); return inputsSignatures.join( ';' ); }, /** * Get the state for an input depending on its type. * * @param {jQuery|Element} input * @returns {string|boolean|array|*} * @private */ _getInputState: function( input ) { input = $( input ); if ( input.is( ':radio, :checkbox' ) ) { return input.prop( 'checked' ); } else if ( input.is( 'select[multiple]' ) ) { return input.find( 'option:selected' ).map( function () { return $( this ).val(); } ).get(); } else { return input.val(); } }, /** * Update an input's state based on its type. * * @param {jQuery|Element} input * @param {string|boolean|array|*} state * @private */ _setInputState: function ( input, state ) { input = $( input ); if ( input.is( ':radio, :checkbox' ) ) { input.prop( 'checked', state ); } else if ( input.is( 'select[multiple]' ) ) { if ( ! $.isArray( state ) ) { state = []; } else { // Make sure all state items are strings since the DOM value is a string state = _.map( state, function ( value ) { return String( value ); } ); } input.find( 'option' ).each( function () { $( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) ); } ); } else { input.val( state ); } }, /*********************************************************************** * Begin public API methods **********************************************************************/ /** * @return {wp.customize.controlConstructor.sidebar_widgets[]} */ getSidebarWidgetsControl: function() { var settingId, sidebarWidgetsControl; settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']'; sidebarWidgetsControl = api.control( settingId ); if ( ! sidebarWidgetsControl ) { return; } return sidebarWidgetsControl; }, /** * Submit the widget form via Ajax and get back the updated instance, * along with the new widget control form to render. * * @param {object} [args] * @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used * @param {Function|null} [args.complete=null] Function which is called when the request finishes. Context is bound to the control. First argument is any error. Following arguments are for success. * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element. */ updateWidget: function( args ) { var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent, updateNumber, params, data, $inputs, processing, jqxhr, isChanged; // The updateWidget logic requires that the form fields to be fully present. self.embedWidgetContent(); args = $.extend( { instance: null, complete: null, ignoreActiveElement: false }, args ); instanceOverride = args.instance; completeCallback = args.complete; this._updateCount += 1; updateNumber = this._updateCount; $widgetRoot = this.container.find( '.widget:first' ); $widgetContent = $widgetRoot.find( '.widget-content:first' ); // Remove a previous error message $widgetContent.find( '.widget-error' ).remove(); this.container.addClass( 'widget-form-loading' ); this.container.addClass( 'previewer-loading' ); processing = api.state( 'processing' ); processing( processing() + 1 ); if ( ! this.liveUpdateMode ) { this.container.addClass( 'widget-form-disabled' ); } params = {}; params.action = 'update-widget'; params.wp_customize = 'on'; params.nonce = api.settings.nonce['update-widget']; params.customize_theme = api.settings.theme.stylesheet; params.customized = wp.customize.previewer.query().customized; data = $.param( params ); $inputs = this._getInputs( $widgetContent ); // Store the value we're submitting in data so that when the response comes back, // we know if it got sanitized; if there is no difference in the sanitized value, // then we do not need to touch the UI and mess up the user's ongoing editing. $inputs.each( function() { $( this ).data( 'state' + updateNumber, self._getInputState( this ) ); } ); if ( instanceOverride ) { data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } ); } else { data += '&' + $inputs.serialize(); } data += '&' + $widgetContent.find( '~ :input' ).serialize(); if ( this._previousUpdateRequest ) { this._previousUpdateRequest.abort(); } jqxhr = $.post( wp.ajax.settings.url, data ); this._previousUpdateRequest = jqxhr; jqxhr.done( function( r ) { var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse, isLiveUpdateAborted = false; // Check if the user is logged out. if ( '0' === r ) { api.previewer.preview.iframe.hide(); api.previewer.login().done( function() { self.updateWidget( args ); api.previewer.preview.iframe.show(); } ); return; } // Check for cheaters. if ( '-1' === r ) { api.previewer.cheatin(); return; } if ( r.success ) { sanitizedForm = $( '<div>' + r.data.form + '</div>' ); $sanitizedInputs = self._getInputs( sanitizedForm ); hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs ); // Restore live update mode if sanitized fields are now aligned with the existing fields if ( hasSameInputsInResponse && ! self.liveUpdateMode ) { self.liveUpdateMode = true; self.container.removeClass( 'widget-form-disabled' ); self.container.find( 'input[name="savewidget"]' ).hide(); } // Sync sanitized field states to existing fields if they are aligned if ( hasSameInputsInResponse && self.liveUpdateMode ) { $inputs.each( function( i ) { var $input = $( this ), $sanitizedInput = $( $sanitizedInputs[i] ), submittedState, sanitizedState, canUpdateState; submittedState = $input.data( 'state' + updateNumber ); sanitizedState = self._getInputState( $sanitizedInput ); $input.data( 'sanitized', sanitizedState ); canUpdateState = ( ! _.isEqual( submittedState, sanitizedState ) && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) ); if ( canUpdateState ) { self._setInputState( $input, sanitizedState ); } } ); $( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] ); // Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled } else if ( self.liveUpdateMode ) { self.liveUpdateMode = false; self.container.find( 'input[name="savewidget"]' ).show(); isLiveUpdateAborted = true; // Otherwise, replace existing form with the sanitized form } else { $widgetContent.html( r.data.form ); self.container.removeClass( 'widget-form-disabled' ); $( document ).trigger( 'widget-updated', [ $widgetRoot ] ); } /** * If the old instance is identical to the new one, there is nothing new * needing to be rendered, and so we can preempt the event for the * preview finishing loading. */ isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance ); if ( isChanged ) { self.isWidgetUpdating = true; // suppress triggering another updateWidget self.setting( r.data.instance ); self.isWidgetUpdating = false; } else { // no change was made, so stop the spinner now instead of when the preview would updates self.container.removeClass( 'previewer-loading' ); } if ( completeCallback ) { completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } ); } } else { // General error message message = l10n.error; if ( r.data && r.data.message ) { message = r.data.message; } if ( completeCallback ) { completeCallback.call( self, message ); } else { $widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' ); } } } ); jqxhr.fail( function( jqXHR, textStatus ) { if ( completeCallback ) { completeCallback.call( self, textStatus ); } } ); jqxhr.always( function() { self.container.removeClass( 'widget-form-loading' ); $inputs.each( function() { $( this ).removeData( 'state' + updateNumber ); } ); processing( processing() - 1 ); } ); }, /** * Expand the accordion section containing a control */ expandControlSection: function() { api.Control.prototype.expand.call( this ); }, /** * @since 4.1.0 * * @param {Boolean} expanded * @param {Object} [params] * @returns {Boolean} false if state already applied */ _toggleExpanded: api.Section.prototype._toggleExpanded, /** * @since 4.1.0 * * @param {Object} [params] * @returns {Boolean} false if already expanded */ expand: api.Section.prototype.expand, /** * Expand the widget form control * * @deprecated 4.1.0 Use this.expand() instead. */ expandForm: function() { this.expand(); }, /** * @since 4.1.0 * * @param {Object} [params] * @returns {Boolean} false if already collapsed */ collapse: api.Section.prototype.collapse, /** * Collapse the widget form control * * @deprecated 4.1.0 Use this.collapse() instead. */ collapseForm: function() { this.collapse(); }, /** * Expand or collapse the widget control * * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide ) * * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility */ toggleForm: function( showOrHide ) { if ( typeof showOrHide === 'undefined' ) { showOrHide = ! this.expanded(); } this.expanded( showOrHide ); }, /** * Respond to change in the expanded state. * * @param {Boolean} expanded * @param {Object} args merged on top of this.defaultActiveArguments */ onChangeExpanded: function ( expanded, args ) { var self = this, $widget, $inside, complete, prevComplete, expandControl; self.embedWidgetControl(); // Make sure the outer form is embedded so that the expanded state can be set in the UI. if ( expanded ) { self.embedWidgetContent(); } // If the expanded state is unchanged only manipulate container expanded states if ( args.unchanged ) { if ( expanded ) { api.Control.prototype.expand.call( self, { completeCallback: args.completeCallback }); } return; } $widget = this.container.find( 'div.widget:first' ); $inside = $widget.find( '.widget-inside:first' ); expandControl = function() { // Close all other widget controls before expanding this one api.control.each( function( otherControl ) { if ( self.params.type === otherControl.params.type && self !== otherControl ) { otherControl.collapse(); } } ); complete = function() { self.container.removeClass( 'expanding' ); self.container.addClass( 'expanded' ); self.container.trigger( 'expanded' ); }; if ( args.completeCallback ) { prevComplete = complete; complete = function () { prevComplete(); args.completeCallback(); }; } if ( self.params.is_wide ) { $inside.fadeIn( args.duration, complete ); } else { $inside.slideDown( args.duration, complete ); } self.container.trigger( 'expand' ); self.container.addClass( 'expanding' ); }; if ( expanded ) { if ( api.section.has( self.section() ) ) { api.section( self.section() ).expand( { completeCallback: expandControl } ); } else { expandControl(); } } else { complete = function() { self.container.removeClass( 'collapsing' ); self.container.removeClass( 'expanded' ); self.container.trigger( 'collapsed' ); }; if ( args.completeCallback ) { prevComplete = complete; complete = function () { prevComplete(); args.completeCallback(); }; } self.container.trigger( 'collapse' ); self.container.addClass( 'collapsing' ); if ( self.params.is_wide ) { $inside.fadeOut( args.duration, complete ); } else { $inside.slideUp( args.duration, function() { $widget.css( { width:'', margin:'' } ); complete(); } ); } } }, /** * Get the position (index) of the widget in the containing sidebar * * @returns {Number} */ getWidgetSidebarPosition: function() { var sidebarWidgetIds, position; sidebarWidgetIds = this.getSidebarWidgetsControl().setting(); position = _.indexOf( sidebarWidgetIds, this.params.widget_id ); if ( position === -1 ) { return; } return position; }, /** * Move widget up one in the sidebar */ moveUp: function() { this._moveWidgetByOne( -1 ); }, /** * Move widget up one in the sidebar */ moveDown: function() { this._moveWidgetByOne( 1 ); }, /** * @private * * @param {Number} offset 1|-1 */ _moveWidgetByOne: function( offset ) { var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId; i = this.getWidgetSidebarPosition(); sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting; sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // clone adjacentWidgetId = sidebarWidgetIds[i + offset]; sidebarWidgetIds[i + offset] = this.params.widget_id; sidebarWidgetIds[i] = adjacentWidgetId; sidebarWidgetsSetting( sidebarWidgetIds ); }, /** * Toggle visibility of the widget move area * * @param {Boolean} [showOrHide] */ toggleWidgetMoveArea: function( showOrHide ) { var self = this, $moveWidgetArea; $moveWidgetArea = this.container.find( '.move-widget-area' ); if ( typeof showOrHide === 'undefined' ) { showOrHide = ! $moveWidgetArea.hasClass( 'active' ); } if ( showOrHide ) { // reset the selected sidebar $moveWidgetArea.find( '.selected' ).removeClass( 'selected' ); $moveWidgetArea.find( 'li' ).filter( function() { return $( this ).data( 'id' ) === self.params.sidebar_id; } ).addClass( 'selected' ); this.container.find( '.move-widget-btn' ).prop( 'disabled', true ); } $moveWidgetArea.toggleClass( 'active', showOrHide ); }, /** * Highlight the widget control and section */ highlightSectionAndControl: function() { var $target; if ( this.container.is( ':hidden' ) ) { $target = this.container.closest( '.control-section' ); } else { $target = this.container; } $( '.highlighted' ).removeClass( 'highlighted' ); $target.addClass( 'highlighted' ); setTimeout( function() { $target.removeClass( 'highlighted' ); }, 500 ); } } ); /** * wp.customize.Widgets.WidgetsPanel * * Customizer panel containing the widget area sections. * * @since 4.4.0 */ api.Widgets.WidgetsPanel = api.Panel.extend({ /** * Add and manage the display of the no-rendered-areas notice. * * @since 4.4.0 */ ready: function () { var panel = this; api.Panel.prototype.ready.call( panel ); panel.deferred.embedded.done(function() { var panelMetaContainer, noRenderedAreasNotice, shouldShowNotice; panelMetaContainer = panel.container.find( '.panel-meta' ); noRenderedAreasNotice = $( '<div></div>', { 'class': 'no-widget-areas-rendered-notice' }); noRenderedAreasNotice.append( $( '<em></em>', { text: l10n.noAreasRendered } ) ); panelMetaContainer.append( noRenderedAreasNotice ); shouldShowNotice = function() { return ( 0 === _.filter( panel.sections(), function( section ) { return section.active(); } ).length ); }; /* * Set the initial visibility state for rendered notice. * Update the visibility of the notice whenever a reflow happens. */ noRenderedAreasNotice.toggle( shouldShowNotice() ); api.previewer.deferred.active.done( function () { noRenderedAreasNotice.toggle( shouldShowNotice() ); }); api.bind( 'pane-contents-reflowed', function() { var duration = ( 'resolved' === api.previewer.deferred.active.state() ) ? 'fast' : 0; if ( shouldShowNotice() ) { noRenderedAreasNotice.slideDown( duration ); } else { noRenderedAreasNotice.slideUp( duration ); } }); }); }, /** * Allow an active widgets panel to be contextually active even when it has no active sections (widget areas). * * This ensures that the widgets panel appears even when there are no * sidebars displayed on the URL currently being previewed. * * @since 4.4.0 * * @returns {boolean} */ isContextuallyActive: function() { var panel = this; return panel.active(); } }); /** * wp.customize.Widgets.SidebarSection * * Customizer section representing a widget area widget * * @since 4.1.0 */ api.Widgets.SidebarSection = api.Section.extend({ /** * Sync the section's active state back to the Backbone model's is_rendered attribute * * @since 4.1.0 */ ready: function () { var section = this, registeredSidebar; api.Section.prototype.ready.call( this ); registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId ); section.active.bind( function ( active ) { registeredSidebar.set( 'is_rendered', active ); }); registeredSidebar.set( 'is_rendered', section.active() ); } }); /** * wp.customize.Widgets.SidebarControl * * Customizer control for widgets. * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type * * @since 3.9.0 * * @constructor * @augments wp.customize.Control */ api.Widgets.SidebarControl = api.Control.extend({ /** * Set up the control */ ready: function() { this.$controlSection = this.container.closest( '.control-section' ); this.$sectionContent = this.container.closest( '.accordion-section-content' ); this._setupModel(); this._setupSortable(); this._setupAddition(); this._applyCardinalOrderClassNames(); }, /** * Update ordering of widget control forms when the setting is updated */ _setupModel: function() { var self = this; this.setting.bind( function( newWidgetIds, oldWidgetIds ) { var widgetFormControls, removedWidgetIds, priority; removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds ); // Filter out any persistent widget IDs for widgets which have been deactivated newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) { var parsedWidgetId = parseWidgetId( newWidgetId ); return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } ); } ); widgetFormControls = _( newWidgetIds ).map( function( widgetId ) { var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId ); if ( ! widgetFormControl ) { widgetFormControl = self.addWidget( widgetId ); } return widgetFormControl; } ); // Sort widget controls to their new positions widgetFormControls.sort( function( a, b ) { var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ), bIndex = _.indexOf( newWidgetIds, b.params.widget_id ); return aIndex - bIndex; }); priority = 0; _( widgetFormControls ).each( function ( control ) { control.priority( priority ); control.section( self.section() ); priority += 1; }); self.priority( priority ); // Make sure sidebar control remains at end // Re-sort widget form controls (including widgets form other sidebars newly moved here) self._applyCardinalOrderClassNames(); // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated _( widgetFormControls ).each( function( widgetFormControl ) { widgetFormControl.params.sidebar_id = self.params.sidebar_id; } ); // Cleanup after widget removal _( removedWidgetIds ).each( function( removedWidgetId ) { // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update setTimeout( function() { var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase, widget, isPresentInAnotherSidebar = false; // Check if the widget is in another sidebar api.each( function( otherSetting ) { if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) { return; } var otherSidebarWidgets = otherSetting(), i; i = _.indexOf( otherSidebarWidgets, removedWidgetId ); if ( -1 !== i ) { isPresentInAnotherSidebar = true; } } ); // If the widget is present in another sidebar, abort! if ( isPresentInAnotherSidebar ) { return; } removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId ); // Detect if widget control was dragged to another sidebar wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] ); // Delete any widget form controls for removed widgets if ( removedControl && ! wasDraggedToAnotherSidebar ) { api.control.remove( removedControl.id ); removedControl.container.remove(); } // Move widget to inactive widgets sidebar (move it to trash) if has been previously saved // This prevents the inactive widgets sidebar from overflowing with throwaway widgets if ( api.Widgets.savedWidgetIds[removedWidgetId] ) { inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice(); inactiveWidgets.push( removedWidgetId ); api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() ); } // Make old single widget available for adding again removedIdBase = parseWidgetId( removedWidgetId ).id_base; widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } ); if ( widget && ! widget.get( 'is_multi' ) ) { widget.set( 'is_disabled', false ); } } ); } ); } ); }, /** * Allow widgets in sidebar to be re-ordered, and for the order to be previewed */ _setupSortable: function() { var self = this; this.isReordering = false; /** * Update widget order setting when controls are re-ordered */ this.$sectionContent.sortable( { items: '> .customize-control-widget_form', handle: '.widget-top', axis: 'y', tolerance: 'pointer', connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)', update: function() { var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds; widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) { return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val(); } ); self.setting( widgetIds ); } } ); /** * Expand other Customizer sidebar section when dragging a control widget over it, * allowing the control to be dropped into another section */ this.$controlSection.find( '.accordion-section-title' ).droppable({ accept: '.customize-control-widget_form', over: function() { var section = api.section( self.section.get() ); section.expand({ allowMultiple: true, // Prevent the section being dragged from to be collapsed completeCallback: function () { // @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed api.section.each( function ( otherSection ) { if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) { otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' ); } } ); } }); } }); /** * Keyboard-accessible reordering */ this.container.find( '.reorder-toggle' ).on( 'click', function() { self.toggleReordering( ! self.isReordering ); } ); }, /** * Set up UI for adding a new widget */ _setupAddition: function() { var self = this; this.container.find( '.add-new-widget' ).on( 'click', function() { var addNewWidgetBtn = $( this ); if ( self.$sectionContent.hasClass( 'reordering' ) ) { return; } if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) { addNewWidgetBtn.attr( 'aria-expanded', 'true' ); api.Widgets.availableWidgetsPanel.open( self ); } else { addNewWidgetBtn.attr( 'aria-expanded', 'false' ); api.Widgets.availableWidgetsPanel.close(); } } ); }, /** * Add classes to the widget_form controls to assist with styling */ _applyCardinalOrderClassNames: function() { var widgetControls = []; _.each( this.setting(), function ( widgetId ) { var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId ); if ( widgetControl ) { widgetControls.push( widgetControl ); } }); if ( 0 === widgetControls.length || ( 1 === api.Widgets.registeredSidebars.length && widgetControls.length <= 1 ) ) { this.container.find( '.reorder-toggle' ).hide(); return; } else { this.container.find( '.reorder-toggle' ).show(); } $( widgetControls ).each( function () { $( this.container ) .removeClass( 'first-widget' ) .removeClass( 'last-widget' ) .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 ); }); _.first( widgetControls ).container .addClass( 'first-widget' ) .find( '.move-widget-up' ).prop( 'tabIndex', -1 ); _.last( widgetControls ).container .addClass( 'last-widget' ) .find( '.move-widget-down' ).prop( 'tabIndex', -1 ); }, /*********************************************************************** * Begin public API methods **********************************************************************/ /** * Enable/disable the reordering UI * * @param {Boolean} showOrHide to enable/disable reordering * * @todo We should have a reordering state instead and rename this to onChangeReordering */ toggleReordering: function( showOrHide ) { var addNewWidgetBtn = this.$sectionContent.find( '.add-new-widget' ), reorderBtn = this.container.find( '.reorder-toggle' ), widgetsTitle = this.$sectionContent.find( '.widget-title' ); showOrHide = Boolean( showOrHide ); if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) { return; } this.isReordering = showOrHide; this.$sectionContent.toggleClass( 'reordering', showOrHide ); if ( showOrHide ) { _( this.getWidgetFormControls() ).each( function( formControl ) { formControl.collapse(); } ); addNewWidgetBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' }); reorderBtn.attr( 'aria-label', l10n.reorderLabelOff ); wp.a11y.speak( l10n.reorderModeOn ); // Hide widget titles while reordering: title is already in the reorder controls. widgetsTitle.attr( 'aria-hidden', 'true' ); } else { addNewWidgetBtn.removeAttr( 'tabindex aria-hidden' ); reorderBtn.attr( 'aria-label', l10n.reorderLabelOn ); wp.a11y.speak( l10n.reorderModeOff ); widgetsTitle.attr( 'aria-hidden', 'false' ); } }, /** * Get the widget_form Customize controls associated with the current sidebar. * * @since 3.9.0 * @return {wp.customize.controlConstructor.widget_form[]} */ getWidgetFormControls: function() { var formControls = []; _( this.setting() ).each( function( widgetId ) { var settingId = widgetIdToSettingId( widgetId ), formControl = api.control( settingId ); if ( formControl ) { formControls.push( formControl ); } } ); return formControls; }, /** * @param {string} widgetId or an id_base for adding a previously non-existing widget * @returns {object|false} widget_form control instance, or false on error */ addWidget: function( widgetId ) { var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor, parsedWidgetId = parseWidgetId( widgetId ), widgetNumber = parsedWidgetId.number, widgetIdBase = parsedWidgetId.id_base, widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ), settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting; if ( ! widget ) { return false; } if ( widgetNumber && ! widget.get( 'is_multi' ) ) { return false; } // Set up new multi widget if ( widget.get( 'is_multi' ) && ! widgetNumber ) { widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 ); widgetNumber = widget.get( 'multi_number' ); } controlHtml = $.trim( $( '#widget-tpl-' + widget.get( 'id' ) ).html() ); if ( widget.get( 'is_multi' ) ) { controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) { return m.replace( /__i__|%i%/g, widgetNumber ); } ); } else { widget.set( 'is_disabled', true ); // Prevent single widget from being added again now } $widget = $( controlHtml ); controlContainer = $( '<li/>' ) .addClass( 'customize-control' ) .addClass( 'customize-control-' + controlType ) .append( $widget ); // Remove icon which is visible inside the panel controlContainer.find( '> .widget-icon' ).remove(); if ( widget.get( 'is_multi' ) ) { controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber ); controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber ); } widgetId = controlContainer.find( '[name="widget-id"]' ).val(); controlContainer.hide(); // to be slid-down below settingId = 'widget_' + widget.get( 'id_base' ); if ( widget.get( 'is_multi' ) ) { settingId += '[' + widgetNumber + ']'; } controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) ); // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget) isExistingWidget = api.has( settingId ); if ( ! isExistingWidget ) { settingArgs = { transport: api.Widgets.data.selectiveRefreshableWidgets[ widget.get( 'id_base' ) ] ? 'postMessage' : 'refresh', previewer: this.setting.previewer }; setting = api.create( settingId, settingId, '', settingArgs ); setting.set( {} ); // mark dirty, changing from '' to {} } controlConstructor = api.controlConstructor[controlType]; widgetFormControl = new controlConstructor( settingId, { params: { settings: { 'default': settingId }, content: controlContainer, sidebar_id: self.params.sidebar_id, widget_id: widgetId, widget_id_base: widget.get( 'id_base' ), type: controlType, is_new: ! isExistingWidget, width: widget.get( 'width' ), height: widget.get( 'height' ), is_wide: widget.get( 'is_wide' ), active: true }, previewer: self.setting.previewer } ); api.control.add( settingId, widgetFormControl ); // Make sure widget is removed from the other sidebars api.each( function( otherSetting ) { if ( otherSetting.id === self.setting.id ) { return; } if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) { return; } var otherSidebarWidgets = otherSetting().slice(), i = _.indexOf( otherSidebarWidgets, widgetId ); if ( -1 !== i ) { otherSidebarWidgets.splice( i ); otherSetting( otherSidebarWidgets ); } } ); // Add widget to this sidebar sidebarWidgets = this.setting().slice(); if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) { sidebarWidgets.push( widgetId ); this.setting( sidebarWidgets ); } controlContainer.slideDown( function() { if ( isExistingWidget ) { widgetFormControl.updateWidget( { instance: widgetFormControl.setting() } ); } } ); return widgetFormControl; } } ); // Register models for custom panel, section, and control types $.extend( api.panelConstructor, { widgets: api.Widgets.WidgetsPanel }); $.extend( api.sectionConstructor, { sidebar: api.Widgets.SidebarSection }); $.extend( api.controlConstructor, { widget_form: api.Widgets.WidgetControl, sidebar_widgets: api.Widgets.SidebarControl }); /** * Init Customizer for widgets. */ api.bind( 'ready', function() { // Set up the widgets panel api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({ collection: api.Widgets.availableWidgets }); // Highlight widget control api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl ); // Open and focus widget control api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl ); } ); /** * Highlight a widget control. * * @param {string} widgetId */ api.Widgets.highlightWidgetFormControl = function( widgetId ) { var control = api.Widgets.getWidgetFormControlForWidget( widgetId ); if ( control ) { control.highlightSectionAndControl(); } }, /** * Focus a widget control. * * @param {string} widgetId */ api.Widgets.focusWidgetFormControl = function( widgetId ) { var control = api.Widgets.getWidgetFormControlForWidget( widgetId ); if ( control ) { control.focus(); } }, /** * Given a widget control, find the sidebar widgets control that contains it. * @param {string} widgetId * @return {object|null} */ api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) { var foundControl = null; // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl() api.control.each( function( control ) { if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) { foundControl = control; } } ); return foundControl; }; /** * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it. * * @param {string} widgetId * @return {object|null} */ api.Widgets.getWidgetFormControlForWidget = function( widgetId ) { var foundControl = null; // @todo We can just use widgetIdToSettingId() here api.control.each( function( control ) { if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) { foundControl = control; } } ); return foundControl; }; /** * Initialize Edit Menu button in Nav Menu widget. */ $( document ).on( 'widget-added', function( event, widgetContainer ) { var parsedWidgetId, widgetControl, navMenuSelect, editMenuButton; parsedWidgetId = parseWidgetId( widgetContainer.find( '> .widget-inside > .form > .widget-id' ).val() ); if ( 'nav_menu' !== parsedWidgetId.id_base ) { return; } widgetControl = api.control( 'widget_nav_menu[' + String( parsedWidgetId.number ) + ']' ); if ( ! widgetControl ) { return; } navMenuSelect = widgetContainer.find( 'select[name*="nav_menu"]' ); editMenuButton = widgetContainer.find( '.edit-selected-nav-menu > button' ); if ( 0 === navMenuSelect.length || 0 === editMenuButton.length ) { return; } navMenuSelect.on( 'change', function() { if ( api.section.has( 'nav_menu[' + navMenuSelect.val() + ']' ) ) { editMenuButton.parent().show(); } else { editMenuButton.parent().hide(); } }); editMenuButton.on( 'click', function() { var section = api.section( 'nav_menu[' + navMenuSelect.val() + ']' ); if ( section ) { focusConstructWithBreadcrumb( section, widgetControl ); } } ); } ); /** * Focus (expand) one construct and then focus on another construct after the first is collapsed. * * This overrides the back button to serve the purpose of breadcrumb navigation. * * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} focusConstruct - The object to initially focus. * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} returnConstruct - The object to return focus. */ function focusConstructWithBreadcrumb( focusConstruct, returnConstruct ) { focusConstruct.focus(); function onceCollapsed( isExpanded ) { if ( ! isExpanded ) { focusConstruct.expanded.unbind( onceCollapsed ); returnConstruct.focus(); } } focusConstruct.expanded.bind( onceCollapsed ); } /** * @param {String} widgetId * @returns {Object} */ function parseWidgetId( widgetId ) { var matches, parsed = { number: null, id_base: null }; matches = widgetId.match( /^(.+)-(\d+)$/ ); if ( matches ) { parsed.id_base = matches[1]; parsed.number = parseInt( matches[2], 10 ); } else { // likely an old single widget parsed.id_base = widgetId; } return parsed; } /** * @param {String} widgetId * @returns {String} settingId */ function widgetIdToSettingId( widgetId ) { var parsed = parseWidgetId( widgetId ), settingId; settingId = 'widget_' + parsed.id_base; if ( parsed.number ) { settingId += '[' + parsed.number + ']'; } return settingId; } })( window.wp, jQuery ); theme.min.js 0000666 00000061142 15213733063 0007001 0 ustar 00 var tb_position;window.wp=window.wp||{},function(a){var n,o=wp.themes=wp.themes||{};o.data=_wpThemeSettings,n=o.data.l10n,o.isInstall=!!o.data.settings.isInstall,_.extend(o,{model:{},view:{},routes:{},router:{},template:wp.template}),o.Model=Backbone.Model.extend({initialize:function(){var e;-1!==_.indexOf(o.data.installedThemes,this.get("slug"))&&this.set({installed:!0}),this.set({id:this.get("slug")||this.get("id")}),this.has("sections")&&(e=this.get("sections").description,this.set({description:e}))}}),o.view.Appearance=wp.Backbone.View.extend({el:"#wpbody-content .wrap .theme-browser",window:a(window),page:0,initialize:function(e){_.bindAll(this,"scroller"),this.SearchView=e.SearchView||o.view.Search,this.window.bind("scroll",_.throttle(this.scroller,300))},render:function(){this.view=new o.view.Themes({collection:this.collection,parent:this}),this.search(),this.view.render(),this.$el.empty().append(this.view.el).addClass("rendered")},searchContainer:a("#wpbody h1:first"),search:function(){var e;1!==o.data.themes.length&&((e=new this.SearchView({collection:this.collection,parent:this})).render(),this.searchContainer.append(a.parseHTML('<label class="screen-reader-text" for="wp-filter-search-input">'+n.search+"</label>")).append(e.el))},scroller:function(){var e=this,t=this.window.scrollTop()+e.window.height(),e=e.$el.offset().top+e.$el.outerHeight(!1)-e.window.height();Math.round(.9*e)<t&&this.trigger("theme:scroll")}}),o.Collection=Backbone.Collection.extend({model:o.Model,terms:"",doSearch:function(e){this.terms!==e&&(this.terms=e,0<this.terms.length&&this.search(this.terms),""===this.terms&&(this.reset(o.data.themes),a("body").removeClass("no-results")),this.trigger("themes:update"))},search:function(t){var i,e,s,r,n;this.reset(o.data.themes,{silent:!0}),t=(t=t.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")).replace(/ /g,")(?=.*"),i=new RegExp("^(?=.*"+t+").+","i"),0===(e=this.filter(function(e){return s=e.get("name").replace(/(<([^>]+)>)/gi,""),r=e.get("description").replace(/(<([^>]+)>)/gi,""),n=e.get("author").replace(/(<([^>]+)>)/gi,""),n=_.union([s,e.get("id"),r,n,e.get("tags")]),i.test(e.get("author"))&&2<t.length&&e.set("displayAuthor",!0),i.test(n)})).length?this.trigger("query:empty"):a("body").removeClass("no-results"),this.reset(e)},paginate:function(e){var t=this;return e=e||0,t=_(t.rest(20*e)),t=_(t.first(20))},count:!1,query:function(t){var e,i,s,r=this.queries,n=this;if(this.currentQuery.request=t,e=_.find(r,function(e){return _.isEqual(e.request,t)}),(i=_.has(t,"page"))||(this.currentQuery.page=1),e||i){if(i)return this.apiCall(t,i).done(function(e){n.add(e.themes),n.trigger("query:success"),n.loadingThemes=!1}).fail(function(){n.trigger("query:fail")});0===e.themes.length?n.trigger("query:empty"):a("body").removeClass("no-results"),_.isNumber(e.total)&&(this.count=e.total),this.reset(e.themes),e.total||(this.count=this.length),this.trigger("themes:update"),this.trigger("query:success",this.count)}else e=this.apiCall(t).done(function(e){e.themes&&(n.reset(e.themes),s=e.info.results,r.push({themes:e.themes,request:t,total:s})),n.trigger("themes:update"),n.trigger("query:success",s),e.themes&&0===e.themes.length&&n.trigger("query:empty")}).fail(function(){n.trigger("query:fail")})},queries:[],currentQuery:{page:1,request:{}},apiCall:function(e,t){return wp.ajax.send("query-themes",{data:{request:_.extend({per_page:100,fields:{description:!0,tested:!0,requires:!0,rating:!0,downloaded:!0,downloadLink:!0,last_updated:!0,homepage:!0,num_ratings:!0}},e)},beforeSend:function(){t||a("body").addClass("loading-content").removeClass("no-results")}})},loadingThemes:!1}),o.view.Theme=wp.Backbone.View.extend({className:"theme",state:"grid",html:o.template("theme"),events:{click:o.isInstall?"preview":"expand",keydown:o.isInstall?"preview":"expand",touchend:o.isInstall?"preview":"expand",keyup:"addFocus",touchmove:"preventExpand","click .theme-install":"installTheme","click .update-message":"updateTheme"},touchDrag:!1,initialize:function(){this.model.on("change",this.render,this)},render:function(){var e=this.model.toJSON();this.$el.html(this.html(e)).attr({tabindex:0,"aria-describedby":e.id+"-action "+e.id+"-name","data-slug":e.id}),this.activeTheme(),this.model.get("displayAuthor")&&this.$el.addClass("display-author")},activeTheme:function(){this.model.get("active")&&this.$el.addClass("active")},addFocus:function(){var e=a(":focus").hasClass("theme")?a(":focus"):a(":focus").parents(".theme");a(".theme.focus").removeClass("focus"),e.addClass("focus")},expand:function(e){if("keydown"!==(e=e||window.event).type||13===e.which||32===e.which)return!0===this.touchDrag?this.touchDrag=!1:void(a(e.target).is(".theme-actions a")||a(e.target).is(".theme-actions a, .update-message, .button-link, .notice-dismiss")||(o.focusedTheme=this.$el,this.trigger("theme:expand",this.model.cid)))},preventExpand:function(){this.touchDrag=!0},preview:function(e){var t,i,s=this;if(e=e||window.event,!0===this.touchDrag)return this.touchDrag=!1;a(e.target).not(".install-theme-preview").parents(".theme-actions").length||"keydown"===e.type&&13!==e.which&&32!==e.which||"keydown"===e.type&&13!==e.which&&a(":focus").hasClass("button")||(e.preventDefault(),e=e||window.event,o.focusedTheme=this.$el,(i=new o.view.Preview({model:this.model})).render(),this.setNavButtonsState(),1===this.model.collection.length?i.$el.addClass("no-navigation"):i.$el.removeClass("no-navigation"),a("div.wrap").append(i.el),this.listenTo(i,"theme:next",function(){return t=s.model,_.isUndefined(s.current)||(t=s.current),s.current=s.model.collection.at(s.model.collection.indexOf(t)+1),_.isUndefined(s.current)?(s.options.parent.parent.trigger("theme:end"),s.current=t):(i.model=s.current,i.render(),this.setNavButtonsState(),void a(".next-theme").focus())}).listenTo(i,"theme:previous",function(){t=s.model,0!==s.model.collection.indexOf(s.current)&&(_.isUndefined(s.current)||(t=s.current),s.current=s.model.collection.at(s.model.collection.indexOf(t)-1),_.isUndefined(s.current)||(i.model=s.current,i.render(),this.setNavButtonsState(),a(".previous-theme").focus()))}),this.listenTo(i,"preview:close",function(){s.current=s.model}))},setNavButtonsState:function(){var e=a(".theme-install-overlay"),t=_.isUndefined(this.current)?this.model:this.current;0===this.model.collection.indexOf(t)&&e.find(".previous-theme").addClass("disabled"),_.isUndefined(this.model.collection.at(this.model.collection.indexOf(t)+1))&&e.find(".next-theme").addClass("disabled")},installTheme:function(e){var i=this;e.preventDefault(),wp.updates.maybeRequestFilesystemCredentials(e),a(document).on("wp-theme-install-success",function(e,t){i.model.get("id")===t.slug&&i.model.set({installed:!0})}),wp.updates.installTheme({slug:a(e.target).data("slug")})},updateTheme:function(e){var i=this;this.model.get("hasPackage")&&(e.preventDefault(),wp.updates.maybeRequestFilesystemCredentials(e),a(document).on("wp-theme-update-success",function(e,t){i.model.off("change",i.render,i),i.model.get("id")===t.slug&&i.model.set({hasUpdate:!1,version:t.newVersion}),i.model.on("change",i.render,i)}),wp.updates.updateTheme({slug:a(e.target).parents("div.theme").first().data("slug")}))}}),o.view.Details=wp.Backbone.View.extend({className:"theme-overlay",events:{click:"collapse","click .delete-theme":"deleteTheme","click .left":"previousTheme","click .right":"nextTheme","click #update-theme":"updateTheme"},html:o.template("theme-single"),render:function(){var e=this.model.toJSON();this.$el.html(this.html(e)),this.activeTheme(),this.navigation(),this.screenshotCheck(this.$el),this.containFocus(this.$el)},activeTheme:function(){this.$el.toggleClass("active",this.model.get("active"))},containFocus:function(s){_.delay(function(){a(".theme-wrap a.button-primary:visible").focus()},100),s.on("keydown.wp-themes",function(e){var t=s.find(".theme-header button:not(.disabled)").first(),i=s.find(".theme-actions a:visible").last();9===e.which&&(t[0]===e.target&&e.shiftKey?(i.focus(),e.preventDefault()):i[0]!==e.target||e.shiftKey||(t.focus(),e.preventDefault()))})},collapse:function(e){var t,i=this;e=e||window.event,1!==o.data.themes.length&&(a(e.target).is(".theme-backdrop")||a(e.target).is(".close")||27===e.keyCode)&&(a("body").addClass("closing-overlay"),this.$el.fadeOut(130,function(){a("body").removeClass("closing-overlay"),i.closeOverlay(),t=document.body.scrollTop,o.router.navigate(o.router.baseUrl("")),document.body.scrollTop=t,o.focusedTheme&&o.focusedTheme.focus()}))},navigation:function(){this.model.cid===this.model.collection.at(0).cid&&this.$el.find(".left").addClass("disabled").prop("disabled",!0),this.model.cid===this.model.collection.at(this.model.collection.length-1).cid&&this.$el.find(".right").addClass("disabled").prop("disabled",!0)},closeOverlay:function(){a("body").removeClass("modal-open"),this.remove(),this.unbind(),this.trigger("theme:collapse")},updateTheme:function(e){var i=this;e.preventDefault(),wp.updates.maybeRequestFilesystemCredentials(e),a(document).on("wp-theme-update-success",function(e,t){i.model.get("id")===t.slug&&i.model.set({hasUpdate:!1,version:t.newVersion}),i.render()}),wp.updates.updateTheme({slug:a(e.target).data("slug")})},deleteTheme:function(e){var i=this,s=i.model.collection,r=o;e.preventDefault(),window.confirm(wp.themes.data.settings.confirmDelete)&&(wp.updates.maybeRequestFilesystemCredentials(e),a(document).one("wp-theme-delete-success",function(e,t){i.$el.find(".close").trigger("click"),a('[data-slug="'+t.slug+'"]').css({backgroundColor:"#faafaa"}).fadeOut(350,function(){a(this).remove(),r.data.themes=_.without(r.data.themes,_.findWhere(r.data.themes,{id:t.slug})),a(".wp-filter-search").val(""),s.doSearch(""),s.remove(i.model),s.trigger("themes:update")})}),wp.updates.deleteTheme({slug:this.model.get("id")}))},nextTheme:function(){return this.trigger("theme:next",this.model.cid),!1},previousTheme:function(){return this.trigger("theme:previous",this.model.cid),!1},screenshotCheck:function(e){var t=e.find(".screenshot img"),i=new Image;i.src=t.attr("src"),i.width&&i.width<=300&&e.addClass("small-screenshot")}}),o.view.Preview=o.view.Details.extend({className:"wp-full-overlay expanded",el:".theme-install-overlay",events:{"click .close-full-overlay":"close","click .collapse-sidebar":"collapse","click .devices button":"previewDevice","click .previous-theme":"previousTheme","click .next-theme":"nextTheme",keyup:"keyEvent","click .theme-install":"installTheme"},html:o.template("theme-preview"),render:function(){var e=this,t=this.model.toJSON(),i=a(document.body);i.attr("aria-busy","true"),this.$el.removeClass("iframe-ready").html(this.html(t)),(t=this.$el.data("current-preview-device"))&&e.tooglePreviewDeviceButtons(t),o.router.navigate(o.router.baseUrl(o.router.themePath+this.model.get("id")),{replace:!0}),this.$el.fadeIn(200,function(){i.addClass("theme-installer-active full-overlay-active")}),this.$el.find("iframe").one("load",function(){e.iframeLoaded()})},iframeLoaded:function(){this.$el.addClass("iframe-ready"),a(document.body).attr("aria-busy","false")},close:function(){return this.$el.fadeOut(200,function(){a("body").removeClass("theme-installer-active full-overlay-active"),o.focusedTheme&&o.focusedTheme.focus()}).removeClass("iframe-ready"),o.router.navigate(o.router.baseUrl("")),this.trigger("preview:close"),this.undelegateEvents(),this.unbind(),!1},collapse:function(e){e=a(e.currentTarget);return"true"===e.attr("aria-expanded")?e.attr({"aria-expanded":"false","aria-label":n.expandSidebar}):e.attr({"aria-expanded":"true","aria-label":n.collapseSidebar}),this.$el.toggleClass("collapsed").toggleClass("expanded"),!1},previewDevice:function(e){e=a(e.currentTarget).data("device");this.$el.removeClass("preview-desktop preview-tablet preview-mobile").addClass("preview-"+e).data("current-preview-device",e),this.tooglePreviewDeviceButtons(e)},tooglePreviewDeviceButtons:function(e){var t=a(".wp-full-overlay-footer .devices");t.find("button").removeClass("active").attr("aria-pressed",!1),t.find("button.preview-"+e).addClass("active").attr("aria-pressed",!0)},keyEvent:function(e){27===e.keyCode&&(this.undelegateEvents(),this.close()),39===e.keyCode&&_.once(this.nextTheme()),37===e.keyCode&&this.previousTheme()},installTheme:function(e){var t=this,i=a(e.target);e.preventDefault(),i.hasClass("disabled")||(wp.updates.maybeRequestFilesystemCredentials(e),a(document).on("wp-theme-install-success",function(){t.model.set({installed:!0})}),wp.updates.installTheme({slug:i.data("slug")}))}}),o.view.Themes=wp.Backbone.View.extend({className:"themes wp-clearfix",$overlay:a("div.theme-overlay"),index:0,count:a(".wrap .theme-count"),liveThemeCount:0,initialize:function(e){var t=this;this.parent=e.parent,this.setView("grid"),t.currentTheme(),this.listenTo(t.collection,"themes:update",function(){t.parent.page=0,t.currentTheme(),t.render(this)}),this.listenTo(t.collection,"query:success",function(e){_.isNumber(e)?(t.count.text(e),t.announceSearchResults(e)):(t.count.text(t.collection.length),t.announceSearchResults(t.collection.length))}),this.listenTo(t.collection,"query:empty",function(){a("body").addClass("no-results")}),this.listenTo(this.parent,"theme:scroll",function(){t.renderThemes(t.parent.page)}),this.listenTo(this.parent,"theme:close",function(){t.overlay&&t.overlay.closeOverlay()}),a("body").on("keyup",function(e){t.overlay&&(a("#request-filesystem-credentials-dialog").is(":visible")||(39===e.keyCode&&t.overlay.nextTheme(),37===e.keyCode&&t.overlay.previousTheme(),27===e.keyCode&&t.overlay.collapse(e)))})},render:function(){this.$el.empty(),1===o.data.themes.length&&(this.singleTheme=new o.view.Details({model:this.collection.models[0]}),this.singleTheme.render(),this.$el.addClass("single-theme"),this.$el.append(this.singleTheme.el)),0<this.options.collection.size()&&this.renderThemes(this.parent.page),this.liveThemeCount=this.collection.count||this.collection.length,this.count.text(this.liveThemeCount),o.isInstall||this.announceSearchResults(this.liveThemeCount)},renderThemes:function(e){var t=this;t.instance=t.collection.paginate(e),0!==t.instance.size()?(!o.isInstall&&1<=e&&a(".add-new-theme").remove(),t.instance.each(function(e){t.theme=new o.view.Theme({model:e,parent:t}),t.theme.render(),t.$el.append(t.theme.el),t.listenTo(t.theme,"theme:expand",t.expand,t)}),!o.isInstall&&o.data.settings.canInstall&&this.$el.append('<div class="theme add-new-theme"><a href="'+o.data.settings.installURI+'"><div class="theme-screenshot"><span></span></div><h2 class="theme-name">'+n.addNew+"</h2></a></div>"),this.parent.page++):this.parent.trigger("theme:end")},currentTheme:function(){var e=this.collection.findWhere({active:!0});e&&(this.collection.remove(e),this.collection.add(e,{at:0}))},setView:function(e){return e},expand:function(e){var t,i=this;this.model=i.collection.get(e),o.router.navigate(o.router.baseUrl(o.router.themePath+this.model.id)),this.setView("detail"),a("body").addClass("modal-open"),this.overlay=new o.view.Details({model:i.model}),this.overlay.render(),this.model.get("hasUpdate")&&(t=a('[data-slug="'+this.model.id+'"]'),e=a(this.overlay.el),t.find(".updating-message").length?(e.find(".notice-warning h3").remove(),e.find(".notice-warning").removeClass("notice-large").addClass("updating-message").find("p").text(wp.updates.l10n.updating)):t.find(".notice-error").length&&e.find(".notice-warning").remove()),this.$overlay.html(this.overlay.el),this.listenTo(this.overlay,"theme:next",function(){i.next([i.model.cid])}).listenTo(this.overlay,"theme:previous",function(){i.previous([i.model.cid])})},next:function(e){var e=this.collection.get(e[0]),e=this.collection.at(this.collection.indexOf(e)+1);void 0!==e&&(this.overlay.closeOverlay(),this.theme.trigger("theme:expand",e.cid))},previous:function(e){var e=this.collection.get(e[0]),e=this.collection.at(this.collection.indexOf(e)-1);void 0!==e&&(this.overlay.closeOverlay(),this.theme.trigger("theme:expand",e.cid))},announceSearchResults:function(e){0===e?wp.a11y.speak(n.noThemesFound):wp.a11y.speak(n.themesFound.replace("%d",e))}}),o.view.Search=wp.Backbone.View.extend({tagName:"input",className:"wp-filter-search",id:"wp-filter-search-input",searching:!1,attributes:{placeholder:n.searchPlaceholder,type:"search","aria-describedby":"live-search-desc"},events:{input:"search",keyup:"search",blur:"pushState"},initialize:function(e){this.parent=e.parent,this.listenTo(this.parent,"theme:close",function(){this.searching=!1})},search:function(e){"keyup"===e.type&&27===e.which&&(e.target.value=""),this.doSearch(e)},doSearch:_.debounce(function(e){var t={};this.collection.doSearch(e.target.value),this.searching&&13!==e.which?t.replace=!0:this.searching=!0,e.target.value?o.router.navigate(o.router.baseUrl(o.router.searchPath+e.target.value),t):o.router.navigate(o.router.baseUrl(""))},500),pushState:function(e){var t=o.router.baseUrl("");e.target.value&&(t=o.router.baseUrl(o.router.searchPath+e.target.value)),this.searching=!1,o.router.navigate(t)}}),o.Router=Backbone.Router.extend({routes:{"themes.php?theme=:slug":"theme","themes.php?search=:query":"search","themes.php?s=:query":"search","themes.php":"themes","":"themes"},baseUrl:function(e){return"themes.php"+e},themePath:"?theme=",searchPath:"?search=",search:function(e){a(".wp-filter-search").val(e)},themes:function(){a(".wp-filter-search").val("")},navigate:function(){Backbone.history._hasPushState&&Backbone.Router.prototype.navigate.apply(this,arguments)}}),o.Run={init:function(){this.themes=new o.Collection(o.data.themes),this.view=new o.view.Appearance({collection:this.themes}),this.render()},render:function(){this.view.render(),this.routes(),Backbone.history.start({root:o.data.settings.adminUrl,pushState:!0,hashChange:!1})},routes:function(){var t=this;o.router=new o.Router,o.router.on("route:theme",function(e){t.view.view.expand(e)}),o.router.on("route:themes",function(){t.themes.doSearch(""),t.view.trigger("theme:close")}),o.router.on("route:search",function(){a(".wp-filter-search").trigger("keyup")}),this.extraRoutes()},extraRoutes:function(){return!1}},o.view.InstallerSearch=o.view.Search.extend({events:{input:"search",keyup:"search"},terms:"",search:function(e){("keyup"!==e.type||9!==e.which&&16!==e.which)&&(this.collection=this.options.parent.view.collection,"keyup"===e.type&&27===e.which&&(e.target.value=""),this.doSearch(e.target.value))},doSearch:_.debounce(function(e){var t={};this.terms!==e&&(this.terms=e,"author:"===(t.search=e).substring(0,7)&&(t.search="",t.author=e.slice(7)),"tag:"===e.substring(0,4)&&(t.search="",t.tag=[e.slice(4)]),a(".filter-links li > a.current").removeClass("current"),a("body").removeClass("show-filters filters-applied show-favorites-form"),a(".drawer-toggle").attr("aria-expanded","false"),this.collection.query(t),o.router.navigate(o.router.baseUrl(o.router.searchPath+e),{replace:!0}))},500)}),o.view.Installer=o.view.Appearance.extend({el:"#wpbody-content .wrap",events:{"click .filter-links li > a":"onSort","click .theme-filter":"onFilter","click .drawer-toggle":"moreFilters","click .filter-drawer .apply-filters":"applyFilters",'click .filter-group [type="checkbox"]':"addFilter","click .filter-drawer .clear-filters":"clearFilters","click .edit-filters":"backToFilters","click .favorites-form-submit":"saveUsername","keyup #wporg-username-input":"saveUsername"},render:function(){var e=this;this.search(),this.uploader(),this.collection=new o.Collection,this.listenTo(this,"theme:end",function(){e.collection.loadingThemes||(e.collection.loadingThemes=!0,e.collection.currentQuery.page++,_.extend(e.collection.currentQuery.request,{page:e.collection.currentQuery.page}),e.collection.query(e.collection.currentQuery.request))}),this.listenTo(this.collection,"query:success",function(){a("body").removeClass("loading-content"),a(".theme-browser").find("div.error").remove()}),this.listenTo(this.collection,"query:fail",function(){a("body").removeClass("loading-content"),a(".theme-browser").find("div.error").remove(),a(".theme-browser").find("div.themes").before('<div class="error"><p>'+n.error+"</p></div>")}),this.view&&this.view.remove(),this.view=new o.view.Themes({collection:this.collection,parent:this}),this.page=0,this.$el.find(".themes").remove(),this.view.render(),this.$el.find(".theme-browser").append(this.view.el).addClass("rendered")},browse:function(e){this.collection.query({browse:e})},onSort:function(e){var t=a(e.target),i=t.data("sort");e.preventDefault(),a("body").removeClass("filters-applied show-filters"),a(".drawer-toggle").attr("aria-expanded","false"),t.hasClass(this.activeClass)||(this.sort(i),o.router.navigate(o.router.baseUrl(o.router.browsePath+i)))},sort:function(e){this.clearSearch(),a(".filter-links li > a, .theme-filter").removeClass(this.activeClass),a('[data-sort="'+e+'"]').addClass(this.activeClass),"favorites"===e?a("body").addClass("show-favorites-form"):a("body").removeClass("show-favorites-form"),this.browse(e)},onFilter:function(e){var t=a(e.target),e=t.data("filter");t.hasClass(this.activeClass)||(a(".filter-links li > a, .theme-section").removeClass(this.activeClass),t.addClass(this.activeClass),e&&(e={tag:[e=_.union([e,this.filtersChecked()])]},this.collection.query(e)))},addFilter:function(){this.filtersChecked()},applyFilters:function(e){var t,i=this.filtersChecked(),s={tag:i},r=a(".filtered-by .tags");e&&e.preventDefault(),i?(a("body").addClass("filters-applied"),a(".filter-links li > a.current").removeClass("current"),r.empty(),_.each(i,function(e){t=a('label[for="filter-id-'+e+'"]').text(),r.append('<span class="tag">'+t+"</span>")}),this.collection.query(s)):wp.a11y.speak(n.selectFeatureFilter)},saveUsername:function(e){var t=a("#wporg-username-input").val(),i=a("#wporg-username-nonce").val(),s={browse:"favorites",user:t},r=this;if(e&&e.preventDefault(),"keyup"!==e.type||13===e.which)return wp.ajax.send("save-wporg-username",{data:{_wpnonce:i,username:t},success:function(){r.collection.query(s)}})},filtersChecked:function(){var e=a(".filter-group").find(":checkbox"),t=[];return _.each(e.filter(":checked"),function(e){t.push(a(e).prop("value"))}),0===t.length?(a(".filter-drawer .apply-filters").find("span").text(""),a(".filter-drawer .clear-filters").hide(),a("body").removeClass("filters-applied"),!1):(a(".filter-drawer .apply-filters").find("span").text(t.length),a(".filter-drawer .clear-filters").css("display","inline-block"),t)},activeClass:"current",searchContainer:a(".wp-filter .search-form"),uploader:function(){var e=a(".upload-view-toggle"),t=a(document.body);e.on("click",function(){t.toggleClass("show-upload-view"),e.attr("aria-expanded",t.hasClass("show-upload-view"))})},moreFilters:function(e){var t=a("body"),i=a(".drawer-toggle");if(e.preventDefault(),t.hasClass("filters-applied"))return this.backToFilters();this.clearSearch(),o.router.navigate(o.router.baseUrl("")),t.toggleClass("show-filters"),i.attr("aria-expanded",t.hasClass("show-filters"))},clearFilters:function(e){var t=a(".filter-group").find(":checkbox"),i=this;e.preventDefault(),_.each(t.filter(":checked"),function(e){return a(e).prop("checked",!1),i.filtersChecked()})},backToFilters:function(e){e&&e.preventDefault(),a("body").removeClass("filters-applied")},clearSearch:function(){a("#wp-filter-search-input").val("")}}),o.InstallerRouter=Backbone.Router.extend({routes:{"theme-install.php?theme=:slug":"preview","theme-install.php?browse=:sort":"sort","theme-install.php?search=:query":"search","theme-install.php":"sort"},baseUrl:function(e){return"theme-install.php"+e},themePath:"?theme=",browsePath:"?browse=",searchPath:"?search=",search:function(e){a(".wp-filter-search").val(e)},navigate:function(){Backbone.history._hasPushState&&Backbone.Router.prototype.navigate.apply(this,arguments)}}),o.RunInstaller={init:function(){this.view=new o.view.Installer({section:"featured",SearchView:o.view.InstallerSearch}),this.render()},render:function(){this.view.render(),this.routes(),Backbone.history.start({root:o.data.settings.adminUrl,pushState:!0,hashChange:!1})},routes:function(){var t=this,i={};o.router=new o.InstallerRouter,o.router.on("route:preview",function(e){i.theme=e,t.view.collection.query(i),t.view.collection.once("update",function(){t.view.view.theme.preview()})}),o.router.on("route:sort",function(e){e=e||"featured",t.view.sort(e),t.view.trigger("theme:close")}),o.router.on("route:search",function(){a(".wp-filter-search").focus().trigger("keyup")}),this.extraRoutes()},extraRoutes:function(){return!1}},a(document).ready(function(){(o.isInstall?o.RunInstaller:o.Run).init(),a(".broken-themes .delete-theme").on("click",function(){return confirm(_wpThemeSettings.settings.confirmDelete)})})}(jQuery),jQuery(document).ready(function(r){tb_position=function(){var e=r("#TB_window"),t=r(window).width(),i=r(window).height(),s=1040<t?1040:t,t=0;r("#wpadminbar").length&&(t=parseInt(r("#wpadminbar").css("height"),10)),e.size()&&(e.width(s-50).height(i-45-t),r("#TB_iframeContent").width(s-50).height(i-75-t),e.css({"margin-left":"-"+parseInt((s-50)/2,10)+"px"}),void 0!==document.body.style.maxWidth&&e.css({top:20+t+"px","margin-top":"0"}))},r(window).resize(function(){tb_position()})}); custom-background.js 0000666 00000004351 15213733063 0010543 0 ustar 00 /* global ajaxurl */ (function($) { $(document).ready(function() { var frame, bgImage = $( '#custom-background-image' ); $('#background-color').wpColorPicker({ change: function( event, ui ) { bgImage.css('background-color', ui.color.toString()); }, clear: function() { bgImage.css('background-color', ''); } }); $( 'select[name="background-size"]' ).change( function() { bgImage.css( 'background-size', $( this ).val() ); }); $( 'input[name="background-position"]' ).change( function() { bgImage.css( 'background-position', $( this ).val() ); }); $( 'input[name="background-repeat"]' ).change( function() { bgImage.css( 'background-repeat', $( this ).is( ':checked' ) ? 'repeat' : 'no-repeat' ); }); $( 'input[name="background-attachment"]' ).change( function() { bgImage.css( 'background-attachment', $( this ).is( ':checked' ) ? 'scroll' : 'fixed' ); }); $('#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.customBackground = 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(); var nonceValue = $( '#_wpnonce' ).val() || ''; // Run an AJAX request to set the background image. $.post( ajaxurl, { action: 'set-background-image', attachment_id: attachment.id, _ajax_nonce: nonceValue, size: 'full' }).done( function() { // When the request completes, reload the window. window.location.reload(); }); }); // Finally, open the modal. frame.open(); }); }); })(jQuery); tags.js 0000666 00000005040 15213733063 0006046 0 ustar 00 /* global ajaxurl, wpAjax, tagsl10n, showNotice, validateForm */ jQuery(document).ready(function($) { $( '#the-list' ).on( 'click', '.delete-tag', function() { 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){ var res, parent, term, indent, i; $('#ajax-response').empty(); res = wpAjax.parseAjaxResponse( r, 'ajax-response' ); if ( ! res || res.errors ) return; 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. term = res.responses[1].supplemental; // Create an indent for the Parent field indent = ''; for ( i = 0; i < res.responses[1].position; i++ ) indent += ' '; 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; }); }); customize-controls.min.js 0000666 00000175037 15213733063 0011573 0 ustar 00 !function(D){var i,e,s,t,n,a,o,I=wp.customize;I.Setting=I.Value.extend({initialize:function(e,t,n){var i=this;I.Value.prototype.initialize.call(i,t,n),i.id=e,i.transport=i.transport||"refresh",i._dirty=n.dirty||!1,i.notifications=new I.Values({defaultConstructor:I.Notification}),i.bind(i.preview)},preview:function(){var e=this,t=e.transport;"postMessage"===(t="postMessage"===t&&!I.state("previewerAlive").get()?"refresh":t)?e.previewer.send("setting",[e.id,e()]):"refresh"===t&&e.previewer.refresh()},findControls:function(){var n=this,i=[];return I.control.each(function(t){_.each(t.settings,function(e){e.id===n.id&&i.push(t)})}),i}}),I._latestRevision=0,I._lastSavedRevision=0,I._latestSettingRevisions={},I.bind("change",function(e){I._latestRevision+=1,I._latestSettingRevisions[e.id]=I._latestRevision}),I.bind("ready",function(){I.bind("add",function(e){e._dirty&&(I._latestRevision+=1,I._latestSettingRevisions[e.id]=I._latestRevision)})}),I.dirtyValues=function(n){var i={};return I.each(function(e){var t;e._dirty&&(t=I._latestSettingRevisions[e.id],I.state("changesetStatus").get()&&n&&n.unsaved&&(_.isUndefined(t)||t<=I._lastSavedRevision)||(i[e.id]=e.get()))}),i},I.requestChangesetUpdate=function(n){var e,i={},t=new D.Deferred;return n&&_.extend(i,n),_.each(I.dirtyValues({unsaved:!0}),function(e,t){n&&null===n[t]||(i[t]=_.extend({},i[t]||{},{value:e}))}),_.isEmpty(i)?t.resolve({}):(I.state("processing").set(I.state("processing").get()+1),t.always(function(){I.state("processing").set(I.state("processing").get()-1)}),I.trigger("changeset-save",i),delete(e=I.previewer.query({excludeCustomizedSaved:!0})).customized,_.extend(e,{nonce:I.settings.nonce.save,customize_theme:I.settings.theme.stylesheet,customize_changeset_data:JSON.stringify(i)}),(e=wp.ajax.post("customize_save",e)).done(function(e){var n={};I._lastSavedRevision=Math.max(I._latestRevision,I._lastSavedRevision),I.state("changesetStatus").set(e.changeset_status),t.resolve(e),I.trigger("changeset-saved",e),e.setting_validities&&_.each(e.setting_validities,function(e,t){!0===e&&_.isObject(i[t])&&!_.isUndefined(i[t].value)&&(n[t]=i[t].value)}),I.previewer.send("changeset-saved",_.extend({},e,{saved_changeset_values:n}))}),e.fail(function(e){t.reject(e),I.trigger("changeset-error",e)}),e.always(function(e){e.setting_validities&&I._handleSettingValidities({settingValidities:e.setting_validities})})),t.promise()},I.utils.bubbleChildValueChanges=function(n,e){D.each(e,function(e,t){n[t].bind(function(e,t){n.parent&&e!==t&&n.parent.trigger("change",n)})})},e=function(e){var t,n,i=this,a=function(){var e=(i.extended(I.Panel)||i.extended(I.Section))&&i.expanded&&i.expanded()?i.contentContainer:i.container;(n=0===(n=e.find(".control-focus:first")).length?e.find("input, select, textarea, button, object, a[href], [tabindex]").filter(":visible").first():n).focus()};(e=e||{}).completeCallback?(t=e.completeCallback,e.completeCallback=function(){a(),t()}):e.completeCallback=a,I.state("paneVisible").set(!0),i.expand?i.expand(e):e.completeCallback()},I.utils.prioritySort=function(e,t){return e.priority()===t.priority()&&"number"==typeof e.params.instanceNumber&&"number"==typeof t.params.instanceNumber?e.params.instanceNumber-t.params.instanceNumber:e.priority()-t.priority()},I.utils.isKeydownButNotEnterEvent=function(e){return"keydown"===e.type&&13!==e.which},I.utils.areElementListsEqual=function(e,t){return e.length===t.length&&-1===_.indexOf(_.map(_.zip(e,t),function(e){return D(e[0]).is(e[1])}),!1)},t=document.createElement("div"),n={transition:"transitionend",OTransition:"oTransitionEnd",MozTransition:"transitionend",WebkitTransition:"webkitTransitionEnd"},a=_.find(_.keys(n),function(e){return!_.isUndefined(t.style[e])}),s=a?n[a]:null,i=I.Class.extend({defaultActiveArguments:{duration:"fast",completeCallback:D.noop},defaultExpandedArguments:{duration:"fast",completeCallback:D.noop},containerType:"container",defaults:{title:"",description:"",priority:100,type:"default",content:null,active:!0,instanceNumber:null},initialize:function(e,t){var n=this;n.id=e,(t=t||{}).params=_.defaults(t.params||{},n.defaults),D.extend(n,t),n.templateSelector="customize-"+n.containerType+"-"+n.params.type,n.container=D(n.params.content),0===n.container.length&&(n.container=D(n.getContainer())),n.headContainer=n.container,n.contentContainer=n.getContent(),n.container=n.container.add(n.contentContainer),n.deferred={embedded:new D.Deferred},n.priority=new I.Value,n.active=new I.Value,n.activeArgumentsQueue=[],n.expanded=new I.Value,n.expandedArgumentsQueue=[],n.active.bind(function(e){var t=n.activeArgumentsQueue.shift(),t=D.extend({},n.defaultActiveArguments,t);e=e&&n.isContextuallyActive(),n.onChangeActive(e,t)}),n.expanded.bind(function(e){var t=n.expandedArgumentsQueue.shift(),t=D.extend({},n.defaultExpandedArguments,t);n.onChangeExpanded(e,t)}),n.deferred.embedded.done(function(){n.attachEvents()}),I.utils.bubbleChildValueChanges(n,["priority","active"]),n.priority.set(n.params.priority),n.active.set(n.params.active),n.expanded.set(!1)},ready:function(){},_children:function(t,e){var n=this,i=[];return I[e].each(function(e){e[t].get()===n.id&&i.push(e)}),i.sort(I.utils.prioritySort),i},isContextuallyActive:function(){throw new Error("Container.isContextuallyActive() must be overridden in a subclass.")},onChangeActive:function(e,t){var n,i=this,a=i.headContainer;t.unchanged?t.completeCallback&&t.completeCallback():(n="resolved"===I.previewer.deferred.active.state()?t.duration:0,i.extended(I.Panel)&&(I.panel.each(function(e){e!==i&&e.expanded()&&(n=0)}),e||_.each(i.sections(),function(e){e.collapse({duration:0})})),D.contains(document,a.get(0))?e?a.slideDown(n,t.completeCallback):i.expanded()?i.collapse({duration:n,completeCallback:function(){a.slideUp(n,t.completeCallback)}}):a.slideUp(n,t.completeCallback):(a.toggle(e),t.completeCallback&&t.completeCallback()))},_toggleActive:function(e,t){return t=t||{},e&&this.active.get()||!e&&!this.active.get()?(t.unchanged=!0,this.onChangeActive(this.active.get(),t),!1):(t.unchanged=!1,this.activeArgumentsQueue.push(t),this.active.set(e),!0)},activate:function(e){return this._toggleActive(!0,e)},deactivate:function(e){return this._toggleActive(!1,e)},onChangeExpanded:function(){throw new Error("Must override with subclass.")},_toggleExpanded:function(e,t){var n,i=this;return n=(t=t||{}).completeCallback,!(e&&!i.active())&&(I.state("paneVisible").set(!0),t.completeCallback=function(){n&&n.apply(i,arguments),e?i.container.trigger("expanded"):i.container.trigger("collapsed")},e&&i.expanded.get()||!e&&!i.expanded.get()?(t.unchanged=!0,i.onChangeExpanded(i.expanded.get(),t),!1):(t.unchanged=!1,i.expandedArgumentsQueue.push(t),i.expanded.set(e),!0))},expand:function(e){return this._toggleExpanded(!0,e)},collapse:function(e){return this._toggleExpanded(!1,e)},_animateChangeExpanded:function(t){var a,o,n,i;s?(o=(a=this).contentContainer,i=o.closest(".wp-full-overlay").add(o),a.panel&&""!==a.panel()&&!I.panel(a.panel()).contentContainer.hasClass("skip-transition")||(i=i.add("#customize-info, .customize-pane-parent")),n=function(e){2===e.eventPhase&&D(e.target).is(o)&&(o.off(s,n),i.removeClass("busy"),t&&t())},o.on(s,n),i.addClass("busy"),_.defer(function(){var e=o.closest(".wp-full-overlay-sidebar-content"),t=e.scrollTop(),n=o.data("previous-scrollTop")||0,i=a.expanded();i&&0<t?(o.css("top",t+"px"),o.data("previous-scrollTop",t)):!i&&0<t+n&&(o.css("top",n-t+"px"),e.scrollTop(n))})):t&&t()},focus:e,getContainer:function(){var e=this,t=0!==D("#tmpl-"+e.templateSelector).length?wp.template(e.templateSelector):wp.template("customize-"+e.containerType+"-default");return t&&e.container?D.trim(t(e.params)):"<li></li>"},getContent:function(){var e=this.container,t=e.find(".accordion-section-content, .control-panel-content").first(),n="sub-"+e.attr("id"),i=n,a=e.attr("aria-owns");return a&&(i=i+" "+a),e.attr("aria-owns",i),t.detach().attr({id:n,"class":"customize-pane-child "+t.attr("class")+" "+e.attr("class")})}}),I.Section=i.extend({containerType:"section",defaults:{title:"",description:"",priority:100,type:"default",content:null,active:!0,instanceNumber:null,panel:null,customizeAction:""},initialize:function(e,t){var n=this;i.prototype.initialize.call(n,e,t),n.id=e,n.panel=new I.Value,n.panel.bind(function(e){D(n.headContainer).toggleClass("control-subsection",!!e)}),n.panel.set(n.params.panel||""),I.utils.bubbleChildValueChanges(n,["panel"]),n.embed(),n.deferred.embedded.done(function(){n.ready()})},embed:function(){var n=this,i=D("#customize-theme-controls"),e=function(e){var t;e?I.panel(e,function(e){e.deferred.embedded.done(function(){t=e.contentContainer,n.headContainer.parent().is(t)||t.append(n.headContainer),n.contentContainer.parent().is(n.headContainer)||i.append(n.contentContainer),n.deferred.embedded.resolve()})}):(t=D(".customize-pane-parent"),n.headContainer.parent().is(t)||t.append(n.headContainer),n.contentContainer.parent().is(n.headContainer)||i.append(n.contentContainer),n.deferred.embedded.resolve())};n.panel.bind(e),e(n.panel.get())},attachEvents:function(){var e,t=this;t.container.hasClass("cannot-expand")||(t.container.find(".accordion-section-title, .customize-section-back").on("click keydown",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),t.expanded()?t.collapse():t.expand())}),t.container.find(".customize-section-title .customize-help-toggle").on("click",function(){(e=t.container.find(".section-meta")).hasClass("cannot-expand")||((e=e.find(".customize-section-description:first")).toggleClass("open"),e.slideToggle(),e.attr("aria-expanded",function(e,t){return"true"===t?"false":"true"}))}))},isContextuallyActive:function(){var e=this.controls(),t=0;return _(e).each(function(e){e.active()&&(t+=1)}),0!==t},controls:function(){return this._children("section","control")},onChangeExpanded:function(e,t){var n,i,a=this,o=a.headContainer.closest(".wp-full-overlay-sidebar-content"),s=a.contentContainer,r=a.headContainer.closest(".wp-full-overlay"),c=s.find(".customize-section-back"),l=a.headContainer.find(".accordion-section-title").first();e&&!s.hasClass("open")?(n=t.unchanged?t.completeCallback:D.proxy(function(){a._animateChangeExpanded(function(){l.attr("tabindex","-1"),c.attr("tabindex","0"),c.focus(),s.css("top",""),o.scrollTop(0),t.completeCallback&&t.completeCallback()}),s.addClass("open"),r.addClass("section-open"),I.state("expandedSection").set(a)},this),t.allowMultiple||I.section.each(function(e){e!==a&&e.collapse({duration:t.duration})}),a.panel()?I.panel(a.panel()).expand({duration:t.duration,completeCallback:n}):(I.panel.each(function(e){e.collapse()}),n())):!e&&s.hasClass("open")?(a.panel()&&(i=I.panel(a.panel())).contentContainer.hasClass("skip-transition")&&i.collapse(),a._animateChangeExpanded(function(){c.attr("tabindex","-1"),l.attr("tabindex","0"),l.focus(),s.css("top",""),t.completeCallback&&t.completeCallback()}),s.removeClass("open"),r.removeClass("section-open"),a===I.state("expandedSection").get()&&I.state("expandedSection").set(!1)):t.completeCallback&&t.completeCallback()}}),I.ThemesSection=I.Section.extend({currentTheme:"",overlay:"",template:"",screenshotQueue:null,$window:D(window),initialize:function(){return this.$customizeSidebar=D(".wp-full-overlay-sidebar-content:first"),I.Section.prototype.initialize.apply(this,arguments)},ready:function(){var t=this;t.overlay=t.container.find(".theme-overlay"),t.template=wp.template("customize-themes-details-view"),t.container.on("keydown",function(e){t.overlay.find(".theme-wrap").is(":visible")&&(39===e.keyCode&&t.nextTheme(),37===e.keyCode&&t.previousTheme(),27===e.keyCode&&(t.closeDetails(),e.stopPropagation()))}),_.bindAll(this,"renderScreenshots")},isContextuallyActive:function(){return this.active()},attachEvents:function(){var n=this;n.container.find(".change-theme, .customize-theme").on("click keydown",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),n.expanded()?n.collapse():n.expand())}),n.container.on("click keydown",".left",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),n.previousTheme())}),n.container.on("click keydown",".right",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),n.nextTheme())}),n.container.on("click keydown",".theme-backdrop, .close",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),n.closeDetails())});var i=_.throttle(_.bind(n.renderScreenshots,this),100);n.container.on("input","#themes-filter",function(e){var t=e.currentTarget.value.toLowerCase().trim().replace("-"," "),e=n.controls();_.each(e,function(e){e.filter(t)}),i(),e=n.container.find("li.customize-control:visible").length,n.container.find(".theme-count").text(e)}),I.bind("ready",function(){_.each(n.controls().slice(0,3),function(e){e=e.params.theme.screenshot[0];e&&((new Image).src=e)})})},onChangeExpanded:function(e,t){var n,i,a,o,s,r;t.unchanged?t.completeCallback&&t.completeCallback():(a=(i=(n=this).contentContainer).closest(".wp-full-overlay"),o=i.closest(".wp-full-overlay-sidebar-content"),s=i.find(".customize-theme"),r=n.headContainer.find(".change-theme"),e&&!i.hasClass("current-panel")?(I.section.each(function(e){e!==n&&e.collapse({duration:t.duration})}),I.panel.each(function(e){e.collapse({duration:0})}),n._animateChangeExpanded(function(){r.attr("tabindex","-1"),s.attr("tabindex","0"),s.focus(),i.css("top",""),o.scrollTop(0),t.completeCallback&&t.completeCallback()}),a.addClass("in-themes-panel"),i.addClass("current-panel"),_.delay(n.renderScreenshots,10),n.$customizeSidebar.on("scroll.customize-themes-section",_.throttle(n.renderScreenshots,300))):!e&&i.hasClass("current-panel")&&(n._animateChangeExpanded(function(){r.attr("tabindex","0"),s.attr("tabindex","-1"),r.focus(),i.css("top",""),t.completeCallback&&t.completeCallback()}),a.removeClass("in-themes-panel"),i.removeClass("current-panel"),n.$customizeSidebar.off("scroll.customize-themes-section")))},renderScreenshots:function(){var s=this;null===s.screenshotQueue&&(s.screenshotQueue=s.controls()),s.screenshotQueue.length&&(s.screenshotQueue=_.filter(s.screenshotQueue,function(e){var t=e.container.find(".theme-screenshot"),n=t.find("img");if(!n.length)return!1;if(n.is(":hidden"))return!0;var i=s.$window.scrollTop(),a=i+s.$window.height(),o=n.offset().top,n=t.height(),t=3*n,t=i-t<=o+n&&o<=a+t;return t&&e.container.trigger("render-screenshot"),!t}))},nextTheme:function(){var e=this;e.getNextTheme()&&e.showDetails(e.getNextTheme(),function(){e.overlay.find(".right").focus()})},getNextTheme:function(){var e=I.control("theme_"+this.currentTheme),t=e.container.next("li.customize-control-theme");return!!t.length&&(t=t[0].id.replace("customize-control-",""),(e=I.control(t)).params.theme)},previousTheme:function(){var e=this;e.getPreviousTheme()&&e.showDetails(e.getPreviousTheme(),function(){e.overlay.find(".left").focus()})},getPreviousTheme:function(){var e=I.control("theme_"+this.currentTheme),t=e.container.prev("li.customize-control-theme");return!!t.length&&(t=t[0].id.replace("customize-control-",""),(e=I.control(t)).params.theme)},updateLimits:function(){this.getNextTheme()||this.overlay.find(".right").addClass("disabled"),this.getPreviousTheme()||this.overlay.find(".left").addClass("disabled")},loadThemePreview:function(e){var t,n,i=D.Deferred(),a=document.createElement("a");return a.href=location.href,a.search=D.param(_.extend(I.utils.parseQueryString(a.search.substr(1)),{theme:e,changeset_uuid:I.settings.changeset.uuid})),(n=D(".wp-full-overlay")).addClass("customize-loading"),t=function(){var e;0<I.state("processing").get()||(I.state("processing").unbind(t),(e=I.requestChangesetUpdate()).done(function(){D(window).off("beforeunload.customize-confirm"),top.location.href=a.href,i.resolve()}),e.fail(function(){n.removeClass("customize-loading"),i.reject()}))},0===I.state("processing").get()?t():I.state("processing").bind(t),i.promise()},showDetails:function(t,e){var n,i=this;e=e||function(){},i.currentTheme=t.id,i.overlay.html(i.template(t)).fadeIn("fast").focus(),D("body").addClass("modal-open"),i.containFocus(i.overlay),i.updateLimits(),(n=i.overlay.find(".inactive-theme > a")).on("click",function(e){e.preventDefault(),n.hasClass("disabled")||(n.addClass("disabled"),i.loadThemePreview(t.id).fail(function(){n.removeClass("disabled")}))}),e()},closeDetails:function(){D("body").removeClass("modal-open"),this.overlay.fadeOut("fast"),I.control("theme_"+this.currentTheme).focus()},containFocus:function(t){var n;t.on("keydown",function(e){if(9===e.keyCode)return(n=D(":tabbable",t)).last()[0]!==e.target||e.shiftKey?n.first()[0]===e.target&&e.shiftKey?(n.last().focus(),!1):void 0:(n.first().focus(),!1)})}}),I.Panel=i.extend({containerType:"panel",initialize:function(e,t){var n=this;i.prototype.initialize.call(n,e,t),n.embed(),n.deferred.embedded.done(function(){n.ready()})},embed:function(){var e=this,t=D("#customize-theme-controls"),n=D(".customize-pane-parent");e.headContainer.parent().is(n)||n.append(e.headContainer),e.contentContainer.parent().is(e.headContainer)||(t.append(e.contentContainer),e.renderContent()),e.deferred.embedded.resolve()},attachEvents:function(){var t,n=this;n.headContainer.find(".accordion-section-title").on("click keydown",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),n.expanded()||n.expand())}),n.container.find(".customize-panel-back").on("click keydown",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),n.expanded()&&n.collapse())}),(t=n.container.find(".panel-meta:first")).find("> .accordion-section-title .customize-help-toggle").on("click keydown",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),t.hasClass("cannot-expand")||(e=t.find(".customize-panel-description:first"),t.hasClass("open")?(t.toggleClass("open"),e.slideUp(n.defaultExpandedArguments.duration),D(this).attr("aria-expanded",!1)):(e.slideDown(n.defaultExpandedArguments.duration),t.toggleClass("open"),D(this).attr("aria-expanded",!0))))})},sections:function(){return this._children("panel","section")},isContextuallyActive:function(){var e=this.sections(),t=0;return _(e).each(function(e){e.active()&&e.isContextuallyActive()&&(t+=1)}),0!==t},onChangeExpanded:function(e,t){var n,i,a,o,s,r,c;t.unchanged?t.completeCallback&&t.completeCallback():(a=(i=(n=this).contentContainer).closest(".wp-full-overlay"),o=i.closest(".wp-full-overlay-sidebar-content"),s=n.headContainer.find(".accordion-section-title"),r=i.find(".customize-panel-back"),c=n.sections(),e&&!i.hasClass("current-panel")?(I.section.each(function(e){n.id!==e.panel()&&e.collapse({duration:0})}),I.panel.each(function(e){n!==e&&e.collapse({duration:0})}),n.params.autoExpandSoleSection&&1===c.length&&c[0].active.get()?(i.addClass("current-panel skip-transition"),a.addClass("in-sub-panel"),c[0].expand({completeCallback:t.completeCallback})):(n._animateChangeExpanded(function(){s.attr("tabindex","-1"),r.attr("tabindex","0"),r.focus(),i.css("top",""),o.scrollTop(0),t.completeCallback&&t.completeCallback()}),i.addClass("current-panel"),a.addClass("in-sub-panel")),I.state("expandedPanel").set(n)):!e&&i.hasClass("current-panel")&&(i.hasClass("skip-transition")?i.removeClass("skip-transition"):n._animateChangeExpanded(function(){s.attr("tabindex","0"),r.attr("tabindex","-1"),s.focus(),i.css("top",""),t.completeCallback&&t.completeCallback()}),a.removeClass("in-sub-panel"),i.removeClass("current-panel"),n===I.state("expandedPanel").get()&&I.state("expandedPanel").set(!1)))},renderContent:function(){var e=this,t=0!==D("#tmpl-"+e.templateSelector+"-content").length?wp.template(e.templateSelector+"-content"):wp.template("customize-panel-default-content");t&&e.headContainer&&e.contentContainer.html(t(e.params))}}),I.Control=I.Class.extend({defaultActiveArguments:{duration:"fast",completeCallback:D.noop},initialize:function(e,t){var i,a,o=this;o.params={},D.extend(o,t||{}),o.id=e,o.selector="#customize-control-"+e.replace(/\]/g,"").replace(/\[/g,"-"),o.templateSelector="customize-control-"+o.params.type+"-content",o.container=o.params.content?D(o.params.content):D(o.selector),o.deferred={embedded:new D.Deferred},o.section=new I.Value,o.priority=new I.Value,o.active=new I.Value,o.activeArgumentsQueue=[],o.notifications=new I.Values({defaultConstructor:I.Notification}),o.elements=[],i=o.container.find("[data-customize-setting-link]"),a={},i.each(function(){var e,n=D(this);if(n.is(":radio")){if(e=n.prop("name"),a[e])return;a[e]=!0,n=i.filter('[name="'+e+'"]')}I(n.data("customizeSettingLink"),function(e){var t=new I.Element(n);o.elements.push(t),t.sync(e),t.set(e())})}),o.active.bind(function(e){var t=o.activeArgumentsQueue.shift(),t=D.extend({},o.defaultActiveArguments,t);o.onChangeActive(e,t)}),o.section.set(o.params.section),o.priority.set(isNaN(o.params.priority)?10:o.params.priority),o.active.set(o.params.active),I.utils.bubbleChildValueChanges(o,["section","priority","active"]),0===(e=D.map(o.params.settings,function(e){return e})).length?(o.setting=null,o.settings={},o.embed()):I.apply(I,e.concat(function(){for(var e in o.settings={},o.params.settings)o.settings[e]=I(o.params.settings[e]);o.setting=o.settings["default"]||null,_.each(o.settings,function(n){n.notifications.bind("add",function(e){var t=n.id+":"+e.code,e=_.extend({},e,{setting:n.id}),e=new I.Notification(t,e);o.notifications.add(e.code,e)}),n.notifications.bind("remove",function(e){o.notifications.remove(n.id+":"+e.code)})}),o.embed()})),o.deferred.embedded.done(function(){var t=_.debounce(function(){o.renderNotifications()});o.notifications.bind("add",function(e){wp.a11y.speak(e.message,"assertive"),t()}),o.notifications.bind("remove",t),o.renderNotifications(),o.ready()})},embed:function(){var n=this,e=function(e){var t;e&&I.section(e,function(e){e.deferred.embedded.done(function(){t=e.contentContainer.is("ul")?e.contentContainer:e.contentContainer.find("ul:first"),n.container.parent().is(t)||(t.append(n.container),n.renderContent()),n.deferred.embedded.resolve()})})};n.section.bind(e),e(n.section.get())},ready:function(){var t,n=this;"dropdown-pages"===n.params.type&&n.params.allow_addition&&((t=n.container.find(".new-content-item")).hide(),n.container.on("click",".add-new-toggle",function(e){D(e.currentTarget).slideUp(180),t.slideDown(180),t.find(".create-item-input").focus()}),n.container.on("click",".add-content",function(){n.addNewPage()}),n.container.on("keyup",".create-item-input",function(e){13===e.which&&n.addNewPage()}))},getNotificationsContainerElement:function(){var e,t=this,n=t.container.find(".customize-control-notifications-container:first");return n.length||(n=D('<div class="customize-control-notifications-container"></div>'),t.container.hasClass("customize-control-nav_menu_item")?t.container.find(".menu-item-settings:first").prepend(n):t.container.hasClass("customize-control-widget_form")?t.container.find(".widget-inside:first").prepend(n):(e=t.container.find(".customize-control-title")).length?e.after(n):t.container.prepend(n)),n},renderNotifications:function(){var t,e=this,n=!1,i=e.getNotificationsContainerElement();i&&i.length&&(t=[],e.notifications.each(function(e){t.push(e),"error"===e.type&&(n=!0)}),0===t.length?i.stop().slideUp("fast"):i.stop().slideDown("fast",null,function(){D(this).css("height","auto")}),e.notificationsTemplate||(e.notificationsTemplate=wp.template("customize-control-notifications")),e.container.toggleClass("has-notifications",0!==t.length),e.container.toggleClass("has-error",n),i.empty().append(D.trim(e.notificationsTemplate({notifications:t,altNotice:Boolean(e.altNotice)}))))},expand:function(e){I.section(this.section()).expand(e)},focus:e,onChangeActive:function(e,t){t.unchanged?t.completeCallback&&t.completeCallback():D.contains(document,this.container[0])?e?this.container.slideDown(t.duration,t.completeCallback):this.container.slideUp(t.duration,t.completeCallback):(this.container.toggle(e),t.completeCallback&&t.completeCallback())},toggle:function(e){return this.onChangeActive(e,this.defaultActiveArguments)},activate:i.prototype.activate,deactivate:i.prototype.deactivate,_toggleActive:i.prototype._toggleActive,dropdownInit:function(){function e(e){"string"==typeof e&&i.statuses&&i.statuses[e]?n.html(i.statuses[e]).show():n.hide()}var t=this,n=this.container.find(".dropdown-status"),i=this.params,a=!1;this.container.on("click keydown",".dropdown",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),a||t.container.toggleClass("open"),t.container.hasClass("open")&&t.container.parent().parent().find("li.library-selected").focus(),a=!0,setTimeout(function(){a=!1},400))}),this.setting.bind(e),e(this.setting())},renderContent:function(){var e,t=this;0!==D("#tmpl-"+t.templateSelector).length&&(e=wp.template(t.templateSelector))&&t.container&&t.container.html(e(t.params))},addNewPage:function(){var e,a,o,t,s,r,c=this;"dropdown-pages"===c.params.type&&c.params.allow_addition&&I.Menus&&(a=c.container.find(".add-new-toggle"),o=c.container.find(".new-content-item"),t=c.container.find(".create-item-input"),s=t.val(),r=c.container.find("select"),s?(t.removeClass("invalid"),t.attr("disabled","disabled"),(e=I.Menus.insertAutoDraftPost({post_title:s,post_type:"page"})).done(function(e){var t,n,i=new I.Menus.AvailableItemModel({id:"post-"+e.post_id,title:s,type:"post_type",type_label:I.Menus.data.l10n.page_label,object:"page",object_id:e.post_id,url:e.url});I.Menus.availableMenuItemsPanel.collection.add(i),t=D("#available-menu-items-post_type-page").find(".available-menu-items-list"),n=wp.template("available-menu-item"),t.prepend(n(i.attributes)),r.focus(),c.setting.set(String(e.post_id)),o.slideUp(180),a.slideDown(180)}),e.always(function(){t.val("").removeAttr("disabled")})):t.addClass("invalid"))}}),I.ColorControl=I.Control.extend({ready:function(){var t,n=this,e="hue"===this.params.mode,i=!1;e?(t=this.container.find(".color-picker-hue")).val(n.setting()).wpColorPicker({change:function(e,t){i=!0,n.setting(t.color.h()),i=!1}}):(t=this.container.find(".color-picker-hex")).val(n.setting()).wpColorPicker({change:function(){i=!0,n.setting.set(t.wpColorPicker("color")),i=!1},clear:function(){i=!0,n.setting.set(""),i=!1}}),n.setting.bind(function(e){i||(t.val(e),t.wpColorPicker("color",e))}),n.container.on("keydown",function(e){27===e.which&&n.container.find(".wp-picker-container").hasClass("wp-picker-active")&&(t.wpColorPicker("close"),n.container.find(".wp-color-result").focus(),e.stopPropagation())})}}),I.MediaControl=I.Control.extend({ready:function(){var n=this;function e(e){var t=D.Deferred();n.extended(I.UploadControl)?t.resolve():(e=parseInt(e,10),_.isNaN(e)||e<=0?(delete n.params.attachment,t.resolve()):n.params.attachment&&n.params.attachment.id===e&&t.resolve()),"pending"===t.state()&&wp.media.attachment(e).fetch().done(function(){n.params.attachment=this.attributes,t.resolve(),wp.customize.previewer.send(n.setting.id+"-attachment-data",this.attributes)}),t.done(function(){n.renderContent()})}_.bindAll(n,"restoreDefault","removeFile","openFrame","select","pausePlayer"),n.container.on("click keydown",".upload-button",n.openFrame),n.container.on("click keydown",".upload-button",n.pausePlayer),n.container.on("click keydown",".thumbnail-image img",n.openFrame),n.container.on("click keydown",".default-button",n.restoreDefault),n.container.on("click keydown",".remove-button",n.pausePlayer),n.container.on("click keydown",".remove-button",n.removeFile),n.container.on("click keydown",".remove-button",n.cleanupPlayer),I.section(n.section()).container.on("expanded",function(){n.player&&n.player.setControlsSize()}).on("collapsed",function(){n.pausePlayer()}),e(n.setting()),n.setting.bind(e)},pausePlayer:function(){this.player&&this.player.pause()},cleanupPlayer:function(){this.player&&wp.media.mixin.removePlayer(this.player)},openFrame:function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),this.frame||this.initFrame(),this.frame.open())},initFrame:function(){this.frame=wp.media({button:{text:this.params.button_labels.frame_button},states:[new wp.media.controller.Library({title:this.params.button_labels.frame_title,library:wp.media.query({type:this.params.mime_type}),multiple:!1,date:!1})]}),this.frame.on("select",this.select)},select:function(){var e=this.frame.state().get("selection").first().toJSON(),t=window._wpmejsSettings||{};this.params.attachment=e,this.setting(e.id),(e=this.container.find("audio, video").get(0))?this.player=new MediaElementPlayer(e,t):this.cleanupPlayer()},restoreDefault:function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),this.params.attachment=this.params.defaultAttachment,this.setting(this.params.defaultAttachment.url))},removeFile:function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),this.params.attachment={},this.setting(""),this.renderContent())}}),I.UploadControl=I.MediaControl.extend({select:function(){var e=this.frame.state().get("selection").first().toJSON(),t=window._wpmejsSettings||{};this.params.attachment=e,this.setting(e.url),(e=this.container.find("audio, video").get(0))?this.player=new MediaElementPlayer(e,t):this.cleanupPlayer()},success:function(){},removerVisibility:function(){}}),I.ImageControl=I.UploadControl.extend({thumbnailSrc:function(){}}),I.BackgroundControl=I.UploadControl.extend({ready:function(){I.UploadControl.prototype.ready.apply(this,arguments)},select:function(){I.UploadControl.prototype.select.apply(this,arguments),wp.ajax.post("custom-background-add",{nonce:_wpCustomizeBackground.nonces.add,wp_customize:"on",customize_theme:I.settings.theme.stylesheet,attachment_id:this.params.attachment.id})}}),I.BackgroundPositionControl=I.Control.extend({ready:function(){var e,n=this;n.container.on("change",'input[name="background-position"]',function(){var e=D(this).val().split(" ");n.settings.x(e[0]),n.settings.y(e[1])}),e=_.debounce(function(){var e=n.settings.x.get(),t=n.settings.y.get(),t=String(e)+" "+String(t);n.container.find('input[name="background-position"][value="'+t+'"]').click()}),n.settings.x.bind(e),n.settings.y.bind(e),e()}}),I.CroppedImageControl=I.MediaControl.extend({openFrame:function(e){I.utils.isKeydownButNotEnterEvent(e)||(this.initFrame(),this.frame.setState("library").open())},initFrame:function(){var e=_wpMediaViewsL10n;this.frame=wp.media({button:{text:e.select,close:!1},states:[new wp.media.controller.Library({title:this.params.button_labels.frame_title,library:wp.media.query({type:"image"}),multiple:!1,date:!1,priority:20,suggestedWidth:this.params.width,suggestedHeight:this.params.height}),new wp.media.controller.CustomizeImageCropper({imgSelectOptions:this.calculateImageSelectOptions,control:this})]}),this.frame.on("select",this.onSelect,this),this.frame.on("cropped",this.onCropped,this),this.frame.on("skippedcrop",this.onSkippedCrop,this)},onSelect:function(){var e=this.frame.state().get("selection").first().toJSON();this.params.width!==e.width||this.params.height!==e.height||this.params.flex_width||this.params.flex_height?this.frame.setState("cropper"):(this.setImageFromAttachment(e),this.frame.close())},onCropped:function(e){this.setImageFromAttachment(e)},calculateImageSelectOptions:function(e,t){var n=t.get("control"),i=!!parseInt(n.params.flex_width,10),a=!!parseInt(n.params.flex_height,10),o=e.get("width"),s=e.get("height"),r=parseInt(n.params.width,10),c=parseInt(n.params.height,10),l=r/c,d=r,e=c;return t.set("canSkipCrop",!n.mustBeCropped(i,a,r,c,o,s)),l<o/s?r=(c=s)*l:c=(r=o)/l,!(e={handles:!0,keys:!0,instance:!0,persistent:!0,imageWidth:o,imageHeight:s,minWidth:r<d?r:d,minHeight:c<e?c:e,x1:d=(o-r)/2,y1:e=(s-c)/2,x2:r+d,y2:c+e})==a&&!1==i&&(e.aspectRatio=r+":"+c),!0==a&&(delete e.minHeight,e.maxWidth=o),!0==i&&(delete e.minWidth,e.maxHeight=s),e},mustBeCropped:function(e,t,n,i,a,o){return(!0!==e||!0!==t)&&((!0!==e||i!==o)&&((!0!==t||n!==a)&&((n!==a||i!==o)&&!(a<=n))))},onSkippedCrop:function(){var e=this.frame.state().get("selection").first().toJSON();this.setImageFromAttachment(e)},setImageFromAttachment:function(e){this.params.attachment=e,this.setting(e.id)}}),I.SiteIconControl=I.CroppedImageControl.extend({initFrame:function(){var e=_wpMediaViewsL10n;this.frame=wp.media({button:{text:e.select,close:!1},states:[new wp.media.controller.Library({title:this.params.button_labels.frame_title,library:wp.media.query({type:"image"}),multiple:!1,date:!1,priority:20,suggestedWidth:this.params.width,suggestedHeight:this.params.height}),new wp.media.controller.SiteIconCropper({imgSelectOptions:this.calculateImageSelectOptions,control:this})]}),this.frame.on("select",this.onSelect,this),this.frame.on("cropped",this.onCropped,this),this.frame.on("skippedcrop",this.onSkippedCrop,this)},onSelect:function(){var e=this.frame.state().get("selection").first().toJSON(),t=this;this.params.width!==e.width||this.params.height!==e.height||this.params.flex_width||this.params.flex_height?this.frame.setState("cropper"):wp.ajax.post("crop-image",{nonce:e.nonces.edit,id:e.id,context:"site-icon",cropDetails:{x1:0,y1:0,width:this.params.width,height:this.params.height,dst_width:this.params.width,dst_height:this.params.height}}).done(function(e){t.setImageFromAttachment(e),t.frame.close()}).fail(function(){t.frame.trigger("content:error:crop")})},setImageFromAttachment:function(t){var n;_.each(["site_icon-32","thumbnail","full"],function(e){n||_.isUndefined(t.sizes[e])||(n=t.sizes[e])}),this.params.attachment=t,this.setting(t.id),n&&D('link[rel="icon"][sizes="32x32"]').attr("href",n.url)},removeFile:function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),this.params.attachment={},this.setting(""),this.renderContent(),D('link[rel="icon"][sizes="32x32"]').attr("href","/favicon.ico"))}}),I.HeaderControl=I.Control.extend({ready:function(){this.btnRemove=D("#customize-control-header_image .actions .remove"),this.btnNew=D("#customize-control-header_image .actions .new"),_.bindAll(this,"openMedia","removeImage"),this.btnNew.on("click",this.openMedia),this.btnRemove.on("click",this.removeImage),I.HeaderTool.currentHeader=this.getInitialHeaderImage(),new I.HeaderTool.CurrentView({model:I.HeaderTool.currentHeader,el:"#customize-control-header_image .current .container"}),new I.HeaderTool.ChoiceListView({collection:I.HeaderTool.UploadsList=new I.HeaderTool.ChoiceList,el:"#customize-control-header_image .choices .uploaded .list"}),new I.HeaderTool.ChoiceListView({collection:I.HeaderTool.DefaultsList=new I.HeaderTool.DefaultsList,el:"#customize-control-header_image .choices .default .list"}),I.HeaderTool.combinedList=I.HeaderTool.CombinedList=new I.HeaderTool.CombinedList([I.HeaderTool.UploadsList,I.HeaderTool.DefaultsList]),wp.media.controller.Cropper.prototype.defaults.doCropArgs.wp_customize="on",wp.media.controller.Cropper.prototype.defaults.doCropArgs.customize_theme=I.settings.theme.stylesheet},getInitialHeaderImage:function(){if(!I.get().header_image||!I.get().header_image_data||_.contains(["remove-header","random-default-image","random-uploaded-image"],I.get().header_image))return new I.HeaderTool.ImageModel;var e=(e=_.find(_wpCustomizeHeader.uploads,function(e){return e.attachment_id===I.get().header_image_data.attachment_id}))||{url:I.get().header_image,thumbnail_url:I.get().header_image,attachment_id:I.get().header_image_data.attachment_id};return new I.HeaderTool.ImageModel({header:e,choice:e.url.split("/").pop()})},calculateImageSelectOptions:function(e,t){var n=parseInt(_wpCustomizeHeader.data.width,10),i=parseInt(_wpCustomizeHeader.data.height,10),a=!!parseInt(_wpCustomizeHeader.data["flex-width"],10),o=!!parseInt(_wpCustomizeHeader.data["flex-height"],10),s=e.get("width"),e=e.get("height");return this.headerImage=new I.HeaderTool.ImageModel,this.headerImage.set({themeWidth:n,themeHeight:i,themeFlexWidth:a,themeFlexHeight:o,imageWidth:s,imageHeight:e}),t.set("canSkipCrop",!this.headerImage.shouldBeCropped()),(t=n/i)<s/e?n=(i=e)*t:i=(n=s)/t,!(e={handles:!0,keys:!0,instance:!0,persistent:!0,imageWidth:s,imageHeight:e,x1:0,y1:0,x2:n,y2:i})==o&&!1==a&&(e.aspectRatio=n+":"+i),!1==o&&(e.maxHeight=i),!1==a&&(e.maxWidth=n),e},openMedia:function(e){var t=_wpMediaViewsL10n;e.preventDefault(),this.frame=wp.media({button:{text:t.selectAndCrop,close:!1},states:[new wp.media.controller.Library({title:t.chooseImage,library:wp.media.query({type:"image"}),multiple:!1,date:!1,priority:20,suggestedWidth:_wpCustomizeHeader.data.width,suggestedHeight:_wpCustomizeHeader.data.height}),new wp.media.controller.Cropper({imgSelectOptions:this.calculateImageSelectOptions})]}),this.frame.on("select",this.onSelect,this),this.frame.on("cropped",this.onCropped,this),this.frame.on("skippedcrop",this.onSkippedCrop,this),this.frame.open()},onSelect:function(){this.frame.setState("cropper")},onCropped:function(e){var t=e.url,n=e.attachment_id,i=e.width,e=e.height;this.setImageFromURL(t,n,i,e)},onSkippedCrop:function(e){var t=e.get("url"),n=e.get("width"),i=e.get("height");this.setImageFromURL(t,e.id,n,i)},setImageFromURL:function(e,t,n,i){var a={};a.url=e,a.thumbnail_url=e,a.timestamp=_.now(),t&&(a.attachment_id=t),n&&(a.width=n),i&&(a.height=i),e=new I.HeaderTool.ImageModel({header:a,choice:e.split("/").pop()}),I.HeaderTool.UploadsList.add(e),I.HeaderTool.currentHeader.set(e.toJSON()),e.save(),e.importImage()},removeImage:function(){I.HeaderTool.currentHeader.trigger("hide"),I.HeaderTool.CombinedList.trigger("control:removeImage")}}),I.ThemeControl=I.Control.extend({touchDrag:!1,isRendered:!1,renderContent:function(){var t=this,n=arguments;I.section(t.section(),function(e){e.expanded()?(I.Control.prototype.renderContent.apply(t,n),t.isRendered=!0):e.expanded.bind(function(e){e&&!t.isRendered&&(I.Control.prototype.renderContent.apply(t,n),t.isRendered=!0)})})},ready:function(){var t=this;t.container.on("touchmove",".theme",function(){t.touchDrag=!0}),t.container.on("click keydown touchend",".theme",function(e){if(!I.utils.isKeydownButNotEnterEvent(e))return!0===t.touchDrag?t.touchDrag=!1:void(D(e.target).is(".theme-actions .button")||I.section(t.section()).loadThemePreview(t.params.theme.id))}),t.container.on("click keydown",".theme-actions .theme-details",function(e){I.utils.isKeydownButNotEnterEvent(e)||(e.preventDefault(),I.section(t.section()).showDetails(t.params.theme))}),t.container.on("render-screenshot",function(){var e=D(this).find("img"),t=e.data("src");t&&e.attr("src",t)})},filter:function(e){var t=this;-1!==(t.params.theme.name+" "+t.params.theme.description+" "+t.params.theme.tags+" "+t.params.theme.author).toLowerCase().replace("-"," ").search(e)?t.activate():t.deactivate()}}),I.defaultConstructor=I.Setting,I.control=new I.Values({defaultConstructor:I.Control}),I.section=new I.Values({defaultConstructor:I.Section}),I.panel=new I.Values({defaultConstructor:I.Panel}),I.PreviewFrame=I.Messenger.extend({sensitivity:null,initialize:function(e,t){var n=D.Deferred();n.promise(this),this.container=e.container,D.extend(e,{channel:I.PreviewFrame.uuid()}),I.Messenger.prototype.initialize.call(this,e,t),this.add("previewUrl",e.previewUrl),this.query=D.extend(e.query||{},{customize_messenger_channel:this.channel()}),this.run(n)},run:function(t){var e,n,i,a=this,o=!1,s=!1,r=null,c="{}"!==a.query.customized;a._ready&&a.unbind("ready",a._ready),a._ready=function(e){s=!0,r=e,a.container.addClass("iframe-ready"),e&&o&&t.resolveWith(a,[e])},a.bind("ready",a._ready),(e=document.createElement("a")).href=a.previewUrl(),n=_.extend(I.utils.parseQueryString(e.search.substr(1)),{customize_changeset_uuid:a.query.customize_changeset_uuid,customize_theme:a.query.customize_theme,customize_messenger_channel:a.query.customize_messenger_channel}),e.search=D.param(n),a.iframe=D("<iframe />",{title:I.l10n.previewIframeTitle,name:"customize-"+a.channel()}),a.iframe.attr("onmousewheel",""),c?a.iframe.attr("data-src",e.href):a.iframe.attr("src",e.href),a.iframe.appendTo(a.container),a.targetWindow(a.iframe[0].contentWindow),c&&((i=D("<form>",{action:e.href,target:a.iframe.attr("name"),method:"post",hidden:"hidden"})).append(D("<input>",{type:"hidden",name:"_method",value:"GET"})),_.each(a.query,function(e,t){i.append(D("<input>",{type:"hidden",name:t,value:e}))}),a.container.append(i),i.submit(),i.remove()),a.bind("iframe-loading-error",function(e){a.iframe.remove(),0!==e?-1!==e?t.rejectWith(a,["request failure"]):t.rejectWith(a,["cheatin"]):a.login(t)}),a.iframe.one("load",function(){o=!0,s?t.resolveWith(a,[r]):setTimeout(function(){t.rejectWith(a,["ready timeout"])},a.sensitivity)})},login:function(n){var i=this,a=function(){n.rejectWith(i,["logged out"])};if(this.triedLogin)return a();D.get(I.settings.url.ajax,{action:"logged-in"}).fail(a).done(function(e){var t;"1"!==e&&a(),(t=D("<iframe />",{src:i.previewUrl(),title:I.l10n.previewIframeTitle}).hide()).appendTo(i.container),t.on("load",function(){i.triedLogin=!0,t.remove(),i.run(n)})})},destroy:function(){I.Messenger.prototype.destroy.call(this),this.iframe&&this.iframe.remove(),delete this.iframe,delete this.targetWindow}}),o=0,I.PreviewFrame.uuid=function(){return"preview-"+String(o++)},I.setDocumentTitle=function(e){e=I.settings.documentTitleTmpl.replace("%s",e);document.title=e,I.trigger("title",e)},I.Previewer=I.Messenger.extend({refreshBuffer:null,initialize:function(e,t){var n,o=this,i=document.createElement("a");D.extend(o,t||{}),o.deferred={active:D.Deferred()},o.refresh=_.debounce((n=o.refresh,function(){var e,t=function(){return 0===I.state("processing").get()};t()?n.call(o):(e=function(){t()&&(n.call(o),I.state("processing").unbind(e))},I.state("processing").bind(e))}),o.refreshBuffer),o.container=I.ensure(e.container),o.allowedUrls=e.allowedUrls,e.url=window.location.href,I.Messenger.prototype.initialize.call(o,e),i.href=o.origin(),o.add("scheme",i.protocol.replace(/:$/,"")),o.add("previewUrl",e.previewUrl).setter(function(e){var n,i=null,t=[],a=document.createElement("a");return a.href=e,/\/wp-(admin|includes|content)(\/|$)/.test(a.pathname)?null:(1<a.search.length&&(delete(e=I.utils.parseQueryString(a.search.substr(1))).customize_changeset_uuid,delete e.customize_theme,delete e.customize_messenger_channel,_.isEmpty(e)?a.search="":a.search=D.param(e)),t.push(a),o.scheme.get()+":"!==a.protocol&&((a=document.createElement("a")).href=t[0].href,a.protocol=o.scheme.get()+":",t.unshift(a)),n=document.createElement("a"),_.find(t,function(t){return!_.isUndefined(_.find(o.allowedUrls,function(e){if(n.href=e,a.protocol===n.protocol&&a.host===n.host&&0===a.pathname.indexOf(n.pathname.replace(/\/$/,"")))return i=t.href,!0}))}),i)}),o.bind("ready",o.ready),o.deferred.active.done(_.bind(o.keepPreviewAlive,o)),o.bind("synced",function(){o.send("active")}),o.previewUrl.bind(o.refresh),o.scroll=0,o.bind("scroll",function(e){o.scroll=e}),o.bind("url",function(e){var t,n=!1;o.scroll=0,t=function(){n=!0},o.previewUrl.bind(t),o.previewUrl.set(e),o.previewUrl.unbind(t),n||o.refresh()}),o.bind("documentTitle",function(e){I.setDocumentTitle(e)})},ready:function(e){var t=this,n={};n.settings=I.get(),n["settings-modified-while-loading"]=t.settingsModifiedWhileLoading,"resolved"===t.deferred.active.state()&&!t.loading||(n.scroll=t.scroll),n["edit-shortcut-visibility"]=I.state("editShortcutVisibility").get(),t.send("sync",n),e.currentUrl&&(t.previewUrl.unbind(t.refresh),t.previewUrl.set(e.currentUrl),t.previewUrl.bind(t.refresh)),t={panel:e.activePanels,section:e.activeSections,control:e.activeControls},_(t).each(function(n,i){I[i].each(function(e,t){_.isUndefined(I.settings[i+"s"][t])&&_.isUndefined(n[t])||(n[t]?e.activate():e.deactivate())})}),e.settingValidities&&I._handleSettingValidities({settingValidities:e.settingValidities,focusInvalidControl:!1})},keepPreviewAlive:function(){var e,t=function(){e=setTimeout(i,I.settings.timeouts.keepAliveCheck)},n=function(){I.state("previewerAlive").set(!0),clearTimeout(e),t()},i=function(){I.state("previewerAlive").set(!1)};t(),this.bind("ready",n),this.bind("keep-alive",n)},query:function(){},abort:function(){this.loading&&(this.loading.destroy(),delete this.loading)},refresh:function(){var e,i=this;i.send("loading-initiated"),i.abort(),i.loading=new I.PreviewFrame({url:i.url(),previewUrl:i.previewUrl(),query:i.query({excludeCustomizedSaved:!0})||{},container:i.container}),i.settingsModifiedWhileLoading={},e=function(e){i.settingsModifiedWhileLoading[e.id]=!0},I.bind("change",e),i.loading.always(function(){I.unbind("change",e)}),i.loading.done(function(e){var t,n=this;i.preview=n,i.targetWindow(n.targetWindow()),i.channel(n.channel()),t=function(){n.unbind("synced",t),i._previousPreview&&i._previousPreview.destroy(),i._previousPreview=i.preview,i.deferred.active.resolve(),delete i.loading},n.bind("synced",t),i.trigger("ready",e)}),i.loading.fail(function(e){i.send("loading-failed"),"logged out"===e&&(i.preview&&(i.preview.destroy(),delete i.preview),i.login().done(i.refresh)),"cheatin"===e&&i.cheatin()})},login:function(){var t,n,i,a=this;return this._login||(t=D.Deferred(),this._login=t.promise(),n=new I.Messenger({channel:"login",url:I.settings.url.login}),i=D("<iframe />",{src:I.settings.url.login,title:I.l10n.loginIframeTitle}).appendTo(this.container),n.targetWindow(i[0].contentWindow),n.bind("login",function(){var e=a.refreshNonces();e.always(function(){i.remove(),n.destroy(),delete a._login}),e.done(function(){t.resolve()}),e.fail(function(){a.cheatin(),t.reject()})}),this._login)},cheatin:function(){D(document.body).empty().addClass("cheatin").append("<h1>"+I.l10n.cheatin+"</h1><p>"+I.l10n.notAllowed+"</p>")},refreshNonces:function(){var e,t=D.Deferred();return t.promise(),(e=wp.ajax.post("customize_refresh_nonces",{wp_customize:"on",customize_theme:I.settings.theme.stylesheet})).done(function(e){I.trigger("nonce-refresh",e),t.resolve()}),e.fail(function(){t.reject()}),t}}),I.settingConstructor={},I.controlConstructor={color:I.ColorControl,media:I.MediaControl,upload:I.UploadControl,image:I.ImageControl,cropped_image:I.CroppedImageControl,site_icon:I.SiteIconControl,header:I.HeaderControl,background:I.BackgroundControl,background_position:I.BackgroundPositionControl,theme:I.ThemeControl},I.panelConstructor={},I.sectionConstructor={themes:I.ThemesSection},I._handleSettingValidities=function(e){var o=[],n=!1;_.each(e.settingValidities,function(t,e){var a=I(e);a&&(_.isObject(t)&&_.each(t,function(e,t){var n=!1,i=new I.Notification(t,_.extend({fromServer:!0},e)),e=a.notifications(i.code);(n=e?i.type!==e.type||i.message!==e.message||!_.isEqual(i.data,e.data):n)&&a.notifications.remove(t),a.notifications.has(i.code)||a.notifications.add(t,i),o.push(a.id)}),a.notifications.each(function(e){!e.fromServer||"error"!==e.type||!0!==t&&t[e.code]||a.notifications.remove(e.code)}))}),e.focusInvalidControl&&(e=I.findControlsForSettings(o),_(_.values(e)).find(function(e){return _(e).find(function(e){var t=e.section()&&I.section.has(e.section())&&I.section(e.section()).expanded();return(t=t&&e.expanded?e.expanded():t)&&(e.focus(),n=!0),n})}),n||_.isEmpty(e)||_.values(e)[0][0].focus())},I.findControlsForSettings=function(e){var n,i={};return _.each(_.unique(e),function(e){var t=I(e);t&&(n=t.findControls())&&0<n.length&&(i[e]=n)}),i},I.reflowPaneContents=_.bind(function(){var i,e,t,a=[],o=!1;document.activeElement&&(e=D(document.activeElement)),I.panel.each(function(e){var t=e.sections(),n=_.pluck(t,"headContainer");a.push(e),i=e.contentContainer.is("ul")?e.contentContainer:e.contentContainer.find("ul:first"),I.utils.areElementListsEqual(n,i.children("[id]"))||(_(t).each(function(e){i.append(e.headContainer)}),o=!0)}),I.section.each(function(e){var t=e.controls(),n=_.pluck(t,"container");e.panel()||a.push(e),i=e.contentContainer.is("ul")?e.contentContainer:e.contentContainer.find("ul:first"),I.utils.areElementListsEqual(n,i.children("[id]"))||(_(t).each(function(e){i.append(e.container)}),o=!0)}),a.sort(I.utils.prioritySort),t=_.pluck(a,"headContainer"),i=D("#customize-theme-controls .customize-pane-parent"),I.utils.areElementListsEqual(t,i.children())||(_(a).each(function(e){i.append(e.headContainer)}),o=!0),I.panel.each(function(e){var t=e.active();e.active.callbacks.fireWith(e.active,[t,t])}),I.section.each(function(e){var t=e.active();e.active.callbacks.fireWith(e.active,[t,t])}),o&&e&&e.focus(),I.trigger("pane-contents-reflowed")},I),D(function(){var u,t,n,i,a,p,o,s,r,c,l,d,e,h,f,m,g,v,w,b,C,y,x,k,z,S,E,T,A,P;I.settings=window._wpCustomizeSettings,I.l10n=window._wpCustomizeControlsL10n,I.settings&&(!D.support.postMessage||!D.support.cors&&I.settings.isCrossDomain||(null===I.PreviewFrame.prototype.sensitivity&&(I.PreviewFrame.prototype.sensitivity=I.settings.timeouts.previewFrameSensitivity),null===I.Previewer.prototype.refreshBuffer&&(I.Previewer.prototype.refreshBuffer=I.settings.timeouts.windowRefresh),t=D(document.body),n=t.children(".wp-full-overlay"),i=D("#customize-info .panel-title.site-title"),a=D(".customize-controls-close"),p=D("#save"),o=D("#customize-footer-actions"),D("#customize-controls").on("keydown",function(e){var t=13===e.which,n=D(e.target);t&&(n.is("input:not([type=button])")||n.is("select"))&&e.preventDefault()}),D(".customize-info").find("> .accordion-section-title .customize-help-toggle").on("click",function(){var e=D(this).closest(".accordion-section"),t=e.find(".customize-panel-description:first");e.hasClass("cannot-expand")||(e.hasClass("open")?(e.toggleClass("open"),t.slideUp(I.Panel.prototype.defaultExpandedArguments.duration),D(this).attr("aria-expanded",!1)):(t.slideDown(I.Panel.prototype.defaultExpandedArguments.duration),e.toggleClass("open"),D(this).attr("aria-expanded",!0)))}),I.previewer=new I.Previewer({container:"#customize-preview",form:"#customize-controls",previewUrl:I.settings.url.preview,allowedUrls:I.settings.url.allowed},{nonce:I.settings.nonce,query:function(e){var t={wp_customize:"on",customize_theme:I.settings.theme.stylesheet,nonce:this.nonce.preview,customize_changeset_uuid:I.settings.changeset.uuid};return t.customized=JSON.stringify(I.dirtyValues({unsaved:e&&e.excludeCustomizedSaved})),t},save:function(i){var e,t,a,o=this,s=D.Deferred(),r="publish",n=I.state("processing"),c={},l=[];function d(e){c[e.id]=!0}return i&&i.status&&(r=i.status),I.state("saving").get()&&(s.reject("already_saving"),s.promise()),I.state("saving").set(!0),I.bind("change",d),t=function(){var e,n={},t=I._latestRevision;if(I.each(function(t){t.notifications.each(function(e){"error"!==e.type||e.fromServer||(l.push(t.id),n[t.id]||(n[t.id]={}),n[t.id][e.code]=e)})}),a=I.findControlsForSettings(l),!_.isEmpty(a))return _.values(a)[0][0].focus(),I.unbind("change",d),s.rejectWith(o,[{setting_invalidities:n}]),I.state("saving").set(!1),s.promise();e=D.extend(o.query({excludeCustomizedSaved:!1}),{nonce:o.nonce.save,customize_changeset_status:r}),i&&i.date&&(e.customize_changeset_date=i.date),i&&i.title&&(e.customize_changeset_title=i.title),e=wp.ajax.post("customize_save",e),p.prop("disabled",!0),I.trigger("save",e),e.always(function(){I.state("saving").set(!1),p.prop("disabled",!1),I.unbind("change",d)}),e.fail(function(e){"0"===e?e="not_logged_in":"-1"===e&&(e="invalid_nonce"),"invalid_nonce"===e?o.cheatin():"not_logged_in"===e&&(o.preview.iframe.hide(),o.login().done(function(){o.save(),o.preview.iframe.show()})),e.setting_validities&&I._handleSettingValidities({settingValidities:e.setting_validities,focusInvalidControl:!0}),s.rejectWith(o,[e]),I.trigger("error",e)}),e.done(function(e){o.send("saved",e),I.state("changesetStatus").set(e.changeset_status),"publish"===e.changeset_status&&(I.each(function(e){e._dirty&&(_.isUndefined(I._latestSettingRevisions[e.id])||I._latestSettingRevisions[e.id]<=t)&&(e._dirty=!1)}),I.state("changesetStatus").set(""),I.settings.changeset.uuid=e.next_changeset_uuid,u.send("changeset-uuid",I.settings.changeset.uuid)),e.setting_validities&&I._handleSettingValidities({settingValidities:e.setting_validities,focusInvalidControl:!0}),s.resolveWith(o,[e]),I.trigger("saved",e),_.isEmpty(c)||I.state("saved").set(!1)})},0===n()?t():(e=function(){0===n()&&(I.state.unbind("change",e),t())},I.state.bind("change",e)),s.promise()}}),D.ajaxPrefilter(function(e){/wp_customize=on/.test(e.data)&&(e.data+="&"+D.param({customize_preview_nonce:I.settings.nonce.preview}))}),I.previewer.bind("nonce",function(e){D.extend(this.nonce,e)}),I.bind("nonce-refresh",function(e){D.extend(I.settings.nonce,e),D.extend(I.previewer.nonce,e),I.previewer.send("nonce-refresh",e)}),D.each(I.settings.settings,function(e,t){t=new(I.settingConstructor[t.type]||I.Setting)(e,t.value,{transport:t.transport,previewer:I.previewer,dirty:!!t.dirty});I.add(e,t)}),D.each(I.settings.panels,function(e,t){t=new(I.panelConstructor[t.type]||I.Panel)(e,{params:t});I.panel.add(e,t)}),D.each(I.settings.sections,function(e,t){t=new(I.sectionConstructor[t.type]||I.Section)(e,{params:t});I.section.add(e,t)}),D.each(I.settings.controls,function(e,t){t=new(I.controlConstructor[t.type]||I.Control)(e,{params:t,previewer:I.previewer});I.control.add(e,t)}),_.each(["panel","section","control"],function(e){var t=I.settings.autofocus[e];t&&I[e](t,function(e){e.deferred.embedded.done(function(){I.previewer.deferred.active.done(function(){e.focus()})})})}),I.bind("ready",I.reflowPaneContents),D([I.panel,I.section,I.control]).each(function(e,t){var n=_.debounce(I.reflowPaneContents,I.settings.timeouts.reflowPaneContents);t.bind("add",n),t.bind("change",n),t.bind("remove",n)}),r=new I.Values,c=r.create("saved"),l=r.create("saving"),d=r.create("activated"),e=r.create("processing"),h=r.create("paneVisible"),f=r.create("expandedPanel"),m=r.create("expandedSection"),g=r.create("changesetStatus"),v=r.create("previewerAlive"),S=r.create("editShortcutVisibility"),r.bind("change",function(){var e;d()?""===g.get()&&c()?(p.val(I.l10n.saved),a.find(".screen-reader-text").text(I.l10n.close)):(p.val(I.l10n.save),a.find(".screen-reader-text").text(I.l10n.cancel)):(p.val(I.l10n.activate),a.find(".screen-reader-text").text(I.l10n.cancel)),e=!l()&&(!d()||!c()||""!==g()&&"publish"!==g()),p.prop("disabled",!e)}),g(I.settings.changeset.status),c(!0),""===g()&&I.each(function(e){e._dirty&&c(!1)}),l(!1),d(I.settings.theme.active),e(0),h(!0),f(!1),m(!1),v(!0),S("visible"),I.bind("change",function(){r("saved").get()&&(r("saved").set(!1),s(!0))}),l.bind(function(e){t.toggleClass("saving",e)}),I.bind("saved",function(e){r("saved").set(!0),"publish"===e.changeset_status&&r("activated").set(!0)}),d.bind(function(e){e&&I.trigger("activated")}),s=function(e){var t,n;if(history.replaceState){if((t=document.createElement("a")).href=location.href,n=I.utils.parseQueryString(t.search.substr(1)),e){if(n.changeset_uuid===I.settings.changeset.uuid)return;n.changeset_uuid=I.settings.changeset.uuid}else{if(!n.changeset_uuid)return;delete n.changeset_uuid}t.search=D.param(n),history.replaceState({},document.title,t.href)}},g.bind(function(e){s(""!==e&&"publish"!==e)}),I.state=r,I.previewer.previewUrl()?I.previewer.refresh():I.previewer.previewUrl(I.settings.url.home),p.click(function(e){I.previewer.save(),e.preventDefault()}).keydown(function(e){9!==e.which&&(13===e.which&&I.previewer.save(),e.preventDefault())}),a.keydown(function(e){9!==e.which&&(13===e.which&&this.click(),e.preventDefault())}),D(".collapse-sidebar").on("click",function(){I.state("paneVisible").set(!I.state("paneVisible").get())}),I.state("paneVisible").bind(function(e){n.toggleClass("preview-only",!e),n.toggleClass("expanded",e),n.toggleClass("collapsed",!e),e?D(".collapse-sidebar").attr({"aria-expanded":"true","aria-label":I.l10n.collapseSidebar}):D(".collapse-sidebar").attr({"aria-expanded":"false","aria-label":I.l10n.expandSidebar})}),D("body").on("keydown",function(e){var t,n=[],i=[],a=[];27===e.which&&(D(e.target).is("body")||D.contains(D("#customize-controls")[0],e.target))&&(I.control.each(function(e){e.expanded&&e.expanded()&&_.isFunction(e.collapse)&&n.push(e)}),I.section.each(function(e){e.expanded()&&i.push(e)}),I.panel.each(function(e){e.expanded()&&a.push(e)}),0<n.length&&0===i.length&&(n.length=0),(t=n[0]||i[0]||a[0])&&(t.collapse(),e.preventDefault()))}),D(".customize-controls-preview-toggle").on("click",function(){I.state("paneVisible").set(!I.state("paneVisible").get())}),z=D(".wp-full-overlay-sidebar-content"),S=function(e){var t=e,n=I.state("expandedSection").get(),e=I.state("expandedPanel").get();if(x&&x.element&&b(x.element),!t)if(!n&&e&&e.contentContainer)t=e;else{if(e||!n||!n.contentContainer)return void(x=!1);t=n}(e=t.contentContainer.find(".customize-section-title, .panel-meta").first()).length?(x={instance:t,element:e,parent:e.closest(".customize-pane-child"),height:w(e)},n&&C(x.element,x.parent)):x=!1},I.state("expandedSection").bind(S),I.state("expandedPanel").bind(S),z.on("scroll",_.throttle(function(){var e,t;x&&(e=z.scrollTop(),t=!k||e<=k,y(x,k=e,t))},8)),b=function(e){e.hasClass("is-sticky")&&e.removeClass("is-sticky").addClass("maybe-sticky is-in-view").css("top",z.scrollTop()+"px")},C=function(e,t){e.removeClass("maybe-sticky is-in-view").css({width:"",top:""}),t.css("padding-top","")},w=function(e){var t=e.data("height");return t||(t=e.outerHeight(),e.data("height",t)),t},y=function(e,t,n){var i=e.element,a=e.parent,o=e.height,s=parseInt(i.css("top"),10),r=i.hasClass("maybe-sticky"),c=i.hasClass("is-sticky"),e=i.hasClass("is-in-view");if(!n)return c&&(s=t,i.removeClass("is-sticky").css({top:s+"px",width:""})),void(e&&s+o<t&&(i.removeClass("is-in-view"),a.css("padding-top","")));if(!r&&o<=t)r=!0,i.addClass("maybe-sticky");else if(0===t)return i.removeClass("maybe-sticky is-in-view is-sticky").css({top:"",width:""}),void a.css("padding-top","");e&&!c?t<=s&&i.addClass("is-sticky").css({top:"",width:a.outerWidth()+"px"}):r&&!e&&(i.addClass("is-in-view").css("top",t-o+"px"),a.css("padding-top",o+"px"))},I.previewedDevice=new I.Value,I.bind("ready",function(){_.find(I.settings.previewableDevices,function(e,t){if(!0===e["default"])return I.previewedDevice.set(t),!0})}),o.find(".devices button").on("click",function(e){I.previewedDevice.set(D(e.currentTarget).data("device"))}),I.previewedDevice.bind(function(e){var t=D(".wp-full-overlay"),n="";o.find(".devices button").removeClass("active").attr("aria-pressed",!1),o.find(".devices .preview-"+e).addClass("active").attr("aria-pressed",!0),D.each(I.settings.previewableDevices,function(e){n+=" preview-"+e}),t.removeClass(n).addClass("preview-"+e)}),i.length&&I("blogname",function(e){function t(){i.text(D.trim(e())||I.l10n.untitledBlogName)}e.bind(t),t()}),(u=new I.Messenger({url:I.settings.url.parent,channel:"loader"})).bind("back",function(){a.on("click.customize-controls-close",function(e){e.preventDefault(),u.send("close")})}),D(window).on("beforeunload.customize-confirm",function(){if(!I.state("saved")())return setTimeout(function(){n.removeClass("customize-loading")},1),I.l10n.saveAlert}),D.each(["saved","change"],function(e,t){I.bind(t,function(){u.send(t)})}),I.bind("title",function(e){u.send("title",e)}),u.send("changeset-uuid",I.settings.changeset.uuid),u.send("ready"),D.each({background_image:{controls:["background_preset","background_position","background_size","background_repeat","background_attachment"],callback:function(e){return!!e}},show_on_front:{controls:["page_on_front","page_for_posts"],callback:function(e){return"page"===e}},header_textcolor:{controls:["header_textcolor"],callback:function(e){return"blank"!==e}}},function(e,i){I(e,function(n){D.each(i.controls,function(e,t){I.control(t,function(t){function e(e){t.container.toggle(i.callback(e))}e(n.get()),n.bind(e)})})})}),I.control("background_preset",function(e){var i={"default":[!1,!1,!1,!1],fill:[!0,!1,!1,!1],fit:[!0,!1,!0,!1],repeat:[!0,!1,!1,!0],custom:[!0,!0,!0,!0]},a={"default":[_wpCustomizeBackground.defaults["default-position-x"],_wpCustomizeBackground.defaults["default-position-y"],_wpCustomizeBackground.defaults["default-size"],_wpCustomizeBackground.defaults["default-repeat"],_wpCustomizeBackground.defaults["default-attachment"]],fill:["left","top","cover","no-repeat","fixed"],fit:["left","top","contain","no-repeat","fixed"],repeat:["left","top","auto","repeat","scroll"]},t=function(n){_.each(["background_position","background_size","background_repeat","background_attachment"],function(e,t){e=I.control(e);e&&e.container.toggle(i[n][t])})},n=function(n){_.each(["background_position_x","background_position_y","background_size","background_repeat","background_attachment"],function(e,t){e=I(e);e&&e.set(a[n][t])})},o=e.setting.get();t(o),e.setting.bind("change",function(e){t(e),"custom"!==e&&n(e)})}),I.control("background_repeat",function(t){t.elements[0].unsync(I("background_repeat")),t.element=new I.Element(t.container.find("input")),t.element.set("no-repeat"!==t.setting()),t.element.bind(function(e){t.setting.set(e?"repeat":"no-repeat")}),t.setting.bind(function(e){t.element.set("no-repeat"!==e)})}),I.control("background_attachment",function(t){t.elements[0].unsync(I("background_attachment")),t.element=new I.Element(t.container.find("input")),t.element.set("fixed"!==t.setting()),t.element.bind(function(e){t.setting.set(e?"scroll":"fixed")}),t.setting.bind(function(e){t.element.set("fixed"!==e)})}),I.control("display_header_text",function(t){var n="";t.elements[0].unsync(I("header_textcolor")),t.element=new I.Element(t.container.find("input")),t.element.set("blank"!==t.setting()),t.element.bind(function(e){e||(n=I("header_textcolor").get()),t.setting.set(e?n:"blank")}),t.setting.bind(function(e){t.element.set("blank"!==e)})}),I("show_on_front","page_on_front",function(e,t){function n(){"page"===e()&&0<parseInt(t(),10)&&I.previewer.previewUrl.set(I.settings.url.home)}e.bind(n),t.bind(n)}),I("page_for_posts",function(e){e.bind(function(e){0<(e=parseInt(e,10))&&I.previewer.previewUrl.set(I.settings.url.home+"?page_id="+e)})}),I.control("custom_css",function(e){e.deferred.embedded.done(function(){var a=e.container.find("textarea"),o=a[0];a.on("blur",function(){a.data("next-tab-blurs",!1)}),a.on("keydown",function(e){var t,n,i;27!==e.keyCode?9!==e.keyCode||e.ctrlKey||e.altKey||e.shiftKey||a.data("next-tab-blurs")||(t=o.selectionStart,n=o.selectionEnd,i=o.value,0<=t&&(o.value=i.substring(0,t).concat("\t",i.substring(n)),a.selectionStart=o.selectionEnd=t+1),e.stopPropagation(),e.preventDefault()):a.data("next-tab-blurs")||(a.data("next-tab-blurs",!0),e.stopPropagation())})})}),I.control("header_video",function(t){t.deferred.embedded.done(function(){function e(){var e=I.section(t.section());e&&(e=e.container.find(".header-video-not-currently-previewable:first"),t.active.get()?e.stop().slideUp("fast"):e.stop().slideDown("fast"))}e(),t.active.bind(e)})}),I.previewer.bind("selective-refresh-setting-validities",function(e){I._handleSettingValidities({settingValidities:e,focusInvalidControl:!1})}),I.previewer.bind("focus-control-for-setting",function(n){var i=[];I.control.each(function(e){var t=_.pluck(e.settings,"id");-1!==_.indexOf(t,n)&&i.push(e)}),i.length&&(i.sort(function(e,t){return e.priority()-t.priority()}),i[0].focus())}),I.previewer.bind("refresh",function(){I.previewer.refresh()}),I.state("paneVisible").bind(function(e){var t=window.matchMedia?window.matchMedia("screen and ( max-width: 640px )").matches:D(window).width()<=640;I.state("editShortcutVisibility").set(e||t?"visible":"hidden")}),window.matchMedia&&window.matchMedia("screen and ( max-width: 640px )").addListener(function(){var e=I.state("paneVisible");e.callbacks.fireWith(e,[e.get(),e.get()])}),I.previewer.bind("edit-shortcut-visibility",function(e){I.state("editShortcutVisibility").set(e)}),I.state("editShortcutVisibility").bind(function(e){I.previewer.send("edit-shortcut-visibility",e)}),T=!1,A=function(){T||(T=!0,I.requestChangesetUpdate().always(function(){T=!1})),P()},(P=function(){clearTimeout(E),E=setTimeout(function(){A()},I.settings.timeouts.changesetAutoSave)})(),D(window).on("blur.wp-customize-changeset-update",function(){A()}),D(window).on("beforeunload.wp-customize-changeset-update",function(){A()}),I.trigger("ready")))})}((wp,jQuery)); accordion.js 0000666 00000005546 15213733063 0007064 0 ustar 00 /** * Accordion-folding functionality. * * Markup with the appropriate classes will be automatically hidden, * with one section opening at a time when its title is clicked. * Use the following markup structure for accordion behavior: * * <div class="accordion-container"> * <div class="accordion-section open"> * <h3 class="accordion-section-title"></h3> * <div class="accordion-section-content"> * </div> * </div> * <div class="accordion-section"> * <h3 class="accordion-section-title"></h3> * <div class="accordion-section-content"> * </div> * </div> * <div class="accordion-section"> * <h3 class="accordion-section-title"></h3> * <div class="accordion-section-content"> * </div> * </div> * </div> * * Note that any appropriate tags may be used, as long as the above classes are present. * * @since 3.6.0. */ ( function( $ ){ $( document ).ready( function () { // Expand/Collapse accordion sections 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 ) ); }); }); /** * Close the current accordion section and open a new one. * * @param {Object} el Title element of the accordion section to toggle. * @since 3.6.0 */ function accordionSwitch ( el ) { var section = el.closest( '.accordion-section' ), sectionToggleControl = section.find( '[aria-expanded]' ).first(), container = section.closest( '.accordion-container' ), siblings = container.find( '.open' ), siblingsToggleControl = siblings.find( '[aria-expanded]' ).first(), content = section.find( '.accordion-section-content' ); // This section has no content and cannot be expanded. if ( section.hasClass( 'cannot-expand' ) ) { return; } // Add a class to the container to let us know something is happening inside. // This helps in cases such as hiding a scrollbar while animations are executing. container.addClass( 'opening' ); if ( section.hasClass( 'open' ) ) { section.toggleClass( 'open' ); content.toggle( true ).slideToggle( 150 ); } else { siblingsToggleControl.attr( 'aria-expanded', 'false' ); siblings.removeClass( 'open' ); siblings.find( '.accordion-section-content' ).show().slideUp( 150 ); content.toggle( false ).slideToggle( 150 ); section.toggleClass( 'open' ); } // We have to wait for the animations to finish setTimeout(function(){ container.removeClass( 'opening' ); }, 150); // If there's an element with an aria-expanded attribute, assume it's a toggle control and toggle the aria-expanded value. if ( sectionToggleControl ) { sectionToggleControl.attr( 'aria-expanded', String( sectionToggleControl.attr( 'aria-expanded' ) === 'false' ) ); } } })(jQuery); post.min.js 0000666 00000043413 15213733063 0006665 0 ustar 00 var commentsBox,WPSetThumbnailHTML,WPSetThumbnailID,WPRemoveThumbnail,wptitlehint,editPermalink,makeSlugeditClickable=editPermalink=function(){};window.wp=window.wp||{},function(a){var t=!1;commentsBox={st:0,get:function(t,e){var i=this.st;return e=e||20,this.st+=e,this.total=t,a("#commentsdiv .spinner").addClass("is-active"),e={action:"get-comments",mode:"single",_ajax_nonce:a("#add_comment_nonce").val(),p:a("#post_ID").val(),start:i,number:e},a.post(ajaxurl,e,function(t){return t=wpAjax.parseAjaxResponse(t),a("#commentsdiv .widefat").show(),a("#commentsdiv .spinner").removeClass("is-active"),"object"==typeof t&&t.responses[0]?(a("#the-comment-list").append(t.responses[0].data),theList=theExtraList=null,a("a[className*=':']").unbind(),void(commentsBox.st>commentsBox.total?a("#show-comments").hide():a("#show-comments").show().children("a").html(postL10n.showcomm))):void(1!=t?a("#the-comment-list").append('<tr><td colspan="2">'+wpAjax.broken+"</td></tr>"):a("#show-comments").html(postL10n.endcomm))}),!1},load:function(t){this.st=jQuery("#the-comment-list tr.comment:visible").length,this.get(t)}},WPSetThumbnailHTML=function(t){a(".inside","#postimagediv").html(t)},WPSetThumbnailID=function(t){var e=a('input[value="_thumbnail_id"]',"#list-table");0<e.length&&a("#meta\\["+e.attr("id").match(/[0-9]+/)+"\\]\\[value\\]").text(t)},WPRemoveThumbnail=function(t){a.post(ajaxurl,{action:"set-post-thumbnail",post_id:a("#post_ID").val(),thumbnail_id:-1,_ajax_nonce:t,cookie:encodeURIComponent(document.cookie)},function(t){"0"==t?alert(setPostThumbnailL10n.error):WPSetThumbnailHTML(t)})},a(document).on("heartbeat-send.refresh-lock",function(t,e){var i=a("#active_post_lock").val(),n=a("#post_ID").val(),s={};n&&a("#post-lock-dialog").length&&(s.post_id=n,i&&(s.lock=i),e["wp-refresh-post-lock"]=s)}).on("heartbeat-tick.refresh-lock",function(t,e){var i,n;e["wp-refresh-post-lock"]&&((i=e["wp-refresh-post-lock"]).lock_error?(n=a("#post-lock-dialog")).length&&!n.is(":visible")&&(wp.autosave&&(a(document).one("heartbeat-tick",function(){wp.autosave.server.suspend(),n.removeClass("saving").addClass("saved"),a(window).off("beforeunload.edit-post")}),n.addClass("saving"),wp.autosave.server.triggerSave()),i.lock_error.avatar_src&&(e=a('<img class="avatar avatar-64 photo" width="64" height="64" alt="" />').attr("src",i.lock_error.avatar_src.replace(/&/g,"&")),n.find("div.post-locked-avatar").empty().append(e)),n.show().find(".currently-editing").text(i.lock_error.text),n.find(".wp-tab-first").focus()):i.new_lock&&a("#active_post_lock").val(i.new_lock))}).on("before-autosave.update-post-slug",function(){t=document.activeElement&&"title"===document.activeElement.id}).on("after-autosave.update-post-slug",function(){a("#edit-slug-box > *").length||t||a.post(ajaxurl,{action:"sample-permalink",post_id:a("#post_ID").val(),new_title:a("#title").val(),samplepermalinknonce:a("#samplepermalinknonce").val()},function(t){"-1"!=t&&a("#edit-slug-box").html(t)})})}(jQuery),function(s){var a,t;function i(){a=!1,window.clearTimeout(t),t=window.setTimeout(function(){a=!0},3e5)}s(document).on("heartbeat-send.wp-refresh-nonces",function(t,e){var i,n=s("#wp-auth-check-wrap");(a||n.length&&!n.hasClass("hidden"))&&(i=s("#post_ID").val())&&s("#_wpnonce").val()&&(e["wp-refresh-post-nonces"]={post_id:i})}).on("heartbeat-tick.wp-refresh-nonces",function(t,e){e=e["wp-refresh-post-nonces"];e&&(i(),e.replace&&s.each(e.replace,function(t,e){s("#"+t).val(e)}),e.heartbeatNonce&&(window.heartbeatSettings.nonce=e.heartbeatNonce))}).ready(function(){i()})}(jQuery),jQuery(document).ready(function(u){var d,e,i,n,s,a,o,l,t,c,p,r="",h=u("#content"),f=u(document),v=u("#post_ID").val()||0,m=u("#submitpost"),w=!0,b=u("#post-visibility-select"),g=u("#timestampdiv"),k=u("#post-status-select"),y=!!window.navigator.platform&&-1!==window.navigator.platform.indexOf("Mac");function _(t){c.hasClass("wp-editor-expand")||(l?a.theme.resizeTo(null,o+t.pageY):h.height(Math.max(50,o+t.pageY)),t.preventDefault())}function x(){var t;c.hasClass("wp-editor-expand")||(t=l?(a.focus(),((t=parseInt(u("#wp-content-editor-container .mce-toolbar-grp").height(),10))<10||200<t)&&(t=30),parseInt(u("#content_ifr").css("height"),10)+t-28):(h.focus(),parseInt(h.css("height"),10)),f.off(".wp-editor-resize"),t&&50<t&&t<5e3&&setUserSetting("ed_size",t))}postboxes.add_postbox_toggles(pagenow),window.name="",u("#post-lock-dialog .notification-dialog").on("keydown",function(t){var e;9==t.which&&((e=u(t.target)).hasClass("wp-tab-first")&&t.shiftKey?(u(this).find(".wp-tab-last").focus(),t.preventDefault()):e.hasClass("wp-tab-last")&&!t.shiftKey&&(u(this).find(".wp-tab-first").focus(),t.preventDefault()))}).filter(":visible").find(".wp-tab-first").focus(),wp.heartbeat&&u("#post-lock-dialog").length&&wp.heartbeat.interval(15),i=m.find(":submit, a.submitdelete, #post-preview").on("click.edit-post",function(t){var e=u(this);e.hasClass("disabled")?t.preventDefault():e.hasClass("submitdelete")||e.is("#post-preview")||u("form#post").off("submit.edit-post").on("submit.edit-post",function(t){if(!t.isDefaultPrevented()){if(wp.autosave&&wp.autosave.server.suspend(),"undefined"!=typeof commentReply){if(!commentReply.discardCommentChanges())return!1;commentReply.close()}w=!1,u(window).off("beforeunload.edit-post"),i.addClass("disabled"),("publish"===e.attr("id")?m.find("#major-publishing-actions .spinner"):m.find("#minor-publishing .spinner")).addClass("is-active")}})}),u("#post-preview").on("click.post-preview",function(t){var e=u(this),i=u("form#post"),n=u("input#wp-preview"),s=e.attr("target")||"wp-preview",a=navigator.userAgent.toLowerCase();t.preventDefault(),e.hasClass("disabled")||(wp.autosave&&wp.autosave.server.tempBlockSave(),n.val("dopreview"),i.attr("target",s).submit().attr("target",""),-1!==a.indexOf("safari")&&-1===a.indexOf("chrome")&&i.attr("action",function(t,e){return e+"?t="+(new Date).getTime()}),n.val(""))}),u("#title").on("keydown.editor-focus",function(t){var e;if(9===t.keyCode&&!t.ctrlKey&&!t.altKey&&!t.shiftKey){if((e="undefined"!=typeof tinymce&&tinymce.get("content"))&&!e.isHidden())e.focus();else{if(!h.length)return;h.focus()}t.preventDefault()}}),u("#auto_draft").val()&&u("#title").blur(function(){var t;this.value&&!u("#edit-slug-box > *").length&&(u("form#post").one("submit",function(){t=!0}),window.setTimeout(function(){!t&&wp.autosave&&wp.autosave.server.triggerSave()},200))}),f.on("autosave-disable-buttons.edit-post",function(){i.addClass("disabled")}).on("autosave-enable-buttons.edit-post",function(){wp.heartbeat&&wp.heartbeat.hasConnectionError()||i.removeClass("disabled")}).on("before-autosave.edit-post",function(){u(".autosave-message").text(postL10n.savingText)}).on("after-autosave.edit-post",function(t,e){u(".autosave-message").text(e.message),u(document.body).hasClass("post-new-php")&&u(".submitbox .submitdelete").show()}),u(window).on("beforeunload.edit-post",function(){var t="undefined"!=typeof tinymce&&tinymce.get("content");if(t&&!t.isHidden()&&t.isDirty()||wp.autosave&&wp.autosave.server.postChanged())return postL10n.saveAlert}).on("unload.edit-post",function(t){if(w&&(!t.target||"#document"==t.target.nodeName)){var e=u("#post_ID").val(),t=u("#active_post_lock").val();if(e&&t){t={action:"wp-remove-post-lock",_wpnonce:u("#_wpnonce").val(),post_ID:e,active_post_lock:t};if(window.FormData&&window.navigator.sendBeacon){var i=new window.FormData;if(u.each(t,function(t,e){i.append(t,e)}),window.navigator.sendBeacon(ajaxurl,i))return}u.post({async:!1,data:t,url:ajaxurl})}}}),u("#tagsdiv-post_tag").length?window.tagBox&&window.tagBox.init():u(".meta-box-sortables").children("div.postbox").each(function(){if(0===this.id.indexOf("tagsdiv-"))return window.tagBox&&window.tagBox.init(),!1}),u(".categorydiv").each(function(){var t,s,e,i=u(this).attr("id").split("-");i.shift(),s=i.join("-"),e="category"==s?"cats":s+"_tab",u("a","#"+s+"-tabs").click(function(t){t.preventDefault();t=u(this).attr("href");u(this).parent().addClass("tabs").siblings("li").removeClass("tabs"),u("#"+s+"-tabs").siblings(".tabs-panel").hide(),u(t).show(),"#"+s+"-all"==t?deleteUserSetting(e):setUserSetting(e,"pop")}),getUserSetting(e)&&u('a[href="#'+s+'-pop"]',"#"+s+"-tabs").click(),u("#new"+s).one("focus",function(){u(this).val("").removeClass("form-input-tip")}),u("#new"+s).keypress(function(t){13===t.keyCode&&(t.preventDefault(),u("#"+s+"-add-submit").click())}),u("#"+s+"-add-submit").click(function(){u("#new"+s).focus()}),t=function(t){return!!u("#new"+s).val()&&(t.data+="&"+u(":checked","#"+s+"checklist").serialize(),u("#"+s+"-add-submit").prop("disabled",!0),t)},i=function(t,e){var i,n=u("#new"+s+"_parent");u("#"+s+"-add-submit").prop("disabled",!1),"undefined"!=e.parsed.responses[0]&&(i=e.parsed.responses[0].supplemental.newcat_parent)&&(n.before(i),n.remove())},u("#"+s+"checklist").wpList({alt:"",response:s+"-ajax-response",addBefore:t,addAfter:i}),u("#"+s+"-add-toggle").click(function(t){t.preventDefault(),u("#"+s+"-adder").toggleClass("wp-hidden-children"),u('a[href="#'+s+'-all"]',"#"+s+"-tabs").click(),u("#new"+s).focus()}),u("#"+s+"checklist, #"+s+"checklist-pop").on("click",'li.popular-category > label input[type="checkbox"]',function(){var t=u(this),e=t.is(":checked"),i=t.val();i&&t.parents("#taxonomy-"+s).length&&u("#in-"+s+"-"+i+", #in-popular-"+s+"-"+i).prop("checked",e)})}),u("#postcustom").length&&u("#the-list").wpList({addBefore:function(t){return t.data+="&post_id="+u("#post_ID").val(),t},addAfter:function(){u("table#list-table").show()}}),u("#submitdiv").length&&(d=u("#timestamp").html(),e=u("#post-visibility-display").html(),n=function(){"public"!=b.find("input:radio:checked").val()?(u("#sticky").prop("checked",!1),u("#sticky-span").hide()):u("#sticky-span").show(),"password"!=b.find("input:radio:checked").val()?u("#password-span").hide():u("#password-span").show()},s=function(){if(!g.length)return!0;var t,e=u("#post_status"),i=u('option[value="publish"]',e),n=u("#aa").val(),s=u("#mm").val(),a=u("#jj").val(),o=u("#hh").val(),l=u("#mn").val(),c=new Date(n,s-1,a,o,l),p=new Date(u("#hidden_aa").val(),u("#hidden_mm").val()-1,u("#hidden_jj").val(),u("#hidden_hh").val(),u("#hidden_mn").val()),r=new Date(u("#cur_aa").val(),u("#cur_mm").val()-1,u("#cur_jj").val(),u("#cur_hh").val(),u("#cur_mn").val());return c.getFullYear()!=n||1+c.getMonth()!=s||c.getDate()!=a||c.getMinutes()!=l?(g.find(".timestamp-wrap").addClass("form-invalid"),!1):(g.find(".timestamp-wrap").removeClass("form-invalid"),r<c&&"future"!=u("#original_post_status").val()?(t=postL10n.publishOnFuture,u("#publish").val(postL10n.schedule)):c<=r&&"publish"!=u("#original_post_status").val()?(t=postL10n.publishOn,u("#publish").val(postL10n.publish)):(t=postL10n.publishOnPast,u("#publish").val(postL10n.update)),p.toUTCString()==c.toUTCString()?u("#timestamp").html(d):u("#timestamp").html("\n"+t+" <b>"+postL10n.dateFormat.replace("%1$s",u('option[value="'+s+'"]',"#mm").attr("data-text")).replace("%2$s",parseInt(a,10)).replace("%3$s",n).replace("%4$s",("00"+o).slice(-2)).replace("%5$s",("00"+l).slice(-2))+"</b> "),"private"==b.find("input:radio:checked").val()?(u("#publish").val(postL10n.update),0===i.length?e.append('<option value="publish">'+postL10n.privatelyPublished+"</option>"):i.html(postL10n.privatelyPublished),u('option[value="publish"]',e).prop("selected",!0),u("#misc-publishing-actions .edit-post-status").hide()):("future"==u("#original_post_status").val()||"draft"==u("#original_post_status").val()?i.length&&(i.remove(),e.val(u("#hidden_post_status").val())):i.html(postL10n.published),e.is(":hidden")&&u("#misc-publishing-actions .edit-post-status").show()),u("#post-status-display").html(u("option:selected",e).text()),"private"==u("option:selected",e).val()||"publish"==u("option:selected",e).val()?u("#save-post").hide():(u("#save-post").show(),"pending"==u("option:selected",e).val()?u("#save-post").show().val(postL10n.savePending):u("#save-post").show().val(postL10n.saveDraft)),!0)},u("#visibility .edit-visibility").click(function(t){t.preventDefault(),b.is(":hidden")&&(n(),b.slideDown("fast",function(){b.find('input[type="radio"]').first().focus()}),u(this).hide())}),b.find(".cancel-post-visibility").click(function(t){b.slideUp("fast"),u("#visibility-radio-"+u("#hidden-post-visibility").val()).prop("checked",!0),u("#post_password").val(u("#hidden-post-password").val()),u("#sticky").prop("checked",u("#hidden-post-sticky").prop("checked")),u("#post-visibility-display").html(e),u("#visibility .edit-visibility").show().focus(),s(),t.preventDefault()}),b.find(".save-post-visibility").click(function(t){b.slideUp("fast"),u("#visibility .edit-visibility").show().focus(),s(),"public"!=b.find("input:radio:checked").val()&&u("#sticky").prop("checked",!1),r=u("#sticky").prop("checked")?"Sticky":"",u("#post-visibility-display").html(postL10n[b.find("input:radio:checked").val()+r]),t.preventDefault()}),b.find("input:radio").change(function(){n()}),g.siblings("a.edit-timestamp").click(function(t){g.is(":hidden")&&(g.slideDown("fast",function(){u("input, select",g.find(".timestamp-wrap")).first().focus()}),u(this).hide()),t.preventDefault()}),g.find(".cancel-timestamp").click(function(t){g.slideUp("fast").siblings("a.edit-timestamp").show().focus(),u("#mm").val(u("#hidden_mm").val()),u("#jj").val(u("#hidden_jj").val()),u("#aa").val(u("#hidden_aa").val()),u("#hh").val(u("#hidden_hh").val()),u("#mn").val(u("#hidden_mn").val()),s(),t.preventDefault()}),g.find(".save-timestamp").click(function(t){s()&&(g.slideUp("fast"),g.siblings("a.edit-timestamp").show().focus()),t.preventDefault()}),u("#post").on("submit",function(t){s()||(t.preventDefault(),g.show(),wp.autosave&&wp.autosave.enableButtons(),u("#publishing-action .spinner").removeClass("is-active"))}),k.siblings("a.edit-post-status").click(function(t){k.is(":hidden")&&(k.slideDown("fast",function(){k.find("select").focus()}),u(this).hide()),t.preventDefault()}),k.find(".save-post-status").click(function(t){k.slideUp("fast").siblings("a.edit-post-status").show().focus(),s(),t.preventDefault()}),k.find(".cancel-post-status").click(function(t){k.slideUp("fast").siblings("a.edit-post-status").show().focus(),u("#post_status").val(u("#hidden_post_status").val()),s(),t.preventDefault()})),u("#titlediv").on("click",".edit-slug",function(){!function(){var t,e,i,n=0,s=u("#post_name"),a=s.val(),o=u("#sample-permalink"),l=o.html(),c=u("#sample-permalink a").html(),p=u("#edit-slug-buttons"),r=p.html(),d=u("#editable-post-name-full");for(d.find("img").replaceWith(function(){return this.alt}),d=d.html(),o.html(c),e=u("#editable-post-name"),i=e.html(),p.html('<button type="button" class="save button button-small">'+postL10n.ok+'</button> <button type="button" class="cancel button-link">'+postL10n.cancel+"</button>"),p.children(".save").click(function(){var i=e.children("input").val();i!=u("#editable-post-name-full").text()?u.post(ajaxurl,{action:"sample-permalink",post_id:v,new_slug:i,new_title:u("#title").val(),samplepermalinknonce:u("#samplepermalinknonce").val()},function(t){var e=u("#edit-slug-box");e.html(t),e.hasClass("hidden")&&e.fadeIn("fast",function(){e.removeClass("hidden")}),p.html(r),o.html(l),s.val(i),u(".edit-slug").focus(),wp.a11y.speak(postL10n.permalinkSaved)}):p.children(".cancel").click()}),p.children(".cancel").click(function(){u("#view-post-btn").show(),e.html(i),p.html(r),o.html(l),s.val(a),u(".edit-slug").focus()}),t=0;t<d.length;++t)"%"==d.charAt(t)&&n++;c=n>d.length/4?"":d,e.html('<input type="text" id="new-post-slug" value="'+c+'" autocomplete="off" />').children("input").keydown(function(t){var e=t.which;13===e&&(t.preventDefault(),p.children(".save").click()),27===e&&p.children(".cancel").click()}).keyup(function(){s.val(this.value)}).focus()}()}),(wptitlehint=function(t){var e=u("#"+(t=t||"title")),i=u("#"+t+"-prompt-text");""===e.val()&&i.removeClass("screen-reader-text"),i.click(function(){u(this).addClass("screen-reader-text"),e.focus()}),e.blur(function(){""===this.value&&i.removeClass("screen-reader-text")}).focus(function(){i.addClass("screen-reader-text")}).keydown(function(t){i.addClass("screen-reader-text"),u(this).unbind(t)})})(),t=u("#post-status-info"),c=u("#postdivrich"),!h.length||"ontouchstart"in window?u("#content-resize-handle").hide():t.on("mousedown.wp-editor-resize",function(t){(a="undefined"!=typeof tinymce?tinymce.get("content"):a)&&!a.isHidden()?(l=!0,o=u("#content_ifr").height()-t.pageY):(l=!1,o=h.height()-t.pageY,h.blur()),f.on("mousemove.wp-editor-resize",_).on("mouseup.wp-editor-resize mouseleave.wp-editor-resize",x),t.preventDefault()}).on("mouseup.wp-editor-resize",x),"undefined"!=typeof tinymce&&(u("#post-formats-select input.post-format").on("change.set-editor-class",function(){var t,e,i=this.id;i&&u(this).prop("checked")&&(t=tinymce.get("content"))&&((e=t.getBody()).className=e.className.replace(/\bpost-format-[^ ]+/,""),t.dom.addClass(e,"post-format-0"==i?"post-format-standard":i),u(document).trigger("editor-classchange"))}),u("#page_template").on("change.set-editor-class",function(){var t,e,i=u(this).val()||"";(i=i.substr(i.lastIndexOf("/")+1,i.length).replace(/\.php$/,"").replace(/\./g,"-"))&&(t=tinymce.get("content"))&&((e=t.getBody()).className=e.className.replace(/\bpage-template-[^ ]+/,""),t.dom.addClass(e,"page-template-"+i),u(document).trigger("editor-classchange"))})),h.on("keydown.wp-autosave",function(t){83===t.which&&(t.shiftKey||t.altKey||y&&(!t.metaKey||t.ctrlKey)||!y&&!t.ctrlKey||(wp.autosave&&wp.autosave.server.triggerSave(),t.preventDefault()))}),"auto-draft"===u("#original_post_status").val()&&window.history.replaceState&&u("#publish").on("click",function(){p=window.location.href,p+=-1!==p.indexOf("?")?"&":"?",p+="wp-post-new-reload=true",window.history.replaceState(null,null,p)})}),function(t,o){t(function(){var i,e=t("#content"),n=t("#wp-word-count").find(".word-count"),s=0;function a(){var t=!i||i.isHidden()?e.val():i.getContent({format:"raw"}),t=o.count(t);t!==s&&n.text(t),s=t}t(document).on("tinymce-editor-init",function(t,e){"content"===e.id&&(i=e).on("nodechange keyup",_.debounce(a,1e3))}),e.on("input keyup",_.debounce(a,1e3)),a()})}(jQuery,new wp.utils.WordCounter); farbtastic.js 0000666 00000017011 15213733063 0007233 0 ustar 00 /*! * 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); editor-expand.js 0000666 00000101173 15213733063 0007657 0 ustar 00 ( function( window, $, undefined ) { 'use strict'; var $window = $( window ), $document = $( document ), $adminBar = $( '#wpadminbar' ), $footer = $( '#wpfooter' ); /* Autoresize editor. */ $( function() { var $wrap = $( '#postdivrich' ), $contentWrap = $( '#wp-content-wrap' ), $tools = $( '#wp-content-editor-tools' ), $visualTop = $(), $visualEditor = $(), $textTop = $( '#ed_toolbar' ), $textEditor = $( '#content' ), textEditor = $textEditor[0], oldTextLength = 0, $bottom = $( '#post-status-info' ), $menuBar = $(), $statusBar = $(), $sideSortables = $( '#side-sortables' ), $postboxContainer = $( '#postbox-container-1' ), $postBody = $('#post-body'), fullscreen = window.wp.editor && window.wp.editor.fullscreen, mceEditor, mceBind = function(){}, mceUnbind = function(){}, fixedTop = false, fixedBottom = false, fixedSideTop = false, fixedSideBottom = false, scrollTimer, lastScrollPosition = 0, pageYOffsetAtTop = 130, pinnedToolsTop = 56, sidebarBottom = 20, autoresizeMinHeight = 300, initialMode = $contentWrap.hasClass( 'tmce-active' ) ? 'tinymce' : 'html', advanced = !! parseInt( window.getUserSetting( 'hidetb' ), 10 ), // These are corrected when adjust() runs, except on scrolling if already set. heights = { windowHeight: 0, windowWidth: 0, adminBarHeight: 0, toolsHeight: 0, menuBarHeight: 0, visualTopHeight: 0, textTopHeight: 0, bottomHeight: 0, statusBarHeight: 0, sideSortablesHeight: 0 }; var shrinkTextarea = window._.throttle( function() { var x = window.scrollX || document.documentElement.scrollLeft; var y = window.scrollY || document.documentElement.scrollTop; var height = parseInt( textEditor.style.height, 10 ); textEditor.style.height = autoresizeMinHeight + 'px'; if ( textEditor.scrollHeight > autoresizeMinHeight ) { textEditor.style.height = textEditor.scrollHeight + 'px'; } if ( typeof x !== 'undefined' ) { window.scrollTo( x, y ); } if ( textEditor.scrollHeight < height ) { adjust(); } }, 300 ); function textEditorResize() { var length = textEditor.value.length; if ( mceEditor && ! mceEditor.isHidden() ) { return; } if ( ! mceEditor && initialMode === 'tinymce' ) { return; } if ( length < oldTextLength ) { shrinkTextarea(); } else if ( parseInt( textEditor.style.height, 10 ) < textEditor.scrollHeight ) { textEditor.style.height = Math.ceil( textEditor.scrollHeight ) + 'px'; adjust(); } oldTextLength = length; } function getHeights() { var windowWidth = $window.width(); heights = { windowHeight: $window.height(), windowWidth: windowWidth, adminBarHeight: ( windowWidth > 600 ? $adminBar.outerHeight() : 0 ), toolsHeight: $tools.outerHeight() || 0, menuBarHeight: $menuBar.outerHeight() || 0, visualTopHeight: $visualTop.outerHeight() || 0, textTopHeight: $textTop.outerHeight() || 0, bottomHeight: $bottom.outerHeight() || 0, statusBarHeight: $statusBar.outerHeight() || 0, sideSortablesHeight: $sideSortables.height() || 0 }; // Adjust for hidden if ( heights.menuBarHeight < 3 ) { heights.menuBarHeight = 0; } } // We need to wait for TinyMCE to initialize. $document.on( 'tinymce-editor-init.editor-expand', function( event, editor ) { var VK = window.tinymce.util.VK, hideFloatPanels = _.debounce( function() { ! $( '.mce-floatpanel:hover' ).length && window.tinymce.ui.FloatPanel.hideAll(); $( '.mce-tooltip' ).hide(); }, 1000, true ); // Make sure it's the main editor. if ( editor.id !== 'content' ) { return; } // Copy the editor instance. mceEditor = editor; // Set the minimum height to the initial viewport height. editor.settings.autoresize_min_height = autoresizeMinHeight; // Get the necessary UI elements. $visualTop = $contentWrap.find( '.mce-toolbar-grp' ); $visualEditor = $contentWrap.find( '.mce-edit-area' ); $statusBar = $contentWrap.find( '.mce-statusbar' ); $menuBar = $contentWrap.find( '.mce-menubar' ); function mceGetCursorOffset() { var node = editor.selection.getNode(), range, view, offset; if ( editor.wp && editor.wp.getView && ( view = editor.wp.getView( node ) ) ) { offset = view.getBoundingClientRect(); } else { range = editor.selection.getRng(); try { offset = range.getClientRects()[0]; } catch( er ) {} if ( ! offset ) { offset = node.getBoundingClientRect(); } } return offset.height ? offset : false; } // Make sure the cursor is always visible. // This is not only necessary to keep the cursor between the toolbars, // but also to scroll the window when the cursor moves out of the viewport to a wpview. // Setting a buffer > 0 will prevent the browser default. // Some browsers will scroll to the middle, // others to the top/bottom of the *window* when moving the cursor out of the viewport. function mceKeyup( event ) { var key = event.keyCode; // Bail on special keys. if ( key <= 47 && ! ( key === VK.SPACEBAR || key === VK.ENTER || key === VK.DELETE || key === VK.BACKSPACE || key === VK.UP || key === VK.LEFT || key === VK.DOWN || key === VK.UP ) ) { return; // OS keys, function keys, num lock, scroll lock } else if ( ( key >= 91 && key <= 93 ) || ( key >= 112 && key <= 123 ) || key === 144 || key === 145 ) { return; } mceScroll( key ); } function mceScroll( key ) { var offset = mceGetCursorOffset(), buffer = 50, cursorTop, cursorBottom, editorTop, editorBottom; if ( ! offset ) { return; } cursorTop = offset.top + editor.iframeElement.getBoundingClientRect().top; cursorBottom = cursorTop + offset.height; cursorTop = cursorTop - buffer; cursorBottom = cursorBottom + buffer; editorTop = heights.adminBarHeight + heights.toolsHeight + heights.menuBarHeight + heights.visualTopHeight; editorBottom = heights.windowHeight - ( advanced ? heights.bottomHeight + heights.statusBarHeight : 0 ); // Don't scroll if the node is taller than the visible part of the editor if ( editorBottom - editorTop < offset.height ) { return; } if ( cursorTop < editorTop && ( key === VK.UP || key === VK.LEFT || key === VK.BACKSPACE ) ) { window.scrollTo( window.pageXOffset, cursorTop + window.pageYOffset - editorTop ); } else if ( cursorBottom > editorBottom ) { window.scrollTo( window.pageXOffset, cursorBottom + window.pageYOffset - editorBottom ); } } function mceFullscreenToggled( event ) { if ( ! event.state ) { adjust(); } } // Adjust when switching editor modes. function mceShow() { $window.on( 'scroll.mce-float-panels', hideFloatPanels ); setTimeout( function() { editor.execCommand( 'wpAutoResize' ); adjust(); }, 300 ); } function mceHide() { $window.off( 'scroll.mce-float-panels' ); setTimeout( function() { var top = $contentWrap.offset().top; if ( window.pageYOffset > top ) { window.scrollTo( window.pageXOffset, top - heights.adminBarHeight ); } textEditorResize(); adjust(); }, 100 ); adjust(); } function toggleAdvanced() { advanced = ! advanced; } mceBind = function() { editor.on( 'keyup', mceKeyup ); editor.on( 'show', mceShow ); editor.on( 'hide', mceHide ); editor.on( 'wp-toolbar-toggle', toggleAdvanced ); // Adjust when the editor resizes. editor.on( 'setcontent wp-autoresize wp-toolbar-toggle', adjust ); // Don't hide the caret after undo/redo. editor.on( 'undo redo', mceScroll ); // Adjust when exiting TinyMCE's fullscreen mode. editor.on( 'FullscreenStateChanged', mceFullscreenToggled ); $window.off( 'scroll.mce-float-panels' ).on( 'scroll.mce-float-panels', hideFloatPanels ); }; mceUnbind = function() { editor.off( 'keyup', mceKeyup ); editor.off( 'show', mceShow ); editor.off( 'hide', mceHide ); editor.off( 'wp-toolbar-toggle', toggleAdvanced ); editor.off( 'setcontent wp-autoresize wp-toolbar-toggle', adjust ); editor.off( 'undo redo', mceScroll ); editor.off( 'FullscreenStateChanged', mceFullscreenToggled ); $window.off( 'scroll.mce-float-panels' ); }; if ( $wrap.hasClass( 'wp-editor-expand' ) ) { // Adjust "immediately" mceBind(); initialResize( adjust ); } } ); // Adjust the toolbars based on the active editor mode. function adjust( event ) { // Make sure we're not in fullscreen mode. if ( fullscreen && fullscreen.settings.visible ) { return; } var windowPos = $window.scrollTop(), type = event && event.type, resize = type !== 'scroll', visual = mceEditor && ! mceEditor.isHidden(), buffer = autoresizeMinHeight, postBodyTop = $postBody.offset().top, borderWidth = 1, contentWrapWidth = $contentWrap.width(), $top, $editor, sidebarTop, footerTop, canPin, topPos, topHeight, editorPos, editorHeight; // Refresh the heights if ( resize || ! heights.windowHeight ) { getHeights(); } if ( ! visual && type === 'resize' ) { textEditorResize(); } if ( visual ) { $top = $visualTop; $editor = $visualEditor; topHeight = heights.visualTopHeight; } else { $top = $textTop; $editor = $textEditor; topHeight = heights.textTopHeight; } // TinyMCE still initializing. if ( ! visual && ! $top.length ) { return; } topPos = $top.parent().offset().top; editorPos = $editor.offset().top; editorHeight = $editor.outerHeight(); // Should we pin? canPin = visual ? autoresizeMinHeight + topHeight : autoresizeMinHeight + 20; // 20px from textarea padding canPin = editorHeight > ( canPin + 5 ); if ( ! canPin ) { if ( resize ) { $tools.css( { position: 'absolute', top: 0, width: contentWrapWidth } ); if ( visual && $menuBar.length ) { $menuBar.css( { position: 'absolute', top: 0, width: contentWrapWidth - ( borderWidth * 2 ) } ); } $top.css( { position: 'absolute', top: heights.menuBarHeight, width: contentWrapWidth - ( borderWidth * 2 ) - ( visual ? 0 : ( $top.outerWidth() - $top.width() ) ) } ); $statusBar.attr( 'style', advanced ? '' : 'visibility: hidden;' ); $bottom.attr( 'style', '' ); } } else { // Maybe pin the top. if ( ( ! fixedTop || resize ) && // Handle scrolling down. ( windowPos >= ( topPos - heights.toolsHeight - heights.adminBarHeight ) && // Handle scrolling up. windowPos <= ( topPos - heights.toolsHeight - heights.adminBarHeight + editorHeight - buffer ) ) ) { fixedTop = true; $tools.css( { position: 'fixed', top: heights.adminBarHeight, width: contentWrapWidth } ); if ( visual && $menuBar.length ) { $menuBar.css( { position: 'fixed', top: heights.adminBarHeight + heights.toolsHeight, width: contentWrapWidth - ( borderWidth * 2 ) - ( visual ? 0 : ( $top.outerWidth() - $top.width() ) ) } ); } $top.css( { position: 'fixed', top: heights.adminBarHeight + heights.toolsHeight + heights.menuBarHeight, width: contentWrapWidth - ( borderWidth * 2 ) - ( visual ? 0 : ( $top.outerWidth() - $top.width() ) ) } ); // Maybe unpin the top. } else if ( fixedTop || resize ) { // Handle scrolling up. if ( windowPos <= ( topPos - heights.toolsHeight - heights.adminBarHeight ) ) { fixedTop = false; $tools.css( { position: 'absolute', top: 0, width: contentWrapWidth } ); if ( visual && $menuBar.length ) { $menuBar.css( { position: 'absolute', top: 0, width: contentWrapWidth - ( borderWidth * 2 ) } ); } $top.css( { position: 'absolute', top: heights.menuBarHeight, width: contentWrapWidth - ( borderWidth * 2 ) - ( visual ? 0 : ( $top.outerWidth() - $top.width() ) ) } ); // Handle scrolling down. } else if ( windowPos >= ( topPos - heights.toolsHeight - heights.adminBarHeight + editorHeight - buffer ) ) { fixedTop = false; $tools.css( { position: 'absolute', top: editorHeight - buffer, width: contentWrapWidth } ); if ( visual && $menuBar.length ) { $menuBar.css( { position: 'absolute', top: editorHeight - buffer, width: contentWrapWidth - ( borderWidth * 2 ) } ); } $top.css( { position: 'absolute', top: editorHeight - buffer + heights.menuBarHeight, width: contentWrapWidth - ( borderWidth * 2 ) - ( visual ? 0 : ( $top.outerWidth() - $top.width() ) ) } ); } } // Maybe adjust the bottom bar. if ( ( ! fixedBottom || ( resize && advanced ) ) && // +[n] for the border around the .wp-editor-container. ( windowPos + heights.windowHeight ) <= ( editorPos + editorHeight + heights.bottomHeight + heights.statusBarHeight + borderWidth ) ) { if ( event && event.deltaHeight > 0 && event.deltaHeight < 100 ) { window.scrollBy( 0, event.deltaHeight ); } else if ( visual && advanced ) { fixedBottom = true; $statusBar.css( { position: 'fixed', bottom: heights.bottomHeight, visibility: '', width: contentWrapWidth - ( borderWidth * 2 ) } ); $bottom.css( { position: 'fixed', bottom: 0, width: contentWrapWidth } ); } } else if ( ( ! advanced && fixedBottom ) || ( ( fixedBottom || resize ) && ( windowPos + heights.windowHeight ) > ( editorPos + editorHeight + heights.bottomHeight + heights.statusBarHeight - borderWidth ) ) ) { fixedBottom = false; $statusBar.attr( 'style', advanced ? '' : 'visibility: hidden;' ); $bottom.attr( 'style', '' ); } } // Sidebar pinning if ( $postboxContainer.width() < 300 && heights.windowWidth > 600 && // sidebar position is changed with @media from CSS, make sure it is on the side $document.height() > ( $sideSortables.height() + postBodyTop + 120 ) && // the sidebar is not the tallest element heights.windowHeight < editorHeight ) { // the editor is taller than the viewport if ( ( heights.sideSortablesHeight + pinnedToolsTop + sidebarBottom ) > heights.windowHeight || fixedSideTop || fixedSideBottom ) { // Reset when scrolling to the top if ( windowPos + pinnedToolsTop <= postBodyTop ) { $sideSortables.attr( 'style', '' ); fixedSideTop = fixedSideBottom = false; } else { if ( windowPos > lastScrollPosition ) { // Scrolling down if ( fixedSideTop ) { // let it scroll fixedSideTop = false; sidebarTop = $sideSortables.offset().top - heights.adminBarHeight; footerTop = $footer.offset().top; // don't get over the footer if ( footerTop < sidebarTop + heights.sideSortablesHeight + sidebarBottom ) { sidebarTop = footerTop - heights.sideSortablesHeight - 12; } $sideSortables.css({ position: 'absolute', top: sidebarTop, bottom: '' }); } else if ( ! fixedSideBottom && heights.sideSortablesHeight + $sideSortables.offset().top + sidebarBottom < windowPos + heights.windowHeight ) { // pin the bottom fixedSideBottom = true; $sideSortables.css({ position: 'fixed', top: 'auto', bottom: sidebarBottom }); } } else if ( windowPos < lastScrollPosition ) { // Scrolling up if ( fixedSideBottom ) { // let it scroll fixedSideBottom = false; sidebarTop = $sideSortables.offset().top - sidebarBottom; footerTop = $footer.offset().top; // don't get over the footer if ( footerTop < sidebarTop + heights.sideSortablesHeight + sidebarBottom ) { sidebarTop = footerTop - heights.sideSortablesHeight - 12; } $sideSortables.css({ position: 'absolute', top: sidebarTop, bottom: '' }); } else if ( ! fixedSideTop && $sideSortables.offset().top >= windowPos + pinnedToolsTop ) { // pin the top fixedSideTop = true; $sideSortables.css({ position: 'fixed', top: pinnedToolsTop, bottom: '' }); } } } } else { // if the sidebar container is smaller than the viewport, then pin/unpin the top when scrolling if ( windowPos >= ( postBodyTop - pinnedToolsTop ) ) { $sideSortables.css( { position: 'fixed', top: pinnedToolsTop } ); } else { $sideSortables.attr( 'style', '' ); } fixedSideTop = fixedSideBottom = false; } lastScrollPosition = windowPos; } else { $sideSortables.attr( 'style', '' ); fixedSideTop = fixedSideBottom = false; } if ( resize ) { $contentWrap.css( { paddingTop: heights.toolsHeight } ); if ( visual ) { $visualEditor.css( { paddingTop: heights.visualTopHeight + heights.menuBarHeight } ); } else { $textEditor.css( { marginTop: heights.textTopHeight } ); } } } function fullscreenHide() { textEditorResize(); adjust(); } function initialResize( callback ) { for ( var i = 1; i < 6; i++ ) { setTimeout( callback, 500 * i ); } } function afterScroll() { clearTimeout( scrollTimer ); scrollTimer = setTimeout( adjust, 100 ); } function on() { // Scroll to the top when triggering this from JS. // Ensures toolbars are pinned properly. if ( window.pageYOffset && window.pageYOffset > pageYOffsetAtTop ) { window.scrollTo( window.pageXOffset, 0 ); } $wrap.addClass( 'wp-editor-expand' ); // Adjust when the window is scrolled or resized. $window.on( 'scroll.editor-expand resize.editor-expand', function( event ) { adjust( event.type ); afterScroll(); } ); // Adjust when collapsing the menu, changing the columns, changing the body class. $document.on( 'wp-collapse-menu.editor-expand postboxes-columnchange.editor-expand editor-classchange.editor-expand', adjust ) .on( 'postbox-toggled.editor-expand postbox-moved.editor-expand', function() { if ( ! fixedSideTop && ! fixedSideBottom && window.pageYOffset > pinnedToolsTop ) { fixedSideBottom = true; window.scrollBy( 0, -1 ); adjust(); window.scrollBy( 0, 1 ); } adjust(); }).on( 'wp-window-resized.editor-expand', function() { if ( mceEditor && ! mceEditor.isHidden() ) { mceEditor.execCommand( 'wpAutoResize' ); } else { textEditorResize(); } }); $textEditor.on( 'focus.editor-expand input.editor-expand propertychange.editor-expand', textEditorResize ); mceBind(); // Adjust when entering/exiting fullscreen mode. fullscreen && fullscreen.pubsub.subscribe( 'hidden', fullscreenHide ); if ( mceEditor ) { mceEditor.settings.wp_autoresize_on = true; mceEditor.execCommand( 'wpAutoResizeOn' ); if ( ! mceEditor.isHidden() ) { mceEditor.execCommand( 'wpAutoResize' ); } } if ( ! mceEditor || mceEditor.isHidden() ) { textEditorResize(); } adjust(); $document.trigger( 'editor-expand-on' ); } function off() { var height = parseInt( window.getUserSetting( 'ed_size', 300 ), 10 ); if ( height < 50 ) { height = 50; } else if ( height > 5000 ) { height = 5000; } // Scroll to the top when triggering this from JS. // Ensures toolbars are reset properly. if ( window.pageYOffset && window.pageYOffset > pageYOffsetAtTop ) { window.scrollTo( window.pageXOffset, 0 ); } $wrap.removeClass( 'wp-editor-expand' ); $window.off( '.editor-expand' ); $document.off( '.editor-expand' ); $textEditor.off( '.editor-expand' ); mceUnbind(); // Adjust when entering/exiting fullscreen mode. fullscreen && fullscreen.pubsub.unsubscribe( 'hidden', fullscreenHide ); // Reset all css $.each( [ $visualTop, $textTop, $tools, $menuBar, $bottom, $statusBar, $contentWrap, $visualEditor, $textEditor, $sideSortables ], function( i, element ) { element && element.attr( 'style', '' ); }); fixedTop = fixedBottom = fixedSideTop = fixedSideBottom = false; if ( mceEditor ) { mceEditor.settings.wp_autoresize_on = false; mceEditor.execCommand( 'wpAutoResizeOff' ); if ( ! mceEditor.isHidden() ) { $textEditor.hide(); if ( height ) { mceEditor.theme.resizeTo( null, height ); } } } if ( height ) { $textEditor.height( height ); } $document.trigger( 'editor-expand-off' ); } // Start on load if ( $wrap.hasClass( 'wp-editor-expand' ) ) { on(); // Ideally we need to resize just after CSS has fully loaded and QuickTags is ready. if ( $contentWrap.hasClass( 'html-active' ) ) { initialResize( function() { adjust(); textEditorResize(); } ); } } // Show the on/off checkbox $( '#adv-settings .editor-expand' ).show(); $( '#editor-expand-toggle' ).on( 'change.editor-expand', function() { if ( $(this).prop( 'checked' ) ) { on(); window.setUserSetting( 'editor_expand', 'on' ); } else { off(); window.setUserSetting( 'editor_expand', 'off' ); } }); // Expose on() and off() window.editorExpand = { on: on, off: off }; } ); /* DFW. */ $( function() { var $body = $( document.body ), $wrap = $( '#wpcontent' ), $editor = $( '#post-body-content' ), $title = $( '#title' ), $content = $( '#content' ), $overlay = $( document.createElement( 'DIV' ) ), $slug = $( '#edit-slug-box' ), $slugFocusEl = $slug.find( 'a' ) .add( $slug.find( 'button' ) ) .add( $slug.find( 'input' ) ), $menuWrap = $( '#adminmenuwrap' ), $editorWindow = $(), $editorIframe = $(), _isActive = window.getUserSetting( 'editor_expand', 'on' ) === 'on', _isOn = _isActive ? window.getUserSetting( 'post_dfw' ) === 'on' : false, traveledX = 0, traveledY = 0, buffer = 20, faded, fadedAdminBar, fadedSlug, editorRect, x, y, mouseY, scrollY, focusLostTimer, overlayTimer, editorHasFocus; $body.append( $overlay ); $overlay.css( { display: 'none', position: 'fixed', top: $adminBar.height(), right: 0, bottom: 0, left: 0, 'z-index': 9997 } ); $editor.css( { position: 'relative' } ); $window.on( 'mousemove.focus', function( event ) { mouseY = event.pageY; } ); function recalcEditorRect() { editorRect = $editor.offset(); editorRect.right = editorRect.left + $editor.outerWidth(); editorRect.bottom = editorRect.top + $editor.outerHeight(); } function activate() { if ( ! _isActive ) { _isActive = true; $document.trigger( 'dfw-activate' ); $content.on( 'keydown.focus-shortcut', toggleViaKeyboard ); } } function deactivate() { if ( _isActive ) { off(); _isActive = false; $document.trigger( 'dfw-deactivate' ); $content.off( 'keydown.focus-shortcut' ); } } function isActive() { return _isActive; } function on() { if ( ! _isOn && _isActive ) { _isOn = true; $content.on( 'keydown.focus', fadeOut ); $title.add( $content ).on( 'blur.focus', maybeFadeIn ); fadeOut(); window.setUserSetting( 'post_dfw', 'on' ); $document.trigger( 'dfw-on' ); } } function off() { if ( _isOn ) { _isOn = false; $title.add( $content ).off( '.focus' ); fadeIn(); $editor.off( '.focus' ); window.setUserSetting( 'post_dfw', 'off' ); $document.trigger( 'dfw-off' ); } } function toggle() { if ( _isOn ) { off(); } else { on(); } } function isOn() { return _isOn; } function fadeOut( event ) { var isMac, key = event && event.keyCode; if ( window.navigator.platform ) { isMac = ( window.navigator.platform.indexOf( 'Mac' ) > -1 ); } // fadeIn and return on Escape and keyboard shortcut Alt+Shift+W and Ctrl+Opt+W. if ( key === 27 || ( key === 87 && event.altKey && ( ( ! isMac && event.shiftKey ) || ( isMac && event.ctrlKey ) ) ) ) { fadeIn( event ); return; } if ( event && ( event.metaKey || ( event.ctrlKey && ! event.altKey ) || ( event.altKey && event.shiftKey ) || ( key && ( // Special keys ( tab, ctrl, alt, esc, arrow keys... ) ( key <= 47 && key !== 8 && key !== 13 && key !== 32 && key !== 46 ) || // Windows keys ( key >= 91 && key <= 93 ) || // F keys ( key >= 112 && key <= 135 ) || // Num Lock, Scroll Lock, OEM ( key >= 144 && key <= 150 ) || // OEM or non-printable key >= 224 ) ) ) ) { return; } if ( ! faded ) { faded = true; clearTimeout( overlayTimer ); overlayTimer = setTimeout( function() { $overlay.show(); }, 600 ); $editor.css( 'z-index', 9998 ); $overlay // Always recalculate the editor area entering the overlay with the mouse. .on( 'mouseenter.focus', function() { recalcEditorRect(); $window.on( 'scroll.focus', function() { var nScrollY = window.pageYOffset; if ( ( scrollY && mouseY && scrollY !== nScrollY ) && ( mouseY < editorRect.top - buffer || mouseY > editorRect.bottom + buffer ) ) { fadeIn(); } scrollY = nScrollY; } ); } ) .on( 'mouseleave.focus', function() { x = y = null; traveledX = traveledY = 0; $window.off( 'scroll.focus' ); } ) // Fade in when the mouse moves away form the editor area. .on( 'mousemove.focus', function( event ) { var nx = event.clientX, ny = event.clientY, pageYOffset = window.pageYOffset, pageXOffset = window.pageXOffset; if ( x && y && ( nx !== x || ny !== y ) ) { if ( ( ny <= y && ny < editorRect.top - pageYOffset ) || ( ny >= y && ny > editorRect.bottom - pageYOffset ) || ( nx <= x && nx < editorRect.left - pageXOffset ) || ( nx >= x && nx > editorRect.right - pageXOffset ) ) { traveledX += Math.abs( x - nx ); traveledY += Math.abs( y - ny ); if ( ( ny <= editorRect.top - buffer - pageYOffset || ny >= editorRect.bottom + buffer - pageYOffset || nx <= editorRect.left - buffer - pageXOffset || nx >= editorRect.right + buffer - pageXOffset ) && ( traveledX > 10 || traveledY > 10 ) ) { fadeIn(); x = y = null; traveledX = traveledY = 0; return; } } else { traveledX = traveledY = 0; } } x = nx; y = ny; } ) // When the overlay is touched, always fade in and cancel the event. .on( 'touchstart.focus', function( event ) { event.preventDefault(); fadeIn(); } ); $editor.off( 'mouseenter.focus' ); if ( focusLostTimer ) { clearTimeout( focusLostTimer ); focusLostTimer = null; } $body.addClass( 'focus-on' ).removeClass( 'focus-off' ); } fadeOutAdminBar(); fadeOutSlug(); } function fadeIn( event ) { if ( faded ) { faded = false; clearTimeout( overlayTimer ); overlayTimer = setTimeout( function() { $overlay.hide(); }, 200 ); $editor.css( 'z-index', '' ); $overlay.off( 'mouseenter.focus mouseleave.focus mousemove.focus touchstart.focus' ); /* * When fading in, temporarily watch for refocus and fade back out - helps * with 'accidental' editor exits with the mouse. When fading in and the event * is a key event (Escape or Alt+Shift+W) don't watch for refocus. */ if ( 'undefined' === typeof event ) { $editor.on( 'mouseenter.focus', function() { if ( $.contains( $editor.get( 0 ), document.activeElement ) || editorHasFocus ) { fadeOut(); } } ); } focusLostTimer = setTimeout( function() { focusLostTimer = null; $editor.off( 'mouseenter.focus' ); }, 1000 ); $body.addClass( 'focus-off' ).removeClass( 'focus-on' ); } fadeInAdminBar(); fadeInSlug(); } function maybeFadeIn() { setTimeout( function() { var position = document.activeElement.compareDocumentPosition( $editor.get( 0 ) ); function hasFocus( $el ) { return $.contains( $el.get( 0 ), document.activeElement ); } // The focused node is before or behind the editor area, and not outside the wrap. if ( ( position === 2 || position === 4 ) && ( hasFocus( $menuWrap ) || hasFocus( $wrap ) || hasFocus( $footer ) ) ) { fadeIn(); } }, 0 ); } function fadeOutAdminBar() { if ( ! fadedAdminBar && faded ) { fadedAdminBar = true; $adminBar .on( 'mouseenter.focus', function() { $adminBar.addClass( 'focus-off' ); } ) .on( 'mouseleave.focus', function() { $adminBar.removeClass( 'focus-off' ); } ); } } function fadeInAdminBar() { if ( fadedAdminBar ) { fadedAdminBar = false; $adminBar.off( '.focus' ); } } function fadeOutSlug() { if ( ! fadedSlug && faded && ! $slug.find( ':focus').length ) { fadedSlug = true; $slug.stop().fadeTo( 'fast', 0.3 ).on( 'mouseenter.focus', fadeInSlug ).off( 'mouseleave.focus' ); $slugFocusEl.on( 'focus.focus', fadeInSlug ).off( 'blur.focus' ); } } function fadeInSlug() { if ( fadedSlug ) { fadedSlug = false; $slug.stop().fadeTo( 'fast', 1 ).on( 'mouseleave.focus', fadeOutSlug ).off( 'mouseenter.focus' ); $slugFocusEl.on( 'blur.focus', fadeOutSlug ).off( 'focus.focus' ); } } function toggleViaKeyboard( event ) { if ( event.altKey && event.shiftKey && 87 === event.keyCode ) { toggle(); } } if ( $( '#postdivrich' ).hasClass( 'wp-editor-expand' ) ) { $content.on( 'keydown.focus-shortcut', toggleViaKeyboard ); } $document.on( 'tinymce-editor-setup.focus', function( event, editor ) { editor.addButton( 'dfw', { active: _isOn, classes: 'wp-dfw btn widget', disabled: ! _isActive, onclick: toggle, onPostRender: function() { var button = this; $document .on( 'dfw-activate.focus', function() { button.disabled( false ); } ) .on( 'dfw-deactivate.focus', function() { button.disabled( true ); } ) .on( 'dfw-on.focus', function() { button.active( true ); } ) .on( 'dfw-off.focus', function() { button.active( false ); } ); }, tooltip: 'Distraction-free writing mode', shortcut: 'Alt+Shift+W' } ); editor.addCommand( 'wpToggleDFW', toggle ); editor.addShortcut( 'access+w', '', 'wpToggleDFW' ); } ); $document.on( 'tinymce-editor-init.focus', function( event, editor ) { var mceBind, mceUnbind; function focus() { editorHasFocus = true; } function blur() { editorHasFocus = false; } if ( editor.id === 'content' ) { $editorWindow = $( editor.getWin() ); $editorIframe = $( editor.getContentAreaContainer() ).find( 'iframe' ); mceBind = function() { editor.on( 'keydown', fadeOut ); editor.on( 'blur', maybeFadeIn ); editor.on( 'focus', focus ); editor.on( 'blur', blur ); editor.on( 'wp-autoresize', recalcEditorRect ); }; mceUnbind = function() { editor.off( 'keydown', fadeOut ); editor.off( 'blur', maybeFadeIn ); editor.off( 'focus', focus ); editor.off( 'blur', blur ); editor.off( 'wp-autoresize', recalcEditorRect ); }; if ( _isOn ) { mceBind(); } $document.on( 'dfw-on.focus', mceBind ).on( 'dfw-off.focus', mceUnbind ); // Make sure the body focuses when clicking outside it. editor.on( 'click', function( event ) { if ( event.target === editor.getDoc().documentElement ) { editor.focus(); } } ); } } ); $document.on( 'quicktags-init', function( event, editor ) { var $button; if ( editor.settings.buttons && ( ',' + editor.settings.buttons + ',' ).indexOf( ',dfw,' ) !== -1 ) { $button = $( '#' + editor.name + '_dfw' ); $( document ) .on( 'dfw-activate', function() { $button.prop( 'disabled', false ); } ) .on( 'dfw-deactivate', function() { $button.prop( 'disabled', true ); } ) .on( 'dfw-on', function() { $button.addClass( 'active' ); } ) .on( 'dfw-off', function() { $button.removeClass( 'active' ); } ); } } ); $document.on( 'editor-expand-on.focus', activate ).on( 'editor-expand-off.focus', deactivate ); if ( _isOn ) { $content.on( 'keydown.focus', fadeOut ); $title.add( $content ).on( 'blur.focus', maybeFadeIn ); } window.wp = window.wp || {}; window.wp.editor = window.wp.editor || {}; window.wp.editor.dfw = { activate: activate, deactivate: deactivate, isActive: isActive, on: on, off: off, toggle: toggle, isOn: isOn }; } ); } )( window, window.jQuery ); press-this.min.js 0000666 00000025465 15213733063 0010010 0 ustar 00 !function(F,K){K.wp=K.wp||{},K.wp.pressThis=new function(){var r,l,d,e,c=F(K),p=F(document),u=!1,s=document.createElement("textarea"),h=!1,a=K.wpPressThisConfig||{},f=K.wpPressThisData||{},t=128,g=!1,m=[],v="is-off-screen",C="is-hidden",b=v+" "+C,n=/iPad|iPod|iPhone/.test(K.navigator.userAgent),x=F("#pressthis"),i=x[0],o=600,y=0,w=void 0!==(e=document.documentElement.style).transition?"transitionend":void 0!==e.WebkitTransition&&"webkitTransitionEnd";function k(e){return e&&K.pressThisL10n?K.pressThisL10n[e]||e:e||""}function T(e){return(e=e||"").replace(/<!--[\s\S]*?(-->|$)/g,"").replace(/<(script|style)[^>]*>[\s\S]*?(<\/\1>|$)/gi,"").replace(/<\/?[a-z][\s\S]*?(>|$)/gi,"")}function E(e){return e=F.trim(e||""),/^(?:https?:)?\/\//.test(e)?(e=T(e)).replace(/["\\]+/g,""):""}function O(e){r&&!r.isHidden()||(e="reset"===e||y&&y>i.value.length,i.style.height,e?(e=K.pageYOffset,i.style.height="auto",i.style.height=Math.max(i.scrollHeight,o)+"px",K.scrollTo(K.pageXOffset,e)):parseInt(i.style.height,10)<i.scrollHeight&&(i.style.height=i.scrollHeight+"px"),y=i.value.length)}function _(e){var t=K.tinymce.util.VK,e=e.keyCode;e<=47&&e!==t.SPACEBAR&&e!==t.ENTER&&e!==t.DELETE&&e!==t.BACKSPACE&&e!==t.UP&&e!==t.LEFT&&e!==t.DOWN&&e!==t.UP||91<=e&&e<=93||112<=e&&e<=123||144===e||145===e||A(e)}function A(e){var t,s,a,n=function(){if(!r)return!1;var e,t,s,a=r.selection.getNode();if(r.wp&&r.wp.getView&&(t=r.wp.getView(a)))s=t.getBoundingClientRect();else{e=r.selection.getRng();try{s=e.getClientRects()[0]}catch(e){}s=s||a.getBoundingClientRect()}return!!s.height&&s}(),i=K.tinymce.util.VK;n&&(s=(t=n.top+r.iframeElement.getBoundingClientRect().top)+n.height,t-=50,s+=65,(a=c.height())<n.height||(t<0&&(e===i.UP||e===i.LEFT||e===i.BACKSPACE)?K.scrollTo(K.pageXOffset,t+K.pageYOffset):a<s&&K.scrollTo(K.pageXOffset,s+K.pageYOffset-a)))}function D(){var e=F("#title-container");return e.find("img.emoji").each(function(){var e=F(this);e.replaceWith(F("<span>").text(e.attr("alt")))}),function(e){var t=T(e);try{s.innerHTML=t,t=T(s.value)}catch(e){}return t}(e.text())}function P(){var s=F("#pressthis-form"),a=F('<input type="hidden" name="post_category[]" value="">');r&&r.save(),F("#post_title").val(D()),K.tagBox&&F("div.tagsdiv").each(function(){K.tagBox.flushTags(this,!1,1)}),F(".categories-select .category").each(function(e,t){t=F(t);t.hasClass("selected")&&s.append(a.clone().val(t.attr("data-term-id")||""))})}function B(e){u=!1,F(".spinner").addClass("is-active"),F(".post-actions button").attr("disabled","disabled"),"publish"===e&&F("#post_status").val("publish"),P(),e=F("#pressthis-form").serialize(),F.ajax({type:"post",url:K.ajaxurl,data:e}).always(function(){F(".spinner").removeClass("is-active"),F(".post-actions button").removeAttr("disabled"),F("div.alerts").empty(),F(".publish-button").removeClass("is-saving")}).done(function(t){if(t.success){if(t.data.redirect)if(K.opener&&(a.redirInParent||t.data.force))try{K.opener.location.href=t.data.redirect,K.setTimeout(function(){K.self.close()},200)}catch(e){K.location.href=t.data.redirect}else K.location.href=t.data.redirect}else $(t.data.errorMessage)}).fail(function(){$(k("serverError"))})}function R(){var e=F("#new-category").val();e&&(e={action:"press-this-add-category",post_id:F("#post_ID").val()||0,name:e,new_cat_nonce:F("#_ajax_nonce-add-category").val()||"",parent:F("#new-category-parent").val()||0},F.post(K.ajaxurl,e,function(e){var a,n,i;e.success?(i=F("ul.categories-select"),F.each(e.data,function(e,t){var s=F("<li>").append(F('<div class="category selected" tabindex="0" role="checkbox" aria-checked="true">').attr("data-term-id",t.term_id).text(t.name));t.parent?(n&&n.length||(a=i.find('div[data-term-id="'+t.parent+'"]').parent(),(n=a.find("ul.children:first")).length||(n=F('<ul class="children">').appendTo(a))),n.prepend(s)):i.prepend(s),s.focus()}),z()):$(e.data.errorMessage)}))}function S(e,t){t=t?"is-error":"is-notice";F(".editor-wrapper div.alerts").append(F('<p class="alert '+t+'">').text(e))}function $(e){S(e,!0)}function j(){var c=0;l=F("ul.media-list"),d=F('<li class="suggested-media-thumbnail" tabindex="0"><span class="screen-reader-text"></span></li>'),f._embeds&&F.each(f._embeds,function(e,t){var s="",a=d.clone().addClass("is-embed");-1<(t=E(t)).indexOf("youtube.com/")?s="https://i.ytimg.com/vi/"+t.replace(/.+v=([^&]+).*/,"$1")+"/hqdefault.jpg":-1<t.indexOf("youtu.be/")?s="https://i.ytimg.com/vi/"+t.replace(/\/([^\/])$/,"$1")+"/hqdefault.jpg":-1<t.indexOf("dailymotion.com")?s=t.replace("/video/","/thumbnail/video/"):-1<t.indexOf("soundcloud.com")||t.indexOf("twitter.com"),a.attr("data-wp-src",t).find("span").text(k("suggestedEmbedAlt").replace("%d",e+1)),s&&a.css("background-image","url("+s+")"),l.append(a),c++}),f._images&&F.each(f._images,function(n,i){var o,r=new Image;i=E(i),o=i.replace(/^(http[^\?]+)(\?.*)?$/,"$1"),o=-1<i.indexOf("files.wordpress.com/")?o.replace(/\?.*$/,"")+"?w="+t:-1<i.indexOf("gravatar.com/")?o.replace(/\?.*$/,"")+"?s="+t:i,r.onload=function(){var e,t,s,a;r.width&&r.width<256||r.height&&r.height<128||(e=i,t=o,s=n,(a=d.clone().addClass("is-image")).attr("data-wp-src",e).css("background-image","url("+t+")").find("span").text(k("suggestedImgAlt").replace("%d",s+1)),l.append(a))},r.src=i,c++}),c&&F(".media-list-container").addClass("has-media")}function L(){h=!1,F(".options").removeClass("open").addClass("closed"),F(".options-panel-back").addClass(C),F(".press-this-actions, #scanbar").removeClass(C),F(".options-panel").addClass(v).one(w,function(){F(this).addClass(C),F(".post-options").removeClass(b),F(".setting-modal").addClass(b)})}function H(){F(".categories-select").on("click.press-this keydown.press-this",function(e){var t=F(e.target);t.is("div.category")&&("keydown"===e.type&&32!==e.keyCode||((t=t).hasClass("selected")?t.removeClass("selected").attr("aria-checked","false"):t.addClass("selected").attr("aria-checked","true"),e.preventDefault()))})}function N(){F(".split-button").removeClass("is-open"),F(".split-button-toggle").attr("aria-expanded","false")}function I(){f.hasData&&F("#scanbar").hide(),j(),f.errors&&F.each(f.errors,function(e,t){$(t)}),K.tagBox&&K.tagBox.init(),n&&F(document.body).css("cursor","pointer")}function q(){var s,a,t,e,n,i,o=F(".split-button");return p.on("tinymce-editor-init",function(e,t){(r=t).on("nodechange",function(){g=!0}),r.on("focus",function(){N()}),r.on("show",function(){setTimeout(function(){r.execCommand("wpAutoResize")},300)}),r.on("hide",function(){setTimeout(function(){O("reset")},100)}),r.on("keyup",_),r.on("undo redo",A)}).on("click.press-this keypress.press-this",".suggested-media-thumbnail",function(e){var t,s,a;"click"!==e.type&&13!==e.keyCode||(t=F(this),s="",a=E(t.attr("data-wp-src")||""),e=E(f.u),s=t.hasClass("is-image")?'<a href="'+(e=e||a)+'"><img class="alignnone size-full" src="'+a+'" alt="" /></a>':"[embed]"+a+"[/embed]",r&&!r.isHidden()?g?r.execCommand("mceInsertContent",!1,s):r.setContent("<p>"+s+"</p>"+r.getContent()):K.QTags&&K.QTags.insertContent(s))}).on("click.press-this",function(e){F(e.target).closest("button").hasClass("split-button-toggle")||N()}),F(".post-actions").on("click.press-this",function(e){var t=F(e.target).closest("button");t.length&&(t.hasClass("draft-button")?(F(".publish-button").addClass("is-saving"),B("draft")):t.hasClass("publish-button")?(t.addClass("is-saving"),K.history.replaceState&&(e=K.location.href,e+=-1!==e.indexOf("?")?"&":"?",e+="wp-press-this-reload=true",K.history.replaceState(null,null,e)),B("publish")):t.hasClass("preview-button")?(P(),K.opener&&K.opener.focus(),F("#wp-preview").val("dopreview"),F("#pressthis-form").attr("target","_blank").submit().attr("target",""),F("#wp-preview").val("")):t.hasClass("standard-editor-button")?(F(".publish-button").addClass("is-saving"),F("#pt-force-redirect").val("true"),B("draft")):t.hasClass("split-button-toggle")&&(o.hasClass("is-open")?(o.removeClass("is-open"),t.attr("aria-expanded","false")):(o.addClass("is-open"),t.attr("aria-expanded","true"))))}),s=F(".post-options"),a=F(".post-option"),t=F(".setting-modal"),e=F(".modal-close"),a.on("click",function(){var e=F(this).index(),e=t.eq(e);s.addClass(v).one(w,function(){F(this).addClass(C)}),e.removeClass(b).one(w,function(){F(this).find(".modal-close").focus()})}),e.on("click",function(){var e=F(this).parent(),t=e.index();s.removeClass(b),e.addClass(v),w?e.one(w,function(){F(this).addClass(C),a.eq(t-1).focus()}):setTimeout(function(){e.addClass(C),a.eq(t-1).focus()},350)}),n=F("#title-container"),i=F(".post-title-placeholder"),n.on("focus",function(){i.addClass("is-hidden")}).on("blur",function(){n.text()||n.html()||i.removeClass("is-hidden")}).on("keyup",function(){u=!0}).on("paste",function(e){var t,s,a=e.originalEvent.clipboardData||K.clipboardData;if(a){try{(t=a.getData("Text")||a.getData("text/plain"))&&(t=F.trim(t.replace(/\s+/g," ")),K.getSelection?(s=K.getSelection().getRangeAt(0))&&(s.collapsed||s.deleteContents(),s.insertNode(document.createTextNode(t))):document.selection&&(s=document.selection.createRange())&&(s.text=t))}catch(e){}e.preventDefault()}u=!0,setTimeout(function(){n.text(D())},50)}),(n.text()||n.html())&&i.addClass("is-hidden"),H(),F(".options").on("click.press-this",function(){F(this).hasClass("open")?L():(h=!0,F(".options").removeClass("closed").addClass("open"),F(".press-this-actions, #scanbar").addClass(C),F(".options-panel-back").removeClass(C),F(".options-panel").removeClass(b).one(w,function(){F(".post-option:first").focus()}))}),F(".options-panel, .options-panel-back").on("focusout.press-this",function(){setTimeout(function(){var e=document.activeElement,t=F(e);!h||!e||t.hasClass("options-panel-back")||"BODY"!==e.nodeName&&(t.closest(".options-panel").length||t.closest(".options").length)||L()},50)}),F("#post-formats-select input").on("change",function(){var e=F(this);e.is(":checked")&&F("#post-option-post-format").text(F('label[for="'+e.attr("id")+'"]').text()||"")}),c.on("beforeunload.press-this",function(){if(u||r&&r.isDirty())return k("saveAlert")}).on("resize.press-this",function(){r&&!r.isHidden()||O("reset")}),F("button.add-cat-toggle").on("click.press-this",function(){var e=F(this);e.toggleClass("is-toggled"),e.attr("aria-expanded","false"===e.attr("aria-expanded")?"true":"false"),F(".setting-modal .add-category, .categories-search-wrapper").toggleClass("is-hidden")}),F("button.add-cat-submit").on("click.press-this",R),F(".categories-search").on("keyup.press-this",function(){var s=F(this).val().toLowerCase()||"";/[\x20-\xFF]+/.test(s)&&s.length<2||(F.each(m,function(e,t){t.node.removeClass("is-hidden searched-parent")}),s&&F.each(m,function(e,t){-1===t.text.indexOf(s)?t.node.addClass("is-hidden"):t.parents.addClass("searched-parent")}))}),x.on("focus.press-this input.press-this propertychange.press-this",O),1}function z(){F(".categories-select").find("li").each(function(){var e=F(this);m.push({node:e,parents:e.parents("li"),text:e.children(".category").text().toLowerCase()})})}return p.ready(function(){I(),q(),z()}),{renderNotice:S,renderError:$}}}(jQuery,window); wp-fullscreen-stub.js 0000666 00000001254 15213733063 0010654 0 ustar 00 /** * Distraction-Free Writing (wp-fullscreen) backward compatibility stub. * Todo: remove at the end of 2016. * * Original was deprecated in 4.1, removed in 4.3. */ ( function() { var noop = function(){}; window.wp = window.wp || {}; window.wp.editor = window.wp.editor || {}; window.wp.editor.fullscreen = { bind_resize: noop, dfwWidth: noop, off: noop, on: noop, refreshButtons: noop, resizeTextarea: noop, save: noop, switchmode: noop, toggleUI: noop, settings: {}, pubsub: { publish: noop, subscribe: noop, unsubscribe: noop, topics: {} }, fade: { In: noop, Out: noop }, ui: { fade: noop, init: noop } }; }()); revisions.min.js 0000666 00000042576 15213733063 0007732 0 ustar 00 window.wp=window.wp||{},function(h){var s=wp.revisions={model:{},view:{},controller:{}};s.settings=window._wpRevisionsSettings||{},s.debug=!1,s.log=function(){window.console&&s.debug&&window.console.log.apply(window.console,arguments)},h.fn.allOffsets=function(){var e=this.offset()||{top:0,left:0},i=h(window);return _.extend(e,{right:i.width()-e.left-this.outerWidth(),bottom:i.height()-e.top-this.outerHeight()})},h.fn.allPositions=function(){var e=this.position()||{top:0,left:0},i=this.parent();return _.extend(e,{right:i.outerWidth()-e.left-this.outerWidth(),bottom:i.outerHeight()-e.top-this.outerHeight()})},s.model.Slider=Backbone.Model.extend({defaults:{value:null,values:null,min:0,max:1,step:1,range:!1,compareTwoMode:!1},initialize:function(e){this.frame=e.frame,this.revisions=e.revisions,this.listenTo(this.frame,"update:revisions",this.receiveRevisions),this.listenTo(this.frame,"change:compareTwoMode",this.updateMode),this.on("change:from",this.handleLocalChanges),this.on("change:to",this.handleLocalChanges),this.on("change:compareTwoMode",this.updateSliderSettings),this.on("update:revisions",this.updateSliderSettings),this.on("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(e,i){return isRtl?this.revisions.length-this.revisions.indexOf(this.get(e))-1:this.revisions.indexOf(this.get(i))},updateSliderSettings:function(){this.get("compareTwoMode")?this.set({values:[this.getSliderValue("to","from"),this.getSliderValue("from","to")],value:null,range:!0}):this.set({value:this.getSliderValue("to","to"),values:null,range:!1}),this.trigger("update:slider")},hoverRevision:function(e,i){this.trigger("hovered:revision",i)},updateMode:function(e,i){this.set({compareTwoMode:i})},handleLocalChanges:function(){this.frame.set({from:this.get("from"),to:this.get("to")})},receiveRevisions:function(e,i){this.get("from")===e&&this.get("to")===i||(this.set({from:e,to:i},{silent:!0}),this.trigger("update:revisions",e,i))}}),s.model.Tooltip=Backbone.Model.extend({defaults:{revision:null,offset:{},hovering:!1,scrubbing:!1},initialize:function(e){this.frame=e.frame,this.revisions=e.revisions,this.slider=e.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(e){this.set({revision:e})},setHovering:function(e,i){this.set({hovering:i})},setScrubbing:function(e,i){this.set({scrubbing:i})}}),s.model.Revision=Backbone.Model.extend({}),s.model.Revisions=Backbone.Collection.extend({model:s.model.Revision,initialize:function(){_.bindAll(this,"next","prev")},next:function(e){e=this.indexOf(e);if(-1!==e&&e!==this.length-1)return this.at(e+1)},prev:function(e){e=this.indexOf(e);if(-1!==e&&0!==e)return this.at(e-1)}}),s.model.Field=Backbone.Model.extend({}),s.model.Fields=Backbone.Collection.extend({model:s.model.Field}),s.model.Diff=Backbone.Model.extend({initialize:function(){var e=this.get("fields");this.unset("fields"),this.fields=new s.model.Fields(e)}}),s.model.Diffs=Backbone.Collection.extend({initialize:function(e,i){_.bindAll(this,"getClosestUnloaded"),this.loadAll=_.once(this._loadAll),this.revisions=i.revisions,this.postId=i.postId,this.requests={}},model:s.model.Diff,ensure:function(e,i){var t=this.get(e),s=this.requests[e],o=h.Deferred(),n={},r=e.split(":")[0],l=e.split(":")[1];return n[e]=!0,wp.revisions.log("ensure",e),this.trigger("ensure",n,r,l,o.promise()),t?o.resolveWith(i,[t]):(this.trigger("ensure:load",n,r,l,o.promise()),_.each(n,_.bind(function(e){this.requests[e]&&delete n[e],this.get(e)&&delete n[e]},this)),s||(n[e]=!0,s=this.load(_.keys(n))),s.done(_.bind(function(){o.resolveWith(i,[this.get(e)])},this)).fail(_.bind(function(){o.reject()}))),o.promise()},getClosestUnloaded:function(e,i){var t=this;return _.chain([0].concat(e)).initial().zip(e).sortBy(function(e){return Math.abs(i-e[1])}).map(function(e){return e.join(":")}).filter(function(e){return _.isUndefined(t.get(e))&&!t.requests[e]}).value()},_loadAll:function(e,i,t){var s=this,o=h.Deferred(),n=_.first(this.getClosestUnloaded(e,i),t);return 0<_.size(n)?this.load(n).done(function(){s._loadAll(e,i,t).done(function(){o.resolve()})}).fail(function(){1===t?o.reject():s._loadAll(e,i,Math.ceil(t/2)).done(function(){o.resolve()})}):o.resolve(),o},load:function(e){return wp.revisions.log("load",e),this.fetch({data:{compare:e},remove:!1}).done(function(){wp.revisions.log("load:complete",e)})},sync:function(e,i,t){if("read"!==e)return Backbone.Model.prototype.sync.apply(this,arguments);(t=t||{}).context=this,t.data=_.extend(t.data||{},{action:"get-revision-diffs",post_id:this.postId});var s=wp.ajax.send(t),o=this.requests;return t.data.compare&&_.each(t.data.compare,function(e){o[e]=s}),s.always(function(){t.data.compare&&_.each(t.data.compare,function(e){delete o[e]})}),s}}),s.model.FrameState=Backbone.Model.extend({defaults:{loading:!1,error:!1,compareTwoMode:!1},initialize:function(e,i){var t=this.get("initialDiffState");_.bindAll(this,"receiveDiff"),this._debouncedEnsureDiff=_.debounce(this._ensureDiff,200),this.revisions=i.revisions,this.diffs=new s.model.Diffs([],{revisions:this.revisions,postId:this.get("postId")}),this.diffs.set(this.get("diffData")),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),this.set({to:this.revisions.get(t.to),from:this.revisions.get(t.from),compareTwoMode:t.compareTwoMode}),window.history&&window.history.pushState&&(this.router=new s.Router({model:this}),Backbone.history.start({pushState:!0}))},updateLoadingStatus:function(){this.set("error",!1),this.set("loading",!this.diff())},changeMode:function(e,i){var t=this.revisions.indexOf(this.get("to"));i&&0===t&&this.set({from:this.revisions.at(t),to:this.revisions.at(t+1)}),i||0===t||this.set({from:this.revisions.at(t-1),to:this.revisions.at(t)})},updatedRevisions:function(e,i){this.get("compareTwoMode")||this.diffs.loadAll(this.revisions.pluck("id"),i.id,40)},diff:function(){return this.diffs.get(this._diffId)},updateDiff:function(e){var i,t,s;return e=e||{},i=this.get("from"),t=this.get("to"),s=(i?i.id:0)+":"+t.id,this._diffId===s?h.Deferred().reject().promise():(this._diffId=s,this.trigger("update:revisions",i,t),(s=this.diffs.get(s))?(this.receiveDiff(s),h.Deferred().resolve().promise()):e.immediate?this._ensureDiff():(this._debouncedEnsureDiff(),h.Deferred().reject().promise()))},changeRevisionHandler:function(){this.updateDiff()},receiveDiff:function(e){_.isUndefined(e)||_.isUndefined(e.id)?this.set({loading:!1,error:!0}):this._diffId===e.id&&this.trigger("update:diff",e)},_ensureDiff:function(){return this.diffs.ensure(this._diffId,this).always(this.receiveDiff)}}),s.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 s.view.Controls({model:this.model}))},render:function(){return wp.Backbone.View.prototype.render.apply(this,arguments),h("html").css("overflow-y","scroll"),h("#wpbody-content .wrap").append(this.el),this.updateCompareTwoMode(),this.renderDiff(this.model.diff()),this.views.ready(),this},renderDiff:function(e){this.views.set(".revisions-diff-frame",new s.view.Diff({model:e}))},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"))}}),s.view.Controls=wp.Backbone.View.extend({className:"revisions-controls",initialize:function(){_.bindAll(this,"setWidth"),this.views.add(new s.view.Buttons({model:this.model})),this.views.add(new s.view.Checkbox({model:this.model}));var e=new s.model.Slider({frame:this.model,revisions:this.model.revisions}),i=new s.model.Tooltip({frame:this.model,revisions:this.model.revisions,slider:e});this.views.add(new s.view.Tooltip({model:i})),this.views.add(new s.view.Tickmarks({model:i})),this.views.add(new s.view.Slider({model:e})),this.views.add(new s.view.Metabox({model:this.model}))},ready:function(){this.top=this.$el.offset().top,this.window=h(window),this.window.on("scroll.wp.revisions",{controls:this},function(e){var i=e.data.controls,t=i.$el.parent(),s=i.window.scrollTop(),e=i.views.parent;s>=i.top?(e.$el.hasClass("pinned")||(i.setWidth(),t.css("height",t.height()+"px"),i.window.on("resize.wp.revisions.pinning click.wp.revisions.pinning",{controls:i},function(e){e.data.controls.setWidth()})),e.$el.addClass("pinned")):(e.$el.hasClass("pinned")&&(i.window.off(".wp.revisions.pinning"),i.$el.css("width","auto"),e.$el.removeClass("pinned"),t.css("height","auto")),i.top=i.$el.offset().top)})},setWidth:function(){this.$el.css("width",this.$el.parent().width()+"px")}}),s.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(e,i){var t,s=this.model.revisions.indexOf(i),o=this.$el.allOffsets(),i=this.$el.parent().allOffsets();s===this.model.revisions.length-1?t={rightPlusWidth:o.left-i.left+1,leftPlusWidth:o.right-i.right+1}:(t=(s=this.$("div:nth-of-type("+(s+1)+")")).allPositions(),_.extend(t,{left:t.left+o.left-i.left,right:t.right+o.right-i.right}),_.extend(t,{leftPlusWidth:t.left+s.outerWidth(),rightPlusWidth:t.right+s.outerWidth()})),this.model.set({offset:t})},ready:function(){var e=this.model.revisions.length-1,i=1/e;this.$el.css("width",50*this.model.revisions.length+"px"),_(e).times(function(e){this.$el.append('<div style="'+this.direction+": "+100*i*e+'%"></div>')},this)}}),s.view.Metabox=wp.Backbone.View.extend({className:"revisions-meta",initialize:function(){this.views.add(new s.view.MetaFrom({model:this.model,className:"diff-meta diff-meta-from"})),this.views.add(new s.view.MetaTo({model:this.model}))}}),s.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}}),s.view.MetaFrom=s.view.Meta.extend({className:"diff-meta diff-meta-from",type:"from"}),s.view.MetaTo=s.view.Meta.extend({className:"diff-meta diff-meta-to",type:"to"}),s.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(){this.model.revisions.length<3&&h(".revision-toggle-compare-mode").hide()},updateCompareTwoMode:function(){this.$(".compare-two-revisions").prop("checked",this.model.get("compareTwoMode"))},compareTwoToggle:function(){this.model.set({compareTwoMode:h(".compare-two-revisions").prop("checked")})}}),s.view.Tooltip=wp.Backbone.View.extend({className:"revisions-tooltip",template:wp.template("revisions-meta"),initialize:function(){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 _.extend({type:"tooltip"},{attributes:this.model.get("revision").toJSON()})},render:function(){var e,i={},t=.5<(this.model.revisions.indexOf(this.model.get("revision"))+1)/this.model.revisions.length,s=isRtl?(e=t?"left":"right",t?"leftPlusWidth":e):(e=t?"right":"left",t?"rightPlusWidth":e),o="right"===e?"left":"right";wp.Backbone.View.prototype.render.apply(this,arguments),i[e]=this.model.get("offset")[s]+"px",i[o]="",this.$el.toggleClass("flipped",t).css(i)},visible:function(){return this.model.get("scrubbing")||this.model.get("hovering")},toggleVisibility:function(){this.visible()?this.$el.stop().show().fadeTo(100-100*this.el.style.opacity,1):this.$el.stop().fadeTo(300*this.el.style.opacity,0,function(){h(this).hide()})}}),s.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()},gotoModel:function(e){var i={to:this.model.revisions.at(e)};e?i.from=this.model.revisions.at(e-1):this.model.unset("from",{silent:!0}),this.model.set(i)},nextRevision:function(){var e=this.model.revisions.indexOf(this.model.get("to"))+1;this.gotoModel(e)},previousRevision:function(){var e=this.model.revisions.indexOf(this.model.get("to"))-1;this.gotoModel(e)},disabledButtonCheck:function(){var e=this.model.revisions.length-1,i=h(".revisions-next .button"),t=h(".revisions-previous .button"),s=this.model.revisions.indexOf(this.model.get("to"));i.prop("disabled",e===s),t.prop("disabled",0===s)}}),s.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",50*this.model.revisions.length+"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 i=this.model.revisions.length-1,t=this.$el.allOffsets()[this.direction],i=this.$el.width()/i,t=(isRtl?h(window).width()-e.pageX:e.pageX)-t,i=Math.floor((t+i/2)/i);i<0?i=0:i>=this.model.revisions.length&&(i=this.model.revisions.length-1),this.model.set({hoveredRevision:this.model.revisions.at(i)})},mouseLeave:function(){this.model.set({hovering:!1})},mouseEnter:function(){this.model.set({hovering:!0})},applySliderSettings:function(){this.$el.slider(_.pick(this.model.toJSON(),"value","values","range"));var e=this.$("a.ui-slider-handle");this.model.get("compareTwoMode")?(e.first().toggleClass("to-handle",!!isRtl).toggleClass("from-handle",!isRtl),e.last().toggleClass("from-handle",!!isRtl).toggleClass("to-handle",!isRtl)):e.removeClass("from-handle to-handle")},start:function(e,d){this.model.set({scrubbing:!0}),h(window).on("mousemove.wp.revisions",{view:this},function(e){var i=e.data.view,t=i.$el.offset().left,s=t,o=t+i.$el.width(),n="0",r="100%",l=h(d.handle);i.model.get("compareTwoMode")&&(i=l.parent().find(".ui-slider-handle"),l.is(i.first())?r=(o=i.last().offset().left)-s:n=(t=i.first().offset().left+i.first().width())-s),e.pageX<t?l.css("left",n):e.pageX>o?l.css("left",r):l.css("left",e.pageX-s)})},getPosition:function(e){return isRtl?this.model.revisions.length-e-1:e},slide:function(e,i){var t;if(this.model.get("compareTwoMode")){if(i.values[1]===i.values[0])return!1;isRtl&&i.values.reverse(),t={from:this.model.revisions.at(this.getPosition(i.values[0])),to:this.model.revisions.at(this.getPosition(i.values[1]))}}else t={to:this.model.revisions.at(this.getPosition(i.value))},0<this.getPosition(i.value)?t.from=this.model.revisions.at(this.getPosition(i.value)-1):t.from=void 0;i=this.model.revisions.at(this.getPosition(i.value)),this.model.get("scrubbing")&&(t.hoveredRevision=i),this.model.set(t)},stop:function(){h(window).off("mousemove.wp.revisions"),this.model.updateSliderSettings(),this.model.set({scrubbing:!1})}}),s.view.Diff=wp.Backbone.View.extend({className:"revisions-diff",template:wp.template("revisions-diff"),prepare:function(){return _.extend({fields:this.model.fields.toJSON()},this.options)}}),s.Router=Backbone.Router.extend({initialize:function(e){this.model=e.model,this.listenTo(this.model,"update:diff",_.debounce(this.updateUrl,250)),this.listenTo(this.model,"change:compareTwoMode",this.updateUrl)},baseUrl:function(e){return this.model.get("baseUrl")+e},updateUrl:function(){var e=this.model.has("from")?this.model.get("from").id:0,i=this.model.get("to").id;this.model.get("compareTwoMode")?this.navigate(this.baseUrl("?from="+e+"&to="+i),{replace:!0}):this.navigate(this.baseUrl("?revision="+i),{replace:!0})},handleRoute:function(e,i){_.isUndefined(i)||(i=this.model.revisions.get(e),e=this.model.revisions.prev(i),i=i?i.id:0,e=e?e.id:0)}}),s.init=function(){var e;window.adminpage&&"revision-php"===window.adminpage&&(e=new s.model.FrameState({initialDiffState:{to:parseInt(s.settings.to,10),from:parseInt(s.settings.from,10),compareTwoMode:"1"===s.settings.compareTwoMode},diffData:s.settings.diffData,baseUrl:s.settings.baseUrl,postId:parseInt(s.settings.postId,10)},{revisions:new s.model.Revisions(s.settings.revisionData)}),s.view.frame=new s.view.Frame({model:e}).render())},h(s.init)}(jQuery); bookmarklet.min.js 0000666 00000003747 15213733063 0010220 0 ustar 00 (function(e,n,t,i){var a,l,o,r,s,m,g,h=e.encodeURIComponent,c=n.createElement("form"),d=n.getElementsByTagName("head")[0],b="_press_this_app",u=!0;if(i)if(t.match(/^https?:/))if(i+="&u="+h(t),t.match(/^https:/)&&i.match(/^http:/)&&(u=!1),e.getSelection?a=e.getSelection()+"":n.getSelection?a=n.getSelection()+"":n.selection&&(a=n.selection.createRange().text||""),i+="&buster="+(new Date).getTime(),u||(n.title&&(i+="&t="+h(n.title.substr(0,256))),a&&(i+="&s="+h(a.substr(0,512)))),t=(t=e.outerWidth||n.documentElement.clientWidth||600)<800||5e3<t?600:.7*t,h=(h=e.outerHeight||n.documentElement.clientHeight||700)<800||3e3<h?700:.9*h,u){l=d.getElementsByTagName("meta")||[];for(var p=0;p<l.length&&!(200<p);p++){var f=l[p],y=f.getAttribute("name"),v=f.getAttribute("property"),f=f.getAttribute("content");f&&(y?N("_meta["+y+"]",f):v&&N("_meta["+v+"]",f))}o=d.getElementsByTagName("link")||[];for(var E=0;E<o.length&&!(50<=E);E++){var w=o[E],A=w.getAttribute("rel");"canonical"!==A&&"icon"!==A&&"shortlink"!==A||N("_links["+A+"]",w.getAttribute("href"))}n.body.getElementsByClassName&&(r=n.body.getElementsByClassName("hfeed")[0]),s=(r=n.getElementById("content")||r||n.body).getElementsByTagName("img")||[];for(var _=0;_<s.length&&!(100<=_);_++)-1<(g=s[_]).src.indexOf("avatar")||-1<g.className.indexOf("avatar")||g.width&&g.width<256||g.height&&g.height<128||N("_images[]",g.src);m=n.body.getElementsByTagName("iframe")||[];for(var B=0;B<m.length&&!(50<=B);B++)N("_embeds[]",m[B].src);n.title&&N("t",n.title),a&&N("s",a),c.setAttribute("method","POST"),c.setAttribute("action",i),c.setAttribute("target",b),c.setAttribute("style","display: none;"),e.open("about:blank",b,"location,resizable,scrollbars,width="+t+",height="+h),n.body.appendChild(c),c.submit()}else e.open(i,b,"location,resizable,scrollbars,width="+t+",height="+h);else top.location.href=i;function N(e,t){var i;void 0!==t&&((i=n.createElement("input")).name=e,i.value=t,i.type="hidden",c.appendChild(i))}})(window,document,top.location.href,window.pt_url); bookmarklet.js 0000666 00000007565 15213733063 0007440 0 ustar 00 ( function( window, document, href, pt_url ) { var encURI = window.encodeURIComponent, form = document.createElement( 'form' ), head = document.getElementsByTagName( 'head' )[0], target = '_press_this_app', canPost = true, windowWidth, windowHeight, selection, metas, links, content, images, iframes, img; if ( ! pt_url ) { return; } if ( href.match( /^https?:/ ) ) { pt_url += '&u=' + encURI( href ); if ( href.match( /^https:/ ) && pt_url.match( /^http:/ ) ) { canPost = false; } } else { top.location.href = pt_url; return; } if ( window.getSelection ) { selection = window.getSelection() + ''; } else if ( document.getSelection ) { selection = document.getSelection() + ''; } else if ( document.selection ) { selection = document.selection.createRange().text || ''; } pt_url += '&buster=' + ( new Date().getTime() ); if ( ! canPost ) { if ( document.title ) { pt_url += '&t=' + encURI( document.title.substr( 0, 256 ) ); } if ( selection ) { pt_url += '&s=' + encURI( selection.substr( 0, 512 ) ); } } windowWidth = window.outerWidth || document.documentElement.clientWidth || 600; windowHeight = window.outerHeight || document.documentElement.clientHeight || 700; windowWidth = ( windowWidth < 800 || windowWidth > 5000 ) ? 600 : ( windowWidth * 0.7 ); windowHeight = ( windowHeight < 800 || windowHeight > 3000 ) ? 700 : ( windowHeight * 0.9 ); if ( ! canPost ) { window.open( pt_url, target, 'location,resizable,scrollbars,width=' + windowWidth + ',height=' + windowHeight ); return; } function add( name, value ) { if ( typeof value === 'undefined' ) { return; } var input = document.createElement( 'input' ); input.name = name; input.value = value; input.type = 'hidden'; form.appendChild( input ); } metas = head.getElementsByTagName( 'meta' ) || []; for ( var m = 0; m < metas.length; m++ ) { if ( m > 200 ) { break; } var q = metas[ m ], q_name = q.getAttribute( 'name' ), q_prop = q.getAttribute( 'property' ), q_cont = q.getAttribute( 'content' ); if ( q_cont ) { if ( q_name ) { add( '_meta[' + q_name + ']', q_cont ); } else if ( q_prop ) { add( '_meta[' + q_prop + ']', q_cont ); } } } links = head.getElementsByTagName( 'link' ) || []; for ( var y = 0; y < links.length; y++ ) { if ( y >= 50 ) { break; } var g = links[ y ], g_rel = g.getAttribute( 'rel' ); if ( g_rel === 'canonical' || g_rel === 'icon' || g_rel === 'shortlink' ) { add( '_links[' + g_rel + ']', g.getAttribute( 'href' ) ); } } if ( document.body.getElementsByClassName ) { content = document.body.getElementsByClassName( 'hfeed' )[0]; } content = document.getElementById( 'content' ) || content || document.body; images = content.getElementsByTagName( 'img' ) || []; for ( var n = 0; n < images.length; n++ ) { if ( n >= 100 ) { break; } img = images[ n ]; // If we know the image width and/or height, check them now and drop the "uninteresting" images. if ( img.src.indexOf( 'avatar' ) > -1 || img.className.indexOf( 'avatar' ) > -1 || ( img.width && img.width < 256 ) || ( img.height && img.height < 128 ) ) { continue; } add( '_images[]', img.src ); } iframes = document.body.getElementsByTagName( 'iframe' ) || []; for ( var p = 0; p < iframes.length; p++ ) { if ( p >= 50 ) { break; } add( '_embeds[]', iframes[ p ].src ); } if ( document.title ) { add( 't', document.title ); } if ( selection ) { add( 's', selection ); } form.setAttribute( 'method', 'POST' ); form.setAttribute( 'action', pt_url ); form.setAttribute( 'target', target ); form.setAttribute( 'style', 'display: none;' ); window.open( 'about:blank', target, 'location,resizable,scrollbars,width=' + windowWidth + ',height=' + windowHeight ); document.body.appendChild( form ); form.submit(); } )( window, document, top.location.href, window.pt_url ); customize-widgets.min.js 0000666 00000065554 15213733063 0011400 0 ustar 00 !function(u,h){var p,f;function c(e){var t={number:null,id_base:null},i=e.match(/^(.+)-(\d+)$/);return i?(t.id_base=i[1],t.number=parseInt(i[2],10)):t.id_base=e,t}u&&u.customize&&((p=u.customize).Widgets=p.Widgets||{},p.Widgets.savedWidgetIds={},p.Widgets.data=_wpCustomizeWidgetsSettings||{},f=p.Widgets.data.l10n,delete p.Widgets.data.l10n,p.Widgets.WidgetModel=Backbone.Model.extend({id:null,temp_id:null,classname:null,control_tpl:null,description:null,is_disabled:null,is_multi:null,multi_number:null,name:null,id_base:null,transport:null,params:[],width:null,height:null,search_matched:!0}),p.Widgets.WidgetCollection=Backbone.Collection.extend({model:p.Widgets.WidgetModel,doSearch:function(e){this.terms!==e&&(this.terms=e,0<this.terms.length&&this.search(this.terms),""===this.terms&&this.each(function(e){e.set("search_matched",!0)}))},search:function(e){var t,i;e=(e=e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")).replace(/ /g,")(?=.*"),t=new RegExp("^(?=.*"+e+").+","i"),this.each(function(e){i=[e.get("name"),e.get("id"),e.get("description")].join(" "),e.set("search_matched",t.test(i))})}}),p.Widgets.availableWidgets=new p.Widgets.WidgetCollection(p.Widgets.data.availableWidgets),p.Widgets.SidebarModel=Backbone.Model.extend({after_title:null,after_widget:null,before_title:null,before_widget:null,"class":null,description:null,id:null,name:null,is_rendered:!1}),p.Widgets.SidebarCollection=Backbone.Collection.extend({model:p.Widgets.SidebarModel}),p.Widgets.registeredSidebars=new p.Widgets.SidebarCollection(p.Widgets.data.registeredSidebars),p.Widgets.AvailableWidgetsPanelView=u.Backbone.View.extend({el:"#available-widgets",events:{"input #widgets-search":"search","keyup #widgets-search":"search","focus .widget-tpl":"focus","click .widget-tpl":"_submit","keypress .widget-tpl":"_submit",keydown:"keyboardAccessible"},selected:null,currentSidebarControl:null,$search:null,$clearResults:null,searchMatchesCount:null,initialize:function(){var t=this;this.$search=h("#widgets-search"),this.$clearResults=this.$el.find(".clear-results"),_.bindAll(this,"close"),this.listenTo(this.collection,"change",this.updateList),this.updateList(),this.searchMatchesCount=this.collection.length,h("#customize-controls, #available-widgets .customize-section-title").on("click keydown",function(e){e=h(e.target).is(".add-new-widget, .add-new-widget *");h("body").hasClass("adding-widget")&&!e&&t.close()}),this.$clearResults.on("click",function(){t.$search.val("").focus().trigger("keyup")}),p.previewer.bind("url",this.close)},search:function(e){var t;this.collection.doSearch(e.target.value),this.updateSearchMatchesCount(),this.announceSearchMatches(),this.selected&&!this.selected.is(":visible")&&(this.selected.removeClass("selected"),this.selected=null),this.selected&&!e.target.value&&(this.selected.removeClass("selected"),this.selected=null),!this.selected&&e.target.value&&(t=this.$el.find("> .widget-tpl:visible:first")).length&&this.select(t),""!==e.target.value?this.$clearResults.addClass("is-visible"):""===e.target.value&&this.$clearResults.removeClass("is-visible"),this.searchMatchesCount?this.$el.removeClass("no-widgets-found"):this.$el.addClass("no-widgets-found")},updateSearchMatchesCount:function(){this.searchMatchesCount=this.collection.where({search_matched:!0}).length},announceSearchMatches:_.debounce(function(){var e=f.widgetsFound.replace("%d",this.searchMatchesCount);this.searchMatchesCount||(e=f.noWidgetsFound),u.a11y.speak(e)},500),updateList:function(){this.collection.each(function(e){var t=h("#widget-tpl-"+e.id);t.toggle(e.get("search_matched")&&!e.get("is_disabled")),e.get("is_disabled")&&t.is(this.selected)&&(this.selected=null)})},select:function(e){this.selected=h(e),this.selected.siblings(".widget-tpl").removeClass("selected"),this.selected.addClass("selected")},focus:function(e){this.select(h(e.currentTarget))},_submit:function(e){"keypress"===e.type&&13!==e.which&&32!==e.which||this.submit(h(e.currentTarget))},submit:function(e){(e=e||this.selected)&&this.currentSidebarControl&&(this.select(e),e=h(this.selected).data("widget-id"),(e=this.collection.findWhere({id:e}))&&((e=this.currentSidebarControl.addWidget(e.get("id_base")))&&e.focus(),this.close()))},open:function(e){this.currentSidebarControl=e,_(this.currentSidebarControl.getWidgetFormControls()).each(function(e){e.params.is_wide&&e.collapseForm()}),h("body").addClass("adding-widget"),this.$el.find(".selected").removeClass("selected"),this.collection.doSearch(""),p.settings.browser.mobile||this.$search.focus()},close:function(e){(e=e||{}).returnFocus&&this.currentSidebarControl&&this.currentSidebarControl.container.find(".add-new-widget").focus(),this.currentSidebarControl=null,this.selected=null,h("body").removeClass("adding-widget"),this.$search.val("")},keyboardAccessible:function(e){var t=13===e.which,i=27===e.which,n=40===e.which,s=38===e.which,d=9===e.which,a=e.shiftKey,o=null,r=this.$el.find("> .widget-tpl:visible:first"),l=this.$el.find("> .widget-tpl:visible:last"),c=h(e.target).is(this.$search),g=h(e.target).is(".widget-tpl:visible:last");if(n||s)return n?c?o=r:this.selected&&0!==this.selected.nextAll(".widget-tpl:visible").length&&(o=this.selected.nextAll(".widget-tpl:visible:first")):s&&(c?o=l:this.selected&&0!==this.selected.prevAll(".widget-tpl:visible").length&&(o=this.selected.prevAll(".widget-tpl:visible:first"))),this.select(o),void(o||this.$search).focus();t&&!this.$search.val()||(t?this.submit():i&&this.close({returnFocus:!0}),this.currentSidebarControl&&d&&(a&&c||!a&&g)&&(this.currentSidebarControl.container.find(".add-new-widget").focus(),e.preventDefault()))}}),p.Widgets.formSyncHandlers={rss:function(e,t,i){var n=t.find(".widget-error:first"),i=h("<div>"+i+"</div>").find(".widget-error:first");n.length&&i.length?n.replaceWith(i):n.length?n.remove():i.length&&t.find(".widget-content:first").prepend(i)}},p.Widgets.WidgetControl=p.Control.extend({defaultExpandedArguments:{duration:"fast",completeCallback:h.noop},initialize:function(e,t){var i=this;i.widgetControlEmbedded=!1,i.widgetContentEmbedded=!1,i.expanded=new p.Value(!1),i.expandedArgumentsQueue=[],i.expanded.bind(function(e){var t=i.expandedArgumentsQueue.shift(),t=h.extend({},i.defaultExpandedArguments,t);i.onChangeExpanded(e,t)}),i.altNotice=!0,p.Control.prototype.initialize.call(i,e,t)},ready:function(){var n=this;n.section()?p.section(n.section(),function(t){var i=function(e){e&&(n.embedWidgetControl(),t.expanded.unbind(i))};t.expanded()?i(!0):t.expanded.bind(i)}):n.embedWidgetControl()},embedWidgetControl:function(){var e,t=this;t.widgetControlEmbedded||(t.widgetControlEmbedded=!0,e=h(t.params.widget_control),t.container.append(e),t._setupModel(),t._setupWideWidget(),t._setupControlToggle(),t._setupWidgetTitle(),t._setupReorderUI(),t._setupHighlightEffects(),t._setupUpdateUI(),t._setupRemoveUI())},embedWidgetContent:function(){var e,t=this;t.embedWidgetControl(),t.widgetContentEmbedded||(t.widgetContentEmbedded=!0,e=h(t.params.widget_content),t.container.find(".widget-content:first").append(e),h(document).trigger("widget-added",[t.container.find(".widget:first")]))},_setupModel:function(){var i=this,e=function(){p.Widgets.savedWidgetIds[i.params.widget_id]=!0};p.bind("ready",e),p.bind("saved",e),this._updateCount=0,this.isWidgetUpdating=!1,this.liveUpdateMode=!0,this.setting.bind(function(e,t){_(t).isEqual(e)||i.isWidgetUpdating||i.updateWidget({instance:e})})},_setupWideWidget:function(){var n,s,e,t,i,d=this;this.params.is_wide&&(n=this.container.find(".widget-inside"),s=n.find("> .form"),e=h(".wp-full-overlay-sidebar-content:first"),this.container.addClass("wide-widget-control"),this.container.find(".widget-content:first").css({"max-width":this.params.width,"min-height":this.params.height}),i=function(){var e=d.container.offset().top,t=h(window).height(),i=s.outerHeight();n.css("max-height",t),i=Math.max(0,Math.min(Math.max(e,0),t-i)),n.css("top",i)},t=h("#customize-theme-controls"),this.container.on("expand",function(){i(),e.on("scroll",i),h(window).on("resize",i),t.on("expanded collapsed",i)}),this.container.on("collapsed",function(){e.off("scroll",i),h(window).off("resize",i),t.off("expanded collapsed",i)}),p.each(function(e){0===e.id.indexOf("sidebars_widgets[")&&e.bind(function(){d.container.hasClass("expanded")&&i()})}))},_setupControlToggle:function(){var t=this;this.container.find(".widget-top").on("click",function(e){e.preventDefault(),t.getSidebarWidgetsControl().isReordering||t.expanded(!t.expanded())}),this.container.find(".widget-control-close").on("click",function(e){e.preventDefault(),t.collapse(),t.container.find(".widget-top .widget-action:first").focus()})},_setupWidgetTitle:function(){var i=this,e=function(){var e=i.setting().title,t=i.container.find(".in-widget-title");e?t.text(": "+e):t.text("")};this.setting.bind(e),e()},_setupReorderUI:function(){var t,e,d=this,s=function(e){e.siblings(".selected").removeClass("selected"),e.addClass("selected");e=e.data("id")===d.params.sidebar_id;d.container.find(".move-widget-btn").prop("disabled",e)};this.container.find(".widget-title-action").after(h(p.Widgets.data.tpl.widgetReorderNav)),e=_.template(p.Widgets.data.tpl.moveWidgetArea),t=h(e({sidebars:_(p.Widgets.registeredSidebars.toArray()).pluck("attributes")})),this.container.find(".widget-top").after(t),(e=function(){var e=t.find("li"),i=0,n=e.filter(function(){return h(this).data("id")===d.params.sidebar_id});e.each(function(){var e=h(this),t=e.data("id"),t=p.Widgets.registeredSidebars.get(t).get("is_rendered");e.toggle(t),t&&(i+=1),e.hasClass("selected")&&!t&&s(n)}),1<i?d.container.find(".move-widget").show():d.container.find(".move-widget").hide()})(),p.Widgets.registeredSidebars.on("change:is_rendered",e),this.container.find(".widget-reorder-nav").find(".move-widget, .move-widget-down, .move-widget-up").each(function(){h(this).prepend(d.container.find(".widget-title").text()+": ")}).on("click keypress",function(e){var t,i;"keypress"===e.type&&13!==e.which&&32!==e.which||(h(this).focus(),h(this).is(".move-widget")?d.toggleWidgetMoveArea():(t=h(this).is(".move-widget-down"),i=h(this).is(".move-widget-up"),e=d.getWidgetSidebarPosition(),i&&0===e||t&&e===d.getSidebarWidgetsControl().setting().length-1||(i?(d.moveUp(),u.a11y.speak(f.widgetMovedUp)):(d.moveDown(),u.a11y.speak(f.widgetMovedDown)),h(this).focus())))}),this.container.find(".widget-area-select").on("click keypress","li",function(e){"keypress"===e.type&&13!==e.which&&32!==e.which||(e.preventDefault(),s(h(this)))}),this.container.find(".move-widget-btn").click(function(){d.getSidebarWidgetsControl().toggleReordering(!1);var e=d.params.sidebar_id,t=d.container.find(".widget-area-select li.selected").data("id"),i=p("sidebars_widgets["+e+"]"),n=p("sidebars_widgets["+t+"]"),s=Array.prototype.slice.call(i()),e=Array.prototype.slice.call(n()),t=d.getWidgetSidebarPosition();s.splice(t,1),e.push(d.params.widget_id),i(s),n(e),d.focus()})},_setupHighlightEffects:function(){var e=this;this.container.on("mouseenter click",function(){e.setting.previewer.send("highlight-widget",e.params.widget_id)}),this.setting.bind(function(){e.setting.previewer.send("highlight-widget",e.params.widget_id)})},_setupUpdateUI:function(){var t,i,n=this,s=this.container.find(".widget:first"),e=s.find(".widget-content:first"),d=this.container.find(".widget-control-save");d.val(f.saveBtnLabel),d.attr("title",f.saveBtnTooltip),d.removeClass("button-primary"),d.on("click",function(e){e.preventDefault(),n.updateWidget({disable_form:!0})}),t=_.debounce(function(){n.updateWidget()},250),e.on("keydown","input",function(e){13===e.which&&(e.preventDefault(),n.updateWidget({ignoreActiveElement:!0}))}),e.on("change input propertychange",":input",function(e){n.liveUpdateMode&&("change"===e.type||this.checkValidity&&this.checkValidity())&&t()}),this.setting.previewer.channel.bind("synced",function(){n.container.removeClass("previewer-loading")}),p.previewer.bind("widget-updated",function(e){e===n.params.widget_id&&n.container.removeClass("previewer-loading")}),(i=p.Widgets.formSyncHandlers[this.params.widget_id_base])&&h(document).on("widget-synced",function(e,t){s.is(t)&&i.apply(document,arguments)})},onChangeActive:function(e,t){this.container.toggleClass("widget-rendered",e),t.completeCallback&&t.completeCallback()},_setupRemoveUI:function(){var e,s=this,t=this.container.find("a.widget-control-remove");t.on("click",function(e){var n;e.preventDefault(),n=s.container.next().is(".customize-control-widget_form")?s.container.next().find(".widget-action:first"):s.container.prev().is(".customize-control-widget_form")?s.container.prev().find(".widget-action:first"):s.container.next(".customize-control-sidebar_widgets").find(".add-new-widget:first"),s.container.slideUp(function(){var e,t,i=p.Widgets.getSidebarWidgetControlContainingWidget(s.params.widget_id);i&&(e=i.setting().slice(),-1!==(t=_.indexOf(e,s.params.widget_id))&&(e.splice(t,1),i.setting(e),n.focus()))})}),e=function(){t.text(f.removeBtnLabel),t.attr("title",f.removeBtnTooltip)},this.params.is_new?p.bind("saved",e):e()},_getInputs:function(e){return h(e).find(":input[name]")},_getInputsSignature:function(e){return _(e).map(function(e){e=h(e),e=e.is(":checkbox, :radio")?[e.attr("id"),e.attr("name"),e.prop("value")]:[e.attr("id"),e.attr("name")];return e.join(",")}).join(";")},_getInputState:function(e){return(e=h(e)).is(":radio, :checkbox")?e.prop("checked"):e.is("select[multiple]")?e.find("option:selected").map(function(){return h(this).val()}).get():e.val()},_setInputState:function(e,t){(e=h(e)).is(":radio, :checkbox")?e.prop("checked",t):e.is("select[multiple]")?(t=h.isArray(t)?_.map(t,function(e){return String(e)}):[],e.find("option").each(function(){h(this).prop("selected",-1!==_.indexOf(t,String(this.value)))})):e.val(t)},getSidebarWidgetsControl:function(){var e="sidebars_widgets["+this.params.sidebar_id+"]",e=p.control(e);if(e)return e},updateWidget:function(s){var e,d,a,o,r,l,t,i,c,g=this;g.embedWidgetContent(),e=(s=h.extend({instance:null,complete:null,ignoreActiveElement:!1},s)).instance,d=s.complete,this._updateCount+=1,r=this._updateCount,a=this.container.find(".widget:first"),(o=a.find(".widget-content:first")).find(".widget-error").remove(),this.container.addClass("widget-form-loading"),this.container.addClass("previewer-loading"),(t=p.state("processing"))(t()+1),this.liveUpdateMode||this.container.addClass("widget-form-disabled"),(i={action:"update-widget",wp_customize:"on"}).nonce=p.settings.nonce["update-widget"],i.customize_theme=p.settings.theme.stylesheet,i.customized=u.customize.previewer.query().customized,i=h.param(i),(l=this._getInputs(o)).each(function(){h(this).data("state"+r,g._getInputState(this))}),i+=e?"&"+h.param({sanitized_widget_setting:JSON.stringify(e)}):"&"+l.serialize(),i+="&"+o.find("~ :input").serialize(),this._previousUpdateRequest&&this._previousUpdateRequest.abort(),i=h.post(u.ajax.settings.url,i),(this._previousUpdateRequest=i).done(function(e){var n,t,i=!1;if("0"===e)return p.previewer.preview.iframe.hide(),void p.previewer.login().done(function(){g.updateWidget(s),p.previewer.preview.iframe.show()});"-1"!==e?e.success?(t=h("<div>"+e.data.form+"</div>"),n=g._getInputs(t),(t=g._getInputsSignature(l)===g._getInputsSignature(n))&&!g.liveUpdateMode&&(g.liveUpdateMode=!0,g.container.removeClass("widget-form-disabled"),g.container.find('input[name="savewidget"]').hide()),t&&g.liveUpdateMode?(l.each(function(e){var t=h(this),i=h(n[e]),e=t.data("state"+r),i=g._getInputState(i);t.data("sanitized",i),_.isEqual(e,i)||!s.ignoreActiveElement&&t.is(document.activeElement)||g._setInputState(t,i)}),h(document).trigger("widget-synced",[a,e.data.form])):g.liveUpdateMode?(g.liveUpdateMode=!1,g.container.find('input[name="savewidget"]').show(),i=!0):(o.html(e.data.form),g.container.removeClass("widget-form-disabled"),h(document).trigger("widget-updated",[a])),(c=!i&&!_(g.setting()).isEqual(e.data.instance))?(g.isWidgetUpdating=!0,g.setting(e.data.instance),g.isWidgetUpdating=!1):g.container.removeClass("previewer-loading"),d&&d.call(g,null,{noChange:!c,ajaxFinished:!0})):(i=f.error,e.data&&e.data.message&&(i=e.data.message),d?d.call(g,i):o.prepend('<p class="widget-error"><strong>'+i+"</strong></p>")):p.previewer.cheatin()}),i.fail(function(e,t){d&&d.call(g,t)}),i.always(function(){g.container.removeClass("widget-form-loading"),l.each(function(){h(this).removeData("state"+r)}),t(t()-1)})},expandControlSection:function(){p.Control.prototype.expand.call(this)},_toggleExpanded:p.Section.prototype._toggleExpanded,expand:p.Section.prototype.expand,expandForm:function(){this.expand()},collapse:p.Section.prototype.collapse,collapseForm:function(){this.collapse()},toggleForm:function(e){void 0===e&&(e=!this.expanded()),this.expanded(e)},onChangeExpanded:function(e,t){var i,n,s,d,a,o=this;o.embedWidgetControl(),e&&o.embedWidgetContent(),t.unchanged?e&&p.Control.prototype.expand.call(o,{completeCallback:t.completeCallback}):(i=this.container.find("div.widget:first"),n=i.find(".widget-inside:first"),a=function(){p.control.each(function(e){o.params.type===e.params.type&&o!==e&&e.collapse()}),s=function(){o.container.removeClass("expanding"),o.container.addClass("expanded"),o.container.trigger("expanded")},t.completeCallback&&(d=s,s=function(){d(),t.completeCallback()}),o.params.is_wide?n.fadeIn(t.duration,s):n.slideDown(t.duration,s),o.container.trigger("expand"),o.container.addClass("expanding")},e?p.section.has(o.section())?p.section(o.section()).expand({completeCallback:a}):a():(s=function(){o.container.removeClass("collapsing"),o.container.removeClass("expanded"),o.container.trigger("collapsed")},t.completeCallback&&(d=s,s=function(){d(),t.completeCallback()}),o.container.trigger("collapse"),o.container.addClass("collapsing"),o.params.is_wide?n.fadeOut(t.duration,s):n.slideUp(t.duration,function(){i.css({width:"",margin:""}),s()})))},getWidgetSidebarPosition:function(){var e=this.getSidebarWidgetsControl().setting(),e=_.indexOf(e,this.params.widget_id);if(-1!==e)return e},moveUp:function(){this._moveWidgetByOne(-1)},moveDown:function(){this._moveWidgetByOne(1)},_moveWidgetByOne:function(e){var t=this.getWidgetSidebarPosition(),i=this.getSidebarWidgetsControl().setting,n=Array.prototype.slice.call(i()),s=n[t+e];n[t+e]=this.params.widget_id,n[t]=s,i(n)},toggleWidgetMoveArea:function(e){var t=this,i=this.container.find(".move-widget-area");(e=void 0===e?!i.hasClass("active"):e)&&(i.find(".selected").removeClass("selected"),i.find("li").filter(function(){return h(this).data("id")===t.params.sidebar_id}).addClass("selected"),this.container.find(".move-widget-btn").prop("disabled",!0)),i.toggleClass("active",e)},highlightSectionAndControl:function(){var e=this.container.is(":hidden")?this.container.closest(".control-section"):this.container;h(".highlighted").removeClass("highlighted"),e.addClass("highlighted"),setTimeout(function(){e.removeClass("highlighted")},500)}}),p.Widgets.WidgetsPanel=p.Panel.extend({ready:function(){var n=this;p.Panel.prototype.ready.call(n),n.deferred.embedded.done(function(){var t,e=n.container.find(".panel-meta"),i=h("<div></div>",{"class":"no-widget-areas-rendered-notice"});i.append(h("<em></em>",{text:f.noAreasRendered})),e.append(i),t=function(){return 0===_.filter(n.sections(),function(e){return e.active()}).length},i.toggle(t()),p.previewer.deferred.active.done(function(){i.toggle(t())}),p.bind("pane-contents-reflowed",function(){var e="resolved"===p.previewer.deferred.active.state()?"fast":0;t()?i.slideDown(e):i.slideUp(e)})})},isContextuallyActive:function(){return this.active()}}),p.Widgets.SidebarSection=p.Section.extend({ready:function(){var t;p.Section.prototype.ready.call(this),t=p.Widgets.registeredSidebars.get(this.params.sidebarId),this.active.bind(function(e){t.set("is_rendered",e)}),t.set("is_rendered",this.active())}}),p.Widgets.SidebarControl=p.Control.extend({ready:function(){this.$controlSection=this.container.closest(".control-section"),this.$sectionContent=this.container.closest(".accordion-section-content"),this._setupModel(),this._setupSortable(),this._setupAddition(),this._applyCardinalOrderClassNames()},_setupModel:function(){var d=this;this.setting.bind(function(i,e){var t,n=_(e).difference(i);i=_(i).filter(function(e){e=c(e);return!!p.Widgets.availableWidgets.findWhere({id_base:e.id_base})}),(e=_(i).map(function(e){return p.Widgets.getWidgetFormControlForWidget(e)||d.addWidget(e)})).sort(function(e,t){return _.indexOf(i,e.params.widget_id)-_.indexOf(i,t.params.widget_id)}),t=0,_(e).each(function(e){e.priority(t),e.section(d.section()),t+=1}),d.priority(t),d._applyCardinalOrderClassNames(),_(e).each(function(e){e.params.sidebar_id=d.params.sidebar_id}),_(n).each(function(s){setTimeout(function(){var e,t,i,n=!1;p.each(function(e){e.id!==d.setting.id&&0===e.id.indexOf("sidebars_widgets[")&&"sidebars_widgets[wp_inactive_widgets]"!==e.id&&(e=e(),-1!==_.indexOf(e,s)&&(n=!0))}),n||(t=(e=p.Widgets.getWidgetFormControlForWidget(s))&&h.contains(document,e.container[0])&&!h.contains(d.$sectionContent[0],e.container[0]),e&&!t&&(p.control.remove(e.id),e.container.remove()),p.Widgets.savedWidgetIds[s]&&((i=p.value("sidebars_widgets[wp_inactive_widgets]")().slice()).push(s),p.value("sidebars_widgets[wp_inactive_widgets]")(_(i).unique())),i=c(s).id_base,(i=p.Widgets.availableWidgets.findWhere({id_base:i}))&&!i.get("is_multi")&&i.set("is_disabled",!1))})})})},_setupSortable:function(){var t=this;this.isReordering=!1,this.$sectionContent.sortable({items:"> .customize-control-widget_form",handle:".widget-top",axis:"y",tolerance:"pointer",connectWith:".accordion-section-content:has(.customize-control-sidebar_widgets)",update:function(){var e=t.$sectionContent.sortable("toArray"),e=h.map(e,function(e){return h("#"+e).find(":input[name=widget-id]").val()});t.setting(e)}}),this.$controlSection.find(".accordion-section-title").droppable({accept:".customize-control-widget_form",over:function(){p.section(t.section.get()).expand({allowMultiple:!0,completeCallback:function(){p.section.each(function(e){e.container.find(".customize-control-sidebar_widgets").length&&e.container.find(".accordion-section-content:first").sortable("refreshPositions")})}})}}),this.container.find(".reorder-toggle").on("click",function(){t.toggleReordering(!t.isReordering)})},_setupAddition:function(){var t=this;this.container.find(".add-new-widget").on("click",function(){var e=h(this);t.$sectionContent.hasClass("reordering")||(h("body").hasClass("adding-widget")?(e.attr("aria-expanded","false"),p.Widgets.availableWidgetsPanel.close()):(e.attr("aria-expanded","true"),p.Widgets.availableWidgetsPanel.open(t)))})},_applyCardinalOrderClassNames:function(){var t=[];_.each(this.setting(),function(e){e=p.Widgets.getWidgetFormControlForWidget(e);e&&t.push(e)}),0===t.length||1===p.Widgets.registeredSidebars.length&&t.length<=1?this.container.find(".reorder-toggle").hide():(this.container.find(".reorder-toggle").show(),h(t).each(function(){h(this.container).removeClass("first-widget").removeClass("last-widget").find(".move-widget-down, .move-widget-up").prop("tabIndex",0)}),_.first(t).container.addClass("first-widget").find(".move-widget-up").prop("tabIndex",-1),_.last(t).container.addClass("last-widget").find(".move-widget-down").prop("tabIndex",-1))},toggleReordering:function(e){var t=this.$sectionContent.find(".add-new-widget"),i=this.container.find(".reorder-toggle"),n=this.$sectionContent.find(".widget-title");(e=Boolean(e))!==this.$sectionContent.hasClass("reordering")&&(this.isReordering=e,this.$sectionContent.toggleClass("reordering",e),e?(_(this.getWidgetFormControls()).each(function(e){e.collapse()}),t.attr({tabindex:"-1","aria-hidden":"true"}),i.attr("aria-label",f.reorderLabelOff),u.a11y.speak(f.reorderModeOn),n.attr("aria-hidden","true")):(t.removeAttr("tabindex aria-hidden"),i.attr("aria-label",f.reorderLabelOn),u.a11y.speak(f.reorderModeOff),n.attr("aria-hidden","false")))},getWidgetFormControls:function(){var t=[];return _(this.setting()).each(function(e){e=function(e){var t=c(e);e="widget_"+t.id_base,t.number&&(e+="["+t.number+"]");return e}(e),e=p.control(e);e&&t.push(e)}),t},addWidget:function(n){var e,t,i,s=this,d="widget_form",a=c(n),o=a.number,r=a.id_base,l=p.Widgets.availableWidgets.findWhere({id_base:r});return!!l&&(!(o&&!l.get("is_multi"))&&(l.get("is_multi")&&!o&&(l.set("multi_number",l.get("multi_number")+1),o=l.get("multi_number")),a=h.trim(h("#widget-tpl-"+l.get("id")).html()),l.get("is_multi")?a=a.replace(/<[^<>]+>/g,function(e){return e.replace(/__i__|%i%/g,o)}):l.set("is_disabled",!0),r=h(a),(a=h("<li/>").addClass("customize-control").addClass("customize-control-"+d).append(r)).find("> .widget-icon").remove(),l.get("is_multi")&&(a.find('input[name="widget_number"]').val(o),a.find('input[name="multi_number"]').val(o)),n=a.find('[name="widget-id"]').val(),a.hide(),r="widget_"+l.get("id_base"),l.get("is_multi")&&(r+="["+o+"]"),a.attr("id","customize-control-"+r.replace(/\]/g,"").replace(/\[/g,"-")),(e=p.has(r))||(i={transport:p.Widgets.data.selectiveRefreshableWidgets[l.get("id_base")]?"postMessage":"refresh",previewer:this.setting.previewer},p.create(r,r,"",i).set({})),i=p.controlConstructor[d],t=new i(r,{params:{settings:{"default":r},content:a,sidebar_id:s.params.sidebar_id,widget_id:n,widget_id_base:l.get("id_base"),type:d,is_new:!e,width:l.get("width"),height:l.get("height"),is_wide:l.get("is_wide"),active:!0},previewer:s.setting.previewer}),p.control.add(r,t),p.each(function(e){var t,i;e.id!==s.setting.id&&0===e.id.indexOf("sidebars_widgets[")&&(t=e().slice(),-1!==(i=_.indexOf(t,n))&&(t.splice(i),e(t)))}),r=this.setting().slice(),-1===_.indexOf(r,n)&&(r.push(n),this.setting(r)),a.slideDown(function(){e&&t.updateWidget({instance:t.setting()})}),t))}}),h.extend(p.panelConstructor,{widgets:p.Widgets.WidgetsPanel}),h.extend(p.sectionConstructor,{sidebar:p.Widgets.SidebarSection}),h.extend(p.controlConstructor,{widget_form:p.Widgets.WidgetControl,sidebar_widgets:p.Widgets.SidebarControl}),p.bind("ready",function(){p.Widgets.availableWidgetsPanel=new p.Widgets.AvailableWidgetsPanelView({collection:p.Widgets.availableWidgets}),p.previewer.bind("highlight-widget-control",p.Widgets.highlightWidgetFormControl),p.previewer.bind("focus-widget-control",p.Widgets.focusWidgetFormControl)}),p.Widgets.highlightWidgetFormControl=function(e){e=p.Widgets.getWidgetFormControlForWidget(e);e&&e.highlightSectionAndControl()},p.Widgets.focusWidgetFormControl=function(e){e=p.Widgets.getWidgetFormControlForWidget(e);e&&e.focus()},p.Widgets.getSidebarWidgetControlContainingWidget=function(t){var i=null;return p.control.each(function(e){"sidebar_widgets"===e.params.type&&-1!==_.indexOf(e.setting(),t)&&(i=e)}),i},p.Widgets.getWidgetFormControlForWidget=function(t){var i=null;return p.control.each(function(e){"widget_form"===e.params.type&&e.params.widget_id===t&&(i=e)}),i},h(document).on("widget-added",function(e,t){var s,d,i,n=c(t.find("> .widget-inside > .form > .widget-id").val());"nav_menu"===n.id_base&&(s=p.control("widget_nav_menu["+String(n.number)+"]"))&&(d=t.find('select[name*="nav_menu"]'),i=t.find(".edit-selected-nav-menu > button"),0!==d.length&&0!==i.length&&(d.on("change",function(){p.section.has("nav_menu["+d.val()+"]")?i.parent().show():i.parent().hide()}),i.on("click",function(){var i,n,e=p.section("nav_menu["+d.val()+"]");e&&(n=s,(i=e).focus(),i.expanded.bind(function e(t){t||(i.expanded.unbind(e),n.focus())}))})))}))}(window.wp,jQuery); xfn.js 0000666 00000001164 15213733063 0005706 0 ustar 00 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 ) ); }); }); svg-painter.min.js 0000666 00000004445 15213733063 0010141 0 ustar 00 window.wp=window.wp||{},wp.svgPainter=function(e,o,n){"use strict";var t,r,a,m,i,s,c,u,l,f={},g=[];function p(){for(;l<256;)m=String.fromCharCode(l),s+=m,u[l]=l,c[l]=i.indexOf(m),++l}function d(n,t,e,a,i,o){for(var r,s=0,c=0,u="",l=0,f=(n=String(n)).length;c<f;){for(s=(s<<i)+(m=(m=n.charCodeAt(c))<256?e[m]:-1),l+=i;o<=l;)r=s>>(l-=o),u+=a.charAt(r),s^=r<<l;++c}return!t&&0<l&&(u+=a.charAt(s<<o-l)),u}return e(n).ready(function(){n.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1")&&(e(n.body).removeClass("no-svg").addClass("svg"),wp.svgPainter.init())}),i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s="",c=[256],u=[256],l=0,r={atob:function(n){var t;for(m||p(),n=n.replace(/[^A-Za-z0-9\+\/\=]/g,""),n=String(n).split("="),t=n.length;n[--t]=d(n[t],!0,c,s,6,8),0<t;);return n=n.join("")},btoa:function(n){return m||p(),(n=d(n,!1,u,i,8,6))+"====".slice(n.length%4||4)}},{init:function(){a=this,t=e("#adminmenu .wp-menu-image, #wpadminbar .ab-item"),this.setColors(),this.findElements(),this.paint()},setColors:function(n){(n=void 0===n&&void 0!==o._wpColorScheme?o._wpColorScheme:n)&&n.icons&&n.icons.base&&n.icons.current&&n.icons.focus&&(f=n.icons)},findElements:function(){t.each(function(){var n=e(this),t=n.css("background-image");t&&-1!=t.indexOf("data:image/svg+xml;base64")&&g.push(n)})},paint:function(){e.each(g,function(n,t){var e=t.parent().parent();e.hasClass("current")||e.hasClass("wp-has-current-submenu")?a.paintElement(t,"current"):(a.paintElement(t,"base"),e.hover(function(){a.paintElement(t,"focus")},function(){o.setTimeout(function(){a.paintElement(t,"base")},100)}))})},paintElement:function(n,t){var e,a,i;if(t&&f.hasOwnProperty(t)&&(i=f[t],i.match(/^(#[0-9a-f]{3}|#[0-9a-f]{6})$/i)&&"none"!==(e=n.data("wp-ui-svg-"+i)))){if(!e){if(!(a=n.css("background-image").match(/.+data:image\/svg\+xml;base64,([A-Za-z0-9\+\/\=]+)/))||!a[1])return void n.data("wp-ui-svg-"+i,"none");try{e=("atob"in o?o:r).atob(a[1])}catch(n){}if(!e)return void n.data("wp-ui-svg-"+i,"none");e=(e=(e=e.replace(/fill="(.+?)"/g,'fill="'+i+'"')).replace(/style="(.+?)"/g,'style="fill:'+i+'"')).replace(/fill:.*?;/g,"fill: "+i+";"),e=("btoa"in o?o:r).btoa(e),n.data("wp-ui-svg-"+i,e)}n.attr("style",'background-image: url("data:image/svg+xml;base64,'+e+'") !important;')}}}}(jQuery,window,document); user-profile.js 0000666 00000027466 15213733063 0007544 0 ustar 00 /* global ajaxurl, pwsL10n, userProfileL10n */ (function($) { var updateLock = false, $pass1Row, $pass1Wrap, $pass1, $pass1Text, $pass1Label, $pass2, $weakRow, $weakCheckbox, $toggleButton, $submitButtons, $submitButton, currentPass, inputEvent; /* * Use feature detection to determine whether password inputs should use * the `keyup` or `input` event. Input is preferred but lacks support * in legacy browsers. */ if ( 'oninput' in document.createElement( 'input' ) ) { inputEvent = 'input'; } else { inputEvent = 'keyup'; } function generatePassword() { if ( typeof zxcvbn !== 'function' ) { setTimeout( generatePassword, 50 ); return; } else if ( ! $pass1.val() ) { // zxcvbn loaded before user entered password. $pass1.val( $pass1.data( 'pw' ) ); $pass1.trigger( 'pwupdate' ); showOrHideWeakPasswordCheckbox(); } else { // zxcvbn loaded after the user entered password, check strength. check_pass_strength(); showOrHideWeakPasswordCheckbox(); } if ( 1 !== parseInt( $toggleButton.data( 'start-masked' ), 10 ) ) { $pass1Wrap.addClass( 'show-password' ); } else { $toggleButton.trigger( 'click' ); } // Once zxcvbn loads, passwords strength is known. $( '#pw-weak-text-label' ).html( userProfileL10n.warnWeak ); } function bindPass1() { currentPass = $pass1.val(); $pass1Wrap = $pass1.parent(); $pass1Text = $( '<input type="text"/>' ) .attr( { 'id': 'pass1-text', 'name': 'pass1-text', 'autocomplete': 'off' } ) .addClass( $pass1[0].className ) .data( 'pw', $pass1.data( 'pw' ) ) .val( $pass1.val() ) .on( inputEvent, function () { if ( $pass1Text.val() === currentPass ) { return; } $pass2.val( $pass1Text.val() ); $pass1.val( $pass1Text.val() ).trigger( 'pwupdate' ); currentPass = $pass1Text.val(); } ); $pass1.after( $pass1Text ); if ( 1 === parseInt( $pass1.data( 'reveal' ), 10 ) ) { generatePassword(); } $pass1.on( inputEvent + ' pwupdate', function () { if ( $pass1.val() === currentPass ) { return; } currentPass = $pass1.val(); if ( $pass1Text.val() !== currentPass ) { $pass1Text.val( currentPass ); } $pass1.add( $pass1Text ).removeClass( 'short bad good strong' ); showOrHideWeakPasswordCheckbox(); } ); } function resetToggle() { $toggleButton .data( 'toggle', 0 ) .attr({ 'aria-label': userProfileL10n.ariaHide }) .find( '.text' ) .text( userProfileL10n.hide ) .end() .find( '.dashicons' ) .removeClass( 'dashicons-visibility' ) .addClass( 'dashicons-hidden' ); $pass1Text.focus(); $pass1Label.attr( 'for', 'pass1-text' ); } function bindToggleButton() { $toggleButton = $pass1Row.find('.wp-hide-pw'); $toggleButton.show().on( 'click', function () { if ( 1 === parseInt( $toggleButton.data( 'toggle' ), 10 ) ) { $pass1Wrap.addClass( 'show-password' ); resetToggle(); if ( ! _.isUndefined( $pass1Text[0].setSelectionRange ) ) { $pass1Text[0].setSelectionRange( 0, 100 ); } } else { $pass1Wrap.removeClass( 'show-password' ); $toggleButton .data( 'toggle', 1 ) .attr({ 'aria-label': userProfileL10n.ariaShow }) .find( '.text' ) .text( userProfileL10n.show ) .end() .find( '.dashicons' ) .removeClass('dashicons-hidden') .addClass('dashicons-visibility'); $pass1.focus(); $pass1Label.attr( 'for', 'pass1' ); if ( ! _.isUndefined( $pass1[0].setSelectionRange ) ) { $pass1[0].setSelectionRange( 0, 100 ); } } }); } function bindPasswordForm() { var $passwordWrapper, $generateButton, $cancelButton; $pass1Row = $('.user-pass1-wrap'); $pass1Label = $pass1Row.find('th label').attr( 'for', 'pass1-text' ); // hide this $('.user-pass2-wrap').hide(); $submitButton = $( '#submit' ).on( 'click', function () { updateLock = false; }); $submitButtons = $submitButton.add( ' #createusersub' ); $weakRow = $( '.pw-weak' ); $weakCheckbox = $weakRow.find( '.pw-checkbox' ); $weakCheckbox.change( function() { $submitButtons.prop( 'disabled', ! $weakCheckbox.prop( 'checked' ) ); } ); $pass1 = $('#pass1'); if ( $pass1.length ) { bindPass1(); } /** * Fix a LastPass mismatch issue, LastPass only changes pass2. * * This fixes the issue by copying any changes from the hidden * pass2 field to the pass1 field, then running check_pass_strength. */ $pass2 = $('#pass2').on( inputEvent, function () { if ( $pass2.val().length > 0 ) { $pass1.val( $pass2.val() ); $pass2.val(''); currentPass = ''; $pass1.trigger( 'pwupdate' ); } } ); // Disable hidden inputs to prevent autofill and submission. if ( $pass1.is( ':hidden' ) ) { $pass1.prop( 'disabled', true ); $pass2.prop( 'disabled', true ); $pass1Text.prop( 'disabled', true ); } $passwordWrapper = $pass1Row.find( '.wp-pwd' ); $generateButton = $pass1Row.find( 'button.wp-generate-pw' ); bindToggleButton(); if ( $generateButton.length ) { $passwordWrapper.hide(); } $generateButton.show(); $generateButton.on( 'click', function () { updateLock = true; $generateButton.hide(); $passwordWrapper.show(); // Enable the inputs when showing. $pass1.attr( 'disabled', false ); $pass2.attr( 'disabled', false ); $pass1Text.attr( 'disabled', false ); if ( $pass1Text.val().length === 0 ) { generatePassword(); } _.defer( function() { $pass1Text.focus(); if ( ! _.isUndefined( $pass1Text[0].setSelectionRange ) ) { $pass1Text[0].setSelectionRange( 0, 100 ); } }, 0 ); } ); $cancelButton = $pass1Row.find( 'button.wp-cancel-pw' ); $cancelButton.on( 'click', function () { updateLock = false; // Clear any entered password. $pass1Text.val( '' ); // Generate a new password. wp.ajax.post( 'generate-password' ) .done( function( data ) { $pass1.data( 'pw', data ); } ); $generateButton.show(); $passwordWrapper.hide(); $weakRow.hide( 0, function () { $weakCheckbox.removeProp( 'checked' ); } ); // Disable the inputs when hiding to prevent autofill and submission. $pass1.prop( 'disabled', true ); $pass2.prop( 'disabled', true ); $pass1Text.prop( 'disabled', true ); resetToggle(); if ( $pass1Row.closest( 'form' ).is( '#your-profile' ) ) { // Clear password field to prevent update $pass1.val( '' ).trigger( 'pwupdate' ); $submitButtons.prop( 'disabled', false ); } } ); $pass1Row.closest( 'form' ).on( 'submit', function () { updateLock = false; $pass1.prop( 'disabled', false ); $pass2.prop( 'disabled', false ); $pass2.val( $pass1.val() ); $pass1Wrap.removeClass( 'show-password' ); }); } function check_pass_strength() { var pass1 = $('#pass1').val(), strength; $('#pass-strength-result').removeClass('short bad good strong'); if ( ! pass1 ) { $('#pass-strength-result').html( ' ' ); return; } strength = wp.passwordStrength.meter( pass1, wp.passwordStrength.userInputBlacklist(), pass1 ); switch ( strength ) { case -1: $( '#pass-strength-result' ).addClass( 'bad' ).html( pwsL10n.unknown ); break; 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'] ); } } function showOrHideWeakPasswordCheckbox() { var passStrength = $('#pass-strength-result')[0]; if ( passStrength.className ) { $pass1.add( $pass1Text ).addClass( passStrength.className ); if ( 'short' === passStrength.className || 'bad' === passStrength.className ) { if ( ! $weakCheckbox.prop( 'checked' ) ) { $submitButtons.prop( 'disabled', true ); } $weakRow.show(); } else { $submitButtons.prop( 'disabled', false ); $weakRow.hide(); } } } $(document).ready( function() { var $colorpicker, $stylesheet, user_id, current_user_id, select = $( '#display_name' ); $('#pass1').val('').on( inputEvent + ' pwupdate', 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 ); } }); }); } $colorpicker = $( '#color-picker' ); $stylesheet = $( '#colors-css' ); user_id = $( 'input#user_id' ).val(); current_user_id = $( 'input[name="checkuser_id"]' ).val(); $colorpicker.on( 'click.colorpicker', '.color-option', function() { var colors, $this = $(this); if ( $this.hasClass( 'selected' ) ) { return; } $this.siblings( '.selected' ).removeClass( 'selected' ); $this.addClass( 'selected' ).find( 'input[type="radio"]' ).prop( 'checked', true ); // Set color scheme if ( user_id === current_user_id ) { // Load the colors stylesheet. // The default color scheme won't have one, so we'll need to create an element. if ( 0 === $stylesheet.length ) { $stylesheet = $( '<link rel="stylesheet" />' ).appendTo( 'head' ); } $stylesheet.attr( 'href', $this.children( '.css_url' ).val() ); // repaint icons if ( typeof wp !== 'undefined' && wp.svgPainter ) { try { colors = $.parseJSON( $this.children( '.icon_colors' ).val() ); } catch ( error ) {} if ( colors ) { wp.svgPainter.setColors( colors ); wp.svgPainter.paint(); } } // update user option $.post( ajaxurl, { action: 'save-user-color-scheme', color_scheme: $this.children( 'input[name="admin_color"]' ).val(), nonce: $('#color-nonce').val() }).done( function( response ) { if ( response.success ) { $( 'body' ).removeClass( response.data.previousScheme ).addClass( response.data.currentScheme ); } }); } }); bindPasswordForm(); }); $( '#destroy-sessions' ).on( 'click', function( e ) { var $this = $(this); wp.ajax.post( 'destroy-sessions', { nonce: $( '#_wpnonce' ).val(), user_id: $( '#user_id' ).val() }).done( function( response ) { $this.prop( 'disabled', true ); $this.siblings( '.notice' ).remove(); $this.before( '<div class="notice notice-success inline"><p>' + response.message + '</p></div>' ); }).fail( function( response ) { $this.siblings( '.notice' ).remove(); $this.before( '<div class="notice notice-error inline"><p>' + response.message + '</p></div>' ); }); e.preventDefault(); }); window.generatePassword = generatePassword; /* Warn the user if password was generated but not saved */ $( window ).on( 'beforeunload', function () { if ( true === updateLock ) { return userProfileL10n.warn; } } ); })(jQuery); gallery.js 0000666 00000012656 15213733063 0006562 0 ustar 00 /* global unescape, getUserSetting, setUserSetting */ jQuery(document).ready(function($) { var gallerySortable, gallerySortableInit, sortIt, clearAll, w, desc = false; gallerySortableInit = function() { gallerySortable = $('#media-items').sortable( { items: 'div.media-item', placeholder: 'sorthelper', axis: 'y', distance: 2, handle: 'div.filename', stop: function() { // When an update has occurred, adjust the order for each item var all = $('#media-items').sortable('toArray'), len = all.length; $.each(all, function(i, id) { var order = desc ? (len - i) : (1 + i); $('#' + id + ' .menu_order input').val(order); }); } } ); }; sortIt = function() { var all = $('.menu_order_input'), len = all.length; all.each(function(i){ var order = desc ? (len - i) : (1 + i); $(this).val(order); }); }; clearAll = function(c) { c = c || 0; $('.menu_order_input').each( function() { if ( this.value === '0' || c ) { this.value = ''; } }); }; $('#asc').click( function( e ) { e.preventDefault(); desc = false; sortIt(); }); $('#desc').click( function( e ) { e.preventDefault(); desc = true; sortIt(); }); $('#clear').click( function( e ) { e.preventDefault(); clearAll(1); }); $('#showall').click( function( e ) { e.preventDefault(); $('#sort-buttons span a').toggle(); $('a.describe-toggle-on').hide(); $('a.describe-toggle-off, table.slidetoggle').show(); $('img.pinkynail').toggle(false); }); $('#hideall').click( function( e ) { e.preventDefault(); $('#sort-buttons span a').toggle(); $('a.describe-toggle-on').show(); $('a.describe-toggle-off, table.slidetoggle').hide(); $('img.pinkynail').toggle(true); }); // initialize sortable gallerySortableInit(); clearAll(); if ( $('#media-items>*').length > 1 ) { w = wpgallery.getWin(); $('#save-all, #gallery-settings').show(); if ( typeof w.tinyMCE !== 'undefined' && w.tinyMCE.activeEditor && ! w.tinyMCE.activeEditor.isHidden() ) { wpgallery.mcemode = true; wpgallery.init(); } else { $('#insert-gallery').show(); } } }); jQuery(window).unload( function () { tinymce = tinyMCE = wpgallery = null; } ); // Cleanup /* gallery settings */ var tinymce = null, tinyMCE, wpgallery; wpgallery = { mcemode : false, editor : {}, dom : {}, is_update : false, el : {}, I : function(e) { return document.getElementById(e); }, init: function() { var t = this, li, q, i, it, w = t.getWin(); if ( ! t.mcemode ) { return; } li = ('' + document.location.search).replace(/^\?/, '').split('&'); q = {}; for (i=0; i<li.length; i++) { it = li[i].split('='); q[unescape(it[0])] = unescape(it[1]); } if ( q.mce_rdomain ) { document.domain = q.mce_rdomain; } // Find window & API tinymce = w.tinymce; tinyMCE = w.tinyMCE; t.editor = tinymce.EditorManager.activeEditor; t.setup(); }, getWin : function() { return window.dialogArguments || opener || parent || top; }, setup : function() { var t = this, a, ed = t.editor, g, columns, link, order, orderby; if ( ! t.mcemode ) { return; } t.el = ed.selection.getNode(); if ( t.el.nodeName !== 'IMG' || ! ed.dom.hasClass(t.el, 'wpGallery') ) { if ( ( g = ed.dom.select('img.wpGallery') ) && g[0] ) { t.el = g[0]; } else { if ( getUserSetting('galfile') === '1' ) { t.I('linkto-file').checked = 'checked'; } if ( getUserSetting('galdesc') === '1' ) { t.I('order-desc').checked = 'checked'; } if ( getUserSetting('galcols') ) { t.I('columns').value = getUserSetting('galcols'); } if ( getUserSetting('galord') ) { t.I('orderby').value = getUserSetting('galord'); } jQuery('#insert-gallery').show(); return; } } a = ed.dom.getAttrib(t.el, 'title'); a = ed.dom.decode(a); if ( a ) { jQuery('#update-gallery').show(); t.is_update = true; columns = a.match(/columns=['"]([0-9]+)['"]/); link = a.match(/link=['"]([^'"]+)['"]/i); order = a.match(/order=['"]([^'"]+)['"]/i); orderby = a.match(/orderby=['"]([^'"]+)['"]/i); if ( link && link[1] ) { t.I('linkto-file').checked = 'checked'; } if ( order && order[1] ) { t.I('order-desc').checked = 'checked'; } if ( columns && columns[1] ) { t.I('columns').value = '' + columns[1]; } if ( orderby && orderby[1] ) { t.I('orderby').value = orderby[1]; } } else { jQuery('#insert-gallery').show(); } }, update : function() { var t = this, ed = t.editor, all = '', s; if ( ! t.mcemode || ! t.is_update ) { s = '[gallery' + t.getSettings() + ']'; t.getWin().send_to_editor(s); return; } if ( t.el.nodeName !== 'IMG' ) { return; } all = ed.dom.decode( ed.dom.getAttrib( t.el, 'title' ) ); all = all.replace(/\s*(order|link|columns|orderby)=['"]([^'"]+)['"]/gi, ''); all += t.getSettings(); ed.dom.setAttrib(t.el, 'title', all); t.getWin().tb_remove(); }, getSettings : function() { var I = this.I, s = ''; if ( I('linkto-file').checked ) { s += ' link="file"'; setUserSetting('galfile', '1'); } if ( I('order-desc').checked ) { s += ' order="DESC"'; setUserSetting('galdesc', '1'); } if ( I('columns').value !== 3 ) { s += ' columns="' + I('columns').value + '"'; setUserSetting('galcols', I('columns').value); } if ( I('orderby').value !== 'menu_order' ) { s += ' orderby="' + I('orderby').value + '"'; setUserSetting('galord', I('orderby').value); } return s; } }; language-chooser.min.js 0000666 00000000566 15213733063 0011125 0 ustar 00 jQuery(function(n){var a=n("#language"),e=n("#language-continue");n("body").hasClass("language-chooser")&&(a.focus().on("change",function(){var n=a.children("option:selected");e.attr({value:n.data("continue"),lang:n.attr("lang")})}),n("form").submit(function(){a.children("option:selected").data("installed")||n(this).find(".step .spinner").css("visibility","visible")}))}); media.min.js 0000666 00000003522 15213733063 0006754 0 ustar 00 var findPosts;!function(s){findPosts={open:function(n,i){var e=s(".ui-find-overlay");return 0===e.length&&(s("body").append('<div class="ui-find-overlay"></div>'),findPosts.overlay()),e.show(),n&&i&&s("#affected").attr("name",n).val(i),s("#find-posts").show(),s("#find-posts-input").focus().keyup(function(n){27==n.which&&findPosts.close()}),findPosts.send(),!1},close:function(){s("#find-posts-response").empty(),s("#find-posts").hide(),s(".ui-find-overlay").hide()},overlay:function(){s(".ui-find-overlay").on("click",function(){findPosts.close()})},send:function(){var n={ps:s("#find-posts-input").val(),action:"find_posts",_ajax_nonce:s("#_ajax_nonce").val()},i=s(".find-box-search .spinner");i.addClass("is-active"),s.ajax(ajaxurl,{type:"POST",data:n,dataType:"json"}).always(function(){i.removeClass("is-active")}).done(function(n){n.success||s("#find-posts-response").text(attachMediaBoxL10n.error),s("#find-posts-response").html(n.data)}).fail(function(){s("#find-posts-response").text(attachMediaBoxL10n.error)})}},s(document).ready(function(){var n,i=s("#wp-media-grid");i.length&&window.wp&&window.wp.media&&(n=_wpMediaGridSettings,window.wp.media({frame:"manage",container:i,library:n.queryVars}).open()),s("#find-posts-submit").click(function(n){s('#find-posts-response input[type="radio"]:checked').length||n.preventDefault()}),s("#find-posts .find-box-search :input").keypress(function(n){if(13==n.which)return findPosts.send(),!1}),s("#find-posts-search").click(findPosts.send),s("#find-posts-close").click(findPosts.close),s("#doaction, #doaction2").click(function(i){s('select[name^="action"]').each(function(){var n=s(this).val();"attach"===n?(i.preventDefault(),findPosts.open()):"delete"===n&&(showNotice.warn()||i.preventDefault())})}),s(".find-box-inside").on("click","tr",function(){s(this).find(".found-radio input").prop("checked",!0)})})}(jQuery); inline-edit-post.js 0000666 00000026604 15213733063 0010305 0 ustar 00 /* global inlineEditL10n, ajaxurl, typenow */ window.wp = window.wp || {}; var inlineEditPost; ( function( $, wp ) { inlineEditPost = { init : function(){ var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit'); t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post'; t.what = '#post-'; // prepare the edit rows qeRow.keyup(function(e){ if ( e.which === 27 ) { return inlineEditPost.revert(); } }); bulkRow.keyup(function(e){ if ( e.which === 27 ) { return inlineEditPost.revert(); } }); $( '.cancel', qeRow ).click( function() { return inlineEditPost.revert(); }); $( '.save', qeRow ).click( function() { return inlineEditPost.save(this); }); $('td', qeRow).keydown(function(e){ if ( e.which === 13 && ! $( e.target ).hasClass( 'cancel' ) ) { return inlineEditPost.save(this); } }); $( '.cancel', bulkRow ).click( function() { return inlineEditPost.revert(); }); $('#inline-edit .inline-edit-private input[value="private"]').click( function(){ var pw = $('input.inline-edit-password-input'); if ( $(this).prop('checked') ) { pw.val('').prop('disabled', true); } else { pw.prop('disabled', false); } }); // add events $('#the-list').on( 'click', 'a.editinline', function( e ) { e.preventDefault(); inlineEditPost.edit(this); }); $('#bulk-edit').find('fieldset:first').after( $('#inline-edit fieldset.inline-edit-categories').clone() ).siblings( 'fieldset:last' ).prepend( $('#inline-edit label.inline-edit-tags').clone() ); $('select[name="_status"] option[value="future"]', bulkRow).remove(); $('#doaction, #doaction2').click(function(e){ var n; t.whichBulkButtonId = $( this ).attr( 'id' ); n = t.whichBulkButtonId.substr( 2 ); if ( 'edit' === $( 'select[name="' + n + '"]' ).val() ) { e.preventDefault(); t.setBulk(); } else if ( $('form#posts-filter tr.inline-editor').length > 0 ) { t.revert(); } }); }, toggle : function(el){ var t = this; $( t.what + t.getId( el ) ).css( 'display' ) === 'none' ? t.revert() : t.edit( el ); }, setBulk : function(){ var te = '', type = this.type, c = true; this.revert(); $( '#bulk-edit td' ).attr( 'colspan', $( 'th:visible, td:visible', '.widefat:first thead' ).length ); // Insert the editor at the top of the table with an empty row above to maintain zebra striping. $('table.widefat tbody').prepend( $('#bulk-edit') ).prepend('<tr class="hidden"></tr>'); $('#bulk-edit').addClass('inline-editor').show(); $( 'tbody th.check-column input[type="checkbox"]' ).each( function() { if ( $(this).prop('checked') ) { c = false; var id = $(this).val(), theTitle; theTitle = $('#inline_'+id+' .post_title').html() || inlineEditL10n.notitle; te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>'; } }); if ( c ) { return this.revert(); } $('#bulk-titles').html(te); $('#bulk-titles a').click(function(){ var id = $(this).attr('id').substr(1); $('table.widefat input[value="' + id + '"]').prop('checked', false); $('#ttle'+id).remove(); }); // enable autocomplete for tags if ( 'post' === type ) { $( 'tr.inline-editor textarea[data-wp-taxonomy]' ).each( function ( i, element ) { /* * While Quick Edit clones the form each time, Bulk Edit always re-uses * the same form. Let's check if an autocomplete instance already exists. */ if ( $( element ).autocomplete( 'instance' ) ) { // jQuery equivalent of `continue` within an `each()` loop. return; } $( element ).wpTagsSuggest(); } ); } $('html, body').animate( { scrollTop: 0 }, 'fast' ); }, edit : function(id) { var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, f, val, pw; t.revert(); if ( typeof(id) === 'object' ) { id = t.getId(id); } fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order', 'page_template']; if ( t.type === 'page' ) { fields.push('post_parent'); } // add the new edit row with an extra blank row underneath to maintain zebra striping. editRow = $('#inline-edit').clone(true); $( 'td', editRow ).attr( 'colspan', $( 'th:visible, td:visible', '.widefat:first thead' ).length ); $(t.what+id).removeClass('is-expanded').hide().after(editRow).after('<tr class="hidden"></tr>'); // populate the data rowData = $('#inline_'+id); if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) { // author no longer has edit caps, so we need to add them to the list of authors $(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>'); } if ( $( ':input[name="post_author"] option', editRow ).length === 1 ) { $('label.inline-edit-author', editRow).hide(); } for ( f = 0; f < fields.length; f++ ) { val = $('.'+fields[f], rowData); // Deal with Twemoji val.find( 'img' ).replaceWith( function() { return this.alt; } ); val = val.text(); $(':input[name="' + fields[f] + '"]', editRow).val( val ); } if ( $( '.comment_status', rowData ).text() === 'open' ) { $( 'input[name="comment_status"]', editRow ).prop( 'checked', true ); } if ( $( '.ping_status', rowData ).text() === 'open' ) { $( 'input[name="ping_status"]', editRow ).prop( 'checked', true ); } if ( $( '.sticky', rowData ).text() === 'sticky' ) { $( 'input[name="sticky"]', editRow ).prop( 'checked', true ); } // hierarchical taxonomies $('.post_category', rowData).each(function(){ var taxname, term_ids = $(this).text(); if ( term_ids ) { taxname = $(this).attr('id').replace('_'+id, ''); $('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(',')); } }); //flat taxonomies $('.tags_input', rowData).each(function(){ var terms = $(this), taxname = $(this).attr('id').replace('_' + id, ''), textarea = $('textarea.tax_input_' + taxname, editRow), comma = inlineEditL10n.comma; terms.find( 'img' ).replaceWith( function() { return this.alt; } ); terms = terms.text(); if ( terms ) { if ( ',' !== comma ) { terms = terms.replace(/,/g, comma); } textarea.val(terms); } textarea.wpTagsSuggest(); }); // handle the post status status = $('._status', rowData).text(); if ( 'future' !== status ) { $('select[name="_status"] option[value="future"]', editRow).remove(); } pw = $( '.inline-edit-password-input' ).prop( 'disabled', false ); if ( 'private' === status ) { $('input[name="keep_private"]', editRow).prop('checked', true); pw.val( '' ).prop( 'disabled', true ); } // remove the current page and children from the parent dropdown pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow); if ( pageOpt.length > 0 ) { pageLevel = pageOpt[0].className.split('-')[1]; nextPage = pageOpt; while ( pageLoop ) { nextPage = nextPage.next('option'); if ( nextPage.length === 0 ) { break; } nextLevel = nextPage[0].className.split('-')[1]; if ( nextLevel <= pageLevel ) { pageLoop = false; } else { nextPage.remove(); nextPage = pageOpt; } } pageOpt.remove(); } $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show(); $('.ptitle', editRow).focus(); return false; }, // Ajax saving is only for Quick Edit. save : function(id) { var params, fields, page = $('.post_status_page').val() || ''; if ( typeof(id) === 'object' ) { id = this.getId(id); } $( 'table.widefat .spinner' ).addClass( 'is-active' ); params = { action: 'inline-save', post_type: typenow, post_ID: id, edit_date: 'true', post_status: page }; fields = $('#edit-'+id).find(':input').serialize(); params = fields + '&' + $.param(params); // make ajax request $.post( ajaxurl, params, function(r) { var $errorSpan = $( '#edit-' + id + ' .inline-edit-save .error' ); $( 'table.widefat .spinner' ).removeClass( 'is-active' ); $( '.ac_results' ).hide(); if (r) { if ( -1 !== r.indexOf( '<tr' ) ) { $(inlineEditPost.what+id).siblings('tr.hidden').addBack().remove(); $('#edit-'+id).before(r).remove(); $( inlineEditPost.what + id ).hide().fadeIn( 400, function() { // Move focus back to the Quick Edit link. $( this ) is the row being animated. $( this ).find( '.editinline' ).focus(); wp.a11y.speak( inlineEditL10n.saved ); }); } else { r = r.replace( /<.[^<>]*?>/g, '' ); $errorSpan.html( r ).show(); wp.a11y.speak( $errorSpan.text() ); } } else { $errorSpan.html( inlineEditL10n.error ).show(); wp.a11y.speak( inlineEditL10n.error ); } }, 'html'); // Prevent submitting the form when pressing Enter on a focused field. return false; }, // Revert is for both Quick Edit and Bulk Edit. revert : function(){ var $tableWideFat = $( '.widefat' ), id = $( '.inline-editor', $tableWideFat ).attr( 'id' ); if ( id ) { $( '.spinner', $tableWideFat ).removeClass( 'is-active' ); $( '.ac_results' ).hide(); if ( 'bulk-edit' === id ) { $( '#bulk-edit', $tableWideFat ).removeClass( 'inline-editor' ).hide().siblings( '.hidden' ).remove(); $('#bulk-titles').empty(); $('#inlineedit').append( $('#bulk-edit') ); // Move focus back to the Bulk Action button that was activated. $( '#' + inlineEditPost.whichBulkButtonId ).focus(); } else { $('#'+id).siblings('tr.hidden').addBack().remove(); id = id.substr( id.lastIndexOf('-') + 1 ); // Show the post row and move focus back to the Quick Edit link. $( this.what + id ).show().find( '.editinline' ).focus(); } } return false; }, getId : function(o) { var id = $(o).closest('tr').attr('id'), parts = id.split('-'); return parts[parts.length - 1]; } }; $( document ).ready( function(){ inlineEditPost.init(); } ); // Show/hide locks on posts $( document ).on( 'heartbeat-tick.wp-check-locked-posts', function( e, data ) { var locked = data['wp-check-locked-posts'] || {}; $('#the-list tr').each( function(i, el) { var key = el.id, row = $(el), lock_data, avatar; if ( locked.hasOwnProperty( key ) ) { if ( ! row.hasClass('wp-locked') ) { lock_data = locked[key]; row.find('.column-title .locked-text').text( lock_data.text ); row.find('.check-column checkbox').prop('checked', false); if ( lock_data.avatar_src ) { avatar = $( '<img class="avatar avatar-18 photo" width="18" height="18" alt="" />' ).attr( 'src', lock_data.avatar_src.replace( /&/g, '&' ) ); row.find('.column-title .locked-avatar').empty().append( avatar ); } row.addClass('wp-locked'); } } else if ( row.hasClass('wp-locked') ) { // Make room for the CSS animation row.removeClass('wp-locked').delay(1000).find('.locked-info span').empty(); } }); }).on( 'heartbeat-send.wp-check-locked-posts', function( e, data ) { var check = []; $('#the-list tr').each( function(i, el) { if ( el.id ) { check.push( el.id ); } }); if ( check.length ) { data['wp-check-locked-posts'] = check; } }).ready( function() { // Set the heartbeat interval to 15 sec. if ( typeof wp !== 'undefined' && wp.heartbeat ) { wp.heartbeat.interval( 15 ); } }); })( jQuery, window.wp ); press-this.js 0000666 00000062256 15213733063 0007225 0 ustar 00 /** * PressThis App * */ ( function( $, window ) { var PressThis = function() { var editor, $mediaList, $mediaThumbWrap, $window = $( window ), $document = $( document ), saveAlert = false, textarea = document.createElement( 'textarea' ), sidebarIsOpen = false, settings = window.wpPressThisConfig || {}, data = window.wpPressThisData || {}, smallestWidth = 128, hasSetFocus = false, catsCache = [], isOffScreen = 'is-off-screen', isHidden = 'is-hidden', offscreenHidden = isOffScreen + ' ' + isHidden, iOS = /iPad|iPod|iPhone/.test( window.navigator.userAgent ), $textEditor = $( '#pressthis' ), textEditor = $textEditor[0], textEditorMinHeight = 600, textLength = 0, transitionEndEvent = ( function() { var style = document.documentElement.style; if ( typeof style.transition !== 'undefined' ) { return 'transitionend'; } if ( typeof style.WebkitTransition !== 'undefined' ) { return 'webkitTransitionEnd'; } return false; }() ); /* *************************************************************** * HELPER FUNCTIONS *************************************************************** */ /** * Emulates our PHP __() gettext function, powered by the strings exported in pressThisL10n. * * @param key string Key of the string to be translated, as found in pressThisL10n. * @returns string Original or translated string, or empty string if no key. */ function __( key ) { if ( key && window.pressThisL10n ) { return window.pressThisL10n[key] || key; } return key || ''; } /** * Strips HTML tags * * @param string string Text to have the HTML tags striped out of. * @returns string Stripped text. */ function stripTags( string ) { string = string || ''; return string .replace( /<!--[\s\S]*?(-->|$)/g, '' ) .replace( /<(script|style)[^>]*>[\s\S]*?(<\/\1>|$)/ig, '' ) .replace( /<\/?[a-z][\s\S]*?(>|$)/ig, '' ); } /** * Strip HTML tags and convert HTML entities. * * @param text string Text. * @returns string Sanitized text. */ function sanitizeText( text ) { var _text = stripTags( text ); try { textarea.innerHTML = _text; _text = stripTags( textarea.value ); } catch ( er ) {} return _text; } /** * Allow only HTTP or protocol relative URLs. * * @param url string The URL. * @returns string Processed URL. */ function checkUrl( url ) { url = $.trim( url || '' ); if ( /^(?:https?:)?\/\//.test( url ) ) { url = stripTags( url ); return url.replace( /["\\]+/g, '' ); } return ''; } /** * Show UX spinner */ function showSpinner() { $( '.spinner' ).addClass( 'is-active' ); $( '.post-actions button' ).attr( 'disabled', 'disabled' ); } /** * Hide UX spinner */ function hideSpinner() { $( '.spinner' ).removeClass( 'is-active' ); $( '.post-actions button' ).removeAttr( 'disabled' ); } function textEditorResize( reset ) { var pageYOffset, height; if ( editor && ! editor.isHidden() ) { return; } reset = ( reset === 'reset' ) || ( textLength && textLength > textEditor.value.length ); height = textEditor.style.height; if ( reset ) { pageYOffset = window.pageYOffset; textEditor.style.height = 'auto'; textEditor.style.height = Math.max( textEditor.scrollHeight, textEditorMinHeight ) + 'px'; window.scrollTo( window.pageXOffset, pageYOffset ); } else if ( parseInt( textEditor.style.height, 10 ) < textEditor.scrollHeight ) { textEditor.style.height = textEditor.scrollHeight + 'px'; } textLength = textEditor.value.length; } function mceGetCursorOffset() { if ( ! editor ) { return false; } var node = editor.selection.getNode(), range, view, offset; if ( editor.wp && editor.wp.getView && ( view = editor.wp.getView( node ) ) ) { offset = view.getBoundingClientRect(); } else { range = editor.selection.getRng(); try { offset = range.getClientRects()[0]; } catch( er ) {} if ( ! offset ) { offset = node.getBoundingClientRect(); } } return offset.height ? offset : false; } // Make sure the caret is always visible. function mceKeyup( event ) { var VK = window.tinymce.util.VK, key = event.keyCode; // Bail on special keys. if ( key <= 47 && ! ( key === VK.SPACEBAR || key === VK.ENTER || key === VK.DELETE || key === VK.BACKSPACE || key === VK.UP || key === VK.LEFT || key === VK.DOWN || key === VK.UP ) ) { return; // OS keys, function keys, num lock, scroll lock } else if ( ( key >= 91 && key <= 93 ) || ( key >= 112 && key <= 123 ) || key === 144 || key === 145 ) { return; } mceScroll( key ); } function mceScroll( key ) { var cursorTop, cursorBottom, editorBottom, offset = mceGetCursorOffset(), bufferTop = 50, bufferBottom = 65, VK = window.tinymce.util.VK; if ( ! offset ) { return; } cursorTop = offset.top + editor.iframeElement.getBoundingClientRect().top; cursorBottom = cursorTop + offset.height; cursorTop = cursorTop - bufferTop; cursorBottom = cursorBottom + bufferBottom; editorBottom = $window.height(); // Don't scroll if the node is taller than the visible part of the editor if ( editorBottom < offset.height ) { return; } if ( cursorTop < 0 && ( key === VK.UP || key === VK.LEFT || key === VK.BACKSPACE ) ) { window.scrollTo( window.pageXOffset, cursorTop + window.pageYOffset ); } else if ( cursorBottom > editorBottom ) { window.scrollTo( window.pageXOffset, cursorBottom + window.pageYOffset - editorBottom ); } } /** * Replace emoji images with chars and sanitize the text content. */ function getTitleText() { var $element = $( '#title-container' ); $element.find( 'img.emoji' ).each( function() { var $image = $( this ); $image.replaceWith( $( '<span>' ).text( $image.attr( 'alt' ) ) ); }); return sanitizeText( $element.text() ); } /** * Prepare the form data for saving. */ function prepareFormData() { var $form = $( '#pressthis-form' ), $input = $( '<input type="hidden" name="post_category[]" value="">' ); editor && editor.save(); $( '#post_title' ).val( getTitleText() ); // Make sure to flush out the tags with tagBox before saving if ( window.tagBox ) { $( 'div.tagsdiv' ).each( function() { window.tagBox.flushTags( this, false, 1 ); } ); } // Get selected categories $( '.categories-select .category' ).each( function( i, element ) { var $cat = $( element ); if ( $cat.hasClass( 'selected' ) ) { // Have to append a node as we submit the actual form on preview $form.append( $input.clone().val( $cat.attr( 'data-term-id' ) || '' ) ); } }); } /** * Submit the post form via AJAX, and redirect to the proper screen if published vs saved as a draft. * * @param action string publish|draft */ function submitPost( action ) { var data; saveAlert = false; showSpinner(); if ( 'publish' === action ) { $( '#post_status' ).val( 'publish' ); } prepareFormData(); data = $( '#pressthis-form' ).serialize(); $.ajax( { type: 'post', url: window.ajaxurl, data: data }).always( function() { hideSpinner(); clearNotices(); $( '.publish-button' ).removeClass( 'is-saving' ); }).done( function( response ) { if ( ! response.success ) { renderError( response.data.errorMessage ); } else if ( response.data.redirect ) { if ( window.opener && ( settings.redirInParent || response.data.force ) ) { try { window.opener.location.href = response.data.redirect; window.setTimeout( function() { window.self.close(); }, 200 ); } catch( er ) { window.location.href = response.data.redirect; } } else { window.location.href = response.data.redirect; } } }).fail( function() { renderError( __( 'serverError' ) ); }); } /** * Inserts the media a user has selected from the presented list inside the editor, as an image or embed, based on type * * @param type string img|embed * @param src string Source URL * @param link string Optional destination link, for images (defaults to src) */ function insertSelectedMedia( $element ) { var src, link, newContent = ''; src = checkUrl( $element.attr( 'data-wp-src' ) || '' ); link = checkUrl( data.u ); if ( $element.hasClass( 'is-image' ) ) { if ( ! link ) { link = src; } newContent = '<a href="' + link + '"><img class="alignnone size-full" src="' + src + '" alt="" /></a>'; } else { newContent = '[embed]' + src + '[/embed]'; } if ( editor && ! editor.isHidden() ) { if ( ! hasSetFocus ) { editor.setContent( '<p>' + newContent + '</p>' + editor.getContent() ); } else { editor.execCommand( 'mceInsertContent', false, newContent ); } } else if ( window.QTags ) { window.QTags.insertContent( newContent ); } } /** * Save a new user-generated category via AJAX */ function saveNewCategory() { var data, name = $( '#new-category' ).val(); if ( ! name ) { return; } data = { action: 'press-this-add-category', post_id: $( '#post_ID' ).val() || 0, name: name, new_cat_nonce: $( '#_ajax_nonce-add-category' ).val() || '', parent: $( '#new-category-parent' ).val() || 0 }; $.post( window.ajaxurl, data, function( response ) { if ( ! response.success ) { renderError( response.data.errorMessage ); } else { var $parent, $ul, $wrap = $( 'ul.categories-select' ); $.each( response.data, function( i, newCat ) { var $node = $( '<li>' ).append( $( '<div class="category selected" tabindex="0" role="checkbox" aria-checked="true">' ) .attr( 'data-term-id', newCat.term_id ) .text( newCat.name ) ); if ( newCat.parent ) { if ( ! $ul || ! $ul.length ) { $parent = $wrap.find( 'div[data-term-id="' + newCat.parent + '"]' ).parent(); $ul = $parent.find( 'ul.children:first' ); if ( ! $ul.length ) { $ul = $( '<ul class="children">' ).appendTo( $parent ); } } $ul.prepend( $node ); } else { $wrap.prepend( $node ); } $node.focus(); } ); refreshCatsCache(); } } ); } /* *************************************************************** * RENDERING FUNCTIONS *************************************************************** */ /** * Hide the form letting users enter a URL to be scanned, if a URL was already passed. */ function renderToolsVisibility() { if ( data.hasData ) { $( '#scanbar' ).hide(); } } /** * Render error notice * * @param msg string Notice/error message * @param error string error|notice CSS class for display */ function renderNotice( msg, error ) { var $alerts = $( '.editor-wrapper div.alerts' ), className = error ? 'is-error' : 'is-notice'; $alerts.append( $( '<p class="alert ' + className + '">' ).text( msg ) ); } /** * Render error notice * * @param msg string Error message */ function renderError( msg ) { renderNotice( msg, true ); } function clearNotices() { $( 'div.alerts' ).empty(); } /** * Render notices on page load, if any already */ function renderStartupNotices() { // Render errors sent in the data, if any if ( data.errors ) { $.each( data.errors, function( i, msg ) { renderError( msg ); } ); } } /** * Add an image to the list of found images. */ function addImg( src, displaySrc, i ) { var $element = $mediaThumbWrap.clone().addClass( 'is-image' ); $element.attr( 'data-wp-src', src ).css( 'background-image', 'url(' + displaySrc + ')' ) .find( 'span' ).text( __( 'suggestedImgAlt' ).replace( '%d', i + 1 ) ); $mediaList.append( $element ); } /** * Render the detected images and embed for selection, if any */ function renderDetectedMedia() { var found = 0; $mediaList = $( 'ul.media-list' ); $mediaThumbWrap = $( '<li class="suggested-media-thumbnail" tabindex="0"><span class="screen-reader-text"></span></li>' ); if ( data._embeds ) { $.each( data._embeds, function ( i, src ) { var displaySrc = '', cssClass = '', $element = $mediaThumbWrap.clone().addClass( 'is-embed' ); src = checkUrl( src ); if ( src.indexOf( 'youtube.com/' ) > -1 ) { displaySrc = 'https://i.ytimg.com/vi/' + src.replace( /.+v=([^&]+).*/, '$1' ) + '/hqdefault.jpg'; cssClass += ' is-video'; } else if ( src.indexOf( 'youtu.be/' ) > -1 ) { displaySrc = 'https://i.ytimg.com/vi/' + src.replace( /\/([^\/])$/, '$1' ) + '/hqdefault.jpg'; cssClass += ' is-video'; } else if ( src.indexOf( 'dailymotion.com' ) > -1 ) { displaySrc = src.replace( '/video/', '/thumbnail/video/' ); cssClass += ' is-video'; } else if ( src.indexOf( 'soundcloud.com' ) > -1 ) { cssClass += ' is-audio'; } else if ( src.indexOf( 'twitter.com' ) > -1 ) { cssClass += ' is-tweet'; } else { cssClass += ' is-video'; } $element.attr( 'data-wp-src', src ).find( 'span' ).text( __( 'suggestedEmbedAlt' ).replace( '%d', i + 1 ) ); if ( displaySrc ) { $element.css( 'background-image', 'url(' + displaySrc + ')' ); } $mediaList.append( $element ); found++; } ); } if ( data._images ) { $.each( data._images, function( i, src ) { var displaySrc, img = new Image(); src = checkUrl( src ); displaySrc = src.replace( /^(http[^\?]+)(\?.*)?$/, '$1' ); if ( src.indexOf( 'files.wordpress.com/' ) > -1 ) { displaySrc = displaySrc.replace( /\?.*$/, '' ) + '?w=' + smallestWidth; } else if ( src.indexOf( 'gravatar.com/' ) > -1 ) { displaySrc = displaySrc.replace( /\?.*$/, '' ) + '?s=' + smallestWidth; } else { displaySrc = src; } img.onload = function() { if ( ( img.width && img.width < 256 ) || ( img.height && img.height < 128 ) ) { return; } addImg( src, displaySrc, i ); }; img.src = src; found++; } ); } if ( found ) { $( '.media-list-container' ).addClass( 'has-media' ); } } /* *************************************************************** * MONITORING FUNCTIONS *************************************************************** */ /** * Interactive navigation behavior for the options modal (post format, tags, categories) */ function monitorOptionsModal() { var $postOptions = $( '.post-options' ), $postOption = $( '.post-option' ), $settingModal = $( '.setting-modal' ), $modalClose = $( '.modal-close' ); $postOption.on( 'click', function() { var index = $( this ).index(), $targetSettingModal = $settingModal.eq( index ); $postOptions.addClass( isOffScreen ) .one( transitionEndEvent, function() { $( this ).addClass( isHidden ); } ); $targetSettingModal.removeClass( offscreenHidden ) .one( transitionEndEvent, function() { $( this ).find( '.modal-close' ).focus(); } ); } ); $modalClose.on( 'click', function() { var $targetSettingModal = $( this ).parent(), index = $targetSettingModal.index(); $postOptions.removeClass( offscreenHidden ); $targetSettingModal.addClass( isOffScreen ); if ( transitionEndEvent ) { $targetSettingModal.one( transitionEndEvent, function() { $( this ).addClass( isHidden ); $postOption.eq( index - 1 ).focus(); } ); } else { setTimeout( function() { $targetSettingModal.addClass( isHidden ); $postOption.eq( index - 1 ).focus(); }, 350 ); } } ); } /** * Interactive behavior for the sidebar toggle, to show the options modals */ function openSidebar() { sidebarIsOpen = true; $( '.options' ).removeClass( 'closed' ).addClass( 'open' ); $( '.press-this-actions, #scanbar' ).addClass( isHidden ); $( '.options-panel-back' ).removeClass( isHidden ); $( '.options-panel' ).removeClass( offscreenHidden ) .one( transitionEndEvent, function() { $( '.post-option:first' ).focus(); } ); } function closeSidebar() { sidebarIsOpen = false; $( '.options' ).removeClass( 'open' ).addClass( 'closed' ); $( '.options-panel-back' ).addClass( isHidden ); $( '.press-this-actions, #scanbar' ).removeClass( isHidden ); $( '.options-panel' ).addClass( isOffScreen ) .one( transitionEndEvent, function() { $( this ).addClass( isHidden ); // Reset to options list $( '.post-options' ).removeClass( offscreenHidden ); $( '.setting-modal').addClass( offscreenHidden ); }); } /** * Interactive behavior for the post title's field placeholder */ function monitorPlaceholder() { var $titleField = $( '#title-container' ), $placeholder = $( '.post-title-placeholder' ); $titleField.on( 'focus', function() { $placeholder.addClass( 'is-hidden' ); }).on( 'blur', function() { if ( ! $titleField.text() && ! $titleField.html() ) { $placeholder.removeClass( 'is-hidden' ); } }).on( 'keyup', function() { saveAlert = true; }).on( 'paste', function( event ) { var text, range, clipboard = event.originalEvent.clipboardData || window.clipboardData; if ( clipboard ) { try{ text = clipboard.getData( 'Text' ) || clipboard.getData( 'text/plain' ); if ( text ) { text = $.trim( text.replace( /\s+/g, ' ' ) ); if ( window.getSelection ) { range = window.getSelection().getRangeAt(0); if ( range ) { if ( ! range.collapsed ) { range.deleteContents(); } range.insertNode( document.createTextNode( text ) ); } } else if ( document.selection ) { range = document.selection.createRange(); if ( range ) { range.text = text; } } } } catch ( er ) {} event.preventDefault(); } saveAlert = true; setTimeout( function() { $titleField.text( getTitleText() ); }, 50 ); }); if ( $titleField.text() || $titleField.html() ) { $placeholder.addClass('is-hidden'); } } function toggleCatItem( $element ) { if ( $element.hasClass( 'selected' ) ) { $element.removeClass( 'selected' ).attr( 'aria-checked', 'false' ); } else { $element.addClass( 'selected' ).attr( 'aria-checked', 'true' ); } } function monitorCatList() { $( '.categories-select' ).on( 'click.press-this keydown.press-this', function( event ) { var $element = $( event.target ); if ( $element.is( 'div.category' ) ) { if ( event.type === 'keydown' && event.keyCode !== 32 ) { return; } toggleCatItem( $element ); event.preventDefault(); } }); } function splitButtonClose() { $( '.split-button' ).removeClass( 'is-open' ); $( '.split-button-toggle' ).attr( 'aria-expanded', 'false' ); } /* *************************************************************** * PROCESSING FUNCTIONS *************************************************************** */ /** * Calls all the rendring related functions to happen on page load */ function render(){ // We're on! renderToolsVisibility(); renderDetectedMedia(); renderStartupNotices(); if ( window.tagBox ) { window.tagBox.init(); } // iOS doesn't fire click events on "standard" elements without this... if ( iOS ) { $( document.body ).css( 'cursor', 'pointer' ); } } /** * Set app events and other state monitoring related code. */ function monitor() { var $splitButton = $( '.split-button' ); $document.on( 'tinymce-editor-init', function( event, ed ) { editor = ed; editor.on( 'nodechange', function() { hasSetFocus = true; }); editor.on( 'focus', function() { splitButtonClose(); }); editor.on( 'show', function() { setTimeout( function() { editor.execCommand( 'wpAutoResize' ); }, 300 ); }); editor.on( 'hide', function() { setTimeout( function() { textEditorResize( 'reset' ); }, 100 ); }); editor.on( 'keyup', mceKeyup ); editor.on( 'undo redo', mceScroll ); }).on( 'click.press-this keypress.press-this', '.suggested-media-thumbnail', function( event ) { if ( event.type === 'click' || event.keyCode === 13 ) { insertSelectedMedia( $( this ) ); } }).on( 'click.press-this', function( event ) { if ( ! $( event.target ).closest( 'button' ).hasClass( 'split-button-toggle' ) ) { splitButtonClose(); } }); // Publish, Draft and Preview buttons $( '.post-actions' ).on( 'click.press-this', function( event ) { var location, $target = $( event.target ), $button = $target.closest( 'button' ); if ( $button.length ) { if ( $button.hasClass( 'draft-button' ) ) { $( '.publish-button' ).addClass( 'is-saving' ); submitPost( 'draft' ); } else if ( $button.hasClass( 'publish-button' ) ) { $button.addClass( 'is-saving' ); if ( window.history.replaceState ) { location = window.location.href; location += ( location.indexOf( '?' ) !== -1 ) ? '&' : '?'; location += 'wp-press-this-reload=true'; window.history.replaceState( null, null, location ); } submitPost( 'publish' ); } else if ( $button.hasClass( 'preview-button' ) ) { prepareFormData(); window.opener && window.opener.focus(); $( '#wp-preview' ).val( 'dopreview' ); $( '#pressthis-form' ).attr( 'target', '_blank' ).submit().attr( 'target', '' ); $( '#wp-preview' ).val( '' ); } else if ( $button.hasClass( 'standard-editor-button' ) ) { $( '.publish-button' ).addClass( 'is-saving' ); $( '#pt-force-redirect' ).val( 'true' ); submitPost( 'draft' ); } else if ( $button.hasClass( 'split-button-toggle' ) ) { if ( $splitButton.hasClass( 'is-open' ) ) { $splitButton.removeClass( 'is-open' ); $button.attr( 'aria-expanded', 'false' ); } else { $splitButton.addClass( 'is-open' ); $button.attr( 'aria-expanded', 'true' ); } } } }); monitorOptionsModal(); monitorPlaceholder(); monitorCatList(); $( '.options' ).on( 'click.press-this', function() { if ( $( this ).hasClass( 'open' ) ) { closeSidebar(); } else { openSidebar(); } }); // Close the sidebar when focus moves outside of it. $( '.options-panel, .options-panel-back' ).on( 'focusout.press-this', function() { setTimeout( function() { var node = document.activeElement, $node = $( node ); if ( sidebarIsOpen && node && ! $node.hasClass( 'options-panel-back' ) && ( node.nodeName === 'BODY' || ( ! $node.closest( '.options-panel' ).length && ! $node.closest( '.options' ).length ) ) ) { closeSidebar(); } }, 50 ); }); $( '#post-formats-select input' ).on( 'change', function() { var $this = $( this ); if ( $this.is( ':checked' ) ) { $( '#post-option-post-format' ).text( $( 'label[for="' + $this.attr( 'id' ) + '"]' ).text() || '' ); } } ); $window.on( 'beforeunload.press-this', function() { if ( saveAlert || ( editor && editor.isDirty() ) ) { return __( 'saveAlert' ); } } ).on( 'resize.press-this', function() { if ( ! editor || editor.isHidden() ) { textEditorResize( 'reset' ); } }); $( 'button.add-cat-toggle' ).on( 'click.press-this', function() { var $this = $( this ); $this.toggleClass( 'is-toggled' ); $this.attr( 'aria-expanded', 'false' === $this.attr( 'aria-expanded' ) ? 'true' : 'false' ); $( '.setting-modal .add-category, .categories-search-wrapper' ).toggleClass( 'is-hidden' ); } ); $( 'button.add-cat-submit' ).on( 'click.press-this', saveNewCategory ); $( '.categories-search' ).on( 'keyup.press-this', function() { var search = $( this ).val().toLowerCase() || ''; // Don't search when less thasn 3 extended ASCII chars if ( /[\x20-\xFF]+/.test( search ) && search.length < 2 ) { return; } $.each( catsCache, function( i, cat ) { cat.node.removeClass( 'is-hidden searched-parent' ); } ); if ( search ) { $.each( catsCache, function( i, cat ) { if ( cat.text.indexOf( search ) === -1 ) { cat.node.addClass( 'is-hidden' ); } else { cat.parents.addClass( 'searched-parent' ); } } ); } } ); $textEditor.on( 'focus.press-this input.press-this propertychange.press-this', textEditorResize ); return true; } function refreshCatsCache() { $( '.categories-select' ).find( 'li' ).each( function() { var $this = $( this ); catsCache.push( { node: $this, parents: $this.parents( 'li' ), text: $this.children( '.category' ).text().toLowerCase() } ); } ); } // Let's go! $document.ready( function() { render(); monitor(); refreshCatsCache(); }); // Expose public methods? return { renderNotice: renderNotice, renderError: renderError }; }; window.wp = window.wp || {}; window.wp.pressThis = new PressThis(); }( jQuery, window )); user-profile.min.js 0000666 00000014000 15213733063 0010302 0 ustar 00 !function(o){var a,t,n,i,l,r,d,p,c,u,h,f,v,w=!1;function m(){"function"==typeof zxcvbn?(n.val()?b():(n.val(n.data("pw")),n.trigger("pwupdate")),k(),1!==parseInt(c.data("start-masked"),10)?t.addClass("show-password"):c.trigger("click"),o("#pw-weak-text-label").html(userProfileL10n.warnWeak)):setTimeout(m,50)}function g(){c.data("toggle",0).attr({"aria-label":userProfileL10n.ariaHide}).find(".text").text(userProfileL10n.hide).end().find(".dashicons").removeClass("dashicons-visibility").addClass("dashicons-hidden"),i.focus(),l.attr("for","pass1-text")}function s(){var e,s;a=o(".user-pass1-wrap"),l=a.find("th label").attr("for","pass1-text"),o(".user-pass2-wrap").hide(),h=o("#submit").on("click",function(){w=!1}),u=h.add(" #createusersub"),d=o(".pw-weak"),(p=d.find(".pw-checkbox")).change(function(){u.prop("disabled",!p.prop("checked"))}),(n=o("#pass1")).length&&(f=n.val(),t=n.parent(),i=o('<input type="text"/>').attr({id:"pass1-text",name:"pass1-text",autocomplete:"off"}).addClass(n[0].className).data("pw",n.data("pw")).val(n.val()).on(v,function(){i.val()!==f&&(r.val(i.val()),n.val(i.val()).trigger("pwupdate"),f=i.val())}),n.after(i),1===parseInt(n.data("reveal"),10)&&m(),n.on(v+" pwupdate",function(){n.val()!==f&&(f=n.val(),i.val()!==f&&i.val(f),n.add(i).removeClass("short bad good strong"),k())})),r=o("#pass2").on(v,function(){0<r.val().length&&(n.val(r.val()),r.val(""),f="",n.trigger("pwupdate"))}),n.is(":hidden")&&(n.prop("disabled",!0),r.prop("disabled",!0),i.prop("disabled",!0)),e=a.find(".wp-pwd"),s=a.find("button.wp-generate-pw"),(c=a.find(".wp-hide-pw")).show().on("click",function(){1===parseInt(c.data("toggle"),10)?(t.addClass("show-password"),g(),_.isUndefined(i[0].setSelectionRange)||i[0].setSelectionRange(0,100)):(t.removeClass("show-password"),c.data("toggle",1).attr({"aria-label":userProfileL10n.ariaShow}).find(".text").text(userProfileL10n.show).end().find(".dashicons").removeClass("dashicons-hidden").addClass("dashicons-visibility"),n.focus(),l.attr("for","pass1"),_.isUndefined(n[0].setSelectionRange)||n[0].setSelectionRange(0,100))}),s.length&&e.hide(),s.show(),s.on("click",function(){w=!0,s.hide(),e.show(),n.attr("disabled",!1),r.attr("disabled",!1),i.attr("disabled",!1),0===i.val().length&&m(),_.defer(function(){i.focus(),_.isUndefined(i[0].setSelectionRange)||i[0].setSelectionRange(0,100)},0)}),a.find("button.wp-cancel-pw").on("click",function(){w=!1,i.val(""),wp.ajax.post("generate-password").done(function(e){n.data("pw",e)}),s.show(),e.hide(),d.hide(0,function(){p.removeProp("checked")}),n.prop("disabled",!0),r.prop("disabled",!0),i.prop("disabled",!0),g(),a.closest("form").is("#your-profile")&&(n.val("").trigger("pwupdate"),u.prop("disabled",!1))}),a.closest("form").on("submit",function(){w=!1,n.prop("disabled",!1),r.prop("disabled",!1),r.val(n.val()),t.removeClass("show-password")})}function b(){var e=o("#pass1").val();if(o("#pass-strength-result").removeClass("short bad good strong"),e)switch(wp.passwordStrength.meter(e,wp.passwordStrength.userInputBlacklist(),e)){case-1:o("#pass-strength-result").addClass("bad").html(pwsL10n.unknown);break;case 2:o("#pass-strength-result").addClass("bad").html(pwsL10n.bad);break;case 3:o("#pass-strength-result").addClass("good").html(pwsL10n.good);break;case 4:o("#pass-strength-result").addClass("strong").html(pwsL10n.strong);break;case 5:o("#pass-strength-result").addClass("short").html(pwsL10n.mismatch);break;default:o("#pass-strength-result").addClass("short").html(pwsL10n["short"])}else o("#pass-strength-result").html(" ")}function k(){var e=o("#pass-strength-result")[0];e.className&&(n.add(i).addClass(e.className),"short"===e.className||"bad"===e.className?(p.prop("checked")||u.prop("disabled",!0),d.show()):(u.prop("disabled",!1),d.hide()))}v="oninput"in document.createElement("input")?"input":"keyup",o(document).ready(function(){var e,a,t,n,i=o("#display_name");o("#pass1").val("").on(v+" pwupdate",b),o("#pass-strength-result").show(),o(".color-palette").click(function(){o(this).siblings('input[name="admin_color"]').prop("checked",!0)}),i.length&&o("#first_name, #last_name, #nickname").bind("blur.user_profile",function(){var a=[],t={display_nickname:o("#nickname").val()||"",display_username:o("#user_login").val()||"",display_firstname:o("#first_name").val()||"",display_lastname:o("#last_name").val()||""};t.display_firstname&&t.display_lastname&&(t.display_firstlast=t.display_firstname+" "+t.display_lastname,t.display_lastfirst=t.display_lastname+" "+t.display_firstname),o.each(o("option",i),function(e,s){a.push(s.value)}),o.each(t,function(e,s){s&&(s=s.replace(/<\/?[a-z][^>]*>/gi,""),t[e].length&&-1===o.inArray(s,a)&&(a.push(s),o("<option />",{text:s}).appendTo(i)))})}),e=o("#color-picker"),a=o("#colors-css"),t=o("input#user_id").val(),n=o('input[name="checkuser_id"]').val(),e.on("click.colorpicker",".color-option",function(){var e,s=o(this);if(!s.hasClass("selected")&&(s.siblings(".selected").removeClass("selected"),s.addClass("selected").find('input[type="radio"]').prop("checked",!0),t===n)){if((a=0===a.length?o('<link rel="stylesheet" />').appendTo("head"):a).attr("href",s.children(".css_url").val()),"undefined"!=typeof wp&&wp.svgPainter){try{e=o.parseJSON(s.children(".icon_colors").val())}catch(e){}e&&(wp.svgPainter.setColors(e),wp.svgPainter.paint())}o.post(ajaxurl,{action:"save-user-color-scheme",color_scheme:s.children('input[name="admin_color"]').val(),nonce:o("#color-nonce").val()}).done(function(e){e.success&&o("body").removeClass(e.data.previousScheme).addClass(e.data.currentScheme)})}}),s()}),o("#destroy-sessions").on("click",function(e){var s=o(this);wp.ajax.post("destroy-sessions",{nonce:o("#_wpnonce").val(),user_id:o("#user_id").val()}).done(function(e){s.prop("disabled",!0),s.siblings(".notice").remove(),s.before('<div class="notice notice-success inline"><p>'+e.message+"</p></div>")}).fail(function(e){s.siblings(".notice").remove(),s.before('<div class="notice notice-error inline"><p>'+e.message+"</p></div>")}),e.preventDefault()}),window.generatePassword=m,o(window).on("beforeunload",function(){if(!0===w)return userProfileL10n.warn})}(jQuery);word-count.min.js 0000666 00000002734 15213733063 0010002 0 ustar 00 !function(){function e(e){var t,s;if(e)for(t in e)e.hasOwnProperty(t)&&(this.settings[t]=e[t]);(s=this.settings.l10n.shortcodes)&&s.length&&(this.settings.shortcodesRegExp=new RegExp("\\[\\/?(?:"+s.join("|")+")[^\\]]*?\\]","g"))}e.prototype.settings={HTMLRegExp:/<\/?[a-z][^>]*?>/gi,HTMLcommentRegExp:/<!--[\s\S]*?-->/g,spaceRegExp:/ | /gi,HTMLEntityRegExp:/&\S+?;/g,connectorRegExp:/--|\u2014/g,removeRegExp:new RegExp(["[","!-@[-`{-~","\x80-\xbf\xd7\xf7","\u2000-\u2bff","\u2e00-\u2e7f","]"].join(""),"g"),astralRegExp:/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,wordsRegExp:/\S\s+/g,characters_excluding_spacesRegExp:/\S/g,characters_including_spacesRegExp:/[^\f\n\r\t\v\u00AD\u2028\u2029]/g,l10n:window.wordCountL10n||{}},e.prototype.count=function(e,t){var s=0;return"characters_excluding_spaces"!==(t=t||this.settings.l10n.type)&&"characters_including_spaces"!==t&&(t="words"),e&&(e=(e=(e+="\n").replace(this.settings.HTMLRegExp,"\n")).replace(this.settings.HTMLcommentRegExp,""),e=(e=this.settings.shortcodesRegExp?e.replace(this.settings.shortcodesRegExp,"\n"):e).replace(this.settings.spaceRegExp," "),(e=(e="words"===t?(e=(e=e.replace(this.settings.HTMLEntityRegExp,"")).replace(this.settings.connectorRegExp," ")).replace(this.settings.removeRegExp,""):(e=e.replace(this.settings.HTMLEntityRegExp,"a")).replace(this.settings.astralRegExp,"a")).match(this.settings[t+"RegExp"]))&&(s=e.length)),s},window.wp=window.wp||{},window.wp.utils=window.wp.utils||{},window.wp.utils.WordCounter=e}(); tags-suggest.min.js 0000666 00000004055 15213733063 0010314 0 ustar 00 !function(u){var s,a;function l(e){return e.split(new RegExp(a+"\\s*"))}void 0!==window.tagsSuggestL10n&&void 0!==window.uiAutocompleteL10n&&(s=0,a=window.tagsSuggestL10n.tagDelimiter||",",u.fn.wpTagsSuggest=function(e){var i,o,n=u(this),r=(e=e||{}).taxonomy||n.attr("data-wp-taxonomy")||"post_tag";return delete e.taxonomy,e=u.extend({source:function(e,a){var t;o!==e.term?(t=l(e.term).pop(),u.get(window.ajaxurl,{action:"ajax-tag-search",tax:r,q:t}).always(function(){n.removeClass("ui-autocomplete-loading")}).done(function(e){var t,o=[];if(e){for(t in e=e.split("\n")){var n=++s;o.push({id:n,name:e[t]})}a(i=o)}else a(o)}),o=e.term):a(i)},focus:function(e,t){n.attr("aria-activedescendant","wp-tags-autocomplete-"+t.item.id),e.preventDefault()},select:function(e,t){var o=l(n.val());return o.pop(),o.push(t.item.name,""),n.val(o.join(a+" ")),u.ui.keyCode.TAB===e.keyCode?(window.wp.a11y.speak(window.tagsSuggestL10n.termSelected,"assertive"),e.preventDefault()):u.ui.keyCode.ENTER===e.keyCode&&(e.preventDefault(),e.stopPropagation()),!1},open:function(){n.attr("aria-expanded","true")},close:function(){n.attr("aria-expanded","false")},minLength:2,position:{my:"left top+2",at:"left bottom",collision:"none"},messages:{noResults:window.uiAutocompleteL10n.noResults,results:function(e){return 1<e?window.uiAutocompleteL10n.manyResults.replace("%d",e):window.uiAutocompleteL10n.oneResult}}},e),n.on("keydown",function(){n.removeAttr("aria-activedescendant")}).autocomplete(e).autocomplete("instance")._renderItem=function(e,t){return u('<li role="option" id="wp-tags-autocomplete-'+t.id+'">').text(t.name).appendTo(e)},n.attr({role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-owns":n.autocomplete("widget").attr("id")}).on("focus",function(){l(n.val()).pop()&&n.autocomplete("search")}).autocomplete("widget").addClass("wp-tags-autocomplete").attr("role","listbox").removeAttr("tabindex").on("menufocus",function(e,t){t.item.attr("aria-selected","true")}).on("menublur",function(){u(this).find('[aria-selected="true"]').removeAttr("aria-selected")}),this})}(jQuery); wp-fullscreen-stub.min.js 0000666 00000000506 15213733063 0011435 0 ustar 00 !function(){function i(){}window.wp=window.wp||{},window.wp.editor=window.wp.editor||{},window.wp.editor.fullscreen={bind_resize:i,dfwWidth:i,off:i,on:i,refreshButtons:i,resizeTextarea:i,save:i,switchmode:i,toggleUI:i,settings:{},pubsub:{publish:i,subscribe:i,unsubscribe:i,topics:{}},fade:{In:i,Out:i},ui:{fade:i,init:i}}}(); tags.min.js 0000666 00000002764 15213733063 0006642 0 ustar 00 jQuery(document).ready(function(r){r("#the-list").on("click",".delete-tag",function(){var t,e=r(this),a=e.parents("tr"),n=!0;return(n="undefined"!=showNotice?showNotice.warn():n)&&(t=e.attr("href").replace(/[^?]*\?/,"").replace(/action=delete/,"action=delete-tag"),r.post(ajaxurl,t,function(e){"1"==e?(r("#ajax-response").empty(),a.fadeOut("normal",function(){a.remove()}),r('select#parent option[value="'+t.match(/tag_ID=(\d+)/)[1]+'"]').remove(),r("a.tag-link-"+t.match(/tag_ID=(\d+)/)[1]).remove()):("-1"==e?r("#ajax-response").empty().append('<div class="error"><p>'+tagsl10n.noPerm+"</p></div>"):r("#ajax-response").empty().append('<div class="error"><p>'+tagsl10n.broken+"</p></div>"),a.children().css("backgroundColor",""))}),a.children().css("backgroundColor","#f33")),!1}),r("#submit").click(function(){var s=r(this).parents("form");return validateForm(s)&&r.post(ajaxurl,r("#addtag").serialize(),function(e){var t,a,n;if(r("#ajax-response").empty(),(t=wpAjax.parseAjaxResponse(e,"ajax-response"))&&!t.errors){if(0<(e=s.find("select#parent").val())&&0<r("#tag-"+e).length?r(".tags #tag-"+e).after(t.responses[0].supplemental.noparents):r(".tags").prepend(t.responses[0].supplemental.parents),r(".tags .no-items").remove(),s.find("select#parent")){for(e=t.responses[1].supplemental,a="",n=0;n<t.responses[1].position;n++)a+=" ";s.find("select#parent option:selected").after('<option value="'+e.term_id+'">'+a+e.name+"</option>")}r('input[type="text"]:visible, textarea:visible',s).val("")}}),!1})}); media-gallery.min.js 0000666 00000001102 15213733063 0010401 0 ustar 00 jQuery(function(o){o("body").bind("click.wp-gallery",function(a){var e,t,n=o(a.target);n.hasClass("wp-set-header")?((window.dialogArguments||opener||parent||top).location.href=n.data("location"),a.preventDefault()):n.hasClass("wp-set-background")&&(e=n.data("attachment-id"),t=o('input[name="attachments['+e+'][image-size]"]:checked').val(),n=o("#_wpnonce").val()&&"",jQuery.post(ajaxurl,{action:"set-background-image",attachment_id:e,_ajax_nonce:n,size:t},function(){var a=window.dialogArguments||opener||parent||top;a.tb_remove(),a.location.reload()}),a.preventDefault())})}); customize-controls.js 0000666 00000504253 15213733063 0011005 0 ustar 00 /* global _wpCustomizeHeader, _wpCustomizeBackground, _wpMediaViewsL10n, MediaElementPlayer */ (function( exports, $ ){ var Container, focus, normalizedTransitionendEventName, api = wp.customize; /** * A Customizer Setting. * * A setting is WordPress data (theme mod, option, menu, etc.) that the user can * draft changes to in the Customizer. * * @see PHP class WP_Customize_Setting. * * @class * @augments wp.customize.Value * @augments wp.customize.Class * * @param {object} id The Setting ID. * @param {object} value The initial value of the setting. * @param {object} options.previewer The Previewer instance to sync with. * @param {object} options.transport The transport to use for previewing. Supports 'refresh' and 'postMessage'. * @param {object} options.dirty */ api.Setting = api.Value.extend({ initialize: function( id, value, options ) { var setting = this; api.Value.prototype.initialize.call( setting, value, options ); setting.id = id; setting.transport = setting.transport || 'refresh'; setting._dirty = options.dirty || false; setting.notifications = new api.Values({ defaultConstructor: api.Notification }); // Whenever the setting's value changes, refresh the preview. setting.bind( setting.preview ); }, /** * Refresh the preview, respective of the setting's refresh policy. * * If the preview hasn't sent a keep-alive message and is likely * disconnected by having navigated to a non-allowed URL, then the * refresh transport will be forced when postMessage is the transport. * Note that postMessage does not throw an error when the recipient window * fails to match the origin window, so using try/catch around the * previewer.send() call to then fallback to refresh will not work. * * @since 3.4.0 * @access public * * @returns {void} */ preview: function() { var setting = this, transport; transport = setting.transport; if ( 'postMessage' === transport && ! api.state( 'previewerAlive' ).get() ) { transport = 'refresh'; } if ( 'postMessage' === transport ) { setting.previewer.send( 'setting', [ setting.id, setting() ] ); } else if ( 'refresh' === transport ) { setting.previewer.refresh(); } }, /** * Find controls associated with this setting. * * @since 4.6.0 * @returns {wp.customize.Control[]} Controls associated with setting. */ findControls: function() { var setting = this, controls = []; api.control.each( function( control ) { _.each( control.settings, function( controlSetting ) { if ( controlSetting.id === setting.id ) { controls.push( control ); } } ); } ); return controls; } }); /** * Current change count. * * @since 4.7.0 * @type {number} * @protected */ api._latestRevision = 0; /** * Last revision that was saved. * * @since 4.7.0 * @type {number} * @protected */ api._lastSavedRevision = 0; /** * Latest revisions associated with the updated setting. * * @since 4.7.0 * @type {object} * @protected */ api._latestSettingRevisions = {}; /* * Keep track of the revision associated with each updated setting so that * requestChangesetUpdate knows which dirty settings to include. Also, once * ready is triggered and all initial settings have been added, increment * revision for each newly-created initially-dirty setting so that it will * also be included in changeset update requests. */ api.bind( 'change', function incrementChangedSettingRevision( setting ) { api._latestRevision += 1; api._latestSettingRevisions[ setting.id ] = api._latestRevision; } ); api.bind( 'ready', function() { api.bind( 'add', function incrementCreatedSettingRevision( setting ) { if ( setting._dirty ) { api._latestRevision += 1; api._latestSettingRevisions[ setting.id ] = api._latestRevision; } } ); } ); /** * Get the dirty setting values. * * @since 4.7.0 * @access public * * @param {object} [options] Options. * @param {boolean} [options.unsaved=false] Whether only values not saved yet into a changeset will be returned (differential changes). * @returns {object} Dirty setting values. */ api.dirtyValues = function dirtyValues( options ) { var values = {}; api.each( function( setting ) { var settingRevision; if ( ! setting._dirty ) { return; } settingRevision = api._latestSettingRevisions[ setting.id ]; // Skip including settings that have already been included in the changeset, if only requesting unsaved. if ( api.state( 'changesetStatus' ).get() && ( options && options.unsaved ) && ( _.isUndefined( settingRevision ) || settingRevision <= api._lastSavedRevision ) ) { return; } values[ setting.id ] = setting.get(); } ); return values; }; /** * Request updates to the changeset. * * @since 4.7.0 * @access public * * @param {object} [changes] Mapping of setting IDs to setting params each normally including a value property, or mapping to null. * If not provided, then the changes will still be obtained from unsaved dirty settings. * @returns {jQuery.Promise} Promise resolving with the response data. */ api.requestChangesetUpdate = function requestChangesetUpdate( changes ) { var deferred, request, submittedChanges = {}, data; deferred = new $.Deferred(); if ( changes ) { _.extend( submittedChanges, changes ); } // Ensure all revised settings (changes pending save) are also included, but not if marked for deletion in changes. _.each( api.dirtyValues( { unsaved: true } ), function( dirtyValue, settingId ) { if ( ! changes || null !== changes[ settingId ] ) { submittedChanges[ settingId ] = _.extend( {}, submittedChanges[ settingId ] || {}, { value: dirtyValue } ); } } ); // Short-circuit when there are no pending changes. if ( _.isEmpty( submittedChanges ) ) { deferred.resolve( {} ); return deferred.promise(); } // Make sure that publishing a changeset waits for all changeset update requests to complete. api.state( 'processing' ).set( api.state( 'processing' ).get() + 1 ); deferred.always( function() { api.state( 'processing' ).set( api.state( 'processing' ).get() - 1 ); } ); // Allow plugins to attach additional params to the settings. api.trigger( 'changeset-save', submittedChanges ); // Ensure that if any plugins add data to save requests by extending query() that they get included here. data = api.previewer.query( { excludeCustomizedSaved: true } ); delete data.customized; // Being sent in customize_changeset_data instead. _.extend( data, { nonce: api.settings.nonce.save, customize_theme: api.settings.theme.stylesheet, customize_changeset_data: JSON.stringify( submittedChanges ) } ); request = wp.ajax.post( 'customize_save', data ); request.done( function requestChangesetUpdateDone( data ) { var savedChangesetValues = {}; // Ensure that all settings updated subsequently will be included in the next changeset update request. api._lastSavedRevision = Math.max( api._latestRevision, api._lastSavedRevision ); api.state( 'changesetStatus' ).set( data.changeset_status ); deferred.resolve( data ); api.trigger( 'changeset-saved', data ); if ( data.setting_validities ) { _.each( data.setting_validities, function( validity, settingId ) { if ( true === validity && _.isObject( submittedChanges[ settingId ] ) && ! _.isUndefined( submittedChanges[ settingId ].value ) ) { savedChangesetValues[ settingId ] = submittedChanges[ settingId ].value; } } ); } api.previewer.send( 'changeset-saved', _.extend( {}, data, { saved_changeset_values: savedChangesetValues } ) ); } ); request.fail( function requestChangesetUpdateFail( data ) { deferred.reject( data ); api.trigger( 'changeset-error', data ); } ); request.always( function( data ) { if ( data.setting_validities ) { api._handleSettingValidities( { settingValidities: data.setting_validities } ); } } ); return deferred.promise(); }; /** * Watch all changes to Value properties, and bubble changes to parent Values instance * * @since 4.1.0 * * @param {wp.customize.Class} instance * @param {Array} properties The names of the Value instances to watch. */ api.utils.bubbleChildValueChanges = function ( instance, properties ) { $.each( properties, function ( i, key ) { instance[ key ].bind( function ( to, from ) { if ( instance.parent && to !== from ) { instance.parent.trigger( 'change', instance ); } } ); } ); }; /** * Expand a panel, section, or control and focus on the first focusable element. * * @since 4.1.0 * * @param {Object} [params] * @param {Function} [params.completeCallback] */ focus = function ( params ) { var construct, completeCallback, focus, focusElement; construct = this; params = params || {}; focus = function () { var focusContainer; if ( ( construct.extended( api.Panel ) || construct.extended( api.Section ) ) && construct.expanded && construct.expanded() ) { focusContainer = construct.contentContainer; } else { focusContainer = construct.container; } focusElement = focusContainer.find( '.control-focus:first' ); if ( 0 === focusElement.length ) { // Note that we can't use :focusable due to a jQuery UI issue. See: https://github.com/jquery/jquery-ui/pull/1583 focusElement = focusContainer.find( 'input, select, textarea, button, object, a[href], [tabindex]' ).filter( ':visible' ).first(); } focusElement.focus(); }; if ( params.completeCallback ) { completeCallback = params.completeCallback; params.completeCallback = function () { focus(); completeCallback(); }; } else { params.completeCallback = focus; } api.state( 'paneVisible' ).set( true ); if ( construct.expand ) { construct.expand( params ); } else { params.completeCallback(); } }; /** * Stable sort for Panels, Sections, and Controls. * * If a.priority() === b.priority(), then sort by their respective params.instanceNumber. * * @since 4.1.0 * * @param {(wp.customize.Panel|wp.customize.Section|wp.customize.Control)} a * @param {(wp.customize.Panel|wp.customize.Section|wp.customize.Control)} b * @returns {Number} */ api.utils.prioritySort = function ( a, b ) { if ( a.priority() === b.priority() && typeof a.params.instanceNumber === 'number' && typeof b.params.instanceNumber === 'number' ) { return a.params.instanceNumber - b.params.instanceNumber; } else { return a.priority() - b.priority(); } }; /** * Return whether the supplied Event object is for a keydown event but not the Enter key. * * @since 4.1.0 * * @param {jQuery.Event} event * @returns {boolean} */ api.utils.isKeydownButNotEnterEvent = function ( event ) { return ( 'keydown' === event.type && 13 !== event.which ); }; /** * Return whether the two lists of elements are the same and are in the same order. * * @since 4.1.0 * * @param {Array|jQuery} listA * @param {Array|jQuery} listB * @returns {boolean} */ api.utils.areElementListsEqual = function ( listA, listB ) { var equal = ( listA.length === listB.length && // if lists are different lengths, then naturally they are not equal -1 === _.indexOf( _.map( // are there any false values in the list returned by map? _.zip( listA, listB ), // pair up each element between the two lists function ( pair ) { return $( pair[0] ).is( pair[1] ); // compare to see if each pair are equal } ), false ) // check for presence of false in map's return value ); return equal; }; /** * Return browser supported `transitionend` event name. * * @since 4.7.0 * * @returns {string|null} Normalized `transitionend` event name or null if CSS transitions are not supported. */ normalizedTransitionendEventName = (function () { var el, transitions, prop; el = document.createElement( 'div' ); transitions = { 'transition' : 'transitionend', 'OTransition' : 'oTransitionEnd', 'MozTransition' : 'transitionend', 'WebkitTransition': 'webkitTransitionEnd' }; prop = _.find( _.keys( transitions ), function( prop ) { return ! _.isUndefined( el.style[ prop ] ); } ); if ( prop ) { return transitions[ prop ]; } else { return null; } })(); /** * Base class for Panel and Section. * * @since 4.1.0 * * @class * @augments wp.customize.Class */ Container = api.Class.extend({ defaultActiveArguments: { duration: 'fast', completeCallback: $.noop }, defaultExpandedArguments: { duration: 'fast', completeCallback: $.noop }, containerType: 'container', defaults: { title: '', description: '', priority: 100, type: 'default', content: null, active: true, instanceNumber: null }, /** * @since 4.1.0 * * @param {string} id - The ID for the container. * @param {object} options - Object containing one property: params. * @param {object} options.params - Object containing the following properties. * @param {string} options.params.title - Title shown when panel is collapsed and expanded. * @param {string=} [options.params.description] - Description shown at the top of the panel. * @param {number=100} [options.params.priority] - The sort priority for the panel. * @param {string=default} [options.params.type] - The type of the panel. See wp.customize.panelConstructor. * @param {string=} [options.params.content] - The markup to be used for the panel container. If empty, a JS template is used. * @param {boolean=true} [options.params.active] - Whether the panel is active or not. */ initialize: function ( id, options ) { var container = this; container.id = id; options = options || {}; options.params = _.defaults( options.params || {}, container.defaults ); $.extend( container, options ); container.templateSelector = 'customize-' + container.containerType + '-' + container.params.type; container.container = $( container.params.content ); if ( 0 === container.container.length ) { container.container = $( container.getContainer() ); } container.headContainer = container.container; container.contentContainer = container.getContent(); container.container = container.container.add( container.contentContainer ); container.deferred = { embedded: new $.Deferred() }; container.priority = new api.Value(); container.active = new api.Value(); container.activeArgumentsQueue = []; container.expanded = new api.Value(); container.expandedArgumentsQueue = []; container.active.bind( function ( active ) { var args = container.activeArgumentsQueue.shift(); args = $.extend( {}, container.defaultActiveArguments, args ); active = ( active && container.isContextuallyActive() ); container.onChangeActive( active, args ); }); container.expanded.bind( function ( expanded ) { var args = container.expandedArgumentsQueue.shift(); args = $.extend( {}, container.defaultExpandedArguments, args ); container.onChangeExpanded( expanded, args ); }); container.deferred.embedded.done( function () { container.attachEvents(); }); api.utils.bubbleChildValueChanges( container, [ 'priority', 'active' ] ); container.priority.set( container.params.priority ); container.active.set( container.params.active ); container.expanded.set( false ); }, /** * @since 4.1.0 * * @abstract */ ready: function() {}, /** * Get the child models associated with this parent, sorting them by their priority Value. * * @since 4.1.0 * * @param {String} parentType * @param {String} childType * @returns {Array} */ _children: function ( parentType, childType ) { var parent = this, children = []; api[ childType ].each( function ( child ) { if ( child[ parentType ].get() === parent.id ) { children.push( child ); } } ); children.sort( api.utils.prioritySort ); return children; }, /** * To override by subclass, to return whether the container has active children. * * @since 4.1.0 * * @abstract */ isContextuallyActive: function () { throw new Error( 'Container.isContextuallyActive() must be overridden in a subclass.' ); }, /** * Active state change handler. * * Shows the container if it is active, hides it if not. * * To override by subclass, update the container's UI to reflect the provided active state. * * @since 4.1.0 * * @param {boolean} active - The active state to transiution to. * @param {Object} [args] - Args. * @param {Object} [args.duration] - The duration for the slideUp/slideDown animation. * @param {boolean} [args.unchanged] - Whether the state is already known to not be changed, and so short-circuit with calling completeCallback early. * @param {Function} [args.completeCallback] - Function to call when the slideUp/slideDown has completed. */ onChangeActive: function( active, args ) { var construct = this, headContainer = construct.headContainer, duration, expandedOtherPanel; if ( args.unchanged ) { if ( args.completeCallback ) { args.completeCallback(); } return; } duration = ( 'resolved' === api.previewer.deferred.active.state() ? args.duration : 0 ); if ( construct.extended( api.Panel ) ) { // If this is a panel is not currently expanded but another panel is expanded, do not animate. api.panel.each(function ( panel ) { if ( panel !== construct && panel.expanded() ) { expandedOtherPanel = panel; duration = 0; } }); // Collapse any expanded sections inside of this panel first before deactivating. if ( ! active ) { _.each( construct.sections(), function( section ) { section.collapse( { duration: 0 } ); } ); } } if ( ! $.contains( document, headContainer.get( 0 ) ) ) { // If the element is not in the DOM, then jQuery.fn.slideUp() does nothing. In this case, a hard toggle is required instead. headContainer.toggle( active ); if ( args.completeCallback ) { args.completeCallback(); } } else if ( active ) { headContainer.slideDown( duration, args.completeCallback ); } else { if ( construct.expanded() ) { construct.collapse({ duration: duration, completeCallback: function() { headContainer.slideUp( duration, args.completeCallback ); } }); } else { headContainer.slideUp( duration, args.completeCallback ); } } }, /** * @since 4.1.0 * * @params {Boolean} active * @param {Object} [params] * @returns {Boolean} false if state already applied */ _toggleActive: function ( active, params ) { var self = this; params = params || {}; if ( ( active && this.active.get() ) || ( ! active && ! this.active.get() ) ) { params.unchanged = true; self.onChangeActive( self.active.get(), params ); return false; } else { params.unchanged = false; this.activeArgumentsQueue.push( params ); this.active.set( active ); return true; } }, /** * @param {Object} [params] * @returns {Boolean} false if already active */ activate: function ( params ) { return this._toggleActive( true, params ); }, /** * @param {Object} [params] * @returns {Boolean} false if already inactive */ deactivate: function ( params ) { return this._toggleActive( false, params ); }, /** * To override by subclass, update the container's UI to reflect the provided active state. * @abstract */ onChangeExpanded: function () { throw new Error( 'Must override with subclass.' ); }, /** * Handle the toggle logic for expand/collapse. * * @param {Boolean} expanded - The new state to apply. * @param {Object} [params] - Object containing options for expand/collapse. * @param {Function} [params.completeCallback] - Function to call when expansion/collapse is complete. * @returns {Boolean} false if state already applied or active state is false */ _toggleExpanded: function( expanded, params ) { var instance = this, previousCompleteCallback; params = params || {}; previousCompleteCallback = params.completeCallback; // Short-circuit expand() if the instance is not active. if ( expanded && ! instance.active() ) { return false; } api.state( 'paneVisible' ).set( true ); params.completeCallback = function() { if ( previousCompleteCallback ) { previousCompleteCallback.apply( instance, arguments ); } if ( expanded ) { instance.container.trigger( 'expanded' ); } else { instance.container.trigger( 'collapsed' ); } }; if ( ( expanded && instance.expanded.get() ) || ( ! expanded && ! instance.expanded.get() ) ) { params.unchanged = true; instance.onChangeExpanded( instance.expanded.get(), params ); return false; } else { params.unchanged = false; instance.expandedArgumentsQueue.push( params ); instance.expanded.set( expanded ); return true; } }, /** * @param {Object} [params] * @returns {Boolean} false if already expanded or if inactive. */ expand: function ( params ) { return this._toggleExpanded( true, params ); }, /** * @param {Object} [params] * @returns {Boolean} false if already collapsed. */ collapse: function ( params ) { return this._toggleExpanded( false, params ); }, /** * Animate container state change if transitions are supported by the browser. * * @since 4.7.0 * @private * * @param {function} completeCallback Function to be called after transition is completed. * @returns {void} */ _animateChangeExpanded: function( completeCallback ) { // Return if CSS transitions are not supported. if ( ! normalizedTransitionendEventName ) { if ( completeCallback ) { completeCallback(); } return; } var construct = this, content = construct.contentContainer, overlay = content.closest( '.wp-full-overlay' ), elements, transitionEndCallback, transitionParentPane; // Determine set of elements that are affected by the animation. elements = overlay.add( content ); if ( ! construct.panel || '' === construct.panel() ) { transitionParentPane = true; } else if ( api.panel( construct.panel() ).contentContainer.hasClass( 'skip-transition' ) ) { transitionParentPane = true; } else { transitionParentPane = false; } if ( transitionParentPane ) { elements = elements.add( '#customize-info, .customize-pane-parent' ); } // Handle `transitionEnd` event. transitionEndCallback = function( e ) { if ( 2 !== e.eventPhase || ! $( e.target ).is( content ) ) { return; } content.off( normalizedTransitionendEventName, transitionEndCallback ); elements.removeClass( 'busy' ); if ( completeCallback ) { completeCallback(); } }; content.on( normalizedTransitionendEventName, transitionEndCallback ); elements.addClass( 'busy' ); // Prevent screen flicker when pane has been scrolled before expanding. _.defer( function() { var container = content.closest( '.wp-full-overlay-sidebar-content' ), currentScrollTop = container.scrollTop(), previousScrollTop = content.data( 'previous-scrollTop' ) || 0, expanded = construct.expanded(); if ( expanded && 0 < currentScrollTop ) { content.css( 'top', currentScrollTop + 'px' ); content.data( 'previous-scrollTop', currentScrollTop ); } else if ( ! expanded && 0 < currentScrollTop + previousScrollTop ) { content.css( 'top', previousScrollTop - currentScrollTop + 'px' ); container.scrollTop( previousScrollTop ); } } ); }, /** * Bring the container into view and then expand this and bring it into view * @param {Object} [params] */ focus: focus, /** * Return the container html, generated from its JS template, if it exists. * * @since 4.3.0 */ getContainer: function () { var template, container = this; if ( 0 !== $( '#tmpl-' + container.templateSelector ).length ) { template = wp.template( container.templateSelector ); } else { template = wp.template( 'customize-' + container.containerType + '-default' ); } if ( template && container.container ) { return $.trim( template( container.params ) ); } return '<li></li>'; }, /** * Find content element which is displayed when the section is expanded. * * After a construct is initialized, the return value will be available via the `contentContainer` property. * By default the element will be related it to the parent container with `aria-owns` and detached. * Custom panels and sections (such as the `NewMenuSection`) that do not have a sliding pane should * just return the content element without needing to add the `aria-owns` element or detach it from * the container. Such non-sliding pane custom sections also need to override the `onChangeExpanded` * method to handle animating the panel/section into and out of view. * * @since 4.7.0 * @access public * * @returns {jQuery} Detached content element. */ getContent: function() { var construct = this, container = construct.container, content = container.find( '.accordion-section-content, .control-panel-content' ).first(), contentId = 'sub-' + container.attr( 'id' ), ownedElements = contentId, alreadyOwnedElements = container.attr( 'aria-owns' ); if ( alreadyOwnedElements ) { ownedElements = ownedElements + ' ' + alreadyOwnedElements; } container.attr( 'aria-owns', ownedElements ); return content.detach().attr( { 'id': contentId, 'class': 'customize-pane-child ' + content.attr( 'class' ) + ' ' + container.attr( 'class' ) } ); } }); /** * @since 4.1.0 * * @class * @augments wp.customize.Class */ api.Section = Container.extend({ containerType: 'section', defaults: { title: '', description: '', priority: 100, type: 'default', content: null, active: true, instanceNumber: null, panel: null, customizeAction: '' }, /** * @since 4.1.0 * * @param {string} id - The ID for the section. * @param {object} options - Object containing one property: params. * @param {object} options.params - Object containing the following properties. * @param {string} options.params.title - Title shown when section is collapsed and expanded. * @param {string=} [options.params.description] - Description shown at the top of the section. * @param {number=100} [options.params.priority] - The sort priority for the section. * @param {string=default} [options.params.type] - The type of the section. See wp.customize.sectionConstructor. * @param {string=} [options.params.content] - The markup to be used for the section container. If empty, a JS template is used. * @param {boolean=true} [options.params.active] - Whether the section is active or not. * @param {string} options.params.panel - The ID for the panel this section is associated with. * @param {string=} [options.params.customizeAction] - Additional context information shown before the section title when expanded. */ initialize: function ( id, options ) { var section = this; Container.prototype.initialize.call( section, id, options ); section.id = id; section.panel = new api.Value(); section.panel.bind( function ( id ) { $( section.headContainer ).toggleClass( 'control-subsection', !! id ); }); section.panel.set( section.params.panel || '' ); api.utils.bubbleChildValueChanges( section, [ 'panel' ] ); section.embed(); section.deferred.embedded.done( function () { section.ready(); }); }, /** * Embed the container in the DOM when any parent panel is ready. * * @since 4.1.0 */ embed: function () { var inject, section = this, container = $( '#customize-theme-controls' ); // Watch for changes to the panel state inject = function ( panelId ) { var parentContainer; if ( panelId ) { // The panel has been supplied, so wait until the panel object is registered api.panel( panelId, function ( panel ) { // The panel has been registered, wait for it to become ready/initialized panel.deferred.embedded.done( function () { parentContainer = panel.contentContainer; if ( ! section.headContainer.parent().is( parentContainer ) ) { parentContainer.append( section.headContainer ); } if ( ! section.contentContainer.parent().is( section.headContainer ) ) { container.append( section.contentContainer ); } section.deferred.embedded.resolve(); }); } ); } else { // There is no panel, so embed the section in the root of the customizer parentContainer = $( '.customize-pane-parent' ); // @todo This should be defined elsewhere, and to be configurable if ( ! section.headContainer.parent().is( parentContainer ) ) { parentContainer.append( section.headContainer ); } if ( ! section.contentContainer.parent().is( section.headContainer ) ) { container.append( section.contentContainer ); } section.deferred.embedded.resolve(); } }; section.panel.bind( inject ); inject( section.panel.get() ); // Since a section may never get a panel, assume that it won't ever get one }, /** * Add behaviors for the accordion section. * * @since 4.1.0 */ attachEvents: function () { var meta, content, section = this; if ( section.container.hasClass( 'cannot-expand' ) ) { return; } // Expand/Collapse accordion sections on click. section.container.find( '.accordion-section-title, .customize-section-back' ).on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above if ( section.expanded() ) { section.collapse(); } else { section.expand(); } }); // This is very similar to what is found for api.Panel.attachEvents(). section.container.find( '.customize-section-title .customize-help-toggle' ).on( 'click', function() { meta = section.container.find( '.section-meta' ); if ( meta.hasClass( 'cannot-expand' ) ) { return; } content = meta.find( '.customize-section-description:first' ); content.toggleClass( 'open' ); content.slideToggle(); content.attr( 'aria-expanded', function ( i, attr ) { return 'true' === attr ? 'false' : 'true'; }); }); }, /** * Return whether this section has any active controls. * * @since 4.1.0 * * @returns {Boolean} */ isContextuallyActive: function () { var section = this, controls = section.controls(), activeCount = 0; _( controls ).each( function ( control ) { if ( control.active() ) { activeCount += 1; } } ); return ( activeCount !== 0 ); }, /** * Get the controls that are associated with this section, sorted by their priority Value. * * @since 4.1.0 * * @returns {Array} */ controls: function () { return this._children( 'section', 'control' ); }, /** * Update UI to reflect expanded state. * * @since 4.1.0 * * @param {Boolean} expanded * @param {Object} args */ onChangeExpanded: function ( expanded, args ) { var section = this, container = section.headContainer.closest( '.wp-full-overlay-sidebar-content' ), content = section.contentContainer, overlay = section.headContainer.closest( '.wp-full-overlay' ), backBtn = content.find( '.customize-section-back' ), sectionTitle = section.headContainer.find( '.accordion-section-title' ).first(), expand, panel; if ( expanded && ! content.hasClass( 'open' ) ) { if ( args.unchanged ) { expand = args.completeCallback; } else { expand = $.proxy( function() { section._animateChangeExpanded( function() { sectionTitle.attr( 'tabindex', '-1' ); backBtn.attr( 'tabindex', '0' ); backBtn.focus(); content.css( 'top', '' ); container.scrollTop( 0 ); if ( args.completeCallback ) { args.completeCallback(); } } ); content.addClass( 'open' ); overlay.addClass( 'section-open' ); api.state( 'expandedSection' ).set( section ); }, this ); } if ( ! args.allowMultiple ) { api.section.each( function ( otherSection ) { if ( otherSection !== section ) { otherSection.collapse( { duration: args.duration } ); } }); } if ( section.panel() ) { api.panel( section.panel() ).expand({ duration: args.duration, completeCallback: expand }); } else { api.panel.each( function( panel ) { panel.collapse(); }); expand(); } } else if ( ! expanded && content.hasClass( 'open' ) ) { if ( section.panel() ) { panel = api.panel( section.panel() ); if ( panel.contentContainer.hasClass( 'skip-transition' ) ) { panel.collapse(); } } section._animateChangeExpanded( function() { backBtn.attr( 'tabindex', '-1' ); sectionTitle.attr( 'tabindex', '0' ); sectionTitle.focus(); content.css( 'top', '' ); if ( args.completeCallback ) { args.completeCallback(); } } ); content.removeClass( 'open' ); overlay.removeClass( 'section-open' ); if ( section === api.state( 'expandedSection' ).get() ) { api.state( 'expandedSection' ).set( false ); } } else { if ( args.completeCallback ) { args.completeCallback(); } } } }); /** * wp.customize.ThemesSection * * Custom section for themes that functions similarly to a backwards panel, * and also handles the theme-details view rendering and navigation. * * @constructor * @augments wp.customize.Section * @augments wp.customize.Container */ api.ThemesSection = api.Section.extend({ currentTheme: '', overlay: '', template: '', screenshotQueue: null, $window: $( window ), /** * @since 4.2.0 */ initialize: function () { this.$customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' ); return api.Section.prototype.initialize.apply( this, arguments ); }, /** * @since 4.2.0 */ ready: function () { var section = this; section.overlay = section.container.find( '.theme-overlay' ); section.template = wp.template( 'customize-themes-details-view' ); // Bind global keyboard events. section.container.on( 'keydown', function( event ) { if ( ! section.overlay.find( '.theme-wrap' ).is( ':visible' ) ) { return; } // Pressing the right arrow key fires a theme:next event if ( 39 === event.keyCode ) { section.nextTheme(); } // Pressing the left arrow key fires a theme:previous event if ( 37 === event.keyCode ) { section.previousTheme(); } // Pressing the escape key fires a theme:collapse event if ( 27 === event.keyCode ) { section.closeDetails(); event.stopPropagation(); // Prevent section from being collapsed. } }); _.bindAll( this, 'renderScreenshots' ); }, /** * Override Section.isContextuallyActive method. * * Ignore the active states' of the contained theme controls, and just * use the section's own active state instead. This ensures empty search * results for themes to cause the section to become inactive. * * @since 4.2.0 * * @returns {Boolean} */ isContextuallyActive: function () { return this.active(); }, /** * @since 4.2.0 */ attachEvents: function () { var section = this; // Expand/Collapse section/panel. section.container.find( '.change-theme, .customize-theme' ).on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above if ( section.expanded() ) { section.collapse(); } else { section.expand(); } }); // Theme navigation in details view. section.container.on( 'click keydown', '.left', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above section.previousTheme(); }); section.container.on( 'click keydown', '.right', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above section.nextTheme(); }); section.container.on( 'click keydown', '.theme-backdrop, .close', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above section.closeDetails(); }); var renderScreenshots = _.throttle( _.bind( section.renderScreenshots, this ), 100 ); section.container.on( 'input', '#themes-filter', function( event ) { var count, term = event.currentTarget.value.toLowerCase().trim().replace( '-', ' ' ), controls = section.controls(); _.each( controls, function( control ) { control.filter( term ); }); renderScreenshots(); // Update theme count. count = section.container.find( 'li.customize-control:visible' ).length; section.container.find( '.theme-count' ).text( count ); }); // Pre-load the first 3 theme screenshots. api.bind( 'ready', function () { _.each( section.controls().slice( 0, 3 ), function ( control ) { var img, src = control.params.theme.screenshot[0]; if ( src ) { img = new Image(); img.src = src; } }); }); }, /** * Update UI to reflect expanded state * * @since 4.2.0 * * @param {Boolean} expanded * @param {Object} args * @param {Boolean} args.unchanged * @param {Callback} args.completeCallback */ onChangeExpanded: function ( expanded, args ) { // Immediately call the complete callback if there were no changes if ( args.unchanged ) { if ( args.completeCallback ) { args.completeCallback(); } return; } // Note: there is a second argument 'args' passed var panel = this, section = panel.contentContainer, overlay = section.closest( '.wp-full-overlay' ), container = section.closest( '.wp-full-overlay-sidebar-content' ), customizeBtn = section.find( '.customize-theme' ), changeBtn = panel.headContainer.find( '.change-theme' ); if ( expanded && ! section.hasClass( 'current-panel' ) ) { // Collapse any sibling sections/panels api.section.each( function ( otherSection ) { if ( otherSection !== panel ) { otherSection.collapse( { duration: args.duration } ); } }); api.panel.each( function ( otherPanel ) { otherPanel.collapse( { duration: 0 } ); }); panel._animateChangeExpanded( function() { changeBtn.attr( 'tabindex', '-1' ); customizeBtn.attr( 'tabindex', '0' ); customizeBtn.focus(); section.css( 'top', '' ); container.scrollTop( 0 ); if ( args.completeCallback ) { args.completeCallback(); } } ); overlay.addClass( 'in-themes-panel' ); section.addClass( 'current-panel' ); _.delay( panel.renderScreenshots, 10 ); // Wait for the controls panel.$customizeSidebar.on( 'scroll.customize-themes-section', _.throttle( panel.renderScreenshots, 300 ) ); } else if ( ! expanded && section.hasClass( 'current-panel' ) ) { panel._animateChangeExpanded( function() { changeBtn.attr( 'tabindex', '0' ); customizeBtn.attr( 'tabindex', '-1' ); changeBtn.focus(); section.css( 'top', '' ); if ( args.completeCallback ) { args.completeCallback(); } } ); overlay.removeClass( 'in-themes-panel' ); section.removeClass( 'current-panel' ); panel.$customizeSidebar.off( 'scroll.customize-themes-section' ); } }, /** * Render control's screenshot if the control comes into view. * * @since 4.2.0 */ renderScreenshots: function( ) { var section = this; // Fill queue initially. if ( section.screenshotQueue === null ) { section.screenshotQueue = section.controls(); } // Are all screenshots rendered? if ( ! section.screenshotQueue.length ) { return; } section.screenshotQueue = _.filter( section.screenshotQueue, function( control ) { var $imageWrapper = control.container.find( '.theme-screenshot' ), $image = $imageWrapper.find( 'img' ); if ( ! $image.length ) { return false; } if ( $image.is( ':hidden' ) ) { return true; } // Based on unveil.js. var wt = section.$window.scrollTop(), wb = wt + section.$window.height(), et = $image.offset().top, ih = $imageWrapper.height(), eb = et + ih, threshold = ih * 3, inView = eb >= wt - threshold && et <= wb + threshold; if ( inView ) { control.container.trigger( 'render-screenshot' ); } // If the image is in view return false so it's cleared from the queue. return ! inView; } ); }, /** * Advance the modal to the next theme. * * @since 4.2.0 */ nextTheme: function () { var section = this; if ( section.getNextTheme() ) { section.showDetails( section.getNextTheme(), function() { section.overlay.find( '.right' ).focus(); } ); } }, /** * Get the next theme model. * * @since 4.2.0 */ getNextTheme: function () { var control, next; control = api.control( 'theme_' + this.currentTheme ); next = control.container.next( 'li.customize-control-theme' ); if ( ! next.length ) { return false; } next = next[0].id.replace( 'customize-control-', '' ); control = api.control( next ); return control.params.theme; }, /** * Advance the modal to the previous theme. * * @since 4.2.0 */ previousTheme: function () { var section = this; if ( section.getPreviousTheme() ) { section.showDetails( section.getPreviousTheme(), function() { section.overlay.find( '.left' ).focus(); } ); } }, /** * Get the previous theme model. * * @since 4.2.0 */ getPreviousTheme: function () { var control, previous; control = api.control( 'theme_' + this.currentTheme ); previous = control.container.prev( 'li.customize-control-theme' ); if ( ! previous.length ) { return false; } previous = previous[0].id.replace( 'customize-control-', '' ); control = api.control( previous ); return control.params.theme; }, /** * Disable buttons when we're viewing the first or last theme. * * @since 4.2.0 */ updateLimits: function () { if ( ! this.getNextTheme() ) { this.overlay.find( '.right' ).addClass( 'disabled' ); } if ( ! this.getPreviousTheme() ) { this.overlay.find( '.left' ).addClass( 'disabled' ); } }, /** * Load theme preview. * * @since 4.7.0 * @access public * * @param {string} themeId Theme ID. * @returns {jQuery.promise} Promise. */ loadThemePreview: function( themeId ) { var deferred = $.Deferred(), onceProcessingComplete, overlay, urlParser; urlParser = document.createElement( 'a' ); urlParser.href = location.href; urlParser.search = $.param( _.extend( api.utils.parseQueryString( urlParser.search.substr( 1 ) ), { theme: themeId, changeset_uuid: api.settings.changeset.uuid } ) ); overlay = $( '.wp-full-overlay' ); overlay.addClass( 'customize-loading' ); onceProcessingComplete = function() { var request; if ( api.state( 'processing' ).get() > 0 ) { return; } api.state( 'processing' ).unbind( onceProcessingComplete ); request = api.requestChangesetUpdate(); request.done( function() { $( window ).off( 'beforeunload.customize-confirm' ); top.location.href = urlParser.href; deferred.resolve(); } ); request.fail( function() { overlay.removeClass( 'customize-loading' ); deferred.reject(); } ); }; if ( 0 === api.state( 'processing' ).get() ) { onceProcessingComplete(); } else { api.state( 'processing' ).bind( onceProcessingComplete ); } return deferred.promise(); }, /** * Render & show the theme details for a given theme model. * * @since 4.2.0 * * @param {Object} theme */ showDetails: function ( theme, callback ) { var section = this, link; callback = callback || function(){}; section.currentTheme = theme.id; section.overlay.html( section.template( theme ) ) .fadeIn( 'fast' ) .focus(); $( 'body' ).addClass( 'modal-open' ); section.containFocus( section.overlay ); section.updateLimits(); link = section.overlay.find( '.inactive-theme > a' ); link.on( 'click', function( event ) { event.preventDefault(); // Short-circuit if request is currently being made. if ( link.hasClass( 'disabled' ) ) { return; } link.addClass( 'disabled' ); section.loadThemePreview( theme.id ).fail( function() { link.removeClass( 'disabled' ); } ); } ); callback(); }, /** * Close the theme details modal. * * @since 4.2.0 */ closeDetails: function () { $( 'body' ).removeClass( 'modal-open' ); this.overlay.fadeOut( 'fast' ); api.control( 'theme_' + this.currentTheme ).focus(); }, /** * Keep tab focus within the theme details modal. * * @since 4.2.0 */ containFocus: function( el ) { var tabbables; el.on( 'keydown', function( event ) { // Return if it's not the tab key // When navigating with prev/next focus is already handled if ( 9 !== event.keyCode ) { return; } // uses jQuery UI to get the tabbable elements tabbables = $( ':tabbable', el ); // Keep focus within the overlay if ( tabbables.last()[0] === event.target && ! event.shiftKey ) { tabbables.first().focus(); return false; } else if ( tabbables.first()[0] === event.target && event.shiftKey ) { tabbables.last().focus(); return false; } }); } }); /** * @since 4.1.0 * * @class * @augments wp.customize.Class */ api.Panel = Container.extend({ containerType: 'panel', /** * @since 4.1.0 * * @param {string} id - The ID for the panel. * @param {object} options - Object containing one property: params. * @param {object} options.params - Object containing the following properties. * @param {string} options.params.title - Title shown when panel is collapsed and expanded. * @param {string=} [options.params.description] - Description shown at the top of the panel. * @param {number=100} [options.params.priority] - The sort priority for the panel. * @param {string=default} [options.params.type] - The type of the panel. See wp.customize.panelConstructor. * @param {string=} [options.params.content] - The markup to be used for the panel container. If empty, a JS template is used. * @param {boolean=true} [options.params.active] - Whether the panel is active or not. */ initialize: function ( id, options ) { var panel = this; Container.prototype.initialize.call( panel, id, options ); panel.embed(); panel.deferred.embedded.done( function () { panel.ready(); }); }, /** * Embed the container in the DOM when any parent panel is ready. * * @since 4.1.0 */ embed: function () { var panel = this, container = $( '#customize-theme-controls' ), parentContainer = $( '.customize-pane-parent' ); // @todo This should be defined elsewhere, and to be configurable if ( ! panel.headContainer.parent().is( parentContainer ) ) { parentContainer.append( panel.headContainer ); } if ( ! panel.contentContainer.parent().is( panel.headContainer ) ) { container.append( panel.contentContainer ); panel.renderContent(); } panel.deferred.embedded.resolve(); }, /** * @since 4.1.0 */ attachEvents: function () { var meta, panel = this; // Expand/Collapse accordion sections on click. panel.headContainer.find( '.accordion-section-title' ).on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above if ( ! panel.expanded() ) { panel.expand(); } }); // Close panel. panel.container.find( '.customize-panel-back' ).on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above if ( panel.expanded() ) { panel.collapse(); } }); meta = panel.container.find( '.panel-meta:first' ); meta.find( '> .accordion-section-title .customize-help-toggle' ).on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above if ( meta.hasClass( 'cannot-expand' ) ) { return; } var content = meta.find( '.customize-panel-description:first' ); if ( meta.hasClass( 'open' ) ) { meta.toggleClass( 'open' ); content.slideUp( panel.defaultExpandedArguments.duration ); $( this ).attr( 'aria-expanded', false ); } else { content.slideDown( panel.defaultExpandedArguments.duration ); meta.toggleClass( 'open' ); $( this ).attr( 'aria-expanded', true ); } }); }, /** * Get the sections that are associated with this panel, sorted by their priority Value. * * @since 4.1.0 * * @returns {Array} */ sections: function () { return this._children( 'panel', 'section' ); }, /** * Return whether this panel has any active sections. * * @since 4.1.0 * * @returns {boolean} */ isContextuallyActive: function () { var panel = this, sections = panel.sections(), activeCount = 0; _( sections ).each( function ( section ) { if ( section.active() && section.isContextuallyActive() ) { activeCount += 1; } } ); return ( activeCount !== 0 ); }, /** * Update UI to reflect expanded state * * @since 4.1.0 * * @param {Boolean} expanded * @param {Object} args * @param {Boolean} args.unchanged * @param {Function} args.completeCallback */ onChangeExpanded: function ( expanded, args ) { // Immediately call the complete callback if there were no changes if ( args.unchanged ) { if ( args.completeCallback ) { args.completeCallback(); } return; } // Note: there is a second argument 'args' passed var panel = this, accordionSection = panel.contentContainer, overlay = accordionSection.closest( '.wp-full-overlay' ), container = accordionSection.closest( '.wp-full-overlay-sidebar-content' ), topPanel = panel.headContainer.find( '.accordion-section-title' ), backBtn = accordionSection.find( '.customize-panel-back' ), childSections = panel.sections(), skipTransition; if ( expanded && ! accordionSection.hasClass( 'current-panel' ) ) { // Collapse any sibling sections/panels api.section.each( function ( section ) { if ( panel.id !== section.panel() ) { section.collapse( { duration: 0 } ); } }); api.panel.each( function ( otherPanel ) { if ( panel !== otherPanel ) { otherPanel.collapse( { duration: 0 } ); } }); if ( panel.params.autoExpandSoleSection && 1 === childSections.length && childSections[0].active.get() ) { accordionSection.addClass( 'current-panel skip-transition' ); overlay.addClass( 'in-sub-panel' ); childSections[0].expand( { completeCallback: args.completeCallback } ); } else { panel._animateChangeExpanded( function() { topPanel.attr( 'tabindex', '-1' ); backBtn.attr( 'tabindex', '0' ); backBtn.focus(); accordionSection.css( 'top', '' ); container.scrollTop( 0 ); if ( args.completeCallback ) { args.completeCallback(); } } ); accordionSection.addClass( 'current-panel' ); overlay.addClass( 'in-sub-panel' ); } api.state( 'expandedPanel' ).set( panel ); } else if ( ! expanded && accordionSection.hasClass( 'current-panel' ) ) { skipTransition = accordionSection.hasClass( 'skip-transition' ); if ( ! skipTransition ) { panel._animateChangeExpanded( function() { topPanel.attr( 'tabindex', '0' ); backBtn.attr( 'tabindex', '-1' ); topPanel.focus(); accordionSection.css( 'top', '' ); if ( args.completeCallback ) { args.completeCallback(); } } ); } else { accordionSection.removeClass( 'skip-transition' ); } overlay.removeClass( 'in-sub-panel' ); accordionSection.removeClass( 'current-panel' ); if ( panel === api.state( 'expandedPanel' ).get() ) { api.state( 'expandedPanel' ).set( false ); } } }, /** * Render the panel from its JS template, if it exists. * * The panel's container must already exist in the DOM. * * @since 4.3.0 */ renderContent: function () { var template, panel = this; // Add the content to the container. if ( 0 !== $( '#tmpl-' + panel.templateSelector + '-content' ).length ) { template = wp.template( panel.templateSelector + '-content' ); } else { template = wp.template( 'customize-panel-default-content' ); } if ( template && panel.headContainer ) { panel.contentContainer.html( template( panel.params ) ); } } }); /** * A Customizer Control. * * A control provides a UI element that allows a user to modify a Customizer Setting. * * @see PHP class WP_Customize_Control. * * @class * @augments wp.customize.Class * * @param {string} id Unique identifier for the control instance. * @param {object} options Options hash for the control instance. * @param {object} options.params * @param {object} options.params.type Type of control (e.g. text, radio, dropdown-pages, etc.) * @param {string} options.params.content The HTML content for the control. * @param {string} options.params.priority Order of priority to show the control within the section. * @param {string} options.params.active * @param {string} options.params.section The ID of the section the control belongs to. * @param {string} options.params.settings.default The ID of the setting the control relates to. * @param {string} options.params.settings.data * @param {string} options.params.label * @param {string} options.params.description * @param {string} options.params.instanceNumber Order in which this instance was created in relation to other instances. */ api.Control = api.Class.extend({ defaultActiveArguments: { duration: 'fast', completeCallback: $.noop }, initialize: function( id, options ) { var control = this, nodes, radios, settings; control.params = {}; $.extend( control, options || {} ); control.id = id; control.selector = '#customize-control-' + id.replace( /\]/g, '' ).replace( /\[/g, '-' ); control.templateSelector = 'customize-control-' + control.params.type + '-content'; control.container = control.params.content ? $( control.params.content ) : $( control.selector ); control.deferred = { embedded: new $.Deferred() }; control.section = new api.Value(); control.priority = new api.Value(); control.active = new api.Value(); control.activeArgumentsQueue = []; control.notifications = new api.Values({ defaultConstructor: api.Notification }); control.elements = []; nodes = control.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() ); }); }); control.active.bind( function ( active ) { var args = control.activeArgumentsQueue.shift(); args = $.extend( {}, control.defaultActiveArguments, args ); control.onChangeActive( active, args ); } ); control.section.set( control.params.section ); control.priority.set( isNaN( control.params.priority ) ? 10 : control.params.priority ); control.active.set( control.params.active ); api.utils.bubbleChildValueChanges( control, [ 'section', 'priority', 'active' ] ); /* * After all settings related to the control are available, * make them available on the control and embed the control into the page. */ settings = $.map( control.params.settings, function( value ) { return value; }); if ( 0 === settings.length ) { control.setting = null; control.settings = {}; control.embed(); } else { 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; // Add setting notifications to the control notification. _.each( control.settings, function( setting ) { setting.notifications.bind( 'add', function( settingNotification ) { var controlNotification, code, params; code = setting.id + ':' + settingNotification.code; params = _.extend( {}, settingNotification, { setting: setting.id } ); controlNotification = new api.Notification( code, params ); control.notifications.add( controlNotification.code, controlNotification ); } ); setting.notifications.bind( 'remove', function( settingNotification ) { control.notifications.remove( setting.id + ':' + settingNotification.code ); } ); } ); control.embed(); }) ); } // After the control is embedded on the page, invoke the "ready" method. control.deferred.embedded.done( function () { /* * Note that this debounced/deferred rendering is needed for two reasons: * 1) The 'remove' event is triggered just _before_ the notification is actually removed. * 2) Improve performance when adding/removing multiple notifications at a time. */ var debouncedRenderNotifications = _.debounce( function renderNotifications() { control.renderNotifications(); } ); control.notifications.bind( 'add', function( notification ) { wp.a11y.speak( notification.message, 'assertive' ); debouncedRenderNotifications(); } ); control.notifications.bind( 'remove', debouncedRenderNotifications ); control.renderNotifications(); control.ready(); }); }, /** * Embed the control into the page. */ embed: function () { var control = this, inject; // Watch for changes to the section state inject = function ( sectionId ) { var parentContainer; if ( ! sectionId ) { // @todo allow a control to be embedded without a section, for instance a control embedded in the front end. return; } // Wait for the section to be registered api.section( sectionId, function ( section ) { // Wait for the section to be ready/initialized section.deferred.embedded.done( function () { parentContainer = ( section.contentContainer.is( 'ul' ) ) ? section.contentContainer : section.contentContainer.find( 'ul:first' ); if ( ! control.container.parent().is( parentContainer ) ) { parentContainer.append( control.container ); control.renderContent(); } control.deferred.embedded.resolve(); }); }); }; control.section.bind( inject ); inject( control.section.get() ); }, /** * Triggered when the control's markup has been injected into the DOM. * * @returns {void} */ ready: function() { var control = this, newItem; if ( 'dropdown-pages' === control.params.type && control.params.allow_addition ) { newItem = control.container.find( '.new-content-item' ); newItem.hide(); // Hide in JS to preserve flex display when showing. control.container.on( 'click', '.add-new-toggle', function( e ) { $( e.currentTarget ).slideUp( 180 ); newItem.slideDown( 180 ); newItem.find( '.create-item-input' ).focus(); }); control.container.on( 'click', '.add-content', function() { control.addNewPage(); }); control.container.on( 'keyup', '.create-item-input', function( e ) { if ( 13 === e.which ) { // Enter control.addNewPage(); } }); } }, /** * Get the element inside of a control's container that contains the validation error message. * * Control subclasses may override this to return the proper container to render notifications into. * Injects the notification container for existing controls that lack the necessary container, * including special handling for nav menu items and widgets. * * @since 4.6.0 * @returns {jQuery} Setting validation message element. * @this {wp.customize.Control} */ getNotificationsContainerElement: function() { var control = this, controlTitle, notificationsContainer; notificationsContainer = control.container.find( '.customize-control-notifications-container:first' ); if ( notificationsContainer.length ) { return notificationsContainer; } notificationsContainer = $( '<div class="customize-control-notifications-container"></div>' ); if ( control.container.hasClass( 'customize-control-nav_menu_item' ) ) { control.container.find( '.menu-item-settings:first' ).prepend( notificationsContainer ); } else if ( control.container.hasClass( 'customize-control-widget_form' ) ) { control.container.find( '.widget-inside:first' ).prepend( notificationsContainer ); } else { controlTitle = control.container.find( '.customize-control-title' ); if ( controlTitle.length ) { controlTitle.after( notificationsContainer ); } else { control.container.prepend( notificationsContainer ); } } return notificationsContainer; }, /** * Render notifications. * * Renders the `control.notifications` into the control's container. * Control subclasses may override this method to do their own handling * of rendering notifications. * * @since 4.6.0 * @this {wp.customize.Control} */ renderNotifications: function() { var control = this, container, notifications, hasError = false; container = control.getNotificationsContainerElement(); if ( ! container || ! container.length ) { return; } notifications = []; control.notifications.each( function( notification ) { notifications.push( notification ); if ( 'error' === notification.type ) { hasError = true; } } ); if ( 0 === notifications.length ) { container.stop().slideUp( 'fast' ); } else { container.stop().slideDown( 'fast', null, function() { $( this ).css( 'height', 'auto' ); } ); } if ( ! control.notificationsTemplate ) { control.notificationsTemplate = wp.template( 'customize-control-notifications' ); } control.container.toggleClass( 'has-notifications', 0 !== notifications.length ); control.container.toggleClass( 'has-error', hasError ); container.empty().append( $.trim( control.notificationsTemplate( { notifications: notifications, altNotice: Boolean( control.altNotice ) } ) ) ); }, /** * Normal controls do not expand, so just expand its parent * * @param {Object} [params] */ expand: function ( params ) { api.section( this.section() ).expand( params ); }, /** * Bring the containing section and panel into view and then * this control into view, focusing on the first input. */ focus: focus, /** * Update UI in response to a change in the control's active state. * This does not change the active state, it merely handles the behavior * for when it does change. * * @since 4.1.0 * * @param {Boolean} active * @param {Object} args * @param {Number} args.duration * @param {Callback} args.completeCallback */ onChangeActive: function ( active, args ) { if ( args.unchanged ) { if ( args.completeCallback ) { args.completeCallback(); } return; } if ( ! $.contains( document, this.container[0] ) ) { // jQuery.fn.slideUp is not hiding an element if it is not in the DOM this.container.toggle( active ); if ( args.completeCallback ) { args.completeCallback(); } } else if ( active ) { this.container.slideDown( args.duration, args.completeCallback ); } else { this.container.slideUp( args.duration, args.completeCallback ); } }, /** * @deprecated 4.1.0 Use this.onChangeActive() instead. */ toggle: function ( active ) { return this.onChangeActive( active, this.defaultActiveArguments ); }, /** * Shorthand way to enable the active state. * * @since 4.1.0 * * @param {Object} [params] * @returns {Boolean} false if already active */ activate: Container.prototype.activate, /** * Shorthand way to disable the active state. * * @since 4.1.0 * * @param {Object} [params] * @returns {Boolean} false if already inactive */ deactivate: Container.prototype.deactivate, /** * Re-use _toggleActive from Container class. * * @access private */ _toggleActive: Container.prototype._toggleActive, dropdownInit: function() { var control = this, statuses = this.container.find('.dropdown-status'), params = this.params, toggleFreeze = false, update = function( to ) { if ( typeof to === 'string' && params.statuses && params.statuses[ to ] ) statuses.html( params.statuses[ to ] ).show(); else statuses.hide(); }; // Support the .dropdown class to open/close complex elements this.container.on( 'click keydown', '.dropdown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { 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() ); }, /** * Render the control from its JS template, if it exists. * * The control's container must already exist in the DOM. * * @since 4.1.0 */ renderContent: function () { var template, control = this; // Replace the container element's content with the control. if ( 0 !== $( '#tmpl-' + control.templateSelector ).length ) { template = wp.template( control.templateSelector ); if ( template && control.container ) { control.container.html( template( control.params ) ); } } }, /** * Add a new page to a dropdown-pages control reusing menus code for this. * * @since 4.7.0 * @access private * @returns {void} */ addNewPage: function () { var control = this, promise, toggle, container, input, title, select; if ( 'dropdown-pages' !== control.params.type || ! control.params.allow_addition || ! api.Menus ) { return; } toggle = control.container.find( '.add-new-toggle' ); container = control.container.find( '.new-content-item' ); input = control.container.find( '.create-item-input' ); title = input.val(); select = control.container.find( 'select' ); if ( ! title ) { input.addClass( 'invalid' ); return; } input.removeClass( 'invalid' ); input.attr( 'disabled', 'disabled' ); // The menus functions add the page, publish when appropriate, and also add the new page to the dropdown-pages controls. promise = api.Menus.insertAutoDraftPost( { post_title: title, post_type: 'page' } ); promise.done( function( data ) { var availableItem, $content, itemTemplate; // Prepare the new page as an available menu item. // See api.Menus.submitNew(). availableItem = new api.Menus.AvailableItemModel( { 'id': 'post-' + data.post_id, // Used for available menu item Backbone models. 'title': title, 'type': 'post_type', 'type_label': api.Menus.data.l10n.page_label, 'object': 'page', 'object_id': data.post_id, 'url': data.url } ); // Add the new item to the list of available menu items. api.Menus.availableMenuItemsPanel.collection.add( availableItem ); $content = $( '#available-menu-items-post_type-page' ).find( '.available-menu-items-list' ); itemTemplate = wp.template( 'available-menu-item' ); $content.prepend( itemTemplate( availableItem.attributes ) ); // Focus the select control. select.focus(); control.setting.set( String( data.post_id ) ); // Triggers a preview refresh and updates the setting. // Reset the create page form. container.slideUp( 180 ); toggle.slideDown( 180 ); } ); promise.always( function() { input.val( '' ).removeAttr( 'disabled' ); } ); } }); /** * A colorpicker control. * * @class * @augments wp.customize.Control * @augments wp.customize.Class */ api.ColorControl = api.Control.extend({ ready: function() { var control = this, isHueSlider = this.params.mode === 'hue', updating = false, picker; if ( isHueSlider ) { picker = this.container.find( '.color-picker-hue' ); picker.val( control.setting() ).wpColorPicker({ change: function( event, ui ) { updating = true; control.setting( ui.color.h() ); updating = false; } }); } else { picker = this.container.find( '.color-picker-hex' ); picker.val( control.setting() ).wpColorPicker({ change: function() { updating = true; control.setting.set( picker.wpColorPicker( 'color' ) ); updating = false; }, clear: function() { updating = true; control.setting.set( '' ); updating = false; } }); } control.setting.bind( function ( value ) { // Bail if the update came from the control itself. if ( updating ) { return; } picker.val( value ); picker.wpColorPicker( 'color', value ); } ); // Collapse color picker when hitting Esc instead of collapsing the current section. control.container.on( 'keydown', function( event ) { var pickerContainer; if ( 27 !== event.which ) { // Esc. return; } pickerContainer = control.container.find( '.wp-picker-container' ); if ( pickerContainer.hasClass( 'wp-picker-active' ) ) { picker.wpColorPicker( 'close' ); control.container.find( '.wp-color-result' ).focus(); event.stopPropagation(); // Prevent section from being collapsed. } } ); } }); /** * A control that implements the media modal. * * @class * @augments wp.customize.Control * @augments wp.customize.Class */ api.MediaControl = api.Control.extend({ /** * When the control's DOM structure is ready, * set up internal event bindings. */ ready: function() { var control = this; // Shortcut so that we don't have to use _.bind every time we add a callback. _.bindAll( control, 'restoreDefault', 'removeFile', 'openFrame', 'select', 'pausePlayer' ); // Bind events, with delegation to facilitate re-rendering. control.container.on( 'click keydown', '.upload-button', control.openFrame ); control.container.on( 'click keydown', '.upload-button', control.pausePlayer ); control.container.on( 'click keydown', '.thumbnail-image img', control.openFrame ); control.container.on( 'click keydown', '.default-button', control.restoreDefault ); control.container.on( 'click keydown', '.remove-button', control.pausePlayer ); control.container.on( 'click keydown', '.remove-button', control.removeFile ); control.container.on( 'click keydown', '.remove-button', control.cleanupPlayer ); // Resize the player controls when it becomes visible (ie when section is expanded) api.section( control.section() ).container .on( 'expanded', function() { if ( control.player ) { control.player.setControlsSize(); } }) .on( 'collapsed', function() { control.pausePlayer(); }); /** * Set attachment data and render content. * * Note that BackgroundImage.prototype.ready applies this ready method * to itself. Since BackgroundImage is an UploadControl, the value * is the attachment URL instead of the attachment ID. In this case * we skip fetching the attachment data because we have no ID available, * and it is the responsibility of the UploadControl to set the control's * attachmentData before calling the renderContent method. * * @param {number|string} value Attachment */ function setAttachmentDataAndRenderContent( value ) { var hasAttachmentData = $.Deferred(); if ( control.extended( api.UploadControl ) ) { hasAttachmentData.resolve(); } else { value = parseInt( value, 10 ); if ( _.isNaN( value ) || value <= 0 ) { delete control.params.attachment; hasAttachmentData.resolve(); } else if ( control.params.attachment && control.params.attachment.id === value ) { hasAttachmentData.resolve(); } } // Fetch the attachment data. if ( 'pending' === hasAttachmentData.state() ) { wp.media.attachment( value ).fetch().done( function() { control.params.attachment = this.attributes; hasAttachmentData.resolve(); // Send attachment information to the preview for possible use in `postMessage` transport. wp.customize.previewer.send( control.setting.id + '-attachment-data', this.attributes ); } ); } hasAttachmentData.done( function() { control.renderContent(); } ); } // Ensure attachment data is initially set (for dynamically-instantiated controls). setAttachmentDataAndRenderContent( control.setting() ); // Update the attachment data and re-render the control when the setting changes. control.setting.bind( setAttachmentDataAndRenderContent ); }, pausePlayer: function () { this.player && this.player.pause(); }, cleanupPlayer: function () { this.player && wp.media.mixin.removePlayer( this.player ); }, /** * Open the media modal. */ openFrame: function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); if ( ! this.frame ) { this.initFrame(); } this.frame.open(); }, /** * Create a media modal select frame, and store it so the instance can be reused when needed. */ initFrame: function() { this.frame = wp.media({ button: { text: this.params.button_labels.frame_button }, states: [ new wp.media.controller.Library({ title: this.params.button_labels.frame_title, library: wp.media.query({ type: this.params.mime_type }), multiple: false, date: false }) ] }); // When a file is selected, run a callback. this.frame.on( 'select', this.select ); }, /** * Callback handler for when an attachment is selected in the media modal. * Gets the selected image information, and sets it within the control. */ select: function() { // Get the attachment from the modal frame. var node, attachment = this.frame.state().get( 'selection' ).first().toJSON(), mejsSettings = window._wpmejsSettings || {}; this.params.attachment = attachment; // Set the Customizer setting; the callback takes care of rendering. this.setting( attachment.id ); node = this.container.find( 'audio, video' ).get(0); // Initialize audio/video previews. if ( node ) { this.player = new MediaElementPlayer( node, mejsSettings ); } else { this.cleanupPlayer(); } }, /** * Reset the setting to the default value. */ restoreDefault: function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); this.params.attachment = this.params.defaultAttachment; this.setting( this.params.defaultAttachment.url ); }, /** * Called when the "Remove" link is clicked. Empties the setting. * * @param {object} event jQuery Event object */ removeFile: function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); this.params.attachment = {}; this.setting( '' ); this.renderContent(); // Not bound to setting change when emptying. } }); /** * An upload control, which utilizes the media modal. * * @class * @augments wp.customize.MediaControl * @augments wp.customize.Control * @augments wp.customize.Class */ api.UploadControl = api.MediaControl.extend({ /** * Callback handler for when an attachment is selected in the media modal. * Gets the selected image information, and sets it within the control. */ select: function() { // Get the attachment from the modal frame. var node, attachment = this.frame.state().get( 'selection' ).first().toJSON(), mejsSettings = window._wpmejsSettings || {}; this.params.attachment = attachment; // Set the Customizer setting; the callback takes care of rendering. this.setting( attachment.url ); node = this.container.find( 'audio, video' ).get(0); // Initialize audio/video previews. if ( node ) { this.player = new MediaElementPlayer( node, mejsSettings ); } else { this.cleanupPlayer(); } }, // @deprecated success: function() {}, // @deprecated removerVisibility: function() {} }); /** * A control for uploading images. * * This control no longer needs to do anything more * than what the upload control does in JS. * * @class * @augments wp.customize.UploadControl * @augments wp.customize.MediaControl * @augments wp.customize.Control * @augments wp.customize.Class */ api.ImageControl = api.UploadControl.extend({ // @deprecated thumbnailSrc: function() {} }); /** * A control for uploading background images. * * @class * @augments wp.customize.UploadControl * @augments wp.customize.MediaControl * @augments wp.customize.Control * @augments wp.customize.Class */ api.BackgroundControl = api.UploadControl.extend({ /** * When the control's DOM structure is ready, * set up internal event bindings. */ ready: function() { api.UploadControl.prototype.ready.apply( this, arguments ); }, /** * Callback handler for when an attachment is selected in the media modal. * Does an additional AJAX request for setting the background context. */ select: function() { api.UploadControl.prototype.select.apply( this, arguments ); wp.ajax.post( 'custom-background-add', { nonce: _wpCustomizeBackground.nonces.add, wp_customize: 'on', customize_theme: api.settings.theme.stylesheet, attachment_id: this.params.attachment.id } ); } }); /** * A control for positioning a background image. * * @since 4.7.0 * * @class * @augments wp.customize.Control * @augments wp.customize.Class */ api.BackgroundPositionControl = api.Control.extend( { /** * Set up control UI once embedded in DOM and settings are created. * * @since 4.7.0 * @access public */ ready: function() { var control = this, updateRadios; control.container.on( 'change', 'input[name="background-position"]', function() { var position = $( this ).val().split( ' ' ); control.settings.x( position[0] ); control.settings.y( position[1] ); } ); updateRadios = _.debounce( function() { var x, y, radioInput, inputValue; x = control.settings.x.get(); y = control.settings.y.get(); inputValue = String( x ) + ' ' + String( y ); radioInput = control.container.find( 'input[name="background-position"][value="' + inputValue + '"]' ); radioInput.click(); } ); control.settings.x.bind( updateRadios ); control.settings.y.bind( updateRadios ); updateRadios(); // Set initial UI. } } ); /** * A control for selecting and cropping an image. * * @class * @augments wp.customize.MediaControl * @augments wp.customize.Control * @augments wp.customize.Class */ api.CroppedImageControl = api.MediaControl.extend({ /** * Open the media modal to the library state. */ openFrame: function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } this.initFrame(); this.frame.setState( 'library' ).open(); }, /** * Create a media modal select frame, and store it so the instance can be reused when needed. */ initFrame: function() { var l10n = _wpMediaViewsL10n; this.frame = wp.media({ button: { text: l10n.select, close: false }, states: [ new wp.media.controller.Library({ title: this.params.button_labels.frame_title, library: wp.media.query({ type: 'image' }), multiple: false, date: false, priority: 20, suggestedWidth: this.params.width, suggestedHeight: this.params.height }), new wp.media.controller.CustomizeImageCropper({ imgSelectOptions: this.calculateImageSelectOptions, control: this }) ] }); this.frame.on( 'select', this.onSelect, this ); this.frame.on( 'cropped', this.onCropped, this ); this.frame.on( 'skippedcrop', this.onSkippedCrop, this ); }, /** * After an image is selected in the media modal, switch to the cropper * state if the image isn't the right size. */ onSelect: function() { var attachment = this.frame.state().get( 'selection' ).first().toJSON(); if ( this.params.width === attachment.width && this.params.height === attachment.height && ! this.params.flex_width && ! this.params.flex_height ) { this.setImageFromAttachment( attachment ); this.frame.close(); } else { this.frame.setState( 'cropper' ); } }, /** * After the image has been cropped, apply the cropped image data to the setting. * * @param {object} croppedImage Cropped attachment data. */ onCropped: function( croppedImage ) { this.setImageFromAttachment( croppedImage ); }, /** * Returns a set of options, computed from the attached image data and * control-specific data, to be fed to the imgAreaSelect plugin in * wp.media.view.Cropper. * * @param {wp.media.model.Attachment} attachment * @param {wp.media.controller.Cropper} controller * @returns {Object} Options */ calculateImageSelectOptions: function( attachment, controller ) { var control = controller.get( 'control' ), flexWidth = !! parseInt( control.params.flex_width, 10 ), flexHeight = !! parseInt( control.params.flex_height, 10 ), realWidth = attachment.get( 'width' ), realHeight = attachment.get( 'height' ), xInit = parseInt( control.params.width, 10 ), yInit = parseInt( control.params.height, 10 ), ratio = xInit / yInit, xImg = xInit, yImg = yInit, x1, y1, imgSelectOptions; controller.set( 'canSkipCrop', ! control.mustBeCropped( flexWidth, flexHeight, xInit, yInit, realWidth, realHeight ) ); if ( realWidth / realHeight > ratio ) { yInit = realHeight; xInit = yInit * ratio; } else { xInit = realWidth; yInit = xInit / ratio; } x1 = ( realWidth - xInit ) / 2; y1 = ( realHeight - yInit ) / 2; imgSelectOptions = { handles: true, keys: true, instance: true, persistent: true, imageWidth: realWidth, imageHeight: realHeight, minWidth: xImg > xInit ? xInit : xImg, minHeight: yImg > yInit ? yInit : yImg, x1: x1, y1: y1, x2: xInit + x1, y2: yInit + y1 }; if ( flexHeight === false && flexWidth === false ) { imgSelectOptions.aspectRatio = xInit + ':' + yInit; } if ( true === flexHeight ) { delete imgSelectOptions.minHeight; imgSelectOptions.maxWidth = realWidth; } if ( true === flexWidth ) { delete imgSelectOptions.minWidth; imgSelectOptions.maxHeight = realHeight; } return imgSelectOptions; }, /** * Return whether the image must be cropped, based on required dimensions. * * @param {bool} flexW * @param {bool} flexH * @param {int} dstW * @param {int} dstH * @param {int} imgW * @param {int} imgH * @return {bool} */ mustBeCropped: function( flexW, flexH, dstW, dstH, imgW, imgH ) { if ( true === flexW && true === flexH ) { return false; } if ( true === flexW && dstH === imgH ) { return false; } if ( true === flexH && dstW === imgW ) { return false; } if ( dstW === imgW && dstH === imgH ) { return false; } if ( imgW <= dstW ) { return false; } return true; }, /** * If cropping was skipped, apply the image data directly to the setting. */ onSkippedCrop: function() { var attachment = this.frame.state().get( 'selection' ).first().toJSON(); this.setImageFromAttachment( attachment ); }, /** * Updates the setting and re-renders the control UI. * * @param {object} attachment */ setImageFromAttachment: function( attachment ) { this.params.attachment = attachment; // Set the Customizer setting; the callback takes care of rendering. this.setting( attachment.id ); } }); /** * A control for selecting and cropping Site Icons. * * @class * @augments wp.customize.CroppedImageControl * @augments wp.customize.MediaControl * @augments wp.customize.Control * @augments wp.customize.Class */ api.SiteIconControl = api.CroppedImageControl.extend({ /** * Create a media modal select frame, and store it so the instance can be reused when needed. */ initFrame: function() { var l10n = _wpMediaViewsL10n; this.frame = wp.media({ button: { text: l10n.select, close: false }, states: [ new wp.media.controller.Library({ title: this.params.button_labels.frame_title, library: wp.media.query({ type: 'image' }), multiple: false, date: false, priority: 20, suggestedWidth: this.params.width, suggestedHeight: this.params.height }), new wp.media.controller.SiteIconCropper({ imgSelectOptions: this.calculateImageSelectOptions, control: this }) ] }); this.frame.on( 'select', this.onSelect, this ); this.frame.on( 'cropped', this.onCropped, this ); this.frame.on( 'skippedcrop', this.onSkippedCrop, this ); }, /** * After an image is selected in the media modal, switch to the cropper * state if the image isn't the right size. */ onSelect: function() { var attachment = this.frame.state().get( 'selection' ).first().toJSON(), controller = this; if ( this.params.width === attachment.width && this.params.height === attachment.height && ! this.params.flex_width && ! this.params.flex_height ) { wp.ajax.post( 'crop-image', { nonce: attachment.nonces.edit, id: attachment.id, context: 'site-icon', cropDetails: { x1: 0, y1: 0, width: this.params.width, height: this.params.height, dst_width: this.params.width, dst_height: this.params.height } } ).done( function( croppedImage ) { controller.setImageFromAttachment( croppedImage ); controller.frame.close(); } ).fail( function() { controller.frame.trigger('content:error:crop'); } ); } else { this.frame.setState( 'cropper' ); } }, /** * Updates the setting and re-renders the control UI. * * @param {object} attachment */ setImageFromAttachment: function( attachment ) { var sizes = [ 'site_icon-32', 'thumbnail', 'full' ], link, icon; _.each( sizes, function( size ) { if ( ! icon && ! _.isUndefined ( attachment.sizes[ size ] ) ) { icon = attachment.sizes[ size ]; } } ); this.params.attachment = attachment; // Set the Customizer setting; the callback takes care of rendering. this.setting( attachment.id ); if ( ! icon ) { return; } // Update the icon in-browser. link = $( 'link[rel="icon"][sizes="32x32"]' ); link.attr( 'href', icon.url ); }, /** * Called when the "Remove" link is clicked. Empties the setting. * * @param {object} event jQuery Event object */ removeFile: function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); this.params.attachment = {}; this.setting( '' ); this.renderContent(); // Not bound to setting change when emptying. $( 'link[rel="icon"][sizes="32x32"]' ).attr( 'href', '/favicon.ico' ); // Set to default. } }); /** * @class * @augments wp.customize.Control * @augments wp.customize.Class */ api.HeaderControl = api.Control.extend({ ready: function() { this.btnRemove = $('#customize-control-header_image .actions .remove'); this.btnNew = $('#customize-control-header_image .actions .new'); _.bindAll(this, 'openMedia', 'removeImage'); this.btnNew.on( 'click', this.openMedia ); this.btnRemove.on( 'click', this.removeImage ); api.HeaderTool.currentHeader = this.getInitialHeaderImage(); new api.HeaderTool.CurrentView({ model: api.HeaderTool.currentHeader, el: '#customize-control-header_image .current .container' }); new api.HeaderTool.ChoiceListView({ collection: api.HeaderTool.UploadsList = new api.HeaderTool.ChoiceList(), el: '#customize-control-header_image .choices .uploaded .list' }); new api.HeaderTool.ChoiceListView({ collection: api.HeaderTool.DefaultsList = new api.HeaderTool.DefaultsList(), el: '#customize-control-header_image .choices .default .list' }); api.HeaderTool.combinedList = api.HeaderTool.CombinedList = new api.HeaderTool.CombinedList([ api.HeaderTool.UploadsList, api.HeaderTool.DefaultsList ]); // Ensure custom-header-crop Ajax requests bootstrap the Customizer to activate the previewed theme. wp.media.controller.Cropper.prototype.defaults.doCropArgs.wp_customize = 'on'; wp.media.controller.Cropper.prototype.defaults.doCropArgs.customize_theme = api.settings.theme.stylesheet; }, /** * Returns a new instance of api.HeaderTool.ImageModel based on the currently * saved header image (if any). * * @since 4.2.0 * * @returns {Object} Options */ getInitialHeaderImage: function() { if ( ! api.get().header_image || ! api.get().header_image_data || _.contains( [ 'remove-header', 'random-default-image', 'random-uploaded-image' ], api.get().header_image ) ) { return new api.HeaderTool.ImageModel(); } // Get the matching uploaded image object. var currentHeaderObject = _.find( _wpCustomizeHeader.uploads, function( imageObj ) { return ( imageObj.attachment_id === api.get().header_image_data.attachment_id ); } ); // Fall back to raw current header image. if ( ! currentHeaderObject ) { currentHeaderObject = { url: api.get().header_image, thumbnail_url: api.get().header_image, attachment_id: api.get().header_image_data.attachment_id }; } return new api.HeaderTool.ImageModel({ header: currentHeaderObject, choice: currentHeaderObject.url.split( '/' ).pop() }); }, /** * Returns a set of options, computed from the attached image data and * theme-specific data, to be fed to the imgAreaSelect plugin in * wp.media.view.Cropper. * * @param {wp.media.model.Attachment} attachment * @param {wp.media.controller.Cropper} controller * @returns {Object} Options */ calculateImageSelectOptions: function(attachment, controller) { var xInit = parseInt(_wpCustomizeHeader.data.width, 10), yInit = parseInt(_wpCustomizeHeader.data.height, 10), flexWidth = !! parseInt(_wpCustomizeHeader.data['flex-width'], 10), flexHeight = !! parseInt(_wpCustomizeHeader.data['flex-height'], 10), ratio, xImg, yImg, realHeight, realWidth, imgSelectOptions; realWidth = attachment.get('width'); realHeight = attachment.get('height'); this.headerImage = new api.HeaderTool.ImageModel(); this.headerImage.set({ themeWidth: xInit, themeHeight: yInit, themeFlexWidth: flexWidth, themeFlexHeight: flexHeight, imageWidth: realWidth, imageHeight: realHeight }); controller.set( 'canSkipCrop', ! this.headerImage.shouldBeCropped() ); ratio = xInit / yInit; xImg = realWidth; yImg = realHeight; if ( xImg / yImg > ratio ) { yInit = yImg; xInit = yInit * ratio; } else { xInit = xImg; yInit = xInit / ratio; } imgSelectOptions = { handles: true, keys: true, instance: true, persistent: true, imageWidth: realWidth, imageHeight: realHeight, x1: 0, y1: 0, x2: xInit, y2: yInit }; if (flexHeight === false && flexWidth === false) { imgSelectOptions.aspectRatio = xInit + ':' + yInit; } if (flexHeight === false ) { imgSelectOptions.maxHeight = yInit; } if (flexWidth === false ) { imgSelectOptions.maxWidth = xInit; } return imgSelectOptions; }, /** * Sets up and opens the Media Manager in order to select an image. * Depending on both the size of the image and the properties of the * current theme, a cropping step after selection may be required or * skippable. * * @param {event} event */ openMedia: function(event) { var l10n = _wpMediaViewsL10n; event.preventDefault(); this.frame = wp.media({ button: { text: l10n.selectAndCrop, close: false }, states: [ new wp.media.controller.Library({ title: l10n.chooseImage, library: wp.media.query({ type: 'image' }), multiple: false, date: false, priority: 20, suggestedWidth: _wpCustomizeHeader.data.width, suggestedHeight: _wpCustomizeHeader.data.height }), new wp.media.controller.Cropper({ imgSelectOptions: this.calculateImageSelectOptions }) ] }); this.frame.on('select', this.onSelect, this); this.frame.on('cropped', this.onCropped, this); this.frame.on('skippedcrop', this.onSkippedCrop, this); this.frame.open(); }, /** * After an image is selected in the media modal, * switch to the cropper state. */ onSelect: function() { this.frame.setState('cropper'); }, /** * After the image has been cropped, apply the cropped image data to the setting. * * @param {object} croppedImage Cropped attachment data. */ onCropped: function(croppedImage) { var url = croppedImage.url, attachmentId = croppedImage.attachment_id, w = croppedImage.width, h = croppedImage.height; this.setImageFromURL(url, attachmentId, w, h); }, /** * If cropping was skipped, apply the image data directly to the setting. * * @param {object} selection */ onSkippedCrop: function(selection) { var url = selection.get('url'), w = selection.get('width'), h = selection.get('height'); this.setImageFromURL(url, selection.id, w, h); }, /** * Creates a new wp.customize.HeaderTool.ImageModel from provided * header image data and inserts it into the user-uploaded headers * collection. * * @param {String} url * @param {Number} attachmentId * @param {Number} width * @param {Number} height */ setImageFromURL: function(url, attachmentId, width, height) { var choice, data = {}; data.url = url; data.thumbnail_url = url; data.timestamp = _.now(); if (attachmentId) { data.attachment_id = attachmentId; } if (width) { data.width = width; } if (height) { data.height = height; } choice = new api.HeaderTool.ImageModel({ header: data, choice: url.split('/').pop() }); api.HeaderTool.UploadsList.add(choice); api.HeaderTool.currentHeader.set(choice.toJSON()); choice.save(); choice.importImage(); }, /** * Triggers the necessary events to deselect an image which was set as * the currently selected one. */ removeImage: function() { api.HeaderTool.currentHeader.trigger('hide'); api.HeaderTool.CombinedList.trigger('control:removeImage'); } }); /** * wp.customize.ThemeControl * * @constructor * @augments wp.customize.Control * @augments wp.customize.Class */ api.ThemeControl = api.Control.extend({ touchDrag: false, isRendered: false, /** * Defer rendering the theme control until the section is displayed. * * @since 4.2.0 */ renderContent: function () { var control = this, renderContentArgs = arguments; api.section( control.section(), function( section ) { if ( section.expanded() ) { api.Control.prototype.renderContent.apply( control, renderContentArgs ); control.isRendered = true; } else { section.expanded.bind( function( expanded ) { if ( expanded && ! control.isRendered ) { api.Control.prototype.renderContent.apply( control, renderContentArgs ); control.isRendered = true; } } ); } } ); }, /** * @since 4.2.0 */ ready: function() { var control = this; control.container.on( 'touchmove', '.theme', function() { control.touchDrag = true; }); // Bind details view trigger. control.container.on( 'click keydown touchend', '.theme', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } // Bail if the user scrolled on a touch device. if ( control.touchDrag === true ) { return control.touchDrag = false; } // Prevent the modal from showing when the user clicks the action button. if ( $( event.target ).is( '.theme-actions .button' ) ) { return; } api.section( control.section() ).loadThemePreview( control.params.theme.id ); }); control.container.on( 'click keydown', '.theme-actions .theme-details', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above api.section( control.section() ).showDetails( control.params.theme ); }); control.container.on( 'render-screenshot', function() { var $screenshot = $( this ).find( 'img' ), source = $screenshot.data( 'src' ); if ( source ) { $screenshot.attr( 'src', source ); } }); }, /** * Show or hide the theme based on the presence of the term in the title, description, and author. * * @since 4.2.0 */ filter: function( term ) { var control = this, haystack = control.params.theme.name + ' ' + control.params.theme.description + ' ' + control.params.theme.tags + ' ' + control.params.theme.author; haystack = haystack.toLowerCase().replace( '-', ' ' ); if ( -1 !== haystack.search( term ) ) { control.activate(); } else { control.deactivate(); } } }); // Change objects contained within the main customize object to Settings. api.defaultConstructor = api.Setting; // Create the collections for Controls, Sections and Panels. api.control = new api.Values({ defaultConstructor: api.Control }); api.section = new api.Values({ defaultConstructor: api.Section }); api.panel = new api.Values({ defaultConstructor: api.Panel }); /** * An object that fetches a preview in the background of the document, which * allows for seamless replacement of an existing preview. * * @class * @augments wp.customize.Messenger * @augments wp.customize.Class * @mixes wp.customize.Events */ api.PreviewFrame = api.Messenger.extend({ sensitivity: null, // Will get set to api.settings.timeouts.previewFrameSensitivity. /** * Initialize the PreviewFrame. * * @param {object} params.container * @param {object} params.previewUrl * @param {object} params.query * @param {object} options */ initialize: function( params, options ) { var deferred = $.Deferred(); /* * Make the instance of the PreviewFrame the promise object * so other objects can easily interact with it. */ deferred.promise( this ); this.container = params.container; $.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 the preview request. * * @param {object} deferred jQuery Deferred object to be resolved with * the request. */ run: function( deferred ) { var previewFrame = this, loaded = false, ready = false, readyData = null, hasPendingChangesetUpdate = '{}' !== previewFrame.query.customized, urlParser, params, form; if ( previewFrame._ready ) { previewFrame.unbind( 'ready', previewFrame._ready ); } previewFrame._ready = function( data ) { ready = true; readyData = data; previewFrame.container.addClass( 'iframe-ready' ); if ( ! data ) { return; } if ( loaded ) { deferred.resolveWith( previewFrame, [ data ] ); } }; previewFrame.bind( 'ready', previewFrame._ready ); urlParser = document.createElement( 'a' ); urlParser.href = previewFrame.previewUrl(); params = _.extend( api.utils.parseQueryString( urlParser.search.substr( 1 ) ), { customize_changeset_uuid: previewFrame.query.customize_changeset_uuid, customize_theme: previewFrame.query.customize_theme, customize_messenger_channel: previewFrame.query.customize_messenger_channel } ); urlParser.search = $.param( params ); previewFrame.iframe = $( '<iframe />', { title: api.l10n.previewIframeTitle, name: 'customize-' + previewFrame.channel() } ); previewFrame.iframe.attr( 'onmousewheel', '' ); // Workaround for Safari bug. See WP Trac #38149. if ( ! hasPendingChangesetUpdate ) { previewFrame.iframe.attr( 'src', urlParser.href ); } else { previewFrame.iframe.attr( 'data-src', urlParser.href ); // For debugging purposes. } previewFrame.iframe.appendTo( previewFrame.container ); previewFrame.targetWindow( previewFrame.iframe[0].contentWindow ); /* * Submit customized data in POST request to preview frame window since * there are setting value changes not yet written to changeset. */ if ( hasPendingChangesetUpdate ) { form = $( '<form>', { action: urlParser.href, target: previewFrame.iframe.attr( 'name' ), method: 'post', hidden: 'hidden' } ); form.append( $( '<input>', { type: 'hidden', name: '_method', value: 'GET' } ) ); _.each( previewFrame.query, function( value, key ) { form.append( $( '<input>', { type: 'hidden', name: key, value: value } ) ); } ); previewFrame.container.append( form ); form.submit(); form.remove(); // No need to keep the form around after submitted. } previewFrame.bind( 'iframe-loading-error', function( error ) { previewFrame.iframe.remove(); // Check if the user is not logged in. if ( 0 === error ) { previewFrame.login( deferred ); return; } // Check for cheaters. if ( -1 === error ) { deferred.rejectWith( previewFrame, [ 'cheatin' ] ); return; } deferred.rejectWith( previewFrame, [ 'request failure' ] ); } ); previewFrame.iframe.one( 'load', function() { loaded = true; if ( ready ) { deferred.resolveWith( previewFrame, [ readyData ] ); } else { setTimeout( function() { deferred.rejectWith( previewFrame, [ 'ready timeout' ] ); }, previewFrame.sensitivity ); } }); }, 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(), 'title': api.l10n.previewIframeTitle } ).hide(); iframe.appendTo( self.container ); iframe.on( 'load', function() { self.triedLogin = true; iframe.remove(); self.run( deferred ); }); }); }, destroy: function() { api.Messenger.prototype.destroy.call( this ); if ( this.iframe ) { this.iframe.remove(); } delete this.iframe; delete this.targetWindow; } }); (function(){ var id = 0; /** * Return an incremented ID for a preview messenger channel. * * This function is named "uuid" for historical reasons, but it is a * misnomer as it is not an actual UUID, and it is not universally unique. * This is not to be confused with `api.settings.changeset.uuid`. * * @return {string} */ api.PreviewFrame.uuid = function() { return 'preview-' + String( id++ ); }; }()); /** * Set the document title of the customizer. * * @since 4.1.0 * * @param {string} documentTitle */ api.setDocumentTitle = function ( documentTitle ) { var tmpl, title; tmpl = api.settings.documentTitleTmpl; title = tmpl.replace( '%s', documentTitle ); document.title = title; api.trigger( 'title', title ); }; /** * @class * @augments wp.customize.Messenger * @augments wp.customize.Class * @mixes wp.customize.Events */ api.Previewer = api.Messenger.extend({ refreshBuffer: null, // Will get set to api.settings.timeouts.windowRefresh. /** * @param {array} params.allowedUrls * @param {string} params.container A selector or jQuery element for the preview * frame to be placed. * @param {string} params.form * @param {string} params.previewUrl The URL to preview. * @param {object} options */ initialize: function( params, options ) { var previewer = this, urlParser = document.createElement( 'a' ); $.extend( previewer, options || {} ); previewer.deferred = { active: $.Deferred() }; // Debounce to prevent hammering server and then wait for any pending update requests. previewer.refresh = _.debounce( ( function( originalRefresh ) { return function() { var isProcessingComplete, refreshOnceProcessingComplete; isProcessingComplete = function() { return 0 === api.state( 'processing' ).get(); }; if ( isProcessingComplete() ) { originalRefresh.call( previewer ); } else { refreshOnceProcessingComplete = function() { if ( isProcessingComplete() ) { originalRefresh.call( previewer ); api.state( 'processing' ).unbind( refreshOnceProcessingComplete ); } }; api.state( 'processing' ).bind( refreshOnceProcessingComplete ); } }; }( previewer.refresh ) ), previewer.refreshBuffer ); previewer.container = api.ensure( params.container ); previewer.allowedUrls = params.allowedUrls; params.url = window.location.href; api.Messenger.prototype.initialize.call( previewer, params ); urlParser.href = previewer.origin(); previewer.add( 'scheme', urlParser.protocol.replace( /:$/, '' ) ); // Limit the URL to internal, front-end links. // // If the front end 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 front end // are on different domains to avoid the case where the front end doesn't have // ssl certs. previewer.add( 'previewUrl', params.previewUrl ).setter( function( to ) { var result = null, urlParser, queryParams, parsedAllowedUrl, parsedCandidateUrls = []; urlParser = document.createElement( 'a' ); urlParser.href = to; // Abort if URL is for admin or (static) files in wp-includes or wp-content. if ( /\/wp-(admin|includes|content)(\/|$)/.test( urlParser.pathname ) ) { return null; } // Remove state query params. if ( urlParser.search.length > 1 ) { queryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) ); delete queryParams.customize_changeset_uuid; delete queryParams.customize_theme; delete queryParams.customize_messenger_channel; if ( _.isEmpty( queryParams ) ) { urlParser.search = ''; } else { urlParser.search = $.param( queryParams ); } } parsedCandidateUrls.push( urlParser ); // Prepend list with URL that matches the scheme/protocol of the iframe. if ( previewer.scheme.get() + ':' !== urlParser.protocol ) { urlParser = document.createElement( 'a' ); urlParser.href = parsedCandidateUrls[0].href; urlParser.protocol = previewer.scheme.get() + ':'; parsedCandidateUrls.unshift( urlParser ); } // Attempt to match the URL to the control frame's scheme and check if it's allowed. If not, try the original URL. parsedAllowedUrl = document.createElement( 'a' ); _.find( parsedCandidateUrls, function( parsedCandidateUrl ) { return ! _.isUndefined( _.find( previewer.allowedUrls, function( allowedUrl ) { parsedAllowedUrl.href = allowedUrl; if ( urlParser.protocol === parsedAllowedUrl.protocol && urlParser.host === parsedAllowedUrl.host && 0 === urlParser.pathname.indexOf( parsedAllowedUrl.pathname.replace( /\/$/, '' ) ) ) { result = parsedCandidateUrl.href; return true; } } ) ); } ); return result; }); previewer.bind( 'ready', previewer.ready ); // Start listening for keep-alive messages when iframe first loads. previewer.deferred.active.done( _.bind( previewer.keepPreviewAlive, previewer ) ); previewer.bind( 'synced', function() { previewer.send( 'active' ); } ); // Refresh the preview when the URL is changed (but not yet). previewer.previewUrl.bind( previewer.refresh ); previewer.scroll = 0; previewer.bind( 'scroll', function( distance ) { previewer.scroll = distance; }); // Update the URL when the iframe sends a URL message, resetting scroll position. If URL is unchanged, then refresh. previewer.bind( 'url', function( url ) { var onUrlChange, urlChanged = false; previewer.scroll = 0; onUrlChange = function() { urlChanged = true; }; previewer.previewUrl.bind( onUrlChange ); previewer.previewUrl.set( url ); previewer.previewUrl.unbind( onUrlChange ); if ( ! urlChanged ) { previewer.refresh(); } } ); // Update the document title when the preview changes. previewer.bind( 'documentTitle', function ( title ) { api.setDocumentTitle( title ); } ); }, /** * Handle the preview receiving the ready message. * * @since 4.7.0 * @access public * * @param {object} data - Data from preview. * @param {string} data.currentUrl - Current URL. * @param {object} data.activePanels - Active panels. * @param {object} data.activeSections Active sections. * @param {object} data.activeControls Active controls. * @returns {void} */ ready: function( data ) { var previewer = this, synced = {}, constructs; synced.settings = api.get(); synced['settings-modified-while-loading'] = previewer.settingsModifiedWhileLoading; if ( 'resolved' !== previewer.deferred.active.state() || previewer.loading ) { synced.scroll = previewer.scroll; } synced['edit-shortcut-visibility'] = api.state( 'editShortcutVisibility' ).get(); previewer.send( 'sync', synced ); // Set the previewUrl without causing the url to set the iframe. if ( data.currentUrl ) { previewer.previewUrl.unbind( previewer.refresh ); previewer.previewUrl.set( data.currentUrl ); previewer.previewUrl.bind( previewer.refresh ); } /* * Walk over all panels, sections, and controls and set their * respective active states to true if the preview explicitly * indicates as such. */ constructs = { panel: data.activePanels, section: data.activeSections, control: data.activeControls }; _( constructs ).each( function ( activeConstructs, type ) { api[ type ].each( function ( construct, id ) { var isDynamicallyCreated = _.isUndefined( api.settings[ type + 's' ][ id ] ); /* * If the construct was created statically in PHP (not dynamically in JS) * then consider a missing (undefined) value in the activeConstructs to * mean it should be deactivated (since it is gone). But if it is * dynamically created then only toggle activation if the value is defined, * as this means that the construct was also then correspondingly * created statically in PHP and the active callback is available. * Otherwise, dynamically-created constructs should normally have * their active states toggled in JS rather than from PHP. */ if ( ! isDynamicallyCreated || ! _.isUndefined( activeConstructs[ id ] ) ) { if ( activeConstructs[ id ] ) { construct.activate(); } else { construct.deactivate(); } } } ); } ); if ( data.settingValidities ) { api._handleSettingValidities( { settingValidities: data.settingValidities, focusInvalidControl: false } ); } }, /** * Keep the preview alive by listening for ready and keep-alive messages. * * If a message is not received in the allotted time then the iframe will be set back to the last known valid URL. * * @since 4.7.0 * @access public * * @returns {void} */ keepPreviewAlive: function keepPreviewAlive() { var previewer = this, keepAliveTick, timeoutId, handleMissingKeepAlive, scheduleKeepAliveCheck; /** * Schedule a preview keep-alive check. * * Note that if a page load takes longer than keepAliveCheck milliseconds, * the keep-alive messages will still be getting sent from the previous * URL. */ scheduleKeepAliveCheck = function() { timeoutId = setTimeout( handleMissingKeepAlive, api.settings.timeouts.keepAliveCheck ); }; /** * Set the previewerAlive state to true when receiving a message from the preview. */ keepAliveTick = function() { api.state( 'previewerAlive' ).set( true ); clearTimeout( timeoutId ); scheduleKeepAliveCheck(); }; /** * Set the previewerAlive state to false if keepAliveCheck milliseconds have transpired without a message. * * This is most likely to happen in the case of a connectivity error, or if the theme causes the browser * to navigate to a non-allowed URL. Setting this state to false will force settings with a postMessage * transport to use refresh instead, causing the preview frame also to be replaced with the current * allowed preview URL. */ handleMissingKeepAlive = function() { api.state( 'previewerAlive' ).set( false ); }; scheduleKeepAliveCheck(); previewer.bind( 'ready', keepAliveTick ); previewer.bind( 'keep-alive', keepAliveTick ); }, /** * Query string data sent with each preview request. * * @abstract */ query: function() {}, abort: function() { if ( this.loading ) { this.loading.destroy(); delete this.loading; } }, /** * Refresh the preview seamlessly. * * @since 3.4.0 * @access public * @returns {void} */ refresh: function() { var previewer = this, onSettingChange; // Display loading indicator previewer.send( 'loading-initiated' ); previewer.abort(); previewer.loading = new api.PreviewFrame({ url: previewer.url(), previewUrl: previewer.previewUrl(), query: previewer.query( { excludeCustomizedSaved: true } ) || {}, container: previewer.container }); previewer.settingsModifiedWhileLoading = {}; onSettingChange = function( setting ) { previewer.settingsModifiedWhileLoading[ setting.id ] = true; }; api.bind( 'change', onSettingChange ); previewer.loading.always( function() { api.unbind( 'change', onSettingChange ); } ); previewer.loading.done( function( readyData ) { var loadingFrame = this, onceSynced; previewer.preview = loadingFrame; previewer.targetWindow( loadingFrame.targetWindow() ); previewer.channel( loadingFrame.channel() ); onceSynced = function() { loadingFrame.unbind( 'synced', onceSynced ); if ( previewer._previousPreview ) { previewer._previousPreview.destroy(); } previewer._previousPreview = previewer.preview; previewer.deferred.active.resolve(); delete previewer.loading; }; loadingFrame.bind( 'synced', onceSynced ); // This event will be received directly by the previewer in normal navigation; this is only needed for seamless refresh. previewer.trigger( 'ready', readyData ); }); previewer.loading.fail( function( reason ) { previewer.send( 'loading-failed' ); if ( 'logged out' === reason ) { if ( previewer.preview ) { previewer.preview.destroy(); delete previewer.preview; } previewer.login().done( previewer.refresh ); } if ( 'cheatin' === reason ) { previewer.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, 'title': api.l10n.loginIframeTitle } ).appendTo( this.container ); messenger.targetWindow( iframe[0].contentWindow ); messenger.bind( 'login', function () { var refreshNonces = previewer.refreshNonces(); refreshNonces.always( function() { iframe.remove(); messenger.destroy(); delete previewer._login; }); refreshNonces.done( function() { deferred.resolve(); }); refreshNonces.fail( function() { previewer.cheatin(); deferred.reject(); }); }); return this._login; }, cheatin: function() { $( document.body ).empty().addClass( 'cheatin' ).append( '<h1>' + api.l10n.cheatin + '</h1>' + '<p>' + api.l10n.notAllowed + '</p>' ); }, refreshNonces: function() { var request, deferred = $.Deferred(); deferred.promise(); request = wp.ajax.post( 'customize_refresh_nonces', { wp_customize: 'on', customize_theme: api.settings.theme.stylesheet }); request.done( function( response ) { api.trigger( 'nonce-refresh', response ); deferred.resolve(); }); request.fail( function() { deferred.reject(); }); return deferred; } }); api.settingConstructor = {}; api.controlConstructor = { color: api.ColorControl, media: api.MediaControl, upload: api.UploadControl, image: api.ImageControl, cropped_image: api.CroppedImageControl, site_icon: api.SiteIconControl, header: api.HeaderControl, background: api.BackgroundControl, background_position: api.BackgroundPositionControl, theme: api.ThemeControl }; api.panelConstructor = {}; api.sectionConstructor = { themes: api.ThemesSection }; /** * Handle setting_validities in an error response for the customize-save request. * * Add notifications to the settings and focus on the first control that has an invalid setting. * * @since 4.6.0 * @private * * @param {object} args * @param {object} args.settingValidities * @param {boolean} [args.focusInvalidControl=false] * @returns {void} */ api._handleSettingValidities = function handleSettingValidities( args ) { var invalidSettingControls, invalidSettings = [], wasFocused = false; // Find the controls that correspond to each invalid setting. _.each( args.settingValidities, function( validity, settingId ) { var setting = api( settingId ); if ( setting ) { // Add notifications for invalidities. if ( _.isObject( validity ) ) { _.each( validity, function( params, code ) { var notification, existingNotification, needsReplacement = false; notification = new api.Notification( code, _.extend( { fromServer: true }, params ) ); // Remove existing notification if already exists for code but differs in parameters. existingNotification = setting.notifications( notification.code ); if ( existingNotification ) { needsReplacement = notification.type !== existingNotification.type || notification.message !== existingNotification.message || ! _.isEqual( notification.data, existingNotification.data ); } if ( needsReplacement ) { setting.notifications.remove( code ); } if ( ! setting.notifications.has( notification.code ) ) { setting.notifications.add( code, notification ); } invalidSettings.push( setting.id ); } ); } // Remove notification errors that are no longer valid. setting.notifications.each( function( notification ) { if ( notification.fromServer && 'error' === notification.type && ( true === validity || ! validity[ notification.code ] ) ) { setting.notifications.remove( notification.code ); } } ); } } ); if ( args.focusInvalidControl ) { invalidSettingControls = api.findControlsForSettings( invalidSettings ); // Focus on the first control that is inside of an expanded section (one that is visible). _( _.values( invalidSettingControls ) ).find( function( controls ) { return _( controls ).find( function( control ) { var isExpanded = control.section() && api.section.has( control.section() ) && api.section( control.section() ).expanded(); if ( isExpanded && control.expanded ) { isExpanded = control.expanded(); } if ( isExpanded ) { control.focus(); wasFocused = true; } return wasFocused; } ); } ); // Focus on the first invalid control. if ( ! wasFocused && ! _.isEmpty( invalidSettingControls ) ) { _.values( invalidSettingControls )[0][0].focus(); } } }; /** * Find all controls associated with the given settings. * * @since 4.6.0 * @param {string[]} settingIds Setting IDs. * @returns {object<string, wp.customize.Control>} Mapping setting ids to arrays of controls. */ api.findControlsForSettings = function findControlsForSettings( settingIds ) { var controls = {}, settingControls; _.each( _.unique( settingIds ), function( settingId ) { var setting = api( settingId ); if ( setting ) { settingControls = setting.findControls(); if ( settingControls && settingControls.length > 0 ) { controls[ settingId ] = settingControls; } } } ); return controls; }; /** * Sort panels, sections, controls by priorities. Hide empty sections and panels. * * @since 4.1.0 */ api.reflowPaneContents = _.bind( function () { var appendContainer, activeElement, rootHeadContainers, rootNodes = [], wasReflowed = false; if ( document.activeElement ) { activeElement = $( document.activeElement ); } // Sort the sections within each panel api.panel.each( function ( panel ) { var sections = panel.sections(), sectionHeadContainers = _.pluck( sections, 'headContainer' ); rootNodes.push( panel ); appendContainer = ( panel.contentContainer.is( 'ul' ) ) ? panel.contentContainer : panel.contentContainer.find( 'ul:first' ); if ( ! api.utils.areElementListsEqual( sectionHeadContainers, appendContainer.children( '[id]' ) ) ) { _( sections ).each( function ( section ) { appendContainer.append( section.headContainer ); } ); wasReflowed = true; } } ); // Sort the controls within each section api.section.each( function ( section ) { var controls = section.controls(), controlContainers = _.pluck( controls, 'container' ); if ( ! section.panel() ) { rootNodes.push( section ); } appendContainer = ( section.contentContainer.is( 'ul' ) ) ? section.contentContainer : section.contentContainer.find( 'ul:first' ); if ( ! api.utils.areElementListsEqual( controlContainers, appendContainer.children( '[id]' ) ) ) { _( controls ).each( function ( control ) { appendContainer.append( control.container ); } ); wasReflowed = true; } } ); // Sort the root panels and sections rootNodes.sort( api.utils.prioritySort ); rootHeadContainers = _.pluck( rootNodes, 'headContainer' ); appendContainer = $( '#customize-theme-controls .customize-pane-parent' ); // @todo This should be defined elsewhere, and to be configurable if ( ! api.utils.areElementListsEqual( rootHeadContainers, appendContainer.children() ) ) { _( rootNodes ).each( function ( rootNode ) { appendContainer.append( rootNode.headContainer ); } ); wasReflowed = true; } // Now re-trigger the active Value callbacks to that the panels and sections can decide whether they can be rendered api.panel.each( function ( panel ) { var value = panel.active(); panel.active.callbacks.fireWith( panel.active, [ value, value ] ); } ); api.section.each( function ( section ) { var value = section.active(); section.active.callbacks.fireWith( section.active, [ value, value ] ); } ); // Restore focus if there was a reflow and there was an active (focused) element if ( wasReflowed && activeElement ) { activeElement.focus(); } api.trigger( 'pane-contents-reflowed' ); }, api ); $( function() { api.settings = window._wpCustomizeSettings; api.l10n = window._wpCustomizeControlsL10n; // Check if we can run the Customizer. if ( ! api.settings ) { return; } // Bail if any incompatibilities are found. if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) ) { return; } if ( null === api.PreviewFrame.prototype.sensitivity ) { api.PreviewFrame.prototype.sensitivity = api.settings.timeouts.previewFrameSensitivity; } if ( null === api.Previewer.prototype.refreshBuffer ) { api.Previewer.prototype.refreshBuffer = api.settings.timeouts.windowRefresh; } var parent, body = $( document.body ), overlay = body.children( '.wp-full-overlay' ), title = $( '#customize-info .panel-title.site-title' ), closeBtn = $( '.customize-controls-close' ), saveBtn = $( '#save' ), footerActions = $( '#customize-footer-actions' ); // Prevent the form from saving when enter is pressed on an input or select element. $('#customize-controls').on( 'keydown', function( e ) { var isEnter = ( 13 === e.which ), $el = $( e.target ); if ( isEnter && ( $el.is( 'input:not([type=button])' ) || $el.is( 'select' ) ) ) { e.preventDefault(); } }); // Expand/Collapse the main customizer customize info. $( '.customize-info' ).find( '> .accordion-section-title .customize-help-toggle' ).on( 'click', function() { var section = $( this ).closest( '.accordion-section' ), content = section.find( '.customize-panel-description:first' ); if ( section.hasClass( 'cannot-expand' ) ) { return; } if ( section.hasClass( 'open' ) ) { section.toggleClass( 'open' ); content.slideUp( api.Panel.prototype.defaultExpandedArguments.duration ); $( this ).attr( 'aria-expanded', false ); } else { content.slideDown( api.Panel.prototype.defaultExpandedArguments.duration ); section.toggleClass( 'open' ); $( this ).attr( 'aria-expanded', true ); } }); // Initialize Previewer api.previewer = new api.Previewer({ container: '#customize-preview', form: '#customize-controls', previewUrl: api.settings.url.preview, allowedUrls: api.settings.url.allowed }, { nonce: api.settings.nonce, /** * Build the query to send along with the Preview request. * * @since 3.4.0 * @since 4.7.0 Added options param. * @access public * * @param {object} [options] Options. * @param {boolean} [options.excludeCustomizedSaved=false] Exclude saved settings in customized response (values pending writing to changeset). * @return {object} Query vars. */ query: function( options ) { var queryVars = { wp_customize: 'on', customize_theme: api.settings.theme.stylesheet, nonce: this.nonce.preview, customize_changeset_uuid: api.settings.changeset.uuid }; /* * Exclude customized data if requested especially for calls to requestChangesetUpdate. * Changeset updates are differential and so it is a performance waste to send all of * the dirty settings with each update. */ queryVars.customized = JSON.stringify( api.dirtyValues( { unsaved: options && options.excludeCustomizedSaved } ) ); return queryVars; }, /** * Save (and publish) the customizer changeset. * * Updates to the changeset are transactional. If any of the settings * are invalid then none of them will be written into the changeset. * A revision will be made for the changeset post if revisions support * has been added to the post type. * * @since 3.4.0 * @since 4.7.0 Added args param and return value. * * @param {object} [args] Args. * @param {string} [args.status=publish] Status. * @param {string} [args.date] Date, in local time in MySQL format. * @param {string} [args.title] Title * @returns {jQuery.promise} Promise. */ save: function( args ) { var previewer = this, deferred = $.Deferred(), changesetStatus = 'publish', processing = api.state( 'processing' ), submitWhenDoneProcessing, submit, modifiedWhileSaving = {}, invalidSettings = [], invalidControls; if ( args && args.status ) { changesetStatus = args.status; } if ( api.state( 'saving' ).get() ) { deferred.reject( 'already_saving' ); deferred.promise(); } api.state( 'saving' ).set( true ); function captureSettingModifiedDuringSave( setting ) { modifiedWhileSaving[ setting.id ] = true; } api.bind( 'change', captureSettingModifiedDuringSave ); submit = function () { var request, query, settingInvalidities = {}, latestRevision = api._latestRevision; /* * Block saving if there are any settings that are marked as * invalid from the client (not from the server). Focus on * the control. */ api.each( function( setting ) { setting.notifications.each( function( notification ) { if ( 'error' === notification.type && ! notification.fromServer ) { invalidSettings.push( setting.id ); if ( ! settingInvalidities[ setting.id ] ) { settingInvalidities[ setting.id ] = {}; } settingInvalidities[ setting.id ][ notification.code ] = notification; } } ); } ); invalidControls = api.findControlsForSettings( invalidSettings ); if ( ! _.isEmpty( invalidControls ) ) { _.values( invalidControls )[0][0].focus(); api.unbind( 'change', captureSettingModifiedDuringSave ); deferred.rejectWith( previewer, [ { setting_invalidities: settingInvalidities } ] ); api.state( 'saving' ).set( false ); return deferred.promise(); } /* * Note that excludeCustomizedSaved is intentionally false so that the entire * set of customized data will be included if bypassed changeset update. */ query = $.extend( previewer.query( { excludeCustomizedSaved: false } ), { nonce: previewer.nonce.save, customize_changeset_status: changesetStatus } ); if ( args && args.date ) { query.customize_changeset_date = args.date; } if ( args && args.title ) { query.customize_changeset_title = args.title; } /* * Note that the dirty customized values will have already been set in the * changeset and so technically query.customized could be deleted. However, * it is remaining here to make sure that any settings that got updated * quietly which may have not triggered an update request will also get * included in the values that get saved to the changeset. This will ensure * that values that get injected via the saved event will be included in * the changeset. This also ensures that setting values that were invalid * will get re-validated, perhaps in the case of settings that are invalid * due to dependencies on other settings. */ request = wp.ajax.post( 'customize_save', query ); // Disable save button during the save request. saveBtn.prop( 'disabled', true ); api.trigger( 'save', request ); request.always( function () { api.state( 'saving' ).set( false ); saveBtn.prop( 'disabled', false ); api.unbind( 'change', captureSettingModifiedDuringSave ); } ); request.fail( function ( response ) { if ( '0' === response ) { response = 'not_logged_in'; } else if ( '-1' === response ) { // Back-compat in case any other check_ajax_referer() call is dying response = 'invalid_nonce'; } if ( 'invalid_nonce' === response ) { previewer.cheatin(); } else if ( 'not_logged_in' === response ) { previewer.preview.iframe.hide(); previewer.login().done( function() { previewer.save(); previewer.preview.iframe.show(); } ); } if ( response.setting_validities ) { api._handleSettingValidities( { settingValidities: response.setting_validities, focusInvalidControl: true } ); } deferred.rejectWith( previewer, [ response ] ); api.trigger( 'error', response ); } ); request.done( function( response ) { previewer.send( 'saved', response ); api.state( 'changesetStatus' ).set( response.changeset_status ); if ( 'publish' === response.changeset_status ) { // Mark all published as clean if they haven't been modified during the request. api.each( function( setting ) { /* * Note that the setting revision will be undefined in the case of setting * values that are marked as dirty when the customizer is loaded, such as * when applying starter content. All other dirty settings will have an * associated revision due to their modification triggering a change event. */ if ( setting._dirty && ( _.isUndefined( api._latestSettingRevisions[ setting.id ] ) || api._latestSettingRevisions[ setting.id ] <= latestRevision ) ) { setting._dirty = false; } } ); api.state( 'changesetStatus' ).set( '' ); api.settings.changeset.uuid = response.next_changeset_uuid; parent.send( 'changeset-uuid', api.settings.changeset.uuid ); } if ( response.setting_validities ) { api._handleSettingValidities( { settingValidities: response.setting_validities, focusInvalidControl: true } ); } deferred.resolveWith( previewer, [ response ] ); api.trigger( 'saved', response ); // Restore the global dirty state if any settings were modified during save. if ( ! _.isEmpty( modifiedWhileSaving ) ) { api.state( 'saved' ).set( false ); } } ); }; if ( 0 === processing() ) { submit(); } else { submitWhenDoneProcessing = function () { if ( 0 === processing() ) { api.state.unbind( 'change', submitWhenDoneProcessing ); submit(); } }; api.state.bind( 'change', submitWhenDoneProcessing ); } return deferred.promise(); } }); // Ensure preview nonce is included with every customized request, to allow post data to be read. $.ajaxPrefilter( function injectPreviewNonce( options ) { if ( ! /wp_customize=on/.test( options.data ) ) { return; } options.data += '&' + $.param({ customize_preview_nonce: api.settings.nonce.preview }); }); // Refresh the nonces if the preview sends updated nonces over. api.previewer.bind( 'nonce', function( nonce ) { $.extend( this.nonce, nonce ); }); // Refresh the nonces if login sends updated nonces over. api.bind( 'nonce-refresh', function( nonce ) { $.extend( api.settings.nonce, nonce ); $.extend( api.previewer.nonce, nonce ); api.previewer.send( 'nonce-refresh', nonce ); }); // Create Settings $.each( api.settings.settings, function( id, data ) { var constructor = api.settingConstructor[ data.type ] || api.Setting, setting; setting = new constructor( id, data.value, { transport: data.transport, previewer: api.previewer, dirty: !! data.dirty } ); api.add( id, setting ); }); // Create Panels $.each( api.settings.panels, function ( id, data ) { var constructor = api.panelConstructor[ data.type ] || api.Panel, panel; panel = new constructor( id, { params: data } ); api.panel.add( id, panel ); }); // Create Sections $.each( api.settings.sections, function ( id, data ) { var constructor = api.sectionConstructor[ data.type ] || api.Section, section; section = new constructor( id, { params: data } ); api.section.add( id, section ); }); // Create Controls $.each( api.settings.controls, function( id, data ) { var constructor = api.controlConstructor[ data.type ] || api.Control, control; control = new constructor( id, { params: data, previewer: api.previewer } ); api.control.add( id, control ); }); // Focus the autofocused element _.each( [ 'panel', 'section', 'control' ], function( type ) { var id = api.settings.autofocus[ type ]; if ( ! id ) { return; } /* * Defer focus until: * 1. The panel, section, or control exists (especially for dynamically-created ones). * 2. The instance is embedded in the document (and so is focusable). * 3. The preview has finished loading so that the active states have been set. */ api[ type ]( id, function( instance ) { instance.deferred.embedded.done( function() { api.previewer.deferred.active.done( function() { instance.focus(); }); }); }); }); api.bind( 'ready', api.reflowPaneContents ); $( [ api.panel, api.section, api.control ] ).each( function ( i, values ) { var debouncedReflowPaneContents = _.debounce( api.reflowPaneContents, api.settings.timeouts.reflowPaneContents ); values.bind( 'add', debouncedReflowPaneContents ); values.bind( 'change', debouncedReflowPaneContents ); values.bind( 'remove', debouncedReflowPaneContents ); } ); // Save and activated states (function() { var state = new api.Values(), saved = state.create( 'saved' ), saving = state.create( 'saving' ), activated = state.create( 'activated' ), processing = state.create( 'processing' ), paneVisible = state.create( 'paneVisible' ), expandedPanel = state.create( 'expandedPanel' ), expandedSection = state.create( 'expandedSection' ), changesetStatus = state.create( 'changesetStatus' ), previewerAlive = state.create( 'previewerAlive' ), editShortcutVisibility = state.create( 'editShortcutVisibility' ), populateChangesetUuidParam; state.bind( 'change', function() { var canSave; if ( ! activated() ) { saveBtn.val( api.l10n.activate ); closeBtn.find( '.screen-reader-text' ).text( api.l10n.cancel ); } else if ( '' === changesetStatus.get() && saved() ) { saveBtn.val( api.l10n.saved ); closeBtn.find( '.screen-reader-text' ).text( api.l10n.close ); } else { saveBtn.val( api.l10n.save ); closeBtn.find( '.screen-reader-text' ).text( api.l10n.cancel ); } /* * Save (publish) button should be enabled if saving is not currently happening, * and if the theme is not active or the changeset exists but is not published. */ canSave = ! saving() && ( ! activated() || ! saved() || ( '' !== changesetStatus() && 'publish' !== changesetStatus() ) ); saveBtn.prop( 'disabled', ! canSave ); }); // Set default states. changesetStatus( api.settings.changeset.status ); saved( true ); if ( '' === changesetStatus() ) { // Handle case for loading starter content. api.each( function( setting ) { if ( setting._dirty ) { saved( false ); } } ); } saving( false ); activated( api.settings.theme.active ); processing( 0 ); paneVisible( true ); expandedPanel( false ); expandedSection( false ); previewerAlive( true ); editShortcutVisibility( 'visible' ); api.bind( 'change', function() { if ( state( 'saved' ).get() ) { state( 'saved' ).set( false ); populateChangesetUuidParam( true ); } }); saving.bind( function( isSaving ) { body.toggleClass( 'saving', isSaving ); } ); api.bind( 'saved', function( response ) { state('saved').set( true ); if ( 'publish' === response.changeset_status ) { state( 'activated' ).set( true ); } }); activated.bind( function( to ) { if ( to ) { api.trigger( 'activated' ); } }); /** * Populate URL with UUID via `history.replaceState()`. * * @since 4.7.0 * @access private * * @param {boolean} isIncluded Is UUID included. * @returns {void} */ populateChangesetUuidParam = function( isIncluded ) { var urlParser, queryParams; // Abort on IE9 which doesn't support history management. if ( ! history.replaceState ) { return; } urlParser = document.createElement( 'a' ); urlParser.href = location.href; queryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) ); if ( isIncluded ) { if ( queryParams.changeset_uuid === api.settings.changeset.uuid ) { return; } queryParams.changeset_uuid = api.settings.changeset.uuid; } else { if ( ! queryParams.changeset_uuid ) { return; } delete queryParams.changeset_uuid; } urlParser.search = $.param( queryParams ); history.replaceState( {}, document.title, urlParser.href ); }; changesetStatus.bind( function( newStatus ) { populateChangesetUuidParam( '' !== newStatus && 'publish' !== newStatus ); } ); // Expose states to the API. api.state = state; }()); // Check if preview url is valid and load the preview frame. if ( api.previewer.previewUrl() ) { api.previewer.refresh(); } else { api.previewer.previewUrl( api.settings.url.home ); } // Button bindings. saveBtn.click( function( event ) { api.previewer.save(); event.preventDefault(); }).keydown( function( event ) { if ( 9 === event.which ) // tab return; if ( 13 === event.which ) // enter api.previewer.save(); event.preventDefault(); }); closeBtn.keydown( function( event ) { if ( 9 === event.which ) // tab return; if ( 13 === event.which ) // enter this.click(); event.preventDefault(); }); $( '.collapse-sidebar' ).on( 'click', function() { api.state( 'paneVisible' ).set( ! api.state( 'paneVisible' ).get() ); }); api.state( 'paneVisible' ).bind( function( paneVisible ) { overlay.toggleClass( 'preview-only', ! paneVisible ); overlay.toggleClass( 'expanded', paneVisible ); overlay.toggleClass( 'collapsed', ! paneVisible ); if ( ! paneVisible ) { $( '.collapse-sidebar' ).attr({ 'aria-expanded': 'false', 'aria-label': api.l10n.expandSidebar }); } else { $( '.collapse-sidebar' ).attr({ 'aria-expanded': 'true', 'aria-label': api.l10n.collapseSidebar }); } }); // Keyboard shortcuts - esc to exit section/panel. $( 'body' ).on( 'keydown', function( event ) { var collapsedObject, expandedControls = [], expandedSections = [], expandedPanels = []; if ( 27 !== event.which ) { // Esc. return; } /* * Abort if the event target is not the body (the default) and not inside of #customize-controls. * This ensures that ESC meant to collapse a modal dialog or a TinyMCE toolbar won't collapse something else. */ if ( ! $( event.target ).is( 'body' ) && ! $.contains( $( '#customize-controls' )[0], event.target ) ) { return; } // Check for expanded expandable controls (e.g. widgets and nav menus items), sections, and panels. api.control.each( function( control ) { if ( control.expanded && control.expanded() && _.isFunction( control.collapse ) ) { expandedControls.push( control ); } }); api.section.each( function( section ) { if ( section.expanded() ) { expandedSections.push( section ); } }); api.panel.each( function( panel ) { if ( panel.expanded() ) { expandedPanels.push( panel ); } }); // Skip collapsing expanded controls if there are no expanded sections. if ( expandedControls.length > 0 && 0 === expandedSections.length ) { expandedControls.length = 0; } // Collapse the most granular expanded object. collapsedObject = expandedControls[0] || expandedSections[0] || expandedPanels[0]; if ( collapsedObject ) { collapsedObject.collapse(); event.preventDefault(); } }); $( '.customize-controls-preview-toggle' ).on( 'click', function() { api.state( 'paneVisible' ).set( ! api.state( 'paneVisible' ).get() ); }); /* * Sticky header feature. */ (function initStickyHeaders() { var parentContainer = $( '.wp-full-overlay-sidebar-content' ), changeContainer, getHeaderHeight, releaseStickyHeader, resetStickyHeader, positionStickyHeader, activeHeader, lastScrollTop; /** * Determine which panel or section is currently expanded. * * @since 4.7.0 * @access private * * @param {wp.customize.Panel|wp.customize.Section} container Construct. * @returns {void} */ changeContainer = function( container ) { var newInstance = container, expandedSection = api.state( 'expandedSection' ).get(), expandedPanel = api.state( 'expandedPanel' ).get(), headerElement; // Release previously active header element. if ( activeHeader && activeHeader.element ) { releaseStickyHeader( activeHeader.element ); } if ( ! newInstance ) { if ( ! expandedSection && expandedPanel && expandedPanel.contentContainer ) { newInstance = expandedPanel; } else if ( ! expandedPanel && expandedSection && expandedSection.contentContainer ) { newInstance = expandedSection; } else { activeHeader = false; return; } } headerElement = newInstance.contentContainer.find( '.customize-section-title, .panel-meta' ).first(); if ( headerElement.length ) { activeHeader = { instance: newInstance, element: headerElement, parent: headerElement.closest( '.customize-pane-child' ), height: getHeaderHeight( headerElement ) }; if ( expandedSection ) { resetStickyHeader( activeHeader.element, activeHeader.parent ); } } else { activeHeader = false; } }; api.state( 'expandedSection' ).bind( changeContainer ); api.state( 'expandedPanel' ).bind( changeContainer ); // Throttled scroll event handler. parentContainer.on( 'scroll', _.throttle( function() { if ( ! activeHeader ) { return; } var scrollTop = parentContainer.scrollTop(), isScrollingUp = ( lastScrollTop ) ? scrollTop <= lastScrollTop : true; lastScrollTop = scrollTop; positionStickyHeader( activeHeader, scrollTop, isScrollingUp ); }, 8 ) ); // Release header element if it is sticky. releaseStickyHeader = function( headerElement ) { if ( ! headerElement.hasClass( 'is-sticky' ) ) { return; } headerElement .removeClass( 'is-sticky' ) .addClass( 'maybe-sticky is-in-view' ) .css( 'top', parentContainer.scrollTop() + 'px' ); }; // Reset position of the sticky header. resetStickyHeader = function( headerElement, headerParent ) { headerElement .removeClass( 'maybe-sticky is-in-view' ) .css( { width: '', top: '' } ); headerParent.css( 'padding-top', '' ); }; /** * Get header height. * * @since 4.7.0 * @access private * * @param {jQuery} headerElement Header element. * @returns {number} Height. */ getHeaderHeight = function( headerElement ) { var height = headerElement.data( 'height' ); if ( ! height ) { height = headerElement.outerHeight(); headerElement.data( 'height', height ); } return height; }; /** * Reposition header on throttled `scroll` event. * * @since 4.7.0 * @access private * * @param {object} header Header. * @param {number} scrollTop Scroll top. * @param {boolean} isScrollingUp Is scrolling up? * @returns {void} */ positionStickyHeader = function( header, scrollTop, isScrollingUp ) { var headerElement = header.element, headerParent = header.parent, headerHeight = header.height, headerTop = parseInt( headerElement.css( 'top' ), 10 ), maybeSticky = headerElement.hasClass( 'maybe-sticky' ), isSticky = headerElement.hasClass( 'is-sticky' ), isInView = headerElement.hasClass( 'is-in-view' ); // When scrolling down, gradually hide sticky header. if ( ! isScrollingUp ) { if ( isSticky ) { headerTop = scrollTop; headerElement .removeClass( 'is-sticky' ) .css( { top: headerTop + 'px', width: '' } ); } if ( isInView && scrollTop > headerTop + headerHeight ) { headerElement.removeClass( 'is-in-view' ); headerParent.css( 'padding-top', '' ); } return; } // Scrolling up. if ( ! maybeSticky && scrollTop >= headerHeight ) { maybeSticky = true; headerElement.addClass( 'maybe-sticky' ); } else if ( 0 === scrollTop ) { // Reset header in base position. headerElement .removeClass( 'maybe-sticky is-in-view is-sticky' ) .css( { top: '', width: '' } ); headerParent.css( 'padding-top', '' ); return; } if ( isInView && ! isSticky ) { // Header is in the view but is not yet sticky. if ( headerTop >= scrollTop ) { // Header is fully visible. headerElement .addClass( 'is-sticky' ) .css( { top: '', width: headerParent.outerWidth() + 'px' } ); } } else if ( maybeSticky && ! isInView ) { // Header is out of the view. headerElement .addClass( 'is-in-view' ) .css( 'top', ( scrollTop - headerHeight ) + 'px' ); headerParent.css( 'padding-top', headerHeight + 'px' ); } }; }()); // Previewed device bindings. api.previewedDevice = new api.Value(); // Set the default device. api.bind( 'ready', function() { _.find( api.settings.previewableDevices, function( value, key ) { if ( true === value['default'] ) { api.previewedDevice.set( key ); return true; } } ); } ); // Set the toggled device. footerActions.find( '.devices button' ).on( 'click', function( event ) { api.previewedDevice.set( $( event.currentTarget ).data( 'device' ) ); }); // Bind device changes. api.previewedDevice.bind( function( newDevice ) { var overlay = $( '.wp-full-overlay' ), devices = ''; footerActions.find( '.devices button' ) .removeClass( 'active' ) .attr( 'aria-pressed', false ); footerActions.find( '.devices .preview-' + newDevice ) .addClass( 'active' ) .attr( 'aria-pressed', true ); $.each( api.settings.previewableDevices, function( device ) { devices += ' preview-' + device; } ); overlay .removeClass( devices ) .addClass( 'preview-' + newDevice ); } ); // Bind site title display to the corresponding field. if ( title.length ) { api( 'blogname', function( setting ) { var updateTitle = function() { title.text( $.trim( setting() ) || api.l10n.untitledBlogName ); }; setting.bind( updateTitle ); updateTitle(); } ); } /* * Create a postMessage connection with a parent frame, * in case the Customizer frame was opened with the Customize loader. * * @see wp.customize.Loader */ 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() { closeBtn.on( 'click.customize-controls-close', function( event ) { event.preventDefault(); parent.send( 'close' ); }); }); // Prompt user with AYS dialog if leaving the Customizer with unsaved changes $( window ).on( 'beforeunload.customize-confirm', function () { if ( ! api.state( 'saved' )() ) { setTimeout( function() { overlay.removeClass( 'customize-loading' ); }, 1 ); return api.l10n.saveAlert; } } ); // Pass events through to the parent. $.each( [ 'saved', 'change' ], function ( i, event ) { api.bind( event, function() { parent.send( event ); }); } ); // Pass titles to the parent api.bind( 'title', function( newTitle ) { parent.send( 'title', newTitle ); }); parent.send( 'changeset-uuid', api.settings.changeset.uuid ); // Initialize the connection with the parent frame. parent.send( 'ready' ); // Control visibility for default controls $.each({ 'background_image': { controls: [ 'background_preset', 'background_position', 'background_size', 'background_repeat', '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 ); }); }); }); }); api.control( 'background_preset', function( control ) { var visibility, defaultValues, values, toggleVisibility, updateSettings, preset; visibility = { // position, size, repeat, attachment 'default': [ false, false, false, false ], 'fill': [ true, false, false, false ], 'fit': [ true, false, true, false ], 'repeat': [ true, false, false, true ], 'custom': [ true, true, true, true ] }; defaultValues = [ _wpCustomizeBackground.defaults['default-position-x'], _wpCustomizeBackground.defaults['default-position-y'], _wpCustomizeBackground.defaults['default-size'], _wpCustomizeBackground.defaults['default-repeat'], _wpCustomizeBackground.defaults['default-attachment'] ]; values = { // position_x, position_y, size, repeat, attachment 'default': defaultValues, 'fill': [ 'left', 'top', 'cover', 'no-repeat', 'fixed' ], 'fit': [ 'left', 'top', 'contain', 'no-repeat', 'fixed' ], 'repeat': [ 'left', 'top', 'auto', 'repeat', 'scroll' ] }; // @todo These should actually toggle the active state, but without the preview overriding the state in data.activeControls. toggleVisibility = function( preset ) { _.each( [ 'background_position', 'background_size', 'background_repeat', 'background_attachment' ], function( controlId, i ) { var control = api.control( controlId ); if ( control ) { control.container.toggle( visibility[ preset ][ i ] ); } } ); }; updateSettings = function( preset ) { _.each( [ 'background_position_x', 'background_position_y', 'background_size', 'background_repeat', 'background_attachment' ], function( settingId, i ) { var setting = api( settingId ); if ( setting ) { setting.set( values[ preset ][ i ] ); } } ); }; preset = control.setting.get(); toggleVisibility( preset ); control.setting.bind( 'change', function( preset ) { toggleVisibility( preset ); if ( 'custom' !== preset ) { updateSettings( preset ); } } ); } ); api.control( 'background_repeat', function( control ) { control.elements[0].unsync( api( 'background_repeat' ) ); control.element = new api.Element( control.container.find( 'input' ) ); control.element.set( 'no-repeat' !== control.setting() ); control.element.bind( function( to ) { control.setting.set( to ? 'repeat' : 'no-repeat' ); } ); control.setting.bind( function( to ) { control.element.set( 'no-repeat' !== to ); } ); } ); api.control( 'background_attachment', function( control ) { control.elements[0].unsync( api( 'background_attachment' ) ); control.element = new api.Element( control.container.find( 'input' ) ); control.element.set( 'fixed' !== control.setting() ); control.element.bind( function( to ) { control.setting.set( to ? 'scroll' : 'fixed' ); } ); control.setting.bind( function( to ) { control.element.set( 'fixed' !== to ); } ); } ); // 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 ); }); }); // Change previewed URL to the homepage when changing the page_on_front. api( 'show_on_front', 'page_on_front', function( showOnFront, pageOnFront ) { var updatePreviewUrl = function() { if ( showOnFront() === 'page' && parseInt( pageOnFront(), 10 ) > 0 ) { api.previewer.previewUrl.set( api.settings.url.home ); } }; showOnFront.bind( updatePreviewUrl ); pageOnFront.bind( updatePreviewUrl ); }); // Change the previewed URL to the selected page when changing the page_for_posts. api( 'page_for_posts', function( setting ) { setting.bind(function( pageId ) { pageId = parseInt( pageId, 10 ); if ( pageId > 0 ) { api.previewer.previewUrl.set( api.settings.url.home + '?page_id=' + pageId ); } }); }); // Allow tabs to be entered in Custom CSS textarea. api.control( 'custom_css', function setupCustomCssControl( control ) { control.deferred.embedded.done( function allowTabs() { var $textarea = control.container.find( 'textarea' ), textarea = $textarea[0]; $textarea.on( 'blur', function onBlur() { $textarea.data( 'next-tab-blurs', false ); } ); $textarea.on( 'keydown', function onKeydown( event ) { var selectionStart, selectionEnd, value, tabKeyCode = 9, escKeyCode = 27; if ( escKeyCode === event.keyCode ) { if ( ! $textarea.data( 'next-tab-blurs' ) ) { $textarea.data( 'next-tab-blurs', true ); event.stopPropagation(); // Prevent collapsing the section. } return; } // Short-circuit if tab key is not being pressed or if a modifier key *is* being pressed. if ( tabKeyCode !== event.keyCode || event.ctrlKey || event.altKey || event.shiftKey ) { return; } // Prevent capturing Tab characters if Esc was pressed. if ( $textarea.data( 'next-tab-blurs' ) ) { return; } selectionStart = textarea.selectionStart; selectionEnd = textarea.selectionEnd; value = textarea.value; if ( selectionStart >= 0 ) { textarea.value = value.substring( 0, selectionStart ).concat( '\t', value.substring( selectionEnd ) ); $textarea.selectionStart = textarea.selectionEnd = selectionStart + 1; } event.stopPropagation(); event.preventDefault(); } ); } ); } ); // Toggle visibility of Header Video notice when active state change. api.control( 'header_video', function( headerVideoControl ) { headerVideoControl.deferred.embedded.done( function() { var toggleNotice = function() { var section = api.section( headerVideoControl.section() ), notice; if ( ! section ) { return; } notice = section.container.find( '.header-video-not-currently-previewable:first' ); if ( headerVideoControl.active.get() ) { notice.stop().slideUp( 'fast' ); } else { notice.stop().slideDown( 'fast' ); } }; toggleNotice(); headerVideoControl.active.bind( toggleNotice ); } ); } ); // Update the setting validities. api.previewer.bind( 'selective-refresh-setting-validities', function handleSelectiveRefreshedSettingValidities( settingValidities ) { api._handleSettingValidities( { settingValidities: settingValidities, focusInvalidControl: false } ); } ); // Focus on the control that is associated with the given setting. api.previewer.bind( 'focus-control-for-setting', function( settingId ) { var matchedControls = []; api.control.each( function( control ) { var settingIds = _.pluck( control.settings, 'id' ); if ( -1 !== _.indexOf( settingIds, settingId ) ) { matchedControls.push( control ); } } ); // Focus on the matched control with the lowest priority (appearing higher). if ( matchedControls.length ) { matchedControls.sort( function( a, b ) { return a.priority() - b.priority(); } ); matchedControls[0].focus(); } } ); // Refresh the preview when it requests. api.previewer.bind( 'refresh', function() { api.previewer.refresh(); }); // Update the edit shortcut visibility state. api.state( 'paneVisible' ).bind( function( isPaneVisible ) { var isMobileScreen; if ( window.matchMedia ) { isMobileScreen = window.matchMedia( 'screen and ( max-width: 640px )' ).matches; } else { isMobileScreen = $( window ).width() <= 640; } api.state( 'editShortcutVisibility' ).set( isPaneVisible || isMobileScreen ? 'visible' : 'hidden' ); } ); if ( window.matchMedia ) { window.matchMedia( 'screen and ( max-width: 640px )' ).addListener( function() { var state = api.state( 'paneVisible' ); state.callbacks.fireWith( state, [ state.get(), state.get() ] ); } ); } api.previewer.bind( 'edit-shortcut-visibility', function( visibility ) { api.state( 'editShortcutVisibility' ).set( visibility ); } ); api.state( 'editShortcutVisibility' ).bind( function( visibility ) { api.previewer.send( 'edit-shortcut-visibility', visibility ); } ); // Autosave changeset. ( function() { var timeoutId, updateChangesetWithReschedule, scheduleChangesetUpdate, updatePending = false; /** * Request changeset update and then re-schedule the next changeset update time. * * @since 4.7.0 * @private */ updateChangesetWithReschedule = function() { if ( ! updatePending ) { updatePending = true; api.requestChangesetUpdate().always( function() { updatePending = false; } ); } scheduleChangesetUpdate(); }; /** * Schedule changeset update. * * @since 4.7.0 * @private */ scheduleChangesetUpdate = function() { clearTimeout( timeoutId ); timeoutId = setTimeout( function() { updateChangesetWithReschedule(); }, api.settings.timeouts.changesetAutoSave ); }; // Start auto-save interval for updating changeset. scheduleChangesetUpdate(); // Save changeset when focus removed from window. $( window ).on( 'blur.wp-customize-changeset-update', function() { updateChangesetWithReschedule(); } ); // Save changeset before unloading window. $( window ).on( 'beforeunload.wp-customize-changeset-update', function() { updateChangesetWithReschedule(); } ); } ()); api.trigger( 'ready' ); }); })( wp, jQuery ); plugin-install.min.js 0000666 00000004347 15213733063 0010645 0 ustar 00 var tb_position;jQuery(document).ready(function(o){var e,n,i,a,l,r,d=o(".upload-view-toggle"),t=o(".wrap"),s=o(document.body);function c(){var t;a=o(":tabbable",i),l=e.find("#TB_closeWindowButton"),r=a.last(),(t=l.add(r)).off("keydown.wp-plugin-details"),t.on("keydown.wp-plugin-details",function(t){9===(t=t).which&&(r[0]!==t.target||t.shiftKey?l[0]===t.target&&t.shiftKey&&(t.preventDefault(),r.focus()):(t.preventDefault(),l.focus()))})}tb_position=function(){var t=o(window).width(),i=o(window).height()-(792<t?60:20),n=792<t?772:t-20;return(e=o("#TB_window")).length&&(e.width(n).height(i),o("#TB_iframeContent").width(n).height(i),e.css({"margin-left":"-"+parseInt(n/2,10)+"px"}),void 0!==document.body.style.maxWidth&&e.css({top:"30px","margin-top":"0"})),o("a.thickbox").each(function(){var t=o(this).attr("href");t&&(t=(t=t.replace(/&width=[0-9]+/g,"")).replace(/&height=[0-9]+/g,""),o(this).attr("href",t+"&width="+n+"&height="+i))})},o(window).resize(function(){tb_position()}),s.on("thickbox:iframe:loaded",e,function(){var t;t=e.find("#TB_iframeContent"),i=t.contents().find("body"),c(),l.focus(),o("#plugin-information-tabs a",i).on("click",function(){c()}),i.on("keydown",function(t){27===t.which&&tb_remove()})}).on("thickbox:removed",function(){n.focus()}),o(".thickbox.open-plugin-details-modal").on("click",function(t){var i=o(this).data("title")?plugininstallL10n.plugin_information+" "+o(this).data("title"):plugininstallL10n.plugin_modal_label;t.preventDefault(),t.stopPropagation(),n=o(this),tb_click.call(this),e.attr({role:"dialog","aria-label":plugininstallL10n.plugin_modal_label}),e.find("#TB_iframeContent").attr("title",i)}),o("#plugin-information-tabs a").click(function(t){var i=o(this).attr("name");t.preventDefault(),o("#plugin-information-tabs a.current").removeClass("current"),o(this).addClass("current"),"description"!==i&&o(window).width()<772?o("#plugin-information-content").find(".fyi").hide():o("#plugin-information-content").find(".fyi").show(),o("#section-holder div.section").hide(),o("#section-"+i).show()}),t.hasClass("plugin-install-tab-upload")||d.attr({role:"button","aria-expanded":"false"}).on("click",function(t){t.preventDefault(),s.toggleClass("show-upload-view"),d.attr("aria-expanded",s.hasClass("show-upload-view"))})}); revisions.js 0000666 00000101617 15213733063 0007140 0 ustar 00 /* global isRtl */ /** * @file Revisions interface functions, Backbone classes and * the revisions.php document.ready bootstrap. * */ window.wp = window.wp || {}; (function($) { var revisions; /** * Expose the module in window.wp.revisions. */ revisions = wp.revisions = { model: {}, view: {}, controller: {} }; // Link post revisions data served from the back end. revisions.settings = window._wpRevisionsSettings || {}; // For debugging revisions.debug = false; /** * wp.revisions.log * * A debugging utility for revisions. Works only when a * debug flag is on and the browser supports it. */ revisions.log = function() { if ( window.console && revisions.debug ) { window.console.log.apply( window.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() }); }; /** * ======================================================================== * 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.on( 'change:from', this.handleLocalChanges ); this.on( 'change:to', this.handleLocalChanges ); this.on( 'change:compareTwoMode', this.updateSliderSettings ); this.on( 'update:revisions', this.updateSliderSettings ); // Listen for changes to the hovered revision this.on( '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({}); /** * wp.revisions.model.Revisions * * A collection of post revisions. */ 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() { 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.postId = options.postId; this.requests = {}; }, model: revisions.model.Diff, ensure: function( id, context ) { var diff = this.get( id ), request = this.requests[ id ], deferred = $.Deferred(), ids = {}, from = id.split(':')[0], 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: this.postId }); var deferred = wp.ajax.send( options ), 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 ); } } }); /** * wp.revisions.model.FrameState * * The frame state. * * @see wp.revisions.view.Frame * * @param {object} attributes Model attributes - none are required. * @param {object} options Options for the model. * @param {revisions.model.Revisions} options.revisions A collection of revisions. */ revisions.model.FrameState = Backbone.Model.extend({ defaults: { loading: false, error: false, compareTwoMode: false }, initialize: function( attributes, options ) { var state = this.get( 'initialDiffState' ); _.bindAll( this, 'receiveDiff' ); this._debouncedEnsureDiff = _.debounce( this._ensureDiff, 200 ); this.revisions = options.revisions; this.diffs = new revisions.model.Diffs( [], { revisions: this.revisions, postId: this.get( 'postId' ) } ); // Set the initial diffs collection. this.diffs.set( this.get( '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 attributes. this.set( { to : this.revisions.get( state.to ), from : this.revisions.get( state.from ), compareTwoMode : state.compareTwoMode } ); // 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 ) { var toIndex = this.revisions.indexOf( this.get( 'to' ) ); // If we were on the first revision before switching to two-handled mode, // bump the 'to' position over one if ( value && 0 === toIndex ) { this.set({ from: this.revisions.at( toIndex ), to: this.revisions.at( toIndex + 1 ) }); } // When switching back to single-handled mode, reset 'from' model to // one position before the 'to' model if ( ! value && 0 !== toIndex ) { // '! value' means switching to single-handled mode this.set({ from: this.revisions.at( toIndex - 1 ), to: this.revisions.at( toIndex ) }); } }, 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() { 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 * ======================================================================== */ /** * wp.revisions.view.Frame * * Top level frame that orchestrates the revisions experience. * * @param {object} options The options hash for the view. * @param {revisions.model.FrameState} options.model The frame state model. */ 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') ); } }); /** * wp.revisions.view.Controls * * The controls view. * * 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 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, container = controls.$el.parent(), scrolled = controls.window.scrollTop(), 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() { // 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() { 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 otherDirection, 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() { 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 ) - sliderFrom, // Flipped for RTL - sliderFrom; 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 handles, 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') ) { 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() { $( 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. // Maintains the URL routes so browser URL matches state. revisions.Router = Backbone.Router.extend({ initialize: function( options ) { this.model = options.model; // 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, to = this.model.get('to').id; if ( this.model.get('compareTwoMode' ) ) { this.navigate( this.baseUrl( '?from=' + from + '&to=' + to ), { replace: true } ); } else { this.navigate( this.baseUrl( '?revision=' + to ), { replace: true } ); } }, handleRoute: function( a, b ) { var 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; } } }); /** * Initialize the revisions UI for revision.php. */ revisions.init = function() { var state; // Bail if the current page is not revision.php. if ( ! window.adminpage || 'revision-php' !== window.adminpage ) { return; } state = new revisions.model.FrameState({ initialDiffState: { // wp_localize_script doesn't stringifies ints, so cast them. to: parseInt( revisions.settings.to, 10 ), from: parseInt( revisions.settings.from, 10 ), // wp_localize_script does not allow for top-level booleans so do a comparator here. compareTwoMode: ( revisions.settings.compareTwoMode === '1' ) }, diffData: revisions.settings.diffData, baseUrl: revisions.settings.baseUrl, postId: parseInt( revisions.settings.postId, 10 ) }, { revisions: new revisions.model.Revisions( revisions.settings.revisionData ) }); revisions.view.frame = new revisions.view.Frame({ model: state }).render(); }; $( revisions.init ); }(jQuery)); edit-comments.js 0000666 00000065555 15213733063 0007701 0 ustar 00 /* global adminCommentsL10n, thousandsSeparator, list_args, QTags, ajaxurl, wpAjax */ var setCommentsList, theList, theExtraList, commentReply; (function($) { var getCount, updateCount, updateCountText, updatePending, updateApproved, updateHtmlTitle, updateDashboardText, adminTitle = document.title, isDashboard = $('#dashboard_right_now').length, titleDiv, titleRegEx; 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); }; updateApproved = function( diff, commentPostId ) { var postSelector = '.post-com-count-' + commentPostId, noClass = 'comment-count-no-comments', approvedClass = 'comment-count-approved', approved, noComments; updateCountText( 'span.approved-count', diff ); if ( ! commentPostId ) { return; } // cache selectors to not get dupes approved = $( 'span.' + approvedClass, postSelector ); noComments = $( 'span.' + noClass, postSelector ); approved.each(function() { var a = $(this), n = getCount(a) + diff; if ( n < 1 ) n = 0; if ( 0 === n ) { a.removeClass( approvedClass ).addClass( noClass ); } else { a.addClass( approvedClass ).removeClass( noClass ); } updateCount( a, n ); }); noComments.each(function() { var a = $(this); if ( diff > 0 ) { a.removeClass( noClass ).addClass( approvedClass ); } else { a.addClass( noClass ).removeClass( approvedClass ); } updateCount( a, diff ); }); }; updateCountText = function( selector, diff ) { $( selector ).each(function() { var a = $(this), n = getCount(a) + diff; if ( n < 1 ) { n = 0; } updateCount( a, n ); }); }; updateDashboardText = function ( response ) { if ( ! isDashboard || ! response || ! response.i18n_comments_text ) { return; } var rightNow = $( '#dashboard_right_now' ); $( '.comment-count a', rightNow ).text( response.i18n_comments_text ); $( '.comment-mod-count a', rightNow ).text( response.i18n_moderation_text ) .parent() [ response.in_moderation > 0 ? 'removeClass' : 'addClass' ]( 'hidden' ); }; updateHtmlTitle = function ( diff ) { var newTitle, regExMatch, titleCount, commentFrag; titleRegEx = titleRegEx || new RegExp( adminCommentsL10n.docTitleCommentsCount.replace( '%s', '\\([0-9' + thousandsSeparator + ']+\\)' ) + '?' ); // count funcs operate on a $'d element titleDiv = titleDiv || $( '<div />' ); newTitle = adminTitle; commentFrag = titleRegEx.exec( document.title ); if ( commentFrag ) { commentFrag = commentFrag[0]; titleDiv.html( commentFrag ); titleCount = getCount( titleDiv ) + diff; } else { titleDiv.html( 0 ); titleCount = diff; } if ( titleCount >= 1 ) { updateCount( titleDiv, titleCount ); regExMatch = titleRegEx.exec( document.title ); if ( regExMatch ) { newTitle = document.title.replace( regExMatch[0], adminCommentsL10n.docTitleCommentsCount.replace( '%s', titleDiv.text() ) + ' ' ); } } else { regExMatch = titleRegEx.exec( newTitle ); if ( regExMatch ) { newTitle = newTitle.replace( regExMatch[0], adminCommentsL10n.docTitleComments ); } } document.title = newTitle; }; updatePending = function( diff, commentPostId ) { var postSelector = '.post-com-count-' + commentPostId, noClass = 'comment-count-no-pending', noParentClass = 'post-com-count-no-pending', pendingClass = 'comment-count-pending', pending, noPending; if ( ! isDashboard ) { updateHtmlTitle( 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 ); }); if ( ! commentPostId ) { return; } // cache selectors to not get dupes pending = $( 'span.' + pendingClass, postSelector ); noPending = $( 'span.' + noClass, postSelector ); pending.each(function() { var a = $(this), n = getCount(a) + diff; if ( n < 1 ) n = 0; if ( 0 === n ) { a.parent().addClass( noParentClass ); a.removeClass( pendingClass ).addClass( noClass ); } else { a.parent().removeClass( noParentClass ); a.addClass( pendingClass ).removeClass( noClass ); } updateCount( a, n ); }); noPending.each(function() { var a = $(this); if ( diff > 0 ) { a.parent().removeClass( noParentClass ); a.removeClass( noClass ).addClass( pendingClass ); } else { a.parent().addClass( noParentClass ); a.addClass( noClass ).removeClass( pendingClass ); } updateCount( a, diff ); }); }; setCommentsList = function() { var totalInput, perPageInput, pageInput, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList, diff, lastConfidentTime = 0; totalInput = $('input[name="_total"]', '#comments-form'); perPageInput = $('input[name="_per_page"]', '#comments-form'); pageInput = $('input[name="_page"]', '#comments-form'); // 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() ); }; // this fires when viewing "All" dimAfter = function( r, settings ) { var editRow, replyID, replyButton, response, c = $( '#' + settings.element ); if ( true !== settings.parsed ) { response = settings.parsed.responses[0]; } 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( '.row-actions span.view' ).addClass( 'hidden' ).end() .find( 'div.comment_status' ).html( '0' ); } else { if ( settings.data.id == replyID ) replyButton.text(adminCommentsL10n.reply); c.find( '.row-actions span.view' ).removeClass( 'hidden' ).end() .find( 'div.comment_status' ).html( '1' ); } diff = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1; if ( response ) { updateDashboardText( response.supplemental ); updatePending( diff, response.supplemental.postId ); updateApproved( -1 * diff, response.supplemental.postId ); } else { updatePending( diff ); updateApproved( -1 * diff ); } }; // Send current total, page, per_page and url delBefore = function( settings, list ) { var note, id, el, n, h, a, author, action = false, wpListsData = $( settings.target ).attr( 'data-wp-lists' ); 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).first().clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside'); a.click(function( e ){ e.preventDefault(); e.stopPropagation(); // ticket #35904 list.wpList.del(this); $('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){ $(this).remove(); $('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show(); }); }); }); } return settings; }; // In admin-ajax.php, we send back the unix time stamp instead of 1 on success delAfter = function( r, settings ) { var total_items_i18n, total, animated, animatedCallback, response = true === settings.parsed ? {} : settings.parsed.responses[0], commentStatus = true === settings.parsed ? '' : response.supplemental.status, commentPostId = true === settings.parsed ? '' : response.supplemental.postId, newTotal = true === settings.parsed ? '' : response.supplemental, targetParent = $( settings.target ).parent(), commentRow = $('#' + settings.element), spamDiff, trashDiff, pendingDiff, approvedDiff, approved = commentRow.hasClass( 'approved' ), unapproved = commentRow.hasClass( 'unapproved' ), spammed = commentRow.hasClass( 'spam' ), trashed = commentRow.hasClass( 'trash' ), undoing = false; // ticket #35904 updateDashboardText( newTotal ); // the order of these checks is important // .unspam can also have .approve or .unapprove // .untrash can also have .approve or .unapprove if ( targetParent.is( 'span.undo' ) ) { // the comment was spammed if ( targetParent.hasClass( 'unspam' ) ) { spamDiff = -1; if ( 'trash' === commentStatus ) { trashDiff = 1; } else if ( '1' === commentStatus ) { approvedDiff = 1; } else if ( '0' === commentStatus ) { pendingDiff = 1; } // the comment was trashed } else if ( targetParent.hasClass( 'untrash' ) ) { trashDiff = -1; if ( 'spam' === commentStatus ) { spamDiff = 1; } else if ( '1' === commentStatus ) { approvedDiff = 1; } else if ( '0' === commentStatus ) { pendingDiff = 1; } } undoing = true; // user clicked "Spam" } else if ( targetParent.is( 'span.spam' ) ) { // the comment is currently approved if ( approved ) { approvedDiff = -1; // the comment is currently pending } else if ( unapproved ) { pendingDiff = -1; // the comment was in the trash } else if ( trashed ) { trashDiff = -1; } // you can't spam an item on the spam screen spamDiff = 1; // user clicked "Unspam" } else if ( targetParent.is( 'span.unspam' ) ) { if ( approved ) { pendingDiff = 1; } else if ( unapproved ) { approvedDiff = 1; } else if ( trashed ) { // the comment was previously approved if ( targetParent.hasClass( 'approve' ) ) { approvedDiff = 1; // the comment was previously pending } else if ( targetParent.hasClass( 'unapprove' ) ) { pendingDiff = 1; } } else if ( spammed ) { if ( targetParent.hasClass( 'approve' ) ) { approvedDiff = 1; } else if ( targetParent.hasClass( 'unapprove' ) ) { pendingDiff = 1; } } // you can Unspam an item on the spam screen spamDiff = -1; // user clicked "Trash" } else if ( targetParent.is( 'span.trash' ) ) { if ( approved ) { approvedDiff = -1; } else if ( unapproved ) { pendingDiff = -1; // the comment was in the spam queue } else if ( spammed ) { spamDiff = -1; } // you can't trash an item on the trash screen trashDiff = 1; // user clicked "Restore" } else if ( targetParent.is( 'span.untrash' ) ) { if ( approved ) { pendingDiff = 1; } else if ( unapproved ) { approvedDiff = 1; } else if ( trashed ) { if ( targetParent.hasClass( 'approve' ) ) { approvedDiff = 1; } else if ( targetParent.hasClass( 'unapprove' ) ) { pendingDiff = 1; } } // you can't go from trash to spam // you can untrash on the trash screen trashDiff = -1; // User clicked "Approve" } else if ( targetParent.is( 'span.approve:not(.unspam):not(.untrash)' ) ) { approvedDiff = 1; pendingDiff = -1; // User clicked "Unapprove" } else if ( targetParent.is( 'span.unapprove:not(.unspam):not(.untrash)' ) ) { approvedDiff = -1; pendingDiff = 1; // User clicked "Delete Permanently" } else if ( targetParent.is( 'span.delete' ) ) { if ( spammed ) { spamDiff = -1; } else if ( trashed ) { trashDiff = -1; } } if ( pendingDiff ) { updatePending( pendingDiff, commentPostId ); updateCountText( 'span.all-count', pendingDiff ); } if ( approvedDiff ) { updateApproved( approvedDiff, commentPostId ); updateCountText( 'span.all-count', approvedDiff ); } if ( spamDiff ) { updateCountText( 'span.spam-count', spamDiff ); } if ( trashDiff ) { updateCountText( 'span.trash-count', trashDiff ); } if ( ! isDashboard ) { 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 ) { if ( response.supplemental.total_items_i18n && lastConfidentTime < response.supplemental.time ) { total_items_i18n = response.supplemental.total_items_i18n || ''; if ( total_items_i18n ) { $('.displaying-num').text( total_items_i18n ); $('.total-pages').text( response.supplemental.total_pages_i18n ); $('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', response.supplemental.total_pages == $('.current-page').val()); } updateTotalCount( total, response.supplemental.time, true ); } else if ( response.supplemental.time ) { updateTotalCount( total, response.supplemental.time, false ); } } else { updateTotalCount( total, r, false ); } } if ( ! theExtraList || theExtraList.length === 0 || theExtraList.children().length === 0 || undoing ) { return; } theList.get(0).wpList.add( theExtraList.children( ':eq(0):not(.no-items)' ).remove().clone() ); refillTheExtraList(); animated = $( ':animated', '#the-comment-list' ); animatedCallback = function () { if ( ! $( '#the-comment-list tr:visible' ).length ) { theList.get(0).wpList.add( theExtraList.find( '.no-items' ).clone() ); } }; if ( animated.length ) { animated.promise().done( animatedCallback ); } else { animatedCallback(); } }; 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 : '', originalContent : '', init : function() { var row = $('#replyrow'); $('a.cancel', row).click(function() { return commentReply.revert(); }); $('a.save', row).click(function() { return commentReply.send(); }); $( 'input#author-name, 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(){ 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 ( 'none' !== $( el ).css( 'display' ) && ( $( '#replyrow' ).parent().is('#com-reply') || window.confirm( adminCommentsL10n.warnQuickEdit ) ) ) { $( 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).empty().hide(); $( '.spinner', replyrow ).removeClass( 'is-active' ); this.cid = ''; this.originalContent = ''; }, open : function(comment_id, post_id, action) { var editRow, rowData, act, replyButton, editHeight, t = this, c = $('#comment-' + comment_id), h = c.height(), colspanVal = 0; if ( ! this.discardCommentChanges() ) { return false; } 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'; t.originalContent = $('textarea.comment', rowData).val(); colspanVal = $( '> th:visible, > td:visible', c ).length; // Make sure it's actually a table and there's a `colspan` value to apply. if ( editRow.hasClass( 'inline-edit-row' ) && 0 !== colspanVal ) { $( 'td', editRow ).attr( 'colspan', colspanVal ); } $('#action', editRow).val(act); $('#comment_post_ID', editRow).val(post_id); $('#comment_ID', editRow).val(comment_id); if ( action == 'edit' ) { $( '#author-name', 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, #editlegend, #savebtn', editRow ).show(); $('#replyhead, #replybtn, #addhead, #addbtn', editRow).hide(); if ( h > 120 ) { // Limit the maximum height when editing very long comments to make it more manageable. // The textarea is resizable in most browsers, so the user can adjust it if needed. editHeight = h > 500 ? 500 : h; $('#replycontent', editRow).css('height', editHeight + 'px'); } c.after( editRow ).fadeOut('fast', function(){ $('#replyrow').fadeIn(300, function(){ $(this).show(); }); }); } else if ( action == 'add' ) { $('#addhead, #addbtn', editRow).show(); $( '#replyhead, #replybtn, #edithead, #editlegend, #savebtn', editRow ) .hide(); $('#the-comment-list').prepend(editRow); $('#replyrow').fadeIn(300); } else { replyButton = $('#replybtn', editRow); $( '#edithead, #editlegend, #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 || window.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' ).addClass( 'is-active' ); $('#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]; id = '#comment-' + r.id; if ( 'edit-comment' == t.act ) $(id).remove(); if ( r.supplemental.parent_approved ) { pid = $('#comment-' + r.supplemental.parent_approved); updatePending( -1, r.supplemental.parent_post_id ); if ( this.comments_listing == 'moderated' ) { pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){ pid.fadeOut(); }); return; } } if ( r.supplemental.i18n_comments_text ) { if ( isDashboard ) { updateDashboardText( r.supplemental ); } else { updateApproved( 1, r.supplemental.parent_post_id ); updateCountText( 'span.all-count', 1 ); } } c = $.trim(r.data); // Trim leading whitespaces $(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' ).removeClass( 'is-active' ); 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(); }); }, /** * Alert the user if they have unsaved changes on a comment that will be * lost if they proceed. * * @returns {boolean} */ discardCommentChanges: function() { var editRow = $( '#replyrow' ); if ( this.originalContent === $( '#replycontent', editRow ).val() ) { return true; } return window.confirm( adminCommentsL10n.warnCommentChanges ); } }; $(document).ready(function(){ var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk; setCommentsList(); commentReply.init(); $(document).on( 'click', 'span.delete a.delete', function( e ) { e.preventDefault(); }); 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() { $('#cb-select-all-1').data( 'wp-toggle', 1 ).trigger( 'click' ).removeData( 'wp-toggle' ); }; 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'), hotkeys_opts: { disableInInput: true, type: 'keypress', noDisable: '.check-column input[type="checkbox"]' }, cycle_expr: '#the-comment-list tr', start_row_index: 0 } ); } // Quick Edit and Reply have an inline comment editor. $( '#the-comment-list' ).on( 'click', '.comment-inline', function (e) { e.preventDefault(); var $el = $( this ), action = 'replyto'; if ( 'undefined' !== typeof $el.data( 'action' ) ) { action = $el.data( 'action' ); } commentReply.open( $el.data( 'commentId' ), $el.data( 'postId' ), action ); } ); }); })(jQuery); plugin-install.js 0000666 00000014172 15213733063 0010060 0 ustar 00 /* global plugininstallL10n, tb_click, tb_remove */ /** * Functionality for the plugin install screens. */ var tb_position; jQuery( document ).ready( function( $ ) { var tbWindow, $focusedBefore, $iframeBody, $tabbables, $firstTabbable, $lastTabbable, $uploadViewToggle = $( '.upload-view-toggle' ), $wrap = $ ( '.wrap' ), $body = $( document.body ); tb_position = function() { var width = $( window ).width(), H = $( window ).height() - ( ( 792 < width ) ? 60 : 20 ), W = ( 792 < width ) ? 772 : width - 20; tbWindow = $( '#TB_window' ); if ( tbWindow.length ) { tbWindow.width( W ).height( H ); $( '#TB_iframeContent' ).width( W ).height( H ); tbWindow.css({ 'margin-left': '-' + parseInt( ( W / 2 ), 10 ) + 'px' }); if ( typeof document.body.style.maxWidth !== 'undefined' ) { tbWindow.css({ 'top': '30px', '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 + '&height=' + ( H ) ); }); }; $( window ).resize( function() { tb_position(); }); /* * Custom events: when a Thickbox iframe has loaded and when the Thickbox * modal gets removed from the DOM. */ $body .on( 'thickbox:iframe:loaded', tbWindow, function() { iframeLoaded(); }) .on( 'thickbox:removed', function() { // Set focus back to the element that opened the modal dialog. // Note: IE 8 would need this wrapped in a fake setTimeout `0`. $focusedBefore.focus(); }); function iframeLoaded() { var $iframe = tbWindow.find( '#TB_iframeContent' ); // Get the iframe body. $iframeBody = $iframe.contents().find( 'body' ); // Get the tabbable elements and handle the keydown event on first load. handleTabbables(); // Set initial focus on the "Close" button. $firstTabbable.focus(); /* * When the "Install" button is disabled (e.g. the Plugin is already installed) * then we can't predict where the last focusable element is. We need to get * the tabbable elements and handle the keydown event again and again, * each time the active tab panel changes. */ $( '#plugin-information-tabs a', $iframeBody ).on( 'click', function() { handleTabbables(); }); // Close the modal when pressing Escape. $iframeBody.on( 'keydown', function( event ) { if ( 27 !== event.which ) { return; } tb_remove(); }); } /* * Get the tabbable elements and detach/attach the keydown event. * Called after the iframe has fully loaded so we have all the elements we need. * Called again each time a Tab gets clicked. * @todo Consider to implement a WordPress general utility for this and don't use jQuery UI. */ function handleTabbables() { var $firstAndLast; // Get all the tabbable elements. $tabbables = $( ':tabbable', $iframeBody ); // Our first tabbable element is always the "Close" button. $firstTabbable = tbWindow.find( '#TB_closeWindowButton' ); // Get the last tabbable element. $lastTabbable = $tabbables.last(); // Make a jQuery collection. $firstAndLast = $firstTabbable.add( $lastTabbable ); // Detach any previously attached keydown event. $firstAndLast.off( 'keydown.wp-plugin-details' ); // Attach again the keydown event on the first and last focusable elements. $firstAndLast.on( 'keydown.wp-plugin-details', function( event ) { constrainTabbing( event ); }); } // Constrain tabbing within the plugin modal dialog. function constrainTabbing( event ) { if ( 9 !== event.which ) { return; } if ( $lastTabbable[0] === event.target && ! event.shiftKey ) { event.preventDefault(); $firstTabbable.focus(); } else if ( $firstTabbable[0] === event.target && event.shiftKey ) { event.preventDefault(); $lastTabbable.focus(); } } // Open the Plugin details modal. $( '.thickbox.open-plugin-details-modal' ).on( 'click', function( e ) { // The `data-title` attribute is used only in the Plugin screens. var title = $( this ).data( 'title' ) ? plugininstallL10n.plugin_information + ' ' + $( this ).data( 'title' ) : plugininstallL10n.plugin_modal_label; e.preventDefault(); e.stopPropagation(); // Store the element that has focus before opening the modal dialog, i.e. the control which opens it. $focusedBefore = $( this ); tb_click.call(this); // Set ARIA role and ARIA label. tbWindow.attr({ 'role': 'dialog', 'aria-label': plugininstallL10n.plugin_modal_label }); // Set title attribute on the iframe. tbWindow.find( '#TB_iframeContent' ).attr( 'title', title ); }); /* Plugin install related JS */ $( '#plugin-information-tabs a' ).click( function( event ) { var tab = $( this ).attr( 'name' ); event.preventDefault(); // Flip the tab $( '#plugin-information-tabs a.current' ).removeClass( 'current' ); $( this ).addClass( 'current' ); // Only show the fyi box in the description section, on smaller screen, where it's otherwise always displayed at the top. if ( 'description' !== tab && $( window ).width() < 772 ) { $( '#plugin-information-content' ).find( '.fyi' ).hide(); } else { $( '#plugin-information-content' ).find( '.fyi' ).show(); } // Flip the content. $( '#section-holder div.section' ).hide(); // Hide 'em all. $( '#section-' + tab ).show(); }); /* * When a user presses the "Upload Plugin" button, show the upload form in place * rather than sending them to the devoted upload plugin page. * The `?tab=upload` page still exists for no-js support and for plugins that * might access it directly. When we're in this page, let the link behave * like a link. Otherwise we're in the normal plugin installer pages and the * link should behave like a toggle button. */ if ( ! $wrap.hasClass( 'plugin-install-tab-upload' ) ) { $uploadViewToggle .attr({ role: 'button', 'aria-expanded': 'false' }) .on( 'click', function( event ) { event.preventDefault(); $body.toggleClass( 'show-upload-view' ); $uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) ); }); } }); password-strength-meter.js 0000666 00000004547 15213733063 0011733 0 ustar 00 /* global zxcvbn */ window.wp = window.wp || {}; var passwordStrength; (function($){ wp.passwordStrength = { /** * Determine the strength of a given password * * @param string password1 The password * @param array blacklist An array of words that will lower the entropy of the password * @param string password2 The confirmed password */ meter : function( password1, blacklist, password2 ) { if ( ! $.isArray( blacklist ) ) blacklist = [ blacklist.toString() ]; if (password1 != password2 && password2 && password2.length > 0) return 5; if ( 'undefined' === typeof window.zxcvbn ) { // Password strength unknown. return -1; } var result = zxcvbn( password1, blacklist ); return result.score; }, /** * Builds an array of data that should be penalized, because it would lower the entropy of a password if it were used * * @return array The array of data to be blacklisted */ userInputBlacklist : function() { var i, userInputFieldsLength, rawValuesLength, currentField, rawValues = [], blacklist = [], userInputFields = [ 'user_login', 'first_name', 'last_name', 'nickname', 'display_name', 'email', 'url', 'description', 'weblog_title', 'admin_email' ]; // Collect all the strings we want to blacklist rawValues.push( document.title ); rawValues.push( document.URL ); userInputFieldsLength = userInputFields.length; for ( i = 0; i < userInputFieldsLength; i++ ) { currentField = $( '#' + userInputFields[ i ] ); if ( 0 === currentField.length ) { continue; } rawValues.push( currentField[0].defaultValue ); rawValues.push( currentField.val() ); } // Strip out non-alphanumeric characters and convert each word to an individual entry rawValuesLength = rawValues.length; for ( i = 0; i < rawValuesLength; i++ ) { if ( rawValues[ i ] ) { blacklist = blacklist.concat( rawValues[ i ].replace( /\W/g, ' ' ).split( ' ' ) ); } } // Remove empty values, short words, and duplicates. Short words are likely to cause many false positives. blacklist = $.grep( blacklist, function( value, key ) { if ( '' === value || 4 > value.length ) { return false; } return $.inArray( value, blacklist ) === key; }); return blacklist; } }; // Back-compat. passwordStrength = wp.passwordStrength.meter; })(jQuery); user-suggest.min.js 0000666 00000001221 15213733063 0010324 0 ustar 00 !function(i){var n="undefined"!=typeof current_site_id?"&site_id="+current_site_id:"";i(document).ready(function(){var a={offset:"0, -1"};"undefined"!=typeof isRtl&&isRtl&&(a.my="right top",a.at="right bottom"),i(".wp-suggest-user").each(function(){var e=i(this),t=void 0!==e.data("autocompleteType")?e.data("autocompleteType"):"add",o=void 0!==e.data("autocompleteField")?e.data("autocompleteField"):"user_login";e.autocomplete({source:ajaxurl+"?action=autocomplete-user&autocomplete_type="+t+"&autocomplete_field="+o+n,delay:500,minLength:2,position:a,open:function(){i(this).addClass("open")},close:function(){i(this).removeClass("open")}})})})}(jQuery); color-picker.js 0000666 00000012537 15213733063 0007512 0 ustar 00 /* global wpColorPickerL10n */ ( function( $, undef ){ var ColorPicker, // html stuff _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 ColorPicker = { options: { defaultColor: false, change: false, clear: false, hide: true, palettes: true, width: 255, mode: 'hsv', type: 'full', slider: 'horizontal' }, _createHueOnly: function() { var self = this, el = self.element, color; // hide input el.hide(); // max saturated color for hue to be obvious color = 'hsl(' + el.val() + ', 100, 50)'; el.iris( { mode: 'hsl', type: 'hue', hide: false, color: color, change: function( event, ui ) { if ( $.isFunction( self.options.change ) ) { self.options.change.call( this, event, ui ); } }, width: self.options.width, slider: self.options.slider } ); }, _create: function() { // bail early for unsupported Iris. if ( ! $.support.iris ) { return; } var self = this, el = self.element; $.extend( self.options, el.data() ); // hue-only gets created differently if ( self.options.type === 'hue' ) { return self._createHueOnly(); } // keep close bound so it can be attached to a body listener self.close = $.proxy( self.close, self ); 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: self.options.hide, width: self.options.width, mode: self.options.mode, 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; // prevent any clicks inside this widget from leaking to the top and closing it self.wrap.on( 'click.wpcolorpicker', function( event ) { event.stopPropagation(); }); self.toggler.click( function(){ if ( self.toggler.hasClass( 'wp-picker-open' ) ) { self.close(); } else { self.open(); } }); 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( event ) { if ( event.keyCode === 13 || event.keyCode === 32 ) { event.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(); } }); }, open: function() { this.element.show().iris( 'toggle' ).focus(); this.button.removeClass( 'hidden' ); this.wrap.addClass( 'wp-picker-active' ); this.toggler.addClass( 'wp-picker-open' ); $( 'body' ).trigger( 'click.wpcolorpicker' ).on( 'click.wpcolorpicker', this.close ); }, close: function() { this.element.hide().iris( 'toggle' ); this.button.addClass( 'hidden' ); this.wrap.removeClass( 'wp-picker-active' ); this.toggler.removeClass( 'wp-picker-open' ); $( 'body' ).off( 'click.wpcolorpicker', this.close ); }, // $("#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 ) ); link.js 0000666 00000004307 15213733063 0006052 0 ustar 00 /* global postboxes, deleteUserSetting, setUserSetting, getUserSetting */ jQuery(document).ready( function($) { var newCat, noSyncChecks = false, syncChecks, catAddAfter; $('#link_name').focus(); // postboxes postboxes.add_postbox_toggles('link'); // category tabs $('#category-tabs a').click(function(){ var t = $(this).attr('href'); $(this).parent().addClass('tabs').siblings('li').removeClass('tabs'); $('.tabs-panel').hide(); $(t).show(); if ( '#categories-all' == t ) deleteUserSetting('cats'); else setUserSetting('cats','pop'); return false; }); if ( getUserSetting('cats') ) $('#category-tabs a[href="#categories-pop"]').click(); // Ajax Cat newCat = $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ); } ); $('#link-category-add-submit').click( function() { newCat.focus(); } ); syncChecks = function() { if ( noSyncChecks ) return; noSyncChecks = true; var th = $(this), c = th.is(':checked'), id = th.val().toString(); $('#in-link-category-' + id + ', #in-popular-link_category-' + id).prop( 'checked', c ); noSyncChecks = false; }; catAddAfter = function( r, s ) { $(s.what + ' response_data', r).each( function() { var t = $($(this).text()); t.find( 'label' ).each( function() { var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name = $.trim( th.text() ), o; $('#' + id).change( syncChecks ); o = $( '<option value="' + parseInt( val, 10 ) + '"></option>' ).text( name ); } ); } ); }; $('#categorychecklist').wpList( { alt: '', what: 'link-category', response: 'category-ajax-response', addAfter: catAddAfter } ); $('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');}); $('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');}); if ( 'pop' == getUserSetting('cats') ) $('a[href="#categories-pop"]').click(); $('#category-add-toggle').click( function() { $(this).parents('div:first').toggleClass( 'wp-hidden-children' ); $('#category-tabs a[href="#categories-all"]').click(); $('#newcategory').focus(); return false; } ); $('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change(); }); widgets.min.js 0000666 00000023301 15213733063 0007340 0 ustar 00 var wpWidgets;!function(c){var g=c(document);wpWidgets={hoveredSidebar:null,init:function(){var r,o,s=this,i=c(".widgets-chooser"),d=i.find(".widgets-chooser-sidebars"),e=c("div.widgets-sortables"),l=!("undefined"==typeof isRtl||!isRtl);c("#widgets-right .sidebar-name").click(function(){var e=c(this),i=e.closest(".widgets-holder-wrap");i.hasClass("closed")?(i.removeClass("closed"),e.parent().sortable("refresh")):i.addClass("closed"),g.triggerHandler("wp-pin-menu")}),c("#widgets-left .sidebar-name").click(function(){c(this).closest(".widgets-holder-wrap").toggleClass("closed"),g.triggerHandler("wp-pin-menu")}),c(document.body).bind("click.widgets-toggle",function(e){var i,t,s,d,n=c(e.target),a={"z-index":100};n.parents(".widget-top").length&&!n.parents("#available-widgets").length?(t=(i=n.closest("div.widget")).children(".widget-inside"),s=parseInt(i.find("input.widget-width").val(),10),d=i.parent().width(),t.is(":hidden")?(250<s&&d<s+30&&i.closest("div.widgets-sortables").length&&(a[i.closest("div.widget-liquid-right").length?l?"margin-right":"margin-left":l?"margin-left":"margin-right"]=d-(s+30)+"px",i.css(a)),i.addClass("open"),t.slideDown("fast")):t.slideUp("fast",function(){i.attr("style",""),i.removeClass("open")}),e.preventDefault()):n.hasClass("widget-control-save")?(wpWidgets.save(n.closest("div.widget"),0,1,0),e.preventDefault()):n.hasClass("widget-control-remove")?(wpWidgets.save(n.closest("div.widget"),1,1,0),e.preventDefault()):n.hasClass("widget-control-close")?((i=n.closest("div.widget")).removeClass("open"),wpWidgets.close(i),e.preventDefault()):"inactive-widgets-control-remove"===n.attr("id")&&(wpWidgets.removeInactiveWidgets(),e.preventDefault())}),e.children(".widget").each(function(){var e=c(this);wpWidgets.appendTitle(this),e.find("p.widget-error").length&&e.find("a.widget-action").trigger("click")}),c("#widget-list").children(".widget").draggable({connectToSortable:"div.widgets-sortables",handle:"> .widget-top > .widget-title",distance:2,helper:"clone",zIndex:100,containment:"#wpwrap",refreshPositions:!0,start:function(e,i){var t=c(this).find(".widgets-chooser");i.helper.find("div.widget-description").hide(),o=this.id,t.length&&(c("#wpbody-content").append(t.hide()),i.helper.find(".widgets-chooser").remove(),s.clearWidgetSelection())},stop:function(){r&&c(r).hide(),r=""}}),e.droppable({tolerance:"intersect",over:function(e){var i=c(e.target).parent();wpWidgets.hoveredSidebar&&!i.is(wpWidgets.hoveredSidebar)&&wpWidgets.closeSidebar(e),i.hasClass("closed")&&(wpWidgets.hoveredSidebar=i).removeClass("closed"),c(this).sortable("refresh")},out:function(e){wpWidgets.hoveredSidebar&&wpWidgets.closeSidebar(e)}}),e.sortable({placeholder:"widget-placeholder",items:"> .widget",handle:"> .widget-top > .widget-title",cursor:"move",distance:2,containment:"#wpwrap",tolerance:"pointer",refreshPositions:!0,start:function(e,i){var t=c(this),s=t.parent(),d=i.item.children(".widget-inside");"block"===d.css("display")&&(i.item.removeClass("open"),d.hide(),c(this).sortable("refreshPositions")),s.hasClass("closed")||(i=i.item.hasClass("ui-draggable")?t.height():1+t.height(),t.css("min-height",i+"px"))},stop:function(e,i){var t,s,d,n=i.item,a=o;if(wpWidgets.hoveredSidebar=null,n.hasClass("deleting"))return wpWidgets.save(n,1,0,1),void n.remove();t=n.find("input.add_new").val(),s=n.find("input.multi_number").val(),n.attr("style","").removeClass("ui-draggable"),o="",t&&("multi"===t?(n.html(n.html().replace(/<[^<>]+>/g,function(e){return e.replace(/__i__|%i%/g,s)})),n.attr("id",a.replace("__i__",s)),s++,c("div#"+a).find("input.multi_number").val(s)):"single"===t&&(n.attr("id","new-"+a),r="div#"+a),wpWidgets.save(n,0,0,1),n.find("input.add_new").val(""),g.trigger("widget-added",[n])),(d=n.parent()).parent().hasClass("closed")&&(d.parent().removeClass("closed"),1<(i=d.children(".widget")).length&&(a=i.get(0),i=n.get(0),a.id&&i.id&&a.id!==i.id&&c(a).before(n))),t?n.find("a.widget-action").trigger("click"):wpWidgets.saveOrder(d.attr("id"))},activate:function(){c(this).parent().addClass("widget-hover")},deactivate:function(){c(this).css("min-height","").parent().removeClass("widget-hover")},receive:function(e,i){i=c(i.sender);-1<this.id.indexOf("orphaned_widgets")?i.sortable("cancel"):-1<i.attr("id").indexOf("orphaned_widgets")&&!i.children(".widget").length&&i.parents(".orphan-sidebar").slideUp(400,function(){c(this).remove()})}}).sortable("option","connectWith","div.widgets-sortables"),c("#available-widgets").droppable({tolerance:"pointer",accept:function(e){return"widget-list"!==c(e).parent().attr("id")},drop:function(e,i){i.draggable.addClass("deleting"),c("#removing-widget").hide().children("span").empty()},over:function(e,i){i.draggable.addClass("deleting"),c("div.widget-placeholder").hide(),i.draggable.hasClass("ui-sortable-helper")&&c("#removing-widget").show().children("span").html(i.draggable.find("div.widget-title").children("h3").html())},out:function(e,i){i.draggable.removeClass("deleting"),c("div.widget-placeholder").show(),c("#removing-widget").hide().children("span").empty()}}),c("#widgets-right .widgets-holder-wrap").each(function(e,i){var t=c(i),i=t.find(".sidebar-name h2").text(),t=t.find(".widgets-sortables").attr("id"),i=c('<li tabindex="0">').text(c.trim(i));0===e&&i.addClass("widgets-chooser-selected"),d.append(i),i.data("sidebarId",t)}),c("#available-widgets .widget .widget-title").on("click.widgets-chooser",function(){var e=c(this).closest(".widget");e.hasClass("widget-in-question")||c("#widgets-left").hasClass("chooser")?s.closeChooser():(s.clearWidgetSelection(),c("#widgets-left").addClass("chooser"),e.addClass("widget-in-question").children(".widget-description").after(i),i.slideDown(300,function(){d.find(".widgets-chooser-selected").focus()}),d.find("li").on("focusin.widgets-chooser",function(){d.find(".widgets-chooser-selected").removeClass("widgets-chooser-selected"),c(this).addClass("widgets-chooser-selected")}))}),i.on("click.widgets-chooser",function(e){e=c(e.target);e.hasClass("button-primary")?(s.addWidget(i),s.closeChooser()):e.hasClass("widgets-chooser-cancel")&&s.closeChooser()}).on("keyup.widgets-chooser",function(e){e.which===c.ui.keyCode.ENTER?(c(e.target).hasClass("widgets-chooser-cancel")||s.addWidget(i),s.closeChooser()):e.which===c.ui.keyCode.ESCAPE&&s.closeChooser()})},saveOrder:function(e){var i={action:"widgets-order",savewidgets:c("#_wpnonce_widgets").val(),sidebars:[]};e&&c("#"+e).find(".spinner:first").addClass("is-active"),c("div.widgets-sortables").each(function(){c(this).sortable&&(i["sidebars["+c(this).attr("id")+"]"]=c(this).sortable("toArray").join(","))}),c.post(ajaxurl,i,function(){c("#inactive-widgets-control-remove").prop("disabled",!c("#wp_inactive_widgets .widget").length),c(".spinner").removeClass("is-active")})},save:function(t,s,d,n){var e,a=t.closest("div.widgets-sortables").attr("id"),i=t.find("form").serialize();t=c(t),c(".spinner",t).addClass("is-active"),e={action:"save-widget",savewidgets:c("#_wpnonce_widgets").val(),sidebar:a},s&&(e.delete_widget=1),i+="&"+c.param(e),c.post(ajaxurl,i,function(e){var i;s?(c("input.widget_number",t).val()||(i=c("input.widget-id",t).val(),c("#available-widgets").find("input.widget-id").each(function(){c(this).val()===i&&c(this).closest("div.widget").show()})),d?(n=0,t.slideUp("fast",function(){c(this).remove(),wpWidgets.saveOrder()})):(t.remove(),"wp_inactive_widgets"===a&&c("#inactive-widgets-control-remove").prop("disabled",!c("#wp_inactive_widgets .widget").length))):(c(".spinner").removeClass("is-active"),e&&2<e.length&&(c("div.widget-content",t).html(e),wpWidgets.appendTitle(t),g.trigger("widget-updated",[t]),"wp_inactive_widgets"===a&&c("#inactive-widgets-control-remove").prop("disabled",!c("#wp_inactive_widgets .widget").length))),n&&wpWidgets.saveOrder()})},removeInactiveWidgets:function(){var e,i=c(".remove-inactive-widgets");c(".spinner",i).addClass("is-active"),e={action:"delete-inactive-widgets",removeinactivewidgets:c("#_wpnonce_remove_inactive_widgets").val()},e=c.param(e),c.post(ajaxurl,e,function(){c("#wp_inactive_widgets .widget").remove(),c("#inactive-widgets-control-remove").prop("disabled",!0),c(".spinner",i).removeClass("is-active")})},appendTitle:function(e){var i=(i=c('input[id*="-title"]',e).val()||"")&&": "+i.replace(/<[^<>]+>/g,"").replace(/</g,"<").replace(/>/g,">");c(e).children(".widget-top").children(".widget-title").children().children(".in-widget-title").html(i)},close:function(e){e.children(".widget-inside").slideUp("fast",function(){e.attr("style","")})},addWidget:function(e){var i=e.find(".widgets-chooser-selected").data("sidebarId"),t=c("#"+i),s=c("#available-widgets").find(".widget-in-question").clone(),d=s.attr("id"),e=s.find("input.add_new").val(),n=s.find("input.multi_number").val();s.find(".widgets-chooser").remove(),"multi"===e?(s.html(s.html().replace(/<[^<>]+>/g,function(e){return e.replace(/__i__|%i%/g,n)})),s.attr("id",d.replace("__i__",n)),n++,c("#"+d).find("input.multi_number").val(n)):"single"===e&&(s.attr("id","new-"+d),c("#"+d).hide()),t.closest(".widgets-holder-wrap").removeClass("closed"),t.append(s),t.sortable("refresh"),wpWidgets.save(s,0,0,1),s.find("input.add_new").val(""),g.trigger("widget-added",[s]),e=(i=c(window).scrollTop())+c(window).height(),(d=t.offset()).bottom=d.top+t.outerHeight(),(i>d.bottom||e<d.top)&&c("html, body").animate({scrollTop:d.top-130},200),window.setTimeout(function(){s.find(".widget-title").trigger("click")},250)},closeChooser:function(){var e=this;c(".widgets-chooser").slideUp(200,function(){c("#wpbody-content").append(this),e.clearWidgetSelection()})},clearWidgetSelection:function(){c("#widgets-left").removeClass("chooser"),c(".widget-in-question").removeClass("widget-in-question")},closeSidebar:function(e){this.hoveredSidebar.addClass("closed"),c(e.target).css("min-height",""),this.hoveredSidebar=null}},g.ready(function(){wpWidgets.init()})}(jQuery); tags-box.min.js 0000666 00000006055 15213733063 0007425 0 ustar 00 var tagBox,array_unique_noempty;!function(o){var r=window.tagsSuggestL10n&&window.tagsSuggestL10n.tagDelimiter||",";array_unique_noempty=function(t){var a=[];return o.each(t,function(t,e){(e=o.trim(e))&&-1===o.inArray(e,a)&&a.push(e)}),a},tagBox={clean:function(t){return t=(t=","!==r?t.replace(new RegExp(r,"g"),","):t).replace(/\s*,\s*/g,",").replace(/,+/g,",").replace(/[,\s]+$/,"").replace(/^[,\s]+/,""),t=","!==r?t.replace(/,/g,r):t},parseTags:function(t){var e=t.id.split("-check-num-")[1],a=o(t).closest(".tagsdiv"),s=a.find(".the-tags"),t=s.val().split(r),n=[];return delete t[e],o.each(t,function(t,e){(e=o.trim(e))&&n.push(e)}),s.val(this.clean(n.join(r))),this.quickClicks(a),!1},quickClicks:function(t){var a,e=o(".the-tags",t),s=o(".tagchecklist",t),n=o(t).attr("id");e.length&&(a=e.prop("disabled"),e=e.val().split(r),s.empty(),o.each(e,function(t,e){(e=o.trim(e))&&(e=o("<span />").text(e),a||((t=o('<button type="button" id="'+n+"-check-num-"+t+'" class="ntdelbutton"><span class="remove-tag-icon" aria-hidden="true"></span><span class="screen-reader-text">'+window.tagsSuggestL10n.removeTerm+" "+e.html()+"</span></button>")).on("click keypress",function(t){"click"!==t.type&&13!==t.keyCode&&32!==t.keyCode||(13!==t.keyCode&&32!==t.keyCode||o(this).closest(".tagsdiv").find("input.newtag").focus(),tagBox.userAction="remove",tagBox.parseTags(this))}),e.prepend(" ").prepend(t)),s.append(e))}),tagBox.screenReadersMessage())},flushTags:function(t,e,a){var s,n,i=o(".the-tags",t),c=o("input.newtag",t);return void 0===(n=(e=e||!1)?o(e).text():c.val())||""===n||(n=(s=i.val())?s+r+n:n,n=this.clean(n),n=array_unique_noempty(n.split(r)).join(r),i.val(n),this.quickClicks(t),e||c.val(""),void 0===a&&c.focus()),!1},get:function(a){var s=a.substr(a.indexOf("-")+1);o.post(ajaxurl,{action:"get-tagcloud",tax:s},function(t,e){0!==t&&"success"==e&&(t=o('<p id="tagcloud-'+s+'" class="the-tagcloud">'+t+"</p>"),o("a",t).click(function(){return tagBox.userAction="add",tagBox.flushTags(o("#"+s),this),!1}),o("#"+a).after(t))})},userAction:"",screenReadersMessage:function(){var t;switch(this.userAction){case"remove":t=window.tagsSuggestL10n.termRemoved;break;case"add":t=window.tagsSuggestL10n.termAdded;break;default:return}window.wp.a11y.speak(t,"assertive")},init:function(){var t=o("div.ajaxtag");o(".tagsdiv").each(function(){tagBox.quickClicks(this)}),o(".tagadd",t).click(function(){tagBox.userAction="add",tagBox.flushTags(o(this).closest(".tagsdiv"))}),o("input.newtag",t).keyup(function(t){13==t.which&&(tagBox.userAction="add",tagBox.flushTags(o(this).closest(".tagsdiv")),t.preventDefault(),t.stopPropagation())}).keypress(function(t){13==t.which&&(t.preventDefault(),t.stopPropagation())}).each(function(t,e){o(e).wpTagsSuggest()}),o("#post").submit(function(){o("div.tagsdiv").each(function(){tagBox.flushTags(this,!1,1)})}),o(".tagcloud-link").click(function(){tagBox.get(o(this).attr("id")),o(this).attr("aria-expanded","true").unbind().click(function(){o(this).attr("aria-expanded","false"===o(this).attr("aria-expanded")?"true":"false").siblings(".the-tagcloud").toggle()})})}}}(jQuery); editor-expand.min.js 0000666 00000032050 15213733063 0010436 0 ustar 00 !function(F,I){"use strict";var L=I(F),M=I(document),V=I("#wpadminbar"),N=I("#wpfooter");I(function(){var g,e,u=I("#postdivrich"),h=I("#wp-content-wrap"),m=I("#wp-content-editor-tools"),w=I(),H=I(),b=I("#ed_toolbar"),v=I("#content"),i=v[0],o=0,x=I("#post-status-info"),y=I(),T=I(),B=I("#side-sortables"),C=I("#postbox-container-1"),S=I("#post-body"),O=F.wp.editor&&F.wp.editor.fullscreen,r=function(){},l=function(){},z=!1,E=!1,k=!1,A=!1,W=0,K=56,R=20,Y=300,n=h.hasClass("tmce-active")?"tinymce":"html",U=!!parseInt(F.getUserSetting("hidetb"),10),D={windowHeight:0,windowWidth:0,adminBarHeight:0,toolsHeight:0,menuBarHeight:0,visualTopHeight:0,textTopHeight:0,bottomHeight:0,statusBarHeight:0,sideSortablesHeight:0},s=F._.throttle(function(){var t=F.scrollX||document.documentElement.scrollLeft,e=F.scrollY||document.documentElement.scrollTop,o=parseInt(i.style.height,10);i.style.height=Y+"px",i.scrollHeight>Y&&(i.style.height=i.scrollHeight+"px"),void 0!==t&&F.scrollTo(t,e),i.scrollHeight<o&&p()},300);function P(){var t=i.value.length;g&&!g.isHidden()||!g&&"tinymce"===n||(t<o?s():parseInt(i.style.height,10)<i.scrollHeight&&(i.style.height=Math.ceil(i.scrollHeight)+"px",p()),o=t)}function p(t){var e,o,i,n,s,f,a,d,c,u,r,l,p;O&&O.settings.visible||(e=L.scrollTop(),o="scroll"!==(r=t&&t.type),i=g&&!g.isHidden(),n=Y,s=S.offset().top,f=h.width(),!o&&D.windowHeight||(p=L.width(),(D={windowHeight:L.height(),windowWidth:p,adminBarHeight:600<p?V.outerHeight():0,toolsHeight:m.outerHeight()||0,menuBarHeight:y.outerHeight()||0,visualTopHeight:w.outerHeight()||0,textTopHeight:b.outerHeight()||0,bottomHeight:x.outerHeight()||0,statusBarHeight:T.outerHeight()||0,sideSortablesHeight:B.height()||0}).menuBarHeight<3&&(D.menuBarHeight=0)),i||"resize"!==r||P(),u=i?(a=w,l=H,D.visualTopHeight):(a=b,l=v,D.textTopHeight),(i||a.length)&&(p=a.parent().offset().top,r=l.offset().top,l=l.outerHeight(),(i?Y+u:Y+20)+5<l?((!z||o)&&e>=p-D.toolsHeight-D.adminBarHeight&&e<=p-D.toolsHeight-D.adminBarHeight+l-n?(z=!0,m.css({position:"fixed",top:D.adminBarHeight,width:f}),i&&y.length&&y.css({position:"fixed",top:D.adminBarHeight+D.toolsHeight,width:f-2-(i?0:a.outerWidth()-a.width())}),a.css({position:"fixed",top:D.adminBarHeight+D.toolsHeight+D.menuBarHeight,width:f-2-(i?0:a.outerWidth()-a.width())})):(z||o)&&(e<=p-D.toolsHeight-D.adminBarHeight?(z=!1,m.css({position:"absolute",top:0,width:f}),i&&y.length&&y.css({position:"absolute",top:0,width:f-2}),a.css({position:"absolute",top:D.menuBarHeight,width:f-2-(i?0:a.outerWidth()-a.width())})):e>=p-D.toolsHeight-D.adminBarHeight+l-n&&(z=!1,m.css({position:"absolute",top:l-n,width:f}),i&&y.length&&y.css({position:"absolute",top:l-n,width:f-2}),a.css({position:"absolute",top:l-n+D.menuBarHeight,width:f-2-(i?0:a.outerWidth()-a.width())}))),(!E||o&&U)&&e+D.windowHeight<=r+l+D.bottomHeight+D.statusBarHeight+1?t&&0<t.deltaHeight&&t.deltaHeight<100?F.scrollBy(0,t.deltaHeight):i&&U&&(E=!0,T.css({position:"fixed",bottom:D.bottomHeight,visibility:"",width:f-2}),x.css({position:"fixed",bottom:0,width:f})):(!U&&E||(E||o)&&e+D.windowHeight>r+l+D.bottomHeight+D.statusBarHeight-1)&&(E=!1,T.attr("style",U?"":"visibility: hidden;"),x.attr("style",""))):o&&(m.css({position:"absolute",top:0,width:f}),i&&y.length&&y.css({position:"absolute",top:0,width:f-2}),a.css({position:"absolute",top:D.menuBarHeight,width:f-2-(i?0:a.outerWidth()-a.width())}),T.attr("style",U?"":"visibility: hidden;"),x.attr("style","")),C.width()<300&&600<D.windowWidth&&M.height()>B.height()+s+120&&D.windowHeight<l?(D.sideSortablesHeight+K+R>D.windowHeight||k||A?e+K<=s?(B.attr("style",""),k=A=!1):W<e?k?(k=!1,d=B.offset().top-D.adminBarHeight,(c=N.offset().top)<d+D.sideSortablesHeight+R&&(d=c-D.sideSortablesHeight-12),B.css({position:"absolute",top:d,bottom:""})):!A&&D.sideSortablesHeight+B.offset().top+R<e+D.windowHeight&&(A=!0,B.css({position:"fixed",top:"auto",bottom:R})):e<W&&(A?(A=!1,d=B.offset().top-R,(c=N.offset().top)<d+D.sideSortablesHeight+R&&(d=c-D.sideSortablesHeight-12),B.css({position:"absolute",top:d,bottom:""})):!k&&B.offset().top>=e+K&&(k=!0,B.css({position:"fixed",top:K,bottom:""}))):(s-K<=e?B.css({position:"fixed",top:K}):B.attr("style",""),k=A=!1),W=e):(B.attr("style",""),k=A=!1),o&&(h.css({paddingTop:D.toolsHeight}),i?H.css({paddingTop:D.visualTopHeight+D.menuBarHeight}):v.css({marginTop:D.textTopHeight}))))}function f(){P(),p()}function X(t){for(var e=1;e<6;e++)setTimeout(t,500*e)}function t(){F.pageYOffset&&130<F.pageYOffset&&F.scrollTo(F.pageXOffset,0),u.addClass("wp-editor-expand"),L.on("scroll.editor-expand resize.editor-expand",function(t){p(t.type),clearTimeout(e),e=setTimeout(p,100)}),M.on("wp-collapse-menu.editor-expand postboxes-columnchange.editor-expand editor-classchange.editor-expand",p).on("postbox-toggled.editor-expand postbox-moved.editor-expand",function(){!k&&!A&&F.pageYOffset>K&&(A=!0,F.scrollBy(0,-1),p(),F.scrollBy(0,1)),p()}).on("wp-window-resized.editor-expand",function(){g&&!g.isHidden()?g.execCommand("wpAutoResize"):P()}),v.on("focus.editor-expand input.editor-expand propertychange.editor-expand",P),r(),O&&O.pubsub.subscribe("hidden",f),g&&(g.settings.wp_autoresize_on=!0,g.execCommand("wpAutoResizeOn"),g.isHidden()||g.execCommand("wpAutoResize")),g&&!g.isHidden()||P(),p(),M.trigger("editor-expand-on")}function a(){var t=parseInt(F.getUserSetting("ed_size",300),10);t<50?t=50:5e3<t&&(t=5e3),F.pageYOffset&&130<F.pageYOffset&&F.scrollTo(F.pageXOffset,0),u.removeClass("wp-editor-expand"),L.off(".editor-expand"),M.off(".editor-expand"),v.off(".editor-expand"),l(),O&&O.pubsub.unsubscribe("hidden",f),I.each([w,b,m,y,x,T,h,H,v,B],function(t,e){e&&e.attr("style","")}),z=E=k=A=!1,g&&(g.settings.wp_autoresize_on=!1,g.execCommand("wpAutoResizeOff"),g.isHidden()||(v.hide(),t&&g.theme.resizeTo(null,t))),t&&v.height(t),M.trigger("editor-expand-off")}M.on("tinymce-editor-init.editor-expand",function(t,f){var a=F.tinymce.util.VK,e=_.debounce(function(){I(".mce-floatpanel:hover").length||F.tinymce.ui.FloatPanel.hideAll(),I(".mce-tooltip").hide()},1e3,!0);function o(t){t=t.keyCode;t<=47&&t!==a.SPACEBAR&&t!==a.ENTER&&t!==a.DELETE&&t!==a.BACKSPACE&&t!==a.UP&&t!==a.LEFT&&t!==a.DOWN&&t!==a.UP||91<=t&&t<=93||112<=t&&t<=123||144===t||145===t||i(t)}function i(t){var e,o,i,n,s=function(){var t,e,o,i=f.selection.getNode();if(f.wp&&f.wp.getView&&(e=f.wp.getView(i)))o=e.getBoundingClientRect();else{t=f.selection.getRng();try{o=t.getClientRects()[0]}catch(t){}o=o||i.getBoundingClientRect()}return!!o.height&&o}();s&&(o=(e=s.top+f.iframeElement.getBoundingClientRect().top)+s.height,e-=50,o+=50,i=D.adminBarHeight+D.toolsHeight+D.menuBarHeight+D.visualTopHeight,(n=D.windowHeight-(U?D.bottomHeight+D.statusBarHeight:0))-i<s.height||(e<i&&(t===a.UP||t===a.LEFT||t===a.BACKSPACE)?F.scrollTo(F.pageXOffset,e+F.pageYOffset-i):n<o&&F.scrollTo(F.pageXOffset,o+F.pageYOffset-n)))}function n(t){t.state||p()}function s(){L.on("scroll.mce-float-panels",e),setTimeout(function(){f.execCommand("wpAutoResize"),p()},300)}function d(){L.off("scroll.mce-float-panels"),setTimeout(function(){var t=h.offset().top;F.pageYOffset>t&&F.scrollTo(F.pageXOffset,t-D.adminBarHeight),P(),p()},100),p()}function c(){U=!U}"content"===f.id&&((g=f).settings.autoresize_min_height=Y,w=h.find(".mce-toolbar-grp"),H=h.find(".mce-edit-area"),T=h.find(".mce-statusbar"),y=h.find(".mce-menubar"),r=function(){f.on("keyup",o),f.on("show",s),f.on("hide",d),f.on("wp-toolbar-toggle",c),f.on("setcontent wp-autoresize wp-toolbar-toggle",p),f.on("undo redo",i),f.on("FullscreenStateChanged",n),L.off("scroll.mce-float-panels").on("scroll.mce-float-panels",e)},l=function(){f.off("keyup",o),f.off("show",s),f.off("hide",d),f.off("wp-toolbar-toggle",c),f.off("setcontent wp-autoresize wp-toolbar-toggle",p),f.off("undo redo",i),f.off("FullscreenStateChanged",n),L.off("scroll.mce-float-panels")},u.hasClass("wp-editor-expand")&&(r(),X(p)))}),u.hasClass("wp-editor-expand")&&(t(),h.hasClass("html-active")&&X(function(){p(),P()})),I("#adv-settings .editor-expand").show(),I("#editor-expand-toggle").on("change.editor-expand",function(){I(this).prop("checked")?(t(),F.setUserSetting("editor_expand","on")):(a(),F.setUserSetting("editor_expand","off"))}),F.editorExpand={on:t,off:a}}),I(function(){var i,n,t,s,f,a,d,c,u,r,l,p=I(document.body),o=I("#wpcontent"),g=I("#post-body-content"),e=I("#title"),h=I("#content"),m=I(document.createElement("DIV")),w=I("#edit-slug-box"),H=w.find("a").add(w.find("button")).add(w.find("input")),b=I("#adminmenuwrap"),v=(I(),I(),"on"===F.getUserSetting("editor_expand","on")),x=!!v&&"on"===F.getUserSetting("post_dfw"),y=0,T=0,B=20;function C(){(s=g.offset()).right=s.left+g.outerWidth(),s.bottom=s.top+g.outerHeight()}function S(){v||(v=!0,M.trigger("dfw-activate"),h.on("keydown.focus-shortcut",Y))}function O(){v&&(E(),v=!1,M.trigger("dfw-deactivate"),h.off("keydown.focus-shortcut"))}function z(){!x&&v&&(x=!0,h.on("keydown.focus",k),e.add(h).on("blur.focus",W),k(),F.setUserSetting("post_dfw","on"),M.trigger("dfw-on"))}function E(){x&&(x=!1,e.add(h).off(".focus"),A(),g.off(".focus"),F.setUserSetting("post_dfw","off"),M.trigger("dfw-off"))}function _(){(x?E:z)()}function k(t){var e,o=t&&t.keyCode;F.navigator.platform&&(e=-1<F.navigator.platform.indexOf("Mac")),27===o||87===o&&t.altKey&&(!e&&t.shiftKey||e&&t.ctrlKey)?A(t):t&&(t.metaKey||t.ctrlKey&&!t.altKey||t.altKey&&t.shiftKey||o&&(o<=47&&8!==o&&13!==o&&32!==o&&46!==o||91<=o&&o<=93||112<=o&&o<=135||144<=o&&o<=150||224<=o))||(i||(i=!0,clearTimeout(r),r=setTimeout(function(){m.show()},600),g.css("z-index",9998),m.on("mouseenter.focus",function(){C(),L.on("scroll.focus",function(){var t=F.pageYOffset;c&&d&&c!==t&&(d<s.top-B||d>s.bottom+B)&&A(),c=t})}).on("mouseleave.focus",function(){f=a=null,y=T=0,L.off("scroll.focus")}).on("mousemove.focus",function(t){var e=t.clientX,o=t.clientY,i=F.pageYOffset,t=F.pageXOffset;if(f&&a&&(e!==f||o!==a))if(o<=a&&o<s.top-i||a<=o&&o>s.bottom-i||e<=f&&e<s.left-t||f<=e&&e>s.right-t){if(y+=Math.abs(f-e),T+=Math.abs(a-o),(o<=s.top-B-i||o>=s.bottom+B-i||e<=s.left-B-t||e>=s.right+B-t)&&(10<y||10<T))return A(),f=a=null,void(y=T=0)}else y=T=0;f=e,a=o}).on("touchstart.focus",function(t){t.preventDefault(),A()}),g.off("mouseenter.focus"),u&&(clearTimeout(u),u=null),p.addClass("focus-on").removeClass("focus-off")),!n&&i&&(n=!0,V.on("mouseenter.focus",function(){V.addClass("focus-off")}).on("mouseleave.focus",function(){V.removeClass("focus-off")})),K())}function A(t){i&&(i=!1,clearTimeout(r),r=setTimeout(function(){m.hide()},200),g.css("z-index",""),m.off("mouseenter.focus mouseleave.focus mousemove.focus touchstart.focus"),void 0===t&&g.on("mouseenter.focus",function(){(I.contains(g.get(0),document.activeElement)||l)&&k()}),u=setTimeout(function(){u=null,g.off("mouseenter.focus")},1e3),p.addClass("focus-off").removeClass("focus-on")),n&&(n=!1,V.off(".focus")),R()}function W(){setTimeout(function(){var t=document.activeElement.compareDocumentPosition(g.get(0));function e(t){return I.contains(t.get(0),document.activeElement)}2!==t&&4!==t||!(e(b)||e(o)||e(N))||A()},0)}function K(){t||!i||w.find(":focus").length||(t=!0,w.stop().fadeTo("fast",.3).on("mouseenter.focus",R).off("mouseleave.focus"),H.on("focus.focus",R).off("blur.focus"))}function R(){t&&(t=!1,w.stop().fadeTo("fast",1).on("mouseleave.focus",K).off("mouseenter.focus"),H.on("blur.focus",K).off("focus.focus"))}function Y(t){t.altKey&&t.shiftKey&&87===t.keyCode&&_()}p.append(m),m.css({display:"none",position:"fixed",top:V.height(),right:0,bottom:0,left:0,"z-index":9997}),g.css({position:"relative"}),L.on("mousemove.focus",function(t){d=t.pageY}),I("#postdivrich").hasClass("wp-editor-expand")&&h.on("keydown.focus-shortcut",Y),M.on("tinymce-editor-setup.focus",function(t,e){e.addButton("dfw",{active:x,classes:"wp-dfw btn widget",disabled:!v,onclick:_,onPostRender:function(){var t=this;M.on("dfw-activate.focus",function(){t.disabled(!1)}).on("dfw-deactivate.focus",function(){t.disabled(!0)}).on("dfw-on.focus",function(){t.active(!0)}).on("dfw-off.focus",function(){t.active(!1)})},tooltip:"Distraction-free writing mode",shortcut:"Alt+Shift+W"}),e.addCommand("wpToggleDFW",_),e.addShortcut("access+w","","wpToggleDFW")}),M.on("tinymce-editor-init.focus",function(t,e){var o,i;function n(){l=!0}function s(){l=!1}"content"===e.id&&(I(e.getWin()),I(e.getContentAreaContainer()).find("iframe"),o=function(){e.on("keydown",k),e.on("blur",W),e.on("focus",n),e.on("blur",s),e.on("wp-autoresize",C)},i=function(){e.off("keydown",k),e.off("blur",W),e.off("focus",n),e.off("blur",s),e.off("wp-autoresize",C)},x&&o(),M.on("dfw-on.focus",o).on("dfw-off.focus",i),e.on("click",function(t){t.target===e.getDoc().documentElement&&e.focus()}))}),M.on("quicktags-init",function(t,e){var o;e.settings.buttons&&-1!==(","+e.settings.buttons+",").indexOf(",dfw,")&&(o=I("#"+e.name+"_dfw"),I(document).on("dfw-activate",function(){o.prop("disabled",!1)}).on("dfw-deactivate",function(){o.prop("disabled",!0)}).on("dfw-on",function(){o.addClass("active")}).on("dfw-off",function(){o.removeClass("active")}))}),M.on("editor-expand-on.focus",S).on("editor-expand-off.focus",O),x&&(h.on("keydown.focus",k),e.add(h).on("blur.focus",W)),F.wp=F.wp||{},F.wp.editor=F.wp.editor||{},F.wp.editor.dfw={activate:S,deactivate:O,isActive:function(){return v},on:z,off:E,toggle:_,isOn:function(){return x}}})}(window,window.jQuery); nav-menu.min.js 0000666 00000050377 15213733063 0007435 0 ustar 00 var wpNavMenu;!function(I){var y=wpNavMenu={options:{menuItemDepthPerLevel:30,globalMaxDepth:11,sortableItems:"> *",targetTolerance:0},menuList:void 0,targetList:void 0,menusChanged:!1,isRTL:!("undefined"==typeof isRtl||!isRtl),negateIfRTL:"undefined"!=typeof isRtl&&isRtl?-1:1,lastSearch:"",init:function(){y.menuList=I("#menu-to-edit"),y.targetList=y.menuList,this.jQueryExtensions(),this.attachMenuEditListeners(),this.attachQuickSearchListeners(),this.attachThemeLocationsListeners(),this.attachMenuSaveSubmitListeners(),this.attachTabsPanelListeners(),this.attachUnsavedChangesListener(),y.menuList.length&&this.initSortables(),menus.oneThemeLocationNoMenus&&I("#posttype-page").addSelectedToMenu(y.addMenuItemToBottom),this.initManageLocations(),this.initAccessibility(),this.initToggles(),this.initPreviewing()},jQueryExtensions:function(){I.fn.extend({menuItemDepth:function(){var e=y.isRTL?this.eq(0).css("margin-right"):this.eq(0).css("margin-left");return y.pxToDepth(e&&-1!=e.indexOf("px")?e.slice(0,-2):0)},updateDepthClass:function(t,n){return this.each(function(){var e=I(this);n=n||e.menuItemDepth(),I(this).removeClass("menu-item-depth-"+n).addClass("menu-item-depth-"+t)})},shiftDepthClass:function(i){return this.each(function(){var e=I(this),t=e.menuItemDepth(),n=t+i;e.removeClass("menu-item-depth-"+t).addClass("menu-item-depth-"+n),0===n&&e.find(".is-submenu").hide()})},childMenuItems:function(){var i=I();return this.each(function(){for(var e=I(this),t=e.menuItemDepth(),n=e.next(".menu-item");n.length&&n.menuItemDepth()>t;)i=i.add(n),n=n.next(".menu-item")}),i},shiftHorizontally:function(i){return this.each(function(){var e=I(this),t=e.menuItemDepth(),n=t+i;e.moveHorizontally(n,t)})},moveHorizontally:function(a,s){return this.each(function(){var e=I(this),t=e.childMenuItems(),i=a-s,n=e.find(".is-submenu");e.updateDepthClass(a,s).updateParentMenuItemDBId(),t&&t.each(function(){var e=I(this),t=e.menuItemDepth(),n=t+i;e.updateDepthClass(n,t).updateParentMenuItemDBId()}),0===a?n.hide():n.show()})},updateParentMenuItemDBId:function(){return this.each(function(){var e=I(this),t=e.find(".menu-item-data-parent-id"),n=parseInt(e.menuItemDepth(),10),i=n-1,i=e.prevAll(".menu-item-depth-"+i).first();0===n?t.val(0):t.val(i.find(".menu-item-data-db-id").val())})},hideAdvancedMenuItemFields:function(){return this.each(function(){var e=I(this);I(".hide-column-tog").not(":checked").each(function(){e.find(".field-"+I(this).val()).addClass("hidden-field")})})},addSelectedToMenu:function(a){return 0!==I("#menu-to-edit").length&&this.each(function(){var e=I(this),n={},t=menus.oneThemeLocationNoMenus&&0===e.find(".tabs-panel-active .categorychecklist li input:checked").length?e.find('#page-all li input[type="checkbox"]'):e.find(".tabs-panel-active .categorychecklist li input:checked"),i=/menu-item\[([^\]]*)/;if(a=a||y.addMenuItemToBottom,!t.length)return!1;e.find(".button-controls .spinner").addClass("is-active"),I(t).each(function(){var e=I(this),t=i.exec(e.attr("name")),t=void 0===t[1]?0:parseInt(t[1],10);this.className&&-1!=this.className.indexOf("add-to-top")&&(a=y.addMenuItemToTop),n[t]=e.closest("li").getItemData("add-menu-item",t)}),y.addItemToMenu(n,a,function(){t.removeAttr("checked"),e.find(".button-controls .spinner").removeClass("is-active")})})},getItemData:function(t,n){t=t||"menu-item";var i,a={},s=["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"];return(n=n||"menu-item"!=t?n:this.find(".menu-item-data-db-id").val())&&this.find("input").each(function(){var e;for(i=s.length;i--;)"menu-item"==t?e=s[i]+"["+n+"]":"add-menu-item"==t&&(e="menu-item["+n+"]["+s[i]+"]"),this.name&&e==this.name&&(a[s[i]]=this.value)}),a},setItemData:function(e,a,s){return a=a||"menu-item",(s=s||"menu-item"!=a?s:I(".menu-item-data-db-id",this).val())&&this.find("input").each(function(){var n,i=I(this);I.each(e,function(e,t){"menu-item"==a?n=e+"["+s+"]":"add-menu-item"==a&&(n="menu-item["+s+"]["+e+"]"),n==i.attr("name")&&i.val(t)})}),this}})},countMenuItems:function(e){return I(".menu-item-depth-"+e).length},moveMenuItem:function(e,t){var n,i,a=I("#menu-to-edit li"),s=a.length,m=e.parents("li.menu-item"),u=m.childMenuItems(),o=m.getItemData(),r=parseInt(m.menuItemDepth(),10),c=parseInt(m.index(),10),l=m.next(),d=l.childMenuItems(),h=parseInt(l.menuItemDepth(),10)+1,f=m.prev(),p=parseInt(f.menuItemDepth(),10),v=f.getItemData()["menu-item-db-id"];switch(t){case"up":if(i=c-1,0===c)break;0==i&&0!==r&&m.moveHorizontally(0,r),0!==p&&m.moveHorizontally(p,r),(u?n=m.add(u):m).detach().insertBefore(a.eq(i)).updateParentMenuItemDBId();break;case"down":if(u){if(n=m.add(u),(d=0!==(l=a.eq(n.length+c)).childMenuItems().length)&&(i=parseInt(l.menuItemDepth(),10)+1,m.moveHorizontally(i,r)),s===c+n.length)break;n.detach().insertAfter(a.eq(c+n.length)).updateParentMenuItemDBId()}else{if(0!==d.length&&m.moveHorizontally(h,r),s===c+1)break;m.detach().insertAfter(a.eq(c+1)).updateParentMenuItemDBId()}break;case"top":if(0===c)break;(u?n=m.add(u):m).detach().insertBefore(a.eq(0)).updateParentMenuItemDBId();break;case"left":if(0===r)break;m.shiftHorizontally(-1);break;case"right":if(0===c)break;if(o["menu-item-parent-id"]===v)break;m.shiftHorizontally(1)}e.focus(),y.registerChange(),y.refreshKeyboardAccessibility(),y.refreshAdvancedAccessibility()},initAccessibility:function(){var e=I("#menu-to-edit");y.refreshKeyboardAccessibility(),y.refreshAdvancedAccessibility(),e.on("mouseenter.refreshAccessibility focus.refreshAccessibility touchstart.refreshAccessibility",".menu-item",function(){y.refreshAdvancedAccessibilityOfItem(I(this).find("a.item-edit"))}),e.on("click","a.item-edit",function(){y.refreshAdvancedAccessibilityOfItem(I(this))}),e.on("click",".menus-move",function(){var e=I(this).data("dir");void 0!==e&&y.moveMenuItem(I(this).parents("li.menu-item").find("a.item-edit"),e)})},refreshAdvancedAccessibilityOfItem:function(e){var t,n,i,a,s,m,u,o,r,c,l,d,h;!0===I(e).data("needs_accessibility_refresh")&&(o=0===(u=(m=(s=I(e)).closest("li.menu-item").first()).menuItemDepth()),r=s.closest(".menu-item-handle").find(".menu-item-title").text(),c=parseInt(m.index(),10),h=o?u:parseInt(u-1,10),l=m.prevAll(".menu-item-depth-"+h).first().find(".menu-item-title").text(),d=m.prevAll(".menu-item-depth-"+u).first().find(".menu-item-title").text(),e=I("#menu-to-edit li").length,h=m.nextAll(".menu-item-depth-"+u).length,m.find(".field-move").toggle(1<e),0!==c&&(t=m.find(".menus-move-up")).attr("aria-label",menus.moveUp).css("display","inline"),0!==c&&o&&(t=m.find(".menus-move-top")).attr("aria-label",menus.moveToTop).css("display","inline"),c+1!==e&&0!==c&&(t=m.find(".menus-move-down")).attr("aria-label",menus.moveDown).css("display","inline"),0===c&&0!==h&&(t=m.find(".menus-move-down")).attr("aria-label",menus.moveDown).css("display","inline"),o||(t=m.find(".menus-move-left"),n=menus.outFrom.replace("%s",l),t.attr("aria-label",menus.moveOutFrom.replace("%s",l)).text(n).css("display","inline")),0!==c&&m.find(".menu-item-data-parent-id").val()!==m.prev().find(".menu-item-data-db-id").val()&&(t=m.find(".menus-move-right"),n=menus.under.replace("%s",d),t.attr("aria-label",menus.moveUnder.replace("%s",d)).text(n).css("display","inline")),a=o?(i=(o=I(".menu-item-depth-0")).index(m)+1,e=o.length,menus.menuFocus.replace("%1$s",r).replace("%2$d",i).replace("%3$d",e)):(u=(a=m.prevAll(".menu-item-depth-"+parseInt(u-1,10)).first()).find(".menu-item-data-db-id").val(),a=a.find(".menu-item-title").text(),u=I('.menu-item .menu-item-data-parent-id[value="'+u+'"]'),i=I(u.parents(".menu-item").get().reverse()).index(m)+1,menus.subMenuFocus.replace("%1$s",r).replace("%2$d",i).replace("%3$s",a)),s.attr("aria-label",a).text(a),s.data("needs_accessibility_refresh",!1))},refreshAdvancedAccessibility:function(){I(".menu-item-settings .field-move .menus-move").hide(),I("a.item-edit").data("needs_accessibility_refresh",!0),I(".menu-item-edit-active a.item-edit").each(function(){y.refreshAdvancedAccessibilityOfItem(this)})},refreshKeyboardAccessibility:function(){I("a.item-edit").off("focus").on("focus",function(){I(this).off("keydown").on("keydown",function(e){var t,n=I(this),i=n.parents("li.menu-item").getItemData();if((37==e.which||38==e.which||39==e.which||40==e.which)&&(n.off("keydown"),1!==I("#menu-to-edit li").length)){switch(t={38:"up",40:"down",37:"left",39:"right"},(t=I("body").hasClass("rtl")?{38:"up",40:"down",39:"left",37:"right"}:t)[e.which]){case"up":y.moveMenuItem(n,"up");break;case"down":y.moveMenuItem(n,"down");break;case"left":y.moveMenuItem(n,"left");break;case"right":y.moveMenuItem(n,"right")}return I("#edit-"+i["menu-item-db-id"]).focus(),!1}})})},initPreviewing:function(){I("#menu-to-edit").on("change input",".edit-menu-item-title",function(e){var t=I(e.currentTarget),e=t.val(),t=t.closest(".menu-item").find(".menu-item-title");e?t.text(e).removeClass("no-title"):t.text(navMenuL10n.untitled).addClass("no-title")})},initToggles:function(){postboxes.add_postbox_toggles("nav-menus"),columns.useCheckboxesForHidden(),columns.checked=function(e){I(".field-"+e).removeClass("hidden-field")},columns.unchecked=function(e){I(".field-"+e).addClass("hidden-field")},y.menuList.hideAdvancedMenuItemFields(),I(".hide-postbox-tog").click(function(){var e=I(".accordion-container li.accordion-section").filter(":hidden").map(function(){return this.id}).get().join(",");I.post(ajaxurl,{action:"closed-postboxes",hidden:e,closedpostboxesnonce:jQuery("#closedpostboxesnonce").val(),page:"nav-menus"})})},initSortables:function(){var s,a,m,n,u,o,r,c,l,d,h=0,f=y.menuList.offset().left,p=I("body"),v=function(){if(!p[0].className)return 0;var e=p[0].className.match(/menu-max-depth-(\d+)/);return e&&e[1]?parseInt(e[1],10):0}();function g(e){n=e.placeholder.prev(".menu-item"),u=e.placeholder.next(".menu-item"),n[0]==e.item[0]&&(n=n.prev(".menu-item")),u[0]==e.item[0]&&(u=u.next(".menu-item")),o=n.length?n.offset().top+n.height():0,r=u.length?u.offset().top+u.height()/3:0,a=u.length?u.menuItemDepth():0,m=n.length?(e=n.menuItemDepth()+1)>y.options.globalMaxDepth?y.options.globalMaxDepth:e:0}function b(e,t){e.placeholder.updateDepthClass(t,h),h=t}0!==I("#menu-to-edit li").length&&I(".drag-instructions").show(),f+=y.isRTL?y.menuList.width():0,y.menuList.sortable({handle:".menu-item-handle",placeholder:"sortable-placeholder",items:y.options.sortableItems,start:function(e,t){var n,i;y.isRTL&&(t.item[0].style.right="auto"),l=t.item.children(".menu-item-transport"),s=t.item.menuItemDepth(),b(t,s),i=(t.item.next()[0]==t.placeholder[0]?t.item.next():t.item).childMenuItems(),l.append(i),n=l.outerHeight(),n+=0<n?+t.placeholder.css("margin-top").slice(0,-2):0,n+=t.helper.outerHeight(),c=n,n-=2,t.placeholder.height(n),d=s,i.each(function(){var e=I(this).menuItemDepth();d=d<e?e:d}),i=t.helper.find(".menu-item-handle").outerWidth(),i+=y.depthToPx(d-s),i-=2,t.placeholder.width(i),(i=t.placeholder.next(".menu-item")).css("margin-top",c+"px"),t.placeholder.detach(),I(this).sortable("refresh"),t.item.after(t.placeholder),i.css("margin-top",0),g(t)},stop:function(e,t){var n=h-s,i=l.children().insertAfter(t.item),a=t.item.find(".item-title .is-submenu");0<h?a.show():a.hide(),0!=n&&(t.item.updateDepthClass(h),i.shiftDepthClass(n),function(e){var t,n=v;if(0!==e){if(0<e)v<(t=d+e)&&(n=t);else if(e<0&&d==v)for(;!I(".menu-item-depth-"+n,y.menuList).length&&0<n;)n--;p.removeClass("menu-max-depth-"+v).addClass("menu-max-depth-"+n),v=n}}(n)),y.registerChange(),t.item.updateParentMenuItemDBId(),t.item[0].style.top=0,y.isRTL&&(t.item[0].style.left="auto",t.item[0].style.right=0),y.refreshKeyboardAccessibility(),y.refreshAdvancedAccessibility()},change:function(e,t){t.placeholder.parent().hasClass("menu")||(n.length?n.after(t.placeholder):y.menuList.prepend(t.placeholder)),g(t)},sort:function(e,t){var n=t.helper.offset(),i=y.isRTL?n.left+t.helper.width():n.left,i=y.negateIfRTL*y.pxToDepth(i-f);m<i||n.top<o-y.options.targetTolerance?i=m:i<a&&(i=a),i!=h&&b(t,i),r&&n.top+c>r&&(u.after(t.placeholder),g(t),I(this).sortable("refreshPositions"))}})},initManageLocations:function(){I("#menu-locations-wrap form").submit(function(){window.onbeforeunload=null}),I(".menu-location-menus select").on("change",function(){var e=I(this).closest("tr").find(".locations-edit-menu-link");I(this).find("option:selected").data("orig")?e.show():e.hide()})},attachMenuEditListeners:function(){var t=this;I("#update-nav-menu").bind("click",function(e){if(e.target&&e.target.className)return-1!=e.target.className.indexOf("item-edit")?t.eventOnClickEditLink(e.target):-1!=e.target.className.indexOf("menu-save")?t.eventOnClickMenuSave(e.target):-1!=e.target.className.indexOf("menu-delete")?t.eventOnClickMenuDelete(e.target):-1!=e.target.className.indexOf("item-delete")?t.eventOnClickMenuItemDelete(e.target):-1!=e.target.className.indexOf("item-cancel")?t.eventOnClickCancelLink(e.target):void 0}),I('#add-custom-links input[type="text"]').keypress(function(e){I("#customlinkdiv").removeClass("form-invalid"),13===e.keyCode&&(e.preventDefault(),I("#submit-customlinkdiv").click())})},attachMenuSaveSubmitListeners:function(){I("#update-nav-menu").submit(function(){var e=I("#update-nav-menu").serializeArray();I('[name="nav-menu-data"]').val(JSON.stringify(e))})},attachThemeLocationsListeners:function(){var e=I("#nav-menu-theme-locations"),t={action:"menu-locations-save"};t["menu-settings-column-nonce"]=I("#menu-settings-column-nonce").val(),e.find('input[type="submit"]').click(function(){return e.find("select").each(function(){t[this.name]=I(this).val()}),e.find(".spinner").addClass("is-active"),I.post(ajaxurl,t,function(){e.find(".spinner").removeClass("is-active")}),!1})},attachQuickSearchListeners:function(){var t,e;I("#nav-menu-meta").on("submit",function(e){e.preventDefault()}),e="oninput"in document.createElement("input")?"input":"keyup",I("#nav-menu-meta").on(e,".quick-search",function(){var e=I(this);e.attr("autocomplete","off"),t&&clearTimeout(t),t=setTimeout(function(){y.updateQuickSearchResults(e)},500)}).on("blur",".quick-search",function(){y.lastSearch=""})},updateQuickSearchResults:function(e){var t,n,i=e.val();i.length<2||y.lastSearch==i||(y.lastSearch=i,t=e.parents(".tabs-panel"),n={action:"menu-quick-search","response-format":"markup",menu:I("#menu").val(),"menu-settings-column-nonce":I("#menu-settings-column-nonce").val(),q:i,type:e.attr("name")},I(".spinner",t).addClass("is-active"),I.post(ajaxurl,n,function(e){y.processQuickSearchQueryResponse(e,n,t)}))},addCustomLink:function(e){var t=I("#custom-menu-item-url").val(),n=I("#custom-menu-item-name").val();if(e=e||y.addMenuItemToBottom,""===t||"http://"==t)return I("#customlinkdiv").addClass("form-invalid"),!1;I(".customlinkdiv .spinner").addClass("is-active"),this.addLinkToMenu(t,n,e,function(){I(".customlinkdiv .spinner").removeClass("is-active"),I("#custom-menu-item-name").val("").blur(),I("#custom-menu-item-url").val("http://")})},addLinkToMenu:function(e,t,n,i){n=n||y.addMenuItemToBottom,i=i||function(){},y.addItemToMenu({"-1":{"menu-item-type":"custom","menu-item-url":e,"menu-item-title":t}},n,i)},addItemToMenu:function(e,n,i){var a,t=I("#menu").val(),s=I("#menu-settings-column-nonce").val();n=n||function(){},i=i||function(){},a={action:"add-menu-item",menu:t,"menu-settings-column-nonce":s,"menu-item":e},I.post(ajaxurl,a,function(e){var t=I("#menu-instructions");e=I.trim(e),n(e,a),I("li.pending").hide().fadeIn("slow"),I(".drag-instructions").show(),!t.hasClass("menu-instructions-inactive")&&t.siblings().length&&t.addClass("menu-instructions-inactive"),i()})},addMenuItemToBottom:function(e){I(e).hideAdvancedMenuItemFields().appendTo(y.targetList),y.refreshKeyboardAccessibility(),y.refreshAdvancedAccessibility()},addMenuItemToTop:function(e){I(e).hideAdvancedMenuItemFields().prependTo(y.targetList),y.refreshKeyboardAccessibility(),y.refreshAdvancedAccessibility()},attachUnsavedChangesListener:function(){I("#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select").change(function(){y.registerChange()}),0!==I("#menu-to-edit").length||0!==I(".menu-location-menus select").length?window.onbeforeunload=function(){if(y.menusChanged)return navMenuL10n.saveAlert}:I("#menu-settings-column").find("input,select").end().find("a").attr("href","#").unbind("click")},registerChange:function(){y.menusChanged=!0},attachTabsPanelListeners:function(){I("#menu-settings-column").bind("click",function(e){var t,n,i=I(e.target);if(i.hasClass("nav-tab-link"))t=i.data("type"),n=i.parents(".accordion-section-content").first(),I("input",n).removeAttr("checked"),I(".tabs-panel-active",n).removeClass("tabs-panel-active").addClass("tabs-panel-inactive"),I("#"+t,n).removeClass("tabs-panel-inactive").addClass("tabs-panel-active"),I(".tabs",n).removeClass("tabs"),i.parent().addClass("tabs"),I(".quick-search",n).focus(),n.find(".tabs-panel-active .menu-item-title").length?n.removeClass("has-no-menu-item"):n.addClass("has-no-menu-item"),e.preventDefault();else if(i.hasClass("select-all")){if((n=/#(.*)$/.exec(e.target.href))&&n[1])return(n=I("#"+n[1]+" .tabs-panel-active .menu-item-title input")).length===n.filter(":checked").length?n.removeAttr("checked"):n.prop("checked",!0),!1}else if(i.hasClass("submit-add-to-menu"))return y.registerChange(),e.target.id&&"submit-customlinkdiv"==e.target.id?y.addCustomLink(y.addMenuItemToBottom):e.target.id&&-1!=e.target.id.indexOf("submit-")&&I("#"+e.target.id.replace(/submit-/,"")).addSelectedToMenu(y.addMenuItemToBottom),!1}),I("#nav-menu-meta").on("click","a.page-numbers",function(){var n=I(this).closest(".inside");return I.post(ajaxurl,this.href.replace(/.*\?/,"").replace(/action=([^&]*)/,"")+"&action=menu-get-metabox",function(e){var t=I.parseJSON(e);-1!==e.indexOf("replace-id")&&(e=document.getElementById(t["replace-id"]),t.markup&&e&&n.html(t.markup))}),!1})},eventOnClickEditLink:function(e){var t,n,e=/#(.*)$/.exec(e.href);if(e&&e[1]&&0!==(n=(t=I("#"+e[1])).parent()).length)return n.hasClass("menu-item-edit-inactive")?(t.data("menu-item-data")||t.data("menu-item-data",t.getItemData()),t.slideDown("fast"),n.removeClass("menu-item-edit-inactive").addClass("menu-item-edit-active")):(t.slideUp("fast"),n.removeClass("menu-item-edit-active").addClass("menu-item-edit-inactive")),!1},eventOnClickCancelLink:function(e){var t=I(e).closest(".menu-item-settings");return I(e).closest(".menu-item").removeClass("menu-item-edit-active").addClass("menu-item-edit-inactive"),t.setItemData(t.data("menu-item-data")).hide(),!1},eventOnClickMenuSave:function(){var e=I("#menu-name"),t=e.val();if(!t||t==e.attr("title")||!t.replace(/\s+/,""))return e.parent().addClass("form-invalid"),!1;var n=I("#update-nav-menu");return I("#nav-menu-theme-locations select").each(function(){n.append(I("<input>",{type:"hidden",name:this.name,value:I(this).val()}))}),y.menuList.find(".menu-item-data-position").val(function(e){return e+1}),!(window.onbeforeunload=null)},eventOnClickMenuDelete:function(){return!!window.confirm(navMenuL10n.warnDeleteMenu)&&!(window.onbeforeunload=null)},eventOnClickMenuItemDelete:function(e){e=parseInt(e.id.replace("delete-",""),10);return y.removeMenuItem(I("#menu-item-"+e)),y.registerChange(),!1},processQuickSearchQueryResponse:function(e,t,n){var i,a,s,m={},u=document.getElementById("nav-menu-meta"),o=/menu-item[(\[^]\]*/,r=I("<div>").html(e).find("li"),c=n.closest(".accordion-section-content");if(!r.length){var l=I("<li>"),e=I("<p>",{text:navMenuL10n.noResultsFound});return l.append(e),I(".categorychecklist",n).empty().append(l),I(".spinner",n).removeClass("is-active"),void c.addClass("has-no-menu-item")}r.each(function(){if(s=I(this),(i=o.exec(s.html()))&&i[1]){for(a=i[1];u.elements["menu-item["+a+"][menu-item-type]"]||m[a];)a--;m[a]=!0,a!=i[1]&&s.html(s.html().replace(new RegExp("menu-item\\["+i[1]+"\\]","g"),"menu-item["+a+"]"))}}),I(".categorychecklist",n).html(r),I(".spinner",n).removeClass("is-active"),c.removeClass("has-no-menu-item")},removeMenuItem:function(t){var n=t.childMenuItems();t.addClass("deleting").animate({opacity:0,height:0},350,function(){var e=I("#menu-instructions");t.remove(),n.shiftDepthClass(-1).updateParentMenuItemDBId(),0===I("#menu-to-edit li").length&&(I(".drag-instructions").hide(),e.removeClass("menu-instructions-inactive")),y.refreshAdvancedAccessibility()})},depthToPx:function(e){return e*y.options.menuItemDepthPerLevel},pxToDepth:function(e){return Math.floor(e/y.options.menuItemDepthPerLevel)}};I(document).ready(function(){wpNavMenu.init()})}(jQuery); color-picker.min.js 0000666 00000006005 15213733063 0010265 0 ustar 00 !function(i,o){var e={options:{defaultColor:!1,change:!1,clear:!1,hide:!0,palettes:!0,width:255,mode:"hsv",type:"full",slider:"horizontal"},_createHueOnly:function(){var e,t=this,o=t.element;o.hide(),e="hsl("+o.val()+", 100, 50)",o.iris({mode:"hsl",type:"hue",hide:!1,color:e,change:function(e,o){i.isFunction(t.options.change)&&t.options.change.call(this,e,o)},width:t.options.width,slider:t.options.slider})},_create:function(){if(i.support.iris){var t=this,e=t.element;if(i.extend(t.options,e.data()),"hue"===t.options.type)return t._createHueOnly();t.close=i.proxy(t.close,t),t.initialValue=e.val(),e.addClass("wp-color-picker").hide().wrap('<div class="wp-picker-container" />'),t.wrap=e.parent(),t.toggler=i('<a tabindex="0" class="wp-color-result" />').insertBefore(e).css({backgroundColor:t.initialValue}).attr("title",wpColorPickerL10n.pick).attr("data-current",wpColorPickerL10n.current),t.pickerContainer=i('<div class="wp-picker-holder" />').insertAfter(e),t.button=i('<input type="button" class="button button-small hidden" />'),t.options.defaultColor?t.button.addClass("wp-picker-default").val(wpColorPickerL10n.defaultString):t.button.addClass("wp-picker-clear").val(wpColorPickerL10n.clear),e.wrap('<span class="wp-picker-input-wrap" />').after(t.button),e.iris({target:t.pickerContainer,hide:t.options.hide,width:t.options.width,mode:t.options.mode,palettes:t.options.palettes,change:function(e,o){t.toggler.css({backgroundColor:o.color.toString()}),i.isFunction(t.options.change)&&t.options.change.call(this,e,o)}}),e.val(t.initialValue),t._addListeners(),t.options.hide||t.toggler.click()}},_addListeners:function(){var t=this;t.wrap.on("click.wpcolorpicker",function(e){e.stopPropagation()}),t.toggler.click(function(){t.toggler.hasClass("wp-picker-open")?t.close():t.open()}),t.element.change(function(e){var o=i(this).val();""!==o&&"#"!==o||(t.toggler.css("backgroundColor",""),i.isFunction(t.options.clear)&&t.options.clear.call(this,e))}),t.toggler.on("keyup",function(e){13!==e.keyCode&&32!==e.keyCode||(e.preventDefault(),t.toggler.trigger("click").next().focus())}),t.button.click(function(e){var o=i(this);o.hasClass("wp-picker-clear")?(t.element.val(""),t.toggler.css("backgroundColor",""),i.isFunction(t.options.clear)&&t.options.clear.call(this,e)):o.hasClass("wp-picker-default")&&t.element.val(t.options.defaultColor).change()})},open:function(){this.element.show().iris("toggle").focus(),this.button.removeClass("hidden"),this.wrap.addClass("wp-picker-active"),this.toggler.addClass("wp-picker-open"),i("body").trigger("click.wpcolorpicker").on("click.wpcolorpicker",this.close)},close:function(){this.element.hide().iris("toggle"),this.button.addClass("hidden"),this.wrap.removeClass("wp-picker-active"),this.toggler.removeClass("wp-picker-open"),i("body").off("click.wpcolorpicker",this.close)},color:function(e){if(e===o)return this.element.iris("option","color");this.element.iris("option","color",e)},defaultColor:function(e){if(e===o)return this.options.defaultColor;this.options.defaultColor=e}};i.widget("wp.wpColorPicker",e)}(jQuery); custom-background.min.js 0000666 00000002212 15213733063 0011317 0 ustar 00 !function(e){e(document).ready(function(){var o,a=e("#custom-background-image");e("#background-color").wpColorPicker({change:function(n,c){a.css("background-color",c.color.toString())},clear:function(){a.css("background-color","")}}),e('select[name="background-size"]').change(function(){a.css("background-size",e(this).val())}),e('input[name="background-position"]').change(function(){a.css("background-position",e(this).val())}),e('input[name="background-repeat"]').change(function(){a.css("background-repeat",e(this).is(":checked")?"repeat":"no-repeat")}),e('input[name="background-attachment"]').change(function(){a.css("background-attachment",e(this).is(":checked")?"scroll":"fixed")}),e("#choose-from-library-link").click(function(n){var c=e(this);n.preventDefault(),o||(o=wp.media.frames.customBackground=wp.media({title:c.data("choose"),library:{type:"image"},button:{text:c.data("update"),close:!1}})).on("select",function(){var n=o.state().get("selection").first(),c=e("#_wpnonce").val()||"";e.post(ajaxurl,{action:"set-background-image",attachment_id:n.id,_ajax_nonce:c,size:"full"}).done(function(){window.location.reload()})}),o.open()})})}(jQuery); media-upload.min.js 0000666 00000002143 15213733063 0010234 0 ustar 00 var wpActiveEditor,tb_position,send_to_editor=function(t){var e,i="undefined"!=typeof tinymce,n="undefined"!=typeof QTags;if(wpActiveEditor)i&&(e=tinymce.get(wpActiveEditor));else if(i&&tinymce.activeEditor)e=tinymce.activeEditor,wpActiveEditor=e.id;else if(!n)return!1;if(e&&!e.isHidden()?e.execCommand("mceInsertContent",!1,t):n?QTags.insertContent(t):document.getElementById(wpActiveEditor).value+=t,window.tb_remove)try{window.tb_remove()}catch(t){}};!function(d){tb_position=function(){var t=d("#TB_window"),e=d(window).width(),i=d(window).height(),n=833<e?833:e,o=0;return d("#wpadminbar").length&&(o=parseInt(d("#wpadminbar").css("height"),10)),t.length&&(t.width(n-50).height(i-45-o),d("#TB_iframeContent").width(n-50).height(i-75-o),t.css({"margin-left":"-"+parseInt((n-50)/2,10)+"px"}),void 0!==document.body.style.maxWidth&&t.css({top:20+o+"px","margin-top":"0"})),d("a.thickbox").each(function(){var t=d(this).attr("href");t&&(t=(t=t.replace(/&width=[0-9]+/g,"")).replace(/&height=[0-9]+/g,""),d(this).attr("href",t+"&width="+(n-80)+"&height="+(i-85-o)))})},d(window).resize(function(){tb_position()})}(jQuery); word-count.js 0000666 00000017116 15213733063 0007220 0 ustar 00 /** * Word or character counting functionality. Count words or characters in a provided text string. * * @summary Count words or characters in a text. * * @namespace wp.utils * @since 2.6 */ ( function() { /** * Word counting utility * * @namespace wp.utils.wordcounter * @memberof wp.utils * * @class * * @param {Object} settings Optional. Key-value object containing overrides for * settings. * @param {RegExp} settings.HTMLRegExp Optional. Regular expression to find HTML elements. * @param {RegExp} settings.HTMLcommentRegExp Optional. Regular expression to find HTML comments. * @param {RegExp} settings.spaceRegExp Optional. Regular expression to find irregular space * characters. * @param {RegExp} settings.HTMLEntityRegExp Optional. Regular expression to find HTML entities. * @param {RegExp} settings.connectorRegExp Optional. Regular expression to find connectors that * split words. * @param {RegExp} settings.removeRegExp Optional. Regular expression to find remove unwanted * characters to reduce false-positives. * @param {RegExp} settings.astralRegExp Optional. Regular expression to find unwanted * characters when searching for non-words. * @param {RegExp} settings.wordsRegExp Optional. Regular expression to find words by spaces. * @param {RegExp} settings.characters_excluding_spacesRegExp Optional. Regular expression to find characters which * are non-spaces. * @param {RegExp} settings.characters_including_spacesRegExp Optional. Regular expression to find characters * including spaces. * @param {RegExp} settings.shortcodesRegExp Optional. Regular expression to find shortcodes. * @param {Object} settings.l10n Optional. Localization object containing specific * configuration for the current localization. * @param {String} settings.l10n.type Optional. Method of finding words to count. * @param {Array} settings.l10n.shortcodes Optional. Array of shortcodes that should be removed * from the text. * * @return void */ function WordCounter( settings ) { var key, shortcodes; // Apply provided settings to object settings. if ( settings ) { for ( key in settings ) { // Only apply valid settings. if ( settings.hasOwnProperty( key ) ) { this.settings[ key ] = settings[ key ]; } } } shortcodes = this.settings.l10n.shortcodes; // If there are any localization shortcodes, add this as type in the settings. if ( shortcodes && shortcodes.length ) { this.settings.shortcodesRegExp = new RegExp( '\\[\\/?(?:' + shortcodes.join( '|' ) + ')[^\\]]*?\\]', 'g' ); } } // Default settings. WordCounter.prototype.settings = { HTMLRegExp: /<\/?[a-z][^>]*?>/gi, HTMLcommentRegExp: /<!--[\s\S]*?-->/g, spaceRegExp: / | /gi, HTMLEntityRegExp: /&\S+?;/g, // \u2014 = em-dash connectorRegExp: /--|\u2014/g, // Characters to be removed from input text. removeRegExp: new RegExp( [ '[', // Basic Latin (extract) '\u0021-\u0040\u005B-\u0060\u007B-\u007E', // Latin-1 Supplement (extract) '\u0080-\u00BF\u00D7\u00F7', /* * The following range consists of: * General Punctuation * Superscripts and Subscripts * Currency Symbols * Combining Diacritical Marks for Symbols * Letterlike Symbols * Number Forms * Arrows * Mathematical Operators * Miscellaneous Technical * Control Pictures * Optical Character Recognition * Enclosed Alphanumerics * Box Drawing * Block Elements * Geometric Shapes * Miscellaneous Symbols * Dingbats * Miscellaneous Mathematical Symbols-A * Supplemental Arrows-A * Braille Patterns * Supplemental Arrows-B * Miscellaneous Mathematical Symbols-B * Supplemental Mathematical Operators * Miscellaneous Symbols and Arrows */ '\u2000-\u2BFF', // Supplemental Punctuation '\u2E00-\u2E7F', ']' ].join( '' ), 'g' ), // Remove UTF-16 surrogate points, see https://en.wikipedia.org/wiki/UTF-16#U.2BD800_to_U.2BDFFF astralRegExp: /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, wordsRegExp: /\S\s+/g, characters_excluding_spacesRegExp: /\S/g, /* * Match anything that is not a formatting character, excluding: * \f = form feed * \n = new line * \r = carriage return * \t = tab * \v = vertical tab * \u00AD = soft hyphen * \u2028 = line separator * \u2029 = paragraph separator */ characters_including_spacesRegExp: /[^\f\n\r\t\v\u00AD\u2028\u2029]/g, l10n: window.wordCountL10n || {} }; /** * Counts the number of words (or other specified type) in the specified text. * * @summary Count the number of elements in a text. * * @since 2.6 * @memberof wp.utils.wordcounter * * @param {String} text Text to count elements in. * @param {String} type Optional. Specify type to use. * * @return {Number} The number of items counted. */ WordCounter.prototype.count = function( text, type ) { var count = 0; // Use default type if none was provided. type = type || this.settings.l10n.type; // Sanitize type to one of three possibilities: 'words', 'characters_excluding_spaces' or 'characters_including_spaces'. if ( type !== 'characters_excluding_spaces' && type !== 'characters_including_spaces' ) { type = 'words'; } // If we have any text at all. if ( text ) { text = text + '\n'; // Replace all HTML with a new-line. text = text.replace( this.settings.HTMLRegExp, '\n' ); // Remove all HTML comments. text = text.replace( this.settings.HTMLcommentRegExp, '' ); // If a shortcode regular expression has been provided use it to remove shortcodes. if ( this.settings.shortcodesRegExp ) { text = text.replace( this.settings.shortcodesRegExp, '\n' ); } // Normalize non-breaking space to a normal space. text = text.replace( this.settings.spaceRegExp, ' ' ); if ( type === 'words' ) { // Remove HTML Entities. text = text.replace( this.settings.HTMLEntityRegExp, '' ); // Convert connectors to spaces to count attached text as words. text = text.replace( this.settings.connectorRegExp, ' ' ); // Remove unwanted characters. text = text.replace( this.settings.removeRegExp, '' ); } else { // Convert HTML Entities to "a". text = text.replace( this.settings.HTMLEntityRegExp, 'a' ); // Remove surrogate points. text = text.replace( this.settings.astralRegExp, 'a' ); } // Match with the selected type regular expression to count the items. text = text.match( this.settings[ type + 'RegExp' ] ); // If we have any matches, set the count to the number of items found. if ( text ) { count = text.length; } } return count; }; // Add the WordCounter to the WP Utils. window.wp = window.wp || {}; window.wp.utils = window.wp.utils || {}; window.wp.utils.WordCounter = WordCounter; } )(); xfn.min.js 0000666 00000000671 15213733063 0006472 0 ustar 00 jQuery(document).ready(function(n){n("#link_rel").prop("readonly",!0),n("#linkxfndiv input").bind("click keyup",function(){var e=n("#me").is(":checked"),i="";n("input.valinp").each(function(){e?n(this).prop("disabled",!0).parent().addClass("disabled"):(n(this).removeAttr("disabled").parent().removeClass("disabled"),n(this).is(":checked")&&""!==n(this).val()&&(i+=n(this).val()+" "))}),n("#link_rel").val(e?"me":i.substr(0,i.length-1))})}); media-upload.js 0000666 00000003700 15213733063 0007452 0 ustar 00 /* global tinymce, QTags */ // send html to the post editor var wpActiveEditor, send_to_editor; send_to_editor = function( html ) { var editor, hasTinymce = typeof tinymce !== 'undefined', hasQuicktags = typeof QTags !== 'undefined'; if ( ! wpActiveEditor ) { if ( hasTinymce && tinymce.activeEditor ) { editor = tinymce.activeEditor; wpActiveEditor = editor.id; } else if ( ! hasQuicktags ) { return false; } } else if ( hasTinymce ) { editor = tinymce.get( wpActiveEditor ); } if ( editor && ! editor.isHidden() ) { editor.execCommand( 'mceInsertContent', false, html ); } else if ( hasQuicktags ) { QTags.insertContent( html ); } else { document.getElementById( wpActiveEditor ).value += html; } // If the old thickbox remove function exists, call it if ( window.tb_remove ) { try { window.tb_remove(); } catch( e ) {} } }; // thickbox settings var tb_position; (function($) { tb_position = function() { var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 833 < width ) ? 833 : width, adminbar_height = 0; if ( $('#wpadminbar').length ) { adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 ); } if ( tbWindow.length ) { 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(); }); })(jQuery); updates.js 0000666 00000232142 15213733063 0006562 0 ustar 00 /** * Functions for ajaxified updates, deletions and installs inside the WordPress admin. * * @version 4.2.0 * * @package WordPress * @subpackage Administration */ /* global pagenow */ /** * @param {jQuery} $ jQuery object. * @param {object} wp WP object. * @param {object} settings WP Updates settings. * @param {string} settings.ajax_nonce AJAX nonce. * @param {object} settings.l10n Translation strings. * @param {object=} settings.plugins Base names of plugins in their different states. * @param {Array} settings.plugins.all Base names of all plugins. * @param {Array} settings.plugins.active Base names of active plugins. * @param {Array} settings.plugins.inactive Base names of inactive plugins. * @param {Array} settings.plugins.upgrade Base names of plugins with updates available. * @param {Array} settings.plugins.recently_activated Base names of recently activated plugins. * @param {object=} settings.themes Plugin/theme status information or null. * @param {number} settings.themes.all Amount of all themes. * @param {number} settings.themes.upgrade Amount of themes with updates available. * @param {number} settings.themes.disabled Amount of disabled themes. * @param {object=} settings.totals Combined information for available update counts. * @param {number} settings.totals.count Holds the amount of available updates. */ (function( $, wp, settings ) { var $document = $( document ); wp = wp || {}; /** * The WP Updates object. * * @since 4.2.0 * * @type {object} */ wp.updates = {}; /** * User nonce for ajax calls. * * @since 4.2.0 * * @type {string} */ wp.updates.ajaxNonce = settings.ajax_nonce; /** * Localized strings. * * @since 4.2.0 * * @type {object} */ wp.updates.l10n = settings.l10n; /** * Current search term. * * @since 4.6.0 * * @type {string} */ wp.updates.searchTerm = ''; /** * Whether filesystem credentials need to be requested from the user. * * @since 4.2.0 * * @type {bool} */ wp.updates.shouldRequestFilesystemCredentials = false; /** * Filesystem credentials to be packaged along with the request. * * @since 4.2.0 * @since 4.6.0 Added `available` property to indicate whether credentials have been provided. * * @type {object} filesystemCredentials Holds filesystem credentials. * @type {object} filesystemCredentials.ftp Holds FTP credentials. * @type {string} filesystemCredentials.ftp.host FTP host. Default empty string. * @type {string} filesystemCredentials.ftp.username FTP user name. Default empty string. * @type {string} filesystemCredentials.ftp.password FTP password. Default empty string. * @type {string} filesystemCredentials.ftp.connectionType Type of FTP connection. 'ssh', 'ftp', or 'ftps'. * Default empty string. * @type {object} filesystemCredentials.ssh Holds SSH credentials. * @type {string} filesystemCredentials.ssh.publicKey The public key. Default empty string. * @type {string} filesystemCredentials.ssh.privateKey The private key. Default empty string. * @type {string} filesystemCredentials.fsNonce Filesystem credentials form nonce. * @type {bool} filesystemCredentials.available Whether filesystem credentials have been provided. * Default 'false'. */ wp.updates.filesystemCredentials = { ftp: { host: '', username: '', password: '', connectionType: '' }, ssh: { publicKey: '', privateKey: '' }, fsNonce: '', available: false }; /** * Whether we're waiting for an Ajax request to complete. * * @since 4.2.0 * @since 4.6.0 More accurately named `ajaxLocked`. * * @type {bool} */ wp.updates.ajaxLocked = false; /** * Admin notice template. * * @since 4.6.0 * * @type {function} A function that lazily-compiles the template requested. */ wp.updates.adminNotice = wp.template( 'wp-updates-admin-notice' ); /** * Update queue. * * If the user tries to update a plugin while an update is * already happening, it can be placed in this queue to perform later. * * @since 4.2.0 * @since 4.6.0 More accurately named `queue`. * * @type {Array.object} */ wp.updates.queue = []; /** * Holds a jQuery reference to return focus to when exiting the request credentials modal. * * @since 4.2.0 * * @type {jQuery} */ wp.updates.$elToReturnFocusToFromCredentialsModal = undefined; /** * Adds or updates an admin notice. * * @since 4.6.0 * * @param {object} data * @param {*=} data.selector Optional. Selector of an element to be replaced with the admin notice. * @param {string=} data.id Optional. Unique id that will be used as the notice's id attribute. * @param {string=} data.className Optional. Class names that will be used in the admin notice. * @param {string=} data.message Optional. The message displayed in the notice. * @param {number=} data.successes Optional. The amount of successful operations. * @param {number=} data.errors Optional. The amount of failed operations. * @param {Array=} data.errorMessages Optional. Error messages of failed operations. * */ wp.updates.addAdminNotice = function( data ) { var $notice = $( data.selector ), $adminNotice; delete data.selector; $adminNotice = wp.updates.adminNotice( data ); // Check if this admin notice already exists. if ( ! $notice.length ) { $notice = $( '#' + data.id ); } if ( $notice.length ) { $notice.replaceWith( $adminNotice ); } else { $( '.wrap' ).find( '> h1' ).after( $adminNotice ); } $document.trigger( 'wp-updates-notice-added' ); }; /** * Handles Ajax requests to WordPress. * * @since 4.6.0 * * @param {string} action The type of Ajax request ('update-plugin', 'install-theme', etc). * @param {object} data Data that needs to be passed to the ajax callback. * @return {$.promise} A jQuery promise that represents the request, * decorated with an abort() method. */ wp.updates.ajax = function( action, data ) { var options = {}; if ( wp.updates.ajaxLocked ) { wp.updates.queue.push( { action: action, data: data } ); // Return a Deferred object so callbacks can always be registered. return $.Deferred(); } wp.updates.ajaxLocked = true; if ( data.success ) { options.success = data.success; delete data.success; } if ( data.error ) { options.error = data.error; delete data.error; } options.data = _.extend( data, { action: action, _ajax_nonce: wp.updates.ajaxNonce, _fs_nonce: wp.updates.filesystemCredentials.fsNonce, username: wp.updates.filesystemCredentials.ftp.username, password: wp.updates.filesystemCredentials.ftp.password, hostname: wp.updates.filesystemCredentials.ftp.hostname, connection_type: wp.updates.filesystemCredentials.ftp.connectionType, public_key: wp.updates.filesystemCredentials.ssh.publicKey, private_key: wp.updates.filesystemCredentials.ssh.privateKey } ); return wp.ajax.send( options ).always( wp.updates.ajaxAlways ); }; /** * Actions performed after every Ajax request. * * @since 4.6.0 * * @param {object} response * @param {array=} response.debug Optional. Debug information. * @param {string=} response.errorCode Optional. Error code for an error that occurred. */ wp.updates.ajaxAlways = function( response ) { if ( ! response.errorCode || 'unable_to_connect_to_filesystem' !== response.errorCode ) { wp.updates.ajaxLocked = false; wp.updates.queueChecker(); } if ( 'undefined' !== typeof response.debug && window.console && window.console.log ) { _.map( response.debug, function( message ) { window.console.log( $( '<p />' ).html( message ).text() ); } ); } }; /** * Refreshes update counts everywhere on the screen. * * @since 4.7.0 */ wp.updates.refreshCount = function() { var $adminBarUpdates = $( '#wp-admin-bar-updates' ), $dashboardNavMenuUpdateCount = $( 'a[href="update-core.php"] .update-plugins' ), $pluginsNavMenuUpdateCount = $( 'a[href="plugins.php"] .update-plugins' ), $appearanceNavMenuUpdateCount = $( 'a[href="themes.php"] .update-plugins' ), itemCount; $adminBarUpdates.find( '.ab-item' ).removeAttr( 'title' ); $adminBarUpdates.find( '.ab-label' ).text( settings.totals.counts.total ); // Remove the update count from the toolbar if it's zero. if ( 0 === settings.totals.counts.total ) { $adminBarUpdates.find( '.ab-label' ).parents( 'li' ).remove(); } // Update the "Updates" menu item. $dashboardNavMenuUpdateCount.each( function( index, element ) { element.className = element.className.replace( /count-\d+/, 'count-' + settings.totals.counts.total ); } ); if ( settings.totals.counts.total > 0 ) { $dashboardNavMenuUpdateCount.find( '.update-count' ).text( settings.totals.counts.total ); } else { $dashboardNavMenuUpdateCount.remove(); } // Update the "Plugins" menu item. $pluginsNavMenuUpdateCount.each( function( index, element ) { element.className = element.className.replace( /count-\d+/, 'count-' + settings.totals.counts.plugins ); } ); if ( settings.totals.counts.total > 0 ) { $pluginsNavMenuUpdateCount.find( '.plugin-count' ).text( settings.totals.counts.plugins ); } else { $pluginsNavMenuUpdateCount.remove(); } // Update the "Appearance" menu item. $appearanceNavMenuUpdateCount.each( function( index, element ) { element.className = element.className.replace( /count-\d+/, 'count-' + settings.totals.counts.themes ); } ); if ( settings.totals.counts.total > 0 ) { $appearanceNavMenuUpdateCount.find( '.theme-count' ).text( settings.totals.counts.themes ); } else { $appearanceNavMenuUpdateCount.remove(); } // Update list table filter navigation. if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) { itemCount = settings.totals.counts.plugins; } else if ( 'themes' === pagenow || 'themes-network' === pagenow ) { itemCount = settings.totals.counts.themes; } if ( itemCount > 0 ) { $( '.subsubsub .upgrade .count' ).text( '(' + itemCount + ')' ); } else { $( '.subsubsub .upgrade' ).remove(); } }; /** * Decrements the update counts throughout the various menus. * * This includes the toolbar, the "Updates" menu item and the menu items * for plugins and themes. * * @since 3.9.0 * * @param {string} type The type of item that was updated or deleted. * Can be 'plugin', 'theme'. */ wp.updates.decrementCount = function( type ) { settings.totals.counts.total = Math.max( --settings.totals.counts.total, 0 ); if ( 'plugin' === type ) { settings.totals.counts.plugins = Math.max( --settings.totals.counts.plugins, 0 ); } else if ( 'theme' === type ) { settings.totals.counts.themes = Math.max( --settings.totals.counts.themes, 0 ); } wp.updates.refreshCount( type ); }; /** * Sends an Ajax request to the server to update a plugin. * * @since 4.2.0 * @since 4.6.0 More accurately named `updatePlugin`. * * @param {object} args Arguments. * @param {string} args.plugin Plugin basename. * @param {string} args.slug Plugin slug. * @param {updatePluginSuccess=} args.success Optional. Success callback. Default: wp.updates.updatePluginSuccess * @param {updatePluginError=} args.error Optional. Error callback. Default: wp.updates.updatePluginError * @return {$.promise} A jQuery promise that represents the request, * decorated with an abort() method. */ wp.updates.updatePlugin = function( args ) { var $updateRow, $card, $message, message; args = _.extend( { success: wp.updates.updatePluginSuccess, error: wp.updates.updatePluginError }, args ); if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) { $updateRow = $( 'tr[data-plugin="' + args.plugin + '"]' ); $message = $updateRow.find( '.update-message' ).removeClass( 'notice-error' ).addClass( 'updating-message notice-warning' ).find( 'p' ); message = wp.updates.l10n.updatingLabel.replace( '%s', $updateRow.find( '.plugin-title strong' ).text() ); } else if ( 'plugin-install' === pagenow || 'plugin-install-network' === pagenow ) { $card = $( '.plugin-card-' + args.slug ); $message = $card.find( '.update-now' ).addClass( 'updating-message' ); message = wp.updates.l10n.updatingLabel.replace( '%s', $message.data( 'name' ) ); // Remove previous error messages, if any. $card.removeClass( 'plugin-card-update-failed' ).find( '.notice.notice-error' ).remove(); } if ( $message.html() !== wp.updates.l10n.updating ) { $message.data( 'originaltext', $message.html() ); } $message .attr( 'aria-label', message ) .text( wp.updates.l10n.updating ); $document.trigger( 'wp-plugin-updating', args ); return wp.updates.ajax( 'update-plugin', args ); }; /** * Updates the UI appropriately after a successful plugin update. * * @since 4.2.0 * @since 4.6.0 More accurately named `updatePluginSuccess`. * * @typedef {object} updatePluginSuccess * @param {object} response Response from the server. * @param {string} response.slug Slug of the plugin to be updated. * @param {string} response.plugin Basename of the plugin to be updated. * @param {string} response.pluginName Name of the plugin to be updated. * @param {string} response.oldVersion Old version of the plugin. * @param {string} response.newVersion New version of the plugin. */ wp.updates.updatePluginSuccess = function( response ) { var $pluginRow, $updateMessage, newText; if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) { $pluginRow = $( 'tr[data-plugin="' + response.plugin + '"]' ) .removeClass( 'update' ) .addClass( 'updated' ); $updateMessage = $pluginRow.find( '.update-message' ) .removeClass( 'updating-message notice-warning' ) .addClass( 'updated-message notice-success' ).find( 'p' ); // Update the version number in the row. newText = $pluginRow.find( '.plugin-version-author-uri' ).html().replace( response.oldVersion, response.newVersion ); $pluginRow.find( '.plugin-version-author-uri' ).html( newText ); } else if ( 'plugin-install' === pagenow || 'plugin-install-network' === pagenow ) { $updateMessage = $( '.plugin-card-' + response.slug ).find( '.update-now' ) .removeClass( 'updating-message' ) .addClass( 'button-disabled updated-message' ); } $updateMessage .attr( 'aria-label', wp.updates.l10n.updatedLabel.replace( '%s', response.pluginName ) ) .text( wp.updates.l10n.updated ); wp.a11y.speak( wp.updates.l10n.updatedMsg, 'polite' ); wp.updates.decrementCount( 'plugin' ); $document.trigger( 'wp-plugin-update-success', response ); }; /** * Updates the UI appropriately after a failed plugin update. * * @since 4.2.0 * @since 4.6.0 More accurately named `updatePluginError`. * * @typedef {object} updatePluginError * @param {object} response Response from the server. * @param {string} response.slug Slug of the plugin to be updated. * @param {string} response.plugin Basename of the plugin to be updated. * @param {string=} response.pluginName Optional. Name of the plugin to be updated. * @param {string} response.errorCode Error code for the error that occurred. * @param {string} response.errorMessage The error that occurred. */ wp.updates.updatePluginError = function( response ) { var $card, $message, errorMessage; if ( ! wp.updates.isValidResponse( response, 'update' ) ) { return; } if ( wp.updates.maybeHandleCredentialError( response, 'update-plugin' ) ) { return; } errorMessage = wp.updates.l10n.updateFailed.replace( '%s', response.errorMessage ); if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) { if ( response.plugin ) { $message = $( 'tr[data-plugin="' + response.plugin + '"]' ).find( '.update-message' ); } else { $message = $( 'tr[data-slug="' + response.slug + '"]' ).find( '.update-message' ); } $message.removeClass( 'updating-message notice-warning' ).addClass( 'notice-error' ).find( 'p' ).html( errorMessage ); if ( response.pluginName ) { $message.find( 'p' ) .attr( 'aria-label', wp.updates.l10n.updateFailedLabel.replace( '%s', response.pluginName ) ); } else { $message.find( 'p' ).removeAttr( 'aria-label' ); } } else if ( 'plugin-install' === pagenow || 'plugin-install-network' === pagenow ) { $card = $( '.plugin-card-' + response.slug ) .addClass( 'plugin-card-update-failed' ) .append( wp.updates.adminNotice( { className: 'update-message notice-error notice-alt is-dismissible', message: errorMessage } ) ); $card.find( '.update-now' ) .text( wp.updates.l10n.updateFailedShort ).removeClass( 'updating-message' ); if ( response.pluginName ) { $card.find( '.update-now' ) .attr( 'aria-label', wp.updates.l10n.updateFailedLabel.replace( '%s', response.pluginName ) ); } else { $card.find( '.update-now' ).removeAttr( 'aria-label' ); } $card.on( 'click', '.notice.is-dismissible .notice-dismiss', function() { // Use same delay as the total duration of the notice fadeTo + slideUp animation. setTimeout( function() { $card .removeClass( 'plugin-card-update-failed' ) .find( '.column-name a' ).focus(); $card.find( '.update-now' ) .attr( 'aria-label', false ) .text( wp.updates.l10n.updateNow ); }, 200 ); } ); } wp.a11y.speak( errorMessage, 'assertive' ); $document.trigger( 'wp-plugin-update-error', response ); }; /** * Sends an Ajax request to the server to install a plugin. * * @since 4.6.0 * * @param {object} args Arguments. * @param {string} args.slug Plugin identifier in the WordPress.org Plugin repository. * @param {installPluginSuccess=} args.success Optional. Success callback. Default: wp.updates.installPluginSuccess * @param {installPluginError=} args.error Optional. Error callback. Default: wp.updates.installPluginError * @return {$.promise} A jQuery promise that represents the request, * decorated with an abort() method. */ wp.updates.installPlugin = function( args ) { var $card = $( '.plugin-card-' + args.slug ), $message = $card.find( '.install-now' ); args = _.extend( { success: wp.updates.installPluginSuccess, error: wp.updates.installPluginError }, args ); if ( 'import' === pagenow ) { $message = $( '[data-slug="' + args.slug + '"]' ); } if ( $message.html() !== wp.updates.l10n.installing ) { $message.data( 'originaltext', $message.html() ); } $message .addClass( 'updating-message' ) .attr( 'aria-label', wp.updates.l10n.pluginInstallingLabel.replace( '%s', $message.data( 'name' ) ) ) .text( wp.updates.l10n.installing ); wp.a11y.speak( wp.updates.l10n.installingMsg, 'polite' ); // Remove previous error messages, if any. $card.removeClass( 'plugin-card-install-failed' ).find( '.notice.notice-error' ).remove(); $document.trigger( 'wp-plugin-installing', args ); return wp.updates.ajax( 'install-plugin', args ); }; /** * Updates the UI appropriately after a successful plugin install. * * @since 4.6.0 * * @typedef {object} installPluginSuccess * @param {object} response Response from the server. * @param {string} response.slug Slug of the installed plugin. * @param {string} response.pluginName Name of the installed plugin. * @param {string} response.activateUrl URL to activate the just installed plugin. */ wp.updates.installPluginSuccess = function( response ) { var $message = $( '.plugin-card-' + response.slug ).find( '.install-now' ); $message .removeClass( 'updating-message' ) .addClass( 'updated-message installed button-disabled' ) .attr( 'aria-label', wp.updates.l10n.pluginInstalledLabel.replace( '%s', response.pluginName ) ) .text( wp.updates.l10n.installed ); wp.a11y.speak( wp.updates.l10n.installedMsg, 'polite' ); $document.trigger( 'wp-plugin-install-success', response ); if ( response.activateUrl ) { setTimeout( function() { // Transform the 'Install' button into an 'Activate' button. $message.removeClass( 'install-now installed button-disabled updated-message' ).addClass( 'activate-now button-primary' ) .attr( 'href', response.activateUrl ) .attr( 'aria-label', wp.updates.l10n.activatePluginLabel.replace( '%s', response.pluginName ) ) .text( wp.updates.l10n.activatePlugin ); }, 1000 ); } }; /** * Updates the UI appropriately after a failed plugin install. * * @since 4.6.0 * * @typedef {object} installPluginError * @param {object} response Response from the server. * @param {string} response.slug Slug of the plugin to be installed. * @param {string=} response.pluginName Optional. Name of the plugin to be installed. * @param {string} response.errorCode Error code for the error that occurred. * @param {string} response.errorMessage The error that occurred. */ wp.updates.installPluginError = function( response ) { var $card = $( '.plugin-card-' + response.slug ), $button = $card.find( '.install-now' ), errorMessage; if ( ! wp.updates.isValidResponse( response, 'install' ) ) { return; } if ( wp.updates.maybeHandleCredentialError( response, 'install-plugin' ) ) { return; } errorMessage = wp.updates.l10n.installFailed.replace( '%s', response.errorMessage ); $card .addClass( 'plugin-card-update-failed' ) .append( '<div class="notice notice-error notice-alt is-dismissible"><p>' + errorMessage + '</p></div>' ); $card.on( 'click', '.notice.is-dismissible .notice-dismiss', function() { // Use same delay as the total duration of the notice fadeTo + slideUp animation. setTimeout( function() { $card .removeClass( 'plugin-card-update-failed' ) .find( '.column-name a' ).focus(); }, 200 ); } ); $button .removeClass( 'updating-message' ).addClass( 'button-disabled' ) .attr( 'aria-label', wp.updates.l10n.pluginInstallFailedLabel.replace( '%s', $button.data( 'name' ) ) ) .text( wp.updates.l10n.installFailedShort ); wp.a11y.speak( errorMessage, 'assertive' ); $document.trigger( 'wp-plugin-install-error', response ); }; /** * Updates the UI appropriately after a successful importer install. * * @since 4.6.0 * * @typedef {object} installImporterSuccess * @param {object} response Response from the server. * @param {string} response.slug Slug of the installed plugin. * @param {string} response.pluginName Name of the installed plugin. * @param {string} response.activateUrl URL to activate the just installed plugin. */ wp.updates.installImporterSuccess = function( response ) { wp.updates.addAdminNotice( { id: 'install-success', className: 'notice-success is-dismissible', message: wp.updates.l10n.importerInstalledMsg.replace( '%s', response.activateUrl + '&from=import' ) } ); $( '[data-slug="' + response.slug + '"]' ) .removeClass( 'install-now updating-message' ) .addClass( 'activate-now' ) .attr({ 'href': response.activateUrl + '&from=import', 'aria-label': wp.updates.l10n.activateImporterLabel.replace( '%s', response.pluginName ) }) .text( wp.updates.l10n.activateImporter ); wp.a11y.speak( wp.updates.l10n.installedMsg, 'polite' ); $document.trigger( 'wp-importer-install-success', response ); }; /** * Updates the UI appropriately after a failed importer install. * * @since 4.6.0 * * @typedef {object} installImporterError * @param {object} response Response from the server. * @param {string} response.slug Slug of the plugin to be installed. * @param {string=} response.pluginName Optional. Name of the plugin to be installed. * @param {string} response.errorCode Error code for the error that occurred. * @param {string} response.errorMessage The error that occurred. */ wp.updates.installImporterError = function( response ) { var errorMessage = wp.updates.l10n.installFailed.replace( '%s', response.errorMessage ), $installLink = $( '[data-slug="' + response.slug + '"]' ), pluginName = $installLink.data( 'name' ); if ( ! wp.updates.isValidResponse( response, 'install' ) ) { return; } if ( wp.updates.maybeHandleCredentialError( response, 'install-plugin' ) ) { return; } wp.updates.addAdminNotice( { id: response.errorCode, className: 'notice-error is-dismissible', message: errorMessage } ); $installLink .removeClass( 'updating-message' ) .text( wp.updates.l10n.installNow ) .attr( 'aria-label', wp.updates.l10n.installNowLabel.replace( '%s', pluginName ) ); wp.a11y.speak( errorMessage, 'assertive' ); $document.trigger( 'wp-importer-install-error', response ); }; /** * Sends an Ajax request to the server to delete a plugin. * * @since 4.6.0 * * @param {object} args Arguments. * @param {string} args.plugin Basename of the plugin to be deleted. * @param {string} args.slug Slug of the plugin to be deleted. * @param {deletePluginSuccess=} args.success Optional. Success callback. Default: wp.updates.deletePluginSuccess * @param {deletePluginError=} args.error Optional. Error callback. Default: wp.updates.deletePluginError * @return {$.promise} A jQuery promise that represents the request, * decorated with an abort() method. */ wp.updates.deletePlugin = function( args ) { var $link = $( '[data-plugin="' + args.plugin + '"]' ).find( '.row-actions a.delete' ); args = _.extend( { success: wp.updates.deletePluginSuccess, error: wp.updates.deletePluginError }, args ); if ( $link.html() !== wp.updates.l10n.deleting ) { $link .data( 'originaltext', $link.html() ) .text( wp.updates.l10n.deleting ); } wp.a11y.speak( wp.updates.l10n.deleting, 'polite' ); $document.trigger( 'wp-plugin-deleting', args ); return wp.updates.ajax( 'delete-plugin', args ); }; /** * Updates the UI appropriately after a successful plugin deletion. * * @since 4.6.0 * * @typedef {object} deletePluginSuccess * @param {object} response Response from the server. * @param {string} response.slug Slug of the plugin that was deleted. * @param {string} response.plugin Base name of the plugin that was deleted. * @param {string} response.pluginName Name of the plugin that was deleted. */ wp.updates.deletePluginSuccess = function( response ) { // Removes the plugin and updates rows. $( '[data-plugin="' + response.plugin + '"]' ).css( { backgroundColor: '#faafaa' } ).fadeOut( 350, function() { var $form = $( '#bulk-action-form' ), $views = $( '.subsubsub' ), $pluginRow = $( this ), columnCount = $form.find( 'thead th:not(.hidden), thead td' ).length, pluginDeletedRow = wp.template( 'item-deleted-row' ), /** @type {object} plugins Base names of plugins in their different states. */ plugins = settings.plugins; // Add a success message after deleting a plugin. if ( ! $pluginRow.hasClass( 'plugin-update-tr' ) ) { $pluginRow.after( pluginDeletedRow( { slug: response.slug, plugin: response.plugin, colspan: columnCount, name: response.pluginName } ) ); } $pluginRow.remove(); // Remove plugin from update count. if ( -1 !== _.indexOf( plugins.upgrade, response.plugin ) ) { plugins.upgrade = _.without( plugins.upgrade, response.plugin ); wp.updates.decrementCount( 'plugin' ); } // Remove from views. if ( -1 !== _.indexOf( plugins.inactive, response.plugin ) ) { plugins.inactive = _.without( plugins.inactive, response.plugin ); if ( plugins.inactive.length ) { $views.find( '.inactive .count' ).text( '(' + plugins.inactive.length + ')' ); } else { $views.find( '.inactive' ).remove(); } } if ( -1 !== _.indexOf( plugins.active, response.plugin ) ) { plugins.active = _.without( plugins.active, response.plugin ); if ( plugins.active.length ) { $views.find( '.active .count' ).text( '(' + plugins.active.length + ')' ); } else { $views.find( '.active' ).remove(); } } if ( -1 !== _.indexOf( plugins.recently_activated, response.plugin ) ) { plugins.recently_activated = _.without( plugins.recently_activated, response.plugin ); if ( plugins.recently_activated.length ) { $views.find( '.recently_activated .count' ).text( '(' + plugins.recently_activated.length + ')' ); } else { $views.find( '.recently_activated' ).remove(); } } plugins.all = _.without( plugins.all, response.plugin ); if ( plugins.all.length ) { $views.find( '.all .count' ).text( '(' + plugins.all.length + ')' ); } else { $form.find( '.tablenav' ).css( { visibility: 'hidden' } ); $views.find( '.all' ).remove(); if ( ! $form.find( 'tr.no-items' ).length ) { $form.find( '#the-list' ).append( '<tr class="no-items"><td class="colspanchange" colspan="' + columnCount + '">' + wp.updates.l10n.noPlugins + '</td></tr>' ); } } } ); wp.a11y.speak( wp.updates.l10n.deleted, 'polite' ); $document.trigger( 'wp-plugin-delete-success', response ); }; /** * Updates the UI appropriately after a failed plugin deletion. * * @since 4.6.0 * * @typedef {object} deletePluginError * @param {object} response Response from the server. * @param {string} response.slug Slug of the plugin to be deleted. * @param {string} response.plugin Base name of the plugin to be deleted * @param {string=} response.pluginName Optional. Name of the plugin to be deleted. * @param {string} response.errorCode Error code for the error that occurred. * @param {string} response.errorMessage The error that occurred. */ wp.updates.deletePluginError = function( response ) { var $plugin, $pluginUpdateRow, pluginUpdateRow = wp.template( 'item-update-row' ), noticeContent = wp.updates.adminNotice( { className: 'update-message notice-error notice-alt', message: response.errorMessage } ); if ( response.plugin ) { $plugin = $( 'tr.inactive[data-plugin="' + response.plugin + '"]' ); $pluginUpdateRow = $plugin.siblings( '[data-plugin="' + response.plugin + '"]' ); } else { $plugin = $( 'tr.inactive[data-slug="' + response.slug + '"]' ); $pluginUpdateRow = $plugin.siblings( '[data-slug="' + response.slug + '"]' ); } if ( ! wp.updates.isValidResponse( response, 'delete' ) ) { return; } if ( wp.updates.maybeHandleCredentialError( response, 'delete-plugin' ) ) { return; } // Add a plugin update row if it doesn't exist yet. if ( ! $pluginUpdateRow.length ) { $plugin.addClass( 'update' ).after( pluginUpdateRow( { slug: response.slug, plugin: response.plugin || response.slug, colspan: $( '#bulk-action-form' ).find( 'thead th:not(.hidden), thead td' ).length, content: noticeContent } ) ); } else { // Remove previous error messages, if any. $pluginUpdateRow.find( '.notice-error' ).remove(); $pluginUpdateRow.find( '.plugin-update' ).append( noticeContent ); } $document.trigger( 'wp-plugin-delete-error', response ); }; /** * Sends an Ajax request to the server to update a theme. * * @since 4.6.0 * * @param {object} args Arguments. * @param {string} args.slug Theme stylesheet. * @param {updateThemeSuccess=} args.success Optional. Success callback. Default: wp.updates.updateThemeSuccess * @param {updateThemeError=} args.error Optional. Error callback. Default: wp.updates.updateThemeError * @return {$.promise} A jQuery promise that represents the request, * decorated with an abort() method. */ wp.updates.updateTheme = function( args ) { var $notice; args = _.extend( { success: wp.updates.updateThemeSuccess, error: wp.updates.updateThemeError }, args ); if ( 'themes-network' === pagenow ) { $notice = $( '[data-slug="' + args.slug + '"]' ).find( '.update-message' ).removeClass( 'notice-error' ).addClass( 'updating-message notice-warning' ).find( 'p' ); } else { $notice = $( '#update-theme' ).closest( '.notice' ).removeClass( 'notice-large' ); $notice.find( 'h3' ).remove(); $notice = $notice.add( $( '[data-slug="' + args.slug + '"]' ).find( '.update-message' ) ); $notice = $notice.addClass( 'updating-message' ).find( 'p' ); } if ( $notice.html() !== wp.updates.l10n.updating ) { $notice.data( 'originaltext', $notice.html() ); } wp.a11y.speak( wp.updates.l10n.updatingMsg, 'polite' ); $notice.text( wp.updates.l10n.updating ); $document.trigger( 'wp-theme-updating', args ); return wp.updates.ajax( 'update-theme', args ); }; /** * Updates the UI appropriately after a successful theme update. * * @since 4.6.0 * * @typedef {object} updateThemeSuccess * @param {object} response * @param {string} response.slug Slug of the theme to be updated. * @param {object} response.theme Updated theme. * @param {string} response.oldVersion Old version of the theme. * @param {string} response.newVersion New version of the theme. */ wp.updates.updateThemeSuccess = function( response ) { var isModalOpen = $( 'body.modal-open' ).length, $theme = $( '[data-slug="' + response.slug + '"]' ), updatedMessage = { className: 'updated-message notice-success notice-alt', message: wp.updates.l10n.updated }, $notice, newText; if ( 'themes-network' === pagenow ) { $notice = $theme.find( '.update-message' ); // Update the version number in the row. newText = $theme.find( '.theme-version-author-uri' ).html().replace( response.oldVersion, response.newVersion ); $theme.find( '.theme-version-author-uri' ).html( newText ); } else { $notice = $( '.theme-info .notice' ).add( $theme.find( '.update-message' ) ); // Focus on Customize button after updating. if ( isModalOpen ) { $( '.load-customize:visible' ).focus(); } else { $theme.find( '.load-customize' ).focus(); } } wp.updates.addAdminNotice( _.extend( { selector: $notice }, updatedMessage ) ); wp.a11y.speak( wp.updates.l10n.updatedMsg, 'polite' ); wp.updates.decrementCount( 'theme' ); $document.trigger( 'wp-theme-update-success', response ); // Show updated message after modal re-rendered. if ( isModalOpen ) { $( '.theme-info .theme-author' ).after( wp.updates.adminNotice( updatedMessage ) ); } }; /** * Updates the UI appropriately after a failed theme update. * * @since 4.6.0 * * @typedef {object} updateThemeError * @param {object} response Response from the server. * @param {string} response.slug Slug of the theme to be updated. * @param {string} response.errorCode Error code for the error that occurred. * @param {string} response.errorMessage The error that occurred. */ wp.updates.updateThemeError = function( response ) { var $theme = $( '[data-slug="' + response.slug + '"]' ), errorMessage = wp.updates.l10n.updateFailed.replace( '%s', response.errorMessage ), $notice; if ( ! wp.updates.isValidResponse( response, 'update' ) ) { return; } if ( wp.updates.maybeHandleCredentialError( response, 'update-theme' ) ) { return; } if ( 'themes-network' === pagenow ) { $notice = $theme.find( '.update-message ' ); } else { $notice = $( '.theme-info .notice' ).add( $theme.find( '.notice' ) ); $( 'body.modal-open' ).length ? $( '.load-customize:visible' ).focus() : $theme.find( '.load-customize' ).focus(); } wp.updates.addAdminNotice( { selector: $notice, className: 'update-message notice-error notice-alt is-dismissible', message: errorMessage } ); wp.a11y.speak( errorMessage, 'polite' ); $document.trigger( 'wp-theme-update-error', response ); }; /** * Sends an Ajax request to the server to install a theme. * * @since 4.6.0 * * @param {object} args * @param {string} args.slug Theme stylesheet. * @param {installThemeSuccess=} args.success Optional. Success callback. Default: wp.updates.installThemeSuccess * @param {installThemeError=} args.error Optional. Error callback. Default: wp.updates.installThemeError * @return {$.promise} A jQuery promise that represents the request, * decorated with an abort() method. */ wp.updates.installTheme = function( args ) { var $message = $( '.theme-install[data-slug="' + args.slug + '"]' ); args = _.extend( { success: wp.updates.installThemeSuccess, error: wp.updates.installThemeError }, args ); $message.addClass( 'updating-message' ); $message.parents( '.theme' ).addClass( 'focus' ); if ( $message.html() !== wp.updates.l10n.installing ) { $message.data( 'originaltext', $message.html() ); } $message .text( wp.updates.l10n.installing ) .attr( 'aria-label', wp.updates.l10n.themeInstallingLabel.replace( '%s', $message.data( 'name' ) ) ); wp.a11y.speak( wp.updates.l10n.installingMsg, 'polite' ); // Remove previous error messages, if any. $( '.install-theme-info, [data-slug="' + args.slug + '"]' ).removeClass( 'theme-install-failed' ).find( '.notice.notice-error' ).remove(); $document.trigger( 'wp-theme-installing', args ); return wp.updates.ajax( 'install-theme', args ); }; /** * Updates the UI appropriately after a successful theme install. * * @since 4.6.0 * * @typedef {object} installThemeSuccess * @param {object} response Response from the server. * @param {string} response.slug Slug of the theme to be installed. * @param {string} response.customizeUrl URL to the Customizer for the just installed theme. * @param {string} response.activateUrl URL to activate the just installed theme. */ wp.updates.installThemeSuccess = function( response ) { var $card = $( '.wp-full-overlay-header, [data-slug=' + response.slug + ']' ), $message; $document.trigger( 'wp-theme-install-success', response ); $message = $card.find( '.button-primary' ) .removeClass( 'updating-message' ) .addClass( 'updated-message disabled' ) .attr( 'aria-label', wp.updates.l10n.themeInstalledLabel.replace( '%s', response.themeName ) ) .text( wp.updates.l10n.installed ); wp.a11y.speak( wp.updates.l10n.installedMsg, 'polite' ); setTimeout( function() { if ( response.activateUrl ) { // Transform the 'Install' button into an 'Activate' button. $message .attr( 'href', response.activateUrl ) .removeClass( 'theme-install updated-message disabled' ) .addClass( 'activate' ) .attr( 'aria-label', wp.updates.l10n.activateThemeLabel.replace( '%s', response.themeName ) ) .text( wp.updates.l10n.activateTheme ); } if ( response.customizeUrl ) { // Transform the 'Preview' button into a 'Live Preview' button. $message.siblings( '.preview' ).replaceWith( function () { return $( '<a>' ) .attr( 'href', response.customizeUrl ) .addClass( 'button load-customize' ) .text( wp.updates.l10n.livePreview ); } ); } }, 1000 ); }; /** * Updates the UI appropriately after a failed theme install. * * @since 4.6.0 * * @typedef {object} installThemeError * @param {object} response Response from the server. * @param {string} response.slug Slug of the theme to be installed. * @param {string} response.errorCode Error code for the error that occurred. * @param {string} response.errorMessage The error that occurred. */ wp.updates.installThemeError = function( response ) { var $card, $button, errorMessage = wp.updates.l10n.installFailed.replace( '%s', response.errorMessage ), $message = wp.updates.adminNotice( { className: 'update-message notice-error notice-alt', message: errorMessage } ); if ( ! wp.updates.isValidResponse( response, 'install' ) ) { return; } if ( wp.updates.maybeHandleCredentialError( response, 'install-theme' ) ) { return; } if ( $document.find( 'body' ).hasClass( 'full-overlay-active' ) ) { $button = $( '.theme-install[data-slug="' + response.slug + '"]' ); $card = $( '.install-theme-info' ).prepend( $message ); } else { $card = $( '[data-slug="' + response.slug + '"]' ).removeClass( 'focus' ).addClass( 'theme-install-failed' ).append( $message ); $button = $card.find( '.theme-install' ); } $button .removeClass( 'updating-message' ) .attr( 'aria-label', wp.updates.l10n.themeInstallFailedLabel.replace( '%s', $button.data( 'name' ) ) ) .text( wp.updates.l10n.installFailedShort ); wp.a11y.speak( errorMessage, 'assertive' ); $document.trigger( 'wp-theme-install-error', response ); }; /** * Sends an Ajax request to the server to install a theme. * * @since 4.6.0 * * @param {object} args * @param {string} args.slug Theme stylesheet. * @param {deleteThemeSuccess=} args.success Optional. Success callback. Default: wp.updates.deleteThemeSuccess * @param {deleteThemeError=} args.error Optional. Error callback. Default: wp.updates.deleteThemeError * @return {$.promise} A jQuery promise that represents the request, * decorated with an abort() method. */ wp.updates.deleteTheme = function( args ) { var $button; if ( 'themes' === pagenow ) { $button = $( '.theme-actions .delete-theme' ); } else if ( 'themes-network' === pagenow ) { $button = $( '[data-slug="' + args.slug + '"]' ).find( '.row-actions a.delete' ); } args = _.extend( { success: wp.updates.deleteThemeSuccess, error: wp.updates.deleteThemeError }, args ); if ( $button && $button.html() !== wp.updates.l10n.deleting ) { $button .data( 'originaltext', $button.html() ) .text( wp.updates.l10n.deleting ); } wp.a11y.speak( wp.updates.l10n.deleting, 'polite' ); // Remove previous error messages, if any. $( '.theme-info .update-message' ).remove(); $document.trigger( 'wp-theme-deleting', args ); return wp.updates.ajax( 'delete-theme', args ); }; /** * Updates the UI appropriately after a successful theme deletion. * * @since 4.6.0 * * @typedef {object} deleteThemeSuccess * @param {object} response Response from the server. * @param {string} response.slug Slug of the theme that was deleted. */ wp.updates.deleteThemeSuccess = function( response ) { var $themeRows = $( '[data-slug="' + response.slug + '"]' ); if ( 'themes-network' === pagenow ) { // Removes the theme and updates rows. $themeRows.css( { backgroundColor: '#faafaa' } ).fadeOut( 350, function() { var $views = $( '.subsubsub' ), $themeRow = $( this ), totals = settings.themes, deletedRow = wp.template( 'item-deleted-row' ); if ( ! $themeRow.hasClass( 'plugin-update-tr' ) ) { $themeRow.after( deletedRow( { slug: response.slug, colspan: $( '#bulk-action-form' ).find( 'thead th:not(.hidden), thead td' ).length, name: $themeRow.find( '.theme-title strong' ).text() } ) ); } $themeRow.remove(); // Remove theme from update count. if ( $themeRow.hasClass( 'update' ) ) { totals.upgrade--; wp.updates.decrementCount( 'theme' ); } // Remove from views. if ( $themeRow.hasClass( 'inactive' ) ) { totals.disabled--; if ( totals.disabled ) { $views.find( '.disabled .count' ).text( '(' + totals.disabled + ')' ); } else { $views.find( '.disabled' ).remove(); } } // There is always at least one theme available. $views.find( '.all .count' ).text( '(' + --totals.all + ')' ); } ); } wp.a11y.speak( wp.updates.l10n.deleted, 'polite' ); $document.trigger( 'wp-theme-delete-success', response ); }; /** * Updates the UI appropriately after a failed theme deletion. * * @since 4.6.0 * * @typedef {object} deleteThemeError * @param {object} response Response from the server. * @param {string} response.slug Slug of the theme to be deleted. * @param {string} response.errorCode Error code for the error that occurred. * @param {string} response.errorMessage The error that occurred. */ wp.updates.deleteThemeError = function( response ) { var $themeRow = $( 'tr.inactive[data-slug="' + response.slug + '"]' ), $button = $( '.theme-actions .delete-theme' ), updateRow = wp.template( 'item-update-row' ), $updateRow = $themeRow.siblings( '#' + response.slug + '-update' ), errorMessage = wp.updates.l10n.deleteFailed.replace( '%s', response.errorMessage ), $message = wp.updates.adminNotice( { className: 'update-message notice-error notice-alt', message: errorMessage } ); if ( wp.updates.maybeHandleCredentialError( response, 'delete-theme' ) ) { return; } if ( 'themes-network' === pagenow ) { if ( ! $updateRow.length ) { $themeRow.addClass( 'update' ).after( updateRow( { slug: response.slug, colspan: $( '#bulk-action-form' ).find( 'thead th:not(.hidden), thead td' ).length, content: $message } ) ); } else { // Remove previous error messages, if any. $updateRow.find( '.notice-error' ).remove(); $updateRow.find( '.plugin-update' ).append( $message ); } } else { $( '.theme-info .theme-description' ).before( $message ); } $button.html( $button.data( 'originaltext' ) ); wp.a11y.speak( errorMessage, 'assertive' ); $document.trigger( 'wp-theme-delete-error', response ); }; /** * Adds the appropriate callback based on the type of action and the current page. * * @since 4.6.0 * @private * * @param {object} data AJAX payload. * @param {string} action The type of request to perform. * @return {object} The AJAX payload with the appropriate callbacks. */ wp.updates._addCallbacks = function( data, action ) { if ( 'import' === pagenow && 'install-plugin' === action ) { data.success = wp.updates.installImporterSuccess; data.error = wp.updates.installImporterError; } return data; }; /** * Pulls available jobs from the queue and runs them. * * @since 4.2.0 * @since 4.6.0 Can handle multiple job types. */ wp.updates.queueChecker = function() { var job; if ( wp.updates.ajaxLocked || ! wp.updates.queue.length ) { return; } job = wp.updates.queue.shift(); // Handle a queue job. switch ( job.action ) { case 'install-plugin': wp.updates.installPlugin( job.data ); break; case 'update-plugin': wp.updates.updatePlugin( job.data ); break; case 'delete-plugin': wp.updates.deletePlugin( job.data ); break; case 'install-theme': wp.updates.installTheme( job.data ); break; case 'update-theme': wp.updates.updateTheme( job.data ); break; case 'delete-theme': wp.updates.deleteTheme( job.data ); break; default: break; } }; /** * Requests the users filesystem credentials if they aren't already known. * * @since 4.2.0 * * @param {Event=} event Optional. Event interface. */ wp.updates.requestFilesystemCredentials = function( event ) { if ( false === wp.updates.filesystemCredentials.available ) { /* * After exiting the credentials request modal, * return the focus to the element triggering the request. */ if ( event && ! wp.updates.$elToReturnFocusToFromCredentialsModal ) { wp.updates.$elToReturnFocusToFromCredentialsModal = $( event.target ); } wp.updates.ajaxLocked = true; wp.updates.requestForCredentialsModalOpen(); } }; /** * Requests the users filesystem credentials if needed and there is no lock. * * @since 4.6.0 * * @param {Event=} event Optional. Event interface. */ wp.updates.maybeRequestFilesystemCredentials = function( event ) { if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) { wp.updates.requestFilesystemCredentials( event ); } }; /** * Keydown handler for the request for credentials modal. * * Closes the modal when the escape key is pressed and * constrains keyboard navigation to inside the modal. * * @since 4.2.0 * * @param {Event} event Event interface. */ wp.updates.keydown = function( event ) { if ( 27 === event.keyCode ) { wp.updates.requestForCredentialsModalCancel(); } else if ( 9 === event.keyCode ) { // #upgrade button must always be the last focus-able element in the dialog. if ( 'upgrade' === event.target.id && ! event.shiftKey ) { $( '#hostname' ).focus(); event.preventDefault(); } else if ( 'hostname' === event.target.id && event.shiftKey ) { $( '#upgrade' ).focus(); event.preventDefault(); } } }; /** * Opens the request for credentials modal. * * @since 4.2.0 */ wp.updates.requestForCredentialsModalOpen = function() { var $modal = $( '#request-filesystem-credentials-dialog' ); $( 'body' ).addClass( 'modal-open' ); $modal.show(); $modal.find( 'input:enabled:first' ).focus(); $modal.on( 'keydown', wp.updates.keydown ); }; /** * Closes the request for credentials modal. * * @since 4.2.0 */ wp.updates.requestForCredentialsModalClose = function() { $( '#request-filesystem-credentials-dialog' ).hide(); $( 'body' ).removeClass( 'modal-open' ); if ( wp.updates.$elToReturnFocusToFromCredentialsModal ) { wp.updates.$elToReturnFocusToFromCredentialsModal.focus(); } }; /** * Takes care of the steps that need to happen when the modal is canceled out. * * @since 4.2.0 * @since 4.6.0 Triggers an event for callbacks to listen to and add their actions. */ wp.updates.requestForCredentialsModalCancel = function() { // Not ajaxLocked and no queue means we already have cleared things up. if ( ! wp.updates.ajaxLocked && ! wp.updates.queue.length ) { return; } _.each( wp.updates.queue, function( job ) { $document.trigger( 'credential-modal-cancel', job ); } ); // Remove the lock, and clear the queue. wp.updates.ajaxLocked = false; wp.updates.queue = []; wp.updates.requestForCredentialsModalClose(); }; /** * Displays an error message in the request for credentials form. * * @since 4.2.0 * * @param {string} message Error message. */ wp.updates.showErrorInCredentialsForm = function( message ) { var $filesystemForm = $( '#request-filesystem-credentials-form' ); // Remove any existing error. $filesystemForm.find( '.notice' ).remove(); $filesystemForm.find( '#request-filesystem-credentials-title' ).after( '<div class="notice notice-alt notice-error"><p>' + message + '</p></div>' ); }; /** * Handles credential errors and runs events that need to happen in that case. * * @since 4.2.0 * * @param {object} response Ajax response. * @param {string} action The type of request to perform. */ wp.updates.credentialError = function( response, action ) { // Restore callbacks. response = wp.updates._addCallbacks( response, action ); wp.updates.queue.unshift( { action: action, /* * Not cool that we're depending on response for this data. * This would feel more whole in a view all tied together. */ data: response } ); wp.updates.filesystemCredentials.available = false; wp.updates.showErrorInCredentialsForm( response.errorMessage ); wp.updates.requestFilesystemCredentials(); }; /** * Handles credentials errors if it could not connect to the filesystem. * * @since 4.6.0 * * @typedef {object} maybeHandleCredentialError * @param {object} response Response from the server. * @param {string} response.errorCode Error code for the error that occurred. * @param {string} response.errorMessage The error that occurred. * @param {string} action The type of request to perform. * @returns {boolean} Whether there is an error that needs to be handled or not. */ wp.updates.maybeHandleCredentialError = function( response, action ) { if ( wp.updates.shouldRequestFilesystemCredentials && response.errorCode && 'unable_to_connect_to_filesystem' === response.errorCode ) { wp.updates.credentialError( response, action ); return true; } return false; }; /** * Validates an AJAX response to ensure it's a proper object. * * If the response deems to be invalid, an admin notice is being displayed. * * @param {(object|string)} response Response from the server. * @param {function=} response.always Optional. Callback for when the Deferred is resolved or rejected. * @param {string=} response.statusText Optional. Status message corresponding to the status code. * @param {string=} response.responseText Optional. Request response as text. * @param {string} action Type of action the response is referring to. Can be 'delete', * 'update' or 'install'. */ wp.updates.isValidResponse = function( response, action ) { var error = wp.updates.l10n.unknownError, errorMessage; // Make sure the response is a valid data object and not a Promise object. if ( _.isObject( response ) && ! _.isFunction( response.always ) ) { return true; } if ( _.isString( response ) && '-1' === response ) { error = wp.updates.l10n.nonceError; } else if ( _.isString( response ) ) { error = response; } else if ( 'undefined' !== typeof response.readyState && 0 === response.readyState ) { error = wp.updates.l10n.connectionError; } else if ( _.isString( response.responseText ) && '' !== response.responseText ) { error = response.responseText; } else if ( _.isString( response.statusText ) ) { error = response.statusText; } switch ( action ) { case 'update': errorMessage = wp.updates.l10n.updateFailed; break; case 'install': errorMessage = wp.updates.l10n.installFailed; break; case 'delete': errorMessage = wp.updates.l10n.deleteFailed; break; } // Messages are escaped, remove HTML tags to make them more readable. error = error.replace( /<[\/a-z][^<>]*>/gi, '' ); errorMessage = errorMessage.replace( '%s', error ); // Add admin notice. wp.updates.addAdminNotice( { id: 'unknown_error', className: 'notice-error is-dismissible', message: _.escape( errorMessage ) } ); // Remove the lock, and clear the queue. wp.updates.ajaxLocked = false; wp.updates.queue = []; // Change buttons of all running updates. $( '.button.updating-message' ) .removeClass( 'updating-message' ) .removeAttr( 'aria-label' ) .prop( 'disabled', true ) .text( wp.updates.l10n.updateFailedShort ); $( '.updating-message:not(.button):not(.thickbox)' ) .removeClass( 'updating-message notice-warning' ) .addClass( 'notice-error' ) .find( 'p' ) .removeAttr( 'aria-label' ) .text( errorMessage ); wp.a11y.speak( errorMessage, 'assertive' ); return false; }; /** * Potentially adds an AYS to a user attempting to leave the page. * * If an update is on-going and a user attempts to leave the page, * opens an "Are you sure?" alert. * * @since 4.2.0 */ wp.updates.beforeunload = function() { if ( wp.updates.ajaxLocked ) { return wp.updates.l10n.beforeunload; } }; $( function() { var $pluginFilter = $( '#plugin-filter' ), $bulkActionForm = $( '#bulk-action-form' ), $filesystemForm = $( '#request-filesystem-credentials-form' ), $filesystemModal = $( '#request-filesystem-credentials-dialog' ), $pluginSearch = $( '.plugins-php .wp-filter-search' ), $pluginInstallSearch = $( '.plugin-install-php .wp-filter-search' ); settings = _.extend( settings, window._wpUpdatesItemCounts || {} ); if ( settings.totals ) { wp.updates.refreshCount(); } /* * Whether a user needs to submit filesystem credentials. * * This is based on whether the form was output on the page server-side. * * @see {wp_print_request_filesystem_credentials_modal() in PHP} */ wp.updates.shouldRequestFilesystemCredentials = $filesystemModal.length > 0; /** * File system credentials form submit noop-er / handler. * * @since 4.2.0 */ $filesystemModal.on( 'submit', 'form', function( event ) { event.preventDefault(); // Persist the credentials input by the user for the duration of the page load. wp.updates.filesystemCredentials.ftp.hostname = $( '#hostname' ).val(); wp.updates.filesystemCredentials.ftp.username = $( '#username' ).val(); wp.updates.filesystemCredentials.ftp.password = $( '#password' ).val(); wp.updates.filesystemCredentials.ftp.connectionType = $( 'input[name="connection_type"]:checked' ).val(); wp.updates.filesystemCredentials.ssh.publicKey = $( '#public_key' ).val(); wp.updates.filesystemCredentials.ssh.privateKey = $( '#private_key' ).val(); wp.updates.filesystemCredentials.fsNonce = $( '#_fs_nonce' ).val(); wp.updates.filesystemCredentials.available = true; // Unlock and invoke the queue. wp.updates.ajaxLocked = false; wp.updates.queueChecker(); wp.updates.requestForCredentialsModalClose(); } ); /** * Closes the request credentials modal when clicking the 'Cancel' button or outside of the modal. * * @since 4.2.0 */ $filesystemModal.on( 'click', '[data-js-action="close"], .notification-dialog-background', wp.updates.requestForCredentialsModalCancel ); /** * Hide SSH fields when not selected. * * @since 4.2.0 */ $filesystemForm.on( 'change', 'input[name="connection_type"]', function() { $( '#ssh-keys' ).toggleClass( 'hidden', ( 'ssh' !== $( this ).val() ) ); } ).change(); /** * Handles events after the credential modal was closed. * * @since 4.6.0 * * @param {Event} event Event interface. * @param {string} job The install/update.delete request. */ $document.on( 'credential-modal-cancel', function( event, job ) { var $updatingMessage = $( '.updating-message' ), $message, originalText; if ( 'import' === pagenow ) { $updatingMessage.removeClass( 'updating-message' ); } else if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) { if ( 'update-plugin' === job.action ) { $message = $( 'tr[data-plugin="' + job.data.plugin + '"]' ).find( '.update-message' ); } else if ( 'delete-plugin' === job.action ) { $message = $( '[data-plugin="' + job.data.plugin + '"]' ).find( '.row-actions a.delete' ); } } else if ( 'themes' === pagenow || 'themes-network' === pagenow ) { if ( 'update-theme' === job.action ) { $message = $( '[data-slug="' + job.data.slug + '"]' ).find( '.update-message' ); } else if ( 'delete-theme' === job.action && 'themes-network' === pagenow ) { $message = $( '[data-slug="' + job.data.slug + '"]' ).find( '.row-actions a.delete' ); } else if ( 'delete-theme' === job.action && 'themes' === pagenow ) { $message = $( '.theme-actions .delete-theme' ); } } else { $message = $updatingMessage; } if ( $message && $message.hasClass( 'updating-message' ) ) { originalText = $message.data( 'originaltext' ); if ( 'undefined' === typeof originalText ) { originalText = $( '<p>' ).html( $message.find( 'p' ).data( 'originaltext' ) ); } $message .removeClass( 'updating-message' ) .html( originalText ); if ( 'plugin-install' === pagenow || 'plugin-install-network' === pagenow ) { if ( 'update-plugin' === job.action ) { $message.attr( 'aria-label', wp.updates.l10n.updateNowLabel.replace( '%s', $message.data( 'name' ) ) ); } else if ( 'install-plugin' === job.action ) { $message.attr( 'aria-label', wp.updates.l10n.installNowLabel.replace( '%s', $message.data( 'name' ) ) ); } } } wp.a11y.speak( wp.updates.l10n.updateCancel, 'polite' ); } ); /** * Click handler for plugin updates in List Table view. * * @since 4.2.0 * * @param {Event} event Event interface. */ $bulkActionForm.on( 'click', '[data-plugin] .update-link', function( event ) { var $message = $( event.target ), $pluginRow = $message.parents( 'tr' ); event.preventDefault(); if ( $message.hasClass( 'updating-message' ) || $message.hasClass( 'button-disabled' ) ) { return; } wp.updates.maybeRequestFilesystemCredentials( event ); // Return the user to the input box of the plugin's table row after closing the modal. wp.updates.$elToReturnFocusToFromCredentialsModal = $pluginRow.find( '.check-column input' ); wp.updates.updatePlugin( { plugin: $pluginRow.data( 'plugin' ), slug: $pluginRow.data( 'slug' ) } ); } ); /** * Click handler for plugin updates in plugin install view. * * @since 4.2.0 * * @param {Event} event Event interface. */ $pluginFilter.on( 'click', '.update-now', function( event ) { var $button = $( event.target ); event.preventDefault(); if ( $button.hasClass( 'updating-message' ) || $button.hasClass( 'button-disabled' ) ) { return; } wp.updates.maybeRequestFilesystemCredentials( event ); wp.updates.updatePlugin( { plugin: $button.data( 'plugin' ), slug: $button.data( 'slug' ) } ); } ); /** * Click handler for plugin installs in plugin install view. * * @since 4.6.0 * * @param {Event} event Event interface. */ $pluginFilter.on( 'click', '.install-now', function( event ) { var $button = $( event.target ); event.preventDefault(); if ( $button.hasClass( 'updating-message' ) || $button.hasClass( 'button-disabled' ) ) { return; } if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) { wp.updates.requestFilesystemCredentials( event ); $document.on( 'credential-modal-cancel', function() { var $message = $( '.install-now.updating-message' ); $message .removeClass( 'updating-message' ) .text( wp.updates.l10n.installNow ); wp.a11y.speak( wp.updates.l10n.updateCancel, 'polite' ); } ); } wp.updates.installPlugin( { slug: $button.data( 'slug' ) } ); } ); /** * Click handler for importer plugins installs in the Import screen. * * @since 4.6.0 * * @param {Event} event Event interface. */ $document.on( 'click', '.importer-item .install-now', function( event ) { var $button = $( event.target ), pluginName = $( this ).data( 'name' ); event.preventDefault(); if ( $button.hasClass( 'updating-message' ) ) { return; } if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) { wp.updates.requestFilesystemCredentials( event ); $document.on( 'credential-modal-cancel', function() { $button .removeClass( 'updating-message' ) .text( wp.updates.l10n.installNow ) .attr( 'aria-label', wp.updates.l10n.installNowLabel.replace( '%s', pluginName ) ); wp.a11y.speak( wp.updates.l10n.updateCancel, 'polite' ); } ); } wp.updates.installPlugin( { slug: $button.data( 'slug' ), pagenow: pagenow, success: wp.updates.installImporterSuccess, error: wp.updates.installImporterError } ); } ); /** * Click handler for plugin deletions. * * @since 4.6.0 * * @param {Event} event Event interface. */ $bulkActionForm.on( 'click', '[data-plugin] a.delete', function( event ) { var $pluginRow = $( event.target ).parents( 'tr' ); event.preventDefault(); if ( ! window.confirm( wp.updates.l10n.aysDeleteUninstall.replace( '%s', $pluginRow.find( '.plugin-title strong' ).text() ) ) ) { return; } wp.updates.maybeRequestFilesystemCredentials( event ); wp.updates.deletePlugin( { plugin: $pluginRow.data( 'plugin' ), slug: $pluginRow.data( 'slug' ) } ); } ); /** * Click handler for theme updates. * * @since 4.6.0 * * @param {Event} event Event interface. */ $document.on( 'click', '.themes-php.network-admin .update-link', function( event ) { var $message = $( event.target ), $themeRow = $message.parents( 'tr' ); event.preventDefault(); if ( $message.hasClass( 'updating-message' ) || $message.hasClass( 'button-disabled' ) ) { return; } wp.updates.maybeRequestFilesystemCredentials( event ); // Return the user to the input box of the theme's table row after closing the modal. wp.updates.$elToReturnFocusToFromCredentialsModal = $themeRow.find( '.check-column input' ); wp.updates.updateTheme( { slug: $themeRow.data( 'slug' ) } ); } ); /** * Click handler for theme deletions. * * @since 4.6.0 * * @param {Event} event Event interface. */ $document.on( 'click', '.themes-php.network-admin a.delete', function( event ) { var $themeRow = $( event.target ).parents( 'tr' ); event.preventDefault(); if ( ! window.confirm( wp.updates.l10n.aysDelete.replace( '%s', $themeRow.find( '.theme-title strong' ).text() ) ) ) { return; } wp.updates.maybeRequestFilesystemCredentials( event ); wp.updates.deleteTheme( { slug: $themeRow.data( 'slug' ) } ); } ); /** * Bulk action handler for plugins and themes. * * Handles both deletions and updates. * * @since 4.6.0 * * @param {Event} event Event interface. */ $bulkActionForm.on( 'click', '[type="submit"]', function( event ) { var bulkAction = $( event.target ).siblings( 'select' ).val(), itemsSelected = $bulkActionForm.find( 'input[name="checked[]"]:checked' ), success = 0, error = 0, errorMessages = [], type, action; // Determine which type of item we're dealing with. switch ( pagenow ) { case 'plugins': case 'plugins-network': type = 'plugin'; break; case 'themes-network': type = 'theme'; break; default: return; } // Bail if there were no items selected. if ( ! itemsSelected.length ) { event.preventDefault(); $( 'html, body' ).animate( { scrollTop: 0 } ); return wp.updates.addAdminNotice( { id: 'no-items-selected', className: 'notice-error is-dismissible', message: wp.updates.l10n.noItemsSelected } ); } // Determine the type of request we're dealing with. switch ( bulkAction ) { case 'update-selected': action = bulkAction.replace( 'selected', type ); break; case 'delete-selected': if ( ! window.confirm( 'plugin' === type ? wp.updates.l10n.aysBulkDelete : wp.updates.l10n.aysBulkDeleteThemes ) ) { event.preventDefault(); return; } action = bulkAction.replace( 'selected', type ); break; default: return; } wp.updates.maybeRequestFilesystemCredentials( event ); event.preventDefault(); // Un-check the bulk checkboxes. $bulkActionForm.find( '.manage-column [type="checkbox"]' ).prop( 'checked', false ); $document.trigger( 'wp-' + type + '-bulk-' + bulkAction, itemsSelected ); // Find all the checkboxes which have been checked. itemsSelected.each( function( index, element ) { var $checkbox = $( element ), $itemRow = $checkbox.parents( 'tr' ); // Only add update-able items to the update queue. if ( 'update-selected' === bulkAction && ( ! $itemRow.hasClass( 'update' ) || $itemRow.find( 'notice-error' ).length ) ) { // Un-check the box. $checkbox.prop( 'checked', false ); return; } // Add it to the queue. wp.updates.queue.push( { action: action, data: { plugin: $itemRow.data( 'plugin' ), slug: $itemRow.data( 'slug' ) } } ); } ); // Display bulk notification for updates of any kind. $document.on( 'wp-plugin-update-success wp-plugin-update-error wp-theme-update-success wp-theme-update-error', function( event, response ) { var $itemRow = $( '[data-slug="' + response.slug + '"]' ), $bulkActionNotice, itemName; if ( 'wp-' + response.update + '-update-success' === event.type ) { success++; } else { itemName = response.pluginName ? response.pluginName : $itemRow.find( '.column-primary strong' ).text(); error++; errorMessages.push( itemName + ': ' + response.errorMessage ); } $itemRow.find( 'input[name="checked[]"]:checked' ).prop( 'checked', false ); wp.updates.adminNotice = wp.template( 'wp-bulk-updates-admin-notice' ); wp.updates.addAdminNotice( { id: 'bulk-action-notice', className: 'bulk-action-notice', successes: success, errors: error, errorMessages: errorMessages, type: response.update } ); $bulkActionNotice = $( '#bulk-action-notice' ).on( 'click', 'button', function() { // $( this ) is the clicked button, no need to get it again. $( this ) .toggleClass( 'bulk-action-errors-collapsed' ) .attr( 'aria-expanded', ! $( this ).hasClass( 'bulk-action-errors-collapsed' ) ); // Show the errors list. $bulkActionNotice.find( '.bulk-action-errors' ).toggleClass( 'hidden' ); } ); if ( error > 0 && ! wp.updates.queue.length ) { $( 'html, body' ).animate( { scrollTop: 0 } ); } } ); // Reset admin notice template after #bulk-action-notice was added. $document.on( 'wp-updates-notice-added', function() { wp.updates.adminNotice = wp.template( 'wp-updates-admin-notice' ); } ); // Check the queue, now that the event handlers have been added. wp.updates.queueChecker(); } ); if ( $pluginInstallSearch.length ) { $pluginInstallSearch.attr( 'aria-describedby', 'live-search-desc' ); } /** * Handles changes to the plugin search box on the new-plugin page, * searching the repository dynamically. * * @since 4.6.0 */ $pluginInstallSearch.on( 'keyup input', _.debounce( function( event, eventtype ) { var $searchTab = $( '.plugin-install-search' ), data, searchLocation; data = { _ajax_nonce: wp.updates.ajaxNonce, s: event.target.value, tab: 'search', type: $( '#typeselector' ).val(), pagenow: pagenow }; searchLocation = location.href.split( '?' )[ 0 ] + '?' + $.param( _.omit( data, [ '_ajax_nonce', 'pagenow' ] ) ); // Clear on escape. if ( 'keyup' === event.type && 27 === event.which ) { event.target.value = ''; } if ( wp.updates.searchTerm === data.s && 'typechange' !== eventtype ) { return; } else { $pluginFilter.empty(); wp.updates.searchTerm = data.s; } if ( window.history && window.history.replaceState ) { window.history.replaceState( null, '', searchLocation ); } if ( ! $searchTab.length ) { $searchTab = $( '<li class="plugin-install-search" />' ) .append( $( '<a />', { 'class': 'current', 'href': searchLocation, 'text': wp.updates.l10n.searchResultsLabel } ) ); $( '.wp-filter .filter-links .current' ) .removeClass( 'current' ) .parents( '.filter-links' ) .prepend( $searchTab ); $pluginFilter.prev( 'p' ).remove(); $( '.plugins-popular-tags-wrapper' ).remove(); } if ( 'undefined' !== typeof wp.updates.searchRequest ) { wp.updates.searchRequest.abort(); } $( 'body' ).addClass( 'loading-content' ); wp.updates.searchRequest = wp.ajax.post( 'search-install-plugins', data ).done( function( response ) { $( 'body' ).removeClass( 'loading-content' ); $pluginFilter.append( response.items ); delete wp.updates.searchRequest; if ( 0 === response.count ) { wp.a11y.speak( wp.updates.l10n.noPluginsFound ); } else { wp.a11y.speak( wp.updates.l10n.pluginsFound.replace( '%d', response.count ) ); } } ); }, 500 ) ); if ( $pluginSearch.length ) { $pluginSearch.attr( 'aria-describedby', 'live-search-desc' ); } /** * Handles changes to the plugin search box on the Installed Plugins screen, * searching the plugin list dynamically. * * @since 4.6.0 */ $pluginSearch.on( 'keyup input', _.debounce( function( event ) { var data = { _ajax_nonce: wp.updates.ajaxNonce, s: event.target.value, pagenow: pagenow, plugin_status: 'all' }, queryArgs; // Clear on escape. if ( 'keyup' === event.type && 27 === event.which ) { event.target.value = ''; } if ( wp.updates.searchTerm === data.s ) { return; } else { wp.updates.searchTerm = data.s; } queryArgs = _.object( _.compact( _.map( location.search.slice( 1 ).split( '&' ), function( item ) { if ( item ) return item.split( '=' ); } ) ) ); data.plugin_status = queryArgs.plugin_status || 'all'; if ( window.history && window.history.replaceState ) { window.history.replaceState( null, '', location.href.split( '?' )[ 0 ] + '?s=' + data.s + '&plugin_status=' + data.plugin_status ); } if ( 'undefined' !== typeof wp.updates.searchRequest ) { wp.updates.searchRequest.abort(); } $bulkActionForm.empty(); $( 'body' ).addClass( 'loading-content' ); $( '.subsubsub .current' ).removeClass( 'current' ); wp.updates.searchRequest = wp.ajax.post( 'search-plugins', data ).done( function( response ) { // Can we just ditch this whole subtitle business? var $subTitle = $( '<span />' ).addClass( 'subtitle' ).html( wp.updates.l10n.searchResults.replace( '%s', _.escape( data.s ) ) ), $oldSubTitle = $( '.wrap .subtitle' ); if ( ! data.s.length ) { $oldSubTitle.remove(); $( '.subsubsub .' + data.plugin_status + ' a' ).addClass( 'current' ); } else if ( $oldSubTitle.length ) { $oldSubTitle.replaceWith( $subTitle ); } else { $( '.wrap h1' ).append( $subTitle ); } $( 'body' ).removeClass( 'loading-content' ); $bulkActionForm.append( response.items ); delete wp.updates.searchRequest; if ( 0 === response.count ) { wp.a11y.speak( wp.updates.l10n.noPluginsFound ); } else { wp.a11y.speak( wp.updates.l10n.pluginsFound.replace( '%d', response.count ) ); } } ); }, 500 ) ); /** * Trigger a search event when the search form gets submitted. * * @since 4.6.0 */ $document.on( 'submit', '.search-plugins', function( event ) { event.preventDefault(); $( 'input.wp-filter-search' ).trigger( 'input' ); } ); /** * Trigger a search event when the search type gets changed. * * @since 4.6.0 */ $( '#typeselector' ).on( 'change', function() { var $search = $( 'input[name="s"]' ); if ( $search.val().length ) { $search.trigger( 'input', 'typechange' ); } } ); /** * Click handler for updating a plugin from the details modal on `plugin-install.php`. * * @since 4.2.0 * * @param {Event} event Event interface. */ $( '#plugin_update_from_iframe' ).on( 'click', function( event ) { var target = window.parent === window ? null : window.parent, update; $.support.postMessage = !! window.postMessage; if ( false === $.support.postMessage || null === target || -1 !== window.parent.location.pathname.indexOf( 'update-core.php' ) ) { return; } event.preventDefault(); update = { action: 'update-plugin', data: { plugin: $( this ).data( 'plugin' ), slug: $( this ).data( 'slug' ) } }; target.postMessage( JSON.stringify( update ), window.location.origin ); } ); /** * Click handler for installing a plugin from the details modal on `plugin-install.php`. * * @since 4.6.0 * * @param {Event} event Event interface. */ $( '#plugin_install_from_iframe' ).on( 'click', function( event ) { var target = window.parent === window ? null : window.parent, install; $.support.postMessage = !! window.postMessage; if ( false === $.support.postMessage || null === target || -1 !== window.parent.location.pathname.indexOf( 'index.php' ) ) { return; } event.preventDefault(); install = { action: 'install-plugin', data: { slug: $( this ).data( 'slug' ) } }; target.postMessage( JSON.stringify( install ), window.location.origin ); } ); /** * Handles postMessage events. * * @since 4.2.0 * @since 4.6.0 Switched `update-plugin` action to use the queue. * * @param {Event} event Event interface. */ $( window ).on( 'message', function( event ) { var originalEvent = event.originalEvent, expectedOrigin = document.location.protocol + '//' + document.location.hostname, message; if ( originalEvent.origin !== expectedOrigin ) { return; } try { message = $.parseJSON( originalEvent.data ); } catch ( e ) { return; } if ( 'undefined' === typeof message.action ) { return; } switch ( message.action ) { // Called from `wp-admin/includes/class-wp-upgrader-skins.php`. case 'decrementUpdateCount': /** @property {string} message.upgradeType */ wp.updates.decrementCount( message.upgradeType ); break; case 'install-plugin': case 'update-plugin': /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */ window.tb_remove(); /* jscs:enable */ message.data = wp.updates._addCallbacks( message.data, message.action ); wp.updates.queue.push( message ); wp.updates.queueChecker(); break; } } ); /** * Adds a callback to display a warning before leaving the page. * * @since 4.2.0 */ $( window ).on( 'beforeunload', wp.updates.beforeunload ); } ); })( jQuery, window.wp, window._wpUpdatesSettings ); image-edit.js 0000666 00000042465 15213733063 0007131 0 ustar 00 /* global imageEditL10n, ajaxurl, confirm */ (function($) { var imageEdit = window.imageEdit = { iasapi : {}, hold : {}, postid : '', _view : false, intval : function(f) { /* * Bitwise OR operator: one of the obscure ways to truncate floating point figures, * worth reminding JavaScript doesn't have a distinct "integer" type. */ return f | 0; }, setDisabled : function( el, s ) { /* * `el` can be a single form element or a fieldset. Before #28864, the disabled state on * some text fields was handled targeting $('input', el). Now we need to handle the * disabled state on buttons too so we can just target `el` regardless if it's a single * element or a fieldset because when a fieldset is disabled, its descendants are disabled too. */ if ( s ) { el.removeClass( 'disabled' ).prop( 'disabled', false ); } else { el.addClass( 'disabled' ).prop( 'disabled', true ); } }, init : function(postid) { 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.fadeIn( 'fast' ); } else { wait.fadeOut('fast'); } }, toggleHelp : function(el) { var $el = $( el ); $el .attr( 'aria-expanded', 'false' === $el.attr( 'aria-expanded' ) ? 'true' : 'false' ) .parents( '.imgedit-group-top' ).toggleClass( 'imgedit-help-toggled' ).find( '.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, el ) { var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid), warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = ''; if ( false === this.validateNumeric( el ) ) { return; } 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 + '" alt="" />' ) .on( 'load', { history: data.history }, function( event ) { var max1, max2, parent = $( '#imgedit-crop-' + postid ), t = imageEdit, historyObj; if ( '' !== event.data.history ) { historyObj = JSON.parse( event.data.history ); // If last executed action in history is a crop action. if ( historyObj[historyObj.length - 1].hasOwnProperty( 'c' ) ) { /* * A crop action has completed and the crop button gets disabled * ensure the undo button is enabled. */ t.setDisabled( $( '#image-undo-' + postid) , true ); // Move focus to the undo button to avoid a focus loss. $( '#image-undo-' + postid ).focus(); } } 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 !== 'undefined') && 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); }) .on('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); // refresh the attachment model so that changes propagate if ( t._view ) { t._view.refresh(); } }); }, save : function(postid, nonce) { var data, target = this.getTarget(postid), history = this.filterHistory(postid, 0), self = this; 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 + ' × ' + 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>'); } if ( self._view ) { self._view.save(); } else { imageEdit.close(postid); } }); }, open : function( postid, nonce, view ) { this._view = view; var dfd, data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid), btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('.spinner'); /* * Instead of disabling the button, which causes a focus loss and makes screen * readers announce "unavailable", return if the button was already clicked. */ if ( btn.hasClass( 'button-activated' ) ) { return; } spin.addClass( 'is-active' ); data = { 'action': 'image-editor', '_ajax_nonce': nonce, 'postid': postid, 'do': 'open' }; dfd = $.ajax({ url: ajaxurl, type: 'post', data: data, beforeSend: function() { btn.addClass( 'button-activated' ); } }).done(function( html ) { elem.html( html ); head.fadeOut('fast', function(){ elem.fadeIn('fast'); btn.removeClass( 'button-activated' ); spin.removeClass( 'is-active' ); }); // Initialise the Image Editor now that everything is ready. imageEdit.init( postid ); }); return dfd; }, 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); // Editor is ready, move focus to the first focusable element. $( '.imgedit-wrap .imgedit-help-toggle' ).eq( 0 ).focus(); }, initCrop : function(postid, image, parent) { var t = this, selW = $('#imgedit-sel-width-' + postid), selH = $('#imgedit-sel-height-' + postid), $img; t.iasapi = $(image).imgAreaSelect({ parent: parent, instance: true, handles: true, keys: true, minWidth: 3, minHeight: 3, onInit: function( img ) { // Ensure that the imgareaselect wrapper elements are position:absolute // (even if we're in a position:fixed modal) $img = $( img ); $img.next().css( 'position', 'absolute' ) .nextAll( '.imgareaselect-outer' ).css( 'position', 'absolute' ); 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() { 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; 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; } 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 = {}; // If we've loaded the editor in the context of a Media Modal, then switch to the previous view, // whatever that might have been. if ( this._view ){ this._view.back(); } // In case we are not accessing the image editor in the context of a View, close the editor the old-skool way else { $('#image-editor-' + postid).fadeOut('fast', function() { $( '#media-head-' + postid ).fadeIn( 'fast', function() { // Move focus back to the Edit Image button. Runs also when saving. $( '#imgedit-open-btn-' + postid ).focus(); }); $(this).empty(); }); } }, notsaved : function(postid) { var h = $('#imgedit-history-' + postid).val(), history = ( h !== '' ) ? JSON.parse(h) : [], 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() ) : [], 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() ) : []; t.setDisabled($('#image-redo-' + postid), true); t.setDisabled(button, pop < history.length); // When undo gets disabled, move focus to the redo button to avoid a focus loss. if ( history.length === pop ) { $( '#image-redo-' + postid ).focus(); } }); }, 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); // When redo gets disabled, move focus to the undo button to avoid a focus loss. if ( 0 === pop ) { $( '#image-undo-' + postid ).focus(); } }); }, setNumSelection : function( postid, el ) { 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 ( false === this.validateNumeric( el ) ) { return; } 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 ( false === this.validateNumeric( el ) ) { 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(); } } }, validateNumeric: function( el ) { if ( ! this.intval( $( el ).val() ) ) { $( el ).val( '' ); return false; } } }; })(jQuery); common.js 0000666 00000066317 15213733063 0006416 0 ustar 00 /* global setUserSetting, ajaxurl, commonL10n, alert, confirm, pagenow */ var showNotice, adminMenu, columns, validateForm, screenMeta; ( function( $, window, undefined ) { var $document = $( document ), $window = $( window ), $body = $( document.body ); // 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).removeClass( 'hidden' ); this.colSpanChange(+1); }, unchecked : function(column) { $('.column-' + column).addClass( 'hidden' ); this.colSpanChange(-1); }, hidden : function() { return $( '.manage-column[id]' ).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' ); } ) .length; }; // 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-links' ).find( '.show-settings' ); this.page = $('#wpcontent'); this.toggles.click( this.toggleEvent ); }, toggleEvent: function() { var panel = $( '#' + $( this ).attr( 'aria-controls' ) ); if ( !panel.length ) return; if ( panel.is(':visible') ) screenMeta.close( panel, $(this) ); else screenMeta.open( panel, $(this) ); }, open: function( panel, button ) { $( '#screen-meta-links' ).find( '.screen-meta-toggle' ).not( button.parent() ).css( 'visibility', 'hidden' ); panel.parent().show(); panel.slideDown( 'fast', function() { panel.focus(); button.addClass( 'screen-meta-active' ).attr( 'aria-expanded', true ); }); $document.trigger( 'screen:options:open' ); }, close: function( panel, button ) { panel.slideUp( 'fast', function() { button.removeClass( 'screen-meta-active' ).attr( 'aria-expanded', false ); $('.screen-meta-toggle').css('visibility', ''); panel.parent().hide(); }); $document.trigger( 'screen:options:close' ); } }; /** * Help tabs. */ $('.contextual-help-tabs').delegate('a', 'click', 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 checks, first, last, checked, sliced, mobileEvent, transitionTimeout, focusedRowActions, lastClicked = false, pageInput = $('input.current-page'), currentPage = pageInput.val(), isIOS = /iPhone|iPad|iPod/.test( navigator.userAgent ), isAndroid = navigator.userAgent.indexOf( 'Android' ) !== -1, isIE8 = $( document.documentElement ).hasClass( 'ie8' ), $adminMenuWrap = $( '#adminmenuwrap' ), $wpwrap = $( '#wpwrap' ), $adminmenu = $( '#adminmenu' ), $overlay = $( '#wp-responsive-overlay' ), $toolbar = $( '#wp-toolbar' ), $toolbarPopups = $toolbar.find( 'a[aria-haspopup="true"]' ), $sortables = $('.meta-box-sortables'), wpResponsiveActive = false, $adminbar = $( '#wpadminbar' ), lastScrollPosition = 0, pinnedMenuTop = false, pinnedMenuBottom = false, menuTop = 0, menuState, menuIsPinned = false, height = { window: $window.height(), wpwrap: $wpwrap.height(), adminbar: $adminbar.height(), menu: $adminMenuWrap.height() }, $headerEnd = $( '.wp-header-end' ); // when the menu is folded, make the fly-out submenu header clickable $adminmenu.on('click.wp-submenu-head', '.wp-submenu-head', function(e){ $(e.target).parent().siblings('a').get(0).click(); }); $( '#collapse-button' ).on( 'click.collapse-menu', function() { var viewportWidth = getViewportWidth() || 961; // reset any compensation for submenus near the bottom of the screen $('#adminmenu div.wp-submenu').css('margin-top', ''); if ( viewportWidth < 960 ) { if ( $body.hasClass('auto-fold') ) { $body.removeClass('auto-fold').removeClass('folded'); setUserSetting('unfold', 1); setUserSetting('mfold', 'o'); menuState = 'open'; } else { $body.addClass('auto-fold'); setUserSetting('unfold', 0); menuState = 'folded'; } } else { if ( $body.hasClass('folded') ) { $body.removeClass('folded'); setUserSetting('mfold', 'o'); menuState = 'open'; } else { $body.addClass('folded'); setUserSetting('mfold', 'f'); menuState = 'folded'; } } $document.trigger( 'wp-collapse-menu', { state: menuState } ); }); // Handle the `aria-haspopup` attribute on the current menu item when it has a sub-menu. function currentMenuItemHasPopup() { var $current = $( 'a.wp-has-current-submenu' ); if ( 'folded' === menuState ) { // When folded or auto-folded and not responsive view, the current menu item does have a fly-out sub-menu. $current.attr( 'aria-haspopup', 'true' ); } else { // When expanded or in responsive view, reset aria-haspopup. $current.attr( 'aria-haspopup', 'false' ); } } $document.on( 'wp-menu-state-set wp-collapse-menu wp-responsive-activate wp-responsive-deactivate', currentMenuItemHasPopup ); /** * Ensure an admin submenu is within the visual viewport. * * @since 4.1.0 * * @param {jQuery} $menuItem The parent menu item containing the submenu. */ function adjustSubmenu( $menuItem ) { var bottomOffset, pageHeight, adjustment, theFold, menutop, wintop, maxtop, $submenu = $menuItem.find( '.wp-submenu' ); menutop = $menuItem.offset().top; wintop = $window.scrollTop(); maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar bottomOffset = menutop + $submenu.height() + 1; // Bottom offset of the menu pageHeight = $wpwrap.height(); // Height of the entire page adjustment = 60 + bottomOffset - pageHeight; theFold = $window.height() + wintop - 50; // The fold if ( theFold < ( bottomOffset - adjustment ) ) { adjustment = bottomOffset - theFold; } if ( adjustment > maxtop ) { adjustment = maxtop; } if ( adjustment > 1 ) { $submenu.css( 'margin-top', '-' + adjustment + 'px' ); } else { $submenu.css( 'margin-top', '' ); } } if ( 'ontouchstart' in window || /IEMobile\/[1-9]/.test(navigator.userAgent) ) { // touch screen device // iOS Safari works with touchstart, the rest work with click mobileEvent = isIOS ? 'touchstart' : 'click'; // close any open submenus when touch/click is not on the menu $body.on( mobileEvent+'.wp-mobile-hover', function(e) { if ( $adminmenu.data('wp-responsive') ) { return; } if ( ! $( e.target ).closest( '#adminmenu' ).length ) { $adminmenu.find( 'li.opensub' ).removeClass( 'opensub' ); } }); $adminmenu.find( 'a.wp-has-submenu' ).on( mobileEvent + '.wp-mobile-hover', function( event ) { var $menuItem = $(this).parent(); if ( $adminmenu.data( 'wp-responsive' ) ) { return; } // 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 ( ! $menuItem.hasClass( 'opensub' ) && ( ! $menuItem.hasClass( 'wp-menu-open' ) || $menuItem.width() < 40 ) ) { event.preventDefault(); adjustSubmenu( $menuItem ); $adminmenu.find( 'li.opensub' ).removeClass( 'opensub' ); $menuItem.addClass('opensub'); } }); } if ( ! isIOS && ! isAndroid ) { $adminmenu.find( 'li.wp-has-submenu' ).hoverIntent({ over: function() { var $menuItem = $( this ), $submenu = $menuItem.find( '.wp-submenu' ), top = parseInt( $submenu.css( 'top' ), 10 ); if ( isNaN( top ) || top > -5 ) { // the submenu is visible return; } if ( $adminmenu.data( 'wp-responsive' ) ) { // The menu is in responsive mode, bail return; } adjustSubmenu( $menuItem ); $adminmenu.find( 'li.opensub' ).removeClass( 'opensub' ); $menuItem.addClass( 'opensub' ); }, out: function(){ if ( $adminmenu.data( 'wp-responsive' ) ) { // The menu is in responsive mode, bail return; } $( this ).removeClass( 'opensub' ).find( '.wp-submenu' ).css( 'margin-top', '' ); }, timeout: 200, sensitivity: 7, interval: 90 }); $adminmenu.on( 'focus.adminmenu', '.wp-submenu a', function( event ) { if ( $adminmenu.data( 'wp-responsive' ) ) { // The menu is in responsive mode, bail return; } $( event.target ).closest( 'li.menu-top' ).addClass( 'opensub' ); }).on( 'blur.adminmenu', '.wp-submenu a', function( event ) { if ( $adminmenu.data( 'wp-responsive' ) ) { return; } $( event.target ).closest( 'li.menu-top' ).removeClass( 'opensub' ); }).find( 'li.wp-has-submenu.wp-not-current-submenu' ).on( 'focusin.adminmenu', function() { adjustSubmenu( $( this ) ); }); } /* * The `.below-h2` class is here just for backward compatibility with plugins * that are (incorrectly) using it. Do not use. Use `.inline` instead. See #34570. * If '.wp-header-end' is found, append the notices after it otherwise * after the first h1 or h2 heading found within the main content. */ if ( ! $headerEnd.length ) { $headerEnd = $( '.wrap h1, .wrap h2' ).first(); } $( 'div.updated, div.error, div.notice' ).not( '.inline, .below-h2' ).insertAfter( $headerEnd ); // Make notices dismissible function makeNoticesDismissible() { $( '.notice.is-dismissible' ).each( function() { var $el = $( this ), $button = $( '<button type="button" class="notice-dismiss"><span class="screen-reader-text"></span></button>' ), btnText = commonL10n.dismiss || ''; // Ensure plain text $button.find( '.screen-reader-text' ).text( btnText ); $button.on( 'click.wp-dismiss-notice', function( event ) { event.preventDefault(); $el.fadeTo( 100, 0, function() { $el.slideUp( 100, function() { $el.remove(); }); }); }); $el.append( $button ); }); } $document.on( 'wp-updates-notice-added wp-plugin-install-error wp-plugin-update-error wp-plugin-delete-error wp-theme-install-error wp-theme-delete-error', makeNoticesDismissible ); // Init screen meta screenMeta.init(); // This event needs to be delegated. Ticket #37973. $body.on( 'click', 'tbody > tr > .check-column :checkbox', function( event ) { // Shift click to select a range of checkboxes. if ( 'undefined' == event.shiftKey ) { return true; } if ( event.shiftKey ) { if ( !lastClicked ) { return true; } checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' ).filter( ':visible:enabled' ); first = checks.index( lastClicked ); last = checks.index( this ); checked = $(this).prop('checked'); if ( 0 < first && 0 < last && first != last ) { sliced = ( last > first ) ? checks.slice( first, last ) : checks.slice( last, first ); sliced.prop( 'checked', function() { if ( $(this).closest('tr').is(':visible') ) return checked; return false; }); } } lastClicked = this; // Toggle the "Select all" checkboxes depending if the other ones are all checked or not. var unchecked = $(this).closest('tbody').find(':checkbox').filter(':visible:enabled').not(':checked'); $(this).closest('table').children('thead, tfoot').find(':checkbox').prop('checked', function() { return ( 0 === unchecked.length ); }); return true; }); // This event needs to be delegated. Ticket #37973. $body.on( 'click.wp-toggle-checkboxes', 'thead .check-column :checkbox, tfoot .check-column :checkbox', function( event ) { var $this = $(this), $table = $this.closest( 'table' ), controlChecked = $this.prop('checked'), toggle = event.shiftKey || $this.data('wp-toggle'); $table.children( 'tbody' ).filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( $(this).is(':hidden,:disabled') ) { return false; } if ( toggle ) { return ! $(this).prop( 'checked' ); } else if ( controlChecked ) { return true; } return false; }); $table.children('thead, tfoot').filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( toggle ) { return false; } else if ( controlChecked ) { return true; } return false; }); }); // Show row actions on keyboard focus of its parent container element or any other elements contained within $( '#wpbody-content' ).on({ focusin: function() { clearTimeout( transitionTimeout ); focusedRowActions = $( this ).find( '.row-actions' ); // transitionTimeout is necessary for Firefox, but Chrome won't remove the CSS class without a little help. $( '.row-actions' ).not( this ).removeClass( 'visible' ); focusedRowActions.addClass( 'visible' ); }, focusout: function() { // Tabbing between post title and .row-actions links needs a brief pause, otherwise // the .row-actions div gets hidden in transit in some browsers (ahem, Firefox). transitionTimeout = setTimeout( function() { focusedRowActions.removeClass( 'visible' ); }, 30 ); } }, '.has-row-actions' ); // Toggle list table rows on small screens $( 'tbody' ).on( 'click', '.toggle-row', function() { $( this ).closest( 'tr' ).toggleClass( 'is-expanded' ); }); $('#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 // when pressing Escape: Opera 12 and 27 blur form fields, IE 8 clears them e.preventDefault(); $(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; 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(); }); if ( pageInput.length ) { pageInput.closest('form').submit( function() { // 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'); }); } $('.search-box input[type="search"], .search-box input[type="submit"]').mousedown(function () { $('select[name^="action"]').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); })(); function pinMenu( event ) { var windowPos = $window.scrollTop(), resizing = ! event || event.type !== 'scroll'; if ( isIOS || isIE8 || $adminmenu.data( 'wp-responsive' ) ) { return; } if ( height.menu + height.adminbar < height.window || height.menu + height.adminbar + 20 > height.wpwrap ) { unpinMenu(); return; } menuIsPinned = true; if ( height.menu + height.adminbar > height.window ) { // Check for overscrolling if ( windowPos < 0 ) { if ( ! pinnedMenuTop ) { pinnedMenuTop = true; pinnedMenuBottom = false; $adminMenuWrap.css({ position: 'fixed', top: '', bottom: '' }); } return; } else if ( windowPos + height.window > $document.height() - 1 ) { if ( ! pinnedMenuBottom ) { pinnedMenuBottom = true; pinnedMenuTop = false; $adminMenuWrap.css({ position: 'fixed', top: '', bottom: 0 }); } return; } if ( windowPos > lastScrollPosition ) { // Scrolling down if ( pinnedMenuTop ) { // let it scroll pinnedMenuTop = false; menuTop = $adminMenuWrap.offset().top - height.adminbar - ( windowPos - lastScrollPosition ); if ( menuTop + height.menu + height.adminbar < windowPos + height.window ) { menuTop = windowPos + height.window - height.menu - height.adminbar; } $adminMenuWrap.css({ position: 'absolute', top: menuTop, bottom: '' }); } else if ( ! pinnedMenuBottom && $adminMenuWrap.offset().top + height.menu < windowPos + height.window ) { // pin the bottom pinnedMenuBottom = true; $adminMenuWrap.css({ position: 'fixed', top: '', bottom: 0 }); } } else if ( windowPos < lastScrollPosition ) { // Scrolling up if ( pinnedMenuBottom ) { // let it scroll pinnedMenuBottom = false; menuTop = $adminMenuWrap.offset().top - height.adminbar + ( lastScrollPosition - windowPos ); if ( menuTop + height.menu > windowPos + height.window ) { menuTop = windowPos; } $adminMenuWrap.css({ position: 'absolute', top: menuTop, bottom: '' }); } else if ( ! pinnedMenuTop && $adminMenuWrap.offset().top >= windowPos + height.adminbar ) { // pin the top pinnedMenuTop = true; $adminMenuWrap.css({ position: 'fixed', top: '', bottom: '' }); } } else if ( resizing ) { // Resizing pinnedMenuTop = pinnedMenuBottom = false; menuTop = windowPos + height.window - height.menu - height.adminbar - 1; if ( menuTop > 0 ) { $adminMenuWrap.css({ position: 'absolute', top: menuTop, bottom: '' }); } else { unpinMenu(); } } } lastScrollPosition = windowPos; } function resetHeights() { height = { window: $window.height(), wpwrap: $wpwrap.height(), adminbar: $adminbar.height(), menu: $adminMenuWrap.height() }; } function unpinMenu() { if ( isIOS || ! menuIsPinned ) { return; } pinnedMenuTop = pinnedMenuBottom = menuIsPinned = false; $adminMenuWrap.css({ position: '', top: '', bottom: '' }); } function setPinMenu() { resetHeights(); if ( $adminmenu.data('wp-responsive') ) { $body.removeClass( 'sticky-menu' ); unpinMenu(); } else if ( height.menu + height.adminbar > height.window ) { pinMenu(); $body.removeClass( 'sticky-menu' ); } else { $body.addClass( 'sticky-menu' ); unpinMenu(); } } if ( ! isIOS ) { $window.on( 'scroll.pin-menu', pinMenu ); $document.on( 'tinymce-editor-init.pin-menu', function( event, editor ) { editor.on( 'wp-autoresize', resetHeights ); }); } window.wpResponsive = { init: function() { var self = this; // Modify functionality based on custom activate/deactivate event $document.on( 'wp-responsive-activate.wp-responsive', function() { self.activate(); }).on( 'wp-responsive-deactivate.wp-responsive', function() { self.deactivate(); }); $( '#wp-admin-bar-menu-toggle a' ).attr( 'aria-expanded', 'false' ); // Toggle sidebar when toggle is clicked $( '#wp-admin-bar-menu-toggle' ).on( 'click.wp-responsive', function( event ) { event.preventDefault(); // close any open toolbar submenus $adminbar.find( '.hover' ).removeClass( 'hover' ); $wpwrap.toggleClass( 'wp-responsive-open' ); if ( $wpwrap.hasClass( 'wp-responsive-open' ) ) { $(this).find('a').attr( 'aria-expanded', 'true' ); $( '#adminmenu a:first' ).focus(); } else { $(this).find('a').attr( 'aria-expanded', 'false' ); } } ); // Add menu events $adminmenu.on( 'click.wp-responsive', 'li.wp-has-submenu > a', function( event ) { if ( ! $adminmenu.data('wp-responsive') ) { return; } $( this ).parent( 'li' ).toggleClass( 'selected' ); event.preventDefault(); }); self.trigger(); $document.on( 'wp-window-resized.wp-responsive', $.proxy( this.trigger, this ) ); // This needs to run later as UI Sortable may be initialized later on $(document).ready() $window.on( 'load.wp-responsive', function() { var width = navigator.userAgent.indexOf('AppleWebKit/') > -1 ? $window.width() : window.innerWidth; if ( width <= 782 ) { self.disableSortables(); } }); }, activate: function() { setPinMenu(); if ( ! $body.hasClass( 'auto-fold' ) ) { $body.addClass( 'auto-fold' ); } $adminmenu.data( 'wp-responsive', 1 ); this.disableSortables(); }, deactivate: function() { setPinMenu(); $adminmenu.removeData('wp-responsive'); this.enableSortables(); }, trigger: function() { var viewportWidth = getViewportWidth(); // Exclude IE < 9, it doesn't support @media CSS rules. if ( ! viewportWidth ) { return; } if ( viewportWidth <= 782 ) { if ( ! wpResponsiveActive ) { $document.trigger( 'wp-responsive-activate' ); wpResponsiveActive = true; } } else { if ( wpResponsiveActive ) { $document.trigger( 'wp-responsive-deactivate' ); wpResponsiveActive = false; } } if ( viewportWidth <= 480 ) { this.enableOverlay(); } else { this.disableOverlay(); } }, enableOverlay: function() { if ( $overlay.length === 0 ) { $overlay = $( '<div id="wp-responsive-overlay"></div>' ) .insertAfter( '#wpcontent' ) .hide() .on( 'click.wp-responsive', function() { $toolbar.find( '.menupop.hover' ).removeClass( 'hover' ); $( this ).hide(); }); } $toolbarPopups.on( 'click.wp-responsive', function() { $overlay.show(); }); }, disableOverlay: function() { $toolbarPopups.off( 'click.wp-responsive' ); $overlay.hide(); }, disableSortables: function() { if ( $sortables.length ) { try { $sortables.sortable('disable'); } catch(e) {} } }, enableSortables: function() { if ( $sortables.length ) { try { $sortables.sortable('enable'); } catch(e) {} } } }; // Add an ARIA role `button` to elements that behave like UI controls when JavaScript is on. function aria_button_if_js() { $( '.aria-button-if-js' ).attr( 'role', 'button' ); } $( document ).ajaxComplete( function() { aria_button_if_js(); }); /** * @summary Get the viewport width. * * @since 4.7.0 * * @returns {number|boolean} The current viewport width or false if the * browser doesn't support innerWidth (IE < 9). */ function getViewportWidth() { var viewportWidth = false; if ( window.innerWidth ) { // On phones, window.innerWidth is affected by zooming. viewportWidth = Math.max( window.innerWidth, document.documentElement.clientWidth ); } return viewportWidth; } /** * @summary Set the admin menu collapsed/expanded state. * * Sets the global variable `menuState` and triggers a custom event passing * the current menu state. * * @since 4.7.0 * * @returns {void} */ function setMenuState() { var viewportWidth = getViewportWidth() || 961; if ( viewportWidth <= 782 ) { menuState = 'responsive'; } else if ( $body.hasClass( 'folded' ) || ( $body.hasClass( 'auto-fold' ) && viewportWidth <= 960 && viewportWidth > 782 ) ) { menuState = 'folded'; } else { menuState = 'open'; } $document.trigger( 'wp-menu-state-set', { state: menuState } ); } // Set the menu state when the window gets resized. $document.on( 'wp-window-resized.set-menu-state', setMenuState ); /** * @summary Set ARIA attributes on the collapse/expand menu button. * * When the admin menu is open or folded, updates the `aria-expanded` and * `aria-label` attributes of the button to give feedback to assistive * technologies. In the responsive view, the button is always hidden. * * @since 4.7.0 * * @returns {void} */ $document.on( 'wp-menu-state-set wp-collapse-menu', function( event, eventData ) { var $collapseButton = $( '#collapse-button' ), ariaExpanded = 'true', ariaLabelText = commonL10n.collapseMenu; if ( 'folded' === eventData.state ) { ariaExpanded = 'false'; ariaLabelText = commonL10n.expandMenu; } $collapseButton.attr({ 'aria-expanded': ariaExpanded, 'aria-label': ariaLabelText }); }); window.wpResponsive.init(); setPinMenu(); setMenuState(); currentMenuItemHasPopup(); makeNoticesDismissible(); aria_button_if_js(); $document.on( 'wp-pin-menu wp-window-resized.pin-menu postboxes-columnchange.pin-menu postbox-toggled.pin-menu wp-collapse-menu.pin-menu wp-scroll-start.pin-menu', setPinMenu ); // Set initial focus on a specific element. $( '.wp-initial-focus' ).focus(); }); // Fire a custom jQuery event at the end of window resize ( function() { var timeout; function triggerEvent() { $document.trigger( 'wp-window-resized' ); } function fireOnce() { window.clearTimeout( timeout ); timeout = window.setTimeout( triggerEvent, 200 ); } $window.on( 'resize.wp-fire-once', fireOnce ); }()); // Make Windows 8 devices play along nicely. (function(){ if ( '-ms-user-select' in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/) ) { var msViewportStyle = document.createElement( 'style' ); msViewportStyle.appendChild( document.createTextNode( '@-ms-viewport{width:auto!important}' ) ); document.getElementsByTagName( 'head' )[0].appendChild( msViewportStyle ); } })(); }( jQuery, window )); comment.js 0000666 00000003762 15213733063 0006563 0 ustar 00 /* global postboxes, commentL10n */ jQuery(document).ready( function($) { postboxes.add_postbox_toggles('comment'); var $timestampdiv = $('#timestampdiv'), $timestamp = $( '#timestamp' ), stamp = $timestamp.html(), $timestampwrap = $timestampdiv.find( '.timestamp-wrap' ), $edittimestamp = $timestampdiv.siblings( 'a.edit-timestamp' ); $edittimestamp.click( function( event ) { if ( $timestampdiv.is( ':hidden' ) ) { $timestampdiv.slideDown( 'fast', function() { $( 'input, select', $timestampwrap ).first().focus(); } ); $(this).hide(); } event.preventDefault(); }); $timestampdiv.find('.cancel-timestamp').click( function( event ) { // Move focus back to the Edit link. $edittimestamp.show().focus(); $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()); $timestamp.html( stamp ); event.preventDefault(); }); $timestampdiv.find('.save-timestamp').click( function( event ) { // crazyhorse - multiple ok cancels var aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(), newD = new Date( aa, mm - 1, jj, hh, mn ); event.preventDefault(); if ( newD.getFullYear() != aa || (1 + newD.getMonth()) != mm || newD.getDate() != jj || newD.getMinutes() != mn ) { $timestampwrap.addClass( 'form-invalid' ); return; } else { $timestampwrap.removeClass( 'form-invalid' ); } $timestamp.html( commentL10n.submittedOn + ' <b>' + commentL10n.dateFormat .replace( '%1$s', $( 'option[value="' + mm + '"]', '#mm' ).attr( 'data-text' ) ) .replace( '%2$s', parseInt( jj, 10 ) ) .replace( '%3$s', aa ) .replace( '%4$s', ( '00' + hh ).slice( -2 ) ) .replace( '%5$s', ( '00' + mn ).slice( -2 ) ) + '</b> ' ); // Move focus back to the Edit link. $edittimestamp.show().focus(); $timestampdiv.slideUp( 'fast' ); }); }); user-suggest.js 0000666 00000002056 15213733063 0007551 0 ustar 00 /* global ajaxurl, current_site_id, isRtl */ (function( $ ) { var id = ( typeof current_site_id !== 'undefined' ) ? '&site_id=' + current_site_id : ''; $(document).ready( function() { var position = { offset: '0, -1' }; if ( typeof isRtl !== 'undefined' && isRtl ) { position.my = 'right top'; position.at = 'right bottom'; } $( '.wp-suggest-user' ).each( function(){ var $this = $( this ), autocompleteType = ( typeof $this.data( 'autocompleteType' ) !== 'undefined' ) ? $this.data( 'autocompleteType' ) : 'add', autocompleteField = ( typeof $this.data( 'autocompleteField' ) !== 'undefined' ) ? $this.data( 'autocompleteField' ) : 'user_login'; $this.autocomplete({ source: ajaxurl + '?action=autocomplete-user&autocomplete_type=' + autocompleteType + '&autocomplete_field=' + autocompleteField + id, delay: 500, minLength: 2, position: position, open: function() { $( this ).addClass( 'open' ); }, close: function() { $( this ).removeClass( 'open' ); } }); }); }); })( jQuery ); set-post-thumbnail.min.js 0000666 00000001015 15213733063 0011427 0 ustar 00 function WPSetAsThumbnail(e,t){var o=jQuery("a#wp-post-thumbnail-"+e);o.text(setPostThumbnailL10n.saving),jQuery.post(ajaxurl,{action:"set-post-thumbnail",post_id:post_id,thumbnail_id:e,_ajax_nonce:t,cookie:encodeURIComponent(document.cookie)},function(t){var n=window.dialogArguments||opener||parent||top;o.text(setPostThumbnailL10n.setThumbnail),"0"==t?alert(setPostThumbnailL10n.error):(jQuery("a.wp-post-thumbnail").show(),o.text(setPostThumbnailL10n.done),o.fadeOut(2e3),n.WPSetThumbnailID(e),n.WPSetThumbnailHTML(t))})}
dvadf
dvadf
| ver. 1.4 |
Github
|
.
| PHP 7.0.33 | Generation time: 0.03 |
proxy
|
phpinfo
|
Settings