-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathd2l-image.js
111 lines (92 loc) · 2.17 KB
/
d2l-image.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
import { css, html, LitElement, nothing } from 'lit';
import { ifDefined } from 'lit/directives/if-defined.js';
class D2LImage extends LitElement {
static get properties() {
return {
/**
* Alternate text describing the image
* @type {string}
*/
alternateText: { type: String, attribute: 'alternate-text' },
/**
* URL of the image
* @type {string}
*/
imageUrl: { type: String, attribute: 'image-url' },
/**
* token used to authenticate the image retrieval
* @type {string}
*/
token: { type: String },
_imageUrl: { state: true }
};
}
static get styles() {
return css`
:host {
display: block;
}
img {
border-radius: var(--d2l-image-border-radius);
height: 100%;
object-fit: var(--d2l-image-object-fit);
width: 100%;
}
`;
}
constructor() {
super();
this.imageUrl = '';
this.alternateText = '';
this.token = undefined;
}
render() {
if (!this._imageUrl) {
return nothing;
}
return html`
<img alt="${this.alternateText}" src="${ifDefined(this._imageUrl)}">
`;
}
updated(changedProperties) {
if (changedProperties.has('imageUrl') || changedProperties.has('token')) {
this._loadImage();
}
}
async _loadImage() {
if (!this.imageUrl) {
return;
}
if (!this.token) {
this._imageUrl = this.imageUrl;
return;
}
let response;
try {
const tokenPromise = await (typeof (this.token) === 'function')
? this.token()
: Promise.resolve(this.token);
const tokenString = await tokenPromise;
const headers = new Headers();
if (tokenString) {
headers.append('Authorization', `Bearer ${tokenString}`);
}
response = await window.fetch(this.imageUrl, { method: 'GET', headers });
const blob = await response.blob();
this._imageUrl = URL.createObjectURL(blob);
this.dispatchEvent(new CustomEvent('d2l-image-loaded', {
bubbles: false,
composed: false,
detail: { response }
}));
} catch (e) {
this._imageUrl = this.imageUrl;
this.dispatchEvent(new CustomEvent('d2l-image-failed-to-load', {
bubbles: false,
composed: false,
detail: { response }
}));
}
}
}
customElements.define('d2l-image', D2LImage);