[ Index ] |
PHP Cross Reference of WordPress |
[Summary view] [Print] [Text view]
1 /** 2 * @file Contains all dynamic functionality needed on post and term pages. 3 * 4 * @output wp-admin/js/post.js 5 */ 6 7 /* global ajaxurl, wpAjax, postboxes, pagenow, tinymce, alert, deleteUserSetting, ClipboardJS */ 8 /* global theList:true, theExtraList:true, getUserSetting, setUserSetting, commentReply, commentsBox */ 9 /* global WPSetThumbnailHTML, wptitlehint */ 10 11 // Backward compatibility: prevent fatal errors. 12 window.makeSlugeditClickable = window.editPermalink = function(){}; 13 14 // Make sure the wp object exists. 15 window.wp = window.wp || {}; 16 17 ( function( $ ) { 18 var titleHasFocus = false, 19 __ = wp.i18n.__; 20 21 /** 22 * Control loading of comments on the post and term edit pages. 23 * 24 * @type {{st: number, get: commentsBox.get, load: commentsBox.load}} 25 * 26 * @namespace commentsBox 27 */ 28 window.commentsBox = { 29 // Comment offset to use when fetching new comments. 30 st : 0, 31 32 /** 33 * Fetch comments using Ajax and display them in the box. 34 * 35 * @memberof commentsBox 36 * 37 * @param {number} total Total number of comments for this post. 38 * @param {number} num Optional. Number of comments to fetch, defaults to 20. 39 * @return {boolean} Always returns false. 40 */ 41 get : function(total, num) { 42 var st = this.st, data; 43 if ( ! num ) 44 num = 20; 45 46 this.st += num; 47 this.total = total; 48 $( '#commentsdiv .spinner' ).addClass( 'is-active' ); 49 50 data = { 51 'action' : 'get-comments', 52 'mode' : 'single', 53 '_ajax_nonce' : $('#add_comment_nonce').val(), 54 'p' : $('#post_ID').val(), 55 'start' : st, 56 'number' : num 57 }; 58 59 $.post( 60 ajaxurl, 61 data, 62 function(r) { 63 r = wpAjax.parseAjaxResponse(r); 64 $('#commentsdiv .widefat').show(); 65 $( '#commentsdiv .spinner' ).removeClass( 'is-active' ); 66 67 if ( 'object' == typeof r && r.responses[0] ) { 68 $('#the-comment-list').append( r.responses[0].data ); 69 70 theList = theExtraList = null; 71 $( 'a[className*=\':\']' ).off(); 72 73 // If the offset is over the total number of comments we cannot fetch any more, so hide the button. 74 if ( commentsBox.st > commentsBox.total ) 75 $('#show-comments').hide(); 76 else 77 $('#show-comments').show().children('a').text( __( 'Show more comments' ) ); 78 79 return; 80 } else if ( 1 == r ) { 81 $('#show-comments').text( __( 'No more comments found.' ) ); 82 return; 83 } 84 85 $('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>'); 86 } 87 ); 88 89 return false; 90 }, 91 92 /** 93 * Load the next batch of comments. 94 * 95 * @memberof commentsBox 96 * 97 * @param {number} total Total number of comments to load. 98 */ 99 load: function(total){ 100 this.st = jQuery('#the-comment-list tr.comment:visible').length; 101 this.get(total); 102 } 103 }; 104 105 /** 106 * Overwrite the content of the Featured Image postbox 107 * 108 * @param {string} html New HTML to be displayed in the content area of the postbox. 109 * 110 * @global 111 */ 112 window.WPSetThumbnailHTML = function(html){ 113 $('.inside', '#postimagediv').html(html); 114 }; 115 116 /** 117 * Set the Image ID of the Featured Image 118 * 119 * @param {number} id The post_id of the image to use as Featured Image. 120 * 121 * @global 122 */ 123 window.WPSetThumbnailID = function(id){ 124 var field = $('input[value="_thumbnail_id"]', '#list-table'); 125 if ( field.length > 0 ) { 126 $('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id); 127 } 128 }; 129 130 /** 131 * Remove the Featured Image 132 * 133 * @param {string} nonce Nonce to use in the request. 134 * 135 * @global 136 */ 137 window.WPRemoveThumbnail = function(nonce){ 138 $.post( 139 ajaxurl, { 140 action: 'set-post-thumbnail', 141 post_id: $( '#post_ID' ).val(), 142 thumbnail_id: -1, 143 _ajax_nonce: nonce, 144 cookie: encodeURIComponent( document.cookie ) 145 }, 146 /** 147 * Handle server response 148 * 149 * @param {string} str Response, will be '0' when an error occurred otherwise contains link to add Featured Image. 150 */ 151 function(str){ 152 if ( str == '0' ) { 153 alert( __( 'Could not set that as the thumbnail image. Try a different attachment.' ) ); 154 } else { 155 WPSetThumbnailHTML(str); 156 } 157 } 158 ); 159 }; 160 161 /** 162 * Heartbeat locks. 163 * 164 * Used to lock editing of an object by only one user at a time. 165 * 166 * When the user does not send a heartbeat in a heartbeat-time 167 * the user is no longer editing and another user can start editing. 168 */ 169 $(document).on( 'heartbeat-send.refresh-lock', function( e, data ) { 170 var lock = $('#active_post_lock').val(), 171 post_id = $('#post_ID').val(), 172 send = {}; 173 174 if ( ! post_id || ! $('#post-lock-dialog').length ) 175 return; 176 177 send.post_id = post_id; 178 179 if ( lock ) 180 send.lock = lock; 181 182 data['wp-refresh-post-lock'] = send; 183 184 }).on( 'heartbeat-tick.refresh-lock', function( e, data ) { 185 // Post locks: update the lock string or show the dialog if somebody has taken over editing. 186 var received, wrap, avatar; 187 188 if ( data['wp-refresh-post-lock'] ) { 189 received = data['wp-refresh-post-lock']; 190 191 if ( received.lock_error ) { 192 // Show "editing taken over" message. 193 wrap = $('#post-lock-dialog'); 194 195 if ( wrap.length && ! wrap.is(':visible') ) { 196 if ( wp.autosave ) { 197 // Save the latest changes and disable. 198 $(document).one( 'heartbeat-tick', function() { 199 wp.autosave.server.suspend(); 200 wrap.removeClass('saving').addClass('saved'); 201 $(window).off( 'beforeunload.edit-post' ); 202 }); 203 204 wrap.addClass('saving'); 205 wp.autosave.server.triggerSave(); 206 } 207 208 if ( received.lock_error.avatar_src ) { 209 avatar = $( '<img />', { 210 'class': 'avatar avatar-64 photo', 211 width: 64, 212 height: 64, 213 alt: '', 214 src: received.lock_error.avatar_src, 215 srcset: received.lock_error.avatar_src_2x ? 216 received.lock_error.avatar_src_2x + ' 2x' : 217 undefined 218 } ); 219 wrap.find('div.post-locked-avatar').empty().append( avatar ); 220 } 221 222 wrap.show().find('.currently-editing').text( received.lock_error.text ); 223 wrap.find('.wp-tab-first').trigger( 'focus' ); 224 } 225 } else if ( received.new_lock ) { 226 $('#active_post_lock').val( received.new_lock ); 227 } 228 } 229 }).on( 'before-autosave.update-post-slug', function() { 230 titleHasFocus = document.activeElement && document.activeElement.id === 'title'; 231 }).on( 'after-autosave.update-post-slug', function() { 232 233 /* 234 * Create slug area only if not already there 235 * and the title field was not focused (user was not typing a title) when autosave ran. 236 */ 237 if ( ! $('#edit-slug-box > *').length && ! titleHasFocus ) { 238 $.post( ajaxurl, { 239 action: 'sample-permalink', 240 post_id: $('#post_ID').val(), 241 new_title: $('#title').val(), 242 samplepermalinknonce: $('#samplepermalinknonce').val() 243 }, 244 function( data ) { 245 if ( data != '-1' ) { 246 $('#edit-slug-box').html(data); 247 } 248 } 249 ); 250 } 251 }); 252 253 }(jQuery)); 254 255 /** 256 * Heartbeat refresh nonces. 257 */ 258 (function($) { 259 var check, timeout; 260 261 /** 262 * Only allow to check for nonce refresh every 30 seconds. 263 */ 264 function schedule() { 265 check = false; 266 window.clearTimeout( timeout ); 267 timeout = window.setTimeout( function(){ check = true; }, 300000 ); 268 } 269 270 $( function() { 271 schedule(); 272 }).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) { 273 var post_id, 274 $authCheck = $('#wp-auth-check-wrap'); 275 276 if ( check || ( $authCheck.length && ! $authCheck.hasClass( 'hidden' ) ) ) { 277 if ( ( post_id = $('#post_ID').val() ) && $('#_wpnonce').val() ) { 278 data['wp-refresh-post-nonces'] = { 279 post_id: post_id 280 }; 281 } 282 } 283 }).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) { 284 var nonces = data['wp-refresh-post-nonces']; 285 286 if ( nonces ) { 287 schedule(); 288 289 if ( nonces.replace ) { 290 $.each( nonces.replace, function( selector, value ) { 291 $( '#' + selector ).val( value ); 292 }); 293 } 294 295 if ( nonces.heartbeatNonce ) 296 window.heartbeatSettings.nonce = nonces.heartbeatNonce; 297 } 298 }); 299 }(jQuery)); 300 301 /** 302 * All post and postbox controls and functionality. 303 */ 304 jQuery( function($) { 305 var stamp, visibility, $submitButtons, updateVisibility, updateText, 306 $textarea = $('#content'), 307 $document = $(document), 308 postId = $('#post_ID').val() || 0, 309 $submitpost = $('#submitpost'), 310 releaseLock = true, 311 $postVisibilitySelect = $('#post-visibility-select'), 312 $timestampdiv = $('#timestampdiv'), 313 $postStatusSelect = $('#post-status-select'), 314 isMac = window.navigator.platform ? window.navigator.platform.indexOf( 'Mac' ) !== -1 : false, 315 copyAttachmentURLClipboard = new ClipboardJS( '.copy-attachment-url.edit-media' ), 316 copyAttachmentURLSuccessTimeout, 317 __ = wp.i18n.__, _x = wp.i18n._x; 318 319 postboxes.add_postbox_toggles(pagenow); 320 321 /* 322 * Clear the window name. Otherwise if this is a former preview window where the user navigated to edit another post, 323 * and the first post is still being edited, clicking Preview there will use this window to show the preview. 324 */ 325 window.name = ''; 326 327 // Post locks: contain focus inside the dialog. If the dialog is shown, focus the first item. 328 $('#post-lock-dialog .notification-dialog').on( 'keydown', function(e) { 329 // Don't do anything when [Tab] is pressed. 330 if ( e.which != 9 ) 331 return; 332 333 var target = $(e.target); 334 335 // [Shift] + [Tab] on first tab cycles back to last tab. 336 if ( target.hasClass('wp-tab-first') && e.shiftKey ) { 337 $(this).find('.wp-tab-last').trigger( 'focus' ); 338 e.preventDefault(); 339 // [Tab] on last tab cycles back to first tab. 340 } else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) { 341 $(this).find('.wp-tab-first').trigger( 'focus' ); 342 e.preventDefault(); 343 } 344 }).filter(':visible').find('.wp-tab-first').trigger( 'focus' ); 345 346 // Set the heartbeat interval to 15 seconds if post lock dialogs are enabled. 347 if ( wp.heartbeat && $('#post-lock-dialog').length ) { 348 wp.heartbeat.interval( 15 ); 349 } 350 351 // The form is being submitted by the user. 352 $submitButtons = $submitpost.find( ':submit, a.submitdelete, #post-preview' ).on( 'click.edit-post', function( event ) { 353 var $button = $(this); 354 355 if ( $button.hasClass('disabled') ) { 356 event.preventDefault(); 357 return; 358 } 359 360 if ( $button.hasClass('submitdelete') || $button.is( '#post-preview' ) ) { 361 return; 362 } 363 364 // The form submission can be blocked from JS or by using HTML 5.0 validation on some fields. 365 // Run this only on an actual 'submit'. 366 $('form#post').off( 'submit.edit-post' ).on( 'submit.edit-post', function( event ) { 367 if ( event.isDefaultPrevented() ) { 368 return; 369 } 370 371 // Stop auto save. 372 if ( wp.autosave ) { 373 wp.autosave.server.suspend(); 374 } 375 376 if ( typeof commentReply !== 'undefined' ) { 377 /* 378 * Warn the user they have an unsaved comment before submitting 379 * the post data for update. 380 */ 381 if ( ! commentReply.discardCommentChanges() ) { 382 return false; 383 } 384 385 /* 386 * Close the comment edit/reply form if open to stop the form 387 * action from interfering with the post's form action. 388 */ 389 commentReply.close(); 390 } 391 392 releaseLock = false; 393 $(window).off( 'beforeunload.edit-post' ); 394 395 $submitButtons.addClass( 'disabled' ); 396 397 if ( $button.attr('id') === 'publish' ) { 398 $submitpost.find( '#major-publishing-actions .spinner' ).addClass( 'is-active' ); 399 } else { 400 $submitpost.find( '#minor-publishing .spinner' ).addClass( 'is-active' ); 401 } 402 }); 403 }); 404 405 // Submit the form saving a draft or an autosave, and show a preview in a new tab. 406 $('#post-preview').on( 'click.post-preview', function( event ) { 407 var $this = $(this), 408 $form = $('form#post'), 409 $previewField = $('input#wp-preview'), 410 target = $this.attr('target') || 'wp-preview', 411 ua = navigator.userAgent.toLowerCase(); 412 413 event.preventDefault(); 414 415 if ( $this.hasClass('disabled') ) { 416 return; 417 } 418 419 if ( wp.autosave ) { 420 wp.autosave.server.tempBlockSave(); 421 } 422 423 $previewField.val('dopreview'); 424 $form.attr( 'target', target ).trigger( 'submit' ).attr( 'target', '' ); 425 426 // Workaround for WebKit bug preventing a form submitting twice to the same action. 427 // https://bugs.webkit.org/show_bug.cgi?id=28633 428 if ( ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1 ) { 429 $form.attr( 'action', function( index, value ) { 430 return value + '?t=' + ( new Date() ).getTime(); 431 }); 432 } 433 434 $previewField.val(''); 435 }); 436 437 // This code is meant to allow tabbing from Title to Post content. 438 $('#title').on( 'keydown.editor-focus', function( event ) { 439 var editor; 440 441 if ( event.keyCode === 9 && ! event.ctrlKey && ! event.altKey && ! event.shiftKey ) { 442 editor = typeof tinymce != 'undefined' && tinymce.get('content'); 443 444 if ( editor && ! editor.isHidden() ) { 445 editor.focus(); 446 } else if ( $textarea.length ) { 447 $textarea.trigger( 'focus' ); 448 } else { 449 return; 450 } 451 452 event.preventDefault(); 453 } 454 }); 455 456 // Auto save new posts after a title is typed. 457 if ( $( '#auto_draft' ).val() ) { 458 $( '#title' ).on( 'blur', function() { 459 var cancel; 460 461 if ( ! this.value || $('#edit-slug-box > *').length ) { 462 return; 463 } 464 465 // Cancel the auto save when the blur was triggered by the user submitting the form. 466 $('form#post').one( 'submit', function() { 467 cancel = true; 468 }); 469 470 window.setTimeout( function() { 471 if ( ! cancel && wp.autosave ) { 472 wp.autosave.server.triggerSave(); 473 } 474 }, 200 ); 475 }); 476 } 477 478 $document.on( 'autosave-disable-buttons.edit-post', function() { 479 $submitButtons.addClass( 'disabled' ); 480 }).on( 'autosave-enable-buttons.edit-post', function() { 481 if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) { 482 $submitButtons.removeClass( 'disabled' ); 483 } 484 }).on( 'before-autosave.edit-post', function() { 485 $( '.autosave-message' ).text( __( 'Saving Draft…' ) ); 486 }).on( 'after-autosave.edit-post', function( event, data ) { 487 $( '.autosave-message' ).text( data.message ); 488 489 if ( $( document.body ).hasClass( 'post-new-php' ) ) { 490 $( '.submitbox .submitdelete' ).show(); 491 } 492 }); 493 494 /* 495 * When the user is trying to load another page, or reloads current page 496 * show a confirmation dialog when there are unsaved changes. 497 */ 498 $( window ).on( 'beforeunload.edit-post', function( event ) { 499 var editor = window.tinymce && window.tinymce.get( 'content' ); 500 var changed = false; 501 502 if ( wp.autosave ) { 503 changed = wp.autosave.server.postChanged(); 504 } else if ( editor ) { 505 changed = ( ! editor.isHidden() && editor.isDirty() ); 506 } 507 508 if ( changed ) { 509 event.preventDefault(); 510 // The return string is needed for browser compat. 511 // See https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event. 512 return __( 'The changes you made will be lost if you navigate away from this page.' ); 513 } 514 }).on( 'unload.edit-post', function( event ) { 515 if ( ! releaseLock ) { 516 return; 517 } 518 519 /* 520 * Unload is triggered (by hand) on removing the Thickbox iframe. 521 * Make sure we process only the main document unload. 522 */ 523 if ( event.target && event.target.nodeName != '#document' ) { 524 return; 525 } 526 527 var postID = $('#post_ID').val(); 528 var postLock = $('#active_post_lock').val(); 529 530 if ( ! postID || ! postLock ) { 531 return; 532 } 533 534 var data = { 535 action: 'wp-remove-post-lock', 536 _wpnonce: $('#_wpnonce').val(), 537 post_ID: postID, 538 active_post_lock: postLock 539 }; 540 541 if ( window.FormData && window.navigator.sendBeacon ) { 542 var formData = new window.FormData(); 543 544 $.each( data, function( key, value ) { 545 formData.append( key, value ); 546 }); 547 548 if ( window.navigator.sendBeacon( ajaxurl, formData ) ) { 549 return; 550 } 551 } 552 553 // Fall back to a synchronous POST request. 554 // See https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon 555 $.post({ 556 async: false, 557 data: data, 558 url: ajaxurl 559 }); 560 }); 561 562 // Multiple taxonomies. 563 if ( $('#tagsdiv-post_tag').length ) { 564 window.tagBox && window.tagBox.init(); 565 } else { 566 $('.meta-box-sortables').children('div.postbox').each(function(){ 567 if ( this.id.indexOf('tagsdiv-') === 0 ) { 568 window.tagBox && window.tagBox.init(); 569 return false; 570 } 571 }); 572 } 573 574 // Handle categories. 575 $('.categorydiv').each( function(){ 576 var this_id = $(this).attr('id'), catAddBefore, catAddAfter, taxonomyParts, taxonomy, settingName; 577 578 taxonomyParts = this_id.split('-'); 579 taxonomyParts.shift(); 580 taxonomy = taxonomyParts.join('-'); 581 settingName = taxonomy + '_tab'; 582 583 if ( taxonomy == 'category' ) { 584 settingName = 'cats'; 585 } 586 587 // @todo Move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.js. 588 $('a', '#' + taxonomy + '-tabs').on( 'click', function( e ) { 589 e.preventDefault(); 590 var t = $(this).attr('href'); 591 $(this).parent().addClass('tabs').siblings('li').removeClass('tabs'); 592 $('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide(); 593 $(t).show(); 594 if ( '#' + taxonomy + '-all' == t ) { 595 deleteUserSetting( settingName ); 596 } else { 597 setUserSetting( settingName, 'pop' ); 598 } 599 }); 600 601 if ( getUserSetting( settingName ) ) 602 $('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').trigger( 'click' ); 603 604 // Add category button controls. 605 $('#new' + taxonomy).one( 'focus', function() { 606 $( this ).val( '' ).removeClass( 'form-input-tip' ); 607 }); 608 609 // On [Enter] submit the taxonomy. 610 $('#new' + taxonomy).on( 'keypress', function(event){ 611 if( 13 === event.keyCode ) { 612 event.preventDefault(); 613 $('#' + taxonomy + '-add-submit').trigger( 'click' ); 614 } 615 }); 616 617 // After submitting a new taxonomy, re-focus the input field. 618 $('#' + taxonomy + '-add-submit').on( 'click', function() { 619 $('#new' + taxonomy).trigger( 'focus' ); 620 }); 621 622 /** 623 * Before adding a new taxonomy, disable submit button. 624 * 625 * @param {Object} s Taxonomy object which will be added. 626 * 627 * @return {Object} 628 */ 629 catAddBefore = function( s ) { 630 if ( !$('#new'+taxonomy).val() ) { 631 return false; 632 } 633 634 s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize(); 635 $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true ); 636 return s; 637 }; 638 639 /** 640 * Re-enable submit button after a taxonomy has been added. 641 * 642 * Re-enable submit button. 643 * If the taxonomy has a parent place the taxonomy underneath the parent. 644 * 645 * @param {Object} r Response. 646 * @param {Object} s Taxonomy data. 647 * 648 * @return {void} 649 */ 650 catAddAfter = function( r, s ) { 651 var sup, drop = $('#new'+taxonomy+'_parent'); 652 653 $( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false ); 654 if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) { 655 drop.before(sup); 656 drop.remove(); 657 } 658 }; 659 660 $('#' + taxonomy + 'checklist').wpList({ 661 alt: '', 662 response: taxonomy + '-ajax-response', 663 addBefore: catAddBefore, 664 addAfter: catAddAfter 665 }); 666 667 // Add new taxonomy button toggles input form visibility. 668 $('#' + taxonomy + '-add-toggle').on( 'click', function( e ) { 669 e.preventDefault(); 670 $('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' ); 671 $('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').trigger( 'click' ); 672 $('#new'+taxonomy).trigger( 'focus' ); 673 }); 674 675 // Sync checked items between "All {taxonomy}" and "Most used" lists. 676 $('#' + taxonomy + 'checklist, #' + taxonomy + 'checklist-pop').on( 677 'click', 678 'li.popular-category > label input[type="checkbox"]', 679 function() { 680 var t = $(this), c = t.is(':checked'), id = t.val(); 681 if ( id && t.parents('#taxonomy-'+taxonomy).length ) 682 $('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c ); 683 } 684 ); 685 686 }); // End cats. 687 688 // Custom Fields postbox. 689 if ( $('#postcustom').length ) { 690 $( '#the-list' ).wpList( { 691 /** 692 * Add current post_ID to request to fetch custom fields 693 * 694 * @ignore 695 * 696 * @param {Object} s Request object. 697 * 698 * @return {Object} Data modified with post_ID attached. 699 */ 700 addBefore: function( s ) { 701 s.data += '&post_id=' + $('#post_ID').val(); 702 return s; 703 }, 704 /** 705 * Show the listing of custom fields after fetching. 706 * 707 * @ignore 708 */ 709 addAfter: function() { 710 $('table#list-table').show(); 711 } 712 }); 713 } 714 715 /* 716 * Publish Post box (#submitdiv) 717 */ 718 if ( $('#submitdiv').length ) { 719 stamp = $('#timestamp').html(); 720 visibility = $('#post-visibility-display').html(); 721 722 /** 723 * When the visibility of a post changes sub-options should be shown or hidden. 724 * 725 * @ignore 726 * 727 * @return {void} 728 */ 729 updateVisibility = function() { 730 // Show sticky for public posts. 731 if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) { 732 $('#sticky').prop('checked', false); 733 $('#sticky-span').hide(); 734 } else { 735 $('#sticky-span').show(); 736 } 737 738 // Show password input field for password protected post. 739 if ( $postVisibilitySelect.find('input:radio:checked').val() != 'password' ) { 740 $('#password-span').hide(); 741 } else { 742 $('#password-span').show(); 743 } 744 }; 745 746 /** 747 * Make sure all labels represent the current settings. 748 * 749 * @ignore 750 * 751 * @return {boolean} False when an invalid timestamp has been selected, otherwise True. 752 */ 753 updateText = function() { 754 755 if ( ! $timestampdiv.length ) 756 return true; 757 758 var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'), 759 optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(), 760 mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(); 761 762 attemptedDate = new Date( aa, mm - 1, jj, hh, mn ); 763 originalDate = new Date( 764 $('#hidden_aa').val(), 765 $('#hidden_mm').val() -1, 766 $('#hidden_jj').val(), 767 $('#hidden_hh').val(), 768 $('#hidden_mn').val() 769 ); 770 currentDate = new Date( 771 $('#cur_aa').val(), 772 $('#cur_mm').val() -1, 773 $('#cur_jj').val(), 774 $('#cur_hh').val(), 775 $('#cur_mn').val() 776 ); 777 778 // Catch unexpected date problems. 779 if ( 780 attemptedDate.getFullYear() != aa || 781 (1 + attemptedDate.getMonth()) != mm || 782 attemptedDate.getDate() != jj || 783 attemptedDate.getMinutes() != mn 784 ) { 785 $timestampdiv.find('.timestamp-wrap').addClass('form-invalid'); 786 return false; 787 } else { 788 $timestampdiv.find('.timestamp-wrap').removeClass('form-invalid'); 789 } 790 791 // Determine what the publish should be depending on the date and post status. 792 if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) { 793 publishOn = __( 'Schedule for:' ); 794 $('#publish').val( _x( 'Schedule', 'post action/button label' ) ); 795 } else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) { 796 publishOn = __( 'Publish on:' ); 797 $('#publish').val( __( 'Publish' ) ); 798 } else { 799 publishOn = __( 'Published on:' ); 800 $('#publish').val( __( 'Update' ) ); 801 } 802 803 // If the date is the same, set it to trigger update events. 804 if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { 805 // Re-set to the current value. 806 $('#timestamp').html(stamp); 807 } else { 808 $('#timestamp').html( 809 '\n' + publishOn + ' <b>' + 810 // translators: 1: Month, 2: Day, 3: Year, 4: Hour, 5: Minute. 811 __( '%1$s %2$s, %3$s at %4$s:%5$s' ) 812 .replace( '%1$s', $( 'option[value="' + mm + '"]', '#mm' ).attr( 'data-text' ) ) 813 .replace( '%2$s', parseInt( jj, 10 ) ) 814 .replace( '%3$s', aa ) 815 .replace( '%4$s', ( '00' + hh ).slice( -2 ) ) 816 .replace( '%5$s', ( '00' + mn ).slice( -2 ) ) + 817 '</b> ' 818 ); 819 } 820 821 // Add "privately published" to post status when applies. 822 if ( $postVisibilitySelect.find('input:radio:checked').val() == 'private' ) { 823 $('#publish').val( __( 'Update' ) ); 824 if ( 0 === optPublish.length ) { 825 postStatus.append('<option value="publish">' + __( 'Privately Published' ) + '</option>'); 826 } else { 827 optPublish.html( __( 'Privately Published' ) ); 828 } 829 $('option[value="publish"]', postStatus).prop('selected', true); 830 $('#misc-publishing-actions .edit-post-status').hide(); 831 } else { 832 if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) { 833 if ( optPublish.length ) { 834 optPublish.remove(); 835 postStatus.val($('#hidden_post_status').val()); 836 } 837 } else { 838 optPublish.html( __( 'Published' ) ); 839 } 840 if ( postStatus.is(':hidden') ) 841 $('#misc-publishing-actions .edit-post-status').show(); 842 } 843 844 // Update "Status:" to currently selected status. 845 $('#post-status-display').text( 846 // Remove any potential tags from post status text. 847 wp.sanitize.stripTagsAndEncodeText( $('option:selected', postStatus).text() ) 848 ); 849 850 // Show or hide the "Save Draft" button. 851 if ( 852 $('option:selected', postStatus).val() == 'private' || 853 $('option:selected', postStatus).val() == 'publish' 854 ) { 855 $('#save-post').hide(); 856 } else { 857 $('#save-post').show(); 858 if ( $('option:selected', postStatus).val() == 'pending' ) { 859 $('#save-post').show().val( __( 'Save as Pending' ) ); 860 } else { 861 $('#save-post').show().val( __( 'Save Draft' ) ); 862 } 863 } 864 return true; 865 }; 866 867 // Show the visibility options and hide the toggle button when opened. 868 $( '#visibility .edit-visibility').on( 'click', function( e ) { 869 e.preventDefault(); 870 if ( $postVisibilitySelect.is(':hidden') ) { 871 updateVisibility(); 872 $postVisibilitySelect.slideDown( 'fast', function() { 873 $postVisibilitySelect.find( 'input[type="radio"]' ).first().trigger( 'focus' ); 874 } ); 875 $(this).hide(); 876 } 877 }); 878 879 // Cancel visibility selection area and hide it from view. 880 $postVisibilitySelect.find('.cancel-post-visibility').on( 'click', function( event ) { 881 $postVisibilitySelect.slideUp('fast'); 882 $('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true); 883 $('#post_password').val($('#hidden-post-password').val()); 884 $('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked')); 885 $('#post-visibility-display').html(visibility); 886 $('#visibility .edit-visibility').show().trigger( 'focus' ); 887 updateText(); 888 event.preventDefault(); 889 }); 890 891 // Set the selected visibility as current. 892 $postVisibilitySelect.find('.save-post-visibility').on( 'click', function( event ) { // Crazyhorse - multiple OK cancels. 893 var visibilityLabel = '', selectedVisibility = $postVisibilitySelect.find('input:radio:checked').val(); 894 895 $postVisibilitySelect.slideUp('fast'); 896 $('#visibility .edit-visibility').show().trigger( 'focus' ); 897 updateText(); 898 899 if ( 'public' !== selectedVisibility ) { 900 $('#sticky').prop('checked', false); 901 } 902 903 switch ( selectedVisibility ) { 904 case 'public': 905 visibilityLabel = $( '#sticky' ).prop( 'checked' ) ? __( 'Public, Sticky' ) : __( 'Public' ); 906 break; 907 case 'private': 908 visibilityLabel = __( 'Private' ); 909 break; 910 case 'password': 911 visibilityLabel = __( 'Password Protected' ); 912 break; 913 } 914 915 $('#post-visibility-display').text( visibilityLabel ); 916 event.preventDefault(); 917 }); 918 919 // When the selection changes, update labels. 920 $postVisibilitySelect.find('input:radio').on( 'change', function() { 921 updateVisibility(); 922 }); 923 924 // Edit publish time click. 925 $timestampdiv.siblings('a.edit-timestamp').on( 'click', function( event ) { 926 if ( $timestampdiv.is( ':hidden' ) ) { 927 $timestampdiv.slideDown( 'fast', function() { 928 $( 'input, select', $timestampdiv.find( '.timestamp-wrap' ) ).first().trigger( 'focus' ); 929 } ); 930 $(this).hide(); 931 } 932 event.preventDefault(); 933 }); 934 935 // Cancel editing the publish time and hide the settings. 936 $timestampdiv.find('.cancel-timestamp').on( 'click', function( event ) { 937 $timestampdiv.slideUp('fast').siblings('a.edit-timestamp').show().trigger( 'focus' ); 938 $('#mm').val($('#hidden_mm').val()); 939 $('#jj').val($('#hidden_jj').val()); 940 $('#aa').val($('#hidden_aa').val()); 941 $('#hh').val($('#hidden_hh').val()); 942 $('#mn').val($('#hidden_mn').val()); 943 updateText(); 944 event.preventDefault(); 945 }); 946 947 // Save the changed timestamp. 948 $timestampdiv.find('.save-timestamp').on( 'click', function( event ) { // Crazyhorse - multiple OK cancels. 949 if ( updateText() ) { 950 $timestampdiv.slideUp('fast'); 951 $timestampdiv.siblings('a.edit-timestamp').show().trigger( 'focus' ); 952 } 953 event.preventDefault(); 954 }); 955 956 // Cancel submit when an invalid timestamp has been selected. 957 $('#post').on( 'submit', function( event ) { 958 if ( ! updateText() ) { 959 event.preventDefault(); 960 $timestampdiv.show(); 961 962 if ( wp.autosave ) { 963 wp.autosave.enableButtons(); 964 } 965 966 $( '#publishing-action .spinner' ).removeClass( 'is-active' ); 967 } 968 }); 969 970 // Post Status edit click. 971 $postStatusSelect.siblings('a.edit-post-status').on( 'click', function( event ) { 972 if ( $postStatusSelect.is( ':hidden' ) ) { 973 $postStatusSelect.slideDown( 'fast', function() { 974 $postStatusSelect.find('select').trigger( 'focus' ); 975 } ); 976 $(this).hide(); 977 } 978 event.preventDefault(); 979 }); 980 981 // Save the Post Status changes and hide the options. 982 $postStatusSelect.find('.save-post-status').on( 'click', function( event ) { 983 $postStatusSelect.slideUp( 'fast' ).siblings( 'a.edit-post-status' ).show().trigger( 'focus' ); 984 updateText(); 985 event.preventDefault(); 986 }); 987 988 // Cancel Post Status editing and hide the options. 989 $postStatusSelect.find('.cancel-post-status').on( 'click', function( event ) { 990 $postStatusSelect.slideUp( 'fast' ).siblings( 'a.edit-post-status' ).show().trigger( 'focus' ); 991 $('#post_status').val( $('#hidden_post_status').val() ); 992 updateText(); 993 event.preventDefault(); 994 }); 995 } 996 997 /** 998 * Handle the editing of the post_name. Create the required HTML elements and 999 * update the changes via Ajax. 1000 * 1001 * @global 1002 * 1003 * @return {void} 1004 */ 1005 function editPermalink() { 1006 var i, slug_value, slug_label, 1007 $el, revert_e, 1008 c = 0, 1009 real_slug = $('#post_name'), 1010 revert_slug = real_slug.val(), 1011 permalink = $( '#sample-permalink' ), 1012 permalinkOrig = permalink.html(), 1013 permalinkInner = $( '#sample-permalink a' ).html(), 1014 buttons = $('#edit-slug-buttons'), 1015 buttonsOrig = buttons.html(), 1016 full = $('#editable-post-name-full'); 1017 1018 // Deal with Twemoji in the post-name. 1019 full.find( 'img' ).replaceWith( function() { return this.alt; } ); 1020 full = full.html(); 1021 1022 permalink.html( permalinkInner ); 1023 1024 // Save current content to revert to when cancelling. 1025 $el = $( '#editable-post-name' ); 1026 revert_e = $el.html(); 1027 1028 buttons.html( 1029 '<button type="button" class="save button button-small">' + __( 'OK' ) + '</button> ' + 1030 '<button type="button" class="cancel button-link">' + __( 'Cancel' ) + '</button>' 1031 ); 1032 1033 // Save permalink changes. 1034 buttons.children( '.save' ).on( 'click', function() { 1035 var new_slug = $el.children( 'input' ).val(); 1036 1037 if ( new_slug == $('#editable-post-name-full').text() ) { 1038 buttons.children('.cancel').trigger( 'click' ); 1039 return; 1040 } 1041 1042 $.post( 1043 ajaxurl, 1044 { 1045 action: 'sample-permalink', 1046 post_id: postId, 1047 new_slug: new_slug, 1048 new_title: $('#title').val(), 1049 samplepermalinknonce: $('#samplepermalinknonce').val() 1050 }, 1051 function(data) { 1052 var box = $('#edit-slug-box'); 1053 box.html(data); 1054 if (box.hasClass('hidden')) { 1055 box.fadeIn('fast', function () { 1056 box.removeClass('hidden'); 1057 }); 1058 } 1059 1060 buttons.html(buttonsOrig); 1061 permalink.html(permalinkOrig); 1062 real_slug.val(new_slug); 1063 $( '.edit-slug' ).trigger( 'focus' ); 1064 wp.a11y.speak( __( 'Permalink saved' ) ); 1065 } 1066 ); 1067 }); 1068 1069 // Cancel editing of permalink. 1070 buttons.children( '.cancel' ).on( 'click', function() { 1071 $('#view-post-btn').show(); 1072 $el.html(revert_e); 1073 buttons.html(buttonsOrig); 1074 permalink.html(permalinkOrig); 1075 real_slug.val(revert_slug); 1076 $( '.edit-slug' ).trigger( 'focus' ); 1077 }); 1078 1079 // If more than 1/4th of 'full' is '%', make it empty. 1080 for ( i = 0; i < full.length; ++i ) { 1081 if ( '%' == full.charAt(i) ) 1082 c++; 1083 } 1084 slug_value = ( c > full.length / 4 ) ? '' : full; 1085 slug_label = __( 'URL Slug' ); 1086 1087 $el.html( 1088 '<label for="new-post-slug" class="screen-reader-text">' + slug_label + '</label>' + 1089 '<input type="text" id="new-post-slug" value="' + slug_value + '" autocomplete="off" spellcheck="false" />' 1090 ).children( 'input' ).on( 'keydown', function( e ) { 1091 var key = e.which; 1092 // On [Enter], just save the new slug, don't save the post. 1093 if ( 13 === key ) { 1094 e.preventDefault(); 1095 buttons.children( '.save' ).trigger( 'click' ); 1096 } 1097 // On [Esc] cancel the editing. 1098 if ( 27 === key ) { 1099 buttons.children( '.cancel' ).trigger( 'click' ); 1100 } 1101 } ).on( 'keyup', function() { 1102 real_slug.val( this.value ); 1103 }).trigger( 'focus' ); 1104 } 1105 1106 $( '#titlediv' ).on( 'click', '.edit-slug', function() { 1107 editPermalink(); 1108 }); 1109 1110 /** 1111 * Adds screen reader text to the title label when needed. 1112 * 1113 * Use the 'screen-reader-text' class to emulate a placeholder attribute 1114 * and hide the label when entering a value. 1115 * 1116 * @param {string} id Optional. HTML ID to add the screen reader helper text to. 1117 * 1118 * @global 1119 * 1120 * @return {void} 1121 */ 1122 window.wptitlehint = function( id ) { 1123 id = id || 'title'; 1124 1125 var title = $( '#' + id ), titleprompt = $( '#' + id + '-prompt-text' ); 1126 1127 if ( '' === title.val() ) { 1128 titleprompt.removeClass( 'screen-reader-text' ); 1129 } 1130 1131 title.on( 'input', function() { 1132 if ( '' === this.value ) { 1133 titleprompt.removeClass( 'screen-reader-text' ); 1134 return; 1135 } 1136 1137 titleprompt.addClass( 'screen-reader-text' ); 1138 } ); 1139 }; 1140 1141 wptitlehint(); 1142 1143 // Resize the WYSIWYG and plain text editors. 1144 ( function() { 1145 var editor, offset, mce, 1146 $handle = $('#post-status-info'), 1147 $postdivrich = $('#postdivrich'); 1148 1149 // If there are no textareas or we are on a touch device, we can't do anything. 1150 if ( ! $textarea.length || 'ontouchstart' in window ) { 1151 // Hide the resize handle. 1152 $('#content-resize-handle').hide(); 1153 return; 1154 } 1155 1156 /** 1157 * Handle drag event. 1158 * 1159 * @param {Object} event Event containing details about the drag. 1160 */ 1161 function dragging( event ) { 1162 if ( $postdivrich.hasClass( 'wp-editor-expand' ) ) { 1163 return; 1164 } 1165 1166 if ( mce ) { 1167 editor.theme.resizeTo( null, offset + event.pageY ); 1168 } else { 1169 $textarea.height( Math.max( 50, offset + event.pageY ) ); 1170 } 1171 1172 event.preventDefault(); 1173 } 1174 1175 /** 1176 * When the dragging stopped make sure we return focus and do a sanity check on the height. 1177 */ 1178 function endDrag() { 1179 var height, toolbarHeight; 1180 1181 if ( $postdivrich.hasClass( 'wp-editor-expand' ) ) { 1182 return; 1183 } 1184 1185 if ( mce ) { 1186 editor.focus(); 1187 toolbarHeight = parseInt( $( '#wp-content-editor-container .mce-toolbar-grp' ).height(), 10 ); 1188 1189 if ( toolbarHeight < 10 || toolbarHeight > 200 ) { 1190 toolbarHeight = 30; 1191 } 1192 1193 height = parseInt( $('#content_ifr').css('height'), 10 ) + toolbarHeight - 28; 1194 } else { 1195 $textarea.trigger( 'focus' ); 1196 height = parseInt( $textarea.css('height'), 10 ); 1197 } 1198 1199 $document.off( '.wp-editor-resize' ); 1200 1201 // Sanity check: normalize height to stay within acceptable ranges. 1202 if ( height && height > 50 && height < 5000 ) { 1203 setUserSetting( 'ed_size', height ); 1204 } 1205 } 1206 1207 $handle.on( 'mousedown.wp-editor-resize', function( event ) { 1208 if ( typeof tinymce !== 'undefined' ) { 1209 editor = tinymce.get('content'); 1210 } 1211 1212 if ( editor && ! editor.isHidden() ) { 1213 mce = true; 1214 offset = $('#content_ifr').height() - event.pageY; 1215 } else { 1216 mce = false; 1217 offset = $textarea.height() - event.pageY; 1218 $textarea.trigger( 'blur' ); 1219 } 1220 1221 $document.on( 'mousemove.wp-editor-resize', dragging ) 1222 .on( 'mouseup.wp-editor-resize mouseleave.wp-editor-resize', endDrag ); 1223 1224 event.preventDefault(); 1225 }).on( 'mouseup.wp-editor-resize', endDrag ); 1226 })(); 1227 1228 // TinyMCE specific handling of Post Format changes to reflect in the editor. 1229 if ( typeof tinymce !== 'undefined' ) { 1230 // When changing post formats, change the editor body class. 1231 $( '#post-formats-select input.post-format' ).on( 'change.set-editor-class', function() { 1232 var editor, body, format = this.id; 1233 1234 if ( format && $( this ).prop( 'checked' ) && ( editor = tinymce.get( 'content' ) ) ) { 1235 body = editor.getBody(); 1236 body.className = body.className.replace( /\bpost-format-[^ ]+/, '' ); 1237 editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format ); 1238 $( document ).trigger( 'editor-classchange' ); 1239 } 1240 }); 1241 1242 // When changing page template, change the editor body class. 1243 $( '#page_template' ).on( 'change.set-editor-class', function() { 1244 var editor, body, pageTemplate = $( this ).val() || ''; 1245 1246 pageTemplate = pageTemplate.substr( pageTemplate.lastIndexOf( '/' ) + 1, pageTemplate.length ) 1247 .replace( /\.php$/, '' ) 1248 .replace( /\./g, '-' ); 1249 1250 if ( pageTemplate && ( editor = tinymce.get( 'content' ) ) ) { 1251 body = editor.getBody(); 1252 body.className = body.className.replace( /\bpage-template-[^ ]+/, '' ); 1253 editor.dom.addClass( body, 'page-template-' + pageTemplate ); 1254 $( document ).trigger( 'editor-classchange' ); 1255 } 1256 }); 1257 1258 } 1259 1260 // Save on pressing [Ctrl]/[Command] + [S] in the Text editor. 1261 $textarea.on( 'keydown.wp-autosave', function( event ) { 1262 // Key [S] has code 83. 1263 if ( event.which === 83 ) { 1264 if ( 1265 event.shiftKey || 1266 event.altKey || 1267 ( isMac && ( ! event.metaKey || event.ctrlKey ) ) || 1268 ( ! isMac && ! event.ctrlKey ) 1269 ) { 1270 return; 1271 } 1272 1273 wp.autosave && wp.autosave.server.triggerSave(); 1274 event.preventDefault(); 1275 } 1276 }); 1277 1278 // If the last status was auto-draft and the save is triggered, edit the current URL. 1279 if ( $( '#original_post_status' ).val() === 'auto-draft' && window.history.replaceState ) { 1280 var location; 1281 1282 $( '#publish' ).on( 'click', function() { 1283 location = window.location.href; 1284 location += ( location.indexOf( '?' ) !== -1 ) ? '&' : '?'; 1285 location += 'wp-post-new-reload=true'; 1286 1287 window.history.replaceState( null, null, location ); 1288 }); 1289 } 1290 1291 /** 1292 * Copies the attachment URL in the Edit Media page to the clipboard. 1293 * 1294 * @since 5.5.0 1295 * 1296 * @param {MouseEvent} event A click event. 1297 * 1298 * @return {void} 1299 */ 1300 copyAttachmentURLClipboard.on( 'success', function( event ) { 1301 var triggerElement = $( event.trigger ), 1302 successElement = $( '.success', triggerElement.closest( '.copy-to-clipboard-container' ) ); 1303 1304 // Clear the selection and move focus back to the trigger. 1305 event.clearSelection(); 1306 // Handle ClipboardJS focus bug, see https://github.com/zenorocha/clipboard.js/issues/680 1307 triggerElement.trigger( 'focus' ); 1308 1309 // Show success visual feedback. 1310 clearTimeout( copyAttachmentURLSuccessTimeout ); 1311 successElement.removeClass( 'hidden' ); 1312 1313 // Hide success visual feedback after 3 seconds since last success. 1314 copyAttachmentURLSuccessTimeout = setTimeout( function() { 1315 successElement.addClass( 'hidden' ); 1316 }, 3000 ); 1317 1318 // Handle success audible feedback. 1319 wp.a11y.speak( __( 'The file URL has been copied to your clipboard' ) ); 1320 } ); 1321 } ); 1322 1323 /** 1324 * TinyMCE word count display 1325 */ 1326 ( function( $, counter ) { 1327 $( function() { 1328 var $content = $( '#content' ), 1329 $count = $( '#wp-word-count' ).find( '.word-count' ), 1330 prevCount = 0, 1331 contentEditor; 1332 1333 /** 1334 * Get the word count from TinyMCE and display it 1335 */ 1336 function update() { 1337 var text, count; 1338 1339 if ( ! contentEditor || contentEditor.isHidden() ) { 1340 text = $content.val(); 1341 } else { 1342 text = contentEditor.getContent( { format: 'raw' } ); 1343 } 1344 1345 count = counter.count( text ); 1346 1347 if ( count !== prevCount ) { 1348 $count.text( count ); 1349 } 1350 1351 prevCount = count; 1352 } 1353 1354 /** 1355 * Bind the word count update triggers. 1356 * 1357 * When a node change in the main TinyMCE editor has been triggered. 1358 * When a key has been released in the plain text content editor. 1359 */ 1360 $( document ).on( 'tinymce-editor-init', function( event, editor ) { 1361 if ( editor.id !== 'content' ) { 1362 return; 1363 } 1364 1365 contentEditor = editor; 1366 1367 editor.on( 'nodechange keyup', _.debounce( update, 1000 ) ); 1368 } ); 1369 1370 $content.on( 'input keyup', _.debounce( update, 1000 ) ); 1371 1372 update(); 1373 } ); 1374 1375 } )( jQuery, new wp.utils.WordCounter() );
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Fri Dec 13 01:00:02 2024 | Cross-referenced by PHPXref 0.7.1 |