-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathServerSideRendering.php
1052 lines (926 loc) · 38.4 KB
/
ServerSideRendering.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
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
namespace AmpProject\Optimizer\Transformer;
use AmpProject\Amp;
use AmpProject\Html\Attribute;
use AmpProject\CssLength;
use AmpProject\Dom\Document;
use AmpProject\Dom\Element;
use AmpProject\Exception\MaxCssByteCountExceeded;
use AmpProject\Extension;
use AmpProject\Layout;
use AmpProject\Optimizer\CssRule;
use AmpProject\Optimizer\CssRules;
use AmpProject\Optimizer\Error;
use AmpProject\Optimizer\ErrorCollection;
use AmpProject\Optimizer\Exception\InvalidArgument;
use AmpProject\Optimizer\Exception\InvalidHtmlAttribute;
use AmpProject\Optimizer\Transformer;
use AmpProject\Html\Role;
use AmpProject\Html\Tag;
use DOMAttr;
use Exception;
/**
* Transformer applying the server-side rendering transformations to the HTML input.
*
* This is ported from the NodeJS optimizer while verifying against the Go version.
*
* NodeJS:
* @version c92d6023ea4c9edadff593742a992da2b400a75d
* @link https://github.com/ampproject/amp-toolbox/blob/c92d6023ea4c9edadff593742a992da2b400a75d/packages/optimizer/lib/transformers/ServerSideRendering.js
*
* Go:
* @version ea0959046c179953de43077eafaeb720f9b20bdf
* @link https://github.com/ampproject/amppackager/blob/ea0959046c179953de43077eafaeb720f9b20bdf/transformer/transformers/transformedidentifier.go
*
* @package ampproject/amp-toolbox
*/
final class ServerSideRendering implements Transformer
{
/**
* List of layouts that support server-side rendering.
*
* @var string[]
*/
const SUPPORTED_LAYOUTS = [
'',
Layout::NODISPLAY,
Layout::FIXED,
Layout::FIXED_HEIGHT,
Layout::RESPONSIVE,
Layout::CONTAINER,
Layout::FILL,
Layout::FLEX_ITEM,
Layout::FLUID,
Layout::INTRINSIC,
];
/**
* List of elements to exclude from rendering their layout at the server.
*
* @var string[]
*/
const EXCLUDED_ELEMENTS = [
'amp-audio',
];
/**
* Regex pattern to match a CSS Dimension with an associated media condition.
*
* @var string
*/
const CSS_DIMENSION_WITH_MEDIA_CONDITION_REGEX_PATTERN = '/\s*(?<media_condition>\(.*\))\s+(?<dimension>.*)\s*/m';
/**
* Smallest acceptable difference in floating point comparisons.
*
* @var float
*/
const FLOATING_POINT_EPSILON = 0.00001;
/**
* Associative array of custom sizer styles where the key is the ID of the associated element.
*
* @var string[]
*/
private $customSizerStyles = [];
/**
* Custom CSS rules that were extracted to remove blocking attributes.
*
* @var CssRules
*/
private $customCss;
/**
* Apply transformations to the provided DOM document.
*
* @param Document $document DOM document to apply the transformations to.
* @param ErrorCollection $errors Collection of errors that are collected during transformation.
* @return void
*/
public function transform(Document $document, ErrorCollection $errors)
{
if ($this->isAlreadyTransformed($document)) {
return;
}
// Reset internal state for a new transform.
$this->customCss = new CssRules();
/*
* Within the loop we apply the layout to the custom tags (amp-foo...) where possible, but while we're at this
* we also look for reasons not to remove the boilerplate.
*/
$canRemoveBoilerplate = true;
foreach ($document->ampElements as $ampElement) {
// Make sure we only deal with valid elements.
if (! $ampElement instanceof Element) {
continue;
}
// Skip tags inside a template tag.
if ($this->isWithinTemplate($ampElement)) {
continue;
}
/*
* amp-experiment is a render delaying extension iff the tag is used in the doc. We check for that here
* rather than checking for the existence of the amp-experiment script in IsRenderDelayingExtension below.
*/
if ($ampElement->tagName === Extension::EXPERIMENT && $this->isAmpExperimentUsed($ampElement)) {
$errors->add(Error\CannotRemoveBoilerplate::fromAmpExperiment($ampElement));
$canRemoveBoilerplate = false;
}
/*
* amp-audio requires knowing the dimensions of the browser. Do not remove the boilerplate or apply layout
* if amp-audio is present in the document.
*/
if ($ampElement->tagName === Extension::AUDIO) {
$errors->add(Error\CannotRemoveBoilerplate::fromAmpAudio($ampElement));
$canRemoveBoilerplate = false;
}
/*
* Try to adapt 'sizes', 'heights' and 'media' attribute to turn them from blocking attributes into
* CSS styles we add to <style amp-custom>.
*/
$attributesToRemove = $this->adaptBlockingAttributes($document, $ampElement, $errors);
if ($attributesToRemove === false) {
$canRemoveBoilerplate = false;
}
/*
* Now apply the layout to the custom elements. If we encounter any unsupported layout, the applyLayout()
* method returns false and we can't remove the boilerplate.
*/
$adaptedElement = $this->applyLayout($document, $ampElement, $errors);
if ($adaptedElement === false) {
$errors->add(Error\CannotRemoveBoilerplate::fromUnsupportedLayout($ampElement));
$canRemoveBoilerplate = false;
}
// Removal of attributes is deferred as layout application needs them.
if (is_array($attributesToRemove)) {
foreach ($attributesToRemove as $attributeToRemove) {
$adaptedElement->removeAttribute($attributeToRemove);
}
}
}
$this->renderCustomCss($document);
// Emit the amp-runtime marker to indicate that we're applying server side rendering in the document.
$ampRuntimeMarker = $document->createElement(Tag::STYLE);
$ampRuntimeMarker->setAttribute(Attribute::AMP_RUNTIME, '');
$document->head->insertBefore(
$ampRuntimeMarker,
$document->head->hasChildNodes()
? $document->head->firstChild
: null
);
foreach ($document->xpath->query('.//script[ @custom-element ]', $document->head) as $customElementScript) {
/** @var Element $customElementScript */
// amp-experiment is a render delaying extension iff the tag is used in the doc, which we checked for above.
if (
$customElementScript->getAttribute(Attribute::CUSTOM_ELEMENT) !== Extension::EXPERIMENT
&& Amp::isRenderDelayingExtension($customElementScript)
) {
$errors->add(Error\CannotRemoveBoilerplate::fromRenderDelayingScript($customElementScript));
$canRemoveBoilerplate = false;
}
}
/*
* Below, we're only concerned about removing the boilerplate.
* If we've already determined that we can't, we're done here.
*/
if (! $canRemoveBoilerplate) {
return;
}
// The boilerplate can be removed, note it on the <html> tag.
$document->html->setAttribute(Amp::NO_BOILERPLATE_ATTRIBUTE, '');
/*
* Find the boilerplate and remove it.
* The following code assumes that the <noscript> tag in the head is only ever used for boilerplate.
*/
foreach ($document->xpath->query('.//noscript', $document->head) as $noscriptTagInHead) {
/** @var Element $noscriptTagInHead */
$noscriptTagInHead->parentNode->removeChild($noscriptTagInHead);
}
$boilerplateStyleTags = $document->xpath->query(
'.//style[ @amp-boilerplate or @amp4ads-boilerplate or @amp4email-boilerplate ]',
$document->head
);
foreach ($boilerplateStyleTags as $boilerplateStyleTag) {
/** @var Element $boilerplateStyleTag */
$boilerplateStyleTag->parentNode->removeChild($boilerplateStyleTag);
}
}
/**
* Check whether the document was already transformed.
*
* We want to ensure we don't apply server-side rendering modifications more than once.
*
* @param Document $document DOM document to apply the transformations to.
* @return bool Whether the document was already transformed.
*/
private function isAlreadyTransformed(Document $document)
{
if ($document->html->hasAttribute(Amp::LAYOUT_ATTRIBUTE)) {
return true;
}
// Mark the document as "already transformed".
$document->html->setAttribute(Amp::LAYOUT_ATTRIBUTE, '');
return false;
}
/**
* Apply the adequate layout to a custom element.
*
* @param Document $document DOM document to apply the transformations to.
* @param Element $element Element to apply the layout to.
* @param ErrorCollection $errors Collection of errors that are collected during transformation.
* @return Element|false Adapted element, or false if the layout could not be applied.
*/
private function applyLayout(Document $document, Element $element, ErrorCollection $errors)
{
$ampLayout = $this->parseLayout($element->getAttribute(Attribute::LAYOUT));
$attrWidth = $element->hasAttribute(Attribute::WIDTH) ? $element->getAttribute(Attribute::WIDTH) : null;
$inputWidth = new CssLength($attrWidth);
$inputWidth->validate(/* $allowAuto */ true, /* $allowFluid */ false);
if (! $inputWidth->isValid()) {
$errors->add(Error\CannotPerformServerSideRendering::fromInvalidInputWidth($element));
return false;
}
$attrHeight = $element->hasAttribute(Attribute::HEIGHT) ? $element->getAttribute(Attribute::HEIGHT) : null;
$inputHeight = new CssLength($attrHeight);
$inputHeight->validate(/* $allowAuto */ true, /* $allowFluid */ $ampLayout === Layout::FLUID);
if (! $inputHeight->isValid()) {
$errors->add(Error\CannotPerformServerSideRendering::fromInvalidInputHeight($element));
return false;
}
// Calculate effective width, height and layout.
$width = $this->calculateWidth($ampLayout, $inputWidth, $element->tagName);
$height = $this->calculateHeight($ampLayout, $inputHeight, $element->tagName);
$layout = $this->calculateLayout(
$ampLayout,
$width,
$height,
$element->getAttribute(Attribute::SIZES),
$element->getAttribute(Attribute::HEIGHTS)
);
if (! $this->isSupportedLayout($layout)) {
$errors->add(Error\CannotPerformServerSideRendering::fromUnsupportedLayout($element, $layout));
return false;
}
try {
/** @var Element $newElement */
$newElement = $element->cloneNode(false);
// Transformed AMP validation requires layout attribute to be set.
// See https://github.com/ampproject/amp-toolbox/issues/959.
if ($layout && $layout === Layout::RESPONSIVE) {
$newElement->setAttribute(Attribute::LAYOUT, $layout);
}
$this->applyLayoutAttributes($newElement, $layout, $width, $height);
$this->maybeAddSizerInto($document, $newElement, $layout, $width, $height);
$element->parentNode->replaceChild($newElement, $element);
while ($element->firstChild) {
$newElement->appendChild($element->removeChild($element->firstChild));
}
} catch (MaxCssByteCountExceeded $exception) {
$errors->add(
Error\CannotPerformServerSideRendering::fromMaxCssByteCountExceededException($exception, $element)
);
return false;
}
return $newElement;
}
/**
* Parse the layout attribute value.
*
* @param string $layout Layout attribute value.
* @return string Validated AMP layout, or empty string if none.
*/
private function parseLayout($layout)
{
if (empty($layout)) {
return '';
}
$layout = strtolower($layout);
if (array_key_exists($layout, Layout::TO_SPEC)) {
return $layout;
}
return '';
}
/**
* Calculate the width of an element for its requested layout.
*
* @param string $inputLayout Requested layout.
* @param CssLength $inputWidth Input value for the width.
* @param string $tagName Tag name of the element.
* @return CssLength Calculated Width.
*/
private function calculateWidth($inputLayout, CssLength $inputWidth, $tagName)
{
if ((empty($inputLayout) || $inputLayout === Layout::FIXED) && ! $inputWidth->isDefined()) {
// These values come from AMP's runtime and can be found in
// https://github.com/ampproject/amphtml/blob/292dc66b8c0bb078bbe3a1bca960e8f494f7fc8f/src/layout.js#L70-L86.
switch ($tagName) {
case Extension::ANALYTICS:
case Extension::PIXEL:
$width = new CssLength('1px');
$width->validate(/* $allowAuto */ false, /* $allowFluid */ false);
return $width;
case Extension::AUDIO:
$width = new CssLength(CssLength::AUTO);
$width->validate(/* $allowAuto */ true, /* $allowFluid */ false);
return $width;
case Extension::SOCIAL_SHARE:
$width = new CssLength('60px');
$width->validate(/* $allowAuto */ false, /* $allowFluid */ false);
return $width;
}
}
return $inputWidth;
}
/**
* Calculate the height of an element for its requested layout.
*
* @param string $inputLayout Requested layout.
* @param CssLength $inputHeight Input value for the height.
* @param string $tagName Tag name of the element.
* @return CssLength Calculated Height.
*/
private function calculateHeight($inputLayout, CssLength $inputHeight, $tagName)
{
if (
(
empty($inputLayout)
|| $inputLayout === Layout::FIXED
|| $inputLayout === Layout::FIXED_HEIGHT
) && ! $inputHeight->isDefined()
) {
// These values come from AMP's runtime and can be found in
// https://github.com/ampproject/amphtml/blob/292dc66b8c0bb078bbe3a1bca960e8f494f7fc8f/src/layout.js#L70-L86.
switch ($tagName) {
case Extension::ANALYTICS:
case Extension::PIXEL:
$height = new CssLength('1px');
$height->validate(/* $allowAuto */ false, /* $allowFluid */ false);
return $height;
case Extension::AUDIO:
$height = new CssLength(CssLength::AUTO);
$height->validate(/* $allowAuto */ true, /* $allowFluid */ false);
return $height;
case Extension::SOCIAL_SHARE:
$height = new CssLength('44px');
$height->validate(/* $allowAuto */ false, /* $allowFluid */ false);
return $height;
}
}
return $inputHeight;
}
/**
* Calculate the final AMP layout attribute for an element.
*
* @param string $inputLayout Requested layout.
* @param CssLength $width Calculated width.
* @param CssLength $height Calculated height.
* @param string $sizesAttr Sizes attribute value.
* @param string $heightsAttr Heights attribute value.
* @return string Calculated layout.
*/
private function calculateLayout(
$inputLayout,
CssLength $width,
CssLength $height,
$sizesAttr,
$heightsAttr
) {
if (! empty($inputLayout)) {
return $inputLayout;
}
if (! $width->isDefined() && ! $height->isDefined()) {
return Layout::CONTAINER;
}
if ($height->isDefined() && (! $width->isDefined() || $width->isAuto())) {
return Layout::FIXED_HEIGHT;
}
if ($height->isDefined() && $width->isDefined() && (! empty($sizesAttr) || ! empty($heightsAttr))) {
return Layout::RESPONSIVE;
}
return Layout::FIXED;
}
/**
* Check whether a layout is support for SSR.
*
* @param string $layout Layout to check.
* @return bool Whether the layout is supported for SSR.
*/
private function isSupportedLayout($layout)
{
return in_array($layout, self::SUPPORTED_LAYOUTS, true);
}
/**
* Apply the calculated layout attributes to an element.
*
* @param Element $element Element to apply the layout attributes to.
* @param string $layout Final layout.
* @param CssLength $width Calculated width.
* @param CssLength $height Calculated height.
*/
private function applyLayoutAttributes(Element $element, $layout, CssLength $width, CssLength $height)
{
if ($this->isExcludedElement($element)) {
return;
}
$this->addClass($element, $this->getLayoutClass($layout));
if ($this->isLayoutSizeDefined($layout)) {
$this->addClass($element, Amp::LAYOUT_SIZE_DEFINED_CLASS);
}
$styles = '';
switch ($layout) {
case Layout::NODISPLAY:
$element->setAttribute(Attribute::HIDDEN, Attribute::HIDDEN);
break;
case Layout::FIXED:
$styles = "width:{$width->getNumeral()}{$width->getUnit()};"
. "height:{$height->getNumeral()}{$height->getUnit()};";
break;
case Layout::FIXED_HEIGHT:
$styles = "height:{$height->getNumeral()}{$height->getUnit()};";
break;
case Layout::RESPONSIVE:
case Layout::INTRINSIC:
// Do nothing here but emit <i-amphtml-sizer> later.
break;
case Layout::FILL:
case Layout::CONTAINER:
// Do nothing here.
break;
case Layout::FLUID:
$styles = 'width:100%;height:0;';
$this->addClass($element, Amp::LAYOUT_AWAITING_SIZE_CLASS);
break;
case Layout::FLEX_ITEM:
if ($width->isDefined()) {
$styles = "width:{$width->getNumeral()}{$width->getUnit()};";
}
if ($height->isDefined()) {
$styles .= "height:{$height->getNumeral()}{$height->getUnit()};";
}
break;
}
if (!empty($styles)) {
$element->addInlineStyle($styles);
}
$element->setAttribute(Amp::LAYOUT_ATTRIBUTE, $layout);
}
/**
* Get the class to use for a given layout.
*
* @param string $layout Layout to get the class for.
* @return string Class name to use for the layout.
*/
private function getLayoutClass($layout)
{
if (empty($layout)) {
return '';
}
return Amp::LAYOUT_CLASS_PREFIX . $layout;
}
/**
* Add a class to an element.
*
* This makes sure we keep existing classes on the element.
*
* @param Element $element Element to add a class to.
* @param string $class Class to add.
*/
private function addClass(Element $element, $class)
{
if ($element->hasAttribute(Attribute::CLASS_) && ! empty($element->getAttribute(Attribute::CLASS_))) {
$class = "{$element->getAttribute(Attribute::CLASS_)} {$class}";
}
$element->setAttribute(Attribute::CLASS_, $class);
}
/**
* Check whether the provided layout is a layout with a defined size.
*
* @param string $layout Layout to check.
* @return bool Whether the layout has a defined size.
*/
private function isLayoutSizeDefined($layout)
{
return in_array($layout, Layout::SIZE_DEFINED_LAYOUTS, true);
}
/**
* Insert a sizer element if one is required.
*
* @param Document $document DOM document to add a sizer to.
* @param Element $element Element to add a sizer to.
* @param string $layout Calculated layout of the element.
* @param CssLength $width Calculated width of the element.
* @param CssLength $height Calculated height of the element.
*/
private function maybeAddSizerInto(
Document $document,
Element $element,
$layout,
CssLength $width,
CssLength $height
) {
if (
! $width->isDefined()
|| $this->isZero($width->getNumeral())
|| ! $height->isDefined()
|| $width->getUnit() !== $height->getUnit()
) {
return;
}
$sizer = null;
if ($layout === Layout::RESPONSIVE) {
$elementId = $element->getAttribute(Attribute::ID);
if (!empty($elementId) && array_key_exists($elementId, $this->customSizerStyles)) {
$sizer = $this->createResponsiveSizer($document, $width, $height, $this->customSizerStyles[$elementId]);
} else {
$sizer = $this->createResponsiveSizer($document, $width, $height);
}
} elseif ($layout === Layout::INTRINSIC) {
$sizer = $this->createIntrinsicSizer($document, $width, $height);
}
if ($sizer) {
$element->insertBefore($sizer, $element->firstChild);
}
}
/**
* Create a sizer element for a responsive layout.
*
* @param Document $document DOM document to create the sizer for.
* @param CssLength $width Calculated width of the element.
* @param CssLength $height Calculated height of the element.
* @param string $style Style to use for the sizer. Defaults to padding-top in percentage.
* @return Element
*/
private function createResponsiveSizer(
Document $document,
CssLength $width,
CssLength $height,
$style = 'padding-top:%s%%'
) {
$padding = $height->getNumeral() / $width->getNumeral() * 100;
$paddingString = rtrim(rtrim(sprintf('%.4F', round($padding, 4)), '0'), '.');
$style = empty($style) ? 'display:block' : "display:block;{$style}";
$sizer = $document->createElement(Amp::SIZER_ELEMENT);
$sizer->setAttribute(Attribute::SLOT, Amp::SERVICE_SLOT);
$sizer->addInlineStyle(sprintf($style, $paddingString));
return $sizer;
}
/**
* Create a sizer element for an intrinsic layout.
*
* Intrinsic uses an svg inside the sizer element rather than the padding trick.
* Note: a naked svg won't work because other things expect the i-amphtml-sizer element.
*
* @param Document $document DOM document to create the sizer for.
* @param CssLength $width Calculated width of the element.
* @param CssLength $height Calculated height of the element.
* @return Element
*/
private function createIntrinsicSizer(Document $document, CssLength $width, CssLength $height)
{
$sizer = $document->createElement(Amp::SIZER_ELEMENT);
$sizer->setAttribute(Attribute::SLOT, Amp::SERVICE_SLOT);
$sizer->setAttribute(Attribute::CLASS_, Amp::SIZER_ELEMENT);
$sizer_img = $document->createElement(Tag::IMG);
$sizer_img->setAttribute(Attribute::ALT, '');
$sizer_img->setAttribute(Attribute::ARIA_HIDDEN, 'true');
$sizer_img->setAttribute(Attribute::CLASS_, Amp::INTRINSIC_SIZER_ELEMENT);
$sizer_img->setAttribute(Attribute::ROLE, Role::PRESENTATION);
$sizer_img->setAttribute(
Attribute::SRC,
sprintf(
'data:image/svg+xml;base64,%s',
base64_encode("<svg height=\"{$height->getNumeral()}\" width=\"{$width->getNumeral()}\" "
. "xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"/>")
)
);
$sizer->appendChild($sizer_img);
return $sizer;
}
/**
* Check whether the element is within a template.
*
* @param Element $element Element to check.
* @return bool Whether the element is within a template.
*/
private function isWithinTemplate(Element $element)
{
$parent = $element->parentNode;
while ($parent !== null) {
if ($parent instanceof Element) {
if ($parent->tagName === Tag::TEMPLATE) {
return true;
}
if ($parent->tagName === Tag::SCRIPT && $parent->hasAttribute(Attribute::TEMPLATE)) {
return true;
}
}
$parent = $parent->parentNode;
}
return false;
}
/**
* Check if the amp-experiment element is actually used.
*
* This checks if amp-experiment has one child that is a script/json tag with a textnode that is parsable JSON and
* not empty. The validator ensures that the script/json is parsable but since transformers may be used outside of
* validation it is checked here as well.
*
* @param Element $element Element to check.
* @return bool Whether the amp-experiment element is actually used.
*/
private function isAmpExperimentUsed(Element $element)
{
$script = null;
$child = $element->firstChild;
while ($child) {
if (
$child instanceof Element
&& $child->tagName === Tag::SCRIPT
&& strtolower($child->getAttribute(Attribute::TYPE)) === Attribute::TYPE_JSON
) {
$script = $child;
break;
}
$child = $child->nextSibling;
}
// If not script/json tag, then not used.
if ($script === null) {
return false;
}
// If not exactly one child is present, then not used.
if ($script->childNodes->length !== 1) {
return false;
}
$child = $script->firstChild;
// If child is not a text node or CDATA section, then not used.
if ($child->nodeType !== XML_TEXT_NODE && $child->nodeType !== XML_CDATA_SECTION_NODE) {
return false;
}
$json = $child->textContent;
// If textnode is not JSON parsable, then not used.
$experiment = json_decode($json, /*$assoc*/ true);
if ($experiment === null) {
return false;
}
// If JSON is empty, then not used.
if (empty($experiment)) {
return false;
}
// Otherwise, used.
return true;
}
/**
* Adapt blocking attributes so that they allow for boilerplate removal.
*
* Blocking attributes that need special attention are `sizes`, `heights` and `media`.
*
* @see https://github.com/ampproject/amp-wp/issues/4439
*
* @param Document $document DOM document to apply the transformations to.
* @param Element $ampElement Element to adapt.
* @param ErrorCollection $errors Collection of errors that are collected during transformation.
* @return string[]|false Attribute names to remove, or false if attributes could not be adapted.
*/
private function adaptBlockingAttributes(Document $document, Element $ampElement, ErrorCollection $errors)
{
$attributes = $ampElement->attributes;
$customCss = [];
$attributesToRemove = [];
foreach ($attributes as $attribute) {
/**
* Attribute to check.
*
* @var DOMAttr $attribute
*/
$normalizedAttributeName = strtolower($attribute->name);
try {
switch ($normalizedAttributeName) {
case Attribute::SIZES:
if ($ampElement->hasAttribute(Attribute::DISABLE_INLINE_WIDTH)) {
// Don't remove sizes when disable-inline-width is set.
// @see https://github.com/ampproject/amphtml/pull/27083.
break;
}
$customCss = array_merge(
$customCss,
$this->extractSizesAttributeCss($document, $ampElement, $attribute)
);
$attributesToRemove[] = $attribute->name;
break;
case Attribute::HEIGHTS:
$customCss = array_merge(
$customCss,
$this->extractHeightsAttributeCss($document, $ampElement, $attribute)
);
$attributesToRemove[] = $attribute->name;
break;
case Attribute::MEDIA:
$customCss = array_merge(
$customCss,
$this->extractMediaAttributeCss($document, $ampElement, $attribute)
);
$attributesToRemove[] = $attribute->name;
break;
}
} catch (Exception $exception) {
$errors->add(Error\CannotRemoveBoilerplate::fromAttributeThrowingException($exception));
return false;
}
}
foreach ($customCss as $cssRule) {
if ($document->getRemainingCustomCssSpace() < $cssRule->getByteCount()) {
$errors->add(Error\CannotRemoveBoilerplate::fromAttributesRequiringBoilerplate($ampElement));
return false;
}
$this->customCss = $this->customCss->add($cssRule);
}
return $attributesToRemove;
}
/**
* Render the custom CSS styling into the document.
*
* @param Document $document Document to add the custom CSS styling to.
*/
private function renderCustomCss(Document $document)
{
$customCss = $this->customCss->getCss();
if (empty($customCss)) {
return;
}
$document->addAmpCustomStyle($customCss);
}
/**
* Extract the custom CSS styling from a 'sizes' attribute.
*
* __sizes__
* "One or more strings separated by commas, indicating a set of source sizes. Each source size consists of:
* - A media condition. This must be omitted for the last item in the list.
* - A source size value."
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes
*
* @param Document $document Document containing the element to adapt.
* @param Element $element Element to adapt.
* @param DOMAttr $attribute Attribute to be extracted.
* @return CssRule[] Extract custom CSS styling.
*/
private function extractSizesAttributeCss(Document $document, Element $element, DOMAttr $attribute)
{
if (!$element->hasAttribute(Attribute::SRCSET) || empty($element->getAttribute(Attribute::SRCSET))) {
// According to the Mozilla docs, a sizes attribute without a valid srcset attribute should have no effect.
// Therefore, it should simply be stripped, without producing media queries.
// @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes.
return [];
}
return $this->extractAttributeCss(
$document,
$element,
$attribute,
['#__ID__', 'width:%s'],
['@media %s', '#__ID__', 'width:%s']
);
}
/**
* Extract the custom CSS styling from a 'heights' attribute.
*
* __heights__ (AMP-specific)
* "The value of this attribute is a sizes expression based on media expressions, similar to the sizes attribute on
* img tags but with two key differences:
* - The value applies to the height, not the width of the element.
* - Percent values are allowed. A percent value indicates the percent of the element's width. For example, a value
* of 80% indicates that the height of the element will be 80% of the element's width."
*
* @see https://amp.dev/documentation/guides-and-tutorials/learn/common_attributes/#heights
*
* @param Document $document Document containing the element to adapt.
* @param Element $element Element to adapt.
* @param DOMAttr $attribute Attribute to be extracted.
* @return CssRule[] Extract custom CSS styling.
*/
private function extractHeightsAttributeCss(Document $document, Element $element, DOMAttr $attribute)
{
// TODO: I'm not sure why I initially added this here, it looks very intentional.
// However, it doesn't match what the NodeJS version does, which is to add padding-top
// to the inline style of the element.
// phpcs:ignore Squiz.Commenting.InlineComment.InvalidEndChar
// $this->customSizerStyles[$document->getElementId($element)] = '';
return $this->extractAttributeCss(
$document,
$element,
$attribute,
['#__ID__>:first-child', 'padding-top:%s'],
['@media %s', '#__ID__>:first-child', 'padding-top:%s']
);
}
/**
* Extract the custom CSS styling from an attribute and turn into a templated CSS style string.
*
* @param Document $document Document containing the element to adapt.
* @param Element $element Element to adapt.
* @param DOMAttr $attribute Attribute to be extracted.
* @param string[] $mainStyle CSS rule template for the main style.
* @param string[] $mediaQueryStyle CSS rule template for a media query style.
* @return CssRule[] Array of CSS rules to use.
*/
private function extractAttributeCss(
Document $document,
Element $element,
DOMAttr $attribute,
$mainStyle,
$mediaQueryStyle
) {
if (empty($attribute->nodeValue)) {
return [];
}
$sourceSizes = explode(',', $attribute->nodeValue);
$lastItem = trim(array_pop($sourceSizes), CssRule::CSS_TRIM_CHARACTERS);
if (empty($lastItem)) {
throw InvalidHtmlAttribute::fromAttribute($attribute->nodeName, $element);
}
$cssRules = [];
$cssRules[] = new CssRule($mainStyle[0], sprintf($mainStyle[1], $lastItem));
foreach (array_reverse($sourceSizes) as $sourceSize) {
$matches = [];
if (!preg_match(self::CSS_DIMENSION_WITH_MEDIA_CONDITION_REGEX_PATTERN, $sourceSize, $matches)) {
throw InvalidHtmlAttribute::fromAttribute($attribute->nodeName, $element);
}
$mediaCondition = trim($matches['media_condition'], CssRule::CSS_TRIM_CHARACTERS);
if (empty($mediaCondition)) {
throw InvalidHtmlAttribute::fromAttribute($attribute->nodeName, $element);
}
$dimension = trim($matches['dimension'], CssRule::CSS_TRIM_CHARACTERS);
if (empty($dimension)) {
throw InvalidHtmlAttribute::fromAttribute($attribute->nodeName, $element);
}
$cssRules[] = CssRule::withMediaQuery(
sprintf($mediaQueryStyle[0], $mediaCondition),
$mediaQueryStyle[1],
sprintf($mediaQueryStyle[2], $dimension)
);
}
$elementId = $document->getElementId($element);
$cssRules = array_map(
static function (CssRule $cssRule) use ($elementId) {
return $cssRule->applyID($elementId);
},
$cssRules
);
return $cssRules;
}
/**
* Extract the custom CSS styling from a 'media' attribute.
*
* __media__
* "The value of media is a media query. If the query does not match, the element is not rendered and its resources
* and potentially its child resources will not be fetched. If the browser window changes size or orientation, the
* media queries are re-evaluated and elements are hidden and shown based on the new results."
*
* @param Document $document Document containing the element to adapt.
* @param Element $element Element to adapt.
* @param DOMAttr $attribute Attribute to be extracted.
* @return CssRule[] Extract custom CSS styling.
*/
private function extractMediaAttributeCss(Document $document, Element $element, DOMAttr $attribute)
{
$attributeValue = trim($attribute->nodeValue, CssRule::CSS_TRIM_CHARACTERS);
if (empty($attributeValue)) {