Commit f3eafc1a authored by Stephan Zeidler's avatar Stephan Zeidler Committed by Stephan Zeidler
Browse files

Issue #3030727 by szeidler, Jens Peter: Option: Popup should open as default instead of onclick

parent 6ce17a9c
Loading
Loading
Loading
Loading
+6 −0
Original line number Diff line number Diff line
@@ -12,6 +12,12 @@ block.settings.mailchimp_popup_block:
    mailchimp_lid:
      type: label
      label: 'Mailchimp List ID'
    method:
      type: string
      label: 'Popup method (triggered or automatic)'
    popup_reappear_offset:
      type: integer
      label: 'Popup reappear offset'
    description:
      type: text
      label: 'Description'
+78 −9
Original line number Diff line number Diff line
@@ -2,30 +2,99 @@
 * @file
 * Mailchimp Popup Block listener.
 */

(function (Drupal, window, document) {
  'use strict';

  var mailchimpPopupLoader = document.createElement('script');
  mailchimpPopupLoader.src = '//downloads.mailchimp.com/js/signup-forms/popup/embed.js';
  mailchimpPopupLoader.setAttribute('id', 'mailchimp-embed-library');
  mailchimpPopupLoader.setAttribute('data-dojo-config', 'usePlainJson: true, isDebug: false');
  document.body.appendChild(mailchimpPopupLoader);

  Drupal.behaviors.mailchimpPopupBlockListener = {
    attach: function (context) {
      document.body.appendChild(mailchimpPopupLoader);
    attach: function (context, settings) {
      var method = settings.mailchimp_popup_block.method;

      // For the automatic method load the mailchimp popup, once the embed
      // script has been successfully loaded.
      if (method === 'automatic') {
        var script = document.querySelector('#mailchimp-embed-library');
        script.addEventListener('load', function () {
          var config = {
            baseUrl: settings.mailchimp_popup_block.mailchimp_baseurl,
            uuid: settings.mailchimp_popup_block.mailchimp_uuid,
            lid: settings.mailchimp_popup_block.mailchimp_lid
          };

          var popup_reappear_offset = settings.mailchimp_popup_block.popup_reappear_offset;
          var cookies_just_deleted = false;

          require(['mojo/signup-forms/Loader'], function (L) {
            L.start(config, function () {
            });

            // If the cookie not-exists, the popup should have been shown,
            // so set our cookies.
            if (document.cookie.indexOf('MCPopupClosed=') === -1) {
              var date_keep_closed = new Date();
              date_keep_closed.setFullYear(new Date().getFullYear() + 1);
              document.cookie = 'MCPopupBlockKeepClosed=yes;path=/;expires=' + date_keep_closed.toUTCString() + ';';

              var date_keep_closed_until = new Date();
              // Javascript dates uses milliseconds, so convert it.
              date_keep_closed_until.setTime(date_keep_closed_until.getTime() + (popup_reappear_offset * 1000));
              document.cookie = 'MCPopupBlockKeepClosedUntil=;path=/;expires=' + date_keep_closed_until.toUTCString() + ';';
            }
            // If the cookie exists, the popup was once closed. So we set
            // a custom cookie, that will trigger the deletion of this one,
            // which lasts for a year.
            else {
              // If the control cookie was not set, set it for one year expiry.
              if (document.cookie.indexOf('MCPopupBlockKeepClosed=') === -1) {
                var date_keep_closed = new Date();
                date_keep_closed.setFullYear(new Date().getFullYear() + 1);
                document.cookie = 'MCPopupBlockKeepClosed=yes;path=/;expires=' + date_keep_closed.toUTCString() + ';';
              }

              // If our control cookie was set, but the expiry cookie is missing.
              // Invalidate all cookies, so that the cookie will be shown again.
              if (document.cookie.indexOf('MCPopupBlockKeepClosed=') !== -1 && document.cookie.indexOf('MCPopupBlockKeepClosedUntil=') === -1) {
                document.cookie = 'MCPopupClosed=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC;';
                document.cookie = 'MCPopupBlockKeepClosed=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC;';
                document.cookie = 'MCPopupBlockKeepClosedUntil=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC;';
                cookies_just_deleted = true;
              }

              // If the cookies just have been deleted, reinitialize value.
              if (cookies_just_deleted) {
                var date_keep_closed = new Date();
                date_keep_closed.setFullYear(new Date().getFullYear() + 1);
                document.cookie = 'MCPopupBlockKeepClosed=yes;path=/;expires=' + date_keep_closed.toUTCString() + ';';
              }

              // If own expiry time cookie was not set. Set it.
              if (cookies_just_deleted || document.cookie.indexOf('MCPopupBlockKeepClosedUntil=') === -1) {
                var date_keep_closed_until = new Date();
                // Javascript dates uses milliseconds, so convert it.
                date_keep_closed_until.setTime(date_keep_closed_until.getTime() + (popup_reappear_offset * 1000));
                document.cookie = 'MCPopupBlockKeepClosedUntil=;path=/;expires=' + date_keep_closed_until.toUTCString() + ';';
                cookies_just_deleted = false;
              }
            }
          });
        });
      }

      var trigger = context.querySelector('.mailchimp-popup-block__trigger');
      if (trigger) {
        trigger.addEventListener('click', function (e) {
          e.preventDefault();

          var baseUrl = this.getAttribute('data-mailchimp-popup-block-baseurl');
          var uuid = this.getAttribute('data-mailchimp-popup-block-uuid');
          var lid = this.getAttribute('data-mailchimp-popup-block-lid');

          var config = {
            baseUrl: baseUrl,
            uuid: uuid,
            lid: lid
            baseUrl: this.getAttribute('data-mailchimp-popup-block-baseurl'),
            uuid: this.getAttribute('data-mailchimp-popup-block-uuid'),
            lid: this.getAttribute('data-mailchimp-popup-block-lid')
          };

          require(['mojo/signup-forms/Loader'], function (L) {
+24 −0
Original line number Diff line number Diff line
<?php

/**
 * @file
 * Install, update and uninstall functions for Mailchimp Popup Block.
 */

/**
 * Configure existing mailchimp blocks with manual popup method.
 */
function mailchimp_popup_block_update_8001() {
  // Save all existing mailchimp popup blocks with the Method: manually,
  // after we introduced different methods.
  $config_factory = \Drupal::configFactory();

  foreach ($config_factory->listAll('block.block.') as $block_config_name) {
    $block = $config_factory->getEditable($block_config_name);
    $plugin = $block->get('plugin');
    if ($plugin === 'mailchimp_popup_block') {
      $block->set('settings.method', 'manual');
      $block->save();
    }
  }
}
+13 −0
Original line number Diff line number Diff line
@@ -45,3 +45,16 @@ function mailchimp_popup_block_theme($existing, $type, $theme, $path) {
      ],
  ];
}

/**
 * Implements hook_preprocess_HOOK().
 */
function mailchimp_popup_block_preprocess_block(&$variables) {
  if ($variables['plugin_id'] === 'mailchimp_popup_block') {
    // Automatic mailchimp popup blocks will not be shown, but only invoke
    // javascript. So hide the empty wrappers.
    if (isset($variables['configuration']['method']) && $variables['configuration']['method'] === 'automatic') {
      $variables['attributes']['style'] = 'display:none;';
    }
  }
}
+100 −1
Original line number Diff line number Diff line
@@ -20,15 +20,77 @@ class MailchimpPopupBlock extends BlockBase {
   */
  public function build() {
    $config = $this->getConfiguration();
    $method = $config['method'];

    return [
    // Invoke the selected build method.
    switch ($method) {
      case 'automatic':
        $build = $this->buildAutomatic($config);
        break;

      default:
        $build = $this->buildManual($config);
    }

    return $build;
  }

  /**
   * Returns the automatic triggered popup block.
   *
   * @param array $config
   *   Block configuration.
   *
   * @return array
   *   Block render array.
   */
  protected function buildAutomatic(array $config) {
    $build = [
      '#cache' => [
        'tags' => $this->getCacheTags(),
        'contexts' => $this->getCacheContexts(),
      ],
    ];
    $build['#attached']['library'][] = 'mailchimp_popup_block/mailchimp_popup_block';

    // Automatic popup block loads mailchimp without data attributes from
    // the block instance. So we need to attach those settings globally to the
    // javascript settings.
    $build['#attached']['drupalSettings']['mailchimp_popup_block'] = [
      'method' => $config['method'],
      'mailchimp_baseurl' => $config['mailchimp_baseurl'],
      'mailchimp_uuid' => $config['mailchimp_uuid'],
      'mailchimp_lid' => $config['mailchimp_lid'],
      'popup_reappear_offset' => $config['popup_reappear_offset'],
    ];

    return $build;
  }

  /**
   * Returns the manual triggered popup block.
   *
   * @param array $config
   *   Block configuration.
   *
   * @return array
   *   Block render array.
   */
  protected function buildManual(array $config) {
    $build = [
      '#theme' => 'mailchimp_popup',
      '#description' => $config['description'],
      '#button_text' => $config['button_text'],
      '#mailchimp_baseurl' => $config['mailchimp_baseurl'],
      '#mailchimp_uuid' => $config['mailchimp_uuid'],
      '#mailchimp_lid' => $config['mailchimp_lid'],
      '#cache' => [
        'tags' => $this->getCacheTags(),
        'contexts' => $this->getCacheContexts(),
      ],
    ];
    $build['#attached']['drupalSettings']['mailchimp_popup_block']['method'] = $config['method'];
    return $build;
  }

  /**
@@ -64,12 +126,42 @@ class MailchimpPopupBlock extends BlockBase {
      '#description' => $this->t('The mailchimp list id.'),
      '#default_value' => isset($config['mailchimp_lid']) ? $config['mailchimp_lid'] : NULL,
    ];
    $form['method'] = [
      '#type' => 'select',
      '#title' => $this->t('Popup Method'),
      '#description' => $this->t('How should the Popup be opened.'),
      '#default_value' => isset($config['method']) ? $config['method'] : NULL,
      '#options' => [
        'manual' => $this->t('Trigger manually by click on a button'),
        'automatic' => $this->t('Open automatically on pageload'),
      ],
    ];

    // Automatic popup.
    $form['popup_reappear_offset'] = [
      '#type' => 'number',
      '#title' => $this->t('Popup reappear offset.'),
      '#description' => $this->t('After how much time should the popup reappear, after it has been closed by the user (in seconds). Set to <code>0</code> for forcing the popup to open at every request.<br> 1 hour: 3600<br> 1 day: 86400<br> 1 week: 604800<br> 1 month: 2630000</li></ul>'),
      '#default_value' => isset($config['popup_reappear_offset']) ? $config['popup_reappear_offset'] : 2630000,
      '#min' => 0,
      '#states' => [
        'visible' => [
          ':input[name="method"]' => ['value' => 'automatic'],
        ],
      ],
    ];

    // Manual popup trigger.
    $form['description'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Description'),
      '#description' => $this->t('Intro text for the newsletter, shown before the button.'),
      '#default_value' => isset($config['description']) ? $config['description'] : NULL,
      '#states' => [
        'visible' => [
          ':input[name="method"]' => ['value' => 'manual'],
        ],
      ],
    ];
    $form['button_text'] = [
      '#type' => 'textfield',
@@ -77,6 +169,11 @@ class MailchimpPopupBlock extends BlockBase {
      '#title' => $this->t('Button text'),
      '#description' => $this->t('The text of the popup trigger button.'),
      '#default_value' => isset($config['button_text']) ? $config['button_text'] : NULL,
      '#states' => [
        'visible' => [
          ':input[name="method"]' => ['value' => 'manual'],
        ],
      ],
    ];

    return $form;
@@ -99,8 +196,10 @@ class MailchimpPopupBlock extends BlockBase {
        'mailchimp',
        'mailchimp_lid',
      ]));
      $this->setConfigurationValue('method', $form_state->getValue('method'));
      $this->setConfigurationValue('description', $form_state->getValue('description'));
      $this->setConfigurationValue('button_text', $form_state->getValue('button_text'));
      $this->setConfigurationValue('popup_reappear_offset', $form_state->getValue('popup_reappear_offset'));
    }
  }