contextual.module 8.2 KB

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