This repository has been archived by the owner on Feb 6, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 181
/
deckdeckgo-lazy-img.tsx
303 lines (245 loc) · 7.34 KB
/
deckdeckgo-lazy-img.tsx
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
import {Component, Element, Event, EventEmitter, Method, Prop, Watch, h, State, Host} from '@stencil/core';
import {getSvgContent} from '../utils/request';
import {DeckDeckGoCustomLoad} from '../interfaces/custom-load';
/**
* @part img - A CSS :part to access the slotted <img />
*/
@Component({
tag: 'deckgo-lazy-img',
styleUrl: 'deckdeckgo-lazy-img.scss',
shadow: true
})
export class DeckdeckgoLazyImg {
@Element() el: HTMLElement;
/**
* An event emitted after initialization when the component did load
*/
@Event() lazyImgDidLoad: EventEmitter;
/**
* An event emitted when the shadowed image has loaded
*/
@Event() innerImgDidLoad: EventEmitter;
/**
* The image source (= src) to lazy load
*/
@Prop({reflect: true})
imgSrc: string;
/**
* The attribute "srcset" (= multiple URI) to lazy load in case you would like to provide multiple images for responsiveness
*/
@Prop({reflect: true})
imgSrcSet: string;
/**
* The image alternate text
*/
@Prop({reflect: true})
imgAlt: string;
/**
* The set of media conditions to indicates what image size would be best to choose
*/
@Prop({reflect: true})
imgSizes: string;
/**
* A string which specifies a set of offsets to add to the root's bounding_box when calculating intersections, effectively shrinking or growing the root for calculation purposes.
*/
@Prop()
observerRootMargin: string = '300px';
/**
* Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target.
*/
@Prop()
observerThreshold: number | number[] = 0.25;
/**
* An optional image which could be displayed in case the main image would not be resolved
*/
@Prop()
imgErrorSrc: string;
/**
* The SVG image source (= URI) to lazy load and to parse (no <img/> tag will be use to render the svg) aria-label string
*/
@Prop({reflect: true})
svgSrc: string;
/**
* If you are using the above SVG option, provide the accessibility information using this attribute
*/
@Prop({reflect: true})
ariaLabel: string;
/**
* An intrinsicsize for the native lazy-loading
*/
@Prop()
intrinsicsize: string;
/**
* The image width
*/
@Prop()
imgWidth: number;
/**
* The image height
*/
@Prop()
imgHeight: number;
/**
* In case you would like to take care by yourself to apply the load of the image. If turn to true then the component will emit an event customLoad when the image intersect the viewport instead of displaying it (doesn't apply for svg but only for img-src and img-src-set)
*/
@Prop()
customLoader: boolean = false;
/**
* If set to lazy, the web native lazy capability of the browser, if available, will be used to lazy load the image
*/
@Prop()
loading: 'lazy' | 'eager' = 'eager';
@State()
private svgContent: string;
private observer: IntersectionObserver;
@State()
private imgLoaded: boolean = false;
/**
* Emitted if component property custom-loader is set to true and if an image (img-src or img-src-set) has to be loaded.
*/
@Event()
customLoad: EventEmitter<DeckDeckGoCustomLoad>;
async componentDidLoad() {
await this.init();
this.lazyImgDidLoad.emit();
}
@Watch('imgSrc')
async handleAttrImgSrc() {
await this.init();
}
private async init() {
if ('loading' in HTMLImageElement.prototype && !this.svgSrc && this.loading === 'lazy') {
// In this case, loadImmediately apply the attributes but the platform will takes care of lazy loading the images
await this.loadImmediately();
} else if (window && 'IntersectionObserver' in window) {
await this.deferIntersectionObserverLoad();
} else {
await this.loadImmediately();
}
}
private loadImmediately(): Promise<void> {
return this.load();
}
private deferIntersectionObserverLoad(): Promise<void> {
return new Promise<void>((resolve) => {
this.observer = new IntersectionObserver(this.onIntersection, {
rootMargin: this.observerRootMargin,
threshold: this.observerThreshold
});
this.observer.observe(this.el.shadowRoot.host);
resolve();
});
}
/**
* This component also export an async method lazyLoad() in case you would like to trigger "manually" the loading of the image
*/
@Method()
lazyLoad(): Promise<void> {
return new Promise<void>(async (resolve) => {
await this.load();
resolve();
});
}
private onIntersection = async (entries: IntersectionObserverEntry[]) => {
if (!entries || entries.length <= 0) {
return;
}
await this.handleIntersection(entries[0]);
};
private handleIntersection(entry: IntersectionObserverEntry): Promise<void> {
return new Promise<void>(async (resolve) => {
if (entry.isIntersecting) {
if (this.observer) {
this.observer.disconnect();
}
await this.load();
}
resolve();
});
}
private load(): Promise<void> {
return new Promise<void>(async (resolve) => {
if (this.svgSrc) {
await this.loadSvg();
} else {
await this.loadImg();
}
resolve();
});
}
private loadImg(): Promise<void> {
return new Promise<void>((resolve) => {
const img: HTMLImageElement = this.el.shadowRoot.querySelector('img');
if (!img) {
resolve();
return;
}
if (this.customLoader) {
this.customLoad.emit({
imgElement: img,
imgSrc: this.imgSrc,
imgSrcSet: this.imgSrcSet
});
resolve();
return;
}
if (this.imgSrc) {
img.setAttribute('src', this.imgSrc);
}
if (this.imgSrcSet) {
img.setAttribute('srcset', this.imgSrcSet);
}
resolve();
});
}
private loadSvg(): Promise<void> {
return new Promise<void>(async (resolve) => {
try {
this.svgContent = await getSvgContent(this.svgSrc);
} catch (err) {
console.error(err);
}
resolve();
});
}
private loadError(): Promise<void> {
return new Promise<void>((resolve) => {
const img: HTMLImageElement = this.el.shadowRoot.querySelector('img');
if (!img) {
resolve();
return;
}
if (!this.imgErrorSrc || img.src === this.imgErrorSrc) {
resolve();
return;
}
if (img.src === this.imgSrc || img.srcset === this.imgSrcSet) {
img.src = this.imgErrorSrc;
}
resolve();
});
}
private onImgDidLoad() {
this.imgLoaded = true;
this.innerImgDidLoad.emit();
}
render() {
const hostClass: string = this.imgLoaded || this.svgContent ? 'loaded' : '';
if (this.svgContent) {
return (
<Host class={hostClass}>
<div innerHTML={this.svgContent} class="svg-container"></div>
</Host>
);
} else {
return <Host class={hostClass}>{this.renderImage()}</Host>;
}
}
private renderImage() {
// prettier-ignore
// @ts-ignore
return <img alt={this.imgLoaded ? (this.imgAlt ? this.imgAlt : this.imgSrc) : ''} loading={this.loading} sizes={this.imgSizes ? this.imgSizes : undefined} intrinsicsize={this.intrinsicsize}
width={this.imgWidth} height={this.imgHeight} part="img"
onLoad={() => this.onImgDidLoad()} onError={() => this.loadError()}/>
}
}