-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.ts
409 lines (377 loc) · 12.3 KB
/
index.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
import { defineComponent, h, ref, watchEffect, type PropType } from 'vue';
import {
absolutePositioning,
isIntersectionObserverAvailable,
isSsr,
tag,
toCss,
} from './utils';
import { useInView } from '../../composables/useInView';
import {
buildRegularSource,
buildSrcSet,
buildWebpSource,
} from '../NakedImage/utils';
import { Sizer } from './Sizer';
type Maybe<T> = T | null;
export type ResponsiveImageType = {
/** A base64-encoded thumbnail to offer during image loading */
base64?: Maybe<string>;
/** The height of the image */
height?: Maybe<number>;
/** The width of the image */
width: number;
/** The aspect ratio (width/height) of the image */
aspectRatio?: number;
/** The HTML5 `sizes` attribute for the image */
sizes?: Maybe<string>;
/** The fallback `src` attribute for the image */
src?: Maybe<string>;
/** The HTML5 `srcSet` attribute for the image */
srcSet?: Maybe<string>;
/** The HTML5 `srcSet` attribute for the image in WebP format, for browsers that support the format */
webpSrcSet?: Maybe<string>;
/** The background color for the image placeholder */
bgColor?: Maybe<string>;
/** Alternate text (`alt`) for the image */
alt?: Maybe<string>;
/** Title attribute (`title`) for the image */
title?: Maybe<string>;
};
type State = {
priority?: boolean;
inView: boolean;
loaded: boolean;
};
const imageAddStrategy = ({ priority, inView, loaded }: State) => {
if (priority) {
return true;
}
if (isSsr()) {
return false;
}
if (isIntersectionObserverAvailable()) {
return inView || loaded;
}
return true;
};
const imageShowStrategy = ({ priority, loaded }: State) => {
if (priority) {
return true;
}
if (isSsr()) {
return false;
}
if (isIntersectionObserverAvailable()) {
return loaded;
}
return true;
};
export const Image = defineComponent({
name: 'DatocmsImage',
inheritAttrs: false,
emits: ['load'],
props: {
/** The actual response you get from a DatoCMS `responsiveImage` GraphQL query */
data: {
type: Object as PropType<ResponsiveImageType>,
required: true,
},
/** Additional CSS class for the `<picture />` tag */
pictureClass: {
type: String,
},
/** Additional CSS class for the image inside the `<picture />` tag */
imgClass: {
type: String,
},
/** Additional CSS class for the placeholder image */
placeholderClass: {
type: String,
},
/** Duration (in ms) of the fade-in transition effect upoad image loading */
fadeInDuration: {
type: Number,
},
/** @deprecated Use the intersectionThreshold prop */
intersectionTreshold: {
type: Number,
default: 0,
},
/** Indicate at what percentage of the placeholder visibility the loading of the image should be triggered. A value of 0 means that as soon as even one pixel is visible, the callback will be run. A value of 1.0 means that the threshold isn't considered passed until every pixel is visible */
intersectionThreshold: {
type: Number,
},
/** Margin around the placeholder. Can have values similar to the CSS margin property (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the placeholder element's bounding box before computing intersections */
intersectionMargin: {
type: String,
default: '0px 0px 0px 0px',
},
/** Additional CSS rules to add to the `<picture />` tag */
pictureStyle: {
type: Object,
default: () => ({}),
},
/** Additional CSS rules to add to the image inside the `<picture />` tag */
imgStyle: {
type: Object,
default: () => ({}),
},
/** Additional CSS rules to add to the placeholder image */
placeholderStyle: {
type: Object,
default: () => ({}),
},
/**
* The layout behavior of the image as the viewport changes size
*
* Possible values:
*
* * `intrinsic`: the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports
* * `fixed`: the image dimensions will not change as the viewport changes (no responsiveness) similar to the native img element
* * `responsive` (default): the image will scale the dimensions down for smaller viewports and scale up for larger viewports
* * `fill`: image will stretch both width and height to the dimensions of the parent element, provided the parent element is `relative`
**/
layout: {
type: String,
default: () => 'intrinsic',
validator: (value: string) =>
['intrinsic', 'fixed', 'responsive', 'fill'].includes(value),
},
/** Defines how the image will fit into its parent container when using layout="fill" */
objectFit: {
type: String,
},
/** Defines how the image is positioned within its parent element when using layout="fill". */
objectPosition: {
type: String,
},
/** Whether the component should use a blurred image placeholder */
usePlaceholder: {
type: Boolean,
default: true,
},
/**
* The HTML5 `sizes` attribute for the image
*
* Learn more about srcset and sizes:
* -> https://web.dev/learn/design/responsive-images/#sizes
* -> https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes
**/
sizes: {
type: String,
},
/**
* When true, the image will be considered high priority. Lazy loading is automatically disabled, and fetchpriority="high" is added to the image.
* You should use the priority property on any image detected as the Largest Contentful Paint (LCP) element. It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes.
* Should only be used when the image is visible above the fold.
**/
priority: {
type: Boolean,
default: false,
},
/**
* If `data` does not contain `srcSet`, the candidates for the `srcset` of the image will be auto-generated based on these width multipliers
*
* Default candidate multipliers are [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4]
**/
srcSetCandidates: {
type: Array,
validator: (values: any[]): values is number[] =>
values.every((value): value is number => {
return typeof value === 'number';
}),
default: () => [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4],
},
},
setup(props, { emit, expose }) {
const loaded = ref(false);
function handleLoad() {
emit('load');
loaded.value = true;
}
const { inView, elRef: rootRef } = useInView({
threshold: props.intersectionThreshold || props.intersectionTreshold || 0,
rootMargin: props.intersectionMargin || '0px 0px 0px 0px',
});
const imageRef = ref<HTMLImageElement>();
// See: https://stackoverflow.com/q/39777833/266535
watchEffect(() => {
if (!imageRef.value) {
return;
}
if (imageRef.value.complete && imageRef.value.naturalWidth) {
handleLoad();
}
});
expose({
rootRef,
imageRef,
});
return {
inView,
rootRef,
loaded,
handleLoad,
imageRef,
};
},
render() {
const addImage = imageAddStrategy({
priority: this.priority,
inView: this.inView,
loaded: this.loaded,
});
const showImage = imageShowStrategy({
priority: this.priority,
inView: this.inView,
loaded: this.loaded,
});
const webpSource = buildWebpSource(this.data, this.sizes);
const regularSource = buildRegularSource(
this.data,
this.sizes,
this.srcSetCandidates,
);
const transition =
typeof this.fadeInDuration === 'undefined' || this.fadeInDuration > 0
? `opacity ${this.fadeInDuration || 500}ms`
: undefined;
const basePlaceholderStyle = {
transition: transition,
opacity: showImage ? 0 : 1,
// During the opacity transition of the placeholder to the definitive version,
// hardware acceleration is triggered. This results in the browser trying to render the
// placeholder with your GPU, causing blurred edges. Solution: style the placeholder
// so the edges overflow the container
position: 'absolute',
left: '-5%',
top: '-5%',
width: '110%',
height: this.data.base64 ? 'auto' : '110%',
maxWidth: 'none',
maxHeight: 'none',
...this.placeholderStyle,
};
const placeholder =
this.usePlaceholder && this.data.base64
? h('img', {
'aria-hidden': 'true',
src: this.data.base64,
class: this.placeholderClass,
style: {
objectFit: this.objectFit,
objectPosition: this.objectPosition,
...basePlaceholderStyle,
},
})
: this.usePlaceholder && this.data.bgColor
? h('div', {
class: this.placeholderClass,
style: {
backgroundColor: this.data.bgColor,
...basePlaceholderStyle,
},
})
: null;
const { width, aspectRatio } = this.data;
const height = this.data.height ?? (aspectRatio ? width / aspectRatio : 0);
const sizer =
this.layout !== 'fill'
? h(Sizer, {
sizerClass: this.imgClass,
sizerStyle: this.imgStyle,
width,
height,
})
: null;
return h(
'div',
{
class: this.$attrs.class,
style: {
overflow: 'hidden',
...(this.layout === 'fill'
? absolutePositioning
: this.layout === 'intrinsic'
? { position: 'relative', width: '100%', maxWidth: `${width}px` }
: this.layout === 'fixed'
? { position: 'relative', width: `${width}px` }
: { position: 'relative', width: '100%' }),
...(this.$attrs.style || {}),
},
ref: 'rootRef',
},
[
sizer,
placeholder,
addImage &&
h('picture', { class: this.pictureClass, style: this.pictureStyle }, [
webpSource,
regularSource,
this.data.src &&
h('img', {
src: this.data.src,
alt: this.data.alt,
title: this.data.title,
fetchpriority: this.priority ? 'high' : undefined,
onLoad: this.handleLoad,
ref: 'imageRef',
class: this.imgClass,
style: {
opacity: showImage ? 1 : 0,
transition,
...absolutePositioning,
objectFit: this.objectFit,
objectPosition: this.objectPosition,
...this.imgStyle,
},
}),
]),
h('noscript', {
innerHTML: tag(
'picture',
{ class: this.pictureClass, style: toCss(this.pictureStyle) },
[
this.data.webpSrcSet &&
tag('source', {
srcset: this.data.webpSrcSet,
sizes: this.sizes ?? this.data.sizes ?? undefined,
type: 'image/webp',
}),
tag('source', {
srcset:
this.data.srcSet ??
buildSrcSet(
this.data.src,
this.data.width,
this.srcSetCandidates as number[],
),
sizes: this.sizes ?? this.data.sizes ?? undefined,
}),
tag('img', {
src: this.data.src,
alt: this.data.alt,
title: this.data.title,
class: this.imgClass,
style: toCss({
...absolutePositioning,
objectFit: this.objectFit,
objectPosition: this.objectPosition,
...this.imgStyle,
}),
loading: this.priority ? undefined : 'lazy',
fetchpriority: this.priority ? 'high' : undefined,
}),
],
),
}),
],
);
},
});
export const DatocmsImagePlugin = {
install: (Vue: any) => {
Vue.component('DatocmsImage', Image);
},
};