You are here

class SidrTrigger in Sidr: Accessible Mobile Menus 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/Block/SidrTrigger.php \Drupal\sidr\Plugin\Block\SidrTrigger
  2. 8.2 src/Plugin/Block/SidrTrigger.php \Drupal\sidr\Plugin\Block\SidrTrigger

Provides a trigger button with Sidr integration.

Plugin annotation


@Block(
  id = "sidr_trigger",
  admin_label = @Translation("Sidr trigger button block"),
)

Hierarchy

Expanded class hierarchy of SidrTrigger

File

src/Plugin/Block/SidrTrigger.php, line 20

Namespace

Drupal\sidr\Plugin\Block
View source
class SidrTrigger extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Default sidr theme.
   */
  const DEFAULT_THEME = 'dark';

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config_factory) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->configFactory = $config_factory;
  }

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

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return parent::defaultConfiguration() + [
      'trigger_text' => '',
      'trigger_icon' => '',
      'sidr_name' => '',
      'sidr_source' => '',
      'sidr_side' => 'left',
      'sidr_renaming' => FALSE,
      'sidr_speed' => '',
      'sidr_timing' => '',
      'sidr_method' => 'toggle',
      'sidr_displace' => '',
      'sidr_body' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $conf = $this->configuration;
    $settings = $this->configFactory
      ->get('sidr.settings');

    // Determine sidr theme.
    $sidr_theme = $settings
      ->get('sidr_theme') ?: static::DEFAULT_THEME;

    // Wrapper element.
    $build = [
      '#type' => 'container',
      '#theme_wrappers' => [
        'container' => [
          '#attributes' => [
            'class' => [
              'sidr-trigger',
              'js-sidr-trigger',
            ],
            'data-sidr-options' => json_encode($this
              ->getSidrJsOptions()),
          ],
        ],
      ],
      '#attached' => [
        'library' => [
          'sidr/behaviors',
          'sidr/sidr.' . $sidr_theme,
        ],
      ],
    ];

    // Display icon, if any.
    if ($conf['trigger_icon']) {
      $build['icon'] = [
        '#type' => 'markup',
        '#markup' => $conf['trigger_icon'],
        '#prefix' => '<span class="sidr-trigger__icon">',
        '#suffix' => '</span>',
      ];
      $build['#theme_wrappers']['container']['#attributes']['class'][] = 'has-icon';
    }

    // Display text, if any.
    if ($conf['trigger_text']) {
      $build['text'] = [
        '#type' => 'html_tag',
        '#tag' => 'span',
        '#attributes' => [
          'class' => [
            'sidr-trigger__text',
          ],
        ],
        '#value' => $conf['trigger_text'],
      ];
      $build['#theme_wrappers']['container']['#attributes']['class'][] = 'has-text';
    }
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $conf = $this
      ->getConfiguration();
    $settings = $this->configFactory
      ->get('sidr.settings');

    // Basic settings.
    $form['basic'] = [
      '#title' => $this
        ->t('Basic settings'),
      '#type' => 'fieldset',
    ];
    $form['basic']['trigger_text'] = [
      '#title' => $this
        ->t('Trigger text'),
      '#type' => 'textfield',
      '#description' => $this
        ->t('Text to display on the trigger. Example: @example', [
        '@example' => 'Menu',
      ]),
      '#rows' => 3,
      '#maxlength' => 255,
      '#default_value' => $conf['trigger_text'],
    ];
    $form['basic']['sidr_source'] = [
      '#title' => $this
        ->t('Source'),
      '#type' => 'textarea',
      '#description' => $this
        ->t('A jQuery selector, a URL or a callback function.'),
      '#required' => TRUE,
      '#maxlength' => 255,
      '#default_value' => $conf['sidr_source'],
    ];
    $form['basic']['sidr_side'] = [
      '#title' => $this
        ->t('Location'),
      '#type' => 'radios',
      '#options' => [
        'left' => $this
          ->t('Left'),
        'right' => $this
          ->t('Right'),
      ],
      '#default_value' => $conf['sidr_side'],
    ];
    $form['basic']['theme'] = [
      '#title' => 'Theme',
      '#type' => 'textfield',
      '#description' => $this
        ->t('To modify the global sidr theme, visit the <a href="@sidr-settings">Sidr settings</a> page.', [
        '@sidr-settings' => Url::fromRoute('sidr.settings')
          ->toString(),
      ]),
      '#disabled' => TRUE,
      '#default_value' => $settings
        ->get('sidr_theme'),
    ];

    // Advanced settings.
    $form['advanced'] = [
      '#title' => $this
        ->t('Advanced settings'),
      '#type' => 'details',
      '#description' => $this
        ->t('For more information about various Sidr options, see the <a href="@sidr-documentation">Sidr documentation</a> page.', [
        '@sidr-documentation' => 'https://www.berriart.com/sidr/',
      ]),
      '#open' => FALSE,
    ];
    $form['advanced']['trigger_icon'] = [
      '#title' => $this
        ->t('Trigger icon'),
      '#type' => 'textarea',
      '#description' => $this
        ->t('Icon to display on the trigger. Example: @example', [
        '@example' => '<span class="icon-hamburger"></span>',
      ]),
      '#maxlength' => 255,
      '#default_value' => $conf['trigger_icon'],
    ];
    $form['advanced']['sidr_name'] = [
      '#title' => $this
        ->t('Unique ID'),
      '#type' => 'textfield',
      '#description' => $this
        ->t('A unique DOM ID for the sidr instance. Example: @example', [
        '@example' => 'sidr-left',
      ]),
      '#maxlength' => 255,
      '#default_value' => $conf['sidr_name'],
    ];
    $form['advanced']['sidr_method'] = [
      '#title' => $this
        ->t('Trigger action'),
      '#type' => 'select',
      '#options' => [
        'toggle' => $this
          ->t('Toggle'),
        'open' => $this
          ->t('Open'),
        'close' => $this
          ->t('Close'),
      ],
      '#default_value' => $conf['sidr_method'],
    ];
    $form['advanced']['sidr_speed'] = [
      '#title' => $this
        ->t('Animation speed'),
      '#type' => 'textfield',
      '#description' => $this
        ->t('Examples: @example', [
        '@example' => 'slow, fast, 400',
      ]),
      '#default_value' => $conf['sidr_speed'],
    ];
    $form['advanced']['sidr_timing'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Animation timing function'),
      '#description' => $this
        ->t('Examples: @example', [
        '@example' => 'linear, ease, cubic-bezier(...)',
      ]),
      '#maxlength' => 32,
      '#default_value' => $conf['sidr_timing'],
    ];
    $form['advanced']['sidr_renaming'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Rename elements?'),
      '#description' => $this
        ->t('Rename classes and IDs of source elements when filling the Sidr with existing content.'),
      '#default_value' => $conf['sidr_renaming'],
    ];
    $form['advanced']['sidr_displace'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Displace content?'),
      '#description' => $this
        ->t('Whether to displace page content during open and close animations.'),
      '#default_value' => $conf['sidr_displace'],
    ];
    $form['advanced']['sidr_body'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Element to displace'),
      '#description' => $this
        ->t('The element to be displaced during open / close animations instead of the @body element.', [
        '@body' => 'BODY',
      ]),
      '#default_value' => $conf['sidr_body'],
      '#maxlength' => 255,
      '#states' => [
        'visible' => [
          ':input[name="settings[advanced][sidr_displace]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockValidate($form, FormStateInterface $form_state) {
    parent::blockValidate($form, $form_state);
    $values = $form_state
      ->getValues();
    $values = $values['basic'] + $values['advanced'];

    // Either trigger text or trigger icon must be set.
    if (!$values['trigger_text'] && !$values['trigger_icon']) {
      $message = $this
        ->t('Please provide either trigger text or a trigger icon.');
      $form_state
        ->setError($form['basic']['trigger_text'], $message);
      $form_state
        ->setError($form['advanced']['trigger_icon'], $message);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state
      ->getValues();
    $values = $values['basic'] + $values['advanced'];
    $keys = array_keys($this
      ->defaultConfiguration());
    foreach ($keys as $key) {
      switch ($key) {
        case 'sidr_renaming':
        case 'sidr_displace':
          $this->configuration[$key] = (bool) $values[$key];
          break;
        default:
          $this->configuration[$key] = $values[$key];
      }
    }
  }

  /**
   * Returns block configuration as options for the Sidr jQuery plugin.
   *
   * @return array
   *   Sidr options.
   */
  protected function getSidrJsOptions() {
    $conf = $this
      ->getConfiguration();
    $output = [
      'source' => $conf['sidr_source'],
      'name' => $conf['sidr_name'],
      'side' => $conf['sidr_side'],
      'method' => $conf['sidr_method'],
      'speed' => $conf['sidr_speed'],
      'timing' => is_numeric($conf['sidr_timing']) ? (int) $conf['sidr_timing'] : $conf['sidr_timing'],
      'renaming' => $conf['sidr_renaming'],
      'displace' => $conf['sidr_displace'],
      'body' => $conf['sidr_displace'] ? $conf['sidr_body'] : '',
    ];

    // TODO: Require PHP 5.3 and use anonymous callback.
    return array_filter($output, [
      __CLASS__,
      'isOptionNonEmpty',
    ]);
  }

  /**
   * Test whether a Sidr option is not empty.
   *
   * @param mixed $value
   *   The value to test.
   *
   * @return bool
   *   TRUE if the value is non-empty.
   */
  public static function isOptionNonEmpty($value) {
    return is_bool($value) || !empty($value);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockAccess protected function Indicates whether the block should be shown. 16
BlockPluginTrait::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. 2
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit().
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts 9
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 4
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__get public function Implements magic __get() method.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function
PluginWithFormsTrait::hasFormClass public function
SidrTrigger::$configFactory protected property Config factory.
SidrTrigger::blockForm public function Overrides BlockPluginTrait::blockForm
SidrTrigger::blockSubmit public function Overrides BlockPluginTrait::blockSubmit
SidrTrigger::blockValidate public function Overrides BlockPluginTrait::blockValidate
SidrTrigger::build public function Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface::build
SidrTrigger::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
SidrTrigger::defaultConfiguration public function Overrides BlockPluginTrait::defaultConfiguration
SidrTrigger::DEFAULT_THEME constant Default sidr theme.
SidrTrigger::getSidrJsOptions protected function Returns block configuration as options for the Sidr jQuery plugin.
SidrTrigger::isOptionNonEmpty public static function Test whether a Sidr option is not empty.
SidrTrigger::__construct public function Overrides BlockPluginTrait::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2