├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ └── main.yml ├── .gitignore ├── .husky └── pre-commit ├── .prettierignore ├── LICENSE ├── README.md ├── bin └── gentoc.sh ├── example ├── .gitignore ├── .npmignore ├── README.md ├── clean-build-and-run.sh ├── index.html ├── index.tsx ├── package.json └── tsconfig.json ├── jest.config.js ├── package-lock.json ├── package.json ├── rollup.config.mjs ├── src └── index.tsx ├── test └── index.test.tsx └── tsconfig.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | 8 | [*] 9 | 10 | # Change these settings to your own preference 11 | indent_style = space 12 | indent_size = 2 13 | 14 | # We recommend you to keep these unchanged 15 | end_of_line = lf 16 | charset = utf-8 17 | trim_trailing_whitespace = true 18 | insert_final_newline = true 19 | 20 | [*.md] 21 | trim_trailing_whitespace = false 22 | 23 | [*.json] 24 | indent_size = 2 25 | 26 | [*.{html,js,md}] 27 | block_comment_start = /** 28 | block_comment = * 29 | block_comment_end = */ 30 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['react-app', 'react-app/jest', 'plugin:prettier/recommended'], 3 | settings: { 4 | react: { 5 | version: '999.999.999', 6 | }, 7 | }, 8 | rules: { 9 | strict: 'off', 10 | }, 11 | }; 12 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Otherwise prettier will fail in CI on Windows because of line endings get 2 | # converted to CRLF when checking out the code. 3 | # See https://prettier.io/docs/en/options.html#end-of-line 4 | * text=auto eol=lf 5 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Please see the documentation for all configuration options: 2 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 3 | 4 | version: 2 5 | updates: 6 | - package-ecosystem: 'npm' 7 | directory: '/' 8 | schedule: 9 | interval: 'weekly' 10 | open-pull-requests-limit: 0 # pause dependabot 11 | commit-message: 12 | prefix: 'chore: ' 13 | ignore: 14 | # eslint's CLI changed a lot in eslint@9. Staying on eslint@8 for now. 15 | - dependency-name: 'eslint' 16 | update-types: ['version-update:semver-major'] 17 | 18 | # Do not get one pull request per version bump. Instead get one pull request 19 | # bumping several dependency versions at once: 20 | groups: 21 | all-deps: 22 | patterns: 23 | - '*' 24 | 25 | - package-ecosystem: 'npm' 26 | directory: '/example' 27 | schedule: 28 | interval: 'weekly' 29 | commit-message: 30 | prefix: 'chore: ' 31 | 32 | # Do not get one pull request per version bump. Instead get one pull request 33 | # bumping several dependency versions at once: 34 | groups: 35 | all-deps: 36 | patterns: 37 | - '*' 38 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | build: 7 | name: Build, lint, and test component on Node ${{ matrix.node }} and ${{ matrix.os }} 8 | 9 | runs-on: ${{ matrix.os }} 10 | strategy: 11 | matrix: 12 | node: ['16', '18'] 13 | os: [ubuntu-latest, windows-latest, macOS-latest] 14 | 15 | steps: 16 | - name: Checkout repo 17 | uses: actions/checkout@v3 18 | 19 | - name: Use Node ${{ matrix.node }} 20 | uses: actions/setup-node@v3 21 | with: 22 | node-version: ${{ matrix.node }} 23 | 24 | - name: Install deps and build component (with cache) 25 | run: npm install 26 | 27 | - name: Lint 28 | run: npm run lint 29 | 30 | - name: Test component 31 | run: npm run test --ci --coverage --maxWorkers=2 32 | 33 | pack: 34 | name: Pack and upload component 35 | 36 | runs-on: ubuntu-latest 37 | 38 | steps: 39 | - name: Checkout repo 40 | uses: actions/checkout@v3 41 | 42 | - name: Install deps and build component (with cache) 43 | run: npm install 44 | 45 | - name: Pack component 46 | run: npm pack 47 | 48 | - name: Upload component 49 | uses: actions/upload-artifact@v4 50 | with: 51 | name: react-image-display-control 52 | path: frameright-react-image-display-control-*.tgz 53 | if-no-files-found: error 54 | 55 | example: 56 | name: Build the example 57 | 58 | runs-on: ubuntu-latest 59 | 60 | steps: 61 | - name: Checkout repo 62 | uses: actions/checkout@v3 63 | 64 | - name: Build component and example 65 | run: ./clean-build-and-run.sh --build-only 66 | working-directory: example/ 67 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .DS_Store 3 | .vscode 4 | node_modules 5 | .*cache 6 | dist 7 | frameright-react-image-display-control*.tgz 8 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npm run lint && npm run test 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | /coverage/ 2 | /generated-docs/ 3 | /npm-debug.log 4 | 5 | .DS_Store 6 | .idea/ 7 | .tmp/ 8 | .vscode/ 9 | dist/ 10 | node_modules/ 11 | package-lock.json 12 | *.md 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Frameright (Coberg Ltd) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [](https://frameright.io) 2 | [![npm version](https://img.shields.io/npm/v/@frameright/react-image-display-control)](https://www.npmjs.com/package/@frameright/react-image-display-control) 3 | [![github actions](https://github.com/Frameright/react-image-display-control/actions/workflows/main.yml/badge.svg)](https://github.com/Frameright/react-image-display-control/actions/workflows/main.yml) 4 | 5 |   6 | 7 | 17 | 18 | # Image Display Control React Component 19 | 20 | > **➡️ See this document rendered at [docs.frameright.io/react](https://docs.frameright.io/react)** 21 | 22 | An easy way to do [Image Display Control](https://frameright.io) in your React 23 | web app. Made with :heart: by [Frameright](https://frameright.io). Power 24 | to the pictures! 25 | 26 | > **Less than 5kB in your final client-side bundle.** 27 | 28 |   :sparkles: [Live demo](https://react.frameright.io) 29 | 30 |   💻 [CodeSandbox](https://codesandbox.io/s/image-display-control-react-component-m6qj9r) 31 | 32 | ## Table of Contents 33 | 34 | 35 | 36 | - [Overview](#overview) 37 | * [Without this component](#without-this-component) 38 | * [Basic usage](#basic-usage) 39 | - [Image Display Control metadata](#image-display-control-metadata) 40 | - [Installation](#installation) 41 | - [Usage](#usage) 42 | 43 | 44 | 45 | ## Overview 46 | 47 | This React component extends any ``-like element/component with the ability 48 | to retrieve Image Display Control metadata from its image file in order to 49 | automatically and responsively zoom in on the most interesting part of the 50 | image. 51 | 52 | It integrates nicely with other advanced features you may be using in your 53 | existing project, e.g.: 54 | * [image candidates (srcset)](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset), 55 | whether you define them yourself or whether they are generated on your behalf 56 | by another component like 57 | [Next.js ``](https://nextjs.org/docs/api-reference/next/image), 58 | * [server-side rendering](https://docs.frameright.io/react/ssr) 59 | and static site generation, e.g. in a Next.js or in a Vite-based project. 60 | 61 | It doesn't change the structure of your DOM: your existing CSS rules still 62 | apply. 63 | 64 |   :sparkles: [Live demo](https://react.frameright.io) 65 | 66 |   :bulb: [GitHub Discussions](https://github.com/Frameright/react-image-display-control/discussions) 67 | 68 | > **NOTE**: if you are not using React, you may want to have a look at the 69 | > [Image Display Control Web component](https://github.com/Frameright/image-display-control-web-component) 70 | > instead. 71 | 72 | ### Without this component 73 | 74 | When an image is too big for its `` HTML element, the best option browsers 75 | offer nowadays is to use the 76 | [`object-fit: cover;`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) 77 | CSS property in order to scale and middle-crop it: 78 | 79 | 80 | 81 | ```html 82 | 88 | ``` 89 | 90 | This is less than optimal, as there might be, in the example above, a better 91 | square-ish region in the image that could be displayed instead of the 92 | middle-crop. 93 | 94 | ### Basic usage 95 | 96 | This React component extends its ``-like children with the ability to 97 | retrieve image regions from their image metadata, and to zoom in on the best one 98 | for the current element size: 99 | 100 | 101 | 102 | ```html 103 | 104 | 109 | 110 | ``` 111 | 112 | The resulting HTML element is responsive and will automatically reassess the 113 | best region to zoom in on when it gets resized, e.g. when the user turns their 114 | phone from portrait to landscape. 115 | 116 | [![Youtube](https://img.youtube.com/vi/UsBtRSyY-7c/0.jpg)](https://www.youtube.com/watch?v=UsBtRSyY-7c "Youtube") 117 | 118 |   :sparkles: [Live demo](https://react.frameright.io) 119 | 120 |   💻 [CodeSandbox](https://codesandbox.io/s/image-display-control-react-component-m6qj9r) 121 | 122 |   :bulb: [GitHub Discussions](https://github.com/Frameright/react-image-display-control/discussions) 123 | 124 | ## Image Display Control metadata 125 | 126 | Nowadays an image file (e.g. JPEG, PNG) can contain this type of image regions 127 | in their metadata according to 128 | [the IPTC standard](https://iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#image-region). 129 | This React component uses 130 | [a library](https://github.com/Frameright/image-display-control-metadata-parser) 131 | to let the back-end or front-end extract the regions from the image file. It 132 | then passes them to the `` tag and turns it into 133 | [a web component](https://github.com/Frameright/image-display-control-web-component), 134 | which automatically and responsively zooms in on the best region. 135 | 136 | Photographers, or anyone else, can use the 137 | [Frameright webapp](https://frameright.app/) to define and store image regions in 138 | the metadata of their pictures. 139 | 140 | ## Installation 141 | 142 | In your Node.js-based project (e.g. using [Next.js](https://nextjs.org/) or 143 | [Vite](https://vitejs.dev/)) run: 144 | 145 | ```bash 146 | npm install @frameright/react-image-display-control 147 | ``` 148 | 149 | > **Less than 5kB in your final client-side bundle.** 150 | 151 |   :floppy_disk: 152 | [Importing in your project](https://docs.frameright.io/react/importing) 153 | 154 | ## Usage 155 | 156 | ```tsx 157 | // src/MyComponent.tsx 158 | 159 | import { ImageDisplayControl } from "@frameright/react-image-display-control"; 160 | 161 | export default function MyComponent() { 162 | return ( 163 | 164 | 169 | 170 | ); 171 | } 172 | ``` 173 | 174 | This doesn't change the structure of the resulting DOM, i.e.: 175 | * the `` tag remains an `` tag, and 176 | * no new parent elements are added around it, so 177 | * the CSS rules that used to target the `` tag directly will still apply, 178 | and 179 | * the `` tag will still naturally take the same space and position in the 180 | layout. 181 | 182 | Other ``-like elements/components are supported as well, e.g. 183 | [Next.js ``s](https://nextjs.org/docs/api-reference/next/image) or 184 | [React-Bootstrap ``s](https://react-bootstrap.github.io/components/images/). 185 | 186 |   :airplane: 187 | [Advanced usage](https://docs.frameright.io/react/usage) 188 | 189 |   🌍 190 | [Supported environments](https://docs.frameright.io/react/environments) 191 | 192 |   :wrench: [Contributing](https://docs.frameright.io/react/contributing) 193 | 194 |   📝 [Changelog](https://docs.frameright.io/react/changelog) 195 | 196 |   :sparkles: [Local demo](https://docs.frameright.io/react/example) 197 | 198 |   :bulb: [GitHub Discussions](https://github.com/Frameright/react-image-display-control/discussions) 199 | 200 |   :sparkles: [Live demo](https://react.frameright.io) 201 | 202 |   🙏 203 | [Dependency tree / credits](https://docs.frameright.io/react/credits) 204 | -------------------------------------------------------------------------------- /bin/gentoc.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | set -e 4 | 5 | if [ "$npm_execpath" = "" ]; then 6 | echo "Run me with 'npm run gentoc' instead" 7 | exit 1 8 | fi 9 | 10 | for md in $(git grep -l "<\\!-- toc -->"); do 11 | echo "$md" 12 | npx markdown-toc -i "$md"; 13 | done 14 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # The react component that we have spontaneously built in the parent directory 2 | # may not have a checksum that matches the one in the package-lock.json file 3 | # that would be checked in this repository, so it's best not to check it in. 4 | /package-lock.json 5 | -------------------------------------------------------------------------------- /example/.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .*cache 3 | dist 4 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Local demo 2 | 3 | 9 | 10 | Run me with: 11 | 12 | ```bash 13 | ./clean-build-and-run.sh 14 | ``` 15 | 16 |   :sparkles: [Live demo](https://react.frameright.io) 17 | 18 |   :bulb: [GitHub Discussions](https://github.com/Frameright/react-image-display-control/discussions) 19 | 20 |   💻 [CodeSandbox](https://codesandbox.io/s/image-display-control-react-component-m6qj9r) 21 | -------------------------------------------------------------------------------- /example/clean-build-and-run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ex 4 | 5 | option=$1 6 | 7 | pushd ../ 8 | rm -rf dist/ node_modules/ package-lock.json frameright-react-image-display-control-*.tgz 9 | npm install 10 | npm pack 11 | popd 12 | 13 | rm -rf dist/ node_modules/ package-lock.json .parcel-cache/ 14 | mv ../frameright-react-image-display-control-*.tgz frameright-react-image-display-control.tgz 15 | npm install 16 | npx tsc --noEmit # validate types 17 | npm run build 18 | 19 | if [ "$option" != "--build-only" ]; then 20 | npm start 21 | fi 22 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Playground 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /example/index.tsx: -------------------------------------------------------------------------------- 1 | import 'react-app-polyfill/ie11'; 2 | import * as React from 'react'; 3 | import { createRoot } from 'react-dom/client'; 4 | import { ImageDisplayControl } from '@frameright/react-image-display-control'; 5 | 6 | const App = () => { 7 | return ( 8 | 9 | 10 | 11 | 44 | 45 | 46 | 47 | 48 | 49 |
12 |
22 | 23 | Skater 1 32 | Skater 2 41 | 42 |
43 |
Resize me ▲
50 | ); 51 | }; 52 | 53 | const rootElement = document.getElementById('root'); 54 | const root = createRoot(rootElement!); 55 | root.render(); 56 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "license": "MIT", 4 | "scripts": { 5 | "start": "parcel index.html", 6 | "build": "parcel build index.html" 7 | }, 8 | "dependencies": { 9 | "@frameright/react-image-display-control": "file:./frameright-react-image-display-control.tgz", 10 | "react": "^19.0.0", 11 | "react-app-polyfill": "^3.0.0", 12 | "react-dom": "^19.0.0" 13 | }, 14 | "devDependencies": { 15 | "@types/react": "^19.0.2", 16 | "@types/react-dom": "^19.0.2", 17 | "buffer": "^6.0.3", 18 | "parcel": "^2.9.1", 19 | "process": "^0.11.10", 20 | "typescript": "^5.0.4" 21 | }, 22 | "_comment": "Workaround for https://github.com/swc-project/swc/issues/8988 - @swc/core 1.5.11 is broken", 23 | "overrides": { 24 | "parcel": { 25 | "@swc/core": "1.5.7" 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": false, 4 | "target": "es5", 5 | "module": "commonjs", 6 | "jsx": "react", 7 | "moduleResolution": "node", 8 | "noImplicitAny": false, 9 | "noUnusedLocals": false, 10 | "noUnusedParameters": false, 11 | "removeComments": true, 12 | "strictNullChecks": true, 13 | "preserveConstEnums": true, 14 | "sourceMap": true, 15 | "lib": ["es2015", "es2016", "dom"], 16 | "types": ["node"] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'jsdom', 4 | globals: { 5 | transform: { 6 | tsconfig: './tsconfig.json', 7 | }, 8 | }, 9 | }; 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@frameright/react-image-display-control", 3 | "description": "Image Display Control React component", 4 | "keywords": [ 5 | "metadata", 6 | "image", 7 | "image-manipulation", 8 | "responsive-design", 9 | "responsive-layout", 10 | "responsive-images", 11 | "metadata-extraction", 12 | "metadata-parser", 13 | "iptc-metadata", 14 | "image-display-control", 15 | "frameright", 16 | "image-publishing", 17 | "react", 18 | "react-component", 19 | "reactjs" 20 | ], 21 | "version": "1.0.7", 22 | "license": "MIT", 23 | "repository": "https://github.com/Frameright/react-image-display-control", 24 | "author": { 25 | "name": "Frameright (Coberg Ltd)", 26 | "email": "hello@frameright.io", 27 | "url": "https://frameright.io/" 28 | }, 29 | "main": "dist/react-image-display-control.min.cjs", 30 | "typings": "dist/index.d.ts", 31 | "files": [ 32 | "dist", 33 | "src" 34 | ], 35 | "engines": { 36 | "node": ">=16" 37 | }, 38 | "scripts": { 39 | "build": "rollup -c", 40 | "test": "tsc && jest", 41 | "lint": "eslint . --ignore-pattern dist && prettier --check .", 42 | "format": "eslint . --ignore-pattern dist --fix && prettier --write .", 43 | "prepare": "husky install && rollup -c", 44 | "gentoc": "./bin/gentoc.sh" 45 | }, 46 | "peerDependencies": { 47 | "react": ">=16" 48 | }, 49 | "prettier": { 50 | "printWidth": 80, 51 | "semi": true, 52 | "singleQuote": true, 53 | "trailingComma": "es5" 54 | }, 55 | "module": "dist/react-image-display-control.min.mjs", 56 | "devDependencies": { 57 | "@babel/plugin-proposal-private-property-in-object": "^7.21.11", 58 | "@rollup/plugin-commonjs": "^28.0.0", 59 | "@rollup/plugin-node-resolve": "^16.0.0", 60 | "@rollup/plugin-terser": "^0.4.3", 61 | "@rollup/plugin-typescript": "^12.1.0", 62 | "@types/jest": "^29.0.0", 63 | "@types/react": "^18.2.7 || ^19.0.2", 64 | "@types/react-dom": "^18.2.4 || ^19.0.2", 65 | "@types/uuid": "^10.0.0", 66 | "eslint": "^8.57.0", 67 | "eslint-config-prettier": "^10.0.1", 68 | "eslint-config-react-app": "^7.0.1", 69 | "eslint-plugin-prettier": "^5.0.0", 70 | "husky": "^9.0.7", 71 | "jest": "^29.0.0", 72 | "jest-environment-jsdom": "^29.5.0", 73 | "markdown-toc": "^1.2.0", 74 | "prettier": "3.5.3", 75 | "react": "^18.2.0 || ^19.0.0", 76 | "react-dom": "^18.2.0 || ^19.0.0", 77 | "rollup": "^4.0.2", 78 | "ts-jest": "^29.0.0", 79 | "typescript": "^5.2.0" 80 | }, 81 | "dependencies": { 82 | "@frameright/image-display-control-metadata-parser": "^2.0.0", 83 | "@frameright/image-display-control-web-component": "^1.1.7", 84 | "tslib": "^2.5.2", 85 | "uuid": "^11.0.2" 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | // Inspired by 2 | // https://github.com/jaredpalmer/tsdx/blob/2d7981b/src/createRollupConfig.ts 3 | 4 | // Import rollup plugins 5 | import commonjs from '@rollup/plugin-commonjs'; 6 | import resolve from '@rollup/plugin-node-resolve'; 7 | import terser from '@rollup/plugin-terser'; 8 | import typescript from '@rollup/plugin-typescript'; 9 | import path from 'path'; 10 | 11 | const outputOptions = { 12 | all: { 13 | inlineDynamicImports: true, 14 | sourcemap: true, 15 | globals: { react: 'React' }, 16 | }, 17 | esm: { 18 | format: 'esm', 19 | freeze: false, 20 | esModule: true, 21 | exports: 'named', 22 | }, 23 | cjs: { 24 | format: 'cjs', 25 | }, 26 | min: { 27 | plugins: [ 28 | terser({ 29 | output: { comments: false }, 30 | compress: { 31 | keep_infinity: true, 32 | pure_getters: true, 33 | passes: 10, 34 | }, 35 | ecma: 2020, 36 | toplevel: true, 37 | warnings: true, 38 | }), 39 | ], 40 | }, 41 | }; 42 | 43 | const config = { 44 | plugins: [ 45 | // Resolve bare module specifiers to relative paths 46 | resolve(), 47 | 48 | // All bundled external modules need to be converted from CJS to ESM 49 | commonjs(), 50 | 51 | typescript({ 52 | declarationDir: 'dist', 53 | compilerOptions: { 54 | sourceMap: true, 55 | declaration: true, 56 | jsx: 'react', 57 | }, 58 | }), 59 | ], 60 | input: './src/index.tsx', 61 | output: [ 62 | { 63 | file: './dist/react-image-display-control.mjs', 64 | ...outputOptions.all, 65 | ...outputOptions.esm, 66 | }, 67 | { 68 | file: './dist/react-image-display-control.min.mjs', 69 | ...outputOptions.all, 70 | ...outputOptions.esm, 71 | ...outputOptions.min, 72 | }, 73 | { 74 | file: './dist/react-image-display-control.cjs', 75 | ...outputOptions.all, 76 | ...outputOptions.cjs, 77 | }, 78 | { 79 | file: './dist/react-image-display-control.min.cjs', 80 | ...outputOptions.all, 81 | ...outputOptions.cjs, 82 | ...outputOptions.min, 83 | }, 84 | ], 85 | external: (id) => { 86 | return !id.startsWith('.') && !path.isAbsolute(id); 87 | }, 88 | }; 89 | 90 | export default config; 91 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import { v4 as uuidv4 } from 'uuid'; 2 | 3 | import * as React from 'react'; 4 | 5 | import { Parser } from '@frameright/image-display-control-metadata-parser'; 6 | 7 | // If true, we are either running on the server at request-time, or at 8 | // build time, building a static (e.g. Next.js) page. 9 | const isServerOrStatic = typeof window === 'undefined'; 10 | 11 | const isBrowser = !isServerOrStatic; 12 | 13 | let isRunningTests = false; 14 | try { 15 | // See https://stackoverflow.com/questions/50940640/how-to-determine-if-jest-is-running-the-code-or-not 16 | isRunningTests = process.env.JEST_WORKER_ID !== undefined; 17 | } catch (e) { 18 | // Probably "ReferenceError: process is not defined", ignore. 19 | } 20 | 21 | // See https://docs.frameright.io/web-component/importing 22 | if (isBrowser && !isRunningTests) { 23 | // Defines the web component. 24 | import( 25 | '@frameright/image-display-control-web-component/dist/src/image-display-control.js' 26 | ); 27 | } 28 | 29 | interface FsModule { 30 | readFileSync: (path: string) => Buffer; 31 | } 32 | 33 | let fs: FsModule | null = null; 34 | if (!isBrowser) { 35 | // We need to use `require()` here with Vite/Vike in prod as otherwise 36 | // `import()` will happen later than the server-side rendering. However 37 | // `require()` isn't defined in dev mode, so then we fall back to `import()`. 38 | if (require) { 39 | // FIXME: for this to work on Next.js, we need to set 40 | // `config.resolve.fallback = { fs: false };` in next.config.js. See 41 | // https://stackoverflow.com/questions/64926174/module-not-found-cant-resolve-fs-in-next-js-application 42 | fs = require('fs'); 43 | } else { 44 | import('fs').then((fsModule) => { 45 | fs = fsModule; 46 | }); 47 | } 48 | } 49 | 50 | interface ImageSource { 51 | src: string; // URL 52 | 53 | // Optional. If provided, this is the path to the image on server, for 54 | // server-side rendering or static site generation. If not provided although 55 | // server-side rendering or static site generation is used, a warning will be 56 | // issued. Pass `none` to disable this warning. 57 | pathOnServer?: string; 58 | } 59 | 60 | export function ImageDisplayControl({ 61 | children, 62 | 'data-debug': debug = false, 63 | }: { 64 | children?: React.ReactElement | React.ReactElement[]; 65 | 'data-debug'?: boolean; 66 | }) { 67 | _traceIfDebug(debug, 'Rendering...'); 68 | 69 | const allChildren = children || []; 70 | 71 | // Same UUID and ref for all -like children of one same 72 | // component. 73 | // 74 | // Note: it may happen that when adding new children later, they will obtain 75 | // a different UUID than previous children. This is fine, as this UUID is only 76 | // used for finding server-side rendered image regions in the DOM on initial 77 | // hydration. 78 | // New children will not have any new server-side rendered image regions to 79 | // take from the DOM. Instead, all initially server-side rendered image 80 | // regions will be already present in the state anyway. 81 | const [uuid] = React.useState((): string => uuidv4()); 82 | const ref = React.useRef(null); 83 | 84 | // This maps an image src to its image regions as a json string. Let's 85 | // initially render the web component with empty image regions. Image regions 86 | // will be fetched asynchronously with useEffect(). 87 | const [imageRegionsMap, setImageRegionsMap] = React.useState( 88 | new Map() 89 | ); 90 | _initializeImageRegionsMap(imageRegionsMap, allChildren, debug); 91 | 92 | // We are going to extend all -like elements by adding attributes to 93 | // them, in order to turn them into elements 94 | // under the hood. 95 | let numImgChildren = 0; 96 | const extendedChildren = React.Children.map(allChildren, (child) => { 97 | const imageSource = _getImageSource(child); 98 | if (!imageSource) { 99 | // This child isn't an -like element. No need to extend it with the 100 | // web component functionality. 101 | return child; 102 | } 103 | 104 | ++numImgChildren; 105 | 106 | const childProps = { 107 | class: null, 108 | className: null, 109 | ...(child.props as object), 110 | }; 111 | 112 | const newAttrs: { 113 | is: string; 114 | class: string; 115 | ref: React.MutableRefObject; 116 | 'data-idc-uuid': string; 117 | suppressHydrationWarning: boolean; 118 | 'data-src-prop': string; 119 | 'data-path-on-server'?: string; 120 | 'data-image-regions'?: string; 121 | } = { 122 | // Note: thanks to this, react will recognize this as a custom element. 123 | // https://react.dev/reference/react-dom/components#custom-html-elements 124 | is: 'image-display-control', 125 | 126 | // Because this is a custom element, `class=` should be used instead of 127 | // `className=`. However we want to allow the user to use `className=`, so 128 | // we copy it over to `class=`: 129 | class: `${childProps.class || ''} ${childProps.className || ''}`.trim(), 130 | 131 | ref, 132 | 'data-idc-uuid': uuid, 133 | 134 | // There might be a `data-image-regions=` attribute mismatch between 135 | // what's rendered on the server and what's rendered during the initial 136 | // client-side hydration. This is because for performance reasons, if the 137 | // server has already parsed the image regions, we don't want to do this 138 | // work again in the browse. Instead we don't explicitly re-render the 139 | // `data-image-regions=` attribute, see below. This makes React issue a 140 | // warning, which we suppress here. See also 141 | // * https://react.dev/reference/react-dom/client/hydrateRoot#suppressing-unavoidable-hydration-mismatch-errors 142 | // * https://stackoverflow.com/questions/40093655/how-do-i-add-attributes-to-existing-html-elements-in-typescript-jsx 143 | suppressHydrationWarning: true, 144 | 145 | // On Next.js in prod, the react `src` prop may end up being different 146 | // from the rendered DOM `src` attribute. Keep track of the prop for 147 | // mapping. 148 | 'data-src-prop': imageSource.src, 149 | }; 150 | 151 | if (isServerOrStatic) { 152 | // We don't want to leak `data-path-on-server` to the client, so we remove 153 | // it from the attributes. 154 | newAttrs['data-path-on-server'] = undefined; 155 | } 156 | 157 | const knownImageRegions = imageRegionsMap.get(imageSource.src); 158 | if (knownImageRegions) { 159 | newAttrs['data-image-regions'] = knownImageRegions; 160 | } else { 161 | if (isBrowser) { 162 | // Note that at this point, possibly the DOM already has the attributes 163 | // `data-image-regions=` etc., pre-rendered by the server. In that case, 164 | // `cloneElement()` won't discard them, but they'll survive. 165 | } 166 | } 167 | 168 | const extendedChild = React.cloneElement(child, newAttrs); 169 | _traceIfDebug(debug, 'Rendering extended child:', extendedChild); 170 | 171 | return extendedChild; 172 | }); 173 | 174 | // See 175 | // https://stackoverflow.com/questions/57847626/using-async-await-inside-a-react-functional-component 176 | React.useEffect(() => { 177 | _populateImageRegionsMap(imageRegionsMap, setImageRegionsMap, ref, debug); 178 | 179 | _checkParentElement(ref); 180 | }, [imageRegionsMap, ref, debug, numImgChildren]); 181 | 182 | return <>{extendedChildren}; 183 | } 184 | 185 | // This function makes sure that each -like child has an entry in the map, 186 | // worst case with no image regions. 187 | // If we are on server-side, it tries to synchronously reads the image regions 188 | // from the metadata of the image file on disk. 189 | function _initializeImageRegionsMap( 190 | imageRegionsMap: Map, 191 | children: React.ReactElement | React.ReactElement[], 192 | debug: boolean 193 | ) { 194 | _traceIfDebug(debug, 'Initializing image regions map...'); 195 | 196 | React.Children.forEach(children, (child) => { 197 | _traceIfDebug(debug, 'Initializing image regions map for child:', child); 198 | 199 | const imageSource = _getImageSource(child); 200 | if (!imageSource) { 201 | // This child isn't an -like element, skipping. 202 | return; 203 | } 204 | 205 | if (!imageRegionsMap.get(imageSource.src)) { 206 | let imageRegions = ''; 207 | if (isServerOrStatic) { 208 | if (!imageSource.pathOnServer) { 209 | _warn( 210 | 'Missing data-path-on-server attribute for', 211 | imageSource.src, 212 | ", can't read image regions from disk. You probably want to read " + 213 | 'https://docs.frameright.io/react/ssr' 214 | ); 215 | } else if (imageSource.pathOnServer !== 'none') { 216 | _traceIfDebug( 217 | debug, 218 | 'Reading image regions on disk for', 219 | imageSource.src 220 | ); 221 | imageRegions = _readImageRegionsJsonFromDisk( 222 | imageSource.pathOnServer, 223 | debug 224 | ); 225 | } 226 | } 227 | imageRegionsMap.set(imageSource.src, imageRegions); 228 | } else { 229 | _traceIfDebug(debug, 'Found image regions in state for', imageSource.src); 230 | } 231 | }); 232 | } 233 | 234 | // On client-side, for each key of the map, which is an image src, fetch/parse 235 | // the image regions from the image's metadata, if it hasn't been done already, 236 | // and populate the map accordingly. 237 | // Not only it populates the map, but it also calls the provided react state 238 | // setter. 239 | // 240 | // Note: imgChildRef is a ref to one of the -like children. 241 | async function _populateImageRegionsMap( 242 | imageRegionsMap: Map, 243 | setImageRegionsMap: React.Dispatch>>, 244 | imgChildRef: React.MutableRefObject, 245 | debug: boolean 246 | ) { 247 | _traceIfDebug(debug, 'Populating image regions map if needed...'); 248 | 249 | // Building a map of image regions from the pre-rendered DOM, if any. 250 | const imageRegionsMapFromDom = new Map(); 251 | for (const child of _getImgChildren(imgChildRef)) { 252 | const imageSource = _getImageSource(child); 253 | if (imageSource) { 254 | _traceIfDebug( 255 | debug, 256 | 'Reading image regions from DOM for', 257 | imageSource.src, 258 | '...' 259 | ); 260 | 261 | const imageRegions = child.dataset.imageRegions; 262 | if (imageRegions) { 263 | imageRegionsMapFromDom.set(imageSource.src, imageRegions); 264 | } 265 | } 266 | } 267 | 268 | let modified = false; 269 | for (const [src, imageRegions] of imageRegionsMap) { 270 | if (!imageRegions) { 271 | const imageRegionsFromDom = imageRegionsMapFromDom.get(src); 272 | if (imageRegionsFromDom) { 273 | // No need to fetch/parse the image regions from the image's metadata, 274 | // we already have them from the pre-rendered DOM. 275 | _traceIfDebug(debug, 'Populating image regions from DOM for', src); 276 | imageRegionsMap.set(src, imageRegionsFromDom); 277 | } else { 278 | // The regions for this image haven't been fetched yet. Let's fetch them 279 | // now. 280 | _traceIfDebug( 281 | debug, 282 | 'Image regions not found in DOM for', 283 | src, 284 | ', fetching...' 285 | ); 286 | 287 | let arrayBuffer: ArrayBuffer; 288 | try { 289 | // Notes: 290 | // * may or may not be in cache yet. 291 | // * may lead to CORS-related errors. 292 | const image = await fetch(src); 293 | 294 | arrayBuffer = await image.arrayBuffer(); 295 | } catch (error) { 296 | _warn('Error fetching image:', error); 297 | continue; 298 | } 299 | 300 | // Because of the awaits, the regions may have been populated already by 301 | // another promise. Let's check again: 302 | if (imageRegionsMap.get(src)) { 303 | _traceIfDebug( 304 | debug, 305 | 'Image regions for', 306 | src, 307 | 'already populated meanwhile, aborting.' 308 | ); 309 | continue; 310 | } 311 | 312 | await _waitForImports(debug); 313 | const regions = _readImageRegionsJsonFromBuffer(arrayBuffer); 314 | if (regions) { 315 | _traceIfDebug( 316 | debug, 317 | 'Populating image regions from metadata for', 318 | src 319 | ); 320 | imageRegionsMap.set(src, regions); 321 | modified = true; 322 | } 323 | } 324 | } 325 | } 326 | 327 | if (modified) { 328 | _traceIfDebug(debug, 'Updating image regions map in state.'); 329 | setImageRegionsMap(new Map(imageRegionsMap)); 330 | } else { 331 | _traceIfDebug(debug, 'Image regions map in state is up-to-date.'); 332 | } 333 | 334 | _traceIfDebug(debug, 'Image regions map in state:', imageRegionsMap); 335 | } 336 | 337 | // Note: imgChildRef is a ref to one of the -like children. 338 | function _checkParentElement( 339 | imgChildRef: React.MutableRefObject 340 | ) { 341 | const child = imgChildRef.current; 342 | if (child) { 343 | const parent = child.parentElement; 344 | if (parent && !parent.dataset.idcParent) { 345 | _warn( 346 | "Parent element of doesn't have a " + 347 | "'data-idc-parent' attribute. You probably want to read " + 348 | 'https://docs.frameright.io/react/attributes#parent-dom-elements-attributes' 349 | ); 350 | } 351 | } 352 | } 353 | 354 | // Note: imgChildRef is a ref to one of the -like children. 355 | function _getImgChildren( 356 | imgChildRef: React.MutableRefObject 357 | ): HTMLImageElement[] { 358 | const child = imgChildRef.current; 359 | if (child) { 360 | // Note: we use the UUID to make sure we don't catch neighboring images 361 | // managed by another : 362 | // 363 | //
<-- DOM parent of all the s 364 | // <-- doesn't produce a DOM element 365 | // 366 | // 367 | // 368 | // <-- doesn't produce a DOM element 369 | // <-- DOM sibling of the previous s 370 | // 371 | //
372 | const uuid = child.dataset.idcUuid; 373 | if (uuid) { 374 | const parent = child.parentElement; 375 | if (parent) { 376 | return Array.from( 377 | parent.querySelectorAll('[data-idc-uuid="' + uuid + '"]') 378 | ); 379 | } 380 | } 381 | } 382 | return []; 383 | } 384 | 385 | // To be used only on server-side. 386 | function _readImageRegionsJsonFromDisk( 387 | pathOnServer: string, 388 | debug: boolean 389 | ): string { 390 | if (!fs) { 391 | _warn("fs module not available, can't read image regions from disk."); 392 | return ''; 393 | } 394 | 395 | let result = ''; 396 | try { 397 | _traceIfDebug(debug, 'Reading image regions from', pathOnServer); 398 | const buffer = fs.readFileSync(pathOnServer); 399 | result = _readImageRegionsJsonFromBuffer(buffer); 400 | _traceIfDebug(debug, 'Found image regions:', result); 401 | } catch (error) { 402 | _warn('Error while reading image regions from disk:', error); 403 | } 404 | return result; 405 | } 406 | 407 | function _readImageRegionsJsonFromBuffer(buffer: Buffer | ArrayBuffer): string { 408 | const parser = new Parser(buffer); 409 | const regions = parser.getIdcMetadata('rectangle', 'crop'); 410 | return JSON.stringify(regions); 411 | } 412 | 413 | function _getImageSource( 414 | element: React.ReactElement | HTMLImageElement 415 | ): ImageSource | null { 416 | if (!_isImgElement(element)) { 417 | return null; 418 | } 419 | 420 | let result: ImageSource | null = null; 421 | if ('props' in element) { 422 | // React element 423 | 424 | const elementProps = { 425 | src: {}, 426 | 'data-path-on-server': null, 427 | ...(element.props as object), 428 | }; 429 | 430 | if (typeof elementProps.src === 'string') { 431 | result = { 432 | src: elementProps.src, 433 | }; 434 | } else if ('src' in elementProps.src) { 435 | // This typically happen when statically importing an image on Next.js, 436 | // the resulting object being an instance of StaticImageData. 437 | result = { 438 | src: elementProps.src.src as string, 439 | }; 440 | 441 | if ('pathOnServer' in elementProps.src) { 442 | result.pathOnServer = elementProps.src.pathOnServer as string; 443 | } 444 | } else { 445 | _warn('Unknown src= attribute format: ', elementProps.src); 446 | return null; 447 | } 448 | 449 | if (elementProps['data-path-on-server']) { 450 | result.pathOnServer = elementProps['data-path-on-server']; 451 | } 452 | } else { 453 | // HTML element 454 | 455 | result = { 456 | src: 457 | element.attributes.getNamedItem('data-src-prop')?.value || 458 | element.attributes.getNamedItem('src')?.value || 459 | element.src, 460 | }; 461 | } 462 | 463 | return result; 464 | } 465 | 466 | // Returns true if the element is an -like element, i.e. also Next.js 467 | // or react-bootstrap elements, for example. 468 | function _isImgElement( 469 | element: React.ReactElement | HTMLImageElement 470 | ): boolean { 471 | if ('props' in element) { 472 | // React element 473 | 474 | const elementProps = { 475 | src: null, 476 | ...(element.props as object), 477 | }; 478 | 479 | return !!elementProps.src; 480 | } else if ('attributes' in element) { 481 | // HTML element 482 | return !!element.attributes.getNamedItem('src')?.value; 483 | } 484 | return false; 485 | } 486 | 487 | // FIXME: workaround for async import() on Vite/Vike in dev mode. 488 | async function _waitForImports(debug: boolean) { 489 | for (const waitMs of [100, 200, 500, 1000, 1000]) { 490 | if (fs || isBrowser) { 491 | _traceIfDebug(debug, 'All imports have resolved.'); 492 | return; 493 | } 494 | _traceIfDebug(debug, 'Waiting for imports to resolve...'); 495 | await new Promise((resolve) => setTimeout(resolve, waitMs)); 496 | } 497 | _warn('Some imports are still missing, image regions will not be available.'); 498 | } 499 | 500 | const consolePrefix = '[idc]'; 501 | 502 | function _warn(...args: any[]) { 503 | console.warn(consolePrefix, '[warn]', ...args); 504 | } 505 | 506 | function _traceIfDebug(debug: boolean, ...args: any[]) { 507 | if (debug) { 508 | console.log(consolePrefix, '[debug]', ...args); 509 | } 510 | } 511 | -------------------------------------------------------------------------------- /test/index.test.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { createRoot } from 'react-dom/client'; 3 | 4 | // Workaround for "ReferenceError: TextDecoder is not defined". See 5 | // * https://stackoverflow.com/questions/68468203/why-am-i-getting-textencoder-is-not-defined-in-jest 6 | // * https://mattbatman.com/textencoder-textdecoder-jest-and-jsdom/ 7 | import { TextDecoder } from 'util'; 8 | Object.defineProperty(window, 'TextDecoder', { 9 | writable: true, 10 | value: TextDecoder, 11 | }); 12 | // eslint-disable-next-line import/first 13 | import { ImageDisplayControl } from '../src'; 14 | 15 | describe('it', () => { 16 | it('renders without crashing', () => { 17 | const div = document.createElement('div'); 18 | const root = createRoot(div); 19 | root.render(); 20 | root.unmount(); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // see https://www.typescriptlang.org/tsconfig to better understand tsconfigs 3 | "include": ["src", "types"], 4 | "compilerOptions": { 5 | // Needed for iterating on maps with for...of 6 | "target": "es2015", 7 | 8 | "module": "esnext", 9 | "lib": ["dom", "esnext"], 10 | "importHelpers": true, 11 | // output .d.ts declaration files for consumers 12 | "declaration": true, 13 | // output .js.map sourcemap files for consumers 14 | "sourceMap": true, 15 | // match output dir to input dir. e.g. dist/index instead of dist/src/index 16 | "rootDir": "./src", 17 | // stricter type-checking for stronger correctness. Recommended by TS 18 | "strict": true, 19 | // linter checks for common issues 20 | "noImplicitReturns": true, 21 | "noImplicitAny": true, 22 | "noFallthroughCasesInSwitch": true, 23 | // noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative 24 | "noUnusedLocals": true, 25 | "noUnusedParameters": true, 26 | // use Node's module resolution algorithm, instead of the legacy TS one 27 | "moduleResolution": "node", 28 | // transpile JSX to React.createElement 29 | "jsx": "react", 30 | // interop between ESM and CJS modules. Recommended by TS 31 | "esModuleInterop": true, 32 | // significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS 33 | "skipLibCheck": true, 34 | // error out if import and file system have a casing mismatch. Recommended by TS 35 | "forceConsistentCasingInFileNames": true, 36 | // commonly used when type-checking separately with `tsc` 37 | "noEmit": true 38 | } 39 | } 40 | --------------------------------------------------------------------------------