custom-html-widgets.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /* global wp */
  2. /* eslint consistent-this: [ "error", "control" ] */
  3. /* eslint no-magic-numbers: ["error", { "ignore": [0,1,-1] }] */
  4. wp.customHtmlWidgets = ( function( $ ) {
  5. 'use strict';
  6. var component = {
  7. idBases: [ 'custom_html' ],
  8. codeEditorSettings: {},
  9. l10n: {
  10. errorNotice: {
  11. singular: '',
  12. plural: ''
  13. }
  14. }
  15. };
  16. /**
  17. * Text widget control.
  18. *
  19. * @class CustomHtmlWidgetControl
  20. * @constructor
  21. * @abstract
  22. */
  23. component.CustomHtmlWidgetControl = Backbone.View.extend({
  24. /**
  25. * View events.
  26. *
  27. * @type {Object}
  28. */
  29. events: {},
  30. /**
  31. * Initialize.
  32. *
  33. * @param {Object} options - Options.
  34. * @param {jQuery} options.el - Control field container element.
  35. * @param {jQuery} options.syncContainer - Container element where fields are synced for the server.
  36. * @returns {void}
  37. */
  38. initialize: function initialize( options ) {
  39. var control = this;
  40. if ( ! options.el ) {
  41. throw new Error( 'Missing options.el' );
  42. }
  43. if ( ! options.syncContainer ) {
  44. throw new Error( 'Missing options.syncContainer' );
  45. }
  46. Backbone.View.prototype.initialize.call( control, options );
  47. control.syncContainer = options.syncContainer;
  48. control.widgetIdBase = control.syncContainer.parent().find( '.id_base' ).val();
  49. control.widgetNumber = control.syncContainer.parent().find( '.widget_number' ).val();
  50. control.customizeSettingId = 'widget_' + control.widgetIdBase + '[' + String( control.widgetNumber ) + ']';
  51. control.$el.addClass( 'custom-html-widget-fields' );
  52. control.$el.html( wp.template( 'widget-custom-html-control-fields' )( { codeEditorDisabled: component.codeEditorSettings.disabled } ) );
  53. control.errorNoticeContainer = control.$el.find( '.code-editor-error-container' );
  54. control.currentErrorAnnotations = [];
  55. control.saveButton = control.syncContainer.add( control.syncContainer.parent().find( '.widget-control-actions' ) ).find( '.widget-control-save, #savewidget' );
  56. control.saveButton.addClass( 'custom-html-widget-save-button' ); // To facilitate style targeting.
  57. control.fields = {
  58. title: control.$el.find( '.title' ),
  59. content: control.$el.find( '.content' )
  60. };
  61. // Sync input fields to hidden sync fields which actually get sent to the server.
  62. _.each( control.fields, function( fieldInput, fieldName ) {
  63. fieldInput.on( 'input change', function updateSyncField() {
  64. var syncInput = control.syncContainer.find( '.sync-input.' + fieldName );
  65. if ( syncInput.val() !== fieldInput.val() ) {
  66. syncInput.val( fieldInput.val() );
  67. syncInput.trigger( 'change' );
  68. }
  69. });
  70. // Note that syncInput cannot be re-used because it will be destroyed with each widget-updated event.
  71. fieldInput.val( control.syncContainer.find( '.sync-input.' + fieldName ).val() );
  72. });
  73. },
  74. /**
  75. * Update input fields from the sync fields.
  76. *
  77. * This function is called at the widget-updated and widget-synced events.
  78. * A field will only be updated if it is not currently focused, to avoid
  79. * overwriting content that the user is entering.
  80. *
  81. * @returns {void}
  82. */
  83. updateFields: function updateFields() {
  84. var control = this, syncInput;
  85. if ( ! control.fields.title.is( document.activeElement ) ) {
  86. syncInput = control.syncContainer.find( '.sync-input.title' );
  87. control.fields.title.val( syncInput.val() );
  88. }
  89. /*
  90. * Prevent updating content when the editor is focused or if there are current error annotations,
  91. * to prevent the editor's contents from getting sanitized as soon as a user removes focus from
  92. * the editor. This is particularly important for users who cannot unfiltered_html.
  93. */
  94. control.contentUpdateBypassed = control.fields.content.is( document.activeElement ) || control.editor && control.editor.codemirror.state.focused || 0 !== control.currentErrorAnnotations;
  95. if ( ! control.contentUpdateBypassed ) {
  96. syncInput = control.syncContainer.find( '.sync-input.content' );
  97. control.fields.content.val( syncInput.val() ).trigger( 'change' );
  98. }
  99. },
  100. /**
  101. * Show linting error notice.
  102. *
  103. * @param {Array} errorAnnotations - Error annotations.
  104. * @returns {void}
  105. */
  106. updateErrorNotice: function( errorAnnotations ) {
  107. var control = this, errorNotice, message = '', customizeSetting;
  108. if ( 1 === errorAnnotations.length ) {
  109. message = component.l10n.errorNotice.singular.replace( '%d', '1' );
  110. } else if ( errorAnnotations.length > 1 ) {
  111. message = component.l10n.errorNotice.plural.replace( '%d', String( errorAnnotations.length ) );
  112. }
  113. if ( control.fields.content[0].setCustomValidity ) {
  114. control.fields.content[0].setCustomValidity( message );
  115. }
  116. if ( wp.customize && wp.customize.has( control.customizeSettingId ) ) {
  117. customizeSetting = wp.customize( control.customizeSettingId );
  118. customizeSetting.notifications.remove( 'htmlhint_error' );
  119. if ( 0 !== errorAnnotations.length ) {
  120. customizeSetting.notifications.add( 'htmlhint_error', new wp.customize.Notification( 'htmlhint_error', {
  121. message: message,
  122. type: 'error'
  123. } ) );
  124. }
  125. } else if ( 0 !== errorAnnotations.length ) {
  126. errorNotice = $( '<div class="inline notice notice-error notice-alt"></div>' );
  127. errorNotice.append( $( '<p></p>', {
  128. text: message
  129. } ) );
  130. control.errorNoticeContainer.empty();
  131. control.errorNoticeContainer.append( errorNotice );
  132. control.errorNoticeContainer.slideDown( 'fast' );
  133. wp.a11y.speak( message );
  134. } else {
  135. control.errorNoticeContainer.slideUp( 'fast' );
  136. }
  137. },
  138. /**
  139. * Initialize editor.
  140. *
  141. * @returns {void}
  142. */
  143. initializeEditor: function initializeEditor() {
  144. var control = this, settings;
  145. if ( component.codeEditorSettings.disabled ) {
  146. return;
  147. }
  148. settings = _.extend( {}, component.codeEditorSettings, {
  149. /**
  150. * Handle tabbing to the field before the editor.
  151. *
  152. * @returns {void}
  153. */
  154. onTabPrevious: function onTabPrevious() {
  155. control.fields.title.focus();
  156. },
  157. /**
  158. * Handle tabbing to the field after the editor.
  159. *
  160. * @returns {void}
  161. */
  162. onTabNext: function onTabNext() {
  163. var tabbables = control.syncContainer.add( control.syncContainer.parent().find( '.widget-position, .widget-control-actions' ) ).find( ':tabbable' );
  164. tabbables.first().focus();
  165. },
  166. /**
  167. * Disable save button and store linting errors for use in updateFields.
  168. *
  169. * @param {Array} errorAnnotations - Error notifications.
  170. * @returns {void}
  171. */
  172. onChangeLintingErrors: function onChangeLintingErrors( errorAnnotations ) {
  173. control.currentErrorAnnotations = errorAnnotations;
  174. },
  175. /**
  176. * Update error notice.
  177. *
  178. * @param {Array} errorAnnotations - Error annotations.
  179. * @returns {void}
  180. */
  181. onUpdateErrorNotice: function onUpdateErrorNotice( errorAnnotations ) {
  182. control.saveButton.toggleClass( 'validation-blocked disabled', errorAnnotations.length > 0 );
  183. control.updateErrorNotice( errorAnnotations );
  184. }
  185. });
  186. control.editor = wp.codeEditor.initialize( control.fields.content, settings );
  187. // Improve the editor accessibility.
  188. $( control.editor.codemirror.display.lineDiv )
  189. .attr({
  190. role: 'textbox',
  191. 'aria-multiline': 'true',
  192. 'aria-labelledby': control.fields.content[0].id + '-label',
  193. 'aria-describedby': 'editor-keyboard-trap-help-1 editor-keyboard-trap-help-2 editor-keyboard-trap-help-3 editor-keyboard-trap-help-4'
  194. });
  195. // Focus the editor when clicking on its label.
  196. $( '#' + control.fields.content[0].id + '-label' ).on( 'click', function() {
  197. control.editor.codemirror.focus();
  198. });
  199. control.fields.content.on( 'change', function() {
  200. if ( this.value !== control.editor.codemirror.getValue() ) {
  201. control.editor.codemirror.setValue( this.value );
  202. }
  203. });
  204. control.editor.codemirror.on( 'change', function() {
  205. var value = control.editor.codemirror.getValue();
  206. if ( value !== control.fields.content.val() ) {
  207. control.fields.content.val( value ).trigger( 'change' );
  208. }
  209. });
  210. // Make sure the editor gets updated if the content was updated on the server (sanitization) but not updated in the editor since it was focused.
  211. control.editor.codemirror.on( 'blur', function() {
  212. if ( control.contentUpdateBypassed ) {
  213. control.syncContainer.find( '.sync-input.content' ).trigger( 'change' );
  214. }
  215. });
  216. // Prevent hitting Esc from collapsing the widget control.
  217. if ( wp.customize ) {
  218. control.editor.codemirror.on( 'keydown', function onKeydown( codemirror, event ) {
  219. var escKeyCode = 27;
  220. if ( escKeyCode === event.keyCode ) {
  221. event.stopPropagation();
  222. }
  223. });
  224. }
  225. }
  226. });
  227. /**
  228. * Mapping of widget ID to instances of CustomHtmlWidgetControl subclasses.
  229. *
  230. * @type {Object.<string, wp.textWidgets.CustomHtmlWidgetControl>}
  231. */
  232. component.widgetControls = {};
  233. /**
  234. * Handle widget being added or initialized for the first time at the widget-added event.
  235. *
  236. * @param {jQuery.Event} event - Event.
  237. * @param {jQuery} widgetContainer - Widget container element.
  238. * @returns {void}
  239. */
  240. component.handleWidgetAdded = function handleWidgetAdded( event, widgetContainer ) {
  241. var widgetForm, idBase, widgetControl, widgetId, animatedCheckDelay = 50, renderWhenAnimationDone, fieldContainer, syncContainer;
  242. widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' ); // Note: '.form' appears in the customizer, whereas 'form' on the widgets admin screen.
  243. idBase = widgetForm.find( '> .id_base' ).val();
  244. if ( -1 === component.idBases.indexOf( idBase ) ) {
  245. return;
  246. }
  247. // Prevent initializing already-added widgets.
  248. widgetId = widgetForm.find( '.widget-id' ).val();
  249. if ( component.widgetControls[ widgetId ] ) {
  250. return;
  251. }
  252. /*
  253. * Create a container element for the widget control fields.
  254. * This is inserted into the DOM immediately before the the .widget-content
  255. * element because the contents of this element are essentially "managed"
  256. * by PHP, where each widget update cause the entire element to be emptied
  257. * and replaced with the rendered output of WP_Widget::form() which is
  258. * sent back in Ajax request made to save/update the widget instance.
  259. * To prevent a "flash of replaced DOM elements and re-initialized JS
  260. * components", the JS template is rendered outside of the normal form
  261. * container.
  262. */
  263. fieldContainer = $( '<div></div>' );
  264. syncContainer = widgetContainer.find( '.widget-content:first' );
  265. syncContainer.before( fieldContainer );
  266. widgetControl = new component.CustomHtmlWidgetControl({
  267. el: fieldContainer,
  268. syncContainer: syncContainer
  269. });
  270. component.widgetControls[ widgetId ] = widgetControl;
  271. /*
  272. * Render the widget once the widget parent's container finishes animating,
  273. * as the widget-added event fires with a slideDown of the container.
  274. * This ensures that the textarea is visible and the editor can be initialized.
  275. */
  276. renderWhenAnimationDone = function() {
  277. if ( ! ( wp.customize ? widgetContainer.parent().hasClass( 'expanded' ) : widgetContainer.hasClass( 'open' ) ) ) { // Core merge: The wp.customize condition can be eliminated with this change being in core: https://github.com/xwp/wordpress-develop/pull/247/commits/5322387d
  278. setTimeout( renderWhenAnimationDone, animatedCheckDelay );
  279. } else {
  280. widgetControl.initializeEditor();
  281. }
  282. };
  283. renderWhenAnimationDone();
  284. };
  285. /**
  286. * Setup widget in accessibility mode.
  287. *
  288. * @returns {void}
  289. */
  290. component.setupAccessibleMode = function setupAccessibleMode() {
  291. var widgetForm, idBase, widgetControl, fieldContainer, syncContainer;
  292. widgetForm = $( '.editwidget > form' );
  293. if ( 0 === widgetForm.length ) {
  294. return;
  295. }
  296. idBase = widgetForm.find( '> .widget-control-actions > .id_base' ).val();
  297. if ( -1 === component.idBases.indexOf( idBase ) ) {
  298. return;
  299. }
  300. fieldContainer = $( '<div></div>' );
  301. syncContainer = widgetForm.find( '> .widget-inside' );
  302. syncContainer.before( fieldContainer );
  303. widgetControl = new component.CustomHtmlWidgetControl({
  304. el: fieldContainer,
  305. syncContainer: syncContainer
  306. });
  307. widgetControl.initializeEditor();
  308. };
  309. /**
  310. * Sync widget instance data sanitized from server back onto widget model.
  311. *
  312. * This gets called via the 'widget-updated' event when saving a widget from
  313. * the widgets admin screen and also via the 'widget-synced' event when making
  314. * a change to a widget in the customizer.
  315. *
  316. * @param {jQuery.Event} event - Event.
  317. * @param {jQuery} widgetContainer - Widget container element.
  318. * @returns {void}
  319. */
  320. component.handleWidgetUpdated = function handleWidgetUpdated( event, widgetContainer ) {
  321. var widgetForm, widgetId, widgetControl, idBase;
  322. widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' );
  323. idBase = widgetForm.find( '> .id_base' ).val();
  324. if ( -1 === component.idBases.indexOf( idBase ) ) {
  325. return;
  326. }
  327. widgetId = widgetForm.find( '> .widget-id' ).val();
  328. widgetControl = component.widgetControls[ widgetId ];
  329. if ( ! widgetControl ) {
  330. return;
  331. }
  332. widgetControl.updateFields();
  333. };
  334. /**
  335. * Initialize functionality.
  336. *
  337. * This function exists to prevent the JS file from having to boot itself.
  338. * When WordPress enqueues this script, it should have an inline script
  339. * attached which calls wp.textWidgets.init().
  340. *
  341. * @param {object} settings - Options for code editor, exported from PHP.
  342. * @returns {void}
  343. */
  344. component.init = function init( settings ) {
  345. var $document = $( document );
  346. _.extend( component.codeEditorSettings, settings );
  347. $document.on( 'widget-added', component.handleWidgetAdded );
  348. $document.on( 'widget-synced widget-updated', component.handleWidgetUpdated );
  349. /*
  350. * Manually trigger widget-added events for media widgets on the admin
  351. * screen once they are expanded. The widget-added event is not triggered
  352. * for each pre-existing widget on the widgets admin screen like it is
  353. * on the customizer. Likewise, the customizer only triggers widget-added
  354. * when the widget is expanded to just-in-time construct the widget form
  355. * when it is actually going to be displayed. So the following implements
  356. * the same for the widgets admin screen, to invoke the widget-added
  357. * handler when a pre-existing media widget is expanded.
  358. */
  359. $( function initializeExistingWidgetContainers() {
  360. var widgetContainers;
  361. if ( 'widgets' !== window.pagenow ) {
  362. return;
  363. }
  364. widgetContainers = $( '.widgets-holder-wrap:not(#available-widgets)' ).find( 'div.widget' );
  365. widgetContainers.one( 'click.toggle-widget-expanded', function toggleWidgetExpanded() {
  366. var widgetContainer = $( this );
  367. component.handleWidgetAdded( new jQuery.Event( 'widget-added' ), widgetContainer );
  368. });
  369. // Accessibility mode.
  370. $( window ).on( 'load', function() {
  371. component.setupAccessibleMode();
  372. });
  373. });
  374. };
  375. return component;
  376. })( jQuery );