forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlayout.js
541 lines (509 loc) · 16.5 KB
/
layout.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
/**
* Copyright 2015 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 Implements element layout. See https://goo.gl/9avXuT for
* details.
*/
import {dev, devAssert, userAssert} from './log';
import {htmlFor} from './static-template';
import {isFiniteNumber} from './types';
import {setStyle, setStyles, toggle} from './style';
import {startsWith} from './string';
/**
* @enum {string}
*/
export const Layout = {
NODISPLAY: 'nodisplay',
FIXED: 'fixed',
FIXED_HEIGHT: 'fixed-height',
RESPONSIVE: 'responsive',
CONTAINER: 'container',
FILL: 'fill',
FLEX_ITEM: 'flex-item',
FLUID: 'fluid',
INTRINSIC: 'intrinsic',
};
/**
* Layout priorities to use with BaseElement#getLayoutPriority() and
* BaseElement#updateLayoutPriority().
* @enum {number}
*/
export const LayoutPriority = {
CONTENT: 0,
METADATA: 1,
ADS: 2,
BACKGROUND: 3,
};
/**
* CSS Length type. E.g. "1px" or "20vh".
* @typedef {string}
*/
export let LengthDef;
/**
* @typedef {{
* width: string,
* height: string
* }}
*/
let DimensionsDef;
/**
* The set of elements with natural dimensions, that is, elements
* which have a known dimension either based on their value specified here,
* or, if the value is null, a dimension specific to the browser.
* `hasNaturalDimensions` checks for membership in this set.
* `getNaturalDimensions` determines the dimensions for an element in the
* set and caches it.
* @type {!Object<string, ?DimensionsDef>}
* @private Visible for testing only!
*/
export const naturalDimensions_ = {
'AMP-PIXEL': {width: '0px', height: '0px'},
'AMP-ANALYTICS': {width: '1px', height: '1px'},
// TODO(dvoytenko): audio should have width:auto.
'AMP-AUDIO': null,
'AMP-SOCIAL-SHARE': {width: '60px', height: '44px'},
};
/**
* Elements that the progress can be shown for. This set has to be externalized
* since the element's implementation may not be downloaded yet.
* This list does not include video players which are found via regex later.
* @enum {boolean}
* @private Visible for testing only!
*/
export const LOADING_ELEMENTS_ = {
'AMP-AD': true,
'AMP-ANIM': true,
'AMP-EMBED': true,
'AMP-FACEBOOK': true,
'AMP-FACEBOOK-COMMENTS': true,
'AMP-FACEBOOK-PAGE': true,
'AMP-GOOGLE-DOCUMENT-EMBED': true,
'AMP-IFRAME': true,
'AMP-IMG': true,
'AMP-INSTAGRAM': true,
'AMP-LIST': true,
'AMP-PINTEREST': true,
'AMP-PLAYBUZZ': true,
'AMP-TWITTER': true,
};
/**
* All video player components must either have a) "video" or b) "player" in
* their name. A few components don't follow this convention for historical
* reasons, so they are listed individually.
* @private @const {!RegExp}
*/
const videoPlayerTagNameRe = /^amp\-(video|.+player)|AMP-BRIGHTCOVE|AMP-DAILYMOTION|AMP-YOUTUBE|AMP-VIMEO|AMP-IMA-VIDEO/i;
/**
* @param {string} s
* @return {Layout|undefined} Returns undefined in case of failure to parse
* the layout string.
*/
export function parseLayout(s) {
for (const k in Layout) {
if (Layout[k] == s) {
return Layout[k];
}
}
return undefined;
}
/**
* @param {!Layout} layout
* @return {string}
*/
export function getLayoutClass(layout) {
return 'i-amphtml-layout-' + layout;
}
/**
* Whether an element with this layout inherently defines the size.
* @param {!Layout} layout
* @return {boolean}
*/
export function isLayoutSizeDefined(layout) {
return (
layout == Layout.FIXED ||
layout == Layout.FIXED_HEIGHT ||
layout == Layout.RESPONSIVE ||
layout == Layout.FILL ||
layout == Layout.FLEX_ITEM ||
layout == Layout.FLUID ||
layout == Layout.INTRINSIC
);
}
/**
* Whether an element with this layout has a fixed dimension.
* @param {!Layout} layout
* @return {boolean}
*/
export function isLayoutSizeFixed(layout) {
return layout == Layout.FIXED || layout == Layout.FIXED_HEIGHT;
}
/**
* Whether the tag is an internal (service) AMP tag.
* @param {!Node|string} tag
* @return {boolean}
*/
export function isInternalElement(tag) {
const tagName = typeof tag == 'string' ? tag : tag.tagName;
return tagName && startsWith(tagName.toLowerCase(), 'i-');
}
/**
* Parses the CSS length value. If no units specified, the assumed value is
* "px". Returns undefined in case of parsing error.
* @param {string|undefined|null} s
* @return {!LengthDef|undefined}
*/
export function parseLength(s) {
if (typeof s == 'number') {
return s + 'px';
}
if (!s) {
return undefined;
}
if (!/^\d+(\.\d+)?(px|em|rem|vh|vw|vmin|vmax|cm|mm|q|in|pc|pt)?$/.test(s)) {
return undefined;
}
if (/^\d+(\.\d+)?$/.test(s)) {
return s + 'px';
}
return s;
}
/**
* Asserts that the supplied value is a non-percent CSS Length value.
* @param {!LengthDef|string|null|undefined} length
* @return {!LengthDef}
* @closurePrimitive {asserts.matchesReturn}
*/
export function assertLength(length) {
userAssert(
/^\d+(\.\d+)?(px|em|rem|vh|vw|vmin|vmax|cm|mm|q|in|pc|pt)$/.test(length),
'Invalid length value: %s',
length
);
return /** @type {!LengthDef} */ (length);
}
/**
* Asserts that the supplied value is a CSS Length value
* (including percent unit).
* @param {!LengthDef|string} length
* @return {!LengthDef}
* @closurePrimitive {asserts.matchesReturn}
*/
export function assertLengthOrPercent(length) {
userAssert(
/^\d+(\.\d+)?(px|em|rem|vh|vw|vmin|vmax|%)$/.test(length),
'Invalid length or percent value: %s',
length
);
return length;
}
/**
* Returns units from the CSS length value.
* @param {!LengthDef|string|null|undefined} length
* @return {string}
*/
export function getLengthUnits(length) {
assertLength(length);
dev().assertString(length);
const m = userAssert(
length.match(/[a-z]+/i),
'Failed to read units from %s',
length
);
return m[0];
}
/**
* Returns the numeric value of a CSS length value.
* @param {!LengthDef|string|null|undefined} length
* @return {number|undefined}
*/
export function getLengthNumeral(length) {
const res = parseFloat(length);
return isFiniteNumber(res) ? res : undefined;
}
/**
* Determines whether the tagName is a known element that has natural dimensions
* in our runtime or the browser.
* @param {string} tagName The element tag name.
* @return {boolean}
*/
export function hasNaturalDimensions(tagName) {
tagName = tagName.toUpperCase();
return naturalDimensions_[tagName] !== undefined;
}
/**
* Determines the default dimensions for an element which could vary across
* different browser implementations, like <audio> for instance.
* This operation can only be completed for an element whitelisted by
* `hasNaturalDimensions`.
* @param {!Element} element
* @return {DimensionsDef}
*/
export function getNaturalDimensions(element) {
const tagName = element.tagName.toUpperCase();
devAssert(naturalDimensions_[tagName] !== undefined);
if (!naturalDimensions_[tagName]) {
const doc = element.ownerDocument;
const naturalTagName = tagName.replace(/^AMP\-/, '');
const temp = doc.createElement(naturalTagName);
// For audio, should no-op elsewhere.
temp.controls = true;
setStyles(temp, {
position: 'absolute',
visibility: 'hidden',
});
doc.body.appendChild(temp);
naturalDimensions_[tagName] = {
width: (temp./*OK*/ offsetWidth || 1) + 'px',
height: (temp./*OK*/ offsetHeight || 1) + 'px',
};
doc.body.removeChild(temp);
}
return /** @type {DimensionsDef} */ (naturalDimensions_[tagName]);
}
/**
* Whether the loading can be shown for the specified elemeent. This set has
* to be externalized since the element's implementation may not be
* downloaded yet.
* @param {!Element} element
* @return {boolean}
*/
export function isLoadingAllowed(element) {
const tagName = element.tagName.toUpperCase();
return LOADING_ELEMENTS_[tagName] || isIframeVideoPlayerComponent(tagName);
}
/**
* All video player components must either have a) "video" or b) "player" in
* their name. A few components don't follow this convention for historical
* reasons, so they're present in the LOADING_ELEMENTS_ whitelist.
* @param {string} tagName
* @return {boolean}
*/
export function isIframeVideoPlayerComponent(tagName) {
if (tagName == 'AMP-VIDEO') {
return false;
}
return videoPlayerTagNameRe.test(tagName);
}
/**
* Applies layout to the element. Visible for testing only.
*
* \ \ / \ / / / \ | _ \ | \ | | | | | \ | | / _____|
* \ \/ \/ / / ^ \ | |_) | | \| | | | | \| | | | __
* \ / / /_\ \ | / | . ` | | | | . ` | | | |_ |
* \ /\ / / _____ \ | |\ \----.| |\ | | | | |\ | | |__| |
* \__/ \__/ /__/ \__\ | _| `._____||__| \__| |__| |__| \__| \______|
*
* The equivalent of this method is used for server-side rendering (SSR) and
* any changes made to it must be made in coordination with caches that
* implement SSR. For more information on SSR see bit.ly/amp-ssr.
*
* @param {!Element} element
* @return {!Layout}
*/
export function applyStaticLayout(element) {
// Check if the layout has already been done by server-side rendering or
// client-side rendering and the element was cloned. The document may be
// visible to the user if the boilerplate was removed so please take care in
// making changes here.
const completedLayoutAttr = element.getAttribute('i-amphtml-layout');
if (completedLayoutAttr) {
const layout = /** @type {!Layout} */ (devAssert(
parseLayout(completedLayoutAttr)
));
if (
(layout == Layout.RESPONSIVE || layout == Layout.INTRINSIC) &&
element.firstElementChild
) {
// Find sizer, but assume that it might not have been parsed yet.
element.sizerElement =
element.querySelector('i-amphtml-sizer') || undefined;
} else if (layout == Layout.NODISPLAY) {
toggle(element, false);
// TODO(jridgewell): Temporary hack while SSR still adds an inline
// `display: none`
element['style']['display'] = '';
}
return layout;
}
// If the layout was already done by server-side rendering (SSR), then the
// code below will not run. Any changes below will necessitate a change to SSR
// and must be coordinated with caches that implement SSR. See bit.ly/amp-ssr.
// Parse layout from the element.
const layoutAttr = element.getAttribute('layout');
const widthAttr = element.getAttribute('width');
const heightAttr = element.getAttribute('height');
const sizesAttr = element.getAttribute('sizes');
const heightsAttr = element.getAttribute('heights');
// Input layout attributes.
const inputLayout = layoutAttr ? parseLayout(layoutAttr) : null;
userAssert(inputLayout !== undefined, 'Unknown layout: %s', layoutAttr);
/** @const {string|null|undefined} */
const inputWidth =
widthAttr && widthAttr != 'auto' ? parseLength(widthAttr) : widthAttr;
userAssert(inputWidth !== undefined, 'Invalid width value: %s', widthAttr);
/** @const {string|null|undefined} */
const inputHeight =
heightAttr && heightAttr != 'fluid' ? parseLength(heightAttr) : heightAttr;
userAssert(inputHeight !== undefined, 'Invalid height value: %s', heightAttr);
// Effective layout attributes. These are effectively constants.
let width;
let height;
let layout;
// Calculate effective width and height.
if (
(!inputLayout ||
inputLayout == Layout.FIXED ||
inputLayout == Layout.FIXED_HEIGHT) &&
(!inputWidth || !inputHeight) &&
hasNaturalDimensions(element.tagName)
) {
// Default width and height: handle elements that do not specify a
// width/height and are defined to have natural browser dimensions.
const dimensions = getNaturalDimensions(element);
width =
inputWidth || inputLayout == Layout.FIXED_HEIGHT
? inputWidth
: dimensions.width;
height = inputHeight || dimensions.height;
} else {
width = inputWidth;
height = inputHeight;
}
// Calculate effective layout.
if (inputLayout) {
layout = inputLayout;
} else if (!width && !height) {
layout = Layout.CONTAINER;
} else if (height == 'fluid') {
layout = Layout.FLUID;
} else if (height && (!width || width == 'auto')) {
layout = Layout.FIXED_HEIGHT;
} else if (height && width && (sizesAttr || heightsAttr)) {
layout = Layout.RESPONSIVE;
} else {
layout = Layout.FIXED;
}
// Verify layout attributes.
if (
layout == Layout.FIXED ||
layout == Layout.FIXED_HEIGHT ||
layout == Layout.RESPONSIVE ||
layout == Layout.INTRINSIC
) {
userAssert(height, 'Expected height to be available: %s', heightAttr);
}
if (layout == Layout.FIXED_HEIGHT) {
userAssert(
!width || width == 'auto',
'Expected width to be either absent or equal "auto" ' +
'for fixed-height layout: %s',
widthAttr
);
}
if (
layout == Layout.FIXED ||
layout == Layout.RESPONSIVE ||
layout == Layout.INTRINSIC
) {
userAssert(
width && width != 'auto',
'Expected width to be available and not equal to "auto": %s',
widthAttr
);
}
if (layout == Layout.RESPONSIVE || layout == Layout.INTRINSIC) {
userAssert(
getLengthUnits(width) == getLengthUnits(height),
'Length units should be the same for width and height: %s, %s',
widthAttr,
heightAttr
);
} else {
userAssert(
heightsAttr === null,
'Unexpected "heights" attribute for none-responsive layout'
);
}
// Apply UI.
element.classList.add(getLayoutClass(layout));
if (isLayoutSizeDefined(layout)) {
element.classList.add('i-amphtml-layout-size-defined');
}
if (layout == Layout.NODISPLAY) {
// CSS defines layout=nodisplay automatically with `display:none`. Thus
// no additional styling is needed.
toggle(element, false);
// TODO(jridgewell): Temporary hack while SSR still adds an inline
// `display: none`
element['style']['display'] = '';
} else if (layout == Layout.FIXED) {
setStyles(element, {
width: dev().assertString(width),
height: dev().assertString(height),
});
} else if (layout == Layout.FIXED_HEIGHT) {
setStyle(element, 'height', dev().assertString(height));
} else if (layout == Layout.RESPONSIVE) {
const sizer = element.ownerDocument.createElement('i-amphtml-sizer');
setStyles(sizer, {
paddingTop:
(getLengthNumeral(height) / getLengthNumeral(width)) * 100 + '%',
});
element.insertBefore(sizer, element.firstChild);
element.sizerElement = sizer;
} else if (layout == Layout.INTRINSIC) {
// Intrinsic uses an svg inside the sizer element rather than the padding
// trick Note a naked svg won't work becasue other thing expect the
// i-amphtml-sizer element
const sizer = htmlFor(element)`
<i-amphtml-sizer class="i-amphtml-sizer">
<img alt="" role="presentation" aria-hidden="true"
class="i-amphtml-intrinsic-sizer" />
</i-amphtml-sizer>`;
const intrinsicSizer = sizer.firstElementChild;
intrinsicSizer.setAttribute(
'src',
`data:image/svg+xml;charset=utf-8,<svg height="${height}" width="${width}" xmlns="http://www.w3.org/2000/svg" version="1.1"/>`
);
element.insertBefore(sizer, element.firstChild);
element.sizerElement = sizer;
} else if (layout == Layout.FILL) {
// Do nothing.
} else if (layout == Layout.CONTAINER) {
// Do nothing. Elements themselves will check whether the supplied
// layout value is acceptable. In particular container is only OK
// sometimes.
} else if (layout == Layout.FLEX_ITEM) {
// Set height and width to a flex item if they exist.
// The size set to a flex item could be overridden by `display: flex` later.
if (width) {
setStyle(element, 'width', width);
}
if (height) {
setStyle(element, 'height', height);
}
} else if (layout == Layout.FLUID) {
element.classList.add('i-amphtml-layout-awaiting-size');
if (width) {
setStyle(element, 'width', width);
}
setStyle(element, 'height', 0);
}
// Mark the element as having completed static layout, in case it is cloned
// in the future.
element.setAttribute('i-amphtml-layout', layout);
return layout;
}