@webstudio-is/image 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/lib/__generated__/image.props.json +575 -0
  2. package/lib/cjs/__generated__/image.props.json +575 -0
  3. package/lib/cjs/image-dev.stories.cjs +77 -0
  4. package/lib/cjs/image-dev.stories.d.ts +35 -0
  5. package/lib/cjs/image-dev.stories.d.ts.map +1 -0
  6. package/lib/cjs/image-loaders.cjs +39 -0
  7. package/lib/cjs/image-loaders.d.ts +14 -0
  8. package/lib/cjs/image-loaders.d.ts.map +1 -0
  9. package/lib/cjs/image-optimize.cjs +187 -0
  10. package/lib/cjs/image-optimize.d.ts +107 -0
  11. package/lib/cjs/image-optimize.d.ts.map +1 -0
  12. package/lib/cjs/image-optimize.test.cjs +157 -0
  13. package/lib/cjs/image-optimize.test.d.ts +2 -0
  14. package/lib/cjs/image-optimize.test.d.ts.map +1 -0
  15. package/lib/cjs/image.cjs +49 -0
  16. package/lib/cjs/image.d.ts +11 -0
  17. package/lib/cjs/image.d.ts.map +1 -0
  18. package/lib/cjs/index.cjs +34 -0
  19. package/lib/cjs/index.d.ts +5 -0
  20. package/lib/cjs/index.d.ts.map +1 -0
  21. package/lib/image-dev.stories.d.ts +35 -0
  22. package/lib/image-dev.stories.d.ts.map +1 -0
  23. package/lib/image-dev.stories.js +65 -0
  24. package/lib/image-loaders.d.ts +14 -0
  25. package/lib/image-loaders.d.ts.map +1 -0
  26. package/lib/image-loaders.js +31 -0
  27. package/lib/image-optimize.d.ts +107 -0
  28. package/lib/image-optimize.d.ts.map +1 -0
  29. package/lib/image-optimize.js +183 -0
  30. package/lib/image-optimize.test.d.ts +2 -0
  31. package/lib/image-optimize.test.d.ts.map +1 -0
  32. package/lib/image-optimize.test.js +155 -0
  33. package/lib/image.d.ts +11 -0
  34. package/lib/image.d.ts.map +1 -0
  35. package/lib/image.js +46 -0
  36. package/lib/index.d.ts +5 -0
  37. package/lib/index.d.ts.map +1 -0
  38. package/lib/index.js +3 -0
  39. package/lib/tsconfig.tsbuildinfo +1 -0
  40. package/package.json +62 -0
@@ -0,0 +1,35 @@
1
+ import React from "react";
2
+ import type { ComponentMeta, ComponentStory } from "@storybook/react";
3
+ declare const _default: ComponentMeta<React.ForwardRefExoticComponent<Pick<React.ClassAttributes<HTMLImageElement> & React.ImgHTMLAttributes<HTMLImageElement> & {
4
+ quality?: number | undefined;
5
+ optimize?: boolean | undefined;
6
+ loader: import("./image-optimize").ImageLoader;
7
+ }, "quality" | "loader" | "key" | keyof React.ImgHTMLAttributes<HTMLImageElement> | "optimize"> & React.RefAttributes<HTMLImageElement>>>;
8
+ export default _default;
9
+ /**
10
+ * Load images depending on image width and device per pixel ratio.
11
+ **/
12
+ export declare const FixedWidthImage: ComponentStory<React.FunctionComponent>;
13
+ /**
14
+ * Preserve ratio using object-fit: cover. Load images depending on image width and device per pixel ratio.
15
+ **/
16
+ export declare const FixedWidthImageCover: ComponentStory<React.FunctionComponent>;
17
+ /**
18
+ * Load images depending on the viewport width.
19
+ **/
20
+ export declare const UnknownWidthImage: ComponentStory<React.FunctionComponent>;
21
+ /**
22
+ * Fit width of the parent container, has own aspect-ratio and object-fit=cover.
23
+ * Load images depending on the viewport width.
24
+ **/
25
+ export declare const AspectRatioImage: ComponentStory<React.FunctionComponent>;
26
+ /**
27
+ * Fill width and height of the relative parent container, object-fit=cover. Load images depending on the viewport width.
28
+ **/
29
+ export declare const FillParentImage: ComponentStory<React.FunctionComponent>;
30
+ /**
31
+ * "sizes" attribute explicitly equal to 100vw allowing to skip the default behavior.
32
+ * See DEFAULT_SIZES in the Image component. Load images depending on the viewport width.
33
+ **/
34
+ export declare const HeroImage: ComponentStory<React.FunctionComponent>;
35
+ //# sourceMappingURL=image-dev.stories.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-dev.stories.d.ts","sourceRoot":"","sources":["../src/image-dev.stories.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAmD,MAAM,OAAO,CAAC;AACxE,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;;;;;;AAQtE,wBAE0C;AA0C1C;;IAEI;AACJ,eAAO,MAAM,eAAe,EAAE,cAAc,CAAC,KAAK,CAAC,iBAAiB,CAEnE,CAAC;AAEF;;IAEI;AACJ,eAAO,MAAM,oBAAoB,EAAE,cAAc,CAC/C,KAAK,CAAC,iBAAiB,CAQxB,CAAC;AAEF;;IAEI;AACJ,eAAO,MAAM,iBAAiB,EAAE,cAAc,CAC5C,KAAK,CAAC,iBAAiB,CACa,CAAC;AAEvC;;;IAGI;AACJ,eAAO,MAAM,gBAAgB,EAAE,cAAc,CAAC,KAAK,CAAC,iBAAiB,CAOpE,CAAC;AAEF;;IAEI;AACJ,eAAO,MAAM,eAAe,EAAE,cAAc,CAAC,KAAK,CAAC,iBAAiB,CAYnE,CAAC;AAEF;;;IAGI;AACJ,eAAO,MAAM,SAAS,EAAE,cAAc,CAAC,KAAK,CAAC,iBAAiB,CAU7D,CAAC"}
@@ -0,0 +1,65 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Image as ImagePrimitive, loaders } from "./";
3
+ // to not allow include local assets everywhere, just enable it for this file
4
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
5
+ // @ts-ignore
6
+ import localLogoImage from "../storybook-assets/logo.webp";
7
+ export default {
8
+ title: "Components/ImageDev",
9
+ };
10
+ /**
11
+ * In case you need to test img with real cloudflare trasforms
12
+ * set USE_CLOUDFLARE_IMAGE_TRANSFORM = true
13
+ **/
14
+ const USE_CLOUDFLARE_IMAGE_TRANSFORM = false;
15
+ // For cloudflare image transform testing, logo should be the most consistent image on the site
16
+ const REMOTE_SELF_DOMAIN_IMAGE = "https://webstudio.is/logo.webp";
17
+ const imageSrc = USE_CLOUDFLARE_IMAGE_TRANSFORM
18
+ ? REMOTE_SELF_DOMAIN_IMAGE
19
+ : localLogoImage;
20
+ const imageLoader = USE_CLOUDFLARE_IMAGE_TRANSFORM
21
+ ? loaders.cloudflareImageLoader({ resizeOrigin: "https://webstudio.is" })
22
+ : loaders.localImageLoader();
23
+ const ImageBase = (args) => {
24
+ const style = {
25
+ maxWidth: "100%",
26
+ display: "block",
27
+ ...args.style,
28
+ };
29
+ return (_jsx(ImagePrimitive, { ...args, optimize: true, loader: imageLoader, style: style }));
30
+ };
31
+ /**
32
+ * Load images depending on image width and device per pixel ratio.
33
+ **/
34
+ export const FixedWidthImage = () => (_jsx(ImageBase, { src: imageSrc, width: "300", height: "400" }));
35
+ /**
36
+ * Preserve ratio using object-fit: cover. Load images depending on image width and device per pixel ratio.
37
+ **/
38
+ export const FixedWidthImageCover = () => (_jsx(ImageBase, { src: imageSrc, width: "300", height: "400", style: { objectFit: "cover" } }));
39
+ /**
40
+ * Load images depending on the viewport width.
41
+ **/
42
+ export const UnknownWidthImage = () => _jsx(ImageBase, { src: imageSrc });
43
+ /**
44
+ * Fit width of the parent container, has own aspect-ratio and object-fit=cover.
45
+ * Load images depending on the viewport width.
46
+ **/
47
+ export const AspectRatioImage = () => (_jsx("div", { style: { width: "50%" }, children: _jsx(ImageBase, { src: imageSrc, style: { aspectRatio: "2/1", objectFit: "cover", width: "100%" } }) }));
48
+ /**
49
+ * Fill width and height of the relative parent container, object-fit=cover. Load images depending on the viewport width.
50
+ **/
51
+ export const FillParentImage = () => (_jsx("div", { style: { width: "50%", aspectRatio: "2/1", position: "relative" }, children: _jsx(ImageBase, { src: imageSrc, style: {
52
+ objectFit: "cover",
53
+ position: "absolute",
54
+ width: "100%",
55
+ height: "100%",
56
+ } }) }));
57
+ /**
58
+ * "sizes" attribute explicitly equal to 100vw allowing to skip the default behavior.
59
+ * See DEFAULT_SIZES in the Image component. Load images depending on the viewport width.
60
+ **/
61
+ export const HeroImage = () => (_jsx(ImageBase, { src: imageSrc, sizes: "100vw", style: {
62
+ aspectRatio: "3/1",
63
+ objectFit: "cover",
64
+ width: "100%",
65
+ } }));
@@ -0,0 +1,14 @@
1
+ import { type ImageLoader } from "./image-optimize";
2
+ export declare type CloudflareImageLoaderOptions = {
3
+ resizeOrigin?: string | null;
4
+ };
5
+ /**
6
+ * Default image loader in case of no loader provided
7
+ * https://developers.cloudflare.com/images/image-resizing/url-format/
8
+ **/
9
+ export declare const cloudflareImageLoader: (ops: CloudflareImageLoaderOptions | null) => ImageLoader;
10
+ /**
11
+ * Fake pseudo loader for local testing purposes
12
+ **/
13
+ export declare const localImageLoader: () => ImageLoader;
14
+ //# sourceMappingURL=image-loaders.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-loaders.d.ts","sourceRoot":"","sources":["../src/image-loaders.ts"],"names":[],"mappings":"AACA,OAAO,EAAY,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE9D,oBAAY,4BAA4B,GAAG;IACzC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B,CAAC;AAEF;;;IAGI;AACJ,eAAO,MAAM,qBAAqB,EAAE,CAClC,GAAG,EAAE,4BAA4B,GAAG,IAAI,KACrC,WAoBF,CAAC;AAEJ;;IAEI;AACJ,eAAO,MAAM,gBAAgB,EAAE,MAAM,WAQlC,CAAC"}
@@ -0,0 +1,31 @@
1
+ import warnOnce from "warn-once";
2
+ import { allSizes } from "./image-optimize";
3
+ /**
4
+ * Default image loader in case of no loader provided
5
+ * https://developers.cloudflare.com/images/image-resizing/url-format/
6
+ **/
7
+ export const cloudflareImageLoader = (loaderOptions) => ({ width, src, quality }) => {
8
+ if (process.env.NODE_ENV !== "production") {
9
+ warnOnce(allSizes.includes(width) === false, "Width must be only from allowed values");
10
+ }
11
+ const options = `width=${width},quality=${quality},format=auto`;
12
+ // Cloudflare docs say that we don't need to urlencode the path params
13
+ const pathname = `/cdn-cgi/image/${options}/${src}`;
14
+ if (loaderOptions?.resizeOrigin != null) {
15
+ const url = new URL(pathname, loaderOptions.resizeOrigin);
16
+ return url.href;
17
+ }
18
+ else {
19
+ return pathname;
20
+ }
21
+ };
22
+ /**
23
+ * Fake pseudo loader for local testing purposes
24
+ **/
25
+ export const localImageLoader = () => ({ width, src, quality }) => {
26
+ // Just emulate like we really resize the image
27
+ const params = new URLSearchParams();
28
+ params.set("width", `${width}`);
29
+ params.set("quality", `${quality}`);
30
+ return `${src}?${params.toString()}`;
31
+ };
@@ -0,0 +1,107 @@
1
+ /**
2
+ * # Responsive Image component helpers.
3
+ *
4
+ * ## Quick summary about img srcset and sizes attributes:
5
+ *
6
+ * There are 2 ways to define what image will be loaded in the img property srcset.
7
+ *
8
+ * 1. via pixel density descriptor 'x', like `srcset="photo-small.jpg 1x, photo-medium.jpg 1.5x, photo-huge.jpg 2x"`
9
+ * src will be selected depending on `device-pixel-ratio`.
10
+ *
11
+ * 2. via viewport width descriptor 'w' and sizes property containing source size descriptors, like
12
+ * `srcset="photo-small.jpg 320w, photo-medium.jpg 640w, photo-huge.jpg 1280w"`
13
+ * `sizes="(max-width: 600px) 400px, (max-width: 1200px) 70vw, 50vw"`
14
+ *
15
+ * The browser finds the first matching media query from source size descriptors,
16
+ * then use source size value to generate internally srcset
17
+ * with pixel density descriptors dividing width descriptor value by source size value.
18
+ *
19
+ * Using the example above for viewport width 800px.
20
+ * The first matching media query is (max-width: 1200px)
21
+ * source size value is 70vw equal to 800px * 0,7 = 560px
22
+ *
23
+ * browser internal srcset will be (we divide `w` descriptor by source size value):
24
+ * photo-small.jpg 320/560x, photo-medium.jpg 640/560x, photo-huge.jpg 1280/560x =>
25
+ * photo-small.jpg 0.57x, photo-medium.jpg 1.14x, photo-huge.jpg 2.28x
26
+ *
27
+ * Finally same rules as for pixel density descriptor 'x' are applied.
28
+ *
29
+ * ## Algorithm (without optimizations):
30
+ *
31
+ * We have a predefined array of all supported image sizes allSizes, this is the real width of an image in pixels.
32
+ * This is good for caching, as we can cache image with specific width and then use it for different devices.
33
+ *
34
+ * > allSizes array is a tradeoff between cache and the best possible image size you deliver to the user.
35
+ * > If allSizes.length is too small, you will deliver too big images to the user,
36
+ * > if allSizes.length is too big, you will have many caches misses.
37
+ *
38
+ * If img has a defined width property.
39
+ * 1. find the first value from allSizes which is greater or equal to the width property
40
+ * 2. use found value to generate srcset with pixel density descriptor 'x'
41
+ *
42
+ *
43
+ * If img has no defined width property.
44
+ * 1. Generate srcset = allSizes.map((w) => `${getImageSrcAtWidth(w)} ${w}w`)
45
+ * 2. Use sizes property, or if it is not defined use opinionated DEFAULT_SIZES = "(min-width: 1280px) 50vw, 100vw";
46
+ *
47
+ * Optimizations applied now:
48
+ *
49
+ * - If the sizes property is defined, we can exclude from `srcsets` all images
50
+ * which are smaller than the `smallestRatio * smallesDeviceSize`
51
+ *
52
+ * Future (not implemented) optimizations and improvements:
53
+ *
54
+ * - Knowing image size on different viewport widths we can provide nondefault sizes property
55
+ * - Knowledge of Image aspect-ratio would allow cropping images serverside.
56
+ * - Early hints for high priority images https://blog.cloudflare.com/early-hints/
57
+ * - Slow networks optimizations
58
+ * - 404 etc processing with CSS - https://bitsofco.de/styling-broken-images/ (has some opinionated issues) or js solution with custom user fallback.
59
+ *
60
+ * # Attributions
61
+ *
62
+ * The MIT License (MIT)
63
+ *
64
+ * applies to:
65
+ *
66
+ * - https://github.com/vercel/next.js, Copyright (c) 2022 Vercel, Inc.
67
+ *
68
+ * The MIT License (MIT)
69
+ *
70
+ * Copyright (c) 2022 Vercel, Inc.
71
+ *
72
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
73
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
74
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
75
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
76
+ * is furnished to do so, subject to the following conditions:
77
+ *
78
+ * The above copyright notice and this permission notice shall be included in all copies
79
+ * or substantial portions of the Software.
80
+ *
81
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
82
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
83
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
84
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
85
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
86
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
87
+ **/
88
+ export declare type ImageLoader = (props: {
89
+ width: number;
90
+ quality: number;
91
+ src: string;
92
+ }) => string;
93
+ export declare const allSizes: number[];
94
+ export declare const getImageAttributes: (props: {
95
+ src: string | undefined;
96
+ srcSet: string | undefined;
97
+ sizes: string | undefined;
98
+ width: string | number | undefined;
99
+ quality: string | number | undefined;
100
+ loader: ImageLoader;
101
+ optimize: boolean;
102
+ }) => {
103
+ src: string;
104
+ srcSet?: string;
105
+ sizes?: string;
106
+ } | null;
107
+ //# sourceMappingURL=image-optimize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-optimize.d.ts","sourceRoot":"","sources":["../src/image-optimize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAsFI;AAEJ,oBAAY,WAAW,GAAG,CAAC,KAAK,EAAE;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;CACb,KAAK,MAAM,CAAC;AAQb,eAAO,MAAM,QAAQ,UAAkC,CAAC;AA4GxD,eAAO,MAAM,kBAAkB,UAAW;IACxC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACnC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACrC,MAAM,EAAE,WAAW,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;CACnB,KAAG;IACF,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,GAAG,IAuCH,CAAC"}
@@ -0,0 +1,183 @@
1
+ /**
2
+ * # Responsive Image component helpers.
3
+ *
4
+ * ## Quick summary about img srcset and sizes attributes:
5
+ *
6
+ * There are 2 ways to define what image will be loaded in the img property srcset.
7
+ *
8
+ * 1. via pixel density descriptor 'x', like `srcset="photo-small.jpg 1x, photo-medium.jpg 1.5x, photo-huge.jpg 2x"`
9
+ * src will be selected depending on `device-pixel-ratio`.
10
+ *
11
+ * 2. via viewport width descriptor 'w' and sizes property containing source size descriptors, like
12
+ * `srcset="photo-small.jpg 320w, photo-medium.jpg 640w, photo-huge.jpg 1280w"`
13
+ * `sizes="(max-width: 600px) 400px, (max-width: 1200px) 70vw, 50vw"`
14
+ *
15
+ * The browser finds the first matching media query from source size descriptors,
16
+ * then use source size value to generate internally srcset
17
+ * with pixel density descriptors dividing width descriptor value by source size value.
18
+ *
19
+ * Using the example above for viewport width 800px.
20
+ * The first matching media query is (max-width: 1200px)
21
+ * source size value is 70vw equal to 800px * 0,7 = 560px
22
+ *
23
+ * browser internal srcset will be (we divide `w` descriptor by source size value):
24
+ * photo-small.jpg 320/560x, photo-medium.jpg 640/560x, photo-huge.jpg 1280/560x =>
25
+ * photo-small.jpg 0.57x, photo-medium.jpg 1.14x, photo-huge.jpg 2.28x
26
+ *
27
+ * Finally same rules as for pixel density descriptor 'x' are applied.
28
+ *
29
+ * ## Algorithm (without optimizations):
30
+ *
31
+ * We have a predefined array of all supported image sizes allSizes, this is the real width of an image in pixels.
32
+ * This is good for caching, as we can cache image with specific width and then use it for different devices.
33
+ *
34
+ * > allSizes array is a tradeoff between cache and the best possible image size you deliver to the user.
35
+ * > If allSizes.length is too small, you will deliver too big images to the user,
36
+ * > if allSizes.length is too big, you will have many caches misses.
37
+ *
38
+ * If img has a defined width property.
39
+ * 1. find the first value from allSizes which is greater or equal to the width property
40
+ * 2. use found value to generate srcset with pixel density descriptor 'x'
41
+ *
42
+ *
43
+ * If img has no defined width property.
44
+ * 1. Generate srcset = allSizes.map((w) => `${getImageSrcAtWidth(w)} ${w}w`)
45
+ * 2. Use sizes property, or if it is not defined use opinionated DEFAULT_SIZES = "(min-width: 1280px) 50vw, 100vw";
46
+ *
47
+ * Optimizations applied now:
48
+ *
49
+ * - If the sizes property is defined, we can exclude from `srcsets` all images
50
+ * which are smaller than the `smallestRatio * smallesDeviceSize`
51
+ *
52
+ * Future (not implemented) optimizations and improvements:
53
+ *
54
+ * - Knowing image size on different viewport widths we can provide nondefault sizes property
55
+ * - Knowledge of Image aspect-ratio would allow cropping images serverside.
56
+ * - Early hints for high priority images https://blog.cloudflare.com/early-hints/
57
+ * - Slow networks optimizations
58
+ * - 404 etc processing with CSS - https://bitsofco.de/styling-broken-images/ (has some opinionated issues) or js solution with custom user fallback.
59
+ *
60
+ * # Attributions
61
+ *
62
+ * The MIT License (MIT)
63
+ *
64
+ * applies to:
65
+ *
66
+ * - https://github.com/vercel/next.js, Copyright (c) 2022 Vercel, Inc.
67
+ *
68
+ * The MIT License (MIT)
69
+ *
70
+ * Copyright (c) 2022 Vercel, Inc.
71
+ *
72
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
73
+ * and associated documentation files (the "Software"), to deal in the Software without restriction,
74
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
75
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
76
+ * is furnished to do so, subject to the following conditions:
77
+ *
78
+ * The above copyright notice and this permission notice shall be included in all copies
79
+ * or substantial portions of the Software.
80
+ *
81
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
82
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
83
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
84
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
85
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
86
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
87
+ **/
88
+ /**
89
+ * max(...imageSizes) must be less then min(...deviceSizes)
90
+ **/
91
+ const imageSizes = [16, 32, 48, 64, 96, 128, 256, 384];
92
+ const deviceSizes = [640, 750, 828, 1080, 1200, 1920, 2048, 3840];
93
+ export const allSizes = [...imageSizes, ...deviceSizes];
94
+ /**
95
+ * https://github.com/vercel/next.js/blob/canary/packages/next/client/image.tsx
96
+ **/
97
+ const getWidths = (width, sizes) => {
98
+ if (sizes) {
99
+ // Find all the "vw" percent sizes used in the sizes prop
100
+ const viewportWidthRe = /(^|\s)(1?\d?\d)vw/g;
101
+ const percentSizes = [];
102
+ for (let match; (match = viewportWidthRe.exec(sizes)); match) {
103
+ percentSizes.push(parseInt(match[2], 10));
104
+ }
105
+ if (percentSizes.length) {
106
+ // we can exclude from srcSets all images which are smaller than the smallestRatio * smallesDeviceSize
107
+ const smallestRatio = Math.min(...percentSizes) * 0.01;
108
+ return {
109
+ widths: allSizes.filter((s) => s >= deviceSizes[0] * smallestRatio),
110
+ kind: "w",
111
+ };
112
+ }
113
+ return { widths: allSizes, kind: "w" };
114
+ }
115
+ if (width == null) {
116
+ return { widths: deviceSizes, kind: "w" };
117
+ }
118
+ const widths = [
119
+ ...new Set([width, width * 2].map((w) => allSizes.find((p) => p >= w) || allSizes[allSizes.length - 1])),
120
+ ];
121
+ return { widths, kind: "x" };
122
+ };
123
+ const generateImgAttrs = ({ src, width, quality, sizes, loader, }) => {
124
+ const { widths, kind } = getWidths(width, sizes);
125
+ return {
126
+ sizes: !sizes && kind === "w" ? "100vw" : sizes,
127
+ srcSet: widths
128
+ .map((w, i) => `${loader({ src, quality, width: w })} ${kind === "w" ? w : i + 1}${kind}`)
129
+ .join(", "),
130
+ // Must be last, to prevent Safari to load images twice
131
+ src: loader({
132
+ src,
133
+ quality,
134
+ width: widths[widths.length - 1],
135
+ }),
136
+ };
137
+ };
138
+ const getInt = (value) => {
139
+ if (typeof value === "number") {
140
+ return Math.round(value);
141
+ }
142
+ if (typeof value === "string") {
143
+ const vNum = Number.parseFloat(value);
144
+ if (!Number.isNaN(vNum)) {
145
+ return Math.round(vNum);
146
+ }
147
+ }
148
+ return undefined;
149
+ };
150
+ /**
151
+ * DEFAULT_SIZES Just an assumption that most images (except hero and icons) are 100% wide on mobile and 50% on desktop.
152
+ * For icons width are usually set explicitly so DEFAULT_SIZES is not applied.
153
+ * For hero images, we can allow in UI to select sizes=100vw explicitly.
154
+ * Anyway, the best would be to calculate this based on canvas data from different breakpoints.
155
+ * See ../component-utils/image for detailed description
156
+ **/
157
+ const DEFAULT_SIZES = "(min-width: 1280px) 50vw, 100vw";
158
+ const DEFAULT_QUALITY = 80;
159
+ export const getImageAttributes = (props) => {
160
+ const width = getInt(props.width);
161
+ const quality = Math.max(Math.min(getInt(props.quality) ?? DEFAULT_QUALITY, 100), 0);
162
+ if (props.src != null && props.src != "") {
163
+ if (props.srcSet == null && props.optimize) {
164
+ const sizes = props.sizes ?? (props.width == null ? DEFAULT_SIZES : undefined);
165
+ return generateImgAttrs({
166
+ src: props.src,
167
+ width,
168
+ quality,
169
+ sizes,
170
+ loader: props.loader,
171
+ });
172
+ }
173
+ const resAttrs = { src: props.src };
174
+ if (props.srcSet != null) {
175
+ resAttrs.srcSet = props.srcSet;
176
+ }
177
+ if (props.sizes != null) {
178
+ resAttrs.sizes = props.sizes;
179
+ }
180
+ return resAttrs;
181
+ }
182
+ return null;
183
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=image-optimize.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-optimize.test.d.ts","sourceRoot":"","sources":["../src/image-optimize.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,155 @@
1
+ import { getImageAttributes } from "./image-optimize";
2
+ import { cloudflareImageLoader } from "./image-loaders";
3
+ describe("Image optimizations applied", () => {
4
+ test("width is number, create pixel density descriptor 'x'", () => {
5
+ const imgAttr = getImageAttributes({
6
+ optimize: true,
7
+ width: 100,
8
+ src: "https://webstudio.is/logo.webp",
9
+ srcSet: undefined,
10
+ sizes: undefined,
11
+ quality: 100,
12
+ loader: cloudflareImageLoader({ resizeOrigin: null }),
13
+ });
14
+ expect(imgAttr).toMatchInlineSnapshot(`
15
+ {
16
+ "sizes": undefined,
17
+ "src": "/cdn-cgi/image/width=256,quality=100,format=auto/https://webstudio.is/logo.webp",
18
+ "srcSet": "/cdn-cgi/image/width=128,quality=100,format=auto/https://webstudio.is/logo.webp 1x, /cdn-cgi/image/width=256,quality=100,format=auto/https://webstudio.is/logo.webp 2x",
19
+ }
20
+ `);
21
+ });
22
+ test("width is undefined, create 'w' descriptor and sizes prop", () => {
23
+ const imgAttr = getImageAttributes({
24
+ optimize: true,
25
+ width: undefined,
26
+ src: "https://webstudio.is/logo.webp",
27
+ srcSet: undefined,
28
+ sizes: undefined,
29
+ quality: 90,
30
+ loader: cloudflareImageLoader({ resizeOrigin: null }),
31
+ });
32
+ expect(imgAttr).toMatchInlineSnapshot(`
33
+ {
34
+ "sizes": "(min-width: 1280px) 50vw, 100vw",
35
+ "src": "/cdn-cgi/image/width=3840,quality=90,format=auto/https://webstudio.is/logo.webp",
36
+ "srcSet": "/cdn-cgi/image/width=384,quality=90,format=auto/https://webstudio.is/logo.webp 384w, /cdn-cgi/image/width=640,quality=90,format=auto/https://webstudio.is/logo.webp 640w, /cdn-cgi/image/width=750,quality=90,format=auto/https://webstudio.is/logo.webp 750w, /cdn-cgi/image/width=828,quality=90,format=auto/https://webstudio.is/logo.webp 828w, /cdn-cgi/image/width=1080,quality=90,format=auto/https://webstudio.is/logo.webp 1080w, /cdn-cgi/image/width=1200,quality=90,format=auto/https://webstudio.is/logo.webp 1200w, /cdn-cgi/image/width=1920,quality=90,format=auto/https://webstudio.is/logo.webp 1920w, /cdn-cgi/image/width=2048,quality=90,format=auto/https://webstudio.is/logo.webp 2048w, /cdn-cgi/image/width=3840,quality=90,format=auto/https://webstudio.is/logo.webp 3840w",
37
+ }
38
+ `);
39
+ });
40
+ test("width is undefined and size defined, creates 'w' descriptor and use input sizes props", () => {
41
+ const imgAttr = getImageAttributes({
42
+ optimize: true,
43
+ width: undefined,
44
+ src: "https://webstudio.is/logo.webp",
45
+ srcSet: undefined,
46
+ sizes: "100vw",
47
+ quality: 70,
48
+ loader: cloudflareImageLoader({ resizeOrigin: null }),
49
+ });
50
+ expect(imgAttr).toMatchInlineSnapshot(`
51
+ {
52
+ "sizes": "100vw",
53
+ "src": "/cdn-cgi/image/width=3840,quality=70,format=auto/https://webstudio.is/logo.webp",
54
+ "srcSet": "/cdn-cgi/image/width=640,quality=70,format=auto/https://webstudio.is/logo.webp 640w, /cdn-cgi/image/width=750,quality=70,format=auto/https://webstudio.is/logo.webp 750w, /cdn-cgi/image/width=828,quality=70,format=auto/https://webstudio.is/logo.webp 828w, /cdn-cgi/image/width=1080,quality=70,format=auto/https://webstudio.is/logo.webp 1080w, /cdn-cgi/image/width=1200,quality=70,format=auto/https://webstudio.is/logo.webp 1200w, /cdn-cgi/image/width=1920,quality=70,format=auto/https://webstudio.is/logo.webp 1920w, /cdn-cgi/image/width=2048,quality=70,format=auto/https://webstudio.is/logo.webp 2048w, /cdn-cgi/image/width=3840,quality=70,format=auto/https://webstudio.is/logo.webp 3840w",
55
+ }
56
+ `);
57
+ });
58
+ test("width is undefined and size defined, creates 'w' descriptor and use input sizes props, resizeOrigin defined", () => {
59
+ const imgAttr = getImageAttributes({
60
+ optimize: true,
61
+ width: undefined,
62
+ src: "https://webstudio.is/logo.webp",
63
+ srcSet: undefined,
64
+ sizes: "100vw",
65
+ quality: 70,
66
+ loader: cloudflareImageLoader({
67
+ resizeOrigin: "https://resize-origin.is",
68
+ }),
69
+ });
70
+ expect(imgAttr).toMatchInlineSnapshot(`
71
+ {
72
+ "sizes": "100vw",
73
+ "src": "https://resize-origin.is/cdn-cgi/image/width=3840,quality=70,format=auto/https://webstudio.is/logo.webp",
74
+ "srcSet": "https://resize-origin.is/cdn-cgi/image/width=640,quality=70,format=auto/https://webstudio.is/logo.webp 640w, https://resize-origin.is/cdn-cgi/image/width=750,quality=70,format=auto/https://webstudio.is/logo.webp 750w, https://resize-origin.is/cdn-cgi/image/width=828,quality=70,format=auto/https://webstudio.is/logo.webp 828w, https://resize-origin.is/cdn-cgi/image/width=1080,quality=70,format=auto/https://webstudio.is/logo.webp 1080w, https://resize-origin.is/cdn-cgi/image/width=1200,quality=70,format=auto/https://webstudio.is/logo.webp 1200w, https://resize-origin.is/cdn-cgi/image/width=1920,quality=70,format=auto/https://webstudio.is/logo.webp 1920w, https://resize-origin.is/cdn-cgi/image/width=2048,quality=70,format=auto/https://webstudio.is/logo.webp 2048w, https://resize-origin.is/cdn-cgi/image/width=3840,quality=70,format=auto/https://webstudio.is/logo.webp 3840w",
75
+ }
76
+ `);
77
+ });
78
+ test("custom loader", () => {
79
+ const imgAttr = getImageAttributes({
80
+ optimize: true,
81
+ width: undefined,
82
+ src: "https://webstudio.is/logo.webp",
83
+ srcSet: undefined,
84
+ sizes: "100vw",
85
+ quality: 70,
86
+ loader: ({ width, src, quality }) => `${new URL(src).pathname}?w=${width}&q=${quality}`,
87
+ });
88
+ expect(imgAttr).toMatchInlineSnapshot(`
89
+ {
90
+ "sizes": "100vw",
91
+ "src": "/logo.webp?w=3840&q=70",
92
+ "srcSet": "/logo.webp?w=640&q=70 640w, /logo.webp?w=750&q=70 750w, /logo.webp?w=828&q=70 828w, /logo.webp?w=1080&q=70 1080w, /logo.webp?w=1200&q=70 1200w, /logo.webp?w=1920&q=70 1920w, /logo.webp?w=2048&q=70 2048w, /logo.webp?w=3840&q=70 3840w",
93
+ }
94
+ `);
95
+ });
96
+ });
97
+ describe("Image optimizations not applied", () => {
98
+ test("optimize is false", () => {
99
+ const imgAttr = getImageAttributes({
100
+ optimize: false,
101
+ width: 100,
102
+ src: "https://webstudio.is/logo.webp",
103
+ srcSet: undefined,
104
+ sizes: undefined,
105
+ quality: 100,
106
+ loader: cloudflareImageLoader({ resizeOrigin: null }),
107
+ });
108
+ expect(imgAttr).toMatchInlineSnapshot(`
109
+ {
110
+ "src": "https://webstudio.is/logo.webp",
111
+ }
112
+ `);
113
+ });
114
+ test("srcSet is defined", () => {
115
+ const imgAttr = getImageAttributes({
116
+ optimize: true,
117
+ width: 100,
118
+ src: "https://webstudio.is/logo.webp",
119
+ srcSet: "user-defined-srcset",
120
+ sizes: undefined,
121
+ quality: 100,
122
+ loader: cloudflareImageLoader({ resizeOrigin: null }),
123
+ });
124
+ expect(imgAttr).toMatchInlineSnapshot(`
125
+ {
126
+ "src": "https://webstudio.is/logo.webp",
127
+ "srcSet": "user-defined-srcset",
128
+ }
129
+ `);
130
+ });
131
+ test("src is empty", () => {
132
+ const imgAttr = getImageAttributes({
133
+ optimize: true,
134
+ width: 100,
135
+ src: "",
136
+ srcSet: undefined,
137
+ sizes: undefined,
138
+ quality: 100,
139
+ loader: cloudflareImageLoader({ resizeOrigin: null }),
140
+ });
141
+ expect(imgAttr).toMatchInlineSnapshot(`null`);
142
+ });
143
+ test("src is undefined", () => {
144
+ const imgAttr = getImageAttributes({
145
+ optimize: true,
146
+ width: 100,
147
+ src: undefined,
148
+ srcSet: undefined,
149
+ sizes: undefined,
150
+ quality: 100,
151
+ loader: cloudflareImageLoader({ resizeOrigin: null }),
152
+ });
153
+ expect(imgAttr).toMatchInlineSnapshot(`null`);
154
+ });
155
+ });
package/lib/image.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { type ComponentProps } from "react";
2
+ import { type ImageLoader } from "./image-optimize";
3
+ declare const defaultTag = "img";
4
+ declare type ImageProps = ComponentProps<typeof defaultTag> & {
5
+ quality?: number;
6
+ optimize?: boolean;
7
+ loader: ImageLoader;
8
+ };
9
+ export declare const Image: import("react").ForwardRefExoticComponent<Pick<ImageProps, "quality" | "loader" | "key" | keyof import("react").ImgHTMLAttributes<HTMLImageElement> | "optimize"> & import("react").RefAttributes<HTMLImageElement>>;
10
+ export {};
11
+ //# sourceMappingURL=image.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../src/image.tsx"],"names":[],"mappings":"AAAA,OAAO,EAA+B,KAAK,cAAc,EAAE,MAAM,OAAO,CAAC;AACzE,OAAO,EAAsB,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAExE,QAAA,MAAM,UAAU,QAAQ,CAAC;AAEzB,aAAK,UAAU,GAAG,cAAc,CAAC,OAAO,UAAU,CAAC,GAAG;IACpD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,WAAW,CAAC;CACrB,CAAC;AAEF,eAAO,MAAM,KAAK,sNAmBjB,CAAC"}