-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathImage.tsx
More file actions
382 lines (322 loc) · 10.5 KB
/
Copy pathImage.tsx
File metadata and controls
382 lines (322 loc) · 10.5 KB
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
import { Head, IS_BROWSER } from "$fresh/runtime.ts";
import type { JSX } from "preact";
import { createContext } from "preact";
import { forwardRef } from "preact/compat";
import { useContext } from "preact/hooks";
const DEFAULT_CDN_HOST = "https://decoims.com";
// CDN host can be overridden via DECO_CDN_HOST env var (server) or
// window.DECO.featureFlags.cdnHost (browser, injected by Events.tsx).
const getCdnHost = (): string => {
if (IS_BROWSER) {
// deno-lint-ignore no-explicit-any
return (globalThis as any).DECO?.featureFlags?.cdnHost ?? DEFAULT_CDN_HOST;
}
return Deno.env.get("DECO_CDN_HOST") ?? DEFAULT_CDN_HOST;
};
// Strip these prefixes before passing the remainder to the CDN's `?src=` so
// the worker hits GCS directly instead of doing an absolute-URL hop. The
// configured CDN host is included so a non-default DECO_CDN_HOST still
// strips correctly; the GCS deco-assets bucket is kept unconditionally as a
// well-known origin.
const getAssetUrlPrefixesToStrip = (): readonly string[] => [
`${getCdnHost()}/`,
"https://storage.googleapis.com/deco-assets/",
"https://assets.decocache.com/",
"https://deco-sites-assets.s3.sa-east-1.amazonaws.com/",
"https://data.decoassets.com/",
];
export type SetEarlyHint = (hint: string) => void;
export type Props =
& Omit<
JSX.IntrinsicElements["img"],
"width" | "height" | "preload"
>
& {
src: string;
/** @description Improves Web Vitals (CLS|LCP) */
width: number;
/** @description Improves Web Vitals (CLS|LCP) */
height?: number;
/** @description Web Vitals (LCP). Adds a link[rel="preload"] tag in head. Use one preload per page for better performance */
preload?: boolean;
/** @description Improves Web Vitals (LCP). Use high for LCP image. Auto for other images */
fetchPriority?: "high" | "low" | "auto";
/** @description Object-fit */
fit?: FitOptions;
/** @description Quality */
quality?: QualityOptions;
setEarlyHint?: SetEarlyHint;
};
export const FACTORS = [1, 2];
type FitOptions = "contain" | "cover";
// By default we use the platform image optimization, with functions like:
// optimizeVTEX, optimizeWake, optmizeShopify
// if you want to use deco optimization
// you can set the BYPASS_PLATFORM_IMAGE_OPTIMIZATION environment variable to true
// Default is false
const bypassPlatformImageOptimization = () =>
IS_BROWSER
// deno-lint-ignore no-explicit-any
? (globalThis as any).DECO?.featureFlags?.bypassPlatformImageOptimization
: Deno.env.get("BYPASS_PLATFORM_IMAGE_OPTIMIZATION") === "true";
// Default is false
const bypassDecoImageOptimization = () =>
IS_BROWSER
// deno-lint-ignore no-explicit-any
? (globalThis as any).DECO?.featureFlags?.bypassDecoImageOptimization
: Deno.env.get("BYPASS_DECO_IMAGE_OPTIMIZATION") === "true";
/** Quality options available per component (includes "original" = 100%). */
export type QualityOptions = "low" | "medium" | "high" | "original"; // 60% - 70% - 80% - 100%
/** Quality options for the site-wide default in mod.ts — "original" is excluded
* because a global 100% quality default would hurt performance. */
export type DefaultQualityOptions = "low" | "medium" | "high";
/** Provides the site-wide default quality to Image/Picture components.
* Typed as QualityOptions because components may override with "original". */
export const DefaultImageQualityContext = createContext<
QualityOptions | undefined
>(undefined);
interface OptimizationOptions {
originalSrc: string;
width: number;
height?: number;
factor: number;
fit: FitOptions;
quality?: QualityOptions;
}
const optmizeVNDA = (opts: OptimizationOptions) => {
const { width, height, originalSrc } = opts;
const src = new URL(originalSrc);
const [replaceStr] = /\/\d*x\d*/g.exec(src.pathname) ?? [""];
const pathname = src.pathname.replace(replaceStr, "");
const url = new URL(
`/${width}x${height}${pathname}${src.search}`,
src.origin,
);
return url.href;
};
const optmizeShopify = (opts: OptimizationOptions) => {
const { originalSrc, width, height } = opts;
const url = new URL(originalSrc);
url.searchParams.set("width", `${width}`);
url.searchParams.set("height", `${height}`);
url.searchParams.set("crop", "center");
return url.href;
};
const optimizeVTEX = (opts: OptimizationOptions) => {
const { originalSrc, width } = opts;
const src = new URL(originalSrc);
const [slash, arquivos, ids, rawId, ...rest] = src.pathname.split("/");
const [trueId] = rawId.split("-");
src.pathname = [
slash,
arquivos,
ids,
`${trueId}-${width}-0`,
...rest]
.join("/");
return src.href;
};
const optimizeWake = (opts: OptimizationOptions) => {
const { originalSrc, width, height } = opts;
const url = new URL(originalSrc);
url.searchParams.set("w", `${width}`);
url.searchParams.set("h", `${height}`);
return url.href;
};
const qualityToNumber = (quality: "low" | "medium" | "high" | "original") => {
switch (quality) {
case "low":
return 60;
case "medium":
return 70;
case "high":
return 80;
case "original":
return 100;
}
};
const optimizeSourei = (opts: OptimizationOptions) => {
const { originalSrc, width, height, fit, quality } = opts;
const url = new URL(originalSrc);
url.searchParams.set("w", `${width}`);
height && url.searchParams.set("h", `${height}`);
fit && url.searchParams.set("fit", fit);
quality &&
url.searchParams.set("q", qualityToNumber(quality).toString());
return url.href;
};
const optimizeMagento = (opts: OptimizationOptions) => {
const { originalSrc, width, height } = opts;
const url = new URL(originalSrc);
url.searchParams.set("width", `${width}`);
url.searchParams.set("height", `${height}`);
url.searchParams.set("canvas", `${width}:${height}`);
url.searchParams.set("optimize", "low");
url.searchParams.set("fit", opts.fit === "cover" ? "" : "bounds");
return url.href;
};
export const getOptimizedMediaUrl = (opts: OptimizationOptions) => {
const { originalSrc, width, height, fit, quality } = opts;
if (originalSrc.startsWith("data:")) {
return originalSrc;
}
if (!bypassPlatformImageOptimization()) {
if (originalSrc.startsWith("https://media-storage.soureicdn.com")) {
return optimizeSourei(opts);
}
if (originalSrc.includes("media/catalog/product")) {
return optimizeMagento(opts);
}
if (originalSrc.includes("fbitsstatic.net/img/")) {
return optimizeWake(opts);
}
if (originalSrc.startsWith("https://cdn.vnda.")) {
return optmizeVNDA(opts);
}
if (originalSrc.startsWith("https://cdn.shopify.com")) {
return optmizeShopify(opts);
}
if (
/(vteximg.com.br|vtexassets.com|myvtex.com)\/arquivos\/ids\/\d+/.test(
originalSrc,
)
) {
return optimizeVTEX(opts);
}
}
if (bypassDecoImageOptimization()) {
return originalSrc;
}
const params = new URLSearchParams();
params.set("fit", fit);
params.set("width", `${width}`);
height && params.set("height", `${height}`);
const srcQuality = quality ||
new URL(originalSrc, "https://a.com").searchParams.get("quality");
srcQuality && params.set("quality", srcQuality);
// Strip known CDN prefixes so the worker can hit GCS directly instead of
// doing an absolute-URL hop. Anything left (path + any query string —
// signed URLs, cache busters, etc.) is preserved verbatim through
// URLSearchParams encoding and recovered on the worker via
// searchParams.get("src").
const src = getAssetUrlPrefixesToStrip().reduce(
(acc, url) => acc.replace(url, ""),
opts.originalSrc,
);
params.set("src", src);
return `${getCdnHost()}/image?${params}`;
};
export const getSrcSet = (
originalSrc: string,
width: number,
height?: number,
fit?: FitOptions,
factors: number[] = FACTORS,
quality?: QualityOptions,
) => {
const srcSet = [];
for (let it = 0; it < factors.length; it++) {
const factor = factors[it];
const w = Math.trunc(factor * width);
const h = height && Math.trunc(factor * height);
const src = getOptimizedMediaUrl({
originalSrc,
width: w,
height: h,
factor,
fit: fit || "cover",
quality: quality,
});
if (src) {
srcSet.push(`${src} ${w}w`);
}
}
return srcSet.length > 0 ? srcSet.join(", ") : undefined;
};
export const getEarlyHintFromSrcProps = (srcProps: {
fetchpriority: "high" | "low" | "auto" | undefined;
src: string;
fit?: FitOptions;
width: number;
height?: number;
quality?: QualityOptions;
}) => {
const factor = FACTORS.at(-1)!;
const src = getOptimizedMediaUrl({
originalSrc: srcProps.src,
width: Math.trunc(srcProps.width * factor),
height: srcProps.height && Math.trunc(srcProps.height * factor),
fit: srcProps.fit || "cover",
factor,
quality: srcProps.quality,
});
const earlyHintParts = [
`<${src}>`,
`rel=preload`,
`as=image`,
];
if (srcProps?.fetchpriority) {
earlyHintParts.push(`fetchpriority=${srcProps.fetchpriority}`);
}
return earlyHintParts.join("; ");
};
const Image = forwardRef<HTMLImageElement, Props>((props, ref) => {
const { preload, loading = "lazy" } = props;
const defaultQuality = useContext(DefaultImageQualityContext);
const quality = props.quality ?? defaultQuality;
const shouldSetEarlyHint = !!props.setEarlyHint && preload;
const srcSet = props.srcSet ??
getSrcSet(
props.src,
props.width,
props.height,
props.fit,
shouldSetEarlyHint ? FACTORS.slice(-1) : FACTORS,
quality,
);
const linkProps = srcSet &&
({
imageSrcSet: srcSet,
imageSizes: props.sizes,
fetchPriority: props.fetchPriority,
media: props.media,
} as
| ""
| undefined
| {
imageSrcSet: string;
imageSizes: string | undefined;
fetchPriority: "high" | "low" | "auto" | undefined;
media: string | undefined;
});
if (!IS_BROWSER && shouldSetEarlyHint) {
props.setEarlyHint!(
getEarlyHintFromSrcProps({
width: props.width,
height: props.height,
fetchpriority: props.fetchPriority,
src: props.src,
quality,
}),
);
}
return (
<>
{preload && (
<Head>
<link as="image" rel="preload" href={props.src} {...linkProps} />
</Head>
)}
<img
{...props}
data-fresh-disable-lock
preload={undefined}
src={props.src}
srcSet={srcSet}
loading={loading}
ref={ref}
/>
</>
);
});
export default Image;