mirror of
https://github.com/iib0011/omni-tools.git
synced 2026-11-30 00:51:10 +03:00
Merge branch 'main' into pr/idsoke/458
This commit is contained in:
commit
bb729b0a40
28 files changed
+585
-268
No files matched your search
@@ -154,16 +154,16 @@ The translation files are [here](public/locales). Only edit these if you are a d
|
||||
<!-- I18N-COVERAGE:START -->
|
||||
| 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 |
|
||||
<!-- I18N-COVERAGE:END -->
|
||||
|
||||
## ⭐ Star History
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -115,7 +115,7 @@
|
||||
"inputFooter": {
|
||||
"clear": "Clear",
|
||||
"copyToClipboard": "Copy to clipboard",
|
||||
"importFromFile": "Import from file"
|
||||
"importFromFile": "Select files"
|
||||
},
|
||||
"list": {
|
||||
"group": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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++) {
|
||||
|
||||
@@ -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<InitialValuesType>[] = [
|
||||
{
|
||||
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<File | null>(null);
|
||||
const [result, setResult] = useState<File | null>(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<InitialValuesType> | null = ({
|
||||
values,
|
||||
updateField
|
||||
}) => [
|
||||
{
|
||||
title: t('changeOpacity.options.opacitySettings'),
|
||||
component: (
|
||||
<Box>
|
||||
<TextFieldWithDesc
|
||||
description={t('changeOpacity.options.opacityDescription')}
|
||||
value={values.opacity}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'opacity', updateField)
|
||||
}
|
||||
type="number"
|
||||
inputProps={{ step: 0.1, min: 0, max: 1 }}
|
||||
/>
|
||||
<SimpleRadio
|
||||
onClick={() => updateField('mode', 'solid')}
|
||||
checked={values.mode === 'solid'}
|
||||
description={t('changeOpacity.options.solidOpacityDescription')}
|
||||
title={t('changeOpacity.options.solidOpacityTitle')}
|
||||
/>
|
||||
<SimpleRadio
|
||||
onClick={() => updateField('mode', 'gradient')}
|
||||
checked={values.mode === 'gradient'}
|
||||
description={t('changeOpacity.options.gradientOpacityDescription')}
|
||||
title={t('changeOpacity.options.gradientOpacityTitle')}
|
||||
/>
|
||||
|
||||
{values.mode === 'gradient' && (
|
||||
<Box mt={2}>
|
||||
<SelectWithDesc
|
||||
selected={values.gradientType}
|
||||
options={[
|
||||
{
|
||||
label: t('changeOpacity.options.linearOpacity'),
|
||||
value: 'linear'
|
||||
},
|
||||
{
|
||||
label: t('changeOpacity.options.radialOpacity'),
|
||||
value: 'radial'
|
||||
}
|
||||
]}
|
||||
onChange={(value) => {
|
||||
updateField('gradientType', value);
|
||||
|
||||
if (value === 'linear') {
|
||||
updateField('gradientDirection', 'left-to-right');
|
||||
} else {
|
||||
updateField('gradientDirection', 'inside-out');
|
||||
}
|
||||
}}
|
||||
description={t('changeOpacity.options.gradientType')}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{values.gradientType === 'radial' && (
|
||||
<Box mt={2}>
|
||||
<SelectWithDesc
|
||||
selected={values.gradientDirection}
|
||||
options={[
|
||||
{
|
||||
label: t('changeOpacity.options.insideOut'),
|
||||
value: 'inside-out'
|
||||
},
|
||||
{
|
||||
label: t('changeOpacity.options.outsideIn'),
|
||||
value: 'outside-in'
|
||||
}
|
||||
]}
|
||||
onChange={(value) => updateField('gradientDirection', value)}
|
||||
description={t('changeOpacity.options.gradientDirection')}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
...(values.mode === 'gradient'
|
||||
? [
|
||||
{
|
||||
title: t('changeOpacity.options.opacityArea'),
|
||||
component: (
|
||||
<Box>
|
||||
<TextFieldWithDesc
|
||||
description={t('changeOpacity.options.leftPosition')}
|
||||
value={values.areaLeft}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'areaLeft', updateField)
|
||||
}
|
||||
inputProps={{
|
||||
min: 0,
|
||||
max: getMaxAreaPosition(imageSize.width, values.areaWidth)
|
||||
}}
|
||||
type="number"
|
||||
/>
|
||||
|
||||
<TextFieldWithDesc
|
||||
description={t('changeOpacity.options.topPosition')}
|
||||
value={values.areaTop}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'areaTop', updateField)
|
||||
}
|
||||
inputProps={{
|
||||
min: 0,
|
||||
max: getMaxAreaPosition(imageSize.height, values.areaHeight)
|
||||
}}
|
||||
type="number"
|
||||
/>
|
||||
|
||||
<TextFieldWithDesc
|
||||
description={t('changeOpacity.options.width')}
|
||||
value={values.areaWidth}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'areaWidth', updateField)
|
||||
}
|
||||
inputProps={{
|
||||
min: 1,
|
||||
max: imageSize.width || undefined
|
||||
}}
|
||||
type="number"
|
||||
/>
|
||||
|
||||
<TextFieldWithDesc
|
||||
description={t('changeOpacity.options.height')}
|
||||
value={values.areaHeight}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'areaHeight', updateField)
|
||||
}
|
||||
inputProps={{
|
||||
min: 1,
|
||||
max: imageSize.height || undefined
|
||||
}}
|
||||
type="number"
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{
|
||||
title: t('changeOpacity.options.backgroundOptions'),
|
||||
component: (
|
||||
<Box>
|
||||
<SimpleRadio
|
||||
onClick={() => updateField('backgroundMode', 'transparent')}
|
||||
checked={values.backgroundMode === 'transparent'}
|
||||
description={t('changeOpacity.options.transparentAlphaDescription')}
|
||||
title={t('changeOpacity.options.transparentAlpha')}
|
||||
/>
|
||||
<SimpleRadio
|
||||
onClick={() => updateField('backgroundMode', 'color')}
|
||||
checked={values.backgroundMode === 'color'}
|
||||
description={t('changeOpacity.options.solidColorDescription')}
|
||||
title={t('changeOpacity.options.solidColor')}
|
||||
/>
|
||||
{values.backgroundMode === 'color' && (
|
||||
<Box mt={2}>
|
||||
<ColorSelector
|
||||
value={values.backgroundColor}
|
||||
onColorChange={(val) => updateField('backgroundColor', val)}
|
||||
description={t('changeOpacity.options.chooseBackgroundColor')}
|
||||
inputProps={{ 'data-testid': 'background-color-input' }}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<ToolContent
|
||||
key={`${imageSize.width}x${imageSize.height}`}
|
||||
title={title}
|
||||
input={input}
|
||||
inputComponent={
|
||||
@@ -98,103 +252,15 @@ export default function ChangeOpacity({ title }: ToolComponentProps) {
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
accept={['image/*']}
|
||||
title={'Input image'}
|
||||
title={t('changeOpacity.inputTitle')}
|
||||
/>
|
||||
}
|
||||
resultComponent={
|
||||
<ToolFileResult title={'Changed image'} value={result} />
|
||||
<ToolFileResult title={t('changeOpacity.resultTitle')} value={result} />
|
||||
}
|
||||
initialValues={initialValues}
|
||||
// exampleCards={exampleCards}
|
||||
getGroups={({ values, updateField }) => [
|
||||
{
|
||||
title: 'Opacity Settings',
|
||||
component: (
|
||||
<Box>
|
||||
<TextFieldWithDesc
|
||||
description="Set opacity between 0 (transparent) and 1 (opaque)"
|
||||
value={values.opacity}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'opacity', updateField)
|
||||
}
|
||||
type="number"
|
||||
inputProps={{ step: 0.1, min: 0, max: 1 }}
|
||||
/>
|
||||
<SimpleRadio
|
||||
onClick={() => updateField('mode', 'solid')}
|
||||
checked={values.mode === 'solid'}
|
||||
description={'Set the same opacity level for all pixels'}
|
||||
title={'Apply Solid Opacity'}
|
||||
/>
|
||||
<SimpleRadio
|
||||
onClick={() => updateField('mode', 'gradient')}
|
||||
checked={values.mode === 'gradient'}
|
||||
description={'Change opacity in a gradient'}
|
||||
title={'Apply Gradient Opacity'}
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Gradient Options',
|
||||
component: (
|
||||
<Box>
|
||||
<SimpleRadio
|
||||
onClick={() => updateField('gradientType', 'linear')}
|
||||
checked={values.gradientType === 'linear'}
|
||||
description={'Linear opacity direction'}
|
||||
title={'Linear Gradient'}
|
||||
/>
|
||||
<SimpleRadio
|
||||
onClick={() => updateField('gradientType', 'radial')}
|
||||
checked={values.gradientType === 'radial'}
|
||||
description={'Radial opacity direction'}
|
||||
title={'Radial Gradient'}
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Opacity Area',
|
||||
component: (
|
||||
<Box>
|
||||
<TextFieldWithDesc
|
||||
description="Left position"
|
||||
value={values.areaLeft}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'areaLeft', updateField)
|
||||
}
|
||||
type="number"
|
||||
/>
|
||||
<TextFieldWithDesc
|
||||
description="Top position"
|
||||
value={values.areaTop}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'areaTop', updateField)
|
||||
}
|
||||
type="number"
|
||||
/>
|
||||
<TextFieldWithDesc
|
||||
description="Width"
|
||||
value={values.areaWidth}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'areaWidth', updateField)
|
||||
}
|
||||
type="number"
|
||||
/>
|
||||
<TextFieldWithDesc
|
||||
description="Height"
|
||||
value={values.areaHeight}
|
||||
onOwnChange={(val) =>
|
||||
updateNumberField(val, 'areaHeight', updateField)
|
||||
}
|
||||
type="number"
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
]}
|
||||
compute={compute}
|
||||
getGroups={getGroups}
|
||||
compute={debouncedCompute}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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<File> {
|
||||
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;
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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 })
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
};
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 ? (
|
||||
<RadioWithTextField
|
||||
key={type}
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
export type NumberExtractionType = 'smart' | 'delimiter';
|
||||
|
||||
function getAllNumbers(text: string): number[] {
|
||||
const regex = /\d+/g;
|
||||
const matches = text.match(regex);
|
||||
const matches = text.match(/-?\d+(?:\.\d+)?/g);
|
||||
return matches ? matches.map(Number) : [];
|
||||
}
|
||||
function getDelimitedNumbers(text: string, separator: string): number[] {
|
||||
const normalizedSeparator = separator.replace(/\\n/g, '\n').trim();
|
||||
const pattern = normalizedSeparator
|
||||
? new RegExp(
|
||||
normalizedSeparator.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*'
|
||||
)
|
||||
: /\s+/;
|
||||
|
||||
return text
|
||||
.split(pattern)
|
||||
.map((part) => 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();
|
||||
};
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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('');
|
||||
|
||||
@@ -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: (
|
||||
<Box>
|
||||
<TextFieldWithDesc
|
||||
name="frameDelay"
|
||||
type="number"
|
||||
inputProps={{ min: 50, max: 10000, step: 50 }}
|
||||
description={t('gif.imagesToGif.frameDelayDescription')}
|
||||
onOwnChange={(value) => {
|
||||
const clamped = Math.min(
|
||||
10000,
|
||||
Math.max(50, Number(value))
|
||||
).toString();
|
||||
updateNumberField(clamped, 'frameDelay', updateField);
|
||||
}}
|
||||
value={values.frameDelay}
|
||||
<SimpleRadio
|
||||
checked={values.frameRateMode === 'fps'}
|
||||
title={t('gif.imagesToGif.frameRate')}
|
||||
description={t('gif.imagesToGif.frameRateDescription')}
|
||||
onClick={() => updateField('frameRateMode', 'fps')}
|
||||
/>
|
||||
|
||||
<SimpleRadio
|
||||
checked={values.frameRateMode === 'delay'}
|
||||
title={t('gif.imagesToGif.frameDelay')}
|
||||
description={t('gif.imagesToGif.frameDelayDescription')}
|
||||
onClick={() => updateField('frameRateMode', 'delay')}
|
||||
/>
|
||||
|
||||
<Box mt={2}>
|
||||
<TextFieldWithDesc
|
||||
name="frameRate"
|
||||
type="number"
|
||||
inputProps={
|
||||
values.frameRateMode === 'fps'
|
||||
? { min: 1, max: 60, step: 1 }
|
||||
: { min: 50, max: 10000, step: 50 }
|
||||
}
|
||||
description={t('gif.imagesToGif.frameRateValueDescription')}
|
||||
onOwnChange={(value) => {
|
||||
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}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,12 +8,14 @@ export async function imagesToGif(
|
||||
optionsValues: InitialValuesType
|
||||
): Promise<File> {
|
||||
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
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export interface InitialValuesType {
|
||||
frameDelay: number;
|
||||
frameRateMode: 'fps' | 'delay';
|
||||
frameRateValue: number;
|
||||
}
|
||||
@@ -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<InitialValuesType>[] = [
|
||||
{
|
||||
@@ -16,22 +20,37 @@ const exampleCards: CardExampleType<InitialValuesType>[] = [
|
||||
description: 'Beautify a compact XML string for readability.',
|
||||
sampleText: '<root><item>1</item><item>2</item></root>',
|
||||
sampleResult: `<root>\n <item>1</item>\n <item>2</item>\n</root>`,
|
||||
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<string>('');
|
||||
const [result, setResult] = useState<string>('');
|
||||
|
||||
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<InitialValuesType> | null = ({
|
||||
values,
|
||||
updateField
|
||||
}) => [
|
||||
{
|
||||
title: t('xmlBeautifier.options.title'),
|
||||
component: (
|
||||
<CheckboxWithDesc
|
||||
checked={values.preserveAttributes}
|
||||
onChange={(value) => updateField('preserveAttributes', value)}
|
||||
title={t('xmlBeautifier.options.preserveAttributesTitle')}
|
||||
description={t('xmlBeautifier.options.preserveAttributesDesc')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<ToolContent
|
||||
title={title}
|
||||
@@ -52,12 +71,12 @@ export default function XmlBeautifier({
|
||||
}
|
||||
initialValues={initialValues}
|
||||
exampleCards={exampleCards}
|
||||
getGroups={null}
|
||||
getGroups={getGroups}
|
||||
setInput={setInput}
|
||||
compute={compute}
|
||||
toolInfo={{
|
||||
title: t('xmlBeautifier.toolInfo.title', { title }),
|
||||
description: longDescription
|
||||
title: t('xmlBeautifier.toolInfo.title'),
|
||||
description: t('xmlBeautifier.toolInfo.description')
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -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}`;
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export type InitialValuesType = {
|
||||
// splitSeparator: string;
|
||||
preserveAttributes: boolean;
|
||||
};
|
||||
@@ -4,15 +4,22 @@ import { beautifyXml } from './service';
|
||||
describe('xml-beautifier', () => {
|
||||
it('beautifies valid XML', () => {
|
||||
const input = '<root><a>1</a><b>2</b></root>';
|
||||
const result = beautifyXml(input, {});
|
||||
const result = beautifyXml(input, { preserveAttributes: true });
|
||||
expect(result).toContain('<root>');
|
||||
expect(result).toContain(' <a>1</a>');
|
||||
expect(result).toContain(' <b>2</b>');
|
||||
});
|
||||
|
||||
it('preserves attributes while beautifying XML', () => {
|
||||
const input = '<root><user id="42" role="admin">Alice</user></root>';
|
||||
const result = beautifyXml(input, { preserveAttributes: true });
|
||||
|
||||
expect(result).toContain('<user id="42" role="admin">Alice</user>');
|
||||
});
|
||||
|
||||
it('returns error for invalid XML', () => {
|
||||
const input = '<root><a>1</b></root>';
|
||||
const result = beautifyXml(input, {});
|
||||
const result = beautifyXml(input, { preserveAttributes: true });
|
||||
expect(result).toMatch(/Invalid XML/i);
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user