class Style
CKEditor 5 Style plugin configuration.
@internal Plugin classes are internal.
Hierarchy
- class \Drupal\Component\Plugin\PluginBase implements \Drupal\Component\Plugin\PluginInspectionInterface, \Drupal\Component\Plugin\DerivativeInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses \Drupal\Core\StringTranslation\StringTranslationTrait, \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Messenger\MessengerTrait extends \Drupal\Component\Plugin\PluginBase
- class \Drupal\ckeditor5\Plugin\CKEditor5PluginDefault implements \Drupal\ckeditor5\Plugin\CKEditor5PluginInterface extends \Drupal\Core\Plugin\PluginBase
- class \Drupal\ckeditor5\Plugin\CKEditor5Plugin\Style implements \Drupal\ckeditor5\Plugin\CKEditor5PluginConfigurableInterface, \Drupal\ckeditor5\Plugin\CKEditor5PluginElementsSubsetInterface uses \Drupal\ckeditor5\Plugin\CKEditor5PluginConfigurableTrait extends \Drupal\ckeditor5\Plugin\CKEditor5PluginDefault
 
 
 - class \Drupal\ckeditor5\Plugin\CKEditor5PluginDefault implements \Drupal\ckeditor5\Plugin\CKEditor5PluginInterface extends \Drupal\Core\Plugin\PluginBase
 
 - class \Drupal\Core\Plugin\PluginBase uses \Drupal\Core\StringTranslation\StringTranslationTrait, \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Messenger\MessengerTrait extends \Drupal\Component\Plugin\PluginBase
 
Expanded class hierarchy of Style
3 files declare their use of Style
- Core.php in core/
modules/ ckeditor5/ src/ Plugin/ CKEditor4To5Upgrade/ Core.php  - StylePluginTest.php in core/
modules/ ckeditor5/ tests/ src/ Unit/ StylePluginTest.php  - StyleSensibleElementConstraintValidator.php in core/
modules/ ckeditor5/ src/ Plugin/ Validation/ Constraint/ StyleSensibleElementConstraintValidator.php  
66 string references to 'Style'
- ArgumentPluginBase::calculateDependencies in core/
modules/ views/ src/ Plugin/ views/ argument/ ArgumentPluginBase.php  - Calculates dependencies for the configured plugin.
 - ArgumentPluginBase::defaultSummaryForm in core/
modules/ views/ src/ Plugin/ views/ argument/ ArgumentPluginBase.php  - Provides a form for selecting summary options.
 - ArgumentPluginBase::getCacheContexts in core/
modules/ views/ src/ Plugin/ views/ argument/ ArgumentPluginBase.php  - The cache contexts associated with this object.
 - ArgumentPluginBase::getCacheMaxAge in core/
modules/ views/ src/ Plugin/ views/ argument/ ArgumentPluginBase.php  - The maximum age for which this object may be cached.
 - ArgumentPluginBase::getCacheTags in core/
modules/ views/ src/ Plugin/ views/ argument/ ArgumentPluginBase.php  - The cache tags associated with this object.
 
File
- 
              core/
modules/ ckeditor5/ src/ Plugin/ CKEditor5Plugin/ Style.php, line 21  
Namespace
Drupal\ckeditor5\Plugin\CKEditor5PluginView source
class Style extends CKEditor5PluginDefault implements CKEditor5PluginConfigurableInterface, CKEditor5PluginElementsSubsetInterface {
  use CKEditor5PluginConfigurableTrait;
  
  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['styles'] = [
      '#title' => $this->t('Styles'),
      '#type' => 'textarea',
      '#description' => $this->t('A list of classes that will be provided in the "Style" dropdown. Enter one or more classes on each line in the format: element.classA.classB|Label. Example: h1.title|Title. Advanced example: h1.fancy.title|Fancy title.<br />These styles should be available in your theme\'s CSS file.'),
    ];
    if (!empty($this->configuration['styles'])) {
      $as_selectors = '';
      foreach ($this->configuration['styles'] as $style) {
        [$tag, $classes] = self::getTagAndClasses(HTMLRestrictions::fromString($style['element']));
        $as_selectors .= sprintf("%s.%s|%s\n", $tag, implode('.', $classes), $style['label']);
      }
      $form['styles']['#default_value'] = $as_selectors;
    }
    return $form;
  }
  
  /**
   * Gets the tag and classes for a parsed style element.
   *
   * @param \Drupal\ckeditor5\HTMLRestrictions $style_element
   *   A parsed style element.
   *
   * @return array
   *   An array containing two values:
   *   - a HTML tag name
   *   - a list of classes
   *
   * @internal
   */
  public static function getTagAndClasses(HTMLRestrictions $style_element) : array {
    $tag = array_keys($style_element->getAllowedElements())[0];
    $classes = array_keys($style_element->getAllowedElements()[$tag]['class']);
    return [
      $tag,
      $classes,
    ];
  }
  
  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    // Match the config schema structure at ckeditor5.plugin.ckeditor5_style.
    $form_value = $form_state->getValue('styles');
    [$styles, $unparseable_lines] = self::parseStylesFormValue($form_value);
    if (!empty($unparseable_lines)) {
      $line_numbers = array_keys($unparseable_lines);
      $form_state->setError($form['styles'], $this->formatPlural(count($unparseable_lines), 'Line @line-number does not contain a valid value. Enter a valid CSS selector containing one or more classes, followed by a pipe symbol and a label.', 'Lines @line-numbers do not contain a valid value. Enter a valid CSS selector containing one or more classes, followed by a pipe symbol and a label.', [
        '@line-number' => reset($line_numbers),
        '@line-numbers' => implode(', ', $line_numbers),
      ]));
    }
    $form_state->setValue('styles', $styles);
  }
  
  /**
   * Parses the line-based (for form) style configuration.
   *
   * @param string $form_value
   *   A string containing >=1 lines with on each line a CSS selector targeting
   *   1 tag with >=1 classes, a pipe symbol and a label. An example of a single
   *   line: `p.foo.bar|Foo bar paragraph`.
   *
   * @return array
   *   The parsed equivalent: a list of arrays with each containing:
   *   - label: the label after the pipe symbol, with whitespace trimmed
   *   - element: the CKEditor 5 element equivalent of the tag + classes
   *
   * @internal
   *   This method is public only to allow the CKEditor 4 to 5 upgrade path to
   *   reuse this logic. Mark this private in https://www.drupal.org/i/3239012.
   *
   * @see \Drupal\ckeditor5\Plugin\CKEditor4To5Upgrade\Core::mapCKEditor4SettingsToCKEditor5Configuration()
   */
  public static function parseStylesFormValue(string $form_value) : array {
    $unparseable_lines = [];
    $lines = explode("\n", $form_value);
    $styles = [];
    foreach ($lines as $index => $line) {
      if (empty(trim($line))) {
        continue;
      }
      // Parse the line.
      [$selector, $label] = array_map('trim', explode('|', $line));
      // Validate the selector.
      $selector_matches = [];
      // @see https://www.w3.org/TR/CSS2/syndata.html#:~:text=In%20CSS%2C%20identifiers%20(including%20element,hyphen%20followed%20by%20a%20digit
      if (!preg_match('/^([a-z][0-9a-zA-Z\\-]*)((\\.[a-zA-Z0-9\\x{00A0}-\\x{FFFF}\\-_]+)+)$/u', $selector, $selector_matches)) {
        $unparseable_lines[$index + 1] = $line;
        continue;
      }
      // Parse selector into tag + classes and normalize.
      $tag = $selector_matches[1];
      $classes = array_filter(explode('.', $selector_matches[2]));
      $normalized = HTMLRestrictions::fromString(sprintf('<%s class="%s">', $tag, implode(' ', $classes)));
      $styles[] = [
        'label' => $label,
        'element' => $normalized->toCKEditor5ElementsArray()[0],
      ];
    }
    return [
      $styles,
      $unparseable_lines,
    ];
  }
  
  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['styles'] = $form_state->getValue('styles');
  }
  
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'styles' => [],
    ];
  }
  
  /**
   * {@inheritdoc}
   */
  public function getElementsSubset() : array {
    return array_column($this->configuration['styles'], 'element');
  }
  
  /**
   * {@inheritdoc}
   */
  public function getDynamicPluginConfig(array $static_plugin_config, EditorInterface $editor) : array {
    $definitions = [];
    foreach ($this->configuration['styles'] as $style) {
      [$tag, $classes] = self::getTagAndClasses(HTMLRestrictions::fromString($style['element']));
      // Transform configured styles to the configuration structure expected by
      // the CKEditor 5 Style plugin.
      $definitions[] = [
        'name' => $style['label'],
        'element' => $tag,
        'classes' => $classes,
      ];
    }
    return [
      'style' => [
        'definitions' => $definitions,
      ],
    ];
  }
}
Members
| Title Sort descending | Modifiers | Object type | Summary | Overriden Title | Overrides | 
|---|---|---|---|---|---|
| CKEditor5PluginConfigurableTrait::getConfiguration | public | function | |||
| CKEditor5PluginConfigurableTrait::setConfiguration | public | function | |||
| CKEditor5PluginDefault::__construct | public | function | Constructs a \Drupal\Component\Plugin\PluginBase object. | Overrides PluginBase::__construct | 2 | 
| 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 | 2 | ||
| DependencySerializationTrait::__wakeup | public | function | #[\ReturnTypeWillChange] | 2 | |
| 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. | ||
| StringTranslationTrait::$stringTranslation | protected | property | The string translation service. | 3 | |
| 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. | ||
| Style::buildConfigurationForm | public | function | Form constructor. | Overrides PluginFormInterface::buildConfigurationForm | |
| Style::defaultConfiguration | public | function | Gets default configuration for this plugin. | Overrides ConfigurableInterface::defaultConfiguration | |
| Style::getDynamicPluginConfig | public | function | Allows a plugin to modify its static configuration. | Overrides CKEditor5PluginDefault::getDynamicPluginConfig | |
| Style::getElementsSubset | public | function | Returns a configured subset of the elements supported by this plugin. | Overrides CKEditor5PluginElementsSubsetInterface::getElementsSubset | |
| Style::getTagAndClasses | public static | function | Gets the tag and classes for a parsed style element. | ||
| Style::parseStylesFormValue | public static | function | Parses the line-based (for form) style configuration. | ||
| Style::submitConfigurationForm | public | function | Form submission handler. | Overrides PluginFormInterface::submitConfigurationForm | |
| Style::validateConfigurationForm | public | function | Form validation handler. | Overrides PluginFormInterface::validateConfigurationForm | 
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.