Skip to content

Commit a5dc70f

Browse files
committed
Update ordering of widget form controls when setting is updated
Ensures that UI responds to changes to model, just as currently we update model in reponse to UI changes.
1 parent 3bbdcf5 commit a5dc70f

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

widget-customizer.js

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ var WidgetCustomizer = (function ($) {
2121
*/
2222
ready: function() {
2323
var control = this;
24-
control.makeWidgetsReorderable();
24+
control.setupOrdering();
2525
// @todo Set up control for adding new widgets (via a dropdown, and with jQuery Chosen)
2626
// @todo Set up control for deleting widgets (add a delete link to each widget form control)
2727
// @link https://github.com/x-team/wp-widget-customizer/issues/3
@@ -30,19 +30,50 @@ var WidgetCustomizer = (function ($) {
3030
/**
3131
* Allow widgets in sidebar to be re-ordered, and for the order to be previewed
3232
*/
33-
makeWidgetsReorderable: function () {
33+
setupOrdering: function () {
3434
var control = this;
35+
36+
// Update widget order setting when controls are re-ordered
3537
this.container.closest( '.accordion-section-content' ).sortable({
3638
items: '> .customize-control-widget_form',
3739
axis: 'y',
3840
update: function () {
3941
var widget_container_ids = $(this).sortable('toArray');
4042
var widget_ids = $.map( widget_container_ids, function ( widget_container_id ) {
4143
return $('#' + widget_container_id).find(':input[name=widget-id]').val();
42-
} );
44+
});
4345
control.setting( widget_ids );
4446
}
4547
});
48+
49+
// Update ordering of widget control forms when the setting is updated
50+
control.setting.bind( function( to ) {
51+
var section_container = control.container.closest('.accordion-section-content');
52+
var controls = section_container.find('> .customize-control-widget_form');
53+
54+
// Build up index
55+
var widget_positions = {};
56+
$.each( to, function ( i, widget_id ) {
57+
widget_positions[widget_id] = i;
58+
});
59+
controls.each( function () {
60+
var widget_id = $(this).find('input[name="widget-id"]').val();
61+
$(this).data('widget-id', widget_id);
62+
});
63+
64+
// Sort widget controls to their new positions
65+
controls.sort(function ( a, b ) {
66+
var a_widget_id = $(a).data('widget-id');
67+
var b_widget_id = $(b).data('widget-id');
68+
if ( widget_positions[a_widget_id] === widget_positions[b_widget_id] ) {
69+
return 0;
70+
}
71+
return widget_positions[a_widget_id] < widget_positions[b_widget_id] ? -1 : 1;
72+
});
73+
74+
// Append the controls to put them in the right order
75+
section_container.append( controls );
76+
});
4677
}
4778

4879
});

0 commit comments

Comments
 (0)