@@ -21,7 +21,7 @@ var WidgetCustomizer = (function ($) {
2121 */
2222ready : function ( ) {
2323var 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 ( ) {
3434var control = this ;
35+
36+ // Update widget order setting when controls are re-ordered
3537this . container . closest ( '.accordion-section-content' ) . sortable ( {
3638items : '> .customize-control-widget_form' ,
3739axis : 'y' ,
3840update : function ( ) {
3941var widget_container_ids = $ ( this ) . sortable ( 'toArray' ) ;
4042var widget_ids = $ . map ( widget_container_ids , function ( widget_container_id ) {
4143return $ ( '#' + widget_container_id ) . find ( ':input[name=widget-id]' ) . val ( ) ;
42- } ) ;
44+ } ) ;
4345control . 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