From 408e90130e07e4f16376115f9138ad26da0fbacc Mon Sep 17 00:00:00 2001 From: Archit1235 Date: Sat, 8 Nov 2025 15:54:27 +0530 Subject: [PATCH 001/114] error correction level selection to QR code generator --- package-lock.json | 41 ++++++++++++++++++- .../tools/image/generic/qr-code/index.tsx | 26 +++++++++++- .../tools/image/generic/qr-code/types.ts | 3 ++ 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 250551e7..36f09629 100644 --- a/package-lock.json +++ b/package-lock.json @@ -584,6 +584,7 @@ "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.14.0.tgz", "integrity": "sha512-O000MLDBDdk/EohJPFUqvnp4qnHeYkVP5B0xEG0D/L7cOKP9kefu2DXn8dj74cQfsEzUqh+sr1RzFqiL1o+PpA==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.18.3", "@emotion/babel-plugin": "^11.13.5", @@ -627,6 +628,7 @@ "resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.14.1.tgz", "integrity": "sha512-qEEJt42DuToa3gurlH4Qqc1kVpNq8wO8cJtDzU46TjlzWjDlsVyevtYCRijVq3SrHsROS+gVQ8Fnea108GnKzw==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.18.3", "@emotion/babel-plugin": "^11.13.5", @@ -1576,6 +1578,7 @@ "resolved": "https://registry.npmjs.org/@jimp/custom/-/custom-0.22.12.tgz", "integrity": "sha512-xcmww1O/JFP2MrlGUMd3Q78S3Qu6W3mYTXYuIqFq33EorgYHV/HqymHfXy9GjiCJ7OI+7lWx6nYFOzU7M4rd1Q==", "license": "MIT", + "peer": true, "dependencies": { "@jimp/core": "^0.22.12" } @@ -1612,6 +1615,7 @@ "resolved": "https://registry.npmjs.org/@jimp/plugin-blit/-/plugin-blit-0.22.12.tgz", "integrity": "sha512-xslz2ZoFZOPLY8EZ4dC29m168BtDx95D6K80TzgUi8gqT7LY6CsajWO0FAxDwHz6h0eomHMfyGX0stspBrTKnQ==", "license": "MIT", + "peer": true, "dependencies": { "@jimp/utils": "^0.22.12" }, @@ -1624,6 +1628,7 @@ "resolved": "https://registry.npmjs.org/@jimp/plugin-blur/-/plugin-blur-0.22.12.tgz", "integrity": "sha512-S0vJADTuh1Q9F+cXAwFPlrKWzDj2F9t/9JAbUvaaDuivpyWuImEKXVz5PUZw2NbpuSHjwssbTpOZ8F13iJX4uw==", "license": "MIT", + "peer": true, "dependencies": { "@jimp/utils": "^0.22.12" }, @@ -1648,6 +1653,7 @@ "resolved": "https://registry.npmjs.org/@jimp/plugin-color/-/plugin-color-0.22.12.tgz", "integrity": "sha512-xImhTE5BpS8xa+mAN6j4sMRWaUgUDLoaGHhJhpC+r7SKKErYDR0WQV4yCE4gP+N0gozD0F3Ka1LUSaMXrn7ZIA==", "license": "MIT", + "peer": true, "dependencies": { "@jimp/utils": "^0.22.12", "tinycolor2": "^1.6.0" @@ -1691,6 +1697,7 @@ "resolved": "https://registry.npmjs.org/@jimp/plugin-crop/-/plugin-crop-0.22.12.tgz", "integrity": "sha512-FNuUN0OVzRCozx8XSgP9MyLGMxNHHJMFt+LJuFjn1mu3k0VQxrzqbN06yIl46TVejhyAhcq5gLzqmSCHvlcBVw==", "license": "MIT", + "peer": true, "dependencies": { "@jimp/utils": "^0.22.12" }, @@ -1814,6 +1821,7 @@ "resolved": "https://registry.npmjs.org/@jimp/plugin-resize/-/plugin-resize-0.22.12.tgz", "integrity": "sha512-3NyTPlPbTnGKDIbaBgQ3HbE6wXbAlFfxHVERmrbqAi8R3r6fQPxpCauA8UVDnieg5eo04D0T8nnnNIX//i/sXg==", "license": "MIT", + "peer": true, "dependencies": { "@jimp/utils": "^0.22.12" }, @@ -1826,6 +1834,7 @@ "resolved": "https://registry.npmjs.org/@jimp/plugin-rotate/-/plugin-rotate-0.22.12.tgz", "integrity": "sha512-9YNEt7BPAFfTls2FGfKBVgwwLUuKqy+E8bDGGEsOqHtbuhbshVGxN2WMZaD4gh5IDWvR+emmmPPWGgaYNYt1gA==", "license": "MIT", + "peer": true, "dependencies": { "@jimp/utils": "^0.22.12" }, @@ -1841,6 +1850,7 @@ "resolved": "https://registry.npmjs.org/@jimp/plugin-scale/-/plugin-scale-0.22.12.tgz", "integrity": "sha512-dghs92qM6MhHj0HrV2qAwKPMklQtjNpoYgAB94ysYpsXslhRTiPisueSIELRwZGEr0J0VUxpUY7HgJwlSIgGZw==", "license": "MIT", + "peer": true, "dependencies": { "@jimp/utils": "^0.22.12" }, @@ -2071,6 +2081,7 @@ "resolved": "https://registry.npmjs.org/@mui/material/-/material-5.18.0.tgz", "integrity": "sha512-bbH/HaJZpFtXGvWg3TsBWG4eyt3gah3E7nCNU8GLyRjVoWcA91Vm/T+sjHfUcwgJSw9iLtucfHBoq+qW/T30aA==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.23.9", "@mui/core-downloads-tracker": "^5.18.0", @@ -3478,6 +3489,7 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.19.tgz", "integrity": "sha512-pb1Uqj5WJP7wrcbLU7Ru4QtA0+3kAXrkutGiD26wUKzSMgNNaPARTUDQmElUXp64kh3cWdou3Q0C7qwwxqSFmg==", "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~6.21.0" } @@ -3526,6 +3538,7 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.25.tgz", "integrity": "sha512-oSVZmGtDPmRZtVDqvdKUi/qgCsWp5IDY29wp8na8Bj4B3cc99hfNzvNhlMkVVxctkAOGUA3Km7MMpBHAnWfcIA==", "license": "MIT", + "peer": true, "dependencies": { "@types/prop-types": "*", "csstype": "^3.0.2" @@ -3536,6 +3549,7 @@ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz", "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^18.0.0" } @@ -3639,6 +3653,7 @@ "integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==", "dev": true, "license": "BSD-2-Clause", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "6.21.0", "@typescript-eslint/types": "6.21.0", @@ -3918,6 +3933,7 @@ "integrity": "sha512-xa57bCPGuzEFqGjPs3vVLyqareG8DX0uMkr5U/v5vLv5/ZUrBrPL7gzxzTJedEyZxFMfsozwTIbbYfEQVo3kgg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@vitest/utils": "1.6.1", "fast-glob": "^3.3.2", @@ -3990,6 +4006,7 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -4581,6 +4598,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.9", "caniuse-lite": "^1.0.30001746", @@ -5231,6 +5249,7 @@ "integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", @@ -5391,7 +5410,8 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/csvjson": { "version": "5.1.0", @@ -6180,6 +6200,7 @@ "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -6236,6 +6257,7 @@ "integrity": "sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==", "dev": true, "license": "MIT", + "peer": true, "bin": { "eslint-config-prettier": "bin/cli.js" }, @@ -7508,6 +7530,7 @@ "integrity": "sha512-JzUXOh0wdNGY54oKng5hliuBkq/+aT1V3YpTM+lrN/GoLQTANZsMaIvmHiHe612rauHvPJnDZkZ+5GZR++1Abg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "css.escape": "^1.5.1", "entities": "^4.5.0", @@ -7731,6 +7754,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.27.6" }, @@ -8766,7 +8790,8 @@ "url": "https://github.com/sponsors/lavrton" } ], - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/laravelphp": { "version": "2.0.4", @@ -9517,6 +9542,7 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.53.0.tgz", "integrity": "sha512-0WNThgC6CMWNXXBxTbaYYcunj08iB5rnx4/G56UOPeL9UVIUGGHA1GR0EWIh9Ebabj7NpCRawQ5b0hfN1jQmYQ==", "license": "MIT", + "peer": true, "dependencies": { "@types/trusted-types": "^1.0.6" } @@ -9900,6 +9926,7 @@ "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.21.0.tgz", "integrity": "sha512-adzOe+7uI7lKz6pQNbAsLMQd2Fq5Jhmoxd8LZjJr8m3KvbFyiYyRxRiC57/XXD+jb18voppjeGAjoZmskXG+7A==", "license": "MIT", + "peer": true, "dependencies": { "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", @@ -10431,6 +10458,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -10589,6 +10617,7 @@ "integrity": "sha512-22UbSzg8luF4UuZtzgiUOfcGM8s4tjBv6dJRT7j275NXsy2jb4aJa4NNveul5x4eqlF1wuhuR2RElK71RvmVaw==", "dev": true, "license": "MIT", + "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -11037,6 +11066,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -11049,6 +11079,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -11180,6 +11211,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@types/react-reconciler": "^0.28.2", "its-fine": "^1.1.1", @@ -12573,6 +12605,7 @@ "resolved": "https://registry.npmjs.org/styled-components/-/styled-components-6.1.19.tgz", "integrity": "sha512-1v/e3Dl1BknC37cXMhwGomhO8AkYmN41CqyX9xhUDxry1ns3BFQy2lLDRQXJRdVVWB9OHemv/53xaStimvWyuA==", "license": "MIT", + "peer": true, "dependencies": { "@emotion/is-prop-valid": "1.2.2", "@emotion/unitless": "0.8.1", @@ -12799,6 +12832,7 @@ "integrity": "sha512-6A2rnmW5xZMdw11LYjhcI5846rt9pbLSabY5XPxo+XWdxwZaFEn47Go4NzFiHu9sNNmr/kXivP1vStfvMaK1GQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", @@ -13218,6 +13252,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -13365,6 +13400,7 @@ "integrity": "sha512-j3lYzGC3P+B5Yfy/pfKNgVEg4+UtcIJcVRt2cDjIOmhLourAqPqf8P7acgxeiSgUB7E3p2P8/3gNIgDLpwzs4g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", @@ -13483,6 +13519,7 @@ "integrity": "sha512-Ljb1cnSJSivGN0LqXd/zmDbWEM0RNNg2t1QW/XUhYl/qPqyu7CsqeWtqQXHVaJsecLPuDoak2oJcZN2QoRIOag==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@vitest/expect": "1.6.1", "@vitest/runner": "1.6.1", diff --git a/src/pages/tools/image/generic/qr-code/index.tsx b/src/pages/tools/image/generic/qr-code/index.tsx index 26f83058..3f1765ae 100644 --- a/src/pages/tools/image/generic/qr-code/index.tsx +++ b/src/pages/tools/image/generic/qr-code/index.tsx @@ -18,6 +18,7 @@ const initialValues: InitialValuesType = { size: '200', bgColor: '#FFFFFF', fgColor: '#000000', + correctionLevel: 'M', // URL url: 'https://example.com', @@ -117,6 +118,9 @@ const validationSchema = Yup.object().shape({ .required('Size is required'), bgColor: Yup.string().required('Background color is required'), fgColor: Yup.string().required('Foreground color is required'), + correctionLevel: Yup.mixed<'L' | 'M' | 'Q' | 'H'>() + .oneOf(['L', 'M', 'Q', 'H']) + .required('Correction level is required'), // URL url: Yup.string().when('qrCodeType', { @@ -211,6 +215,25 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { max: 1000 }} /> + + updateField( + 'correctionLevel', + e.target.value as 'L' | 'M' | 'Q' | 'H' + ) + } + helperText="Higher levels survive more damage but encode less data" + > + L (~7%) + M (~15%) + Q (~25%) + H (~30%) + { const res = await fetch(url); diff --git a/src/pages/tools/image/generic/qr-code/types.ts b/src/pages/tools/image/generic/qr-code/types.ts index b9959247..4aa78280 100644 --- a/src/pages/tools/image/generic/qr-code/types.ts +++ b/src/pages/tools/image/generic/qr-code/types.ts @@ -7,6 +7,8 @@ export type QRCodeType = | 'WiFi' | 'vCard'; +export type QRErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H'; + export type WifiEncryptionType = 'WPA' | 'WEP' | 'None'; export interface InitialValuesType { @@ -16,6 +18,7 @@ export interface InitialValuesType { size: string; bgColor: string; fgColor: string; + correctionLevel: QRErrorCorrectionLevel; // URL url: string; From 59c9ad7298e2ec8964e8b23f29d911c1085be0c1 Mon Sep 17 00:00:00 2001 From: Tyler Date: Mon, 16 Feb 2026 17:03:27 -0500 Subject: [PATCH 002/114] feat(image): add batch watermark tool with multi-file support and tests --- public/locales/en/image.json | 5 + .../image/generic/batch-watermark/index.tsx | 212 ++++++++++++++++++ .../image/generic/batch-watermark/meta.ts | 27 +++ .../generic/batch-watermark/service.test.ts | 195 ++++++++++++++++ .../image/generic/batch-watermark/service.ts | 161 +++++++++++++ .../image/generic/batch-watermark/types.ts | 11 + src/pages/tools/image/generic/index.ts | 5 +- 7 files changed, 615 insertions(+), 1 deletion(-) create mode 100644 src/pages/tools/image/generic/batch-watermark/index.tsx create mode 100644 src/pages/tools/image/generic/batch-watermark/meta.ts create mode 100644 src/pages/tools/image/generic/batch-watermark/service.test.ts create mode 100644 src/pages/tools/image/generic/batch-watermark/service.ts create mode 100644 src/pages/tools/image/generic/batch-watermark/types.ts diff --git a/public/locales/en/image.json b/public/locales/en/image.json index 9a03c734..3693ba24 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -101,5 +101,10 @@ "description": "Rotate an image by a specified angle.", "shortDescription": "Rotate an image easily.", "title": "Rotate Image" + }, + "batchWatermark": { + "title": "Batch Watermark Images", + "description": "Add a text watermark based on each file name. Process multiple images at once.", + "shortDescription": "Watermark images from filename" } } diff --git a/src/pages/tools/image/generic/batch-watermark/index.tsx b/src/pages/tools/image/generic/batch-watermark/index.tsx new file mode 100644 index 00000000..a7f0824c --- /dev/null +++ b/src/pages/tools/image/generic/batch-watermark/index.tsx @@ -0,0 +1,212 @@ +import { Box, Button, Typography } from '@mui/material'; +import React, { useRef, useState } from 'react'; +import * as Yup from 'yup'; +import ToolFileResult from '@components/result/ToolFileResult'; +import { GetGroupsType } from '@components/options/ToolOptions'; +import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; +import ToolContent from '@components/ToolContent'; +import { ToolComponentProps } from '@tools/defineTool'; +import SimpleRadio from '@components/options/SimpleRadio'; +import { processImage } from './service'; +import { InitialValuesType } from './types'; + +const initialValues: InitialValuesType = { + watermarkOpacity: 0.35, + fontSize: 32, + position: 'bottom-right', + color: '#ffffff' +}; + +const validationSchema = Yup.object({ + watermarkOpacity: Yup.number() + .min(0, 'Opacity must be between 0 and 1') + .max(1, 'Opacity must be between 0 and 1') + .required('Opacity is required'), + fontSize: Yup.number() + .min(8, 'Font size must be at least 8px') + .max(512, 'Font size is too large') + .required('Font size is required'), + color: Yup.string().required('Color is required') +}); + +export default function BatchWatermark({ title }: ToolComponentProps) { + const [input, setInput] = useState([]); + const [results, setResults] = useState([]); + const fileInputRef = useRef(null); + + const compute = async (optionsValues: InitialValuesType, files: File[]) => { + if (!files || files.length === 0) return; + + const out: File[] = []; + for (const f of files) { + const processed = await processImage(f, optionsValues); + if (processed) out.push(processed); + } + setResults(out); + }; + + const getGroups: GetGroupsType = ({ + values, + updateField + }) => [ + { + title: 'Watermark appearance', + component: ( + + updateField('watermarkOpacity', Number(val))} + description={'Opacity (0 to 1). Example: 0.35'} + inputProps={{ + 'data-testid': 'opacity-input', + type: 'number', + min: 0, + max: 1, + step: 0.05 + }} + /> + updateField('fontSize', Number(val))} + description={'Font size in pixels'} + inputProps={{ + 'data-testid': 'font-size-input', + type: 'number', + min: 8, + max: 512, + step: 1 + }} + /> + updateField('color', val)} + description={'Text color (hex). Example: #ffffff'} + inputProps={{ + 'data-testid': 'color-input' + }} + /> + + ) + }, + { + title: 'Position', + component: ( + + updateField('position', 'bottom-right')} + checked={values.position === 'bottom-right'} + description={'Bottom-right corner'} + title={'Bottom-right'} + /> + updateField('position', 'bottom-left')} + checked={values.position === 'bottom-left'} + description={'Bottom-left corner'} + title={'Bottom-left'} + /> + updateField('position', 'top-right')} + checked={values.position === 'top-right'} + description={'Top-right corner'} + title={'Top-right'} + /> + updateField('position', 'top-left')} + checked={values.position === 'top-left'} + description={'Top-left corner'} + title={'Top-left'} + /> + updateField('position', 'center')} + checked={values.position === 'center'} + description={'Centered on the image'} + title={'Center'} + /> + + ) + } + ]; + + return ( + + { + const files = Array.from(e.target.files ?? []); + setInput(files); + }} + /> + + + + + + {input.length === 0 && 'No files selected'} + {input.length > 0 && `${input.length} file(s) selected`} + + + {input.length > 0 && ( + + )} + + + {input.length > 0 && ( + +
    + {input.map((f) => ( +
  • + {f.name} +
  • + ))} +
+
+ )} + + } + resultComponent={ + + {results.map((file) => ( + + + + ))} + + } + toolInfo={{ + title: 'Batch watermark images (filename)', + description: + 'Uploads multiple images and adds a text watermark based on each file’s name.' + }} + /> + ); +} diff --git a/src/pages/tools/image/generic/batch-watermark/meta.ts b/src/pages/tools/image/generic/batch-watermark/meta.ts new file mode 100644 index 00000000..b6c3ee25 --- /dev/null +++ b/src/pages/tools/image/generic/batch-watermark/meta.ts @@ -0,0 +1,27 @@ +import { defineTool } from '@tools/defineTool'; +import { lazy } from 'react'; + +export const tool = defineTool('image-generic', { + i18n: { + name: 'image:batchWatermark.title', + description: 'image:batchWatermark.description', + shortDescription: 'image:batchWatermark.shortDescription', + userTypes: ['generalUsers'] + }, + + path: 'batch-watermark', + icon: 'mdi:watermark', + + keywords: [ + 'watermark', + 'batch', + 'image', + 'text', + 'filename', + 'overlay', + 'png', + 'jpg' + ], + + component: lazy(() => import('./index')) +}); diff --git a/src/pages/tools/image/generic/batch-watermark/service.test.ts b/src/pages/tools/image/generic/batch-watermark/service.test.ts new file mode 100644 index 00000000..d4016753 --- /dev/null +++ b/src/pages/tools/image/generic/batch-watermark/service.test.ts @@ -0,0 +1,195 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { + filenameToWatermarkText, + outputSpecForFile, + processImage +} from './service'; + +describe('batch-watermark service', () => { + afterEach(() => { + vi.restoreAllMocks(); + // cleanup stubGlobal + // @ts-expect-error optional cleanup + delete globalThis.createImageBitmap; + }); + + it('filenameToWatermarkText strips extension and prettifies', () => { + expect(filenameToWatermarkText('goose.png')).toBe('goose'); + + expect(filenameToWatermarkText('duck_photo-01.jpeg')).toBe('duck photo 01'); + + expect(filenameToWatermarkText(' __weird--name__.webp ')).toBe( + 'weird name' + ); + }); + + it('outputSpecForFile preserves supported types and defaults unknown to PNG', () => { + const png = new File([new Uint8Array([1])], 'goose.png', { + type: 'image/png' + }); + + const jpg = new File([new Uint8Array([1])], 'duck.jpeg', { + type: 'image/jpeg' + }); + + const webp = new File([new Uint8Array([1])], 'bird.webp', { + type: 'image/webp' + }); + + const unknown = new File([new Uint8Array([1])], 'mystery.bin', { + type: 'application/octet-stream' + }); + + expect(outputSpecForFile(png)).toMatchObject({ + outputType: 'image/png', + ext: 'png' + }); + + expect(outputSpecForFile(jpg)).toMatchObject({ + outputType: 'image/jpeg', + ext: 'jpeg', + quality: 0.92 + }); + + expect(outputSpecForFile(webp)).toMatchObject({ + outputType: 'image/webp', + ext: 'webp' + }); + + expect(outputSpecForFile(unknown)).toMatchObject({ + outputType: 'image/png', + ext: 'png' + }); + }); + + it('processImage returns a watermarked file and uses filename as text', async () => { + vi.stubGlobal( + 'createImageBitmap', + vi.fn(async () => ({ + width: 200, + height: 100 + })) + ); + + const fillText = vi.fn(); + const drawImage = vi.fn(); + const save = vi.fn(); + const restore = vi.fn(); + + const ctxMock: any = { + drawImage, + save, + restore, + fillText, + globalAlpha: 1, + fillStyle: '', + font: '', + textAlign: 'left', + textBaseline: 'alphabetic', + shadowColor: '', + shadowBlur: 0, + shadowOffsetX: 0, + shadowOffsetY: 0 + }; + + const canvasMock: any = { + width: 0, + height: 0, + getContext: vi.fn(() => ctxMock), + toBlob: vi.fn((cb: (b: Blob | null) => void) => { + cb( + new Blob([new Uint8Array([2, 3, 4])], { + type: 'image/png' + }) + ); + }) + }; + + const originalCreateElement = document.createElement.bind(document); + + vi.spyOn(document, 'createElement').mockImplementation((tagName: any) => { + if (tagName === 'canvas') return canvasMock; + return originalCreateElement(tagName); + }); + + const file = new File([new Uint8Array([9])], 'goose.png', { + type: 'image/png' + }); + + const out = await processImage(file, { + watermarkOpacity: 0.35, + fontSize: 32, + position: 'bottom-right', + color: '#ffffff' + }); + + expect(out).not.toBeNull(); + + expect(out!.name).toBe('goose_watermarked.png'); + + expect(out!.type).toBe('image/png'); + + expect(drawImage).toHaveBeenCalled(); + + expect(fillText).toHaveBeenCalled(); + + const [textArg] = fillText.mock.calls[0]; + + expect(textArg).toBe('goose'); + }); + + it('processImage preserves jpeg output naming and type', async () => { + vi.stubGlobal( + 'createImageBitmap', + vi.fn(async () => ({ + width: 100, + height: 100 + })) + ); + + const ctxMock: any = { + drawImage: vi.fn(), + save: vi.fn(), + restore: vi.fn(), + fillText: vi.fn() + }; + + const canvasMock: any = { + width: 0, + height: 0, + getContext: vi.fn(() => ctxMock), + toBlob: vi.fn((cb: (b: Blob | null) => void) => { + cb( + new Blob([new Uint8Array([1])], { + type: 'image/jpeg' + }) + ); + }) + }; + + const originalCreateElement = document.createElement.bind(document); + + vi.spyOn(document, 'createElement').mockImplementation((tagName: any) => { + if (tagName === 'canvas') return canvasMock; + return originalCreateElement(tagName); + }); + + const file = new File([new Uint8Array([9])], 'duck.jpeg', { + type: 'image/jpeg' + }); + + const out = await processImage(file, { + watermarkOpacity: 0.4, + fontSize: 20, + position: 'top-left', + color: '#ffffff' + }); + + expect(out).not.toBeNull(); + + expect(out!.name).toBe('duck_watermarked.jpeg'); + + expect(out!.type).toBe('image/jpeg'); + }); +}); diff --git a/src/pages/tools/image/generic/batch-watermark/service.ts b/src/pages/tools/image/generic/batch-watermark/service.ts new file mode 100644 index 00000000..14d7e29f --- /dev/null +++ b/src/pages/tools/image/generic/batch-watermark/service.ts @@ -0,0 +1,161 @@ +import { InitialValuesType } from './types'; + +export function filenameToWatermarkText(filename: string): string { + const base = filename.replace(/\.[^.]+$/, ''); + return base.replace(/[_-]+/g, ' ').trim(); +} + +export function outputSpecForFile(file: File): { + outputType: 'image/png' | 'image/jpeg' | 'image/webp'; + ext: 'png' | 'jpeg' | 'webp'; + quality?: number; +} { + const inputType = file.type; + + const supported = + inputType === 'image/png' || + inputType === 'image/jpeg' || + inputType === 'image/webp'; + + const outputType = supported + ? (inputType as 'image/png' | 'image/jpeg' | 'image/webp') + : 'image/png'; + + const ext = + outputType === 'image/jpeg' + ? 'jpeg' + : outputType === 'image/webp' + ? 'webp' + : 'png'; + + // Only used for JPEG + const quality = outputType === 'image/jpeg' ? 0.92 : undefined; + + return { outputType, ext, quality }; +} + +function computePosition( + position: InitialValuesType['position'], + canvasWidth: number, + canvasHeight: number, + padding: number +) { + switch (position) { + case 'top-left': + return { + x: padding, + y: padding, + align: 'left' as const, + baseline: 'top' as const + }; + + case 'top-right': + return { + x: canvasWidth - padding, + y: padding, + align: 'right' as const, + baseline: 'top' as const + }; + + case 'bottom-left': + return { + x: padding, + y: canvasHeight - padding, + align: 'left' as const, + baseline: 'bottom' as const + }; + + case 'center': + return { + x: canvasWidth / 2, + y: canvasHeight / 2, + align: 'center' as const, + baseline: 'middle' as const + }; + + case 'bottom-right': + default: + return { + x: canvasWidth - padding, + y: canvasHeight - padding, + align: 'right' as const, + baseline: 'bottom' as const + }; + } +} + +export const processImage = async ( + file: File, + options: InitialValuesType +): Promise => { + // Skip SVG for now (different pipeline) + if (file.type === 'image/svg+xml') { + console.warn('SVG watermark not supported yet.'); + return null; + } + + // Skip GIF for now (frame-by-frame watermarking) + if (file.type === 'image/gif') { + console.warn('GIF watermark not supported yet.'); + return null; + } + + const { watermarkOpacity, fontSize, position, color } = options; + + // Decode image + const bitmap = await createImageBitmap(file); + + // Canvas setup + const canvas = document.createElement('canvas'); + canvas.width = bitmap.width; + canvas.height = bitmap.height; + + const ctx = canvas.getContext('2d'); + if (!ctx) return null; + + // Draw base image + ctx.drawImage(bitmap, 0, 0); + + // Build watermark text from filename + const text = filenameToWatermarkText(file.name); + if (!text) return null; + + // Watermark styling + const padding = Math.max( + 12, + Math.round(Math.min(canvas.width, canvas.height) * 0.02) + ); + + ctx.save(); + ctx.globalAlpha = watermarkOpacity; + ctx.fillStyle = color; + ctx.font = `bold ${fontSize}px sans-serif`; + + // Shadow for readability + ctx.shadowColor = 'rgba(0,0,0,0.65)'; + ctx.shadowBlur = 6; + ctx.shadowOffsetX = 2; + ctx.shadowOffsetY = 2; + + const pos = computePosition(position, canvas.width, canvas.height, padding); + ctx.textAlign = pos.align; + ctx.textBaseline = pos.baseline; + ctx.fillText(text, pos.x, pos.y); + ctx.restore(); + + // Output per-file format (PNG/JPEG/WebP) + const { outputType, ext, quality } = outputSpecForFile(file); + const base = file.name.replace(/\.[^.]+$/, ''); + const outName = `${base}_watermarked.${ext}`; + + const blob = await new Promise((resolve) => { + canvas.toBlob( + (b) => resolve(b), + outputType, + outputType === 'image/jpeg' ? quality : undefined + ); + }); + + if (!blob) return null; + return new File([blob], outName, { type: outputType }); +}; diff --git a/src/pages/tools/image/generic/batch-watermark/types.ts b/src/pages/tools/image/generic/batch-watermark/types.ts new file mode 100644 index 00000000..0b7a1aec --- /dev/null +++ b/src/pages/tools/image/generic/batch-watermark/types.ts @@ -0,0 +1,11 @@ +export type InitialValuesType = { + watermarkOpacity: number; + fontSize: number; + position: + | 'bottom-right' + | 'bottom-left' + | 'top-right' + | 'top-left' + | 'center'; + color: string; +}; diff --git a/src/pages/tools/image/generic/index.ts b/src/pages/tools/image/generic/index.ts index d87de31e..73c58b59 100644 --- a/src/pages/tools/image/generic/index.ts +++ b/src/pages/tools/image/generic/index.ts @@ -10,6 +10,8 @@ import { tool as qrCodeGenerator } from './qr-code/meta'; import { tool as rotateImage } from './rotate/meta'; import { tool as convertToJpg } from './convert-to-jpg/meta'; import { tool as imageEditor } from './editor/meta'; +import { tool as batchWatermark } from './batch-watermark/meta'; + export const imageGenericTools = [ imageEditor, resizeImage, @@ -22,5 +24,6 @@ export const imageGenericTools = [ imageToText, qrCodeGenerator, rotateImage, - convertToJpg + convertToJpg, + batchWatermark ]; From 5371720dbb7dd562459b7f7adb8ee1b8155068eb Mon Sep 17 00:00:00 2001 From: huly64 <1079825614@qq.com> Date: Thu, 21 May 2026 17:40:45 +0800 Subject: [PATCH 003/114] Show installed version in navbar Constraint: users need to identify the deployed app version from the web UI Rejected: hardcode version in React component | package.json remains the source of truth Confidence: high Scope-risk: narrow Directive: Keep build-time version display sourced from package metadata Tested: git diff --check Tested: npm run typecheck Tested: npm run build Not-tested: visual browser smoke test Co-authored-by: OmX --- src/@types/env.d.ts | 1 + src/components/Navbar/index.tsx | 28 +++++++++++++++++++++------- vite.config.ts | 4 +++- 3 files changed, 25 insertions(+), 8 deletions(-) create mode 100644 src/@types/env.d.ts diff --git a/src/@types/env.d.ts b/src/@types/env.d.ts new file mode 100644 index 00000000..41fad5b5 --- /dev/null +++ b/src/@types/env.d.ts @@ -0,0 +1 @@ +declare const __APP_VERSION__: string; diff --git a/src/components/Navbar/index.tsx b/src/components/Navbar/index.tsx index dbacb3aa..1a76b44c 100644 --- a/src/components/Navbar/index.tsx +++ b/src/components/Navbar/index.tsx @@ -16,7 +16,8 @@ import { Stack, Select, MenuItem, - FormControl + FormControl, + Typography } from '@mui/material'; import useMediaQuery from '@mui/material/useMediaQuery'; import { useTheme } from '@mui/material/styles'; @@ -178,12 +179,25 @@ const Navbar: React.FC = ({ mx: { md: '50px', lg: '150px' } }} > - - - + + + + + + v{__APP_VERSION__} + + {isMobile ? ( <> Date: Thu, 4 Jun 2026 09:00:10 +0700 Subject: [PATCH 004/114] feat(json-to-csv): accept NDJSON / multiple objects without array wrapper The JSON to CSV tool only accepted a single JSON value, so pasting several objects (one per line) without wrapping them in an array failed with "Invalid JSON input." (#353). Add a reusable `parseJsonOrNdjson()` helper in `utils/json` that parses standard JSON first and falls back to NDJSON (newline-delimited JSON / JSON Lines): each non-empty line is parsed and the records are returned as an array. A single non-JSON line still surfaces as a normal JSON error, so genuinely invalid input is not misread as NDJSON. The helper lives in `utils/json` so other JSON tools can adopt the same behavior. Wire it into `convertJsonToCsv` and cover it with tests (multi-line objects, blank-line skipping, sparse keys, and the invalid-line case). Closes #353 Co-Authored-By: Claude Opus 4.8 --- .../tools/json/json-to-csv/service.test.ts | 34 ++++++++++++ src/pages/tools/json/json-to-csv/service.ts | 4 +- src/utils/json.ts | 53 +++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/src/pages/tools/json/json-to-csv/service.test.ts b/src/pages/tools/json/json-to-csv/service.test.ts index f6a2011c..8370a87d 100644 --- a/src/pages/tools/json/json-to-csv/service.test.ts +++ b/src/pages/tools/json/json-to-csv/service.test.ts @@ -169,4 +169,38 @@ describe('convertJsonToCsv', () => { ).toThrow('No data found in the provided JSON.'); }); }); + + describe('NDJSON (newline-delimited JSON)', () => { + it('converts objects on separate lines without an array wrapper', () => { + const input = [ + '{"key1": "AAA", "key2": "XXX"}', + '{"key1": "BBB", "key2": "YYY"}', + '{"key1": "CCC", "key2": "ZZZ"}' + ].join('\n'); + + expect(convertJsonToCsv(input, defaultOptions)).toBe( + `key1,key2\r\nAAA,XXX\r\nBBB,YYY\r\nCCC,ZZZ` + ); + }); + + it('ignores blank lines between NDJSON records', () => { + const input = '{"a": 1}\n\n{"a": 2}\n'; + + expect(convertJsonToCsv(input, defaultOptions)).toBe(`a\r\n1\r\n2`); + }); + + it('handles sparse keys across NDJSON records', () => { + const input = '{"a": 1}\n{"b": 2}'; + + expect(convertJsonToCsv(input, defaultOptions)).toBe(`a,b\r\n1,\r\n,2`); + }); + + it('still throws when one NDJSON line is not valid JSON', () => { + const input = '{"a": 1}\nnot json'; + + expect(() => convertJsonToCsv(input, defaultOptions)).toThrow( + 'Invalid JSON input.' + ); + }); + }); }); diff --git a/src/pages/tools/json/json-to-csv/service.ts b/src/pages/tools/json/json-to-csv/service.ts index 33ddeb4e..529773e0 100644 --- a/src/pages/tools/json/json-to-csv/service.ts +++ b/src/pages/tools/json/json-to-csv/service.ts @@ -1,5 +1,5 @@ import { InitialValuesType } from './types'; -import { getJsonHeaders } from 'utils/json'; +import { getJsonHeaders, parseJsonOrNdjson } from 'utils/json'; /** * Recursively flattens any JSON value into a flat object. @@ -87,7 +87,7 @@ export function convertJsonToCsv( let parsed: unknown; try { - parsed = JSON.parse(input); + parsed = parseJsonOrNdjson(input); } catch { throw new Error('Invalid JSON input.'); } diff --git a/src/utils/json.ts b/src/utils/json.ts index c243ab37..ad21d277 100644 --- a/src/utils/json.ts +++ b/src/utils/json.ts @@ -1,3 +1,56 @@ +/** + * Parses a JSON string, falling back to NDJSON (newline-delimited JSON, a.k.a. + * JSON Lines) when the input is not a single valid JSON value. + * + * This lets users paste multiple JSON objects without wrapping them in an + * array, e.g.: + * + * {"key1": "AAA"} + * {"key1": "BBB"} + * + * Standard JSON (an object or array) is parsed first and returned unchanged. + * Otherwise each non-empty line must be a valid JSON value, and the values are + * returned as an array. A single line that is not valid JSON is reported as a + * plain JSON error rather than being misread as NDJSON. + * + * @param input - Raw text to parse + * @returns The parsed JSON value, or an array of values when NDJSON is detected + * @throws SyntaxError when the input is neither valid JSON nor valid NDJSON + * + * @example + * parseJsonOrNdjson('{"a":1}\n{"a":2}') // → [{ a: 1 }, { a: 2 }] + */ +export function parseJsonOrNdjson(input: string): unknown { + const trimmed = input.trim(); + + try { + return JSON.parse(trimmed); + } catch (jsonError) { + const lines = trimmed + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); + + // A single line that already failed JSON.parse is not NDJSON — surface the + // original error instead of masking it. + if (lines.length < 2) { + throw jsonError; + } + + const values: unknown[] = []; + for (const line of lines) { + try { + values.push(JSON.parse(line)); + } catch { + // Not valid NDJSON either — report the original JSON parse failure. + throw jsonError; + } + } + + return values; + } +} + /** * Collects all unique keys from an array of row objects, preserving first-encountered order. * Handles sparse rows where different rows may have different keys. From 3d0a4e6588e6500c82a4b813668bc15f242c7265 Mon Sep 17 00:00:00 2001 From: RajivRatan27 Date: Sat, 6 Jun 2026 22:02:57 +0530 Subject: [PATCH 005/114] feat: add URL editor tool --- public/locales/en/string.json | 26 ++ src/pages/tools/string/index.ts | 2 + .../string/url-editor/UrlDetailsEditor.tsx | 129 +++++++++ src/pages/tools/string/url-editor/index.tsx | 246 ++++++++++++++++++ src/pages/tools/string/url-editor/meta.ts | 25 ++ src/pages/tools/string/url-editor/service.ts | 56 ++++ src/pages/tools/string/url-editor/types.ts | 12 + .../url-editor/url-editor.service.test.ts | 98 +++++++ 8 files changed, 594 insertions(+) create mode 100644 src/pages/tools/string/url-editor/UrlDetailsEditor.tsx create mode 100644 src/pages/tools/string/url-editor/index.tsx create mode 100644 src/pages/tools/string/url-editor/meta.ts create mode 100644 src/pages/tools/string/url-editor/service.ts create mode 100644 src/pages/tools/string/url-editor/types.ts create mode 100644 src/pages/tools/string/url-editor/url-editor.service.test.ts diff --git a/public/locales/en/string.json b/public/locales/en/string.json index 86e5bf20..7bcc4804 100644 --- a/public/locales/en/string.json +++ b/public/locales/en/string.json @@ -312,6 +312,32 @@ "shortDescription": "Convert text to uppercase", "title": "Convert to Uppercase" }, + "urlEditor": { + "addParameter": "Add Parameter", + "delete": "Delete", + "generatedUrl": "Generated URL", + "hash": "Fragment", + "hashPlaceholder": "section", + "host": "Host", + "hostPlaceholder": "example.com", + "inputTitle": "Enter URL", + "invalidUrl": "Invalid URL", + "key": "Key", + "noParameters": "No query parameters", + "parseButton": "Parse URL", + "path": "Path", + "pathPlaceholder": "search", + "protocol": "Protocol", + "queryParameters": "Query Parameters", + "toolInfo": { + "description": "Paste a URL to inspect and edit its query parameters, then copy the updated link.", + "longDescription": "This tool parses a URL into its components and lets you edit the protocol, host, path, fragment, and query parameters visually. Add, remove, or change any part and the generated URL updates in real time. Everything runs in your browser with no server requests.", + "shortDescription": "Inspect and edit URL query parameters.", + "title": "URL Editor" + }, + "urlDetails": "URL Details", + "value": "Value" + }, "urlDecode": { "inputTitle": "Input String(URL-escaped)", "resultTitle": "Output string", diff --git a/src/pages/tools/string/index.ts b/src/pages/tools/string/index.ts index 9b1e62d8..ad00327e 100644 --- a/src/pages/tools/string/index.ts +++ b/src/pages/tools/string/index.ts @@ -22,6 +22,7 @@ import { tool as stringCensor } from './censor/meta'; import { tool as stringPasswordGenerator } from './password-generator/meta'; import { tool as stringEncodeUrl } from './url-encode/meta'; import { tool as stringDecodeUrl } from './url-decode/meta'; +import { tool as stringUrlEditor } from './url-editor/meta'; import { tool as stringCompare } from './text-compare/meta'; import { tool as stringUnicode } from './unicode/meta'; @@ -48,6 +49,7 @@ export const stringTools = [ stringPasswordGenerator, stringEncodeUrl, stringDecodeUrl, + stringUrlEditor, stringUnicode, stringHiddenCharacterDetector, stringCompare, diff --git a/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx b/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx new file mode 100644 index 00000000..caec3b7c --- /dev/null +++ b/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx @@ -0,0 +1,129 @@ +import { + Box, + FormControl, + Grid, + InputAdornment, + InputLabel, + MenuItem, + Select, + TextField +} from '@mui/material'; +import { ParsedUrl } from './types'; + +const PROTOCOLS = ['https:', 'http:'] as const; + +export type UrlDetailField = keyof Omit; + +type UrlDetailsEditorProps = { + value: ParsedUrl; + onChange: (field: UrlDetailField, value: string) => void; + labels: { + protocol: string; + host: string; + path: string; + hash: string; + hostPlaceholder: string; + pathPlaceholder: string; + hashPlaceholder: string; + }; +}; + +export default function UrlDetailsEditor({ + value, + onChange, + labels +}: UrlDetailsEditorProps) { + const hashValue = value.hash.replace(/^#/, ''); + + return ( + + + + + {labels.protocol} + + + + + + onChange('host', event.target.value)} + InputProps={{ + startAdornment: ( + :// + ) + }} + /> + + + + { + const next = event.target.value.replace(/^\//, ''); + onChange('pathname', next ? `/${next}` : '/'); + }} + InputProps={{ + startAdornment: ( + / + ) + }} + inputProps={{ sx: { pl: 0.5 } }} + /> + + + + { + const next = event.target.value.replace(/^#/, ''); + onChange('hash', next ? `#${next}` : ''); + }} + InputProps={{ + startAdornment: ( + # + ) + }} + inputProps={{ sx: { pl: 0.5 } }} + /> + + + + ); +} diff --git a/src/pages/tools/string/url-editor/index.tsx b/src/pages/tools/string/url-editor/index.tsx new file mode 100644 index 00000000..c98cee90 --- /dev/null +++ b/src/pages/tools/string/url-editor/index.tsx @@ -0,0 +1,246 @@ +import { useCallback, useEffect, useState } from 'react'; +import { + Alert, + Box, + Button, + IconButton, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + TextField, + Typography +} from '@mui/material'; +import DeleteIcon from '@mui/icons-material/Delete'; +import AddIcon from '@mui/icons-material/Add'; +import ToolContent from '@components/ToolContent'; +import ToolTextInput from '@components/input/ToolTextInput'; +import ToolTextResult from '@components/result/ToolTextResult'; +import InputHeader from '@components/InputHeader'; +import { ToolComponentProps } from '@tools/defineTool'; +import { useTranslation } from 'react-i18next'; +import UrlDetailsEditor, { UrlDetailField } from './UrlDetailsEditor'; +import { generateUrl, parseUrl } from './service'; +import { ParsedUrl } from './types'; + +const initialValues = {}; + +export default function UrlEditor({ + title, + longDescription +}: ToolComponentProps) { + const { t } = useTranslation('string'); + const [inputUrl, setInputUrl] = useState(''); + const [parsedUrl, setParsedUrl] = useState(null); + const [generatedUrl, setGeneratedUrl] = useState(''); + const [parseError, setParseError] = useState(null); + const [generateError, setGenerateError] = useState(null); + + useEffect(() => { + if (!parsedUrl) { + setGeneratedUrl(''); + setGenerateError(null); + return; + } + + try { + setGeneratedUrl(generateUrl(parsedUrl)); + setGenerateError(null); + } catch { + setGeneratedUrl(''); + setGenerateError(t('urlEditor.invalidUrl')); + } + }, [parsedUrl, t]); + + const handleParse = useCallback(() => { + try { + setParsedUrl(parseUrl(inputUrl)); + setParseError(null); + } catch { + setParsedUrl(null); + setParseError(t('urlEditor.invalidUrl')); + } + }, [inputUrl, t]); + + const handleFieldChange = useCallback( + (field: UrlDetailField, value: string) => { + setParsedUrl((current) => + current ? { ...current, [field]: value } : current + ); + }, + [] + ); + + const handleAddParam = useCallback(() => { + setParsedUrl((current) => + current + ? { ...current, params: [...current.params, { key: '', value: '' }] } + : current + ); + }, []); + + const handleRemoveParam = useCallback((index: number) => { + setParsedUrl((current) => + current + ? { + ...current, + params: current.params.filter((_, i) => i !== index) + } + : current + ); + }, []); + + const handleParamChange = useCallback( + (index: number, field: 'key' | 'value', value: string) => { + setParsedUrl((current) => { + if (!current) return current; + + const params = current.params.map((param, i) => + i === index ? { ...param, [field]: value } : param + ); + + return { ...current, params }; + }); + }, + [] + ); + + return ( + {}} + input={inputUrl} + setInput={setInputUrl} + inputComponent={ + + + + + + + {parseError && ( + + {parseError} + + )} + + {parsedUrl && ( + + + + + + + {parsedUrl.params.length > 0 ? ( + + + + {t('urlEditor.key')} + {t('urlEditor.value')} + + {t('urlEditor.delete')} + + + + + {parsedUrl.params.map((param, index) => ( + + + + handleParamChange( + index, + 'key', + event.target.value + ) + } + size="small" + fullWidth + /> + + + + handleParamChange( + index, + 'value', + event.target.value + ) + } + size="small" + fullWidth + /> + + + handleRemoveParam(index)} + size="small" + > + + + + + ))} + +
+ ) : ( + + {t('urlEditor.noParameters')} + + )} + +
+ + {generateError && ( + + {generateError} + + )} +
+ )} +
+ } + resultComponent={ + + } + toolInfo={{ + title: t('urlEditor.toolInfo.title', { title }), + description: longDescription + }} + /> + ); +} diff --git a/src/pages/tools/string/url-editor/meta.ts b/src/pages/tools/string/url-editor/meta.ts new file mode 100644 index 00000000..88e7d55f --- /dev/null +++ b/src/pages/tools/string/url-editor/meta.ts @@ -0,0 +1,25 @@ +import { defineTool } from '@tools/defineTool'; +import { lazy } from 'react'; + +export const tool = defineTool('string', { + path: 'url-editor', + icon: 'mdi:link-edit', + + keywords: [ + 'url', + 'editor', + 'query', + 'parameters', + 'parse', + 'link', + 'href', + 'search params' + ], + component: lazy(() => import('./index')), + i18n: { + name: 'string:urlEditor.toolInfo.title', + description: 'string:urlEditor.toolInfo.description', + shortDescription: 'string:urlEditor.toolInfo.shortDescription', + longDescription: 'string:urlEditor.toolInfo.longDescription' + } +}); diff --git a/src/pages/tools/string/url-editor/service.ts b/src/pages/tools/string/url-editor/service.ts new file mode 100644 index 00000000..fe469fac --- /dev/null +++ b/src/pages/tools/string/url-editor/service.ts @@ -0,0 +1,56 @@ +import { ParsedUrl, QueryParam } from './types'; + +export function parseUrl(input: string): ParsedUrl { + const trimmed = input.trim(); + if (!trimmed) { + throw new Error('Invalid URL'); + } + + let url: URL; + try { + url = new URL(trimmed); + } catch { + throw new Error('Invalid URL'); + } + + const params: QueryParam[] = Array.from(url.searchParams.entries()).map( + ([key, value]) => ({ key, value }) + ); + + return { + protocol: url.protocol, + host: url.host, + pathname: url.pathname, + hash: url.hash, + params + }; +} + +export function generateUrl(parsed: ParsedUrl): string { + const protocol = parsed.protocol || 'https:'; + const host = parsed.host.trim(); + if (!host) { + throw new Error('Invalid URL'); + } + + let pathname = parsed.pathname || '/'; + if (!pathname.startsWith('/')) { + pathname = `/${pathname}`; + } + + const url = new URL(`${protocol}//${host}${pathname}`); + + let hash = parsed.hash.trim(); + if (hash && !hash.startsWith('#')) { + hash = `#${hash}`; + } + url.hash = hash; + + parsed.params.forEach(({ key, value }) => { + if (key) { + url.searchParams.append(key, value); + } + }); + + return url.toString(); +} diff --git a/src/pages/tools/string/url-editor/types.ts b/src/pages/tools/string/url-editor/types.ts new file mode 100644 index 00000000..8f2c9ca4 --- /dev/null +++ b/src/pages/tools/string/url-editor/types.ts @@ -0,0 +1,12 @@ +export interface QueryParam { + key: string; + value: string; +} + +export interface ParsedUrl { + protocol: string; + host: string; + pathname: string; + hash: string; + params: QueryParam[]; +} diff --git a/src/pages/tools/string/url-editor/url-editor.service.test.ts b/src/pages/tools/string/url-editor/url-editor.service.test.ts new file mode 100644 index 00000000..ae8fa937 --- /dev/null +++ b/src/pages/tools/string/url-editor/url-editor.service.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest'; +import { generateUrl, parseUrl } from './service'; + +describe('url-editor', () => { + it('parses a valid URL with query parameters', () => { + expect(parseUrl('https://example.com/search?q=iphone&page=2')).toEqual({ + protocol: 'https:', + host: 'example.com', + pathname: '/search', + hash: '', + params: [ + { key: 'q', value: 'iphone' }, + { key: 'page', value: '2' } + ] + }); + }); + + it('parses multiple query parameters', () => { + expect(parseUrl('https://example.com?a=1&b=2&c=3').params).toEqual([ + { key: 'a', value: '1' }, + { key: 'b', value: '2' }, + { key: 'c', value: '3' } + ]); + }); + + it('parses URLs without query parameters', () => { + expect(parseUrl('https://example.com')).toEqual({ + protocol: 'https:', + host: 'example.com', + pathname: '/', + hash: '', + params: [] + }); + }); + + it('parses URLs with a hash', () => { + expect(parseUrl('https://example.com/page#section1')).toEqual({ + protocol: 'https:', + host: 'example.com', + pathname: '/page', + hash: '#section1', + params: [] + }); + }); + + it('throws for invalid URLs', () => { + expect(() => parseUrl('abc123')).toThrow('Invalid URL'); + expect(() => parseUrl('')).toThrow('Invalid URL'); + }); + + it('generates an updated URL from parsed components', () => { + const parsed = parseUrl('https://example.com/search?q=iphone&page=2'); + parsed.params = [ + { key: 'q', value: 'samsung' }, + { key: 'page', value: '5' } + ]; + + expect(generateUrl(parsed)).toBe( + 'https://example.com/search?q=samsung&page=5' + ); + }); + + it('round-trips URL components', () => { + const input = 'https://example.com/search?q=test&sort=desc#top'; + expect(generateUrl(parseUrl(input))).toBe(input); + }); + + it('generates URL with edited host and path', () => { + const parsed = parseUrl('https://example.com/search?q=test'); + parsed.host = 'github.com'; + parsed.pathname = '/topics/open-source'; + + expect(generateUrl(parsed)).toBe( + 'https://github.com/topics/open-source?q=test' + ); + }); + + it('normalizes path without a leading slash', () => { + const parsed = parseUrl('https://example.com/search'); + parsed.pathname = 'topics/open-source'; + + expect(generateUrl(parsed)).toBe('https://example.com/topics/open-source'); + }); + + it('normalizes hash without a leading hash symbol', () => { + const parsed = parseUrl('https://example.com/page'); + parsed.hash = 'section1'; + + expect(generateUrl(parsed)).toBe('https://example.com/page#section1'); + }); + + it('throws when host is empty', () => { + const parsed = parseUrl('https://example.com'); + parsed.host = ' '; + + expect(() => generateUrl(parsed)).toThrow('Invalid URL'); + }); +}); From b72aa8bdd0dd19a4208f2dd739ba916f42c5222e Mon Sep 17 00:00:00 2001 From: RajivRatan27 Date: Sat, 6 Jun 2026 22:14:55 +0530 Subject: [PATCH 006/114] fix:edge cases handled --- public/locales/en/string.json | 4 + .../string/url-editor/UrlDetailsEditor.tsx | 6 +- src/pages/tools/string/url-editor/index.tsx | 53 ++++++--- src/pages/tools/string/url-editor/service.ts | 62 +++++++--- src/pages/tools/string/url-editor/types.ts | 3 + .../url-editor/url-editor.service.test.ts | 106 ++++++++++++------ 6 files changed, 172 insertions(+), 62 deletions(-) diff --git a/public/locales/en/string.json b/public/locales/en/string.json index 7bcc4804..3d2045e9 100644 --- a/public/locales/en/string.json +++ b/public/locales/en/string.json @@ -314,7 +314,9 @@ }, "urlEditor": { "addParameter": "Add Parameter", + "credentialsNotSupported": "URLs with username or password are not supported.", "delete": "Delete", + "deleteParamAriaLabel": "Delete parameter row {{row}}", "generatedUrl": "Generated URL", "hash": "Fragment", "hashPlaceholder": "section", @@ -325,6 +327,8 @@ "key": "Key", "noParameters": "No query parameters", "parseButton": "Parse URL", + "paramKeyAriaLabel": "Parameter key, row {{row}}", + "paramValueAriaLabel": "Parameter value, row {{row}}", "path": "Path", "pathPlaceholder": "search", "protocol": "Protocol", diff --git a/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx b/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx index caec3b7c..77ee7b2b 100644 --- a/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx +++ b/src/pages/tools/string/url-editor/UrlDetailsEditor.tsx @@ -1,3 +1,4 @@ +import { useId } from 'react'; import { Box, FormControl, @@ -33,6 +34,7 @@ export default function UrlDetailsEditor({ onChange, labels }: UrlDetailsEditorProps) { + const protocolLabelId = useId(); const hashValue = value.hash.replace(/^#/, ''); return ( @@ -48,9 +50,9 @@ export default function UrlDetailsEditor({ - {labels.protocol} + {labels.protocol} { - const files = Array.from(e.target.files ?? []); - setInput(files); - }} - /> - - - - - - {input.length === 0 && 'No files selected'} - {input.length > 0 && `${input.length} file(s) selected`} - - - {input.length > 0 && ( - - )} - - - {input.length > 0 && ( - -
    - {input.map((f) => ( -
  • - {f.name} -
  • - ))} -
-
- )} - - } - resultComponent={ - - {results.map((file) => ( - - - - ))} - - } - toolInfo={{ - title: 'Batch watermark images (filename)', - description: - 'Uploads multiple images and adds a text watermark based on each file’s name.' - }} - /> - ); -} diff --git a/src/pages/tools/image/generic/batch-watermark/meta.ts b/src/pages/tools/image/generic/batch-watermark/meta.ts deleted file mode 100644 index b6c3ee25..00000000 --- a/src/pages/tools/image/generic/batch-watermark/meta.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { defineTool } from '@tools/defineTool'; -import { lazy } from 'react'; - -export const tool = defineTool('image-generic', { - i18n: { - name: 'image:batchWatermark.title', - description: 'image:batchWatermark.description', - shortDescription: 'image:batchWatermark.shortDescription', - userTypes: ['generalUsers'] - }, - - path: 'batch-watermark', - icon: 'mdi:watermark', - - keywords: [ - 'watermark', - 'batch', - 'image', - 'text', - 'filename', - 'overlay', - 'png', - 'jpg' - ], - - component: lazy(() => import('./index')) -}); diff --git a/src/pages/tools/image/generic/batch-watermark/service.test.ts b/src/pages/tools/image/generic/batch-watermark/service.test.ts deleted file mode 100644 index d4016753..00000000 --- a/src/pages/tools/image/generic/batch-watermark/service.test.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; - -import { - filenameToWatermarkText, - outputSpecForFile, - processImage -} from './service'; - -describe('batch-watermark service', () => { - afterEach(() => { - vi.restoreAllMocks(); - // cleanup stubGlobal - // @ts-expect-error optional cleanup - delete globalThis.createImageBitmap; - }); - - it('filenameToWatermarkText strips extension and prettifies', () => { - expect(filenameToWatermarkText('goose.png')).toBe('goose'); - - expect(filenameToWatermarkText('duck_photo-01.jpeg')).toBe('duck photo 01'); - - expect(filenameToWatermarkText(' __weird--name__.webp ')).toBe( - 'weird name' - ); - }); - - it('outputSpecForFile preserves supported types and defaults unknown to PNG', () => { - const png = new File([new Uint8Array([1])], 'goose.png', { - type: 'image/png' - }); - - const jpg = new File([new Uint8Array([1])], 'duck.jpeg', { - type: 'image/jpeg' - }); - - const webp = new File([new Uint8Array([1])], 'bird.webp', { - type: 'image/webp' - }); - - const unknown = new File([new Uint8Array([1])], 'mystery.bin', { - type: 'application/octet-stream' - }); - - expect(outputSpecForFile(png)).toMatchObject({ - outputType: 'image/png', - ext: 'png' - }); - - expect(outputSpecForFile(jpg)).toMatchObject({ - outputType: 'image/jpeg', - ext: 'jpeg', - quality: 0.92 - }); - - expect(outputSpecForFile(webp)).toMatchObject({ - outputType: 'image/webp', - ext: 'webp' - }); - - expect(outputSpecForFile(unknown)).toMatchObject({ - outputType: 'image/png', - ext: 'png' - }); - }); - - it('processImage returns a watermarked file and uses filename as text', async () => { - vi.stubGlobal( - 'createImageBitmap', - vi.fn(async () => ({ - width: 200, - height: 100 - })) - ); - - const fillText = vi.fn(); - const drawImage = vi.fn(); - const save = vi.fn(); - const restore = vi.fn(); - - const ctxMock: any = { - drawImage, - save, - restore, - fillText, - globalAlpha: 1, - fillStyle: '', - font: '', - textAlign: 'left', - textBaseline: 'alphabetic', - shadowColor: '', - shadowBlur: 0, - shadowOffsetX: 0, - shadowOffsetY: 0 - }; - - const canvasMock: any = { - width: 0, - height: 0, - getContext: vi.fn(() => ctxMock), - toBlob: vi.fn((cb: (b: Blob | null) => void) => { - cb( - new Blob([new Uint8Array([2, 3, 4])], { - type: 'image/png' - }) - ); - }) - }; - - const originalCreateElement = document.createElement.bind(document); - - vi.spyOn(document, 'createElement').mockImplementation((tagName: any) => { - if (tagName === 'canvas') return canvasMock; - return originalCreateElement(tagName); - }); - - const file = new File([new Uint8Array([9])], 'goose.png', { - type: 'image/png' - }); - - const out = await processImage(file, { - watermarkOpacity: 0.35, - fontSize: 32, - position: 'bottom-right', - color: '#ffffff' - }); - - expect(out).not.toBeNull(); - - expect(out!.name).toBe('goose_watermarked.png'); - - expect(out!.type).toBe('image/png'); - - expect(drawImage).toHaveBeenCalled(); - - expect(fillText).toHaveBeenCalled(); - - const [textArg] = fillText.mock.calls[0]; - - expect(textArg).toBe('goose'); - }); - - it('processImage preserves jpeg output naming and type', async () => { - vi.stubGlobal( - 'createImageBitmap', - vi.fn(async () => ({ - width: 100, - height: 100 - })) - ); - - const ctxMock: any = { - drawImage: vi.fn(), - save: vi.fn(), - restore: vi.fn(), - fillText: vi.fn() - }; - - const canvasMock: any = { - width: 0, - height: 0, - getContext: vi.fn(() => ctxMock), - toBlob: vi.fn((cb: (b: Blob | null) => void) => { - cb( - new Blob([new Uint8Array([1])], { - type: 'image/jpeg' - }) - ); - }) - }; - - const originalCreateElement = document.createElement.bind(document); - - vi.spyOn(document, 'createElement').mockImplementation((tagName: any) => { - if (tagName === 'canvas') return canvasMock; - return originalCreateElement(tagName); - }); - - const file = new File([new Uint8Array([9])], 'duck.jpeg', { - type: 'image/jpeg' - }); - - const out = await processImage(file, { - watermarkOpacity: 0.4, - fontSize: 20, - position: 'top-left', - color: '#ffffff' - }); - - expect(out).not.toBeNull(); - - expect(out!.name).toBe('duck_watermarked.jpeg'); - - expect(out!.type).toBe('image/jpeg'); - }); -}); diff --git a/src/pages/tools/image/generic/batch-watermark/service.ts b/src/pages/tools/image/generic/batch-watermark/service.ts deleted file mode 100644 index 14d7e29f..00000000 --- a/src/pages/tools/image/generic/batch-watermark/service.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { InitialValuesType } from './types'; - -export function filenameToWatermarkText(filename: string): string { - const base = filename.replace(/\.[^.]+$/, ''); - return base.replace(/[_-]+/g, ' ').trim(); -} - -export function outputSpecForFile(file: File): { - outputType: 'image/png' | 'image/jpeg' | 'image/webp'; - ext: 'png' | 'jpeg' | 'webp'; - quality?: number; -} { - const inputType = file.type; - - const supported = - inputType === 'image/png' || - inputType === 'image/jpeg' || - inputType === 'image/webp'; - - const outputType = supported - ? (inputType as 'image/png' | 'image/jpeg' | 'image/webp') - : 'image/png'; - - const ext = - outputType === 'image/jpeg' - ? 'jpeg' - : outputType === 'image/webp' - ? 'webp' - : 'png'; - - // Only used for JPEG - const quality = outputType === 'image/jpeg' ? 0.92 : undefined; - - return { outputType, ext, quality }; -} - -function computePosition( - position: InitialValuesType['position'], - canvasWidth: number, - canvasHeight: number, - padding: number -) { - switch (position) { - case 'top-left': - return { - x: padding, - y: padding, - align: 'left' as const, - baseline: 'top' as const - }; - - case 'top-right': - return { - x: canvasWidth - padding, - y: padding, - align: 'right' as const, - baseline: 'top' as const - }; - - case 'bottom-left': - return { - x: padding, - y: canvasHeight - padding, - align: 'left' as const, - baseline: 'bottom' as const - }; - - case 'center': - return { - x: canvasWidth / 2, - y: canvasHeight / 2, - align: 'center' as const, - baseline: 'middle' as const - }; - - case 'bottom-right': - default: - return { - x: canvasWidth - padding, - y: canvasHeight - padding, - align: 'right' as const, - baseline: 'bottom' as const - }; - } -} - -export const processImage = async ( - file: File, - options: InitialValuesType -): Promise => { - // Skip SVG for now (different pipeline) - if (file.type === 'image/svg+xml') { - console.warn('SVG watermark not supported yet.'); - return null; - } - - // Skip GIF for now (frame-by-frame watermarking) - if (file.type === 'image/gif') { - console.warn('GIF watermark not supported yet.'); - return null; - } - - const { watermarkOpacity, fontSize, position, color } = options; - - // Decode image - const bitmap = await createImageBitmap(file); - - // Canvas setup - const canvas = document.createElement('canvas'); - canvas.width = bitmap.width; - canvas.height = bitmap.height; - - const ctx = canvas.getContext('2d'); - if (!ctx) return null; - - // Draw base image - ctx.drawImage(bitmap, 0, 0); - - // Build watermark text from filename - const text = filenameToWatermarkText(file.name); - if (!text) return null; - - // Watermark styling - const padding = Math.max( - 12, - Math.round(Math.min(canvas.width, canvas.height) * 0.02) - ); - - ctx.save(); - ctx.globalAlpha = watermarkOpacity; - ctx.fillStyle = color; - ctx.font = `bold ${fontSize}px sans-serif`; - - // Shadow for readability - ctx.shadowColor = 'rgba(0,0,0,0.65)'; - ctx.shadowBlur = 6; - ctx.shadowOffsetX = 2; - ctx.shadowOffsetY = 2; - - const pos = computePosition(position, canvas.width, canvas.height, padding); - ctx.textAlign = pos.align; - ctx.textBaseline = pos.baseline; - ctx.fillText(text, pos.x, pos.y); - ctx.restore(); - - // Output per-file format (PNG/JPEG/WebP) - const { outputType, ext, quality } = outputSpecForFile(file); - const base = file.name.replace(/\.[^.]+$/, ''); - const outName = `${base}_watermarked.${ext}`; - - const blob = await new Promise((resolve) => { - canvas.toBlob( - (b) => resolve(b), - outputType, - outputType === 'image/jpeg' ? quality : undefined - ); - }); - - if (!blob) return null; - return new File([blob], outName, { type: outputType }); -}; diff --git a/src/pages/tools/image/generic/batch-watermark/types.ts b/src/pages/tools/image/generic/batch-watermark/types.ts deleted file mode 100644 index 0b7a1aec..00000000 --- a/src/pages/tools/image/generic/batch-watermark/types.ts +++ /dev/null @@ -1,11 +0,0 @@ -export type InitialValuesType = { - watermarkOpacity: number; - fontSize: number; - position: - | 'bottom-right' - | 'bottom-left' - | 'top-right' - | 'top-left' - | 'center'; - color: string; -}; From ec7305b8ed0cf79e6486d607a83df62e7e019f36 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Mon, 3 Aug 2026 16:33:09 +0200 Subject: [PATCH 082/114] chore: updated types.ts file for declaring Position type --- src/pages/tools/image/generic/watermark/types.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/pages/tools/image/generic/watermark/types.ts diff --git a/src/pages/tools/image/generic/watermark/types.ts b/src/pages/tools/image/generic/watermark/types.ts new file mode 100644 index 00000000..59fa52db --- /dev/null +++ b/src/pages/tools/image/generic/watermark/types.ts @@ -0,0 +1,15 @@ +export type Position = + | 'bottom-right' + | 'bottom-left' + | 'top-right' + | 'top-left' + | 'center'; + +export type InitialValuesType = { + filename: boolean; + watermark: string; + watermarkOpacity: number; + fontSize: number; + position: Position; + color: string; +}; From d3b1b986af5c1745ff50494133c52b7b09aa76b3 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Mon, 3 Aug 2026 16:34:49 +0200 Subject: [PATCH 083/114] chore: updated service file - refactored functions - Mulitples files handled with zip return --- .../tools/image/generic/watermark/service.ts | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 src/pages/tools/image/generic/watermark/service.ts diff --git a/src/pages/tools/image/generic/watermark/service.ts b/src/pages/tools/image/generic/watermark/service.ts new file mode 100644 index 00000000..98736054 --- /dev/null +++ b/src/pages/tools/image/generic/watermark/service.ts @@ -0,0 +1,192 @@ +import { InitialValuesType, Position } from './types'; +import { heicTo, isHeic } from 'heic-to'; +import JSZip from 'jszip'; + +function computePosition( + position: Position, + canvasWidth: number, + canvasHeight: number, + padding: number +) { + switch (position) { + case 'top-left': + return { + x: padding, + y: padding, + align: 'left' as const, + baseline: 'top' as const + }; + case 'top-right': + return { + x: canvasWidth - padding, + y: padding, + align: 'right' as const, + baseline: 'top' as const + }; + case 'bottom-left': + return { + x: padding, + y: canvasHeight - padding, + align: 'left' as const, + baseline: 'bottom' as const + }; + case 'center': + return { + x: canvasWidth / 2, + y: canvasHeight / 2, + align: 'center' as const, + baseline: 'middle' as const + }; + case 'bottom-right': + default: + return { + x: canvasWidth - padding, + y: canvasHeight - padding, + align: 'right' as const, + baseline: 'bottom' as const + }; + } +} + +const processImage = async ( + file: File, + options: InitialValuesType +): Promise => { + const { watermarkOpacity, fontSize, position, color } = options; + + let processedFile = file; + + if (await isHeic(file)) { + const convertedBlob = await heicTo({ blob: file, type: 'image/jpeg' }); + processedFile = new File( + [convertedBlob], + file.name.replace(/\.[^/.]+$/, '') + '.jpg', + { type: 'image/jpeg' } + ); + } + + // Skip formats we don't watermark yet + if (processedFile.type === 'image/svg+xml') { + console.warn('SVG watermark not supported yet.'); + return; + } + if (processedFile.type === 'image/gif') { + console.warn('GIF watermark not supported yet.'); + return; + } + + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + if (ctx == null) return; + + const img = new Image(); + img.src = URL.createObjectURL(processedFile); + + try { + await img.decode(); + + canvas.width = img.width; + canvas.height = img.height; + ctx.drawImage(img, 0, 0); + + // Watermark text from the original filename + const text = options.filename + ? file.name + .replace(/\.[^/.]+$/, '') + .replace(/[_-]+/g, ' ') + .trim() + : options.watermark; + + if (!text) return; + + const padding = Math.max( + 12, + Math.round(Math.min(canvas.width, canvas.height) * 0.02) + ); + + ctx.save(); + ctx.globalAlpha = watermarkOpacity; + ctx.fillStyle = color; + ctx.font = `bold ${fontSize}px sans-serif`; + ctx.shadowColor = 'rgba(0,0,0,0.65)'; + ctx.shadowBlur = 6; + ctx.shadowOffsetX = 2; + ctx.shadowOffsetY = 2; + + const pos = computePosition(position, canvas.width, canvas.height, padding); + ctx.textAlign = pos.align; + ctx.textBaseline = pos.baseline; + + ctx.fillText(text, pos.x, pos.y); + ctx.restore(); + + // Keep the original format (PNG/JPEG/WebP), default to PNG otherwise + const outputType = + processedFile.type === 'image/jpeg' || processedFile.type === 'image/webp' + ? processedFile.type + : 'image/png'; + const ext = + outputType === 'image/jpeg' + ? 'jpeg' + : outputType === 'image/webp' + ? 'webp' + : 'png'; + const quality = outputType === 'image/jpeg' ? 0.92 : undefined; + + return new Promise((resolve) => { + canvas.toBlob( + (blob) => { + if (blob) { + const fileName = + file.name.replace(/\.[^/.]+$/, '') + `_watermarked.${ext}`; + resolve(new File([blob], fileName, { type: outputType })); + } else { + resolve(undefined); + } + }, + outputType, + quality + ); + }); + } catch (error) { + console.error('Error processing image:', error); + } finally { + URL.revokeObjectURL(img.src); + } +}; + +export const watermarkImages = async ( + files: File[], + options: InitialValuesType +): Promise<{ results: File[]; zipFile: File | null } | null> => { + try { + const watermarked = await Promise.all( + files.map(async (file) => { + try { + return (await processImage(file, options)) ?? null; + } catch (error) { + console.error(`Error watermarking ${file.name}:`, error); + return null; + } + }) + ); + + const results = watermarked.filter((f): f is File => f !== null); + + if (results.length === 0) return null; + + if (results.length === 1) return { results, zipFile: null }; + + const zip = new JSZip(); + results.forEach((file) => zip.file(file.name, file)); + const zipBlob = await zip.generateAsync({ type: 'blob' }); + const zipFile = new File([zipBlob], 'watermarked-images.zip', { + type: 'application/zip' + }); + + return { results, zipFile }; + } catch (error) { + console.error('Error watermarking images:', error); + return null; + } +}; From d25ddd3b70c376e5ce73f2481ac263d3014e3133 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Mon, 3 Aug 2026 16:37:06 +0200 Subject: [PATCH 084/114] chore: meta upated - removed batch keyword from url path - keywords updated --- .../tools/image/generic/watermark/meta.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/pages/tools/image/generic/watermark/meta.ts diff --git a/src/pages/tools/image/generic/watermark/meta.ts b/src/pages/tools/image/generic/watermark/meta.ts new file mode 100644 index 00000000..79d1a286 --- /dev/null +++ b/src/pages/tools/image/generic/watermark/meta.ts @@ -0,0 +1,26 @@ +import { defineTool } from '@tools/defineTool'; +import { lazy } from 'react'; + +export const tool = defineTool('image-generic', { + i18n: { + name: 'image:watermark.title', + description: 'image:watermark.description', + shortDescription: 'image:watermark.shortDescription', + userTypes: ['generalUsers'] + }, + + path: 'watermark', + icon: 'mdi:watermark', + + keywords: [ + 'watermark', + 'image', + 'text', + 'filename', + 'overlay', + 'branding', + 'stamp' + ], + + component: lazy(() => import('./index')) +}); From 6c05b21731e86698ce6d0810ea9b5d1a3c50a6f2 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Mon, 3 Aug 2026 16:38:03 +0200 Subject: [PATCH 085/114] chore: added tool to image index --- src/pages/tools/image/generic/index.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/pages/tools/image/generic/index.ts b/src/pages/tools/image/generic/index.ts index 2c125607..d868cf19 100644 --- a/src/pages/tools/image/generic/index.ts +++ b/src/pages/tools/image/generic/index.ts @@ -10,7 +10,7 @@ import { tool as imageToText } from './image-to-text/meta'; import { tool as qrCodeGenerator } from './qr-code/meta'; import { tool as rotateImage } from './rotate/meta'; import { tool as imageEditor } from './editor/meta'; -import { tool as batchWatermark } from './batch-watermark/meta'; +import { tool as watermark } from './watermark/meta'; export const imageGenericTools = [ imageEditor, @@ -24,7 +24,6 @@ export const imageGenericTools = [ imageToText, qrCodeGenerator, rotateImage, - convertToJpg, - batchWatermark + watermark, splitImage ]; From 3b5084abc09868f00e35f0b4b9c0f5ec52d2fe5a Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Mon, 3 Aug 2026 16:38:21 +0200 Subject: [PATCH 086/114] chore: full i8n support --- public/locales/en/image.json | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/public/locales/en/image.json b/public/locales/en/image.json index 1b1656ce..127e3fe2 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -259,10 +259,37 @@ "shortDescription": "Rotate an image easily.", "title": "Rotate Image" }, - "batchWatermark": { - "title": "Batch Watermark Images", - "description": "Add a text watermark based on each file name. Process multiple images at once.", - "shortDescription": "Watermark images from filename" + "watermark": { + "title": "Watermark Images", + "description": "Add text watermarks to one or more images using each filename or custom text.", + "shortDescription": "Add text watermarks to images", + "inputTitle": "Input Images", + "outputTitle": "Watermarked Images", + "failedToProcess": "Failed to watermark one or more images. Please try again.", + "options": { + "watermarkTitle": "Watermark Source", + "filenameWatermarkTitle": "Use Filename", + "filenameWatermarkDesc": "Use each image's filename as the watermark.", + "customStringWatermarkTitle": "Use Custom Watermark", + "customStringWatermarkDesc": "Apply the same custom text to every image.", + "watermark": "Watermark text.", + "fontSize": "Font size.", + "opacity": "Watermark transparency.", + "color": "Watermark color.", + "positionTitle": "Watermark Position", + "position": { + "bottomLeft": "Bottom Left", + "bottomRight": "Bottom Right", + "topLeft": "Top Left", + "topRight": "Top Right", + "center": "Center" + } + }, + "toolInfo": { + "title": "What is Watermark Images ?", + "longDescription": "An image watermark tool lets you add customizable text watermarks to one or more images. You can automatically use each image's filename as the watermark or apply the same custom text to every image. Watermarks help protect your work, identify ownership, promote your brand, and organize image collections. Customize the font size, opacity, color, and position while preserving the original image quality." + } + }, "split": { "title": "Split Image into Pages", "shortDescription": "Split a large image into multiple pages (PDF).", From 8f0505ed333df881b416573355cce24052b5bff9 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Mon, 3 Aug 2026 16:45:30 +0200 Subject: [PATCH 087/114] chore: index updated - full i8n support - watermark source selection - input for custom watermark --- .../tools/image/generic/watermark/index.tsx | 222 ++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 src/pages/tools/image/generic/watermark/index.tsx diff --git a/src/pages/tools/image/generic/watermark/index.tsx b/src/pages/tools/image/generic/watermark/index.tsx new file mode 100644 index 00000000..202e196f --- /dev/null +++ b/src/pages/tools/image/generic/watermark/index.tsx @@ -0,0 +1,222 @@ +import { Box } from '@mui/material'; +import React, { useState, useContext } from 'react'; +import * as Yup from 'yup'; +import ToolMultipleImageInput, { + MultiImageInput +} from '@components/input/ToolMultipleImageInput'; +import ToolMultiFileResult from '@components/result/ToolMultiFileResult'; +import ColorSelector from '@components/options/ColorSelector'; +import ToolFileResult from '@components/result/ToolFileResult'; +import { GetGroupsType } from '@components/options/ToolOptions'; +import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; +import ToolContent from '@components/ToolContent'; +import { ToolComponentProps } from '@tools/defineTool'; +import SimpleRadio from '@components/options/SimpleRadio'; +import { watermarkImages } from './service'; +import { InitialValuesType } from './types'; +import { CustomSnackBarContext } from 'contexts/CustomSnackBarContext'; +import { useTranslation } from 'react-i18next'; +import { getFileExtension } from '@utils/file'; + +const initialValues: InitialValuesType = { + filename: true, + watermark: 'OMNITOOLS', + watermarkOpacity: 0.35, + fontSize: 32, + position: 'bottom-right', + color: '#ffffff' +}; + +const validationSchema = Yup.object({ + watermarkOpacity: Yup.number() + .min(0, 'Opacity must be between 0 and 1') + .max(1, 'Opacity must be between 0 and 1') + .required('Opacity is required'), + fontSize: Yup.number() + .min(8, 'Font size must be at least 8px') + .max(512, 'Font size is too large') + .required('Font size is required'), + color: Yup.string().required('Color is required') +}); + +export default function Watermark({ title }: ToolComponentProps) { + const { t } = useTranslation('image'); + const [input, setInput] = useState([]); + const [result, setResult] = useState([]); + const [zipFile, setZipFile] = useState(null); + const [isProcessing, setIsProcessing] = useState(false); + const { showSnackBar } = useContext(CustomSnackBarContext); + + const compute = async ( + optionsValues: InitialValuesType, + input: MultiImageInput[] + ) => { + if (!input || input.length === 0) return; + + try { + setIsProcessing(true); + + const output = await watermarkImages( + input.map((img) => img.file), + optionsValues + ); + + if (!output) { + showSnackBar(t('watermark.failedToProcess'), 'error'); + return; + } else { + setResult(output.results); + setZipFile(output.zipFile); + } + } catch (error) { + showSnackBar(`Error converting files: ${error}`, 'error'); + setZipFile(null); + } finally { + setIsProcessing(false); + } + }; + + const getGroups: GetGroupsType = ({ + values, + updateField + }) => [ + { + title: t('watermark.options.watermarkTitle'), + component: ( + + + updateField('filename', true)} + checked={values.filename === true} + title={t('watermark.options.filenameWatermarkTitle')} + description={t('watermark.options.filenameWatermarkDesc')} + /> + updateField('filename', false)} + checked={values.filename === false} + title={t('watermark.options.customStringWatermarkTitle')} + description={t('watermark.options.customStringWatermarkDesc')} + /> + + + {!values.filename && ( + updateField('watermark', val)} + description={t('watermark.options.watermark')} + inputProps={{ + 'data-testid': 'watermark-input', + type: 'string' + }} + /> + )} + updateField('watermarkOpacity', Number(val))} + description={t('watermark.options.opacity')} + inputProps={{ + 'data-testid': 'opacity-input', + type: 'number', + min: 0, + max: 1, + step: 0.05 + }} + /> + updateField('fontSize', Number(val))} + description={t('watermark.options.fontSize')} + inputProps={{ + 'data-testid': 'font-size-input', + type: 'number', + min: 8, + max: 512, + step: 1 + }} + /> + updateField('color', val)} + description={t('watermark.options.color')} + inputProps={{ + 'data-testid': 'color-input' + }} + /> + + ) + }, + { + title: t('watermark.options.positionTitle'), + component: ( + + updateField('position', 'bottom-right')} + checked={values.position === 'bottom-right'} + title={t('watermark.options.position.bottomRight')} + /> + updateField('position', 'bottom-left')} + checked={values.position === 'bottom-left'} + title={t('watermark.options.position.bottomLeft')} + /> + updateField('position', 'top-right')} + checked={values.position === 'top-right'} + title={t('watermark.options.position.topRight')} + /> + updateField('position', 'top-left')} + checked={values.position === 'top-left'} + title={t('watermark.options.position.topLeft')} + /> + updateField('position', 'center')} + checked={values.position === 'center'} + title={t('watermark.options.position.center')} + /> + + ) + } + ]; + + return ( + + } + resultComponent={ + zipFile ? ( + + ) : ( + + ) + } + toolInfo={{ + title: t('watermark.toolInfo.title'), + description: t('watermark.toolInfo.longDescription') + }} + /> + ); +} From 6632d7d8ee881996ef0b0ea306ac9294ea215ed9 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Mon, 3 Aug 2026 16:54:50 +0200 Subject: [PATCH 088/114] chore: sepatated styles options from source options --- public/locales/en/image.json | 5 +-- .../tools/image/generic/watermark/index.tsx | 34 +++++++++++-------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/public/locales/en/image.json b/public/locales/en/image.json index 127e3fe2..b484eb43 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -267,16 +267,17 @@ "outputTitle": "Watermarked Images", "failedToProcess": "Failed to watermark one or more images. Please try again.", "options": { - "watermarkTitle": "Watermark Source", + "watermarkTitle": "Source", "filenameWatermarkTitle": "Use Filename", "filenameWatermarkDesc": "Use each image's filename as the watermark.", "customStringWatermarkTitle": "Use Custom Watermark", "customStringWatermarkDesc": "Apply the same custom text to every image.", + "styleTitle": "Style", "watermark": "Watermark text.", "fontSize": "Font size.", "opacity": "Watermark transparency.", "color": "Watermark color.", - "positionTitle": "Watermark Position", + "positionTitle": "Position", "position": { "bottomLeft": "Bottom Left", "bottomRight": "Bottom Right", diff --git a/src/pages/tools/image/generic/watermark/index.tsx b/src/pages/tools/image/generic/watermark/index.tsx index 202e196f..fa413dd7 100644 --- a/src/pages/tools/image/generic/watermark/index.tsx +++ b/src/pages/tools/image/generic/watermark/index.tsx @@ -84,21 +84,25 @@ export default function Watermark({ title }: ToolComponentProps) { title: t('watermark.options.watermarkTitle'), component: ( - - updateField('filename', true)} - checked={values.filename === true} - title={t('watermark.options.filenameWatermarkTitle')} - description={t('watermark.options.filenameWatermarkDesc')} - /> - updateField('filename', false)} - checked={values.filename === false} - title={t('watermark.options.customStringWatermarkTitle')} - description={t('watermark.options.customStringWatermarkDesc')} - /> - - + updateField('filename', true)} + checked={values.filename === true} + title={t('watermark.options.filenameWatermarkTitle')} + description={t('watermark.options.filenameWatermarkDesc')} + /> + updateField('filename', false)} + checked={values.filename === false} + title={t('watermark.options.customStringWatermarkTitle')} + description={t('watermark.options.customStringWatermarkDesc')} + /> + + ) + }, + { + title: t('watermark.options.styleTitle'), + component: ( + {!values.filename && ( Date: Mon, 3 Aug 2026 16:59:13 +0200 Subject: [PATCH 089/114] chore: index updated --- .../tools/image/generic/watermark/index.tsx | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/pages/tools/image/generic/watermark/index.tsx b/src/pages/tools/image/generic/watermark/index.tsx index fa413dd7..e0878d89 100644 --- a/src/pages/tools/image/generic/watermark/index.tsx +++ b/src/pages/tools/image/generic/watermark/index.tsx @@ -84,25 +84,20 @@ export default function Watermark({ title }: ToolComponentProps) { title: t('watermark.options.watermarkTitle'), component: ( - updateField('filename', true)} - checked={values.filename === true} - title={t('watermark.options.filenameWatermarkTitle')} - description={t('watermark.options.filenameWatermarkDesc')} - /> - updateField('filename', false)} - checked={values.filename === false} - title={t('watermark.options.customStringWatermarkTitle')} - description={t('watermark.options.customStringWatermarkDesc')} - /> - - ) - }, - { - title: t('watermark.options.styleTitle'), - component: ( - + + updateField('filename', true)} + checked={values.filename === true} + title={t('watermark.options.filenameWatermarkTitle')} + description={t('watermark.options.filenameWatermarkDesc')} + /> + updateField('filename', false)} + checked={values.filename === false} + title={t('watermark.options.customStringWatermarkTitle')} + description={t('watermark.options.customStringWatermarkDesc')} + /> + {!values.filename && ( )} + + ) + }, + { + title: t('watermark.options.styleTitle'), + component: ( + updateField('watermarkOpacity', Number(val))} From ba89ee15b3d1b76906477e5bc17b42f7095f3b80 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Tue, 4 Aug 2026 17:27:34 +0200 Subject: [PATCH 090/114] chore: ffmpeg lib - Centralize instance loading - task queue for performance --- src/lib/ffmpeg.ts | 97 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/lib/ffmpeg.ts diff --git a/src/lib/ffmpeg.ts b/src/lib/ffmpeg.ts new file mode 100644 index 00000000..5957e708 --- /dev/null +++ b/src/lib/ffmpeg.ts @@ -0,0 +1,97 @@ +import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { toBlobURL } from '@ffmpeg/util'; + +const CORE_VERSION = '0.12.6'; +const BASE_URL = `https://unpkg.com/@ffmpeg/core@${CORE_VERSION}/dist/esm`; + +let ffmpegInstance: FFmpeg | null = null; +let loadingPromise: Promise | null = null; + +type FFmpegTaskContext = { + ffmpeg: FFmpeg; + tempFile: (extension: string) => string; +}; + +async function getFFmpeg(): Promise { + if (ffmpegInstance?.loaded) { + return ffmpegInstance; + } + + if (!loadingPromise) { + loadingPromise = (async () => { + const ffmpeg = new FFmpeg(); + + await ffmpeg.load({ + coreURL: await toBlobURL( + `${BASE_URL}/ffmpeg-core.js`, + 'text/javascript' + ), + wasmURL: await toBlobURL( + `${BASE_URL}/ffmpeg-core.wasm`, + 'application/wasm' + ) + }); + + ffmpegInstance = ffmpeg; + + return ffmpeg; + })(); + } + + try { + return await loadingPromise; + } finally { + loadingPromise = null; + } +} + +/** + * Destroy the current FFmpeg instance. + * + * Normally not needed because the instance is reused. + * Use only after worker crashes or when explicitly freeing memory. + */ +export function resetFFmpeg(): void { + ffmpegInstance?.terminate(); + + ffmpegInstance = null; + loadingPromise = null; +} + +// FFmpeg worker is not safe for concurrent operations. +let taskQueue: Promise = Promise.resolve(); + +export async function runFFmpegTask( + task: (context: FFmpegTaskContext) => Promise +): Promise { + const ffmpeg = await getFFmpeg(); + + const run = taskQueue + .catch(() => {}) + .then(async () => { + const tempFiles = new Set(); + + const tempFile = (extension: string) => { + const filename = `${crypto.randomUUID()}${extension}`; + + tempFiles.add(filename); + + return filename; + }; + + try { + return await task({ + ffmpeg, + tempFile + }); + } finally { + await Promise.all( + [...tempFiles].map((file) => ffmpeg.deleteFile(file).catch(() => {})) + ); + } + }); + + taskQueue = run.catch(() => {}); + + return run; +} From d9442ac4716b461e13a6b47f76d0cff96ce09a18 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Tue, 4 Aug 2026 17:32:19 +0200 Subject: [PATCH 091/114] chore: rewritten service using ffmpeg lib --- .../converters/audio-converter/service.ts | 78 ++++++------------- 1 file changed, 23 insertions(+), 55 deletions(-) diff --git a/src/pages/tools/converters/audio-converter/service.ts b/src/pages/tools/converters/audio-converter/service.ts index dc243e35..33f742e0 100644 --- a/src/pages/tools/converters/audio-converter/service.ts +++ b/src/pages/tools/converters/audio-converter/service.ts @@ -1,82 +1,50 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { InitialValuesType, AUDIO_FORMATS } from './types'; import { getFileExtension } from 'utils/file'; /** - * optimzed call for FFmpeg instance creation, - * avoiding to download required FFmpeg binaries on every reload - */ -const ffmpeg = new FFmpeg(); -let isLoaded = false; - -async function loadFFmpeg() { - if (!isLoaded) { - await ffmpeg.load(); - isLoaded = true; - } -} - -/** - * Converts input audio file to selected output format ('mp3', 'aac', or 'wav'). - * Supports any input audio file type accepted by FFmpeg. + * Converts input audio file to selected output format. * * @param input - Source audio File - * @param outputFormat - 'mp3' | 'aac' | 'wav' + * @param options - Conversion options * @returns Converted audio File */ export async function convertAudio( input: File, options: InitialValuesType ): Promise { - await loadFFmpeg(); - - // Use the original input extension for input filename const inputExt = getFileExtension(input.name); - if (inputExt === options.outputFormat) return input; + if (inputExt === options.outputFormat) { + return input; + } - const inputFileName = inputExt ? `input.${inputExt}` : 'input'; - const outputFileName = `output.${options.outputFormat}`; + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputFileName = tempFile(inputExt ? `.${inputExt}` : ''); - // Write the input file to FFmpeg FS - await ffmpeg.writeFile(inputFileName, await fetchFile(input)); + const outputFileName = tempFile(`.${options.outputFormat}`); - // Build the FFmpeg args depending on the output format - // You can customize the codec and bitrate options per format here + await ffmpeg.writeFile(inputFileName, await fetchFile(input)); - const format = AUDIO_FORMATS[options.outputFormat]; - const { codec, bitrate, mimeType } = format; + const { codec, bitrate, mimeType } = AUDIO_FORMATS[options.outputFormat]; - const args = bitrate - ? ['-i', inputFileName, '-c:a', codec, '-b:a', bitrate, outputFileName] - : ['-i', inputFileName, '-c:a', codec, outputFileName]; + const args = bitrate + ? ['-i', inputFileName, '-c:a', codec, '-b:a', bitrate, outputFileName] + : ['-i', inputFileName, '-c:a', codec, outputFileName]; - // Execute ffmpeg with arguments - try { await ffmpeg.exec(args); - // Read the output file from FFmpeg FS const data = await ffmpeg.readFile(outputFileName); - // Create a new File with the original name but new extension - const baseName = input.name.replace(/\.[^.]+$/, ''); - const convertedFileName = `${baseName}.${options.outputFormat}`; + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: mimeType + }); - return new File( - [new Blob([data as any], { type: mimeType })], - convertedFileName, - { - type: mimeType - } - ); - } finally { - // Clean up FFmpeg virtual filesystem - try { - await ffmpeg.deleteFile(inputFileName); - await ffmpeg.deleteFile(outputFileName); - } catch (e) { - // Ignore cleanup errors - } - } + const baseName = input.name.replace(/\.[^.]+$/, ''); + + return new File([blob], `${baseName}.${options.outputFormat}`, { + type: mimeType + }); + }); } From c397127eef6c8bfd79058c27f2fd0935d5fce793 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Tue, 4 Aug 2026 17:44:35 +0200 Subject: [PATCH 092/114] chore: rewritten service using ffmpeg lib (add audio to video) --- src/pages/tools/video/add-audio/index.tsx | 2 +- src/pages/tools/video/add-audio/service.ts | 154 +++++++++++---------- 2 files changed, 81 insertions(+), 75 deletions(-) diff --git a/src/pages/tools/video/add-audio/index.tsx b/src/pages/tools/video/add-audio/index.tsx index 2fb769fc..fd6a5028 100644 --- a/src/pages/tools/video/add-audio/index.tsx +++ b/src/pages/tools/video/add-audio/index.tsx @@ -12,7 +12,7 @@ import SelectWithDesc from '@components/options/SelectWithDesc'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { useTranslation } from 'react-i18next'; import { addAudioToVideo } from './service'; -import { AudioMode, timingMode, initialValuesType } from './types'; +import { AudioMode, initialValuesType } from './types'; import debounce from 'lodash/debounce'; const initialValues: initialValuesType = { diff --git a/src/pages/tools/video/add-audio/service.ts b/src/pages/tools/video/add-audio/service.ts index 21b157df..5941d1ff 100644 --- a/src/pages/tools/video/add-audio/service.ts +++ b/src/pages/tools/video/add-audio/service.ts @@ -1,39 +1,39 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { initialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - -async function ensureLoaded() { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - } -} - export function timeToSeconds(time: string): number { const parts = time.split(':').map(Number); - if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2]; - if (parts.length === 2) return parts[0] * 60 + parts[1]; + + if (parts.length === 3) { + return parts[0] * 3600 + parts[1] * 60 + parts[2]; + } + + if (parts.length === 2) { + return parts[0] * 60 + parts[1]; + } + return parts[0] || 0; } function hasDurationConstraint(options: initialValuesType): boolean { const start = timeToSeconds(options.startTime); const end = timeToSeconds(options.endTime); + return start > 0 || end > 0; } function buildAudioFilterChain(options: initialValuesType): string { const volumeScale = (options.volume / 100).toFixed(2); + const start = timeToSeconds(options.startTime); const end = timeToSeconds(options.endTime); + const hasConstraint = start > 0 || end > 0; const delay = start * 1000; const filters: string[] = []; + filters.push(`volume=${volumeScale}`); if (hasConstraint) { @@ -45,6 +45,7 @@ function buildAudioFilterChain(options: initialValuesType): string { } else if (end > 0) { filters.push(`atrim=start=0:end=${end}`); } + filters.push('apad'); } @@ -64,72 +65,77 @@ export async function addAudioToVideo( audio: File, options: initialValuesType ): Promise { - await ensureLoaded(); + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputVideo = tempFile('.mp4'); + const inputAudio = tempFile('.mp3'); + const outputName = tempFile('.mp4'); - const inputVideo = 'input.mp4'; - const inputAudio = 'input-audio.mp3'; - const outputName = 'output.mp4'; + await ffmpeg.writeFile(inputVideo, await fetchFile(video)); - await ffmpeg.writeFile(inputVideo, await fetchFile(video)); - await ffmpeg.writeFile(inputAudio, await fetchFile(audio)); + await ffmpeg.writeFile(inputAudio, await fetchFile(audio)); - const audioModeFilter = buildAudioModeFilter(options); + const audioModeFilter = buildAudioModeFilter(options); - const inputArgs: string[] = []; - inputArgs.push('-i', inputVideo); - if (options.loop) { - inputArgs.push('-stream_loop', '-1'); - } - inputArgs.push('-i', inputAudio); + const inputArgs: string[] = ['-i', inputVideo]; - const hasConstraint = hasDurationConstraint(options); + if (options.loop) { + inputArgs.push('-stream_loop', '-1'); + } - let args: string[]; + inputArgs.push('-i', inputAudio); - if (options.mode === 'replace') { - args = [ - ...inputArgs, - '-c:v', - 'copy', - '-filter_complex', - audioModeFilter, - '-map', - '0:v:0', - '-map', - '[aout]', - '-shortest', - '-y', - outputName - ]; - } else { - args = [ - ...inputArgs, - '-c:v', - 'copy', - '-filter_complex', - audioModeFilter, - '-map', - '0:v', - '-map', - '[aout]', - ...(hasConstraint ? [] : ['-shortest']), - '-y', - outputName - ]; - } + const hasConstraint = hasDurationConstraint(options); - try { - await ffmpeg.exec(args); - const data = await ffmpeg.readFile(outputName); - return new File( - [new Blob([data as any], { type: 'video/mp4' })], - `${video.name.replace(/\.[^/.]+$/, '')}_with_audio.mp4`, - { type: 'video/mp4' } - ); - } catch (error) { - console.error('FFmpeg execution failed:', error); - throw error; - } finally { - await ffmpeg.deleteFile(outputName); - } + const args = + options.mode === 'replace' + ? [ + ...inputArgs, + '-c:v', + 'copy', + '-filter_complex', + audioModeFilter, + '-map', + '0:v:0', + '-map', + '[aout]', + '-shortest', + '-y', + outputName + ] + : [ + ...inputArgs, + '-c:v', + 'copy', + '-filter_complex', + audioModeFilter, + '-map', + '0:v', + '-map', + '[aout]', + ...(hasConstraint ? [] : ['-shortest']), + '-y', + outputName + ]; + + try { + await ffmpeg.exec(args); + + const data = await ffmpeg.readFile(outputName); + + return new File( + [ + new Blob([new Uint8Array(data as Uint8Array)], { + type: 'video/mp4' + }) + ], + `${video.name.replace(/\.[^/.]+$/, '')}_with_audio.mp4`, + { + type: 'video/mp4' + } + ); + } catch (error) { + console.error('FFmpeg execution failed:', error); + throw error; + } + }); } From dcc3a6536b8fffa217ad127eb6a6cd82ce8d32f7 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Tue, 4 Aug 2026 20:35:56 +0200 Subject: [PATCH 093/114] chore: change-video-speed updated - i8n key updated - service isolated to service.ts file - slider used for speed value controling --- public/locales/en/video.json | 8 +- src/pages/tools/video/change-speed/index.tsx | 171 +++++------------- src/pages/tools/video/change-speed/service.ts | 77 +++++++- src/pages/tools/video/change-speed/types.ts | 2 +- 4 files changed, 121 insertions(+), 137 deletions(-) diff --git a/public/locales/en/video.json b/public/locales/en/video.json index 3be86a67..7ed1d9ef 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -29,16 +29,16 @@ "volumeDesc": "Volume level for the new audio track." }, "changeSpeed": { - "defaultMultiplier": "Default multiplier: 2 means 2x faster", "description": "Change the playback speed of video files. Speed up or slow down videos while maintaining audio synchronization. Supports various speed multipliers and common video formats.", "inputTitle": "Input Video", - "newVideoSpeed": "New Video Speed", "resultTitle": "Edited Video", - "settingSpeed": "Setting Speed", + "options": "Options", + "speedLabel": "Speed : x", "shortDescription": "Change video playback speed", "title": "Change Video Speed", "toolInfo": { - "title": "What is a {{title}}?" + "title": "What is a {{title}}?", + "longDescription": "{{title}} allows you to adjust the playback speed of your videos directly in your browser. Speed up videos for fast-motion effects or slow them down for slow-motion playback while keeping the audio synchronized. Choose a speed multiplier between 0.25x and 4x to customize your video, then process it easily without installing additional software. This tool supports common video formats and preserves the original video quality as much as possible during processing." } }, "compress": { diff --git a/src/pages/tools/video/change-speed/index.tsx b/src/pages/tools/video/change-speed/index.tsx index 12acee92..02bc772b 100644 --- a/src/pages/tools/video/change-speed/index.tsx +++ b/src/pages/tools/video/change-speed/index.tsx @@ -1,143 +1,67 @@ -import { Box } from '@mui/material'; -import React, { useState } from 'react'; +import { Box, Slider, Typography } from '@mui/material'; +import React, { useState, useCallback } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import { InitialValuesType } from './types'; import ToolVideoInput from '@components/input/ToolVideoInput'; import ToolFileResult from '@components/result/ToolFileResult'; -import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; +import { ChangeVideoSpeed } from './service'; import { useTranslation } from 'react-i18next'; +import debounce from 'lodash/debounce'; const initialValues: InitialValuesType = { - newSpeed: 2 + speed: 2 }; -export default function ChangeSpeed({ - title, - longDescription -}: ToolComponentProps) { +export default function ChangeSpeed({ title }: ToolComponentProps) { const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); - // FFmpeg only supports a tempo between 0.5 and 2.0, so we chain filters - const computeAudioFilter = (speed: number): string => { - if (speed <= 2 && speed >= 0.5) { - return `atempo=${speed}`; - } - - // Break into supported chunks - const filters: string[] = []; - let remainingSpeed = speed; - while (remainingSpeed > 2.0) { - filters.push('atempo=2.0'); - remainingSpeed /= 2.0; - } - while (remainingSpeed < 0.5) { - filters.push('atempo=0.5'); - remainingSpeed /= 0.5; - } - filters.push(`atempo=${remainingSpeed.toFixed(2)}`); - - return filters.join(','); - }; - - const compute = (optionsValues: InitialValuesType, input: File | null) => { + const compute = async ( + optionsValues: InitialValuesType, + input: File | null + ) => { if (!input) return; - const { newSpeed } = optionsValues; - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; - const processVideo = async ( - file: File, - newSpeed: number - ): Promise => { - if (newSpeed === 0) return; + try { setLoading(true); - - if (!ffmpeg) { - ffmpeg = new FFmpeg(); - } - - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - - // Write file to FFmpeg FS - const fileName = file.name; - const outputName = 'output.mp4'; - - try { - ffmpeg.writeFile(fileName, await fetchFile(file)); - - const videoFilter = `setpts=${1 / newSpeed}*PTS`; - const audioFilter = computeAudioFilter(newSpeed); - - // Run FFmpeg command - await ffmpeg.exec([ - '-i', - fileName, - '-vf', - videoFilter, - '-filter:a', - audioFilter, - '-c:v', - 'libx264', - '-preset', - 'ultrafast', - '-c:a', - 'aac', - outputName - ]); - - const data = await ffmpeg.readFile(outputName); - - // Create new file from processed data - const blob = new Blob([data as any], { type: 'video/mp4' }); - const newFile = new File( - [blob], - file.name.replace('.mp4', `-${newSpeed}x.mp4`), - { type: 'video/mp4' } - ); - - // Clean up to free memory - await ffmpeg.deleteFile(fileName); - await ffmpeg.deleteFile(outputName); - - setResult(newFile); - } catch (err) { - console.error(`Failed to process video: ${err}`); - throw err; - } finally { - setLoading(false); - } - }; - - // Here we set the output video - processVideo(input, newSpeed); + const resultFile = await ChangeVideoSpeed(input, optionsValues); + setResult(resultFile); + } catch (error) { + console.error('Conversion failed:', error); + setResult(null); + } finally { + setLoading(false); + } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); + const getGroups: GetGroupsType | null = ({ values, updateField }) => [ { - title: t('changeSpeed.newVideoSpeed'), + title: t('changeSpeed.options'), component: ( - updateField('newSpeed', Number(val))} - description={t('changeSpeed.defaultMultiplier')} - type="number" + + {t('changeSpeed.speedLabel')} {values.speed} + + + updateField('speed', Array.isArray(value) ? value[0] : value) + } + min={0.25} + max={4} + step={0.25} + valueLabelDisplay="auto" + valueLabelFormat={(value) => `x ${value}`} + sx={{ mt: 1 }} /> ) @@ -155,27 +79,20 @@ export default function ChangeSpeed({ /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} setInput={setInput} - compute={compute} + compute={debouncedCompute} toolInfo={{ title: t('changeSpeed.toolInfo.title', { title }), - description: longDescription + description: t('changeSpeed.toolInfo.longDescription', { title }) }} /> ); diff --git a/src/pages/tools/video/change-speed/service.ts b/src/pages/tools/video/change-speed/service.ts index 18d6dd6f..1dc8d35e 100644 --- a/src/pages/tools/video/change-speed/service.ts +++ b/src/pages/tools/video/change-speed/service.ts @@ -1,8 +1,75 @@ import { InitialValuesType } from './types'; +import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; +import { getFileExtension } from '@utils/file'; -export function main( - input: File | null, +const computeAudioFilter = (speed: number): string => { + if (speed >= 0.5 && speed <= 2) { + return `atempo=${speed}`; + } + + const filters: string[] = []; + let remainingSpeed = speed; + + while (remainingSpeed > 2) { + filters.push('atempo=2.0'); + remainingSpeed /= 2; + } + + while (remainingSpeed < 0.5) { + filters.push('atempo=0.5'); + remainingSpeed /= 0.5; + } + + filters.push(`atempo=${remainingSpeed.toFixed(2)}`); + + return filters.join(','); +}; + +export const ChangeVideoSpeed = async ( + file: File, options: InitialValuesType -): File | null { - return input; -} +): Promise => { + const { speed } = options; + + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const extension = getFileExtension(file.name); + + const fileName = tempFile(extension ? `.${extension}` : ''); + + const outputName = tempFile('.mp4'); + + await ffmpeg.writeFile(fileName, await fetchFile(file)); + + const videoFilter = `setpts=${1 / speed}*PTS`; + const audioFilter = computeAudioFilter(speed); + + await ffmpeg.exec([ + '-i', + fileName, + '-vf', + videoFilter, + '-filter:a', + audioFilter, + '-c:v', + 'libx264', + '-preset', + 'ultrafast', + '-c:a', + 'aac', + outputName + ]); + + const data = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'video/mp4' + }); + + const baseName = file.name.replace(/\.[^/.]+$/, ''); + + return new File([blob], `${baseName}-${speed}x.mp4`, { + type: 'video/mp4' + }); + }); +}; diff --git a/src/pages/tools/video/change-speed/types.ts b/src/pages/tools/video/change-speed/types.ts index 9c748637..bb19b97f 100644 --- a/src/pages/tools/video/change-speed/types.ts +++ b/src/pages/tools/video/change-speed/types.ts @@ -1,3 +1,3 @@ export type InitialValuesType = { - newSpeed: number; + speed: number; }; From 78afe6888a566b07270fb57358dd4beb31ba6966 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Tue, 4 Aug 2026 21:16:54 +0200 Subject: [PATCH 094/114] chore: video compression updated --- src/pages/tools/video/compress/index.tsx | 64 +++-------------- src/pages/tools/video/compress/service.ts | 86 ++++++++++------------- src/pages/tools/video/compress/types.ts | 6 ++ 3 files changed, 54 insertions(+), 102 deletions(-) create mode 100644 src/pages/tools/video/compress/types.ts diff --git a/src/pages/tools/video/compress/index.tsx b/src/pages/tools/video/compress/index.tsx index 069466fc..5440974e 100644 --- a/src/pages/tools/video/compress/index.tsx +++ b/src/pages/tools/video/compress/index.tsx @@ -7,16 +7,16 @@ import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import { debounce } from 'lodash'; import ToolVideoInput from '@components/input/ToolVideoInput'; -import { compressVideo, VideoResolution } from './service'; +import { compressVideo } from './service'; +import { InitialValuesType } from './types'; import SimpleRadio from '@components/options/SimpleRadio'; import Slider from 'rc-slider'; import 'rc-slider/assets/index.css'; import { useTranslation } from 'react-i18next'; -export const initialValues = { - width: 480 as VideoResolution, - crf: 23, - preset: 'medium' +export const initialValues: InitialValuesType = { + width: 480, + crf: 23 }; export const validationSchema = Yup.object({ @@ -29,26 +29,13 @@ export const validationSchema = Yup.object({ crf: Yup.number() .min(0, 'CRF must be at least 0') .max(51, 'CRF must be at most 51') - .required('CRF is required'), - preset: Yup.string() - .oneOf( - [ - 'ultrafast', - 'superfast', - 'veryfast', - 'faster', - 'fast', - 'medium', - 'slow', - 'slower', - 'veryslow' - ], - 'Preset must be a valid ffmpeg preset' - ) - .required('Preset is required') + .required('CRF is required') }); -const resolutionOptions: { value: VideoResolution; label: string }[] = [ +const resolutionOptions: { + value: InitialValuesType['width']; + label: string; +}[] = [ { value: 240, label: '240p' }, { value: 360, label: '360p' }, { value: 480, label: '480p' }, @@ -56,18 +43,6 @@ const resolutionOptions: { value: VideoResolution; label: string }[] = [ { value: 1080, label: '1080p' } ]; -const presetOptions = [ - { value: 'ultrafast', label: 'Ultrafast (Lowest Quality, Smallest Size)' }, - { value: 'superfast', label: 'Superfast' }, - { value: 'veryfast', label: 'Very Fast' }, - { value: 'faster', label: 'Faster' }, - { value: 'fast', label: 'Fast' }, - { value: 'medium', label: 'Medium (Balanced)' }, - { value: 'slow', label: 'Slow' }, - { value: 'slower', label: 'Slower' }, - { value: 'veryslow', label: 'Very Slow (Highest Quality, Largest Size)' } -]; - export default function CompressVideo({ title }: ToolComponentProps) { const { t } = useTranslation('video'); const [input, setInput] = useState(null); @@ -82,11 +57,7 @@ export default function CompressVideo({ title }: ToolComponentProps) { setLoading(true); try { - const compressedFile = await compressVideo(input, { - width: optionsValues.width, - crf: optionsValues.crf, - preset: optionsValues.preset - }); + const compressedFile = await compressVideo(input, optionsValues); setResult(compressedFile); } catch (error) { console.error('Error compressing video:', error); @@ -139,19 +110,6 @@ export default function CompressVideo({ title }: ToolComponentProps) { ) } - // { - // title: 'Encoding Preset', - // component: ( - // updateField('preset', value)} - // options={presetOptions} - // description={ - // 'Determines the compression speed. Slower presets provide better compression (quality per filesize) but take more time.' - // } - // /> - // ) - // } ]; return ( diff --git a/src/pages/tools/video/compress/service.ts b/src/pages/tools/video/compress/service.ts index 73838c7a..8dbf6bc5 100644 --- a/src/pages/tools/video/compress/service.ts +++ b/src/pages/tools/video/compress/service.ts @@ -1,60 +1,48 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; - -const ffmpeg = new FFmpeg(); - -export type VideoResolution = 240 | 360 | 480 | 720 | 1080; - -export interface CompressVideoOptions { - width: VideoResolution; - crf: number; // Constant Rate Factor (quality): lower = better quality, higher = smaller file - preset: string; // Encoding speed preset -} +import { InitialValuesType } from './types'; export async function compressVideo( input: File, - options: CompressVideoOptions + options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - } + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; + await ffmpeg.writeFile(inputName, await fetchFile(input)); - await ffmpeg.writeFile(inputName, await fetchFile(input)); + // Calculate height as -1 to maintain aspect ratio + const scaleFilter = `scale=${options.width}:-2`; - // Calculate height as -1 to maintain aspect ratio - const scaleFilter = `scale=${options.width}:-2`; + const args = [ + '-i', + inputName, + '-vf', + scaleFilter, + '-c:v', + 'libx264', + '-crf', + options.crf.toString(), + '-c:a', + 'aac', + '-b:a', + '128k', + outputName + ]; - const args = [ - '-i', - inputName, - '-vf', - scaleFilter, - '-c:v', - 'libx264', - '-crf', - options.crf.toString(), - '-preset', - options.preset, - '-c:a', - 'aac', // Copy audio stream - outputName - ]; - - try { await ffmpeg.exec(args); - } catch (error) { - console.error('FFmpeg execution failed:', error); - } - const compressedData = await ffmpeg.readFile(outputName); - return new File( - [new Blob([compressedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_compressed_${options.width}p.mp4`, - { type: 'video/mp4' } - ); + + const compressedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(compressedData as Uint8Array)], { + type: 'video/mp4' + }); + + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_compressed_${options.width}p.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/compress/types.ts b/src/pages/tools/video/compress/types.ts new file mode 100644 index 00000000..a197ac8c --- /dev/null +++ b/src/pages/tools/video/compress/types.ts @@ -0,0 +1,6 @@ +export type VideoResolution = 240 | 360 | 480 | 720 | 1080; + +export type InitialValuesType = { + width: VideoResolution; + crf: number; +}; From 6c30c921065eb706c3addd3494d5b135700bdae1 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Tue, 4 Aug 2026 21:20:46 +0200 Subject: [PATCH 095/114] chore: deleted test file --- .../audio-converter.service.test.ts | 95 ------------------- 1 file changed, 95 deletions(-) delete mode 100644 src/pages/tools/converters/audio-converter/audio-converter.service.test.ts diff --git a/src/pages/tools/converters/audio-converter/audio-converter.service.test.ts b/src/pages/tools/converters/audio-converter/audio-converter.service.test.ts deleted file mode 100644 index 9c232995..00000000 --- a/src/pages/tools/converters/audio-converter/audio-converter.service.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { expect, describe, it, vi, beforeEach } from 'vitest'; -import { convertAudio } from './service'; -import { InitialValuesType } from './types'; - -// Mock FFmpeg since it doesn't support Node.js in tests -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([10, 20, 30, 40, 50])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([10, 20, 30, 40, 50])) -})); - -describe('convertAudio', () => { - let mockInputFile: File; - - beforeEach(() => { - const mockAudioData = new Uint8Array([1, 2, 3, 4, 5]); - mockInputFile = new File([mockAudioData], 'input.aac', { - type: 'audio/aac' - }); - }); - - it('should convert to MP3 format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'mp3' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.mp3'); - expect(result.type).toBe('audio/mpeg'); - }); - - it('should convert to AAC format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'aac' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.aac'); - expect(result.type).toBe('audio/aac'); - }); - - it('should convert to WAV format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'wav' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.wav'); - expect(result.type).toBe('audio/wav'); - }); - - it('should convert to FLAC format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'flac' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.flac'); - expect(result.type).toBe('audio/flac'); - }); - - it('should convert to OGG format correctly', async () => { - const options: InitialValuesType = { outputFormat: 'ogg' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('input.ogg'); - expect(result.type).toBe('audio/ogg'); - }); - - it('should return original file if input format matches output format', async () => { - const options: InitialValuesType = { outputFormat: 'aac' }; - const result = await convertAudio(mockInputFile, options); - - expect(result).toBe(mockInputFile); // Same instance - expect(result.name).toBe('input.aac'); - }); - - it('should handle files without extensions', async () => { - const fileNoExt = new File([new Uint8Array([1, 2, 3])], 'audiofile', { - type: 'audio/aac' - }); - const options: InitialValuesType = { outputFormat: 'mp3' }; - const result = await convertAudio(fileNoExt, options); - - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('audiofile.mp3'); - expect(result.type).toBe('audio/mpeg'); - }); -}); From 3c0566b06832e77b4c5d93cb9ee39bcdce8640af Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 12:33:04 +0200 Subject: [PATCH 096/114] chore: crop video updated --- src/pages/tools/video/crop-video/index.tsx | 260 ++++++++++++-------- src/pages/tools/video/crop-video/service.ts | 65 +++-- 2 files changed, 190 insertions(+), 135 deletions(-) diff --git a/src/pages/tools/video/crop-video/index.tsx b/src/pages/tools/video/crop-video/index.tsx index 939bb95d..61066a8f 100644 --- a/src/pages/tools/video/crop-video/index.tsx +++ b/src/pages/tools/video/crop-video/index.tsx @@ -1,5 +1,5 @@ import { Box, Typography, TextField, Alert } from '@mui/material'; -import React, { useState, useCallback } from 'react'; +import React, { useState, useMemo, useEffect } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { cropVideo, getVideoDimensions } from './service'; @@ -19,14 +19,17 @@ const initialValues: InitialValuesType = { export default function CropVideo({ title }: ToolComponentProps) { const { t } = useTranslation('video'); + const [input, setInput] = useState(null); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); + const [videoDimensions, setVideoDimensions] = useState<{ width: number; height: number; } | null>(null); - const [processingError, setProcessingError] = useState(''); + + const [processingError, setProcessingError] = useState(''); const validateDimensions = (values: InitialValuesType): string => { if (!videoDimensions) return ''; @@ -61,6 +64,7 @@ export default function CropVideo({ title }: ToolComponentProps) { if (!input) return; const error = validateDimensions(optionsValues); + if (error) { setProcessingError(error); return; @@ -80,87 +84,146 @@ export default function CropVideo({ title }: ToolComponentProps) { } }; - // 2 seconds to avoid starting job half way through - const debouncedCompute = useCallback(debounce(compute, 2000), [ - videoDimensions - ]); + const debouncedCompute = useMemo( + () => debounce(compute, 2000), + [videoDimensions] + ); + + useEffect(() => { + return () => { + debouncedCompute.cancel(); + }; + }, [debouncedCompute]); const getGroups: GetGroupsType = ({ values, updateField - }) => [ - { - title: t('cropVideo.videoInformation'), - component: ( - - {videoDimensions ? ( - - {t('cropVideo.videoDimensions', { - width: videoDimensions.width, - height: videoDimensions.height - })} - - ) : ( - - {t('cropVideo.loadVideoForDimensions')} - - )} - - ) - }, - { - title: t('cropVideo.cropCoordinates'), - component: ( - - {processingError && ( - - {processingError} - - )} - - updateField('x', parseInt(e.target.value) || 0)} - size="small" - inputProps={{ min: 0 }} - /> - updateField('y', parseInt(e.target.value) || 0)} - size="small" - inputProps={{ min: 0 }} - /> + }) => { + const maxVideoWidth = videoDimensions?.width ?? 0; + const maxVideoHeight = videoDimensions?.height ?? 0; + + const maxX = videoDimensions + ? Math.max(0, maxVideoWidth - values.width) + : 0; + + const maxY = videoDimensions + ? Math.max(0, maxVideoHeight - values.height) + : 0; + + return [ + { + title: t('cropVideo.videoInformation'), + component: ( + + {videoDimensions ? ( + + {t('cropVideo.videoDimensions', { + width: videoDimensions.width, + height: videoDimensions.height + })} + + ) : ( + + {t('cropVideo.loadVideoForDimensions')} + + )} - - - updateField('width', parseInt(e.target.value) || 0) - } - size="small" - inputProps={{ min: 1 }} - /> - - updateField('height', parseInt(e.target.value) || 0) - } - size="small" - inputProps={{ min: 1 }} - /> + ) + }, + { + title: t('cropVideo.cropCoordinates'), + component: ( + + {processingError && ( + {processingError} + )} + + + + updateField( + 'x', + Math.max(0, Math.min(maxX, Number(e.target.value) || 0)) + ) + } + size="small" + inputProps={{ + min: 0, + max: maxX + }} + disabled={!videoDimensions} + /> + + + updateField( + 'y', + Math.max(0, Math.min(maxY, Number(e.target.value) || 0)) + ) + } + size="small" + inputProps={{ + min: 0, + max: maxY + }} + disabled={!videoDimensions} + /> + + + + { + const width = Math.max( + 1, + Math.min(maxVideoWidth, Number(e.target.value) || 1) + ); + + updateField('width', width); + updateField('x', Math.min(values.x, maxVideoWidth - width)); + }} + size="small" + inputProps={{ + min: 1, + max: maxVideoWidth + }} + disabled={!videoDimensions} + /> + + { + const height = Math.max( + 1, + Math.min(maxVideoHeight, Number(e.target.value) || 1) + ); + + updateField('height', height); + updateField('y', Math.min(values.y, maxVideoHeight - height)); + }} + size="small" + inputProps={{ + min: 1, + max: maxVideoHeight + }} + disabled={!videoDimensions} + /> + - - ) - } - ]; + ) + } + ]; + }; return ( { - const newOptions: InitialValuesType = { - x: dimensions.width / 4, - y: dimensions.height / 4, - width: dimensions.width / 2, - height: dimensions.height / 2 + const newValues: InitialValuesType = { + x: Math.floor(dimensions.width / 4), + y: Math.floor(dimensions.height / 4), + width: Math.floor(dimensions.width / 2), + height: Math.floor(dimensions.height / 2) }; - setFieldValue('x', newOptions.x); - setFieldValue('y', newOptions.y); - setFieldValue('width', newOptions.width); - setFieldValue('height', newOptions.height); + + setFieldValue('x', newValues.x); + setFieldValue('y', newValues.y); + setFieldValue('width', newValues.width); + setFieldValue('height', newValues.height); setVideoDimensions(dimensions); setProcessingError(''); }) - .catch((error) => { - console.error('Error getting video dimensions:', error); + .catch(() => { setProcessingError(t('cropVideo.errorLoadingDimensions')); }); } else { setVideoDimensions(null); setProcessingError(''); } + setInput(video); }} title={t('cropVideo.inputTitle')} /> )} resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} diff --git a/src/pages/tools/video/crop-video/service.ts b/src/pages/tools/video/crop-video/service.ts index de664ad3..704537f5 100644 --- a/src/pages/tools/video/crop-video/service.ts +++ b/src/pages/tools/video/crop-video/service.ts @@ -1,9 +1,7 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import { InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - export async function getVideoDimensions( file: File ): Promise<{ width: number; height: number }> { @@ -32,36 +30,37 @@ export async function cropVideo( input: File, options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const args = []; + + if (options.width <= 0 || options.height <= 0) { + throw new Error('Width and height must be positive'); + } + + args.push('-i', inputName); + args.push( + '-vf', + `crop=${options.width}:${options.height}:${options.x}:${options.y}` + ); + args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); + + await ffmpeg.exec(args); + + const croppedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(croppedData as Uint8Array)], { + type: 'video/mp4' }); - } - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const args = []; - - if (options.width <= 0 || options.height <= 0) { - throw new Error('Width and height must be positive'); - } - - args.push('-i', inputName); - args.push( - '-vf', - `crop=${options.width}:${options.height}:${options.x}:${options.y}` - ); - args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); - - await ffmpeg.exec(args); - - const croppedData = await ffmpeg.readFile(outputName); - return await new File( - [new Blob([croppedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_cropped.mp4`, - { type: 'video/mp4' } - ); + return await new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_cropped.mp4`, + { type: 'video/mp4' } + ); + }); } From 1b1e26c0da8005f398e26c9c822aae10f23484fb Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 13:22:16 +0200 Subject: [PATCH 097/114] chore: flip video updated --- public/locales/en/video.json | 1 - src/pages/tools/video/flip/index.tsx | 20 +++------ src/pages/tools/video/flip/service.ts | 64 +++++++++++++-------------- 3 files changed, 37 insertions(+), 48 deletions(-) diff --git a/public/locales/en/video.json b/public/locales/en/video.json index 7ed1d9ef..0bc690fa 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -83,7 +83,6 @@ }, "flip": { "description": "Flip video files horizontally or vertically. Mirror videos for special effects or correct orientation issues.", - "flippingVideo": "Flipping Video", "horizontalLabel": "Horizontal (Mirror)", "inputTitle": "Input Video", "orientation": "Orientation", diff --git a/src/pages/tools/video/flip/index.tsx b/src/pages/tools/video/flip/index.tsx index eef36b1c..60e98de1 100644 --- a/src/pages/tools/video/flip/index.tsx +++ b/src/pages/tools/video/flip/index.tsx @@ -90,20 +90,12 @@ export default function FlipVideo({ title }: ToolComponentProps) { /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} diff --git a/src/pages/tools/video/flip/service.ts b/src/pages/tools/video/flip/service.ts index 37f53d47..0a7d4556 100644 --- a/src/pages/tools/video/flip/service.ts +++ b/src/pages/tools/video/flip/service.ts @@ -1,43 +1,41 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import { FlipOrientation } from './types'; -const ffmpeg = new FFmpeg(); +const flipMap: Record = { + horizontal: 'hflip', + vertical: 'vflip' +}; export async function flipVideo( input: File, orientation: FlipOrientation ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const flipFilter = flipMap[orientation]; + + const args = ['-i', inputName]; + if (flipFilter) { + args.push('-vf', flipFilter); + } + + args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); + + await ffmpeg.exec(args); + + const flippedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(flippedData as Uint8Array)], { + type: 'video/mp4' }); - } - - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const flipMap: Record = { - horizontal: 'hflip', - vertical: 'vflip' - }; - const flipFilter = flipMap[orientation]; - - const args = ['-i', inputName]; - if (flipFilter) { - args.push('-vf', flipFilter); - } - - args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); - - await ffmpeg.exec(args); - - const flippedData = await ffmpeg.readFile(outputName); - return new File( - [new Blob([flippedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_flipped.mp4`, - { type: 'video/mp4' } - ); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_flipped.mp4`, + { type: 'video/mp4' } + ); + }); } From d10aafc19044948a8c2bc99f11996623ef69b367 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 13:42:26 +0200 Subject: [PATCH 098/114] chore: loop video updated --- src/pages/tools/video/loop/index.tsx | 46 ++++++++++---------- src/pages/tools/video/loop/service.ts | 61 +++++++++++++-------------- 2 files changed, 51 insertions(+), 56 deletions(-) diff --git a/src/pages/tools/video/loop/index.tsx b/src/pages/tools/video/loop/index.tsx index 8c23d9fa..d635afb8 100644 --- a/src/pages/tools/video/loop/index.tsx +++ b/src/pages/tools/video/loop/index.tsx @@ -1,9 +1,8 @@ import { Box } from '@mui/material'; -import { useState } from 'react'; +import { useState, useCallback } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; -import { CardExampleType } from '@components/examples/ToolExamples'; import { loopVideo } from './service'; import { InitialValuesType } from './types'; import ToolVideoInput from '@components/input/ToolVideoInput'; @@ -12,6 +11,7 @@ import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { updateNumberField } from '@utils/string'; import * as Yup from 'yup'; import { useTranslation } from 'react-i18next'; +import { debounce } from 'lodash'; const initialValues: InitialValuesType = { loops: 2 @@ -21,7 +21,7 @@ const validationSchema = Yup.object({ loops: Yup.number().min(1, 'Number of loops must be greater than 1') }); -export default function Loop({ title, longDescription }: ToolComponentProps) { +export default function Loop({ title }: ToolComponentProps) { const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); @@ -32,7 +32,7 @@ export default function Loop({ title, longDescription }: ToolComponentProps) { try { setLoading(true); const resultFile = await loopVideo(input, values); - await setResult(resultFile); + setResult(resultFile); } catch (error) { console.error(error); } finally { @@ -40,6 +40,8 @@ export default function Loop({ title, longDescription }: ToolComponentProps) { } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); + const getGroups: GetGroupsType | null = ({ values, updateField @@ -50,10 +52,18 @@ export default function Loop({ title, longDescription }: ToolComponentProps) { - updateNumberField(value, 'loops', updateField) + updateNumberField( + String(Math.max(1, Number(value) || 1)), + 'loops', + updateField + ) } value={values.loops} label={t('loop.numberOfLoops')} + type="number" + inputProps={{ + min: 1 + }} /> ) @@ -65,30 +75,18 @@ export default function Loop({ title, longDescription }: ToolComponentProps) { input={input} inputComponent={} resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} validationSchema={validationSchema} getGroups={getGroups} setInput={setInput} - compute={compute} - toolInfo={{ - title: t('loop.toolInfo.title', { title }), - description: longDescription - }} + compute={debouncedCompute} /> ); } diff --git a/src/pages/tools/video/loop/service.ts b/src/pages/tools/video/loop/service.ts index 5478853e..b237d46c 100644 --- a/src/pages/tools/video/loop/service.ts +++ b/src/pages/tools/video/loop/service.ts @@ -1,41 +1,38 @@ import { InitialValuesType } from './types'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; -const ffmpeg = new FFmpeg(); - export async function loopVideo( input: File, options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const args = []; + const loopCount = options.loops - 1; + + if (loopCount <= 0) { + return input; + } + + args.push('-stream_loop', loopCount.toString()); + args.push('-i', inputName); + args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); + + await ffmpeg.exec(args); + + const loopedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(loopedData as Uint8Array)], { + type: 'video/mp4' }); - } - - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const args = []; - const loopCount = options.loops - 1; - - if (loopCount <= 0) { - return input; - } - - args.push('-stream_loop', loopCount.toString()); - args.push('-i', inputName); - args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); - - await ffmpeg.exec(args); - - const loopedData = await ffmpeg.readFile(outputName); - return await new File( - [new Blob([loopedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_looped.mp4`, - { type: 'video/mp4' } - ); + return await new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_looped.mp4`, + { type: 'video/mp4' } + ); + }); } From 925403cc4bda7815382755b7d97d7ebaa61ef590 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 13:47:20 +0200 Subject: [PATCH 099/114] chore: i8n updates --- public/locales/en/video.json | 3 +-- src/pages/tools/video/loop/index.tsx | 4 ++++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/public/locales/en/video.json b/public/locales/en/video.json index 0bc690fa..bf71e36b 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -101,7 +101,6 @@ "loop": { "description": "Create a looping video by repeating the original video multiple times.", "inputTitle": "Input Video", - "loopingVideo": "Looping Video", "loops": "Loops", "numberOfLoops": "Number of Loops", "resultTitle": "Looped Video", @@ -109,7 +108,7 @@ "title": "Loop Video", "toolInfo": { "description": "This tool allows you to create a looping video by repeating the original video multiple times. You can specify how many times the video should loop.", - "title": "What is a {{title}}?" + "title": "What is {{title}}?" } }, "mergeVideo": { diff --git a/src/pages/tools/video/loop/index.tsx b/src/pages/tools/video/loop/index.tsx index d635afb8..cc3722f2 100644 --- a/src/pages/tools/video/loop/index.tsx +++ b/src/pages/tools/video/loop/index.tsx @@ -87,6 +87,10 @@ export default function Loop({ title }: ToolComponentProps) { getGroups={getGroups} setInput={setInput} compute={debouncedCompute} + toolInfo={{ + title: t('loop.toolInfo.title', { title }), + description: t('loop.toolInfo.description') + }} /> ); } From 18f8b7e6ec45eaf9d89a2a8ed80aa6b8f3a358e9 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 15:32:19 +0200 Subject: [PATCH 100/114] chore: await removed where not needed --- src/pages/tools/video/loop/service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/tools/video/loop/service.ts b/src/pages/tools/video/loop/service.ts index b237d46c..002a8193 100644 --- a/src/pages/tools/video/loop/service.ts +++ b/src/pages/tools/video/loop/service.ts @@ -29,7 +29,7 @@ export async function loopVideo( const blob = new Blob([new Uint8Array(loopedData as Uint8Array)], { type: 'video/mp4' }); - return await new File( + return new File( [blob], `${input.name.replace(/\.[^/.]+$/, '')}_looped.mp4`, { type: 'video/mp4' } From 42fa7bf854cdf52bfbcbf2dc1d28a18db074184c Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 15:37:10 +0200 Subject: [PATCH 101/114] chore: merge video updated --- public/locales/en/video.json | 4 +- src/pages/tools/video/merge-video/index.tsx | 25 ++- .../merge-video/merge-video.service.test.ts | 62 ------- src/pages/tools/video/merge-video/service.ts | 160 +++++------------- src/pages/tools/video/merge-video/types.ts | 9 - 5 files changed, 59 insertions(+), 201 deletions(-) delete mode 100644 src/pages/tools/video/merge-video/merge-video.service.test.ts delete mode 100644 src/pages/tools/video/merge-video/types.ts diff --git a/public/locales/en/video.json b/public/locales/en/video.json index bf71e36b..e477015d 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -115,7 +115,9 @@ "description": "Combine multiple video files into one continuous video.", "longDescription": "This tool allows you to merge or append multiple video files into a single continuous video. Simply upload your video files, arrange them in the desired order, and merge them into one file for easy sharing or editing.", "shortDescription": "Append and merge videos easily.", - "title": "Merge videos" + "title": "Merge videos", + "inputTitle": "Input Videos", + "resultTitle": "Merged Video" }, "rotate": { "180Degrees": "180° (Upside down)", diff --git a/src/pages/tools/video/merge-video/index.tsx b/src/pages/tools/video/merge-video/index.tsx index 8a7de659..57d77f02 100644 --- a/src/pages/tools/video/merge-video/index.tsx +++ b/src/pages/tools/video/merge-video/index.tsx @@ -1,4 +1,3 @@ -import { Box } from '@mui/material'; import React, { useState } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; @@ -7,14 +6,17 @@ import ToolMultipleVideoInput, { MultiVideoInput } from '@components/input/ToolMultipleVideoInput'; import { mergeVideos } from './service'; -import { InitialValuesType } from './types'; +import { useTranslation } from 'react-i18next'; -const initialValues: InitialValuesType = {}; +const initialValues = {}; + +type InitialValuesType = typeof initialValues; export default function MergeVideo({ title, longDescription }: ToolComponentProps) { + const { t } = useTranslation('video'); const [input, setInput] = useState([]); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); @@ -28,12 +30,9 @@ export default function MergeVideo({ } setLoading(true); try { - const files = input.map((item) => item.file); - const mergedBlob = await mergeVideos(files, initialValues); - const mergedFile = new File([mergedBlob], 'merged-video.mp4', { - type: 'video/mp4' - }); - setResult(mergedFile); + const resultFile = await mergeVideos(input.map((item) => item.file)); + + setResult(resultFile); } catch (err) { setResult(null); } finally { @@ -51,15 +50,15 @@ export default function MergeVideo({ onChange={(newInput) => { setInput(newInput); }} - accept={['video/*', '.mp4', '.avi', '.mov', '.mkv']} - title="Input Videos" + accept={['video/*']} + title={t('mergeVideo.inputTitle')} type="video" /> } resultComponent={ @@ -68,7 +67,7 @@ export default function MergeVideo({ getGroups={null} setInput={setInput} compute={compute} - toolInfo={{ title: `What is a ${title}?`, description: longDescription }} + toolInfo={{ title: `${title} ?`, description: longDescription }} /> ); } diff --git a/src/pages/tools/video/merge-video/merge-video.service.test.ts b/src/pages/tools/video/merge-video/merge-video.service.test.ts deleted file mode 100644 index 311c0673..00000000 --- a/src/pages/tools/video/merge-video/merge-video.service.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { expect, describe, it, vi } from 'vitest'; - -// Mock FFmpeg and fetchFile to avoid Node.js compatibility issues -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4])) -})); - -// Import after mocking -import { mergeVideos } from './service'; - -function createMockFile(name: string, type = 'video/mp4') { - return new File([new Uint8Array([0, 1, 2])], name, { type }); -} - -describe('merge-video', () => { - it('throws if less than two files are provided', async () => { - await expect(mergeVideos([], {})).rejects.toThrow( - 'Please provide at least two video files to merge.' - ); - await expect(mergeVideos([createMockFile('a.mp4')], {})).rejects.toThrow( - 'Please provide at least two video files to merge.' - ); - }); - - it('throws if input is not an array', async () => { - // @ts-ignore - testing invalid input - await expect(mergeVideos(null, {})).rejects.toThrow( - 'Please provide at least two video files to merge.' - ); - }); - - it('successfully merges video files (mocked)', async () => { - const mockFile1 = createMockFile('video1.mp4'); - const mockFile2 = createMockFile('video2.mp4'); - - const result = await mergeVideos([mockFile1, mockFile2], {}); - - expect(result).toBeInstanceOf(Blob); - expect(result.type).toBe('video/mp4'); - }); - - it('handles different video formats by re-encoding', async () => { - const mockFile1 = createMockFile('video1.avi', 'video/x-msvideo'); - const mockFile2 = createMockFile('video2.mov', 'video/quicktime'); - - const result = await mergeVideos([mockFile1, mockFile2], {}); - - expect(result).toBeInstanceOf(Blob); - expect(result.type).toBe('video/mp4'); - }); -}); diff --git a/src/pages/tools/video/merge-video/service.ts b/src/pages/tools/video/merge-video/service.ts index 6089125b..0ca3916c 100644 --- a/src/pages/tools/video/merge-video/service.ts +++ b/src/pages/tools/video/merge-video/service.ts @@ -1,134 +1,62 @@ -import { InitialValuesType, MergeVideoInput, MergeVideoOutput } from './types'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; -export async function mergeVideos( - input: MergeVideoInput, - options: InitialValuesType -): Promise { +export async function mergeVideos(input: File[]): Promise { if (!Array.isArray(input) || input.length < 2) { throw new Error('Please provide at least two video files to merge.'); } - // Create a new FFmpeg instance for each operation to avoid conflicts - const ffmpeg = new FFmpeg(); + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const fileNames: string[] = []; + const outputName = tempFile('.mp4'); + const concatListName = tempFile('.txt'); - const fileNames: string[] = []; - const outputName = 'output.mp4'; - - try { - // Load FFmpeg with proper error handling - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm', - workerURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.worker.js' - }); - } - - // Write all input files to ffmpeg FS with better error handling for (let i = 0; i < input.length; i++) { - const fileName = `input${i}.mp4`; + const fileName = tempFile('.mp4'); + fileNames.push(fileName); - try { - const fileData = await fetchFile(input[i]); - await ffmpeg.writeFile(fileName, fileData); - console.log(`Successfully wrote ${fileName}`); - } catch (fileError) { - console.error(`Failed to write ${fileName}:`, fileError); - throw new Error(`Failed to process input file ${i + 1}: ${fileError}`); - } + await ffmpeg.writeFile(fileName, await fetchFile(input[i])); } - // Build the filter_complex string for concat filter - const videoInputs = fileNames.map((_, idx) => `[${idx}:v]`).join(' '); - const audioInputs = fileNames.map((_, idx) => `[${idx}:a]`).join(' '); - const filterComplex = `${videoInputs} ${audioInputs} concat=n=${input.length}:v=1:a=1 [v] [a]`; + // Create concat file + const concatList = fileNames.map((name) => `file '${name}'`).join('\n'); - // Build input arguments - const inputArgs = []; - for (const fileName of fileNames) { - inputArgs.push('-i', fileName); - } + await ffmpeg.writeFile( + concatListName, + new TextEncoder().encode(concatList) + ); - console.log('Starting FFmpeg processing...'); - console.log('Filter complex:', filterComplex); + await ffmpeg.exec([ + '-f', + 'concat', + '-safe', + '0', + '-i', + concatListName, + '-c:v', + 'libx264', + '-preset', + 'ultrafast', + '-crf', + '30', + '-c:a', + 'aac', + outputName + ]); - // Method 2: Fallback to concat demuxer - try { - console.log('Trying concat demuxer method...'); + const data = await ffmpeg.readFile(outputName); - const concatList = fileNames.map((name) => `file '${name}'`).join('\n'); - await ffmpeg.writeFile( - 'concat_list.txt', - new TextEncoder().encode(concatList) - ); + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'video/mp4' + }); - await ffmpeg.exec([ - '-f', - 'concat', - '-safe', - '0', - '-i', - 'concat_list.txt', - '-c:v', - 'libx264', - '-preset', - 'ultrafast', - '-crf', - '30', - '-threads', - '0', - '-y', - outputName - ]); - - // Check if output was created - try { - const testRead = await ffmpeg.readFile(outputName); - if (testRead && testRead.length > 0) { - console.log('Concat demuxer method succeeded'); - } - } catch (readError) { - console.log('Concat demuxer method failed to produce output'); - } - } catch (execError) { - console.error('Concat demuxer method failed:', execError); - } - - // Check if output file exists and read it - let mergedData; - try { - mergedData = await ffmpeg.readFile(outputName); - console.log('Successfully read output file'); - } catch (readError) { - console.error('Failed to read output file:', readError); - throw new Error('Failed to read merged video file'); - } - - if (!mergedData || mergedData.length === 0) { - throw new Error('Output file is empty or corrupted'); - } - - return new Blob([mergedData as any], { type: 'video/mp4' }); - } catch (error) { - console.error('Error merging videos:', error); - throw error instanceof Error - ? error - : new Error('Unknown error occurred during video merge'); - } finally { - // Clean up temporary files with better error handling - const filesToClean = [...fileNames, outputName, 'concat_list.txt']; - - for (const fileName of filesToClean) { - try { - await ffmpeg.deleteFile(fileName); - } catch (cleanupError) { - // Ignore cleanup errors - they're not critical - console.warn(`Could not delete ${fileName}:`, cleanupError); - } - } - } + return new File( + [blob], + `${input[0].name.replace(/\.[^/.]+$/, '')}_merged_with_${ + input.length - 1 + }_videos.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/merge-video/types.ts b/src/pages/tools/video/merge-video/types.ts deleted file mode 100644 index 7cb6a522..00000000 --- a/src/pages/tools/video/merge-video/types.ts +++ /dev/null @@ -1,9 +0,0 @@ -export type InitialValuesType = { - // Add any future options here (e.g., output format, resolution) -}; - -// Type for the main function input -export type MergeVideoInput = File[]; - -// Type for the main function output -export type MergeVideoOutput = Blob; From 00f575fffeae5656c965d23e8b41af2843cfb11a Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 15:40:29 +0200 Subject: [PATCH 102/114] chore: edge case handled in the index --- src/pages/tools/video/merge-video/service.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/pages/tools/video/merge-video/service.ts b/src/pages/tools/video/merge-video/service.ts index 0ca3916c..d2fec2e5 100644 --- a/src/pages/tools/video/merge-video/service.ts +++ b/src/pages/tools/video/merge-video/service.ts @@ -2,10 +2,6 @@ import { fetchFile } from '@ffmpeg/util'; import { runFFmpegTask } from 'lib/ffmpeg'; export async function mergeVideos(input: File[]): Promise { - if (!Array.isArray(input) || input.length < 2) { - throw new Error('Please provide at least two video files to merge.'); - } - return runFFmpegTask(async ({ ffmpeg, tempFile }) => { const fileNames: string[] = []; const outputName = tempFile('.mp4'); From e0b8e9fcb39f9dd24d8ea31dd7d0a02db2c5972e Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 19:44:15 +0200 Subject: [PATCH 103/114] chore: rotate video updated --- public/locales/en/video.json | 1 - src/pages/tools/video/rotate/index.tsx | 32 +++++------ src/pages/tools/video/rotate/service.ts | 72 +++++++++++++------------ src/pages/tools/video/rotate/types.ts | 5 ++ 4 files changed, 54 insertions(+), 56 deletions(-) create mode 100644 src/pages/tools/video/rotate/types.ts diff --git a/public/locales/en/video.json b/public/locales/en/video.json index e477015d..3c529e84 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -126,7 +126,6 @@ "description": "Rotate video files by 90, 180, or 270 degrees. Correct video orientation or create special effects with precise rotation control.", "inputTitle": "Input Video", "resultTitle": "Rotated Video", - "rotatingVideo": "Rotating Video", "rotation": "Rotation", "shortDescription": "Rotate video by specified degrees", "title": "Rotate Video" diff --git a/src/pages/tools/video/rotate/index.tsx b/src/pages/tools/video/rotate/index.tsx index 32c66646..23a7fb4d 100644 --- a/src/pages/tools/video/rotate/index.tsx +++ b/src/pages/tools/video/rotate/index.tsx @@ -8,17 +8,17 @@ import { GetGroupsType } from '@components/options/ToolOptions'; import { debounce } from 'lodash'; import ToolVideoInput from '@components/input/ToolVideoInput'; import { rotateVideo } from './service'; -import { RotationAngle } from '../../pdf/rotate-pdf/types'; import SimpleRadio from '@components/options/SimpleRadio'; import { useTranslation } from 'react-i18next'; +import { InitialValuesType, RotationAngle } from './types'; -export const initialValues = { +export const initialValues: InitialValuesType = { rotation: 90 }; export const validationSchema = Yup.object({ rotation: Yup.number() - .oneOf([0, 90, 180, 270], 'Rotation must be 0, 90, 180, or 270 degrees') + .oneOf([90, 180, 270], 'Rotation must be 90, 180, or 270 degrees') .required('Rotation is required') }); @@ -34,14 +34,14 @@ export default function RotateVideo({ title }: ToolComponentProps) { const [loading, setLoading] = useState(false); const compute = async ( - optionsValues: typeof initialValues, + optionsValues: InitialValuesType, input: File | null ) => { if (!input) return; setLoading(true); try { - const rotatedFile = await rotateVideo(input, optionsValues.rotation); + const rotatedFile = await rotateVideo(input, optionsValues); setResult(rotatedFile); } catch (error) { console.error('Error rotating video:', error); @@ -52,7 +52,7 @@ export default function RotateVideo({ title }: ToolComponentProps) { const debouncedCompute = useCallback(debounce(compute, 1000), []); - const getGroups: GetGroupsType = ({ + const getGroups: GetGroupsType = ({ values, updateField }) => [ @@ -87,20 +87,12 @@ export default function RotateVideo({ title }: ToolComponentProps) { /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} diff --git a/src/pages/tools/video/rotate/service.ts b/src/pages/tools/video/rotate/service.ts index 30e5665d..f27d343b 100644 --- a/src/pages/tools/video/rotate/service.ts +++ b/src/pages/tools/video/rotate/service.ts @@ -1,44 +1,46 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { RotationAngle, InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); +const rotateMap: Record = { + 90: 'transpose=1', + 180: 'transpose=2,transpose=2', + 270: 'transpose=2' +}; export async function rotateVideo( input: File, - rotation: number + options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const { rotation } = options; + + const rotateFilter = rotateMap[rotation]; + + const args = ['-i', inputName]; + if (rotateFilter) { + args.push('-vf', rotateFilter); + } + + args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); + + await ffmpeg.exec(args); + + const rotatedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(rotatedData as Uint8Array)], { + type: 'video/mp4' }); - } - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const rotateMap: Record = { - 90: 'transpose=1', - 180: 'transpose=2,transpose=2', - 270: 'transpose=2', - 0: '' - }; - const rotateFilter = rotateMap[rotation]; - - const args = ['-i', inputName]; - if (rotateFilter) { - args.push('-vf', rotateFilter); - } - - args.push('-c:v', 'libx264', '-preset', 'ultrafast', outputName); - - await ffmpeg.exec(args); - - const rotatedData = await ffmpeg.readFile(outputName); - return new File( - [new Blob([rotatedData as any], { type: 'video/mp4' })], - `${input.name.replace(/\.[^/.]+$/, '')}_rotated.mp4`, - { type: 'video/mp4' } - ); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_rotated.mp4`, + { type: 'video/mp4' } + ); + }); } diff --git a/src/pages/tools/video/rotate/types.ts b/src/pages/tools/video/rotate/types.ts new file mode 100644 index 00000000..982c3185 --- /dev/null +++ b/src/pages/tools/video/rotate/types.ts @@ -0,0 +1,5 @@ +export type RotationAngle = 270 | 180 | 90; + +export type InitialValuesType = { + rotation: RotationAngle; +}; From 8fd30960b94c81884e2ea454d86b925d312d159e Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 20:11:58 +0200 Subject: [PATCH 104/114] chore: trim video updated --- src/pages/tools/video/trim/index.tsx | 87 +++++++++------------------ src/pages/tools/video/trim/service.ts | 42 +++++++++++++ src/pages/tools/video/trim/types.ts | 4 ++ 3 files changed, 74 insertions(+), 59 deletions(-) create mode 100644 src/pages/tools/video/trim/service.ts create mode 100644 src/pages/tools/video/trim/types.ts diff --git a/src/pages/tools/video/trim/index.tsx b/src/pages/tools/video/trim/index.tsx index a3fefcc3..f5af1863 100644 --- a/src/pages/tools/video/trim/index.tsx +++ b/src/pages/tools/video/trim/index.tsx @@ -7,23 +7,21 @@ import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { updateNumberField } from '@utils/string'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; +import { trimVideo } from './service'; +import { InitialValuesType } from './types'; import { debounce } from 'lodash'; import ToolVideoInput from '@components/input/ToolVideoInput'; import { useTranslation } from 'react-i18next'; -const ffmpeg = new FFmpeg(); - -const initialValues = { - trimStart: 0, - trimEnd: 100 +const initialValues: InitialValuesType = { + start: 0, + end: 100 }; const validationSchema = Yup.object({ - trimStart: Yup.number().min(0, 'Start time must be positive'), - trimEnd: Yup.number().min( - Yup.ref('trimStart'), + start: Yup.number().min(0, 'Start time must be positive'), + end: Yup.number().min( + Yup.ref('start'), 'End time must be greater than start time' ) }); @@ -32,57 +30,27 @@ export default function TrimVideo({ title }: ToolComponentProps) { const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); + const [loading, setLoading] = useState(false); const compute = async ( - optionsValues: typeof initialValues, + optionsValues: InitialValuesType, input: File | null ) => { if (!input) return; - - const { trimStart, trimEnd } = optionsValues; + setLoading(true); try { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - } - - const inputName = 'input.mp4'; - const outputName = 'output.mp4'; - // Load file into FFmpeg's virtual filesystem - await ffmpeg.writeFile(inputName, await fetchFile(input)); - // Run FFmpeg command to trim video - await ffmpeg.exec([ - '-i', - inputName, - '-ss', - trimStart.toString(), - '-to', - trimEnd.toString(), - '-c', - 'copy', - outputName - ]); - // Retrieve the processed file - const trimmedData = await ffmpeg.readFile(outputName); - const trimmedBlob = new Blob([trimmedData as any], { type: 'video/mp4' }); - const trimmedFile = new File( - [trimmedBlob], - `${input.name.replace(/\.[^/.]+$/, '')}_trimmed.mp4`, - { - type: 'video/mp4' - } - ); - - setResult(trimmedFile); + const resultFile = await trimVideo(input, optionsValues); + setResult(resultFile); } catch (error) { console.error('Error trimming video:', error); + } finally { + setLoading(false); } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); - const getGroups: GetGroupsType = ({ + const getGroups: GetGroupsType = ({ values, updateField }) => [ @@ -92,17 +60,17 @@ export default function TrimVideo({ title }: ToolComponentProps) { - updateNumberField(value, 'trimStart', updateField) + updateNumberField(value, 'start', updateField) } - value={values.trimStart} + value={Number(values.start)} label={t('trim.startTime')} sx={{ mb: 2, backgroundColor: 'background.paper' }} /> - updateNumberField(value, 'trimEnd', updateField) + updateNumberField(value, 'end', updateField) } - value={values.trimEnd} + value={Number(values.end)} label={t('trim.endTime')} /> @@ -113,19 +81,19 @@ export default function TrimVideo({ title }: ToolComponentProps) { { + renderCustomInput={({ start, end }, setFieldValue) => { return ( { - setFieldValue('trimStart', trimStart); - setFieldValue('trimEnd', trimEnd); + onTrimChange={(start, end) => { + setFieldValue('start', start); + setFieldValue('end', end); }} - trimStart={trimStart} - trimEnd={trimEnd} + trimStart={Number(start)} + trimEnd={Number(end)} /> ); }} @@ -133,6 +101,7 @@ export default function TrimVideo({ title }: ToolComponentProps) { } diff --git a/src/pages/tools/video/trim/service.ts b/src/pages/tools/video/trim/service.ts new file mode 100644 index 00000000..af05218e --- /dev/null +++ b/src/pages/tools/video/trim/service.ts @@ -0,0 +1,42 @@ +import { InitialValuesType } from './types'; +import { fetchFile } from '@ffmpeg/util'; +import { runFFmpegTask } from 'lib/ffmpeg'; + +export async function trimVideo( + input: File, + options: InitialValuesType +): Promise { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { start, end } = options; + + const inputName = tempFile('.mp4'); + const outputName = tempFile('.mp4'); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + await ffmpeg.exec([ + '-i', + inputName, + '-ss', + start.toString(), + '-to', + end.toString(), + '-c', + 'copy', + outputName + ]); + + const trimmedData = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(trimmedData as Uint8Array)], { + type: 'video/mp4' + }); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_trimmed.mp4`, + { + type: 'video/mp4' + } + ); + }); +} diff --git a/src/pages/tools/video/trim/types.ts b/src/pages/tools/video/trim/types.ts new file mode 100644 index 00000000..d45ce19d --- /dev/null +++ b/src/pages/tools/video/trim/types.ts @@ -0,0 +1,4 @@ +export type InitialValuesType = { + start: Number; + end: number; +}; From 0dd15b934efaab386fd1deeb00293df3fa9931cf Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 21:40:17 +0200 Subject: [PATCH 105/114] chore: video to gif updated --- public/locales/en/video.json | 14 +- src/pages/tools/video/video-to-gif/index.tsx | 191 ++++-------------- src/pages/tools/video/video-to-gif/service.ts | 55 +++++ src/pages/tools/video/video-to-gif/types.ts | 31 ++- 4 files changed, 135 insertions(+), 156 deletions(-) create mode 100644 src/pages/tools/video/video-to-gif/service.ts diff --git a/public/locales/en/video.json b/public/locales/en/video.json index 3c529e84..2378dce9 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -143,6 +143,18 @@ "videoToGif": { "description": "Convert video files to animated GIF format. Extract specific time ranges and create shareable animated images.", "shortDescription": "Convert video to animated GIF", - "title": "Video to GIF" + "title": "Video to GIF", + "inputTitle": "Input Video", + "resultTitle": "Output GIF", + "options": { + "quality": "Quality", + "low": "Low", + "mid": "Medium", + "high": "High", + "ultra": "Ultra", + "timestamps": "Timestamps", + "startTime": "Start Time", + "endTime": "End Time" + } } } diff --git a/src/pages/tools/video/video-to-gif/index.tsx b/src/pages/tools/video/video-to-gif/index.tsx index 4c0f61bc..b301d03f 100644 --- a/src/pages/tools/video/video-to-gif/index.tsx +++ b/src/pages/tools/video/video-to-gif/index.tsx @@ -1,172 +1,67 @@ import { Box } from '@mui/material'; -import React, { useState } from 'react'; -import * as Yup from 'yup'; +import React, { useState, useCallback } from 'react'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { updateNumberField } from '@utils/string'; -import { InitialValuesType } from './types'; +import { InitialValuesType, GIF_PRESETS, Quality } from './types'; import ToolVideoInput from '@components/input/ToolVideoInput'; import ToolFileResult from '@components/result/ToolFileResult'; import SimpleRadio from '@components/options/SimpleRadio'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; +import { useTranslation } from 'react-i18next'; +import { debounce } from 'lodash'; +import { videoToGif } from './service'; const initialValues: InitialValuesType = { quality: 'mid', - fps: '10', - scale: '320:-1:flags=bicubic', start: 0, end: 100 }; -const validationSchema = Yup.object({ - start: Yup.number().min(0, 'Start time must be positive'), - end: Yup.number().min( - Yup.ref('start'), - 'End time must be greater than start time' - ) -}); - -export default function VideoToGif({ - title, - longDescription -}: ToolComponentProps) { +export default function VideoToGif({ title }: ToolComponentProps) { + const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); - const compute = (values: InitialValuesType, input: File | null) => { + const compute = async (values: InitialValuesType, input: File | null) => { if (!input) return; - const { fps, scale, start, end } = values; - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; + setLoading(true); - const convertVideoToGif = async ( - file: File, - fps: string, - scale: string, - start: number, - end: number - ): Promise => { - setLoading(true); - - if (!ffmpeg) { - ffmpeg = new FFmpeg(); - } - - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - - const fileName = file.name; - const outputName = 'output.gif'; - - try { - ffmpeg.writeFile(fileName, await fetchFile(file)); - - await ffmpeg.exec([ - '-i', - fileName, - '-ss', - start.toString(), - '-to', - end.toString(), - '-vf', - `fps=${fps},scale=${scale},palettegen`, - 'palette.png' - ]); - - await ffmpeg.exec([ - '-i', - fileName, - '-i', - 'palette.png', - '-ss', - start.toString(), - '-to', - end.toString(), - '-filter_complex', - `fps=${fps},scale=${scale}[x];[x][1:v]paletteuse`, - outputName - ]); - - const data = await ffmpeg.readFile(outputName); - - const blob = new Blob([data as any], { type: 'image/gif' }); - const convertedFile = new File([blob], outputName, { - type: 'image/gif' - }); - - await ffmpeg.deleteFile(fileName); - await ffmpeg.deleteFile(outputName); - - setResult(convertedFile); - } catch (err) { - console.error(`Failed to convert video: ${err}`); - throw err; - } finally { - setLoading(false); - } - }; - - convertVideoToGif(input, fps, scale, start, end); + try { + const resultFile = await videoToGif(input, values); + setResult(resultFile); + } catch (error) { + console.error('Error converting video to gif:', error); + } finally { + setLoading(false); + } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); + const getGroups: GetGroupsType | null = ({ values, updateField }) => [ { - title: 'Set Quality', + title: t('videoToGif.options.quality'), component: ( - { - updateField('quality', 'low'); - updateField('fps', '5'); - updateField('scale', '240:-1:flags=bilinear'); - }} - checked={values.quality === 'low'} - /> - { - updateField('quality', 'mid'); - updateField('fps', '10'); - updateField('scale', '320:-1:flags=bicubic'); - }} - checked={values.quality === 'mid'} - /> - { - updateField('quality', 'high'); - updateField('fps', '15'); - updateField('scale', '480:-1:flags=lanczos'); - }} - checked={values.quality === 'high'} - /> - { - updateField('quality', 'ultra'); - updateField('fps', '15'); - updateField('scale', '640:-1:flags=lanczos'); - }} - checked={values.quality === 'ultra'} - /> + {(Object.keys(GIF_PRESETS) as Quality[]).map((quality) => ( + updateField('quality', quality)} + /> + ))} ) }, { - title: 'Timestamps', + title: t('videoToGif.options.timestamps'), component: ( ) @@ -198,7 +93,7 @@ export default function VideoToGif({ { setFieldValue('start', start); @@ -210,25 +105,17 @@ export default function VideoToGif({ ); }} resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} setInput={setInput} - compute={compute} - toolInfo={{ title: `What is a ${title}?`, description: longDescription }} + compute={debouncedCompute} /> ); } diff --git a/src/pages/tools/video/video-to-gif/service.ts b/src/pages/tools/video/video-to-gif/service.ts new file mode 100644 index 00000000..6af26f02 --- /dev/null +++ b/src/pages/tools/video/video-to-gif/service.ts @@ -0,0 +1,55 @@ +import { runFFmpegTask } from 'lib/ffmpeg'; +import { fetchFile } from '@ffmpeg/util'; +import { GIF_PRESETS, InitialValuesType } from './types'; + +export const videoToGif = async ( + input: File, + options: InitialValuesType +): Promise => { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const fileName = tempFile('.mp4'); + const outputName = tempFile('.gif'); + const paletteName = tempFile('.png'); + + const { start, end, quality } = options; + + const { fps, scale } = GIF_PRESETS[quality]; + + await ffmpeg.writeFile(fileName, await fetchFile(input)); + + await ffmpeg.exec([ + '-i', + fileName, + '-ss', + start.toString(), + '-to', + end.toString(), + '-vf', + `fps=${fps},scale=${scale},palettegen`, + paletteName + ]); + + await ffmpeg.exec([ + '-i', + fileName, + '-i', + paletteName, + '-ss', + start.toString(), + '-to', + end.toString(), + '-filter_complex', + `fps=${fps},scale=${scale}[x];[x][1:v]paletteuse`, + outputName + ]); + + const data = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'image/gif' + }); + return new File([blob], `${input.name.replace(/\.[^/.]+$/, '')}.gif`, { + type: 'image/gif' + }); + }); +}; diff --git a/src/pages/tools/video/video-to-gif/types.ts b/src/pages/tools/video/video-to-gif/types.ts index 0bd16ffd..317d0585 100644 --- a/src/pages/tools/video/video-to-gif/types.ts +++ b/src/pages/tools/video/video-to-gif/types.ts @@ -1,7 +1,32 @@ +export type Quality = 'low' | 'mid' | 'high' | 'ultra'; + export type InitialValuesType = { - quality: 'mid' | 'high' | 'low' | 'ultra'; - fps: string; - scale: string; + quality: Quality; start: number; end: number; }; + +export const GIF_PRESETS: Record< + Quality, + { + fps: string; + scale: string; + } +> = { + low: { + fps: '5', + scale: '240:-1:flags=bilinear' + }, + mid: { + fps: '10', + scale: '320:-1:flags=bicubic' + }, + high: { + fps: '15', + scale: '480:-1:flags=lanczos' + }, + ultra: { + fps: '15', + scale: '640:-1:flags=lanczos' + } +}; From 6bcc2aa6e6a240c1768712f84e2efc082377ec81 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Wed, 5 Aug 2026 23:39:37 +0200 Subject: [PATCH 106/114] chore: - video to gif moved to conversion tools - key deleted from i8n other files --- public/locales/de/video.json | 5 ----- public/locales/en/converters.json | 17 +++++++++++++++++ public/locales/en/video.json | 17 ----------------- public/locales/es/video.json | 5 ----- public/locales/fr/video.json | 5 ----- public/locales/hi/video.json | 19 ------------------- public/locales/ja/video.json | 5 ----- public/locales/nl/video.json | 5 ----- public/locales/pt/video.json | 5 ----- public/locales/ru/video.json | 5 ----- public/locales/zh/video.json | 5 ----- src/pages/tools/converters/index.ts | 4 +++- .../video-to-gif/index.tsx | 2 +- .../video-to-gif/meta.ts | 8 ++++---- .../video-to-gif/service.ts | 0 .../video-to-gif/types.ts | 0 src/pages/tools/video/index.ts | 2 -- 17 files changed, 25 insertions(+), 84 deletions(-) rename src/pages/tools/{video => converters}/video-to-gif/index.tsx (98%) rename src/pages/tools/{video => converters}/video-to-gif/meta.ts (58%) rename src/pages/tools/{video => converters}/video-to-gif/service.ts (100%) rename src/pages/tools/{video => converters}/video-to-gif/types.ts (100%) diff --git a/public/locales/de/video.json b/public/locales/de/video.json index 69cd41e0..ba1f8826 100644 --- a/public/locales/de/video.json +++ b/public/locales/de/video.json @@ -111,10 +111,5 @@ "startTime": "Startzeit", "timestamps": "Zeitstempel", "title": "Video trimmen" - }, - "videoToGif": { - "description": "Konvertieren Sie Videodateien in das animierte GIF-Format. Extrahieren Sie bestimmte Zeitbereiche und erstellen Sie gemeinsam nutzbare animierte Bilder.", - "shortDescription": "Video in animiertes GIF konvertieren", - "title": "Video zu GIF" } } diff --git a/public/locales/en/converters.json b/public/locales/en/converters.json index a2943af4..ad28d09d 100644 --- a/public/locales/en/converters.json +++ b/public/locales/en/converters.json @@ -36,5 +36,22 @@ "resultTitle": "WEBP Images", "shortDescription": "Convert Images to WebP Format with quality control.", "title": "Convert Images to WebP" + }, + "videoToGif": { + "description": "Convert video files to animated GIF format. Extract specific time ranges and create shareable animated images.", + "shortDescription": "Convert video to animated GIF", + "title": "Video to GIF", + "inputTitle": "Input Video", + "resultTitle": "Output GIF", + "options": { + "quality": "Quality", + "low": "Low", + "mid": "Medium", + "high": "High", + "ultra": "Ultra", + "timestamps": "Timestamps", + "startTime": "Start Time", + "endTime": "End Time" + } } } diff --git a/public/locales/en/video.json b/public/locales/en/video.json index 2378dce9..b0d55b21 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -139,22 +139,5 @@ "startTime": "Start Time", "timestamps": "Timestamps", "title": "Trim Video" - }, - "videoToGif": { - "description": "Convert video files to animated GIF format. Extract specific time ranges and create shareable animated images.", - "shortDescription": "Convert video to animated GIF", - "title": "Video to GIF", - "inputTitle": "Input Video", - "resultTitle": "Output GIF", - "options": { - "quality": "Quality", - "low": "Low", - "mid": "Medium", - "high": "High", - "ultra": "Ultra", - "timestamps": "Timestamps", - "startTime": "Start Time", - "endTime": "End Time" - } } } diff --git a/public/locales/es/video.json b/public/locales/es/video.json index 1cbab702..f1bd250b 100644 --- a/public/locales/es/video.json +++ b/public/locales/es/video.json @@ -111,10 +111,5 @@ "startTime": "Hora de inicio", "timestamps": "Marcas de tiempo", "title": "Recortar vídeo" - }, - "videoToGif": { - "description": "Convierte archivos de vídeo a formato GIF animado. Extrae intervalos de tiempo específicos y crea imágenes animadas para compartir.", - "shortDescription": "Convertir vídeo a GIF animado", - "title": "Vídeo a GIF" } } diff --git a/public/locales/fr/video.json b/public/locales/fr/video.json index 64cfac04..0d0afede 100644 --- a/public/locales/fr/video.json +++ b/public/locales/fr/video.json @@ -111,10 +111,5 @@ "startTime": "Heure de début", "timestamps": "Horodatages", "title": "Découper la vidéo" - }, - "videoToGif": { - "description": "Convertissez des fichiers vidéo au format GIF animé. Extrayez des plages horaires spécifiques et créez des images animées partageables.", - "shortDescription": "Convertir une vidéo en GIF animé", - "title": "Vidéo en GIF" } } diff --git a/public/locales/hi/video.json b/public/locales/hi/video.json index bed972a6..a4118cff 100644 --- a/public/locales/hi/video.json +++ b/public/locales/hi/video.json @@ -178,24 +178,5 @@ "timestamps": "मुहर", "title": "वीडियो ट्रिम करें", "trimOptions": "ट्रिम विकल्प" - }, - "videoToGif": { - "conversionOptions": "रूपांतरण विकल्प", - "description": "वीडियो को GIF एनिमेटेड फ़ाइल में बदलें।", - "frameRate": "फ्रेम दर", - "frameRatePlaceholder": "FPS", - "height": "ऊंचाई", - "heightPlaceholder": "पिक्सेल", - "inputTitle": "इनपुट वीडियो", - "quality": "गुणवत्ता", - "qualityHigh": "उच्च", - "qualityLow": "कम", - "qualityMedium": "मध्यम", - "resize": "आकार बदलें", - "resultTitle": "GIF फ़ाइल", - "shortDescription": "वीडियो को एनिमेटेड GIF में बदलें", - "title": "वीडियो से GIF", - "width": "चौड़ाई", - "widthPlaceholder": "पिक्सेल" } } diff --git a/public/locales/ja/video.json b/public/locales/ja/video.json index 32095a65..ff0dae2e 100644 --- a/public/locales/ja/video.json +++ b/public/locales/ja/video.json @@ -111,10 +111,5 @@ "startTime": "開始時間", "timestamps": "タイムスタンプ", "title": "ビデオをトリムする" - }, - "videoToGif": { - "description": "ビデオファイルをアニメーションGIF形式に変換します。特定の時間範囲を抽出し、共有可能なアニメーション画像を作成します。", - "shortDescription": "ビデオをアニメーションGIFに変換する", - "title": "ビデオをGIFに変換" } } diff --git a/public/locales/nl/video.json b/public/locales/nl/video.json index 2408d847..83db8791 100644 --- a/public/locales/nl/video.json +++ b/public/locales/nl/video.json @@ -111,10 +111,5 @@ "startTime": "Starttijd", "timestamps": "Tijdstempels", "title": "Video bijsnijden" - }, - "videoToGif": { - "description": "Converteer videobestanden naar geanimeerde GIF-indeling. Extraheer specifieke tijdsperioden en maak deelbare geanimeerde afbeeldingen.", - "shortDescription": "Converteer video naar geanimeerde GIF", - "title": "Video naar GIF" } } diff --git a/public/locales/pt/video.json b/public/locales/pt/video.json index 35dbe6ed..fcd20c42 100644 --- a/public/locales/pt/video.json +++ b/public/locales/pt/video.json @@ -111,10 +111,5 @@ "startTime": "Hora de início", "timestamps": "Carimbos de data e hora", "title": "Cortar vídeo" - }, - "videoToGif": { - "description": "Converta arquivos de vídeo para o formato GIF animado. Extraia intervalos de tempo específicos e crie imagens animadas compartilháveis.", - "shortDescription": "Converter vídeo em GIF animado", - "title": "Vídeo para GIF" } } diff --git a/public/locales/ru/video.json b/public/locales/ru/video.json index c93eacbd..7836440e 100644 --- a/public/locales/ru/video.json +++ b/public/locales/ru/video.json @@ -111,10 +111,5 @@ "startTime": "Время начала", "timestamps": "Временные метки", "title": "Обрезать видео" - }, - "videoToGif": { - "description": "Конвертируйте видеофайлы в анимированный GIF-формат. Извлекайте определённые временные диапазоны и создавайте анимированные изображения для публикации.", - "shortDescription": "Конвертировать видео в анимированный GIF", - "title": "Видео в GIF" } } diff --git a/public/locales/zh/video.json b/public/locales/zh/video.json index 615af41e..f2199ee3 100644 --- a/public/locales/zh/video.json +++ b/public/locales/zh/video.json @@ -111,10 +111,5 @@ "startTime": "开始时间", "timestamps": "时间戳", "title": "修剪视频" - }, - "videoToGif": { - "description": "将视频文件转换为 GIF 动画格式。提取特定时间范围并创建可共享的动画图像。", - "shortDescription": "将视频转换为动画 GIF", - "title": "视频转GIF" } } diff --git a/src/pages/tools/converters/index.ts b/src/pages/tools/converters/index.ts index ffc9a721..a98b5b52 100644 --- a/src/pages/tools/converters/index.ts +++ b/src/pages/tools/converters/index.ts @@ -1,9 +1,11 @@ import { tool as convertersAudioConverter } from './audio-converter/meta'; import { tool as convertersWebpConverter } from './convert-to-webp/meta'; import { tool as convertersJpgConverter } from './convert-to-jpg/meta'; +import { tool as convertersGifConverter } from './video-to-gif/meta'; export const convertersTools = [ convertersAudioConverter, convertersWebpConverter, - convertersJpgConverter + convertersJpgConverter, + convertersGifConverter ]; diff --git a/src/pages/tools/video/video-to-gif/index.tsx b/src/pages/tools/converters/video-to-gif/index.tsx similarity index 98% rename from src/pages/tools/video/video-to-gif/index.tsx rename to src/pages/tools/converters/video-to-gif/index.tsx index b301d03f..9ed7fccf 100644 --- a/src/pages/tools/video/video-to-gif/index.tsx +++ b/src/pages/tools/converters/video-to-gif/index.tsx @@ -20,7 +20,7 @@ const initialValues: InitialValuesType = { }; export default function VideoToGif({ title }: ToolComponentProps) { - const { t } = useTranslation('video'); + const { t } = useTranslation('converters'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); diff --git a/src/pages/tools/video/video-to-gif/meta.ts b/src/pages/tools/converters/video-to-gif/meta.ts similarity index 58% rename from src/pages/tools/video/video-to-gif/meta.ts rename to src/pages/tools/converters/video-to-gif/meta.ts index b3236866..2e3aaf27 100644 --- a/src/pages/tools/video/video-to-gif/meta.ts +++ b/src/pages/tools/converters/video-to-gif/meta.ts @@ -1,15 +1,15 @@ import { defineTool } from '@tools/defineTool'; import { lazy } from 'react'; -export const tool = defineTool('video', { +export const tool = defineTool('converters', { path: 'video-to-gif', icon: 'material-symbols:gif', keywords: ['video', 'gif', 'convert', 'animated', 'image'], component: lazy(() => import('./index')), i18n: { - name: 'video:videoToGif.title', - description: 'video:videoToGif.description', - shortDescription: 'video:videoToGif.shortDescription', + name: 'converters:videoToGif.title', + description: 'converters:videoToGif.description', + shortDescription: 'converters:videoToGif.shortDescription', userTypes: ['generalUsers'] } }); diff --git a/src/pages/tools/video/video-to-gif/service.ts b/src/pages/tools/converters/video-to-gif/service.ts similarity index 100% rename from src/pages/tools/video/video-to-gif/service.ts rename to src/pages/tools/converters/video-to-gif/service.ts diff --git a/src/pages/tools/video/video-to-gif/types.ts b/src/pages/tools/converters/video-to-gif/types.ts similarity index 100% rename from src/pages/tools/video/video-to-gif/types.ts rename to src/pages/tools/converters/video-to-gif/types.ts diff --git a/src/pages/tools/video/index.ts b/src/pages/tools/video/index.ts index 05c285f3..8b18a566 100644 --- a/src/pages/tools/video/index.ts +++ b/src/pages/tools/video/index.ts @@ -1,5 +1,4 @@ import { tool as videoMergeVideo } from './merge-video/meta'; -import { tool as videoToGif } from './video-to-gif/meta'; import { tool as changeSpeed } from './change-speed/meta'; import { tool as flipVideo } from './flip/meta'; import { gifTools } from './gif'; @@ -19,7 +18,6 @@ export const videoTools = [ flipVideo, cropVideo, changeSpeed, - videoToGif, videoMergeVideo, addAudio ]; From 4c7ddb605b38086b87d3f73260d08a13d4541c5b Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Thu, 6 Aug 2026 01:05:50 +0200 Subject: [PATCH 107/114] chore: change gif speed updated --- public/locales/en/video.json | 8 +- .../tools/video/gif/change-speed/index.tsx | 161 +++++++----------- .../tools/video/gif/change-speed/service.ts | 39 +++++ .../tools/video/gif/change-speed/types.ts | 3 + 4 files changed, 110 insertions(+), 101 deletions(-) create mode 100644 src/pages/tools/video/gif/change-speed/service.ts create mode 100644 src/pages/tools/video/gif/change-speed/types.ts diff --git a/public/locales/en/video.json b/public/locales/en/video.json index b0d55b21..927fae02 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -95,7 +95,13 @@ "changeSpeed": { "description": "Change the playback speed of GIF animations. Speed up or slow down GIFs while maintaining smooth animation.", "shortDescription": "Change GIF animation speed", - "title": "Change GIF Speed" + "title": "Change GIF Speed", + "inputTitle": "Input GIF", + "resultTitle": "output GIF", + "options": { + "title": "Options", + "speedLabel": "Speed : x" + } } }, "loop": { diff --git a/src/pages/tools/video/gif/change-speed/index.tsx b/src/pages/tools/video/gif/change-speed/index.tsx index 1970412f..c37e93d2 100644 --- a/src/pages/tools/video/gif/change-speed/index.tsx +++ b/src/pages/tools/video/gif/change-speed/index.tsx @@ -1,98 +1,72 @@ -import { Box } from '@mui/material'; -import React, { useState } from 'react'; +import { Box, Typography, Slider } from '@mui/material'; +import React, { useState, useCallback } from 'react'; import ToolFileResult from '@components/result/ToolFileResult'; -import TextFieldWithDesc from 'components/options/TextFieldWithDesc'; import ToolContent from '@components/ToolContent'; +import { GetGroupsType } from '@components/options/ToolOptions'; import { ToolComponentProps } from '@tools/defineTool'; import ToolImageInput from '@components/input/ToolImageInput'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; -import { fetchFile } from '@ffmpeg/util'; +import { InitialValuesType } from './types'; +import { changeGifSpeed } from './service'; +import { useTranslation } from 'react-i18next'; +import { debounce } from 'lodash'; -const initialValues = { - newSpeed: 2 +const initialValues: InitialValuesType = { + speed: 2 }; export default function ChangeSpeed({ title }: ToolComponentProps) { + const { t } = useTranslation('video'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); + const [loading, setLoading] = useState(false); - const compute = (optionsValues: typeof initialValues, input: File | null) => { + const compute = async ( + optionsValues: InitialValuesType, + input: File | null + ) => { if (!input) return; - const { newSpeed } = optionsValues; - // Initialize FFmpeg once in your component/app - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; + setLoading(true); - const processImage = async ( - file: File, - newSpeed: number - ): Promise => { - if (!ffmpeg) { - ffmpeg = new FFmpeg(); - } - - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - - try { - await ffmpeg.writeFile('input.gif', await fetchFile(file)); - - // Process the GIF to change playback speed while preserving quality - // The filter_complex does three main operations: - // 1. [0:v]setpts=${1/newSpeed}*PTS - Adjusts frame timing: - // - PTS (Presentation Time Stamp) controls when each frame is displayed - // - Dividing by speed factor (e.g., 2 for 2x speed) reduces display time - // - Example: 1/2 = 0.5 → frames show for half their normal duration - // 2. split[a][b] - Creates two identical streams for parallel processing: - // - [a] goes to palettegen to create an optimized color palette - // - [b] contains the speed-adjusted frames - // 3. [b][p]paletteuse - Applies the generated palette to maintain: - // - Color accuracy - // - Transparency handling - // - Reduced file size - // This approach prevents visual artifacts that occur with simple re-encoding - await ffmpeg.exec([ - '-i', - 'input.gif', - '-filter_complex', - `[0:v]setpts=${ - 1 / newSpeed - }*PTS,split[a][b];[a]palettegen[p];[b][p]paletteuse`, - '-f', - 'gif', - 'output.gif' - ]); - - // Read the result - const data = await ffmpeg.readFile('output.gif'); - - // Create a new file from the processed data - const blob = new Blob([data as any], { type: 'image/gif' }); - const newFile = new File( - [blob], - file.name.replace('.gif', `-${newSpeed}x.gif`), - { - type: 'image/gif' - } - ); - - // Clean up to free memory - await ffmpeg.deleteFile('input.gif'); - await ffmpeg.deleteFile('output.gif'); - - setResult(newFile); - } catch (error) { - console.error('Error processing GIF:', error); - throw error; - } - }; - - processImage(input, newSpeed); + try { + const resultFile = await changeGifSpeed(input, optionsValues); + setResult(resultFile); + } catch (error) { + console.error('Error while processing video:', error); + } finally { + setLoading(false); + } }; + + const debouncedCompute = useCallback(debounce(compute, 1000), []); + + const getGroups: GetGroupsType = ({ + values, + updateField + }) => [ + { + title: t('gif.changeSpeed.options.title'), + component: ( + + + + {t('gif.changeSpeed.options.speedLabel')} {values.speed} + + + updateField('speed', Array.isArray(value) ? value[0] : value) + } + min={0.25} + max={4} + step={0.25} + valueLabelDisplay="auto" + valueLabelFormat={(value) => `x ${value}`} + sx={{ mt: 1 }} + /> + + + ) + } + ]; return ( } resultComponent={ } initialValues={initialValues} - getGroups={({ values, updateField }) => [ - { - title: 'New GIF speed', - component: ( - - updateField('newSpeed', Number(val))} - description={'Default multiplier: 2 means 2x faster'} - type={'number'} - /> - - ) - } - ]} - compute={compute} + getGroups={getGroups} + compute={debouncedCompute} setInput={setInput} /> ); diff --git a/src/pages/tools/video/gif/change-speed/service.ts b/src/pages/tools/video/gif/change-speed/service.ts new file mode 100644 index 00000000..3ac4bf74 --- /dev/null +++ b/src/pages/tools/video/gif/change-speed/service.ts @@ -0,0 +1,39 @@ +import { runFFmpegTask } from 'lib/ffmpeg'; +import { fetchFile } from '@ffmpeg/util'; +import { InitialValuesType } from './types'; + +export const changeGifSpeed = async ( + input: File, + options: InitialValuesType +): Promise => { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.gif'); + const outputName = tempFile('.gif'); + + const { speed } = options; + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + await ffmpeg.exec([ + '-i', + inputName, + '-filter_complex', + `[0:v]setpts=${ + 1 / speed + }*PTS,split[a][b];[a]palettegen[p];[b][p]paletteuse`, + '-f', + 'gif', + outputName + ]); + + const data = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: 'image/gif' + }); + + return new File([blob], input.name.replace('.gif', `-${speed}x.gif`), { + type: 'image/gif' + }); + }); +}; diff --git a/src/pages/tools/video/gif/change-speed/types.ts b/src/pages/tools/video/gif/change-speed/types.ts new file mode 100644 index 00000000..bb19b97f --- /dev/null +++ b/src/pages/tools/video/gif/change-speed/types.ts @@ -0,0 +1,3 @@ +export type InitialValuesType = { + speed: number; +}; From ea771ce9fc3a65a8c797d39700b46c72bebea6c0 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Thu, 6 Aug 2026 01:51:03 +0200 Subject: [PATCH 108/114] chore: change audio speed updated --- public/locales/en/audio.json | 5 +- .../change-speed/change-speed.service.test.ts | 46 ----------------- src/pages/tools/audio/change-speed/index.tsx | 42 ++++++---------- src/pages/tools/audio/change-speed/service.ts | 50 ++++++++----------- src/pages/tools/audio/change-speed/types.ts | 2 +- 5 files changed, 38 insertions(+), 107 deletions(-) delete mode 100644 src/pages/tools/audio/change-speed/change-speed.service.test.ts diff --git a/public/locales/en/audio.json b/public/locales/en/audio.json index 5984b69b..4a08b971 100644 --- a/public/locales/en/audio.json +++ b/public/locales/en/audio.json @@ -8,10 +8,7 @@ "settingSpeed": "Setting Speed", "shortDescription": "Change the speed of audio files", "speedDescription": "Default multiplier: 2 means 2x faster", - "title": "Change audio speed", - "toolInfo": { - "title": "What is {{title}}?" - } + "title": "Change audio speed" }, "extractAudio": { "description": "Extract audio track from video files.", diff --git a/src/pages/tools/audio/change-speed/change-speed.service.test.ts b/src/pages/tools/audio/change-speed/change-speed.service.test.ts deleted file mode 100644 index 0ebd4637..00000000 --- a/src/pages/tools/audio/change-speed/change-speed.service.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { expect, describe, it, vi } from 'vitest'; - -// Mock FFmpeg since it doesn't support Node.js -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])) -})); - -import { changeAudioSpeed } from './service'; -import { InitialValuesType } from './types'; - -describe('changeAudioSpeed', () => { - it('should return a new File with the correct name and type', async () => { - const mockAudioData = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockFile = new File([mockAudioData], 'test.mp3', { - type: 'audio/mp3' - }); - const options: InitialValuesType = { - newSpeed: 2, - outputFormat: 'mp3' - }; - const result = await changeAudioSpeed(mockFile, options); - expect(result).toBeInstanceOf(File); - expect(result?.name).toBe('test-2x.mp3'); - expect(result?.type).toBe('audio/mp3'); - }); - - it('should return null if input is null', async () => { - const options: InitialValuesType = { - newSpeed: 2, - outputFormat: 'mp3' - }; - const result = await changeAudioSpeed(null, options); - expect(result).toBeNull(); - }); -}); diff --git a/src/pages/tools/audio/change-speed/index.tsx b/src/pages/tools/audio/change-speed/index.tsx index bb556b38..27cb10c8 100644 --- a/src/pages/tools/audio/change-speed/index.tsx +++ b/src/pages/tools/audio/change-speed/index.tsx @@ -7,12 +7,11 @@ import { InitialValuesType } from './types'; import ToolAudioInput from '@components/input/ToolAudioInput'; import ToolFileResult from '@components/result/ToolFileResult'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; -import RadioWithTextField from '@components/options/RadioWithTextField'; import { changeAudioSpeed } from './service'; import { useTranslation } from 'react-i18next'; const initialValues: InitialValuesType = { - newSpeed: 2, + speed: 2, outputFormat: 'mp3' }; @@ -22,10 +21,7 @@ const formatOptions = [ { label: 'WAV', value: 'wav' } ]; -export default function ChangeSpeed({ - title, - longDescription -}: ToolComponentProps) { +export default function ChangeSpeed({ title }: ToolComponentProps) { const { t } = useTranslation('audio'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); @@ -35,10 +31,12 @@ export default function ChangeSpeed({ optionsValues: InitialValuesType, input: File | null ) => { + if (!input) return; + setLoading(true); try { - const newFile = await changeAudioSpeed(input, optionsValues); - setResult(newFile); + const resultFile = await changeAudioSpeed(input, optionsValues); + setResult(resultFile); } catch (err) { setResult(null); } finally { @@ -55,9 +53,10 @@ export default function ChangeSpeed({ component: ( updateField('newSpeed', Number(val))} + value={values.speed.toString()} + onOwnChange={(val) => updateField('speed', Number(val))} description={t('changeSpeed.speedDescription')} + inputProps={{ min: 0 }} type="number" /> @@ -102,28 +101,17 @@ export default function ChangeSpeed({ /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} setInput={setInput} compute={compute} - toolInfo={{ - title: t('changeSpeed.toolInfo.title', { title }), - description: longDescription - }} /> ); } diff --git a/src/pages/tools/audio/change-speed/service.ts b/src/pages/tools/audio/change-speed/service.ts index c6638571..2a14f71c 100644 --- a/src/pages/tools/audio/change-speed/service.ts +++ b/src/pages/tools/audio/change-speed/service.ts @@ -1,6 +1,7 @@ import { InitialValuesType } from './types'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { getFileExtension } from '@utils/file'; function computeAudioFilter(speed: number): string { if (speed <= 2 && speed >= 0.5) { @@ -21,27 +22,19 @@ function computeAudioFilter(speed: number): string { } export async function changeAudioSpeed( - input: File | null, + input: File, options: InitialValuesType -): Promise { - if (!input) return null; - const { newSpeed, outputFormat } = options; - let ffmpeg: FFmpeg | null = null; - let ffmpegLoaded = false; - try { - ffmpeg = new FFmpeg(); - if (!ffmpegLoaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - ffmpegLoaded = true; - } - const fileName = input.name; - const outputName = `output.${outputFormat}`; +): Promise { + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { speed, outputFormat } = options; + + const fileName = tempFile(`.${getFileExtension(input.name)}`); + const outputName = tempFile(`.${outputFormat}`); + await ffmpeg.writeFile(fileName, await fetchFile(input)); - const audioFilter = computeAudioFilter(newSpeed); + const audioFilter = computeAudioFilter(speed); const args = ['-i', fileName, '-filter:a', audioFilter]; + if (outputFormat === 'mp3') { args.push('-b:a', '192k', '-f', 'mp3', outputName); } else if (outputFormat === 'aac') { @@ -61,20 +54,19 @@ export async function changeAudioSpeed( } await ffmpeg.exec(args); const data = await ffmpeg.readFile(outputName); + let mimeType = 'audio/mp3'; if (outputFormat === 'aac') mimeType = 'audio/aac'; if (outputFormat === 'wav') mimeType = 'audio/wav'; - const blob = new Blob([data as any], { type: mimeType }); - const newFile = new File( + + const blob = new Blob([new Uint8Array(data as Uint8Array)], { + type: mimeType + }); + + return new File( [blob], - fileName.replace(/\.[^/.]+$/, `-${newSpeed}x.${outputFormat}`), + fileName.replace(/\.[^/.]+$/, `-${speed}x.${outputFormat}`), { type: mimeType } ); - await ffmpeg.deleteFile(fileName); - await ffmpeg.deleteFile(outputName); - return newFile; - } catch (err) { - console.error(`Failed to process audio: ${err}`); - return null; - } + }); } diff --git a/src/pages/tools/audio/change-speed/types.ts b/src/pages/tools/audio/change-speed/types.ts index 587fc4fb..150e8de0 100644 --- a/src/pages/tools/audio/change-speed/types.ts +++ b/src/pages/tools/audio/change-speed/types.ts @@ -1,4 +1,4 @@ export type InitialValuesType = { - newSpeed: number; + speed: number; outputFormat: 'mp3' | 'aac' | 'wav'; }; From 73cc15f092151ff3b6d623fabae40252fb2a053e Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Thu, 6 Aug 2026 11:05:46 +0200 Subject: [PATCH 109/114] chore: extract audio updated --- src/pages/tools/audio/extract-audio/index.tsx | 28 ++--- .../tools/audio/extract-audio/service.ts | 110 ++++++++---------- src/pages/tools/audio/extract-audio/types.ts | 4 +- 3 files changed, 64 insertions(+), 78 deletions(-) diff --git a/src/pages/tools/audio/extract-audio/index.tsx b/src/pages/tools/audio/extract-audio/index.tsx index e54e2901..5da78ab4 100644 --- a/src/pages/tools/audio/extract-audio/index.tsx +++ b/src/pages/tools/audio/extract-audio/index.tsx @@ -9,15 +9,13 @@ import { GetGroupsType } from '@components/options/ToolOptions'; import ToolFileResult from '@components/result/ToolFileResult'; import SelectWithDesc from '@components/options/SelectWithDesc'; import { useTranslation } from 'react-i18next'; +import { getFileExtension } from '@utils/file'; const initialValues: InitialValuesType = { outputFormat: 'aac' }; -export default function ExtractAudio({ - title, - longDescription -}: ToolComponentProps) { +export default function ExtractAudio({ title }: ToolComponentProps) { const { t } = useTranslation('audio'); const [file, setFile] = useState(null); const [audioFile, setAudioFile] = useState(null); @@ -35,7 +33,7 @@ export default function ExtractAudio({ { - updateField('outputFormat', value.toString()); + updateField('outputFormat', value); }} options={[ { label: 'AAC', value: 'aac' }, @@ -75,25 +73,19 @@ export default function ExtractAudio({ /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} compute={compute} toolInfo={{ title: t('extractAudio.toolInfo.title', { title }), - description: longDescription + description: t('extractAudio.toolInfo.description') }} setInput={setFile} /> diff --git a/src/pages/tools/audio/extract-audio/service.ts b/src/pages/tools/audio/extract-audio/service.ts index 644c70a9..f1c054d4 100644 --- a/src/pages/tools/audio/extract-audio/service.ts +++ b/src/pages/tools/audio/extract-audio/service.ts @@ -1,70 +1,62 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import { InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - export async function extractAudioFromVideo( input: File, options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { outputFormat } = options; + + const inputName = tempFile('.mp4'); + const outputName = tempFile(`.${outputFormat}`); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + const args: string[] = ['-i', inputName, '-vn']; + + if (outputFormat === 'mp3') { + args.push( + '-ar', + '44100', + '-ac', + '2', + '-b:a', + '192k', + '-f', + 'mp3', + outputName + ); + } else if (outputFormat === 'wav') { + args.push( + '-acodec', + 'pcm_s16le', + '-ar', + '44100', + '-ac', + '2', + '-f', + 'wav', + outputName + ); + } else { + // Default to AAC or copy + args.push('-acodec', 'copy', outputName); + } + + await ffmpeg.exec(args); + + const extractedAudio = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(extractedAudio as Uint8Array)], { + type: `audio/${outputFormat}` }); - } - const inputName = 'input.mp4'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const configuredOutputAudioFormat = options.outputFormat; - const outputName = `output.${configuredOutputAudioFormat}`; - const args: string[] = ['-i', inputName, '-vn']; - - if (configuredOutputAudioFormat === 'mp3') { - args.push( - '-ar', - '44100', - '-ac', - '2', - '-b:a', - '192k', - '-f', - 'mp3', - outputName + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_audio.${outputFormat}`, + { type: `audio/${outputFormat}` } ); - } else if (configuredOutputAudioFormat === 'wav') { - args.push( - '-acodec', - 'pcm_s16le', - '-ar', - '44100', - '-ac', - '2', - '-f', - 'wav', - outputName - ); - } else { - // Default to AAC or copy - args.push('-acodec', 'copy', outputName); - } - - await ffmpeg.exec(args); - - const extractedAudio = await ffmpeg.readFile(outputName); - - return new File( - [ - new Blob([extractedAudio as any], { - type: `audio/${configuredOutputAudioFormat}` - }) - ], - `${input.name.replace( - /\.[^/.]+$/, - '' - )}_audio.${configuredOutputAudioFormat}`, - { type: `audio/${configuredOutputAudioFormat}` } - ); + }); } diff --git a/src/pages/tools/audio/extract-audio/types.ts b/src/pages/tools/audio/extract-audio/types.ts index d6d4f360..4077a45a 100644 --- a/src/pages/tools/audio/extract-audio/types.ts +++ b/src/pages/tools/audio/extract-audio/types.ts @@ -1,3 +1,5 @@ +type AudioFormat = 'aac' | 'mp3' | 'wav'; + export type InitialValuesType = { - outputFormat: string; + outputFormat: AudioFormat; }; From 1e709987b5d96541df83ebece252e5b5f9717445 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Thu, 6 Aug 2026 17:28:09 +0200 Subject: [PATCH 110/114] chore: trim audio updated --- public/locales/en/audio.json | 6 +- src/pages/tools/audio/trim/index.tsx | 24 +-- src/pages/tools/audio/trim/service.ts | 185 ++++++++---------- .../tools/audio/trim/trim.service.test.ts | 58 ------ 4 files changed, 99 insertions(+), 174 deletions(-) delete mode 100644 src/pages/tools/audio/trim/trim.service.test.ts diff --git a/public/locales/en/audio.json b/public/locales/en/audio.json index 4a08b971..c6f713e8 100644 --- a/public/locales/en/audio.json +++ b/public/locales/en/audio.json @@ -51,8 +51,8 @@ "timeSettings": "Time Settings", "title": "Trim Audio", "toolInfo": { - "title": "What is {{title}}?" - }, - "trimmingAudio": "Trimming Audio" + "title": "What is {{title}}?", + "longDescription": "This tool allows you to trim audio files by specifying start and end times with sub-second precision. You can extract specific segments from longer audio files, remove unwanted parts, or create shorter clips. Supports various audio formats including MP3, AAC, and WAV. Perfect for podcast editing, music production, or any audio editing needs." + } } } diff --git a/src/pages/tools/audio/trim/index.tsx b/src/pages/tools/audio/trim/index.tsx index 1a3efe73..622d21ea 100644 --- a/src/pages/tools/audio/trim/index.tsx +++ b/src/pages/tools/audio/trim/index.tsx @@ -9,6 +9,7 @@ import ToolAudioInput from '@components/input/ToolAudioInput'; import ToolFileResult from '@components/result/ToolFileResult'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { trimAudio } from './service'; +import { getFileExtension } from '@utils/file'; const initialValues: InitialValuesType = { startTime: '00:00:00', @@ -22,7 +23,7 @@ const formatOptions = [ { label: 'WAV', value: 'wav' } ]; -export default function Trim({ title, longDescription }: ToolComponentProps) { +export default function Trim({ title }: ToolComponentProps) { const { t } = useTranslation('audio'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); @@ -110,19 +111,12 @@ export default function Trim({ title, longDescription }: ToolComponentProps) { /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} @@ -130,7 +124,7 @@ export default function Trim({ title, longDescription }: ToolComponentProps) { compute={compute} toolInfo={{ title: t('trim.toolInfo.title', { title }), - description: longDescription + description: t('trim.toolInfo.longDescription') }} /> ); diff --git a/src/pages/tools/audio/trim/service.ts b/src/pages/tools/audio/trim/service.ts index 26b0a66f..de9004cc 100644 --- a/src/pages/tools/audio/trim/service.ts +++ b/src/pages/tools/audio/trim/service.ts @@ -1,108 +1,97 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { getFileExtension } from '@utils/file'; import { InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - export async function trimAudio( input: File, options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { startTime, endTime, outputFormat } = options; + const inputName = tempFile(getFileExtension(input.name)); + const outputName = tempFile(`.${outputFormat}`); + + await ffmpeg.writeFile(inputName, await fetchFile(input)); + + let args: string[] = [ + '-i', + inputName, + '-ss', + startTime, // Start time + '-to', + endTime, // End time + '-c', + 'copy' + ]; + + // Add format-specific arguments + if (outputFormat === 'mp3') { + args = [ + '-i', + inputName, + '-ss', + startTime, + '-to', + endTime, + '-ar', + '44100', + '-ac', + '2', + '-b:a', + '192k', + '-f', + 'mp3', + outputName + ]; + } else if (outputFormat === 'aac') { + args = [ + '-i', + inputName, + '-ss', + startTime, + '-to', + endTime, + '-c:a', + 'aac', + '-b:a', + '192k', + '-f', + 'adts', + outputName + ]; + } else if (outputFormat === 'wav') { + args = [ + '-i', + inputName, + '-ss', + startTime, + '-to', + endTime, + '-acodec', + 'pcm_s16le', + '-ar', + '44100', + '-ac', + '2', + '-f', + 'wav', + outputName + ]; + } + + await ffmpeg.exec(args); + + const trimmedAudio = await ffmpeg.readFile(outputName); + + const blob = new Blob([new Uint8Array(trimmedAudio as Uint8Array)], { + type: `audio/${outputFormat}` }); - } - const inputName = 'input.mp3'; - await ffmpeg.writeFile(inputName, await fetchFile(input)); - - const { startTime, endTime, outputFormat } = options; - const outputName = `output.${outputFormat}`; - - // Build FFmpeg arguments for trimming - let args: string[] = [ - '-i', - inputName, - '-ss', - startTime, // Start time - '-to', - endTime, // End time - '-c', - 'copy' // Copy without re-encoding for speed - ]; - - // Add format-specific arguments - if (outputFormat === 'mp3') { - args = [ - '-i', - inputName, - '-ss', - startTime, - '-to', - endTime, - '-ar', - '44100', - '-ac', - '2', - '-b:a', - '192k', - '-f', - 'mp3', - outputName - ]; - } else if (outputFormat === 'aac') { - args = [ - '-i', - inputName, - '-ss', - startTime, - '-to', - endTime, - '-c:a', - 'aac', - '-b:a', - '192k', - '-f', - 'adts', - outputName - ]; - } else if (outputFormat === 'wav') { - args = [ - '-i', - inputName, - '-ss', - startTime, - '-to', - endTime, - '-acodec', - 'pcm_s16le', - '-ar', - '44100', - '-ac', - '2', - '-f', - 'wav', - outputName - ]; - } - - await ffmpeg.exec(args); - - const trimmedAudio = await ffmpeg.readFile(outputName); - - let mimeType = 'audio/mp3'; - if (outputFormat === 'aac') mimeType = 'audio/aac'; - if (outputFormat === 'wav') mimeType = 'audio/wav'; - - return new File( - [ - new Blob([trimmedAudio as any], { - type: mimeType - }) - ], - `${input.name.replace(/\.[^/.]+$/, '')}_trimmed.${outputFormat}`, - { type: mimeType } - ); + return new File( + [blob], + `${input.name.replace(/\.[^/.]+$/, '')}_trimmed.${outputFormat}`, + { type: `audio/${outputFormat}` } + ); + }); } diff --git a/src/pages/tools/audio/trim/trim.service.test.ts b/src/pages/tools/audio/trim/trim.service.test.ts deleted file mode 100644 index 5d9faa5c..00000000 --- a/src/pages/tools/audio/trim/trim.service.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { expect, describe, it, vi } from 'vitest'; - -// Mock FFmpeg since it doesn't support Node.js -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])) -})); - -import { trimAudio } from './service'; - -describe('trimAudio', () => { - it('should trim audio file with valid time parameters', async () => { - // Create a mock audio file - const mockAudioData = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockFile = new File([mockAudioData], 'test.mp3', { - type: 'audio/mp3' - }); - - const options = { - startTime: '00:00:10', - endTime: '00:00:20', - outputFormat: 'mp3' as const - }; - - const result = await trimAudio(mockFile, options); - expect(result).toBeInstanceOf(File); - expect(result.name).toContain('_trimmed.mp3'); - expect(result.type).toBe('audio/mp3'); - }); - - it('should handle different output formats', async () => { - const mockAudioData = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockFile = new File([mockAudioData], 'test.wav', { - type: 'audio/wav' - }); - - const options = { - startTime: '00:00:00', - endTime: '00:00:30', - outputFormat: 'wav' as const - }; - - const result = await trimAudio(mockFile, options); - expect(result).toBeInstanceOf(File); - expect(result.name).toContain('_trimmed.wav'); - expect(result.type).toBe('audio/wav'); - }); -}); From 4d8c07e094267e8892aec66efcba6f76b9389ab3 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Thu, 6 Aug 2026 17:52:00 +0200 Subject: [PATCH 111/114] chore: merge audio updated --- public/locales/en/audio.json | 1 - src/pages/tools/audio/merge-audio/index.tsx | 21 +-- .../merge-audio/merge-audio.service.test.ts | 73 -------- src/pages/tools/audio/merge-audio/service.ts | 166 ++++++++---------- 4 files changed, 79 insertions(+), 182 deletions(-) delete mode 100644 src/pages/tools/audio/merge-audio/merge-audio.service.test.ts diff --git a/public/locales/en/audio.json b/public/locales/en/audio.json index c6f713e8..5bbfced7 100644 --- a/public/locales/en/audio.json +++ b/public/locales/en/audio.json @@ -28,7 +28,6 @@ "description": "Combine multiple audio files into a single audio file by concatenating them in sequence.", "inputTitle": "Input Audio Files", "longDescription": "This tool allows you to merge multiple audio files into a single file by concatenating them in the order you upload them. Perfect for combining podcast segments, music tracks, or any audio files that need to be joined together. Supports various audio formats including MP3, AAC, and WAV.", - "mergingAudio": "Merging Audio", "outputFormat": "Output Format", "resultTitle": "Merged Audio", "shortDescription": "Merge multiple audio files into one (MP3, AAC, WAV).", diff --git a/src/pages/tools/audio/merge-audio/index.tsx b/src/pages/tools/audio/merge-audio/index.tsx index 02ab2b87..a201416a 100644 --- a/src/pages/tools/audio/merge-audio/index.tsx +++ b/src/pages/tools/audio/merge-audio/index.tsx @@ -34,7 +34,7 @@ export default function MergeAudio({ optionsValues: InitialValuesType, input: MultiAudioInput[] ) => { - if (input.length === 0) return; + if (input.length < 2) return; setLoading(true); try { const files = input.map((item) => item.file); @@ -94,19 +94,12 @@ export default function MergeAudio({ /> } resultComponent={ - loading ? ( - - ) : ( - - ) + } initialValues={initialValues} getGroups={getGroups} diff --git a/src/pages/tools/audio/merge-audio/merge-audio.service.test.ts b/src/pages/tools/audio/merge-audio/merge-audio.service.test.ts deleted file mode 100644 index 6bdaaabb..00000000 --- a/src/pages/tools/audio/merge-audio/merge-audio.service.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { expect, describe, it, vi } from 'vitest'; - -// Mock FFmpeg since it doesn't support Node.js -vi.mock('@ffmpeg/ffmpeg', () => ({ - FFmpeg: vi.fn().mockImplementation(() => ({ - loaded: false, - load: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - exec: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])), - deleteFile: vi.fn().mockResolvedValue(undefined) - })) -})); - -vi.mock('@ffmpeg/util', () => ({ - fetchFile: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3, 4, 5])) -})); - -import { mergeAudioFiles } from './service'; - -describe('mergeAudioFiles', () => { - it('should merge multiple audio files', async () => { - // Create mock audio files - const mockAudioData1 = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockAudioData2 = new Uint8Array([6, 7, 8, 9, 10, 11]); - - const mockFile1 = new File([mockAudioData1], 'test1.mp3', { - type: 'audio/mp3' - }); - const mockFile2 = new File([mockAudioData2], 'test2.mp3', { - type: 'audio/mp3' - }); - - const options = { - outputFormat: 'mp3' as const - }; - - const result = await mergeAudioFiles([mockFile1, mockFile2], options); - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('merged_audio.mp3'); - expect(result.type).toBe('audio/mp3'); - }); - - it('should handle different output formats', async () => { - const mockAudioData = new Uint8Array([0, 1, 2, 3, 4, 5]); - const mockFile = new File([mockAudioData], 'test.wav', { - type: 'audio/wav' - }); - - const options = { - outputFormat: 'aac' as const - }; - - const result = await mergeAudioFiles([mockFile], options); - expect(result).toBeInstanceOf(File); - expect(result.name).toBe('merged_audio.aac'); - expect(result.type).toBe('audio/aac'); - }); - - it('should throw error when no input files provided', async () => { - const options = { - outputFormat: 'mp3' as const - }; - - try { - await mergeAudioFiles([], options); - expect.fail('Should have thrown an error'); - } catch (error) { - expect(error).toBeInstanceOf(Error); - expect((error as Error).message).toBe('No input files provided'); - } - }); -}); diff --git a/src/pages/tools/audio/merge-audio/service.ts b/src/pages/tools/audio/merge-audio/service.ts index 679ac6aa..e4ee8d8c 100644 --- a/src/pages/tools/audio/merge-audio/service.ts +++ b/src/pages/tools/audio/merge-audio/service.ts @@ -1,115 +1,93 @@ -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import { InitialValuesType } from './types'; -const ffmpeg = new FFmpeg(); - export async function mergeAudioFiles( inputs: File[], options: InitialValuesType ): Promise { - if (!ffmpeg.loaded) { - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); - } + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const { outputFormat } = options; - if (inputs.length === 0) { - throw new Error('No input files provided'); - } + const tempWavNames: string[] = []; + const fileListName = tempFile('.txt'); + const concatWavName = tempFile('.wav'); + const outputName = tempFile(`.${outputFormat}`); - const { outputFormat } = options; - const outputName = `output.${outputFormat}`; + for (let i = 0; i < inputs.length; i++) { + const inputName = tempFile( + `.${inputs[i].name.split('.').pop() ?? 'tmp'}` + ); + const tempWavName = tempFile('.wav'); - // 1. Convert all inputs to WAV - const tempWavNames: string[] = []; - for (let i = 0; i < inputs.length; i++) { - const inputName = `input${i}`; - const tempWavName = `temp${i}.wav`; - await ffmpeg.writeFile(inputName, await fetchFile(inputs[i])); - await ffmpeg.exec([ - '-i', - inputName, - '-acodec', - 'pcm_s16le', - '-ar', - '44100', - '-ac', - '2', - tempWavName - ]); - tempWavNames.push(tempWavName); - await ffmpeg.deleteFile(inputName); - } + await ffmpeg.writeFile(inputName, await fetchFile(inputs[i])); - // 2. Create file list for concat - const fileListName = 'filelist.txt'; - const fileListContent = tempWavNames - .map((name) => `file '${name}'`) - .join('\n'); - await ffmpeg.writeFile(fileListName, fileListContent); - - // 3. Concatenate WAV files - const concatWav = 'concat.wav'; - await ffmpeg.exec([ - '-f', - 'concat', - '-safe', - '0', - '-i', - fileListName, - '-c', - 'copy', - concatWav - ]); - - // 4. Convert concatenated WAV to requested output format - let finalOutput = concatWav; - if (outputFormat !== 'wav') { - const args = ['-i', concatWav]; - if (outputFormat === 'mp3') { - args.push( + await ffmpeg.exec([ + '-i', + inputName, + '-acodec', + 'pcm_s16le', '-ar', '44100', '-ac', '2', - '-b:a', - '192k', - '-f', - 'mp3', - outputName - ); - } else if (outputFormat === 'aac') { - args.push('-c:a', 'aac', '-b:a', '192k', '-f', 'adts', outputName); + tempWavName + ]); + + tempWavNames.push(tempWavName); } - await ffmpeg.exec(args); - finalOutput = outputName; - } - const mergedAudio = await ffmpeg.readFile(finalOutput); + // Build concat file list + const fileListContent = tempWavNames + .map((name) => `file '${name}'`) + .join('\n'); - let mimeType = 'audio/wav'; - if (outputFormat === 'mp3') mimeType = 'audio/mp3'; - if (outputFormat === 'aac') mimeType = 'audio/aac'; + await ffmpeg.writeFile(fileListName, fileListContent); - // Clean up files - for (const tempWavName of tempWavNames) { - await ffmpeg.deleteFile(tempWavName); - } - await ffmpeg.deleteFile(fileListName); - await ffmpeg.deleteFile(concatWav); - if (outputFormat !== 'wav') { - await ffmpeg.deleteFile(outputName); - } + // Concatenate WAV files + await ffmpeg.exec([ + '-f', + 'concat', + '-safe', + '0', + '-i', + fileListName, + '-c', + 'copy', + concatWavName + ]); - return new File( - [ - new Blob([mergedAudio as any], { - type: mimeType - }) - ], - `merged_audio.${outputFormat}`, - { type: mimeType } - ); + let finalOutput = concatWavName; + + if (outputFormat !== 'wav') { + const args = ['-i', concatWavName]; + + switch (outputFormat) { + case 'mp3': + args.push('-b:a', '192k', '-f', 'mp3', outputName); + break; + + case 'aac': + args.push('-c:a', 'aac', '-b:a', '192k', '-f', 'adts', outputName); + break; + } + + await ffmpeg.exec(args); + finalOutput = outputName; + } + + const data = await ffmpeg.readFile(finalOutput); + + return new File( + [ + new Blob([new Uint8Array(data as Uint8Array)], { + type: `audio/${outputFormat}` + }) + ], + `merged_audio.${outputFormat}`, + { + type: `audio/${outputFormat}` + } + ); + }); } From 006cecab4cf768b266348bd761c6bce255b9ea51 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Thu, 6 Aug 2026 18:49:28 +0200 Subject: [PATCH 112/114] chore: rotate image updated --- public/locales/en/image.json | 12 ++++- .../tools/image/generic/rotate/index.tsx | 48 +++++++++++-------- .../tools/image/generic/rotate/service.ts | 43 +++++++++-------- 3 files changed, 61 insertions(+), 42 deletions(-) diff --git a/public/locales/en/image.json b/public/locales/en/image.json index b484eb43..831c1fe5 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -257,7 +257,17 @@ "rotate": { "description": "Rotate an image by a specified angle.", "shortDescription": "Rotate an image easily.", - "title": "Rotate Image" + "title": "Rotate Image", + "inputTitle": "Input Images", + "resultTitle": "Rotated images", + "options": { + "method": "Rotation Method", + "presetTitle": "Preset Angle", + "presetDesc": "Rotate by a specific angle in degrees.", + "customTitle": "Custom Angle", + "customDesc": "Rotate by a custom angle in degrees.", + "angle": "Angle" + } }, "watermark": { "title": "Watermark Images", diff --git a/src/pages/tools/image/generic/rotate/index.tsx b/src/pages/tools/image/generic/rotate/index.tsx index 90e329a6..695331e7 100644 --- a/src/pages/tools/image/generic/rotate/index.tsx +++ b/src/pages/tools/image/generic/rotate/index.tsx @@ -1,7 +1,7 @@ import { ToolComponentProps } from '@tools/defineTool'; import { InitialValuesType } from './type'; import * as Yup from 'yup'; - +import { getFileExtension } from '@utils/file'; import { useState } from 'react'; import { GetGroupsType } from '@components/options/ToolOptions'; import SimpleRadio from '@components/options/SimpleRadio'; @@ -12,6 +12,7 @@ import ToolContent from '@components/ToolContent'; import ToolImageInput from '@components/input/ToolImageInput'; import ToolFileResult from '@components/result/ToolFileResult'; import { processImage } from './service'; +import { useTranslation } from 'react-i18next'; const initialValues: InitialValuesType = { rotateAngle: '90', @@ -30,32 +31,43 @@ const validationSchema = Yup.object({ }); export default function RotateImage({ title }: ToolComponentProps) { + const { t } = useTranslation('image'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); + const [loading, setLoading] = useState(false); const compute = async (optionsValues: InitialValuesType, input: any) => { if (!input) return; - setResult(await processImage(input, optionsValues)); + setLoading(true); + try { + const rotatedFile = await processImage(input, optionsValues); + setResult(rotatedFile); + } catch (err) { + console.error(`Failed to rotate image input: ${err}`); + setResult(null); + } finally { + setLoading(false); + } }; const getGroups: GetGroupsType = ({ values, updateField }) => [ { - title: 'Rotate Method', + title: t('rotate.options.method'), component: ( updateField('rotateMethod', 'Preset')} checked={values.rotateMethod === 'Preset'} - description={'Rotate by a specific angle in degrees.'} - title={'Preset angle'} + description={t('rotate.options.presetDesc')} + title={t('rotate.options.presetTitle')} /> updateField('rotateMethod', 'Custom')} checked={values.rotateMethod === 'Custom'} - description={'Rotate by a custom angle in degrees.'} - title={'Custom angle'} + description={t('rotate.options.customDesc')} + title={t('rotate.options.customTitle')} /> ) @@ -63,13 +75,13 @@ export default function RotateImage({ title }: ToolComponentProps) { ...(values.rotateMethod === 'Preset' ? [ { - title: 'Preset angle', + title: t('rotate.options.angle'), component: ( updateField('rotateAngle', val)} - description={'Rotate by a specific angle in degrees.'} + description={''} options={[ { label: '90 degrees', value: '90' }, { label: '180 degrees', value: '180' }, @@ -82,15 +94,13 @@ export default function RotateImage({ title }: ToolComponentProps) { ] : [ { - title: 'Custom angle', + title: t('rotate.options.angle'), component: ( updateField('rotateAngle', val)} - description={ - 'Rotate by a custom angle in degrees(from -360 to 360).' - } + description={'- 360 ↔ 360'} inputProps={{ type: 'number', min: -360, @@ -115,22 +125,18 @@ export default function RotateImage({ title }: ToolComponentProps) { } resultComponent={ } - toolInfo={{ - title: 'Rotate Image', - description: - 'This tool allows you to rotate images by a specific angle in any degrees.' - }} /> ); } diff --git a/src/pages/tools/image/generic/rotate/service.ts b/src/pages/tools/image/generic/rotate/service.ts index 9ace4b19..8f4fe880 100644 --- a/src/pages/tools/image/generic/rotate/service.ts +++ b/src/pages/tools/image/generic/rotate/service.ts @@ -1,12 +1,13 @@ import { InitialValuesType } from './type'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; +import { getFileExtension } from '@utils/file'; export const processImage = async ( file: File, options: InitialValuesType ): Promise => { - const { rotateAngle, rotateMethod } = options; + const { rotateAngle } = options; if (file.type === 'image/svg+xml') { try { // Read the SVG file @@ -45,30 +46,32 @@ export const processImage = async ( } // For non-SVG images, use FFmpeg - try { - const ffmpeg = new FFmpeg(); - await ffmpeg.load(); + return runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const extension = getFileExtension(file.name) ?? 'png'; - // Write input file - await ffmpeg.writeFile('input', await fetchFile(file)); + const inputName = tempFile(`.${extension}`); + const outputName = tempFile('.png'); - // Determine rotation command - const rotateCmd = `rotate=${rotateAngle}*PI/180`; + await ffmpeg.writeFile(inputName, await fetchFile(file)); + + const radians = `${Number(rotateAngle)}*PI/180`; - // Execute FFmpeg command await ffmpeg.exec([ '-i', - 'input', + inputName, '-vf', - rotateCmd, - 'output.' + file.name.split('.').pop() + `rotate=${radians}:ow=rotw(${radians}):oh=roth(${radians}):fillcolor=none`, + outputName ]); - // Read the output file - const data = await ffmpeg.readFile('output.' + file.name.split('.').pop()); - return new File([data as any], file.name, { type: file.type }); - } catch (error) { - console.error('Error processing image:', error); - return null; - } + const data = await ffmpeg.readFile(outputName); + + return new File( + [new Uint8Array(data as Uint8Array)], + `rotated_${file.name.replace(/\.[^/.]+$/, '.png')}`, + { + type: 'image/png' + } + ); + }); }; From 2fdd975beee0d35c5a303a90888eb91406cd32db Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Thu, 6 Aug 2026 19:09:26 +0200 Subject: [PATCH 113/114] chore: resize image updated --- .../tools/image/generic/resize/index.tsx | 1 + .../tools/image/generic/resize/service.ts | 238 +++++++++--------- 2 files changed, 124 insertions(+), 115 deletions(-) diff --git a/src/pages/tools/image/generic/resize/index.tsx b/src/pages/tools/image/generic/resize/index.tsx index 447ee39f..ac2c9a63 100644 --- a/src/pages/tools/image/generic/resize/index.tsx +++ b/src/pages/tools/image/generic/resize/index.tsx @@ -223,6 +223,7 @@ export default function ResizeImage({ title }: ToolComponentProps) { ) diff --git a/src/pages/tools/image/generic/resize/service.ts b/src/pages/tools/image/generic/resize/service.ts index 8ed4859d..5b32e599 100644 --- a/src/pages/tools/image/generic/resize/service.ts +++ b/src/pages/tools/image/generic/resize/service.ts @@ -1,5 +1,5 @@ import { InitialValuesType } from './types'; -import { FFmpeg } from '@ffmpeg/ffmpeg'; +import { runFFmpegTask } from 'lib/ffmpeg'; import { fetchFile } from '@ffmpeg/util'; import JSZip from 'jszip'; @@ -15,54 +15,54 @@ const processImage = async ( dimensionType, maintainAspectRatio } = options; + if (file.type === 'image/svg+xml') { try { - // Read the SVG file const fileText = await file.text(); const parser = new DOMParser(); const svgDoc = parser.parseFromString(fileText, 'image/svg+xml'); const svgElement = svgDoc.documentElement; - // Get original dimensions const viewBox = svgElement.getAttribute('viewBox'); + let originalWidth: string | number | null = svgElement.getAttribute('width'); + let originalHeight: string | number | null = svgElement.getAttribute('height'); - // Parse viewBox if available and width/height are not explicitly set let viewBoxValues = null; + if (viewBox) { viewBoxValues = viewBox.split(' ').map(Number); } - // Determine original dimensions from viewBox if not explicitly set - if (!originalWidth && viewBoxValues && viewBoxValues.length === 4) { + if (!originalWidth && viewBoxValues?.length === 4) { originalWidth = String(viewBoxValues[2]); } - if (!originalHeight && viewBoxValues && viewBoxValues.length === 4) { + + if (!originalHeight && viewBoxValues?.length === 4) { originalHeight = String(viewBoxValues[3]); } - // Default dimensions if still not available originalWidth = originalWidth ? parseFloat(originalWidth) : 300; originalHeight = originalHeight ? parseFloat(originalHeight) : 150; - // Calculate new dimensions let newWidth = originalWidth; let newHeight = originalHeight; if (resizeMethod === 'pixels') { if (dimensionType === 'width') { newWidth = parseInt(width); + if (maintainAspectRatio) { newHeight = Math.round((newWidth / originalWidth) * originalHeight); } else { newHeight = parseInt(height); } } else { - // height newHeight = parseInt(height); + if (maintainAspectRatio) { newWidth = Math.round((newHeight / originalHeight) * originalWidth); } else { @@ -70,17 +70,15 @@ const processImage = async ( } } } else { - // percentage const scale = parseInt(percentage) / 100; + newWidth = Math.round(originalWidth * scale); newHeight = Math.round(originalHeight * scale); } - // Update SVG attributes svgElement.setAttribute('width', String(newWidth)); svgElement.setAttribute('height', String(newHeight)); - // If viewBox isn't already set, add it to preserve scaling if (!viewBox) { svgElement.setAttribute( 'viewBox', @@ -88,134 +86,129 @@ const processImage = async ( ); } - // Serialize the modified SVG document const serializer = new XMLSerializer(); const svgString = serializer.serializeToString(svgDoc); - // Create a new file return new File([svgString], file.name, { type: 'image/svg+xml' }); } catch (error) { console.error('Error processing SVG:', error); - // Fall back to canvas method if SVG processing fails } - } else if (file.type === 'image/gif') { + } + + if (file.type === 'image/gif') { try { - const ffmpeg = new FFmpeg(); + return await runFFmpegTask(async ({ ffmpeg, tempFile }) => { + const inputName = tempFile('.gif'); + const outputName = tempFile('.gif'); - await ffmpeg.load({ - wasmURL: - 'https://cdn.jsdelivr.net/npm/@ffmpeg/core@0.12.9/dist/esm/ffmpeg-core.wasm' - }); + await ffmpeg.writeFile(inputName, await fetchFile(file)); - // Write the input file to memory - await ffmpeg.writeFile('input.gif', await fetchFile(file)); + let scaleFilter = ''; - // Calculate new dimensions - let newWidth = 0; - let newHeight = 0; - let scaleFilter = ''; + if (resizeMethod === 'pixels') { + if (dimensionType === 'width') { + const newWidth = parseInt(width); - if (resizeMethod === 'pixels') { - if (dimensionType === 'width') { - newWidth = parseInt(width); - if (maintainAspectRatio) { - scaleFilter = `scale=${newWidth}:-1`; + scaleFilter = maintainAspectRatio + ? `scale=${newWidth}:-1` + : `scale=${newWidth}:${parseInt(height)}`; } else { - newHeight = parseInt(height); - scaleFilter = `scale=${newWidth}:${newHeight}`; + const newHeight = parseInt(height); + + scaleFilter = maintainAspectRatio + ? `scale=-1:${newHeight}` + : `scale=${parseInt(width)}:${newHeight}`; } } else { - // height - newHeight = parseInt(height); - if (maintainAspectRatio) { - scaleFilter = `scale=-1:${newHeight}`; - } else { - newWidth = parseInt(width); - scaleFilter = `scale=${newWidth}:${newHeight}`; - } + const scale = parseInt(percentage) / 100; + scaleFilter = `scale=iw*${scale}:ih*${scale}`; } - } else { - // percentage - const scale = parseInt(percentage) / 100; - scaleFilter = `scale=iw*${scale}:ih*${scale}`; - } - // Run FFmpeg command - await ffmpeg.exec(['-i', 'input.gif', '-vf', scaleFilter, 'output.gif']); + await ffmpeg.exec([ + '-i', + inputName, + '-vf', + `${scaleFilter},split[a][b];[a]palettegen[p];[b][p]paletteuse`, + outputName + ]); - // Read the output file - const data = await ffmpeg.readFile('output.gif'); + const data = await ffmpeg.readFile(outputName); - // Create a new File object - return new File([data as any], file.name, { type: 'image/gif' }); + return new File([new Uint8Array(data as Uint8Array)], file.name, { + type: 'image/gif' + }); + }); } catch (error) { console.error('Error processing GIF with FFmpeg:', error); - // Fall back to canvas method if FFmpeg processing fails } } - // Create canvas - const canvas = document.createElement('canvas'); - const ctx = canvas.getContext('2d'); - if (ctx == null) return null; - // Load image - const img = new Image(); - img.src = URL.createObjectURL(file); - await img.decode(); + try { + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); - // Calculate new dimensions - let newWidth = img.width; - let newHeight = img.height; + if (!ctx) return null; - if (resizeMethod === 'pixels') { - if (dimensionType === 'width') { - newWidth = parseInt(width); - if (maintainAspectRatio) { - newHeight = Math.round((newWidth / img.width) * img.height); + const img = new Image(); + img.src = URL.createObjectURL(file); + + await img.decode(); + + let newWidth = img.width; + let newHeight = img.height; + + if (resizeMethod === 'pixels') { + if (dimensionType === 'width') { + newWidth = parseInt(width); + + if (maintainAspectRatio) { + newHeight = Math.round((newWidth / img.width) * img.height); + } else { + newHeight = parseInt(height); + } } else { newHeight = parseInt(height); + + if (maintainAspectRatio) { + newWidth = Math.round((newHeight / img.height) * img.width); + } else { + newWidth = parseInt(width); + } } } else { - // height - newHeight = parseInt(height); - if (maintainAspectRatio) { - newWidth = Math.round((newHeight / img.height) * img.width); - } else { - newWidth = parseInt(width); - } + const scale = parseInt(percentage) / 100; + + newWidth = Math.round(img.width * scale); + newHeight = Math.round(img.height * scale); } - } else { - // percentage - const scale = parseInt(percentage) / 100; - newWidth = Math.round(img.width * scale); - newHeight = Math.round(img.height * scale); + + canvas.width = newWidth; + canvas.height = newHeight; + + ctx.drawImage(img, 0, 0, newWidth, newHeight); + + const outputType = file.type || 'image/png'; + + return new Promise((resolve) => { + canvas.toBlob((blob) => { + if (!blob) { + resolve(null); + return; + } + + resolve( + new File([blob], file.name, { + type: outputType + }) + ); + }, outputType); + }); + } catch (error) { + console.error('Error processing image:', error); + return null; } - - // Set canvas dimensions - canvas.width = newWidth; - canvas.height = newHeight; - - // Draw resized image - ctx.drawImage(img, 0, 0, newWidth, newHeight); - - // Determine output type based on input file - let outputType = 'image/png'; - if (file.type) { - outputType = file.type; - } - - // Convert canvas to blob and create file - return new Promise((resolve) => { - canvas.toBlob((blob) => { - if (blob) { - resolve(new File([blob], file.name, { type: outputType })); - } else { - resolve(null); - } - }, outputType); - }); }; export const resizeImages = async ( @@ -234,20 +227,35 @@ export const resizeImages = async ( }) ); - const results = processed.filter((f): f is File => f !== null); + const results = processed.filter((file): file is File => file !== null); - if (results.length === 0) return null; + if (results.length === 0) { + return null; + } - if (results.length === 1) return { results, zipFile: null }; + if (results.length === 1) { + return { + results, + zipFile: null + }; + } const zip = new JSZip(); - results.forEach((file) => zip.file(file.name, file)); - const zipBlob = await zip.generateAsync({ type: 'blob' }); - const zipFile = new File([zipBlob], 'resized-images.zip', { - type: 'application/zip' + + results.forEach((file) => { + zip.file(file.name, file); }); - return { results, zipFile }; + const zipBlob = await zip.generateAsync({ + type: 'blob' + }); + + return { + results, + zipFile: new File([zipBlob], 'resized-images.zip', { + type: 'application/zip' + }) + }; } catch (error) { console.error('Error processing images:', error); return null; From 34a5f8e81f1b5665b5cbda2c83e65ac83823d6e8 Mon Sep 17 00:00:00 2001 From: "Ibrahima G. Coulibaly" Date: Thu, 6 Aug 2026 21:16:02 +0000 Subject: [PATCH 114/114] chore(i18n): update translations --- .idea/workspace.xml | 117 +++++---- public/locales/de/audio.json | 9 +- public/locales/de/time.json | 5 +- public/locales/de/translation.json | 8 +- public/locales/de/video.json | 6 - public/locales/en/audio.json | 4 +- public/locales/en/converters.json | 18 +- public/locales/en/image.json | 402 ++++++++++++++--------------- public/locales/en/json.json | 90 +++---- public/locales/en/number.json | 36 +-- public/locales/en/pdf.json | 16 +- public/locales/en/string.json | 70 ++--- public/locales/en/time.json | 209 +++++++-------- public/locales/en/translation.json | 8 +- public/locales/en/video.json | 28 +- public/locales/es/audio.json | 9 +- public/locales/es/time.json | 5 +- public/locales/es/translation.json | 8 +- public/locales/es/video.json | 6 - public/locales/fr/audio.json | 9 +- public/locales/fr/time.json | 5 +- public/locales/fr/translation.json | 8 +- public/locales/fr/video.json | 6 - public/locales/hi/audio.json | 9 +- public/locales/hi/time.json | 5 +- public/locales/hi/translation.json | 8 +- public/locales/hi/video.json | 6 - public/locales/ja/audio.json | 9 +- public/locales/ja/time.json | 5 +- public/locales/ja/translation.json | 8 +- public/locales/ja/video.json | 6 - public/locales/nl/audio.json | 9 +- public/locales/nl/time.json | 5 +- public/locales/nl/translation.json | 8 +- public/locales/nl/video.json | 6 - public/locales/pt/audio.json | 9 +- public/locales/pt/time.json | 5 +- public/locales/pt/translation.json | 8 +- public/locales/pt/video.json | 6 - public/locales/ru/audio.json | 9 +- public/locales/ru/image.json | 40 +-- public/locales/ru/time.json | 5 +- public/locales/ru/translation.json | 8 +- public/locales/ru/video.json | 6 - public/locales/zh/audio.json | 9 +- public/locales/zh/time.json | 5 +- public/locales/zh/translation.json | 16 +- public/locales/zh/video.json | 6 - 48 files changed, 610 insertions(+), 688 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index b03acf61..4a41825b 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -4,16 +4,22 @@