[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-admin/js/ -> tags.js (source)

   1  /**
   2   * Contains logic for deleting and adding tags.
   3   *
   4   * For deleting tags it makes a request to the server to delete the tag.
   5   * For adding tags it makes a request to the server to add the tag.
   6   *
   7   * @output wp-admin/js/tags.js
   8   */
   9  
  10   /* global ajaxurl, wpAjax, showNotice, validateForm */
  11  
  12   /**
  13    * @param {JQueryStatic} $ The jQuery object.
  14    */
  15  jQuery( function($) {
  16  
  17      var addingTerm = false;
  18  
  19      /**
  20       * Adds an event handler to the delete term link on the term overview page.
  21       *
  22       * Cancels default event handling and event bubbling.
  23       *
  24       * @since 2.8.0
  25       *
  26       * @return {boolean} Always returns false to cancel the default event handling.
  27       */
  28      $( '#the-list' ).on( 'click', '.delete-tag', function() {
  29          var t = $(this), tr = t.parents('tr'), r = true, data;
  30  
  31          if ( 'undefined' != showNotice )
  32              r = showNotice.warn();
  33  
  34          if ( r ) {
  35              data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag');
  36  
  37              tr.children().css('backgroundColor', '#faafaa');
  38  
  39              // Disable pointer events and all form controls/links in the row
  40              tr.css('pointer-events', 'none');
  41              tr.find(':input, a').prop('disabled', true).attr('tabindex', -1);
  42  
  43              /**
  44               * Makes a request to the server to delete the term that corresponds to the
  45               * delete term button.
  46               *
  47               * @param {string} r The response from the server.
  48               *
  49               * @return {void}
  50               */
  51              $.post(ajaxurl, data, function(r){
  52                  var message;
  53                  if ( '1' == r ) {
  54                      $('#ajax-response').empty();
  55                      let nextFocus = tr.next( 'tr' ).find( 'a.row-title' );
  56                      let prevFocus = tr.prev( 'tr' ).find( 'a.row-title' );
  57                      // If there is neither a next row or a previous row, focus the tag input field.
  58                      if ( nextFocus.length < 1 && prevFocus.length < 1 ) {
  59                          nextFocus = $( '#tag-name' ).trigger( 'focus' );
  60                      } else {
  61                          if ( nextFocus.length < 1 ) {
  62                              nextFocus = prevFocus;
  63                          }
  64                      }
  65                      tr.fadeOut('normal', function() {
  66                          tr.remove();
  67                          updateTableNavCount();
  68                      });
  69  
  70                      /**
  71                       * Removes the term from the parent box and the tag cloud.
  72                       *
  73                       * `data.match(/tag_ID=(\d+)/)[1]` matches the term ID from the data variable.
  74                       * This term ID is then used to select the relevant HTML elements:
  75                       * The parent box and the tag cloud.
  76                       */
  77                      $('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
  78                      $('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
  79                      nextFocus.trigger( 'focus' );
  80                      message = wp.i18n.__( 'The selected tag has been deleted.' );
  81  
  82                  } else if ( '-1' == r ) {
  83                      message = wp.i18n.__( 'Sorry, you are not allowed to do that.' );
  84                      $('#ajax-response').empty().append('<div class="notice notice-error"><p>' + message + '</p></div>');
  85                      resetRowAfterFailure( tr );
  86  
  87                  } else {
  88                      message = wp.i18n.__( 'An error occurred while processing your request. Please try again later.' );
  89                      $('#ajax-response').empty().append('<div class="notice notice-error"><p>' + message + '</p></div>');
  90                      resetRowAfterFailure( tr );
  91                  }
  92                  wp.a11y.speak( message, 'assertive' );
  93              });
  94          }
  95  
  96          return false;
  97      });
  98  
  99      /**
 100       * Restores the original UI state of a table row after an AJAX failure.
 101       *
 102       * @param {jQuery} tr The table row to reset.
 103       * @return {void}
 104       */
 105  	function resetRowAfterFailure( tr ) {
 106          tr.children().css( 'backgroundColor', '' );
 107          tr.css( 'pointer-events', '' );
 108          tr.find( ':input, a' ).prop( 'disabled', false ).removeAttr( 'tabindex' );
 109      }
 110  
 111      /**
 112       * Updates the item count and table navigation after a tag is added or removed.
 113       *
 114       * Tags are added and removed client-side, but the item count, the `.tablenav`
 115       * regions, the search box, and the empty-state row are otherwise only
 116       * reconciled by PHP on a full page reload. This keeps them in sync.
 117       *
 118       * @param {string} [action] Pass 'add' when a tag was added. Any other value,
 119       *                          including none, is treated as a removal.
 120       *
 121       * @return {void}
 122       */
 123  	function updateTableNavCount( action ) {
 124          var $displayingNum = $( '.tablenav-pages .displaying-num' ),
 125              currentCount   = parseInt( $displayingNum.first().text().replace( /[^0-9]/g, '' ), 10 ) || 0,
 126              itemCount      = ( 'add' === action ) ? currentCount + 1 : Math.max( currentCount - 1, 0 ),
 127              formattedCount = itemCount.toLocaleString();
 128  
 129          $displayingNum.text(
 130              wp.i18n.sprintf(
 131                  /* translators: %s: Number of items. */
 132                  wp.i18n._n( '%s item', '%s items', itemCount ),
 133                  formattedCount
 134              )
 135          );
 136  
 137          if ( itemCount < 1 ) {
 138              // No tags remain: show the empty-state row and hide the navigation.
 139              var $list = $( '#the-list' );
 140  
 141               if ( ! $list.find( 'tr.no-items' ).length ) {
 142                   var colspan = $list.closest( 'table' ).find( 'thead > tr' ).first().children( ':not(.hidden)' ).length;
 143                   $list.append(
 144                       '<tr class="no-items"><td class="colspanchange" colspan="' + colspan + '">' +
 145                       wp.i18n.__( 'No tags found.' ) +
 146                       '</td></tr>'
 147                   );
 148               }
 149              $( '.tablenav > *' ).hide();
 150              $( 'p.search-box' ).hide();
 151          } else {
 152              $( '#the-list' ).find( 'tr.no-items' ).remove();
 153              $( '.tablenav > *' ).show();
 154              $( 'p.search-box' ).show();
 155          }
 156      }
 157  
 158      /**
 159       * Adds a deletion confirmation when removing a tag.
 160       *
 161       * @since 4.8.0
 162       *
 163       * @return {void}
 164       */
 165      $( '#edittag' ).on( 'click', '.delete', function( e ) {
 166          if ( 'undefined' === typeof showNotice ) {
 167              return true;
 168          }
 169  
 170          // Confirms the deletion, a negative response means the deletion must not be executed.
 171          var response = showNotice.warn();
 172          if ( ! response ) {
 173              e.preventDefault();
 174          }
 175      });
 176  
 177      /**
 178       * Adds an event handler to the form submit on the term overview page.
 179       *
 180       * Cancels default event handling and event bubbling.
 181       *
 182       * @since 2.8.0
 183       *
 184       * @return {boolean} Always returns false to cancel the default event handling.
 185       */
 186      $('#submit').on( 'click', function(){
 187          var form = $(this).parents('form');
 188  
 189          if ( addingTerm ) {
 190              // If we're adding a term, noop the button to avoid duplicate requests.
 191              return false;
 192          }
 193  
 194          addingTerm = true;
 195          form.find( '.submit .spinner' ).addClass( 'is-active' );
 196  
 197          /**
 198           * Does a request to the server to add a new term to the database
 199           *
 200           * @param {string} r The response from the server.
 201           *
 202           * @return {void}
 203           */
 204          $.post(ajaxurl, $('#addtag').serialize(), function(r){
 205              var res, parent, term, indent, i;
 206  
 207              addingTerm = false;
 208              form.find( '.submit .spinner' ).removeClass( 'is-active' );
 209  
 210              $('#ajax-response').empty();
 211              res = wpAjax.parseAjaxResponse( r, 'ajax-response' );
 212  
 213              if ( res.errors && res.responses[0].errors[0].code === 'empty_term_name' ) {
 214                  validateForm( form );
 215              }
 216  
 217              if ( ! res || res.errors ) {
 218                  return;
 219              }
 220  
 221              parent = form.find( 'select#parent' ).val();
 222  
 223              // If the parent exists on this page, insert it below. Else insert it at the top of the list.
 224              if ( parent > 0 && $('#tag-' + parent ).length > 0 ) {
 225                  // As the parent exists, insert the version with - - - prefixed.
 226                  $( '.tags #tag-' + parent ).after( res.responses[0].supplemental.noparents );
 227              } else {
 228                  // As the parent is not visible, insert the version with Parent - Child - ThisTerm.
 229                  $( '.tags' ).prepend( res.responses[0].supplemental.parents );
 230              }
 231  
 232              $('.tags .no-items').remove();
 233  
 234              if ( form.find('select#parent') ) {
 235                  // Parents field exists, Add new term to the list.
 236                  term = res.responses[1].supplemental;
 237  
 238                  // Create an indent for the Parent field.
 239                  indent = '';
 240                  for ( i = 0; i < res.responses[1].position; i++ )
 241                      indent += '&nbsp;&nbsp;&nbsp;';
 242  
 243                  form.find( 'select#parent option:selected' ).after( '<option value="' + term.term_id + '">' + indent + term.name + '</option>' );
 244              }
 245  
 246              $('input:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not([type="reset"]):visible, textarea:visible', form).val('');
 247  
 248              updateTableNavCount( 'add' );
 249          });
 250  
 251          return false;
 252      });
 253  
 254  });


Generated : Fri Sep 4 08:20:24 2026 Cross-referenced by PHPXref