forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amp-auto-lightbox.js
509 lines (429 loc) · 13.7 KB
/
amp-auto-lightbox.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
/**
* Copyright 2019 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.
*/
/**
* @fileoverview Detects <amp-img> elements to set the `lightbox` attribute
* automatically.
*
* This extension is not meant to be included explicitly, e.g. as a script tag.
* Instead, the runtime loads it when encountering an <amp-img>.
*/
import {AmpEvents} from '../../../src/amp-events';
import {AutoLightboxEvents} from '../../../src/auto-lightbox';
import {CarouselCriteria} from './carousel-criteria';
import {CommonSignals} from '../../../src/common-signals';
import {Services} from '../../../src/services';
import {
closestAncestorElementBySelector,
matches,
whenUpgradedToCustomElement,
} from '../../../src/dom';
import {dev} from '../../../src/log';
import {getMode} from '../../../src/mode';
import {resolveFalse, resolveTrue} from './utils/promise';
import {toArray} from '../../../src/types';
import {tryParseJson} from '../../../src/json';
const TAG = 'amp-auto-lightbox';
export const REQUIRED_EXTENSION = 'amp-lightbox-gallery';
export const LIGHTBOXABLE_ATTR = 'lightbox';
/** Attribute to mark scanned lightbox candidates as not to revisit. */
export const VISITED_ATTR = 'i-amphtml-auto-lightbox-visited';
/**
* Types of document by LD+JSON schema `@type` field where auto-lightbox should
* be enabled.
* @private @const {!Object<string|undefined, boolean>}
*/
export const ENABLED_LD_JSON_TYPES = {
'Article': true,
'NewsArticle': true,
'BlogPosting': true,
'LiveBlogPosting': true,
'DiscussionForumPosting': true,
};
/**
* Only of document type by Open Graph `<meta property="og:type">` where
* auto-lightbox should be enabled. Top-level og:type set is tiny, and `article`
* covers all required types.
*/
export const ENABLED_OG_TYPE_ARTICLE = 'article';
/** Factor of naturalArea vs renderArea to lightbox. */
export const RENDER_AREA_RATIO = 1.2;
/** Factor of renderArea vs viewportArea to lightbox. */
export const VIEWPORT_AREA_RATIO = 0.25;
/** @const {!Array<string>} */
const CANDIDATES = ['amp-img', 'amp-carousel'];
/**
* Selector for subnodes by attribute for which the auto-lightbox treatment
* does not apply. These can be set directly on the candidate or on an ancestor.
*/
const DISABLED_BY_ATTR = [
// Runtime-specific.
'[placeholder]',
// Explicitly opted out.
'[data-amp-auto-lightbox-disable]',
// Considered "actionable", i.e. that are bound to a default
// onclick action(e.g. `button`) or where it cannot be determined whether
// they're actionable or not (e.g. `amp-script`).
'amp-selector [option]',
].join(',');
/**
* Selector for subnodes for which the auto-lightbox treatment does not apply.
*/
const DISABLED_ANCESTORS = [
// Ancestors considered "actionable", i.e. that are bound to a default
// onclick action(e.g. `button`) or where it cannot be determined whether
// they're actionable or not (e.g. `amp-script`).
'a[href]',
'amp-script',
'amp-story',
'button',
// No nested lightboxes.
'amp-lightbox',
// Special treatment.
'amp-carousel',
].join(',');
const SCRIPT_LD_JSON = 'script[type="application/ld+json"]';
const META_OG_TYPE = 'meta[property="og:type"]';
const NOOP = () => {};
/**
* For better minification.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {!Document|!ShadowRoot}
*/
const getRootNode = ampdoc => ampdoc.getRootNode();
/** @visibleForTesting */
export class Criteria {
/**
* @param {!Element} element
* @return {!Promise<boolean>}
*/
static meetsAll(element) {
if (!Criteria.meetsSimpleCriteria(element) ||
!Criteria.meetsTreeShapeCriteria(element)) {
return resolveFalse();
}
return Criteria.meetsComplexCriteria(element);
}
/**
* Criteria that is "simple", ie runs quickly and discards elements in order
* to shortcircuit.
* @param {!Element} element
* @return {boolean}
*/
static meetsSimpleCriteria(element) {
if (element.tagName.toUpperCase() == 'AMP-IMG') {
return ImageCriteria.meetsSizingCriteria(element);
}
return true;
}
/**
* Criteria that is "complex", ie takes longer to run and discards elements
* after they're likely to be good candidates per previous conditions.
* @param {!Element} element
* @return {!Promise<boolean>}
*/
static meetsComplexCriteria(element) {
if (element.tagName.toUpperCase() == 'AMP-CAROUSEL') {
return CarouselCriteria.meetsAll(element);
}
return resolveTrue();
}
/**
* @param {!Element} element
* @return {boolean}
*/
static meetsTreeShapeCriteria(element) {
const disabledSelector = `${DISABLED_ANCESTORS},${DISABLED_BY_ATTR}`;
const disabledAncestor =
closestAncestorElementBySelector(element, disabledSelector);
// since we lookup both amp-img and amp-carousel at the same level, and
// we'd like to give amp-carousel special treatment by containing amp-img's,
// we need to filter out images inside carousels, but not carousels
// themselves.
if (disabledAncestor &&
(disabledAncestor != element ||
matches(disabledAncestor, DISABLED_BY_ATTR))) {
return false;
}
const actions = Services.actionServiceForDoc(element);
return !actions.hasResolvableAction(element, 'tap');
}
}
class ImageCriteria {
/**
* @param {!Element} element
* @return {boolean}
*/
static meetsSizingCriteria(element) {
const {naturalWidth, naturalHeight} =
dev().assertElement(element.querySelector('img'));
const {width: renderWidth, height: renderHeight} = element.getLayoutBox();
const viewport = Services.viewportForDoc(element);
const {width: vw, height: vh} = viewport.getSize();
return meetsSizingCriteria(
renderWidth,
renderHeight,
naturalWidth,
naturalHeight,
vw,
vh);
}
}
/**
* @param {number} renderWidth
* @param {number} renderHeight
* @param {number} naturalWidth
* @param {number} naturalHeight
* @param {number} vw
* @param {number} vh
* @return {boolean}
* @visibleForTesting
*/
export function meetsSizingCriteria(
renderWidth,
renderHeight,
naturalWidth,
naturalHeight,
vw,
vh) {
const viewportArea = vw * vh;
const naturalArea = naturalWidth * naturalHeight;
const renderArea = renderWidth * renderHeight;
const isShrunk =
(naturalArea / renderArea) >= RENDER_AREA_RATIO;
const isCoveringSignificantArea =
(renderArea / viewportArea) >= VIEWPORT_AREA_RATIO;
const isLargerThanViewport = naturalWidth > vw || naturalHeight > vh;
return isShrunk ||
isLargerThanViewport ||
isCoveringSignificantArea;
}
/**
* Marks a lightbox candidate as visited as not to rescan on DOM update.
* @param {!Element} candidate
* @return {!Promise<!Element>}
*/
function markAsVisited(candidate) {
return Mutation.mutate(candidate, () => {
candidate.setAttribute(VISITED_ATTR, '');
});
}
/**
* @param {string} tagName
* @return {string}
*/
function candidateSelector(tagName) {
return `${tagName}:not([${LIGHTBOXABLE_ATTR}]):not([${VISITED_ATTR}])`;
}
/**
* @param {!Element} element
* @return {!Promise<!Element>}
*/
function whenLoaded(element) {
return element.signals().whenSignal(CommonSignals.LOAD_END);
}
/** @visibleForTesting */
export class Scanner {
/**
* Gets all unvisited lightbox candidates.
* @param {!Document|!Element} root
* @return {!Array<!Element>}
*/
static getCandidates(root) {
const selector = CANDIDATES.map(candidateSelector).join(',');
const candidates = toArray(root.querySelectorAll(selector));
candidates.forEach(markAsVisited);
return candidates;
}
}
/**
* Parses document metadata annotations as defined by either LD+JSON schema or
* Open Graph <meta> tags.
* @visibleForTesting
*/
export class DocMetaAnnotations {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {string|undefined}
*/
static getOgType(ampdoc) {
const tag = getRootNode(ampdoc).querySelector(META_OG_TYPE);
if (tag) {
return tag.getAttribute('content');
}
}
/**
* Determines wheter the document type as defined by Open Graph meta tag
* e.g. `<meta property="og:type">` is valid.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {boolean}
*/
static hasValidOgType(ampdoc) {
return DocMetaAnnotations.getOgType(ampdoc) == ENABLED_OG_TYPE_ARTICLE;
}
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {!Array<string>}
*/
static getAllLdJsonTypes(ampdoc) {
return toArray(getRootNode(ampdoc).querySelectorAll(SCRIPT_LD_JSON))
.map(({textContent}) => ((tryParseJson(textContent) || {})['@type']))
.filter(typeOrUndefined => typeOrUndefined);
}
/**
* Determines wheter one of the document types (field `@type`) defined in
* LD+JSON schema is in ENABLED_LD_JSON_TYPES.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {boolean}
*/
static hasValidLdJsonType(ampdoc) {
return DocMetaAnnotations.getAllLdJsonTypes(ampdoc)
.some(type => ENABLED_LD_JSON_TYPES[type]);
}
}
/**
* Wrapper for an element-implementation-mutate sequence for readability and
* mocking in tests.
* @visibleForTesting
*/
export class Mutation {
/**
* @param {!Element} ampEl
* @param {function()} mutator
* @return {!Promise}
*/
static mutate(ampEl, mutator) {
return whenUpgradedToCustomElement(ampEl)
.then(ampEl => ampEl.getResources().mutateElement(ampEl, mutator));
}
}
/**
* Determines whether a document uses `amp-lightbox-gallery` explicitly by
* including the extension and explicitly lightboxing at least one element.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {boolean}
*/
function usesLightboxExplicitly(ampdoc) {
// TODO(alanorozco): Backport into Extensions service.
const requiredExtensionSelector =
`script[custom-element="${REQUIRED_EXTENSION}"]`;
const lightboxedElementsSelector =
`[${LIGHTBOXABLE_ATTR}]:not([${VISITED_ATTR}])`;
const exists = selector => !!getRootNode(ampdoc).querySelector(selector);
return exists(requiredExtensionSelector) &&
exists(lightboxedElementsSelector);
}
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {boolean}
*/
function isProxyOriginOrLocalDev(ampdoc) {
// Allow `localDev` in lieu of proxy origin for manual testing, except in
// tests where we need to actually perform the check.
const {win} = ampdoc;
if (getMode(win).localDev && !getMode(win).test) {
return true;
}
// An attached node is required for proxy origin check. If no elements are
// present, short-circuit.
const {firstElementChild} = ampdoc.getBody();
if (!firstElementChild) {
return false;
}
// TODO(alanorozco): Additionally check for transformed, webpackaged flag.
// See git.io/fhQ0a (#20359) for details.
return Services.urlForDoc(firstElementChild).isProxyOrigin(win.location);
}
/**
* Determines whether auto-lightbox is enabled for a document.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @return {boolean}
* @visibleForTesting
*/
export function isEnabledForDoc(ampdoc) {
if (usesLightboxExplicitly(ampdoc)) {
return false;
}
if (!DocMetaAnnotations.hasValidOgType(ampdoc) &&
!DocMetaAnnotations.hasValidLdJsonType(ampdoc)) {
return false;
}
return isProxyOriginOrLocalDev(ampdoc);
}
/** @private {number} */
let uid = 0;
/**
* Generates a unique id for lightbox grouping.
* @return {string}
*/
function generateLightboxUid() {
return `i-amphtml-auto-lightbox-${uid++}`;
}
/**
* Lightboxes an element.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!Element} element
* @return {!Promise<!Element>}
* @visibleForTesting
*/
export function apply(ampdoc, element) {
return Mutation.mutate(element, () => {
element.setAttribute(LIGHTBOXABLE_ATTR, generateLightboxUid());
}).then(() => {
Services.extensionsFor(ampdoc.win)
.installExtensionForDoc(ampdoc, REQUIRED_EXTENSION);
element.dispatchCustomEvent(AutoLightboxEvents.NEWLY_SET);
return element;
});
}
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!Array<!Element>} candidates
* @return {!Array<!Promise<!Element|undefined>>}
*/
export function runCandidates(ampdoc, candidates) {
return candidates.map(candidate =>
whenLoaded(candidate).then(() => {
return Criteria.meetsAll(candidate).then(meetsAll => {
if (!meetsAll) {
return;
}
dev().info(TAG, 'apply', candidate);
return apply(ampdoc, candidate);
});
}, NOOP));
}
/**
* Scans a document on initialization to lightbox elements that meet criteria.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!Element=} opt_root
* @return {!Array<!Promise>|undefined}
*/
export function scan(ampdoc, opt_root) {
if (!isEnabledForDoc(ampdoc)) {
dev().info(TAG, 'disabled');
return;
}
const root = opt_root || ampdoc.win.document;
return runCandidates(ampdoc, Scanner.getCandidates(root));
}
AMP.extension(TAG, '0.1', ({ampdoc}) => {
ampdoc.whenReady().then(() => {
getRootNode(ampdoc).addEventListener(AmpEvents.DOM_UPDATE, ({target}) => {
scan(ampdoc, dev().assertElement(target));
});
scan(ampdoc);
});
});