datafield-1.x-dev/js/paste_clipboard.js

js/paste_clipboard.js
/**
 * @file
 * Paste from clipboard to table field widget.
 */

(function (Drupal, $, once) {
  'use strict';
  Drupal.behaviors.paste_clipboard = {
    attach: function (context) {
      // Initialize the Quick Edit app once per page load.
      $(once('data-field-table-widget', '.field--widget-data-field-table-widget', context)).each(function () {
        $('.field--widget-data-field-table-widget table tbody input:first').on('paste', function (e) {
          var $this = $(this);
          var data = [];
          var promises = [];
          $.each(e.originalEvent.clipboardData.items, function (i, v) {
            if (v.type === 'text/plain') {
              var promise = new Promise(function (resolve) {
                v.getAsString(function (text) {
                  text = text.trim('\r\n');
                  text.split('\r\n').forEach((v2, row) => {
                    let rows = v2.split('\t');
                    data.push(rows);
                  });
                  resolve();
                });
              });
              promises.push(promise);
            }
          });
          Promise.all(promises).then(function () {
            let table = $this.closest('tbody');
            if(data.length>0){
              let totalRow = data.length;
              let rowCount = table.find("tr").length;
              let firstRow = table.find("tr:first").clone();
              if(rowCount < totalRow) {
                for (let i = rowCount; i < totalRow; i++) {
                  let newRow = firstRow.clone();
                  newRow.find('[name*="[0]"]').each(function () {
                    let newName = $(this).attr('name').replace('[0]', '[' + i + ']');
                    $(this).attr('name', newName);
                  });
                  table.append(newRow);
                }
              }
            }
            table.find('tr').each(function (row, tr) {
              if (row in data) {
                let removeFirstCol = 0;
                if ($(this).hasClass('draggable')) {
                  removeFirstCol = 1;
                }
                $(this).find('td').each(function (col, td) {
                  col -= removeFirstCol;
                  if (col in data[row]) {
                    $(this).find("input").val(data[row][col]);
                    //if select check have value
                    const exists = 0 != $(this).find('select').length;
                    if (exists) {
                      let that = $(this);
                      $.each($(this).find("select").prop("options"), function (i, opt) {
                        if (opt.textContent == data[row][col] || opt.value == data[row][col]) {
                          that.find("select").val(opt.value);
                        }
                      });
                    }
                  }
                });
              }
            });
            // Add another item click
            let button = $this.closest('table').parent().find('.form-actions input[type="submit"]');
            button.click();
          });
          return false;
        });

      });
      $(once('paste', '.paste-clipboard', context)).on("click", function () {
        const id_table = $(this).data("table");
        const tab = "\t";
        const breakLine = "\n";
        navigator.permissions.query({ name: 'clipboard-read' }).then(permissionStatus => {
          if (permissionStatus.state === 'granted' || permissionStatus.state === 'prompt') {
            navigator.clipboard.readText().then(text => {
              if (!text) {
                return;
              }
              // Split clipboard.
              let items = text.trim().split(breakLine);
              let data = [];
              $.each(items, function (key, val) {
                if (val) {
                  data[key] = val.trim().split(tab);
                }
              });
              if (!data.length) {
                return;
              }
              let dataCount = data.length;
              let rowCount = $(`table#${id_table} > tbody`).find('tr').length;
              // Add row.
              if (rowCount < dataCount) {
                let rowsToAdd = dataCount - rowCount;
                let firstRow = $(`table#${id_table}`).find('tbody tr:first');
                for (let i = 0; i < rowsToAdd; i++) {
                  let newRow = firstRow.clone();
                  newRow.find('input, select, textarea').each(function () {
                    let name = $(this).attr('name');
                    let id = $(this).attr('id');
                    if (name) {
                      $(this).attr('name', name.replace('[0]', `[${i + rowCount}]`));
                    }
                    if (id) {
                      $(this).attr('id', id.replace('-0-', `-${i + rowCount}-`));
                    }
                    if ($(this).is('input') || $(this).is('textarea')) {
                      $(this).val('');
                    }
                    if ($(this).is('select')) {
                      $(this).val(''); // Reset select
                    }
                  });
                  $(`table#${id_table} > tbody`).append(newRow);
                }
              }

              // Fill data to table.
              $(`table#${id_table} > tbody > tr`).each(function (row, tr) {
                if (!(row in data)) return;
                let removeFirstCol = $(this).hasClass('draggable') ? 1 : 0;
                $(this).find('td').each(function (col, td) {
                  col -= removeFirstCol;
                  if (!(col in data[row])) return;
                  let itemCol = $(this).find('input, textarea');
                  itemCol.each(function () {
                    if ($(this).attr('type') !== 'file') {
                      $(this).val(data[row][col]).trigger('change');
                    }
                  });
                  // Process select
                  let select = $(this).find('select');
                  if (select.length) {
                    select.each(function () {
                      let value = data[row][col];
                      let option = $(this).find('option').filter(function () {
                        return $(this).text() === value || $(this).val() === value;
                      });
                      if (option.length) {
                        $(this).val(option.val()).trigger('change');
                      }
                    });
                  }
                });
              });

          // Trigger button "Add more"
          let button = $(`table#${id_table}`).closest('.form-item').find('.field-add-more-submit');
          if (button.length) {
              button.off('click').trigger('click');
            }
          }).catch(err => {
            console.error('Error read clipboard:', err);
          });
        } else {
            console.error('Access clipboard deny');
        }
      });
    });
  }};
  Drupal.behaviors.btnExpand = {
    attach: function (context) {
      $(once('btn-expand', '.btn-expand', context)).each(function () {
        $(this).on('click', function (e) {
          let $btn = $(this);
          let $table = $btn.closest('table');
          let isExpanded = $table.hasClass('is-expanded');
          if (isExpanded) {
            $table.css('width', 'auto');
            $table.removeClass('is-expanded');
          } else {
            let countCol = $table.find('thead th').length;
            let widthTable = countCol * 300;
            $table.width(widthTable);
            $table.addClass('is-expanded');
          }
        });
      });
    }
  };
}(Drupal, jQuery, once));

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

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