-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathlite-youtube.ts
557 lines (490 loc) · 17.2 KB
/
lite-youtube.ts
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
/**
*
* The shadowDom / Intersection Observer version of Paul's concept:
* https://github.com/paulirish/lite-youtube-embed
*
* A lightweight YouTube embed. Still should feel the same to the user, just
* MUCH faster to initialize and paint.
*
* Thx to these as the inspiration
* https://storage.googleapis.com/amp-vs-non-amp/youtube-lazy.html
* https://autoplay-youtube-player.glitch.me/
*
* Once built it, I also found these (👍👍):
* https://github.com/ampproject/amphtml/blob/master/extensions/amp-youtube
* https://github.com/Daugilas/lazyYT https://github.com/vb/lazyframe
*/
export class LiteYTEmbed extends HTMLElement {
shadowRoot!: ShadowRoot;
private domRefFrame!: HTMLDivElement;
private domRefImg!: {
fallback: HTMLImageElement;
webp: HTMLSourceElement;
jpeg: HTMLSourceElement;
};
private domRefPlayButton!: HTMLButtonElement;
private static isPreconnected = false;
private isIframeLoaded = false;
constructor() {
super();
this.setupDom();
}
static get observedAttributes(): string[] {
return ['videoid', 'playlistid', 'videoplay', 'videotitle'];
}
connectedCallback(): void {
this.addEventListener(
'pointerover',
() => LiteYTEmbed.warmConnections(this),
{
once: true,
},
);
this.addEventListener('click', () => this.addIframe());
}
get videoId(): string {
return encodeURIComponent(this.getAttribute('videoid') || '');
}
set videoId(id: string) {
this.setAttribute('videoid', id);
}
get playlistId(): string {
return encodeURIComponent(this.getAttribute('playlistid') || '');
}
set playlistId(id: string) {
this.setAttribute('playlistid', id);
}
get videoTitle(): string {
return this.getAttribute('videotitle') || 'Video';
}
set videoTitle(title: string) {
this.setAttribute('videotitle', title);
}
get videoPlay(): string {
return this.getAttribute('videoplay') || 'Play';
}
set videoPlay(name: string) {
this.setAttribute('videoplay', name);
}
get videoStartAt(): string {
return this.getAttribute('videoStartAt') || '0';
}
get autoLoad(): boolean {
return this.hasAttribute('autoload');
}
get autoPause(): boolean {
return this.hasAttribute('autopause');
}
get noCookie(): boolean {
return this.hasAttribute('nocookie');
}
get posterQuality(): string {
return this.getAttribute('posterquality') || 'hqdefault';
}
get posterLoading(): HTMLImageElement['loading'] {
return (
(this.getAttribute('posterloading') as HTMLImageElement['loading']) ||
'lazy'
);
}
get params(): string {
return `start=${this.videoStartAt}&${this.getAttribute('params')}`;
}
set params(opts: string) {
this.setAttribute('params', opts);
}
set posterQuality(opts: string) {
this.setAttribute('posterquality', opts);
}
/**
* Define our shadowDOM for the component
*/
private setupDom(): void {
const shadowDom = this.attachShadow({ mode: 'open' });
let nonce = '';
if (window.liteYouTubeNonce) {
nonce = `nonce="${window.liteYouTubeNonce}"`;
}
shadowDom.innerHTML = `
<style ${nonce}>
:host {
--aspect-ratio: var(--lite-youtube-aspect-ratio, 16 / 9);
--aspect-ratio-short: var(--lite-youtube-aspect-ratio-short, 9 / 16);
--frame-shadow-visible: var(--lite-youtube-frame-shadow-visible, yes);
contain: content;
display: block;
position: relative;
width: 100%;
aspect-ratio: var(--aspect-ratio);
}
@media (max-width: 40em) {
:host([short]) {
aspect-ratio: var(--aspect-ratio-short);
}
}
#frame, #fallbackPlaceholder, iframe {
position: absolute;
width: 100%;
height: 100%;
left: 0;
}
#frame {
cursor: pointer;
}
#fallbackPlaceholder, slot[name=image]::slotted(*) {
object-fit: cover;
width: 100%;
}
@container style(--frame-shadow-visible: yes) {
#frame::before {
content: '';
display: block;
position: absolute;
top: 0;
background-image: linear-gradient(180deg, #111 -20%, transparent 90%);
height: 60px;
width: 100%;
z-index: 1;
}
}
#playButton {
width: 68px;
height: 48px;
background-color: transparent;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 68 48"><path d="M66.52 7.74c-.78-2.93-2.49-5.41-5.42-6.19C55.79.13 34 0 34 0S12.21.13 6.9 1.55c-2.93.78-4.63 3.26-5.42 6.19C.06 13.05 0 24 0 24s.06 10.95 1.48 16.26c.78 2.93 2.49 5.41 5.42 6.19C12.21 47.87 34 48 34 48s21.79-.13 27.1-1.55c2.93-.78 4.64-3.26 5.42-6.19C67.94 34.95 68 24 68 24s-.06-10.95-1.48-16.26z" fill="red"/><path d="M45 24 27 14v20" fill="white"/></svg>');
z-index: 1;
border: 0;
border-radius: inherit;
}
#playButton:before {
content: '';
border-style: solid;
border-width: 11px 0 11px 19px;
border-color: transparent transparent transparent #fff;
}
#playButton,
#playButton:before {
position: absolute;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
cursor: inherit;
}
/* Post-click styles */
.activated {
cursor: unset;
}
#frame.activated::before,
#frame.activated > #playButton {
display: none;
}
</style>
<div id="frame">
<picture>
<slot name="image">
<source id="webpPlaceholder" type="image/webp">
<source id="jpegPlaceholder" type="image/jpeg">
<img id="fallbackPlaceholder" referrerpolicy="origin" loading="lazy">
</slot>
</picture>
<button id="playButton"></button>
</div>
`;
this.domRefFrame = shadowDom.querySelector<HTMLDivElement>('#frame')!;
this.domRefImg = {
fallback: shadowDom.querySelector('#fallbackPlaceholder')!,
webp: shadowDom.querySelector('#webpPlaceholder')!,
jpeg: shadowDom.querySelector('#jpegPlaceholder')!,
};
this.domRefPlayButton = shadowDom.querySelector('#playButton')!;
}
/**
* Parse our attributes and fire up some placeholders
*/
private setupComponent(): void {
// If the named slot is not empty, then we save the network requests and
// don't fire up the selector; we use assignedNodes() since we're using
// default slot elements for the picture
const hasImgSlot: HTMLSlotElement =
this.shadowRoot.querySelector('slot[name=image]')!;
if (hasImgSlot.assignedNodes().length === 0) {
this.initImagePlaceholder();
}
this.domRefPlayButton.setAttribute(
'aria-label',
`${this.videoPlay}: ${this.videoTitle}`,
);
this.setAttribute('title', `${this.videoPlay}: ${this.videoTitle}`);
if (this.autoLoad || this.isYouTubeShort() || this.autoPause) {
this.initIntersectionObserver();
}
this.injectSearchNoScript();
}
/**
* Lifecycle method that we use to listen for attribute changes to period
* @param {*} name
* @param {*} oldVal
* @param {*} newVal
*/
attributeChangedCallback(
name: string,
oldVal: unknown,
newVal: unknown,
): void {
if (oldVal !== newVal) {
this.setupComponent();
// if we have a previous iframe, remove it and the activated class
if (this.domRefFrame.classList.contains('activated')) {
this.domRefFrame.classList.remove('activated');
this.shadowRoot.querySelector('iframe')!.remove();
this.isIframeLoaded = false;
}
}
}
// h/t @paulirish et al
// https://github.com/paulirish/lite-youtube-embed/issues/105
// differs in that we inject into the lightdom above any other nodes so our
// slots or fallbacks still work
private injectSearchNoScript(): void {
const eleNoScript = document.createElement('noscript');
this.prepend(eleNoScript);
eleNoScript.innerHTML = this.generateIframe();
}
private generateIframe(isIntersectionObserver = false): string {
let autoplay = isIntersectionObserver ? 0 : 1;
const wantsNoCookie = this.noCookie ? '-nocookie' : '';
let embedTarget;
if (this.playlistId) {
embedTarget = `?listType=playlist&list=${this.playlistId}&`;
} else {
embedTarget = `${this.videoId}?`;
}
// autopause needs the postMessage() in the iframe, so you have to enable
// the jsapi
if (this.autoPause) {
this.params = `enablejsapi=1`;
}
// Oh wait, you're a YouTube short, so let's try to make you more workable
if (this.isYouTubeShort()) {
this.params = `loop=1&mute=1&modestbranding=1&playsinline=1&rel=0&enablejsapi=1&playlist=${this.videoId}`;
autoplay = 1;
}
return `
<iframe credentialless frameborder="0" title="${this.videoTitle}"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen
src="https://www.youtube${wantsNoCookie}.com/embed/${embedTarget}autoplay=${autoplay}&${this.params}"
></iframe>`;
}
/**
* Inject the iframe into the component body
* @param {boolean} isIntersectionObserver
*/
private addIframe(isIntersectionObserver = false): void {
if (!this.isIframeLoaded) {
// Don't autoplay the intersection observer injection, it's weird
const iframeHTML = this.generateIframe(isIntersectionObserver);
this.domRefFrame.insertAdjacentHTML('beforeend', iframeHTML);
this.domRefFrame.classList.add('activated');
this.isIframeLoaded = true;
this.attemptShortAutoPlay();
this.dispatchEvent(
new CustomEvent('liteYoutubeIframeLoaded', {
detail: {
videoId: this.videoId,
},
bubbles: true,
cancelable: true,
}),
);
}
}
/**
* Setup the placeholder image for the component
*/
private initImagePlaceholder(): void {
this.testPosterImage();
this.domRefImg.fallback.setAttribute(
'aria-label',
`${this.videoPlay}: ${this.videoTitle}`,
);
this.domRefImg?.fallback?.setAttribute(
'alt',
`${this.videoPlay}: ${this.videoTitle}`,
);
}
/**
* Slightly varied approach for our shadowDOM, but identical lookup approach to
* paulirish's https://github.com/paulirish/lite-youtube-embed
*
* Note, this won't run if the named slot=image is defined
*/
private async testPosterImage(): Promise<void> {
setTimeout(() => {
const webpUrl = `https://i.ytimg.com/vi_webp/${this.videoId}/${this.posterQuality}.webp`;
const img = new Image();
img.fetchPriority = 'low'; // low priority to reduce network contention
img.referrerPolicy = 'origin'; // Not 100% sure it's needed, but https://github.com/ampproject/amphtml/pull/3940
img.src = webpUrl;
img.onload = async e => {
const target = e.target as HTMLImageElement;
// A pretty ugly hack since onerror won't fire on YouTube image 404.
// This is (probably) due to Youtube's style of returning data even with
// a 404 status. That data is a 120x90 placeholder image.
const noPoster =
target?.naturalHeight == 90 && target?.naturalWidth == 120;
// Diverge: this differs from Paul's in that I have a specific opinion
// about the fallback, given that we allow <slot> overriding and that
// having tested this against a lot of different cases, the safest
// fallback with respect to a missing poster appears to be the hqdefault
// even in cases where the maxresdefault for a JPG (which I find
// _doesn't_ actually always exist for the JPG case either as reported
// by some folks)
if (noPoster) {
this.posterQuality = 'hqdefault';
}
const posterUrlWebp = `https://i.ytimg.com/vi_webp/${this.videoId}/${this.posterQuality}.webp`;
this.domRefImg.webp.srcset = posterUrlWebp;
const posterUrlJpeg = `https://i.ytimg.com/vi/${this.videoId}/${this.posterQuality}.jpg`;
this.domRefImg.fallback.loading = this.posterLoading;
this.domRefImg.jpeg.srcset = posterUrlJpeg;
this.domRefImg.fallback.src = posterUrlJpeg;
this.domRefImg.fallback.loading = this.posterLoading;
};
}, 100);
}
/**
* Setup the Intersection Observer to load the iframe when scrolled into view
*/
private initIntersectionObserver(): void {
const options = {
root: null,
rootMargin: '0px',
threshold: 0,
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting && !this.isIframeLoaded) {
LiteYTEmbed.warmConnections(this);
this.addIframe(true);
observer.unobserve(this);
}
});
}, options);
observer.observe(this);
// this needs the iframe loaded, so it has to run post the IO load at the
// least otherwise things will break
if (this.autoPause) {
const windowPause = new IntersectionObserver(
(e, o) => {
e.forEach(entry => {
if (entry.intersectionRatio !== 1) {
this.shadowRoot
.querySelector('iframe')
?.contentWindow?.postMessage(
'{"event":"command","func":"pauseVideo","args":""}',
'*',
);
}
});
},
{ threshold: 1 },
);
windowPause.observe(this);
}
}
/**
* This is a terrible hack to attempt to get YouTube Short-like autoplay on
* mobile viewports. It's this way because:
* 1. YouTube's Iframe embed does not offer determinism when loading
* 2. Attempting to use onYouTubeIframeAPIReady() does not work in 99% of
* cases
* 3. You can _technically_ load the Frame API library and do more advanced
* things, but I don't want to burn the thread of the wire with its
* shenanigans since this an edge case.
* @private
*/
private attemptShortAutoPlay() {
if (this.isYouTubeShort()) {
setTimeout(() => {
this.shadowRoot
.querySelector('iframe')
?.contentWindow?.postMessage(
'{"event":"command","func":"' + 'playVideo' + '","args":""}',
'*',
);
// for youtube video recording demo
}, 2000);
}
}
/**
* A hacky attr check and viewport peek to see if we're going to try to enable
* a more friendly YouTube Short style loading
* @returns boolean
*/
private isYouTubeShort(): boolean {
return (
this.getAttribute('short') === '' &&
window.matchMedia('(max-width: 40em)').matches
);
}
/**
* Add a <link rel={preload | preconnect} ...> to the head
* @param {string} kind
* @param {string} url
* @param {string} as
*/
private static addPrefetch(kind: string, url: string): void {
const linkElem = document.createElement('link');
linkElem.rel = kind;
linkElem.href = url;
linkElem.crossOrigin = 'true';
document.head.append(linkElem);
}
/**
* Begin preconnecting to warm up the iframe load Since the embed's network
* requests load within its iframe, preload/prefetch'ing them outside the
* iframe will only cause double-downloads. So, the best we can do is warm up
* a few connections to origins that are in the critical path.
*
* Maybe `<link rel=preload as=document>` would work, but it's unsupported:
* http://crbug.com/593267 But TBH, I don't think it'll happen soon with Site
* Isolation and split caches adding serious complexity.
*/
private static warmConnections(context: LiteYTEmbed): void {
if (LiteYTEmbed.isPreconnected || window.liteYouTubeIsPreconnected) return;
// we don't know which image type to preload, so warm the connection
LiteYTEmbed.addPrefetch('preconnect', 'https://i.ytimg.com/');
// Host that YT uses to serve JS needed by player, per amp-youtube
LiteYTEmbed.addPrefetch('preconnect', 'https://s.ytimg.com');
if (!context.noCookie) {
// The iframe document and most of its subresources come right off
// youtube.com
LiteYTEmbed.addPrefetch('preconnect', 'https://www.youtube.com');
// The botguard script is fetched off from google.com
LiteYTEmbed.addPrefetch('preconnect', 'https://www.google.com');
// TODO: Not certain if these ad related domains are in the critical path.
// Could verify with domain-specific throttling.
LiteYTEmbed.addPrefetch(
'preconnect',
'https://googleads.g.doubleclick.net',
);
LiteYTEmbed.addPrefetch('preconnect', 'https://static.doubleclick.net');
} else {
LiteYTEmbed.addPrefetch('preconnect', 'https://www.youtube-nocookie.com');
}
LiteYTEmbed.isPreconnected = true;
// multiple embeds in the same page don't check for each other
window.liteYouTubeIsPreconnected = true;
}
}
// Register custom element
customElements.define('lite-youtube', LiteYTEmbed);
declare global {
interface HTMLElementTagNameMap {
'lite-youtube': LiteYTEmbed;
}
interface Window {
liteYouTubeNonce: string;
liteYouTubeIsPreconnected: boolean;
}
}