-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
lightbox-manager-impl.js
389 lines (354 loc) · 11.6 KB
/
lightbox-manager-impl.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
/**
* Copyright 2016 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 {isExperimentOn} from '../../../../src/experiments';
import {dev, user} from '../../../../src/log';
import {
childElement,
closestByTag,
elementByTag,
iterateCursor,
} from '../../../../src/dom';
import {toArray} from '../../../../src/types';
import {CommonSignals} from '../../../../src/common-signals';
import {hasOwn, map} from '../../../../src/utils/object';
const LIGHTBOX_ELIGIBLE_TAGS = {
'amp-img': true,
};
const ELIGIBLE_TAP_TAGS = {
'amp-img': true,
};
const VIEWER_TAG = 'amp-lightbox-viewer';
const CAROUSEL_TAG = 'amp-carousel';
const FIGURE_TAG = 'figure';
const SLIDE_SELECTOR = '.amp-carousel-slide';
const VALIDATION_ERROR_MSG = `lightbox attribute is only supported for the
<amp-img> tag and <figure> and <amp-carousel> tags containing the <amp-img>
tag right now.`;
/** @typedef {{
* url: string,
* element: !Element
* }} */
export let LightboxThumbnailDataDef;
/** @typedef {{
* sourceCarousel: !Element,
* excludedIndexes: !Array<number>
* }} */
let LightboxedCarouselMetadataDef;
/**
* LightboxManager is a document-scoped service responsible for:
* -Finding elements marked to be lightboxable (via `lightbox` attribute)
* -Keeping an ordered list of lightboxable elements
* -Providing functionality to get next/previous lightboxable element given
* the current element.
* -Discovering elements that can be auto-lightboxed and add the
* `lightbox` attribute and possibly an on-tap handler to them
*/
export class LightboxManager {
/**
* @param {!../../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
// Extra safety check, we don't install this service if experiment is off
dev().assert(isExperimentOn(ampdoc.win, 'amp-lightbox-viewer'));
/** @const @private {!../../../../src/service/ampdoc-impl.AmpDoc} */
this.ampdoc_ = ampdoc;
/**
* Cache for the `maybeInit()` call.
* @private {?Promise}
**/
this.initPromise_ = null;
/**
* Ordered lists of lightboxable elements according to group
* @private {!Object<string, !Array<!Element>>}
*/
this.lightboxGroups_ = map({
default: [],
});
/**
* Counter tracking number of carousels without ids
* @private {number}
*/
this.counter_ = 0;
/**
* If the lightbox group is a carousel, this object contains a
* mapping of the lightbox group id to the carousel element.
* @private {!Object<string, !LightboxedCarouselMetadataDef>}
*/
this.lightboxSourceCarousels_ = map();
}
/**
* Initializes the manager only once.
* @return {!Promise}
*/
maybeInit() {
if (this.initPromise_) {
return this.initPromise_;
}
this.initPromise_ = this.scanLightboxables_();
return this.initPromise_;
}
/**
* Returns a reference to the source carousel of the lightbox
* group if one exists.
* @param {string} lightboxGroupId
* @return {!LightboxedCarouselMetadataDef|null}
*/
getCarouselMetadataForLightboxGroup(lightboxGroupId) {
if (hasOwn(this.lightboxSourceCarousels_, lightboxGroupId)) {
return this.lightboxSourceCarousels_[lightboxGroupId];
}
return null;
}
/**
* Returns a reference to the source carousel of the lightbox
* group if one exists.
* @param {string} lightboxGroupId
* @return {Array<number>}
*/
getLightboxExcludedIndexes(lightboxGroupId) {
if (hasOwn(this.lightboxSourceCarousels_, lightboxGroupId)) {
return this.lightboxSourceCarousels_[lightboxGroupId].excludedIndexes;
}
return [];
}
/**
* Returns true if the lightboxGroupId belongs to an amp carousel
* @param {string} lightboxGroupId
* @return {boolean}
*/
hasCarousel(lightboxGroupId) {
return hasOwn(this.lightboxSourceCarousels_, lightboxGroupId);
}
/**
* Decides whether an already lightboxable element should automatically get
* a tap handler to open in the lightbox.
* @param {!Element} element
* @return {boolean}
*/
meetsHeuristicsForTap_(element) {
dev().assert(element);
dev().assert(element.hasAttribute('lightbox'));
if (!ELIGIBLE_TAP_TAGS[element.tagName.toLowerCase()]) {
return false;
}
if (element.hasAttribute('on')) {
return false;
}
return true;
}
/**
* Scans the document for lightboxable elements and updates `this.elements_`
* accordingly.
* @private
* @return {!Promise}
*/
scanLightboxables_() {
return this.ampdoc_.whenReady().then(() => {
const matches = this.ampdoc_.getRootNode().querySelectorAll('[lightbox]');
const processLightboxElement = this.processLightboxElement_.bind(this);
iterateCursor(matches, processLightboxElement);
});
}
/**
* Checks to see if a root element is supported.
* @param {Element} element
* @return {boolean}
* @private
*/
baseElementIsSupported_(element) {
return LIGHTBOX_ELIGIBLE_TAGS[element.tagName.toLowerCase()];
}
/**
* Process an amp-carousel element for lightbox, assigns a lightbox
* group id, installs the lightbox attribute and tap handlers to open
* the lightbox on the eligible slide elements.
* @param {!Element} carousel
*/
processLightboxCarousel_(carousel) {
const lightboxGroupId = carousel.getAttribute('lightbox') ||
'carousel' + (carousel.getAttribute('id') || this.counter_++);
if (carousel.getAttribute('type') == 'slides') {
this.lightboxSourceCarousels_[lightboxGroupId] = map({
'sourceCarousel': carousel,
'excludedIndexes': [],
});
// TODO (#13011): scroll carousel needs to support goToSlide
// before we can use it for lightbox, so they currently don't count.
}
this.getSlidesFromCarousel_(carousel).then(slides => {
slides.forEach((slide, index) => {
const shouldExcludeSlide = slide.hasAttribute('lightbox-exclude')
|| (slide.hasAttribute('lightbox')
&& slide.getAttribute('lightbox') !== lightboxGroupId);
if (shouldExcludeSlide) {
this.lightboxSourceCarousels_[lightboxGroupId]
.excludedIndexes.push(index);
} else {
slide.setAttribute('lightbox', lightboxGroupId);
this.processBaseLightboxElement_(slide, lightboxGroupId);
}
});
});
}
/**
* Adds element to correct lightbox group, installs tap handler.
* @param {!Element} element
* @private
*/
processLightboxElement_(element) {
if (element.tagName.toLowerCase() == CAROUSEL_TAG) {
this.processLightboxCarousel_(element);
} else {
const lightboxGroupId = element.getAttribute('lightbox') || 'default';
this.processBaseLightboxElement_(element, lightboxGroupId);
}
}
/**
* Unwraps a figure element and lightboxes the
* @param {!Element} figure
* @param {string} lightboxGroupId
* @return {?Element}
* @private
*/
unwrapLightboxedFigure_(figure, lightboxGroupId) {
// Assume that the lightbox target is whichever element inside the figure
// that is not the figcaption.
const element = childElement(figure,
child => child.tagName !== 'FIGCAPTION');
if (element) {
element.setAttribute('lightbox', lightboxGroupId);
}
return element;
}
/**
* Assigns each lightboxed element to a lightbox group and adds
* the on tap activate attribute.
* @param {!Element} element
* @param {string} lightboxGroupId
*/
processBaseLightboxElement_(element, lightboxGroupId) {
if (element.tagName.toLowerCase() == FIGURE_TAG) {
const unwrappedFigureElement = this.unwrapLightboxedFigure_(element,
lightboxGroupId);
if (!unwrappedFigureElement) {
return;
} else {
element = unwrappedFigureElement;
}
}
user().assert(this.baseElementIsSupported_(element), VALIDATION_ERROR_MSG);
if (!this.lightboxGroups_[lightboxGroupId]) {
this.lightboxGroups_[lightboxGroupId] = [];
}
this.lightboxGroups_[lightboxGroupId]
.push(dev().assertElement(element));
if (this.meetsHeuristicsForTap_(element)) {
const viewer = elementByTag(this.ampdoc_.getRootNode(), VIEWER_TAG);
element.setAttribute('on', `tap:${viewer.id}.activate`);
}
}
/**
* @param {!Element} element
* @return {!Promise<!Array<!Element>>}
* @private
*/
getSlidesFromCarousel_(element) {
return element.signals().whenSignal(CommonSignals.LOAD_END).then(() => {
return toArray(element./*OK*/querySelectorAll(SLIDE_SELECTOR));
});
}
/**
* Return a list of lightboxable elements
* @param {string} lightboxGroupId
* @return {!Promise<!Array<!Element>>}
*/
getElementsForLightboxGroup(lightboxGroupId) {
return this.maybeInit()
.then(() => dev().assert(this.lightboxGroups_[lightboxGroupId]));
}
/**
* Get the description for single lightboxed item.
* @param {!Element} element
* @return {string|null}
*/
getDescription(element) {
// If the element in question is the descendant of a figure element
// try using the figure caption as the lightbox description.
const figureParent = closestByTag(element, 'figure');
if (figureParent) {
const figCaption = elementByTag(figureParent, 'figcaption');
if (figCaption) {
return figCaption./*OK*/innerText;
}
}
const alt = element.getAttribute('alt');
if (alt) {
return alt;
}
const ariaDescribedBy = element.getAttribute('aria-describedby');
if (ariaDescribedBy) {
const descriptionElement = element.ownerDocument
.getElementById(ariaDescribedBy);
if (descriptionElement) {
return descriptionElement./*OK*/innerText;
}
}
const ariaLabel = element.getAttribute('aria-label');
if (ariaLabel) {
return ariaLabel;
}
const ariaLabelledBy = element.getAttribute('aria-labelledby');
if (ariaLabelledBy) {
const descriptionElement = element.ownerDocument
.getElementById(ariaLabelledBy);
if (descriptionElement) {
return descriptionElement./*OK*/innerText;
}
}
return null;
}
/**
* The function is not implemented yet. Fake for testing.
* Find or create thumbnails for lightboxed elements.
* Return a list of thumbnails obj for lightbox gallery view
* @param {string} lightboxGroupId
* @return {!Array<!LightboxThumbnailDataDef>}
*/
getThumbnails(lightboxGroupId) {
return this.lightboxGroups_[lightboxGroupId]
.map((element, i) => ({
url: this.getThumbnailUrl_(dev().assertElement(element), i),
element,
}));
}
/**
* Get thumbnail url for single element.
* @param {!Element} element
* @param {number=} index fake it for testing only, will delete later
* @return {string}
* @private
*/
getThumbnailUrl_(element, index) {
if (element.hasAttribute('lightbox-thumbnail-src')) {
return element.getAttribute('lightbox-thumbnail-src');
} else if (element.tagName == 'AMP-IMG') {
return element.getAttribute('src');
} else {
// TODO(#12713): implement default thumbnails
return 'https://placehold.it/128x128?text=' + index;
}
}
}