-
Notifications
You must be signed in to change notification settings - Fork 4
/
common_design.theme
1003 lines (899 loc) · 35.8 KB
/
common_design.theme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Template overrides, preprocess, and hooks for the OCHA Common Design theme.
*/
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
/**
* Implements hook_form_system_theme_settings_alter().
*
* Add a setting to the theme for the special handling of the node title.
*
* Add a setting to enable extra fonts.
*/
function common_design_form_system_theme_settings_alter(&$form, FormStateInterface $form_state, $form_id = NULL) {
// Work-around for a core bug affecting admin themes. See issue #943212.
if (isset($form_id)) {
return;
}
if (!isset($form['common_design'])) {
$form['common_design'] = [
'#type' => 'details',
'#title' => t('Common design settings'),
'#open' => TRUE,
];
}
// Load the node view modes.
$storage = \Drupal::entityTypeManager()->getStorage('entity_view_mode');
$view_modes = $storage->loadByProperties([
'targetEntityType' => 'node',
]);
if (empty($view_modes)) {
return;
}
// The view mode ids are in the form `node.viewmode` which is not a valid
// key for the form options, so we strip the `node.`.
$options = [];
foreach ($view_modes as $view_mode) {
$id = preg_replace('/^node\./', '', $view_mode->id());
$options[$id] = $view_mode->label();
}
// By default, this behavior is enabled for the "full" view mode.
$default = theme_get_setting('common_design_node_title');
if (empty($default) && isset($options['full'])) {
$default = ['full'];
}
$form['common_design']['common_design_node_title'] = [
'#type' => 'checkboxes',
'#title' => t('Use node title for view mode'),
'#options' => $options,
'#default_value' => $default,
'#description' => t('Select the <strong>page</strong> node view modes for which to use the node title rather than the global page title block.'),
];
// Theme and library services.
$theme_handler = \Drupal::service('theme_handler');
$library_discovery = \Drupal::service('library.discovery');
// Get the installed themes.
/** @var \Drupal\Core\Extension\Extension[] $theme_list */
$theme_list = $theme_handler->listInfo();
// Get the name of the active theme.
$active_theme = \Drupal::theme()->getActiveTheme()->getName();
// Themes from which to extract the font libraries.
$themes = [];
// Get the name of the base theme. If it's the common design one, then we
// add it to the list of themes.
$base_theme = $theme_list[$active_theme]->base_theme;
if ($base_theme === 'common_design' && isset($theme_list[$base_theme])) {
$themes[$base_theme] = $theme_list[$base_theme];
}
// Add the active theme (after the base theme).
$themes[$active_theme] = $theme_list[$active_theme];
// Extract the font libraries.
$fonts_options = [];
foreach ($themes as $theme_name => $theme_extension) {
// Get the list of libraries defined in the theme's libaries.yml.
$libraries = $library_discovery->getLibrariesByExtension($theme_name);
foreach ($libraries as $name => $info) {
// @todo we could add a "tags" property instead for example.
if (strpos($name, 'fonts-') === 0) {
$value = $theme_name . '/' . $name;
// We prefix the label with the theme name to differentiate between
// libraries from the common design base theme and the ones from the
// subtheme.
$label = implode(' - ', [
$theme_extension->info['name'],
$info['label'] ?? ucfirst(substr($name, 6)),
]);
$fonts_options[$value] = $label;
}
}
}
if (!empty($fonts_options)) {
$form['common_design']['common_design_fonts'] = [
'#type' => 'checkboxes',
'#title' => t('Enable fonts'),
'#options' => $fonts_options,
'#default_value' => theme_get_setting('common_design_fonts') ?? [],
];
}
}
/**
* Implements hook_preprocess().
*/
function common_design_preprocess(&$variables, $hook) {
try {
$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
}
catch (Exception $e) {
$variables['is_front'] = FALSE;
}
// Ensure the cache varies correctly.
$variables['#cache']['contexts'][] = 'url.path.is_front';
// Check if Components module is enabled, to prevent page--demo.html.twig
// breaking due to twig errors.
$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('components')) {
$variables['componentsModule'] = TRUE;
}
}
/**
* Indicate whether to render the page title inside the node or not.
*
* @param string $view_mode
* View mode to check against the theme settings.
*
* @return bool
* TRUE if the page title should be rendered inside the node.
*/
function common_design_use_node_page_title($view_mode) {
if (empty($view_mode)) {
return FALSE;
}
// Get the list of node view modes for which to use the pre-rendered page
// title instead of the normal page title block. This is an associative array
// keyed by view modes and with either the view mode as value when enabled
// or 0 otherwise. If not set, enable the behavior for the full view-mode.
$view_modes = theme_get_setting('common_design_node_title');
if (!isset($view_modes)) {
$view_modes = ['full' => 'full'];
}
return !empty($view_modes[$view_mode]);
}
/**
* Implements hook_preprocess_page().
*
* Remove the default page title and local tasks blocks if they were already
* rendered by a page title paragraph or when viewing full article nodes.
*
* Attach the selected fonts libraries.
*/
function common_design_preprocess_page(&$variables) {
$route_match = \Drupal::routeMatch();
$route_name = $route_match->getRouteName();
// Retrieve the view mode for the node page or preview page.
$view_mode = '';
if ($route_name === 'entity.node.canonical') {
$node = $route_match->getParameter('node');
if (!empty($node)) {
// This gives us an array with the page view mode for the node.
$build = \Drupal::entityTypeManager()
->getViewBuilder('node')
->view($node);
$view_mode = $build['#view_mode'] ?? '';
}
}
elseif ($route_name === 'entity.node.preview') {
$view_mode = $route_match->getParameter('view_mode_id');
}
// If the view mode was selected to use the page title block, then
// we remove the original page title block and local tasks blocks.
// @see common_design_preprocess_node().
// @see common_design_set_page_title().
if (common_design_use_node_page_title($view_mode)) {
if ($route_name === 'entity.node.canonical') {
common_design_hide_rendered_blocks_from_page($variables, [
'page_title_block',
'local_tasks_block',
]);
}
elseif ($route_name === 'entity.node.preview') {
common_design_hide_rendered_blocks_from_page($variables, [
'page_title_block',
]);
}
}
// Extra fronts to enable.
$fonts = theme_get_setting('common_design_fonts') ?? [];
foreach ($fonts as $name => $enabled) {
if (!empty($enabled)) {
$variables['#attached']['library'][] = $name;
}
}
}
/**
* Implements hook_preprocess_node().
*
* Use the page title block for the node title if the view mode was selected
* in the theme settings.
*
* Important: this assumes there is a template for the view mode that uses
* the `title` (and `local_tasks`) variables added by
* common_design_use_node_page_title(). See `node--full.html.twig`.
*
* @see common_design_preprocess_page()
* @see common_design_set_page_title()
*/
function common_design_preprocess_node(&$variables) {
$route_name = \Drupal::routeMatch()->getRouteName();
$node = $variables['node'] ?? NULL;
$view_mode = $variables['view_mode'] ?? '';
// If the node view mode was selected to use the page title block for the
// node title in the template, then we add the page title to the template
// variables. We only do that if we are on the canonical node page or on
// the node preview page.
if (isset($node) && common_design_use_node_page_title($view_mode)) {
if (node_is_page($node)) {
common_design_set_page_title($variables, $node->label(), TRUE);
}
elseif ($node->in_preview && $route_name === 'entity.node.preview') {
common_design_set_page_title($variables, $node->label(), FALSE);
}
}
}
/**
* Set the page title (ex: node page) using the page title block.
*
* @param array $variables
* Variables as passed to a hook_preprocess_HOOK().
* @param string $default_title
* Default title to use if none can be resolved.
* @param bool $is_page
* Flag indicating if we are on a normal page as opposed to viewing an entity
* in preview for example, or if this called outside of a page context.
*/
function common_design_set_page_title(array &$variables, $default_title, $is_page = FALSE) {
// Retrieve the page title block.
$variables['title'] = common_design_get_block_render_array('page_title_block');
if (!empty($variables['title'])) {
// If we are on a normal page (not in a node preview for example), and the
// page title render array doesn't have a default title, then we try to get
// the title from the title resolver service.
// @see https://www.drupal.org/project/drupal/issues/2938129
if ($is_page) {
if (empty($variables['title']['#title'])) {
$request = \Drupal::request();
$route_object = \Drupal::routeMatch()->getRouteObject();
if (!empty($request) && !empty($route_object)) {
$default_title = \Drupal::service('title_resolver')
->getTitle($request, $route_object);
}
}
else {
$default_title = $variables['title']['#title'];
}
}
// Set the default title.
$variables['title']['#title'] = $default_title;
// Copy the title attributes.
if (!empty($variables['title_attributes'])) {
$variables['title']['#title_attributes'] = $variables['title_attributes'];
}
}
// Also pre-render the local tasks when on a normal page.
if ($is_page) {
$variables['local_tasks'] = common_design_get_block_render_array('local_tasks_block');
}
}
/**
* Implements hook_theme_registry_alter().
*
* Ensure we can set the title attributes to the page title.
*/
function common_design_theme_registry_alter(&$theme_registry) {
if (isset($theme_registry['page_title'])) {
$theme_registry['page_title']['variables']['title_attributes'] = [];
}
// The theme discovery (drupal_find_theme_templates()) is too greedy and
// picks up the templates in `common_design/common_design_subtheme`. The code
// below reverts that behavior to use the `common_design` templates instead.
foreach ($theme_registry as $name => $theme_info) {
if (isset($theme_info['path']) && strpos($theme_info['path'], 'common_design/common_design_subtheme') !== FALSE) {
$theme_registry[$name]['path'] = str_replace('common_design/common_design_subtheme', 'common_design', $theme_info['path']);
}
}
}
/**
* Impements hook_theme_suggestions_input_alter().
*/
function common_design_theme_suggestions_input_alter(&$suggestions, array $variables) {
$element = $variables['element'];
if (isset($element['#attributes']['data-twig-suggestion'])) {
$suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['data-twig-suggestion'];
}
}
/**
* Impements hook_theme_suggestions_form_alter().
*/
function common_design_theme_suggestions_form_alter(array &$suggestions, array $variables) {
$suggestions[] = 'form__' . $variables['element']['#form_id'];
}
/**
* Impements hook_theme_suggestions_form_element_alter().
*/
function common_design_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
$suggestions[] = $hook . '__' . $variables['element']['#type'];
}
/**
* Implements hook_theme_suggestions_paragraph_alter().
*
* - paragraph--PARENT-ENTITY--PARAGRAPH.html.twig
* - paragraph--PARENT-ENTITY--PARENT-FIELD--PARAGRAPH.html.twig
*/
function common_design_theme_suggestions_paragraph_alter(array &$suggestions, array $variables) {
$paragraph = $variables['elements']['#paragraph'];
$parent_entity = $paragraph->getParentEntity();
$parent_field_name = $paragraph->parent_field_name->value;
if ($parent_entity) {
$suggestions[] = 'paragraph__' . $parent_entity->bundle() . '__' . $paragraph->bundle();
}
if ($parent_entity && $parent_field_name) {
$suggestions[] = 'paragraph__' . $parent_entity->bundle() . '__' . $parent_field_name . '__' . $paragraph->bundle();
}
}
/**
* Implements hook_form_alter().
*/
function common_design_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// This is for Drupal core search block.
if ($form_id == 'search_block_form') {
$form['#attributes']['class'][] = 'cd-search__form';
$form['#attributes']['aria-labelledby'][] = 'cd-search-form';
$form['#attributes']['data-cd-toggable'][] = 'Search';
$form['#attributes']['data-cd-icon'][] = '';
$form['#attributes']['data-cd-component'][] = 'cd-search';
$form['#attributes']['data-cd-logo'][] = 'search';
// Focus the input when clicking on the toggler button.
$form['#attributes']['data-cd-focus-target'] = 'cd-search';
$form['keys']['#attributes']['placeholder'][] = t('What are you looking for?');
$form['keys']['#attributes']['class'][] = 'cd-search__input';
$form['keys']['#attributes']['id'][] = 'cd-search';
$form['keys']['#attributes']['autocomplete'][] = 'off';
// Theme suggestion for submit element.
$form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_submit';
$form['actions']['submit']['#attributes']['class'][] = 'cd-search__submit';
$form['actions']['submit']['#attributes']['value'][] = 'Search';
// This is for a Drupal core INLINE search block.
// There are templates needed for this. Replace cd-search.html.twig
// with cd-search--inline.html.twig in cd-site-header.html.twig.
// @codingStandardsIgnoreStart
/*
$form['#attributes']['class'][] = 'cd-search--inline__form';
$form['#attributes']['aria-labelledby'][] = 'cd-search-form--inline';
$form['#attributes']['data-cd-toggable'][] = 'Search';
$form['#attributes']['data-cd-icon'][] = '';
$form['#attributes']['data-cd-component'][] = 'cd-search--inline';
$form['#attributes']['data-cd-logo'][] = 'search';
// Focus the input when clicking on the toggler button.
$form['#attributes']['data-cd-focus-target'] = 'cd-search--inline';
$form['keys']['#attributes']['placeholder'][] = t('What are you looking for?');
$form['keys']['#attributes']['class'][] = 'cd-search--inline__input';
$form['keys']['#attributes']['type'][] = 'search';
$form['keys']['#attributes']['id'][] = 'cd-search--inline';
$form['keys']['#attributes']['autocomplete'][] = 'off';
// Theme suggestion for submit element.
$form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_submit';
$form['actions']['submit']['#attributes']['class'][] = 'cd-search--inline__submit';
$form['actions']['submit']['#attributes']['value'][] = 'Search';
*/
// @codingStandardsIgnoreEnd
}
// To use this for Views exposed forms, copy the form alter hook into your
// subtheme and add the relevant Views IDs to this array in your subtheme.
$includeView = [];
// If in array above, add attributes for styling and behaviour.
// Replace $form['keys'] with the appropriate fulltext input eg.
// $form['search_api_fulltext'].
if (in_array($form['#id'], $includeView)) {
$form['#attributes']['class'][] = 'cd-search__form';
$form['#attributes']['aria-labelledby'][] = 'cd-search-form';
$form['#attributes']['data-cd-toggable'][] = 'Search';
$form['#attributes']['data-cd-icon'][] = '';
$form['#attributes']['data-cd-component'][] = 'cd-search';
$form['#attributes']['data-cd-logo'][] = 'search';
// Focus the input when clicking on the toggler button.
$form['#attributes']['data-cd-focus-target'] = 'cd-search';
$form['keys']['#attributes']['placeholder'] = t('What are you looking for?');
$form['keys']['#attributes']['class'][] = 'cd-search__input';
$form['keys']['#attributes']['type'][] = 'search';
$form['keys']['#attributes']['id'][] = 'cd-search';
$form['keys']['#attributes']['autocomplete'][] = 'off';
// Theme suggestion for submit element.
$form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_submit';
$form['actions']['submit']['#attributes']['class'][] = 'cd-search__submit';
$form['actions']['submit']['#attributes']['value'][] = 'Search';
// This is for a Views exposed form INLINE search block.
// There are templates needed for this. Replace cd-search.html.twig
// with cd-search--inline.html.twig in cd-site-header.html.twig.
// @codingStandardsIgnoreStart
/*
$form['#attributes']['class'][] = 'cd-search--inline__form';
$form['#attributes']['aria-labelledby'][] = 'cd-search-form--inline';
$form['#attributes']['data-cd-toggable'][] = 'Search';
$form['#attributes']['data-cd-icon'][] = '';
$form['#attributes']['data-cd-component'][] = 'cd-search--inline';
$form['#attributes']['data-cd-logo'][] = 'search';
// Focus the input when clicking on the toggler button.
$form['#attributes']['data-cd-focus-target'] = 'cd-search--inline';
$form['keys']['#attributes']['placeholder'][] = t('What are you looking for?');
$form['keys']['#attributes']['class'][] = 'cd-search--inline__input';
$form['keys']['#attributes']['type'][] = 'search';
$form['keys']['#attributes']['id'][] = 'cd-search--inline';
$form['keys']['#attributes']['autocomplete'][] = 'off';
// Theme suggestion for submit element.
$form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_submit';
$form['actions']['submit']['#attributes']['class'][] = 'cd-search--inline__submit';
$form['actions']['submit']['#attributes']['value'][] = 'Search';
*/
// @codingStandardsIgnoreEnd
}
/* Add CD button classes to Cancel and Delete */
if (isset($form['actions']['delete'])) {
if ($form['actions']['delete']['#button_type'] == 'danger') {
$form['actions']['delete']['#attributes']['class'][] = 'cd-button cd-button--danger';
}
}
/* Add CD button classes to Delete and Cancel on Node/Term confirmation pages */
if ($form['#theme'] == 'confirm_form') {
if (isset($form['actions']['submit'])) {
if ($form['actions']['submit']['#button_type'] == 'primary') {
$form['actions']['submit']['#attributes']['class'][] = 'cd-button cd-button--danger';
}
}
if (isset($form['actions']['cancel'])) {
if ($form['actions']['cancel']['#type'] == 'link') {
$form['actions']['cancel']['#attributes']['class'][] = 'cd-button cd-button--outline';
}
}
}
}
/**
* Implements hook_preprocess_html().
*/
function common_design_preprocess_html(&$vars) {
// Check if current request is an exception to get error type.
$status_code = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
// Add body classes.
if ($status_code && !is_a($status_code, 'ParamNotConvertedException')) {
if ($status_code->getStatusCode() == 404) {
$vars['attributes']['class'][] = 'path-error path-error--404';
}
if ($status_code->getStatusCode() == 403) {
$vars['attributes']['class'][] = 'path-error path-error--403';
}
}
// Add a script to detect whether javascript is enabled or not and then
// replace the `no-js` class with the `js` one.
//
// Drupal.js does this but way too late on first load causing issues with
// css rules that rely on the `js` class being defined or not.
//
// @TODO: we end up with duplicate `js` classes when both this and Drupal.js
// execute their code. It's also possible to see both `no-js` and `js`
// in old browsers like IE11.
$js_detection = [
'#tag' => 'script',
'#value' => "document.documentElement.className = document.documentElement.className.replace('no-js', typeof document.addEventListener !== 'undefined' ? 'js' : 'no-js');",
'#weight' => -1,
];
$vars['page']['#attached']['html_head'][] = [$js_detection, 'js-detection'];
// Construct <link>s for Roboto: two that preconnect to Google Fonts, for a
// nominal performance improvement, and the link to the CSS file itself.
//
// To load the font in a totally non-blocking manner, we are using the media
// attribute to specify print until the fonts load, then we remove it with JS.
// There is no <noscript> in place, so the fonts won't load on non-JS browsers
// by design.
//
// To edit the font selection, visit the following URL:
//
// @see https://fonts.google.com/share?selection.family=Roboto:ital,wght@0,300;0,400;0,500;0,700;0,900;1,400;1,700
$preconnect_api = [
'rel' => 'preconnect',
'href' => 'https://fonts.googleapis.com',
];
$preconnect_static = [
'rel' => 'preconnect',
'href' => 'https://fonts.gstatic.com',
'crossorigin' => TRUE,
];
$roboto_default = [
'rel' => 'preload',
'href' => 'https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;0,500;0,700;0,900;1,400;1,700&display=swap',
'as' => 'style',
'onload' => 'this.onload=null;this.setAttribute(`rel`, `stylesheet`);',
];
// Add <link>s to HTML response.
$vars['page']['#attached']['html_head_link'][] = [
$preconnect_api,
'preconnect-api',
];
$vars['page']['#attached']['html_head_link'][] = [
$preconnect_static,
'preconnect-static',
];
$vars['page']['#attached']['html_head_link'][] = [
$roboto_default,
'roboto-default',
];
}
/**
* Implements hook_theme_suggestions_HOOK_alter().
*
* - page--demo.html.twig
* - page--401.html.twig
* - page--403.html.twig
* - page--404.html.twig
*/
function common_design_theme_suggestions_page_alter(array &$suggestions, array $variables, $hook) {
$current_uri = \Drupal::request()->getRequestUri();
// Set variable based on path alias to include Component demo page.
if ($current_uri == '/demo') {
$suggestions[] = $hook . '__demo';
}
// Error page template suggestions.: 401, 403, 404, etc
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
$status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
$suggestions[] = 'page__' . (string) $status_code;
}
}
/**
* Implements hook_theme_suggestions_HOOK_alter().
*
* Provides more granularity when Views displays are getting rendered. The two
* suggestions will allow the following templates to be picked up:
*
* - views-view--VIEW.html.twig
* - views-view--VIEW--DISPLAY.html.twig
*
* @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_theme_suggestions_HOOK_alter/8.8.x
*/
function common_design_theme_suggestions_views_view_alter(&$suggestions, $variables) {
$suggestions[] = sprintf('views_view__%s', $variables['view']->id());
$suggestions[] = sprintf('views_view__%s__%s', $variables['view']->id(), $variables['view']->current_display);
}
/**
* Implements hook_block__language_block().
*/
function common_design_preprocess_block__language_block(&$vars) {
// Current language available in template override.
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$vars['language'] = $language;
$language_name = \Drupal::languageManager()->getCurrentLanguage()->getName();
$vars['language_name'] = $language_name;
}
/**
* Implements hook_preprocess_menu().
*
* Ensure we have a user menu hierarchy in the form:
*
* My account
* Edit my account
* ... (potential other menu items)
* Log out
*/
function common_design_preprocess_menu__account(&$variables) {
$items = &$variables['items'] ?? [];
$base_child_menu_item = [
'is_expanded' => FALSE,
'is_collapsed' => FALSE,
'in_active_trail' => FALSE,
'attributes' => new Attribute(),
'below' => [],
];
// Find the "My account" menu item. It may be the default system menu item
// from the core user module or a custom one added as per release instructions
// of the CD 7.4 version.
foreach ($items as &$item) {
if (isset($item['url']) && $item['url']->isRouted() && $item['url']->getRouteName() === 'user.page') {
$account_menu_item = &$item;
break;
}
}
// If there is a menu account, add a child link to the user edit form (or
// user page for Drupal < 9.5) and a child link to log out; and consolidate
// the labels.
if (isset($account_menu_item)) {
$children = $account_menu_item['below'] ?? [];
// Retrieve or create a link to the user page. This is mostly for backward
// compatibility with the CD 7.4.
if (isset($children['user.page'])) {
$user_edit_menu_item = $children['user.page'];
unset($children['user.page']);
}
else {
$user_edit_menu_item = $base_child_menu_item;
}
// For Drupal 9.5+, we redirect to the user edit form.
if (!empty(\Drupal::service('router')->getRouteCollection()->get('user.edit'))) {
$user_edit_menu_item['url'] = Url::fromRoute('user.edit');
}
elseif (!isset($user_edit_menu_item['url'])) {
$user_edit_menu_item['url'] = Url::fromRoute('user.page');
}
// Ensure the title is consistent across sites using the CD.
$user_edit_menu_item['title'] = t('Edit my account');
// Add it as the first link.
$children = ['user.page' => $user_edit_menu_item] + $children;
// Retrieve any existing logout link. This is mostly for backward
// compatibility with the CD 7.4 and prevents multiple logout links.
foreach ($children as $key => $child) {
if (isset($child['url']) && $child['url']->isRouted() && $child['url']->getRouteName() === 'user.logout') {
$logout_menu_item = $child;
unset($children[$key]);
}
}
// Use the top logout link if it exists.
if (isset($items['user.logout'])) {
$logout_menu_item = $items['user.logout'];
unset($items['user.logout']);
}
// Otherwise create a new one if we didn't find one earlier.
elseif (!isset($logout_menu_item)) {
$logout_menu_item = $base_child_menu_item + [
'url' => Url::fromRoute('user.logout'),
];
}
// Ensure the title is consistent across sites using the CD.
$logout_menu_item['title'] = t('Log out');
// Add the link at the bottom.
$children['user.logout'] = $logout_menu_item;
// Mark the menu item as expanded so it's converted to a button.
$account_menu_item['is_expanded'] = TRUE;
$account_menu_item['below'] = $children;
// Ensure the title is consistent across sites using the CD.
$account_menu_item['title'] = t('My account');
}
}
/**
* Load the block entities for the given ids.
*
* @param array $ids
* Block ids.
*
* @return \Drupal\block\BlockInterface[]
* Block entities.
*/
function common_design_load_theme_blocks(array $ids) {
if (empty($ids)) {
return [];
}
$storage = \Drupal::entityTypeManager()->getStorage('block');
$theme = \Drupal::theme()->getActiveTheme();
// Load the blocks with that plugin id for the theme.
return $storage->loadByProperties([
'theme' => $theme->getName(),
'plugin' => $ids,
]);
}
/**
* Render a block.
*
* We store the list of blocks rendered by this function so that we can
* prevent them from being rendered several times on a page.
*
* @param string $id
* Block ID.
*
* @return array
* Renderable array of the block. Empty array if this was already called
* before to avoid displaying the block several times.
*/
function common_design_get_block_render_array($id) {
$rendered = &drupal_static(__FUNCTION__, []);
if (!isset($rendered[$id])) {
// Prevent rendering the block several times.
$rendered[$id] = TRUE;
// Load the blocks with that plugin id for the theme.
$blocks = common_design_load_theme_blocks([$id]);
if (empty($blocks)) {
return [];
}
// Get the render array for the block.
$block = reset($blocks);
$build = $block->getPlugin()->build();
// Check the accessibility to the block.
$build['#access'] = $block->access('view', NULL, TRUE);
// Ensure the appropriate cache metadata is added to the build.
$cache = CacheableMetadata::createFromRenderArray($build);
$cache->addCacheableDependency($block);
$cache->addCacheableDependency($build['#access']);
$cache->applyTo($build);
// The local tasks have by default a max-age cache of 0 which prevents the
// entire caching so we remove it as there are already cache contexts and
// tags to ensure its displayed appropriately.
if ($id === 'local_tasks_block' && empty($build['#cache']['max-age'])) {
unset($build['#cache']['max-age']);
}
return $build;
}
return [];
}
/**
* Remove already rendered blocks from the page.
*
* @param array $variables
* Page variables as passed to hook_preprocess_page().
* @param array $block_ids
* Ids of the blocks to hide.
*/
function common_design_hide_rendered_blocks_from_page(array &$variables, array $block_ids) {
$blocks = common_design_load_theme_blocks($block_ids);
if (!empty($blocks)) {
foreach ($blocks as $block) {
$id = $block->id();
$region = $block->getRegion();
// If the block exists in the page, then deny access to it so that it's
// hidden. We don't remove the block so that access and visibility can
// be restored by other modules/sub-themes.
if (isset($variables['page'][$region][$id])) {
$access = $variables['page'][$region][$id]['#access'] ?? NULL;
// Store the original access information so that other modules that
// want to undo what is done here can do so.
$variables['page'][$region][$id]['#original_access'] = $access;
// Deny access to hide the block. We use the function name as reason
// so that it's easy for modules/sub-themes that want to revert the
// behavior to identify blocks that have been denied access this way.
$forbidden = AccessResult::forbidden(__FUNCTION__);
if ($access instanceof AccessResult) {
// This preserves the cache metadata of the previous access result.
$access = $access->andIf($forbidden);
}
else {
$access = $forbidden;
}
$variables['page'][$region][$id]['#access'] = $access;
}
}
}
}
/**
* Implements hook_theme().
*
* Add themes for the taxonomy term and user edit forms.
*/
function common_design_theme(array $existing, $type, $theme, $path) {
$hooks = [
'taxonomy_term_edit_form',
'user_edit_form',
];
return common_design_get_entity_edit_form_themes($hooks, $existing, $theme, $path);
}
/**
* Generate the list of themes for entity edit forms.
*
* @param array $hooks
* List of base edit form theme ids to create.
* @param array $existing
* List of existing themes.
* @param string $theme
* The current theme (ex: common_design) name.
* @param string $path
* The path of the current theme.
*
* @return array
* Theme data as returned by hook_theme().
*/
function common_design_get_entity_edit_form_themes(array $hooks, array $existing, $theme, $path) {
$themes = [];
$scan = is_dir($path);
foreach ($hooks as $hook) {
// In case Drupal becomes consistent and adds the term and user edit form
// themes like it does with the `node_edit_form` theme for nodes...
if (isset($existing[$hook])) {
continue;
}
// We need to explicitly add a preprocess function so that the
// `preprocess functions` key is not removed in
// \Drupal\Core\Theme\Registry::postProcessExtension()
// which causes a PHP "null given" error when calling array_diff in
// \Drupal\Core\Theme\Registry::mergePreprocessFunctions()...
//
// @see \Drupal\Core\Theme\Registry::postProcessExtension()
// @see \Drupal\Core\Theme\Registry::mergePreprocessFunctions()
$themes[$hook] = [
'render element' => 'form',
'path' => $path . '/templates/form',
'preprocess functions' => [$theme . '_preprocess_' . $hook],
];
// Drupal doesn't allow finding suggestions for themes declared in the
// current theme's hook_theme. So we do a light scan to populate the theme
// registry with suggestions.
//
// Note: we don't need to do that for the node_edit_form theme defined
// in the core node module because it's not defined in this theme and
// drupal_find_theme_templates() will pick the template override and
// suggestions properly.
//
// @see drupal_find_theme_templates()
// @see twig_theme()
if ($scan) {
$regex = '#(^|/)' . strtr($hook, '_', '-') . '--.*\.html\.twig$#';
$files = \Drupal::service('file_system')->scanDirectory($path, $regex);
foreach ($files as $file) {
$template = str_replace('.html.twig', '', $file->filename);
$suggestion = strtr($template, '-', '_');
$themes[$suggestion] = [
'render element' => 'form',
'template' => $template,
'path' => dirname($file->uri),
'base hook' => $hook,
'preprocess functions' => [$theme . '_preprocess_' . $suggestion],
];
}
}
}
return $themes;
}
/**
* Add bundle and view mode theme suggestions for the edit form of an entity.
*
* @param array $form
* The form array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @see seven_form_node_form_alter()
*/
function common_design_add_entity_edit_form_theme(array &$form, FormStateInterface $form_state) {
$display = $form_state->get('form_display');
$entity_type_id = $display->getTargetEntityTypeId();
$bundle = $display->getTargetBundle();
$view_mode = $display->getMode();
$base = $entity_type_id . '_edit_form';
// The order is important.
$form['#theme'][] = $base . '__' . $bundle . '__' . $view_mode;
$form['#theme'][] = $base . '__' . $view_mode;
$form['#theme'][] = $base . '__' . $bundle;
$form['#theme'][] = $base;
}
/**
* Implements hook_form_node_HOOK_alter().
*/
function common_design_form_node_form_alter(&$form, FormStateInterface $form_state) {
common_design_add_entity_edit_form_theme($form, $form_state);
}
/**
* Implements hook_form_node_HOOK_alter().
*/
function common_design_form_taxonomy_term_form_alter(&$form, FormStateInterface $form_state) {
common_design_add_entity_edit_form_theme($form, $form_state);
// Make the form page title consistent with the nodes to avoid the generic
// "Add term" and "Edit term" page titles.
if (!isset($form['#title'])) {
$entity = $form_state->getFormObject()->getEntity();
$bundle_key = $entity->getEntityType()->getKey('bundle');
$bundle_label = $entity->get($bundle_key)->entity->label();
if (empty($form['tid']['#value'])) {
$form['#title'] = t('Create @bundle_label', [
'@bundle_label' => $bundle_label,
]);
}
else {
$form['#title'] = t('<em>Edit @bundle_label</em> @title', [
'@bundle_label' => $bundle_label,
'@title' => $entity->label(),
]);
}
}
}
/**
* Implements hook_form_node_HOOK_alter().
*/
function common_design_form_user_form_alter(array &$form, FormStateInterface $form_state) {
common_design_add_entity_edit_form_theme($form, $form_state);
}
/**
* Implemenents hook_preprocess_fieldset().
*/
function common_design_preprocess_fieldset(array &$variables) {
// Set the visually-hidden class to the legend element itself rather than
// its span when the title is supposed to be hidden.
// @see template_preprocess_fieldset()
if ($variables['title_display'] === 'invisible') {
$variables['legend']['attributes']->addClass('visually-hidden');
$variables['legend_span']['attributes']->removeClass('visually-hidden');
}
}
/**
* Implements hook_preprocess_datetime_wrapper().
*/
function common_design_preprocess_datetime_wrapper(&$variables) {
// Ensure the title is not displayed when instructed to be hidden.
if (isset($variables['element']['#title_display']) && $variables['element']['#title_display'] === 'invisible') {