X-Git-Url: https://scripts.mit.edu/gitweb/autoinstalls/wordpress.git/blobdiff_plain/7f1521bf193b382565eb753043c161f4cb3fcda7..b22765f41bf0b2021b9beb9120ee0ac91fa89292:/wp-admin/js/customize-controls.js diff --git a/wp-admin/js/customize-controls.js b/wp-admin/js/customize-controls.js index e211a41f..8fa7bb09 100644 --- a/wp-admin/js/customize-controls.js +++ b/wp-admin/js/customize-controls.js @@ -1,15 +1,24 @@ -/* globals _wpCustomizeHeader, _wpCustomizeBackground, _wpMediaViewsL10n, MediaElementPlayer */ +/* global _wpCustomizeHeader, _wpCustomizeBackground, _wpMediaViewsL10n, MediaElementPlayer */ (function( exports, $ ){ var Container, focus, api = wp.customize; /** + * A Customizer Setting. + * + * A setting is WordPress data (theme mod, option, menu, etc.) that the user can + * draft changes to in the Customizer. + * + * @see PHP class WP_Customize_Setting. + * * @class * @augments wp.customize.Value * @augments wp.customize.Class * - * @param options - * - previewer - The Previewer instance to sync with. - * - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'. + * @param {object} id The Setting ID. + * @param {object} value The initial value of the setting. + * @param {object} options.previewer The Previewer instance to sync with. + * @param {object} options.transport The transport to use for previewing. Supports 'refresh' and 'postMessage'. + * @param {object} options.dirty */ api.Setting = api.Value.extend({ initialize: function( id, value, options ) { @@ -18,9 +27,15 @@ this.id = id; this.transport = this.transport || 'refresh'; this._dirty = options.dirty || false; + this.notifications = new api.Values({ defaultConstructor: api.Notification }); + // Whenever the setting's value changes, refresh the preview. this.bind( this.preview ); }, + + /** + * Refresh the preview, respective of the setting's refresh policy. + */ preview: function() { switch ( this.transport ) { case 'refresh': @@ -28,6 +43,24 @@ case 'postMessage': return this.previewer.send( 'setting', [ this.id, this() ] ); } + }, + + /** + * Find controls associated with this setting. + * + * @since 4.6.0 + * @returns {wp.customize.Control[]} Controls associated with setting. + */ + findControls: function() { + var setting = this, controls = []; + api.control.each( function( control ) { + _.each( control.settings, function( controlSetting ) { + if ( controlSetting.id === setting.id ) { + controls.push( control ); + } + } ); + } ); + return controls; } }); @@ -60,21 +93,28 @@ * @since 4.1.0 * * @param {Object} [params] - * @param {Callback} [params.completeCallback] + * @param {Function} [params.completeCallback] */ focus = function ( params ) { - var construct, completeCallback, focus; + var construct, completeCallback, focus, focusElement; construct = this; params = params || {}; focus = function () { var focusContainer; - if ( construct.extended( api.Panel ) && construct.expanded() ) { - focusContainer = construct.container.find( '.control-panel-content:first' ); + if ( construct.extended( api.Panel ) && construct.expanded && construct.expanded() ) { + focusContainer = construct.container.find( 'ul.control-panel-content' ); + } else if ( construct.extended( api.Section ) && construct.expanded && construct.expanded() ) { + focusContainer = construct.container.find( 'ul.accordion-section-content' ); } else { focusContainer = construct.container; } - focusContainer.find( ':focusable:first' ).focus(); - focusContainer[0].scrollIntoView( true ); + + focusElement = focusContainer.find( '.control-focus:first' ); + if ( 0 === focusElement.length ) { + // Note that we can't use :focusable due to a jQuery UI issue. See: https://github.com/jquery/jquery-ui/pull/1583 + focusElement = focusContainer.find( 'input, select, textarea, button, object, a[href], [tabindex]' ).filter( ':visible' ).first(); + } + focusElement.focus(); }; if ( params.completeCallback ) { completeCallback = params.completeCallback; @@ -156,19 +196,46 @@ Container = api.Class.extend({ defaultActiveArguments: { duration: 'fast', completeCallback: $.noop }, defaultExpandedArguments: { duration: 'fast', completeCallback: $.noop }, + containerType: 'container', + defaults: { + title: '', + description: '', + priority: 100, + type: 'default', + content: null, + active: true, + instanceNumber: null + }, /** * @since 4.1.0 * - * @param {String} id - * @param {Object} options + * @param {string} id - The ID for the container. + * @param {object} options - Object containing one property: params. + * @param {object} options.params - Object containing the following properties. + * @param {string} options.params.title - Title shown when panel is collapsed and expanded. + * @param {string=} [options.params.description] - Description shown at the top of the panel. + * @param {number=100} [options.params.priority] - The sort priority for the panel. + * @param {string=default} [options.params.type] - The type of the panel. See wp.customize.panelConstructor. + * @param {string=} [options.params.content] - The markup to be used for the panel container. If empty, a JS template is used. + * @param {boolean=true} [options.params.active] - Whether the panel is active or not. */ initialize: function ( id, options ) { var container = this; container.id = id; - container.params = {}; - $.extend( container, options || {} ); + options = options || {}; + + options.params = _.defaults( + options.params || {}, + container.defaults + ); + + $.extend( container, options ); + container.templateSelector = 'customize-' + container.containerType + '-' + container.params.type; container.container = $( container.params.content ); + if ( 0 === container.container.length ) { + container.container = $( container.getContainer() ); + } container.deferred = { embedded: new $.Deferred() @@ -191,11 +258,13 @@ container.onChangeExpanded( expanded, args ); }); - container.attachEvents(); + container.deferred.embedded.done( function () { + container.attachEvents(); + }); api.utils.bubbleChildValueChanges( container, [ 'priority', 'active' ] ); - container.priority.set( isNaN( container.params.priority ) ? 100 : container.params.priority ); + container.priority.set( container.params.priority ); container.active.set( container.params.active ); container.expanded.set( false ); }, @@ -240,10 +309,9 @@ }, /** - * Handle changes to the active state. + * Active state change handler. * - * This does not change the active state, it merely handles the behavior - * for when it does change. + * Shows the container if it is active, hides it if not. * * To override by subclass, update the container's UI to reflect the provided active state. * @@ -254,18 +322,58 @@ * @param {Object} args.duration * @param {Object} args.completeCallback */ - onChangeActive: function ( active, args ) { - var duration = ( 'resolved' === api.previewer.deferred.active.state() ? args.duration : 0 ); - if ( ! $.contains( document, this.container ) ) { + onChangeActive: function( active, args ) { + var duration, construct = this, expandedOtherPanel; + if ( args.unchanged ) { + if ( args.completeCallback ) { + args.completeCallback(); + } + return; + } + + duration = ( 'resolved' === api.previewer.deferred.active.state() ? args.duration : 0 ); + + if ( construct.extended( api.Panel ) ) { + // If this is a panel is not currently expanded but another panel is expanded, do not animate. + api.panel.each(function ( panel ) { + if ( panel !== construct && panel.expanded() ) { + expandedOtherPanel = panel; + duration = 0; + } + }); + + // Collapse any expanded sections inside of this panel first before deactivating. + if ( ! active ) { + _.each( construct.sections(), function( section ) { + section.collapse( { duration: 0 } ); + } ); + } + } + + if ( ! $.contains( document, construct.container[0] ) ) { // jQuery.fn.slideUp is not hiding an element if it is not in the DOM - this.container.toggle( active ); + construct.container.toggle( active ); if ( args.completeCallback ) { args.completeCallback(); } } else if ( active ) { - this.container.stop( true, true ).slideDown( duration, args.completeCallback ); + construct.container.stop( true, true ).slideDown( duration, args.completeCallback ); } else { - this.container.stop( true, true ).slideUp( duration, args.completeCallback ); + if ( construct.expanded() ) { + construct.collapse({ + duration: duration, + completeCallback: function() { + construct.container.stop( true, true ).slideUp( duration, args.completeCallback ); + } + }); + } else { + construct.container.stop( true, true ).slideUp( duration, args.completeCallback ); + } + } + + // Recalculate the margin-top immediately, not waiting for debounced reflow, to prevent momentary (100ms) vertical jiggle. + if ( expandedOtherPanel ) { + expandedOtherPanel._recalculateTopMargin(); } }, @@ -316,39 +424,48 @@ }, /** - * @param {Boolean} expanded - * @param {Object} [params] - * @returns {Boolean} false if state already applied + * Handle the toggle logic for expand/collapse. + * + * @param {Boolean} expanded - The new state to apply. + * @param {Object} [params] - Object containing options for expand/collapse. + * @param {Function} [params.completeCallback] - Function to call when expansion/collapse is complete. + * @returns {Boolean} false if state already applied or active state is false */ - _toggleExpanded: function ( expanded, params ) { - var self = this; + _toggleExpanded: function( expanded, params ) { + var instance = this, previousCompleteCallback; params = params || {}; - var section = this, previousCompleteCallback = params.completeCallback; - params.completeCallback = function () { + previousCompleteCallback = params.completeCallback; + + // Short-circuit expand() if the instance is not active. + if ( expanded && ! instance.active() ) { + return false; + } + + params.completeCallback = function() { if ( previousCompleteCallback ) { - previousCompleteCallback.apply( section, arguments ); + previousCompleteCallback.apply( instance, arguments ); } if ( expanded ) { - section.container.trigger( 'expanded' ); + instance.container.trigger( 'expanded' ); } else { - section.container.trigger( 'collapsed' ); + instance.container.trigger( 'collapsed' ); } }; - if ( ( expanded && this.expanded.get() ) || ( ! expanded && ! this.expanded.get() ) ) { + if ( ( expanded && instance.expanded.get() ) || ( ! expanded && ! instance.expanded.get() ) ) { params.unchanged = true; - self.onChangeExpanded( self.expanded.get(), params ); + instance.onChangeExpanded( instance.expanded.get(), params ); return false; } else { params.unchanged = false; - this.expandedArgumentsQueue.push( params ); - this.expanded.set( expanded ); + instance.expandedArgumentsQueue.push( params ); + instance.expanded.set( expanded ); return true; } }, /** * @param {Object} [params] - * @returns {Boolean} false if already expanded + * @returns {Boolean} false if already expanded or if inactive. */ expand: function ( params ) { return this._toggleExpanded( true, params ); @@ -356,7 +473,7 @@ /** * @param {Object} [params] - * @returns {Boolean} false if already collapsed + * @returns {Boolean} false if already collapsed. */ collapse: function ( params ) { return this._toggleExpanded( false, params ); @@ -366,7 +483,28 @@ * Bring the container into view and then expand this and bring it into view * @param {Object} [params] */ - focus: focus + focus: focus, + + /** + * Return the container html, generated from its JS template, if it exists. + * + * @since 4.3.0 + */ + getContainer: function () { + var template, + container = this; + + if ( 0 !== $( '#tmpl-' + container.templateSelector ).length ) { + template = wp.template( container.templateSelector ); + } else { + template = wp.template( 'customize-' + container.containerType + '-default' ); + } + if ( template && container.container ) { + return $.trim( template( container.params ) ); + } + + return '
  • '; + } }); /** @@ -376,12 +514,33 @@ * @augments wp.customize.Class */ api.Section = Container.extend({ + containerType: 'section', + defaults: { + title: '', + description: '', + priority: 100, + type: 'default', + content: null, + active: true, + instanceNumber: null, + panel: null, + customizeAction: '' + }, /** * @since 4.1.0 * - * @param {String} id - * @param {Array} options + * @param {string} id - The ID for the section. + * @param {object} options - Object containing one property: params. + * @param {object} options.params - Object containing the following properties. + * @param {string} options.params.title - Title shown when section is collapsed and expanded. + * @param {string=} [options.params.description] - Description shown at the top of the section. + * @param {number=100} [options.params.priority] - The sort priority for the section. + * @param {string=default} [options.params.type] - The type of the section. See wp.customize.sectionConstructor. + * @param {string=} [options.params.content] - The markup to be used for the section container. If empty, a JS template is used. + * @param {boolean=true} [options.params.active] - Whether the section is active or not. + * @param {string} options.params.panel - The ID for the panel this section is associated with. + * @param {string=} [options.params.customizeAction] - Additional context information shown before the section title when expanded. */ initialize: function ( id, options ) { var section = this; @@ -435,6 +594,13 @@ }; section.panel.bind( inject ); inject( section.panel.get() ); // Since a section may never get a panel, assume that it won't ever get one + + section.deferred.embedded.done(function() { + // Fix the top margin after reflow. + api.bind( 'pane-contents-reflowed', _.debounce( function() { + section._recalculateTopMargin(); + }, 100 ) ); + }); }, /** @@ -446,7 +612,7 @@ var section = this; // Expand/Collapse accordion sections on click. - section.container.find( '.accordion-section-title' ).on( 'click keydown', function( event ) { + section.container.find( '.accordion-section-title, .customize-section-back' ).on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } @@ -500,17 +666,49 @@ */ onChangeExpanded: function ( expanded, args ) { var section = this, + container = section.container.closest( '.wp-full-overlay-sidebar-content' ), content = section.container.find( '.accordion-section-content' ), - expand; + overlay = section.container.closest( '.wp-full-overlay' ), + backBtn = section.container.find( '.customize-section-back' ), + sectionTitle = section.container.find( '.accordion-section-title' ).first(), + headerActionsHeight = $( '#customize-header-actions' ).height(), + resizeContentHeight, expand, position, scroll; - if ( expanded ) { + if ( expanded && ! section.container.hasClass( 'open' ) ) { if ( args.unchanged ) { expand = args.completeCallback; } else { - expand = function () { - content.stop().slideDown( args.duration, args.completeCallback ); + container.scrollTop( 0 ); + resizeContentHeight = function() { + var matchMedia, offset; + matchMedia = window.matchMedia || window.msMatchMedia; + offset = 90; // 45px for customize header actions + 45px for footer actions. + + // No footer on small screens. + if ( matchMedia && matchMedia( '(max-width: 640px)' ).matches ) { + offset = 45; + } + content.css( 'height', ( window.innerHeight - offset ) ); + }; + expand = function() { section.container.addClass( 'open' ); + overlay.addClass( 'section-open' ); + position = content.offset().top; + scroll = container.scrollTop(); + content.css( 'margin-top', ( headerActionsHeight - position - scroll ) ); + resizeContentHeight(); + sectionTitle.attr( 'tabindex', '-1' ); + backBtn.attr( 'tabindex', '0' ); + backBtn.focus(); + if ( args.completeCallback ) { + args.completeCallback(); + } + + // Fix the height after browser resize. + $( window ).on( 'resize.customizer-section', _.debounce( resizeContentHeight, 100 ) ); + + setTimeout( _.bind( section._recalculateTopMargin, section ), 0 ); }; } @@ -528,12 +726,47 @@ completeCallback: expand }); } else { + api.panel.each( function( panel ) { + panel.collapse(); + }); expand(); } - } else { + } else if ( ! expanded && section.container.hasClass( 'open' ) ) { section.container.removeClass( 'open' ); - content.slideUp( args.duration, args.completeCallback ); + overlay.removeClass( 'section-open' ); + content.css( 'margin-top', '' ); + container.scrollTop( 0 ); + backBtn.attr( 'tabindex', '-1' ); + sectionTitle.attr( 'tabindex', '0' ); + sectionTitle.focus(); + if ( args.completeCallback ) { + args.completeCallback(); + } + $( window ).off( 'resize.customizer-section' ); + } else { + if ( args.completeCallback ) { + args.completeCallback(); + } + } + }, + + /** + * Recalculate the top margin. + * + * @since 4.4.0 + * @private + */ + _recalculateTopMargin: function() { + var section = this, content, offset, headerActionsHeight; + content = section.container.find( '.accordion-section-content' ); + if ( 0 === content.length ) { + return; + } + headerActionsHeight = $( '#customize-header-actions' ).height(); + offset = ( content.offset().top - headerActionsHeight ); + if ( 0 < offset ) { + content.css( 'margin-top', ( parseInt( content.css( 'margin-top' ), 10 ) - offset ) ); } } }); @@ -718,7 +951,6 @@ overlay = section.closest( '.wp-full-overlay' ), container = section.closest( '.wp-full-overlay-sidebar-content' ), siblings = container.find( '.open' ), - topPanel = overlay.find( '#customize-theme-controls > ul > .accordion-section > .accordion-section-title' ).add( '#customize-info > .accordion-section-title' ), customizeBtn = section.find( '.customize-theme' ), changeBtn = section.find( '.change-theme' ), content = section.find( '.control-panel-content' ); @@ -748,8 +980,6 @@ args.completeCallback(); } } ); - topPanel.attr( 'tabindex', '-1' ); - changeBtn.attr( 'tabindex', '-1' ); customizeBtn.focus(); } else { siblings.removeClass( 'open' ); @@ -762,13 +992,22 @@ args.completeCallback(); } } ); - topPanel.attr( 'tabindex', '0' ); customizeBtn.attr( 'tabindex', '0' ); changeBtn.focus(); container.scrollTop( 0 ); } }, + /** + * Recalculate the top margin. + * + * @since 4.4.0 + * @private + */ + _recalculateTopMargin: function() { + api.Panel.prototype._recalculateTopMargin.call( this ); + }, + /** * Render control's screenshot if the control comes into view. * @@ -964,11 +1203,20 @@ * @augments wp.customize.Class */ api.Panel = Container.extend({ + containerType: 'panel', + /** * @since 4.1.0 * - * @param {String} id - * @param {Object} options + * @param {string} id - The ID for the panel. + * @param {object} options - Object containing one property: params. + * @param {object} options.params - Object containing the following properties. + * @param {string} options.params.title - Title shown when panel is collapsed and expanded. + * @param {string=} [options.params.description] - Description shown at the top of the panel. + * @param {number=100} [options.params.priority] - The sort priority for the panel. + * @param {string=default} [options.params.type] - The type of the panel. See wp.customize.panelConstructor. + * @param {string=} [options.params.content] - The markup to be used for the panel container. If empty, a JS template is used. + * @param {boolean=true} [options.params.active] - Whether the panel is active or not. */ initialize: function ( id, options ) { var panel = this; @@ -990,7 +1238,13 @@ if ( ! panel.container.parent().is( parentContainer ) ) { parentContainer.append( panel.container ); + panel.renderContent(); } + + api.bind( 'pane-contents-reflowed', _.debounce( function() { + panel._recalculateTopMargin(); + }, 100 ) ); + panel.deferred.embedded.resolve(); }, @@ -1012,25 +1266,40 @@ } }); + // Close panel. + panel.container.find( '.customize-panel-back' ).on( 'click keydown', function( event ) { + if ( api.utils.isKeydownButNotEnterEvent( event ) ) { + return; + } + event.preventDefault(); // Keep this AFTER the key filter above + + if ( panel.expanded() ) { + panel.collapse(); + } + }); + meta = panel.container.find( '.panel-meta:first' ); - meta.find( '> .accordion-section-title' ).on( 'click keydown', function( event ) { + meta.find( '> .accordion-section-title .customize-help-toggle' ).on( 'click keydown', function( event ) { if ( api.utils.isKeydownButNotEnterEvent( event ) ) { return; } event.preventDefault(); // Keep this AFTER the key filter above + meta = panel.container.find( '.panel-meta' ); if ( meta.hasClass( 'cannot-expand' ) ) { return; } - var content = meta.find( '.accordion-section-content:first' ); + var content = meta.find( '.customize-panel-description:first' ); if ( meta.hasClass( 'open' ) ) { meta.toggleClass( 'open' ); content.slideUp( panel.defaultExpandedArguments.duration ); + $( this ).attr( 'aria-expanded', false ); } else { content.slideDown( panel.defaultExpandedArguments.duration ); meta.toggleClass( 'open' ); + $( this ).attr( 'aria-expanded', true ); } }); @@ -1074,7 +1343,7 @@ * @param {Boolean} expanded * @param {Object} args * @param {Boolean} args.unchanged - * @param {Callback} args.completeCallback + * @param {Function} args.completeCallback */ onChangeExpanded: function ( expanded, args ) { @@ -1089,20 +1358,21 @@ // Note: there is a second argument 'args' passed var position, scroll, panel = this, - section = panel.container.closest( '.accordion-section' ), - overlay = section.closest( '.wp-full-overlay' ), - container = section.closest( '.wp-full-overlay-sidebar-content' ), + accordionSection = panel.container.closest( '.accordion-section' ), + overlay = accordionSection.closest( '.wp-full-overlay' ), + container = accordionSection.closest( '.wp-full-overlay-sidebar-content' ), siblings = container.find( '.open' ), - topPanel = overlay.find( '#customize-theme-controls > ul > .accordion-section > .accordion-section-title' ).add( '#customize-info > .accordion-section-title' ), - backBtn = overlay.find( '.control-panel-back' ), - panelTitle = section.find( '.accordion-section-title' ).first(), - content = section.find( '.control-panel-content' ); + topPanel = overlay.find( '#customize-theme-controls > ul > .accordion-section > .accordion-section-title' ), + backBtn = accordionSection.find( '.customize-panel-back' ), + panelTitle = accordionSection.find( '.accordion-section-title' ).first(), + content = accordionSection.find( '.control-panel-content' ), + headerActionsHeight = $( '#customize-header-actions' ).height(); if ( expanded ) { // Collapse any sibling sections/panels api.section.each( function ( section ) { - if ( ! section.panel() ) { + if ( panel.id !== section.panel() ) { section.collapse( { duration: 0 } ); } }); @@ -1116,8 +1386,8 @@ content.parent().show(); position = content.offset().top; scroll = container.scrollTop(); - content.css( 'margin-top', ( $( '#customize-header-actions' ).height() - position - scroll ) ); - section.addClass( 'current-panel' ); + content.css( 'margin-top', ( headerActionsHeight - position - scroll ) ); + accordionSection.addClass( 'current-panel' ); overlay.addClass( 'in-sub-panel' ); container.scrollTop( 0 ); if ( args.completeCallback ) { @@ -1127,9 +1397,10 @@ topPanel.attr( 'tabindex', '-1' ); backBtn.attr( 'tabindex', '0' ); backBtn.focus(); + panel._recalculateTopMargin(); } else { siblings.removeClass( 'open' ); - section.removeClass( 'current-panel' ); + accordionSection.removeClass( 'current-panel' ); overlay.removeClass( 'in-sub-panel' ); content.delay( 180 ).hide( 0, function() { content.css( 'margin-top', 'inherit' ); // Reset @@ -1142,6 +1413,42 @@ panelTitle.focus(); container.scrollTop( 0 ); } + }, + + /** + * Recalculate the top margin. + * + * @since 4.4.0 + * @private + */ + _recalculateTopMargin: function() { + var panel = this, headerActionsHeight, content, accordionSection; + headerActionsHeight = $( '#customize-header-actions' ).height(); + accordionSection = panel.container.closest( '.accordion-section' ); + content = accordionSection.find( '.control-panel-content' ); + content.css( 'margin-top', ( parseInt( content.css( 'margin-top' ), 10 ) - ( content.offset().top - headerActionsHeight ) ) ); + }, + + /** + * Render the panel from its JS template, if it exists. + * + * The panel's container must already exist in the DOM. + * + * @since 4.3.0 + */ + renderContent: function () { + var template, + panel = this; + + // Add the content to the container. + if ( 0 !== $( '#tmpl-' + panel.templateSelector + '-content' ).length ) { + template = wp.template( panel.templateSelector + '-content' ); + } else { + template = wp.template( 'customize-panel-default-content' ); + } + if ( template && panel.container ) { + panel.container.find( '.accordion-sub-container' ).html( template( panel.params ) ); + } } }); @@ -1155,14 +1462,16 @@ * @class * @augments wp.customize.Class * - * @param {string} id Unique identifier for the control instance. - * @param {object} options Options hash for the control instance. + * @param {string} id Unique identifier for the control instance. + * @param {object} options Options hash for the control instance. * @param {object} options.params - * @param {object} options.params.type Type of control (e.g. text, radio, dropdown-pages, etc.) - * @param {string} options.params.content The HTML content for the control. - * @param {string} options.params.priority Order of priority to show the control within the section. + * @param {object} options.params.type Type of control (e.g. text, radio, dropdown-pages, etc.) + * @param {string} options.params.content The HTML content for the control. + * @param {string} options.params.priority Order of priority to show the control within the section. * @param {string} options.params.active - * @param {string} options.params.section + * @param {string} options.params.section The ID of the section the control belongs to. + * @param {string} options.params.settings.default The ID of the setting the control relates to. + * @param {string} options.params.settings.data * @param {string} options.params.label * @param {string} options.params.description * @param {string} options.params.instanceNumber Order in which this instance was created in relation to other instances. @@ -1188,6 +1497,7 @@ control.priority = new api.Value(); control.active = new api.Value(); control.activeArgumentsQueue = []; + control.notifications = new api.Values({ defaultConstructor: api.Notification }); control.elements = []; @@ -1228,24 +1538,70 @@ api.utils.bubbleChildValueChanges( control, [ 'section', 'priority', 'active' ] ); - // Associate this control with its settings when they are created + /* + * After all settings related to the control are available, + * make them available on the control and embed the control into the page. + */ settings = $.map( control.params.settings, function( value ) { return value; }); - api.apply( api, settings.concat( function () { - var key; + if ( 0 === settings.length ) { + control.setting = null; control.settings = {}; - for ( key in control.params.settings ) { - control.settings[ key ] = api( control.params.settings[ key ] ); - } + control.embed(); + } else { + api.apply( api, settings.concat( function() { + var key; - control.setting = control.settings['default'] || null; + control.settings = {}; + for ( key in control.params.settings ) { + control.settings[ key ] = api( control.params.settings[ key ] ); + } - control.embed(); - }) ); + control.setting = control.settings['default'] || null; + + // Add setting notifications to the control notification. + _.each( control.settings, function( setting ) { + setting.notifications.bind( 'add', function( settingNotification ) { + var controlNotification, code, params; + code = setting.id + ':' + settingNotification.code; + params = _.extend( + {}, + settingNotification, + { + setting: setting.id + } + ); + controlNotification = new api.Notification( code, params ); + control.notifications.add( controlNotification.code, controlNotification ); + } ); + setting.notifications.bind( 'remove', function( settingNotification ) { + control.notifications.remove( setting.id + ':' + settingNotification.code ); + } ); + } ); + + control.embed(); + }) ); + } + // After the control is embedded on the page, invoke the "ready" method. control.deferred.embedded.done( function () { + /* + * Note that this debounced/deferred rendering is needed for two reasons: + * 1) The 'remove' event is triggered just _before_ the notification is actually removed. + * 2) Improve performance when adding/removing multiple notifications at a time. + */ + var debouncedRenderNotifications = _.debounce( function renderNotifications() { + control.renderNotifications(); + } ); + control.notifications.bind( 'add', function( notification ) { + wp.a11y.speak( notification.message, 'assertive' ); + debouncedRenderNotifications(); + } ); + control.notifications.bind( 'remove', debouncedRenderNotifications ); + control.renderNotifications(); + control.ready(); }); }, @@ -1260,7 +1616,7 @@ // Watch for changes to the section state inject = function ( sectionId ) { var parentContainer; - if ( ! sectionId ) { // @todo allow a control to be embedded without a section, for instance a control embedded in the frontend + if ( ! sectionId ) { // @todo allow a control to be embedded without a section, for instance a control embedded in the front end. return; } // Wait for the section to be registered @@ -1287,6 +1643,85 @@ */ ready: function() {}, + /** + * Get the element inside of a control's container that contains the validation error message. + * + * Control subclasses may override this to return the proper container to render notifications into. + * Injects the notification container for existing controls that lack the necessary container, + * including special handling for nav menu items and widgets. + * + * @since 4.6.0 + * @returns {jQuery} Setting validation message element. + * @this {wp.customize.Control} + */ + getNotificationsContainerElement: function() { + var control = this, controlTitle, notificationsContainer; + + notificationsContainer = control.container.find( '.customize-control-notifications-container:first' ); + if ( notificationsContainer.length ) { + return notificationsContainer; + } + + notificationsContainer = $( '
    ' ); + + if ( control.container.hasClass( 'customize-control-nav_menu_item' ) ) { + control.container.find( '.menu-item-settings:first' ).prepend( notificationsContainer ); + } else if ( control.container.hasClass( 'customize-control-widget_form' ) ) { + control.container.find( '.widget-inside:first' ).prepend( notificationsContainer ); + } else { + controlTitle = control.container.find( '.customize-control-title' ); + if ( controlTitle.length ) { + controlTitle.after( notificationsContainer ); + } else { + control.container.prepend( notificationsContainer ); + } + } + return notificationsContainer; + }, + + /** + * Render notifications. + * + * Renders the `control.notifications` into the control's container. + * Control subclasses may override this method to do their own handling + * of rendering notifications. + * + * @since 4.6.0 + * @this {wp.customize.Control} + */ + renderNotifications: function() { + var control = this, container, notifications, hasError = false; + container = control.getNotificationsContainerElement(); + if ( ! container || ! container.length ) { + return; + } + notifications = []; + control.notifications.each( function( notification ) { + notifications.push( notification ); + if ( 'error' === notification.type ) { + hasError = true; + } + } ); + + if ( 0 === notifications.length ) { + container.stop().slideUp( 'fast' ); + } else { + container.stop().slideDown( 'fast', null, function() { + $( this ).css( 'height', 'auto' ); + } ); + } + + if ( ! control.notificationsTemplate ) { + control.notificationsTemplate = wp.template( 'customize-control-notifications' ); + } + + control.container.toggleClass( 'has-notifications', 0 !== notifications.length ); + control.container.toggleClass( 'has-error', hasError ); + container.empty().append( $.trim( + control.notificationsTemplate( { notifications: notifications, altNotice: Boolean( control.altNotice ) } ) + ) ); + }, + /** * Normal controls do not expand, so just expand its parent * @@ -1315,7 +1750,14 @@ * @param {Callback} args.completeCallback */ onChangeActive: function ( active, args ) { - if ( ! $.contains( document, this.container ) ) { + if ( args.unchanged ) { + if ( args.completeCallback ) { + args.completeCallback(); + } + return; + } + + if ( ! $.contains( document, this.container[0] ) ) { // jQuery.fn.slideUp is not hiding an element if it is not in the DOM this.container.toggle( active ); if ( args.completeCallback ) { @@ -1437,7 +1879,7 @@ control.setting.set( picker.wpColorPicker('color') ); }, clear: function() { - control.setting.set( false ); + control.setting.set( '' ); } }); @@ -1486,8 +1928,54 @@ control.pausePlayer(); }); - // Re-render whenever the control's setting changes. - control.setting.bind( function () { control.renderContent(); } ); + /** + * Set attachment data and render content. + * + * Note that BackgroundImage.prototype.ready applies this ready method + * to itself. Since BackgroundImage is an UploadControl, the value + * is the attachment URL instead of the attachment ID. In this case + * we skip fetching the attachment data because we have no ID available, + * and it is the responsibility of the UploadControl to set the control's + * attachmentData before calling the renderContent method. + * + * @param {number|string} value Attachment + */ + function setAttachmentDataAndRenderContent( value ) { + var hasAttachmentData = $.Deferred(); + + if ( control.extended( api.UploadControl ) ) { + hasAttachmentData.resolve(); + } else { + value = parseInt( value, 10 ); + if ( _.isNaN( value ) || value <= 0 ) { + delete control.params.attachment; + hasAttachmentData.resolve(); + } else if ( control.params.attachment && control.params.attachment.id === value ) { + hasAttachmentData.resolve(); + } + } + + // Fetch the attachment data. + if ( 'pending' === hasAttachmentData.state() ) { + wp.media.attachment( value ).fetch().done( function() { + control.params.attachment = this.attributes; + hasAttachmentData.resolve(); + + // Send attachment information to the preview for possible use in `postMessage` transport. + wp.customize.previewer.send( control.setting.id + '-attachment-data', this.attributes ); + } ); + } + + hasAttachmentData.done( function() { + control.renderContent(); + } ); + } + + // Ensure attachment data is initially set (for dynamically-instantiated controls). + setAttachmentDataAndRenderContent( control.setting() ); + + // Update the attachment data and re-render the control when the setting changes. + control.setting.bind( setAttachmentDataAndRenderContent ); }, pausePlayer: function () { @@ -1685,41 +2173,365 @@ }); /** + * A control for selecting and cropping an image. + * * @class + * @augments wp.customize.MediaControl * @augments wp.customize.Control * @augments wp.customize.Class */ - api.HeaderControl = api.Control.extend({ - ready: function() { - this.btnRemove = $('#customize-control-header_image .actions .remove'); - this.btnNew = $('#customize-control-header_image .actions .new'); - - _.bindAll(this, 'openMedia', 'removeImage'); + api.CroppedImageControl = api.MediaControl.extend({ - this.btnNew.on( 'click', this.openMedia ); - this.btnRemove.on( 'click', this.removeImage ); + /** + * Open the media modal to the library state. + */ + openFrame: function( event ) { + if ( api.utils.isKeydownButNotEnterEvent( event ) ) { + return; + } - api.HeaderTool.currentHeader = this.getInitialHeaderImage(); + this.initFrame(); + this.frame.setState( 'library' ).open(); + }, - new api.HeaderTool.CurrentView({ - model: api.HeaderTool.currentHeader, - el: '#customize-control-header_image .current .container' - }); + /** + * Create a media modal select frame, and store it so the instance can be reused when needed. + */ + initFrame: function() { + var l10n = _wpMediaViewsL10n; - new api.HeaderTool.ChoiceListView({ - collection: api.HeaderTool.UploadsList = new api.HeaderTool.ChoiceList(), - el: '#customize-control-header_image .choices .uploaded .list' + this.frame = wp.media({ + button: { + text: l10n.select, + close: false + }, + states: [ + new wp.media.controller.Library({ + title: this.params.button_labels.frame_title, + library: wp.media.query({ type: 'image' }), + multiple: false, + date: false, + priority: 20, + suggestedWidth: this.params.width, + suggestedHeight: this.params.height + }), + new wp.media.controller.CustomizeImageCropper({ + imgSelectOptions: this.calculateImageSelectOptions, + control: this + }) + ] }); - new api.HeaderTool.ChoiceListView({ - collection: api.HeaderTool.DefaultsList = new api.HeaderTool.DefaultsList(), - el: '#customize-control-header_image .choices .default .list' - }); + this.frame.on( 'select', this.onSelect, this ); + this.frame.on( 'cropped', this.onCropped, this ); + this.frame.on( 'skippedcrop', this.onSkippedCrop, this ); + }, + + /** + * After an image is selected in the media modal, switch to the cropper + * state if the image isn't the right size. + */ + onSelect: function() { + var attachment = this.frame.state().get( 'selection' ).first().toJSON(); + + if ( this.params.width === attachment.width && this.params.height === attachment.height && ! this.params.flex_width && ! this.params.flex_height ) { + this.setImageFromAttachment( attachment ); + this.frame.close(); + } else { + this.frame.setState( 'cropper' ); + } + }, + + /** + * After the image has been cropped, apply the cropped image data to the setting. + * + * @param {object} croppedImage Cropped attachment data. + */ + onCropped: function( croppedImage ) { + this.setImageFromAttachment( croppedImage ); + }, + + /** + * Returns a set of options, computed from the attached image data and + * control-specific data, to be fed to the imgAreaSelect plugin in + * wp.media.view.Cropper. + * + * @param {wp.media.model.Attachment} attachment + * @param {wp.media.controller.Cropper} controller + * @returns {Object} Options + */ + calculateImageSelectOptions: function( attachment, controller ) { + var control = controller.get( 'control' ), + flexWidth = !! parseInt( control.params.flex_width, 10 ), + flexHeight = !! parseInt( control.params.flex_height, 10 ), + realWidth = attachment.get( 'width' ), + realHeight = attachment.get( 'height' ), + xInit = parseInt( control.params.width, 10 ), + yInit = parseInt( control.params.height, 10 ), + ratio = xInit / yInit, + xImg = xInit, + yImg = yInit, + x1, y1, imgSelectOptions; + + controller.set( 'canSkipCrop', ! control.mustBeCropped( flexWidth, flexHeight, xInit, yInit, realWidth, realHeight ) ); + + if ( realWidth / realHeight > ratio ) { + yInit = realHeight; + xInit = yInit * ratio; + } else { + xInit = realWidth; + yInit = xInit / ratio; + } + + x1 = ( realWidth - xInit ) / 2; + y1 = ( realHeight - yInit ) / 2; + + imgSelectOptions = { + handles: true, + keys: true, + instance: true, + persistent: true, + imageWidth: realWidth, + imageHeight: realHeight, + minWidth: xImg > xInit ? xInit : xImg, + minHeight: yImg > yInit ? yInit : yImg, + x1: x1, + y1: y1, + x2: xInit + x1, + y2: yInit + y1 + }; + + if ( flexHeight === false && flexWidth === false ) { + imgSelectOptions.aspectRatio = xInit + ':' + yInit; + } + + if ( true === flexHeight ) { + delete imgSelectOptions.minHeight; + imgSelectOptions.maxWidth = realWidth; + } + + if ( true === flexWidth ) { + delete imgSelectOptions.minWidth; + imgSelectOptions.maxHeight = realHeight; + } + + return imgSelectOptions; + }, + + /** + * Return whether the image must be cropped, based on required dimensions. + * + * @param {bool} flexW + * @param {bool} flexH + * @param {int} dstW + * @param {int} dstH + * @param {int} imgW + * @param {int} imgH + * @return {bool} + */ + mustBeCropped: function( flexW, flexH, dstW, dstH, imgW, imgH ) { + if ( true === flexW && true === flexH ) { + return false; + } + + if ( true === flexW && dstH === imgH ) { + return false; + } + + if ( true === flexH && dstW === imgW ) { + return false; + } + + if ( dstW === imgW && dstH === imgH ) { + return false; + } + + if ( imgW <= dstW ) { + return false; + } + + return true; + }, + + /** + * If cropping was skipped, apply the image data directly to the setting. + */ + onSkippedCrop: function() { + var attachment = this.frame.state().get( 'selection' ).first().toJSON(); + this.setImageFromAttachment( attachment ); + }, + + /** + * Updates the setting and re-renders the control UI. + * + * @param {object} attachment + */ + setImageFromAttachment: function( attachment ) { + this.params.attachment = attachment; + + // Set the Customizer setting; the callback takes care of rendering. + this.setting( attachment.id ); + } + }); + + /** + * A control for selecting and cropping Site Icons. + * + * @class + * @augments wp.customize.CroppedImageControl + * @augments wp.customize.MediaControl + * @augments wp.customize.Control + * @augments wp.customize.Class + */ + api.SiteIconControl = api.CroppedImageControl.extend({ + + /** + * Create a media modal select frame, and store it so the instance can be reused when needed. + */ + initFrame: function() { + var l10n = _wpMediaViewsL10n; + + this.frame = wp.media({ + button: { + text: l10n.select, + close: false + }, + states: [ + new wp.media.controller.Library({ + title: this.params.button_labels.frame_title, + library: wp.media.query({ type: 'image' }), + multiple: false, + date: false, + priority: 20, + suggestedWidth: this.params.width, + suggestedHeight: this.params.height + }), + new wp.media.controller.SiteIconCropper({ + imgSelectOptions: this.calculateImageSelectOptions, + control: this + }) + ] + }); + + this.frame.on( 'select', this.onSelect, this ); + this.frame.on( 'cropped', this.onCropped, this ); + this.frame.on( 'skippedcrop', this.onSkippedCrop, this ); + }, + + /** + * After an image is selected in the media modal, switch to the cropper + * state if the image isn't the right size. + */ + onSelect: function() { + var attachment = this.frame.state().get( 'selection' ).first().toJSON(), + controller = this; + + if ( this.params.width === attachment.width && this.params.height === attachment.height && ! this.params.flex_width && ! this.params.flex_height ) { + wp.ajax.post( 'crop-image', { + nonce: attachment.nonces.edit, + id: attachment.id, + context: 'site-icon', + cropDetails: { + x1: 0, + y1: 0, + width: this.params.width, + height: this.params.height, + dst_width: this.params.width, + dst_height: this.params.height + } + } ).done( function( croppedImage ) { + controller.setImageFromAttachment( croppedImage ); + controller.frame.close(); + } ).fail( function() { + controller.frame.trigger('content:error:crop'); + } ); + } else { + this.frame.setState( 'cropper' ); + } + }, + + /** + * Updates the setting and re-renders the control UI. + * + * @param {object} attachment + */ + setImageFromAttachment: function( attachment ) { + var sizes = [ 'site_icon-32', 'thumbnail', 'full' ], + icon; + + _.each( sizes, function( size ) { + if ( ! icon && ! _.isUndefined ( attachment.sizes[ size ] ) ) { + icon = attachment.sizes[ size ]; + } + } ); + + this.params.attachment = attachment; + + // Set the Customizer setting; the callback takes care of rendering. + this.setting( attachment.id ); + + // Update the icon in-browser. + $( 'link[sizes="32x32"]' ).attr( 'href', icon.url ); + }, + + /** + * Called when the "Remove" link is clicked. Empties the setting. + * + * @param {object} event jQuery Event object + */ + removeFile: function( event ) { + if ( api.utils.isKeydownButNotEnterEvent( event ) ) { + return; + } + event.preventDefault(); + + this.params.attachment = {}; + this.setting( '' ); + this.renderContent(); // Not bound to setting change when emptying. + $( 'link[rel="icon"]' ).attr( 'href', '' ); + } + }); + + /** + * @class + * @augments wp.customize.Control + * @augments wp.customize.Class + */ + api.HeaderControl = api.Control.extend({ + ready: function() { + this.btnRemove = $('#customize-control-header_image .actions .remove'); + this.btnNew = $('#customize-control-header_image .actions .new'); + + _.bindAll(this, 'openMedia', 'removeImage'); + + this.btnNew.on( 'click', this.openMedia ); + this.btnRemove.on( 'click', this.removeImage ); + + api.HeaderTool.currentHeader = this.getInitialHeaderImage(); + + new api.HeaderTool.CurrentView({ + model: api.HeaderTool.currentHeader, + el: '#customize-control-header_image .current .container' + }); + + new api.HeaderTool.ChoiceListView({ + collection: api.HeaderTool.UploadsList = new api.HeaderTool.ChoiceList(), + el: '#customize-control-header_image .choices .uploaded .list' + }); + + new api.HeaderTool.ChoiceListView({ + collection: api.HeaderTool.DefaultsList = new api.HeaderTool.DefaultsList(), + el: '#customize-control-header_image .choices .default .list' + }); api.HeaderTool.combinedList = api.HeaderTool.CombinedList = new api.HeaderTool.CombinedList([ api.HeaderTool.UploadsList, api.HeaderTool.DefaultsList ]); + + // Ensure custom-header-crop Ajax requests bootstrap the Customizer to activate the previewed theme. + wp.media.controller.Cropper.prototype.defaults.doCropArgs.wp_customize = 'on'; + wp.media.controller.Cropper.prototype.defaults.doCropArgs.theme = api.settings.theme.stylesheet; }, /** @@ -1879,7 +2691,7 @@ * @param {object} croppedImage Cropped attachment data. */ onCropped: function(croppedImage) { - var url = croppedImage.post_content, + var url = croppedImage.url, attachmentId = croppedImage.attachment_id, w = croppedImage.width, h = croppedImage.height; @@ -2066,6 +2878,9 @@ api.panel = new api.Values({ defaultConstructor: api.Panel }); /** + * An object that fetches a preview in the background of the document, which + * allows for seamless replacement of an existing preview. + * * @class * @augments wp.customize.Messenger * @augments wp.customize.Class @@ -2074,10 +2889,22 @@ api.PreviewFrame = api.Messenger.extend({ sensitivity: 2000, + /** + * Initialize the PreviewFrame. + * + * @param {object} params.container + * @param {object} params.signature + * @param {object} params.previewUrl + * @param {object} params.query + * @param {object} options + */ initialize: function( params, options ) { var deferred = $.Deferred(); - // This is the promise object. + /* + * Make the instance of the PreviewFrame the promise object + * so other objects can easily interact with it. + */ deferred.promise( this ); this.container = params.container; @@ -2094,6 +2921,12 @@ this.run( deferred ); }, + /** + * Run the preview request. + * + * @param {object} deferred jQuery Deferred object to be resolved with + * the request. + */ run: function( deferred ) { var self = this, loaded = false, @@ -2134,9 +2967,20 @@ _( constructs ).each( function ( activeConstructs, type ) { api[ type ].each( function ( construct, id ) { var active = !! ( activeConstructs && activeConstructs[ id ] ); - construct.active( active ); + if ( active ) { + construct.activate(); + } else { + construct.deactivate(); + } } ); } ); + + if ( data.settingValidities ) { + api._handleSettingValidities( { + settingValidities: data.settingValidities, + focusInvalidControl: false + } ); + } } ); this.request = $.ajax( this.previewUrl(), { @@ -2234,7 +3078,7 @@ iframe = $( '