inline-edit-post.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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() + '">' + $('#' + t.type + '-' + 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. status = $('._status', rowData).text();
  327. if ( 'future' !== status ) {
  328. $('select[name="_status"] option[value="future"]', editRow).remove();
  329. }
  330. pw = $( '.inline-edit-password-input' ).prop( 'disabled', false );
  331. if ( 'private' === status ) {
  332. $('input[name="keep_private"]', editRow).prop('checked', true);
  333. pw.val( '' ).prop( 'disabled', true );
  334. }
  335. // Remove the current page and children from the parent dropdown.
  336. pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
  337. if ( pageOpt.length > 0 ) {
  338. pageLevel = pageOpt[0].className.split('-')[1];
  339. nextPage = pageOpt;
  340. while ( pageLoop ) {
  341. nextPage = nextPage.next('option');
  342. if ( nextPage.length === 0 ) {
  343. break;
  344. }
  345. nextLevel = nextPage[0].className.split('-')[1];
  346. if ( nextLevel <= pageLevel ) {
  347. pageLoop = false;
  348. } else {
  349. nextPage.remove();
  350. nextPage = pageOpt;
  351. }
  352. }
  353. pageOpt.remove();
  354. }
  355. $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
  356. $('.ptitle', editRow).trigger( 'focus' );
  357. return false;
  358. },
  359. /**
  360. * Saves the changes made in the quick edit window to the post.
  361. * Ajax saving is only for Quick Edit and not for bulk edit.
  362. *
  363. * @since 2.7.0
  364. *
  365. * @param {number} id The ID for the post that has been changed.
  366. * @return {boolean} False, so the form does not submit when pressing
  367. * Enter on a focused field.
  368. */
  369. save : function(id) {
  370. var params, fields, page = $('.post_status_page').val() || '';
  371. if ( typeof(id) === 'object' ) {
  372. id = this.getId(id);
  373. }
  374. $( 'table.widefat .spinner' ).addClass( 'is-active' );
  375. params = {
  376. action: 'inline-save',
  377. post_type: typenow,
  378. post_ID: id,
  379. edit_date: 'true',
  380. post_status: page
  381. };
  382. fields = $('#edit-'+id).find(':input').serialize();
  383. params = fields + '&' + $.param(params);
  384. // Make Ajax request.
  385. $.post( ajaxurl, params,
  386. function(r) {
  387. var $errorNotice = $( '#edit-' + id + ' .inline-edit-save .notice-error' ),
  388. $error = $errorNotice.find( '.error' );
  389. $( 'table.widefat .spinner' ).removeClass( 'is-active' );
  390. if (r) {
  391. if ( -1 !== r.indexOf( '<tr' ) ) {
  392. $(inlineEditPost.what+id).siblings('tr.hidden').addBack().remove();
  393. $('#edit-'+id).before(r).remove();
  394. $( inlineEditPost.what + id ).hide().fadeIn( 400, function() {
  395. // Move focus back to the Quick Edit button. $( this ) is the row being animated.
  396. $( this ).find( '.editinline' )
  397. .attr( 'aria-expanded', 'false' )
  398. .trigger( 'focus' );
  399. wp.a11y.speak( wp.i18n.__( 'Changes saved.' ) );
  400. });
  401. } else {
  402. r = r.replace( /<.[^<>]*?>/g, '' );
  403. $errorNotice.removeClass( 'hidden' );
  404. $error.html( r );
  405. wp.a11y.speak( $error.text() );
  406. }
  407. } else {
  408. $errorNotice.removeClass( 'hidden' );
  409. $error.text( wp.i18n.__( 'Error while saving the changes.' ) );
  410. wp.a11y.speak( wp.i18n.__( 'Error while saving the changes.' ) );
  411. }
  412. },
  413. 'html');
  414. // Prevent submitting the form when pressing Enter on a focused field.
  415. return false;
  416. },
  417. /**
  418. * Hides and empties the Quick Edit and/or Bulk Edit windows.
  419. *
  420. * @since 2.7.0
  421. *
  422. * @memberof inlineEditPost
  423. *
  424. * @return {boolean} Always returns false.
  425. */
  426. revert : function(){
  427. var $tableWideFat = $( '.widefat' ),
  428. id = $( '.inline-editor', $tableWideFat ).attr( 'id' );
  429. if ( id ) {
  430. $( '.spinner', $tableWideFat ).removeClass( 'is-active' );
  431. if ( 'bulk-edit' === id ) {
  432. // Hide the bulk editor.
  433. $( '#bulk-edit', $tableWideFat ).removeClass( 'inline-editor' ).hide().siblings( '.hidden' ).remove();
  434. $('#bulk-titles').empty();
  435. // Store the empty bulk editor in a hidden element.
  436. $('#inlineedit').append( $('#bulk-edit') );
  437. // Move focus back to the Bulk Action button that was activated.
  438. $( '#' + inlineEditPost.whichBulkButtonId ).trigger( 'focus' );
  439. } else {
  440. // Remove both the inline-editor and its hidden tr siblings.
  441. $('#'+id).siblings('tr.hidden').addBack().remove();
  442. id = id.substr( id.lastIndexOf('-') + 1 );
  443. // Show the post row and move focus back to the Quick Edit button.
  444. $( this.what + id ).show().find( '.editinline' )
  445. .attr( 'aria-expanded', 'false' )
  446. .trigger( 'focus' );
  447. }
  448. }
  449. return false;
  450. },
  451. /**
  452. * Gets the ID for a the post that you want to quick edit from the row in the quick
  453. * edit table.
  454. *
  455. * @since 2.7.0
  456. *
  457. * @memberof inlineEditPost
  458. *
  459. * @param {Object} o DOM row object to get the ID for.
  460. * @return {string} The post ID extracted from the table row in the object.
  461. */
  462. getId : function(o) {
  463. var id = $(o).closest('tr').attr('id'),
  464. parts = id.split('-');
  465. return parts[parts.length - 1];
  466. }
  467. };
  468. $( function() { inlineEditPost.init(); } );
  469. // Show/hide locks on posts.
  470. $( function() {
  471. // Set the heartbeat interval to 15 seconds.
  472. if ( typeof wp !== 'undefined' && wp.heartbeat ) {
  473. wp.heartbeat.interval( 15 );
  474. }
  475. }).on( 'heartbeat-tick.wp-check-locked-posts', function( e, data ) {
  476. var locked = data['wp-check-locked-posts'] || {};
  477. $('#the-list tr').each( function(i, el) {
  478. var key = el.id, row = $(el), lock_data, avatar;
  479. if ( locked.hasOwnProperty( key ) ) {
  480. if ( ! row.hasClass('wp-locked') ) {
  481. lock_data = locked[key];
  482. row.find('.column-title .locked-text').text( lock_data.text );
  483. row.find('.check-column checkbox').prop('checked', false);
  484. if ( lock_data.avatar_src ) {
  485. avatar = $( '<img />', {
  486. 'class': 'avatar avatar-18 photo',
  487. width: 18,
  488. height: 18,
  489. alt: '',
  490. src: lock_data.avatar_src,
  491. srcset: lock_data.avatar_src_2x ? lock_data.avatar_src_2x + ' 2x' : undefined
  492. } );
  493. row.find('.column-title .locked-avatar').empty().append( avatar );
  494. }
  495. row.addClass('wp-locked');
  496. }
  497. } else if ( row.hasClass('wp-locked') ) {
  498. row.removeClass( 'wp-locked' ).find( '.locked-info span' ).empty();
  499. }
  500. });
  501. }).on( 'heartbeat-send.wp-check-locked-posts', function( e, data ) {
  502. var check = [];
  503. $('#the-list tr').each( function(i, el) {
  504. if ( el.id ) {
  505. check.push( el.id );
  506. }
  507. });
  508. if ( check.length ) {
  509. data['wp-check-locked-posts'] = check;
  510. }
  511. });
  512. })( jQuery, window.wp );