PK#ZG3Jcustom-header.jsnu[/** * @output wp-admin/js/custom-header.js */ /* global isRtl */ /** * Initializes the custom header selection page. * * @since 3.5.0 * * @deprecated 4.1.0 The page this is used on is never linked to from the UI. * Setting a custom header is completely handled by the Customizer. */ (function($) { var frame; $( function() { // Fetch available headers. var $headers = $('.available-headers'); // Apply jQuery.masonry once the images have loaded. $headers.imagesLoaded( function() { $headers.masonry({ itemSelector: '.default-header', isRTL: !! ( 'undefined' != typeof isRtl && isRtl ) }); }); /** * Opens the 'choose from library' frame and creates it if it doesn't exist. * * @since 3.5.0 * @deprecated 4.1.0 * * @return {void} */ $('#choose-from-library-link').on( '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 } }); /** * Updates the window location to include the selected attachment. * * @since 3.5.0 * @deprecated 4.1.0 * * @return {void} */ 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)); PK#Z^custom-background.min.jsnu[/*! This file is auto-generated */ !function(e){e(function(){var c,a=e("#custom-background-image");e("#background-color").wpColorPicker({change:function(n,o){a.css("background-color",o.color.toString())},clear:function(){a.css("background-color","")}}),e('select[name="background-size"]').on("change",function(){a.css("background-size",e(this).val())}),e('input[name="background-position"]').on("change",function(){a.css("background-position",e(this).val())}),e('input[name="background-repeat"]').on("change",function(){a.css("background-repeat",e(this).is(":checked")?"repeat":"no-repeat")}),e('input[name="background-attachment"]').on("change",function(){a.css("background-attachment",e(this).is(":checked")?"scroll":"fixed")}),e("#choose-from-library-link").on("click",function(n){var o=e(this);n.preventDefault(),c||(c=wp.media.frames.customBackground=wp.media({title:o.data("choose"),library:{type:"image"},button:{text:o.data("update"),close:!1}})).on("select",function(){var n=c.state().get("selection").first(),o=e("#_wpnonce").val()||"";e.post(ajaxurl,{action:"set-background-image",attachment_id:n.id,_ajax_nonce:o,size:"full"}).done(function(){window.location.reload()})}),c.open()})})}(jQuery);PK#ZBc c plugin-install.min.jsnu[/*! This file is auto-generated */ jQuery(function(e){var o,i,n,a,l,r=e(),s=e(".upload-view-toggle"),t=e(".wrap"),d=e(document.body);function c(){var t;n=e(":tabbable",i),a=o.find("#TB_closeWindowButton"),l=n.last(),(t=a.add(l)).off("keydown.wp-plugin-details"),t.on("keydown.wp-plugin-details",function(t){9===(t=t).which&&(l[0]!==t.target||t.shiftKey?a[0]===t.target&&t.shiftKey&&(t.preventDefault(),l.trigger("focus")):(t.preventDefault(),a.trigger("focus")))})}window.tb_position=function(){var t=e(window).width(),i=e(window).height()-(792").text(e),a||((t=o('")).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").trigger("focus"),tagBox.userAction="remove",tagBox.parseTags(this))}),e.prepend(" ").prepend(t)),i.append(e))}),tagBox.screenReadersMessage())},flushTags:function(t,e,a){var i,n,s=o(".the-tags",t),c=o("input.newtag",t);return void 0!==(n=(e=e||!1)?o(e).text():c.val())&&""!==n&&(i=s.val(),i=this.clean(i=i?i+r+n:n),i=array_unique_noempty(i.split(r)).join(r),s.val(i),this.quickClicks(t),e||c.val(""),void 0===a)&&c.trigger("focus"),!1},get:function(a){var i=a.substr(a.indexOf("-")+1);o.post(ajaxurl,{action:"get-tagcloud",tax:i},function(t,e){0!==t&&"success"==e&&(t=o('
'+t+"
"),o("a",t).on("click",function(){return tagBox.userAction="add",tagBox.flushTags(o("#"+i),this),!1}),o("#"+a).after(t))})},userAction:"",screenReadersMessage:function(){var t;switch(this.userAction){case"remove":t=wp.i18n.__("Term removed.");break;case"add":t=wp.i18n.__("Term added.");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).on("click",function(){tagBox.userAction="add",tagBox.flushTags(o(this).closest(".tagsdiv"))}),o("input.newtag",t).on("keypress",function(t){13==t.which&&(tagBox.userAction="add",tagBox.flushTags(o(this).closest(".tagsdiv")),t.preventDefault(),t.stopPropagation())}).each(function(t,e){o(e).wpTagsSuggest()}),o("#post").on("submit",function(){o("div.tagsdiv").each(function(){tagBox.flushTags(this,!1,1)})}),o(".tagcloud-link").on("click",function(){tagBox.get(o(this).attr("id")),o(this).attr("aria-expanded","true").off().on("click",function(){o(this).attr("aria-expanded","false"===o(this).attr("aria-expanded")?"true":"false").siblings(".the-tagcloud").toggle()})})}}}(jQuery);PK#Z"{(&(&color-picker.jsnu[/** * @output wp-admin/js/color-picker.js */ ( function( $, undef ) { var ColorPicker, _before = '', _after = '
', _wrap = '
', _button = '', _wrappingLabel = '', _wrappingLabelText = '', __ = wp.i18n.__; /** * Creates a jQuery UI color picker that is used in the theme customizer. * * @class $.widget.wp.wpColorPicker * * @since 3.5.0 */ ColorPicker = /** @lends $.widget.wp.wpColorPicker.prototype */{ options: { defaultColor: false, change: false, clear: false, hide: true, palettes: true, width: 255, mode: 'hsv', type: 'full', slider: 'horizontal' }, /** * Creates a color picker that only allows you to adjust the hue. * * @since 3.5.0 * @access private * * @return {void} */ _createHueOnly: function() { var self = this, el = self.element, color; el.hide(); // Set the saturation to the maximum level. color = 'hsl(' + el.val() + ', 100, 50)'; // Create an instance of the color picker, using the hsl mode. el.iris( { mode: 'hsl', type: 'hue', hide: false, color: color, /** * Handles the onChange event if one has been defined in the options. * * @ignore * * @param {Event} event The event that's being called. * @param {HTMLElement} ui The HTMLElement containing the color picker. * * @return {void} */ change: function( event, ui ) { if ( typeof self.options.change === 'function' ) { self.options.change.call( this, event, ui ); } }, width: self.options.width, slider: self.options.slider } ); }, /** * Creates the color picker, sets default values, css classes and wraps it all in HTML. * * @since 3.5.0 * @access private * * @return {void} */ _create: function() { // Return early if Iris support is missing. if ( ! $.support.iris ) { return; } var self = this, el = self.element; // Override default options with options bound to the element. $.extend( self.options, el.data() ); // Create a color picker which only allows adjustments to the hue. if ( self.options.type === 'hue' ) { return self._createHueOnly(); } // Bind the close event. self.close = self.close.bind( self ); self.initialValue = el.val(); // Add a CSS class to the input field. el.addClass( 'wp-color-picker' ); /* * Check if there's already a wrapping label, e.g. in the Customizer. * If there's no label, add a default one to match the Customizer template. */ if ( ! el.parent( 'label' ).length ) { // Wrap the input field in the default label. el.wrap( _wrappingLabel ); // Insert the default label text. self.wrappingLabelText = $( _wrappingLabelText ) .insertBefore( el ) .text( __( 'Color value' ) ); } /* * At this point, either it's the standalone version or the Customizer * one, we have a wrapping label to use as hook in the DOM, let's store it. */ self.wrappingLabel = el.parent(); // Wrap the label in the main wrapper. self.wrappingLabel.wrap( _wrap ); // Store a reference to the main wrapper. self.wrap = self.wrappingLabel.parent(); // Set up the toggle button and insert it before the wrapping label. self.toggler = $( _before ) .insertBefore( self.wrappingLabel ) .css( { backgroundColor: self.initialValue } ); // Set the toggle button span element text. self.toggler.find( '.wp-color-result-text' ).text( __( 'Select Color' ) ); // Set up the Iris container and insert it after the wrapping label. self.pickerContainer = $( _after ).insertAfter( self.wrappingLabel ); // Store a reference to the Clear/Default button. self.button = $( _button ); // Set up the Clear/Default button. if ( self.options.defaultColor ) { self.button .addClass( 'wp-picker-default' ) .val( __( 'Default' ) ) .attr( 'aria-label', __( 'Select default color' ) ); } else { self.button .addClass( 'wp-picker-clear' ) .val( __( 'Clear' ) ) .attr( 'aria-label', __( 'Clear color' ) ); } // Wrap the wrapping label in its wrapper and append the Clear/Default button. self.wrappingLabel .wrap( '
"),i.toggleEditor(o,0,!0),wp.a11y.speak(t,"assertive")}).attr("src",ajaxurl+"?"+c.param(t))},action:function(i,t,e){var a,o,r,n,s=this;if(s.notsaved(i))return!1;if(t={action:"image-editor",_ajax_nonce:t,postid:i},"scale"===e){if(a=c("#imgedit-scale-width-"+i),o=c("#imgedit-scale-height-"+i),r=s.intval(a.val()),n=s.intval(o.val()),r<1)return a.trigger("focus"),!1;if(n<1)return o.trigger("focus"),!1;if(r===s.hold.ow||n===s.hold.oh)return!1;t.do="scale",t.fwidth=r,t.fheight=n}else{if("restore"!==e)return!1;t.do="restore"}s.toggleEditor(i,1),c.post(ajaxurl,t,function(t){c("#image-editor-"+i).empty().append(t.data.html),s.toggleEditor(i,0,!0),s._view&&s._view.refresh()}).done(function(t){t&&t.data.message.msg?wp.a11y.speak(t.data.message.msg):t&&t.data.message.error&&wp.a11y.speak(t.data.message.error)})},save:function(i,t){var e=this.getTarget(i),a=this.filterHistory(i,0),o=this;if(""===a)return!1;this.toggleEditor(i,1),t={action:"image-editor",_ajax_nonce:t,postid:i,history:a,target:e,context:c("#image-edit-context").length?c("#image-edit-context").val():null,do:"save"},c.post(ajaxurl,t,function(t){t.data.error?(c("#imgedit-response-"+i).html('"),d.close(i),wp.a11y.speak(t.data.error)):(t.data.fw&&t.data.fh&&c("#media-dims-"+i).html(t.data.fw+" × "+t.data.fh),t.data.thumbnail&&c(".thumbnail","#thumbnail-head-"+i).attr("src",""+t.data.thumbnail),t.data.msg&&(c("#imgedit-response-"+i).html('"),wp.a11y.speak(t.data.msg)),o._view?o._view.save():d.close(i))})},open:function(e,t,i){this._view=i;var a=c("#image-editor-"+e),o=c("#media-head-"+e),r=c("#imgedit-open-btn-"+e),n=r.siblings(".spinner");if(!r.hasClass("button-activated"))return n.addClass("is-active"),c.ajax({url:ajaxurl,type:"post",data:{action:"image-editor",_ajax_nonce:t,postid:e,do:"open"},beforeSend:function(){r.addClass("button-activated")}}).done(function(t){var i;"-1"===t&&(i=s("Could not load the preview image."),a.html('")),t.data&&t.data.html&&a.html(t.data.html),o.fadeOut("fast",function(){a.fadeIn("fast",function(){i&&c(document).trigger("image-editor-ui-ready")}),r.removeClass("button-activated"),n.removeClass("is-active")}),d.init(e)})},imgLoaded:function(t){var i=c("#image-preview-"+t),e=c("#imgedit-crop-"+t);void 0===this.hold.sizer&&this.init(t),this.calculateImgSize(t),this.initCrop(t,i,e),this.setCropSelection(t,{x1:0,y1:0,x2:0,y2:0,width:i.innerWidth(),height:i.innerHeight()}),this.toggleEditor(t,0,!0)},focusManager:function(){setTimeout(function(){var t=c('.notice[role="alert"]');(t=t.length?t:c(".imgedit-wrap").find(":tabbable:first")).attr("tabindex","-1").trigger("focus")},100)},initCrop:function(r,t,i){var n=this,o=c("#imgedit-sel-width-"+r),s=c("#imgedit-sel-height-"+r),t=c(t);t.data("imgAreaSelect")||(n.iasapi=t.imgAreaSelect({parent:i,instance:!0,handles:!0,keys:!0,minWidth:3,minHeight:3,onInit:function(t){c(t).next().css("position","absolute").nextAll(".imgareaselect-outer").css("position","absolute"),i.children().on("mousedown touchstart",function(t){var i=!1,e=n.iasapi.getSelection(),a=n.intval(c("#imgedit-crop-width-"+r).val()),o=n.intval(c("#imgedit-crop-height-"+r).val());a&&o?i=n.getSelRatio(r):t.shiftKey&&e&&e.width&&e.height&&(i=e.width+":"+e.height),n.iasapi.setOptions({aspectRatio:i})})},onSelectStart:function(){d.setDisabled(c("#imgedit-crop-sel-"+r),1),d.setDisabled(c(".imgedit-crop-clear"),1),d.setDisabled(c(".imgedit-crop-apply"),1)},onSelectEnd:function(t,i){d.setCropSelection(r,i),c("#imgedit-crop > *").is(":visible")||d.toggleControls(c(".imgedit-crop.button"))},onSelectChange:function(t,i){var e=d.hold.sizer,a=d.currentCropSelection;null!=a&&a.width==i.width&&a.height==i.height||(o.val(Math.min(d.hold.w,d.round(i.width/e))),s.val(Math.min(d.hold.h,d.round(i.height/e))),n.currentCropSelection=i)}}))},setCropSelection:function(t,i){var e=c("#imgedit-sel-width-"+t),a=c("#imgedit-sel-height-"+t),o=this.hold.sizer,r=this.hold;if(!(i=i||0)||i.width<3&&i.height<3)return this.setDisabled(c(".imgedit-crop","#imgedit-panel-"+t),1),this.setDisabled(c("#imgedit-crop-sel-"+t),1),c("#imgedit-sel-width-"+t).val(""),c("#imgedit-sel-height-"+t).val(""),c("#imgedit-start-x-"+t).val("0"),c("#imgedit-start-y-"+t).val("0"),c("#imgedit-selection-"+t).val(""),!1;var n=r.w-(Math.round(i.x1/o)+parseInt(e.val())),r=r.h-(Math.round(i.y1/o)+parseInt(a.val())),n={r:1,x:Math.round(i.x1/o)+Math.min(0,n),y:Math.round(i.y1/o)+Math.min(0,r),w:e.val(),h:a.val()};this.setDisabled(c(".imgedit-crop","#imgedit-panel-"+t),1),c("#imgedit-selection-"+t).val(JSON.stringify(n))},close:function(t,i){if((i=i||!1)&&this.notsaved(t))return!1;this.iasapi={},this.hold={},this._view?this._view.back():c("#image-editor-"+t).fadeOut("fast",function(){c("#media-head-"+t).fadeIn("fast",function(){c("#imgedit-open-btn-"+t).trigger("focus")}),c(this).empty()})},notsaved:function(t){var i=c("#imgedit-history-"+t).val(),i=""!==i?JSON.parse(i):[];return this.intval(c("#imgedit-undone-"+t).val())

'+o+"

"),wp.a11y.speak(o,"assertive"),c(i?"#imgedit-crop-height-"+t:"#imgedit-crop-width-"+t).val("")):void 0!==(r=c("#imgedit-crop-"+t).find(".notice-error"))&&r.remove(),this.iasapi.setSelection(e.x1,e.y1,e.x2,a),this.iasapi.update())},validateNumeric:function(t){if(!1===this.intval(c(t).val()))return c(t).val(""),!1}}}(jQuery);PK$Z?@user-profile.min.jsnu[/*! This file is auto-generated */ !function(o){var s,a,t,n,i,r,l,p,d,c,u,h,f,w=!1,m=!1,v=wp.i18n.__;function g(){"function"!=typeof zxcvbn?setTimeout(g,50):(!a.val()||h.hasClass("is-open")?(a.val(a.data("pw")),a.trigger("pwupdate")):C(),x(),y(),1!==parseInt(r.data("start-masked"),10)?a.attr("type","text"):r.trigger("click"),o("#pw-weak-text-label").text(v("Confirm use of weak password")),"mailserver_pass"!==a.prop("id")&&o(a).trigger("focus"))}function b(e){r.attr({"aria-label":v(e?"Show password":"Hide password")}).find(".text").text(v(e?"Show":"Hide")).end().find(".dashicons").removeClass(e?"dashicons-hidden":"dashicons-visibility").addClass(e?"dashicons-visibility":"dashicons-hidden")}function y(){r||(r=s.find(".wp-hide-pw")).show().on("click",function(){"password"===a.attr("type")?(a.attr("type","text"),b(!1)):(a.attr("type","password"),b(!0))})}function k(e,s,a){var t=o("
",{role:"alert"});t.addClass("notice inline"),t.addClass("notice-"+(s?"success":"error")),t.text(o(o.parseHTML(a)).text()).wrapInner("

"),e.prop("disabled",s),e.siblings(".notice").remove(),e.before(t)}function _(){var e;s=o(".user-pass1-wrap, .user-pass-wrap, .mailserver-pass-wrap, .reset-pass-submit"),o(".user-pass2-wrap").hide(),p=o("#submit, #wp-submit").on("click",function(){w=!1}),l=p.add(" #createusersub"),n=o(".pw-weak"),(i=n.find(".pw-checkbox")).on("change",function(){l.prop("disabled",!i.prop("checked"))}),(a=o("#pass1, #mailserver_pass")).length?(d=a.val(),1===parseInt(a.data("reveal"),10)&&g(),a.on("input pwupdate",function(){a.val()!==d&&(d=a.val(),a.removeClass("short bad good strong"),x())})):a=o("#user_pass"),t=o("#pass2").on("input",function(){0]*>/gi,""),t[e].length)&&-1===o.inArray(s,a)&&(a.push(s),o("

")}).fail(function(e){s.siblings(".notice").remove(),s.before('")}),e.preventDefault()}),window.generatePassword=g,o(window).on("beforeunload",function(){return!0===w?v("Your new password has not been saved."):u===c.serialize()||m?void 0:v("The changes you made will be lost if you navigate away from this page.")}),o(function(){o(".reset-pass-submit").length&&o(".reset-pass-submit button.wp-generate-pw").trigger("click")})}(jQuery);PK$Zp[GGrevisions.min.jsnu[/*! This file is auto-generated */ window.wp=window.wp||{},function(a){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)},a.fn.allOffsets=function(){var e=this.offset()||{top:0,left:0},i=a(window);return _.extend(e,{right:i.width()-e.left-this.outerWidth(),bottom:i.height()-e.top-this.outerHeight()})},a.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=a.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=a.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){var s,o;return"read"===e?((t=t||{}).context=this,t.data=_.extend(t.data||{},{action:"get-revision-diffs",post_id:this.postId}),s=wp.ajax.send(t),o=this.requests,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):Backbone.Model.prototype.sync.apply(this,arguments)}}),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.started&&Backbone.history.stop(),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||{},s=this.get("from"),i=this.get("to"),t=(s?s.id:0)+":"+i.id,this._diffId===t?a.Deferred().reject().promise():(this._diffId=t,this.trigger("update:revisions",s,i),(s=this.diffs.get(t))?(this.receiveDiff(s),a.Deferred().resolve().promise()):e.immediate?this._ensureDiff():(this._debouncedEnsureDiff(),a.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),a("html").css("overflow-y","scroll"),a("#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.Checkbox({model:this.model})),this.views.add(new s.view.Buttons({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.SliderHelp),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=a(window),this.window.on("scroll.wp.revisions",{controls:this},function(e){var e=e.data.controls,i=e.$el.parent(),t=e.window.scrollTop(),s=e.views.parent;t>=e.top?(s.$el.hasClass("pinned")||(e.setWidth(),i.css("height",i.height()+"px"),e.window.on("resize.wp.revisions.pinning click.wp.revisions.pinning",{controls:e},function(e){e.data.controls.setWidth()})),s.$el.addClass("pinned")):(s.$el.hasClass("pinned")&&(e.window.off(".wp.revisions.pinning"),e.$el.css("width","auto"),s.$el.removeClass("pinned"),i.css("height","auto")),e.top=e.$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,i=this.model.revisions.indexOf(i),s=this.$el.allOffsets(),o=this.$el.parent().allOffsets();i===this.model.revisions.length-1?t={rightPlusWidth:s.left-o.left+1,leftPlusWidth:s.right-o.right+1}:(t=(i=this.$("div:nth-of-type("+(i+1)+")")).allPositions(),_.extend(t,{left:t.left+s.left-o.left,right:t.right+s.right-o.right}),_.extend(t,{leftPlusWidth:t.left+i.outerWidth(),rightPlusWidth:t.right+i.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('
')},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&&a(".revision-toggle-compare-mode").hide()},updateCompareTwoMode:function(){this.$(".compare-two-revisions").prop("checked",this.model.get("compareTwoMode"))},compareTwoToggle:function(){this.model.set({compareTwoMode:a(".compare-two-revisions").prop("checked")})}}),s.view.SliderHelp=wp.Backbone.View.extend({className:"revisions-slider-hidden-help",template:wp.template("revisions-slider-hidden-help")}),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(){a(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=a(".revisions-next .button"),t=a(".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()},accessibilityHelper:function(){var e=a(".ui-slider-handle");e.first().attr({role:"button","aria-labelledby":"diff-title-from diff-title-author","aria-describedby":"revisions-slider-hidden-help"}),e.last().attr({role:"button","aria-labelledby":"diff-title-to diff-title-author","aria-describedby":"revisions-slider-hidden-help"})},mouseMove:function(e){var i=this.model.revisions.length-1,t=this.$el.allOffsets()[this.direction],i=this.$el.width()/i,e=(isRtl?a(window).width()-e.pageX:e.pageX)-t,t=Math.floor((e+i/2)/i);t<0?t=0:t>=this.model.revisions.length&&(t=this.model.revisions.length-1),this.model.set({hoveredRevision:this.model.revisions.at(t)})},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"),this.accessibilityHelper()},start:function(e,d){this.model.set({scrubbing:!0}),a(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=a(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.pageXo?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 autoresizeMinHeight ) { textEditor.style.height = textEditor.scrollHeight + 'px'; } if ( typeof x !== 'undefined' ) { window.scrollTo( x, y ); } if ( textEditor.scrollHeight < height ) { adjust(); } }, 300 ); /** * Resizes the text editor depending on the old text length. * * If there is an mceEditor and it is hidden, it resizes the editor depending * on the old text length. If the current length of the text is smaller than * the old text length, it shrinks the text area. Otherwise it resizes the editor to * the scroll height. * * @since 4.6.1 * * @return {void} */ 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; } /** * Gets the height and widths of elements. * * Gets the heights of the window, the adminbar, the tools, the menu, * the visualTop, the textTop, the bottom, the statusbar and sideSortables * and stores these in the heights object. Defaults to 0. * Gets the width of the window and stores this in the heights object. * * @since 4.0.0 * * @return {void} */ 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 menubar. if ( heights.menuBarHeight < 3 ) { heights.menuBarHeight = 0; } } // We need to wait for TinyMCE to initialize. /** * Binds all necessary functions for editor expand to the editor when the editor * is initialized. * * @since 4.0.0 * * @param {event} event The TinyMCE editor init event. * @param {object} editor The editor to bind the vents on. * * @return {void} */ $document.on( 'tinymce-editor-init.editor-expand', function( event, editor ) { // VK contains the type of key pressed. VK = virtual keyboard. var VK = window.tinymce.util.VK, /** * Hides any float panel with a hover state. Additionally hides tooltips. * * @return {void} */ 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' ); /** * Gets the offset of the editor. * * @return {number|boolean} Returns the offset of the editor * or false if there is no offset height. */ function mceGetCursorOffset() { var node = editor.selection.getNode(), range, view, offset; /* * If editor.wp.getView and the selection node from the editor selection * are defined, use this as a view for the offset. */ if ( editor.wp && editor.wp.getView && ( view = editor.wp.getView( node ) ) ) { offset = view.getBoundingClientRect(); } else { range = editor.selection.getRng(); // Try to get the offset from a range. try { offset = range.getClientRects()[0]; } catch( er ) {} // Get the offset from the bounding client rectangle of the node. if ( ! offset ) { offset = node.getBoundingClientRect(); } } return offset.height ? offset : false; } /** * Filters the special keys that should not be used for scrolling. * * @since 4.0.0 * * @param {event} event The event to get the key code from. * * @return {void} */ function mceKeyup( event ) { var key = event.keyCode; // Bail on special keys. Key code 47 is a '/'. 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. Key code 91-93 are OS keys. // Key code 112-123 are F1 to F12. Key code 144 is num lock. Key code 145 is scroll lock. } else if ( ( key >= 91 && key <= 93 ) || ( key >= 112 && key <= 123 ) || key === 144 || key === 145 ) { return; } mceScroll( key ); } /** * Makes sure the cursor is always visible in the editor. * * Makes sure the cursor is kept between the toolbars of the editor and scrolls * 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. * * @since 4.1.0 * * @param {string} key The key code of the pressed key. * * @return {void} */ function mceScroll( key ) { var offset = mceGetCursorOffset(), buffer = 50, cursorTop, cursorBottom, editorTop, editorBottom; // Don't scroll if there is no offset. if ( ! offset ) { return; } // Determine the cursorTop based on the offset and the top of the editor iframe. cursorTop = offset.top + editor.iframeElement.getBoundingClientRect().top; // Determine the cursorBottom based on the cursorTop and offset height. cursorBottom = cursorTop + offset.height; // Subtract the buffer from the cursorTop. cursorTop = cursorTop - buffer; // Add the buffer to the cursorBottom. cursorBottom = cursorBottom + buffer; editorTop = heights.adminBarHeight + heights.toolsHeight + heights.menuBarHeight + heights.visualTopHeight; /* * Set the editorBottom based on the window Height, and add the bottomHeight and statusBarHeight if the * advanced editor is enabled. */ 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 the cursorTop is smaller than the editorTop and the up, left * or backspace key is pressed, scroll the editor to the position defined * by the cursorTop, pageYOffset and editorTop. */ if ( cursorTop < editorTop && ( key === VK.UP || key === VK.LEFT || key === VK.BACKSPACE ) ) { window.scrollTo( window.pageXOffset, cursorTop + window.pageYOffset - editorTop ); /* * If any other key is pressed or the cursorTop is bigger than the editorTop, * scroll the editor to the position defined by the cursorBottom, * pageYOffset and editorBottom. */ } else if ( cursorBottom > editorBottom ) { window.scrollTo( window.pageXOffset, cursorBottom + window.pageYOffset - editorBottom ); } } /** * If the editor is fullscreen, calls adjust. * * @since 4.1.0 * * @param {event} event The FullscreenStateChanged event. * * @return {void} */ function mceFullscreenToggled( event ) { // event.state is true if the editor is fullscreen. if ( ! event.state ) { adjust(); } } /** * Shows the editor when scrolled. * * Binds the hideFloatPanels function on the window scroll.mce-float-panels event. * Executes the wpAutoResize on the active editor. * * @since 4.0.0 * * @return {void} */ function mceShow() { $window.on( 'scroll.mce-float-panels', hideFloatPanels ); setTimeout( function() { editor.execCommand( 'wpAutoResize' ); adjust(); }, 300 ); } /** * Resizes the editor. * * Removes all functions from the window scroll.mce-float-panels event. * Resizes the text editor and scrolls to a position based on the pageXOffset and adminBarHeight. * * @since 4.0.0 * * @return {void} */ 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(); } /** * Toggles advanced states. * * @since 4.1.0 * * @return {void} */ function toggleAdvanced() { advanced = ! advanced; } /** * Binds events of the editor and window. * * @since 4.0.0 * * @return {void} */ 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 ); }; /** * Unbinds the events of the editor and window. * * @since 4.0.0 * * @return {void} */ 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 ); } } ); /** * Adjusts the toolbars heights and positions. * * Adjusts the toolbars heights and positions based on the scroll position on * the page, the active editor mode and the heights of the editor, admin bar and * side bar. * * @since 4.0.0 * * @param {event} event The event that calls this function. * * @return {void} */ function adjust( event ) { // Makes 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 type isn't 'scroll' * or heights.windowHeight isn't set. */ if ( resize || ! heights.windowHeight ) { getHeights(); } // Resize on resize event when the editor is in text mode. if ( ! visual && type === 'resize' ) { textEditorResize(); } if ( visual ) { $top = $visualTop; $editor = $visualEditor; topHeight = heights.visualTopHeight; } else { $top = $textTop; $editor = $textEditor; topHeight = heights.textTopHeight; } // Return if TinyMCE is still initializing. if ( ! visual && ! $top.length ) { return; } topPos = $top.parent().offset().top; editorPos = $editor.offset().top; editorHeight = $editor.outerHeight(); /* * If in visual mode, checks if the editorHeight is greater than the autoresizeMinHeight + topHeight. * If not in visual mode, checks if the editorHeight is greater than the autoresizeMinHeight + 20. */ 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 { // Check if the top is not already in a fixed position. if ( ( ! fixedTop || resize ) && ( windowPos >= ( topPos - heights.toolsHeight - heights.adminBarHeight ) && 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() ) ) } ); // Check if the top is already in a fixed position. } else if ( fixedTop || resize ) { 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() ) ) } ); } 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() ) ) } ); } } // Check if the bottom is not already in a fixed position. if ( ( ! fixedBottom || ( resize && advanced ) ) && // Add borderWidth 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', '' ); } } // The postbox container is positioned with @media from CSS. Ensure it is pinned on the side. if ( $postboxContainer.width() < 300 && heights.windowWidth > 600 && // Check if the sidebar is not taller than the document height. $document.height() > ( $sideSortables.height() + postBodyTop + 120 ) && // Check if the editor is taller than the viewport. heights.windowHeight < editorHeight ) { if ( ( heights.sideSortablesHeight + pinnedToolsTop + sidebarBottom ) > heights.windowHeight || fixedSideTop || fixedSideBottom ) { // Reset the sideSortables style when scrolling to the top. if ( windowPos + pinnedToolsTop <= postBodyTop ) { $sideSortables.attr( 'style', '' ); fixedSideTop = fixedSideBottom = false; } else { // When scrolling down. if ( windowPos > lastScrollPosition ) { 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 }); } // When scrolling up. } else if ( windowPos < lastScrollPosition ) { 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 } ); } } } /** * Resizes the editor and adjusts the toolbars. * * @since 4.0.0 * * @return {void} */ function fullscreenHide() { textEditorResize(); adjust(); } /** * Runs the passed function with 500ms intervals. * * @since 4.0.0 * * @param {function} callback The function to run in the timeout. * * @return {void} */ function initialResize( callback ) { for ( var i = 1; i < 6; i++ ) { setTimeout( callback, 500 * i ); } } /** * Runs adjust after 100ms. * * @since 4.0.0 * * @return {void} */ function afterScroll() { clearTimeout( scrollTimer ); scrollTimer = setTimeout( adjust, 100 ); } /** * Binds editor expand events on elements. * * @since 4.0.0 * * @return {void} */ function on() { /* * Scroll to the top when triggering this from JS. * Ensure the 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 * or 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 or 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' ); } /** * Unbinds editor expand events. * * @since 4.0.0 * * @return {void} */ 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. * Ensure the 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 or 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 there is a height found in the user setting. if ( height ) { $textEditor.height( height ); } $document.trigger( 'editor-expand-off' ); } // Start on load. if ( $wrap.hasClass( 'wp-editor-expand' ) ) { on(); // 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 }; } ); /** * Handles the distraction free writing of TinyMCE. * * @since 4.1.0 * * @return {void} */ $( 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; } ); /** * Recalculates the bottom and right position of the editor in the DOM. * * @since 4.1.0 * * @return {void} */ function recalcEditorRect() { editorRect = $editor.offset(); editorRect.right = editorRect.left + $editor.outerWidth(); editorRect.bottom = editorRect.top + $editor.outerHeight(); } /** * Activates the distraction free writing mode. * * @since 4.1.0 * * @return {void} */ function activate() { if ( ! _isActive ) { _isActive = true; $document.trigger( 'dfw-activate' ); $content.on( 'keydown.focus-shortcut', toggleViaKeyboard ); } } /** * Deactivates the distraction free writing mode. * * @since 4.1.0 * * @return {void} */ function deactivate() { if ( _isActive ) { off(); _isActive = false; $document.trigger( 'dfw-deactivate' ); $content.off( 'keydown.focus-shortcut' ); } } /** * Returns _isActive. * * @since 4.1.0 * * @return {boolean} Returns true is _isActive is true. */ function isActive() { return _isActive; } /** * Binds events on the editor for distraction free writing. * * @since 4.1.0 * * @return {void} */ 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' ); } } /** * Unbinds events on the editor for distraction free writing. * * @since 4.1.0 * * @return {void} */ function off() { if ( _isOn ) { _isOn = false; $title.add( $content ).off( '.focus' ); fadeIn(); $editor.off( '.focus' ); window.setUserSetting( 'post_dfw', 'off' ); $document.trigger( 'dfw-off' ); } } /** * Binds or unbinds the editor expand events. * * @since 4.1.0 * * @return {void} */ function toggle() { if ( _isOn ) { off(); } else { on(); } } /** * Returns the value of _isOn. * * @since 4.1.0 * * @return {boolean} Returns true if _isOn is true. */ function isOn() { return _isOn; } /** * Fades out all elements except for the editor. * * The fading is done based on key presses and mouse movements. * Also calls the fadeIn on certain key presses * or if the mouse leaves the editor. * * @since 4.1.0 * * @param event The event that triggers this function. * * @return {void} */ function fadeOut( event ) { var isMac, key = event && event.keyCode; if ( window.navigator.platform ) { isMac = ( window.navigator.platform.indexOf( 'Mac' ) > -1 ); } // Fade in and returns 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; } // Return if any of the following keys or combinations of keys is pressed. 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 when 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, 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(); } /** * Fades all elements back in. * * @since 4.1.0 * * @param event The event that triggers this function. * * @return {void} */ 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(); } /** * Fades in if the focused element based on it position. * * @since 4.1.0 * * @return {void} */ 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 ); } /** * Fades out the admin bar based on focus on the admin bar. * * @since 4.1.0 * * @return {void} */ function fadeOutAdminBar() { if ( ! fadedAdminBar && faded ) { fadedAdminBar = true; $adminBar .on( 'mouseenter.focus', function() { $adminBar.addClass( 'focus-off' ); } ) .on( 'mouseleave.focus', function() { $adminBar.removeClass( 'focus-off' ); } ); } } /** * Fades in the admin bar. * * @since 4.1.0 * * @return {void} */ function fadeInAdminBar() { if ( fadedAdminBar ) { fadedAdminBar = false; $adminBar.off( '.focus' ); } } /** * Fades out the edit slug box. * * @since 4.1.0 * * @return {void} */ 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' ); } } /** * Fades in the edit slug box. * * @since 4.1.0 * * @return {void} */ 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' ); } } /** * Triggers the toggle on Alt + Shift + W. * * Keycode 87 = w. * * @since 4.1.0 * * @param {event} event The event to trigger the toggle. * * @return {void} */ function toggleViaKeyboard( event ) { if ( event.altKey && event.shiftKey && 87 === event.keyCode ) { toggle(); } } if ( $( '#postdivrich' ).hasClass( 'wp-editor-expand' ) ) { $content.on( 'keydown.focus-shortcut', toggleViaKeyboard ); } /** * Adds the distraction free writing button when setting up TinyMCE. * * @since 4.1.0 * * @param {event} event The TinyMCE editor setup event. * @param {object} editor The editor to add the button to. * * @return {void} */ $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; editor.on( 'init', function() { if ( button.disabled() ) { button.hide(); } } ); $document .on( 'dfw-activate.focus', function() { button.disabled( false ); button.show(); } ) .on( 'dfw-deactivate.focus', function() { button.disabled( true ); button.hide(); } ) .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' ); } ); /** * Binds and unbinds events on the editor. * * @since 4.1.0 * * @param {event} event The TinyMCE editor init event. * @param {object} editor The editor to bind events on. * * @return {void} */ $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(); } // Bind and unbind based on the distraction free writing focus. $document.on( 'dfw-on.focus', mceBind ).on( 'dfw-off.focus', mceUnbind ); // Focus the editor when it is the target of the click event. editor.on( 'click', function( event ) { if ( event.target === editor.getDoc().documentElement ) { editor.focus(); } } ); } } ); /** * Binds events on quicktags init. * * @since 4.1.0 * * @param {event} event The quicktags init event. * @param {object} editor The editor to bind events on. * * @return {void} */ $document.on( 'quicktags-init', function( event, editor ) { var $button; // Bind the distraction free writing events if the distraction free writing button is available. 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 ); PK$ZMBcustomize-nav-menus.jsnu[/** * @output wp-admin/js/customize-nav-menus.js */ /* global menus, _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(); }; /** * @namespace wp.customize.Menus */ 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. * * @alias wp.customize.Menus.generatePlaceholderAutoIncrementId * * @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. * * @class wp.customize.Menus.AvailableItemModel * @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. * * @class wp.customize.Menus.AvailableItemCollection * @augments Backbone.Collection */ api.Menus.AvailableItemCollection = Backbone.Collection.extend(/** @lends wp.customize.Menus.AvailableItemCollection.prototype */{ 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 * @alias wp.customize.Menus.insertAutoDraftPost * * @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', 'customize_changeset_uuid': api.settings.changeset.uuid, '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(); }; api.Menus.AvailableMenuItemsPanelView = wp.Backbone.View.extend(/** @lends wp.customize.Menus.AvailableMenuItemsPanelView.prototype */{ el: '#available-menu-items', events: { 'input #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, /** * wp.customize.Menus.AvailableMenuItemsPanelView * * View class for the available menu items panel. * * @constructs wp.customize.Menus.AvailableMenuItemsPanelView * @augments wp.Backbone.View */ 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 an `input` event to fire a new search. this.$clearResults.on( 'click', function() { self.$search.val( '' ).trigger( 'focus' ).trigger( 'input' ); } ); this.$el.on( 'input', '#custom-menu-item-name.invalid, #custom-menu-item-url.invalid', function() { $( this ).removeClass( 'invalid' ); var errorMessageId = $( this ).attr( 'aria-describedby' ); $( '#' + errorMessageId ).hide(); $( this ).removeAttr( 'aria-invalid' ).removeAttr( 'aria-describedby' ); }); // Load available items if it looks like we'll need them. api.panel( 'nav_menus' ).container.on( 'expanded', function() { if ( ! self.rendered ) { self.initList(); self.rendered = true; } }); // Load more items. this.sectionContent.on( '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( $( '
  • ' ).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.} itemTypes List of objects containing type and key. * @param {string} deprecated Formerly the object parameter. * @return {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' ).trigger( '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; } this.currentMenuControl.addItemToMenu( menu_item.attributes ); $( 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' ), urlErrorMessage = $( '#custom-url-error' ), nameErrorMessage = $( '#custom-name-error' ), url = itemUrl.val().trim(), urlRegex, errorText; if ( ! this.currentMenuControl ) { return; } /* * Allow URLs including: * - http://example.com/ * - //example.com * - /directory/ * - ?query-param * - #target * - mailto:foo@example.com * * Any further validation will be handled on the server when the setting is attempted to be saved, * so this pattern does not need to be complete. */ urlRegex = /^((\w+:)?\/\/\w.*|\w+:(?!\/\/$)|\/|\?|#)/; if ( ! urlRegex.test( url ) || '' === itemName.val() ) { if ( ! urlRegex.test( url ) ) { itemUrl.addClass( 'invalid' ) .attr( 'aria-invalid', 'true' ) .attr( 'aria-describedby', 'custom-url-error' ); urlErrorMessage.show(); errorText = urlErrorMessage.text(); // Announce error message via screen reader wp.a11y.speak( errorText, 'assertive' ); } if ( '' === itemName.val() ) { itemName.addClass( 'invalid' ) .attr( 'aria-invalid', 'true' ) .attr( 'aria-describedby', 'custom-name-error' ); nameErrorMessage.show(); errorText = ( '' === errorText ) ? nameErrorMessage.text() : errorText + nameErrorMessage.text(); // Announce error message via screen reader wp.a11y.speak( errorText, 'assertive' ); } return; } urlErrorMessage.hide(); nameErrorMessage.hide(); itemName.removeClass( 'invalid' ) .removeAttr( 'aria-invalid', 'true' ) .removeAttr( 'aria-describedby', 'custom-name-error' ); itemUrl.removeClass( 'invalid' ) .removeAttr( 'aria-invalid', 'true' ) .removeAttr( 'aria-describedby', 'custom-name-error' ); menuItem = { 'title': itemName.val(), 'url': url, 'type': 'custom', 'type_label': api.Menus.data.l10n.custom_label, 'object': 'custom' }; this.currentMenuControl.addItemToMenu( menuItem ); // Reset the custom link form. itemUrl.val( '' ).attr( 'placeholder', 'https://' ); itemName.val( '' ); }, /** * Submit handler for keypress (enter) on field and click on button. * * @since 4.7.0 * @private * * @param {jQuery.Event} event Event. * @return {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 * @return {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 ( '' === itemName.val().trim() ) { 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 ) { var panel = this, close; this.currentMenuControl = menuControl; this.itemSectionHeight(); if ( api.section.has( 'publish_settings' ) ) { api.section( 'publish_settings' ).collapse(); } $( 'body' ).addClass( 'adding-menu-items' ); close = function() { panel.close(); $( this ).off( 'click', close ); }; $( '#customize-preview' ).on( 'click', close ); // Collapse all controls. _( this.currentMenuControl.getMenuItemControls() ).each( function( control ) { control.collapseForm(); } ); this.$el.find( '.selected' ).removeClass( 'selected' ); this.$search.trigger( '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( '' ).trigger( 'input' ); }, // 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. * * @class wp.customize.Menus.MenusPanel * @augments wp.customize.Panel */ api.Menus.MenusPanel = api.Panel.extend(/** @lends wp.customize.Menus.MenusPanel.prototype */{ 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' ).on( 'click', function() { panel.saveManageColumnsState(); }); // Inject additional heading into the menu locations section's head container. api.section( 'menu_locations', function( section ) { section.headContainer.prepend( wp.template( 'nav-menu-locations-header' )( api.Menus.data ) ); } ); }, /** * Save hidden column states. * * @since 4.3.0 * @private * * @return {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 * * @return {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. * * @class wp.customize.Menus.MenuSection * @augments wp.customize.Section */ api.Menus.MenuSection = api.Section.extend(/** @lends wp.customize.Menus.MenuSection.prototype */{ /** * 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} * @return {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, menuLocationsControlId, menuAutoAddControlId, menuDeleteControlId, menuControl, menuNameControl, menuLocationsControl, menuAutoAddControl, menuDeleteControl; // 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, { type: 'nav_menu_name', label: api.Menus.data.l10n.menuNameLabel, section: section.id, priority: 0, settings: { 'default': section.id } } ); api.control.add( menuNameControl ); menuNameControl.active.set( true ); } // Add the menu control. menuControl = api.control( section.id ); if ( ! menuControl ) { menuControl = new api.controlConstructor.nav_menu( section.id, { type: 'nav_menu', section: section.id, priority: 998, settings: { 'default': section.id }, menu_id: section.params.menu_id } ); api.control.add( menuControl ); menuControl.active.set( true ); } // Add the menu locations control. menuLocationsControlId = section.id + '[locations]'; menuLocationsControl = api.control( menuLocationsControlId ); if ( ! menuLocationsControl ) { menuLocationsControl = new api.controlConstructor.nav_menu_locations( menuLocationsControlId, { section: section.id, priority: 999, settings: { 'default': section.id }, menu_id: section.params.menu_id } ); api.control.add( menuLocationsControl.id, menuLocationsControl ); 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, { type: 'nav_menu_auto_add', label: '', section: section.id, priority: 1000, settings: { 'default': section.id } } ); api.control.add( menuAutoAddControl ); menuAutoAddControl.active.set( true ); } // Add the control for deleting the menu. menuDeleteControlId = section.id + '[delete]'; menuDeleteControl = api.control( menuDeleteControlId ); if ( ! menuDeleteControl ) { menuDeleteControl = new api.Control( menuDeleteControlId, { section: section.id, priority: 1001, templateId: 'nav-menu-delete-button' } ); api.control.add( menuDeleteControl.id, menuDeleteControl ); menuDeleteControl.active.set( true ); menuDeleteControl.deferred.embedded.done( function () { menuDeleteControl.container.find( 'button' ).on( 'click', function() { var menuId = section.params.menu_id; var menuControl = api.Menus.getMenuControl( menuId ); menuControl.setting.set( false ); }); } ); } }, /** * */ 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 button:first' ); $title.find( '.menu-in-location' ).remove(); _.each( themeLocationSlugs, function( themeLocationSlug ) { var $label, locationName; $label = $( '' ); 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' ); api.Menus.MenuItemControl.prototype.initAccessibility(); _.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 ); }, /** * Highlight how a user may create new menu items. * * This method reminds the user to create new menu items and how. * It's exposed this way because this class knows best which UI needs * highlighted but those expanding this section know more about why and * when the affordance should be highlighted. * * @since 4.9.0 * * @return {void} */ highlightNewItemButton: function() { api.utils.highlightButton( this.contentContainer.find( '.add-new-menu-item' ), { delay: 2000 } ); } }); /** * Create a nav menu setting and section. * * @since 4.9.0 * * @param {string} [name=''] Nav menu name. * @return {wp.customize.Menus.MenuSection} Added nav menu. */ api.Menus.createNavMenu = function createNavMenu( name ) { var customizeId, placeholderId, setting; placeholderId = api.Menus.generatePlaceholderAutoIncrementId(); customizeId = 'nav_menu[' + String( placeholderId ) + ']'; // Register the menu control setting. setting = api.create( customizeId, customizeId, {}, { type: 'nav_menu', transport: api.Menus.data.settingTransport, previewer: api.previewer } ); setting.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. */ return api.section.add( new api.Menus.MenuSection( customizeId, { panel: 'nav_menus', title: displayNavMenuName( name ), customizeAction: api.Menus.data.l10n.customizingMenus, priority: 10, menu_id: placeholderId } ) ); }; /** * wp.customize.Menus.NewMenuSection * * Customizer section for new menus. * * @class wp.customize.Menus.NewMenuSection * @augments wp.customize.Section */ api.Menus.NewMenuSection = api.Section.extend(/** @lends wp.customize.Menus.NewMenuSection.prototype */{ /** * Add behaviors for the accordion section. * * @since 4.3.0 */ attachEvents: function() { var section = this, container = section.container, contentContainer = section.contentContainer, navMenuSettingPattern = /^nav_menu\[/; section.headContainer.find( '.accordion-section-title' ).replaceWith( wp.template( 'nav-menu-create-menu-section-title' ) ); /* * We have to manually handle section expanded because we do not * apply the `accordion-section-title` class to this button-driven section. */ container.on( 'click', '.customize-add-menu-button', function() { section.expand(); }); contentContainer.on( 'keydown', '.menu-name-field', function( event ) { if ( 13 === event.which ) { // Enter. section.submit(); } } ); contentContainer.on( 'click', '#customize-new-menu-submit', function( event ) { section.submit(); event.stopPropagation(); event.preventDefault(); } ); /** * Get number of non-deleted nav menus. * * @since 4.9.0 * @return {number} Count. */ function getNavMenuCount() { var count = 0; api.each( function( setting ) { if ( navMenuSettingPattern.test( setting.id ) && false !== setting.get() ) { count += 1; } } ); return count; } /** * Update visibility of notice to prompt users to create menus. * * @since 4.9.0 * @return {void} */ function updateNoticeVisibility() { container.find( '.add-new-menu-notice' ).prop( 'hidden', getNavMenuCount() > 0 ); } /** * Handle setting addition. * * @since 4.9.0 * @param {wp.customize.Setting} setting - Added setting. * @return {void} */ function addChangeEventListener( setting ) { if ( navMenuSettingPattern.test( setting.id ) ) { setting.bind( updateNoticeVisibility ); updateNoticeVisibility(); } } /** * Handle setting removal. * * @since 4.9.0 * @param {wp.customize.Setting} setting - Removed setting. * @return {void} */ function removeChangeEventListener( setting ) { if ( navMenuSettingPattern.test( setting.id ) ) { setting.unbind( updateNoticeVisibility ); updateNoticeVisibility(); } } api.each( addChangeEventListener ); api.bind( 'add', addChangeEventListener ); api.bind( 'removed', removeChangeEventListener ); updateNoticeVisibility(); api.Section.prototype.attachEvents.apply( section, arguments ); }, /** * Set up the control. * * @since 4.9.0 */ ready: function() { this.populateControls(); }, /** * Create the controls for this section. * * @since 4.9.0 */ populateControls: function() { var section = this, menuNameControlId, menuLocationsControlId, newMenuSubmitControlId, menuNameControl, menuLocationsControl, newMenuSubmitControl; menuNameControlId = section.id + '[name]'; menuNameControl = api.control( menuNameControlId ); if ( ! menuNameControl ) { menuNameControl = new api.controlConstructor.nav_menu_name( menuNameControlId, { label: api.Menus.data.l10n.menuNameLabel, description: api.Menus.data.l10n.newMenuNameDescription, section: section.id, priority: 0 } ); api.control.add( menuNameControl.id, menuNameControl ); menuNameControl.active.set( true ); } menuLocationsControlId = section.id + '[locations]'; menuLocationsControl = api.control( menuLocationsControlId ); if ( ! menuLocationsControl ) { menuLocationsControl = new api.controlConstructor.nav_menu_locations( menuLocationsControlId, { section: section.id, priority: 1, menu_id: '', isCreating: true } ); api.control.add( menuLocationsControlId, menuLocationsControl ); menuLocationsControl.active.set( true ); } newMenuSubmitControlId = section.id + '[submit]'; newMenuSubmitControl = api.control( newMenuSubmitControlId ); if ( !newMenuSubmitControl ) { newMenuSubmitControl = new api.Control( newMenuSubmitControlId, { section: section.id, priority: 1, templateId: 'nav-menu-submit-new-button' } ); api.control.add( newMenuSubmitControlId, newMenuSubmitControl ); newMenuSubmitControl.active.set( true ); } }, /** * Create the new menu with name and location supplied by the user. * * @since 4.9.0 */ submit: function() { var section = this, contentContainer = section.contentContainer, nameInput = contentContainer.find( '.menu-name-field' ).first(), name = nameInput.val(), menuSection; if ( ! name ) { nameInput.addClass( 'invalid' ); nameInput.focus(); return; } menuSection = api.Menus.createNavMenu( name ); // Clear name field. nameInput.val( '' ); nameInput.removeClass( 'invalid' ); contentContainer.find( '.assigned-menu-location input[type=checkbox]' ).each( function() { var checkbox = $( this ), navMenuLocationSetting; if ( checkbox.prop( 'checked' ) ) { navMenuLocationSetting = api( 'nav_menu_locations[' + checkbox.data( 'location-id' ) + ']' ); navMenuLocationSetting.set( menuSection.params.menu_id ); // Reset state for next new menu. checkbox.prop( 'checked', false ); } } ); wp.a11y.speak( api.Menus.data.l10n.menuAdded ); // Focus on the new menu section. menuSection.focus( { completeCallback: function() { menuSection.highlightNewItemButton(); } } ); }, /** * Select a default location. * * This method selects a single location by default so we can support * creating a menu for a specific menu location. * * @since 4.9.0 * * @param {string|null} locationId - The ID of the location to select. `null` clears all selections. * @return {void} */ selectDefaultLocation: function( locationId ) { var locationControl = api.control( this.id + '[locations]' ), locationSelections = {}; if ( locationId !== null ) { locationSelections[ locationId ] = true; } locationControl.setSelections( locationSelections ); } }); /** * wp.customize.Menus.MenuLocationControl * * Customizer control for menu locations (rendered as a ",{type:"hidden",name:"_method",value:"GET"})),_.each(a.query,function(e,t){i.append(J("",{type:"hidden",name:t,value:e}))}),a.container.append(i),i.trigger("submit"),i.remove()),a.bind("iframe-loading-error",function(e){a.iframe.remove(),0===e?a.login(t):-1===e?t.rejectWith(a,["cheatin"]):t.rejectWith(a,["request failure"])}),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();J.get(Y.settings.url.ajax,{action:"logged-in"}).fail(a).done(function(e){var t;"1"!==e&&a(),(t=J("