swup-1.0.0-alpha1/swup_ui/src/Form/SwupSettings.php

swup_ui/src/Form/SwupSettings.php
<?php

namespace Drupal\swup_ui\Form;

use Drupal\swup_ui\SwupConstants;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Defines a form that configures Swup settings.
 */
class SwupSettings extends ConfigFormBase {

  /**
   * The theme handler.
   *
   * @var \Drupal\Core\Extension\ThemeHandlerInterface
   */
  protected $themeHandler;

  /**
   * Constructs a SwupSettings object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typedConfigManager
   *   The typed config manager.
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler.
   */
  public function __construct(ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typedConfigManager, ThemeHandlerInterface $theme_handler) {
    parent::__construct($config_factory, $typedConfigManager);
    $this->themeHandler = $theme_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('theme_handler')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'swup_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'swup_ui.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get current settings.
    $config = $this->config('swup_ui.settings');

    // Let module handle load Swup.js library.
    $form['load'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Load Swup.js library'),
      '#default_value' => (bool) $config->get('load'),
      '#description' => $this->t(
        "If enabled, this module will attempt to load Swup.js for your site. To prevent loading it twice, leave this option disabled if you're including the assets manually or through another module or theme."
      ),
    ];

    // CDN provider selection.
    $form['cdn_provider'] = [
      '#type' => 'select',
      '#title' => $this->t('CDN Provider'),
      '#options' => [
        'unpkg' => $this->t('unpkg'),
        'jsdelivr' => $this->t('jsDelivr'),
      ],
      '#default_value' => $config->get('cdn_provider') ?: 'unpkg',
      '#description' => $this->t(
        'Select which CDN to use for loading Swup and its plugins. Both ESM and UMD formats will be loaded for maximum browser compatibility.'
      ),
    ];

    // Prefer local installation when available.
    $form['prefer_local'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Prefer local installation'),
      '#default_value' => (bool) $config->get('prefer_local'),
      '#description' => $this->t(
        'When checked and a local installation exists, use it instead of CDN.'
      ),
    ];

    // Local build variant selection.
    $form['local_variant'] = [
      '#type' => 'radios',
      '#title' => $this->t('Local build variant'),
      '#options' => [
        'non-minified' => $this->t('Non-minified (development)'),
        'minified' => $this->t('Minified (production)'),
      ],
      '#default_value' => $config->get('local_variant') ?: 'minified',
      '#description' => $this->t(
        'Choose between minified or non-minified version for local installations. CDN always loads both ESM and UMD for compatibility.'
      ),
      '#states' => [
        'visible' => [
          ':input[name="prefer_local"]' => ['checked' => TRUE],
        ],
      ],
    ];

    // Usability sections.
    $form['usability'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Usability'),
      '#parents' => ['usability_tabs'],
      '#weight' => 99,
    ];

    // Core and plugins selection.
    $form['files'] = [
      '#type' => 'details',
      '#title' => $this->t('Core & Plugins'),
      '#attributes' => ['class' => ['details--settings']],
      '#group' => 'usability_tabs',
      '#open' => TRUE,
    ];
    $form['files']['core'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable Swup core'),
      '#default_value' => (bool) $config->get('core'),
      '#description' => $this->t(
        'Core must be enabled for Swup to work. Plugins require core to be enabled.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::CORE_LATEST_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];

    // Official plugins container.
    $form['files']['plugins'] = [
      '#type' => 'container',
      '#title' => $this->t('Official Swup plugins'),
      '#prefix' => '<div id="swup-plugins">',
      '#suffix' => '</div>',
      '#states' => [
        'invisible' => [
          ':input[name="core"]' => ['checked' => FALSE],
        ],
      ],
    ];
    $form['files']['plugins']['a11y'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Accessibility Plugin'),
      '#default_value' => (bool) $config->get('plugins.a11y'),
      '#description' => $this->t(
        'Enhance accessibility with screen reader announcements and focus management.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::A11Y_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['body_class'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Body Class Plugin'),
      '#default_value' => (bool) $config->get('plugins.body_class'),
      '#description' => $this->t(
        'Update the body classname after each page load.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::BODY_CLASS_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['debug'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Debug Plugin'),
      '#default_value' => (bool) $config->get('plugins.debug'),
      '#description' => $this->t(
        'Enable detailed console logging for development.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::DEBUG_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['forms'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Forms Plugin'),
      '#default_value' => (bool) $config->get('plugins.forms'),
      '#description' => $this->t(
        'Submit forms via AJAX for seamless transitions.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::FORMS_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['fragment'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Fragment Plugin'),
      '#default_value' => (bool) $config->get('plugins.fragment'),
      '#description' => $this->t(
        'Dynamically replace containers based on rules.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::FRAGMENT_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['head'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Head Plugin'),
      '#default_value' => (bool) $config->get('plugins.head'),
      '#description' => $this->t(
        'Update the contents of the head tag including meta tags and assets.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::HEAD_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['js'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('JS Plugin'),
      '#default_value' => (bool) $config->get('plugins.js'),
      '#description' => $this->t(
        'Run JavaScript animations during page transitions.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::JS_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['parallel'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Parallel Plugin'),
      '#default_value' => (bool) $config->get('plugins.parallel'),
      '#description' => $this->t(
        'Animate the previous and next page in parallel for overlays and crossfades.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::PARALLEL_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['preload'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Preload Plugin'),
      '#default_value' => (bool) $config->get('plugins.preload'),
      '#description' => $this->t(
        'Preload pages on hover for instant navigation.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::PRELOAD_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['progress'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Progress Bar Plugin'),
      '#default_value' => (bool) $config->get('plugins.progress'),
      '#description' => $this->t(
        'Display a progress bar for long-running requests.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::PROGRESS_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['route_name'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Route Name Plugin'),
      '#default_value' => (bool) $config->get('plugins.route_name'),
      '#description' => $this->t(
        'Named routes and route-based animation classes.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::ROUTE_NAME_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['scripts'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Scripts Plugin'),
      '#default_value' => (bool) $config->get('plugins.scripts'),
      '#description' => $this->t(
        'Re-evaluate inline scripts after page transitions.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::SCRIPTS_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['plugins']['scroll'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Scroll Plugin'),
      '#default_value' => (bool) $config->get('plugins.scroll'),
      '#description' => $this->t(
        'Customizable smooth scrolling with offset support.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::SCROLL_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];

    // Integration plugins container.
    $form['files']['integrations'] = [
      '#type' => 'container',
      '#title' => $this->t('Integration plugins'),
      '#prefix' => '<div id="swup-integrations">',
      '#suffix' => '</div>',
      '#states' => [
        'invisible' => [
          ':input[name="core"]' => ['checked' => FALSE],
        ],
      ],
    ];
    $form['files']['integrations']['ga'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Google Analytics Plugin'),
      '#default_value' => (bool) $config->get('integrations.ga'),
      '#description' => $this->t(
        'Track page views with Google Analytics.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::GA_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['integrations']['gtm'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Google Tag Manager Plugin'),
      '#default_value' => (bool) $config->get('integrations.gtm'),
      '#description' => $this->t(
        'Track page views with Google Tag Manager.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::GTM_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];
    $form['files']['integrations']['matomo'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Matomo Plugin'),
      '#default_value' => (bool) $config->get('integrations.matomo'),
      '#description' => $this->t(
        'Track page views with Matomo analytics.'
      ),
      '#label_attributes' => [
        'data-version' => SwupConstants::MATOMO_PLUGIN_VERSION,
        'class' => ['swup-has-version'],
      ],
    ];

    // Warning for disabled core.
    $file_warning = $this->t('If core is disabled, Swup cannot load. After saving, loading will be disabled and settings will reset to defaults.');
    $form['files']['file_warning'] = [
      '#type' => 'container',
      '#markup' => '<div class="file-types-report">' . $file_warning . '</div>',
      '#prefix' => '<div id="file-warning">',
      '#suffix' => '</div>',
      '#states' => [
        'visible' => [
          '[data-drupal-selector="edit-core"]' => ['checked' => FALSE],
        ],
      ],
      '#weight' => -9,
    ];

    // Theme visibility.
    $themes = $this->themeHandler->listInfo();
    $active_themes = [];
    foreach ($themes as $key => $theme) {
      if (!empty($theme->status)) {
        $active_themes[$key] = $theme->info['name'];
      }
    }

    $form['theme_groups'] = [
      '#type' => 'details',
      '#title' => $this->t('Themes'),
      '#attributes' => ['class' => ['details--settings']],
      '#group' => 'usability_tabs',
    ];
    $form['theme_groups']['themes'] = [
      '#type' => 'select',
      '#title' => $this->t('Installed themes'),
      '#description' => $this->t(
        'Restrict loading to a subset of themes.'
      ),
      '#options' => $active_themes,
      '#multiple' => TRUE,
      '#default_value' => (array) $config->get('theme_groups.themes'),
    ];
    $form['theme_groups']['theme_negate'] = [
      '#type' => 'radios',
      '#title' => $this->t('Activate on specific themes'),
      '#title_display' => 'invisible',
      '#options' => [
        0 => $this->t('All themes except those selected'),
        1 => $this->t('Only the selected themes'),
      ],
      '#default_value' => (int) $config->get('theme_groups.negate'),
    ];

    // Path visibility.
    $form['request_path'] = [
      '#type' => 'details',
      '#title' => $this->t('Pages'),
      '#attributes' => ['class' => ['details--settings']],
      '#group' => 'usability_tabs',
    ];
    $form['request_path']['pages'] = [
      '#type' => 'textarea',
      '#title' => '<span class="element-invisible">' . $this->t('Pages') . '</span>',
      '#default_value' => _swup_ui_array_to_string(
        (array) $config->get('request_path.pages')
      ),
      '#description' => $this->t(
        'One path per line. Use "*" as wildcard. Example: /admin/*. %front refers to the front page.',
        ['%front' => '<front>']
      ),
    ];
    $form['request_path']['page_negate'] = [
      '#type' => 'radios',
      '#title' => $this->t('Load Swup on specific pages'),
      '#title_display' => 'invisible',
      '#options' => [
        0 => $this->t('All pages except those listed'),
        1 => $this->t('Only the listed pages'),
      ],
      '#default_value' => (int) $config->get('request_path.negate'),
    ];

    // Attach admin UI library.
    $form['#attached']['library'][] = 'swup_ui/swup.settings';

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    // Detect if core is disabled.
    $core_disabled = empty($values['core']);

    // Prepare plugin settings.
    $plugins = $core_disabled ? [
      'a11y' => FALSE,
      'body_class' => FALSE,
      'debug' => FALSE,
      'forms' => FALSE,
      'fragment' => FALSE,
      'head' => FALSE,
      'js' => FALSE,
      'parallel' => FALSE,
      'preload' => FALSE,
      'progress' => FALSE,
      'route_name' => FALSE,
      'scripts' => FALSE,
      'scroll' => FALSE,
    ] : [
      'a11y' => !empty($values['a11y']),
      'body_class' => !empty($values['body_class']),
      'debug' => !empty($values['debug']),
      'forms' => !empty($values['forms']),
      'fragment' => !empty($values['fragment']),
      'head' => !empty($values['head']),
      'js' => !empty($values['js']),
      'parallel' => !empty($values['parallel']),
      'preload' => !empty($values['preload']),
      'progress' => !empty($values['progress']),
      'route_name' => !empty($values['route_name']),
      'scripts' => !empty($values['scripts']),
      'scroll' => !empty($values['scroll']),
    ];

    // Prepare integration settings.
    $integrations = $core_disabled ? [
      'ga' => FALSE,
      'gtm' => FALSE,
      'matomo' => FALSE,
    ] : [
      'ga' => !empty($values['ga']),
      'gtm' => !empty($values['gtm']),
      'matomo' => !empty($values['matomo']),
    ];

    // Save configuration.
    $this->config('swup_ui.settings')
      ->set('load', $core_disabled ? FALSE : (bool) $values['load'])
      ->set('cdn_provider', $values['cdn_provider'])
      ->set('prefer_local', (bool) $values['prefer_local'])
      ->set('local_variant', $values['local_variant'])
      ->set('core', !$core_disabled)
      ->set('plugins.a11y', (bool) $plugins['a11y'])
      ->set('plugins.body_class', (bool) $plugins['body_class'])
      ->set('plugins.debug', (bool) $plugins['debug'])
      ->set('plugins.forms', (bool) $plugins['forms'])
      ->set('plugins.fragment', (bool) $plugins['fragment'])
      ->set('plugins.head', (bool) $plugins['head'])
      ->set('plugins.js', (bool) $plugins['js'])
      ->set('plugins.parallel', (bool) $plugins['parallel'])
      ->set('plugins.preload', (bool) $plugins['preload'])
      ->set('plugins.progress', (bool) $plugins['progress'])
      ->set('plugins.route_name', (bool) $plugins['route_name'])
      ->set('plugins.scripts', (bool) $plugins['scripts'])
      ->set('plugins.scroll', (bool) $plugins['scroll'])
      ->set('integrations.ga', (bool) $integrations['ga'])
      ->set('integrations.gtm', (bool) $integrations['gtm'])
      ->set('integrations.matomo', (bool) $integrations['matomo'])
      ->set('theme_groups.negate', (int) ($values['theme_negate'] ?? 0))
      ->set('theme_groups.themes', (array) ($values['themes'] ?? []))
      ->set('request_path.negate', (int) ($values['page_negate'] ?? 0))
      ->set('request_path.pages', (array) _swup_ui_string_to_array(
        (string) ($values['pages'] ?? '')
      ))
      ->save();

    // Inform the user when a reset occurred.
    if ($core_disabled) {
      $this->messenger()->addWarning($this->t(
        'Core was disabled. Settings were reset to defaults. Global loading was disabled.'
      ));
    }

    // Flush caches so the updated config can be checked.
    drupal_flush_all_caches();

    parent::submitForm($form, $form_state);
  }

}

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

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