├── .dockerignore ├── .eslintrc.cjs ├── .gitignore ├── .prettierrc ├── .vscode └── settings.json ├── Dockerfile ├── Dockerfile.slim ├── LICENSE ├── README.md ├── docs ├── demo1.png ├── demo2.png └── demo3.png ├── index.html ├── nginx.conf ├── package-lock.json ├── package.json ├── public └── logo.svg ├── src ├── App.tsx ├── ContextAction.ts ├── Initial.tsx ├── components │ ├── Compare │ │ ├── index.module.scss │ │ └── index.tsx │ ├── CompressOption │ │ ├── index.module.scss │ │ └── index.tsx │ ├── ImageInput │ │ ├── index.module.scss │ │ └── index.tsx │ ├── Indicator │ │ ├── index.module.scss │ │ └── index.tsx │ ├── Loading │ │ ├── index.module.scss │ │ └── index.tsx │ ├── Logo │ │ ├── index.module.scss │ │ └── index.tsx │ ├── OptionItem │ │ ├── index.module.scss │ │ └── index.tsx │ ├── ProgressHint │ │ ├── index.module.scss │ │ └── index.tsx │ └── UploadCard │ │ ├── index.module.scss │ │ ├── index.tsx │ │ └── state.ts ├── engines │ ├── AvifImage.ts │ ├── AvifWasmModule.js │ ├── CanvasImage.ts │ ├── GifImage.ts │ ├── GifWasmModule.js │ ├── ImageBase.ts │ ├── PngImage.ts │ ├── PngWasmModule.js │ ├── Queue.ts │ ├── SvgImage.ts │ ├── WorkerCompress.ts │ ├── WorkerPreview.ts │ ├── avif.wasm │ ├── gif.wasm │ ├── handler.ts │ ├── png.wasm │ ├── support.ts │ ├── svgConvert.ts │ ├── svgParse.ts │ └── transform.ts ├── functions.ts ├── global.tsx ├── locale.ts ├── locales │ ├── en-US.ts │ ├── es-ES.ts │ ├── fa-IR.ts │ ├── fr-FR.ts │ ├── ja-JP.ts │ ├── ko-KR.ts │ ├── tr-TR.ts │ ├── zh-CN.ts │ └── zh-TW.ts ├── main.scss ├── main.tsx ├── media.ts ├── mimes.ts ├── modules.ts ├── pages │ ├── error404 │ │ ├── index.module.scss │ │ └── index.tsx │ └── home │ │ ├── LeftContent.module.scss │ │ ├── LeftContent.tsx │ │ ├── RightOption.module.scss │ │ ├── RightOption.tsx │ │ ├── index.module.scss │ │ ├── index.tsx │ │ └── useColumn.tsx ├── router.tsx ├── states │ └── home.ts ├── type.ts └── vite-env.d.ts ├── tests └── utils.test.ts ├── tsconfig.json ├── tsconfig.node.json └── vite.config.ts /.dockerignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | docs 3 | node_modules 4 | 5 | .DS_Store -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true }, 4 | extends: [ 5 | "eslint:recommended", 6 | "plugin:@typescript-eslint/recommended", 7 | "plugin:react-hooks/recommended", 8 | ], 9 | ignorePatterns: ["dist", ".eslintrc.cjs"], 10 | parser: "@typescript-eslint/parser", 11 | plugins: ["react-refresh"], 12 | rules: { 13 | "react-refresh/only-export-components": [ 14 | "warn", 15 | { allowConstantExport: true }, 16 | ], 17 | "no-empty": "off", 18 | "@typescript-eslint/no-explicit-any": "off", 19 | }, 20 | }; 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | .yarn/install-state.gz 8 | 9 | # testing 10 | /coverage 11 | 12 | # next.js 13 | /.next/ 14 | /out/ 15 | 16 | # production 17 | /build 18 | /dist 19 | 20 | # misc 21 | .DS_Store 22 | *.pem 23 | 24 | # debug 25 | npm-debug.log* 26 | yarn-debug.log* 27 | yarn-error.log* 28 | 29 | # local env files 30 | .env*.local 31 | 32 | # vercel 33 | .vercel 34 | 35 | # typescript 36 | *.tsbuildinfo 37 | next-env.d.ts 38 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": false, 3 | "trailingComma": "all", 4 | "tabWidth": 2, 5 | "semi": true, 6 | "bracketSpacing": true, 7 | "bracketSameLine": false 8 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib" 3 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:20-alpine 2 | WORKDIR /app 3 | COPY . /app 4 | RUN set -eux \ 5 | && npm install --ignore-scripts \ 6 | && npm run build:preview 7 | CMD [ "npm", "run", "preview" ] 8 | EXPOSE 3001 -------------------------------------------------------------------------------- /Dockerfile.slim: -------------------------------------------------------------------------------- 1 | # -------------------Desciption--------------------- 2 | 3 | # FROM nginx:alpine-slim: Uses the alpine-slim nginx image as the base image. 4 | # COPY nginx.conf /etc/nginx/conf.d/default.conf: Copies the nginx.conf file to the /etc/nginx/conf.d directory in the container, serving as the nginx configuration file. 5 | # COPY dist /usr/share/nginx/html: Copies the contents of the dist directory to the /usr/share/nginx/html directory in the container, which serves as nginx's static file directory. 6 | # EXPOSE 3000: Declares that the container is listening on port 3000. 7 | # CMD ["nginx", "-g", "daemon off"]: Runs the nginx command with the parameters -g daemon off when the container starts, indicating nginx should start in the foreground. 8 | 9 | # -------------------Usage-------------------- 10 | 11 | # $ docker build -f Dockerfile.slim -t picsmaller-slim . 12 | # $ docker run -d -p 9000:3000 picsmaller-slim 13 | 14 | FROM nginx:alpine-slim 15 | 16 | COPY nginx.conf /etc/nginx/conf.d/default.conf 17 | 18 | COPY dist /usr/share/nginx/html 19 | 20 | EXPOSE 3000 21 | 22 | CMD ["nginx", "-g", "daemon off;"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Joye 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 | # Pic Smaller (图小小) 2 | 3 | **Pic Smaller** is a super easy-to-use online image compression tool. Simply upload your desired image(s), and Pic Smaller will automatically perform its compress functionality and provide details on the results. Users can also customize features to suite their desired output, such as setting the output format or number of output colors. It's intuitive, website and mobile friendly, and supports compression configuration. At the same time, because of purely local compression without any server-side logic, it is completely safe. 4 | 5 |
6 | 7 |
8 | Figure 1: Pic Smaller's landing page, where users can upload their images for compression 9 |
10 |
11 |
12 | Figure 2: Example pictures uploaded for compression shown on the left, and Pic Smaller's customizable compression and editing features shown on the right 13 |
14 |
15 |
16 | Figure 3: Pic Smaller's comparison tool, that the user can drag to see the difference between the original and compressed image 17 |
18 |
19 | 20 | ## Usage 21 | 22 | Pic smaller has been deployed to [`vercel`](https://vercel.com/), you can use it by visiting the URL [pic-smaller.vercel.app](https://pic-smaller.vercel.app). Due to the GFW, Chinese users can use it by visiting the URL [picsmaller.com](https://picsmaller.com/) 23 | 24 | > [picsmaller.com](https://picsmaller.com/) is a new domain that has just been applied for. The old domain [txx.cssrefs.com](https://txx.cssrefs.com/) is still accessible, but will be expired on `2025-02-22` and payment will not continue. Please use the latest domain to access the service. 25 | 26 | ## Preqrequisites 27 | 28 | Node.js 29 | 1. Navigate to the Node.js website: https://nodejs.org/en/ 30 | 2. Download the recommended version (which is currently v20.17.0). 31 | 3. Follow the steps on your computer to finish its installation. 32 | 4. To verify installation, open up the command prompt and run the following command. If the version is outputted, you have succesfully installed Node.js. 33 | ``` 34 | node -v 35 | ``` 36 | 37 | ## Develop 38 | 39 | Pic smaller is a [Vite](https://vitejs.dev/) + [React](https://react.dev/) project, you have to get familiar with them first. It uses modern browser technologies such as `OffscreenCanvas`, `WebAssembly`, and `Web Worker`. You should also be familiar with them before developing. 40 | 41 | ```bash 42 | # Clone the repo 43 | git clone https://github.com/joye61/pic-smaller.git 44 | 45 | # Change cwd 46 | cd ./pic-smaller 47 | 48 | # Install dependences 49 | npm install 50 | 51 | # Start to develop 52 | npm run dev 53 | ``` 54 | 55 | Hold control and left click the URL next to "Local:" to open the website on your local machine. 56 | 57 | ![image](https://github.com/user-attachments/assets/b82b296d-74bf-48db-8284-34f2db3b8c3f) 58 |
59 | Figure 4: Where to open the localhost website link 60 | 61 | 62 | ## Deploy 63 | 64 | If you want to independently deploy this project on your own server, the following document based on Docker, and [Dockerfile](./Dockerfile) script has been tested. Within the project root directory, follow the instructions to start docker application 65 | 66 | ```bash 67 | # Build docker image from Dockerfile 68 | docker build -t picsmaller . 69 | 70 | # Start a container 71 | docker run -p 3001:3001 -d picsmaller 72 | ``` 73 | 74 | Now you can access the project via http://127.0.0.1:3001. If you want your project to be accessible to everyone, you need to prepare a domain name pointing to your local machine, and then proxy it to port 3001 of this machine, through a reverse proxy server like nginx. 75 | 76 | ## Contributing 77 | 78 | 1. Ensure all required dependency installations have been properly followed to accurately test your changes. 79 | 2. Update the README.md with information about changes to the interface, including new environment variables, important file locations, and container parameters. 80 | 4. Increase the version numbers in all example files and the README.md to reflect the new version represented by your changes. 81 | 5. Create a Pull Request with an appropriate and descriptive title and description. 82 | 6. You can reach out to other developers to review and merge the Pull Request if appropriate. 83 | 84 | Our standards for contributions: By using welcoming and inclusive language, respecting diverse viewpoints and experiences, embracing constructive criticism, and prioritizing what’s best for the community, we can create a positive and collaborative environment for everyone. 85 | 86 | ## Project Structure 87 | 88 | The src folder stores in all the files and components used in the react application like App.tsx. 89 |
90 | The tests folder includes code to test particular features during the development process. 91 |
92 | The docs folder includes the pictures used for this README documentation. 93 | 94 | ## License 95 | 96 | This project is under [MIT](LICENSE) license. 97 | 98 | ## Contact 99 | 100 | Please contact the repository owner joye61's email for any questions: 89065495@qq.com 101 | 102 | ## Thanks 103 | 104 | - [ant-design](https://github.com/ant-design/ant-design) Provides React-based UI solutions 105 | - [wasm-image-compressor](https://github.com/antelle/wasm-image-compressor) Provides PNG image compression implementation based on Webassembly 106 | - [gifsicle-wasm-browser](https://github.com/renzhezhilu/gifsicle-wasm-browser) Provides GIF image compression implementation based on Webassembly 107 | - [wasm_avif](https://github.com/packurl/wasm_avif) Provides AVIF image compression implementation based on Webassembly 108 | - [svgo](https://github.com/svg/svgo) Provides SVG vector compression 109 | -------------------------------------------------------------------------------- /docs/demo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joye61/pic-smaller/7ddf0508452372d25ff9a3c197e0debafef602fb/docs/demo1.png -------------------------------------------------------------------------------- /docs/demo2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joye61/pic-smaller/7ddf0508452372d25ff9a3c197e0debafef602fb/docs/demo2.png -------------------------------------------------------------------------------- /docs/demo3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joye61/pic-smaller/7ddf0508452372d25ff9a3c197e0debafef602fb/docs/demo3.png -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Pic Smaller – Compress JPEG, PNG, WEBP, AVIF, SVG and GIF images intelligently 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /nginx.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 3000; 3 | server_name localhost; 4 | location / { 5 | root /usr/share/nginx/html; 6 | index index.html; 7 | try_files $uri $uri/ /index.html; 8 | } 9 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pic-smaller", 3 | "private": true, 4 | "version": "1.1.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "tsc && vite build", 9 | "build:preview": "tsc && vite build --mode preview", 10 | "preview": "vite preview", 11 | "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", 12 | "format": "prettier --write --no-error-on-unmatched-pattern --ignore-unknown src/**/*", 13 | "test": "vitest run" 14 | }, 15 | "dependencies": { 16 | "@ant-design/icons": "^5.3.6", 17 | "@vercel/analytics": "^1.2.2", 18 | "antd": "^5.16.4", 19 | "classnames": "^2.5.1", 20 | "filesize": "^10.1.1", 21 | "get-user-locale": "^2.3.2", 22 | "history": "^5.3.0", 23 | "jszip": "^3.10.1", 24 | "mobx": "^6.12.3", 25 | "mobx-react-lite": "^4.0.7", 26 | "react": "^18.2.0", 27 | "react-dom": "^18.2.0", 28 | "react-responsive": "^10.0.0", 29 | "sprintf-js": "^1.1.3", 30 | "svgo": "^3.3.2" 31 | }, 32 | "devDependencies": { 33 | "@types/lodash": "^4.17.0", 34 | "@types/node": "^20.12.7", 35 | "@types/react": "^18.2.66", 36 | "@types/react-dom": "^18.2.22", 37 | "@types/sprintf-js": "^1.1.4", 38 | "@typescript-eslint/eslint-plugin": "^7.2.0", 39 | "@typescript-eslint/parser": "^7.2.0", 40 | "@vitejs/plugin-react": "^4.2.1", 41 | "eslint": "^8.57.0", 42 | "eslint-plugin-react-hooks": "^4.6.0", 43 | "eslint-plugin-react-refresh": "^0.4.6", 44 | "prettier": "^3.2.5", 45 | "sass": "^1.75.0", 46 | "typescript": "^5.2.2", 47 | "vconsole": "^3.15.1", 48 | "vite": "^5.2.0", 49 | "vitest": "^1.6.0" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /public/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import { ConfigProvider, App as AntApp } from "antd"; 2 | import { observer } from "mobx-react-lite"; 3 | import { gstate } from "./global"; 4 | import { ContextAction } from "./ContextAction"; 5 | import { Analytics } from "@vercel/analytics/react"; 6 | import { Loading } from "./components/Loading"; 7 | import { useResponse } from "./media"; 8 | import { useEffect } from "react"; 9 | 10 | function useMobileVConsole() { 11 | const { isMobile } = useResponse(); 12 | useEffect(() => { 13 | if (!isMobile || !import.meta.env.DEV) return; 14 | let vConsole: any = null; 15 | import("vconsole").then((result) => { 16 | vConsole = new result.default({ theme: "dark" }); 17 | }); 18 | return () => vConsole?.destroy(); 19 | }, [isMobile]); 20 | } 21 | 22 | export const App = observer(() => { 23 | useMobileVConsole(); 24 | 25 | return ( 26 | 36 | 37 | 38 | 39 | {import.meta.env.MODE === "production" && } 40 | {gstate.page} 41 | {gstate.loading && } 42 | 43 | ); 44 | }); 45 | -------------------------------------------------------------------------------- /src/ContextAction.ts: -------------------------------------------------------------------------------- 1 | import { App } from "antd"; 2 | import type { MessageInstance } from "antd/es/message/interface"; 3 | import type { ModalStaticFunctions } from "antd/es/modal/confirm"; 4 | import type { NotificationInstance } from "antd/es/notification/interface"; 5 | 6 | let message: MessageInstance; 7 | let notification: NotificationInstance; 8 | let modal: Omit; 9 | 10 | export function ContextAction() { 11 | const staticFunction = App.useApp(); 12 | message = staticFunction.message; 13 | modal = staticFunction.modal; 14 | notification = staticFunction.notification; 15 | return null; 16 | } 17 | 18 | export { message, notification, modal }; 19 | -------------------------------------------------------------------------------- /src/Initial.tsx: -------------------------------------------------------------------------------- 1 | import { observer } from "mobx-react-lite"; 2 | import { Flex, Typography } from "antd"; 3 | import { useEffect } from "react"; 4 | import { locales, modules } from "./modules"; 5 | import { initRouter } from "./router"; 6 | import { gstate } from "./global"; 7 | import { Indicator } from "./components/Indicator"; 8 | import { avifCheck } from "./engines/support"; 9 | 10 | const loadResources = () => { 11 | const loadList: Array> = [ 12 | import("jszip"), 13 | fetch(new URL("./engines/png.wasm", import.meta.url)), 14 | fetch(new URL("./engines/gif.wasm", import.meta.url)), 15 | fetch(new URL("./engines/avif.wasm", import.meta.url)), 16 | import("./engines/WorkerPreview?worker"), 17 | import("./engines/WorkerCompress?worker"), 18 | ]; 19 | const langs = Object.values(locales); 20 | const pages = Object.values(modules); 21 | for (const load of [...langs, ...pages]) { 22 | loadList.push(load()); 23 | } 24 | loadList.push(avifCheck()); 25 | return Promise.all(loadList); 26 | }; 27 | 28 | const useInit = () => { 29 | useEffect(() => { 30 | (async () => { 31 | await loadResources(); 32 | initRouter(); 33 | })(); 34 | }, []); 35 | }; 36 | 37 | export const Initial = observer(() => { 38 | useInit(); 39 | 40 | return ( 41 | 42 | 43 | 44 | 45 | {gstate.locale?.initial} 46 | 47 | 48 | 49 | ); 50 | }); 51 | -------------------------------------------------------------------------------- /src/components/Compare/index.module.scss: -------------------------------------------------------------------------------- 1 | @keyframes BoxShow { 2 | from { 3 | opacity: 0; 4 | } 5 | to { 6 | opacity: 1; 7 | } 8 | } 9 | 10 | @keyframes BoxHide { 11 | from { 12 | opacity: 1; 13 | } 14 | to { 15 | opacity: 0; 16 | } 17 | } 18 | 19 | .container { 20 | width: 100vw; 21 | height: 100vh; 22 | position: absolute; 23 | left: 0; 24 | right: 0; 25 | top: 0; 26 | bottom: 0; 27 | z-index: 9; 28 | user-select: none; 29 | background-color: #fff; 30 | background-image: linear-gradient( 31 | 45deg, 32 | #e0e0e0 25%, 33 | transparent 25%, 34 | transparent 75%, 35 | #e0e0e0 75% 36 | ), 37 | linear-gradient( 38 | 45deg, 39 | #e0e0e0 25%, 40 | transparent 25%, 41 | transparent 75%, 42 | #e0e0e0 75% 43 | ); 44 | background-size: 20px 20px; 45 | background-position: 46 | 0 0, 47 | 10px 10px; 48 | 49 | &.show { 50 | animation: BoxShow 0.3s ease-in forwards; 51 | } 52 | &.hide { 53 | animation: BoxHide 0.3s ease-out forwards; 54 | } 55 | &.moving { 56 | cursor: grab; 57 | } 58 | 59 | > div:nth-child(1), 60 | > div:nth-child(2) { 61 | position: absolute; 62 | top: 0; 63 | bottom: 0; 64 | overflow: hidden; 65 | box-sizing: border-box; 66 | img { 67 | position: absolute; 68 | top: 50%; 69 | transform: translateY(-50%); 70 | } 71 | } 72 | > div:nth-child(1) { 73 | left: 0; 74 | } 75 | > div:nth-child(2) { 76 | right: 0; 77 | } 78 | 79 | > div:nth-child(3) { 80 | position: absolute; 81 | top: 0; 82 | bottom: 0; 83 | z-index: 3; 84 | background-color: #000; 85 | > div { 86 | position: absolute; 87 | width: 30px; 88 | height: 30px; 89 | border-radius: 50%; 90 | cursor: grab; 91 | top: 50%; 92 | left: 50%; 93 | transform: translate(-50%, -50%); 94 | background-color: rgba(0, 0, 0, 0.8); 95 | svg { 96 | width: 20px; 97 | height: 20px; 98 | path { 99 | fill: #fff; 100 | } 101 | } 102 | } 103 | } 104 | } 105 | 106 | .action { 107 | position: absolute; 108 | top: 16px; 109 | right: 16px; 110 | } 111 | 112 | .before { 113 | position: absolute; 114 | left: 16px; 115 | bottom: 16px; 116 | } 117 | .after { 118 | position: absolute; 119 | right: 16px; 120 | bottom: 16px; 121 | } 122 | 123 | .help { 124 | width: 240px; 125 | } 126 | -------------------------------------------------------------------------------- /src/components/Compare/index.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback, useEffect, useRef, useState } from "react"; 2 | import style from "./index.module.scss"; 3 | import { Button, Flex, Popover, Space } from "antd"; 4 | import { CloseOutlined, QuestionCircleOutlined } from "@ant-design/icons"; 5 | import { createPortal } from "react-dom"; 6 | import { ImageItem, homeState } from "@/states/home"; 7 | import { observer } from "mobx-react-lite"; 8 | import classNames from "classnames"; 9 | import { gstate } from "@/global"; 10 | 11 | export interface CompareState { 12 | x: number; 13 | xrate: number; 14 | scale: number; 15 | moving: boolean; 16 | status: "show" | "hide"; 17 | dividerWidth: number; 18 | imageWidth: number; 19 | imageHeight: number; 20 | containerWidth: number; 21 | containerHeight: number; 22 | } 23 | 24 | export const Compare = observer(() => { 25 | const infoRef = useRef>( 26 | homeState.list.get(homeState.compareId!) as Required, 27 | ); 28 | const containerRef = useRef(null); 29 | const barRef = useRef(null); 30 | const [state, setState] = useState({ 31 | x: 0, 32 | xrate: 0.5, 33 | scale: 0.8, 34 | moving: false, 35 | status: "show", 36 | dividerWidth: 2, 37 | containerWidth: 0, 38 | containerHeight: 0, 39 | imageWidth: 0, 40 | imageHeight: 0, 41 | }); 42 | const [oldLoaded, setOldLoaded] = useState(false); 43 | const [newLoaded, setNewLoaded] = useState(false); 44 | 45 | const update = useCallback( 46 | (newState: Partial) => { 47 | setState({ 48 | ...state, 49 | ...newState, 50 | }); 51 | }, 52 | [state], 53 | ); 54 | 55 | const getState = useCallback(() => { 56 | return state; 57 | }, [state]); 58 | 59 | const updateRef = useRef<(newState: Partial) => void>(update); 60 | const stateRef = useRef<() => CompareState>(getState); 61 | useEffect(() => { 62 | updateRef.current = update; 63 | stateRef.current = getState; 64 | }, [update, getState]); 65 | 66 | useEffect(() => { 67 | gstate.loading = true; 68 | }, []); 69 | 70 | useEffect(() => { 71 | if (oldLoaded && newLoaded) { 72 | gstate.loading = false; 73 | } 74 | }, [oldLoaded, newLoaded]); 75 | 76 | useEffect(() => { 77 | const doc = document.documentElement; 78 | const bar = barRef.current!; 79 | 80 | let isControl = false; 81 | let cursorX = 0; 82 | 83 | const resize = () => { 84 | const states = stateRef.current(); 85 | const rect = containerRef.current!.getBoundingClientRect(); 86 | let imageWidth: number; 87 | let imageHeight: number; 88 | if ( 89 | infoRef.current.width / infoRef.current.height > 90 | rect.width / rect.height 91 | ) { 92 | imageWidth = rect.width * states.scale; 93 | imageHeight = 94 | (imageWidth * infoRef.current.height) / infoRef.current.width; 95 | } else { 96 | imageHeight = rect.height * states.scale; 97 | imageWidth = 98 | (imageHeight * infoRef.current.width) / infoRef.current.height; 99 | } 100 | updateRef.current({ 101 | x: rect.width * states.xrate, 102 | imageWidth, 103 | imageHeight, 104 | containerWidth: rect.width, 105 | containerHeight: rect.height, 106 | }); 107 | }; 108 | 109 | const mousedown = (event: MouseEvent) => { 110 | isControl = true; 111 | cursorX = event.clientX; 112 | updateRef.current({ moving: true }); 113 | }; 114 | 115 | const mouseup = () => { 116 | isControl = false; 117 | cursorX = 0; 118 | updateRef.current({ moving: false }); 119 | }; 120 | 121 | const mousemove = (event: MouseEvent) => { 122 | if (isControl) { 123 | const states = stateRef.current(); 124 | let x = states.x + event.clientX - cursorX; 125 | const min = (states.containerWidth - states.imageWidth) / 2; 126 | const max = (states.containerWidth + states.imageWidth) / 2; 127 | if (x < min) { 128 | x = min; 129 | } 130 | if (x > max) { 131 | x = max; 132 | } 133 | cursorX = event.clientX; 134 | updateRef.current({ x, xrate: x / states.containerWidth }); 135 | } 136 | }; 137 | 138 | const wheel = (event: WheelEvent) => { 139 | const states = stateRef.current(); 140 | let scale = -0.001 * event.deltaY + states.scale; 141 | if (scale > 1) { 142 | scale = 1; 143 | } 144 | if (scale < 0.1) { 145 | scale = 0.1; 146 | } 147 | 148 | let imageWidth: number; 149 | let imageHeight: number; 150 | if ( 151 | infoRef.current.width / infoRef.current.height > 152 | states.containerWidth / states.containerHeight 153 | ) { 154 | imageWidth = states.containerWidth * scale; 155 | imageHeight = 156 | (imageWidth * infoRef.current.height) / infoRef.current.width; 157 | } else { 158 | imageHeight = states.containerHeight * scale; 159 | imageWidth = 160 | (imageHeight * infoRef.current.width) / infoRef.current.height; 161 | } 162 | 163 | const innerRate = 164 | (states.x - (states.containerWidth - states.imageWidth) / 2) / 165 | states.imageWidth; 166 | const x = 167 | innerRate * imageWidth + (states.containerWidth - imageWidth) / 2; 168 | 169 | updateRef.current({ scale, imageWidth, imageHeight, x }); 170 | }; 171 | 172 | window.addEventListener("resize", resize); 173 | window.addEventListener("wheel", wheel); 174 | bar.addEventListener("mousedown", mousedown); 175 | doc.addEventListener("mousemove", mousemove); 176 | doc.addEventListener("mouseup", mouseup); 177 | 178 | resize(); 179 | 180 | return () => { 181 | window.removeEventListener("resize", resize); 182 | window.removeEventListener("wheel", wheel); 183 | bar.removeEventListener("mousedown", mousedown); 184 | doc.removeEventListener("mousemove", mousemove); 185 | doc.removeEventListener("mouseup", mouseup); 186 | }; 187 | }, []); 188 | 189 | const leftStyle: React.CSSProperties = { 190 | width: `${state.x}px`, 191 | }; 192 | const rightStyle: React.CSSProperties = { 193 | width: `${state.containerWidth - state.x}px`, 194 | }; 195 | const barStyle: React.CSSProperties = { 196 | width: `${state.dividerWidth}px`, 197 | left: `${state.x - state.dividerWidth / 2}px`, 198 | opacity: state.x === 0 ? 0 : 1, 199 | }; 200 | const imageStyle: React.CSSProperties = { 201 | opacity: newLoaded && oldLoaded ? 1 : 0, 202 | }; 203 | const leftImageStyle: React.CSSProperties = { 204 | width: state.imageWidth, 205 | height: state.imageHeight, 206 | left: (state.containerWidth - state.imageWidth) / 2 + "px", 207 | ...imageStyle, 208 | }; 209 | const rightImageStyle: React.CSSProperties = { 210 | width: state.imageWidth, 211 | height: state.imageHeight, 212 | right: (state.containerWidth - state.imageWidth) / 2 + "px", 213 | ...imageStyle, 214 | }; 215 | 216 | let statusClass: string | undefined = undefined; 217 | if (state.status === "show") { 218 | statusClass = style.show; 219 | } 220 | if (state.status === "hide") { 221 | statusClass = style.hide; 222 | } 223 | 224 | return createPortal( 225 |
{ 233 | if (event.animationName === style.BoxHide) { 234 | homeState.compareId = null; 235 | } 236 | }} 237 | > 238 |
239 | { 243 | setOldLoaded(true); 244 | }} 245 | /> 246 |
247 |
248 | { 252 | setNewLoaded(true); 253 | }} 254 | /> 255 |
256 |
257 | 258 | 259 | 260 | 261 | 262 |
263 | 264 | {gstate.locale?.previewHelp}
267 | } 268 | placement="bottomRight" 269 | > 270 |