feat: compress image

This commit is contained in:
Ibrahima G. Coulibaly
2025-04-02 19:18:20 +00:00
parent a93ef11acb
commit 42eb88ffb0
10 changed files with 263 additions and 112 deletions

View File

@@ -1,20 +0,0 @@
[Coding Aider Plan]
## Overview
This plan outlines the refactoring of existing tools to utilize a `ToolContent` component. This will standardize the structure and styling of tool content across the application, improving maintainability and user experience.
## Problem Description
Currently, some tools directly render their content without using a common `ToolContent` component. This leads to inconsistencies in styling, layout, and overall structure. It also makes it harder to apply global changes or updates to the tool content areas.
## Goals
- Identify tools that do not currently use `ToolContent`.
- Implement `ToolContent` in these tools.
- Ensure consistent styling and layout across all tools.
## Additional Notes and Constraints
- The `ToolContent` component should be flexible enough to accommodate the different types of content used by each tool.
- Ensure that the refactoring does not introduce any regressions or break existing functionality.
- Consider creating a subplan if the number of tools requiring changes is large or if individual tools require complex modifications.
## References
- Existing tools that already use `ToolContent` can serve as examples.

View File

@@ -1,9 +0,0 @@
[Coding Aider Plan - Checklist]
- [ ] Create `ToolContent` component if it doesn't exist.
- [ ] Identify tools that do not use `ToolContent`.
- [x] For each identified tool:
- [x] Implement `ToolContent` wrapper.
- [ ] Adjust styling as needed to match existing design.
- [ ] Test the tool to ensure it functions correctly.
- [ ] Review all modified tools to ensure consistency.

View File

@@ -1,6 +0,0 @@
---
files:
- path: src\pages\tools\list\duplicate\index.tsx
readOnly: false
- path: src\pages\tools\list\index.ts
readOnly: false

156
.idea/workspace.xml generated
View File

@@ -4,9 +4,17 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="b30e2810-c4c1-4aad-b134-794e52cc1c7d" name="Changes" comment="feat: gif resize">
<list default="true" id="b30e2810-c4c1-4aad-b134-794e52cc1c7d" name="Changes" comment="docs: readme">
<change afterPath="$PROJECT_DIR$/src/pages/tools/image/generic/compress/index.tsx" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/pages/tools/image/generic/compress/meta.ts" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/pages/tools/image/generic/compress/service.ts" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/pages/tools/image/generic/compress/types.ts" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.coding-aider-plans/refactor_tools_toolcontent.md" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.coding-aider-plans/refactor_tools_toolcontent_checklist.md" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.coding-aider-plans/refactor_tools_toolcontent_context.yaml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/tools/index.ts" beforeDir="false" afterPath="$PROJECT_DIR$/src/tools/index.ts" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/components/result/ToolFileResult.tsx" beforeDir="false" afterPath="$PROJECT_DIR$/src/components/result/ToolFileResult.tsx" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/pages/tools/image/generic/index.ts" beforeDir="false" afterPath="$PROJECT_DIR$/src/pages/tools/image/generic/index.ts" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -23,7 +31,7 @@
<option name="PUSH_AUTO_UPDATE" value="true" />
<option name="RECENT_BRANCH_BY_REPOSITORY">
<map>
<entry key="$PROJECT_DIR$" value="main" />
<entry key="$PROJECT_DIR$" value="image-resize" />
</map>
</option>
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
@@ -151,56 +159,56 @@
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"ASKED_ADD_EXTERNAL_FILES": "true",
"ASKED_SHARE_PROJECT_CONFIGURATION_FILES": "true",
"Docker.Dockerfile build.executor": "Run",
"Docker.Dockerfile.executor": "Run",
"Playwright.Create transparent PNG.should make png color transparent.executor": "Run",
"Playwright.JoinText Component.executor": "Run",
"Playwright.JoinText Component.should merge text pieces with specified join character.executor": "Run",
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.git.unshallow": "true",
"Vitest.compute function (1).executor": "Run",
"Vitest.compute function.executor": "Run",
"Vitest.mergeText.executor": "Run",
"Vitest.mergeText.should merge lines and preserve blank lines when deleteBlankLines is false.executor": "Run",
"Vitest.mergeText.should merge lines, preserve blank lines and trailing spaces when both deleteBlankLines and deleteTrailingSpaces are false.executor": "Run",
"Vitest.parsePageRanges.executor": "Run",
"Vitest.removeDuplicateLines function.executor": "Run",
"Vitest.removeDuplicateLines function.newlines option.executor": "Run",
"Vitest.removeDuplicateLines function.newlines option.should filter newlines when newlines is set to filter.executor": "Run",
"Vitest.replaceText function (regexp mode).should return the original text when passed an invalid regexp.executor": "Run",
"Vitest.replaceText function.executor": "Run",
"Vitest.timeBetweenDates.executor": "Run",
"git-widget-placeholder": "image-resize",
"ignore.virus.scanning.warn.message": "true",
"kotlin-language-version-configured": "true",
"last_opened_file_path": "C:/Users/Ibrahima/IdeaProjects/omni-tools/@types",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"npm.build.executor": "Run",
"npm.dev.executor": "Run",
"npm.lint.executor": "Run",
"npm.prebuild.executor": "Run",
"npm.script:create:tool.executor": "Run",
"npm.test.executor": "Run",
"npm.test:e2e.executor": "Run",
"npm.test:e2e:run.executor": "Run",
"prettierjs.PrettierConfiguration.Package": "C:\\Users\\Ibrahima\\IdeaProjects\\omni-tools\\node_modules\\prettier",
"project.structure.last.edited": "Problems",
"project.structure.proportion": "0.0",
"project.structure.side.proportion": "0.2",
"settings.editor.selected.configurable": "refactai_advanced_settings",
"ts.external.directory.path": "C:\\Users\\Ibrahima\\IdeaProjects\\omni-tools\\node_modules\\typescript\\lib",
"vue.rearranger.settings.migration": "true"
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;ASKED_ADD_EXTERNAL_FILES&quot;: &quot;true&quot;,
&quot;ASKED_SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;Docker.Dockerfile build.executor&quot;: &quot;Run&quot;,
&quot;Docker.Dockerfile.executor&quot;: &quot;Run&quot;,
&quot;Playwright.Create transparent PNG.should make png color transparent.executor&quot;: &quot;Run&quot;,
&quot;Playwright.JoinText Component.executor&quot;: &quot;Run&quot;,
&quot;Playwright.JoinText Component.should merge text pieces with specified join character.executor&quot;: &quot;Run&quot;,
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.git.unshallow&quot;: &quot;true&quot;,
&quot;Vitest.compute function (1).executor&quot;: &quot;Run&quot;,
&quot;Vitest.compute function.executor&quot;: &quot;Run&quot;,
&quot;Vitest.mergeText.executor&quot;: &quot;Run&quot;,
&quot;Vitest.mergeText.should merge lines and preserve blank lines when deleteBlankLines is false.executor&quot;: &quot;Run&quot;,
&quot;Vitest.mergeText.should merge lines, preserve blank lines and trailing spaces when both deleteBlankLines and deleteTrailingSpaces are false.executor&quot;: &quot;Run&quot;,
&quot;Vitest.parsePageRanges.executor&quot;: &quot;Run&quot;,
&quot;Vitest.removeDuplicateLines function.executor&quot;: &quot;Run&quot;,
&quot;Vitest.removeDuplicateLines function.newlines option.executor&quot;: &quot;Run&quot;,
&quot;Vitest.removeDuplicateLines function.newlines option.should filter newlines when newlines is set to filter.executor&quot;: &quot;Run&quot;,
&quot;Vitest.replaceText function (regexp mode).should return the original text when passed an invalid regexp.executor&quot;: &quot;Run&quot;,
&quot;Vitest.replaceText function.executor&quot;: &quot;Run&quot;,
&quot;Vitest.timeBetweenDates.executor&quot;: &quot;Run&quot;,
&quot;git-widget-placeholder&quot;: &quot;main&quot;,
&quot;ignore.virus.scanning.warn.message&quot;: &quot;true&quot;,
&quot;kotlin-language-version-configured&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;C:/Users/Ibrahima/IdeaProjects/omni-tools/@types&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;npm.build.executor&quot;: &quot;Run&quot;,
&quot;npm.dev.executor&quot;: &quot;Run&quot;,
&quot;npm.lint.executor&quot;: &quot;Run&quot;,
&quot;npm.prebuild.executor&quot;: &quot;Run&quot;,
&quot;npm.script:create:tool.executor&quot;: &quot;Run&quot;,
&quot;npm.test.executor&quot;: &quot;Run&quot;,
&quot;npm.test:e2e.executor&quot;: &quot;Run&quot;,
&quot;npm.test:e2e:run.executor&quot;: &quot;Run&quot;,
&quot;prettierjs.PrettierConfiguration.Package&quot;: &quot;C:\\Users\\Ibrahima\\IdeaProjects\\omni-tools\\node_modules\\prettier&quot;,
&quot;project.structure.last.edited&quot;: &quot;Problems&quot;,
&quot;project.structure.proportion&quot;: &quot;0.0&quot;,
&quot;project.structure.side.proportion&quot;: &quot;0.2&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;refactai_advanced_settings&quot;,
&quot;ts.external.directory.path&quot;: &quot;C:\\Users\\Ibrahima\\IdeaProjects\\omni-tools\\node_modules\\typescript\\lib&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
}
}]]></component>
}</component>
<component name="ReactDesignerToolWindowState">
<option name="myId2Visible">
<map>
@@ -398,22 +406,10 @@
<workItem from="1743103182313" duration="4264000" />
<workItem from="1743348610793" duration="21855000" />
<workItem from="1743556259185" duration="7150000" />
</task>
<task id="LOCAL-00131" summary="style: tool categories">
<option name="closed" value="true" />
<created>1740661744828</created>
<option name="number" value="00131" />
<option name="presentableId" value="LOCAL-00131" />
<option name="project" value="LOCAL" />
<updated>1740661744828</updated>
</task>
<task id="LOCAL-00132" summary="chore: compute only if value">
<option name="closed" value="true" />
<created>1740661864615</created>
<option name="number" value="00132" />
<option name="presentableId" value="LOCAL-00132" />
<option name="project" value="LOCAL" />
<updated>1740661864615</updated>
<workItem from="1743569964813" duration="352000" />
<workItem from="1743570403937" duration="109000" />
<workItem from="1743607343305" duration="20000" />
<workItem from="1743619618671" duration="1756000" />
</task>
<task id="LOCAL-00133" summary="chore: remove prettify test">
<option name="closed" value="true" />
@@ -791,7 +787,23 @@
<option name="project" value="LOCAL" />
<updated>1743567906528</updated>
</task>
<option name="localTasksCounter" value="180" />
<task id="LOCAL-00180" summary="chore: add color">
<option name="closed" value="true" />
<created>1743569026879</created>
<option name="number" value="00180" />
<option name="presentableId" value="LOCAL-00180" />
<option name="project" value="LOCAL" />
<updated>1743569026879</updated>
</task>
<task id="LOCAL-00181" summary="docs: readme">
<option name="closed" value="true" />
<created>1743569711302</created>
<option name="number" value="00181" />
<option name="presentableId" value="LOCAL-00181" />
<option name="project" value="LOCAL" />
<updated>1743569711302</updated>
</task>
<option name="localTasksCounter" value="182" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
@@ -838,8 +850,6 @@
<option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" />
<option name="CHECK_NEW_TODO" value="false" />
<option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" />
<MESSAGE value="chore: remove unnecessary files" />
<MESSAGE value="refactor: validateJson" />
<MESSAGE value="feat: missing tools" />
<MESSAGE value="refactor: use ToolContent" />
<MESSAGE value="fix: prettify json" />
@@ -863,7 +873,9 @@
<MESSAGE value="feat: image resize init" />
<MESSAGE value="feat: svg resize" />
<MESSAGE value="feat: gif resize" />
<option name="LAST_COMMIT_MESSAGE" value="feat: gif resize" />
<MESSAGE value="chore: add color" />
<MESSAGE value="docs: readme" />
<option name="LAST_COMMIT_MESSAGE" value="docs: readme" />
</component>
<component name="XSLT-Support.FileAssociations.UIState">
<expand />

View File

@@ -15,7 +15,7 @@ export default function ToolFileResult({
}: {
title?: string;
value: File | null;
extension: string;
extension?: string;
loading?: boolean;
loadingText?: string;
}) {
@@ -50,9 +50,11 @@ export default function ToolFileResult({
const handleDownload = () => {
if (value) {
const hasExtension = value.name.includes('.');
const filename = hasExtension ? value.name : `${value.name}.${extension}`;
let filename: string = value.name;
if (extension) {
const hasExtension = filename.includes('.');
filename = hasExtension ? filename : `${filename}.${extension}`;
}
const blob = new Blob([value], { type: value.type });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');

View File

@@ -0,0 +1,123 @@
import React, { useContext, useState } from 'react';
import { InitialValuesType } from './types';
import { compressImage } from './service';
import ToolContent from '@components/ToolContent';
import ToolImageInput from '@components/input/ToolImageInput';
import { ToolComponentProps } from '@tools/defineTool';
import ToolFileResult from '@components/result/ToolFileResult';
import TextFieldWithDesc from '@components/options/TextFieldWithDesc';
import { Box } from '@mui/material';
import Typography from '@mui/material/Typography';
import { CustomSnackBarContext } from '../../../../../contexts/CustomSnackBarContext';
import { updateNumberField } from '@utils/string';
const initialValues: InitialValuesType = {
maxFileSizeInMB: 1.0,
quality: 80
};
export default function CompressImage({ title }: ToolComponentProps) {
const [input, setInput] = useState<File | null>(null);
const [result, setResult] = useState<File | null>(null);
const [isProcessing, setIsProcessing] = useState<boolean>(false);
const [originalSize, setOriginalSize] = useState<number | null>(null); // Store original file size
const [compressedSize, setCompressedSize] = useState<number | null>(null); // Store compressed file size
const { showSnackBar } = useContext(CustomSnackBarContext);
const compute = async (values: InitialValuesType, input: File | null) => {
if (!input) return;
setOriginalSize(input.size);
try {
setIsProcessing(true);
const compressed = await compressImage(input, values);
if (compressed) {
setResult(compressed);
setCompressedSize(compressed.size);
} else {
showSnackBar('Failed to compress image. Please try again.', 'error');
}
} catch (err) {
console.error('Error in compression:', err);
} finally {
setIsProcessing(false);
}
};
return (
<ToolContent
title={title}
input={input}
inputComponent={
<ToolImageInput
value={input}
onChange={setInput}
accept={['image/*']}
title={'Input image'}
/>
}
resultComponent={
<ToolFileResult
title={'Compressed image'}
value={result}
loading={isProcessing}
/>
}
initialValues={initialValues}
getGroups={({ values, updateField }) => [
{
title: 'Compression options',
component: (
<Box>
<TextFieldWithDesc
label="Max File Size (MB)"
name="maxFileSizeInMB"
type="number"
inputProps={{ min: 0.1, step: 0.1 }}
description="Maximum file size in megabytes"
onOwnChange={(value) =>
updateNumberField(value, 'maxFileSizeInMB', updateField)
}
value={values.maxFileSizeInMB}
/>
<TextFieldWithDesc
label="Quality (%)"
name="quality"
type="number"
inputProps={{ min: 10, max: 100, step: 1 }}
description="Image quality percentage (lower means smaller file size)"
onOwnChange={(value) =>
updateNumberField(value, 'quality', updateField)
}
value={values.quality}
/>
</Box>
)
},
{
title: 'File sizes',
component: (
<Box>
<Box>
{originalSize !== null && (
<Typography>
Original Size: {(originalSize / 1024).toFixed(2)} KB
</Typography>
)}
{compressedSize !== null && (
<Typography>
Compressed Size: {(compressedSize / 1024).toFixed(2)} KB
</Typography>
)}
</Box>
</Box>
)
}
]}
compute={compute}
setInput={setInput}
/>
);
}

View File

@@ -0,0 +1,14 @@
import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('image-generic', {
name: 'Compress Image',
path: 'compress',
component: lazy(() => import('./index')),
icon: 'material-symbols-light:compress-rounded',
description:
'Compress images to reduce file size while maintaining reasonable quality.',
shortDescription:
'Compress images to reduce file size while maintaining reasonable quality.',
keywords: ['image', 'compress', 'reduce', 'quality']
});

View File

@@ -0,0 +1,30 @@
import { InitialValuesType } from './types';
import imageCompression from 'browser-image-compression';
export const compressImage = async (
file: File,
options: InitialValuesType
): Promise<File | null> => {
try {
const { maxFileSizeInMB, quality } = options;
// Configuration for the compression library
const compressionOptions = {
maxSizeMB: maxFileSizeInMB,
maxWidthOrHeight: 1920, // Reasonable default for most use cases
useWebWorker: true,
initialQuality: quality / 100 // Convert percentage to decimal
};
// Compress the image
const compressedFile = await imageCompression(file, compressionOptions);
// Create a new file with the original name
return new File([compressedFile], file.name, {
type: compressedFile.type
});
} catch (error) {
console.error('Error compressing image:', error);
return null;
}
};

View File

@@ -0,0 +1,4 @@
export interface InitialValuesType {
maxFileSizeInMB: number;
quality: number;
}

View File

@@ -1,3 +1,4 @@
import { tool as resizeImage } from './resize/meta';
import { tool as compressImage } from './compress/meta';
export const imageGenericTools = [resizeImage];
export const imageGenericTools = [resizeImage, compressImage];