Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions cypress/e2e/desktop/imageCompression.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import {
autocompleteInput,
checkTag,
expectFormWasSubmitted,
input,
interceptResourceSubmitRequest,
nextPageOrSubmit,
openContributeMenu,
selectAddress,
selectEntryType,
selectResource
} from 'utils/crowdsourcing.ts';
import { GUIDELINES_TEXTAREA } from 'utils/selectors.ts';

const FIVE_MB = 5 * 1024 * 1024;
const UPLOADED_IMAGE_KEY = 'compressed-image.jpeg';

type TestWindow = Window & typeof globalThis;

const createNoisyPng = (win: TestWindow): Promise<File> => {
const canvas = win.document.createElement('canvas');
canvas.width = 3000;
canvas.height = 2000;

const context = canvas.getContext('2d');
if (!context) {
throw new Error('Could not create canvas context');
}

const imageData = context.createImageData(canvas.width, canvas.height);
const data = imageData.data;
const chunk = new Uint8Array(65536);
for (let offset = 0; offset < data.length; offset += chunk.length) {
win.crypto.getRandomValues(chunk);
data.set(
chunk.subarray(0, Math.min(chunk.length, data.length - offset)),
offset
);
}
for (let alpha = 3; alpha < data.length; alpha += 4) {
data[alpha] = 255;
}
context.putImageData(imageData, 0, 0);

return new Promise((resolve, reject) => {
canvas.toBlob(blob => {
if (!blob) {
reject(new Error('Could not create test image'));
return;
}
resolve(new win.File([blob], 'large-image.png', { type: 'image/png' }));
}, 'image/png');
});
};

const dropFile = (win: TestWindow, file: File) => {
const dataTransfer = new win.DataTransfer();
dataTransfer.items.add(file);

const fileInput =
win.document.querySelector<HTMLInputElement>('input[type="file"]');
if (!fileInput) {
throw new Error('Could not find the image upload input');
}

fileInput.files = dataTransfer.files;
fileInput.dispatchEvent(new win.Event('change', { bubbles: true }));
};

describe('image compression', () => {
beforeEach(() => {
cy.visit('/');
openContributeMenu();
interceptResourceSubmitRequest();

cy.intercept(
{ method: 'GET', hostname: 'phlask.me', pathname: '/submit-image' },
{
statusCode: 200,
body: {
putURL: 'https://s3.test/compressed-image',
getURL: UPLOADED_IMAGE_KEY,
errorMessage: null
}
}
).as('submitImageRequest');

cy.intercept(
{ method: 'PUT', url: 'https://s3.test/compressed-image' },
{ statusCode: 200, body: '' }
).as('uploadImageRequest');
});

it('should compress an image over 5 MB before uploading it', () => {
selectResource('WATER');

input('name', 'Cypress Test Name');
selectAddress();

input('description', 'Cypress Test Description');
selectEntryType();

autocompleteInput('water.dispenser_type', 'Sink');

nextPageOrSubmit();

cy.window().then(async win => {
const file = await createNoisyPng(win);
expect(file.size, 'test image size').to.be.greaterThan(FIVE_MB);
dropFile(win, file);
});

cy.wait('@submitImageRequest', { timeout: 30000 })
.its('request.url')
.should('include', 'type=image/jpeg');

cy.wait('@uploadImageRequest', { timeout: 30000 }).then(({ request }) => {
expect(request.headers['content-type']).to.equal('image/jpeg');
expect(
Number(request.headers['content-length']),
'uploaded image size'
).to.be.lessThan(FIVE_MB);
});

checkTag();
cy.get(GUIDELINES_TEXTAREA).type('Cypress Test');

nextPageOrSubmit();

cy.wait('@resourceSubmitRequest')
.its('request.body')
.then(body => {
expect(body.images).to.deep.equal([UPLOADED_IMAGE_KEY]);
});

expectFormWasSubmitted();
});
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@supabase/supabase-js": "^2.116.0",
"@tanstack/react-query": "^5.102.8",
"@vis.gl/react-google-maps": "^1.10.0",
"compressorjs": "^1.4.0",
"date-fns": "^4.4.0",
"posthog-js": "^1.428.7",
"react": "^19.2.8",
Expand Down
22 changes: 22 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 1 addition & 7 deletions src/components/ImageUploader/ImageUploader.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Box, Stack, Typography } from '@mui/material';
import type { ReactNode } from 'react';
import { useDropzone, type DropzoneOptions } from 'react-dropzone';
import fileSizePretty from 'utils/formatFileSize';
import { Upload } from 'icons';

export type RenderContentConfig = {
Expand All @@ -10,33 +9,28 @@ export type RenderContentConfig = {

type ImageUploaderProps = Pick<
DropzoneOptions,
'accept' | 'maxSize' | 'maxFiles' | 'onDrop'
'accept' | 'maxFiles' | 'onDrop'
> & {
renderContent?: (config: RenderContentConfig) => ReactNode;
};

const ImageUploader = ({
onDrop,
accept,
maxSize,
maxFiles,
renderContent = () => null
}: ImageUploaderProps) => {
const { getRootProps, getInputProps, isDragActive, acceptedFiles } =
useDropzone({
onDrop,
accept,
maxSize,
maxFiles
});
return (
<Stack alignItems="center" gap={2} {...getRootProps()}>
<input {...getInputProps()} />
<Upload fontSize={55} />
<Stack>
<Typography fontSize={14} color="#60718C">
{maxSize ? `Max file size: ${fileSizePretty(maxSize)}` : null}
</Typography>
<Typography fontSize={14} color="#60718C">
{accept
? `accepted: ${Object.values(accept)
Expand Down
16 changes: 10 additions & 6 deletions src/components/forms/FormImageUploadField/FormImageUploadField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import {
type FieldValues,
type Path
} from 'react-hook-form';
import compressImage from 'utils/compressImage';

type FormImageUploadFieldProps<Values extends FieldValues> = {
name: Path<Values>;
accept?: Accept;
maxSize?: number;
maxFiles?: number;
renderContent?: (config: RenderContentConfig) => ReactNode;
};
Expand All @@ -28,29 +28,33 @@ const defaultAccept = {
const FormImageUploadField = <Values extends FieldValues>({
name,
accept = defaultAccept,
maxSize = 5242880,
maxFiles = 1,
renderContent = () => null
}: FormImageUploadFieldProps<Values>) => {
const { control } = useFormContext();
const { mutate: uploadImage } = useUploadImageMutation();
const { field } = useController({ control, name });

const onDrop = (acceptedFiles: File[]) => {
const onDrop = async (acceptedFiles: File[]) => {
const file = acceptedFiles.at(0);
if (!file) {
return;
}
uploadImage(file, {
onSuccess: data => field.onChange('images', [data])

const image = await compressImage(file).catch(error => {
console.error(error instanceof Error ? error.message : error);
return file;
});

uploadImage(image, {
onSuccess: data => field.onChange([data])
});
};

return (
<ImageUploader
onDrop={onDrop}
accept={accept}
maxSize={maxSize}
maxFiles={maxFiles}
renderContent={renderContent}
/>
Expand Down
40 changes: 40 additions & 0 deletions src/utils/compressImage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Compressor from 'compressorjs';

const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
const MAX_IMAGE_DIMENSION = 2048;

const renameToJpeg = (blob: Blob, original: File) => {
const baseName = original.name.replace(/\.[^.]+$/, '') || 'image';
return new File([blob], `${baseName}.jpeg`, {
type: blob.type,
lastModified: original.lastModified
});
};

const compressToBlob = (file: File) =>
new Promise<Blob>((resolve, reject) => {
new Compressor(file, {
maxWidth: MAX_IMAGE_DIMENSION,
maxHeight: MAX_IMAGE_DIMENSION,
mimeType: 'image/jpeg',
convertSize: MAX_IMAGE_BYTES,
quality: 0.8,
success: resolve,
error: reject
});
});

const compressImage = async (file: File): Promise<File> => {
const isCompressibleImage =
file.type.startsWith('image/') && file.type !== 'image/gif';

if (!isCompressibleImage || file.size <= MAX_IMAGE_BYTES) {
return file;
}

const compressed = await compressToBlob(file);

return renameToJpeg(compressed, file);
};

export default compressImage;
23 changes: 0 additions & 23 deletions src/utils/formatFileSize.ts

This file was deleted.

Loading