widgets.js 23 KB

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