@webstudio-is/image 0.1.0 → 0.15.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 (44) hide show
  1. package/lib/__generated__/image.props.json +573 -573
  2. package/lib/cjs/__generated__/image.props.json +573 -573
  3. package/lib/cjs/image-loaders.cjs +48 -33
  4. package/lib/cjs/image-optimize.cjs +101 -171
  5. package/lib/cjs/image.cjs +54 -22
  6. package/lib/cjs/index.cjs +31 -31
  7. package/lib/image-loaders.js +24 -27
  8. package/lib/image-optimize.js +83 -169
  9. package/lib/image.js +30 -15
  10. package/lib/index.js +8 -3
  11. package/package.json +9 -16
  12. package/src/__generated__/image.props.json +575 -0
  13. package/src/image-dev.stories.tsx +128 -0
  14. package/src/image-loaders.ts +47 -0
  15. package/{lib/image-optimize.test.js → src/image-optimize.test.ts} +122 -103
  16. package/{lib/cjs/image-optimize.d.ts → src/image-optimize.ts} +172 -19
  17. package/src/image.tsx +74 -0
  18. package/{lib/cjs/index.d.ts → src/index.ts} +0 -1
  19. package/lib/cjs/image-dev.stories.cjs +0 -77
  20. package/lib/cjs/image-dev.stories.d.ts +0 -35
  21. package/lib/cjs/image-dev.stories.d.ts.map +0 -1
  22. package/lib/cjs/image-loaders.d.ts +0 -14
  23. package/lib/cjs/image-loaders.d.ts.map +0 -1
  24. package/lib/cjs/image-optimize.d.ts.map +0 -1
  25. package/lib/cjs/image-optimize.test.cjs +0 -157
  26. package/lib/cjs/image-optimize.test.d.ts +0 -2
  27. package/lib/cjs/image-optimize.test.d.ts.map +0 -1
  28. package/lib/cjs/image.d.ts +0 -11
  29. package/lib/cjs/image.d.ts.map +0 -1
  30. package/lib/cjs/index.d.ts.map +0 -1
  31. package/lib/image-dev.stories.d.ts +0 -35
  32. package/lib/image-dev.stories.d.ts.map +0 -1
  33. package/lib/image-dev.stories.js +0 -65
  34. package/lib/image-loaders.d.ts +0 -14
  35. package/lib/image-loaders.d.ts.map +0 -1
  36. package/lib/image-optimize.d.ts +0 -107
  37. package/lib/image-optimize.d.ts.map +0 -1
  38. package/lib/image-optimize.test.d.ts +0 -2
  39. package/lib/image-optimize.test.d.ts.map +0 -1
  40. package/lib/image.d.ts +0 -11
  41. package/lib/image.d.ts.map +0 -1
  42. package/lib/index.d.ts +0 -5
  43. package/lib/index.d.ts.map +0 -1
  44. package/lib/tsconfig.tsbuildinfo +0 -1
@@ -1,183 +1,97 @@
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
1
  const imageSizes = [16, 32, 48, 64, 96, 128, 256, 384];
92
2
  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
- **/
3
+ const allSizes = [...imageSizes, ...deviceSizes];
97
4
  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" };
5
+ if (sizes) {
6
+ const viewportWidthRe = /(^|\s)(1?\d?\d)vw/g;
7
+ const percentSizes = [];
8
+ for (let match; match = viewportWidthRe.exec(sizes); match) {
9
+ percentSizes.push(parseInt(match[2], 10));
114
10
  }
115
- if (width == null) {
116
- return { widths: deviceSizes, kind: "w" };
11
+ if (percentSizes.length) {
12
+ const smallestRatio = Math.min(...percentSizes) * 0.01;
13
+ return {
14
+ widths: allSizes.filter((s) => s >= deviceSizes[0] * smallestRatio),
15
+ kind: "w"
16
+ };
117
17
  }
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" };
18
+ return { widths: allSizes, kind: "w" };
19
+ }
20
+ if (width == null) {
21
+ return { widths: deviceSizes, kind: "w" };
22
+ }
23
+ const widths = [
24
+ ...new Set(
25
+ [width, width * 2].map(
26
+ (w) => allSizes.find((p) => p >= w) || allSizes[allSizes.length - 1]
27
+ )
28
+ )
29
+ ];
30
+ return { widths, kind: "x" };
122
31
  };
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
- };
32
+ const generateImgAttrs = ({
33
+ src,
34
+ width,
35
+ quality,
36
+ sizes,
37
+ loader
38
+ }) => {
39
+ const { widths, kind } = getWidths(width, sizes);
40
+ return {
41
+ sizes: !sizes && kind === "w" ? "100vw" : sizes,
42
+ srcSet: widths.map(
43
+ (w, i) => `${loader({ src, quality, width: w })} ${kind === "w" ? w : i + 1}${kind}`
44
+ ).join(", "),
45
+ src: loader({
46
+ src,
47
+ quality,
48
+ width: widths[widths.length - 1]
49
+ })
50
+ };
137
51
  };
138
52
  const getInt = (value) => {
139
- if (typeof value === "number") {
140
- return Math.round(value);
53
+ if (typeof value === "number") {
54
+ return Math.round(value);
55
+ }
56
+ if (typeof value === "string") {
57
+ const vNum = Number.parseFloat(value);
58
+ if (!Number.isNaN(vNum)) {
59
+ return Math.round(vNum);
141
60
  }
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;
61
+ }
62
+ return void 0;
149
63
  };
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
64
  const DEFAULT_SIZES = "(min-width: 1280px) 50vw, 100vw";
158
65
  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;
66
+ const getImageAttributes = (props) => {
67
+ const width = getInt(props.width);
68
+ const quality = Math.max(
69
+ Math.min(getInt(props.quality) ?? DEFAULT_QUALITY, 100),
70
+ 0
71
+ );
72
+ if (props.src != null && props.src !== "") {
73
+ if (props.srcSet == null && props.optimize) {
74
+ const sizes = props.sizes ?? (props.width == null ? DEFAULT_SIZES : void 0);
75
+ return generateImgAttrs({
76
+ src: props.src,
77
+ width,
78
+ quality,
79
+ sizes,
80
+ loader: props.loader
81
+ });
82
+ }
83
+ const resAttrs = { src: props.src };
84
+ if (props.srcSet != null) {
85
+ resAttrs.srcSet = props.srcSet;
181
86
  }
182
- return null;
87
+ if (props.sizes != null) {
88
+ resAttrs.sizes = props.sizes;
89
+ }
90
+ return resAttrs;
91
+ }
92
+ return null;
93
+ };
94
+ export {
95
+ allSizes,
96
+ getImageAttributes
183
97
  };
package/lib/image.js CHANGED
@@ -1,24 +1,36 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
1
+ import { jsx } from "react/jsx-runtime";
2
2
  import { forwardRef } from "react";
3
3
  import { getImageAttributes } from "./image-optimize";
4
4
  const defaultTag = "img";
5
- export const Image = forwardRef(({ quality, loader, optimize, ...imageProps }, ref) => {
6
- // Temporary set to false, to support previous image behaviour
7
- const DEFAULT_OPTIMIZE = false;
5
+ const Image = forwardRef(
6
+ ({
7
+ quality,
8
+ loader,
9
+ optimize = true,
10
+ loading = "lazy",
11
+ decoding = "async",
12
+ ...imageProps
13
+ }, ref) => {
8
14
  const imageAttributes = getImageAttributes({
9
- src: imageProps.src,
10
- srcSet: imageProps.srcSet,
11
- sizes: imageProps.sizes,
12
- width: imageProps.width,
13
- quality,
14
- loader,
15
- optimize: optimize ?? DEFAULT_OPTIMIZE,
15
+ src: imageProps.src,
16
+ srcSet: imageProps.srcSet,
17
+ sizes: imageProps.sizes,
18
+ width: imageProps.width,
19
+ quality,
20
+ loader,
21
+ optimize
16
22
  }) ?? { src: imagePlaceholderSvg };
17
- return (_jsx("img", { ...imageProps, ...imageAttributes, decoding: "async", ref: ref }));
18
- });
23
+ return /* @__PURE__ */ jsx("img", {
24
+ ...imageProps,
25
+ ...imageAttributes,
26
+ decoding,
27
+ loading,
28
+ ref
29
+ });
30
+ }
31
+ );
19
32
  Image.defaultProps = {
20
- src: "",
21
- loading: "lazy",
33
+ src: ""
22
34
  };
23
35
  Image.displayName = "Image";
24
36
  const imagePlaceholderSvg = `data:image/svg+xml;base64,${btoa(`<svg
@@ -44,3 +56,6 @@ const imagePlaceholderSvg = `data:image/svg+xml;base64,${btoa(`<svg
44
56
  fill="#A2A2A2"
45
57
  />
46
58
  </svg>`)}`;
59
+ export {
60
+ Image
61
+ };
package/lib/index.js CHANGED
@@ -1,3 +1,8 @@
1
- export { Image } from "./image";
2
- export * as loaders from "./image-loaders";
3
- export { default as imageProps } from "./__generated__/image.props.json";
1
+ import { Image } from "./image";
2
+ import * as loaders from "./image-loaders";
3
+ import { default as default2 } from "./__generated__/image.props.json";
4
+ export {
5
+ Image,
6
+ default2 as imageProps,
7
+ loaders
8
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webstudio-is/image",
3
- "version": "0.1.0",
3
+ "version": "0.15.0",
4
4
  "description": "Image optimization",
5
5
  "author": "Webstudio <github@webstudio.is>",
6
6
  "homepage": "https://webstudio.is",
@@ -9,10 +9,9 @@
9
9
  "typecheck": "tsc --noEmit",
10
10
  "test": "NODE_OPTIONS=--experimental-vm-modules jest",
11
11
  "checks": "yarn typecheck && yarn lint && yarn test",
12
- "dev": "tsup --watch",
12
+ "dev": "build-package --watch",
13
+ "build": "build-package",
13
14
  "build:args": "generate-arg-types './src/*.tsx !./src/**/*.stories.tsx !./src/**/*.ws.tsx' && prettier --write \"**/*.props.json\"",
14
- "build": "rm -fr lib tsconfig.tsbuildinfo && yarn build:cjs && tsc",
15
- "build:cjs": "tsc --module commonjs --outDir lib/cjs && find lib/cjs -name '*.js' | while read NAME; do mv $NAME ${NAME%.js}.cjs; done",
16
15
  "lint": "eslint ./src --ext .ts,.tsx --max-warnings 0",
17
16
  "storybook:run": "start-storybook -p 6006",
18
17
  "storybook:build": "build-storybook",
@@ -30,9 +29,10 @@
30
29
  "@storybook/manager-webpack4": "^6.5.6",
31
30
  "@storybook/react": "^6.5.6",
32
31
  "@storybook/testing-library": "^0.0.13",
32
+ "@webstudio-is/generate-arg-types": "*",
33
33
  "@webstudio-is/jest-config": "*",
34
- "typescript": "4.7.4",
35
- "@webstudio-is/generate-arg-types": "*"
34
+ "@webstudio-is/scripts": "*",
35
+ "typescript": "4.7.4"
36
36
  },
37
37
  "peerDependencies": {
38
38
  "react": "^17.0.2",
@@ -43,20 +43,13 @@
43
43
  "import": "./lib/index.js",
44
44
  "require": "./lib/cjs/index.cjs"
45
45
  },
46
- "types": "lib/index.d.ts",
46
+ "types": "src/index.ts",
47
47
  "files": [
48
48
  "lib/*",
49
- "README.md",
49
+ "src/*",
50
50
  "!*.test.*"
51
51
  ],
52
52
  "license": "MIT",
53
53
  "private": false,
54
- "sideEffects": false,
55
- "tsup": {
56
- "entry": [
57
- "src/index.ts"
58
- ],
59
- "format": "esm",
60
- "outDir": "lib"
61
- }
54
+ "sideEffects": false
62
55
  }