/
VideoWidget.astro
90 lines (86 loc) · 2.38 KB
/
VideoWidget.astro
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
---
const { widget } = Astro.props;
const placeholder = widget?.aposPlaceholder ? 'true' : '';
const url = widget?.video?.url;
---
<style>
video-widget {
width: 100%;
}
</style>
<video-widget
url={placeholder ? 'https://youtu.be/Q5UX9yexEyM' : url }
>
</video-widget>
<script>
class VideoWidget extends HTMLElement {
result: {
width: number,
height: number,
html: string
};
canvasEl: HTMLElement;
constructor() {
super();
this.init();
}
async init() {
const videoUrl = this.getAttribute('url');
if (!videoUrl) {
return;
}
this.result = await this.oembed(videoUrl);
this.renderVideo();
}
async oembed(url) {
const response = await fetch('/api/v1/@apostrophecms/oembed/query?' + new URLSearchParams({
url
}));
if (response.status >= 400) {
throw new Error(`oembed error code: ${response.status}`);
}
return response.json();
}
renderVideo() {
const shaker = document.createElement('div');
shaker.innerHTML = this.result.html;
const inner = shaker.firstChild;
if (!(inner && (inner instanceof HTMLElement))) {
throw new Error('First child must be an HTML element');
}
this.canvasEl = inner;
this.innerHTML = '';
if (!inner) {
return;
}
inner.removeAttribute('width');
inner.removeAttribute('height');
this.append(inner);
// wait for CSS width to be known
setTimeout(() => {
// If oembed results include width and height we can get the
// video aspect ratio right
if (this.result.width && this.result.height) {
inner.style.width = '100%';
this.resizeVideo();
// If we need to initially size the video, also resize it on window
// resize.
window.addEventListener('resize', this.resizeHandler.bind(this));
} else {
// No, so assume the oembed HTML code is responsive.
}
}, 0);
}
resizeVideo() {
this.canvasEl.style.height = ((this.result.height / this.result.width) * this.canvasEl.offsetWidth) + 'px';
}
resizeHandler() {
if (document.contains(this)) {
this.resizeVideo();
} else {
window.removeEventListener('resize', this.resizeHandler);
}
}
}
customElements.define('video-widget', VideoWidget);
</script>