5 * Adds contextual links to perform actions related to elements on a page.
8 use Drupal\Component\Serialization\Json;
9 use Drupal\Component\Utility\UrlHelper;
10 use Drupal\Core\Language\LanguageInterface;
11 use Drupal\Core\Routing\RouteMatchInterface;
14 * Implements hook_toolbar().
16 function contextual_toolbar() {
18 $items['contextual'] = [
26 if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
30 $items['contextual'] += [
31 '#type' => 'toolbar_item',
33 '#type' => 'html_tag',
35 '#value' => t('Edit'),
37 'class' => ['toolbar-icon', 'toolbar-icon-edit'],
38 'aria-pressed' => 'false',
41 '#wrapper_attributes' => [
42 'class' => ['hidden', 'contextual-toolbar-tab'],
46 'contextual/drupal.contextual-toolbar',
55 * Implements hook_page_attachments().
57 * Adds the drupal.contextual-links library to the page for any user who has the
58 * 'access contextual links' permission.
60 * @see contextual_preprocess()
62 function contextual_page_attachments(array &$page) {
63 if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
67 $page['#attached']['library'][] = 'contextual/drupal.contextual-links';
71 * Implements hook_help().
73 function contextual_help($route_name, RouteMatchInterface $route_match) {
74 switch ($route_name) {
75 case 'help.page.contextual':
77 $output .= '<h3>' . t('About') . '</h3>';
78 $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>';
79 $output .= '<h3>' . t('Uses') . '</h3>';
81 $output .= '<dt>' . t('Displaying contextual links') . '</dt>';
83 $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:');
87 '#uri' => 'core/misc/icons/bebebe/pencil.svg',
88 '#alt' => t('contextual links button')
90 $sample_picture = \Drupal::service('renderer')->render($sample_picture);
91 $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>';
92 $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>';
94 $output .= t('Once the contextual links button for the area of interest is visible, click the button to display the links.');
102 * Implements hook_preprocess().
104 * @see contextual_pre_render_placeholder()
105 * @see contextual_page_attachments()
106 * @see \Drupal\contextual\ContextualController::render()
108 function contextual_preprocess(&$variables, $hook, $info) {
109 $variables['#cache']['contexts'][] = 'user.permissions';
110 if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
114 // Determine the primary theme function argument.
115 if (!empty($info['variables'])) {
116 $keys = array_keys($info['variables']);
119 elseif (!empty($info['render element'])) {
120 $key = $info['render element'];
122 if (!empty($key) && isset($variables[$key])) {
123 $element = $variables[$key];
126 if (isset($element) && is_array($element) && !empty($element['#contextual_links'])) {
127 // Mark this element as potentially having contextual links attached to it.
128 $variables['attributes']['class'][] = 'contextual-region';
130 // Renders a contextual links placeholder unconditionally, thus not breaking
131 // the render cache. Although the empty placeholder is rendered for all
132 // users, contextual_page_attachments() only adds the asset library for
133 // users with the 'access contextual links' permission, thus preventing
134 // unnecessary HTTP requests for users without that permission.
135 $variables['title_suffix']['contextual_links'] = [
136 '#type' => 'contextual_links_placeholder',
137 '#id' => _contextual_links_to_id($element['#contextual_links']),
143 * Implements hook_contextual_links_view_alter().
145 * @see \Drupal\contextual\Plugin\views\field\ContextualLinks::render()
147 function contextual_contextual_links_view_alter(&$element, $items) {
148 if (isset($element['#contextual_links']['contextual'])) {
149 $encoded_links = $element['#contextual_links']['contextual']['metadata']['contextual-views-field-links'];
150 $element['#links'] = Json::decode(rawurldecode($encoded_links));
155 * Serializes #contextual_links property value array to a string.
158 * - node:node=1:langcode=en
159 * - views_ui_edit:view=frontpage:location=page&view_name=frontpage&view_display_id=page_1&langcode=en
160 * - menu:menu=tools:langcode=en|block:block=bartik.tools:langcode=en
162 * So, expressed in a pattern:
163 * <group>:<route parameters>:<metadata>
165 * The route parameters and options are encoded as query strings.
167 * @param array $contextual_links
168 * The $element['#contextual_links'] value for some render element.
171 * A serialized representation of a #contextual_links property value array for
172 * use in a data- attribute.
174 function _contextual_links_to_id($contextual_links) {
176 $langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId();
177 foreach ($contextual_links as $group => $args) {
178 $route_parameters = UrlHelper::buildQuery($args['route_parameters']);
179 $args += ['metadata' => []];
180 // Add the current URL language to metadata so a different ID will be
181 // computed when URLs vary by language. This allows to store different
182 // language-aware contextual links on the client side.
183 $args['metadata'] += ['langcode' => $langcode];
184 $metadata = UrlHelper::buildQuery($args['metadata']);
185 $ids[] = "{$group}:{$route_parameters}:{$metadata}";
187 return implode('|', $ids);
191 * Unserializes the result of _contextual_links_to_id().
193 * @see _contextual_links_to_id
196 * A serialized representation of a #contextual_links property value array.
199 * The value for a #contextual_links property.
201 function _contextual_id_to_links($id) {
202 $contextual_links = [];
203 $contexts = explode('|', $id);
204 foreach ($contexts as $context) {
205 list($group, $route_parameters_raw, $metadata_raw) = explode(':', $context);
206 parse_str($route_parameters_raw, $route_parameters);
208 parse_str($metadata_raw, $metadata);
209 $contextual_links[$group] = [
210 'route_parameters' => $route_parameters,
211 'metadata' => $metadata,
214 return $contextual_links;