You are here

class ScssColor in SCSS Compiler 1.0.x

A form element to represent null-able Sass colors.

Copyright (C) 2021 Library Solutions, LLC (et al.).

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

Plugin annotation

@FormElement("compiler_scss_color");

Hierarchy

Expanded class hierarchy of ScssColor

File

src/Element/ScssColor.php, line 23

Namespace

Drupal\compiler_scss\Element
View source
class ScssColor extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    return [
      '#children' => [],
      '#element_validate' => [
        [
          get_class(),
          'validateColor',
        ],
      ],
      '#input' => TRUE,
      '#required' => FALSE,
      '#theme' => 'container',
      '#theme_wrappers' => [
        'form_element',
      ],
      '#title' => NULL,
      '#tree' => TRUE,
      '#process' => [
        [
          get_class(),
          'processColor',
        ],
      ],
    ];
  }

  /**
   * Attempt to extract the value of the supplied element.
   *
   * @param array $element
   *   The element for which to attempt to extract a value.
   *
   * @return string
   *   The requested value from the supplied element.
   */
  protected static function getValue(array $element) {
    $value = $element['#value'] ?? '';
    if ($value instanceof IntermediateColor) {
      $value = $value
        ->toHex();
    }
    return $value;
  }

  /**
   * Process the element before it gets rendered in the form.
   *
   * @param array $element
   *   The element to process before being rendered.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form.
   *
   * @return array
   *   The resulting element after having been processed.
   */
  public static function processColor(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $element['enable'] = [
      '#type' => 'checkbox',
      '#title' => t('Set value?'),
      '#name' => "{$element['#name']}[enable]",
      '#access' => !$element['#required'],
      '#default_value' => !empty(self::getValue($element)),
    ];
    $element['value'] = [
      '#type' => 'color',
      '#name' => "{$element['#name']}[value]",
      '#title' => $element['#title'],
      '#title_display' => 'none',
      // The "color" element only supports hex codes with long channels and no
      // alpha channel value, so we trim the value here.
      '#default_value' => substr(self::getValue($element), 0, 7),
      '#required' => $element['#required'],
      '#states' => [
        'visible' => [
          ":input[name=\"{$element['enable']['#name']}\"]" => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $element['#children'][] =& $element['enable'];
    $element['#children'][] =& $element['value'];
    return $element;
  }

  /**
   * Validate this element's value on form submission.
   *
   * @param array $element
   *   The element that should be validated.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form.
   */
  public static function validateColor(array &$element, FormStateInterface $form_state, array &$complete_form) {

    // Extract the input value from the element.
    $input = self::getValue($element);

    // Represent the input as a typed data instance to facilitate validation.
    $definition = DataDefinition::create('compiler_scss_color');
    $color = \Drupal::typedDataManager()
      ->create($definition, $input);

    // Check if the input value failed validation.
    if ($color
      ->validate()
      ->count() > 0) {
      $error = $element['#title'] ? t('%name must be a valid color.', [
        '%name' => $element['#title'],
      ]) : t('This field must be a valid color.');
      $form_state
        ->setError($element, $error);
    }
    else {
      $form_state
        ->setValueForElement($element, $input ?: NULL);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {

    // Populate the element with a default value if none already exists.
    $element += [
      '#default_value' => '',
    ];
    if ($element['#default_value'] instanceof IntermediateColor) {
      $element['#default_value'] = $element['#default_value']
        ->toHex();
    }

    // Check if the element's default value should be used in lieu of an input.
    if ($input === FALSE) {

      // Replace the input with the element's default value if FALSE.
      $input = $element['#default_value'];
      $input = [
        'enable' => is_string($input) && !empty($input),
        'value' => is_string($input) ? $input : '',
      ];
    }

    // Only attempt to process the input (or default value) if it's an array.
    if (is_array($input) && array_key_exists('value', $input)) {
      if (!$element['#required']) {
        $enable = $input['enable'] ?? FALSE;

        // Only return a color value if this element is enabled.
        return $enable ? $input['value'] : '';
      }
      else {

        // Always return a value if the field is required.
        return $input['value'];
      }
    }
    return '';
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
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 2
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.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 98
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
ScssColor::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
ScssColor::getValue protected static function Attempt to extract the value of the supplied element.
ScssColor::processColor public static function Process the element before it gets rendered in the form.
ScssColor::validateColor public static function Validate this element's value on form submission.
ScssColor::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
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.