diff --git a/README.md b/README.md index 1c04fa9c..fb051ea5 100644 --- a/README.md +++ b/README.md @@ -154,16 +154,16 @@ The translation files are [here](public/locales). Only edit these if you are a d | Language | Translation status | Missing keys | |----------|--------------------|--------------| -| uk - Ukrainian | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100%` | 0 | -| zh - Chinese | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░ 72%` | 478 | -| hi - Hindi | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 71%` | 505 | -| ru - Russian | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 71%` | 493 | -| de - German | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 70%` | 515 | -| es - Spanish | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 70%` | 515 | -| fr - French | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 70%` | 515 | -| ja - Japanese | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 70%` | 515 | -| nl - Dutch | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 70%` | 515 | -| pt - Portuguese | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 70%` | 515 | +| uk - Ukrainian | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░ 98%` | 32 | +| zh - Chinese | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 71%` | 510 | +| ru - Russian | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 70%` | 525 | +| de - German | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 69%` | 547 | +| es - Spanish | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 69%` | 547 | +| fr - French | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 69%` | 547 | +| hi - Hindi | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 69%` | 537 | +| ja - Japanese | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 69%` | 547 | +| nl - Dutch | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 69%` | 547 | +| pt - Portuguese | `▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░ 69%` | 547 | ## ⭐ Star History diff --git a/public/locales/en/image.json b/public/locales/en/image.json index c887a62e..3a2ba244 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -22,7 +22,34 @@ "changeOpacity": { "description": "Easily adjust the transparency of your images. Simply upload your image, use the slider to set the desired opacity level between 0 (fully transparent) and 1 (fully opaque), and download the modified image.", "shortDescription": "Adjust transparency of images", - "title": "Change image Opacity" + "title": "Change image Opacity", + "inputTitle": "Input image", + "resultTitle": "Processed Image", + "options": { + "opacitySettings": "Opacity Settings", + "opacityDescription": "Set opacity between 0 (transparent) and 1 (opaque)", + "solidOpacityTitle": "Apply Solid Opacity", + "solidOpacityDescription": "Set the same opacity level for all pixels", + "gradientOpacityTitle": "Apply Gradient Opacity", + "gradientOpacityDescription": "Change opacity in a gradient", + "gradientType": "Gradient Type", + "linearOpacity": "Linear opacity", + "radialOpacity": "Radial opacity", + "opacityArea": "Opacity Area", + "leftPosition": "Left position", + "topPosition": "Top position", + "width": "Width", + "height": "Height", + "backgroundOptions": "Background Options", + "transparentAlpha": "Transparent (Alpha)", + "transparentAlphaDescription": "Preserve image transparency (default)", + "solidColor": "Solid Color", + "solidColorDescription": "Composite image over a solid background color", + "chooseBackgroundColor": "Choose background color", + "insideOut": "Inside -> Outside", + "outsideIn": "Outside -> Inside", + "gradientDirection": "Gradient Direction" + } }, "compress": { "compressedSize": "Total compressed size", diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json index 3b20b654..8cec4c81 100644 --- a/public/locales/en/translation.json +++ b/public/locales/en/translation.json @@ -115,7 +115,7 @@ "inputFooter": { "clear": "Clear", "copyToClipboard": "Copy to clipboard", - "importFromFile": "Import from file" + "importFromFile": "Select files" }, "list": { "group": { diff --git a/public/locales/en/video.json b/public/locales/en/video.json index 124e1761..ae701977 100644 --- a/public/locales/en/video.json +++ b/public/locales/en/video.json @@ -111,7 +111,11 @@ "resultTitle": "Animated GIF", "loadingText": "Creating GIF...", "frameOptions": "Frame Options", - "frameDelayDescription": "How long each frame is displayed, in milliseconds (e.g. 500 = 0.5 s per frame)" + "frameDelayDescription": "How long each frame is displayed, in milliseconds (e.g. 500 = 0.5 s per frame)", + "frameRateDescription": "Set the animation speed in frames per second (FPS)", + "frameRateValueDescription": "Set the desired value", + "frameDelay": "Frame delay", + "frameRate": "Frames per second (FPS)" } }, "loop": { diff --git a/public/locales/en/xml.json b/public/locales/en/xml.json index 8acd4fcd..18b2e0a3 100644 --- a/public/locales/en/xml.json +++ b/public/locales/en/xml.json @@ -6,6 +6,11 @@ "resultTitle": "Beautified XML", "shortDescription": "Format and beautify XML code", "title": "XML Beautifier", + "options": { + "title": "Options", + "preserveAttributesTitle": "Preserve Attributes", + "preserveAttributesDesc": "Preserve the original XML attribute formatting and order." + }, "toolInfo": { "description": "This tool allows you to format XML data with proper indentation and spacing, making it more readable and easier to work with.", "title": "XML Beautifier" diff --git a/src/pages/tools/csv/csv-rows-to-columns/csv-rows-to-columns.service.test.ts b/src/pages/tools/csv/csv-rows-to-columns/csv-rows-to-columns.service.test.ts index 7faf0e7f..6cb849ea 100644 --- a/src/pages/tools/csv/csv-rows-to-columns/csv-rows-to-columns.service.test.ts +++ b/src/pages/tools/csv/csv-rows-to-columns/csv-rows-to-columns.service.test.ts @@ -58,4 +58,16 @@ describe('csvRowsToColumns', () => { 'Variety,Arabica,Robusta,Liberica,Mocha\nOrigin,Ethiopia,Africa,Philippines,1x' ); }); + + it('should remove blank lines', () => { + const input = 'a,b\n\n1,2\n\nx,y'; + const result = csvRowsToColumns(input, false, '', '#'); + expect(result).toBe('a,1,x\nb,2,y'); + }); + + it('should remove lines that contain only whitespace', () => { + const input = 'a,b\n \n1,2'; + const result = csvRowsToColumns(input, false, '', '#'); + expect(result).toBe('a,1\nb,2'); + }); }); diff --git a/src/pages/tools/csv/csv-rows-to-columns/service.ts b/src/pages/tools/csv/csv-rows-to-columns/service.ts index 614043fc..005fd643 100644 --- a/src/pages/tools/csv/csv-rows-to-columns/service.ts +++ b/src/pages/tools/csv/csv-rows-to-columns/service.ts @@ -25,7 +25,9 @@ export function csvRowsToColumns( .split('\n') .map((row) => row.split(',')) .filter( - (row) => row.length > 0 && !row[0].trim().startsWith(commentCharacter) + (row) => + !(row.length === 1 && row[0].trim() === '') && + !row[0].trim().startsWith(commentCharacter) ); const columnCount = Math.max(...rows.map((row) => row.length)); for (let i = 0; i < rows.length; i++) { diff --git a/src/pages/tools/image/generic/change-opacity/index.tsx b/src/pages/tools/image/generic/change-opacity/index.tsx index 5aaa9950..beb6c844 100644 --- a/src/pages/tools/image/generic/change-opacity/index.tsx +++ b/src/pages/tools/image/generic/change-opacity/index.tsx @@ -1,96 +1,250 @@ -import React, { useState } from 'react'; +import React, { useState, useMemo, useEffect } from 'react'; import ToolImageInput from '@components/input/ToolImageInput'; import ToolFileResult from '@components/result/ToolFileResult'; import { changeOpacity } from './service'; import ToolContent from '@components/ToolContent'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; -import { CardExampleType } from '@components/examples/ToolExamples'; +import SelectWithDesc from '@components/options/SelectWithDesc'; +import ColorSelector from '@components/options/ColorSelector'; import { ToolComponentProps } from '@tools/defineTool'; +import { GetGroupsType } from '@components/options/ToolOptions'; import { updateNumberField } from '@utils/string'; import { Box } from '@mui/material'; import SimpleRadio from '@components/options/SimpleRadio'; +import { InitialValuesType } from './types'; +import { debounce } from 'lodash'; +import { useTranslation } from 'react-i18next'; +import { getImageDimensions, getMaxAreaPosition } from '@utils/image'; -type InitialValuesType = { - opacity: number; - mode: 'solid' | 'gradient'; - gradientType: 'linear' | 'radial'; - gradientDirection: 'left-to-right' | 'inside-out'; - areaLeft: number; - areaTop: number; - areaWidth: number; - areaHeight: number; -}; - -const initialValues: InitialValuesType = { +const getInitialValues = ( + width: number, + height: number +): InitialValuesType => ({ opacity: 0.5, mode: 'solid', gradientType: 'linear', - gradientDirection: 'left-to-right', + gradientDirection: 'inside-out', + backgroundMode: 'transparent', + backgroundColor: '#ffffff', areaLeft: 0, areaTop: 0, - areaWidth: 100, - areaHeight: 100 -}; - -const exampleCards: CardExampleType[] = [ - { - title: 'Semi-transparent PNG', - description: 'Make an image 50% transparent', - sampleOptions: { - opacity: 0.5, - mode: 'solid', - gradientType: 'linear', - gradientDirection: 'left-to-right', - areaLeft: 0, - areaTop: 0, - areaWidth: 100, - areaHeight: 100 - }, - sampleResult: '' - }, - { - title: 'Slightly Faded PNG', - description: 'Create a subtle transparency effect', - sampleOptions: { - opacity: 0.8, - mode: 'solid', - gradientType: 'linear', - gradientDirection: 'left-to-right', - areaLeft: 0, - areaTop: 0, - areaWidth: 100, - areaHeight: 100 - }, - sampleResult: '' - }, - { - title: 'Radial Gradient Opacity', - description: 'Apply a radial gradient opacity effect', - sampleOptions: { - opacity: 0.8, - mode: 'gradient', - gradientType: 'radial', - gradientDirection: 'inside-out', - areaLeft: 25, - areaTop: 25, - areaWidth: 50, - areaHeight: 50 - }, - sampleResult: '' - } -]; - + areaWidth: width, + areaHeight: height +}); export default function ChangeOpacity({ title }: ToolComponentProps) { + const { t } = useTranslation('image'); const [input, setInput] = useState(null); const [result, setResult] = useState(null); + const [imageSize, setImageSize] = useState({ + width: 0, + height: 0 + }); + + useEffect(() => { + if (!input) { + setImageSize({ width: 0, height: 0 }); + return; + } + + getImageDimensions(input).then(setImageSize); + }, [input]); + + const initialValues = useMemo( + () => getInitialValues(imageSize.width, imageSize.height), + [imageSize.width, imageSize.height] + ); + const compute = (values: InitialValuesType, input: any) => { if (input) { changeOpacity(input, values).then(setResult); } }; + + const debouncedCompute = useMemo(() => debounce(compute, 1000), []); + + useEffect(() => { + return () => { + debouncedCompute.cancel(); + }; + }, [debouncedCompute]); + + const getGroups: GetGroupsType | null = ({ + values, + updateField + }) => [ + { + title: t('changeOpacity.options.opacitySettings'), + component: ( + + + updateNumberField(val, 'opacity', updateField) + } + type="number" + inputProps={{ step: 0.1, min: 0, max: 1 }} + /> + updateField('mode', 'solid')} + checked={values.mode === 'solid'} + description={t('changeOpacity.options.solidOpacityDescription')} + title={t('changeOpacity.options.solidOpacityTitle')} + /> + updateField('mode', 'gradient')} + checked={values.mode === 'gradient'} + description={t('changeOpacity.options.gradientOpacityDescription')} + title={t('changeOpacity.options.gradientOpacityTitle')} + /> + + {values.mode === 'gradient' && ( + + { + updateField('gradientType', value); + + if (value === 'linear') { + updateField('gradientDirection', 'left-to-right'); + } else { + updateField('gradientDirection', 'inside-out'); + } + }} + description={t('changeOpacity.options.gradientType')} + /> + + )} + + {values.gradientType === 'radial' && ( + + updateField('gradientDirection', value)} + description={t('changeOpacity.options.gradientDirection')} + /> + + )} + + ) + }, + ...(values.mode === 'gradient' + ? [ + { + title: t('changeOpacity.options.opacityArea'), + component: ( + + + updateNumberField(val, 'areaLeft', updateField) + } + inputProps={{ + min: 0, + max: getMaxAreaPosition(imageSize.width, values.areaWidth) + }} + type="number" + /> + + + updateNumberField(val, 'areaTop', updateField) + } + inputProps={{ + min: 0, + max: getMaxAreaPosition(imageSize.height, values.areaHeight) + }} + type="number" + /> + + + updateNumberField(val, 'areaWidth', updateField) + } + inputProps={{ + min: 1, + max: imageSize.width || undefined + }} + type="number" + /> + + + updateNumberField(val, 'areaHeight', updateField) + } + inputProps={{ + min: 1, + max: imageSize.height || undefined + }} + type="number" + /> + + ) + } + ] + : []), + { + title: t('changeOpacity.options.backgroundOptions'), + component: ( + + updateField('backgroundMode', 'transparent')} + checked={values.backgroundMode === 'transparent'} + description={t('changeOpacity.options.transparentAlphaDescription')} + title={t('changeOpacity.options.transparentAlpha')} + /> + updateField('backgroundMode', 'color')} + checked={values.backgroundMode === 'color'} + description={t('changeOpacity.options.solidColorDescription')} + title={t('changeOpacity.options.solidColor')} + /> + {values.backgroundMode === 'color' && ( + + updateField('backgroundColor', val)} + description={t('changeOpacity.options.chooseBackgroundColor')} + inputProps={{ 'data-testid': 'background-color-input' }} + /> + + )} + + ) + } + ]; + return ( } resultComponent={ - + } initialValues={initialValues} - // exampleCards={exampleCards} - getGroups={({ values, updateField }) => [ - { - title: 'Opacity Settings', - component: ( - - - updateNumberField(val, 'opacity', updateField) - } - type="number" - inputProps={{ step: 0.1, min: 0, max: 1 }} - /> - updateField('mode', 'solid')} - checked={values.mode === 'solid'} - description={'Set the same opacity level for all pixels'} - title={'Apply Solid Opacity'} - /> - updateField('mode', 'gradient')} - checked={values.mode === 'gradient'} - description={'Change opacity in a gradient'} - title={'Apply Gradient Opacity'} - /> - - ) - }, - { - title: 'Gradient Options', - component: ( - - updateField('gradientType', 'linear')} - checked={values.gradientType === 'linear'} - description={'Linear opacity direction'} - title={'Linear Gradient'} - /> - updateField('gradientType', 'radial')} - checked={values.gradientType === 'radial'} - description={'Radial opacity direction'} - title={'Radial Gradient'} - /> - - ) - }, - { - title: 'Opacity Area', - component: ( - - - updateNumberField(val, 'areaLeft', updateField) - } - type="number" - /> - - updateNumberField(val, 'areaTop', updateField) - } - type="number" - /> - - updateNumberField(val, 'areaWidth', updateField) - } - type="number" - /> - - updateNumberField(val, 'areaHeight', updateField) - } - type="number" - /> - - ) - } - ]} - compute={compute} + getGroups={getGroups} + compute={debouncedCompute} /> ); } diff --git a/src/pages/tools/image/generic/change-opacity/service.ts b/src/pages/tools/image/generic/change-opacity/service.ts index efcecaf3..4a31c239 100644 --- a/src/pages/tools/image/generic/change-opacity/service.ts +++ b/src/pages/tools/image/generic/change-opacity/service.ts @@ -1,17 +1,9 @@ -interface OpacityOptions { - opacity: number; - mode: 'solid' | 'gradient'; - gradientType: 'linear' | 'radial'; - gradientDirection: 'left-to-right' | 'inside-out'; - areaLeft: number; - areaTop: number; - areaWidth: number; - areaHeight: number; -} +import { InitialValuesType } from './types'; +import { parseColorToRgb } from '@utils/color'; export async function changeOpacity( file: File, - options: OpacityOptions + options: InitialValuesType ): Promise { return new Promise((resolve, reject) => { const reader = new FileReader(); @@ -50,20 +42,33 @@ export async function changeOpacity( }); } +function getGradientRgbTriplet(options: InitialValuesType): string { + if (options.backgroundMode === 'color' && options.backgroundColor) { + const { r, g, b } = parseColorToRgb(options.backgroundColor); + return `${r},${g},${b}`; + } + return '255,255,255'; // fallback: white +} + function applySolidOpacity( ctx: CanvasRenderingContext2D, img: HTMLImageElement, - options: OpacityOptions + options: InitialValuesType ) { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); + if (options.backgroundMode === 'color' && options.backgroundColor) { + ctx.fillStyle = options.backgroundColor; + ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); + } ctx.globalAlpha = options.opacity; ctx.drawImage(img, 0, 0); + ctx.globalAlpha = 1.0; } function applyGradientOpacity( ctx: CanvasRenderingContext2D, img: HTMLImageElement, - options: OpacityOptions + options: InitialValuesType ) { const { areaLeft, areaTop, areaWidth, areaHeight } = options; @@ -81,28 +86,30 @@ function applyGradientOpacity( function createLinearGradient( ctx: CanvasRenderingContext2D, - options: OpacityOptions + options: InitialValuesType ) { - const { areaLeft, areaTop, areaWidth, areaHeight } = options; + const { areaLeft, areaTop, areaWidth } = options; + const rgb = getGradientRgbTriplet(options); const gradient = ctx.createLinearGradient( areaLeft, areaTop, areaLeft + areaWidth, areaTop ); - gradient.addColorStop(0, `rgba(255,255,255,${options.opacity})`); - gradient.addColorStop(1, 'rgba(255,255,255,0)'); + gradient.addColorStop(0, `rgba(${rgb},${options.opacity})`); + gradient.addColorStop(1, `rgba(${rgb},0)`); return gradient; } function createRadialGradient( ctx: CanvasRenderingContext2D, - options: OpacityOptions + options: InitialValuesType ) { const { areaLeft, areaTop, areaWidth, areaHeight } = options; const centerX = areaLeft + areaWidth / 2; const centerY = areaTop + areaHeight / 2; const radius = Math.min(areaWidth, areaHeight) / 2; + const rgb = getGradientRgbTriplet(options); const gradient = ctx.createRadialGradient( centerX, @@ -114,11 +121,11 @@ function createRadialGradient( ); if (options.gradientDirection === 'inside-out') { - gradient.addColorStop(0, `rgba(255,255,255,${options.opacity})`); - gradient.addColorStop(1, 'rgba(255,255,255,0)'); + gradient.addColorStop(0, `rgba(${rgb},${options.opacity})`); + gradient.addColorStop(1, `rgba(${rgb},0)`); } else { - gradient.addColorStop(0, 'rgba(255,255,255,0)'); - gradient.addColorStop(1, `rgba(255,255,255,${options.opacity})`); + gradient.addColorStop(0, `rgba(${rgb},0)`); + gradient.addColorStop(1, `rgba(${rgb},${options.opacity})`); } return gradient; diff --git a/src/pages/tools/image/generic/change-opacity/types.ts b/src/pages/tools/image/generic/change-opacity/types.ts new file mode 100644 index 00000000..1aa1412e --- /dev/null +++ b/src/pages/tools/image/generic/change-opacity/types.ts @@ -0,0 +1,12 @@ +export type InitialValuesType = { + opacity: number; + mode: 'solid' | 'gradient'; + gradientType: 'linear' | 'radial'; + gradientDirection: 'left-to-right' | 'inside-out' | 'outside-in'; + backgroundMode: 'transparent' | 'color'; + backgroundColor: string; + areaLeft: number; + areaTop: number; + areaWidth: number; + areaHeight: number; +}; diff --git a/src/pages/tools/image/generic/compress/compress.service.test.ts b/src/pages/tools/image/generic/compress/compress.service.test.ts new file mode 100644 index 00000000..fe374380 --- /dev/null +++ b/src/pages/tools/image/generic/compress/compress.service.test.ts @@ -0,0 +1,28 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import imageCompression from 'browser-image-compression'; +import { compressImages } from './service'; + +vi.mock('browser-image-compression', () => ({ + default: vi.fn() +})); + +describe('compressImages', () => { + beforeEach(() => { + vi.mocked(imageCompression).mockResolvedValue( + new File(['compressed'], 'photo.jpg', { type: 'image/jpeg' }) + ); + }); + + it('preserves JPEG EXIF metadata while compressing', async () => { + const input = new File(['original'], 'photo.jpg', { + type: 'image/jpeg' + }); + + await compressImages([input], { maxFileSizeInMB: 1, quality: 80 }); + + expect(imageCompression).toHaveBeenCalledWith( + input, + expect.objectContaining({ preserveExif: true }) + ); + }); +}); diff --git a/src/pages/tools/image/generic/compress/service.ts b/src/pages/tools/image/generic/compress/service.ts index 3b3afe80..6b6178e5 100644 --- a/src/pages/tools/image/generic/compress/service.ts +++ b/src/pages/tools/image/generic/compress/service.ts @@ -14,6 +14,7 @@ export const compressImages = async ( maxSizeMB: maxFileSizeInMB, maxWidthOrHeight: 1920, // Reasonable default for most use cases useWebWorker: true, + preserveExif: true, initialQuality: quality / 100 // Convert percentage to decimal }; diff --git a/src/pages/tools/list/sort/service.ts b/src/pages/tools/list/sort/service.ts index f6fb5fa8..c6d2895c 100644 --- a/src/pages/tools/list/sort/service.ts +++ b/src/pages/tools/list/sort/service.ts @@ -60,7 +60,7 @@ function customAlphabeticSort( return a.toLowerCase().localeCompare(b.toLowerCase()); } else { // Case-sensitive comparison - return a.charCodeAt(0) - b.charCodeAt(0); + return a === b ? 0 : a < b ? -1 : 1; } } diff --git a/src/pages/tools/list/sort/sort.service.test.ts b/src/pages/tools/list/sort/sort.service.test.ts index 3becba4d..d90afec1 100644 --- a/src/pages/tools/list/sort/sort.service.test.ts +++ b/src/pages/tools/list/sort/sort.service.test.ts @@ -183,6 +183,12 @@ describe('numericSort function', () => { }); // CASE SENSITIVE TEST + it('should compare the full string when prefixes match', () => { + const result = alphabeticSort(['az', 'aa'], true, ',', false, true); + + expect(result).toBe('aa,az'); + }); + it('should sort a list of string (uppercase) in decreasing order with comma separator ', () => { const array: string[] = ['Apple', 'Pineaple', 'Lemon', 'Orange']; const increasing: boolean = false; diff --git a/src/pages/tools/number/sum/index.tsx b/src/pages/tools/number/sum/index.tsx index d649f995..08f0d1c2 100644 --- a/src/pages/tools/number/sum/index.tsx +++ b/src/pages/tools/number/sum/index.tsx @@ -130,7 +130,7 @@ export default function SumNumbers({ title }: ToolComponentProps) { { title: t('sum.numberExtraction'), component: extractionTypes.map( - ({ title, description, type, withTextField, textValueAccessor }) => + ({ title, type, withTextField, textValueAccessor }) => withTextField ? ( part.trim()) + .filter((part) => part !== '' && !Number.isNaN(Number(part))) + .map(Number); +} export const compute = ( input: string, @@ -12,26 +25,17 @@ export const compute = ( printRunningSum: boolean, separator: string ): string => { - let numbers: number[] = []; - if (extractionType === 'smart') { - numbers = getAllNumbers(input); - } else { - const parts = input.split(separator); - // Filter out and convert parts that are numbers - numbers = parts - .filter((part) => !isNaN(Number(part)) && part.trim() !== '') - .map(Number); - } + const numbers = + extractionType === 'smart' + ? getAllNumbers(input) + : getDelimitedNumbers(input, separator); + if (printRunningSum) { - let result: string = ''; - let sum: number = 0; - for (const i of numbers) { - sum = sum + i; - result = result + sum + '\n'; - } - return result; - } else - return numbers - .reduce((previousValue, currentValue) => previousValue + currentValue, 0) - .toString(); + let sum = 0; + return ( + numbers.map((n) => (sum += n)).join('\n') + (numbers.length ? '\n' : '') + ); + } + + return numbers.reduce((acc, n) => acc + n, 0).toString(); }; diff --git a/src/pages/tools/number/sum/sum.service.test.ts b/src/pages/tools/number/sum/sum.service.test.ts index 944a28a9..c576fcb7 100644 --- a/src/pages/tools/number/sum/sum.service.test.ts +++ b/src/pages/tools/number/sum/sum.service.test.ts @@ -61,4 +61,16 @@ describe('compute function', () => { const result = compute(input, 'delimiter', false, ';'); expect(result).toBe('13'); }); + + it('should treat a literal \\n separator as a real line break (multiline sum)', () => { + const input = '1\n2\n4'; + const result = compute(input, 'delimiter', false, '\\n'); + expect(result).toBe('7'); + }); + + it('should return running sum with a literal \\n separator', () => { + const input = '1\n2\n4'; + const result = compute(input, 'delimiter', true, '\\n'); + expect(result).toBe('1\n3\n7\n'); + }); }); diff --git a/src/pages/tools/string/split/service.ts b/src/pages/tools/string/split/service.ts index cea1bdc6..dfea6fd5 100644 --- a/src/pages/tools/string/split/service.ts +++ b/src/pages/tools/string/split/service.ts @@ -18,17 +18,15 @@ function splitIntoChunks(text: string, numChunks: number) { 'Text length must be at least as long as the number of chunks' ); - const chunkSize = Math.ceil(totalLength / numChunks); // Calculate the chunk size, rounding up to handle remainders - let result = []; + const chunkSize = Math.floor(totalLength / numChunks); + const remainder = totalLength % numChunks; + const result: string[] = []; + let offset = 0; - for (let i = 0; i < totalLength; i += chunkSize) { - result.push(text.slice(i, i + chunkSize)); - } - - // Ensure the result contains exactly numChunks, adjusting the last chunk if necessary - if (result.length > numChunks) { - result[numChunks - 1] = result.slice(numChunks - 1).join(''); // Merge any extra chunks into the last chunk - result = result.slice(0, numChunks); // Take only the first numChunks chunks + for (let i = 0; i < numChunks; i++) { + const currentSize = chunkSize + (i < remainder ? 1 : 0); + result.push(text.slice(offset, offset + currentSize)); + offset += currentSize; } return result; diff --git a/src/pages/tools/string/split/string-split.service.test.ts b/src/pages/tools/string/split/string-split.service.test.ts index b1fe2976..21ba98d6 100644 --- a/src/pages/tools/string/split/string-split.service.test.ts +++ b/src/pages/tools/string/split/string-split.service.test.ts @@ -42,6 +42,11 @@ describe('compute function', () => { expect(result).toBe('[hello],[world],[again]'); }); + it('should return the requested number of uneven chunks', () => { + const result = compute('chunks', 'abcdef', '', '', 0, 4, '[', ']', ','); + expect(result).toBe('[ab],[cd],[e],[f]'); + }); + it('should handle empty input', () => { const result = compute('symbol', '', ' ', '', 0, 0, '', '', ','); expect(result).toBe(''); diff --git a/src/pages/tools/video/gif/images-to-gif/index.tsx b/src/pages/tools/video/gif/images-to-gif/index.tsx index de510c17..d4c0ff13 100644 --- a/src/pages/tools/video/gif/images-to-gif/index.tsx +++ b/src/pages/tools/video/gif/images-to-gif/index.tsx @@ -7,6 +7,7 @@ import { ToolComponentProps } from '@tools/defineTool'; import ToolMultipleImageInput, { MultiImageInput } from '@components/input/ToolMultipleImageInput'; +import SimpleRadio from '@components/options/SimpleRadio'; import { InitialValuesType } from './types'; import { updateNumberField } from '@utils/string'; import { useTranslation } from 'react-i18next'; @@ -14,7 +15,8 @@ import { imagesToGif } from './service'; import { debounce } from 'lodash'; const initialValues: InitialValuesType = { - frameDelay: 500 + frameRateMode: 'fps', + frameRateValue: 10 }; export default function ImagesToGif({ title }: ToolComponentProps) { @@ -28,6 +30,7 @@ export default function ImagesToGif({ title }: ToolComponentProps) { input: MultiImageInput[] ) => { if (!input || input.length === 0) return; + setLoading(true); try { const convertedGif = await imagesToGif( input.map((item) => item.file), @@ -71,20 +74,46 @@ export default function ImagesToGif({ title }: ToolComponentProps) { title: t('gif.imagesToGif.frameOptions'), component: ( - { - const clamped = Math.min( - 10000, - Math.max(50, Number(value)) - ).toString(); - updateNumberField(clamped, 'frameDelay', updateField); - }} - value={values.frameDelay} + updateField('frameRateMode', 'fps')} /> + + updateField('frameRateMode', 'delay')} + /> + + + { + const { min, max } = + values.frameRateMode === 'fps' + ? { min: 1, max: 60 } + : { min: 50, max: 10000 }; + + const clamped = Math.min( + max, + Math.max(min, Number(value)) + ).toString(); + + updateNumberField(clamped, 'frameRateValue', updateField); + }} + value={values.frameRateValue} + /> + ) } diff --git a/src/pages/tools/video/gif/images-to-gif/service.ts b/src/pages/tools/video/gif/images-to-gif/service.ts index 6076428f..e2098f14 100644 --- a/src/pages/tools/video/gif/images-to-gif/service.ts +++ b/src/pages/tools/video/gif/images-to-gif/service.ts @@ -8,12 +8,14 @@ export async function imagesToGif( optionsValues: InitialValuesType ): Promise { return runFFmpegTask(async ({ ffmpeg, tempFile }) => { - const { frameDelay } = optionsValues; + const { frameRateMode, frameRateValue } = optionsValues; + const fileNames: string[] = []; const listName = tempFile('.txt'); const outputName = tempFile('.gif'); - const durationSeconds = frameDelay / 1000; + const durationSeconds = + frameRateMode === 'fps' ? 1 / frameRateValue : frameRateValue / 1000; for (let i = 0; i < input.length; i++) { const file = input[i]; @@ -41,7 +43,7 @@ export async function imagesToGif( '-i', listName, '-vf', - 'scale=480:-2:flags=lanczos', + 'scale=iw:-2:flags=lanczos', '-loop', '0', outputName diff --git a/src/pages/tools/video/gif/images-to-gif/types.ts b/src/pages/tools/video/gif/images-to-gif/types.ts index 48cdaecd..a6e2e929 100644 --- a/src/pages/tools/video/gif/images-to-gif/types.ts +++ b/src/pages/tools/video/gif/images-to-gif/types.ts @@ -1,3 +1,4 @@ export interface InitialValuesType { - frameDelay: number; + frameRateMode: 'fps' | 'delay'; + frameRateValue: number; } diff --git a/src/pages/tools/xml/xml-beautifier/index.tsx b/src/pages/tools/xml/xml-beautifier/index.tsx index c1adb57f..8a57fa00 100644 --- a/src/pages/tools/xml/xml-beautifier/index.tsx +++ b/src/pages/tools/xml/xml-beautifier/index.tsx @@ -4,11 +4,15 @@ import { ToolComponentProps } from '@tools/defineTool'; import ToolTextInput from '@components/input/ToolTextInput'; import ToolTextResult from '@components/result/ToolTextResult'; import { CardExampleType } from '@components/examples/ToolExamples'; +import { GetGroupsType } from '@components/options/ToolOptions'; +import CheckboxWithDesc from '@components/options/CheckboxWithDesc'; import { beautifyXml } from './service'; import { InitialValuesType } from './types'; import { useTranslation } from 'react-i18next'; -const initialValues: InitialValuesType = {}; +const initialValues: InitialValuesType = { + preserveAttributes: true +}; const exampleCards: CardExampleType[] = [ { @@ -16,22 +20,37 @@ const exampleCards: CardExampleType[] = [ description: 'Beautify a compact XML string for readability.', sampleText: '12', sampleResult: `\n 1\n 2\n`, - sampleOptions: {} + sampleOptions: { preserveAttributes: true } } ]; -export default function XmlBeautifier({ - title, - longDescription -}: ToolComponentProps) { +export default function XmlBeautifier({ title }: ToolComponentProps) { const { t } = useTranslation('xml'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); - const compute = (_values: InitialValuesType, input: string) => { - setResult(beautifyXml(input, {})); + const compute = (values: InitialValuesType, input: string) => { + if (!input || input.trim() == '') return; + setResult(beautifyXml(input, values)); }; + const getGroups: GetGroupsType | null = ({ + values, + updateField + }) => [ + { + title: t('xmlBeautifier.options.title'), + component: ( + updateField('preserveAttributes', value)} + title={t('xmlBeautifier.options.preserveAttributesTitle')} + description={t('xmlBeautifier.options.preserveAttributesDesc')} + /> + ) + } + ]; + return ( ); diff --git a/src/pages/tools/xml/xml-beautifier/service.ts b/src/pages/tools/xml/xml-beautifier/service.ts index 8da42624..86259a55 100644 --- a/src/pages/tools/xml/xml-beautifier/service.ts +++ b/src/pages/tools/xml/xml-beautifier/service.ts @@ -1,10 +1,7 @@ import { InitialValuesType } from './types'; import { XMLParser, XMLBuilder, XMLValidator } from 'fast-xml-parser'; -export function beautifyXml( - input: string, - _options: InitialValuesType -): string { +export function beautifyXml(input: string, options: InitialValuesType): string { const valid = XMLValidator.validate(input); if (valid !== true) { if (typeof valid === 'object' && valid.err) { @@ -12,10 +9,16 @@ export function beautifyXml( } return 'Invalid XML'; } + + const { preserveAttributes } = options; try { - const parser = new XMLParser(); + const parser = new XMLParser({ ignoreAttributes: !preserveAttributes }); const obj = parser.parse(input); - const builder = new XMLBuilder({ format: true, indentBy: ' ' }); + const builder = new XMLBuilder({ + format: true, + indentBy: ' ', + ignoreAttributes: !preserveAttributes + }); return builder.build(obj); } catch (e: any) { return `Invalid XML: ${e.message}`; diff --git a/src/pages/tools/xml/xml-beautifier/types.ts b/src/pages/tools/xml/xml-beautifier/types.ts index d4135c9c..1ee79584 100644 --- a/src/pages/tools/xml/xml-beautifier/types.ts +++ b/src/pages/tools/xml/xml-beautifier/types.ts @@ -1,3 +1,3 @@ export type InitialValuesType = { - // splitSeparator: string; + preserveAttributes: boolean; }; diff --git a/src/pages/tools/xml/xml-beautifier/xml-beautifier.service.test.ts b/src/pages/tools/xml/xml-beautifier/xml-beautifier.service.test.ts index e832bb81..70d93eab 100644 --- a/src/pages/tools/xml/xml-beautifier/xml-beautifier.service.test.ts +++ b/src/pages/tools/xml/xml-beautifier/xml-beautifier.service.test.ts @@ -4,15 +4,22 @@ import { beautifyXml } from './service'; describe('xml-beautifier', () => { it('beautifies valid XML', () => { const input = '12'; - const result = beautifyXml(input, {}); + const result = beautifyXml(input, { preserveAttributes: true }); expect(result).toContain(''); expect(result).toContain(' 1'); expect(result).toContain(' 2'); }); + it('preserves attributes while beautifying XML', () => { + const input = 'Alice'; + const result = beautifyXml(input, { preserveAttributes: true }); + + expect(result).toContain('Alice'); + }); + it('returns error for invalid XML', () => { const input = '1'; - const result = beautifyXml(input, {}); + const result = beautifyXml(input, { preserveAttributes: true }); expect(result).toMatch(/Invalid XML/i); }); }); diff --git a/src/utils/color.ts b/src/utils/color.ts index 37e73dd8..1db42981 100644 --- a/src/utils/color.ts +++ b/src/utils/color.ts @@ -29,3 +29,27 @@ export function convertHexToRGBA(color: string): number { const alphaChannel = 0xff; return (colorValue << 8) | alphaChannel; } + +/** + * Parses any valid CSS color string into its RGB components, + * using the canvas's own color parser for correctness across + * hex (#fff, #ffffff), rgb()/rgba(), hsl(), and named colors. + */ +export function parseColorToRgb(color: string): { + r: number; + g: number; + b: number; +} { + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = 1; + const ctx = canvas.getContext('2d'); + if (!ctx) { + throw new Error('Canvas context not supported'); + } + + ctx.fillStyle = color; // browser validates & normalizes the color here + ctx.fillRect(0, 0, 1, 1); + + const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data; + return { r, g, b }; +} diff --git a/src/utils/image.ts b/src/utils/image.ts new file mode 100644 index 00000000..29c509dd --- /dev/null +++ b/src/utils/image.ts @@ -0,0 +1,43 @@ +/** + * Gets the dimensions of an image file. + * + * @param file - The image file to get the dimensions from. + * @returns A promise resolving to the image width and height in pixels. + */ +export function getImageDimensions( + file: File +): Promise<{ width: number; height: number }> { + return new Promise((resolve, reject) => { + const url = URL.createObjectURL(file); + const img = new Image(); + + img.onload = () => { + URL.revokeObjectURL(url); + resolve({ + width: img.width, + height: img.height + }); + }; + + img.onerror = () => { + URL.revokeObjectURL(url); + reject(new Error('Failed to load image')); + }; + + img.src = url; + }); +} + +/** + * Returns the maximum position for an area so it stays within the image bounds. + * + * @param imageSize - The image width or height. + * @param areaSize - The width or height of the area. + * @returns The maximum allowed position. + */ +export function getMaxAreaPosition( + imageSize: number, + areaSize: number +): number { + return Math.max(0, imageSize - areaSize); +}