Widget Customizer: Cleanup wp.customize.Widgets.SidebarControl.

see #27690.
Built from https://develop.svn.wordpress.org/trunk@27995


git-svn-id: http://core.svn.wordpress.org/trunk@27825 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Dominik Schilling 2014-04-07 20:00:16 +00:00
parent 2d710c6fad
commit f69f3d3d18
2 changed files with 267 additions and 246 deletions

View File

@ -529,7 +529,7 @@
this.container.find( '.widget-top' ).on( 'click', function( e ) { this.container.find( '.widget-top' ).on( 'click', function( e ) {
e.preventDefault(); e.preventDefault();
var sidebarWidgetsControl = self.getSidebarWidgetsControl(); var sidebarWidgetsControl = self.getSidebarWidgetsControl();
if ( sidebarWidgetsControl.is_reordering ) { if ( sidebarWidgetsControl.isReordering ) {
return; return;
} }
self.toggleForm(); self.toggleForm();
@ -606,14 +606,14 @@
$sidebarItems.each( function() { $sidebarItems.each( function() {
var li = $( this ), var li = $( this ),
sidebarId, sidebarId,
sidebar_model; sidebar;
sidebarId = li.data( 'id' ); sidebarId = li.data( 'id' );
sidebar_model = api.Widgets.registeredSidebars.get( sidebarId ); sidebar = api.Widgets.registeredSidebars.get( sidebarId );
li.toggle( sidebar_model.get( 'is_rendered' ) ); li.toggle( sidebar.get( 'is_rendered' ) );
if ( li.hasClass( 'selected' ) && ! sidebar_model.get( 'is_rendered' ) ) { if ( li.hasClass( 'selected' ) && ! sidebar.get( 'is_rendered' ) ) {
selectSidebarItem( selfSidebarItem ); selectSidebarItem( selfSidebarItem );
} }
} ); } );
@ -725,7 +725,7 @@
$saveBtn.removeClass( 'button-primary' ).addClass( 'button-secondary' ); $saveBtn.removeClass( 'button-primary' ).addClass( 'button-secondary' );
$saveBtn.on( 'click', function( e ) { $saveBtn.on( 'click', function( e ) {
e.preventDefault(); e.preventDefault();
self.updateWidget( { disable_form: true } ); self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
} ); } );
updateWidgetDebounced = _.debounce( function() { updateWidgetDebounced = _.debounce( function() {
@ -736,7 +736,7 @@
this.container.find( '.widget-content' ).on( 'keydown', 'input', function( e ) { this.container.find( '.widget-content' ).on( 'keydown', 'input', function( e ) {
if ( 13 === e.which ) { // Enter if ( 13 === e.which ) { // Enter
e.preventDefault(); e.preventDefault();
self.updateWidget( { ignore_active_element: true } ); self.updateWidget( { ignoreActiveElement: true } );
} }
} ); } );
@ -763,9 +763,10 @@
} ); } );
// Update widget control to indicate whether it is currently rendered // Update widget control to indicate whether it is currently rendered
api.Widgets.Previewer.bind( 'rendered-widgets', function( rendered_widgets ) { api.Widgets.Previewer.bind( 'rendered-widgets', function( renderedWidgets ) {
var is_rendered = !! rendered_widgets[self.params.widget_id]; var isRendered = !! renderedWidgets[self.params.widget_id];
self.container.toggleClass( 'widget-rendered', is_rendered );
self.container.toggleClass( 'widget-rendered', isRendered );
} ); } );
formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ]; formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
@ -800,20 +801,22 @@
} }
self.container.slideUp( function() { self.container.slideUp( function() {
var sidebars_widgets_control = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ), var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
sidebar_widget_ids, sidebarWidgetIds, i;
i;
if ( ! sidebars_widgets_control ) { if ( ! sidebarsWidgetsControl ) {
return; return;
} }
sidebar_widget_ids = sidebars_widgets_control.setting().slice();
i = _.indexOf( sidebar_widget_ids, self.params.widget_id ); sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
if ( -1 === i ) { if ( -1 === i ) {
return; return;
} }
sidebar_widget_ids.splice( i, 1 );
sidebars_widgets_control.setting( sidebar_widget_ids ); sidebarWidgetIds.splice( i, 1 );
sidebarsWidgetsControl.setting( sidebarWidgetIds );
$adjacentFocusTarget.focus(); // keyboard accessibility $adjacentFocusTarget.focus(); // keyboard accessibility
} ); } );
} ); } );
@ -913,7 +916,7 @@
* @param {object} [args] * @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 {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 {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.ignore_active_element=false] Whether or not updating a field will be deferred if focus is still on the element. * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
*/ */
updateWidget: function( args ) { updateWidget: function( args ) {
var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent, var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
@ -922,7 +925,7 @@
args = $.extend( { args = $.extend( {
instance: null, instance: null,
complete: null, complete: null,
ignore_active_element: false ignoreActiveElement: false
}, args ); }, args );
instanceOverride = args.instance; instanceOverride = args.instance;
@ -1016,7 +1019,7 @@
sanitizedState = $sanitizedInput.prop( property ); sanitizedState = $sanitizedInput.prop( property );
$input.data( 'sanitized', sanitizedState ); $input.data( 'sanitized', sanitizedState );
canUpdateState = ( submittedState !== sanitizedState && ( args.ignore_active_element || ! $input.is( document.activeElement ) ) ); canUpdateState = ( submittedState !== sanitizedState && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
if ( canUpdateState ) { if ( canUpdateState ) {
$input.prop( property, sanitizedState ); $input.prop( property, sanitizedState );
} }
@ -1055,7 +1058,7 @@
} }
if ( completeCallback ) { if ( completeCallback ) {
completeCallback.call( self, null, { no_change: ! isChanged, ajax_finished: true } ); completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
} }
} else { } else {
// General error message // General error message
@ -1301,124 +1304,121 @@
* Set up the control * Set up the control
*/ */
ready: function() { ready: function() {
var control = this; this.$controlSection = this.container.closest( '.control-section' );
control.control_section = control.container.closest( '.control-section' ); this.$sectionContent = this.container.closest( '.accordion-section-content' );
control.section_content = control.container.closest( '.accordion-section-content' );
control._setupModel(); this._setupModel();
control._setupSortable(); this._setupSortable();
control._setupAddition(); this._setupAddition();
control._applyCardinalOrderClassNames(); this._applyCardinalOrderClassNames();
}, },
/** /**
* Update ordering of widget control forms when the setting is updated * Update ordering of widget control forms when the setting is updated
*/ */
_setupModel: function() { _setupModel: function() {
var control = this, var self = this,
registered_sidebar = api.Widgets.registeredSidebars.get( control.params.sidebar_id ); registeredSidebar = api.Widgets.registeredSidebars.get( this.params.sidebar_id );
control.setting.bind( function( new_widget_ids, old_widget_ids ) { this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
var widget_form_controls, var widgetFormControls, $sidebarWidgetsAddControl, finalControlContainers, removedWidgetIds;
sidebar_widgets_add_control,
final_control_containers,
removed_widget_ids = _( old_widget_ids ).difference( new_widget_ids );
// Filter out any persistent widget_ids for widgets which have been deactivated removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );
new_widget_ids = _( new_widget_ids ).filter( function( new_widget_id ) {
var parsed_widget_id = parse_widget_id( new_widget_id ); // Filter out any persistent widget IDs for widgets which have been deactivated
return !! api.Widgets.availableWidgets.findWhere( { id_base: parsed_widget_id.id_base } ); newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
var parsedWidgetId = parseWidgetId( newWidgetId );
return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
} ); } );
widget_form_controls = _( new_widget_ids ).map( function( widget_id ) { widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
var widget_form_control = api.Widgets.getWidgetFormControlForWidget( widget_id ); var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
if ( ! widget_form_control ) {
widget_form_control = control.addWidget( widget_id ); if ( ! widgetFormControl ) {
widgetFormControl = self.addWidget( widgetId );
} }
return widget_form_control;
return widgetFormControl;
} ); } );
// Sort widget controls to their new positions // Sort widget controls to their new positions
widget_form_controls.sort( function( a, b ) { widgetFormControls.sort( function( a, b ) {
var a_index = _.indexOf( new_widget_ids, a.params.widget_id ), var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
b_index = _.indexOf( new_widget_ids, b.params.widget_id ); bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
if ( a_index === b_index ) {
if ( aIndex === bIndex ) {
return 0; return 0;
} }
return a_index < b_index ? -1 : 1;
} );
sidebar_widgets_add_control = control.section_content.find( '.customize-control-sidebar_widgets' ); return aIndex < bIndex ? -1 : 1;
} );
// Append the controls to put them in the right order // Append the controls to put them in the right order
final_control_containers = _( widget_form_controls ).map( function( widget_form_controls ) { finalControlContainers = _( widgetFormControls ).map( function( widgetFormControls ) {
return widget_form_controls.container[0]; return widgetFormControls.container[0];
} ); } );
$sidebarWidgetsAddControl = self.$sectionContent.find( '.customize-control-sidebar_widgets' );
$sidebarWidgetsAddControl.before( finalControlContainers );
// Re-sort widget form controls (including widgets form other sidebars newly moved here) // Re-sort widget form controls (including widgets form other sidebars newly moved here)
sidebar_widgets_add_control.before( final_control_containers ); self._applyCardinalOrderClassNames();
control._applyCardinalOrderClassNames();
// If the widget was dragged into the sidebar, make sure the sidebar_id param is updated // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated
_( widget_form_controls ).each( function( widget_form_control ) { _( widgetFormControls ).each( function( widgetFormControl ) {
widget_form_control.params.sidebar_id = control.params.sidebar_id; widgetFormControl.params.sidebar_id = self.params.sidebar_id;
} ); } );
// Cleanup after widget removal // Cleanup after widget removal
_( removed_widget_ids ).each( function( removed_widget_id ) { _( removedWidgetIds ).each( function( removedWidgetId ) {
// Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update
setTimeout( function() { setTimeout( function() {
var is_present_in_another_sidebar = false, var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
removed_control, widget, isPresentInAnotherSidebar = false;
was_dragged_to_another_sidebar,
inactive_widgets,
removed_id_base,
widget;
// Check if the widget is in another sidebar // Check if the widget is in another sidebar
api.each( function( other_setting ) { api.each( function( otherSetting ) {
if ( other_setting.id === control.setting.id || 0 !== other_setting.id.indexOf( 'sidebars_widgets[' ) || other_setting.id === 'sidebars_widgets[wp_inactive_widgets]' ) { if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactiveWidgets]' ) {
return; return;
} }
var other_sidebar_widgets = other_setting(), i;
i = _.indexOf( other_sidebar_widgets, removed_widget_id ); var otherSidebarWidgets = otherSetting(), i;
i = _.indexOf( otherSidebarWidgets, removedWidgetId );
if ( -1 !== i ) { if ( -1 !== i ) {
is_present_in_another_sidebar = true; isPresentInAnotherSidebar = true;
} }
} ); } );
// If the widget is present in another sidebar, abort! // If the widget is present in another sidebar, abort!
if ( is_present_in_another_sidebar ) { if ( isPresentInAnotherSidebar ) {
return; return;
} }
removed_control = api.Widgets.getWidgetFormControlForWidget( removed_widget_id ); removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );
// Detect if widget control was dragged to another sidebar // Detect if widget control was dragged to another sidebar
was_dragged_to_another_sidebar = ( wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
removed_control &&
$.contains( document, removed_control.container[0] ) &&
! $.contains( control.section_content[0], removed_control.container[0] )
);
// Delete any widget form controls for removed widgets // Delete any widget form controls for removed widgets
if ( removed_control && ! was_dragged_to_another_sidebar ) { if ( removedControl && ! wasDraggedToAnotherSidebar ) {
api.control.remove( removed_control.id ); api.control.remove( removedControl.id );
removed_control.container.remove(); removedControl.container.remove();
} }
// Move widget to inactive widgets sidebar (move it to trash) if has been previously saved // 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 // This prevents the inactive widgets sidebar from overflowing with throwaway widgets
if ( api.Widgets.savedWidgetIds[removed_widget_id] ) { if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
inactive_widgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice(); inactiveWidgets = api.value( 'sidebars_widgets[wp_inactiveWidgets]' )().slice();
inactive_widgets.push( removed_widget_id ); inactiveWidgets.push( removedWidgetId );
api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactive_widgets ).unique() ); api.value( 'sidebars_widgets[wp_inactiveWidgets]' )( _( inactiveWidgets ).unique() );
} }
// Make old single widget available for adding again // Make old single widget available for adding again
removed_id_base = parse_widget_id( removed_widget_id ).id_base; removedIdBase = parseWidgetId( removedWidgetId ).id_base;
widget = api.Widgets.availableWidgets.findWhere( { id_base: removed_id_base } ); widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
if ( widget && ! widget.get( 'is_multi' ) ) { if ( widget && ! widget.get( 'is_multi' ) ) {
widget.set( 'is_disabled', false ); widget.set( 'is_disabled', false );
} }
@ -1428,26 +1428,30 @@
} ); } );
// Update the model with whether or not the sidebar is rendered // Update the model with whether or not the sidebar is rendered
api.Widgets.Previewer.bind( 'rendered-sidebars', function( rendered_sidebars ) { api.Widgets.Previewer.bind( 'rendered-sidebars', function( renderedSidebars ) {
var is_rendered = !! rendered_sidebars[control.params.sidebar_id]; var isRendered = !! renderedSidebars[self.params.sidebar_id];
registered_sidebar.set( 'is_rendered', is_rendered );
registeredSidebar.set( 'is_rendered', isRendered );
} ); } );
// Show the sidebar section when it becomes visible // Show the sidebar section when it becomes visible
registered_sidebar.on( 'change:is_rendered', function( ) { registeredSidebar.on( 'change:is_rendered', function( ) {
var section_selector = '#accordion-section-sidebar-widgets-' + this.get( 'id' ), section; var sectionSelector = '#accordion-section-sidebar-widgets-' + this.get( 'id' ), $section;
section = $( section_selector );
$section = $( sectionSelector );
if ( this.get( 'is_rendered' ) ) { if ( this.get( 'is_rendered' ) ) {
section.stop().slideDown( function() { $section.stop().slideDown( function() {
$( this ).css( 'height', 'auto' ); // so that the .accordion-section-content won't overflow $( this ).css( 'height', 'auto' ); // so that the .accordion-section-content won't overflow
} ); } );
} else { } else {
// Make sure that hidden sections get closed first // Make sure that hidden sections get closed first
if ( section.hasClass( 'open' ) ) { if ( $section.hasClass( 'open' ) ) {
// it would be nice if accordionSwitch() in accordion.js was public // it would be nice if accordionSwitch() in accordion.js was public
section.find( '.accordion-section-title' ).trigger( 'click' ); $section.find( '.accordion-section-title' ).trigger( 'click' );
} }
section.stop().slideUp();
$section.stop().slideUp();
} }
} ); } );
}, },
@ -1456,23 +1460,26 @@
* Allow widgets in sidebar to be re-ordered, and for the order to be previewed * Allow widgets in sidebar to be re-ordered, and for the order to be previewed
*/ */
_setupSortable: function() { _setupSortable: function() {
var control = this; var self = this;
control.is_reordering = false;
this.isReordering = false;
/** /**
* Update widget order setting when controls are re-ordered * Update widget order setting when controls are re-ordered
*/ */
control.section_content.sortable( { this.$sectionContent.sortable( {
items: '> .customize-control-widget_form', items: '> .customize-control-widget_form',
handle: '.widget-top', handle: '.widget-top',
axis: 'y', axis: 'y',
connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)', connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
update: function() { update: function() {
var widget_container_ids = control.section_content.sortable( 'toArray' ), widget_ids; var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
widget_ids = $.map( widget_container_ids, function( widget_container_id ) {
return $( '#' + widget_container_id ).find( ':input[name=widget-id]' ).val(); widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
} ); } );
control.setting( widget_ids );
self.setting( widgetIds );
} }
} ); } );
@ -1480,27 +1487,27 @@
* Expand other customizer sidebar section when dragging a control widget over it, * Expand other customizer sidebar section when dragging a control widget over it,
* allowing the control to be dropped into another section * allowing the control to be dropped into another section
*/ */
control.control_section.find( '.accordion-section-title' ).droppable( { this.$controlSection.find( '.accordion-section-title' ).droppable({
accept: '.customize-control-widget_form', accept: '.customize-control-widget_form',
over: function() { over: function() {
if ( ! control.control_section.hasClass( 'open' ) ) { if ( ! self.$controlSection.hasClass( 'open' ) ) {
control.control_section.addClass( 'open' ); self.$controlSection.addClass( 'open' );
control.section_content.toggle( false ).slideToggle( 150, function() { self.$sectionContent.toggle( false ).slideToggle( 150, function() {
control.section_content.sortable( 'refreshPositions' ); self.$sectionContent.sortable( 'refreshPositions' );
} ); } );
} }
} }
} ); });
/** /**
* Keyboard-accessible reordering * Keyboard-accessible reordering
*/ */
control.container.find( '.reorder-toggle' ).on( 'click keydown', function( event ) { this.container.find( '.reorder-toggle' ).on( 'click keydown', function( event ) {
if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar
return; return;
} }
control.toggleReordering( ! control.is_reordering ); self.toggleReordering( ! self.isReordering );
} ); } );
}, },
@ -1508,20 +1515,19 @@
* Set up UI for adding a new widget * Set up UI for adding a new widget
*/ */
_setupAddition: function() { _setupAddition: function() {
var control = this; var self = this;
control.container.find( '.add-new-widget' ).on( 'click keydown', function( event ) { this.container.find( '.add-new-widget' ).on( 'click keydown', function( event ) {
if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar if ( event.type === 'keydown' && ! ( event.which === 13 || event.which === 32 ) ) { // Enter or Spacebar
return; return;
} }
if ( control.section_content.hasClass( 'reordering' ) ) { if ( self.$sectionContent.hasClass( 'reordering' ) ) {
return; return;
} }
// @todo Use an control.is_adding state
if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) { if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
api.Widgets.availableWidgetsPanel.open( control ); api.Widgets.availableWidgetsPanel.open( self );
} else { } else {
api.Widgets.availableWidgetsPanel.close(); api.Widgets.availableWidgetsPanel.close();
} }
@ -1532,16 +1538,16 @@
* Add classes to the widget_form controls to assist with styling * Add classes to the widget_form controls to assist with styling
*/ */
_applyCardinalOrderClassNames: function() { _applyCardinalOrderClassNames: function() {
var control = this; this.$sectionContent.find( '.customize-control-widget_form' )
control.section_content.find( '.customize-control-widget_form' )
.removeClass( 'first-widget' ) .removeClass( 'first-widget' )
.removeClass( 'last-widget' ) .removeClass( 'last-widget' )
.find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 ); .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
control.section_content.find( '.customize-control-widget_form:first' ) this.$sectionContent.find( '.customize-control-widget_form:first' )
.addClass( 'first-widget' ) .addClass( 'first-widget' )
.find( '.move-widget-up' ).prop( 'tabIndex', -1 ); .find( '.move-widget-up' ).prop( 'tabIndex', -1 );
control.section_content.find( '.customize-control-widget_form:last' )
this.$sectionContent.find( '.customize-control-widget_form:last' )
.addClass( 'last-widget' ) .addClass( 'last-widget' )
.find( '.move-widget-down' ).prop( 'tabIndex', -1 ); .find( '.move-widget-down' ).prop( 'tabIndex', -1 );
}, },
@ -1554,21 +1560,21 @@
/** /**
* Enable/disable the reordering UI * Enable/disable the reordering UI
* *
* @param {Boolean} toggle to enable/disable reordering * @param {Boolean} showOrHide to enable/disable reordering
*/ */
toggleReordering: function( toggle ) { toggleReordering: function( showOrHide ) {
var control = this; showOrHide = Boolean( showOrHide );
toggle = Boolean( toggle );
if ( toggle === control.section_content.hasClass( 'reordering' ) ) { if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
return; return;
} }
control.is_reordering = toggle; this.isReordering = showOrHide;
control.section_content.toggleClass( 'reordering', toggle ); this.$sectionContent.toggleClass( 'reordering', showOrHide );
if ( toggle ) { if ( showOrHide ) {
_( control.getWidgetFormControls() ).each( function( form_control ) { _( this.getWidgetFormControls() ).each( function( formControl ) {
form_control.collapseForm(); formControl.collapseForm();
} ); } );
} }
}, },
@ -1577,178 +1583,171 @@
* @return {wp.customize.controlConstructor.widget_form[]} * @return {wp.customize.controlConstructor.widget_form[]}
*/ */
getWidgetFormControls: function() { getWidgetFormControls: function() {
var control = this, form_controls; var formControls;
form_controls = _( control.setting() ).map( function( widget_id ) { formControls = _( this.setting() ).map( function( widgetId ) {
var setting_id = widgetIdToSettingId( widget_id ), var settingId = widgetIdToSettingId( widgetId ),
form_control = api.control( setting_id ); formControl = api.control( settingId );
if ( ! form_control ) { if ( ! formControl ) {
throw new Error( 'Unable to find widget_form control for ' + widget_id ); return;
} }
return form_control;
return formControl;
} ); } );
return form_controls;
return formControls;
}, },
/** /**
* @param {string} widget_id or an id_base for adding a previously non-existing widget * @param {string} widgetId or an id_base for adding a previously non-existing widget
* @returns {object} widget_form control instance * @returns {object} widget_form control instance
*/ */
addWidget: function( widget_id ) { addWidget: function( widgetId ) {
var control = this, var self = this, controlHtml, $widget, controlType = 'widget_form', $control, controlConstructor,
control_html, parsedWidgetId = parseWidgetId( widgetId ),
widget_el, widgetNumber = parsedWidgetId.number,
customize_control_type = 'widget_form', widgetIdBase = parsedWidgetId.id_base,
customize_control, widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
parsed_widget_id = parse_widget_id( widget_id ), settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs;
widget_number = parsed_widget_id.number,
widget_id_base = parsed_widget_id.id_base,
widget = api.Widgets.availableWidgets.findWhere( {id_base: widget_id_base} ),
setting_id,
is_existing_widget,
Constructor,
widget_form_control,
sidebar_widgets,
setting_args;
if ( ! widget ) { if ( ! widget ) {
throw new Error( 'Widget unexpectedly not found.' ); return;
} }
if ( widget_number && ! widget.get( 'is_multi' ) ) {
throw new Error( 'Did not expect a widget number to be supplied for a non-multi widget' ); if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
return;
} }
// Set up new multi widget // Set up new multi widget
if ( widget.get( 'is_multi' ) && ! widget_number ) { if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 ); widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
widget_number = widget.get( 'multi_number' ); widgetNumber = widget.get( 'multi_number' );
} }
control_html = $( '#widget-tpl-' + widget.get( 'id' ) ).html(); controlHtml = $( '#widget-tpl-' + widget.get( 'id' ) ).html();
if ( widget.get( 'is_multi' ) ) { if ( widget.get( 'is_multi' ) ) {
control_html = control_html.replace( /<[^<>]+>/g, function( m ) { controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
return m.replace( /__i__|%i%/g, widget_number ); return m.replace( /__i__|%i%/g, widgetNumber );
} ); } );
} else { } else {
widget.set( 'is_disabled', true ); // Prevent single widget from being added again now widget.set( 'is_disabled', true ); // Prevent single widget from being added again now
} }
widget_el = $( control_html );
customize_control = $( '<li></li>' ); $widget = $( controlHtml );
customize_control.addClass( 'customize-control' );
customize_control.addClass( 'customize-control-' + customize_control_type ); $control = $( '<li/>' )
customize_control.append( widget_el ); .addClass( 'customize-control' )
customize_control.find( '> .widget-icon' ).remove(); .addClass( 'customize-control-' + controlType )
.append( $widget );
// Remove icon which is visible inside the panel
$control.find( '> .widget-icon' ).remove();
if ( widget.get( 'is_multi' ) ) { if ( widget.get( 'is_multi' ) ) {
customize_control.find( 'input[name="widget_number"]' ).val( widget_number ); $control.find( 'input[name="widget_number"]' ).val( widgetNumber );
customize_control.find( 'input[name="multi_number"]' ).val( widget_number ); $control.find( 'input[name="multi_number"]' ).val( widgetNumber );
} }
widget_id = customize_control.find( '[name="widget-id"]' ).val();
customize_control.hide(); // to be slid-down below
setting_id = 'widget_' + widget.get( 'id_base' ); widgetId = $control.find( '[name="widget-id"]' ).val();
$control.hide(); // to be slid-down below
settingId = 'widget_' + widget.get( 'id_base' );
if ( widget.get( 'is_multi' ) ) { if ( widget.get( 'is_multi' ) ) {
setting_id += '[' + widget_number + ']'; settingId += '[' + widgetNumber + ']';
} }
customize_control.attr( 'id', 'customize-control-' + setting_id.replace( /\]/g, '' ).replace( /\[/g, '-' ) ); $control.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );
control.container.after( customize_control ); this.container.after( $control );
// Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget) // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget)
is_existing_widget = api.has( setting_id ); isExistingWidget = api.has( settingId );
if ( ! is_existing_widget ) { if ( ! isExistingWidget ) {
setting_args = { settingArgs = {
transport: 'refresh', transport: 'refresh',
previewer: control.setting.previewer previewer: this.setting.previewer
}; };
api.create( setting_id, setting_id, {}, setting_args ); api.create( settingId, settingId, {}, settingArgs );
} }
Constructor = api.controlConstructor[customize_control_type]; controlConstructor = api.controlConstructor[controlType];
widget_form_control = new Constructor( setting_id, { widgetFormControl = new controlConstructor( settingId, {
params: { params: {
settings: { settings: {
'default': setting_id 'default': settingId
}, },
sidebar_id: control.params.sidebar_id, sidebar_id: self.params.sidebar_id,
widget_id: widget_id, widget_id: widgetId,
widget_id_base: widget.get( 'id_base' ), widget_id_base: widget.get( 'id_base' ),
type: customize_control_type, type: controlType,
is_new: ! is_existing_widget, is_new: ! isExistingWidget,
width: widget.get( 'width' ), width: widget.get( 'width' ),
height: widget.get( 'height' ), height: widget.get( 'height' ),
is_wide: widget.get( 'is_wide' ) is_wide: widget.get( 'is_wide' )
}, },
previewer: control.setting.previewer previewer: self.setting.previewer
} ); } );
api.control.add( setting_id, widget_form_control ); api.control.add( settingId, widgetFormControl );
// Make sure widget is removed from the other sidebars // Make sure widget is removed from the other sidebars
api.each( function( other_setting ) { api.each( function( otherSetting ) {
if ( other_setting.id === control.setting.id ) { if ( otherSetting.id === self.setting.id ) {
return; return;
} }
if ( 0 !== other_setting.id.indexOf( 'sidebars_widgets[' ) ) {
if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
return; return;
} }
var other_sidebar_widgets = other_setting().slice(), i;
i = _.indexOf( other_sidebar_widgets, widget_id ); var otherSidebarWidgets = otherSetting().slice(),
i = _.indexOf( otherSidebarWidgets, widgetId );
if ( -1 !== i ) { if ( -1 !== i ) {
other_sidebar_widgets.splice( i ); otherSidebarWidgets.splice( i );
other_setting( other_sidebar_widgets ); otherSetting( otherSidebarWidgets );
} }
} ); } );
// Add widget to this sidebar // Add widget to this sidebar
sidebar_widgets = control.setting().slice(); sidebarWidgets = this.setting().slice();
if ( -1 === _.indexOf( sidebar_widgets, widget_id ) ) { if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
sidebar_widgets.push( widget_id ); sidebarWidgets.push( widgetId );
control.setting( sidebar_widgets ); this.setting( sidebarWidgets );
} }
customize_control.slideDown( function() { $control.slideDown( function() {
if ( is_existing_widget ) { if ( isExistingWidget ) {
widget_form_control.expandForm(); widgetFormControl.expandForm();
widget_form_control.updateWidget( { widgetFormControl.updateWidget( {
instance: widget_form_control.setting(), instance: widgetFormControl.setting(),
complete: function( error ) { complete: function( error ) {
if ( error ) { if ( error ) {
throw error; throw error;
} }
widget_form_control.focus(); widgetFormControl.focus();
} }
} ); } );
} else { } else {
widget_form_control.focus(); widgetFormControl.focus();
} }
} ); } );
$( document ).trigger( 'widget-added', [ widget_el ] ); $( document ).trigger( 'widget-added', [ $widget ] );
return widget_form_control; return widgetFormControl;
} }
} ); } );
/**
* Extends wp.customizer.controlConstructor with control constructor for
* widget_form and sidebar_widgets.
*/
$.extend( api.controlConstructor, { $.extend( api.controlConstructor, {
widget_form: api.Widgets.WidgetControl, widget_form: api.Widgets.WidgetControl,
sidebar_widgets: api.Widgets.SidebarControl sidebar_widgets: api.Widgets.SidebarControl
}); });
api.bind( 'ready', function() {
// Set up the widgets panel
api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
collection: api.Widgets.availableWidgets
});
// Highlight widget control
api.Widgets.Previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
// Open and focus widget control
api.Widgets.Previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
} );
/** /**
* Capture the instance of the Previewer since it is private * Capture the instance of the Previewer since it is private
*/ */
@ -1761,6 +1760,22 @@
} }
} ); } );
/**
* Init Customizer for widgets.
*/
api.bind( 'ready', function() {
// Set up the widgets panel
api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
collection: api.Widgets.availableWidgets
});
// Highlight widget control
api.Widgets.Previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
// Open and focus widget control
api.Widgets.Previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
} );
/** /**
* Highlight a widget control. * Highlight a widget control.
* *
@ -1789,69 +1804,75 @@
/** /**
* Given a widget control, find the sidebar widgets control that contains it. * Given a widget control, find the sidebar widgets control that contains it.
* @param {string} widget_id * @param {string} widgetId
* @return {object|null} * @return {object|null}
*/ */
api.Widgets.getSidebarWidgetControlContainingWidget = function( widget_id ) { api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
var found_control = null; var foundControl = null;
// @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl() // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl()
api.control.each( function( control ) { api.control.each( function( control ) {
if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widget_id ) ) { if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
found_control = control; foundControl = control;
} }
} ); } );
return found_control; return foundControl;
}; };
/** /**
* Given a widget_id for a widget appearing in the preview, get the widget form control associated with it * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
* @param {string} widget_id *
* @param {string} widgetId
* @return {object|null} * @return {object|null}
*/ */
api.Widgets.getWidgetFormControlForWidget = function( widget_id ) { api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
var found_control = null; var foundControl = null;
// @todo We can just use widgetIdToSettingId() here // @todo We can just use widgetIdToSettingId() here
api.control.each( function( control ) { api.control.each( function( control ) {
if ( control.params.type === 'widget_form' && control.params.widget_id === widget_id ) { if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
found_control = control; foundControl = control;
} }
} ); } );
return found_control; return foundControl;
}; };
/** /**
* @param {String} widget_id * @param {String} widgetId
* @returns {Object} * @returns {Object}
*/ */
function parse_widget_id( widget_id ) { function parseWidgetId( widgetId ) {
var matches, parsed = { var matches, parsed = {
number: null, number: null,
id_base: null id_base: null
}; };
matches = widget_id.match( /^(.+)-(\d+)$/ );
matches = widgetId.match( /^(.+)-(\d+)$/ );
if ( matches ) { if ( matches ) {
parsed.id_base = matches[1]; parsed.id_base = matches[1];
parsed.number = parseInt( matches[2], 10 ); parsed.number = parseInt( matches[2], 10 );
} else { } else {
// likely an old single widget // likely an old single widget
parsed.id_base = widget_id; parsed.id_base = widgetId;
} }
return parsed; return parsed;
} }
/** /**
* @param {String} widget_id * @param {String} widgetId
* @returns {String} settingId * @returns {String} settingId
*/ */
function widgetIdToSettingId( widget_id ) { function widgetIdToSettingId( widgetId ) {
var parsed = parse_widget_id( widget_id ), settingId; var parsed = parseWidgetId( widgetId ), settingId;
settingId = 'widget_' + parsed.id_base; settingId = 'widget_' + parsed.id_base;
if ( parsed.number ) { if ( parsed.number ) {
settingId += '[' + parsed.number + ']'; settingId += '[' + parsed.number + ']';
} }
return settingId; return settingId;
} }

File diff suppressed because one or more lines are too long