customize-widgets.js 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333
  1. /* global _wpCustomizeWidgetsSettings */
  2. (function( wp, $ ){
  3. if ( ! wp || ! wp.customize ) { return; }
  4. // Set up our namespace...
  5. var api = wp.customize,
  6. l10n;
  7. api.Widgets = api.Widgets || {};
  8. api.Widgets.savedWidgetIds = {};
  9. // Link settings
  10. api.Widgets.data = _wpCustomizeWidgetsSettings || {};
  11. l10n = api.Widgets.data.l10n;
  12. /**
  13. * wp.customize.Widgets.WidgetModel
  14. *
  15. * A single widget model.
  16. *
  17. * @constructor
  18. * @augments Backbone.Model
  19. */
  20. api.Widgets.WidgetModel = Backbone.Model.extend({
  21. id: null,
  22. temp_id: null,
  23. classname: null,
  24. control_tpl: null,
  25. description: null,
  26. is_disabled: null,
  27. is_multi: null,
  28. multi_number: null,
  29. name: null,
  30. id_base: null,
  31. transport: null,
  32. params: [],
  33. width: null,
  34. height: null,
  35. search_matched: true
  36. });
  37. /**
  38. * wp.customize.Widgets.WidgetCollection
  39. *
  40. * Collection for widget models.
  41. *
  42. * @constructor
  43. * @augments Backbone.Model
  44. */
  45. api.Widgets.WidgetCollection = Backbone.Collection.extend({
  46. model: api.Widgets.WidgetModel,
  47. // Controls searching on the current widget collection
  48. // and triggers an update event
  49. doSearch: function( value ) {
  50. // Don't do anything if we've already done this search
  51. // Useful because the search handler fires multiple times per keystroke
  52. if ( this.terms === value ) {
  53. return;
  54. }
  55. // Updates terms with the value passed
  56. this.terms = value;
  57. // If we have terms, run a search...
  58. if ( this.terms.length > 0 ) {
  59. this.search( this.terms );
  60. }
  61. // If search is blank, set all the widgets as they matched the search to reset the views.
  62. if ( this.terms === '' ) {
  63. this.each( function ( widget ) {
  64. widget.set( 'search_matched', true );
  65. } );
  66. }
  67. },
  68. // Performs a search within the collection
  69. // @uses RegExp
  70. search: function( term ) {
  71. var match, haystack;
  72. // Escape the term string for RegExp meta characters
  73. term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
  74. // Consider spaces as word delimiters and match the whole string
  75. // so matching terms can be combined
  76. term = term.replace( / /g, ')(?=.*' );
  77. match = new RegExp( '^(?=.*' + term + ').+', 'i' );
  78. this.each( function ( data ) {
  79. haystack = [ data.get( 'name' ), data.get( 'id' ), data.get( 'description' ) ].join( ' ' );
  80. data.set( 'search_matched', match.test( haystack ) );
  81. } );
  82. }
  83. });
  84. api.Widgets.availableWidgets = new api.Widgets.WidgetCollection( api.Widgets.data.availableWidgets );
  85. /**
  86. * wp.customize.Widgets.SidebarModel
  87. *
  88. * A single sidebar model.
  89. *
  90. * @constructor
  91. * @augments Backbone.Model
  92. */
  93. api.Widgets.SidebarModel = Backbone.Model.extend({
  94. after_title: null,
  95. after_widget: null,
  96. before_title: null,
  97. before_widget: null,
  98. 'class': null,
  99. description: null,
  100. id: null,
  101. name: null,
  102. is_rendered: false
  103. });
  104. /**
  105. * wp.customize.Widgets.SidebarCollection
  106. *
  107. * Collection for sidebar models.
  108. *
  109. * @constructor
  110. * @augments Backbone.Collection
  111. */
  112. api.Widgets.SidebarCollection = Backbone.Collection.extend({
  113. model: api.Widgets.SidebarModel
  114. });
  115. api.Widgets.registeredSidebars = new api.Widgets.SidebarCollection( api.Widgets.data.registeredSidebars );
  116. /**
  117. * wp.customize.Widgets.AvailableWidgetsPanelView
  118. *
  119. * View class for the available widgets panel.
  120. *
  121. * @constructor
  122. * @augments wp.Backbone.View
  123. * @augments Backbone.View
  124. */
  125. api.Widgets.AvailableWidgetsPanelView = wp.Backbone.View.extend({
  126. el: '#available-widgets',
  127. events: {
  128. 'input #widgets-search': 'search',
  129. 'keyup #widgets-search': 'search',
  130. 'focus .widget-tpl' : 'focus',
  131. 'click .widget-tpl' : '_submit',
  132. 'keypress .widget-tpl' : '_submit',
  133. 'keydown' : 'keyboardAccessible'
  134. },
  135. // Cache current selected widget
  136. selected: null,
  137. // Cache sidebar control which has opened panel
  138. currentSidebarControl: null,
  139. $search: null,
  140. $clearResults: null,
  141. searchMatchesCount: null,
  142. initialize: function() {
  143. var self = this;
  144. this.$search = $( '#widgets-search' );
  145. this.$clearResults = this.$el.find( '.clear-results' );
  146. _.bindAll( this, 'close' );
  147. this.listenTo( this.collection, 'change', this.updateList );
  148. this.updateList();
  149. // Set the initial search count to the number of available widgets.
  150. this.searchMatchesCount = this.collection.length;
  151. // If the available widgets panel is open and the customize controls are
  152. // interacted with (i.e. available widgets panel is blurred) then close the
  153. // available widgets panel. Also close on back button click.
  154. $( '#customize-controls, #available-widgets .customize-section-title' ).on( 'click keydown', function( e ) {
  155. var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' );
  156. if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) {
  157. self.close();
  158. }
  159. } );
  160. // Clear the search results and trigger a `keyup` event to fire a new search.
  161. this.$clearResults.on( 'click', function() {
  162. self.$search.val( '' ).focus().trigger( 'keyup' );
  163. } );
  164. // Close the panel if the URL in the preview changes
  165. api.previewer.bind( 'url', this.close );
  166. },
  167. // Performs a search and handles selected widget
  168. search: function( event ) {
  169. var firstVisible;
  170. this.collection.doSearch( event.target.value );
  171. // Update the search matches count.
  172. this.updateSearchMatchesCount();
  173. // Announce how many search results.
  174. this.announceSearchMatches();
  175. // Remove a widget from being selected if it is no longer visible
  176. if ( this.selected && ! this.selected.is( ':visible' ) ) {
  177. this.selected.removeClass( 'selected' );
  178. this.selected = null;
  179. }
  180. // If a widget was selected but the filter value has been cleared out, clear selection
  181. if ( this.selected && ! event.target.value ) {
  182. this.selected.removeClass( 'selected' );
  183. this.selected = null;
  184. }
  185. // If a filter has been entered and a widget hasn't been selected, select the first one shown
  186. if ( ! this.selected && event.target.value ) {
  187. firstVisible = this.$el.find( '> .widget-tpl:visible:first' );
  188. if ( firstVisible.length ) {
  189. this.select( firstVisible );
  190. }
  191. }
  192. // Toggle the clear search results button.
  193. if ( '' !== event.target.value ) {
  194. this.$clearResults.addClass( 'is-visible' );
  195. } else if ( '' === event.target.value ) {
  196. this.$clearResults.removeClass( 'is-visible' );
  197. }
  198. // Set a CSS class on the search container when there are no search results.
  199. if ( ! this.searchMatchesCount ) {
  200. this.$el.addClass( 'no-widgets-found' );
  201. } else {
  202. this.$el.removeClass( 'no-widgets-found' );
  203. }
  204. },
  205. // Update the count of the available widgets that have the `search_matched` attribute.
  206. updateSearchMatchesCount: function() {
  207. this.searchMatchesCount = this.collection.where({ search_matched: true }).length;
  208. },
  209. // Send a message to the aria-live region to announce how many search results.
  210. announceSearchMatches: _.debounce( function() {
  211. var message = l10n.widgetsFound.replace( '%d', this.searchMatchesCount ) ;
  212. if ( ! this.searchMatchesCount ) {
  213. message = l10n.noWidgetsFound;
  214. }
  215. wp.a11y.speak( message );
  216. }, 500 ),
  217. // Changes visibility of available widgets
  218. updateList: function() {
  219. this.collection.each( function( widget ) {
  220. var widgetTpl = $( '#widget-tpl-' + widget.id );
  221. widgetTpl.toggle( widget.get( 'search_matched' ) && ! widget.get( 'is_disabled' ) );
  222. if ( widget.get( 'is_disabled' ) && widgetTpl.is( this.selected ) ) {
  223. this.selected = null;
  224. }
  225. } );
  226. },
  227. // Highlights a widget
  228. select: function( widgetTpl ) {
  229. this.selected = $( widgetTpl );
  230. this.selected.siblings( '.widget-tpl' ).removeClass( 'selected' );
  231. this.selected.addClass( 'selected' );
  232. },
  233. // Highlights a widget on focus
  234. focus: function( event ) {
  235. this.select( $( event.currentTarget ) );
  236. },
  237. // Submit handler for keypress and click on widget
  238. _submit: function( event ) {
  239. // Only proceed with keypress if it is Enter or Spacebar
  240. if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
  241. return;
  242. }
  243. this.submit( $( event.currentTarget ) );
  244. },
  245. // Adds a selected widget to the sidebar
  246. submit: function( widgetTpl ) {
  247. var widgetId, widget, widgetFormControl;
  248. if ( ! widgetTpl ) {
  249. widgetTpl = this.selected;
  250. }
  251. if ( ! widgetTpl || ! this.currentSidebarControl ) {
  252. return;
  253. }
  254. this.select( widgetTpl );
  255. widgetId = $( this.selected ).data( 'widget-id' );
  256. widget = this.collection.findWhere( { id: widgetId } );
  257. if ( ! widget ) {
  258. return;
  259. }
  260. widgetFormControl = this.currentSidebarControl.addWidget( widget.get( 'id_base' ) );
  261. if ( widgetFormControl ) {
  262. widgetFormControl.focus();
  263. }
  264. this.close();
  265. },
  266. // Opens the panel
  267. open: function( sidebarControl ) {
  268. this.currentSidebarControl = sidebarControl;
  269. // Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens
  270. _( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) {
  271. if ( control.params.is_wide ) {
  272. control.collapseForm();
  273. }
  274. } );
  275. $( 'body' ).addClass( 'adding-widget' );
  276. this.$el.find( '.selected' ).removeClass( 'selected' );
  277. // Reset search
  278. this.collection.doSearch( '' );
  279. if ( ! api.settings.browser.mobile ) {
  280. this.$search.focus();
  281. }
  282. },
  283. // Closes the panel
  284. close: function( options ) {
  285. options = options || {};
  286. if ( options.returnFocus && this.currentSidebarControl ) {
  287. this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
  288. }
  289. this.currentSidebarControl = null;
  290. this.selected = null;
  291. $( 'body' ).removeClass( 'adding-widget' );
  292. this.$search.val( '' );
  293. },
  294. // Add keyboard accessiblity to the panel
  295. keyboardAccessible: function( event ) {
  296. var isEnter = ( event.which === 13 ),
  297. isEsc = ( event.which === 27 ),
  298. isDown = ( event.which === 40 ),
  299. isUp = ( event.which === 38 ),
  300. isTab = ( event.which === 9 ),
  301. isShift = ( event.shiftKey ),
  302. selected = null,
  303. firstVisible = this.$el.find( '> .widget-tpl:visible:first' ),
  304. lastVisible = this.$el.find( '> .widget-tpl:visible:last' ),
  305. isSearchFocused = $( event.target ).is( this.$search ),
  306. isLastWidgetFocused = $( event.target ).is( '.widget-tpl:visible:last' );
  307. if ( isDown || isUp ) {
  308. if ( isDown ) {
  309. if ( isSearchFocused ) {
  310. selected = firstVisible;
  311. } else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) {
  312. selected = this.selected.nextAll( '.widget-tpl:visible:first' );
  313. }
  314. } else if ( isUp ) {
  315. if ( isSearchFocused ) {
  316. selected = lastVisible;
  317. } else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) {
  318. selected = this.selected.prevAll( '.widget-tpl:visible:first' );
  319. }
  320. }
  321. this.select( selected );
  322. if ( selected ) {
  323. selected.focus();
  324. } else {
  325. this.$search.focus();
  326. }
  327. return;
  328. }
  329. // If enter pressed but nothing entered, don't do anything
  330. if ( isEnter && ! this.$search.val() ) {
  331. return;
  332. }
  333. if ( isEnter ) {
  334. this.submit();
  335. } else if ( isEsc ) {
  336. this.close( { returnFocus: true } );
  337. }
  338. if ( this.currentSidebarControl && isTab && ( isShift && isSearchFocused || ! isShift && isLastWidgetFocused ) ) {
  339. this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
  340. event.preventDefault();
  341. }
  342. }
  343. });
  344. /**
  345. * Handlers for the widget-synced event, organized by widget ID base.
  346. * Other widgets may provide their own update handlers by adding
  347. * listeners for the widget-synced event.
  348. */
  349. api.Widgets.formSyncHandlers = {
  350. /**
  351. * @param {jQuery.Event} e
  352. * @param {jQuery} widget
  353. * @param {String} newForm
  354. */
  355. rss: function( e, widget, newForm ) {
  356. var oldWidgetError = widget.find( '.widget-error:first' ),
  357. newWidgetError = $( '<div>' + newForm + '</div>' ).find( '.widget-error:first' );
  358. if ( oldWidgetError.length && newWidgetError.length ) {
  359. oldWidgetError.replaceWith( newWidgetError );
  360. } else if ( oldWidgetError.length ) {
  361. oldWidgetError.remove();
  362. } else if ( newWidgetError.length ) {
  363. widget.find( '.widget-content:first' ).prepend( newWidgetError );
  364. }
  365. }
  366. };
  367. /**
  368. * wp.customize.Widgets.WidgetControl
  369. *
  370. * Customizer control for widgets.
  371. * Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type
  372. *
  373. * @constructor
  374. * @augments wp.customize.Control
  375. */
  376. api.Widgets.WidgetControl = api.Control.extend({
  377. defaultExpandedArguments: {
  378. duration: 'fast',
  379. completeCallback: $.noop
  380. },
  381. /**
  382. * @since 4.1.0
  383. */
  384. initialize: function( id, options ) {
  385. var control = this;
  386. control.widgetControlEmbedded = false;
  387. control.widgetContentEmbedded = false;
  388. control.expanded = new api.Value( false );
  389. control.expandedArgumentsQueue = [];
  390. control.expanded.bind( function( expanded ) {
  391. var args = control.expandedArgumentsQueue.shift();
  392. args = $.extend( {}, control.defaultExpandedArguments, args );
  393. control.onChangeExpanded( expanded, args );
  394. });
  395. control.altNotice = true;
  396. api.Control.prototype.initialize.call( control, id, options );
  397. },
  398. /**
  399. * Set up the control.
  400. *
  401. * @since 3.9.0
  402. */
  403. ready: function() {
  404. var control = this;
  405. /*
  406. * Embed a placeholder once the section is expanded. The full widget
  407. * form content will be embedded once the control itself is expanded,
  408. * and at this point the widget-added event will be triggered.
  409. */
  410. if ( ! control.section() ) {
  411. control.embedWidgetControl();
  412. } else {
  413. api.section( control.section(), function( section ) {
  414. var onExpanded = function( isExpanded ) {
  415. if ( isExpanded ) {
  416. control.embedWidgetControl();
  417. section.expanded.unbind( onExpanded );
  418. }
  419. };
  420. if ( section.expanded() ) {
  421. onExpanded( true );
  422. } else {
  423. section.expanded.bind( onExpanded );
  424. }
  425. } );
  426. }
  427. },
  428. /**
  429. * Embed the .widget element inside the li container.
  430. *
  431. * @since 4.4.0
  432. */
  433. embedWidgetControl: function() {
  434. var control = this, widgetControl;
  435. if ( control.widgetControlEmbedded ) {
  436. return;
  437. }
  438. control.widgetControlEmbedded = true;
  439. widgetControl = $( control.params.widget_control );
  440. control.container.append( widgetControl );
  441. control._setupModel();
  442. control._setupWideWidget();
  443. control._setupControlToggle();
  444. control._setupWidgetTitle();
  445. control._setupReorderUI();
  446. control._setupHighlightEffects();
  447. control._setupUpdateUI();
  448. control._setupRemoveUI();
  449. },
  450. /**
  451. * Embed the actual widget form inside of .widget-content and finally trigger the widget-added event.
  452. *
  453. * @since 4.4.0
  454. */
  455. embedWidgetContent: function() {
  456. var control = this, widgetContent;
  457. control.embedWidgetControl();
  458. if ( control.widgetContentEmbedded ) {
  459. return;
  460. }
  461. control.widgetContentEmbedded = true;
  462. widgetContent = $( control.params.widget_content );
  463. control.container.find( '.widget-content:first' ).append( widgetContent );
  464. /*
  465. * Trigger widget-added event so that plugins can attach any event
  466. * listeners and dynamic UI elements.
  467. */
  468. $( document ).trigger( 'widget-added', [ control.container.find( '.widget:first' ) ] );
  469. },
  470. /**
  471. * Handle changes to the setting
  472. */
  473. _setupModel: function() {
  474. var self = this, rememberSavedWidgetId;
  475. // Remember saved widgets so we know which to trash (move to inactive widgets sidebar)
  476. rememberSavedWidgetId = function() {
  477. api.Widgets.savedWidgetIds[self.params.widget_id] = true;
  478. };
  479. api.bind( 'ready', rememberSavedWidgetId );
  480. api.bind( 'saved', rememberSavedWidgetId );
  481. this._updateCount = 0;
  482. this.isWidgetUpdating = false;
  483. this.liveUpdateMode = true;
  484. // Update widget whenever model changes
  485. this.setting.bind( function( to, from ) {
  486. if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) {
  487. self.updateWidget( { instance: to } );
  488. }
  489. } );
  490. },
  491. /**
  492. * Add special behaviors for wide widget controls
  493. */
  494. _setupWideWidget: function() {
  495. var self = this, $widgetInside, $widgetForm, $customizeSidebar,
  496. $themeControlsContainer, positionWidget;
  497. if ( ! this.params.is_wide ) {
  498. return;
  499. }
  500. $widgetInside = this.container.find( '.widget-inside' );
  501. $widgetForm = $widgetInside.find( '> .form' );
  502. $customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' );
  503. this.container.addClass( 'wide-widget-control' );
  504. this.container.find( '.widget-content:first' ).css( {
  505. 'max-width': this.params.width,
  506. 'min-height': this.params.height
  507. } );
  508. /**
  509. * Keep the widget-inside positioned so the top of fixed-positioned
  510. * element is at the same top position as the widget-top. When the
  511. * widget-top is scrolled out of view, keep the widget-top in view;
  512. * likewise, don't allow the widget to drop off the bottom of the window.
  513. * If a widget is too tall to fit in the window, don't let the height
  514. * exceed the window height so that the contents of the widget control
  515. * will become scrollable (overflow:auto).
  516. */
  517. positionWidget = function() {
  518. var offsetTop = self.container.offset().top,
  519. windowHeight = $( window ).height(),
  520. formHeight = $widgetForm.outerHeight(),
  521. top;
  522. $widgetInside.css( 'max-height', windowHeight );
  523. top = Math.max(
  524. 0, // prevent top from going off screen
  525. Math.min(
  526. Math.max( offsetTop, 0 ), // distance widget in panel is from top of screen
  527. windowHeight - formHeight // flush up against bottom of screen
  528. )
  529. );
  530. $widgetInside.css( 'top', top );
  531. };
  532. $themeControlsContainer = $( '#customize-theme-controls' );
  533. this.container.on( 'expand', function() {
  534. positionWidget();
  535. $customizeSidebar.on( 'scroll', positionWidget );
  536. $( window ).on( 'resize', positionWidget );
  537. $themeControlsContainer.on( 'expanded collapsed', positionWidget );
  538. } );
  539. this.container.on( 'collapsed', function() {
  540. $customizeSidebar.off( 'scroll', positionWidget );
  541. $( window ).off( 'resize', positionWidget );
  542. $themeControlsContainer.off( 'expanded collapsed', positionWidget );
  543. } );
  544. // Reposition whenever a sidebar's widgets are changed
  545. api.each( function( setting ) {
  546. if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) {
  547. setting.bind( function() {
  548. if ( self.container.hasClass( 'expanded' ) ) {
  549. positionWidget();
  550. }
  551. } );
  552. }
  553. } );
  554. },
  555. /**
  556. * Show/hide the control when clicking on the form title, when clicking
  557. * the close button
  558. */
  559. _setupControlToggle: function() {
  560. var self = this, $closeBtn;
  561. this.container.find( '.widget-top' ).on( 'click', function( e ) {
  562. e.preventDefault();
  563. var sidebarWidgetsControl = self.getSidebarWidgetsControl();
  564. if ( sidebarWidgetsControl.isReordering ) {
  565. return;
  566. }
  567. self.expanded( ! self.expanded() );
  568. } );
  569. $closeBtn = this.container.find( '.widget-control-close' );
  570. $closeBtn.on( 'click', function( e ) {
  571. e.preventDefault();
  572. self.collapse();
  573. self.container.find( '.widget-top .widget-action:first' ).focus(); // keyboard accessibility
  574. } );
  575. },
  576. /**
  577. * Update the title of the form if a title field is entered
  578. */
  579. _setupWidgetTitle: function() {
  580. var self = this, updateTitle;
  581. updateTitle = function() {
  582. var title = self.setting().title,
  583. inWidgetTitle = self.container.find( '.in-widget-title' );
  584. if ( title ) {
  585. inWidgetTitle.text( ': ' + title );
  586. } else {
  587. inWidgetTitle.text( '' );
  588. }
  589. };
  590. this.setting.bind( updateTitle );
  591. updateTitle();
  592. },
  593. /**
  594. * Set up the widget-reorder-nav
  595. */
  596. _setupReorderUI: function() {
  597. var self = this, selectSidebarItem, $moveWidgetArea,
  598. $reorderNav, updateAvailableSidebars, template;
  599. /**
  600. * select the provided sidebar list item in the move widget area
  601. *
  602. * @param {jQuery} li
  603. */
  604. selectSidebarItem = function( li ) {
  605. li.siblings( '.selected' ).removeClass( 'selected' );
  606. li.addClass( 'selected' );
  607. var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id );
  608. self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar );
  609. };
  610. /**
  611. * Add the widget reordering elements to the widget control
  612. */
  613. this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) );
  614. template = _.template( api.Widgets.data.tpl.moveWidgetArea );
  615. $moveWidgetArea = $( template( {
  616. sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' )
  617. } )
  618. );
  619. this.container.find( '.widget-top' ).after( $moveWidgetArea );
  620. /**
  621. * Update available sidebars when their rendered state changes
  622. */
  623. updateAvailableSidebars = function() {
  624. var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem,
  625. renderedSidebarCount = 0;
  626. selfSidebarItem = $sidebarItems.filter( function(){
  627. return $( this ).data( 'id' ) === self.params.sidebar_id;
  628. } );
  629. $sidebarItems.each( function() {
  630. var li = $( this ),
  631. sidebarId, sidebar, sidebarIsRendered;
  632. sidebarId = li.data( 'id' );
  633. sidebar = api.Widgets.registeredSidebars.get( sidebarId );
  634. sidebarIsRendered = sidebar.get( 'is_rendered' );
  635. li.toggle( sidebarIsRendered );
  636. if ( sidebarIsRendered ) {
  637. renderedSidebarCount += 1;
  638. }
  639. if ( li.hasClass( 'selected' ) && ! sidebarIsRendered ) {
  640. selectSidebarItem( selfSidebarItem );
  641. }
  642. } );
  643. if ( renderedSidebarCount > 1 ) {
  644. self.container.find( '.move-widget' ).show();
  645. } else {
  646. self.container.find( '.move-widget' ).hide();
  647. }
  648. };
  649. updateAvailableSidebars();
  650. api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars );
  651. /**
  652. * Handle clicks for up/down/move on the reorder nav
  653. */
  654. $reorderNav = this.container.find( '.widget-reorder-nav' );
  655. $reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() {
  656. $( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' );
  657. } ).on( 'click keypress', function( event ) {
  658. if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
  659. return;
  660. }
  661. $( this ).focus();
  662. if ( $( this ).is( '.move-widget' ) ) {
  663. self.toggleWidgetMoveArea();
  664. } else {
  665. var isMoveDown = $( this ).is( '.move-widget-down' ),
  666. isMoveUp = $( this ).is( '.move-widget-up' ),
  667. i = self.getWidgetSidebarPosition();
  668. if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) {
  669. return;
  670. }
  671. if ( isMoveUp ) {
  672. self.moveUp();
  673. wp.a11y.speak( l10n.widgetMovedUp );
  674. } else {
  675. self.moveDown();
  676. wp.a11y.speak( l10n.widgetMovedDown );
  677. }
  678. $( this ).focus(); // re-focus after the container was moved
  679. }
  680. } );
  681. /**
  682. * Handle selecting a sidebar to move to
  683. */
  684. this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( event ) {
  685. if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
  686. return;
  687. }
  688. event.preventDefault();
  689. selectSidebarItem( $( this ) );
  690. } );
  691. /**
  692. * Move widget to another sidebar
  693. */
  694. this.container.find( '.move-widget-btn' ).click( function() {
  695. self.getSidebarWidgetsControl().toggleReordering( false );
  696. var oldSidebarId = self.params.sidebar_id,
  697. newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ),
  698. oldSidebarWidgetsSetting, newSidebarWidgetsSetting,
  699. oldSidebarWidgetIds, newSidebarWidgetIds, i;
  700. oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' );
  701. newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' );
  702. oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() );
  703. newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() );
  704. i = self.getWidgetSidebarPosition();
  705. oldSidebarWidgetIds.splice( i, 1 );
  706. newSidebarWidgetIds.push( self.params.widget_id );
  707. oldSidebarWidgetsSetting( oldSidebarWidgetIds );
  708. newSidebarWidgetsSetting( newSidebarWidgetIds );
  709. self.focus();
  710. } );
  711. },
  712. /**
  713. * Highlight widgets in preview when interacted with in the Customizer
  714. */
  715. _setupHighlightEffects: function() {
  716. var self = this;
  717. // Highlight whenever hovering or clicking over the form
  718. this.container.on( 'mouseenter click', function() {
  719. self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
  720. } );
  721. // Highlight when the setting is updated
  722. this.setting.bind( function() {
  723. self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
  724. } );
  725. },
  726. /**
  727. * Set up event handlers for widget updating
  728. */
  729. _setupUpdateUI: function() {
  730. var self = this, $widgetRoot, $widgetContent,
  731. $saveBtn, updateWidgetDebounced, formSyncHandler;
  732. $widgetRoot = this.container.find( '.widget:first' );
  733. $widgetContent = $widgetRoot.find( '.widget-content:first' );
  734. // Configure update button
  735. $saveBtn = this.container.find( '.widget-control-save' );
  736. $saveBtn.val( l10n.saveBtnLabel );
  737. $saveBtn.attr( 'title', l10n.saveBtnTooltip );
  738. $saveBtn.removeClass( 'button-primary' );
  739. $saveBtn.on( 'click', function( e ) {
  740. e.preventDefault();
  741. self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
  742. } );
  743. updateWidgetDebounced = _.debounce( function() {
  744. self.updateWidget();
  745. }, 250 );
  746. // Trigger widget form update when hitting Enter within an input
  747. $widgetContent.on( 'keydown', 'input', function( e ) {
  748. if ( 13 === e.which ) { // Enter
  749. e.preventDefault();
  750. self.updateWidget( { ignoreActiveElement: true } );
  751. }
  752. } );
  753. // Handle widgets that support live previews
  754. $widgetContent.on( 'change input propertychange', ':input', function( e ) {
  755. if ( ! self.liveUpdateMode ) {
  756. return;
  757. }
  758. if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) {
  759. updateWidgetDebounced();
  760. }
  761. } );
  762. // Remove loading indicators when the setting is saved and the preview updates
  763. this.setting.previewer.channel.bind( 'synced', function() {
  764. self.container.removeClass( 'previewer-loading' );
  765. } );
  766. api.previewer.bind( 'widget-updated', function( updatedWidgetId ) {
  767. if ( updatedWidgetId === self.params.widget_id ) {
  768. self.container.removeClass( 'previewer-loading' );
  769. }
  770. } );
  771. formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
  772. if ( formSyncHandler ) {
  773. $( document ).on( 'widget-synced', function( e, widget ) {
  774. if ( $widgetRoot.is( widget ) ) {
  775. formSyncHandler.apply( document, arguments );
  776. }
  777. } );
  778. }
  779. },
  780. /**
  781. * Update widget control to indicate whether it is currently rendered.
  782. *
  783. * Overrides api.Control.toggle()
  784. *
  785. * @since 4.1.0
  786. *
  787. * @param {Boolean} active
  788. * @param {Object} args
  789. * @param {Callback} args.completeCallback
  790. */
  791. onChangeActive: function ( active, args ) {
  792. // Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments
  793. this.container.toggleClass( 'widget-rendered', active );
  794. if ( args.completeCallback ) {
  795. args.completeCallback();
  796. }
  797. },
  798. /**
  799. * Set up event handlers for widget removal
  800. */
  801. _setupRemoveUI: function() {
  802. var self = this, $removeBtn, replaceDeleteWithRemove;
  803. // Configure remove button
  804. $removeBtn = this.container.find( '.widget-control-remove' );
  805. $removeBtn.on( 'click', function( e ) {
  806. e.preventDefault();
  807. // Find an adjacent element to add focus to when this widget goes away
  808. var $adjacentFocusTarget;
  809. if ( self.container.next().is( '.customize-control-widget_form' ) ) {
  810. $adjacentFocusTarget = self.container.next().find( '.widget-action:first' );
  811. } else if ( self.container.prev().is( '.customize-control-widget_form' ) ) {
  812. $adjacentFocusTarget = self.container.prev().find( '.widget-action:first' );
  813. } else {
  814. $adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' );
  815. }
  816. self.container.slideUp( function() {
  817. var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
  818. sidebarWidgetIds, i;
  819. if ( ! sidebarsWidgetsControl ) {
  820. return;
  821. }
  822. sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
  823. i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
  824. if ( -1 === i ) {
  825. return;
  826. }
  827. sidebarWidgetIds.splice( i, 1 );
  828. sidebarsWidgetsControl.setting( sidebarWidgetIds );
  829. $adjacentFocusTarget.focus(); // keyboard accessibility
  830. } );
  831. } );
  832. replaceDeleteWithRemove = function() {
  833. $removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the button as "Delete"
  834. $removeBtn.attr( 'title', l10n.removeBtnTooltip );
  835. };
  836. if ( this.params.is_new ) {
  837. api.bind( 'saved', replaceDeleteWithRemove );
  838. } else {
  839. replaceDeleteWithRemove();
  840. }
  841. },
  842. /**
  843. * Find all inputs in a widget container that should be considered when
  844. * comparing the loaded form with the sanitized form, whose fields will
  845. * be aligned to copy the sanitized over. The elements returned by this
  846. * are passed into this._getInputsSignature(), and they are iterated
  847. * over when copying sanitized values over to the form loaded.
  848. *
  849. * @param {jQuery} container element in which to look for inputs
  850. * @returns {jQuery} inputs
  851. * @private
  852. */
  853. _getInputs: function( container ) {
  854. return $( container ).find( ':input[name]' );
  855. },
  856. /**
  857. * Iterate over supplied inputs and create a signature string for all of them together.
  858. * This string can be used to compare whether or not the form has all of the same fields.
  859. *
  860. * @param {jQuery} inputs
  861. * @returns {string}
  862. * @private
  863. */
  864. _getInputsSignature: function( inputs ) {
  865. var inputsSignatures = _( inputs ).map( function( input ) {
  866. var $input = $( input ), signatureParts;
  867. if ( $input.is( ':checkbox, :radio' ) ) {
  868. signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ];
  869. } else {
  870. signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ];
  871. }
  872. return signatureParts.join( ',' );
  873. } );
  874. return inputsSignatures.join( ';' );
  875. },
  876. /**
  877. * Get the state for an input depending on its type.
  878. *
  879. * @param {jQuery|Element} input
  880. * @returns {string|boolean|array|*}
  881. * @private
  882. */
  883. _getInputState: function( input ) {
  884. input = $( input );
  885. if ( input.is( ':radio, :checkbox' ) ) {
  886. return input.prop( 'checked' );
  887. } else if ( input.is( 'select[multiple]' ) ) {
  888. return input.find( 'option:selected' ).map( function () {
  889. return $( this ).val();
  890. } ).get();
  891. } else {
  892. return input.val();
  893. }
  894. },
  895. /**
  896. * Update an input's state based on its type.
  897. *
  898. * @param {jQuery|Element} input
  899. * @param {string|boolean|array|*} state
  900. * @private
  901. */
  902. _setInputState: function ( input, state ) {
  903. input = $( input );
  904. if ( input.is( ':radio, :checkbox' ) ) {
  905. input.prop( 'checked', state );
  906. } else if ( input.is( 'select[multiple]' ) ) {
  907. if ( ! $.isArray( state ) ) {
  908. state = [];
  909. } else {
  910. // Make sure all state items are strings since the DOM value is a string
  911. state = _.map( state, function ( value ) {
  912. return String( value );
  913. } );
  914. }
  915. input.find( 'option' ).each( function () {
  916. $( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) );
  917. } );
  918. } else {
  919. input.val( state );
  920. }
  921. },
  922. /***********************************************************************
  923. * Begin public API methods
  924. **********************************************************************/
  925. /**
  926. * @return {wp.customize.controlConstructor.sidebar_widgets[]}
  927. */
  928. getSidebarWidgetsControl: function() {
  929. var settingId, sidebarWidgetsControl;
  930. settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']';
  931. sidebarWidgetsControl = api.control( settingId );
  932. if ( ! sidebarWidgetsControl ) {
  933. return;
  934. }
  935. return sidebarWidgetsControl;
  936. },
  937. /**
  938. * Submit the widget form via Ajax and get back the updated instance,
  939. * along with the new widget control form to render.
  940. *
  941. * @param {object} [args]
  942. * @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used
  943. * @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.
  944. * @param {Boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
  945. */
  946. updateWidget: function( args ) {
  947. var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
  948. updateNumber, params, data, $inputs, processing, jqxhr, isChanged;
  949. // The updateWidget logic requires that the form fields to be fully present.
  950. self.embedWidgetContent();
  951. args = $.extend( {
  952. instance: null,
  953. complete: null,
  954. ignoreActiveElement: false
  955. }, args );
  956. instanceOverride = args.instance;
  957. completeCallback = args.complete;
  958. this._updateCount += 1;
  959. updateNumber = this._updateCount;
  960. $widgetRoot = this.container.find( '.widget:first' );
  961. $widgetContent = $widgetRoot.find( '.widget-content:first' );
  962. // Remove a previous error message
  963. $widgetContent.find( '.widget-error' ).remove();
  964. this.container.addClass( 'widget-form-loading' );
  965. this.container.addClass( 'previewer-loading' );
  966. processing = api.state( 'processing' );
  967. processing( processing() + 1 );
  968. if ( ! this.liveUpdateMode ) {
  969. this.container.addClass( 'widget-form-disabled' );
  970. }
  971. params = {};
  972. params.action = 'update-widget';
  973. params.wp_customize = 'on';
  974. params.nonce = api.settings.nonce['update-widget'];
  975. params.customize_theme = api.settings.theme.stylesheet;
  976. params.customized = wp.customize.previewer.query().customized;
  977. data = $.param( params );
  978. $inputs = this._getInputs( $widgetContent );
  979. // Store the value we're submitting in data so that when the response comes back,
  980. // we know if it got sanitized; if there is no difference in the sanitized value,
  981. // then we do not need to touch the UI and mess up the user's ongoing editing.
  982. $inputs.each( function() {
  983. $( this ).data( 'state' + updateNumber, self._getInputState( this ) );
  984. } );
  985. if ( instanceOverride ) {
  986. data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } );
  987. } else {
  988. data += '&' + $inputs.serialize();
  989. }
  990. data += '&' + $widgetContent.find( '~ :input' ).serialize();
  991. if ( this._previousUpdateRequest ) {
  992. this._previousUpdateRequest.abort();
  993. }
  994. jqxhr = $.post( wp.ajax.settings.url, data );
  995. this._previousUpdateRequest = jqxhr;
  996. jqxhr.done( function( r ) {
  997. var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse,
  998. isLiveUpdateAborted = false;
  999. // Check if the user is logged out.
  1000. if ( '0' === r ) {
  1001. api.previewer.preview.iframe.hide();
  1002. api.previewer.login().done( function() {
  1003. self.updateWidget( args );
  1004. api.previewer.preview.iframe.show();
  1005. } );
  1006. return;
  1007. }
  1008. // Check for cheaters.
  1009. if ( '-1' === r ) {
  1010. api.previewer.cheatin();
  1011. return;
  1012. }
  1013. if ( r.success ) {
  1014. sanitizedForm = $( '<div>' + r.data.form + '</div>' );
  1015. $sanitizedInputs = self._getInputs( sanitizedForm );
  1016. hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs );
  1017. // Restore live update mode if sanitized fields are now aligned with the existing fields
  1018. if ( hasSameInputsInResponse && ! self.liveUpdateMode ) {
  1019. self.liveUpdateMode = true;
  1020. self.container.removeClass( 'widget-form-disabled' );
  1021. self.container.find( 'input[name="savewidget"]' ).hide();
  1022. }
  1023. // Sync sanitized field states to existing fields if they are aligned
  1024. if ( hasSameInputsInResponse && self.liveUpdateMode ) {
  1025. $inputs.each( function( i ) {
  1026. var $input = $( this ),
  1027. $sanitizedInput = $( $sanitizedInputs[i] ),
  1028. submittedState, sanitizedState, canUpdateState;
  1029. submittedState = $input.data( 'state' + updateNumber );
  1030. sanitizedState = self._getInputState( $sanitizedInput );
  1031. $input.data( 'sanitized', sanitizedState );
  1032. canUpdateState = ( ! _.isEqual( submittedState, sanitizedState ) && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
  1033. if ( canUpdateState ) {
  1034. self._setInputState( $input, sanitizedState );
  1035. }
  1036. } );
  1037. $( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] );
  1038. // Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled
  1039. } else if ( self.liveUpdateMode ) {
  1040. self.liveUpdateMode = false;
  1041. self.container.find( 'input[name="savewidget"]' ).show();
  1042. isLiveUpdateAborted = true;
  1043. // Otherwise, replace existing form with the sanitized form
  1044. } else {
  1045. $widgetContent.html( r.data.form );
  1046. self.container.removeClass( 'widget-form-disabled' );
  1047. $( document ).trigger( 'widget-updated', [ $widgetRoot ] );
  1048. }
  1049. /**
  1050. * If the old instance is identical to the new one, there is nothing new
  1051. * needing to be rendered, and so we can preempt the event for the
  1052. * preview finishing loading.
  1053. */
  1054. isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance );
  1055. if ( isChanged ) {
  1056. self.isWidgetUpdating = true; // suppress triggering another updateWidget
  1057. self.setting( r.data.instance );
  1058. self.isWidgetUpdating = false;
  1059. } else {
  1060. // no change was made, so stop the spinner now instead of when the preview would updates
  1061. self.container.removeClass( 'previewer-loading' );
  1062. }
  1063. if ( completeCallback ) {
  1064. completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
  1065. }
  1066. } else {
  1067. // General error message
  1068. message = l10n.error;
  1069. if ( r.data && r.data.message ) {
  1070. message = r.data.message;
  1071. }
  1072. if ( completeCallback ) {
  1073. completeCallback.call( self, message );
  1074. } else {
  1075. $widgetContent.prepend( '<p class="widget-error"><strong>' + message + '</strong></p>' );
  1076. }
  1077. }
  1078. } );
  1079. jqxhr.fail( function( jqXHR, textStatus ) {
  1080. if ( completeCallback ) {
  1081. completeCallback.call( self, textStatus );
  1082. }
  1083. } );
  1084. jqxhr.always( function() {
  1085. self.container.removeClass( 'widget-form-loading' );
  1086. $inputs.each( function() {
  1087. $( this ).removeData( 'state' + updateNumber );
  1088. } );
  1089. processing( processing() - 1 );
  1090. } );
  1091. },
  1092. /**
  1093. * Expand the accordion section containing a control
  1094. */
  1095. expandControlSection: function() {
  1096. api.Control.prototype.expand.call( this );
  1097. },
  1098. /**
  1099. * @since 4.1.0
  1100. *
  1101. * @param {Boolean} expanded
  1102. * @param {Object} [params]
  1103. * @returns {Boolean} false if state already applied
  1104. */
  1105. _toggleExpanded: api.Section.prototype._toggleExpanded,
  1106. /**
  1107. * @since 4.1.0
  1108. *
  1109. * @param {Object} [params]
  1110. * @returns {Boolean} false if already expanded
  1111. */
  1112. expand: api.Section.prototype.expand,
  1113. /**
  1114. * Expand the widget form control
  1115. *
  1116. * @deprecated 4.1.0 Use this.expand() instead.
  1117. */
  1118. expandForm: function() {
  1119. this.expand();
  1120. },
  1121. /**
  1122. * @since 4.1.0
  1123. *
  1124. * @param {Object} [params]
  1125. * @returns {Boolean} false if already collapsed
  1126. */
  1127. collapse: api.Section.prototype.collapse,
  1128. /**
  1129. * Collapse the widget form control
  1130. *
  1131. * @deprecated 4.1.0 Use this.collapse() instead.
  1132. */
  1133. collapseForm: function() {
  1134. this.collapse();
  1135. },
  1136. /**
  1137. * Expand or collapse the widget control
  1138. *
  1139. * @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
  1140. *
  1141. * @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility
  1142. */
  1143. toggleForm: function( showOrHide ) {
  1144. if ( typeof showOrHide === 'undefined' ) {
  1145. showOrHide = ! this.expanded();
  1146. }
  1147. this.expanded( showOrHide );
  1148. },
  1149. /**
  1150. * Respond to change in the expanded state.
  1151. *
  1152. * @param {Boolean} expanded
  1153. * @param {Object} args merged on top of this.defaultActiveArguments
  1154. */
  1155. onChangeExpanded: function ( expanded, args ) {
  1156. var self = this, $widget, $inside, complete, prevComplete, expandControl, $toggleBtn;
  1157. self.embedWidgetControl(); // Make sure the outer form is embedded so that the expanded state can be set in the UI.
  1158. if ( expanded ) {
  1159. self.embedWidgetContent();
  1160. }
  1161. // If the expanded state is unchanged only manipulate container expanded states
  1162. if ( args.unchanged ) {
  1163. if ( expanded ) {
  1164. api.Control.prototype.expand.call( self, {
  1165. completeCallback: args.completeCallback
  1166. });
  1167. }
  1168. return;
  1169. }
  1170. $widget = this.container.find( 'div.widget:first' );
  1171. $inside = $widget.find( '.widget-inside:first' );
  1172. $toggleBtn = this.container.find( '.widget-top button.widget-action' );
  1173. expandControl = function() {
  1174. // Close all other widget controls before expanding this one
  1175. api.control.each( function( otherControl ) {
  1176. if ( self.params.type === otherControl.params.type && self !== otherControl ) {
  1177. otherControl.collapse();
  1178. }
  1179. } );
  1180. complete = function() {
  1181. self.container.removeClass( 'expanding' );
  1182. self.container.addClass( 'expanded' );
  1183. $toggleBtn.attr( 'aria-expanded', 'true' );
  1184. self.container.trigger( 'expanded' );
  1185. };
  1186. if ( args.completeCallback ) {
  1187. prevComplete = complete;
  1188. complete = function () {
  1189. prevComplete();
  1190. args.completeCallback();
  1191. };
  1192. }
  1193. if ( self.params.is_wide ) {
  1194. $inside.fadeIn( args.duration, complete );
  1195. } else {
  1196. $inside.slideDown( args.duration, complete );
  1197. }
  1198. self.container.trigger( 'expand' );
  1199. self.container.addClass( 'expanding' );
  1200. };
  1201. if ( expanded ) {
  1202. if ( api.section.has( self.section() ) ) {
  1203. api.section( self.section() ).expand( {
  1204. completeCallback: expandControl
  1205. } );
  1206. } else {
  1207. expandControl();
  1208. }
  1209. } else {
  1210. complete = function() {
  1211. self.container.removeClass( 'collapsing' );
  1212. self.container.removeClass( 'expanded' );
  1213. $toggleBtn.attr( 'aria-expanded', 'false' );
  1214. self.container.trigger( 'collapsed' );
  1215. };
  1216. if ( args.completeCallback ) {
  1217. prevComplete = complete;
  1218. complete = function () {
  1219. prevComplete();
  1220. args.completeCallback();
  1221. };
  1222. }
  1223. self.container.trigger( 'collapse' );
  1224. self.container.addClass( 'collapsing' );
  1225. if ( self.params.is_wide ) {
  1226. $inside.fadeOut( args.duration, complete );
  1227. } else {
  1228. $inside.slideUp( args.duration, function() {
  1229. $widget.css( { width:'', margin:'' } );
  1230. complete();
  1231. } );
  1232. }
  1233. }
  1234. },
  1235. /**
  1236. * Get the position (index) of the widget in the containing sidebar
  1237. *
  1238. * @returns {Number}
  1239. */
  1240. getWidgetSidebarPosition: function() {
  1241. var sidebarWidgetIds, position;
  1242. sidebarWidgetIds = this.getSidebarWidgetsControl().setting();
  1243. position = _.indexOf( sidebarWidgetIds, this.params.widget_id );
  1244. if ( position === -1 ) {
  1245. return;
  1246. }
  1247. return position;
  1248. },
  1249. /**
  1250. * Move widget up one in the sidebar
  1251. */
  1252. moveUp: function() {
  1253. this._moveWidgetByOne( -1 );
  1254. },
  1255. /**
  1256. * Move widget up one in the sidebar
  1257. */
  1258. moveDown: function() {
  1259. this._moveWidgetByOne( 1 );
  1260. },
  1261. /**
  1262. * @private
  1263. *
  1264. * @param {Number} offset 1|-1
  1265. */
  1266. _moveWidgetByOne: function( offset ) {
  1267. var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId;
  1268. i = this.getWidgetSidebarPosition();
  1269. sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting;
  1270. sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // clone
  1271. adjacentWidgetId = sidebarWidgetIds[i + offset];
  1272. sidebarWidgetIds[i + offset] = this.params.widget_id;
  1273. sidebarWidgetIds[i] = adjacentWidgetId;
  1274. sidebarWidgetsSetting( sidebarWidgetIds );
  1275. },
  1276. /**
  1277. * Toggle visibility of the widget move area
  1278. *
  1279. * @param {Boolean} [showOrHide]
  1280. */
  1281. toggleWidgetMoveArea: function( showOrHide ) {
  1282. var self = this, $moveWidgetArea;
  1283. $moveWidgetArea = this.container.find( '.move-widget-area' );
  1284. if ( typeof showOrHide === 'undefined' ) {
  1285. showOrHide = ! $moveWidgetArea.hasClass( 'active' );
  1286. }
  1287. if ( showOrHide ) {
  1288. // reset the selected sidebar
  1289. $moveWidgetArea.find( '.selected' ).removeClass( 'selected' );
  1290. $moveWidgetArea.find( 'li' ).filter( function() {
  1291. return $( this ).data( 'id' ) === self.params.sidebar_id;
  1292. } ).addClass( 'selected' );
  1293. this.container.find( '.move-widget-btn' ).prop( 'disabled', true );
  1294. }
  1295. $moveWidgetArea.toggleClass( 'active', showOrHide );
  1296. },
  1297. /**
  1298. * Highlight the widget control and section
  1299. */
  1300. highlightSectionAndControl: function() {
  1301. var $target;
  1302. if ( this.container.is( ':hidden' ) ) {
  1303. $target = this.container.closest( '.control-section' );
  1304. } else {
  1305. $target = this.container;
  1306. }
  1307. $( '.highlighted' ).removeClass( 'highlighted' );
  1308. $target.addClass( 'highlighted' );
  1309. setTimeout( function() {
  1310. $target.removeClass( 'highlighted' );
  1311. }, 500 );
  1312. }
  1313. } );
  1314. /**
  1315. * wp.customize.Widgets.WidgetsPanel
  1316. *
  1317. * Customizer panel containing the widget area sections.
  1318. *
  1319. * @since 4.4.0
  1320. */
  1321. api.Widgets.WidgetsPanel = api.Panel.extend({
  1322. /**
  1323. * Add and manage the display of the no-rendered-areas notice.
  1324. *
  1325. * @since 4.4.0
  1326. */
  1327. ready: function () {
  1328. var panel = this;
  1329. api.Panel.prototype.ready.call( panel );
  1330. panel.deferred.embedded.done(function() {
  1331. var panelMetaContainer, noticeContainer, updateNotice, getActiveSectionCount, shouldShowNotice;
  1332. panelMetaContainer = panel.container.find( '.panel-meta' );
  1333. // @todo This should use the Notifications API introduced to panels. See <https://core.trac.wordpress.org/ticket/38794>.
  1334. noticeContainer = $( '<div></div>', {
  1335. 'class': 'no-widget-areas-rendered-notice'
  1336. });
  1337. panelMetaContainer.append( noticeContainer );
  1338. /**
  1339. * Get the number of active sections in the panel.
  1340. *
  1341. * @return {number} Number of active sidebar sections.
  1342. */
  1343. getActiveSectionCount = function() {
  1344. return _.filter( panel.sections(), function( section ) {
  1345. return section.active();
  1346. } ).length;
  1347. };
  1348. /**
  1349. * Determine whether or not the notice should be displayed.
  1350. *
  1351. * @return {boolean}
  1352. */
  1353. shouldShowNotice = function() {
  1354. var activeSectionCount = getActiveSectionCount();
  1355. if ( 0 === activeSectionCount ) {
  1356. return true;
  1357. } else {
  1358. return activeSectionCount !== api.Widgets.data.registeredSidebars.length;
  1359. }
  1360. };
  1361. /**
  1362. * Update the notice.
  1363. *
  1364. * @returns {void}
  1365. */
  1366. updateNotice = function() {
  1367. var activeSectionCount = getActiveSectionCount(), someRenderedMessage, nonRenderedAreaCount, registeredAreaCount;
  1368. noticeContainer.empty();
  1369. registeredAreaCount = api.Widgets.data.registeredSidebars.length;
  1370. if ( activeSectionCount !== registeredAreaCount ) {
  1371. if ( 0 !== activeSectionCount ) {
  1372. nonRenderedAreaCount = registeredAreaCount - activeSectionCount;
  1373. someRenderedMessage = l10n.someAreasShown[ nonRenderedAreaCount ];
  1374. } else {
  1375. someRenderedMessage = l10n.noAreasShown;
  1376. }
  1377. if ( someRenderedMessage ) {
  1378. noticeContainer.append( $( '<p></p>', {
  1379. text: someRenderedMessage
  1380. } ) );
  1381. }
  1382. noticeContainer.append( $( '<p></p>', {
  1383. text: l10n.navigatePreview
  1384. } ) );
  1385. }
  1386. };
  1387. updateNotice();
  1388. /*
  1389. * Set the initial visibility state for rendered notice.
  1390. * Update the visibility of the notice whenever a reflow happens.
  1391. */
  1392. noticeContainer.toggle( shouldShowNotice() );
  1393. api.previewer.deferred.active.done( function () {
  1394. noticeContainer.toggle( shouldShowNotice() );
  1395. });
  1396. api.bind( 'pane-contents-reflowed', function() {
  1397. var duration = ( 'resolved' === api.previewer.deferred.active.state() ) ? 'fast' : 0;
  1398. updateNotice();
  1399. if ( shouldShowNotice() ) {
  1400. noticeContainer.slideDown( duration );
  1401. } else {
  1402. noticeContainer.slideUp( duration );
  1403. }
  1404. });
  1405. });
  1406. },
  1407. /**
  1408. * Allow an active widgets panel to be contextually active even when it has no active sections (widget areas).
  1409. *
  1410. * This ensures that the widgets panel appears even when there are no
  1411. * sidebars displayed on the URL currently being previewed.
  1412. *
  1413. * @since 4.4.0
  1414. *
  1415. * @returns {boolean}
  1416. */
  1417. isContextuallyActive: function() {
  1418. var panel = this;
  1419. return panel.active();
  1420. }
  1421. });
  1422. /**
  1423. * wp.customize.Widgets.SidebarSection
  1424. *
  1425. * Customizer section representing a widget area widget
  1426. *
  1427. * @since 4.1.0
  1428. */
  1429. api.Widgets.SidebarSection = api.Section.extend({
  1430. /**
  1431. * Sync the section's active state back to the Backbone model's is_rendered attribute
  1432. *
  1433. * @since 4.1.0
  1434. */
  1435. ready: function () {
  1436. var section = this, registeredSidebar;
  1437. api.Section.prototype.ready.call( this );
  1438. registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId );
  1439. section.active.bind( function ( active ) {
  1440. registeredSidebar.set( 'is_rendered', active );
  1441. });
  1442. registeredSidebar.set( 'is_rendered', section.active() );
  1443. }
  1444. });
  1445. /**
  1446. * wp.customize.Widgets.SidebarControl
  1447. *
  1448. * Customizer control for widgets.
  1449. * Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type
  1450. *
  1451. * @since 3.9.0
  1452. *
  1453. * @constructor
  1454. * @augments wp.customize.Control
  1455. */
  1456. api.Widgets.SidebarControl = api.Control.extend({
  1457. /**
  1458. * Set up the control
  1459. */
  1460. ready: function() {
  1461. this.$controlSection = this.container.closest( '.control-section' );
  1462. this.$sectionContent = this.container.closest( '.accordion-section-content' );
  1463. this._setupModel();
  1464. this._setupSortable();
  1465. this._setupAddition();
  1466. this._applyCardinalOrderClassNames();
  1467. },
  1468. /**
  1469. * Update ordering of widget control forms when the setting is updated
  1470. */
  1471. _setupModel: function() {
  1472. var self = this;
  1473. this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
  1474. var widgetFormControls, removedWidgetIds, priority;
  1475. removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );
  1476. // Filter out any persistent widget IDs for widgets which have been deactivated
  1477. newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
  1478. var parsedWidgetId = parseWidgetId( newWidgetId );
  1479. return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
  1480. } );
  1481. widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
  1482. var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
  1483. if ( ! widgetFormControl ) {
  1484. widgetFormControl = self.addWidget( widgetId );
  1485. }
  1486. return widgetFormControl;
  1487. } );
  1488. // Sort widget controls to their new positions
  1489. widgetFormControls.sort( function( a, b ) {
  1490. var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
  1491. bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
  1492. return aIndex - bIndex;
  1493. });
  1494. priority = 0;
  1495. _( widgetFormControls ).each( function ( control ) {
  1496. control.priority( priority );
  1497. control.section( self.section() );
  1498. priority += 1;
  1499. });
  1500. self.priority( priority ); // Make sure sidebar control remains at end
  1501. // Re-sort widget form controls (including widgets form other sidebars newly moved here)
  1502. self._applyCardinalOrderClassNames();
  1503. // If the widget was dragged into the sidebar, make sure the sidebar_id param is updated
  1504. _( widgetFormControls ).each( function( widgetFormControl ) {
  1505. widgetFormControl.params.sidebar_id = self.params.sidebar_id;
  1506. } );
  1507. // Cleanup after widget removal
  1508. _( removedWidgetIds ).each( function( removedWidgetId ) {
  1509. // Using setTimeout so that when moving a widget to another sidebar, the other sidebars_widgets settings get a chance to update
  1510. setTimeout( function() {
  1511. var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
  1512. widget, isPresentInAnotherSidebar = false;
  1513. // Check if the widget is in another sidebar
  1514. api.each( function( otherSetting ) {
  1515. if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) {
  1516. return;
  1517. }
  1518. var otherSidebarWidgets = otherSetting(), i;
  1519. i = _.indexOf( otherSidebarWidgets, removedWidgetId );
  1520. if ( -1 !== i ) {
  1521. isPresentInAnotherSidebar = true;
  1522. }
  1523. } );
  1524. // If the widget is present in another sidebar, abort!
  1525. if ( isPresentInAnotherSidebar ) {
  1526. return;
  1527. }
  1528. removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );
  1529. // Detect if widget control was dragged to another sidebar
  1530. wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
  1531. // Delete any widget form controls for removed widgets
  1532. if ( removedControl && ! wasDraggedToAnotherSidebar ) {
  1533. api.control.remove( removedControl.id );
  1534. removedControl.container.remove();
  1535. }
  1536. // Move widget to inactive widgets sidebar (move it to trash) if has been previously saved
  1537. // This prevents the inactive widgets sidebar from overflowing with throwaway widgets
  1538. if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
  1539. inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice();
  1540. inactiveWidgets.push( removedWidgetId );
  1541. api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() );
  1542. }
  1543. // Make old single widget available for adding again
  1544. removedIdBase = parseWidgetId( removedWidgetId ).id_base;
  1545. widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
  1546. if ( widget && ! widget.get( 'is_multi' ) ) {
  1547. widget.set( 'is_disabled', false );
  1548. }
  1549. } );
  1550. } );
  1551. } );
  1552. },
  1553. /**
  1554. * Allow widgets in sidebar to be re-ordered, and for the order to be previewed
  1555. */
  1556. _setupSortable: function() {
  1557. var self = this;
  1558. this.isReordering = false;
  1559. /**
  1560. * Update widget order setting when controls are re-ordered
  1561. */
  1562. this.$sectionContent.sortable( {
  1563. items: '> .customize-control-widget_form',
  1564. handle: '.widget-top',
  1565. axis: 'y',
  1566. tolerance: 'pointer',
  1567. connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
  1568. update: function() {
  1569. var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
  1570. widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
  1571. return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
  1572. } );
  1573. self.setting( widgetIds );
  1574. }
  1575. } );
  1576. /**
  1577. * Expand other Customizer sidebar section when dragging a control widget over it,
  1578. * allowing the control to be dropped into another section
  1579. */
  1580. this.$controlSection.find( '.accordion-section-title' ).droppable({
  1581. accept: '.customize-control-widget_form',
  1582. over: function() {
  1583. var section = api.section( self.section.get() );
  1584. section.expand({
  1585. allowMultiple: true, // Prevent the section being dragged from to be collapsed
  1586. completeCallback: function () {
  1587. // @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed
  1588. api.section.each( function ( otherSection ) {
  1589. if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) {
  1590. otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' );
  1591. }
  1592. } );
  1593. }
  1594. });
  1595. }
  1596. });
  1597. /**
  1598. * Keyboard-accessible reordering
  1599. */
  1600. this.container.find( '.reorder-toggle' ).on( 'click', function() {
  1601. self.toggleReordering( ! self.isReordering );
  1602. } );
  1603. },
  1604. /**
  1605. * Set up UI for adding a new widget
  1606. */
  1607. _setupAddition: function() {
  1608. var self = this;
  1609. this.container.find( '.add-new-widget' ).on( 'click', function() {
  1610. var addNewWidgetBtn = $( this );
  1611. if ( self.$sectionContent.hasClass( 'reordering' ) ) {
  1612. return;
  1613. }
  1614. if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
  1615. addNewWidgetBtn.attr( 'aria-expanded', 'true' );
  1616. api.Widgets.availableWidgetsPanel.open( self );
  1617. } else {
  1618. addNewWidgetBtn.attr( 'aria-expanded', 'false' );
  1619. api.Widgets.availableWidgetsPanel.close();
  1620. }
  1621. } );
  1622. },
  1623. /**
  1624. * Add classes to the widget_form controls to assist with styling
  1625. */
  1626. _applyCardinalOrderClassNames: function() {
  1627. var widgetControls = [];
  1628. _.each( this.setting(), function ( widgetId ) {
  1629. var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
  1630. if ( widgetControl ) {
  1631. widgetControls.push( widgetControl );
  1632. }
  1633. });
  1634. if ( 0 === widgetControls.length || ( 1 === api.Widgets.registeredSidebars.length && widgetControls.length <= 1 ) ) {
  1635. this.container.find( '.reorder-toggle' ).hide();
  1636. return;
  1637. } else {
  1638. this.container.find( '.reorder-toggle' ).show();
  1639. }
  1640. $( widgetControls ).each( function () {
  1641. $( this.container )
  1642. .removeClass( 'first-widget' )
  1643. .removeClass( 'last-widget' )
  1644. .find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
  1645. });
  1646. _.first( widgetControls ).container
  1647. .addClass( 'first-widget' )
  1648. .find( '.move-widget-up' ).prop( 'tabIndex', -1 );
  1649. _.last( widgetControls ).container
  1650. .addClass( 'last-widget' )
  1651. .find( '.move-widget-down' ).prop( 'tabIndex', -1 );
  1652. },
  1653. /***********************************************************************
  1654. * Begin public API methods
  1655. **********************************************************************/
  1656. /**
  1657. * Enable/disable the reordering UI
  1658. *
  1659. * @param {Boolean} showOrHide to enable/disable reordering
  1660. *
  1661. * @todo We should have a reordering state instead and rename this to onChangeReordering
  1662. */
  1663. toggleReordering: function( showOrHide ) {
  1664. var addNewWidgetBtn = this.$sectionContent.find( '.add-new-widget' ),
  1665. reorderBtn = this.container.find( '.reorder-toggle' ),
  1666. widgetsTitle = this.$sectionContent.find( '.widget-title' );
  1667. showOrHide = Boolean( showOrHide );
  1668. if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
  1669. return;
  1670. }
  1671. this.isReordering = showOrHide;
  1672. this.$sectionContent.toggleClass( 'reordering', showOrHide );
  1673. if ( showOrHide ) {
  1674. _( this.getWidgetFormControls() ).each( function( formControl ) {
  1675. formControl.collapse();
  1676. } );
  1677. addNewWidgetBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
  1678. reorderBtn.attr( 'aria-label', l10n.reorderLabelOff );
  1679. wp.a11y.speak( l10n.reorderModeOn );
  1680. // Hide widget titles while reordering: title is already in the reorder controls.
  1681. widgetsTitle.attr( 'aria-hidden', 'true' );
  1682. } else {
  1683. addNewWidgetBtn.removeAttr( 'tabindex aria-hidden' );
  1684. reorderBtn.attr( 'aria-label', l10n.reorderLabelOn );
  1685. wp.a11y.speak( l10n.reorderModeOff );
  1686. widgetsTitle.attr( 'aria-hidden', 'false' );
  1687. }
  1688. },
  1689. /**
  1690. * Get the widget_form Customize controls associated with the current sidebar.
  1691. *
  1692. * @since 3.9.0
  1693. * @return {wp.customize.controlConstructor.widget_form[]}
  1694. */
  1695. getWidgetFormControls: function() {
  1696. var formControls = [];
  1697. _( this.setting() ).each( function( widgetId ) {
  1698. var settingId = widgetIdToSettingId( widgetId ),
  1699. formControl = api.control( settingId );
  1700. if ( formControl ) {
  1701. formControls.push( formControl );
  1702. }
  1703. } );
  1704. return formControls;
  1705. },
  1706. /**
  1707. * @param {string} widgetId or an id_base for adding a previously non-existing widget
  1708. * @returns {object|false} widget_form control instance, or false on error
  1709. */
  1710. addWidget: function( widgetId ) {
  1711. var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor,
  1712. parsedWidgetId = parseWidgetId( widgetId ),
  1713. widgetNumber = parsedWidgetId.number,
  1714. widgetIdBase = parsedWidgetId.id_base,
  1715. widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
  1716. settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting;
  1717. if ( ! widget ) {
  1718. return false;
  1719. }
  1720. if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
  1721. return false;
  1722. }
  1723. // Set up new multi widget
  1724. if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
  1725. widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
  1726. widgetNumber = widget.get( 'multi_number' );
  1727. }
  1728. controlHtml = $.trim( $( '#widget-tpl-' + widget.get( 'id' ) ).html() );
  1729. if ( widget.get( 'is_multi' ) ) {
  1730. controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
  1731. return m.replace( /__i__|%i%/g, widgetNumber );
  1732. } );
  1733. } else {
  1734. widget.set( 'is_disabled', true ); // Prevent single widget from being added again now
  1735. }
  1736. $widget = $( controlHtml );
  1737. controlContainer = $( '<li/>' )
  1738. .addClass( 'customize-control' )
  1739. .addClass( 'customize-control-' + controlType )
  1740. .append( $widget );
  1741. // Remove icon which is visible inside the panel
  1742. controlContainer.find( '> .widget-icon' ).remove();
  1743. if ( widget.get( 'is_multi' ) ) {
  1744. controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber );
  1745. controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber );
  1746. }
  1747. widgetId = controlContainer.find( '[name="widget-id"]' ).val();
  1748. controlContainer.hide(); // to be slid-down below
  1749. settingId = 'widget_' + widget.get( 'id_base' );
  1750. if ( widget.get( 'is_multi' ) ) {
  1751. settingId += '[' + widgetNumber + ']';
  1752. }
  1753. controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );
  1754. // Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget)
  1755. isExistingWidget = api.has( settingId );
  1756. if ( ! isExistingWidget ) {
  1757. settingArgs = {
  1758. transport: api.Widgets.data.selectiveRefreshableWidgets[ widget.get( 'id_base' ) ] ? 'postMessage' : 'refresh',
  1759. previewer: this.setting.previewer
  1760. };
  1761. setting = api.create( settingId, settingId, '', settingArgs );
  1762. setting.set( {} ); // mark dirty, changing from '' to {}
  1763. }
  1764. controlConstructor = api.controlConstructor[controlType];
  1765. widgetFormControl = new controlConstructor( settingId, {
  1766. params: {
  1767. settings: {
  1768. 'default': settingId
  1769. },
  1770. content: controlContainer,
  1771. sidebar_id: self.params.sidebar_id,
  1772. widget_id: widgetId,
  1773. widget_id_base: widget.get( 'id_base' ),
  1774. type: controlType,
  1775. is_new: ! isExistingWidget,
  1776. width: widget.get( 'width' ),
  1777. height: widget.get( 'height' ),
  1778. is_wide: widget.get( 'is_wide' ),
  1779. active: true
  1780. },
  1781. previewer: self.setting.previewer
  1782. } );
  1783. api.control.add( settingId, widgetFormControl );
  1784. // Make sure widget is removed from the other sidebars
  1785. api.each( function( otherSetting ) {
  1786. if ( otherSetting.id === self.setting.id ) {
  1787. return;
  1788. }
  1789. if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
  1790. return;
  1791. }
  1792. var otherSidebarWidgets = otherSetting().slice(),
  1793. i = _.indexOf( otherSidebarWidgets, widgetId );
  1794. if ( -1 !== i ) {
  1795. otherSidebarWidgets.splice( i );
  1796. otherSetting( otherSidebarWidgets );
  1797. }
  1798. } );
  1799. // Add widget to this sidebar
  1800. sidebarWidgets = this.setting().slice();
  1801. if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
  1802. sidebarWidgets.push( widgetId );
  1803. this.setting( sidebarWidgets );
  1804. }
  1805. controlContainer.slideDown( function() {
  1806. if ( isExistingWidget ) {
  1807. widgetFormControl.updateWidget( {
  1808. instance: widgetFormControl.setting()
  1809. } );
  1810. }
  1811. } );
  1812. return widgetFormControl;
  1813. }
  1814. } );
  1815. // Register models for custom panel, section, and control types
  1816. $.extend( api.panelConstructor, {
  1817. widgets: api.Widgets.WidgetsPanel
  1818. });
  1819. $.extend( api.sectionConstructor, {
  1820. sidebar: api.Widgets.SidebarSection
  1821. });
  1822. $.extend( api.controlConstructor, {
  1823. widget_form: api.Widgets.WidgetControl,
  1824. sidebar_widgets: api.Widgets.SidebarControl
  1825. });
  1826. /**
  1827. * Init Customizer for widgets.
  1828. */
  1829. api.bind( 'ready', function() {
  1830. // Set up the widgets panel
  1831. api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
  1832. collection: api.Widgets.availableWidgets
  1833. });
  1834. // Highlight widget control
  1835. api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
  1836. // Open and focus widget control
  1837. api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
  1838. } );
  1839. /**
  1840. * Highlight a widget control.
  1841. *
  1842. * @param {string} widgetId
  1843. */
  1844. api.Widgets.highlightWidgetFormControl = function( widgetId ) {
  1845. var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
  1846. if ( control ) {
  1847. control.highlightSectionAndControl();
  1848. }
  1849. },
  1850. /**
  1851. * Focus a widget control.
  1852. *
  1853. * @param {string} widgetId
  1854. */
  1855. api.Widgets.focusWidgetFormControl = function( widgetId ) {
  1856. var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
  1857. if ( control ) {
  1858. control.focus();
  1859. }
  1860. },
  1861. /**
  1862. * Given a widget control, find the sidebar widgets control that contains it.
  1863. * @param {string} widgetId
  1864. * @return {object|null}
  1865. */
  1866. api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
  1867. var foundControl = null;
  1868. // @todo this can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl()
  1869. api.control.each( function( control ) {
  1870. if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
  1871. foundControl = control;
  1872. }
  1873. } );
  1874. return foundControl;
  1875. };
  1876. /**
  1877. * Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
  1878. *
  1879. * @param {string} widgetId
  1880. * @return {object|null}
  1881. */
  1882. api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
  1883. var foundControl = null;
  1884. // @todo We can just use widgetIdToSettingId() here
  1885. api.control.each( function( control ) {
  1886. if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
  1887. foundControl = control;
  1888. }
  1889. } );
  1890. return foundControl;
  1891. };
  1892. /**
  1893. * Initialize Edit Menu button in Nav Menu widget.
  1894. */
  1895. $( document ).on( 'widget-added', function( event, widgetContainer ) {
  1896. var parsedWidgetId, widgetControl, navMenuSelect, editMenuButton;
  1897. parsedWidgetId = parseWidgetId( widgetContainer.find( '> .widget-inside > .form > .widget-id' ).val() );
  1898. if ( 'nav_menu' !== parsedWidgetId.id_base ) {
  1899. return;
  1900. }
  1901. widgetControl = api.control( 'widget_nav_menu[' + String( parsedWidgetId.number ) + ']' );
  1902. if ( ! widgetControl ) {
  1903. return;
  1904. }
  1905. navMenuSelect = widgetContainer.find( 'select[name*="nav_menu"]' );
  1906. editMenuButton = widgetContainer.find( '.edit-selected-nav-menu > button' );
  1907. if ( 0 === navMenuSelect.length || 0 === editMenuButton.length ) {
  1908. return;
  1909. }
  1910. navMenuSelect.on( 'change', function() {
  1911. if ( api.section.has( 'nav_menu[' + navMenuSelect.val() + ']' ) ) {
  1912. editMenuButton.parent().show();
  1913. } else {
  1914. editMenuButton.parent().hide();
  1915. }
  1916. });
  1917. editMenuButton.on( 'click', function() {
  1918. var section = api.section( 'nav_menu[' + navMenuSelect.val() + ']' );
  1919. if ( section ) {
  1920. focusConstructWithBreadcrumb( section, widgetControl );
  1921. }
  1922. } );
  1923. } );
  1924. /**
  1925. * Focus (expand) one construct and then focus on another construct after the first is collapsed.
  1926. *
  1927. * This overrides the back button to serve the purpose of breadcrumb navigation.
  1928. *
  1929. * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} focusConstruct - The object to initially focus.
  1930. * @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} returnConstruct - The object to return focus.
  1931. */
  1932. function focusConstructWithBreadcrumb( focusConstruct, returnConstruct ) {
  1933. focusConstruct.focus();
  1934. function onceCollapsed( isExpanded ) {
  1935. if ( ! isExpanded ) {
  1936. focusConstruct.expanded.unbind( onceCollapsed );
  1937. returnConstruct.focus();
  1938. }
  1939. }
  1940. focusConstruct.expanded.bind( onceCollapsed );
  1941. }
  1942. /**
  1943. * @param {String} widgetId
  1944. * @returns {Object}
  1945. */
  1946. function parseWidgetId( widgetId ) {
  1947. var matches, parsed = {
  1948. number: null,
  1949. id_base: null
  1950. };
  1951. matches = widgetId.match( /^(.+)-(\d+)$/ );
  1952. if ( matches ) {
  1953. parsed.id_base = matches[1];
  1954. parsed.number = parseInt( matches[2], 10 );
  1955. } else {
  1956. // likely an old single widget
  1957. parsed.id_base = widgetId;
  1958. }
  1959. return parsed;
  1960. }
  1961. /**
  1962. * @param {String} widgetId
  1963. * @returns {String} settingId
  1964. */
  1965. function widgetIdToSettingId( widgetId ) {
  1966. var parsed = parseWidgetId( widgetId ), settingId;
  1967. settingId = 'widget_' + parsed.id_base;
  1968. if ( parsed.number ) {
  1969. settingId += '[' + parsed.number + ']';
  1970. }
  1971. return settingId;
  1972. }
  1973. })( window.wp, jQuery );