Skip to content
Merged
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
133 changes: 133 additions & 0 deletions app-modules/identity/src/User/Concerns/HasProfileImages.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<?php

declare(strict_types=1);

namespace He4rt\Identity\User\Concerns;

use He4rt\Identity\User\Enums\ProfileImage;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Spatie\Image\Enums\Fit;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

/**
* Avatar e capa do perfil: como são guardados, convertidos e enquadrados.
*
* As dimensões e limites moram no enum ProfileImage; aqui fica só o que
* acontece com o arquivo.
*/
trait HasProfileImages
{
/**
* Chamado pelo `registerMediaCollections()` do model: o media library
* também define esse método, e dois traits com o mesmo nome colidem.
*/
public function registerProfileImageCollections(): void
{
foreach (ProfileImage::cases() as $image) {
$this->addMediaCollection($image->value)
->singleFile()
->useDisk('public')
->acceptsMimeTypes(ProfileImage::mimeTypes())
->registerMediaConversions(function (?Media $media = null) use ($image): void {
// O que é servido inteiro não passa por aqui: converter
// acharia o primeiro quadro de um GIF e mataria a animação.
// O enquadramento desses fica por conta do object-cover.
if (in_array($media?->mime_type, ProfileImage::unconvertedMimeTypes(), strict: true)) {
return;
}

// Para o resto, o front recebe sempre a mesma dimensão e o
// mesmo formato, independente do arquivo enviado. Aqui
// também é onde o upscale acontece, quando necessário.
$this->addMediaConversion($image->value)
->nonQueued()
->fit(Fit::Crop, $image->width(), $image->height())
->format('webp');
});
}
}

public function putImage(ProfileImage $image, UploadedFile $file): void
{
$this->refreshMediaRelation();

// A collection é singleFile: o media library troca a imagem anterior.
$this->addMedia($file)
->usingFileName(Str::uuid()->toString().'.'.$this->extensionOf($file))
->toMediaCollection($image->value);
}

public function removeImage(ProfileImage $image): void
{
$this->refreshMediaRelation();

$this->clearMediaCollection($image->value);
}

/**
* URL da conversão normalizada, caindo no original quando não existe
* conversão: mídia antiga, ou formato que é servido como chega.
*/
public function imageUrl(ProfileImage $image): ?string
{
$media = $this->getFirstMedia($image->value);

if (!$media instanceof Media) {
return null;
}

return $media->hasGeneratedConversion($image->value)
? $media->getUrl($image->value)
: $media->getUrl();
}

/**
* Imagem servida inteira, sem conversão, depende do enquadramento para
* decidir o que aparece no recorte da tela.
*/
public function imageNeedsFraming(ProfileImage $image): bool
{
$media = $this->getFirstMedia($image->value);

return $media instanceof Media && !$media->hasGeneratedConversion($image->value);
}

/**
* Faixa vertical da imagem que aparece no recorte da tela, em porcentagem.
*/
public function imageFocalY(ProfileImage $image): int
{
$focalY = $this->getFirstMedia($image->value)?->getCustomProperty('focal_y');

return is_numeric($focalY) ? (int) $focalY : ProfileImage::DEFAULT_FOCAL_Y;
}

public function setImageFocalY(ProfileImage $image, int $focalY): void
{
$media = $this->getFirstMedia($image->value);

if (!$media instanceof Media) {
return;
}

$media->setCustomProperty('focal_y', max(0, min(100, $focalY)));
$media->save();
}

/**
* O media library resolve `singleFile` lendo a relação já carregada. Numa
* requisição Livewire ela foi carregada na renderização, antes do upload,
* então sem descartar o cache a imagem anterior não é encontrada e fica
* órfã no disco.
*/
private function refreshMediaRelation(): void
{
$this->unsetRelation('media');
}

private function extensionOf(UploadedFile $file): string
{
return $file->getClientOriginalExtension() ?: $file->guessExtension() ?: 'jpg';
}
}
144 changes: 144 additions & 0 deletions app-modules/identity/src/User/Enums/ProfileImage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?php

declare(strict_types=1);

namespace He4rt\Identity\User\Enums;

/**
* Fonte única de configuração das imagens de perfil: nome da collection no
* media library, dimensão servida ao front, piso aceito no upload, proporção
* e limite de tamanho.
*
* Variação de imagem aqui é dado, não subclasse: uma imagem nova entra como
* mais um case e já nasce com upload, recorte, validação e conversão.
*
* Altura é sempre derivada da proporção, nunca armazenada, senão largura e
* altura divergem e o recorte deixa de ser previsível.
*/
enum ProfileImage: string
{
case Avatar = 'avatar';
case Cover = 'cover';

/** Centro da imagem: o recorte pega a faixa do meio. */
public const int DEFAULT_FOCAL_Y = 50;

/**
* @return list<string>
*/
public static function mimeTypes(): array
{
return ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
}

/**
* Formatos servidos exatamente como chegam, sem conversão.
*
* @return list<string>
*/
public static function unconvertedMimeTypes(): array
{
return ['image/gif'];
}

/**
* Teto menor para o que é servido sem conversão: nesses formatos o peso do
* upload é o peso que cada visita ao perfil baixa.
*/
public static function unconvertedMaxKilobytes(): int
{
return 2_048;
}

/**
* Os mesmos formatos, como o usuário os reconhece.
*
* GIF entra e é servido como chega, com a animação intacta: converter
* leria só o primeiro quadro no GD. Quem recorta pelo editor perde a
* animação, porque o recorte acontece no canvas do browser.
*/
Comment thread
sirelves marked this conversation as resolved.
Resolved
public static function formatLabels(): string
{
return 'JPG, PNG, GIF, WEBP';
}

/**
* Largura da conversão servida ao front.
*/
public function width(): int
{
return match ($this) {
self::Avatar => 500,
self::Cover => 1_800,
};
}

public function height(): int
{
return $this->heightFor($this->width());
}

/**
* Menor largura aceita no upload. Abaixo disso o upscale ficaria agressivo
* demais; entre o piso e a largura ideal, quem estica é a conversão.
*/
public function minWidth(): int
{
return match ($this) {
self::Avatar => 256,
self::Cover => 1_200,
};
}

public function minHeight(): int
{
return $this->heightFor($this->minWidth());
}

/**
* Proporção no formato aceito pelo editor de recorte do Filament.
*/
public function aspectRatio(): string
{
[$width, $height] = $this->ratio();

return sprintf('%d:%d', $width, $height);
}

/**
* A mesma proporção, no formato da propriedade CSS `aspect-ratio`. O blade
* não deve conhecer esses números por conta própria.
*/
public function cssAspectRatio(): string
{
[$width, $height] = $this->ratio();

return sprintf('%d / %d', $width, $height);
}

public function maxKilobytes(): int
{
return match ($this) {
self::Avatar => 2_048,
self::Cover => 4_096,
};
}

/**
* @return array{int, int}
*/
private function ratio(): array
{
return match ($this) {
self::Avatar => [1, 1],
self::Cover => [3, 1],
};
}

private function heightFor(int $width): int
{
[$ratioWidth, $ratioHeight] = $this->ratio();

return intdiv($width * $ratioHeight, $ratioWidth);
}
}
10 changes: 3 additions & 7 deletions app-modules/identity/src/User/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use He4rt\Gamification\Character\Models\Character;
use He4rt\Identity\Database\Factories\UserFactory;
use He4rt\Identity\ExternalIdentity\Models\ExternalIdentity;
use He4rt\Identity\User\Concerns\HasProfileImages;
use He4rt\Identity\User\Enums\UserSituation;
use He4rt\Identity\User\Observers\UserObserver;
use He4rt\Profile\Models\Profile;
Expand Down Expand Up @@ -54,6 +55,7 @@ final class User extends Authenticatable implements FilamentUser, HasMedia, HasN
/** @use HasFactory<UserFactory> */
use HasFactory;
use HasInteractions;
use HasProfileImages;
use HasUuids;
use InteractsWithMedia;
use Notifiable;
Expand Down Expand Up @@ -94,13 +96,7 @@ public function getFilamentName(): string

public function registerMediaCollections(): void
{
$this->addMediaCollection('avatar')
->singleFile()
->useDisk('public');

$this->addMediaCollection('cover')
->singleFile()
->useDisk('public');
$this->registerProfileImageCollections();
}

public function canAccessPanel(Panel $panel): bool
Expand Down
26 changes: 26 additions & 0 deletions app-modules/identity/tests/Unit/User/ProfileImageTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

use He4rt\Identity\User\Enums\ProfileImage;

test('height is always derived from the aspect ratio', function (ProfileImage $image): void {
[$ratioWidth, $ratioHeight] = explode(':', $image->aspectRatio());

expect($image->height())->toBe(intdiv($image->width() * (int) $ratioHeight, (int) $ratioWidth))
->and($image->minHeight())->toBe(intdiv($image->minWidth() * (int) $ratioHeight, (int) $ratioWidth));
})->with(ProfileImage::cases());

test('the minimum is never bigger than the recommended size', function (ProfileImage $image): void {
expect($image->minWidth())->toBeLessThanOrEqual($image->width())
->and($image->minHeight())->toBeLessThanOrEqual($image->height());
})->with(ProfileImage::cases());

test('css aspect ratio mirrors the cropper aspect ratio', function (ProfileImage $image): void {
expect($image->cssAspectRatio())->toBe(str_replace(':', ' / ', $image->aspectRatio()));
})->with(ProfileImage::cases());

test('cover is wide and avatar is square', function (): void {
expect(ProfileImage::Cover->aspectRatio())->toBe('3:1')
->and(ProfileImage::Avatar->aspectRatio())->toBe('1:1');
});
13 changes: 13 additions & 0 deletions app-modules/panel-app/lang/en/profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@
],

'hints' => [
'adjust_framing' => 'Drag to choose which slice of the image stays visible.',
'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.',
'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.',
'headline' => 'e.g. Frontend Developer, Product Designer',
'available_for_proposals' => 'When active, recruiters will see a green badge on your profile',
'city' => 'If your city is not listed, search for it.',
Expand All @@ -66,13 +69,22 @@
'skills' => 'Pick your skills and set your level and years of experience for each.',
],

'validation' => [
'image_dimensions' => 'After cropping, the image must be at least :min_width × :min_height px. The recommended size is :width × :height px.',
'image_mimetypes' => 'Unsupported format. Upload a :formats image.',
'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.',
],

'actions' => [
'save' => 'Save profile',
'add_social_link' => 'Add social link',
'add_work_experience' => 'Add experience',
'add_skill' => 'Add skill',
'change_avatar' => 'Change photo',
'change_cover' => 'Change cover',
'adjust_avatar' => 'Adjust photo framing',
'adjust_cover' => 'Adjust framing',
'save_framing' => 'Save framing',
'save_avatar' => 'Save photo',
'save_cover' => 'Save cover',
],
Expand All @@ -81,6 +93,7 @@
'saved' => 'Profile saved successfully!',
'avatar_updated' => 'Photo updated successfully!',
'cover_updated' => 'Cover updated successfully!',
'framing_updated' => 'Framing saved!',
'no_profile' => 'Profile not found for this tenant.',
],

Expand Down
Loading