contextual.module 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. <?php
  2. /**
  3. * @file
  4. * Adds contextual links to perform actions related to elements on a page.
  5. */
  6. use Drupal\Component\Serialization\Json;
  7. use Drupal\Component\Utility\UrlHelper;
  8. use Drupal\Core\Language\LanguageInterface;
  9. use Drupal\Core\Routing\RouteMatchInterface;
  10. /**
  11. * Implements hook_toolbar().
  12. */
  13. function contextual_toolbar() {
  14. $items = [];
  15. $items['contextual'] = [
  16. '#cache' => [
  17. 'contexts' => [
  18. 'user.permissions',
  19. ],
  20. ],
  21. ];
  22. if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
  23. return $items;
  24. }
  25. $items['contextual'] += [
  26. '#type' => 'toolbar_item',
  27. 'tab' => [
  28. '#type' => 'html_tag',
  29. '#tag' => 'button',
  30. '#value' => t('Edit'),
  31. '#attributes' => [
  32. 'class' => ['toolbar-icon', 'toolbar-icon-edit'],
  33. 'aria-pressed' => 'false',
  34. 'type' => 'button',
  35. ],
  36. ],
  37. '#wrapper_attributes' => [
  38. 'class' => ['hidden', 'contextual-toolbar-tab'],
  39. ],
  40. '#attached' => [
  41. 'library' => [
  42. 'contextual/drupal.contextual-toolbar',
  43. ],
  44. ],
  45. ];
  46. return $items;
  47. }
  48. /**
  49. * Implements hook_page_attachments().
  50. *
  51. * Adds the drupal.contextual-links library to the page for any user who has the
  52. * 'access contextual links' permission.
  53. *
  54. * @see contextual_preprocess()
  55. */
  56. function contextual_page_attachments(array &$page) {
  57. if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
  58. return;
  59. }
  60. $page['#attached']['library'][] = 'contextual/drupal.contextual-links';
  61. }
  62. /**
  63. * Implements hook_help().
  64. */
  65. function contextual_help($route_name, RouteMatchInterface $route_match) {
  66. switch ($route_name) {
  67. case 'help.page.contextual':
  68. $output = '';
  69. $output .= '<h3>' . t('About') . '</h3>';
  70. $output .= '<p>' . t('The Contextual links module gives users with the <em>Use contextual links</em> permission quick access to tasks associated with certain areas of pages on your site. For example, a menu displayed as a block has links to edit the menu and configure the block. For more information, see the <a href=":contextual">online documentation for the Contextual Links module</a>.', [':contextual' => 'https://www.drupal.org/documentation/modules/contextual']) . '</p>';
  71. $output .= '<h3>' . t('Uses') . '</h3>';
  72. $output .= '<dl>';
  73. $output .= '<dt>' . t('Displaying contextual links') . '</dt>';
  74. $output .= '<dd>';
  75. $output .= t('Contextual links for an area on a page are displayed using a contextual links button. There are two ways to make the contextual links button visible:');
  76. $output .= '<ol>';
  77. $sample_picture = [
  78. '#theme' => 'image',
  79. '#uri' => 'core/misc/icons/bebebe/pencil.svg',
  80. '#alt' => t('contextual links button'),
  81. ];
  82. $sample_picture = \Drupal::service('renderer')->render($sample_picture);
  83. $output .= '<li>' . t('Hovering over the area of interest will temporarily make the contextual links button visible (which looks like a pencil in most themes, and is normally displayed in the upper right corner of the area). The icon typically looks like this: @picture', ['@picture' => $sample_picture]) . '</li>';
  84. $output .= '<li>' . t('If you have the <a href=":toolbar">Toolbar module</a> enabled, clicking the contextual links button in the toolbar (which looks like a pencil) will make all contextual links buttons on the page visible. Clicking this button again will toggle them to invisible.', [':toolbar' => (\Drupal::moduleHandler()->moduleExists('toolbar')) ? \Drupal::url('help.page', ['name' => 'toolbar']) : '#']) . '</li>';
  85. $output .= '</ol>';
  86. $output .= t('Once the contextual links button for the area of interest is visible, click the button to display the links.');
  87. $output .= '</dd>';
  88. $output .= '</dl>';
  89. return $output;
  90. }
  91. }
  92. /**
  93. * Implements hook_preprocess().
  94. *
  95. * @see contextual_pre_render_placeholder()
  96. * @see contextual_page_attachments()
  97. * @see \Drupal\contextual\ContextualController::render()
  98. */
  99. function contextual_preprocess(&$variables, $hook, $info) {
  100. $variables['#cache']['contexts'][] = 'user.permissions';
  101. if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
  102. return;
  103. }
  104. // Determine the primary theme function argument.
  105. if (!empty($info['variables'])) {
  106. $keys = array_keys($info['variables']);
  107. $key = $keys[0];
  108. }
  109. elseif (!empty($info['render element'])) {
  110. $key = $info['render element'];
  111. }
  112. if (!empty($key) && isset($variables[$key])) {
  113. $element = $variables[$key];
  114. }
  115. if (isset($element) && is_array($element) && !empty($element['#contextual_links'])) {
  116. // Mark this element as potentially having contextual links attached to it.
  117. $variables['attributes']['class'][] = 'contextual-region';
  118. // Renders a contextual links placeholder unconditionally, thus not breaking
  119. // the render cache. Although the empty placeholder is rendered for all
  120. // users, contextual_page_attachments() only adds the asset library for
  121. // users with the 'access contextual links' permission, thus preventing
  122. // unnecessary HTTP requests for users without that permission.
  123. $variables['title_suffix']['contextual_links'] = [
  124. '#type' => 'contextual_links_placeholder',
  125. '#id' => _contextual_links_to_id($element['#contextual_links']),
  126. ];
  127. }
  128. }
  129. /**
  130. * Implements hook_contextual_links_view_alter().
  131. *
  132. * @see \Drupal\contextual\Plugin\views\field\ContextualLinks::render()
  133. */
  134. function contextual_contextual_links_view_alter(&$element, $items) {
  135. if (isset($element['#contextual_links']['contextual'])) {
  136. $encoded_links = $element['#contextual_links']['contextual']['metadata']['contextual-views-field-links'];
  137. $element['#links'] = Json::decode(rawurldecode($encoded_links));
  138. }
  139. }
  140. /**
  141. * Serializes #contextual_links property value array to a string.
  142. *
  143. * Examples:
  144. * - node:node=1:langcode=en
  145. * - views_ui_edit:view=frontpage:location=page&view_name=frontpage&view_display_id=page_1&langcode=en
  146. * - menu:menu=tools:langcode=en|block:block=bartik.tools:langcode=en
  147. *
  148. * So, expressed in a pattern:
  149. * <group>:<route parameters>:<metadata>
  150. *
  151. * The route parameters and options are encoded as query strings.
  152. *
  153. * @param array $contextual_links
  154. * The $element['#contextual_links'] value for some render element.
  155. *
  156. * @return string
  157. * A serialized representation of a #contextual_links property value array for
  158. * use in a data- attribute.
  159. */
  160. function _contextual_links_to_id($contextual_links) {
  161. $ids = [];
  162. $langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId();
  163. foreach ($contextual_links as $group => $args) {
  164. $route_parameters = UrlHelper::buildQuery($args['route_parameters']);
  165. $args += ['metadata' => []];
  166. // Add the current URL language to metadata so a different ID will be
  167. // computed when URLs vary by language. This allows to store different
  168. // language-aware contextual links on the client side.
  169. $args['metadata'] += ['langcode' => $langcode];
  170. $metadata = UrlHelper::buildQuery($args['metadata']);
  171. $ids[] = "{$group}:{$route_parameters}:{$metadata}";
  172. }
  173. return implode('|', $ids);
  174. }
  175. /**
  176. * Unserializes the result of _contextual_links_to_id().
  177. *
  178. * Note that $id is user input. Before calling this method the ID should be
  179. * checked against the token stored in the 'data-contextual-token' attribute
  180. * which is passed via the 'tokens' request parameter to
  181. * \Drupal\contextual\ContextualController::render().
  182. *
  183. * @param string $id
  184. * A serialized representation of a #contextual_links property value array.
  185. *
  186. * @return array
  187. * The value for a #contextual_links property.
  188. *
  189. * @see _contextual_links_to_id()
  190. * @see \Drupal\contextual\ContextualController::render()
  191. */
  192. function _contextual_id_to_links($id) {
  193. $contextual_links = [];
  194. $contexts = explode('|', $id);
  195. foreach ($contexts as $context) {
  196. list($group, $route_parameters_raw, $metadata_raw) = explode(':', $context);
  197. parse_str($route_parameters_raw, $route_parameters);
  198. $metadata = [];
  199. parse_str($metadata_raw, $metadata);
  200. $contextual_links[$group] = [
  201. 'route_parameters' => $route_parameters,
  202. 'metadata' => $metadata,
  203. ];
  204. }
  205. return $contextual_links;
  206. }