-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParagraph.php
596 lines (545 loc) · 19.6 KB
/
Paragraph.php
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
<?php
namespace Drupal\ghi_content\Plugin\Block;
use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\ghi_blocks\Interfaces\MultiStepFormBlockInterface;
use Drupal\ghi_blocks\Interfaces\OptionalTitleBlockInterface;
use Drupal\ghi_content\RemoteContent\RemoteArticleInterface;
use Drupal\ghi_content\RemoteContent\RemoteParagraphInterface;
use Drupal\gho_footnotes\GhoFootnotes;
/**
* Provides a 'Paragraph' block.
*
* @Block(
* id = "paragraph",
* admin_label = @Translation("Paragraph"),
* category = @Translation("Narrative Content"),
* config_forms = {
* "article_select" = {
* "title" = @Translation("Article selection"),
* "callback" = "articleSelectForm",
* "base_form" = TRUE
* },
* "paragraph" = {
* "title" = @Translation("Paragraph"),
* "callback" = "paragraphForm"
* }
* }
* )
*/
class Paragraph extends ContentBlockBase implements OptionalTitleBlockInterface, MultiStepFormBlockInterface, TrustedCallbackInterface {
/**
* The CSS class used for promoted paragraphs. This comes from the NCMS.
*/
const PROMOTED_CLASS = 'gho-paragraph-promoted';
/**
* {@inheritdoc}
*/
public function getTitleSubform() {
return 'paragraph';
}
/**
* {@inheritdoc}
*/
public function getPreviewFallbackString() {
$paragraph = $this->getParagraph();
if (!$paragraph) {
return parent::getPreviewFallbackString();
}
return $this->t('"@block: @paragraph_type" block', [
'@block' => $this->label(),
'@paragraph_type' => $paragraph->getTypeLabel(),
]);
}
/**
* {@inheritdoc}
*/
public function buildContent() {
$paragraph = $this->getParagraph();
if (!$paragraph) {
return;
}
return $this->buildParagraph($paragraph, $this->label(), $this->isPreview());
}
/**
* Build the render array for a paragraph.
*
* @param \Drupal\ghi_content\RemoteContent\RemoteParagraphInterface $paragraph
* The remote paragraph object.
* @param string|null $title
* A title for the paragraph or NULL.
* @param bool $preview
* Whether this is a preview of the paragraph or not. The main reason this
* is needed is for proper footnote support.
* @param bool $internal_preview
* Whether this is an internal preview for the paragraph selection.
*
* @return array
* The full render array for this paragraph block.
*/
private function buildParagraph(RemoteParagraphInterface $paragraph, $title = NULL, $preview = FALSE, $internal_preview = FALSE) {
// Add GHO specific theme components.
$theme_components = $this->getThemeComponents($paragraph);
// Get the rendered paragraph.
$rendered = $paragraph->getRendered();
$full_width_paragraph_types = [
'story',
];
// Move gho specific paragraph classes to the block wrapper attributes, so
// that CSS logic that targets subsequent elements can be applied.
$wrapper_attributes = [];
$block_attributes = [];
$dom = Html::load($rendered);
if ($paragraph->getType() == 'sub_article') {
// Remove the footer from sub articles.
foreach (iterator_to_array($dom->getElementsByTagName('footer')) as $footer) {
$footer->parentNode->removeChild($footer);
}
}
$child = $dom->getElementsByTagName('div')->item(0);
if ($child) {
$attributes = $child->attributes;
if ($attributes && $attributes->getNamedItem('class') && $attributes->getNamedItem('class')->nodeValue) {
$class_attribute = $attributes->getNamedItem('class')->nodeValue;
$classes = explode(' ', $class_attribute);
// Get the original GHO specific classes.
$gho_classes = !empty($classes) ? array_filter($classes, function ($class) {
return strpos($class, 'gho-') === 0;
}) : [];
// Set new classes specific to our system.
$block_attributes['class'] = array_map(function ($class) {
return $this->getPluginId() . '--' . $class;
}, $gho_classes);
// Special logic for bottom figure rows to assure that styles are also
// applied during preview.
if (($preview || $internal_preview) && in_array('gho-bottom-figure-row', $classes)) {
$block_attributes['class'][] = 'gho-bottom-figure-row';
}
$wrapper_attributes['class'] = $gho_classes;
$attributes->getNamedItem('class')->nodeValue = implode(' ', array_diff($classes, $gho_classes));
}
}
// See if there are links to be replaced.
$links = $dom->getElementsByTagName('a') ?? [];
if (!empty($links)) {
$link_map = $paragraph->getSource()->getLinkMap($paragraph);
foreach ($links as $link) {
$href = $link->attributes->getNamedItem('href')?->value ?? NULL;
if (!$href) {
continue;
}
if (array_key_exists($href, $link_map)) {
$link->attributes->getNamedItem('href')->value = $link_map[$href];
}
elseif (strpos($href, '/') === 0) {
$link->parentNode->removeChild($link);
}
}
}
// Make sure to update the rendered string.
$rendered = trim(Html::serialize($dom));
if ($internal_preview) {
// Make sure we have gho specific classes available during internal
// previews, e.g. in the paragraph selection form.
$block_attributes['class'] = array_merge($block_attributes['class'], $gho_classes);
}
if (!$internal_preview && $this->isPromoted()) {
// Mark the paragraph as being promoted if not in internal preview.
$block_attributes['class'][] = self::PROMOTED_CLASS;
}
if (!$this->isPromoted()) {
// If the paragraph is not be promoted, make sure to remove the
// respective class from both the block classes and the wrapper.
$block_attributes['class'] = array_diff($block_attributes['class'] ?? [], [self::PROMOTED_CLASS]);
$wrapper_attributes['class'] = array_diff($wrapper_attributes['class'] ?? [], [self::PROMOTED_CLASS]);
}
// See if this paragraph should render as a full-width block.
$full_width_paragraph = in_array($paragraph->getType(), $full_width_paragraph_types);
$full_width = $full_width_paragraph || $this->isPromoted();
$build = [
'#type' => 'container',
'#title' => $title,
'#attributes' => [
'data-paragraph-id' => $paragraph->getId(),
] + $block_attributes,
'content' => [
[
'#type' => 'markup',
'#markup' => Markup::create($rendered),
'#view_mode' => 'full',
],
],
'#wrapper_attributes' => $wrapper_attributes,
'#full_width' => $full_width,
];
if ($this->moduleHandler->moduleExists('gho_footnotes')) {
// Make sure to add the gho-footnotes component.
$theme_components[] = 'common_design_subtheme/gho-footnotes';
if ($preview || $internal_preview) {
$build['content']['#post_render'][] = [
static::class,
'preparePreviewParagraph',
];
}
}
$build['content']['#attached'] = [
'library' => $theme_components,
];
if (!$internal_preview && $this->canLinkToArticlePage()) {
$article_node = $this->getArticlePage();
$link = $article_node->toLink($this->t('Read more'));
$link->getUrl()->setOptions([
'attributes' => [
'class' => ['cd-button', 'read-more'],
],
]);
// We need to embed the link inside a container, because we need a block
// level element to which we can apply the content-width class.
$build['content'][] = [
'#type' => 'container',
'#attributes' => [
'class' => ['content-width'],
],
0 => $link->toRenderable(),
];
}
if ($this->shouldLinkToArticlePage() && $article_node = $this->getArticlePage()) {
$build['#cache'] = [
'tags' => $article_node->getCacheTags(),
];
}
return $build;
}
/**
* Get the required theme components for the given paragraph.
*
* @param \Drupal\ghi_content\RemoteContent\RemoteParagraphInterface $paragraph
* The paragraph for which theme components should be fetched.
*
* @return array
* An array of library keys.
*/
public function getThemeComponents(RemoteParagraphInterface $paragraph) {
$theme_components = [];
$theme_components[] = 'common_design_subtheme/gho-' . Html::getClass($paragraph->getType());
if ($paragraph->getType() == 'bottom_figure_row') {
$theme_components[] = 'common_design_subtheme/gho-needs-and-requirements';
$theme_components[] = 'ghi_content/bottom_figures.tooltips';
}
if ($paragraph->getPromoted() || $this->isPromoted()) {
$theme_components[] = 'common_design_subtheme/gho-promoted-paragraph';
}
if ($paragraph->getType() == 'story') {
// Stories always use the gho-aside component.
$theme_components[] = 'common_design_subtheme/gho-aside';
}
if ($paragraph->getType() == 'interactive_content_2_columns') {
// Interactive content in 2 columns still needs styles.
$theme_components[] = 'common_design_subtheme/gho-interactive-content';
}
if ($paragraph->getType() == 'sub_article') {
// Find the paragraph types used in the sub article and add the
// components for those too.
$matches = [];
preg_match_all('/paragraph--type--((\w|-)*)/', $paragraph->getRendered(), $matches);
$types = !empty($matches[1]) ? array_unique($matches[1]) : [];
foreach ($types as $type) {
$theme_components[] = 'common_design_subtheme/gho-' . $type;
if ($type == 'bottom-figure-row') {
$theme_components[] = 'common_design_subtheme/gho-needs-and-requirements';
$theme_components[] = 'ghi_content/bottom_figures.tooltips';
}
}
$matches = [];
preg_match_all('/gho-paragraph-promoted/', $paragraph->getRendered(), $matches);
if (!empty($matches)) {
$theme_components[] = 'common_design_subtheme/gho-promoted-paragraph';
}
}
return $theme_components;
}
/**
* Returns generic default configuration for block plugins.
*
* @return array
* An associative array with the default configuration.
*/
protected function getConfigurationDefaults() {
return [
'article_select' => [
'article' => [
'remote_source' => NULL,
'article_id' => NULL,
],
],
'paragraph' => [
'paragraph_id' => NULL,
'label' => NULL,
'link_to_article' => FALSE,
'promoted' => FALSE,
],
];
}
/**
* {@inheritdoc}
*/
public function getDefaultSubform($is_new = FALSE) {
if (!$this->getArticle()) {
return 'article_select';
}
return 'paragraph';
}
/**
* {@inheritdoc}
*/
public function canShowSubform(array $form, FormStateInterface $form_state, $subform_key) {
if ($subform_key == 'paragraph') {
return $this->getArticle() && $this->getArticle() instanceof RemoteArticleInterface;
}
return !$this->lockArticle();
}
/**
* Select article form.
*/
public function articleSelectForm(array $form, FormStateInterface $form_state) {
$form['article'] = [
'#type' => 'remote_article',
'#default_value' => $this->getArticle(),
'#required' => TRUE,
];
$form['select_article'] = [
'#type' => 'submit',
'#value' => $this->t('Select this article'),
'#element_submit' => [get_class($this) . '::ajaxMultiStepSubmit'],
'#ajax' => [
'callback' => [$this, 'navigateFormStep'],
'wrapper' => $this->getContainerWrapper(),
'effect' => 'fade',
'method' => 'replace',
'parents' => ['settings', 'container'],
],
'#next_step' => 'paragraph',
];
return $form;
}
/**
* Paragraph config form.
*/
public function paragraphForm(array $form, FormStateInterface $form_state) {
$article = $this->getArticle();
$paragraph = $this->getParagraph();
$form['article_summary'] = [
'#type' => 'item',
'#title' => $this->lockArticle() ? $this->t('Article (locked)') : $this->t('Selected article'),
'#markup' => $article->getSource()->getPluginLabel() . ': ' . $article->getTitle(),
'#weight' => -2,
];
$form['label']['#weight'] = -1;
$form['link_to_article'] = [
'#type' => 'checkbox',
'#title' => $this->t('Add a link to the article page.'),
'#description' => $this->t('The link will only be added if the article page exists and is accessible to the user.'),
'#default_value' => $this->getDefaultFormValueFromFormState($form_state, 'link_to_article'),
'#access' => !$this->displayedOnArticlePage(),
];
$form['promoted'] = [
'#type' => 'checkbox',
'#title' => $this->t('Mark as promoted.'),
'#description' => $this->t('Mark the paragraph as promoted, which will make it visually highlighted.'),
'#default_value' => $this->getDefaultFormValueFromFormState($form_state, 'promoted'),
'#access' => !$this->displayedOnArticlePage(),
];
$options = [];
$theme_components = [];
foreach ($article->getParagraphs() as $_paragraph) {
// We need to fully prerender the paragraph so that things like footnotes
// are handled correctly.
$build = $this->buildParagraph($_paragraph, NULL, TRUE, TRUE);
$options[$_paragraph->getId()] = $this->renderer->render($build);
$theme_components += array_merge($theme_components, $this->getThemeComponents($_paragraph));
}
$form['paragraph_id'] = [
'#type' => 'markup_select',
'#title' => $this->t('Paragraph'),
'#description' => $this->t('Select a paragraph from the article.'),
'#options' => $options,
'#limit' => 1,
'#cols' => 3,
'#default_value' => $paragraph ? $paragraph->getId() : NULL,
'#attached' => [
'library' => array_unique($theme_components),
],
];
return $form;
}
/**
* Get the configured article.
*
* @return \Drupal\ghi_content\RemoteContent\RemoteArticleInterface
* The remote article.
*/
public function getArticle() {
$conf = $this->getBlockConfig();
$remote_source_key = $conf['article_select']['article']['remote_source'] ?? NULL;
if (!$remote_source_key) {
return NULL;
}
/** @var \Drupal\ghi_content\RemoteSource\RemoteSourceManager $remote_source_manager */
$remote_source_manager = \Drupal::service('plugin.manager.remote_source');
/** @var \Drupal\ghi_content\RemoteSource\RemoteSourceInterface $remote_source */
$remote_source = $remote_source_manager->createInstance($remote_source_key);
$article_id = $conf['article_select']['article']['article_id'] ?? NULL;
if (!$remote_source || !$article_id) {
return NULL;
}
return $remote_source->getArticle($article_id);
}
/**
* Get the configured paragraph from the article.
*
* @return \Drupal\ghi_content\RemoteContent\RemoteParagraphInterface|null
* A paragraph object as retrieved from the article.
*/
private function getParagraph() {
$article = $this->getArticle();
$conf = $this->getBlockConfig();
if (!$article || empty($conf['paragraph']['paragraph_id'])) {
return;
}
// Make sure we have an array, as this is the way that the markup_select
// form element provides it's value.
$paragraph_id = (array) $conf['paragraph']['paragraph_id'];
return $article->getParagraph(reset($paragraph_id));
}
/**
* Check if the article is locked for this paragraph element.
*
* The article for a paragraph is locked if there is an article set and if
* additionally the lock_article flag is set in the configuration.
*
* @return bool
* TRUE if the article is locked, FALSE otherwise.
*/
public function lockArticle() {
return $this->getArticle() && !empty($this->configuration['lock_article']);
}
/**
* Get the article page associated to the configured source article.
*
* @return \Drupal\node\NodeInterface|null
* A node object.s
*/
private function getArticlePage() {
$article = $this->getArticle();
if (!$article) {
return NULL;
}
return $this->articleManager->loadNodeForRemoteContent($article);
}
/**
* See if a paragraph block should have a "Read more" link.
*
* @return bool
* TRUE if the article page should be linked to, FALSE otherwhise.
*/
private function shouldLinkToArticlePage() {
$conf = $this->getBlockConfig();
return !empty($conf['paragraph']['link_to_article']);
}
/**
* See if a paragraph block can have a "Read more" link.
*
* This depends on configuration (whether the paragraph should have a link)
* and the publication status of the linked article.
*
* @return bool
* TRUE if the article page can be linked to, FALSE otherwhise.
*/
private function canLinkToArticlePage() {
if (!$this->shouldLinkToArticlePage()) {
return FALSE;
}
$article_node = $this->getArticlePage();
if (!$article_node || !$article_node->access('view')) {
return FALSE;
}
return !$this->displayedOnArticlePage();
}
/**
* See if the paragraph is promoted.
*
* @return bool
* TRUE if promoted, FALSE otherwise.
*/
private function isPromoted() {
// Display paragraph on its article page.
if ($this->displayedOnArticlePage()) {
$paragraph = $this->getParagraph();
return $paragraph && $paragraph->getPromoted();
}
else {
// Outside the article page, we rely on what is configured.
$conf = $this->getBlockConfig();
return !empty($conf['paragraph']['promoted']);
}
}
/**
* See if the paragraph is displayed on the article page where it originates.
*
* @return bool
* TRUE if displayed on its article page, FALSE otherwise.
*/
private function displayedOnArticlePage() {
$page_node = $this->getPageNode();
$article_page = $this->getArticlePage();
if (!$page_node || !$article_page) {
return FALSE;
}
return $article_page->id() == $page_node->id();
}
/**
* {@inheritdoc}
*/
public static function trustedCallbacks() {
return [
'preparePreviewParagraph',
];
}
/**
* Post render function to prepare a paragraph for display.
*
* In preview, we need to call GhoFootnotes::updateFootnotes, so that
* footnotes inside each paragraph are processed inidividually, thus turning
* the custom gho footnote markup into little jump links, assuring a frontend
* rendering that equals the output on a fully rendered page.
* We also need to wrap that into logic for temporarily disabling theme
* debug, because the file suggestion HTML comments might create file
* suggestions containing double-hyphens, which are not allowed in XML
* comments and prevent the dom related logic in
* GhoFootnotes::updateFootnotes from working correctly.
*
* In GHI the problem is introduced by the Gin Layout Builder module, which
* alters file suggestions in gin_lb_theme_suggestions_alter() for some
* routes, particularily the block remove route.
*
* We could have made modifications directly in GhoFootnotes, but because the
* gho_footnotes module is a straight copy from the GHO project, it's better
* to handle this here and leave the module untouched so that we can easier
* keep both versions in sync.
*/
public static function preparePreviewParagraph($html, $build) {
/** @var \Twig\Environment $twig_service */
$twig_service = \Drupal::service('twig');
$twig_debug = $twig_service->isDebug();
if ($twig_debug) {
$twig_service->disableDebug();
}
$html = GhoFootnotes::updateFootnotes($html, $build);
if ($twig_debug) {
$twig_service->enableDebug();
}
return $html;
}
}