View source
<?php
namespace Drupal\bootstrap\Plugin\Preprocess;
use Drupal\bootstrap\Annotation\BootstrapPreprocess;
use Drupal\bootstrap\Utility\Element;
use Drupal\bootstrap\Utility\Unicode;
use Drupal\bootstrap\Utility\Variables;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Url;
class BootstrapDropdown extends PreprocessBase implements PreprocessInterface {
protected function preprocessVariables(Variables $variables) {
$this
->preprocessLinks($variables);
$toggle = Element::create($variables->toggle);
$toggle
->setProperty('split', $variables->split);
$variables->items = [
'#theme' => 'item_list__dropdown',
'#items' => $variables->items,
'#context' => [
'alignment' => $variables->alignment,
],
];
$this
->preprocessAttributes();
}
protected function preprocessLinks(Variables $variables) {
if (Unicode::strpos($variables->theme_hook_original, 'links__dropbutton') !== FALSE && !empty($variables->links)) {
$operations = !!Unicode::strpos($variables->theme_hook_original, 'operations');
foreach ($variables->links as &$element) {
if (isset($element['title']) && $element['url']) {
if (!empty($element['query'])) {
$url_query = $element['url']
->getOption('query') ?: [];
$element['url']
->setOption('query', NestedArray::mergeDeep($url_query, $element['query']));
}
$element = [
'#type' => 'link',
'#title' => $element['title'],
'#url' => $element['url'],
];
}
}
$items = Element::createStandalone();
$primary_action = NULL;
$links = Element::create($variables->links);
$i = -1;
foreach ($links
->children(TRUE) as $key => $child) {
$i++;
if ($i === 0) {
$child
->getProperty('id', $child
->getAttribute('id', Html::getUniqueId('dropdown-item')));
$primary_action = $child
->addClass('hidden');
}
if ($child
->isType('link')) {
$items->{$key}->link = $child
->getArrayCopy();
}
else {
$items->{$key}->element = $child
->addClass('hidden')
->getArrayCopy();
$id = $child
->getProperty('id', $child
->getAttribute('id', Html::getUniqueId('dropdown-item')));
$items->{$key}->link = Element::createStandalone([
'#type' => 'link',
'#title' => $child
->getProperty('value', $child
->getProperty('title', $child
->getProperty('text'))),
'#url' => Url::fromUserInput('#'),
'#attributes' => [
'data-dropdown-target' => "#{$id}",
],
]);
if ($i === 0) {
$items->{$key}->link
->addClass('hidden');
}
}
}
$toggle = Element::createStandalone([
'#type' => 'button',
'#attributes' => $primary_action
->getAttributes()
->getArrayCopy(),
'#value' => $primary_action
->getProperty('value', $primary_action
->getProperty('title', $primary_action
->getProperty('text'))),
]);
$toggle
->removeClass('hidden')
->removeAttribute('id')
->setAttribute('data-dropdown-target', '#' . $primary_action
->getAttribute('id'));
if ($operations) {
$toggle
->setButtonSize('btn-xs', FALSE);
}
$variables->toggle = $toggle
->getArrayCopy();
$variables->split = count($items) > 1;
$variables->items = $items
->getArrayCopy();
unset($variables->links);
}
}
}