toolbar_plus-1.0.x-dev/js/toolbar-plus.js

js/toolbar-plus.js
import * as toolPluginBase from './toolbar_plus/tool-plugin-base.js';
import * as pluginManager from './toolbar_plus/tool-plugin-manager.js';
import * as topBar from './toolbar_plus/top-bar.js'; // Do not remove!

(($, Drupal, once) => {

  Drupal.ToolbarPlus = {};

  pluginManager.default($, Drupal, once);

  /**
   * Toolbar Plus Edit Mode.
   */
  Drupal.behaviors.ToolbarPlusEditMode = {
    attach: (context, settings) => {
      once('ToolbarPlusToggleEditMode', '#toggle-edit-mode', context).forEach(toggleEditModeButton => {

        if (Drupal.ToolbarPlus.isInitialView()) {
          Drupal.behaviors.ToolbarPlusEditMode.EnableEditMode();
        } else if (Drupal.ToolbarPlus.getCookieValue('editMode') === 'enabled') {
          // Enable active tools on page load.
          Drupal.behaviors.ToolbarPlusEditMode.activateTool();
        }

        // Listen for tool activation clicks.
        document.querySelectorAll('.toolbar-plus-button').forEach((toolButton) => {
          toolButton.onclick = (event) => {
            const activeTool = localStorage.getItem('toolbar_plus.tool.active') ?? 'pointer';
            const nextTool = event.currentTarget.dataset.tool;

            Drupal.ToolbarPlus.PluginManager.getPlugin(activeTool).disable().then(() => {
              Drupal.behaviors.ToolbarPlusEditMode.activateTool(nextTool);
            });
          }
        });

        // Enable and disable edit mode.
        toggleEditModeButton.onclick = e => {
          e.preventDefault();
          const toolbar = document.querySelector("#toolbar-plus");
          if (toolbar.classList.contains('toolbar-plus-hidden')) {
            Drupal.behaviors.ToolbarPlusEditMode.EnableEditMode();
          } else {
            Drupal.behaviors.ToolbarPlusEditMode.DisableEditMode();
          }
        }
      });
    },
    activateTool: (toolPluginId = null) => {
      const isInitialPageEdit = Drupal.ToolbarPlus.isInitialView();

      if (!toolPluginId) {
        const defaultTool = drupalSettings.toolbarPlus.defaultTool ?? 'pointer';
        if (isInitialPageEdit) {
          // Use the configured tool for this content type when initially editing
          // a page.
          toolPluginId = defaultTool;
        } else {
          // Ensure the active tool is till valid for this entity type.
          let activeToolId = localStorage.getItem('toolbar_plus.tool.active');
          try {
            Drupal.ToolbarPlus.PluginManager.getPlugin(activeToolId);
          } catch (e) {
            activeToolId = null;
          }
          toolPluginId = activeToolId ?? defaultTool;
        }
      }

      Drupal.behaviors.ToolbarPlusEditMode.changeMouse(toolPluginId);
      const tool = Drupal.ToolbarPlus.PluginManager.getPlugin(toolPluginId);
      tool.enable().then(() => {
        if (isInitialPageEdit) {
          tool.initialEdit();
          // Keep track if we have edited this page before.
          const storedPages = sessionStorage.getItem('toolbarPlus.EditedPages');
          let editedPages = storedPages ? JSON.parse(storedPages) : [];
          editedPages.push(window.location.pathname);
          sessionStorage.setItem('toolbarPlus.EditedPages', JSON.stringify(editedPages));
        }
        localStorage.setItem('toolbar_plus.tool.active', toolPluginId);
        document.cookie="activeTool=" + toolPluginId + "; path=/";
      });
    },
    /**
     * Reload page elements.
     *
     * When the editMode cookie changes, AJAX reload the page so that the page
     * elements will have the UI attributes applied to them.
     */
    ReloadPageElements: () => {
      return new Promise((resolve, reject) => {
        const wrapper = Drupal.behaviors.ToolbarPlusEditMode.getEntityWrapperToEdit();
        if (!wrapper) {
          return;
        }
        const parts = wrapper.dataset.toolbarPlusEntityWrapper.split('::');

        let ajax = toolPluginBase.ajax({
          url: Drupal.url('toolbar-plus/load-editable-page/' + parts[0] + '/' + parts[1] + '/' + wrapper.dataset.toolbarPlusViewMode),
          type: 'POST',
          dataType: 'text',
          progress: {
            type: 'fullscreen',
            message: Drupal.t('Loading Layout Builder...')
          },
          error: error => {
            document.querySelectorAll('.ajax-progress').forEach(progress => {
              progress.remove();
            });
            console.info('Failed to load the editing UI for ' + wrapper.dataset.toolbarPlusEntityWrapper);
            console.info(error.responseText);
          },
          success: (response, status) => {
            Promise.resolve(
              Drupal.Ajax.prototype.success.call(ajax, response, status)
            ).then(() => {
              resolve();
            });
          }
        });
        ajax.execute();
      });
    },
    EnableEditMode: () => {
      // Hide the other navigation items.
      Drupal.behaviors.ToolbarPlusEditMode.getOtherNavigationItems().forEach(navigationItem => {
        navigationItem.classList.add('toolbar-plus-hidden');
      });
      // Reveal the toolbar.
      const toolbar = document.querySelector("#toolbar-plus");
      const toggleEditModeButton = document.querySelector("#toggle-edit-mode");
      toggleEditModeButton.classList.add('active');
      toolbar.classList.remove('toolbar-plus-hidden');
      document.cookie="editMode=enabled; path=" + window.location.pathname;
      // Reveal the top bar.
      const navigationBar = document.querySelector('.top-bar:not(#toolbar-plus-top-bar)');
      if (navigationBar) {
        navigationBar.classList.add('toolbar-plus-hidden');
      }
      document.querySelector('#toolbar-plus-top-bar').classList.remove('toolbar-plus-hidden');
      // Reveal the sidebar.
      document.querySelector('.toolbar-plus-sidebar-wrapper').classList.remove('toolbar-plus-hidden');

      Drupal.behaviors.ToolbarPlusEditMode.ReloadPageElements().then((response, status) => {
        Drupal.behaviors.ToolbarPlusEditMode.activateTool();
      }).catch((error) => {
        console.error('An error occurred while trying to load the editing UI:', error);
      });
    },
    DisableEditMode:() => {
      // Reveal the other navigation items.
      Drupal.behaviors.ToolbarPlusEditMode.getOtherNavigationItems().forEach(navigationItem => {
        navigationItem.classList.remove('toolbar-plus-hidden');
      });
      // Hide the toolbar.
      const toolbar = document.querySelector("#toolbar-plus");
      toolbar.classList.add('toolbar-plus-hidden');
      const toggleEditModeButton = document.querySelector("#toggle-edit-mode");
      toggleEditModeButton.classList.remove('active');
      Drupal.behaviors.ToolbarPlusEditMode.removeMouse();
      const activeTool = localStorage.getItem('toolbar_plus.tool.active');
      Drupal.ToolbarPlus.PluginManager.getPlugin(activeTool).disable(true);
      document.cookie="editMode=disabled; path=" + window.location.pathname;
      // Reveal the top bar.
      const navigationBar = document.querySelector('.top-bar:not(#toolbar-plus-top-bar)');
      if (navigationBar) {
        navigationBar.classList.remove('toolbar-plus-hidden');
      }
      document.querySelector('#toolbar-plus-top-bar').classList.add('toolbar-plus-hidden');
      // Hide the sidebar.
      document.querySelector('.toolbar-plus-sidebar-wrapper').classList.add('toolbar-plus-hidden');

      Drupal.behaviors.ToolbarPlusEditMode.ReloadPageElements();
    },
    removeMouse: () => {
      document.querySelectorAll('.toolbar-plus-button.active').forEach(button => {
        document.querySelector('html').classList.remove(button.dataset.tool);
        button.classList.remove('active');
      });
    },
    changeMouse: (pluginId) => {
      Drupal.behaviors.ToolbarPlusEditMode.removeMouse();
      document.querySelector('[data-tool="' + pluginId + '"]').classList.add('active');
      document.querySelector('html').classList.add(pluginId);
      sessionStorage.setItem('mouseState', pluginId);
    },
    getOtherNavigationItems: () => {
      return document.querySelectorAll('#menu-builder .toolbar-block:not(#toolbar-plus)');
    },
    getEntityWrapperToEdit: () => {
      return document.querySelector('[data-toolbar-plus-entity-wrapper]');
    },
  };

  /**
   * Is initial edit.
   *
   * @returns {boolean}
   *   Whether this page has been edited before.
   */
  Drupal.ToolbarPlus.isInitialView = () => {
    // Has this page been configured to do something on initial view?
    if (!drupalSettings.toolbarPlus.initialMode) {
      return false;
    }
    const storedPages = sessionStorage.getItem('toolbarPlus.EditedPages');
    let editedPages = storedPages ? JSON.parse(storedPages) : [];
    return !editedPages.includes(window.location.pathname);
  }

  /**
   * Get cookie value.
   *
   * @param name
   *   The cookie name.
   * @returns {string|string}
   *   The cookie value.
   */
  Drupal.ToolbarPlus.getCookieValue = (name) => {
    const match = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)');
    return match ? match.pop() : null;
  }

})(jQuery, Drupal, once);



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

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