toolbar.module 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php
  2. /**
  3. * @file
  4. * Administration toolbar for quick access to top level administration items.
  5. */
  6. use Drupal\Core\Cache\CacheableMetadata;
  7. use Drupal\Core\Menu\MenuTreeParameters;
  8. use Drupal\Core\Render\Element;
  9. use Drupal\Core\Routing\RouteMatchInterface;
  10. use Drupal\Core\Template\Attribute;
  11. use Drupal\Component\Utility\Crypt;
  12. use Drupal\Core\Url;
  13. /**
  14. * Implements hook_help().
  15. */
  16. function toolbar_help($route_name, RouteMatchInterface $route_match) {
  17. switch ($route_name) {
  18. case 'help.page.toolbar':
  19. $output = '<h3>' . t('About') . '</h3>';
  20. $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>';
  21. $output .= '<h4>' . t('Terminology') . '</h4>';
  22. $output .= '<dl>';
  23. $output .= '<dt>' . t('Tabs') . '</dt>';
  24. $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>';
  25. $output .= '<dt>' . t('Trays') . '</dt>';
  26. $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>';
  27. $output .= '</dl>';
  28. return $output;
  29. }
  30. }
  31. /**
  32. * Implements hook_theme().
  33. */
  34. function toolbar_theme($existing, $type, $theme, $path) {
  35. $items['toolbar'] = [
  36. 'render element' => 'element',
  37. ];
  38. $items['menu__toolbar'] = [
  39. 'base hook' => 'menu',
  40. 'variables' => ['items' => [], 'attributes' => []],
  41. ];
  42. return $items;
  43. }
  44. /**
  45. * Implements hook_page_top().
  46. *
  47. * Add admin toolbar to the top of the page automatically.
  48. */
  49. function toolbar_page_top(array &$page_top) {
  50. $page_top['toolbar'] = [
  51. '#type' => 'toolbar',
  52. '#access' => \Drupal::currentUser()->hasPermission('access toolbar'),
  53. '#cache' => [
  54. 'keys' => ['toolbar'],
  55. 'contexts' => ['user.permissions'],
  56. ],
  57. ];
  58. }
  59. /**
  60. * Prepares variables for administration toolbar templates.
  61. *
  62. * Default template: toolbar.html.twig.
  63. *
  64. * @param array $variables
  65. * An associative array containing:
  66. * - element: An associative array containing the properties and children of
  67. * the tray. Properties used: #children, #attributes and #bar.
  68. */
  69. function template_preprocess_toolbar(&$variables) {
  70. $element = $variables['element'];
  71. // Prepare the toolbar attributes.
  72. $variables['attributes'] = $element['#attributes'];
  73. $variables['toolbar_attributes'] = new Attribute($element['#bar']['#attributes']);
  74. $variables['toolbar_heading'] = $element['#bar']['#heading'];
  75. // Prepare the trays and tabs for each toolbar item as well as the remainder
  76. // variable that will hold any non-tray, non-tab elements.
  77. $variables['trays'] = [];
  78. $variables['tabs'] = [];
  79. $variables['remainder'] = [];
  80. foreach (Element::children($element) as $key) {
  81. // Early rendering to collect the wrapper attributes from
  82. // ToolbarItem elements.
  83. if (!empty($element[$key])) {
  84. Drupal::service('renderer')->render($element[$key]);
  85. }
  86. // Add the tray.
  87. if (isset($element[$key]['tray'])) {
  88. $attributes = [];
  89. if (!empty($element[$key]['tray']['#wrapper_attributes'])) {
  90. $attributes = $element[$key]['tray']['#wrapper_attributes'];
  91. }
  92. $variables['trays'][$key] = [
  93. 'links' => $element[$key]['tray'],
  94. 'attributes' => new Attribute($attributes),
  95. ];
  96. if (array_key_exists('#heading', $element[$key]['tray'])) {
  97. $variables['trays'][$key]['label'] = $element[$key]['tray']['#heading'];
  98. }
  99. }
  100. // Add the tab.
  101. if (isset($element[$key]['tab'])) {
  102. $attributes = [];
  103. // Pass the wrapper attributes along.
  104. if (!empty($element[$key]['#wrapper_attributes'])) {
  105. $attributes = $element[$key]['#wrapper_attributes'];
  106. }
  107. $variables['tabs'][$key] = [
  108. 'link' => $element[$key]['tab'],
  109. 'attributes' => new Attribute($attributes),
  110. ];
  111. }
  112. // Add other non-tray, non-tab child elements to the remainder variable for
  113. // later rendering.
  114. foreach (Element::children($element[$key]) as $child_key) {
  115. if (!in_array($child_key, ['tray', 'tab'])) {
  116. $variables['remainder'][$key][$child_key] = $element[$key][$child_key];
  117. }
  118. }
  119. }
  120. }
  121. /**
  122. * Implements hook_toolbar().
  123. */
  124. function toolbar_toolbar() {
  125. // The 'Home' tab is a simple link, with no corresponding tray.
  126. $items['home'] = [
  127. '#type' => 'toolbar_item',
  128. 'tab' => [
  129. '#type' => 'link',
  130. '#title' => t('Back to site'),
  131. '#url' => Url::fromRoute('<front>'),
  132. '#attributes' => [
  133. 'title' => t('Return to site content'),
  134. 'class' => ['toolbar-icon', 'toolbar-icon-escape-admin'],
  135. 'data-toolbar-escape-admin' => TRUE,
  136. ],
  137. ],
  138. '#wrapper_attributes' => [
  139. 'class' => ['home-toolbar-tab'],
  140. ],
  141. '#attached' => [
  142. 'library' => [
  143. 'toolbar/toolbar.escapeAdmin',
  144. ],
  145. ],
  146. '#weight' => -20,
  147. ];
  148. // To conserve bandwidth, we only include the top-level links in the HTML.
  149. // The subtrees are fetched through a JSONP script that is generated at the
  150. // toolbar_subtrees route. We provide the JavaScript requesting that JSONP
  151. // script here with the hash parameter that is needed for that route.
  152. // @see toolbar_subtrees_jsonp()
  153. list($hash, $hash_cacheability) = _toolbar_get_subtrees_hash();
  154. $subtrees_attached['drupalSettings']['toolbar'] = [
  155. 'subtreesHash' => $hash,
  156. ];
  157. // The administration element has a link that is themed to correspond to
  158. // a toolbar tray. The tray contains the full administrative menu of the site.
  159. $items['administration'] = [
  160. '#type' => 'toolbar_item',
  161. 'tab' => [
  162. '#type' => 'link',
  163. '#title' => t('Manage'),
  164. '#url' => Url::fromRoute('system.admin'),
  165. '#attributes' => [
  166. 'title' => t('Admin menu'),
  167. 'class' => ['toolbar-icon', 'toolbar-icon-menu'],
  168. // A data attribute that indicates to the client to defer loading of
  169. // the admin menu subtrees until this tab is activated. Admin menu
  170. // subtrees will not render to the DOM if this attribute is removed.
  171. // The value of the attribute is intentionally left blank. Only the
  172. // presence of the attribute is necessary.
  173. 'data-drupal-subtrees' => '',
  174. ],
  175. ],
  176. 'tray' => [
  177. '#heading' => t('Administration menu'),
  178. '#attached' => $subtrees_attached,
  179. 'toolbar_administration' => [
  180. '#pre_render' => [
  181. 'toolbar_prerender_toolbar_administration_tray',
  182. ],
  183. '#type' => 'container',
  184. '#attributes' => [
  185. 'class' => ['toolbar-menu-administration'],
  186. ],
  187. ],
  188. ],
  189. '#weight' => -15,
  190. ];
  191. $hash_cacheability->applyTo($items['administration']);
  192. return $items;
  193. }
  194. /**
  195. * Renders the toolbar's administration tray.
  196. *
  197. * @param array $element
  198. * A renderable array.
  199. *
  200. * @return array
  201. * The updated renderable array.
  202. *
  203. * @see \Drupal\Core\Render\RendererInterface::render()
  204. */
  205. function toolbar_prerender_toolbar_administration_tray(array $element) {
  206. $menu_tree = \Drupal::service('toolbar.menu_tree');
  207. // Load the administrative menu. The first level is the "Administration" link.
  208. // In order to load the children of that link, start and end on the second
  209. // level.
  210. $parameters = new MenuTreeParameters();
  211. $parameters->setMinDepth(2)->setMaxDepth(2)->onlyEnabledLinks();
  212. // @todo Make the menu configurable in https://www.drupal.org/node/1869638.
  213. $tree = $menu_tree->load('admin', $parameters);
  214. $manipulators = [
  215. ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  216. ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
  217. ['callable' => 'toolbar_menu_navigation_links'],
  218. ];
  219. $tree = $menu_tree->transform($tree, $manipulators);
  220. $element['administration_menu'] = $menu_tree->build($tree);
  221. return $element;
  222. }
  223. /**
  224. * Adds toolbar-specific attributes to the menu link tree.
  225. *
  226. * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
  227. * The menu link tree to manipulate.
  228. *
  229. * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
  230. * The manipulated menu link tree.
  231. */
  232. function toolbar_menu_navigation_links(array $tree) {
  233. foreach ($tree as $element) {
  234. if ($element->subtree) {
  235. toolbar_menu_navigation_links($element->subtree);
  236. }
  237. // Make sure we have a path specific ID in place, so we can attach icons
  238. // and behaviors to the menu links.
  239. $link = $element->link;
  240. $url = $link->getUrlObject();
  241. if (!$url->isRouted()) {
  242. // This is an unusual case, so just get a distinct, safe string.
  243. $id = substr(Crypt::hashBase64($url->getUri()), 0, 16);
  244. }
  245. else {
  246. $id = str_replace(['.', '<', '>'], ['-', '', ''], $url->getRouteName());
  247. }
  248. // Get the non-localized title to make the icon class.
  249. $definition = $link->getPluginDefinition();
  250. $element->options['attributes']['id'] = 'toolbar-link-' . $id;
  251. $element->options['attributes']['class'][] = 'toolbar-icon';
  252. $element->options['attributes']['class'][] = 'toolbar-icon-' . strtolower(str_replace(['.', ' ', '_'], ['-', '-', '-'], $definition['id']));
  253. $element->options['attributes']['title'] = $link->getDescription();
  254. }
  255. return $tree;
  256. }
  257. /**
  258. * Implements hook_preprocess_HOOK() for HTML document templates.
  259. */
  260. function toolbar_preprocess_html(&$variables) {
  261. if (!\Drupal::currentUser()->hasPermission('access toolbar')) {
  262. return;
  263. }
  264. $variables['attributes'] = new Attribute($variables['attributes']);
  265. $variables['attributes']->addClass(['toolbar-tray-open', 'toolbar-horizontal', 'toolbar-fixed', 'toolbar-loading']);
  266. }
  267. /**
  268. * Returns the rendered subtree of each top-level toolbar link.
  269. *
  270. * @return array
  271. * An array with the following key-value pairs:
  272. * - 'subtrees': the rendered subtrees
  273. * - 'cacheability: the associated cacheability.
  274. */
  275. function toolbar_get_rendered_subtrees() {
  276. $data = [
  277. '#pre_render' => ['_toolbar_do_get_rendered_subtrees'],
  278. '#cache' => [
  279. 'keys' => [
  280. 'toolbar_rendered_subtrees',
  281. ],
  282. ],
  283. '#cache_properties' => ['#subtrees'],
  284. ];
  285. \Drupal::service('renderer')->renderPlain($data);
  286. return [$data['#subtrees'], CacheableMetadata::createFromRenderArray($data)];
  287. }
  288. /**
  289. * #pre_render callback for toolbar_get_rendered_subtrees().
  290. */
  291. function _toolbar_do_get_rendered_subtrees(array $data) {
  292. $menu_tree = \Drupal::service('toolbar.menu_tree');
  293. // Load the administration menu. The first level is the "Administration" link.
  294. // In order to load the children of that link and the subsequent two levels,
  295. // start at the second level and end at the fourth.
  296. $parameters = new MenuTreeParameters();
  297. $parameters->setMinDepth(2)->setMaxDepth(4)->onlyEnabledLinks();
  298. // @todo Make the menu configurable in https://www.drupal.org/node/1869638.
  299. $tree = $menu_tree->load('admin', $parameters);
  300. $manipulators = [
  301. ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  302. ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
  303. ['callable' => 'toolbar_menu_navigation_links'],
  304. ];
  305. $tree = $menu_tree->transform($tree, $manipulators);
  306. $subtrees = [];
  307. // Calculated the combined cacheability of all subtrees.
  308. $cacheability = new CacheableMetadata();
  309. foreach ($tree as $element) {
  310. /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
  311. $link = $element->link;
  312. if ($element->subtree) {
  313. $subtree = $menu_tree->build($element->subtree);
  314. $output = \Drupal::service('renderer')->renderPlain($subtree);
  315. $cacheability = $cacheability->merge(CacheableMetadata::createFromRenderArray($subtree));
  316. }
  317. else {
  318. $output = '';
  319. }
  320. // Many routes have dots as route name, while some special ones like <front>
  321. // have <> characters in them.
  322. $url = $link->getUrlObject();
  323. $id = str_replace(['.', '<', '>'], ['-', '', ''], $url->isRouted() ? $url->getRouteName() : $url->getUri());
  324. $subtrees[$id] = $output;
  325. }
  326. // Store the subtrees, along with the cacheability metadata.
  327. $cacheability->applyTo($data);
  328. $data['#subtrees'] = $subtrees;
  329. return $data;
  330. }
  331. /**
  332. * Returns the hash of the per-user rendered toolbar subtrees.
  333. *
  334. * @return string
  335. * The hash of the admin_menu subtrees.
  336. */
  337. function _toolbar_get_subtrees_hash() {
  338. list($subtrees, $cacheability) = toolbar_get_rendered_subtrees();
  339. $hash = Crypt::hashBase64(serialize($subtrees));
  340. return [$hash, $cacheability];
  341. }