-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
consent-ui.js
924 lines (814 loc) · 26.6 KB
/
consent-ui.js
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
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Deferred} from '../../../src/utils/promise';
import {Services} from '../../../src/services';
import {assertHttpsUrl} from '../../../src/url';
import {dev, user} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {
elementByTag,
insertAtStart,
isAmpElement,
removeElement,
tryFocus,
whenUpgradedToCustomElement,
} from '../../../src/dom';
import {expandConsentEndpointUrl} from './consent-config';
import {getConsentStateValue} from './consent-info';
import {getData} from '../../../src/event-helper';
import {getServicePromiseForDoc} from '../../../src/service';
import {htmlFor} from '../../../src/static-template';
import {isExperimentOn} from '../../../src/experiments';
import {setImportantStyles, setStyles, toggle} from '../../../src/style';
const TAG = 'amp-consent-ui';
const CONSENT_STATE_MANAGER = 'consentStateManager';
const MINIMUM_INITIAL_HEIGHT = 10;
const DEFAULT_INITIAL_HEIGHT = 30;
const MODAL_HEIGHT_ENABLED = 60;
const MAX_INITIAL_HEIGHT = 80;
const DEFAULT_ENABLE_BORDER = true;
const FULLSCREEN_SUCCESS = 'Entering fullscreen.';
const FULLSCREEN_ERROR =
'Could not enter fullscreen. Fullscreen is only supported ' +
'when the iframe is visible as a bottom sheet and after ' +
'user interaction.';
const CONSENT_PROMPT_CAPTION = 'User Consent Prompt';
const BUTTON_ACTION_CAPTION = 'Focus Prompt';
const CANCEL_OVERLAY = 'cancelFullOverlay';
const REQUEST_OVERLAY = 'requestFullOverlay';
const IFRAME_RUNNING_TIMEOUT = 1000;
export const actionState = {
error: 'error',
success: 'success',
};
export const ampConsentMessageType = {
response: 'amp-consent-response',
};
// Classes for consent UI
export const consentUiClasses = {
iframeFullscreen: 'i-amphtml-consent-ui-iframe-fullscreen',
iframeActive: 'i-amphtml-consent-ui-iframe-active',
modal: 'i-amphtml-consent-ui-modal',
in: 'i-amphtml-consent-ui-in',
loading: 'i-amphtml-consent-ui-loading',
fill: 'i-amphtml-consent-ui-fill',
placeholder: 'i-amphtml-consent-ui-placeholder',
mask: 'i-amphtml-consent-ui-mask',
borderEnabled: 'i-amphtml-consent-ui-border-enabled',
screenReaderDialog: 'i-amphtml-consent-alertdialog',
iframeTransform: 'i-amphtml-consent-ui-iframe-transform',
};
export class ConsentUI {
/**
* @param {!AMP.BaseElement} baseInstance
* @param {!JsonObject} config
* @param {string=} opt_postPromptUI
*/
constructor(baseInstance, config, opt_postPromptUI) {
/** @private {!AMP.BaseElement} */
this.baseInstance_ = baseInstance;
/** @private {boolean} */
this.isCreatedIframe_ = false;
/** @private {boolean} */
this.isPostPrompt_ = false;
/** @private {boolean} */
this.isVisible_ = false;
/** @private {boolean} */
this.isIframeVisible_ = false;
/** @private {boolean} */
this.isFullscreen_ = false;
/** @private {?Element} */
this.ui_ = null;
/** @private {boolean} */
this.overlayEnabled_ =
config['uiConfig'] && config['uiConfig']['overlay'] === true;
/** @private {string} */
this.consentPromptCaption_ =
(config['captions'] && config['captions']['consentPromptCaption']) ||
CONSENT_PROMPT_CAPTION;
/** @private {string} */
this.buttonActionCaption_ =
(config['captions'] && config['captions']['buttonActionCaption']) ||
BUTTON_ACTION_CAPTION;
/** @private {boolean} */
this.srAlertShown_ = false;
/** @private {boolean} */
this.scrollEnabled_ = true;
/** @private {?Element} */
this.maskElement_ = null;
/** @private {?Element} */
this.srAlert_ = null;
/** @private {?Element} */
this.elementWithFocusBeforeShowing_ = null;
/** @private {!../../../src/service/ampdoc-impl.AmpDoc} */
this.ampdoc_ = baseInstance.getAmpDoc();
/** @private {!../../../src/service/viewport/viewport-interface.ViewportInterface} */
this.viewport_ = Services.viewportForDoc(this.ampdoc_);
/** @private {?../../../src/service/viewer-interface.ViewerInterface} */
this.viewer_ = Services.viewerForDoc(this.ampdoc_);
/** @private {!Element} */
this.parent_ = baseInstance.element;
/** @private {!Window} */
this.win_ = baseInstance.win;
/** @private @const {!Document} */
this.document_ = this.win_.document;
/** @private {?Deferred} */
this.iframeReady_ = null;
/** @private {boolean} */
this.removeIframe_ = false;
/** @private {?JsonObject} */
this.clientConfig_ = null;
/** @private {?Element} */
this.placeholder_ = null;
/** @private {string} */
this.initialHeight_ = `${DEFAULT_INITIAL_HEIGHT}vh`;
/** @private {boolean} */
this.borderEnabled_ = DEFAULT_ENABLE_BORDER;
/** @private {boolean} */
this.modalEnabled_ = false;
/** @private {boolean} */
this.isActionPromptTrigger_ = false;
/** @private @const {!Function} */
this.boundHandleIframeMessages_ = this.handleIframeMessages_.bind(this);
/** @private {?Promise<string>} */
this.promptUISrcPromise_ = null;
this.isGranularConsentExperimentOn_ = isExperimentOn(
this.win_,
'amp-consent-granular-consent'
);
this.init_(config, opt_postPromptUI);
}
/**
* @param {!JsonObject} config
* @param {string=} opt_postPromptUI
*/
init_(config, opt_postPromptUI) {
if (opt_postPromptUI) {
const postPromptUI = this.ampdoc_.getElementById(opt_postPromptUI);
if (!postPromptUI) {
user().error(
TAG,
'postPromptUI element with id=%s not found',
opt_postPromptUI
);
}
this.ui_ = dev().assertElement(postPromptUI);
this.isPostPrompt_ = true;
return;
}
const promptUI = config['promptUI'];
const promptUISrc = config['promptUISrc'];
if (promptUI) {
// Always respect promptUI first
const promptElement = this.ampdoc_.getElementById(promptUI);
if (!promptElement || !this.parent_.contains(promptElement)) {
user().error(
TAG,
'child element of <amp-consent> with promptUI id %s not found',
promptUI
);
}
this.ui_ = dev().assertElement(promptElement);
} else if (promptUISrc) {
// Create an iframe element with the provided src
this.isCreatedIframe_ = true;
assertHttpsUrl(promptUISrc, this.parent_);
// TODO: Preconnect to the promptUISrc?
this.promptUISrcPromise_ = expandConsentEndpointUrl(
this.parent_,
promptUISrc
);
this.ui_ = this.createPromptIframe_(promptUISrc);
this.placeholder_ = this.createPlaceholder_();
this.clientConfig_ = config['clientConfig'] || null;
}
}
/**
* Display the UI.
* @param {boolean} isActionPromptTrigger
*/
show(isActionPromptTrigger) {
if (!this.ui_) {
// No prompt UI specified, nothing to do
return;
}
if (this.isPostPrompt_ && !this.parent_.contains(this.ui_)) {
toggle(this.ui_, true);
return;
}
toggle(dev().assertElement(this.parent_), true);
const {classList} = this.parent_;
classList.add('amp-active');
classList.remove('amp-hidden');
// Add to fixed layer
this.baseInstance_.getViewport().addToFixedLayer(this.parent_);
if (this.isCreatedIframe_ && this.promptUISrcPromise_) {
// show() can be called multiple times, but notificationsUiManager
// ensures that only 1 is shown at a time, so no race condition here
this.isActionPromptTrigger_ = isActionPromptTrigger;
this.loadIframe_().then(() => {
// It is safe to assume that the loadIframe_ promise will resolve
// before resetIframe_. Because the iframe needs to be shown first
// being hidden. CMP iframe is responsible to call consent-iframe-ready
// API before consent-response API.
this.baseInstance_.mutateElement(() => {
if (!this.isPostPrompt_) {
this.elementWithFocusBeforeShowing_ = this.document_.activeElement;
}
this.maybeShowOverlay_();
// Create and append SR alert for the when iframe
// initially loads.
this.maybeShowSrAlert_();
this.showIframe_();
});
});
} else {
const show = () => {
if (!this.ui_) {
return;
}
toggle(this.ui_, true);
if (!this.isPostPrompt_) {
this.elementWithFocusBeforeShowing_ = this.document_.activeElement;
this.maybeShowOverlay_();
this.resume();
this.ui_./*OK*/ focus();
}
};
// If the UI is an AMP Element, wait until it's built before showing it,
// to avoid race conditions where the UI would be hidden by the runtime
// at build time. (see #18841).
if (isAmpElement(this.ui_)) {
whenUpgradedToCustomElement(this.ui_)
.then(() => this.ui_.build())
.then(() => show());
} else {
show();
}
}
this.isVisible_ = true;
}
/**
* Hide the UI
*/
hide() {
if (!this.ui_) {
// Nothing to hide from;
return;
}
this.pause();
this.baseInstance_.mutateElement(() => {
if (this.isCreatedIframe_) {
this.resetIframe_();
}
if (!this.isPostPrompt_) {
const {classList} = this.parent_;
classList.remove('amp-active');
classList.add('amp-hidden');
}
// Hide the overlay
this.maybeHideOverlay_();
// Remove the SR alert from DOM
this.maybeRemoveSrAlert_();
// Enable the scroll, in case we were fullscreen with no overlay
this.enableScroll_();
// Reset any animation styles set by style attribute
this.resetAnimationStyles_();
// NOTE (torch2424): This is very sensitive. Fixed layer applies
// a `top: calc(0px)` in order to fix some bugs, thus
// We should be careful in moving this around as
// `removeFromFixedLayer` will remove the `top` styling.
// This will preserve The animation,
// and prevent element flashing.
this.baseInstance_.getViewport().removeFromFixedLayer(this.parent_);
toggle(dev().assertElement(this.ui_), false);
this.isVisible_ = false;
if (this.elementWithFocusBeforeShowing_) {
this.elementWithFocusBeforeShowing_./*OK*/ focus();
this.elementWithFocusBeforeShowing_ = null;
} else if (this.win_.document.body.children.length > 0) {
// TODO (torch2424): Find if the first child can not be
// focusable due to styling.
this.win_.document.body.children[0]./*OK*/ focus();
}
});
}
/** */
pause() {
if (this.ui_) {
Services.ownersForDoc(this.baseInstance_.element).schedulePause(
this.baseInstance_.element,
this.ui_
);
}
}
/** */
resume() {
if (this.ui_) {
// scheduleLayout is required everytime because some AMP element may
// get un laid out after toggle display (#unlayoutOnPause)
// for example <amp-iframe>
Services.ownersForDoc(this.baseInstance_.element).scheduleLayout(
this.baseInstance_.element,
this.ui_
);
Services.ownersForDoc(this.baseInstance_.element).scheduleResume(
this.baseInstance_.element,
this.ui_
);
}
}
/**
* Handle the ready event from the CMP iframe
* @param {!JsonObject} data
*/
handleReady_(data) {
this.initialHeight_ = `${DEFAULT_INITIAL_HEIGHT}vh`;
this.borderEnabled_ = DEFAULT_ENABLE_BORDER;
this.modalEnabled_ = false;
// Set our initial height
if (data['initialHeight']) {
if (
typeof data['initialHeight'] === 'string' &&
data['initialHeight'].indexOf('vh') >= 0
) {
const dataHeight = parseInt(data['initialHeight'], 10);
// Set initialHeight to max height fallback if applicable
this.initialHeight_ =
dataHeight >= MAX_INITIAL_HEIGHT
? `${MAX_INITIAL_HEIGHT}vh`
: this.initialHeight_;
if (
dataHeight >= MINIMUM_INITIAL_HEIGHT &&
dataHeight <= MAX_INITIAL_HEIGHT
) {
this.initialHeight_ = `${dataHeight}vh`;
this.modalEnabled_ = dataHeight > MODAL_HEIGHT_ENABLED;
// Force overlay if modal is enabled.
this.overlayEnabled_ = this.modalEnabled_ || this.overlayEnabled_;
} else {
user().error(
TAG,
`Inavlid initial height: ${data['initialHeight']}.` +
`Minimum: ${MINIMUM_INITIAL_HEIGHT}vh. Maximum: ${MAX_INITIAL_HEIGHT}vh.`
);
}
} else {
user().error(
TAG,
`Inavlid initial height: ${data['initialHeight']}.` +
'Must be a string in "vh" units.'
);
}
}
// Disable our border, if set to false and not modal view.
if (data['border'] === false && !this.modalEnabled_) {
this.borderEnabled_ = false;
}
this.iframeReady_.resolve();
}
/**
* Enter the fullscreen state for the UI
*/
enterFullscreen_() {
if (!this.ui_ || !this.isVisible_ || this.isFullscreen_) {
return;
}
this.resetAnimationStyles_();
this.sendViewerEvent_(REQUEST_OVERLAY);
const {classList} = this.parent_;
classList.add(consentUiClasses.iframeFullscreen);
this.disableScroll_();
this.isFullscreen_ = true;
}
/**
* Send viewer an event.
* @param {string} event
*/
sendViewerEvent_(event) {
this.viewer_.sendMessage(event, dict(), /* cancelUnsent */ true);
}
/**
* Create the iframe if promptUISrc is valid
* @param {string} promptUISrc
* @return {!Element}
*/
createPromptIframe_(promptUISrc) {
const iframe = this.parent_.ownerDocument.createElement('iframe');
const sandbox = ['allow-scripts', 'allow-popups'];
const allowSameOrigin = this.allowSameOrigin_(promptUISrc);
if (allowSameOrigin) {
sandbox.push('allow-same-origin');
}
iframe.setAttribute('sandbox', sandbox.join(' '));
const {classList} = iframe;
classList.add(consentUiClasses.fill);
// Append iframe lazily to save resources.
return iframe;
}
/**
* Determines if allow-same-origin should be enabled for the prompt iframe
* @param {string} src
* @return {boolean}
*/
allowSameOrigin_(src) {
const urlService = Services.urlForDoc(this.parent_);
const srcUrl = urlService.parse(src);
const containerUrl = urlService.parse(this.ampdoc_.getUrl());
return srcUrl.origin != containerUrl.origin;
}
/**
* Create the default placeholder
* @return {!Element}
*/
createPlaceholder_() {
const placeholder = this.parent_.ownerDocument.createElement('placeholder');
toggle(placeholder, false);
placeholder.classList.add(consentUiClasses.placeholder);
const loadingSpinner = htmlFor(placeholder)`
<svg viewBox="0 0 40 40">
<defs>
<linearGradient id="grad">
<stop stop-color="rgb(105, 105, 105)"></stop>
<stop offset="100%"
stop-color="rgb(105, 105, 105)"
stop-opacity="0"></stop>
</linearGradient>
</defs>
<path d="M11,4.4 A18,18, 0,1,0, 38,20" stroke="url(#grad)"></path>
</svg>`;
placeholder.appendChild(loadingSpinner);
return placeholder;
}
/**
* Get the client information that needs to be passed to cmp iframe
* @return {!Promise<JsonObject>}
*/
getClientInfoPromise_() {
const consentStatePromise = getServicePromiseForDoc(
this.ampdoc_,
CONSENT_STATE_MANAGER
);
return consentStatePromise.then((consentStateManager) => {
return consentStateManager
.getLastConsentInstanceInfo()
.then((consentInfo) => {
const returnValue = dict({
'clientConfig': this.clientConfig_,
// consentState to be deprecated
'consentState': getConsentStateValue(consentInfo['consentState']),
'consentStateValue': getConsentStateValue(
consentInfo['consentState']
),
'consentMetadata': consentInfo['consentMetadata'],
'consentString': consentInfo['consentString'],
'promptTrigger': this.isActionPromptTrigger_ ? 'action' : 'load',
'isDirty': !!consentInfo['isDirty'],
});
if (this.isGranularConsentExperimentOn_) {
returnValue['purposeConsents'] = consentInfo['purposeConsents'];
}
return returnValue;
});
});
}
/**
* Apply placeholder
* Set up event listener to handle UI related messages.
* @return {!Promise}
*/
loadIframe_() {
this.iframeReady_ = new Deferred();
const {classList} = this.parent_;
if (!elementByTag(this.parent_, 'placeholder')) {
insertAtStart(this.parent_, dev().assertElement(this.placeholder_));
}
classList.add(consentUiClasses.loading);
toggle(dev().assertElement(this.ui_), false);
const iframePromise = this.promptUISrcPromise_.then((expandedSrc) => {
this.removeIframe_ = false;
this.ui_.src = expandedSrc;
return this.getClientInfoPromise_().then((clientInfo) => {
this.ui_.setAttribute('name', JSON.stringify(clientInfo));
this.win_.addEventListener('message', this.boundHandleIframeMessages_);
insertAtStart(this.parent_, dev().assertElement(this.ui_));
});
});
return Promise.all([
iframePromise,
this.iframeReady_.promise,
this.baseInstance_.mutateElement(() => {
toggle(dev().assertElement(this.placeholder_), true);
}),
]);
}
/**
* Hide the placeholder
* Apply animation to show the iframe
*/
showIframe_() {
const {classList} = this.parent_;
classList.add(consentUiClasses.iframeActive);
toggle(dev().assertElement(this.placeholder_), false);
toggle(dev().assertElement(this.ui_), true);
if (this.modalEnabled_) {
classList.add(consentUiClasses.modal);
tryFocus(dev().assertElement(this.ui_));
}
// Remove transition styles added by the fixed layer
// Transform styles applied by us for the animation.
this.resetAnimationStyles_();
/**
* Waiting for mutation twice here.
* First mutation is for when the correct elements,
* are shown/hidden, and the iframe active class
* pushes it out of view.
* Second, is for the loading class to be removed.
* This will avoid race conditions with the slidein transition.
*/
this.baseInstance_.mutateElement(() => {
classList.remove(consentUiClasses.loading);
this.baseInstance_.mutateElement(() => {
classList.add(consentUiClasses.in);
this.isIframeVisible_ = true;
this.applyInitialStyles_();
});
});
}
/**
* Remove the iframe from doc
* Remove event listener
* Reset UI state
* Takes in a function to call after our transition has ended
*/
resetIframe_() {
const {classList} = this.parent_;
// It is ok to remove classes even when they're not present
classList.remove(consentUiClasses.iframeActive);
classList.remove(consentUiClasses.modal);
classList.remove(consentUiClasses.borderEnabled);
this.win_.removeEventListener('message', this.boundHandleIframeMessages_);
classList.remove(consentUiClasses.iframeFullscreen);
// TODO(micajuineho) consolidate code to user viewport
if (this.isFullscreen_) {
this.sendViewerEvent_(CANCEL_OVERLAY);
} else if (this.modalEnabled_) {
this.viewport_.leaveLightboxMode();
}
this.isFullscreen_ = false;
classList.remove(consentUiClasses.in);
this.isIframeVisible_ = false;
this.ui_.removeAttribute('name');
toggle(dev().assertElement(this.placeholder_), false);
this.removeIframe_ = true;
this.win_.setTimeout(() => {
if (this.removeIframe_) {
removeElement(dev().assertElement(this.ui_));
}
}, IFRAME_RUNNING_TIMEOUT);
}
/**
* If this is the first time viewing the iframe, create
* an 'invisible' alert dialog with a title and a button.
* Clicking on the button will transfer focus to the iframe.
*
* This only applies for bottom pane iframes.
*/
maybeShowSrAlert_() {
// If the SR alert has been shown, don't show it again
if (this.srAlertShown_ || this.modalEnabled_) {
return;
}
const alertDialog = this.document_.createElement('div');
const button = this.document_.createElement('button');
const titleDiv = this.document_.createElement('div');
alertDialog.setAttribute('role', 'alertdialog');
titleDiv.textContent = this.consentPromptCaption_;
button.textContent = this.buttonActionCaption_;
button.onclick = () => {
tryFocus(dev().assertElement(this.ui_));
};
alertDialog.appendChild(titleDiv);
alertDialog.appendChild(button);
// Style to be visiblly hidden, but not hidden from the SR
const {classList} = alertDialog;
classList.add(consentUiClasses.screenReaderDialog);
this.baseInstance_.element.appendChild(alertDialog);
tryFocus(button);
// SR alert was shown when consent prompt loaded for
// the first time. Don't show it again
this.srAlertShown_ = true;
// Keep reference of the SR alert to remove later
this.srAlert_ = alertDialog;
}
/**
* Remove the SR alert from the DOM once it has been shown once
*/
maybeRemoveSrAlert_() {
if (this.srAlert_) {
removeElement(this.srAlert_);
delete this.srAlert_;
}
}
/**
* Reset transition and transform styles
* Set by the fixed layer, and us
*/
resetAnimationStyles_() {
setStyles(this.parent_, {
transform: '',
transition: '',
});
}
/**
* Apply styles for ready event
*/
applyInitialStyles_() {
const {classList} = this.parent_;
// Apply our initial height and border
if (this.ui_) {
setStyles(this.ui_, {
height: this.initialHeight_,
});
}
setImportantStyles(this.parent_, {
'--i-amphtml-modal-height': `${this.initialHeight_}`,
});
classList.add(consentUiClasses.iframeTransform);
// Border is default with modal enabled and option with non-modal
if (this.borderEnabled_ || this.modalEnabled_) {
classList.add(consentUiClasses.borderEnabled);
}
if (this.modalEnabled_) {
this.viewport_.enterLightboxMode();
}
}
/**
* Shows the overlay (mask element, and lock scrolling)
* if the overlay is enabled
* @private
*/
maybeShowOverlay_() {
if (!this.overlayEnabled_) {
return;
}
if (!this.maskElement_) {
const mask = this.win_.document.createElement('div');
mask.classList.add(consentUiClasses.mask);
this.parent_.ownerDocument.body.appendChild(mask);
this.maskElement_ = mask;
}
toggle(this.maskElement_, /* display */ true);
this.disableScroll_();
}
/**
* Hides the overlay (mask element, and lock scrolling)
* if the overlay is enabled
* @private
*/
maybeHideOverlay_() {
if (!this.overlayEnabled_) {
return;
}
if (this.maskElement_) {
toggle(this.maskElement_, /* display */ false);
}
this.enableScroll_();
}
/**
* Disables scrolling on the document
* @private
*/
disableScroll_() {
if (this.scrollEnabled_) {
this.viewport_.enterOverlayMode();
this.scrollEnabled_ = false;
}
}
/**
* Disables scrolling on the document
* @private
*/
enableScroll_() {
if (!this.scrollEnabled_) {
this.viewport_.leaveOverlayMode();
this.scrollEnabled_ = true;
}
}
/**
* Listen to iframe messages and handle events.
* Current supported APIs:
*
* Required message from iframe to hide placeholder and display iframe
* {
* type: 'consent-ui',
* action: 'ready',
* initialHeight: '30vh',
* border: true
* }
*
* Enter Fullscreen
* {
* type: 'consent-ui',
* action: 'enter-fullscreen'
* }
*
* @param {!Event} event
*/
handleIframeMessages_(event) {
if (this.ui_.contentWindow !== event.source) {
// Ignore messages from else where
return;
}
const data = getData(event);
if (!data || data['type'] != 'consent-ui') {
return;
}
const requestAction = data['action'];
const requestType = data['type'];
if (requestAction === 'ready') {
this.handleReady_(/** @type {!JsonObject} */ (data));
}
if (requestAction === 'enter-fullscreen') {
// Do nothing iff:
// - iframe not visible or
// - iframe not active element && not called via actionPromptTrigger
// - iframe is not modalEnabled
if (
!this.isIframeVisible_ ||
this.modalEnabled_ ||
(this.document_.activeElement !== this.ui_ &&
!this.isActionPromptTrigger_)
) {
user().warn(TAG, FULLSCREEN_ERROR);
this.sendEnterFullscreenResponse_(requestType, requestAction, true);
return;
}
this.sendEnterFullscreenResponse_(requestType, requestAction);
this.baseInstance_.mutateElement(() => {
this.enterFullscreen_();
});
}
}
/**
* @param {string} requestType
* @param {string} requestAction
* @param {boolean} isError
* */
sendEnterFullscreenResponse_(requestType, requestAction, isError = false) {
this.sendIframeMessage_(
ampConsentMessageType.response,
requestType,
requestAction,
isError ? actionState.error : actionState.success,
isError ? FULLSCREEN_ERROR : FULLSCREEN_SUCCESS
);
}
/**
* Send message to iframe, regarding action response or other info.
* Silently die if iframe does not have content window.
*
* Example message:
* {
* type: 'amp-consent-response'
* requestType:'consent-ui'
* requestAction: 'enter-fullscreen'
* state: 'error/success'
* info: 'msg'
* }
* @param {string} type
* @param {string} requestType
* @param {string} requestAction
* @param {string} state
* @param {string} info
*/
sendIframeMessage_(type, requestType, requestAction, state, info) {
const iframeWindow = this.ui_.contentWindow;
if (iframeWindow) {
// No sensitive information sent, so safe to use '*'
iframeWindow./*OK*/ postMessage(
/** @type {!JsonObject} */ ({
type,
requestType,
requestAction,
state,
info,
}),
'*'
);
}
}
}