├── .editorconfig ├── .eslintrc.cjs ├── .github └── workflows │ └── npm-publish.yml ├── .gitignore ├── .husky ├── .gitignore └── pre-commit ├── .npmignore ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── components │ └── Image.tsx ├── helpers │ ├── check-avif-feature.ts │ ├── check-webp-feature.ts │ └── get-format-features.ts └── index.ts └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | end_of_line = lf 3 | charset = utf-8 4 | 5 | # Code files 6 | [*.cs,*.csx,*.js,*.jsx,*.ts,*,tsx,*.css,*.scss] 7 | insert_final_newline = true 8 | indent_style = space 9 | indent_size = 4 10 | trim_trailing_whitespace = true 11 | max_line_length = 140 12 | quote_type = double 13 | curly_bracket_next_line = true 14 | spaces_around_operators = true 15 | spaces_around_brackets = true 16 | indent_brace_style = Allman 17 | continuation_indent_size = 4 18 | 19 | [*.xml] 20 | indent_style = space 21 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ["./node_modules/@labeg/code-style/.eslintrc.js"], 3 | ignorePatterns: ["node_modules/*"], 4 | rules:{ 5 | // override here 6 | "react/jsx-no-bind": "off", 7 | "react/destructuring-assignment": "off", 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | name: Docker 2 | 3 | # This workflow uses actions that are not certified by GitHub. 4 | # They are provided by a third-party and are governed by 5 | # separate terms of service, privacy policy, and support 6 | # documentation. 7 | 8 | on: 9 | push: 10 | branches: [ main ] 11 | workflow_dispatch: 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v3 20 | 21 | - name: Build and publish package 22 | uses: actions/setup-node@v3 23 | with: 24 | node-version: 18 25 | registry-url: https://registry.npmjs.org/ 26 | 27 | - run: npm ci 28 | - run: npm run build 29 | - run: npm publish --access public 30 | env: 31 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .idea 3 | dist -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx lint-staged -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | * 2 | !dist/**/* 3 | !package.json 4 | !README.md 5 | !LICENSE -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React component for using optimized images in the browser. 2 | 3 | Works in conjunction with the [Image Optimizer](https://github.com/MobileTeleSystems/image-optimize). 4 | 5 | Optimizing images helps reduce image weight and increases website loading speed, which is very important for both users and search engines. For these purposes, we have created a microservice that perfectly copes with this task. 6 | 7 | Features: 8 | - Resize images for the user's screen size, 9 | - Image compressions to reduce traffic, 10 | - Converting images to modern formats such as webp and avif, 11 | - Works with dynamically content, compression occurs on the fly, 12 | - High compression speed, an average picture is processed in just 200 ms, 13 | - Includes exporter of metrics for Prometheus, 14 | - Supports basic authorization for multiple domains and endpoints, 15 | - Supports security restrictions for allowed addresses. 16 | 17 | ### Before use 18 | [The optimization microservice](https://github.com/MobileTeleSystems/image-optimize) must be deployed on the server along the path `/optimizer`. React component will use it. 19 | 20 | ### Instalation 21 | Run script: 22 | ``` 23 | npm i @mts-pjsc/image-optimize 24 | ``` 25 | 26 | ### Using 27 | 28 | Just replace the \ element with the Image component from the package. The component is fully compatible with the \ element. Next, the component will do all the magic on its own. 29 | 30 | Sample: 31 | ```typescript 32 | import {Image} from "@mts-pjsc/image-optimize"; 33 | 34 | Sample of work Image Optimizer 38 | ``` 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@mts-pjsc/image-optimize", 3 | "version": "1.2.2", 4 | "description": "React component for image optimizer", 5 | "main": "dist/index.js", 6 | "module": "dist/index.js", 7 | "esnext": "dist/index.js", 8 | "type": "module", 9 | "scripts": { 10 | "eslint": "eslint --fix -c .eslintrc.cjs --ext .tsx,.ts,.jsx,.js ./src/", 11 | "test": "echo \"Error: no test specified. For test need deployed microservice part\" && exit 1", 12 | "test:module": "node ./dist/index.js", 13 | "build": "rm -rf dist/ && tsc --project tsconfig.json && npm run test:module", 14 | "prepare": "husky install" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/MobileTeleSystems/image-optimize-react.git" 19 | }, 20 | "keywords": [ 21 | "image", 22 | "optimization" 23 | ], 24 | "lint-staged": { 25 | "./src/**/*.(ts|tsx|js|jsx)": [ 26 | "eslint --fix -c .eslintrc.cjs --ext .tsx,.ts,.jsx,.js" 27 | ] 28 | }, 29 | "author": "MobileTeleSystems", 30 | "license": "Apache-2.0", 31 | "bugs": { 32 | "url": "https://github.com/MobileTeleSystems/image-optimize-react/issues" 33 | }, 34 | "homepage": "https://github.com/MobileTeleSystems/image-optimize-react#readme", 35 | "peerDependencies": { 36 | "react": ">=16.0.0" 37 | }, 38 | "devDependencies": { 39 | "@labeg/code-style": "^2.0.51", 40 | "@types/node": "^18.11.9", 41 | "@types/react": "^18.0.25", 42 | "husky": "^8.0.2", 43 | "lint-staged": "^13.0.3", 44 | "typescript": "^4.9.3" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/components/Image.tsx: -------------------------------------------------------------------------------- 1 | // For Next.js 13 and react 18. Switch component for support server components later. 2 | "use client"; 3 | 4 | import {Component} from "react"; 5 | import {getFormatFeatures} from "../helpers/get-format-features.js"; 6 | 7 | export interface IImageOptions extends React.DetailedHTMLProps, HTMLImageElement> { 8 | src: string; 9 | alt: string; 10 | offset?: number; 11 | quality?: number; 12 | setRef?: (elem: HTMLImageElement | null) => void; 13 | } 14 | 15 | export class Image

extends Component

{ 16 | 17 | public static isShowDiagnostic: boolean = false; 18 | 19 | public static controlPoints: number[] = [160, 320, 640, 1280, 1920]; 20 | 21 | /** 22 | * Image optimizer will take source url for show image. 23 | * 24 | * This is required when working on localhost. 25 | * Because a remote microservice cannot make requests to your localhost. 26 | * 27 | * Example: 28 | * Image.isUseSourceUrl = process.env.NODE_ENV !== "production"; 29 | */ 30 | public static isUseSourceUrl: boolean = false; 31 | 32 | /** 33 | * Image optimizer will change origin to other domain. 34 | * 35 | * This is necessary when you developing locally, this will take pictures from the DEV server by CORS. 36 | * 37 | * Also, this parameter must be specified if the component works in the microfront. 38 | * Then you need to specify the address to the server with pictures. 39 | * 40 | * Example: 41 | * Image.imgOrigin = https://tb.mts.ru 42 | * 43 | */ 44 | public static imgOrigin?: string = void 0; 45 | 46 | private static isAvif: boolean | null = null; 47 | 48 | private static isWebP: boolean | null = null; 49 | 50 | public resultUrl: string = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; 51 | 52 | public resizeCheckTimeout: number = 0; 53 | 54 | public thisComponent: HTMLImageElement | null = null; 55 | 56 | protected sourceUrl: string = ""; 57 | 58 | protected readonly extensionsRegexp: RegExp = /\.\w+$/u; 59 | 60 | protected readonly windowResizeHandler: EventListenerOrEventListenerObject; 61 | 62 | protected lastOptimalSize: number = 0; 63 | 64 | /** 65 | * Serves to prevent recursion when resizing images to determine the optimal size. 66 | * This recursion can be caught with poor layout that does not take into account the scaling of images. 67 | */ 68 | protected checks: number = 0; 69 | 70 | public constructor (props: P) { 71 | super(props); 72 | 73 | this.windowResizeHandler = (): void => this.onWindowResize(); 74 | } 75 | 76 | public componentDidMount (): void { 77 | this.shouldComponentUpdate(this.props); 78 | window.addEventListener("resize", this.windowResizeHandler); 79 | } 80 | 81 | public shouldComponentUpdate (props: P): boolean { 82 | if (this.sourceUrl !== props.src) { 83 | this.sourceUrl = props.src; 84 | this.checks = 0; 85 | 86 | // Raf for correct image position after redraw outer components 87 | requestAnimationFrame(() => this.checkImage()); 88 | } 89 | return true; 90 | } 91 | 92 | public componentWillUnmount (): void { 93 | window.removeEventListener("resize", this.windowResizeHandler); 94 | } 95 | 96 | public render (): JSX.Element { 97 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 98 | const {offset, quality, setRef, src, alt, ...props} = this.props; 99 | 100 | return ( 101 | {alt} requestAnimationFrame(() => this.checkImage())} 106 | ref={(elem: HTMLImageElement | null): void => { 107 | this.thisComponent = elem; 108 | this.props.setRef?.(elem); 109 | }} 110 | src={this.resultUrl} 111 | /> 112 | ); 113 | } 114 | 115 | protected async checkImage (isResize: boolean = false): Promise { 116 | if (this.checks > 1) { 117 | return; 118 | } 119 | this.checks += 1; 120 | 121 | if (Image.isUseSourceUrl && this.thisComponent) { 122 | this.thisComponent.src = this.sourceUrl; 123 | return; 124 | } 125 | 126 | if (Image.isAvif === null || Image.isWebP === null) { 127 | await this.initImageFormats(); 128 | } 129 | 130 | this.processImage(isResize); 131 | } 132 | 133 | protected processImage (isResize: boolean): void { 134 | const containerSize = this.getContainerSize(); 135 | const optimalSize = this.getOptimalSize(containerSize); 136 | this.showWarningOnResize(isResize, optimalSize); 137 | const url = this.makeResultUrl(optimalSize); 138 | this.applyResultUrl(url); 139 | this.showResultInLog(containerSize, optimalSize); 140 | } 141 | 142 | protected onWindowResize (): void { 143 | if (this.resizeCheckTimeout) { 144 | clearTimeout(this.resizeCheckTimeout); 145 | } 146 | 147 | this.resizeCheckTimeout = window.setTimeout(() => { 148 | this.checks = 0; 149 | this.checkImage(true); 150 | }, 500); 151 | } 152 | 153 | protected getContainerSize (): number { 154 | let containerSize: number = 0; 155 | 156 | let element: HTMLElement | null = this.thisComponent; 157 | 158 | while (containerSize < 2 && element) { 159 | containerSize = element.getBoundingClientRect().width || 160 | Number.parseFloat(getComputedStyle(element).width) || 0; 161 | element = element.parentElement; 162 | } 163 | 164 | return containerSize * window.devicePixelRatio; 165 | } 166 | 167 | protected getOptimalSize (containerSize: number): number { 168 | let index: number = Image.controlPoints 169 | .findIndex((width: number) => containerSize <= width); 170 | 171 | // If bigger then maximum size or NaN 172 | if (index < 0) { 173 | index = Image.controlPoints.length - 1; 174 | } 175 | 176 | // Make manual more or less size 177 | index += this.props.offset ?? 0; 178 | 179 | // If offset make out of boundary 180 | if (index < 0) { 181 | index = 0; 182 | } else if (index >= Image.controlPoints.length) { 183 | index = Image.controlPoints.length - 1; 184 | } 185 | 186 | return Image.controlPoints[index]; 187 | } 188 | 189 | protected makeResultUrl (optimalSize: number): URL { 190 | const sourceUrl = new URL( 191 | this.sourceUrl, 192 | Image.imgOrigin ?? location.origin 193 | ); 194 | 195 | const url = new URL("/optimizer/optimize", location.origin); 196 | url.searchParams.set("src", sourceUrl.toString()); 197 | url.searchParams.set("size", String(optimalSize)); 198 | 199 | if (typeof this.props.quality === "number") { 200 | url.searchParams.set("quality", String(this.props.quality)); 201 | } 202 | 203 | const format = this.extractImageFormat(sourceUrl.pathname); 204 | url.searchParams.set("format", format); 205 | 206 | return url; 207 | } 208 | 209 | protected extractImageFormat (path: string): string { 210 | let format = ""; 211 | 212 | const match: RegExpExecArray | null = this.extensionsRegexp.exec(path); 213 | 214 | if (Image.isAvif === true) { 215 | format = "avif"; 216 | } else if (Image.isWebP === true) { 217 | format = "webp"; 218 | } else { 219 | format = String(match?.[0]) 220 | .replace(".", "") 221 | .replace("jpg", "jpeg"); 222 | } 223 | 224 | return format; 225 | } 226 | 227 | protected applyResultUrl (url: URL): void { 228 | const resultUrl = url.toString(); 229 | if (this.resultUrl !== resultUrl && this.thisComponent) { 230 | this.resultUrl = resultUrl; 231 | this.thisComponent.src = this.resultUrl; 232 | } 233 | } 234 | 235 | /** 236 | * This function should motivate the developer to make a layout that does not cause resizing. 237 | * 238 | * @param {boolean} isResize 239 | * @param {number} optimalSize 240 | */ 241 | protected showWarningOnResize (isResize: boolean, optimalSize: number): void { 242 | if ( 243 | !isResize && 244 | this.lastOptimalSize >= 0 && 245 | this.lastOptimalSize !== optimalSize 246 | ) { 247 | // eslint-disable-next-line no-console 248 | console.warn( 249 | "New image size", 250 | this.lastOptimalSize, 251 | optimalSize, 252 | this.sourceUrl 253 | ); 254 | } 255 | this.lastOptimalSize = optimalSize; 256 | } 257 | 258 | protected showResultInLog (containerSize: number, optimalSize: number): void { 259 | if (process.env.NODE_ENV !== "production" && Image.isShowDiagnostic) { 260 | // eslint-disable-next-line no-console 261 | console.log([ 262 | "🏄 Image optimization:", 263 | `Container size ${containerSize}px,`, 264 | `optimal size ${optimalSize},`, 265 | `image ${this.sourceUrl}` 266 | ].join(" ")); 267 | } 268 | } 269 | 270 | protected async initImageFormats (): Promise { 271 | const format = await getFormatFeatures(); 272 | 273 | if (Image.isAvif === null || Image.isWebP === null) { 274 | Image.isAvif = format === "avif"; 275 | Image.isWebP = format === "webp"; 276 | } 277 | } 278 | 279 | } 280 | -------------------------------------------------------------------------------- /src/helpers/check-avif-feature.ts: -------------------------------------------------------------------------------- 1 | 2 | export const checkAvifFeature = (): Promise => new Promise((resolve: (result: boolean) => void) => { 3 | const img = new Image(); 4 | img.onload = (): void => { 5 | const result = (img.width > 0) && (img.height > 0); 6 | resolve(result); 7 | }; 8 | img.onerror = (): void => { 9 | resolve(false); 10 | }; 11 | // eslint-disable-next-line max-len 12 | img.src = "data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="; 13 | }); 14 | -------------------------------------------------------------------------------- /src/helpers/check-webp-feature.ts: -------------------------------------------------------------------------------- 1 | const kTestImages = { 2 | lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA", 3 | lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==", 4 | alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==", 5 | animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////" + 6 | "AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA" 7 | }; 8 | 9 | export const checkWebpFeature = (): Promise => new Promise((resolve: (result: boolean) => void) => { 10 | const img = new Image(); 11 | img.onload = (): void => { 12 | const result = (img.width > 0) && (img.height > 0); 13 | resolve(result); 14 | }; 15 | img.onerror = (): void => { 16 | resolve(false); 17 | }; 18 | img.src = `data:image/webp;base64,${kTestImages.lossless}`; 19 | }); 20 | -------------------------------------------------------------------------------- /src/helpers/get-format-features.ts: -------------------------------------------------------------------------------- 1 | 2 | import {checkAvifFeature} from "./check-avif-feature.js"; 3 | import {checkWebpFeature} from "./check-webp-feature.js"; 4 | 5 | // eslint-disable-next-line @typescript-eslint/no-type-alias 6 | type FormatType = "avif" | "webp" | null; 7 | 8 | const promisesPool: ((value: FormatType) => void)[] = []; 9 | 10 | const resolvePromises = (format: FormatType): void => { 11 | promisesPool.forEach((resolve) => resolve(format)); 12 | }; 13 | 14 | const checkFormats = async (): Promise => { 15 | const isAvif = await checkAvifFeature(); 16 | if (isAvif) { 17 | resolvePromises("avif"); 18 | return; 19 | } 20 | 21 | const isWebp = await checkWebpFeature(); 22 | if (isWebp) { 23 | resolvePromises("webp"); 24 | return; 25 | } 26 | 27 | resolvePromises(null); 28 | }; 29 | 30 | export const getFormatFeatures = (): Promise => { 31 | if (promisesPool.length === 0) { 32 | checkFormats(); 33 | } 34 | 35 | return new Promise((resolve) => { 36 | promisesPool.push(resolve); 37 | }); 38 | }; 39 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | // Components 2 | export * from "./components/Image.js"; 3 | 4 | // Helpers 5 | export * from "./helpers/check-avif-feature.js"; 6 | export * from "./helpers/check-webp-feature.js"; 7 | 8 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2017", 4 | "module": "ESNext", 5 | "esModuleInterop": true, 6 | "forceConsistentCasingInFileNames": true, 7 | "strict": true, 8 | "skipLibCheck": true, 9 | "declaration": true, 10 | "jsx": "react-jsx", 11 | "outDir": "./dist/", 12 | }, 13 | "include": [ 14 | "./src/**/*" 15 | ], 16 | } 17 | --------------------------------------------------------------------------------