toolbar.module 13 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Administration toolbar for quick access to top level administration items.
 */

8
use Drupal\Core\Cache\CacheableMetadata;
9
use Drupal\Core\Menu\MenuTreeParameters;
10
use Drupal\Core\Render\Element;
11
use Drupal\Core\Routing\RouteMatchInterface;
12
use Drupal\Core\Template\Attribute;
13
use Drupal\Component\Utility\Crypt;
14
use Drupal\Core\Url;
15

16 17 18
/**
 * Implements hook_help().
 */
19
function toolbar_help($route_name, RouteMatchInterface $route_match) {
20 21
  switch ($route_name) {
    case 'help.page.toolbar':
22
      $output = '<h3>' . t('About') . '</h3>';
23
      $output .= '<p>' . t('The Toolbar module provides a toolbar for site administrators, which displays tabs and trays provided by the Toolbar module itself and other modules. For more information, see the <a href=":toolbar_docs">online documentation for the Toolbar module</a>.', [':toolbar_docs' => 'https://www.drupal.org/documentation/modules/toolbar']) . '</p>';
24
      $output .= '<h4>' . t('Terminology') . '</h4>';
25
      $output .= '<dl>';
26 27 28 29
      $output .= '<dt>' . t('Tabs') . '</dt>';
      $output .= '<dd>' . t('Tabs are buttons, displayed in a bar across the top of the screen. Some tabs execute an action (such as starting Edit mode), while other tabs toggle which tray is open.') . '</dd>';
      $output .= '<dt>' . t('Trays') . '</dt>';
      $output .= '<dd>' . t('Trays are usually lists of links, which can be hierarchical like a menu. If a tray has been toggled open, it is displayed either vertically or horizontally below the tab bar, depending on the browser width. Only one tray may be open at a time. If you click another tab, that tray will replace the tray being displayed. In wide browser widths, the user has the ability to toggle from vertical to horizontal, using a link at the bottom or right of the tray. Hierarchical menus only have open/close behavior in vertical mode; if you display a tray containing a hierarchical menu horizontally, only the top-level links will be available.') . '</dd>';
30 31 32 33 34
      $output .= '</dl>';
      return $output;
  }
}

35
/**
36
 * Implements hook_theme().
37 38
 */
function toolbar_theme($existing, $type, $theme, $path) {
39
  $items['toolbar'] = [
40
    'render element' => 'element',
41 42
  ];
  $items['menu__toolbar'] = [
43
    'base hook' => 'menu',
44 45
    'variables' => ['items' => [], 'attributes' => []],
  ];
46

47 48 49
  return $items;
}

50
/**
51
 * Implements hook_page_top().
52
 *
53
 * Add admin toolbar to the top of the page automatically.
54
 */
55
function toolbar_page_top(array &$page_top) {
56
  $page_top['toolbar'] = [
57
    '#type' => 'toolbar',
58
    '#access' => \Drupal::currentUser()->hasPermission('access toolbar'),
59 60 61 62
    '#cache' => [
      'keys' => ['toolbar'],
      'contexts' => ['user.permissions'],
    ],
63
  ];
64 65
}

66
/**
67 68 69
 * Prepares variables for administration toolbar templates.
 *
 * Default template: toolbar.html.twig.
70 71 72 73 74 75
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: An associative array containing the properties and children of
 *     the tray. Properties used: #children, #attributes and #bar.
 */
76 77 78 79 80 81 82 83 84 85
function template_preprocess_toolbar(&$variables) {
  $element = $variables['element'];

  // Prepare the toolbar attributes.
  $variables['attributes'] = $element['#attributes'];
  $variables['toolbar_attributes'] = new Attribute($element['#bar']['#attributes']);
  $variables['toolbar_heading'] = $element['#bar']['#heading'];

  // Prepare the trays and tabs for each toolbar item as well as the remainder
  // variable that will hold any non-tray, non-tab elements.
86 87 88
  $variables['trays'] = [];
  $variables['tabs'] = [];
  $variables['remainder'] = [];
89
  foreach (Element::children($element) as $key) {
90 91 92 93 94
    // Early rendering to collect the wrapper attributes from
    // ToolbarItem elements.
    if (!empty($element[$key])) {
      Drupal::service('renderer')->render($element[$key]);
    }
95 96
    // Add the tray.
    if (isset($element[$key]['tray'])) {
97
      $attributes = [];
98 99 100
      if (!empty($element[$key]['tray']['#wrapper_attributes'])) {
        $attributes = $element[$key]['tray']['#wrapper_attributes'];
      }
101
      $variables['trays'][$key] = [
102
        'links' => $element[$key]['tray'],
103
        'attributes' => new Attribute($attributes),
104
      ];
105 106 107 108 109 110
      if (array_key_exists('#heading', $element[$key]['tray'])) {
        $variables['trays'][$key]['label'] = $element[$key]['tray']['#heading'];
      }
    }

    // Add the tab.
111
    if (isset($element[$key]['tab'])) {
112
      $attributes = [];
113
      // Pass the wrapper attributes along.
114
      if (!empty($element[$key]['#wrapper_attributes'])) {
115 116 117
        $attributes = $element[$key]['#wrapper_attributes'];
      }

118
      $variables['tabs'][$key] = [
119 120
        'link' => $element[$key]['tab'],
        'attributes' => new Attribute($attributes),
121
      ];
122
    }
123 124 125

    // Add other non-tray, non-tab child elements to the remainder variable for
    // later rendering.
126
    foreach (Element::children($element[$key]) as $child_key) {
127
      if (!in_array($child_key, ['tray', 'tab'])) {
128 129
        $variables['remainder'][$key][$child_key] = $element[$key][$child_key];
      }
130 131
    }
  }
132 133 134
}

/**
135
 * Implements hook_toolbar().
136
 */
137 138
function toolbar_toolbar() {
  // The 'Home' tab is a simple link, with no corresponding tray.
139
  $items['home'] = [
140
    '#type' => 'toolbar_item',
141
    'tab' => [
142
      '#type' => 'link',
143
      '#title' => t('Back to site'),
144
      '#url' => Url::fromRoute('<front>'),
145
      '#attributes' => [
146
        'title' => t('Return to site content'),
147
        'class' => ['toolbar-icon', 'toolbar-icon-escape-admin'],
148
        'data-toolbar-escape-admin' => TRUE,
149 150 151
      ],
    ],
    '#wrapper_attributes' => [
152
      'class' => ['home-toolbar-tab'],
153 154 155
    ],
    '#attached' => [
      'library' => [
156
        'toolbar/toolbar.escapeAdmin',
157 158
      ],
    ],
159
    '#weight' => -20,
160
  ];
161

162
  // To conserve bandwidth, we only include the top-level links in the HTML.
163 164 165
  // The subtrees are fetched through a JSONP script that is generated at the
  // toolbar_subtrees route. We provide the JavaScript requesting that JSONP
  // script here with the hash parameter that is needed for that route.
166
  // @see toolbar_subtrees_jsonp()
167
  list($hash, $hash_cacheability) = _toolbar_get_subtrees_hash();
168
  $subtrees_attached['drupalSettings']['toolbar'] = [
169
    'subtreesHash' => $hash,
170
  ];
171

172 173
  // The administration element has a link that is themed to correspond to
  // a toolbar tray. The tray contains the full administrative menu of the site.
174
  $items['administration'] = [
175
    '#type' => 'toolbar_item',
176
    'tab' => [
177
      '#type' => 'link',
178
      '#title' => t('Manage'),
179
      '#url' => Url::fromRoute('system.admin'),
180
      '#attributes' => [
181
        'title' => t('Admin menu'),
182
        'class' => ['toolbar-icon', 'toolbar-icon-menu'],
183 184 185 186 187 188
        // A data attribute that indicates to the client to defer loading of
        // the admin menu subtrees until this tab is activated. Admin menu
        // subtrees will not render to the DOM if this attribute is removed.
        // The value of the attribute is intentionally left blank. Only the
        // presence of the attribute is necessary.
        'data-drupal-subtrees' => '',
189 190 191
      ],
    ],
    'tray' => [
192 193
      '#heading' => t('Administration menu'),
      '#attached' => $subtrees_attached,
194 195
      'toolbar_administration' => [
        '#pre_render' => [
196
          'toolbar_prerender_toolbar_administration_tray',
197
        ],
198
        '#type' => 'container',
199 200 201 202 203
        '#attributes' => [
          'class' => ['toolbar-menu-administration'],
        ],
      ],
    ],
204
    '#weight' => -15,
205
  ];
206
  $hash_cacheability->applyTo($items['administration']);
207 208 209 210

  return $items;
}

211
/**
212
 * Renders the toolbar's administration tray.
213
 *
214 215 216 217 218 219 220
 * @param array $element
 *   A renderable array.
 *
 * @return array
 *   The updated renderable array.
 *
 * @see drupal_render()
221
 */
222
function toolbar_prerender_toolbar_administration_tray(array $element) {
223
  $menu_tree = \Drupal::service('toolbar.menu_tree');
224 225 226
  // Load the administrative menu. The first level is the "Administration" link.
  // In order to load the children of that link, start and end on the second
  // level.
227
  $parameters = new MenuTreeParameters();
228 229 230
  $parameters->setMinDepth(2)->setMaxDepth(2)->onlyEnabledLinks();
  // @todo Make the menu configurable in https://www.drupal.org/node/1869638.
  $tree = $menu_tree->load('admin', $parameters);
231 232 233 234 235
  $manipulators = [
    ['callable' => 'menu.default_tree_manipulators:checkAccess'],
    ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
    ['callable' => 'toolbar_menu_navigation_links'],
  ];
236 237 238
  $tree = $menu_tree->transform($tree, $manipulators);
  $element['administration_menu'] = $menu_tree->build($tree);
  return $element;
239 240 241
}

/**
242
 * Adds toolbar-specific attributes to the menu link tree.
243
 *
244 245
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu link tree to manipulate.
246
 *
247 248
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   The manipulated menu link tree.
249
 */
250 251 252 253
function toolbar_menu_navigation_links(array $tree) {
  foreach ($tree as $element) {
    if ($element->subtree) {
      toolbar_menu_navigation_links($element->subtree);
254
    }
255

256
    // Make sure we have a path specific ID in place, so we can attach icons
257 258 259
    // and behaviors to the menu links.
    $link = $element->link;
    $url = $link->getUrlObject();
260
    if (!$url->isRouted()) {
261
      // This is an unusual case, so just get a distinct, safe string.
262
      $id = substr(Crypt::hashBase64($url->getUri()), 0, 16);
263 264
    }
    else {
265
      $id = str_replace(['.', '<', '>'], ['-', '', ''], $url->getRouteName());
266 267 268 269 270 271 272
    }

    // Get the non-localized title to make the icon class.
    $definition = $link->getPluginDefinition();

    $element->options['attributes']['id'] = 'toolbar-link-' . $id;
    $element->options['attributes']['class'][] = 'toolbar-icon';
273
    $element->options['attributes']['class'][] = 'toolbar-icon-' . strtolower(str_replace(['.', ' ', '_'], ['-', '-', '-'], $definition['id']));
274
    $element->options['attributes']['title'] = $link->getDescription();
275
  }
276
  return $tree;
277
}
278

279 280 281 282 283 284 285 286 287 288 289 290
/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 */
function toolbar_preprocess_html(&$variables) {
  if (!\Drupal::currentUser()->hasPermission('access toolbar')) {
    return;
  }

  $variables['attributes'] = new Attribute($variables['attributes']);
  $variables['attributes']->addClass(['toolbar-tray-open', 'toolbar-horizontal', 'toolbar-fixed', 'toolbar-loading']);
}

291 292
/**
 * Returns the rendered subtree of each top-level toolbar link.
293 294 295 296 297
 *
 * @return array
 *   An array with the following key-value pairs:
 *   - 'subtrees': the rendered subtrees
 *   - 'cacheability: the associated cacheability.
298 299
 */
function toolbar_get_rendered_subtrees() {
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
  $data = [
    '#pre_render' => ['_toolbar_do_get_rendered_subtrees'],
    '#cache' => [
      'keys' => [
        'toolbar_rendered_subtrees',
      ],
    ],
    '#cache_properties' => ['#subtrees'],
  ];
  \Drupal::service('renderer')->renderPlain($data);
  return [$data['#subtrees'], CacheableMetadata::createFromRenderArray($data)];
}

/**
 * #pre_render callback for toolbar_get_rendered_subtrees().
 */
function _toolbar_do_get_rendered_subtrees(array $data) {
317
  $menu_tree = \Drupal::service('toolbar.menu_tree');
318 319 320
  // Load the administration menu. The first level is the "Administration" link.
  // In order to load the children of that link and the subsequent two levels,
  // start at the second level and end at the fourth.
321
  $parameters = new MenuTreeParameters();
322 323 324
  $parameters->setMinDepth(2)->setMaxDepth(4)->onlyEnabledLinks();
  // @todo Make the menu configurable in https://www.drupal.org/node/1869638.
  $tree = $menu_tree->load('admin', $parameters);
325 326 327 328 329
  $manipulators = [
    ['callable' => 'menu.default_tree_manipulators:checkAccess'],
    ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
    ['callable' => 'toolbar_menu_navigation_links'],
  ];
330
  $tree = $menu_tree->transform($tree, $manipulators);
331
  $subtrees = [];
332 333
  // Calculated the combined cacheability of all subtrees.
  $cacheability = new CacheableMetadata();
334 335 336 337 338
  foreach ($tree as $element) {
    /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
    $link = $element->link;
    if ($element->subtree) {
      $subtree = $menu_tree->build($element->subtree);
339
      $output = \Drupal::service('renderer')->renderPlain($subtree);
340
      $cacheability = $cacheability->merge(CacheableMetadata::createFromRenderArray($subtree));
341
    }
342 343 344 345 346
    else {
      $output = '';
    }
    // Many routes have dots as route name, while some special ones like <front>
    // have <> characters in them.
347
    $url = $link->getUrlObject();
348
    $id = str_replace(['.', '<', '>'], ['-', '', ''], $url->isRouted() ? $url->getRouteName() : $url->getUri());
349 350

    $subtrees[$id] = $output;
351
  }
352 353 354 355 356 357

  // Store the subtrees, along with the cacheability metadata.
  $cacheability->applyTo($data);
  $data['#subtrees'] = $subtrees;

  return $data;
358 359
}

360 361
/**
 * Returns the hash of the per-user rendered toolbar subtrees.
362 363 364
 *
 * @return string
 *   The hash of the admin_menu subtrees.
365
 */
366 367 368 369
function _toolbar_get_subtrees_hash() {
  list($subtrees, $cacheability) = toolbar_get_rendered_subtrees();
  $hash = Crypt::hashBase64(serialize($subtrees));
  return [$hash, $cacheability];
370
}