You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

604 lines
18 KiB

1 year ago
  1. /**
  2. * This file contains the functions needed for the inline editing of posts.
  3. *
  4. * @since 2.7.0
  5. * @output wp-admin/js/inline-edit-post.js
  6. */
  7. /* global ajaxurl, typenow, inlineEditPost */
  8. window.wp = window.wp || {};
  9. /**
  10. * Manages the quick edit and bulk edit windows for editing posts or pages.
  11. *
  12. * @namespace inlineEditPost
  13. *
  14. * @since 2.7.0
  15. *
  16. * @type {Object}
  17. *
  18. * @property {string} type The type of inline editor.
  19. * @property {string} what The prefix before the post ID.
  20. *
  21. */
  22. ( function( $, wp ) {
  23. window.inlineEditPost = {
  24. /**
  25. * Initializes the inline and bulk post editor.
  26. *
  27. * Binds event handlers to the Escape key to close the inline editor
  28. * and to the save and close buttons. Changes DOM to be ready for inline
  29. * editing. Adds event handler to bulk edit.
  30. *
  31. * @since 2.7.0
  32. *
  33. * @memberof inlineEditPost
  34. *
  35. * @return {void}
  36. */
  37. init : function(){
  38. var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit');
  39. t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post';
  40. // Post ID prefix.
  41. t.what = '#post-';
  42. /**
  43. * Binds the Escape key to revert the changes and close the quick editor.
  44. *
  45. * @return {boolean} The result of revert.
  46. */
  47. qeRow.on( 'keyup', function(e){
  48. // Revert changes if Escape key is pressed.
  49. if ( e.which === 27 ) {
  50. return inlineEditPost.revert();
  51. }
  52. });
  53. /**
  54. * Binds the Escape key to revert the changes and close the bulk editor.
  55. *
  56. * @return {boolean} The result of revert.
  57. */
  58. bulkRow.on( 'keyup', function(e){
  59. // Revert changes if Escape key is pressed.
  60. if ( e.which === 27 ) {
  61. return inlineEditPost.revert();
  62. }
  63. });
  64. /**
  65. * Reverts changes and close the quick editor if the cancel button is clicked.
  66. *
  67. * @return {boolean} The result of revert.
  68. */
  69. $( '.cancel', qeRow ).on( 'click', function() {
  70. return inlineEditPost.revert();
  71. });
  72. /**
  73. * Saves changes in the quick editor if the save(named: update) button is clicked.
  74. *
  75. * @return {boolean} The result of save.
  76. */
  77. $( '.save', qeRow ).on( 'click', function() {
  78. return inlineEditPost.save(this);
  79. });
  80. /**
  81. * If Enter is pressed, and the target is not the cancel button, save the post.
  82. *
  83. * @return {boolean} The result of save.
  84. */
  85. $('td', qeRow).on( 'keydown', function(e){
  86. if ( e.which === 13 && ! $( e.target ).hasClass( 'cancel' ) ) {
  87. return inlineEditPost.save(this);
  88. }
  89. });
  90. /**
  91. * Reverts changes and close the bulk editor if the cancel button is clicked.
  92. *
  93. * @return {boolean} The result of revert.
  94. */
  95. $( '.cancel', bulkRow ).on( 'click', function() {
  96. return inlineEditPost.revert();
  97. });
  98. /**
  99. * Disables the password input field when the private post checkbox is checked.
  100. */
  101. $('#inline-edit .inline-edit-private input[value="private"]').on( 'click', function(){
  102. var pw = $('input.inline-edit-password-input');
  103. if ( $(this).prop('checked') ) {
  104. pw.val('').prop('disabled', true);
  105. } else {
  106. pw.prop('disabled', false);
  107. }
  108. });
  109. /**
  110. * Binds click event to the .editinline button which opens the quick editor.
  111. */
  112. $( '#the-list' ).on( 'click', '.editinline', function() {
  113. $( this ).attr( 'aria-expanded', 'true' );
  114. inlineEditPost.edit( this );
  115. });
  116. $('#bulk-edit').find('fieldset:first').after(
  117. $('#inline-edit fieldset.inline-edit-categories').clone()
  118. ).siblings( 'fieldset:last' ).prepend(
  119. $( '#inline-edit .inline-edit-tags-wrap' ).clone()
  120. );
  121. $('select[name="_status"] option[value="future"]', bulkRow).remove();
  122. /**
  123. * Adds onclick events to the apply buttons.
  124. */
  125. $('#doaction').on( 'click', function(e){
  126. var n;
  127. t.whichBulkButtonId = $( this ).attr( 'id' );
  128. n = t.whichBulkButtonId.substr( 2 );
  129. if ( 'edit' === $( 'select[name="' + n + '"]' ).val() ) {
  130. e.preventDefault();
  131. t.setBulk();
  132. } else if ( $('form#posts-filter tr.inline-editor').length > 0 ) {
  133. t.revert();
  134. }
  135. });
  136. },
  137. /**
  138. * Toggles the quick edit window, hiding it when it's active and showing it when
  139. * inactive.
  140. *
  141. * @since 2.7.0
  142. *
  143. * @memberof inlineEditPost
  144. *
  145. * @param {Object} el Element within a post table row.
  146. */
  147. toggle : function(el){
  148. var t = this;
  149. $( t.what + t.getId( el ) ).css( 'display' ) === 'none' ? t.revert() : t.edit( el );
  150. },
  151. /**
  152. * Creates the bulk editor row to edit multiple posts at once.
  153. *
  154. * @since 2.7.0
  155. *
  156. * @memberof inlineEditPost
  157. */
  158. setBulk : function(){
  159. var te = '', type = this.type, c = true;
  160. this.revert();
  161. $( '#bulk-edit td' ).attr( 'colspan', $( 'th:visible, td:visible', '.widefat:first thead' ).length );
  162. // Insert the editor at the top of the table with an empty row above to maintain zebra striping.
  163. $('table.widefat tbody').prepend( $('#bulk-edit') ).prepend('<tr class="hidden"></tr>');
  164. $('#bulk-edit').addClass('inline-editor').show();
  165. /**
  166. * Create a HTML div with the title and a link(delete-icon) for each selected
  167. * post.
  168. *
  169. * Get the selected posts based on the checked checkboxes in the post table.
  170. */
  171. $( 'tbody th.check-column input[type="checkbox"]' ).each( function() {
  172. // If the checkbox for a post is selected, add the post to the edit list.
  173. if ( $(this).prop('checked') ) {
  174. c = false;
  175. var id = $( this ).val(),
  176. theTitle = $( '#inline_' + id + ' .post_title' ).html() || wp.i18n.__( '(no title)' ),
  177. buttonVisuallyHiddenText = wp.i18n.sprintf(
  178. /* translators: %s: Post title. */
  179. wp.i18n.__( 'Remove &#8220;%s&#8221; from Bulk Edit' ),
  180. theTitle
  181. );
  182. te += '<li class="ntdelitem"><button type="button" id="_' + id + '" class="button-link ntdelbutton"><span class="screen-reader-text">' + buttonVisuallyHiddenText + '</span></button><span class="ntdeltitle" aria-hidden="true">' + theTitle + '</span></li>';
  183. }
  184. });
  185. // If no checkboxes where checked, just hide the quick/bulk edit rows.
  186. if ( c ) {
  187. return this.revert();
  188. }
  189. // Populate the list of items to bulk edit.
  190. $( '#bulk-titles' ).html( '<ul id="bulk-titles-list" role="list">' + te + '</ul>' );
  191. /**
  192. * Binds on click events to handle the list of items to bulk edit.
  193. *
  194. * @listens click
  195. */
  196. $( '#bulk-titles .ntdelbutton' ).click( function() {
  197. var $this = $( this ),
  198. id = $this.attr( 'id' ).substr( 1 ),
  199. $prev = $this.parent().prev().children( '.ntdelbutton' ),
  200. $next = $this.parent().next().children( '.ntdelbutton' );
  201. $( 'table.widefat input[value="' + id + '"]' ).prop( 'checked', false );
  202. $( '#_' + id ).parent().remove();
  203. wp.a11y.speak( wp.i18n.__( 'Item removed.' ), 'assertive' );
  204. // Move focus to a proper place when items are removed.
  205. if ( $next.length ) {
  206. $next.focus();
  207. } else if ( $prev.length ) {
  208. $prev.focus();
  209. } else {
  210. $( '#bulk-titles-list' ).remove();
  211. inlineEditPost.revert();
  212. wp.a11y.speak( wp.i18n.__( 'All selected items have been removed. Select new items to use Bulk Actions.' ) );
  213. }
  214. });
  215. // Enable auto-complete for tags when editing posts.
  216. if ( 'post' === type ) {
  217. $( 'tr.inline-editor textarea[data-wp-taxonomy]' ).each( function ( i, element ) {
  218. /*
  219. * While Quick Edit clones the form each time, Bulk Edit always re-uses
  220. * the same form. Let's check if an autocomplete instance already exists.
  221. */
  222. if ( $( element ).autocomplete( 'instance' ) ) {
  223. // jQuery equivalent of `continue` within an `each()` loop.
  224. return;
  225. }
  226. $( element ).wpTagsSuggest();
  227. } );
  228. }
  229. // Set initial focus on the Bulk Edit region.
  230. $( '#bulk-edit .inline-edit-wrapper' ).attr( 'tabindex', '-1' ).focus();
  231. // Scrolls to the top of the table where the editor is rendered.
  232. $('html, body').animate( { scrollTop: 0 }, 'fast' );
  233. },
  234. /**
  235. * Creates a quick edit window for the post that has been clicked.
  236. *
  237. * @since 2.7.0
  238. *
  239. * @memberof inlineEditPost
  240. *
  241. * @param {number|Object} id The ID of the clicked post or an element within a post
  242. * table row.
  243. * @return {boolean} Always returns false at the end of execution.
  244. */
  245. edit : function(id) {
  246. var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, f, val, pw;
  247. t.revert();
  248. if ( typeof(id) === 'object' ) {
  249. id = t.getId(id);
  250. }
  251. fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order', 'page_template'];
  252. if ( t.type === 'page' ) {
  253. fields.push('post_parent');
  254. }
  255. // Add the new edit row with an extra blank row underneath to maintain zebra striping.
  256. editRow = $('#inline-edit').clone(true);
  257. $( 'td', editRow ).attr( 'colspan', $( 'th:visible, td:visible', '.widefat:first thead' ).length );
  258. // Remove the ID from the copied row and let the `for` attribute reference the hidden ID.
  259. $( 'td', editRow ).find('#quick-edit-legend').removeAttr('id');
  260. $( 'td', editRow ).find('p[id^="quick-edit-"]').removeAttr('id');
  261. $(t.what+id).removeClass('is-expanded').hide().after(editRow).after('<tr class="hidden"></tr>');
  262. // Populate fields in the quick edit window.
  263. rowData = $('#inline_'+id);
  264. if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
  265. // The post author no longer has edit capabilities, so we need to add them to the list of authors.
  266. $(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#post-' + id + ' .author').text() + '</option>');
  267. }
  268. if ( $( ':input[name="post_author"] option', editRow ).length === 1 ) {
  269. $('label.inline-edit-author', editRow).hide();
  270. }
  271. for ( f = 0; f < fields.length; f++ ) {
  272. val = $('.'+fields[f], rowData);
  273. /**
  274. * Replaces the image for a Twemoji(Twitter emoji) with it's alternate text.
  275. *
  276. * @return {string} Alternate text from the image.
  277. */
  278. val.find( 'img' ).replaceWith( function() { return this.alt; } );
  279. val = val.text();
  280. $(':input[name="' + fields[f] + '"]', editRow).val( val );
  281. }
  282. if ( $( '.comment_status', rowData ).text() === 'open' ) {
  283. $( 'input[name="comment_status"]', editRow ).prop( 'checked', true );
  284. }
  285. if ( $( '.ping_status', rowData ).text() === 'open' ) {
  286. $( 'input[name="ping_status"]', editRow ).prop( 'checked', true );
  287. }
  288. if ( $( '.sticky', rowData ).text() === 'sticky' ) {
  289. $( 'input[name="sticky"]', editRow ).prop( 'checked', true );
  290. }
  291. /**
  292. * Creates the select boxes for the categories.
  293. */
  294. $('.post_category', rowData).each(function(){
  295. var taxname,
  296. term_ids = $(this).text();
  297. if ( term_ids ) {
  298. taxname = $(this).attr('id').replace('_'+id, '');
  299. $('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
  300. }
  301. });
  302. /**
  303. * Gets all the taxonomies for live auto-fill suggestions when typing the name
  304. * of a tag.
  305. */
  306. $('.tags_input', rowData).each(function(){
  307. var terms = $(this),
  308. taxname = $(this).attr('id').replace('_' + id, ''),
  309. textarea = $('textarea.tax_input_' + taxname, editRow),
  310. comma = wp.i18n._x( ',', 'tag delimiter' ).trim();
  311. // Ensure the textarea exists.
  312. if ( ! textarea.length ) {
  313. return;
  314. }
  315. terms.find( 'img' ).replaceWith( function() { return this.alt; } );
  316. terms = terms.text();
  317. if ( terms ) {
  318. if ( ',' !== comma ) {
  319. terms = terms.replace(/,/g, comma);
  320. }
  321. textarea.val(terms);
  322. }
  323. textarea.wpTagsSuggest();
  324. });
  325. // Handle the post status.
  326. var post_date_string = $(':input[name="aa"]').val() + '-' + $(':input[name="mm"]').val() + '-' + $(':input[name="jj"]').val();
  327. post_date_string += ' ' + $(':input[name="hh"]').val() + ':' + $(':input[name="mn"]').val() + ':' + $(':input[name="ss"]').val();
  328. var post_date = new Date( post_date_string );
  329. status = $('._status', rowData).text();
  330. if ( 'future' !== status && Date.now() > post_date ) {
  331. $('select[name="_status"] option[value="future"]', editRow).remove();
  332. } else {
  333. $('select[name="_status"] option[value="publish"]', editRow).remove();
  334. }
  335. pw = $( '.inline-edit-password-input' ).prop( 'disabled', false );
  336. if ( 'private' === status ) {
  337. $('input[name="keep_private"]', editRow).prop('checked', true);
  338. pw.val( '' ).prop( 'disabled', true );
  339. }
  340. // Remove the current page and children from the parent dropdown.
  341. pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
  342. if ( pageOpt.length > 0 ) {
  343. pageLevel = pageOpt[0].className.split('-')[1];
  344. nextPage = pageOpt;
  345. while ( pageLoop ) {
  346. nextPage = nextPage.next('option');
  347. if ( nextPage.length === 0 ) {
  348. break;
  349. }
  350. nextLevel = nextPage[0].className.split('-')[1];
  351. if ( nextLevel <= pageLevel ) {
  352. pageLoop = false;
  353. } else {
  354. nextPage.remove();
  355. nextPage = pageOpt;
  356. }
  357. }
  358. pageOpt.remove();
  359. }
  360. $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
  361. $('.ptitle', editRow).trigger( 'focus' );
  362. return false;
  363. },
  364. /**
  365. * Saves the changes made in the quick edit window to the post.
  366. * Ajax saving is only for Quick Edit and not for bulk edit.
  367. *
  368. * @since 2.7.0
  369. *
  370. * @param {number} id The ID for the post that has been changed.
  371. * @return {boolean} False, so the form does not submit when pressing
  372. * Enter on a focused field.
  373. */
  374. save : function(id) {
  375. var params, fields, page = $('.post_status_page').val() || '';
  376. if ( typeof(id) === 'object' ) {
  377. id = this.getId(id);
  378. }
  379. $( 'table.widefat .spinner' ).addClass( 'is-active' );
  380. params = {
  381. action: 'inline-save',
  382. post_type: typenow,
  383. post_ID: id,
  384. edit_date: 'true',
  385. post_status: page
  386. };
  387. fields = $('#edit-'+id).find(':input').serialize();
  388. params = fields + '&' + $.param(params);
  389. // Make Ajax request.
  390. $.post( ajaxurl, params,
  391. function(r) {
  392. var $errorNotice = $( '#edit-' + id + ' .inline-edit-save .notice-error' ),
  393. $error = $errorNotice.find( '.error' );
  394. $( 'table.widefat .spinner' ).removeClass( 'is-active' );
  395. if (r) {
  396. if ( -1 !== r.indexOf( '<tr' ) ) {
  397. $(inlineEditPost.what+id).siblings('tr.hidden').addBack().remove();
  398. $('#edit-'+id).before(r).remove();
  399. $( inlineEditPost.what + id ).hide().fadeIn( 400, function() {
  400. // Move focus back to the Quick Edit button. $( this ) is the row being animated.
  401. $( this ).find( '.editinline' )
  402. .attr( 'aria-expanded', 'false' )
  403. .trigger( 'focus' );
  404. wp.a11y.speak( wp.i18n.__( 'Changes saved.' ) );
  405. });
  406. } else {
  407. r = r.replace( /<.[^<>]*?>/g, '' );
  408. $errorNotice.removeClass( 'hidden' );
  409. $error.html( r );
  410. wp.a11y.speak( $error.text() );
  411. }
  412. } else {
  413. $errorNotice.removeClass( 'hidden' );
  414. $error.text( wp.i18n.__( 'Error while saving the changes.' ) );
  415. wp.a11y.speak( wp.i18n.__( 'Error while saving the changes.' ) );
  416. }
  417. },
  418. 'html');
  419. // Prevent submitting the form when pressing Enter on a focused field.
  420. return false;
  421. },
  422. /**
  423. * Hides and empties the Quick Edit and/or Bulk Edit windows.
  424. *
  425. * @since 2.7.0
  426. *
  427. * @memberof inlineEditPost
  428. *
  429. * @return {boolean} Always returns false.
  430. */
  431. revert : function(){
  432. var $tableWideFat = $( '.widefat' ),
  433. id = $( '.inline-editor', $tableWideFat ).attr( 'id' );
  434. if ( id ) {
  435. $( '.spinner', $tableWideFat ).removeClass( 'is-active' );
  436. if ( 'bulk-edit' === id ) {
  437. // Hide the bulk editor.
  438. $( '#bulk-edit', $tableWideFat ).removeClass( 'inline-editor' ).hide().siblings( '.hidden' ).remove();
  439. $('#bulk-titles').empty();
  440. // Store the empty bulk editor in a hidden element.
  441. $('#inlineedit').append( $('#bulk-edit') );
  442. // Move focus back to the Bulk Action button that was activated.
  443. $( '#' + inlineEditPost.whichBulkButtonId ).trigger( 'focus' );
  444. } else {
  445. // Remove both the inline-editor and its hidden tr siblings.
  446. $('#'+id).siblings('tr.hidden').addBack().remove();
  447. id = id.substr( id.lastIndexOf('-') + 1 );
  448. // Show the post row and move focus back to the Quick Edit button.
  449. $( this.what + id ).show().find( '.editinline' )
  450. .attr( 'aria-expanded', 'false' )
  451. .trigger( 'focus' );
  452. }
  453. }
  454. return false;
  455. },
  456. /**
  457. * Gets the ID for a the post that you want to quick edit from the row in the quick
  458. * edit table.
  459. *
  460. * @since 2.7.0
  461. *
  462. * @memberof inlineEditPost
  463. *
  464. * @param {Object} o DOM row object to get the ID for.
  465. * @return {string} The post ID extracted from the table row in the object.
  466. */
  467. getId : function(o) {
  468. var id = $(o).closest('tr').attr('id'),
  469. parts = id.split('-');
  470. return parts[parts.length - 1];
  471. }
  472. };
  473. $( function() { inlineEditPost.init(); } );
  474. // Show/hide locks on posts.
  475. $( function() {
  476. // Set the heartbeat interval to 15 seconds.
  477. if ( typeof wp !== 'undefined' && wp.heartbeat ) {
  478. wp.heartbeat.interval( 15 );
  479. }
  480. }).on( 'heartbeat-tick.wp-check-locked-posts', function( e, data ) {
  481. var locked = data['wp-check-locked-posts'] || {};
  482. $('#the-list tr').each( function(i, el) {
  483. var key = el.id, row = $(el), lock_data, avatar;
  484. if ( locked.hasOwnProperty( key ) ) {
  485. if ( ! row.hasClass('wp-locked') ) {
  486. lock_data = locked[key];
  487. row.find('.column-title .locked-text').text( lock_data.text );
  488. row.find('.check-column checkbox').prop('checked', false);
  489. if ( lock_data.avatar_src ) {
  490. avatar = $( '<img />', {
  491. 'class': 'avatar avatar-18 photo',
  492. width: 18,
  493. height: 18,
  494. alt: '',
  495. src: lock_data.avatar_src,
  496. srcset: lock_data.avatar_src_2x ? lock_data.avatar_src_2x + ' 2x' : undefined
  497. } );
  498. row.find('.column-title .locked-avatar').empty().append( avatar );
  499. }
  500. row.addClass('wp-locked');
  501. }
  502. } else if ( row.hasClass('wp-locked') ) {
  503. row.removeClass( 'wp-locked' ).find( '.locked-info span' ).empty();
  504. }
  505. });
  506. }).on( 'heartbeat-send.wp-check-locked-posts', function( e, data ) {
  507. var check = [];
  508. $('#the-list tr').each( function(i, el) {
  509. if ( el.id ) {
  510. check.push( el.id );
  511. }
  512. });
  513. if ( check.length ) {
  514. data['wp-check-locked-posts'] = check;
  515. }
  516. });
  517. })( jQuery, window.wp );