text-widgets.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /**
  2. * @output wp-admin/js/widgets/text-widgets.js
  3. */
  4. /* global tinymce, switchEditors */
  5. /* eslint consistent-this: [ "error", "control" ] */
  6. /**
  7. * @namespace wp.textWidgets
  8. */
  9. wp.textWidgets = ( function( $ ) {
  10. 'use strict';
  11. var component = {
  12. dismissedPointers: [],
  13. idBases: [ 'text' ]
  14. };
  15. component.TextWidgetControl = Backbone.View.extend(/** @lends wp.textWidgets.TextWidgetControl.prototype */{
  16. /**
  17. * View events.
  18. *
  19. * @type {Object}
  20. */
  21. events: {},
  22. /**
  23. * Text widget control.
  24. *
  25. * @constructs wp.textWidgets.TextWidgetControl
  26. * @augments Backbone.View
  27. * @abstract
  28. *
  29. * @param {Object} options - Options.
  30. * @param {jQuery} options.el - Control field container element.
  31. * @param {jQuery} options.syncContainer - Container element where fields are synced for the server.
  32. *
  33. * @return {void}
  34. */
  35. initialize: function initialize( options ) {
  36. var control = this;
  37. if ( ! options.el ) {
  38. throw new Error( 'Missing options.el' );
  39. }
  40. if ( ! options.syncContainer ) {
  41. throw new Error( 'Missing options.syncContainer' );
  42. }
  43. Backbone.View.prototype.initialize.call( control, options );
  44. control.syncContainer = options.syncContainer;
  45. control.$el.addClass( 'text-widget-fields' );
  46. control.$el.html( wp.template( 'widget-text-control-fields' ) );
  47. control.customHtmlWidgetPointer = control.$el.find( '.wp-pointer.custom-html-widget-pointer' );
  48. if ( control.customHtmlWidgetPointer.length ) {
  49. control.customHtmlWidgetPointer.find( '.close' ).on( 'click', function( event ) {
  50. event.preventDefault();
  51. control.customHtmlWidgetPointer.hide();
  52. $( '#' + control.fields.text.attr( 'id' ) + '-html' ).trigger( 'focus' );
  53. control.dismissPointers( [ 'text_widget_custom_html' ] );
  54. });
  55. control.customHtmlWidgetPointer.find( '.add-widget' ).on( 'click', function( event ) {
  56. event.preventDefault();
  57. control.customHtmlWidgetPointer.hide();
  58. control.openAvailableWidgetsPanel();
  59. });
  60. }
  61. control.pasteHtmlPointer = control.$el.find( '.wp-pointer.paste-html-pointer' );
  62. if ( control.pasteHtmlPointer.length ) {
  63. control.pasteHtmlPointer.find( '.close' ).on( 'click', function( event ) {
  64. event.preventDefault();
  65. control.pasteHtmlPointer.hide();
  66. control.editor.focus();
  67. control.dismissPointers( [ 'text_widget_custom_html', 'text_widget_paste_html' ] );
  68. });
  69. }
  70. control.fields = {
  71. title: control.$el.find( '.title' ),
  72. text: control.$el.find( '.text' )
  73. };
  74. // Sync input fields to hidden sync fields which actually get sent to the server.
  75. _.each( control.fields, function( fieldInput, fieldName ) {
  76. fieldInput.on( 'input change', function updateSyncField() {
  77. var syncInput = control.syncContainer.find( '.sync-input.' + fieldName );
  78. if ( syncInput.val() !== fieldInput.val() ) {
  79. syncInput.val( fieldInput.val() );
  80. syncInput.trigger( 'change' );
  81. }
  82. });
  83. // Note that syncInput cannot be re-used because it will be destroyed with each widget-updated event.
  84. fieldInput.val( control.syncContainer.find( '.sync-input.' + fieldName ).val() );
  85. });
  86. },
  87. /**
  88. * Dismiss pointers for Custom HTML widget.
  89. *
  90. * @since 4.8.1
  91. *
  92. * @param {Array} pointers Pointer IDs to dismiss.
  93. * @return {void}
  94. */
  95. dismissPointers: function dismissPointers( pointers ) {
  96. _.each( pointers, function( pointer ) {
  97. wp.ajax.post( 'dismiss-wp-pointer', {
  98. pointer: pointer
  99. });
  100. component.dismissedPointers.push( pointer );
  101. });
  102. },
  103. /**
  104. * Open available widgets panel.
  105. *
  106. * @since 4.8.1
  107. * @return {void}
  108. */
  109. openAvailableWidgetsPanel: function openAvailableWidgetsPanel() {
  110. var sidebarControl;
  111. wp.customize.section.each( function( section ) {
  112. if ( section.extended( wp.customize.Widgets.SidebarSection ) && section.expanded() ) {
  113. sidebarControl = wp.customize.control( 'sidebars_widgets[' + section.params.sidebarId + ']' );
  114. }
  115. });
  116. if ( ! sidebarControl ) {
  117. return;
  118. }
  119. setTimeout( function() { // Timeout to prevent click event from causing panel to immediately collapse.
  120. wp.customize.Widgets.availableWidgetsPanel.open( sidebarControl );
  121. wp.customize.Widgets.availableWidgetsPanel.$search.val( 'HTML' ).trigger( 'keyup' );
  122. });
  123. },
  124. /**
  125. * Update input fields from the sync fields.
  126. *
  127. * This function is called at the widget-updated and widget-synced events.
  128. * A field will only be updated if it is not currently focused, to avoid
  129. * overwriting content that the user is entering.
  130. *
  131. * @return {void}
  132. */
  133. updateFields: function updateFields() {
  134. var control = this, syncInput;
  135. if ( ! control.fields.title.is( document.activeElement ) ) {
  136. syncInput = control.syncContainer.find( '.sync-input.title' );
  137. control.fields.title.val( syncInput.val() );
  138. }
  139. syncInput = control.syncContainer.find( '.sync-input.text' );
  140. if ( control.fields.text.is( ':visible' ) ) {
  141. if ( ! control.fields.text.is( document.activeElement ) ) {
  142. control.fields.text.val( syncInput.val() );
  143. }
  144. } else if ( control.editor && ! control.editorFocused && syncInput.val() !== control.fields.text.val() ) {
  145. control.editor.setContent( wp.oldEditor.autop( syncInput.val() ) );
  146. }
  147. },
  148. /**
  149. * Initialize editor.
  150. *
  151. * @return {void}
  152. */
  153. initializeEditor: function initializeEditor() {
  154. var control = this, changeDebounceDelay = 1000, id, textarea, triggerChangeIfDirty, restoreTextMode = false, needsTextareaChangeTrigger = false, previousValue;
  155. textarea = control.fields.text;
  156. id = textarea.attr( 'id' );
  157. previousValue = textarea.val();
  158. /**
  159. * Trigger change if dirty.
  160. *
  161. * @return {void}
  162. */
  163. triggerChangeIfDirty = function() {
  164. var updateWidgetBuffer = 300; // See wp.customize.Widgets.WidgetControl._setupUpdateUI() which uses 250ms for updateWidgetDebounced.
  165. if ( control.editor.isDirty() ) {
  166. /*
  167. * Account for race condition in customizer where user clicks Save & Publish while
  168. * focus was just previously given to the editor. Since updates to the editor
  169. * are debounced at 1 second and since widget input changes are only synced to
  170. * settings after 250ms, the customizer needs to be put into the processing
  171. * state during the time between the change event is triggered and updateWidget
  172. * logic starts. Note that the debounced update-widget request should be able
  173. * to be removed with the removal of the update-widget request entirely once
  174. * widgets are able to mutate their own instance props directly in JS without
  175. * having to make server round-trips to call the respective WP_Widget::update()
  176. * callbacks. See <https://core.trac.wordpress.org/ticket/33507>.
  177. */
  178. if ( wp.customize && wp.customize.state ) {
  179. wp.customize.state( 'processing' ).set( wp.customize.state( 'processing' ).get() + 1 );
  180. _.delay( function() {
  181. wp.customize.state( 'processing' ).set( wp.customize.state( 'processing' ).get() - 1 );
  182. }, updateWidgetBuffer );
  183. }
  184. if ( ! control.editor.isHidden() ) {
  185. control.editor.save();
  186. }
  187. }
  188. // Trigger change on textarea when it has changed so the widget can enter a dirty state.
  189. if ( needsTextareaChangeTrigger && previousValue !== textarea.val() ) {
  190. textarea.trigger( 'change' );
  191. needsTextareaChangeTrigger = false;
  192. previousValue = textarea.val();
  193. }
  194. };
  195. // Just-in-time force-update the hidden input fields.
  196. control.syncContainer.closest( '.widget' ).find( '[name=savewidget]:first' ).on( 'click', function onClickSaveButton() {
  197. triggerChangeIfDirty();
  198. });
  199. /**
  200. * Build (or re-build) the visual editor.
  201. *
  202. * @return {void}
  203. */
  204. function buildEditor() {
  205. var editor, onInit, showPointerElement;
  206. // Abort building if the textarea is gone, likely due to the widget having been deleted entirely.
  207. if ( ! document.getElementById( id ) ) {
  208. return;
  209. }
  210. // The user has disabled TinyMCE.
  211. if ( typeof window.tinymce === 'undefined' ) {
  212. wp.oldEditor.initialize( id, {
  213. quicktags: true,
  214. mediaButtons: true
  215. });
  216. return;
  217. }
  218. // Destroy any existing editor so that it can be re-initialized after a widget-updated event.
  219. if ( tinymce.get( id ) ) {
  220. restoreTextMode = tinymce.get( id ).isHidden();
  221. wp.oldEditor.remove( id );
  222. }
  223. // Add or enable the `wpview` plugin.
  224. $( document ).one( 'wp-before-tinymce-init.text-widget-init', function( event, init ) {
  225. // If somebody has removed all plugins, they must have a good reason.
  226. // Keep it that way.
  227. if ( ! init.plugins ) {
  228. return;
  229. } else if ( ! /\bwpview\b/.test( init.plugins ) ) {
  230. init.plugins += ',wpview';
  231. }
  232. } );
  233. wp.oldEditor.initialize( id, {
  234. tinymce: {
  235. wpautop: true
  236. },
  237. quicktags: true,
  238. mediaButtons: true
  239. });
  240. /**
  241. * Show a pointer, focus on dismiss, and speak the contents for a11y.
  242. *
  243. * @param {jQuery} pointerElement Pointer element.
  244. * @return {void}
  245. */
  246. showPointerElement = function( pointerElement ) {
  247. pointerElement.show();
  248. pointerElement.find( '.close' ).trigger( 'focus' );
  249. wp.a11y.speak( pointerElement.find( 'h3, p' ).map( function() {
  250. return $( this ).text();
  251. } ).get().join( '\n\n' ) );
  252. };
  253. editor = window.tinymce.get( id );
  254. if ( ! editor ) {
  255. throw new Error( 'Failed to initialize editor' );
  256. }
  257. onInit = function() {
  258. // When a widget is moved in the DOM the dynamically-created TinyMCE iframe will be destroyed and has to be re-built.
  259. $( editor.getWin() ).on( 'unload', function() {
  260. _.defer( buildEditor );
  261. });
  262. // If a prior mce instance was replaced, and it was in text mode, toggle to text mode.
  263. if ( restoreTextMode ) {
  264. switchEditors.go( id, 'html' );
  265. }
  266. // Show the pointer.
  267. $( '#' + id + '-html' ).on( 'click', function() {
  268. control.pasteHtmlPointer.hide(); // Hide the HTML pasting pointer.
  269. if ( -1 !== component.dismissedPointers.indexOf( 'text_widget_custom_html' ) ) {
  270. return;
  271. }
  272. showPointerElement( control.customHtmlWidgetPointer );
  273. });
  274. // Hide the pointer when switching tabs.
  275. $( '#' + id + '-tmce' ).on( 'click', function() {
  276. control.customHtmlWidgetPointer.hide();
  277. });
  278. // Show pointer when pasting HTML.
  279. editor.on( 'pastepreprocess', function( event ) {
  280. var content = event.content;
  281. if ( -1 !== component.dismissedPointers.indexOf( 'text_widget_paste_html' ) || ! content || ! /&lt;\w+.*?&gt;/.test( content ) ) {
  282. return;
  283. }
  284. // Show the pointer after a slight delay so the user sees what they pasted.
  285. _.delay( function() {
  286. showPointerElement( control.pasteHtmlPointer );
  287. }, 250 );
  288. });
  289. };
  290. if ( editor.initialized ) {
  291. onInit();
  292. } else {
  293. editor.on( 'init', onInit );
  294. }
  295. control.editorFocused = false;
  296. editor.on( 'focus', function onEditorFocus() {
  297. control.editorFocused = true;
  298. });
  299. editor.on( 'paste', function onEditorPaste() {
  300. editor.setDirty( true ); // Because pasting doesn't currently set the dirty state.
  301. triggerChangeIfDirty();
  302. });
  303. editor.on( 'NodeChange', function onNodeChange() {
  304. needsTextareaChangeTrigger = true;
  305. });
  306. editor.on( 'NodeChange', _.debounce( triggerChangeIfDirty, changeDebounceDelay ) );
  307. editor.on( 'blur hide', function onEditorBlur() {
  308. control.editorFocused = false;
  309. triggerChangeIfDirty();
  310. });
  311. control.editor = editor;
  312. }
  313. buildEditor();
  314. }
  315. });
  316. /**
  317. * Mapping of widget ID to instances of TextWidgetControl subclasses.
  318. *
  319. * @memberOf wp.textWidgets
  320. *
  321. * @type {Object.<string, wp.textWidgets.TextWidgetControl>}
  322. */
  323. component.widgetControls = {};
  324. /**
  325. * Handle widget being added or initialized for the first time at the widget-added event.
  326. *
  327. * @memberOf wp.textWidgets
  328. *
  329. * @param {jQuery.Event} event - Event.
  330. * @param {jQuery} widgetContainer - Widget container element.
  331. *
  332. * @return {void}
  333. */
  334. component.handleWidgetAdded = function handleWidgetAdded( event, widgetContainer ) {
  335. var widgetForm, idBase, widgetControl, widgetId, animatedCheckDelay = 50, renderWhenAnimationDone, fieldContainer, syncContainer;
  336. widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' ); // Note: '.form' appears in the customizer, whereas 'form' on the widgets admin screen.
  337. idBase = widgetForm.find( '> .id_base' ).val();
  338. if ( -1 === component.idBases.indexOf( idBase ) ) {
  339. return;
  340. }
  341. // Prevent initializing already-added widgets.
  342. widgetId = widgetForm.find( '.widget-id' ).val();
  343. if ( component.widgetControls[ widgetId ] ) {
  344. return;
  345. }
  346. // Bypass using TinyMCE when widget is in legacy mode.
  347. if ( ! widgetForm.find( '.visual' ).val() ) {
  348. return;
  349. }
  350. /*
  351. * Create a container element for the widget control fields.
  352. * This is inserted into the DOM immediately before the .widget-content
  353. * element because the contents of this element are essentially "managed"
  354. * by PHP, where each widget update cause the entire element to be emptied
  355. * and replaced with the rendered output of WP_Widget::form() which is
  356. * sent back in Ajax request made to save/update the widget instance.
  357. * To prevent a "flash of replaced DOM elements and re-initialized JS
  358. * components", the JS template is rendered outside of the normal form
  359. * container.
  360. */
  361. fieldContainer = $( '<div></div>' );
  362. syncContainer = widgetContainer.find( '.widget-content:first' );
  363. syncContainer.before( fieldContainer );
  364. widgetControl = new component.TextWidgetControl({
  365. el: fieldContainer,
  366. syncContainer: syncContainer
  367. });
  368. component.widgetControls[ widgetId ] = widgetControl;
  369. /*
  370. * Render the widget once the widget parent's container finishes animating,
  371. * as the widget-added event fires with a slideDown of the container.
  372. * This ensures that the textarea is visible and an iframe can be embedded
  373. * with TinyMCE being able to set contenteditable on it.
  374. */
  375. renderWhenAnimationDone = function() {
  376. if ( ! widgetContainer.hasClass( 'open' ) ) {
  377. setTimeout( renderWhenAnimationDone, animatedCheckDelay );
  378. } else {
  379. widgetControl.initializeEditor();
  380. }
  381. };
  382. renderWhenAnimationDone();
  383. };
  384. /**
  385. * Setup widget in accessibility mode.
  386. *
  387. * @memberOf wp.textWidgets
  388. *
  389. * @return {void}
  390. */
  391. component.setupAccessibleMode = function setupAccessibleMode() {
  392. var widgetForm, idBase, widgetControl, fieldContainer, syncContainer;
  393. widgetForm = $( '.editwidget > form' );
  394. if ( 0 === widgetForm.length ) {
  395. return;
  396. }
  397. idBase = widgetForm.find( '.id_base' ).val();
  398. if ( -1 === component.idBases.indexOf( idBase ) ) {
  399. return;
  400. }
  401. // Bypass using TinyMCE when widget is in legacy mode.
  402. if ( ! widgetForm.find( '.visual' ).val() ) {
  403. return;
  404. }
  405. fieldContainer = $( '<div></div>' );
  406. syncContainer = widgetForm.find( '> .widget-inside' );
  407. syncContainer.before( fieldContainer );
  408. widgetControl = new component.TextWidgetControl({
  409. el: fieldContainer,
  410. syncContainer: syncContainer
  411. });
  412. widgetControl.initializeEditor();
  413. };
  414. /**
  415. * Sync widget instance data sanitized from server back onto widget model.
  416. *
  417. * This gets called via the 'widget-updated' event when saving a widget from
  418. * the widgets admin screen and also via the 'widget-synced' event when making
  419. * a change to a widget in the customizer.
  420. *
  421. * @memberOf wp.textWidgets
  422. *
  423. * @param {jQuery.Event} event - Event.
  424. * @param {jQuery} widgetContainer - Widget container element.
  425. * @return {void}
  426. */
  427. component.handleWidgetUpdated = function handleWidgetUpdated( event, widgetContainer ) {
  428. var widgetForm, widgetId, widgetControl, idBase;
  429. widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' );
  430. idBase = widgetForm.find( '> .id_base' ).val();
  431. if ( -1 === component.idBases.indexOf( idBase ) ) {
  432. return;
  433. }
  434. widgetId = widgetForm.find( '> .widget-id' ).val();
  435. widgetControl = component.widgetControls[ widgetId ];
  436. if ( ! widgetControl ) {
  437. return;
  438. }
  439. widgetControl.updateFields();
  440. };
  441. /**
  442. * Initialize functionality.
  443. *
  444. * This function exists to prevent the JS file from having to boot itself.
  445. * When WordPress enqueues this script, it should have an inline script
  446. * attached which calls wp.textWidgets.init().
  447. *
  448. * @memberOf wp.textWidgets
  449. *
  450. * @return {void}
  451. */
  452. component.init = function init() {
  453. var $document = $( document );
  454. $document.on( 'widget-added', component.handleWidgetAdded );
  455. $document.on( 'widget-synced widget-updated', component.handleWidgetUpdated );
  456. /*
  457. * Manually trigger widget-added events for media widgets on the admin
  458. * screen once they are expanded. The widget-added event is not triggered
  459. * for each pre-existing widget on the widgets admin screen like it is
  460. * on the customizer. Likewise, the customizer only triggers widget-added
  461. * when the widget is expanded to just-in-time construct the widget form
  462. * when it is actually going to be displayed. So the following implements
  463. * the same for the widgets admin screen, to invoke the widget-added
  464. * handler when a pre-existing media widget is expanded.
  465. */
  466. $( function initializeExistingWidgetContainers() {
  467. var widgetContainers;
  468. if ( 'widgets' !== window.pagenow ) {
  469. return;
  470. }
  471. widgetContainers = $( '.widgets-holder-wrap:not(#available-widgets)' ).find( 'div.widget' );
  472. widgetContainers.one( 'click.toggle-widget-expanded', function toggleWidgetExpanded() {
  473. var widgetContainer = $( this );
  474. component.handleWidgetAdded( new jQuery.Event( 'widget-added' ), widgetContainer );
  475. });
  476. // Accessibility mode.
  477. component.setupAccessibleMode();
  478. });
  479. };
  480. return component;
  481. })( jQuery );