Skip to content

Commit 10dd7c1

Browse files
authored
fix(profile): corrige upload de capa e avatar (#458) (#523)
2 parents a6cb22f + c90e104 commit 10dd7c1

16 files changed

Lines changed: 1090 additions & 97 deletions

File tree

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace He4rt\Identity\User\Concerns;
6+
7+
use He4rt\Identity\User\Enums\ProfileImage;
8+
use Illuminate\Http\UploadedFile;
9+
use Illuminate\Support\Str;
10+
use Spatie\Image\Enums\Fit;
11+
use Spatie\MediaLibrary\MediaCollections\Models\Media;
12+
13+
/**
14+
* Avatar e capa do perfil: como são guardados, convertidos e enquadrados.
15+
*
16+
* As dimensões e limites moram no enum ProfileImage; aqui fica só o que
17+
* acontece com o arquivo.
18+
*/
19+
trait HasProfileImages
20+
{
21+
/**
22+
* Chamado pelo `registerMediaCollections()` do model: o media library
23+
* também define esse método, e dois traits com o mesmo nome colidem.
24+
*/
25+
public function registerProfileImageCollections(): void
26+
{
27+
foreach (ProfileImage::cases() as $image) {
28+
$this->addMediaCollection($image->value)
29+
->singleFile()
30+
->useDisk('public')
31+
->acceptsMimeTypes(ProfileImage::mimeTypes())
32+
->registerMediaConversions(function (?Media $media = null) use ($image): void {
33+
// O que é servido inteiro não passa por aqui: converter
34+
// acharia o primeiro quadro de um GIF e mataria a animação.
35+
// O enquadramento desses fica por conta do object-cover.
36+
if (in_array($media?->mime_type, ProfileImage::unconvertedMimeTypes(), strict: true)) {
37+
return;
38+
}
39+
40+
// Para o resto, o front recebe sempre a mesma dimensão e o
41+
// mesmo formato, independente do arquivo enviado. Aqui
42+
// também é onde o upscale acontece, quando necessário.
43+
$this->addMediaConversion($image->value)
44+
->nonQueued()
45+
->fit(Fit::Crop, $image->width(), $image->height())
46+
->format('webp');
47+
});
48+
}
49+
}
50+
51+
public function putImage(ProfileImage $image, UploadedFile $file): void
52+
{
53+
$this->refreshMediaRelation();
54+
55+
// A collection é singleFile: o media library troca a imagem anterior.
56+
$this->addMedia($file)
57+
->usingFileName(Str::uuid()->toString().'.'.$this->extensionOf($file))
58+
->toMediaCollection($image->value);
59+
}
60+
61+
public function removeImage(ProfileImage $image): void
62+
{
63+
$this->refreshMediaRelation();
64+
65+
$this->clearMediaCollection($image->value);
66+
}
67+
68+
/**
69+
* URL da conversão normalizada, caindo no original quando não existe
70+
* conversão: mídia antiga, ou formato que é servido como chega.
71+
*/
72+
public function imageUrl(ProfileImage $image): ?string
73+
{
74+
$media = $this->getFirstMedia($image->value);
75+
76+
if (!$media instanceof Media) {
77+
return null;
78+
}
79+
80+
return $media->hasGeneratedConversion($image->value)
81+
? $media->getUrl($image->value)
82+
: $media->getUrl();
83+
}
84+
85+
/**
86+
* Imagem servida inteira, sem conversão, depende do enquadramento para
87+
* decidir o que aparece no recorte da tela.
88+
*/
89+
public function imageNeedsFraming(ProfileImage $image): bool
90+
{
91+
$media = $this->getFirstMedia($image->value);
92+
93+
return $media instanceof Media && !$media->hasGeneratedConversion($image->value);
94+
}
95+
96+
/**
97+
* Faixa vertical da imagem que aparece no recorte da tela, em porcentagem.
98+
*/
99+
public function imageFocalY(ProfileImage $image): int
100+
{
101+
$focalY = $this->getFirstMedia($image->value)?->getCustomProperty('focal_y');
102+
103+
return is_numeric($focalY) ? (int) $focalY : ProfileImage::DEFAULT_FOCAL_Y;
104+
}
105+
106+
public function setImageFocalY(ProfileImage $image, int $focalY): void
107+
{
108+
$media = $this->getFirstMedia($image->value);
109+
110+
if (!$media instanceof Media) {
111+
return;
112+
}
113+
114+
$media->setCustomProperty('focal_y', max(0, min(100, $focalY)));
115+
$media->save();
116+
}
117+
118+
/**
119+
* O media library resolve `singleFile` lendo a relação já carregada. Numa
120+
* requisição Livewire ela foi carregada na renderização, antes do upload,
121+
* então sem descartar o cache a imagem anterior não é encontrada e fica
122+
* órfã no disco.
123+
*/
124+
private function refreshMediaRelation(): void
125+
{
126+
$this->unsetRelation('media');
127+
}
128+
129+
private function extensionOf(UploadedFile $file): string
130+
{
131+
return $file->getClientOriginalExtension() ?: $file->guessExtension() ?: 'jpg';
132+
}
133+
}
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace He4rt\Identity\User\Enums;
6+
7+
/**
8+
* Fonte única de configuração das imagens de perfil: nome da collection no
9+
* media library, dimensão servida ao front, piso aceito no upload, proporção
10+
* e limite de tamanho.
11+
*
12+
* Variação de imagem aqui é dado, não subclasse: uma imagem nova entra como
13+
* mais um case e já nasce com upload, recorte, validação e conversão.
14+
*
15+
* Altura é sempre derivada da proporção, nunca armazenada, senão largura e
16+
* altura divergem e o recorte deixa de ser previsível.
17+
*/
18+
enum ProfileImage: string
19+
{
20+
case Avatar = 'avatar';
21+
case Cover = 'cover';
22+
23+
/** Centro da imagem: o recorte pega a faixa do meio. */
24+
public const int DEFAULT_FOCAL_Y = 50;
25+
26+
/**
27+
* @return list<string>
28+
*/
29+
public static function mimeTypes(): array
30+
{
31+
return ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
32+
}
33+
34+
/**
35+
* Formatos servidos exatamente como chegam, sem conversão.
36+
*
37+
* @return list<string>
38+
*/
39+
public static function unconvertedMimeTypes(): array
40+
{
41+
return ['image/gif'];
42+
}
43+
44+
/**
45+
* Teto menor para o que é servido sem conversão: nesses formatos o peso do
46+
* upload é o peso que cada visita ao perfil baixa.
47+
*/
48+
public static function unconvertedMaxKilobytes(): int
49+
{
50+
return 2_048;
51+
}
52+
53+
/**
54+
* Os mesmos formatos, como o usuário os reconhece.
55+
*
56+
* GIF entra e é servido como chega, com a animação intacta: converter
57+
* leria só o primeiro quadro no GD. Quem recorta pelo editor perde a
58+
* animação, porque o recorte acontece no canvas do browser.
59+
*/
60+
public static function formatLabels(): string
61+
{
62+
return 'JPG, PNG, GIF, WEBP';
63+
}
64+
65+
/**
66+
* Largura da conversão servida ao front.
67+
*/
68+
public function width(): int
69+
{
70+
return match ($this) {
71+
self::Avatar => 500,
72+
self::Cover => 1_800,
73+
};
74+
}
75+
76+
public function height(): int
77+
{
78+
return $this->heightFor($this->width());
79+
}
80+
81+
/**
82+
* Menor largura aceita no upload. Abaixo disso o upscale ficaria agressivo
83+
* demais; entre o piso e a largura ideal, quem estica é a conversão.
84+
*/
85+
public function minWidth(): int
86+
{
87+
return match ($this) {
88+
self::Avatar => 256,
89+
self::Cover => 1_200,
90+
};
91+
}
92+
93+
public function minHeight(): int
94+
{
95+
return $this->heightFor($this->minWidth());
96+
}
97+
98+
/**
99+
* Proporção no formato aceito pelo editor de recorte do Filament.
100+
*/
101+
public function aspectRatio(): string
102+
{
103+
[$width, $height] = $this->ratio();
104+
105+
return sprintf('%d:%d', $width, $height);
106+
}
107+
108+
/**
109+
* A mesma proporção, no formato da propriedade CSS `aspect-ratio`. O blade
110+
* não deve conhecer esses números por conta própria.
111+
*/
112+
public function cssAspectRatio(): string
113+
{
114+
[$width, $height] = $this->ratio();
115+
116+
return sprintf('%d / %d', $width, $height);
117+
}
118+
119+
public function maxKilobytes(): int
120+
{
121+
return match ($this) {
122+
self::Avatar => 2_048,
123+
self::Cover => 4_096,
124+
};
125+
}
126+
127+
/**
128+
* @return array{int, int}
129+
*/
130+
private function ratio(): array
131+
{
132+
return match ($this) {
133+
self::Avatar => [1, 1],
134+
self::Cover => [3, 1],
135+
};
136+
}
137+
138+
private function heightFor(int $width): int
139+
{
140+
[$ratioWidth, $ratioHeight] = $this->ratio();
141+
142+
return intdiv($width * $ratioHeight, $ratioWidth);
143+
}
144+
}

‎app-modules/identity/src/User/Models/User.php‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use He4rt\Gamification\Character\Models\Character;
1414
use He4rt\Identity\Database\Factories\UserFactory;
1515
use He4rt\Identity\ExternalIdentity\Models\ExternalIdentity;
16+
use He4rt\Identity\User\Concerns\HasProfileImages;
1617
use He4rt\Identity\User\Enums\UserSituation;
1718
use He4rt\Identity\User\Observers\UserObserver;
1819
use He4rt\Profile\Models\Profile;
@@ -54,6 +55,7 @@ final class User extends Authenticatable implements FilamentUser, HasMedia, HasN
5455
/** @use HasFactory<UserFactory> */
5556
use HasFactory;
5657
use HasInteractions;
58+
use HasProfileImages;
5759
use HasUuids;
5860
use InteractsWithMedia;
5961
use Notifiable;
@@ -94,13 +96,7 @@ public function getFilamentName(): string
9496

9597
public function registerMediaCollections(): void
9698
{
97-
$this->addMediaCollection('avatar')
98-
->singleFile()
99-
->useDisk('public');
100-
101-
$this->addMediaCollection('cover')
102-
->singleFile()
103-
->useDisk('public');
99+
$this->registerProfileImageCollections();
104100
}
105101

106102
public function canAccessPanel(Panel $panel): bool
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use He4rt\Identity\User\Enums\ProfileImage;
6+
7+
test('height is always derived from the aspect ratio', function (ProfileImage $image): void {
8+
[$ratioWidth, $ratioHeight] = explode(':', $image->aspectRatio());
9+
10+
expect($image->height())->toBe(intdiv($image->width() * (int) $ratioHeight, (int) $ratioWidth))
11+
->and($image->minHeight())->toBe(intdiv($image->minWidth() * (int) $ratioHeight, (int) $ratioWidth));
12+
})->with(ProfileImage::cases());
13+
14+
test('the minimum is never bigger than the recommended size', function (ProfileImage $image): void {
15+
expect($image->minWidth())->toBeLessThanOrEqual($image->width())
16+
->and($image->minHeight())->toBeLessThanOrEqual($image->height());
17+
})->with(ProfileImage::cases());
18+
19+
test('css aspect ratio mirrors the cropper aspect ratio', function (ProfileImage $image): void {
20+
expect($image->cssAspectRatio())->toBe(str_replace(':', ' / ', $image->aspectRatio()));
21+
})->with(ProfileImage::cases());
22+
23+
test('cover is wide and avatar is square', function (): void {
24+
expect(ProfileImage::Cover->aspectRatio())->toBe('3:1')
25+
->and(ProfileImage::Avatar->aspectRatio())->toBe('1:1');
26+
});

‎app-modules/panel-app/lang/en/profile.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@
5858
],
5959

6060
'hints' => [
61+
'adjust_framing' => 'Drag to choose which slice of the image stays visible.',
62+
'image_upload' => ':formats up to :max_mb MB. Recommended :width × :height px, at least :min_width × :min_height px after cropping. GIFs keep their animation, but cropping drops it.',
63+
'image_upload_with_gif_limit' => ':formats up to :max_mb MB, GIF up to :gif_mb MB. Recommended :width × :height px, at least :min_width × :min_height px after cropping. GIFs keep their animation, but cropping drops it.',
6164
'headline' => 'e.g. Frontend Developer, Product Designer',
6265
'available_for_proposals' => 'When active, recruiters will see a green badge on your profile',
6366
'city' => 'If your city is not listed, search for it.',
@@ -66,13 +69,22 @@
6669
'skills' => 'Pick your skills and set your level and years of experience for each.',
6770
],
6871

72+
'validation' => [
73+
'image_dimensions' => 'After cropping, the image must be at least :min_width × :min_height px. The recommended size is :width × :height px.',
74+
'image_mimetypes' => 'Unsupported format. Upload a :formats image.',
75+
'image_unconverted_max_size' => 'A GIF can be at most :gif_mb MB. It is served exactly as it arrives, with no compression, so the file weighs on every profile visit.',
76+
],
77+
6978
'actions' => [
7079
'save' => 'Save profile',
7180
'add_social_link' => 'Add social link',
7281
'add_work_experience' => 'Add experience',
7382
'add_skill' => 'Add skill',
7483
'change_avatar' => 'Change photo',
7584
'change_cover' => 'Change cover',
85+
'adjust_avatar' => 'Adjust photo framing',
86+
'adjust_cover' => 'Adjust framing',
87+
'save_framing' => 'Save framing',
7688
'save_avatar' => 'Save photo',
7789
'save_cover' => 'Save cover',
7890
],
@@ -81,6 +93,7 @@
8193
'saved' => 'Profile saved successfully!',
8294
'avatar_updated' => 'Photo updated successfully!',
8395
'cover_updated' => 'Cover updated successfully!',
96+
'framing_updated' => 'Framing saved!',
8497
'no_profile' => 'Profile not found for this tenant.',
8598
],
8699

0 commit comments

Comments
 (0)