(function ($, Drupal) {

  Drupal.behaviors.pagedesignerIcon = {
    attach: function (context, settings) {
      if (typeof settings.pagedesigner != 'undefined') {
        // Add the edit icon.
        $('body', context).append('<a class="pd-edit-icon" href="' + settings.pagedesigner.edit_link + '" title="' + Drupal.t('Open pagedesigner') + ' (e)"><i class="fas fa-edit"></i></a>');

        // Add a shortcut to open the editor.
        $('body', context).on('keydown', function (e) {
          // Prevent execution when composing.
          if (e.isComposing || e.keyCode === 229) {
            return;
          }
          // Prevent execution in forms and editable elements.
          if (
            e.target.ckeditorInstance  ||
            e.target.classList.contains('ck-editor__editable') ||
            e.target.attributes['contenteditable'] === 'true' ||
            e.target.tagName == 'INPUT' ||
            e.target.tagName == 'TEXTAREA' ||
            e.target.contenteditable ||
            $(e.target).parents('form').length > 0) {
            return;
          }
          // React to "e" key, open the editor.
          if (e.keyCode == 69) {
            window.location.href = settings.pagedesigner.edit_link;
          }
        });
      }
    }
  };

})(jQuery, Drupal);
