// Controls searching on the current widget collection // and triggers an update event. doSearch: function( value ) {
// Don't do anything if we've already done this search. // Useful because the search handler fires multiple times per keystroke. if ( this.terms === value ) { return; }
// Updates terms with the value passed. this.terms = value;
// If we have terms, run a search... if ( this.terms.length > 0 ) { this.search( this.terms ); }
// If search is blank, set all the widgets as they matched the search to reset the views. if ( this.terms === '' ) { this.each( function ( widget ) { widget.set( 'search_matched', true ); } ); } },
// Performs a search within the collection. // @uses RegExp search: function( term ) { var match, haystack;
// Escape the term string for RegExp meta characters. term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
// Consider spaces as word delimiters and match the whole string // so matching terms can be combined. term = term.replace( / /g, ')(?=.*' ); match = new RegExp( '^(?=.*' + term + ').+', 'i' );
// Cache sidebar control which has opened panel. currentSidebarControl: null, $search: null, $clearResults: null, searchMatchesCount: null,
/** * View class for the available widgets panel. * * @constructs wp.customize.Widgets.AvailableWidgetsPanelView * @augments wp.Backbone.View */ initialize: function() { var self = this;
// Set the initial search count to the number of available widgets. this.searchMatchesCount = this.collection.length;
/* * If the available widgets panel is open and the customize controls * are interacted with (i.e. available widgets panel is blurred) then * close the available widgets panel. Also close on back button click. */ $( '#customize-controls, #available-widgets .customize-section-title' ).on( 'click keydown', function( e ) { var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' ); if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) { self.close(); } } );
// Clear the search results and trigger an `input` event to fire a new search. this.$clearResults.on( 'click', function() { self.$search.val( '' ).trigger( 'focus' ).trigger( 'input' ); } );
// Close the panel if the URL in the preview changes. api.previewer.bind( 'url', this.close ); },
/** * Performs a search and handles selected widget. */ search: _.debounce( function( event ) { var firstVisible;
this.collection.doSearch( event.target.value ); // Update the search matches count. this.updateSearchMatchesCount(); // Announce how many search results. this.announceSearchMatches();
// Remove a widget from being selected if it is no longer visible. if ( this.selected && ! this.selected.is( ':visible' ) ) { this.selected.removeClass( 'selected' ); this.selected = null; }
// If a widget was selected but the filter value has been cleared out, clear selection. if ( this.selected && ! event.target.value ) { this.selected.removeClass( 'selected' ); this.selected = null; }
// If a filter has been entered and a widget hasn't been selected, select the first one shown. if ( ! this.selected && event.target.value ) { firstVisible = this.$el.find( '> .widget-tpl:visible:first' ); if ( firstVisible.length ) { this.select( firstVisible ); } }
// Toggle the clear search results button. if ( '' !== event.target.value ) { this.$clearResults.addClass( 'is-visible' ); } else if ( '' === event.target.value ) { this.$clearResults.removeClass( 'is-visible' ); }
// Set a CSS class on the search container when there are no search results. if ( ! this.searchMatchesCount ) { this.$el.addClass( 'no-widgets-found' ); } else { this.$el.removeClass( 'no-widgets-found' ); } }, 500 ),
/** * Updates the count of the available widgets that have the `search_matched` attribute. */ updateSearchMatchesCount: function() { this.searchMatchesCount = this.collection.where({ search_matched: true }).length; },
/** * Sends a message to the aria-live region to announce how many search results. */ announceSearchMatches: function() { var message = l10n.widgetsFound.replace( '%d', this.searchMatchesCount ) ;
if ( ! this.searchMatchesCount ) { message = l10n.noWidgetsFound; }
/** * Highlights a widget on focus. */ focus: function( event ) { this.select( $( event.currentTarget ) ); },
/** * Handles submit for keypress and click on widget. */ _submit: function( event ) { // Only proceed with keypress if it is Enter or Spacebar. if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) { return; }
this.submit( $( event.currentTarget ) ); },
/** * Adds a selected widget to the sidebar. */ submit: function( widgetTpl ) { var widgetId, widget, widgetFormControl;
// Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens. _( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) { if ( control.params.is_wide ) { control.collapseForm(); } } );
/** * Handlers for the widget-synced event, organized by widget ID base. * Other widgets may provide their own update handlers by adding * listeners for the widget-synced event. * * @alias wp.customize.Widgets.formSyncHandlers */ api.Widgets.formSyncHandlers = {
/** * wp.customize.Widgets.WidgetControl * * Customizer control for widgets. * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type * * @since 4.1.0 * * @constructs wp.customize.Widgets.WidgetControl * @augments wp.customize.Control */ initialize: function( id, options ) { var control = this;
/** * Set up the control. * * @since 3.9.0 */ ready: function() { var control = this;
/* * Embed a placeholder once the section is expanded. The full widget * form content will be embedded once the control itself is expanded, * and at this point the widget-added event will be triggered. */ if ( ! control.section() ) { control.embedWidgetControl(); } else { api.section( control.section(), function( section ) { var onExpanded = function( isExpanded ) { if ( isExpanded ) { control.embedWidgetControl(); section.expanded.unbind( onExpanded ); } }; if ( section.expanded() ) { onExpanded( true ); } else { section.expanded.bind( onExpanded ); } } ); } },
/** * Embed the .widget element inside the li container. * * @since 4.4.0 */ embedWidgetControl: function() { var control = this, widgetControl;
if ( control.widgetControlEmbedded ) { return; } control.widgetControlEmbedded = true;
/** * Embed the actual widget form inside of .widget-content and finally trigger the widget-added event. * * @since 4.4.0 */ embedWidgetContent: function() { var control = this, widgetContent;
// Update the notification container element now that the widget content has been embedded. control.notifications.container = control.getNotificationsContainerElement(); control.notifications.render();
// Update widget whenever model changes. this.setting.bind( function( to, from ) { if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) { self.updateWidget( { instance: to } ); } } ); },
/** * Add special behaviors for wide widget controls */ _setupWideWidget: function() { var self = this, $widgetInside, $widgetForm, $customizeSidebar, $themeControlsContainer, positionWidget;
if ( ! this.params.is_wide || $( window ).width() <= 640 /* max-width breakpoint in customize-controls.css */ ) { return; }
/** * Keep the widget-inside positioned so the top of fixed-positioned * element is at the same top position as the widget-top. When the * widget-top is scrolled out of view, keep the widget-top in view; * likewise, don't allow the widget to drop off the bottom of the window. * If a widget is too tall to fit in the window, don't let the height * exceed the window height so that the contents of the widget control * will become scrollable (overflow:auto). */ positionWidget = function() { var offsetTop = self.container.offset().top, windowHeight = $( window ).height(), formHeight = $widgetForm.outerHeight(), top; $widgetInside.css( 'max-height', windowHeight ); top = Math.max( 0, // Prevent top from going off screen. Math.min( Math.max( offsetTop, 0 ), // Distance widget in panel is from top of screen. windowHeight - formHeight // Flush up against bottom of screen. ) ); $widgetInside.css( 'top', top ); };
// Reposition whenever a sidebar's widgets are changed. api.each( function( setting ) { if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) { setting.bind( function() { if ( self.container.hasClass( 'expanded' ) ) { positionWidget(); } } ); } } ); },
/** * Show/hide the control when clicking on the form title, when clicking * the close button */ _setupControlToggle: function() { var self = this, $closeBtn;
this.container.find( '.widget-top' ).on( 'click', function( e ) { e.preventDefault(); var sidebarWidgetsControl = self.getSidebarWidgetsControl(); if ( sidebarWidgetsControl.isReordering ) { return; } self.expanded( ! self.expanded() ); } );
/** * Update the title of the form if a title field is entered */ _setupWidgetTitle: function() { var self = this, updateTitle;
updateTitle = function() { var title = self.setting().title, inWidgetTitle = self.container.find( '.in-widget-title' );
if ( title ) { inWidgetTitle.text( ': ' + title ); } else { inWidgetTitle.text( '' ); } }; this.setting.bind( updateTitle ); updateTitle(); },
/** * Set up the widget-reorder-nav */ _setupReorderUI: function() { var self = this, selectSidebarItem, $moveWidgetArea, $reorderNav, updateAvailableSidebars, template;
/** * select the provided sidebar list item in the move widget area * * @param {jQuery} li */ selectSidebarItem = function( li ) { li.siblings( '.selected' ).removeClass( 'selected' ); li.addClass( 'selected' ); var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id ); self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar ); };
/** * Add the widget reordering elements to the widget control */ this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) );
/** * Update available sidebars when their rendered state changes */ updateAvailableSidebars = function() { var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem, renderedSidebarCount = 0;
// Trigger widget form update when hitting Enter within an input. $widgetContent.on( 'keydown', 'input', function( e ) { if ( 13 === e.which ) { // Enter. e.preventDefault(); self.updateWidget( { ignoreActiveElement: true } ); } } );
// Handle widgets that support live previews. $widgetContent.on( 'change input propertychange', ':input', function( e ) { if ( ! self.liveUpdateMode ) { return; } if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) { updateWidgetDebounced(); } } );
// Remove loading indicators when the setting is saved and the preview updates. this.setting.previewer.channel.bind( 'synced', function() { self.container.removeClass( 'previewer-loading' ); } );
/** * Update widget control to indicate whether it is currently rendered. * * Overrides api.Control.toggle() * * @since 4.1.0 * * @param {boolean} active * @param {Object} args * @param {function} args.completeCallback */ onChangeActive: function ( active, args ) { // Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments. this.container.toggleClass( 'widget-rendered', active ); if ( args.completeCallback ) { args.completeCallback(); } },
/** * Set up event handlers for widget removal */ _setupRemoveUI: function() { var self = this, $removeBtn, replaceDeleteWithRemove;
// Configure remove button. $removeBtn = this.container.find( '.widget-control-remove' ); $removeBtn.on( 'click', function() { // Find an adjacent element to add focus to when this widget goes away. var $adjacentFocusTarget; if ( self.container.next().is( '.customize-control-widget_form' ) ) { $adjacentFocusTarget = self.container.next().find( '.widget-action:first' ); } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) { $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' ); } else { $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' ); }
/** * Find all inputs in a widget container that should be considered when * comparing the loaded form with the sanitized form, whose fields will * be aligned to copy the sanitized over. The elements returned by this * are passed into this._getInputsSignature(), and they are iterated * over when copying sanitized values over to the form loaded. * * @param {jQuery} container element in which to look for inputs * @return {jQuery} inputs * @private */ _getInputs: function( container ) { return $( container ).find( ':input[name]' ); },
/** * Iterate over supplied inputs and create a signature string for all of them together. * This string can be used to compare whether or not the form has all of the same fields. * * @param {jQuery} inputs * @return {string} * @private */ _getInputsSignature: function( inputs ) { var inputsSignatures = _( inputs ).map( function( input ) { var $input = $( input ), signatureParts;
/** * Get the state for an input depending on its type. * * @param {jQuery|Element} input * @return {string|boolean|Array|*} * @private */ _getInputState: function( input ) { input = $( input ); if ( input.is( ':radio, :checkbox' ) ) { return input.prop( 'checked' ); } else if ( input.is( 'select[multiple]' ) ) { return input.find( 'option:selected' ).map( function () { return $( this ).val(); } ).get(); } else { return input.val(); } },
/** * Update an input's state based on its type. * * @param {jQuery|Element} input * @param {string|boolean|Array|*} state * @private */ _setInputState: function ( input, state ) { input = $( input ); if ( input.is( ':radio, :checkbox' ) ) { input.prop( 'checked', state ); } else if ( input.is( 'select[multiple]' ) ) { if ( ! Array.isArray( state ) ) { state = []; } else { // Make sure all state items are strings since the DOM value is a string. state = _.map( state, function ( value ) { return String( value ); } ); } input.find( 'option' ).each( function () { $( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) ); } ); } else { input.val( state ); } },
/*********************************************************************** * Begin public API methods **********************************************************************/
/** * Submit the widget form via Ajax and get back the updated instance, * along with the new widget control form to render. * * @param {Object} [args] * @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used * @param {Function|null} [args.complete=null] Function which is called when the request finishes. Context is bound to the control. First argument is any error. Following arguments are for success. * @param {boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element. */ updateWidget: function( args ) { var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent, updateNumber, params, data, $inputs, processing, jqxhr, isChanged;
// The updateWidget logic requires that the form fields to be fully present. self.embedWidgetContent();
data = $.param( params ); $inputs = this._getInputs( $widgetContent );
/* * Store the value we're submitting in data so that when the response comes back, * we know if it got sanitized; if there is no difference in the sanitized value, * then we do not need to touch the UI and mess up the user's ongoing editing. */ $inputs.each( function() { $( this ).data( 'state' + updateNumber, self._getInputState( this ) ); } );
if ( instanceOverride ) { data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } ); } else { data += '&' + $inputs.serialize(); } data += '&' + $widgetContent.find( '~ :input' ).serialize();
if ( this._previousUpdateRequest ) { this._previousUpdateRequest.abort(); } jqxhr = $.post( wp.ajax.settings.url, data ); this._previousUpdateRequest = jqxhr;
jqxhr.done( function( r ) { var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse, isLiveUpdateAborted = false;
// Check if the user is logged out. if ( '0' === r ) { api.previewer.preview.iframe.hide(); api.previewer.login().done( function() { self.updateWidget( args ); api.previewer.preview.iframe.show(); } ); return; }
// Check for cheaters. if ( '-1' === r ) { api.previewer.cheatin(); return; }
// Restore live update mode if sanitized fields are now aligned with the existing fields. if ( hasSameInputsInResponse && ! self.liveUpdateMode ) { self.liveUpdateMode = true; self.container.removeClass( 'widget-form-disabled' ); self.container.find( 'input[name="savewidget"]' ).hide(); }
// Sync sanitized field states to existing fields if they are aligned. if ( hasSameInputsInResponse && self.liveUpdateMode ) { $inputs.each( function( i ) { var $input = $( this ), $sanitizedInput = $( $sanitizedInputs[i] ), submittedState, sanitizedState, canUpdateState;
// Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled. } else if ( self.liveUpdateMode ) { self.liveUpdateMode = false; self.container.find( 'input[name="savewidget"]' ).show(); isLiveUpdateAborted = true;
// Otherwise, replace existing form with the sanitized form. } else { $widgetContent.html( r.data.form );
/** * If the old instance is identical to the new one, there is nothing new * needing to be rendered, and so we can preempt the event for the * preview finishing loading. */ isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance ); if ( isChanged ) { self.isWidgetUpdating = true; // Suppress triggering another updateWidget. self.setting( r.data.instance ); self.isWidgetUpdating = false; } else { // No change was made, so stop the spinner now instead of when the preview would updates. self.container.removeClass( 'previewer-loading' ); }
/** * Collapse the widget form control * * @deprecated 4.1.0 Use this.collapse() instead. */ collapseForm: function() { this.collapse(); },
/** * Expand or collapse the widget control * * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide ) * * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility */ toggleForm: function( showOrHide ) { if ( typeof showOrHide === 'undefined' ) { showOrHide = ! this.expanded(); } this.expanded( showOrHide ); },
/** * Respond to change in the expanded state. * * @param {boolean} expanded * @param {Object} args merged on top of this.defaultActiveArguments */ onChangeExpanded: function ( expanded, args ) { var self = this, $widget, $inside, complete, prevComplete, expandControl, $toggleBtn;
self.embedWidgetControl(); // Make sure the outer form is embedded so that the expanded state can be set in the UI. if ( expanded ) { self.embedWidgetContent(); }
// If the expanded state is unchanged only manipulate container expanded states. if ( args.unchanged ) { if ( expanded ) { api.Control.prototype.expand.call( self, { completeCallback: args.completeCallback }); } return; }
// Close all other widget controls before expanding this one. api.control.each( function( otherControl ) { if ( self.params.type === otherControl.params.type && self !== otherControl ) { otherControl.collapse(); } } );
/** * Get the position (index) of the widget in the containing sidebar * * @return {number} */ getWidgetSidebarPosition: function() { var sidebarWidgetIds, position;
sidebarWidgetIds = this.getSidebarWidgetsControl().setting(); position = _.indexOf( sidebarWidgetIds, this.params.widget_id );
if ( position === -1 ) { return; }
return position; },
/** * Move widget up one in the sidebar */ moveUp: function() { this._moveWidgetByOne( -1 ); },
/** * Move widget up one in the sidebar */ moveDown: function() { this._moveWidgetByOne( 1 ); },
/** * @private * * @param {number} offset 1|-1 */ _moveWidgetByOne: function( offset ) { var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId;
// @todo This should use the Notifications API introduced to panels. See <https://core.trac.wordpress.org/ticket/38794>. noticeContainer = $( '<div></div>', { 'class': 'no-widget-areas-rendered-notice', 'role': 'alert' }); panelMetaContainer.append( noticeContainer );
/** * Get the number of active sections in the panel. * * @return {number} Number of active sidebar sections. */ getActiveSectionCount = function() { return _.filter( panel.sections(), function( section ) { return 'sidebar' === section.params.type && section.active(); } ).length; };
/** * Determine whether or not the notice should be displayed. * * @return {boolean} */ shouldShowNotice = function() { var activeSectionCount = getActiveSectionCount(); if ( 0 === activeSectionCount ) { return true; } else { return activeSectionCount !== api.Widgets.data.registeredSidebars.length; } };
/* * Set the initial visibility state for rendered notice. * Update the visibility of the notice whenever a reflow happens. */ noticeContainer.toggle( shouldShowNotice() ); api.previewer.deferred.active.done( function () { noticeContainer.toggle( shouldShowNotice() ); }); api.bind( 'pane-contents-reflowed', function() { var duration = ( 'resolved' === api.previewer.deferred.active.state() ) ? 'fast' : 0; updateNotice(); if ( shouldShowNotice() ) { noticeContainer.slideDown( duration ); } else { noticeContainer.slideUp( duration ); } }); }); },
/** * Allow an active widgets panel to be contextually active even when it has no active sections (widget areas). * * This ensures that the widgets panel appears even when there are no * sidebars displayed on the URL currently being previewed. * * @since 4.4.0 * * @return {boolean} */ isContextuallyActive: function() { var panel = this; return panel.active(); } });
/** * Sync the section's active state back to the Backbone model's is_rendered attribute * * @since 4.1.0 */ ready: function () { var section = this, registeredSidebar; api.Section.prototype.ready.call( this ); registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId ); section.active.bind( function ( active ) { registeredSidebar.set( 'is_rendered', active ); }); registeredSidebar.set( 'is_rendered', section.active() ); } });
/** * wp.customize.Widgets.SidebarControl * * Customizer control for widgets. * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type * * @since 3.9.0 * * @class wp.customize.Widgets.SidebarControl * @augments wp.customize.Control */ api.Widgets.SidebarControl = api.Control.extend(/** @lends wp.customize.Widgets.SidebarControl.prototype */{
/** * Set up the control */ ready: function() { this.$controlSection = this.container.closest( '.control-section' ); this.$sectionContent = this.container.closest( '.accordion-section-content' );
// Filter out any persistent widget IDs for widgets which have been deactivated. newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) { var parsedWidgetId = parseWidgetId( newWidgetId );
// Sort widget controls to their new positions. widgetFormControls.sort( function( a, b ) { var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ), bIndex = _.indexOf( newWidgetIds, b.params.widget_id ); return aIndex - bIndex; });
priority = 0; _( widgetFormControls ).each( function ( control ) { control.priority( priority ); control.section( self.section() ); priority += 1; }); self.priority( priority ); // Make sure sidebar control remains at end.
// Re-sort widget form controls (including widgets form other sidebars newly moved here). self._applyCardinalOrderClassNames();
// If the widget was dragged into the sidebar, make sure the sidebar_id param is updated. _( widgetFormControls ).each( function( widgetFormControl ) { widgetFormControl.params.sidebar_id = self.params.sidebar_id; } );
// Using setTimeout so that when moving a widget to another sidebar, // the other sidebars_widgets settings get a chance to update. setTimeout( function() { var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase, widget, isPresentInAnotherSidebar = false;
// Check if the widget is in another sidebar. api.each( function( otherSetting ) { if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) { return; }
var otherSidebarWidgets = otherSetting(), i;
i = _.indexOf( otherSidebarWidgets, removedWidgetId ); if ( -1 !== i ) { isPresentInAnotherSidebar = true; } } );
// If the widget is present in another sidebar, abort! if ( isPresentInAnotherSidebar ) { return; }
// Detect if widget control was dragged to another sidebar. wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
// Delete any widget form controls for removed widgets. if ( removedControl && ! wasDraggedToAnotherSidebar ) { api.control.remove( removedControl.id ); removedControl.container.remove(); }
// Move widget to inactive widgets sidebar (move it to Trash) if has been previously saved. // This prevents the inactive widgets sidebar from overflowing with throwaway widgets. if ( api.Widgets.savedWidgetIds[removedWidgetId] ) { inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice(); inactiveWidgets.push( removedWidgetId ); api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() ); }
// Make old single widget available for adding again. removedIdBase = parseWidgetId( removedWidgetId ).id_base; widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } ); if ( widget && ! widget.get( 'is_multi' ) ) { widget.set( 'is_disabled', false ); } } );
} ); } ); },
/** * Allow widgets in sidebar to be re-ordered, and for the order to be previewed */ _setupSortable: function() { var self = this;
this.isReordering = false;
/** * Update widget order setting when controls are re-ordered */ this.$sectionContent.sortable( { items: '> .customize-control-widget_form', handle: '.widget-top', axis: 'y', tolerance: 'pointer', connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)', update: function() { var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
/** * Expand other Customizer sidebar section when dragging a control widget over it, * allowing the control to be dropped into another section */ this.$controlSection.find( '.accordion-section-title' ).droppable({ accept: '.customize-control-widget_form', over: function() { var section = api.section( self.section.get() ); section.expand({ allowMultiple: true, // Prevent the section being dragged from to be collapsed. completeCallback: function () { // @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed. api.section.each( function ( otherSection ) { if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) { otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' ); } } ); } }); } });
/*********************************************************************** * Begin public API methods **********************************************************************/
/** * Enable/disable the reordering UI * * @param {boolean} showOrHide to enable/disable reordering * * @todo We should have a reordering state instead and rename this to onChangeReordering */ toggleReordering: function( showOrHide ) { var addNewWidgetBtn = this.$sectionContent.find( '.add-new-widget' ), reorderBtn = this.container.find( '.reorder-toggle' ), widgetsTitle = this.$sectionContent.find( '.widget-title' );
addNewWidgetBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' }); reorderBtn.attr( 'aria-label', l10n.reorderLabelOff ); wp.a11y.speak( l10n.reorderModeOn ); // Hide widget titles while reordering: title is already in the reorder controls. widgetsTitle.attr( 'aria-hidden', 'true' ); } else { addNewWidgetBtn.removeAttr( 'tabindex aria-hidden' ); reorderBtn.attr( 'aria-label', l10n.reorderLabelOn ); wp.a11y.speak( l10n.reorderModeOff ); widgetsTitle.attr( 'aria-hidden', 'false' ); } },
/** * Get the widget_form Customize controls associated with the current sidebar. * * @since 3.9.0 * @return {wp.customize.controlConstructor.widget_form[]} */ getWidgetFormControls: function() { var formControls = [];
// Register models for custom panel, section, and control types. $.extend( api.panelConstructor, { widgets: api.Widgets.WidgetsPanel }); $.extend( api.sectionConstructor, { sidebar: api.Widgets.SidebarSection }); $.extend( api.controlConstructor, { widget_form: api.Widgets.WidgetControl, sidebar_widgets: api.Widgets.SidebarControl });
/** * Init Customizer for widgets. */ api.bind( 'ready', function() { // Set up the widgets panel. api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({ collection: api.Widgets.availableWidgets });
// Open and focus widget control. api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl ); } );
/** * Highlight a widget control. * * @param {string} widgetId */ api.Widgets.highlightWidgetFormControl = function( widgetId ) { var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
if ( control ) { control.highlightSectionAndControl(); } },
/** * Focus a widget control. * * @param {string} widgetId */ api.Widgets.focusWidgetFormControl = function( widgetId ) { var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
if ( control ) { control.focus(); } },
/** * Given a widget control, find the sidebar widgets control that contains it. * @param {string} widgetId * @return {Object|null} */ api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) { var foundControl = null;
// @todo This can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl(). api.control.each( function( control ) { if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) { foundControl = control; } } );
return foundControl; };
/** * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it. * * @param {string} widgetId * @return {Object|null} */ api.Widgets.getWidgetFormControlForWidget = function( widgetId ) { var foundControl = null;
// @todo We can just use widgetIdToSettingId() here. api.control.each( function( control ) { if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) { foundControl = control; } } );
/** * Focus (expand) one construct and then focus on another construct after the first is collapsed. * * This overrides the back button to serve the purpose of breadcrumb navigation. * * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} focusConstruct - The object to initially focus. * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} returnConstruct - The object to return focus. */ function focusConstructWithBreadcrumb( focusConstruct, returnConstruct ) { focusConstruct.focus(); function onceCollapsed( isExpanded ) { if ( ! isExpanded ) { focusConstruct.expanded.unbind( onceCollapsed ); returnConstruct.focus(); } } focusConstruct.expanded.bind( onceCollapsed ); }