Skip to content
Snippets Groups Projects
Commit ddf9710a authored by Sviatoslav Smovdyr's avatar Sviatoslav Smovdyr Committed by Pierre Dureau
Browse files

Issue #3477419 by smovs, just_like_good_vibes, pdureau: New source plugin for attributes

parent 58bb95db
No related branches found
No related tags found
1 merge request!232#3477419 - Added a new source plugin for class attribute.
Pipeline #309438 passed with warnings
......@@ -16,7 +16,7 @@ use Drupal\ui_patterns\PropTypePluginBase;
id: 'attributes',
label: new TranslatableMarkup('Attributes'),
description: new TranslatableMarkup('HTML attributes as a a mapping.'),
default_source: 'attributes',
default_source: 'class_attribute',
schema: [
'type' => 'object',
'patternProperties' => [
......
<?php
declare(strict_types=1);
namespace Drupal\ui_patterns\Plugin\UiPatterns\Source;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\ui_patterns\Attribute\Source;
use Drupal\ui_patterns\SourcePluginPropValue;
/**
* Plugin implementation of the source.
*/
#[Source(
id: 'class_attribute',
label: new TranslatableMarkup('Class attribute'),
description: new TranslatableMarkup('A space-separated list of HTML classes.'),
prop_types: ['attributes']
)]
class ClassAttributeWidget extends SourcePluginPropValue {
/**
* {@inheritdoc}
*/
public function getPropValue(): mixed {
// In UI Patterns Settings, we built the Attribute object here. It is not
// possible anymore because SDC will not validate it against the prop
// type schema.
$value = parent::getPropValue();
return is_string($value) ? $this->convertStringToAttributesMapping($value) : [];
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state): array {
$form = parent::settingsForm($form, $form_state);
$form['value'] = [
'#type' => 'textfield',
'#default_value' => $this->getSetting('value'),
];
$form['value']['#pattern'] = $this->buildRegexPattern();
// To allow form errors to be displayed correctly.
$form['value']['#title'] = '';
$form['value']['#placeholder'] = 'foo bar baz';
$form['value']['#description'] = $this->t("A space-separated list of HTML classes");
$this->addRequired($form['value']);
return $form;
}
/**
* Build regular expression pattern.
*/
protected function buildRegexPattern(): string {
// Each classname cannot start with a hyphen followed by a digit or a digit.
$class_name = "(?!(?:\\d|[-]\\d))[\\S]+";
// Return the pattern for valid CSS class names.
return "^\\s*(" . $class_name . "(\\s+" . $class_name . ")*)?\\s*$";
}
/**
* Convert a string to an attribute mapping.
*/
protected function convertStringToAttributesMapping(string $value): array {
// Set a filtered array or an empty value if the array is empty.
return [
'class' => array_filter(explode(' ', $value), function ($raw_value) {
return !empty($raw_value);
}),
];
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment