contextual.module 11.9 KB
Newer Older
1
2
3
4
5
6
7
<?php

/**
 * @file
 * Adds contextual links to perform actions related to elements on a page.
 */

8
9
10
use Drupal\Component\Utility\Url;
use Drupal\Core\Template\Attribute;

11
12
13
14
/**
 * Implements hook_toolbar().
 */
function contextual_toolbar() {
15

16
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
17
18
19
20
    return;
  }

  $tab['contextual'] = array(
21
    '#type' => 'toolbar_item',
22
23
24
25
26
    'tab' => array(
      '#type' => 'html_tag',
      '#tag' => 'button',
      '#value' => t('Edit'),
      '#attributes' => array(
27
        'class' => array('toolbar-icon', 'toolbar-icon-edit'),
28
29
30
31
32
        'role' => 'button',
        'aria-pressed' => 'false',
      ),
    ),
    '#wrapper_attributes' => array(
33
      'class' => array('hidden', 'contextual-toolbar-tab'),
34
35
36
37
38
39
40
41
42
43
44
    ),
    '#attached' => array(
      'library' => array(
        array('contextual', 'drupal.contextual-toolbar'),
      ),
    ),
  );

  return $tab;
}

45
46
47
48
49
50
51
52
53
/**
 * Implements hook_page_build().
 *
 * Adds the drupal.contextual-links library to the page for any user who has the
 * 'access contextual links' permission.
 *
 * @see contextual_preprocess()
 */
function contextual_page_build(&$page) {
54

55
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
56
57
58
59
60
61
    return;
  }

  $page['#attached']['library'][] = array('contextual', 'drupal.contextual-links');
}

62
63
64
65
66
67
68
69
/**
 * Implements hook_help().
 */
function contextual_help($path, $arg) {
  switch ($path) {
    case 'admin/help#contextual':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
70
      $output .= '<p>' . t('The Contextual Links module displays links related to regions of pages on your site to users with <em>access contextual links</em> permission. For more information, see the online handbook entry for <a href="@contextual">Contextual Links module</a>.', array('@contextual' => 'http://drupal.org/documentation/modules/contextual')) . '</p>';
71
72
73
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Displaying contextual links') . '</dt>';
74
      $output .= '<dd>' . t('Contextual links are supplied by modules, to give you quick access to tasks associated with regions of pages on your site. For instance, if you have a custom menu block displayed in a sidebar of your site, the Blocks and Menus modules will supply links to configure the block and edit the menu. The Contextual Links module collects these links into a list for display by your theme, and also adds JavaScript code to the page to hide the links initially, and display them when your mouse hovers over the block.') . '</dd>';
75
76
77
78
79
      $output .= '</dl>';
      return $output;
  }
}

80
81
82
83
84
85
86
87
88
89
90
91
92
/**
 * Implements hook_permission().
 */
function contextual_permission() {
  return array(
    'access contextual links' => array(
      'title' => t('Use contextual links'),
      'description' => t('Use contextual links to perform actions related to elements on a page.'),
    ),
  );
}

/**
93
 * Implements hook_library_info().
94
 */
95
function contextual_library_info() {
96
  $path = drupal_get_path('module', 'contextual');
97
98
99
100
101
102
  // Add the JavaScript, with a group and weight such that it will run
  // before core/modules/contextual/js/contextual.toolbar.js.
  $options = array(
    'group' => JS_LIBRARY,
    'weight' => -2,
  );
103
  $libraries['drupal.contextual-links'] = array(
104
    'title' => 'Contextual Links',
105
    'website' => 'http://drupal.org/node/473268',
106
    'version' => \Drupal::VERSION,
107
    'js' => array(
108
109
110
111
112
113
114
115
116
      // Core.
      $path . '/js/contextual.js' => $options,
      // Models.
      $path . '/js/models/StateModel.js' => $options,
      // Views.
      $path . '/js/views/AuralView.js' => $options,
      $path . '/js/views/KeyboardView.js' => $options,
      $path . '/js/views/RegionView.js' => $options,
      $path . '/js/views/VisualView.js' => $options,
117
118
    ),
    'css' => array(
119
120
      $path . '/css/contextual.module.css' => array(),
      $path . '/css/contextual.theme.css' => array(),
121
      $path . '/css/contextual.icons.css' => array(),
122
    ),
123
124
125
    'dependencies' => array(
      array('system', 'jquery'),
      array('system', 'drupal'),
126
127
128
      array('system', 'drupalSettings'),
      array('system', 'backbone'),
      array('system', 'modernizr'),
129
130
      array('system', 'jquery.once'),
    ),
131
  );
132
133
  $libraries['drupal.contextual-toolbar'] = array(
    'title' => 'Contextual Links Toolbar Tab',
134
    'version' => \Drupal::VERSION,
135
    'js' => array(
136
      $path . '/js/contextual.toolbar.js' => array('group' => JS_LIBRARY),
137
138
    ),
    'css' => array(
139
      $path . '/css/contextual.toolbar.css' => array(),
140
141
142
    ),
    'dependencies' => array(
      array('system', 'jquery'),
143
      array('system', 'drupal'),
144
      array('system', 'backbone'),
145
      array('system', 'jquery.once'),
146
      array('system', 'drupal.tabbingmanager'),
147
      array('system', 'drupal.announce'),
148
149
    ),
  );
150

151
152
153
  return $libraries;
}

154
155
156
157
/**
 * Implements hook_element_info().
 */
function contextual_element_info() {
158
159
160
161
  $types['contextual_links_placeholder'] = array(
    '#pre_render' => array('contextual_pre_render_placeholder'),
    '#id' => NULL,
  );
162
163
164
165
  $types['contextual_links'] = array(
    '#pre_render' => array('contextual_pre_render_links'),
    '#theme' => 'links__contextual',
    '#links' => array(),
166
    '#attributes' => array('class' => array('contextual-links')),
167
168
    '#attached' => array(
      'library' => array(
169
        array('contextual', 'drupal.contextual-links'),
170
171
172
173
174
175
      ),
    ),
  );
  return $types;
}

176
/**
177
 * Implements hook_preprocess().
178
 *
179
180
181
 * @see contextual_pre_render_placeholder()
 * @see contextual_page_build()
 * @see \Drupal\contextual\ContextualController::render()
182
 */
183
function contextual_preprocess(&$variables, $hook, $info) {
184
  // Determine the primary theme function argument.
185
186
  if (!empty($info['variables'])) {
    $keys = array_keys($info['variables']);
187
188
    $key = $keys[0];
  }
189
190
  elseif (!empty($info['render element'])) {
    $key = $info['render element'];
191
  }
192
  if (!empty($key) && isset($variables[$key])) {
193
194
195
196
    $element = $variables[$key];
  }

  if (isset($element) && is_array($element) && !empty($element['#contextual_links'])) {
197
    // Mark this element as potentially having contextual links attached to it.
198
    $variables['attributes']['class'][] = 'contextual-region';
199
200
201
202
203
204
205
206
207
208

    // Renders a contextual links placeholder unconditionally, thus not breaking
    // the render cache. Although the empty placeholder is rendered for all
    // users, contextual_page_build() only adds the drupal.contextual-links
    // library for users with the 'access contextual links' permission, thus
    // preventing unnecessary HTTP requests for users without that permission.
    $variables['title_suffix']['contextual_links'] = array(
      '#type' => 'contextual_links_placeholder',
      '#id' => _contextual_links_to_id($element['#contextual_links']),
    );
209
210
211
  }
}

212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/**
 * Pre-render callback: Renders a contextual links placeholder into #markup.
 *
 * Renders an empty (hence invisible) placeholder div with a data-attribute that
 * contains an identifier ("contextual id"), which allows the JavaScript of the
 * drupal.contextual-links library to dynamically render contextual links.
 *
 * @param $element
 *   A structured array with #id containing a "contextual id".
 *
 * @return
 *   The passed-in element with a contextual link placeholder in '#markup'.
 *
 * @see _contextual_links_to_id()
 * @see contextual_element_info()
 */
function contextual_pre_render_placeholder($element) {
229
  $element['#markup'] = '<div' . new Attribute(array('data-contextual-id' => $element['#id'])) . '></div>';
230
231
232
  return $element;
}

233
/**
234
 * Pre-render callback: Builds a renderable array for contextual links.
235
236
237
 *
 * @param $element
 *   A renderable array containing a #contextual_links property, which is a
238
239
240
241
242
243
 *   keyed array. Each key is the name of the group of contextual links to
 *   render (based on the 'group' key in the *.contextual_links.yml files for
 *   all enabled modules). The value contains an associative array containing
 *   the following keys:
 *   - route_parameters: The route parameters passed to the url generator.
 *   - metadata: Any additional data needed in order to alter the link.
244
245
 *   @code
 *     array('#contextual_links' => array(
246
247
248
249
250
251
 *       'block' => array(
 *         'route_parameters' => array('block' => 'system.menu-tools'),
 *       ),
 *       'menu' => array(
 *         'route_parameters' => array('menu' => 'tools'),
 *       ),
252
253
254
255
256
257
 *     ))
 *   @endcode
 *
 * @return
 *   A renderable array representing contextual links.
 *
258
 * @see contextual_element_info()
259
 */
260
function contextual_pre_render_links($element) {
261
262
  // Retrieve contextual menu links.
  $items = array();
263
264
265
266
267
268
269
270
271

  /** @var $contextual_links_manager \Drupal\Core\Menu\ContextualLinkManager */
  $contextual_links_manager = \Drupal::service('plugin.manager.menu.contextual_link');
  foreach ($element['#contextual_links'] as $group => $args) {
    $args += array(
      'route_parameters' => array(),
      'metadata' => array(),
    );
    $items += $contextual_links_manager->getContextualLinksArrayByGroup($group, $args['route_parameters'], $args['metadata']);
272
273
  }

274
  // Transform contextual links into parameters suitable for theme_links().
275
276
277
278
279
  $links = array();
  foreach ($items as $class => $item) {
    $class = drupal_html_class($class);
    $links[$class] = array(
      'title' => $item['title'],
280
281
      'route_name' => isset($item['route_name']) ? $item['route_name'] : '',
      'route_parameters' => isset($item['route_parameters']) ? $item['route_parameters'] : array(),
282
283
    );
  }
284
285
286
287
288
289
290
291
  $element['#links'] = $links;

  // Allow modules to alter the renderable contextual links element.
  drupal_alter('contextual_links_view', $element, $items);

  // If there are no links, tell drupal_render() to abort rendering.
  if (empty($element['#links'])) {
    $element['#printed'] = TRUE;
292
  }
293
294

  return $element;
295
296
}

297
298
299
300
301
302
303
/**
 * Implements hook_contextual_links_view_alter().
 *
 * @see \Drupal\contextual\Plugin\views\field\ContextualLinks::render()
 */
function contextual_contextual_links_view_alter(&$element, $items) {
  if (isset($element['#contextual_links']['contextual'])) {
304
    $encoded_links = $element['#contextual_links']['contextual']['metadata']['contextual-views-field-links'];
305
306
307
308
309
310
311
312
    $element['#links'] = drupal_json_decode(rawurldecode($encoded_links));
  }
}

/**
 * Serializes #contextual_links property value array to a string.
 *
 * Examples:
313
314
315
 *  - node:node=1:
 *  - views_ui_edit:view=frontpage:location=page&view_name=frontpage&view_display_id=page_1
 *  - menu:menu=tools:|block:block=bartik.tools:
316
317
 *
 * So, expressed in a pattern:
318
 *  <group>:<route parameters>:<metadata>
319
 *
320
 * The route parameters and options are encoded as query strings.
321
322
323
324
325
326
327
328
329
 *
 * @param array $contextual_links
 *   The $element['#contextual_links'] value for some render element.
 *
 * @return string
 *   A serialized representation of a #contextual_links property value array for
 *   use in a data- attribute.
 */
function _contextual_links_to_id($contextual_links) {
330
331
332
333
334
  $ids = array();
  foreach ($contextual_links as $group => $args) {
    $route_parameters = Url::buildQuery($args['route_parameters']);
    $metadata = Url::buildQuery((isset($args['metadata'])) ? $args['metadata'] : array());
    $ids[] = "{$group}:{$route_parameters}:{$metadata}";
335
  }
336
  return implode('|', $ids);
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
}

/**
 * Unserializes the result of _contextual_links_to_id().
 *
 * @see _contextual_links_to_id
 *
 * @param string $id
 *   A serialized representation of a #contextual_links property value array.
 *
 * @return array
 *   The value for a #contextual_links property.
 */
function _contextual_id_to_links($id) {
  $contextual_links = array();
  $contexts = explode('|', $id);
  foreach ($contexts as $context) {
354
355
    list($group, $route_parameters_raw, $metadata_raw) = explode(':', $context);
    parse_str($route_parameters_raw, $route_parameters);
356
357
    $metadata = array();
    parse_str($metadata_raw, $metadata);
358
359
360
361
    $contextual_links[$group] = array(
      'route_parameters' => $route_parameters,
      'metadata' => $metadata,
    );
362
363
364
  }
  return $contextual_links;
}