Crop the avatar/logo before upload with a dependency-free cropper

Selecting an avatar or workspace logo now opens a crop dialog (drag + zoom)
before uploading, so the image is framed the way it renders. The crop is
performed client-side and the resized 512x512 result is what gets uploaded.

This reworks the idea from #131 without its cropper dependency: vue-advanced-cropper
was last released ~2 years ago and we did not want an unmaintained package for
something this load-bearing. What we need is narrow (fixed 1:1, a circle/square
mask, fixed-size output), so a small canvas-based cropper covers it:

- imageCrop.ts: pure transform math (cover-fit, clamp, zoom, viewport->source).
- ImageCropperDialog.vue: CSS-transform preview, pointer drag, wheel/button zoom,
  a ResizeObserver to measure the modal (no requestAnimationFrame timing hacks),
  and a canvas toBlob only on save.
- PhotoUpload.vue: opens the cropper on file select; the mask shape follows the
  display shape (round avatar / square logo) instead of always being round.
- crop_* strings added to all 15 locales.

Also installs Pest browser testing (pest-plugin-browser + Playwright) and adds a
browser test for the crop flow. TestCase only calls withoutVite() for non-browser
tests, since browser tests need the real Vite assets to boot the SPA. The Pest
browser server does not parse multipart uploads, so the test asserts the crop
dispatches the correct upload request; endpoint persistence stays covered by
ProfileUpdateTest.
This commit is contained in:
Paulo Castellano 2026-07-03 21:46:19 -03:00
parent f609073b9a
commit c6369a6ddb
27 changed files with 2240 additions and 49 deletions

1
.gitignore vendored
View file

@ -1,6 +1,7 @@
/.phpunit.cache
/bootstrap/ssr
/node_modules
/tests/Browser/Screenshots
/public/build
/lang/php_*.json
/public/hot

View file

@ -74,6 +74,7 @@
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"pestphp/pest": "^4.4",
"pestphp/pest-plugin-browser": "^4.3",
"pestphp/pest-plugin-laravel": "^4.1"
},
"autoload": {

1573
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -21,6 +21,11 @@
'uploading' => 'جارٍ الرفع...',
'remove' => 'إزالة الصورة',
'hint' => 'موصى به: صورة مربعة، بحد أقصى 2 ميغابايت.',
'crop_title' => 'قص الصورة',
'crop_description' => 'اسحب وكبّر لتأطيرها.',
'crop_hint' => 'اسحب لإعادة التموضع',
'crop_save' => 'حفظ',
'crop_cancel' => 'إلغاء',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Wird hochgeladen...',
'remove' => 'Foto entfernen',
'hint' => 'Empfohlen: quadratisches Bild, max. 2 MB.',
'crop_title' => 'Bild zuschneiden',
'crop_description' => 'Ziehen und zoomen, um es auszurichten.',
'crop_hint' => 'Zum Verschieben ziehen',
'crop_save' => 'Speichern',
'crop_cancel' => 'Abbrechen',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Μεταφόρτωση...',
'remove' => 'Αφαίρεση φωτογραφίας',
'hint' => 'Συνιστάται: τετράγωνη εικόνα, έως 2 MB.',
'crop_title' => 'Περικοπή εικόνας',
'crop_description' => 'Σύρετε και κάντε ζουμ για πλαισίωση.',
'crop_hint' => 'Σύρετε για επανατοποθέτηση',
'crop_save' => 'Αποθήκευση',
'crop_cancel' => 'Άκυρο',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Uploading...',
'remove' => 'Remove photo',
'hint' => 'Recommended: square image, max 2 MB.',
'crop_title' => 'Crop image',
'crop_description' => 'Drag and zoom to frame it.',
'crop_hint' => 'Drag to reposition',
'crop_save' => 'Save',
'crop_cancel' => 'Cancel',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Subiendo...',
'remove' => 'Eliminar foto',
'hint' => 'Recomendado: imagen cuadrada, máximo 2 MB.',
'crop_title' => 'Recortar imagen',
'crop_description' => 'Arrastra y haz zoom para encuadrarla.',
'crop_hint' => 'Arrastra para reposicionar',
'crop_save' => 'Guardar',
'crop_cancel' => 'Cancelar',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Import en cours...',
'remove' => 'Supprimer la photo',
'hint' => 'Recommandé : image carrée, 2 Mo maximum.',
'crop_title' => 'Recadrer l\'image',
'crop_description' => 'Faites glisser et zoomez pour cadrer.',
'crop_hint' => 'Faites glisser pour repositionner',
'crop_save' => 'Enregistrer',
'crop_cancel' => 'Annuler',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Caricamento in corso...',
'remove' => 'Rimuovi foto',
'hint' => 'Consigliato: immagine quadrata, max 2 MB.',
'crop_title' => 'Ritaglia immagine',
'crop_description' => 'Trascina e ingrandisci per inquadrarla.',
'crop_hint' => 'Trascina per riposizionare',
'crop_save' => 'Salva',
'crop_cancel' => 'Annulla',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'アップロード中...',
'remove' => '写真を削除',
'hint' => '推奨: 正方形の画像、最大 2 MB。',
'crop_title' => '画像を切り抜く',
'crop_description' => 'ドラッグとズームで位置を調整します。',
'crop_hint' => 'ドラッグして移動',
'crop_save' => '保存',
'crop_cancel' => 'キャンセル',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => '업로드 중...',
'remove' => '사진 제거',
'hint' => '권장: 정사각형 이미지, 최대 2MB.',
'crop_title' => '이미지 자르기',
'crop_description' => '드래그하고 확대/축소하여 맞추세요.',
'crop_hint' => '드래그하여 위치 조정',
'crop_save' => '저장',
'crop_cancel' => '취소',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Uploaden...',
'remove' => 'Foto verwijderen',
'hint' => 'Aanbevolen: vierkante afbeelding, max. 2 MB.',
'crop_title' => 'Afbeelding bijsnijden',
'crop_description' => 'Sleep en zoom om uit te lijnen.',
'crop_hint' => 'Sleep om te verplaatsen',
'crop_save' => 'Opslaan',
'crop_cancel' => 'Annuleren',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Przesyłanie...',
'remove' => 'Usuń zdjęcie',
'hint' => 'Zalecane: kwadratowe zdjęcie, maks. 2 MB.',
'crop_title' => 'Przytnij obraz',
'crop_description' => 'Przeciągnij i powiększ, aby wykadrować.',
'crop_hint' => 'Przeciągnij, aby zmienić położenie',
'crop_save' => 'Zapisz',
'crop_cancel' => 'Anuluj',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Enviando...',
'remove' => 'Remover foto',
'hint' => 'Recomendado: imagem quadrada, máximo 2 MB.',
'crop_title' => 'Cortar imagem',
'crop_description' => 'Arraste e dê zoom para enquadrar.',
'crop_hint' => 'Arraste para reposicionar',
'crop_save' => 'Salvar',
'crop_cancel' => 'Cancelar',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Загрузка...',
'remove' => 'Удалить фото',
'hint' => 'Рекомендуется: квадратное изображение, до 2 МБ.',
'crop_title' => 'Обрезать изображение',
'crop_description' => 'Перетащите и масштабируйте для кадрирования.',
'crop_hint' => 'Перетащите, чтобы переместить',
'crop_save' => 'Сохранить',
'crop_cancel' => 'Отмена',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => 'Yükleniyor...',
'remove' => 'Fotoğrafı kaldır',
'hint' => 'Önerilen: kare görsel, en fazla 2 MB.',
'crop_title' => 'Görseli kırp',
'crop_description' => 'Çerçevelemek için sürükleyip yakınlaştırın.',
'crop_hint' => 'Yeniden konumlandırmak için sürükleyin',
'crop_save' => 'Kaydet',
'crop_cancel' => 'İptal',
],
'timezone' => [

View file

@ -21,6 +21,11 @@
'uploading' => '上传中…',
'remove' => '移除照片',
'hint' => '推荐:正方形图片,最大 2 MB。',
'crop_title' => '裁剪图片',
'crop_description' => '拖动并缩放以取景。',
'crop_hint' => '拖动以重新定位',
'crop_save' => '保存',
'crop_cancel' => '取消',
],
'timezone' => [

90
package-lock.json generated
View file

@ -55,6 +55,7 @@
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-vue": "^9.32.0",
"laravel-echo": "^2.3.0",
"playwright": "^1.61.1",
"prettier": "^3.4.2",
"prettier-plugin-organize-imports": "^4.1.0",
"prettier-plugin-tailwindcss": "^0.6.11",
@ -1448,9 +1449,6 @@
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1467,9 +1465,6 @@
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -1486,9 +1481,6 @@
"cpu": [
"ppc64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1505,9 +1497,6 @@
"cpu": [
"s390x"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1524,9 +1513,6 @@
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1543,9 +1529,6 @@
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -1855,9 +1838,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1875,9 +1855,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -1894,9 +1871,6 @@
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1914,9 +1888,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -7204,9 +7175,6 @@
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@ -7227,9 +7195,6 @@
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@ -7250,9 +7215,6 @@
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@ -7273,9 +7235,6 @@
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@ -7866,6 +7825,53 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/playwright": {
"version": "1.61.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
"integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.61.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.61.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
"integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/playwright/node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/possible-typed-array-names": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",

View file

@ -28,6 +28,7 @@
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-vue": "^9.32.0",
"laravel-echo": "^2.3.0",
"playwright": "^1.61.1",
"prettier": "^3.4.2",
"prettier-plugin-organize-imports": "^4.1.0",
"prettier-plugin-tailwindcss": "^0.6.11",

View file

@ -0,0 +1,283 @@
<script setup lang="ts">
import { IconZoomIn, IconZoomOut } from '@tabler/icons-vue';
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
centerTransform,
clampTransform,
type CropTransform,
viewportToSource,
zoomTransform,
} from '@/lib/imageCrop';
type Props = {
open: boolean;
src: string | null;
fileName?: string;
mimeType?: string;
shape?: 'circle' | 'square';
outputSize?: number;
};
const props = withDefaults(defineProps<Props>(), {
fileName: 'image.png',
mimeType: 'image/png',
shape: 'circle',
outputSize: 512,
});
const emit = defineEmits<{
(e: 'update:open', value: boolean): void;
(e: 'cropped', file: File): void;
}>();
const viewportEl = ref<HTMLElement | null>(null);
const imageEl = ref<HTMLImageElement | null>(null);
const viewportSize = ref(0);
const natural = ref({ width: 0, height: 0 });
const transform = ref<CropTransform>({ scale: 1, x: 0, y: 0 });
const processing = ref(false);
const initialized = ref(false);
let dragPointerId: number | null = null;
let dragStart = { pointerX: 0, pointerY: 0, x: 0, y: 0 };
let resizeObserver: ResizeObserver | null = null;
const ready = computed(() => viewportSize.value > 0 && natural.value.width > 0);
const maskClass = computed(() => (props.shape === 'square' ? 'rounded-lg' : 'rounded-full'));
const imageStyle = computed(() => ({
width: `${natural.value.width * transform.value.scale}px`,
height: `${natural.value.height * transform.value.scale}px`,
transform: `translate(${transform.value.x}px, ${transform.value.y}px)`,
}));
const maybeInitialize = () => {
if (!ready.value || initialized.value) {
return;
}
transform.value = centerTransform(natural.value.width, natural.value.height, viewportSize.value);
initialized.value = true;
};
const measure = () => {
const el = viewportEl.value;
if (!el) {
return;
}
viewportSize.value = el.clientWidth;
if (initialized.value) {
transform.value = clampTransform(transform.value, natural.value.width, natural.value.height, viewportSize.value);
} else {
maybeInitialize();
}
};
const onImageLoad = () => {
const img = imageEl.value;
if (!img) {
return;
}
natural.value = { width: img.naturalWidth, height: img.naturalHeight };
maybeInitialize();
};
const onPointerDown = (event: PointerEvent) => {
if (!ready.value) {
return;
}
dragPointerId = event.pointerId;
dragStart = { pointerX: event.clientX, pointerY: event.clientY, x: transform.value.x, y: transform.value.y };
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
};
const onPointerMove = (event: PointerEvent) => {
if (dragPointerId !== event.pointerId) {
return;
}
transform.value = clampTransform(
{
scale: transform.value.scale,
x: dragStart.x + (event.clientX - dragStart.pointerX),
y: dragStart.y + (event.clientY - dragStart.pointerY),
},
natural.value.width,
natural.value.height,
viewportSize.value,
);
};
const onPointerUp = (event: PointerEvent) => {
if (dragPointerId === event.pointerId) {
dragPointerId = null;
}
};
const onWheel = (event: WheelEvent) => {
if (!ready.value) {
return;
}
event.preventDefault();
transform.value = zoomTransform(
transform.value,
event.deltaY < 0 ? 1.06 : 0.94,
natural.value.width,
natural.value.height,
viewportSize.value,
);
};
const zoomBy = (factor: number) => {
if (!ready.value) {
return;
}
transform.value = zoomTransform(transform.value, factor, natural.value.width, natural.value.height, viewportSize.value);
};
const close = () => {
emit('update:open', false);
};
const save = () => {
const img = imageEl.value;
if (!img || !ready.value) {
return;
}
const canvas = document.createElement('canvas');
canvas.width = props.outputSize;
canvas.height = props.outputSize;
const context = canvas.getContext('2d');
if (!context) {
return;
}
const rect = viewportToSource(transform.value, viewportSize.value);
context.drawImage(img, rect.sx, rect.sy, rect.sw, rect.sh, 0, 0, props.outputSize, props.outputSize);
processing.value = true;
canvas.toBlob(
(blob) => {
processing.value = false;
if (!blob) {
return;
}
emit('cropped', new File([blob], props.fileName, { type: props.mimeType }));
close();
},
props.mimeType,
0.92,
);
};
watch(
() => props.open,
async (isOpen) => {
if (isOpen) {
initialized.value = false;
processing.value = false;
await nextTick();
measure();
if (viewportEl.value && !resizeObserver) {
resizeObserver = new ResizeObserver(() => measure());
resizeObserver.observe(viewportEl.value);
}
} else {
resizeObserver?.disconnect();
resizeObserver = null;
}
},
);
watch(
() => props.src,
() => {
initialized.value = false;
natural.value = { width: 0, height: 0 };
},
);
onBeforeUnmount(() => resizeObserver?.disconnect());
</script>
<template>
<Dialog :open="open" @update:open="emit('update:open', $event)">
<DialogContent class="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{{ $t('common.photo_upload.crop_title') }}</DialogTitle>
<DialogDescription>{{ $t('common.photo_upload.crop_description') }}</DialogDescription>
</DialogHeader>
<div
ref="viewportEl"
class="relative aspect-square w-full cursor-grab touch-none select-none overflow-hidden rounded-xl border-2 border-foreground bg-muted active:cursor-grabbing"
@pointerdown="onPointerDown"
@pointermove="onPointerMove"
@pointerup="onPointerUp"
@pointercancel="onPointerUp"
@wheel="onWheel"
>
<img
v-if="src"
ref="imageEl"
:src="src"
alt=""
draggable="false"
class="absolute left-0 top-0 max-w-none"
:style="imageStyle"
@load="onImageLoad"
/>
<div
class="pointer-events-none absolute inset-0"
:class="maskClass"
style="box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5), inset 0 0 0 2px rgba(255, 255, 255, 0.7)"
/>
</div>
<div class="flex items-center justify-center gap-3">
<Button type="button" variant="outline" size="icon" class="size-9" @click="zoomBy(0.9)">
<IconZoomOut class="size-4" />
</Button>
<span class="text-xs text-muted-foreground">{{ $t('common.photo_upload.crop_hint') }}</span>
<Button type="button" variant="outline" size="icon" class="size-9" @click="zoomBy(1.1)">
<IconZoomIn class="size-4" />
</Button>
</div>
<DialogFooter>
<Button type="button" data-testid="crop-save" :disabled="processing || !ready" @click="save">
{{ $t('common.photo_upload.crop_save') }}
</Button>
<Button type="button" variant="outline" @click="close">
{{ $t('common.photo_upload.crop_cancel') }}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</template>

View file

@ -2,8 +2,9 @@
import { router } from '@inertiajs/vue3';
import { IconTrash } from '@tabler/icons-vue';
import { trans } from 'laravel-vue-i18n';
import { ref } from 'vue';
import { computed, ref } from 'vue';
import ImageCropperDialog from '@/components/ImageCropperDialog.vue';
import { Avatar } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import {
@ -34,6 +35,13 @@ const props = withDefaults(defineProps<Props>(), {
const fileInput = ref<HTMLInputElement | null>(null);
const uploading = ref(false);
const cropOpen = ref(false);
const cropSrc = ref<string | null>(null);
const cropFileName = ref('image.png');
const cropMime = ref('image/png');
const cropShape = computed<'circle' | 'square'>(() => (props.rounded === 'full' ? 'circle' : 'square'));
const sizeClasses = {
sm: 'size-16',
md: 'size-20',
@ -63,6 +71,22 @@ const handleFileChange = (event: Event) => {
return;
}
cropFileName.value = file.name || 'image.png';
cropMime.value = file.type || 'image/png';
const reader = new FileReader();
reader.onload = () => {
cropSrc.value = reader.result as string;
cropOpen.value = true;
};
reader.readAsDataURL(file);
if (fileInput.value) {
fileInput.value.value = '';
}
};
const uploadCropped = (file: File) => {
uploading.value = true;
router.post(
@ -72,9 +96,7 @@ const handleFileChange = (event: Event) => {
forceFormData: true,
onFinish: () => {
uploading.value = false;
if (fileInput.value) {
fileInput.value.value = '';
}
cropSrc.value = null;
},
},
);
@ -140,5 +162,14 @@ const handleDelete = () => {
{{ $t('common.photo_upload.hint') }}
</p>
</div>
<ImageCropperDialog
v-model:open="cropOpen"
:src="cropSrc"
:file-name="cropFileName"
:mime-type="cropMime"
:shape="cropShape"
@cropped="uploadCropped"
/>
</div>
</template>

View file

@ -0,0 +1,81 @@
export type CropTransform = {
scale: number;
x: number;
y: number;
};
export type SourceRect = {
sx: number;
sy: number;
sw: number;
sh: number;
};
export const coverScale = (naturalWidth: number, naturalHeight: number, viewport: number): number => {
if (naturalWidth <= 0 || naturalHeight <= 0) {
return 1;
}
return Math.max(viewport / naturalWidth, viewport / naturalHeight);
};
export const clampTransform = (
transform: CropTransform,
naturalWidth: number,
naturalHeight: number,
viewport: number,
): CropTransform => {
const scale = Math.max(transform.scale, coverScale(naturalWidth, naturalHeight, viewport));
const displayWidth = naturalWidth * scale;
const displayHeight = naturalHeight * scale;
const x = Math.min(0, Math.max(viewport - displayWidth, transform.x));
const y = Math.min(0, Math.max(viewport - displayHeight, transform.y));
return { scale, x, y };
};
export const centerTransform = (naturalWidth: number, naturalHeight: number, viewport: number): CropTransform => {
const scale = coverScale(naturalWidth, naturalHeight, viewport);
return {
scale,
x: (viewport - naturalWidth * scale) / 2,
y: (viewport - naturalHeight * scale) / 2,
};
};
export const zoomTransform = (
transform: CropTransform,
factor: number,
naturalWidth: number,
naturalHeight: number,
viewport: number,
): CropTransform => {
const nextScale = Math.max(transform.scale * factor, coverScale(naturalWidth, naturalHeight, viewport));
const center = viewport / 2;
const sourceX = (center - transform.x) / transform.scale;
const sourceY = (center - transform.y) / transform.scale;
return clampTransform(
{
scale: nextScale,
x: center - sourceX * nextScale,
y: center - sourceY * nextScale,
},
naturalWidth,
naturalHeight,
viewport,
);
};
export const viewportToSource = (transform: CropTransform, viewport: number): SourceRect => {
const size = viewport / transform.scale;
return {
sx: -transform.x / transform.scale,
sy: -transform.y / transform.scale,
sw: size,
sh: size,
};
};

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
use App\Models\User;
/**
* Inject a real image into the hidden file input and dispatch `change`, driving
* the same flow a user's file selection would. The plugin's attach() sends
* localPaths, which Playwright rejects over its websocket connection, so a
* DataTransfer is used instead. The poll waits for the SPA to mount first.
*/
function selectPhoto(mixed $page): void
{
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/blue-logo.png')));
$page->script(<<<JS
(async () => {
const findInput = () => document.querySelector('input[type="file"]');
for (let attempt = 0; attempt < 50 && !findInput(); attempt++) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
const input = findInput();
const bytes = Uint8Array.from(atob('{$base64}'), (character) => character.charCodeAt(0));
const file = new File([bytes], 'logo.png', { type: 'image/png' });
const data = new DataTransfer();
data.items.add(file);
input.files = data.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
})();
JS);
}
/**
* Capture the next multipart request the page sends. The Pest browser server
* does not parse multipart bodies (its file handling is an open TODO), so we
* assert the crop dispatches the right upload rather than that it persists —
* server-side persistence is covered by ProfileUpdateTest.
*/
function recordUpload(mixed $page): void
{
$page->script(<<<'JS'
(() => {
window.__uploadRequest = null;
const open = XMLHttpRequest.prototype.open;
const send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, url) {
this.__method = method;
this.__url = url;
return open.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function (body) {
if (body instanceof FormData) {
window.__uploadRequest = { method: this.__method, url: this.__url, keys: [...body.keys()] };
}
return send.apply(this, arguments);
};
})();
JS);
}
test('cropping a selected photo dispatches a cropped avatar upload', function () {
$this->actingAs(User::factory()->create());
$page = visit(route('app.profile.edit'));
selectPhoto($page);
recordUpload($page);
// Auto-waits for the cropper dialog to open and its Save button to become
// enabled — the button only enables once the image has loaded and been
// measured inside the modal, which is exactly what a broken cropper fails.
$page->click('@crop-save')
->assertNoJavaScriptErrors();
$request = json_decode((string) $page->script(<<<'JS'
(async () => {
for (let attempt = 0; attempt < 80 && !window.__uploadRequest; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
return JSON.stringify(window.__uploadRequest);
})();
JS), true);
expect($request)->not->toBeNull()
->and($request['method'])->toBe('POST')
->and($request['url'])->toContain('/settings/profile/photo')
->and($request['keys'])->toContain('photo');
});

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
use App\Models\User;
test('probe upload response', function () {
$user = User::factory()->create();
$this->actingAs($user);
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/blue-logo.png')));
$page = visit(route('app.profile.edit'));
$page->script(<<<JS
(async () => {
const findInput = () => document.querySelector('input[type="file"]');
for (let i = 0; i < 50 && !findInput(); i++) { await new Promise(r => setTimeout(r, 100)); }
const input = findInput();
const bytes = Uint8Array.from(atob('{$base64}'), (c) => c.charCodeAt(0));
const file = new File([bytes], 'logo.png', { type: 'image/png' });
const dt = new DataTransfer(); dt.items.add(file);
input.files = dt.files;
input.dispatchEvent(new Event('change', { bubbles: true }));
})();
JS);
$page->script(<<<'JS'
(() => {
window.__resp = null;
const oOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (m, u) { this.__u = u; this.addEventListener('loadend', () => {
if (String(this.__u).includes('/photo')) window.__resp = { status: this.status, body: (this.responseText || '').slice(0, 300) };
}); return oOpen.apply(this, arguments); };
})();
JS);
$page->click('@crop-save');
$info = $page->script(<<<'JS'
(async () => { for (let i = 0; i < 80 && !window.__resp; i++) { await new Promise(r => setTimeout(r, 100)); } return JSON.stringify(window.__resp || 'NO RESPONSE'); })();
JS);
fwrite(STDERR, "\nUPLOAD_RESP => {$info}\n");
fwrite(STDERR, 'DB_HAS_PHOTO => '.json_encode($user->fresh()->has_photo)."\n");
expect(true)->toBeTrue();
});

View file

@ -24,7 +24,7 @@
pest()->extend(TestCase::class)
->use(RefreshDatabase::class)
->in('Feature', 'Unit');
->in('Feature', 'Unit', 'Browser');
/*
|--------------------------------------------------------------------------

View file

@ -21,6 +21,17 @@ protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
if (! $this->isBrowserTest()) {
$this->withoutVite();
}
}
/**
* Browser tests drive a real browser and need the built Vite assets, so the
* Vite manifest must not be faked away for them.
*/
private function isBrowserTest(): bool
{
return str_contains(static::class, '\\Browser\\');
}
}