toolbar.module 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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\Render\Element;
  8. use Drupal\Core\Routing\RouteMatchInterface;
  9. use Drupal\Core\Template\Attribute;
  10. use Drupal\Component\Utility\Crypt;
  11. use Drupal\Core\Url;
  12. use Drupal\toolbar\Controller\ToolbarController;
  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' => [[ToolbarController::class, 'preRenderAdministrationTray']],
  181. '#type' => 'container',
  182. '#attributes' => [
  183. 'class' => ['toolbar-menu-administration'],
  184. ],
  185. ],
  186. ],
  187. '#weight' => -15,
  188. ];
  189. $hash_cacheability->applyTo($items['administration']);
  190. return $items;
  191. }
  192. /**
  193. * Renders the toolbar's administration tray.
  194. *
  195. * @param array $element
  196. * A renderable array.
  197. *
  198. * @return array
  199. * The updated renderable array.
  200. *
  201. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  202. * \Drupal\toolbar\Controller\ToolbarController::preRenderAdministrationTray()
  203. * instead.
  204. *
  205. * @see https://www.drupal.org/node/2966725
  206. * @see \Drupal\Core\Render\RendererInterface::render()
  207. */
  208. function toolbar_prerender_toolbar_administration_tray(array $element) {
  209. @trigger_error('toolbar_prerender_toolbar_administration_tray() is deprecated in Drupal 8.8.0 and will be removed before Drupal 9.0.0. Use \Drupal\toolbar\Controller\ToolbarController::preRenderAdministrationTray() instead. See https://www.drupal.org/node/2966725', E_USER_DEPRECATED);
  210. return ToolbarController::preRenderAdministrationTray($element);
  211. }
  212. /**
  213. * Adds toolbar-specific attributes to the menu link tree.
  214. *
  215. * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
  216. * The menu link tree to manipulate.
  217. *
  218. * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
  219. * The manipulated menu link tree.
  220. */
  221. function toolbar_menu_navigation_links(array $tree) {
  222. foreach ($tree as $element) {
  223. if ($element->subtree) {
  224. toolbar_menu_navigation_links($element->subtree);
  225. }
  226. // Make sure we have a path specific ID in place, so we can attach icons
  227. // and behaviors to the menu links.
  228. $link = $element->link;
  229. $url = $link->getUrlObject();
  230. if (!$url->isRouted()) {
  231. // This is an unusual case, so just get a distinct, safe string.
  232. $id = substr(Crypt::hashBase64($url->getUri()), 0, 16);
  233. }
  234. else {
  235. $id = str_replace(['.', '<', '>'], ['-', '', ''], $url->getRouteName());
  236. }
  237. // Get the non-localized title to make the icon class.
  238. $definition = $link->getPluginDefinition();
  239. $element->options['attributes']['id'] = 'toolbar-link-' . $id;
  240. $element->options['attributes']['class'][] = 'toolbar-icon';
  241. $element->options['attributes']['class'][] = 'toolbar-icon-' . strtolower(str_replace(['.', ' ', '_'], ['-', '-', '-'], $definition['id']));
  242. $element->options['attributes']['title'] = $link->getDescription();
  243. }
  244. return $tree;
  245. }
  246. /**
  247. * Implements hook_preprocess_HOOK() for HTML document templates.
  248. */
  249. function toolbar_preprocess_html(&$variables) {
  250. if (!\Drupal::currentUser()->hasPermission('access toolbar')) {
  251. return;
  252. }
  253. $variables['attributes']['class'][] = 'toolbar-tray-open';
  254. $variables['attributes']['class'][] = 'toolbar-horizontal';
  255. $variables['attributes']['class'][] = 'toolbar-fixed';
  256. $variables['attributes']['class'][] = 'toolbar-loading';
  257. }
  258. /**
  259. * Returns the rendered subtree of each top-level toolbar link.
  260. *
  261. * @return array
  262. * An array with the following key-value pairs:
  263. * - 'subtrees': the rendered subtrees
  264. * - 'cacheability: the associated cacheability.
  265. */
  266. function toolbar_get_rendered_subtrees() {
  267. $data = [
  268. '#pre_render' => [[ToolbarController::class, 'preRenderGetRenderedSubtrees']],
  269. '#cache' => [
  270. 'keys' => [
  271. 'toolbar_rendered_subtrees',
  272. ],
  273. ],
  274. '#cache_properties' => ['#subtrees'],
  275. ];
  276. \Drupal::service('renderer')->renderPlain($data);
  277. return [$data['#subtrees'], CacheableMetadata::createFromRenderArray($data)];
  278. }
  279. /**
  280. * #pre_render callback for toolbar_get_rendered_subtrees().
  281. *
  282. * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
  283. * \Drupal\toolbar\Controller\ToolbarController::preRenderGetRenderedSubtrees()
  284. * instead.
  285. *
  286. * @see https://www.drupal.org/node/2966725
  287. */
  288. function _toolbar_do_get_rendered_subtrees(array $data) {
  289. @trigger_error('_toolbar_do_get_rendered_subtrees() is deprecated in Drupal 8.8.0 and will be removed before Drupal 9.0.0. Use Drupal\toolbar\Controller\ToolbarController::preRenderGetRenderedSubtrees() instead. See https://www.drupal.org/node/2966725', E_USER_DEPRECATED);
  290. return ToolbarController::preRenderGetRenderedSubtrees($data);
  291. }
  292. /**
  293. * Returns the hash of the per-user rendered toolbar subtrees.
  294. *
  295. * @return string
  296. * The hash of the admin_menu subtrees.
  297. */
  298. function _toolbar_get_subtrees_hash() {
  299. list($subtrees, $cacheability) = toolbar_get_rendered_subtrees();
  300. $hash = Crypt::hashBase64(serialize($subtrees));
  301. return [$hash, $cacheability];
  302. }