knowledge-8.x-1.x-dev/js/knowledge.competency.admin.js

js/knowledge.competency.admin.js
/**
 * @file
 * Competency admin behaviors.
 */

(function (window, $, Drupal, debounce, once) {
  /**
   * Filters the block list by a text input search string.
   *
   * The text input will have the selector `input.field-filter-text`.
   *
   * The target element to do searching in will be in the selector
   * `input.field-filter-text[data-element]`
   *
   * The text source where the text should be found will have the selector
   * `.field-filter-text-source`
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the behavior for the block filtering.
   */
  Drupal.behaviors.knowledgeCompetencyFilterByText = {
    attach(context, settings) {
      const $input = $(once('field-filter-text', 'input.field-filter-text'));
      const $table = $($input.attr('data-element'));
      let $filterRows;

      /**
       * Filters the block list.
       *
       * @param {jQuery.Event} e
       *   The jQuery event for the keyup event that triggered the filter.
       */
      function filterBlockList(e) {
        const query = e.target.value.toLowerCase();

        /**
         * Shows or hides the block entry based on the query.
         *
         * @param {number} index
         *   The index in the loop, as provided by `jQuery.each`
         * @param {HTMLElement} label
         *   The label of the block.
         */
        function toggleBlockEntry(index, label) {
          const $row = $(label).parent().parent();
          const textMatch = label.textContent.toLowerCase().includes(query);
          $row.toggle(textMatch);
        }

        // Filter if the length of the query is at least 2 characters.
        if (query.length >= 2) {
          $filterRows.each(toggleBlockEntry);
          Drupal.announce(
            Drupal.formatPlural(
              $table.find('tr:visible').length - 1,
              '1 block is available in the modified list.',
              '@count blocks are available in the modified list.',
            ),
          );
        } else {
          $filterRows.each(function (index) {
            $(this).parent().parent().show();
          });
        }
      }

      if ($table.length) {
        $filterRows = $table.find('div.field-filter-text-source');
        $input.on('keyup', debounce(filterBlockList, 200));
      }
    },
  };

  /**
   * Highlights the block that was just placed into the block listing.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the behavior for the block placement highlighting.
   */
  Drupal.behaviors.knowledgeCompetencyHighlightPlacement = {
    attach(context, settings) {
      // Ensure that the block we are attempting to scroll to actually exists.
      if (settings.blockPlacement && $('.js-field-placed').length) {
        once(
          'field-highlight',
          '[data-drupal-selector="edit-fields"]',
          context,
        ).forEach((container) => {
          const $container = $(container);
          window.scrollTo({
            top:
              $('.js-field-placed').offset().top -
              $container.offset().top +
              $container.scrollTop(),
            behavior: 'smooth',
          });
        });
      }
    },
  };

  /**
   * Move a block in the blocks table between regions via select list.
   *
   * This behavior is dependent on the tableDrag behavior, since it uses the
   * objects initialized in that behavior to update the row.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the tableDrag behavior for blocks in block administration.
   */
  Drupal.behaviors.knowledgeCompetencyDrag = {
    attach(context, settings) {
      // tableDrag is required and we should be on the blocks admin page.
      if (
        typeof Drupal.tableDrag === 'undefined' ||
        typeof Drupal.tableDrag.knowledge_competency === 'undefined'
      ) {
        return;
      }

      /**
       * Function to check empty regions and toggle classes based on this.
       *
       * @param {jQuery} table
       *   The jQuery object representing the table to inspect.
       * @param {Drupal.tableDrag.row} rowObject
       *   Drupal table drag row dropped.
       */
      function checkEmptyRegions(table, rowObject) {
        'debugger';
        table.find('tr.role-message').each(function () {
          const $this = $(this);
          // If the dragged row is in this region, but above the message row,
          // swap it down one space.
          if ($this.prev('tr').get(0) === rowObject.element) {
            // Prevent a recursion problem when using the keyboard to move rows
            // up.
            if (
              rowObject.method !== 'keyboard' ||
              rowObject.direction === 'down'
            ) {
              rowObject.swap('after', this);
            }
          }
          // This region has become empty.
          if (
            $this.next('tr').length === 0 ||
            !$this.next('tr')[0].matches('.draggable')
          ) {
            $this.removeClass('role-populated').addClass('role-empty');
          }
          // This region has become populated.
          else if (this.matches('.role-empty')) {
            $this.removeClass('role-empty').addClass('role-populated');
          }
        });
      }

      /**
       * Function to update the last placed row with the correct classes.
       *
       * @param {jQuery} table
       *   The jQuery object representing the table to inspect.
       * @param {Drupal.tableDrag.row} rowObject
       *   Drupal table drag row dropped.
       */
      function updateLastPlaced(table, rowObject) {
        // Remove the color-success class from new block if applicable.
        table.find('.color-success').removeClass('color-success');
        const $rowObject = $(rowObject);
        if (!rowObject.element.matches('.drag-previous')) {
          table.find('.drag-previous').removeClass('drag-previous');
          $rowObject.addClass('drag-previous');
        }
      }

      /**
       * Update block weights in the given region.
       *
       * @param {jQuery} table
       *   Table with draggable items.
       * @param {string} region
       *   Machine name of region containing blocks to update.
       */
      function updateBlockWeights(table, region) {
        console.log(region);
        // Calculate minimum weight.
        let weight = -Math.round(table.find('.draggable').length / 2);
        // Update the block weights.
        table
          .find(`.role-${region}-message`)
          .nextUntil('.role-title')
          .find('select.field-weight')
          .each(function () {
            // Increment the weight before assigning it to prevent using the
            // absolute minimum available weight. This way we always have an
            // unused upper and lower bound, which makes manually setting the
            // weights easier for users who prefer to do it that way.
            this.value = ++weight;
          });
      }

      const table = $('#edit-fields');
      console.log(table);
      // Get the blocks tableDrag object.
      const tableDrag = Drupal.tableDrag.knowledge_competency;
      // Add a handler for when a row is swapped, update empty regions.
      tableDrag.row.prototype.onSwap = function (swappedRow) {
        checkEmptyRegions(table, this);
        updateLastPlaced(table, this);
      };

      // Add a handler so when a row is dropped, update fields dropped into
      // new regions.
      tableDrag.onDrop = function () {
        const dragObject = this;
        const $rowElement = $(dragObject.rowObject.element);
        // Use "role-message" row instead of "region" row because
        // "role-{region_name}-message" is less prone to regexp match errors.
        const regionRow = $rowElement.prevAll('tr.role-message').get(0);
        const regionName = regionRow.className.replace(
          /([^ ]+[ ]+)*role-([^ ]+)-message([ ]+[^ ]+)*/,
          '$2',
        );
        const regionField = $rowElement.find('select.field-role-select');
        // Check whether the newly picked region is available for this block.
        if (regionField.find(`option[value=${regionName}]`).length === 0) {
          // If not, alert the user and keep the block in its old region
          // setting.
          window.alert(Drupal.t('The block cannot be placed in this region.'));
          // Simulate that there was a selected element change, so the row is
          // put back to from where the user tried to drag it.
          regionField.trigger('change');
        }

        // Update region and weight fields if the region has been changed.
        if (!regionField[0].matches(`.field-role-${regionName}`)) {
          const weightField = $rowElement.find('select.field-weight');
          const oldRegionName = weightField[0].className.replace(
            /([^ ]+[ ]+)*field-weight-([^ ]+)([ ]+[^ ]+)*/,
            '$2',
          );
          regionField
            .removeClass(`field-role-${oldRegionName}`)
            .addClass(`field-role-${regionName}`);
          weightField
            .removeClass(`field-weight-${oldRegionName}`)
            .addClass(`field-weight-${regionName}`);
          regionField[0].value = regionName;
        }

        updateBlockWeights(table, regionName);
      };

      // Add the behavior to each region select list.
      $(once('field-role-select', 'select.field-role-select', context)).on(
        'change',
        function (event) {
          // Make our new row and select field.
          const row = $(this).closest('tr');
          const select = $(this);
          // Find the correct region and insert the row as the last in the
          // region.
          tableDrag.rowObject = new tableDrag.row(row[0]);
          const regionMessage = table.find(
            `.role-${select[0].value}-message`,
          );
          const regionItems = regionMessage.nextUntil(
            '.role-message, .role-title',
          );
          if (regionItems.length) {
            regionItems.last().after(row);
          }
          // We found that regionMessage is the last row.
          else {
            regionMessage.after(row);
          }
          updateBlockWeights(table, select[0].value);
          // Modify empty regions with added or removed fields.
          checkEmptyRegions(table, tableDrag.rowObject);
          // Update last placed block indication.
          updateLastPlaced(table, tableDrag.rowObject);
          // Show unsaved changes warning.
          if (!tableDrag.changed) {
            $(Drupal.theme('tableDragChangedWarning'))
              .insertBefore(tableDrag.table)
              .hide()
              .fadeIn('slow');
            tableDrag.changed = true;
          }
          // Remove focus from selectbox.
          select.trigger('blur');
        },
      );
    },
  };

})(window, jQuery, Drupal, Drupal.debounce, once);

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc