dimanche 21 novembre 2021

How can I convert My vanilla JS code into mousetrap.js

I am trying to create a keyboard shortcut which enables the shortcuts for the specific element or button and can be updated as per user needs, there is an existing library for shortcuts that I want to use here is a mousetrap.js There is two-part one is a list of keyboard shortcuts and the second is two select the keys for updating in a bootstrap modal popup

Keyboard Shortcuts

      const defaultOptions = {
        apply: {
          keyEvent: 's',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 0,
          selector: 'joomla-toolbar-button button.button-apply',
        },
        new: {
          keyEvent: 'n',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 0,
          selector: 'joomla-toolbar-button button.button-new',
        },
        save: {
          keyEvent: 'w',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 0,
          selector: 'joomla-toolbar-button button.button-save',
        },
        saveNew: {
          keyEvent: 'n',
          hasShift: 1,
          hasAlt: 1,
          hasControl: 0,
          selector: 'joomla-toolbar-button button.button-save-new',
        },
        help: {
          keyEvent: 'x',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 0,
          selector: 'joomla-toolbar-button button.button-help',
        },
        cancel: {
          keyEvent: 'q',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 0,
          selector: 'joomla-toolbar-button button.button-cancel',
        },
        copy: {
          keyEvent: 'c',
          hasShift: 1,
          hasAlt: 1,
          hasControl: 0,
          selector: 'joomla-toolbar-button button.button-button-copy',
        },
        article: {
          keyEvent: 'a',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 1,
          selector: 'joomla-editor-option~article_modal',
        },
        contact: {
          keyEvent: 'c',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 1,
          selector: 'joomla-editor-option~contact_modal',
        },
        fields: {
          keyEvent: 'f',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 1,
          selector: 'joomla-editor-option~fields_modal',
        },
        image: {
          keyEvent: 'i',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 1,
          selector: 'joomla-editor-option~image_modal',
        },
        menu: {
          keyEvent: 'm',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 1,
          selector: 'joomla-editor-option~menu_modal',
        },
        module: {
          keyEvent: 'm',
          hasShift: 1,
          hasAlt: 1,
          hasControl: 1,
          selector: 'joomla-editor-option~module_modal',
        },
        pagebreak: {
          keyEvent: 'p',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 1,
          selector: 'joomla-editor-option~pagebreak_modal',
        },
        readmore: {
          keyEvent: 'r',
          hasShift: 0,
          hasAlt: 1,
          hasControl: 1,
          selector: 'joomla-editor-option~read_more',
        },
      };
      const phpOptions = Joomla.getOptions('joomla-shortcut-keys');
      this.bootstrapModals = Joomla.getOptions('bootstrap.modal');
      this.options = { ...defaultOptions, ...phpOptions };
      this.handleKeyPressEvent = this.handleKeyPressEvent.bind(this);
      document.addEventListener('keydown', this.handleKeyPressEvent, false);
      if (window && window.tinyMCE) {
        window.tinyMCE.activeEditor.on('keydown', (e) => {
          this.handleKeyPressEvent(e);
        });
      }
    }
  
    execCommand(event, selector, prevent) {
      if (
        selector.includes('joomla-editor-option')
        && Joomla.getOptions('editor') === 'tinymce'
      ) {
        // Editor Option
        const selectorArr = selector.split('~');
        if (selectorArr[1] !== undefined) {
          if (selectorArr[1] !== 'read_more') {
            Object.entries(this.bootstrapModals).forEach((eModal) => {
                if (eModal.includes(selectorArr[1])) {
                  const modalElement = document.getElementById(
                    eModal.replace('#', ''),
                  );
                  if (modalElement) {
                    window.bootstrap.Modal.getInstance(modalElement).show(
                      modalElement,
                    );
                  }
                }
              });
          }
        }
        event.preventDefault();
      } else {
        const actionBtn = document.querySelector(selector);
        if (actionBtn) {
          if (prevent) {
            event.preventDefault();
          }
          actionBtn.click();
        }
      }
    }
  
    handleKeyPressEvent(e) {
      Object.keys(this.options).forEach((action) => {
        // check for meta+shift+alt+ctrl key
        const { keyEvent } = this.options[action];
        const altKey = this.options[action].hasAlt;
        const shiftKey = this.options[action].hasShift;
        const ctrlKey = this.options[action].hasControl;

        if (

          (Number(altKey) === 0
            || (Number(altKey) === 1
              && (navigator.platform.match('Mac') ? e.metaKey : e.altKey)))
          && (Number(shiftKey) === 0 || (Number(shiftKey) === 1 && e.shiftKey))
          && (Number(ctrlKey) === 0 || (Number(ctrlKey) === 1 && e.ctrlKey))
          && e.key.toLowerCase() === keyEvent
        ) {
          this.execCommand(e, this.options[action].selector);
        }
      });
    }
  }

Key Select

this.setModalAttributes = this.setModalAttributes.bind(this);
        this.handleKeyCombinationkeyUpEvent = this.handleKeyCombinationkeyUpEvent.bind(this);
        this.initialiseKeySelectModal = this.initialiseKeySelectModal.bind(this);
        this.handleSaveCombinationkeyUpEvent = this.handleSaveCombinationkeyUpEvent.bind(this);
        document.addEventListener('DOMContentLoaded',this.initialiseKeySelectModal);
        const keySelectBtns = document.getElementsByClassName("keySelectBtn");
        for(let x = 0; x < keySelectBtns.length; x+=1) {
            keySelectBtns[x].addEventListener("click",this.handleKeySelectClickEvent,false);
        }
    }
    initialiseKeySelectModal() {
        const modalDiv = document.createElement("div");
        this.setModalAttributes(modalDiv, {"class": "modal fade", "id": "keySelectModal", "tabindex": "-1", "role": "dialog", "aria-labelledby": "keySelectModalLabel", "aria-hidden": "true"});
        modalDiv.innerHTML = '<div class="modal-dialog modal-dialog-centered" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="keySelectModalLabel">'+Joomla.getOptions('set_shorcut_text')+'</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><div class="p-3"><p>'+Joomla.getOptions('current_combination_text')+': <span id="currentKeyCombination"></span></p><div class="form-group"><input type="hidden" id="current_KeyEvent" value="" /><input type="hidden" id="current_keyValue" value="" /><input type="hidden" id="current_hasControl" value="0" /><input type="hidden" id="current_hasShift" value="0" /><input type="hidden" id="current_hasAlt" value="0" /></div><p>'+Joomla.getOptions('new_combination_text')+': <span id="newKeyCombination"></span></p></div></div><div class="modal-footer"><button type="button" class="btn btn-primary" data-bs-dismiss="modal" aria-label="Close">'+Joomla.getOptions('cancel_button_text')+'</button><button type="button" class="btn btn-success" id="saveKeyCombination">'+Joomla.getOptions('save_button_text')+'</button></div></div></div>';
        document.body.appendChild(modalDiv);
        const keySelectModal = document.getElementById("keySelectModal");
        Joomla.initialiseModal(keySelectModal);
        keySelectModal.addEventListener('keydown', this.handleKeyDownEvent, false);
        keySelectModal.addEventListener('keyup', this.handleKeyCombinationkeyUpEvent, false);
        const saveKeyCombination = document.getElementById("saveKeyCombination");
        saveKeyCombination.addEventListener('click', this.handleSaveCombinationkeyUpEvent, false);
    }
    setModalAttributes(element, attrs) {
        Object.entries(attrs).forEach(([key, value]) => element.setAttribute(key, value));
    }
    handleKeySelectClickEvent(e){
        e.preventDefault();
        document.getElementById("currentKeyCombination").textContent = this.textContent;
        document.getElementById("newKeyCombination").textContent = "";
        document.getElementById("current_KeyEvent").value = this.getAttribute("data-class");
        const keySelectModal = document.getElementById("keySelectModal");
        window.bootstrap.Modal.getInstance(keySelectModal).show(keySelectModal);
    }
    handleKeyCombinationkeyUpEvent(e){
        if(e.keyCode >= 65 && e.keyCode <= 90){
            let keyValue = e.key;
            keyValue = keyValue.toUpperCase();
            document.getElementById("current_hasControl").value = 0;
            document.getElementById("current_hasShift").value = 0;
            document.getElementById("current_hasAlt").value = 0;
            const newKeySelectCombination = [];
            if(e.ctrlKey){
                newKeySelectCombination.push("CTRL");
                document.getElementById("current_hasControl").value = 1;
            }
            if(e.shiftKey){
                newKeySelectCombination.push("SHIFT");
                document.getElementById("current_hasShift").value = 1;
            }
            if(e.metaKey || e.altKey){
                if(navigator.platform.match('Mac')){
                    newKeySelectCombination.push("META");
                }
                else{
                    newKeySelectCombination.push("ALT");
                    document.getElementById("current_hasAlt").value = 1;
                }
            }
            newKeySelectCombination.push(keyValue);
            const newKeySelect = newKeySelectCombination.join(' + ');
            document.getElementById("newKeyCombination").textContent = newKeySelect;
            document.getElementById("current_keyValue").value = keyValue.toLowerCase();
        }
    }
    handleSaveCombinationkeyUpEvent(e){
        e.preventDefault();
        const keySelectModal = document.getElementById("keySelectModal");
        if(document.getElementById("newKeyCombination").textContent){
            const currentKeyEventVal = document.getElementById("current_KeyEvent").value;
            document.getElementById(`jform_params_${currentKeyEventVal}_keyEvent`).value = document.getElementById("current_keyValue").value;
            document.getElementById(`jform_params_${currentKeyEventVal}_hasControl`).value = document.getElementById("current_hasControl").value;
            document.getElementById(`jform_params_${currentKeyEventVal}_hasShift`).value = document.getElementById("current_hasShift").value;
            document.getElementById(`jform_params_${currentKeyEventVal}_hasAlt`).value = document.getElementById("current_hasAlt").value;
            document.getElementById(`jform_params_${currentKeyEventVal}_keySelect_btn`).textContent = document.getElementById("newKeyCombination").textContent;
            document.getElementById(`jform_params_${currentKeyEventVal}_keySelect`).value = document.getElementById("newKeyCombination").textContent;
        }
        window.bootstrap.Modal.getInstance(keySelectModal).hide();
    }
}



Aucun commentaire:

Enregistrer un commentaire