widgets.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. /**
  2. * @output wp-admin/js/widgets.js
  3. */
  4. /* global ajaxurl, isRtl, wpWidgets */
  5. (function($) {
  6. var $document = $( document );
  7. window.wpWidgets = {
  8. /**
  9. * A closed Sidebar that gets a Widget dragged over it.
  10. *
  11. * @var {element|null}
  12. */
  13. hoveredSidebar: null,
  14. /**
  15. * Translations.
  16. *
  17. * Exported from PHP in wp_default_scripts().
  18. *
  19. * @var {object}
  20. */
  21. l10n: {
  22. save: '{save}',
  23. saved: '{saved}',
  24. saveAlert: '{saveAlert}',
  25. widgetAdded: '{widgetAdded}'
  26. },
  27. /**
  28. * Lookup of which widgets have had change events triggered.
  29. *
  30. * @var {object}
  31. */
  32. dirtyWidgets: {},
  33. init : function() {
  34. var rem, the_id,
  35. self = this,
  36. chooser = $('.widgets-chooser'),
  37. selectSidebar = chooser.find('.widgets-chooser-sidebars'),
  38. sidebars = $('div.widgets-sortables'),
  39. isRTL = !! ( 'undefined' !== typeof isRtl && isRtl );
  40. // Handle the widgets containers in the right column.
  41. $( '#widgets-right .sidebar-name' )
  42. /*
  43. * Toggle the widgets containers when clicked and update the toggle
  44. * button `aria-expanded` attribute value.
  45. */
  46. .click( function() {
  47. var $this = $( this ),
  48. $wrap = $this.closest( '.widgets-holder-wrap '),
  49. $toggle = $this.find( '.handlediv' );
  50. if ( $wrap.hasClass( 'closed' ) ) {
  51. $wrap.removeClass( 'closed' );
  52. $toggle.attr( 'aria-expanded', 'true' );
  53. // Refresh the jQuery UI sortable items.
  54. $this.parent().sortable( 'refresh' );
  55. } else {
  56. $wrap.addClass( 'closed' );
  57. $toggle.attr( 'aria-expanded', 'false' );
  58. }
  59. // Update the admin menu "sticky" state.
  60. $document.triggerHandler( 'wp-pin-menu' );
  61. })
  62. /*
  63. * Set the initial `aria-expanded` attribute value on the widgets
  64. * containers toggle button. The first one is expanded by default.
  65. */
  66. .find( '.handlediv' ).each( function( index ) {
  67. if ( 0 === index ) {
  68. // jQuery equivalent of `continue` within an `each()` loop.
  69. return;
  70. }
  71. $( this ).attr( 'aria-expanded', 'false' );
  72. });
  73. // Show AYS dialog when there are unsaved widget changes.
  74. $( window ).on( 'beforeunload.widgets', function( event ) {
  75. var dirtyWidgetIds = [], unsavedWidgetsElements;
  76. $.each( self.dirtyWidgets, function( widgetId, dirty ) {
  77. if ( dirty ) {
  78. dirtyWidgetIds.push( widgetId );
  79. }
  80. });
  81. if ( 0 !== dirtyWidgetIds.length ) {
  82. unsavedWidgetsElements = $( '#widgets-right' ).find( '.widget' ).filter( function() {
  83. return -1 !== dirtyWidgetIds.indexOf( $( this ).prop( 'id' ).replace( /^widget-\d+_/, '' ) );
  84. });
  85. unsavedWidgetsElements.each( function() {
  86. if ( ! $( this ).hasClass( 'open' ) ) {
  87. $( this ).find( '.widget-title-action:first' ).click();
  88. }
  89. });
  90. // Bring the first unsaved widget into view and focus on the first tabbable field.
  91. unsavedWidgetsElements.first().each( function() {
  92. if ( this.scrollIntoViewIfNeeded ) {
  93. this.scrollIntoViewIfNeeded();
  94. } else {
  95. this.scrollIntoView();
  96. }
  97. $( this ).find( '.widget-inside :tabbable:first' ).focus();
  98. } );
  99. event.returnValue = wpWidgets.l10n.saveAlert;
  100. return event.returnValue;
  101. }
  102. });
  103. // Handle the widgets containers in the left column.
  104. $( '#widgets-left .sidebar-name' ).click( function() {
  105. var $wrap = $( this ).closest( '.widgets-holder-wrap' );
  106. $wrap
  107. .toggleClass( 'closed' )
  108. .find( '.handlediv' ).attr( 'aria-expanded', ! $wrap.hasClass( 'closed' ) );
  109. // Update the admin menu "sticky" state.
  110. $document.triggerHandler( 'wp-pin-menu' );
  111. });
  112. $(document.body).bind('click.widgets-toggle', function(e) {
  113. var target = $(e.target),
  114. css = { 'z-index': 100 },
  115. widget, inside, targetWidth, widgetWidth, margin, saveButton, widgetId,
  116. toggleBtn = target.closest( '.widget' ).find( '.widget-top button.widget-action' );
  117. if ( target.parents('.widget-top').length && ! target.parents('#available-widgets').length ) {
  118. widget = target.closest('div.widget');
  119. inside = widget.children('.widget-inside');
  120. targetWidth = parseInt( widget.find('input.widget-width').val(), 10 );
  121. widgetWidth = widget.parent().width();
  122. widgetId = inside.find( '.widget-id' ).val();
  123. // Save button is initially disabled, but is enabled when a field is changed.
  124. if ( ! widget.data( 'dirty-state-initialized' ) ) {
  125. saveButton = inside.find( '.widget-control-save' );
  126. saveButton.prop( 'disabled', true ).val( wpWidgets.l10n.saved );
  127. inside.on( 'input change', function() {
  128. self.dirtyWidgets[ widgetId ] = true;
  129. widget.addClass( 'widget-dirty' );
  130. saveButton.prop( 'disabled', false ).val( wpWidgets.l10n.save );
  131. });
  132. widget.data( 'dirty-state-initialized', true );
  133. }
  134. if ( inside.is(':hidden') ) {
  135. if ( targetWidth > 250 && ( targetWidth + 30 > widgetWidth ) && widget.closest('div.widgets-sortables').length ) {
  136. if ( widget.closest('div.widget-liquid-right').length ) {
  137. margin = isRTL ? 'margin-right' : 'margin-left';
  138. } else {
  139. margin = isRTL ? 'margin-left' : 'margin-right';
  140. }
  141. css[ margin ] = widgetWidth - ( targetWidth + 30 ) + 'px';
  142. widget.css( css );
  143. }
  144. /*
  145. * Don't change the order of attributes changes and animation:
  146. * it's important for screen readers, see ticket #31476.
  147. */
  148. toggleBtn.attr( 'aria-expanded', 'true' );
  149. inside.slideDown( 'fast', function() {
  150. widget.addClass( 'open' );
  151. });
  152. } else {
  153. /*
  154. * Don't change the order of attributes changes and animation:
  155. * it's important for screen readers, see ticket #31476.
  156. */
  157. toggleBtn.attr( 'aria-expanded', 'false' );
  158. inside.slideUp( 'fast', function() {
  159. widget.attr( 'style', '' );
  160. widget.removeClass( 'open' );
  161. });
  162. }
  163. } else if ( target.hasClass('widget-control-save') ) {
  164. wpWidgets.save( target.closest('div.widget'), 0, 1, 0 );
  165. e.preventDefault();
  166. } else if ( target.hasClass('widget-control-remove') ) {
  167. wpWidgets.save( target.closest('div.widget'), 1, 1, 0 );
  168. } else if ( target.hasClass('widget-control-close') ) {
  169. widget = target.closest('div.widget');
  170. widget.removeClass( 'open' );
  171. toggleBtn.attr( 'aria-expanded', 'false' );
  172. wpWidgets.close( widget );
  173. } else if ( target.attr( 'id' ) === 'inactive-widgets-control-remove' ) {
  174. wpWidgets.removeInactiveWidgets();
  175. e.preventDefault();
  176. }
  177. });
  178. sidebars.children('.widget').each( function() {
  179. var $this = $(this);
  180. wpWidgets.appendTitle( this );
  181. if ( $this.find( 'p.widget-error' ).length ) {
  182. $this.find( '.widget-action' ).trigger( 'click' ).attr( 'aria-expanded', 'true' );
  183. }
  184. });
  185. $('#widget-list').children('.widget').draggable({
  186. connectToSortable: 'div.widgets-sortables',
  187. handle: '> .widget-top > .widget-title',
  188. distance: 2,
  189. helper: 'clone',
  190. zIndex: 100,
  191. containment: '#wpwrap',
  192. refreshPositions: true,
  193. start: function( event, ui ) {
  194. var chooser = $(this).find('.widgets-chooser');
  195. ui.helper.find('div.widget-description').hide();
  196. the_id = this.id;
  197. if ( chooser.length ) {
  198. // Hide the chooser and move it out of the widget
  199. $( '#wpbody-content' ).append( chooser.hide() );
  200. // Delete the cloned chooser from the drag helper
  201. ui.helper.find('.widgets-chooser').remove();
  202. self.clearWidgetSelection();
  203. }
  204. },
  205. stop: function() {
  206. if ( rem ) {
  207. $(rem).hide();
  208. }
  209. rem = '';
  210. }
  211. });
  212. /**
  213. * Opens and closes previously closed Sidebars when Widgets are dragged over/out of them.
  214. */
  215. sidebars.droppable( {
  216. tolerance: 'intersect',
  217. /**
  218. * Open Sidebar when a Widget gets dragged over it.
  219. *
  220. * @ignore
  221. *
  222. * @param {object} event jQuery event object.
  223. */
  224. over: function( event ) {
  225. var $wrap = $( event.target ).parent();
  226. if ( wpWidgets.hoveredSidebar && ! $wrap.is( wpWidgets.hoveredSidebar ) ) {
  227. // Close the previous Sidebar as the Widget has been dragged onto another Sidebar.
  228. wpWidgets.closeSidebar( event );
  229. }
  230. if ( $wrap.hasClass( 'closed' ) ) {
  231. wpWidgets.hoveredSidebar = $wrap;
  232. $wrap
  233. .removeClass( 'closed' )
  234. .find( '.handlediv' ).attr( 'aria-expanded', 'true' );
  235. }
  236. $( this ).sortable( 'refresh' );
  237. },
  238. /**
  239. * Close Sidebar when the Widget gets dragged out of it.
  240. *
  241. * @ignore
  242. *
  243. * @param {object} event jQuery event object.
  244. */
  245. out: function( event ) {
  246. if ( wpWidgets.hoveredSidebar ) {
  247. wpWidgets.closeSidebar( event );
  248. }
  249. }
  250. } );
  251. sidebars.sortable({
  252. placeholder: 'widget-placeholder',
  253. items: '> .widget',
  254. handle: '> .widget-top > .widget-title',
  255. cursor: 'move',
  256. distance: 2,
  257. containment: '#wpwrap',
  258. tolerance: 'pointer',
  259. refreshPositions: true,
  260. start: function( event, ui ) {
  261. var height, $this = $(this),
  262. $wrap = $this.parent(),
  263. inside = ui.item.children('.widget-inside');
  264. if ( inside.css('display') === 'block' ) {
  265. ui.item.removeClass('open');
  266. ui.item.find( '.widget-top button.widget-action' ).attr( 'aria-expanded', 'false' );
  267. inside.hide();
  268. $(this).sortable('refreshPositions');
  269. }
  270. if ( ! $wrap.hasClass('closed') ) {
  271. // Lock all open sidebars min-height when starting to drag.
  272. // Prevents jumping when dragging a widget from an open sidebar to a closed sidebar below.
  273. height = ui.item.hasClass('ui-draggable') ? $this.height() : 1 + $this.height();
  274. $this.css( 'min-height', height + 'px' );
  275. }
  276. },
  277. stop: function( event, ui ) {
  278. var addNew, widgetNumber, $sidebar, $children, child, item,
  279. $widget = ui.item,
  280. id = the_id;
  281. // Reset the var to hold a previously closed sidebar.
  282. wpWidgets.hoveredSidebar = null;
  283. if ( $widget.hasClass('deleting') ) {
  284. wpWidgets.save( $widget, 1, 0, 1 ); // delete widget
  285. $widget.remove();
  286. return;
  287. }
  288. addNew = $widget.find('input.add_new').val();
  289. widgetNumber = $widget.find('input.multi_number').val();
  290. $widget.attr( 'style', '' ).removeClass('ui-draggable');
  291. the_id = '';
  292. if ( addNew ) {
  293. if ( 'multi' === addNew ) {
  294. $widget.html(
  295. $widget.html().replace( /<[^<>]+>/g, function( tag ) {
  296. return tag.replace( /__i__|%i%/g, widgetNumber );
  297. })
  298. );
  299. $widget.attr( 'id', id.replace( '__i__', widgetNumber ) );
  300. widgetNumber++;
  301. $( 'div#' + id ).find( 'input.multi_number' ).val( widgetNumber );
  302. } else if ( 'single' === addNew ) {
  303. $widget.attr( 'id', 'new-' + id );
  304. rem = 'div#' + id;
  305. }
  306. wpWidgets.save( $widget, 0, 0, 1 );
  307. $widget.find('input.add_new').val('');
  308. $document.trigger( 'widget-added', [ $widget ] );
  309. }
  310. $sidebar = $widget.parent();
  311. if ( $sidebar.parent().hasClass('closed') ) {
  312. $sidebar.parent()
  313. .removeClass( 'closed' )
  314. .find( '.handlediv' ).attr( 'aria-expanded', 'true' );
  315. $children = $sidebar.children('.widget');
  316. // Make sure the dropped widget is at the top
  317. if ( $children.length > 1 ) {
  318. child = $children.get(0);
  319. item = $widget.get(0);
  320. if ( child.id && item.id && child.id !== item.id ) {
  321. $( child ).before( $widget );
  322. }
  323. }
  324. }
  325. if ( addNew ) {
  326. $widget.find( '.widget-action' ).trigger( 'click' );
  327. } else {
  328. wpWidgets.saveOrder( $sidebar.attr('id') );
  329. }
  330. },
  331. activate: function() {
  332. $(this).parent().addClass( 'widget-hover' );
  333. },
  334. deactivate: function() {
  335. // Remove all min-height added on "start"
  336. $(this).css( 'min-height', '' ).parent().removeClass( 'widget-hover' );
  337. },
  338. receive: function( event, ui ) {
  339. var $sender = $( ui.sender );
  340. // Don't add more widgets to orphaned sidebars
  341. if ( this.id.indexOf('orphaned_widgets') > -1 ) {
  342. $sender.sortable('cancel');
  343. return;
  344. }
  345. // If the last widget was moved out of an orphaned sidebar, close and remove it.
  346. if ( $sender.attr('id').indexOf('orphaned_widgets') > -1 && ! $sender.children('.widget').length ) {
  347. $sender.parents('.orphan-sidebar').slideUp( 400, function(){ $(this).remove(); } );
  348. }
  349. }
  350. }).sortable( 'option', 'connectWith', 'div.widgets-sortables' );
  351. $('#available-widgets').droppable({
  352. tolerance: 'pointer',
  353. accept: function(o){
  354. return $(o).parent().attr('id') !== 'widget-list';
  355. },
  356. drop: function(e,ui) {
  357. ui.draggable.addClass('deleting');
  358. $('#removing-widget').hide().children('span').empty();
  359. },
  360. over: function(e,ui) {
  361. ui.draggable.addClass('deleting');
  362. $('div.widget-placeholder').hide();
  363. if ( ui.draggable.hasClass('ui-sortable-helper') ) {
  364. $('#removing-widget').show().children('span')
  365. .html( ui.draggable.find( 'div.widget-title' ).children( 'h3' ).html() );
  366. }
  367. },
  368. out: function(e,ui) {
  369. ui.draggable.removeClass('deleting');
  370. $('div.widget-placeholder').show();
  371. $('#removing-widget').hide().children('span').empty();
  372. }
  373. });
  374. // Area Chooser
  375. $( '#widgets-right .widgets-holder-wrap' ).each( function( index, element ) {
  376. var $element = $( element ),
  377. name = $element.find( '.sidebar-name h2' ).text(),
  378. ariaLabel = $element.find( '.sidebar-name' ).data( 'add-to' ),
  379. id = $element.find( '.widgets-sortables' ).attr( 'id' ),
  380. li = $( '<li>' ),
  381. button = $( '<button>', {
  382. type: 'button',
  383. 'aria-pressed': 'false',
  384. 'class': 'widgets-chooser-button',
  385. 'aria-label': ariaLabel
  386. } ).text( $.trim( name ) );
  387. li.append( button );
  388. if ( index === 0 ) {
  389. li.addClass( 'widgets-chooser-selected' );
  390. button.attr( 'aria-pressed', 'true' );
  391. }
  392. selectSidebar.append( li );
  393. li.data( 'sidebarId', id );
  394. });
  395. $( '#available-widgets .widget .widget-top' ).on( 'click.widgets-chooser', function() {
  396. var $widget = $( this ).closest( '.widget' ),
  397. toggleButton = $( this ).find( '.widget-action' ),
  398. chooserButtons = selectSidebar.find( '.widgets-chooser-button' );
  399. if ( $widget.hasClass( 'widget-in-question' ) || $( '#widgets-left' ).hasClass( 'chooser' ) ) {
  400. toggleButton.attr( 'aria-expanded', 'false' );
  401. self.closeChooser();
  402. } else {
  403. // Open the chooser
  404. self.clearWidgetSelection();
  405. $( '#widgets-left' ).addClass( 'chooser' );
  406. // Add CSS class and insert the chooser after the widget description.
  407. $widget.addClass( 'widget-in-question' ).children( '.widget-description' ).after( chooser );
  408. // Open the chooser with a slide down animation.
  409. chooser.slideDown( 300, function() {
  410. // Update the toggle button aria-expanded attribute after previous DOM manipulations.
  411. toggleButton.attr( 'aria-expanded', 'true' );
  412. });
  413. chooserButtons.on( 'click.widgets-chooser', function() {
  414. selectSidebar.find( '.widgets-chooser-selected' ).removeClass( 'widgets-chooser-selected' );
  415. chooserButtons.attr( 'aria-pressed', 'false' );
  416. $( this )
  417. .attr( 'aria-pressed', 'true' )
  418. .closest( 'li' ).addClass( 'widgets-chooser-selected' );
  419. } );
  420. }
  421. });
  422. // Add event handlers
  423. chooser.on( 'click.widgets-chooser', function( event ) {
  424. var $target = $( event.target );
  425. if ( $target.hasClass('button-primary') ) {
  426. self.addWidget( chooser );
  427. self.closeChooser();
  428. } else if ( $target.hasClass( 'widgets-chooser-cancel' ) ) {
  429. self.closeChooser();
  430. }
  431. }).on( 'keyup.widgets-chooser', function( event ) {
  432. if ( event.which === $.ui.keyCode.ESCAPE ) {
  433. self.closeChooser();
  434. }
  435. });
  436. },
  437. saveOrder : function( sidebarId ) {
  438. var data = {
  439. action: 'widgets-order',
  440. savewidgets: $('#_wpnonce_widgets').val(),
  441. sidebars: []
  442. };
  443. if ( sidebarId ) {
  444. $( '#' + sidebarId ).find( '.spinner:first' ).addClass( 'is-active' );
  445. }
  446. $('div.widgets-sortables').each( function() {
  447. if ( $(this).sortable ) {
  448. data['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
  449. }
  450. });
  451. $.post( ajaxurl, data, function() {
  452. $( '#inactive-widgets-control-remove' ).prop( 'disabled' , ! $( '#wp_inactive_widgets .widget' ).length );
  453. $( '.spinner' ).removeClass( 'is-active' );
  454. });
  455. },
  456. save : function( widget, del, animate, order ) {
  457. var self = this, data, a,
  458. sidebarId = widget.closest( 'div.widgets-sortables' ).attr( 'id' ),
  459. form = widget.find( 'form' ),
  460. isAdd = widget.find( 'input.add_new' ).val();
  461. if ( ! del && ! isAdd && form.prop( 'checkValidity' ) && ! form[0].checkValidity() ) {
  462. return;
  463. }
  464. data = form.serialize();
  465. widget = $(widget);
  466. $( '.spinner', widget ).addClass( 'is-active' );
  467. a = {
  468. action: 'save-widget',
  469. savewidgets: $('#_wpnonce_widgets').val(),
  470. sidebar: sidebarId
  471. };
  472. if ( del ) {
  473. a.delete_widget = 1;
  474. }
  475. data += '&' + $.param(a);
  476. $.post( ajaxurl, data, function(r) {
  477. var id = $('input.widget-id', widget).val();
  478. if ( del ) {
  479. if ( ! $('input.widget_number', widget).val() ) {
  480. $('#available-widgets').find('input.widget-id').each(function(){
  481. if ( $(this).val() === id ) {
  482. $(this).closest('div.widget').show();
  483. }
  484. });
  485. }
  486. if ( animate ) {
  487. order = 0;
  488. widget.slideUp( 'fast', function() {
  489. $( this ).remove();
  490. wpWidgets.saveOrder();
  491. delete self.dirtyWidgets[ id ];
  492. });
  493. } else {
  494. widget.remove();
  495. delete self.dirtyWidgets[ id ];
  496. if ( sidebarId === 'wp_inactive_widgets' ) {
  497. $( '#inactive-widgets-control-remove' ).prop( 'disabled' , ! $( '#wp_inactive_widgets .widget' ).length );
  498. }
  499. }
  500. } else {
  501. $( '.spinner' ).removeClass( 'is-active' );
  502. if ( r && r.length > 2 ) {
  503. $( 'div.widget-content', widget ).html( r );
  504. wpWidgets.appendTitle( widget );
  505. // Re-disable the save button.
  506. widget.find( '.widget-control-save' ).prop( 'disabled', true ).val( wpWidgets.l10n.saved );
  507. widget.removeClass( 'widget-dirty' );
  508. // Clear the dirty flag from the widget.
  509. delete self.dirtyWidgets[ id ];
  510. $document.trigger( 'widget-updated', [ widget ] );
  511. if ( sidebarId === 'wp_inactive_widgets' ) {
  512. $( '#inactive-widgets-control-remove' ).prop( 'disabled' , ! $( '#wp_inactive_widgets .widget' ).length );
  513. }
  514. }
  515. }
  516. if ( order ) {
  517. wpWidgets.saveOrder();
  518. }
  519. });
  520. },
  521. removeInactiveWidgets : function() {
  522. var $element = $( '.remove-inactive-widgets' ), self = this, a, data;
  523. $( '.spinner', $element ).addClass( 'is-active' );
  524. a = {
  525. action : 'delete-inactive-widgets',
  526. removeinactivewidgets : $( '#_wpnonce_remove_inactive_widgets' ).val()
  527. };
  528. data = $.param( a );
  529. $.post( ajaxurl, data, function() {
  530. $( '#wp_inactive_widgets .widget' ).each(function() {
  531. var $widget = $( this );
  532. delete self.dirtyWidgets[ $widget.find( 'input.widget-id' ).val() ];
  533. $widget.remove();
  534. });
  535. $( '#inactive-widgets-control-remove' ).prop( 'disabled', true );
  536. $( '.spinner', $element ).removeClass( 'is-active' );
  537. } );
  538. },
  539. appendTitle : function(widget) {
  540. var title = $('input[id*="-title"]', widget).val() || '';
  541. if ( title ) {
  542. title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  543. }
  544. $(widget).children('.widget-top').children('.widget-title').children()
  545. .children('.in-widget-title').html(title);
  546. },
  547. close : function(widget) {
  548. widget.children('.widget-inside').slideUp('fast', function() {
  549. widget.attr( 'style', '' )
  550. .find( '.widget-top button.widget-action' )
  551. .attr( 'aria-expanded', 'false' )
  552. .focus();
  553. });
  554. },
  555. addWidget: function( chooser ) {
  556. var widget, widgetId, add, n, viewportTop, viewportBottom, sidebarBounds,
  557. sidebarId = chooser.find( '.widgets-chooser-selected' ).data('sidebarId'),
  558. sidebar = $( '#' + sidebarId );
  559. widget = $('#available-widgets').find('.widget-in-question').clone();
  560. widgetId = widget.attr('id');
  561. add = widget.find( 'input.add_new' ).val();
  562. n = widget.find( 'input.multi_number' ).val();
  563. // Remove the cloned chooser from the widget
  564. widget.find('.widgets-chooser').remove();
  565. if ( 'multi' === add ) {
  566. widget.html(
  567. widget.html().replace( /<[^<>]+>/g, function(m) {
  568. return m.replace( /__i__|%i%/g, n );
  569. })
  570. );
  571. widget.attr( 'id', widgetId.replace( '__i__', n ) );
  572. n++;
  573. $( '#' + widgetId ).find('input.multi_number').val(n);
  574. } else if ( 'single' === add ) {
  575. widget.attr( 'id', 'new-' + widgetId );
  576. $( '#' + widgetId ).hide();
  577. }
  578. // Open the widgets container.
  579. sidebar.closest( '.widgets-holder-wrap' )
  580. .removeClass( 'closed' )
  581. .find( '.handlediv' ).attr( 'aria-expanded', 'true' );
  582. sidebar.append( widget );
  583. sidebar.sortable('refresh');
  584. wpWidgets.save( widget, 0, 0, 1 );
  585. // No longer "new" widget
  586. widget.find( 'input.add_new' ).val('');
  587. $document.trigger( 'widget-added', [ widget ] );
  588. /*
  589. * Check if any part of the sidebar is visible in the viewport. If it is, don't scroll.
  590. * Otherwise, scroll up to so the sidebar is in view.
  591. *
  592. * We do this by comparing the top and bottom, of the sidebar so see if they are within
  593. * the bounds of the viewport.
  594. */
  595. viewportTop = $(window).scrollTop();
  596. viewportBottom = viewportTop + $(window).height();
  597. sidebarBounds = sidebar.offset();
  598. sidebarBounds.bottom = sidebarBounds.top + sidebar.outerHeight();
  599. if ( viewportTop > sidebarBounds.bottom || viewportBottom < sidebarBounds.top ) {
  600. $( 'html, body' ).animate({
  601. scrollTop: sidebarBounds.top - 130
  602. }, 200 );
  603. }
  604. window.setTimeout( function() {
  605. // Cannot use a callback in the animation above as it fires twice,
  606. // have to queue this "by hand".
  607. widget.find( '.widget-title' ).trigger('click');
  608. // At the end of the animation, announce the widget has been added.
  609. window.wp.a11y.speak( wpWidgets.l10n.widgetAdded, 'assertive' );
  610. }, 250 );
  611. },
  612. closeChooser: function() {
  613. var self = this,
  614. widgetInQuestion = $( '#available-widgets .widget-in-question' );
  615. $( '.widgets-chooser' ).slideUp( 200, function() {
  616. $( '#wpbody-content' ).append( this );
  617. self.clearWidgetSelection();
  618. // Move focus back to the toggle button.
  619. widgetInQuestion.find( '.widget-action' ).attr( 'aria-expanded', 'false' ).focus();
  620. });
  621. },
  622. clearWidgetSelection: function() {
  623. $( '#widgets-left' ).removeClass( 'chooser' );
  624. $( '.widget-in-question' ).removeClass( 'widget-in-question' );
  625. },
  626. /**
  627. * Closes a Sidebar that was previously closed, but opened by dragging a Widget over it.
  628. *
  629. * Used when a Widget gets dragged in/out of the Sidebar and never dropped.
  630. *
  631. * @param {object} event jQuery event object.
  632. */
  633. closeSidebar: function( event ) {
  634. this.hoveredSidebar
  635. .addClass( 'closed' )
  636. .find( '.handlediv' ).attr( 'aria-expanded', 'false' );
  637. $( event.target ).css( 'min-height', '' );
  638. this.hoveredSidebar = null;
  639. }
  640. };
  641. $document.ready( function(){ wpWidgets.init(); } );
  642. })(jQuery);