home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress2 / wp-admin / js / inline-edit-post.js < prev    next >
Encoding:
JavaScript  |  2017-10-02  |  16.0 KB  |  554 lines

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