feat(profile): add round avatar with upload and cropping

- backend: user_avatar_objects binding (PG+SQLite), GC preserves avatar blobs,
  avatar service (EXIF-stripping WebP 128/512), public avatar read route
- web: avatar upload/crop on profile, round avatar in header/members/comments/author
- android: avatar upload/crop, round avatar on profile and albums header
- openspec: add-user-avatar proposal/design/specs/tasks
This commit is contained in:
iu
2026-10-12 16:16:47 +03:00
parent 657a04309e
commit 04617d1cdb
49 changed files with 2362 additions and 21 deletions
+6
View File
@@ -101,6 +101,12 @@ export const authApi = {
me: () => api<{ user: User; preferences?: Preferences }>('/auth/me'),
updateProfile: (name: string) =>
api<{ user: User }>('/auth/me', { method: 'PATCH', body: { name } }),
uploadAvatar: (file: Blob) => {
const form = new FormData();
form.append('file', file, 'avatar.jpg');
return api<{ user: User }>('/auth/me/avatar', { method: 'POST', form });
},
removeAvatar: () => api<{ user: User }>('/auth/me/avatar', { method: 'DELETE' }),
changePassword: (current_password: string, new_password: string) =>
api('/auth/me/password', { method: 'POST', body: { current_password, new_password } }),
addIdentifier: (email: string, phone: string) =>
+3 -2
View File
@@ -2,6 +2,7 @@
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { authApi } from '$lib/api';
import Avatar from './Avatar.svelte';
import Emblem from './Emblem.svelte';
import Icon from './Icon.svelte';
import ThemeSwitcher from './ThemeSwitcher.svelte';
@@ -135,10 +136,10 @@
{#if auth.isAuthenticated}
<a
href="/profile"
class="text-text-muted hover:text-text inline-flex items-center gap-1 text-xs"
class="text-text-muted hover:text-text inline-flex items-center gap-1.5 text-xs"
title="Профиль"
>
<Icon name="settings" class="size-4" />
<Avatar name={auth.user?.name} url={auth.user?.avatar_url} size="size-6" />
<span class="hidden sm:inline">{auth.user?.name ?? 'Профиль'}</span>
</a>
<button
+31
View File
@@ -0,0 +1,31 @@
<script lang="ts">
import Icon from './Icon.svelte';
interface Props {
name?: string;
url?: string | null;
/** Tailwind size classes for the round frame, e.g. "size-6". */
size?: string;
class?: string;
}
let { name = '', url = '', size = 'size-6', class: className = '' }: Props = $props();
</script>
{#if url}
<img
src={url}
alt={name || 'Аватар'}
title={name}
class="{size} {className} shrink-0 rounded-full object-cover"
/>
{:else}
<span
class="{size} {className} bg-bg-muted text-text-muted inline-flex shrink-0 items-center justify-center rounded-full"
role="img"
aria-label={name || 'Аватар'}
title={name}
>
<Icon name="person" class="h-3/4 w-3/4" />
</span>
{/if}
@@ -0,0 +1,191 @@
<script lang="ts">
import { onMount } from 'svelte';
import Icon from './Icon.svelte';
interface Props {
file: File;
onCancel: () => void;
onConfirm: (blob: Blob) => void;
}
let { file, onCancel, onConfirm }: Props = $props();
// The cropper always produces a square. VIEW is the on-screen picker size;
// OUTPUT is the uploaded resolution.
const VIEW = 320;
const OUTPUT = 512;
let canvas: HTMLCanvasElement | null = null;
let img = $state<HTMLImageElement | null>(null);
let zoom = $state(1);
let offsetX = $state(0);
let offsetY = $state(0);
let dragging = false;
let lastX = 0;
let lastY = 0;
let busy = $state(false);
onMount(() => {
const url = URL.createObjectURL(file);
const image = new Image();
image.onload = () => {
img = image;
clamp();
};
image.src = url;
return () => URL.revokeObjectURL(url);
});
function baseScale(): number {
if (!img) return 1;
return Math.max(VIEW / img.naturalWidth, VIEW / img.naturalHeight);
}
function scale(): number {
return baseScale() * zoom;
}
function drawn(): { w: number; h: number } {
if (!img) return { w: VIEW, h: VIEW };
const s = scale();
return { w: img.naturalWidth * s, h: img.naturalHeight * s };
}
function clamp() {
const { w, h } = drawn();
const mx = Math.max(0, (w - VIEW) / 2);
const my = Math.max(0, (h - VIEW) / 2);
offsetX = Math.min(mx, Math.max(-mx, offsetX));
offsetY = Math.min(my, Math.max(-my, offsetY));
}
function draw() {
if (!canvas || !img) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const { w, h } = drawn();
const x = (VIEW - w) / 2 + offsetX;
const y = (VIEW - h) / 2 + offsetY;
ctx.clearRect(0, 0, VIEW, VIEW);
ctx.drawImage(img, x, y, w, h);
// Dim everything outside the circular crop.
ctx.save();
ctx.beginPath();
ctx.rect(0, 0, VIEW, VIEW);
ctx.arc(VIEW / 2, VIEW / 2, VIEW / 2 - 1, 0, Math.PI * 2, true);
ctx.fillStyle = 'rgba(0,0,0,0.55)';
ctx.fill('evenodd');
ctx.restore();
ctx.beginPath();
ctx.arc(VIEW / 2, VIEW / 2, VIEW / 2 - 1, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(255,255,255,0.85)';
ctx.lineWidth = 2;
ctx.stroke();
}
$effect(() => {
img;
zoom;
offsetX;
offsetY;
draw();
});
function onPointerDown(e: PointerEvent) {
dragging = true;
lastX = e.clientX;
lastY = e.clientY;
(e.currentTarget as HTMLCanvasElement).setPointerCapture(e.pointerId);
}
function onPointerMove(e: PointerEvent) {
if (!dragging) return;
offsetX += e.clientX - lastX;
offsetY += e.clientY - lastY;
lastX = e.clientX;
lastY = e.clientY;
clamp();
}
function onPointerUp(e: PointerEvent) {
dragging = false;
try {
(e.currentTarget as HTMLCanvasElement).releasePointerCapture(e.pointerId);
} catch {
/* already released */
}
}
function onZoom(e: Event) {
zoom = Number((e.currentTarget as HTMLInputElement).value);
clamp();
}
async function confirm() {
if (!img || !canvas) return;
busy = true;
try {
const s = scale();
const side = VIEW / s;
const cx = img.naturalWidth / 2 - offsetX / s;
const cy = img.naturalHeight / 2 - offsetY / s;
const out = document.createElement('canvas');
out.width = OUTPUT;
out.height = OUTPUT;
const octx = out.getContext('2d');
if (!octx) return;
octx.drawImage(img, cx - side / 2, cy - side / 2, side, side, 0, 0, OUTPUT, OUTPUT);
const blob = await new Promise<Blob | null>((resolve) =>
out.toBlob(resolve, 'image/jpeg', 0.9)
);
if (blob) onConfirm(blob);
} finally {
busy = false;
}
}
</script>
<div
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
role="dialog"
aria-modal="true"
aria-label="Кадрирование аватара"
>
<div class="border-border bg-bg-elevated w-full max-w-sm rounded-xl border p-4">
<h2 class="mb-3 font-semibold">Кадрирование</h2>
<canvas
bind:this={canvas}
width={VIEW}
height={VIEW}
class="bg-bg mx-auto block touch-none rounded-lg"
style="width: {VIEW}px; height: {VIEW}px;"
onpointerdown={onPointerDown}
onpointermove={onPointerMove}
onpointerup={onPointerUp}
onpointercancel={onPointerUp}
></canvas>
<label class="mt-3 block">
<span class="text-text-muted mb-1 block text-xs">Масштаб</span>
<input type="range" min="1" max="3" step="0.01" value={zoom} oninput={onZoom} class="w-full" />
</label>
<div class="mt-4 flex justify-end gap-2">
<button
type="button"
class="border-border text-text inline-flex items-center gap-1.5 rounded-lg border px-4 py-2 text-sm"
onclick={onCancel}
>
<Icon name="close" class="size-4" />
Отмена
</button>
<button
type="button"
class="bg-primary text-primary-fg inline-flex items-center gap-1.5 rounded-lg px-4 py-2 text-sm disabled:opacity-50"
disabled={busy}
onclick={confirm}
>
<Icon name="check" class="size-4" />
Сохранить
</button>
</div>
</div>
</div>
+4 -2
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { api } from '$lib/api';
import Avatar from './Avatar.svelte';
import Icon from './Icon.svelte';
import { auth } from '$lib/stores/auth.svelte';
import type { Comment } from '$lib/types';
@@ -56,8 +57,9 @@
<div class="mt-2">
{#each comments as comment (comment.id)}
<div class="border-border mb-1 flex items-start justify-between gap-2 border-b py-1 text-sm">
<span class="text-text">
<strong>{comment.user.name}</strong>: {comment.text}
<span class="text-text inline-flex items-start gap-2">
<Avatar name={comment.user.name} url={comment.user.avatar_url} size="size-6" />
<span><strong>{comment.user.name}</strong>: {comment.text}</span>
</span>
{#if auth.user?.id === comment.user_id}
<button
@@ -1,5 +1,6 @@
<script lang="ts">
import { api, photosApi, tagsApi } from '$lib/api';
import Avatar from './Avatar.svelte';
import Icon from './Icon.svelte';
import Comments from './Comments.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
@@ -396,7 +397,7 @@
</button>
{/snippet}
<dl class="space-y-1">
<div class={metaRow}><span>Автор</span><span class="text-text">{photo.uploader.name}</span></div>
<div class={metaRow}><span>Автор</span><span class="text-text inline-flex items-center gap-2"><Avatar name={photo.uploader.name} url={photo.uploader.avatar_url} size="size-6" />{photo.uploader.name}</span></div>
<div class={metaRow}><span>Файл</span><span class="text-text">{formatSize(photo.size)}</span></div>
<div class={metaRow}><span>Тип</span><span class="text-text">{photo.mime_type}</span></div>
<div class={metaRow}>
+1
View File
@@ -23,6 +23,7 @@ export const icons = {
play_arrow: { path: '<path fill="currentColor" d="M8 19V5l11 7z"/>' },
photo_library: { path: '<path fill="currentColor" d="M9 14h10l-3.45-4.5l-2.3 3l-1.55-2zm-1 4q-.825 0-1.412-.587T6 16V4q0-.825.588-1.412T8 2h12q.825 0 1.413.588T22 4v12q0 .825-.587 1.413T20 18zm-4 4q-.825 0-1.412-.587T2 20V6h2v14h14v2z"/>' },
group: { path: '<path fill="currentColor" d="M1 20v-2.8q0-.85.438-1.562T2.6 14.55q1.55-.775 3.15-1.162T9 13t3.25.388t3.15 1.162q.725.375 1.163 1.088T17 17.2V20zm18 0v-3q0-1.1-.612-2.113T16.65 13.15q1.275.15 2.4.513t2.1.887q.9.5 1.375 1.112T23 17v3zM6.175 10.825Q5 9.65 5 8t1.175-2.825T9 4t2.825 1.175T13 8t-1.175 2.825T9 12t-2.825-1.175m11.65 0Q16.65 12 15 12q-.275 0-.7-.062t-.7-.138q.675-.8 1.038-1.775T15 8t-.362-2.025T13.6 4.2q.35-.125.7-.163T15 4q1.65 0 2.825 1.175T19 8t-1.175 2.825"/>' },
person: { path: '<path fill="currentColor" d="M12 12q-1.65 0-2.825-1.175T8 8t1.175-2.825T12 4t2.825 1.175T16 8t-1.175 2.825T12 12m-8 8v-2.8q0-.85.438-1.562T5.6 14.55q1.55-.775 3.15-1.162T12 13t3.25.388t3.15 1.162q.725.375 1.163 1.088T20 17.2V20z"/>' },
settings: { path: '<path fill="currentColor" d="m9.25 22l-.4-3.2q-.325-.125-.612-.3t-.563-.375L4.7 19.375l-2.75-4.75l2.575-1.95Q4.5 12.5 4.5 12.338v-.675q0-.163.025-.338L1.95 9.375l2.75-4.75l2.975 1.25q.275-.2.575-.375t.6-.3l.4-3.2h5.5l.4 3.2q.325.125.613.3t.562.375l2.975-1.25l2.75 4.75l-2.575 1.95q.025.175.025.338v.674q0 .163-.05.338l2.575 1.95l-2.75 4.75l-2.95-1.25q-.275.2-.575.375t-.6.3l-.4 3.2zm2.8-6.5q1.45 0 2.475-1.025T15.55 12t-1.025-2.475T12.05 8.5q-1.475 0-2.488 1.025T8.55 12t1.013 2.475T12.05 15.5"/>' },
cloud_upload: { path: '<path fill="currentColor" d="M11 20H6.5q-2.275 0-3.887-1.575T1 14.575q0-1.95 1.175-3.475T5.25 9.15q.625-2.3 2.5-3.725T12 4q2.925 0 4.963 2.038T19 11q1.725.2 2.863 1.488T23 15.5q0 1.875-1.312 3.188T18.5 20H13v-7.15l1.6 1.55L16 13l-4-4l-4 4l1.4 1.4l1.6-1.55z"/>' },
add_photo_alternate: { path: '<path fill="currentColor" d="M5 21q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h9q-.5.65-.75 1.425T13 6q0 2.075 1.463 3.538T18 11q.8 0 1.575-.25T21 10v9q0 .825-.587 1.413T19 21zm1-4h12l-3.75-5l-3 4L9 13zm11-8V7h-2V5h2V3h2v2h2v2h-2v2z"/>' },
@@ -1,6 +1,7 @@
<script lang="ts">
import { page } from '$app/stores';
import { api } from '$lib/api';
import Avatar from '$lib/components/Avatar.svelte';
import Icon from '$lib/components/Icon.svelte';
import { auth } from '$lib/stores/auth.svelte';
import type { Album, AlbumMember } from '$lib/types';
@@ -101,8 +102,10 @@
</li>
{#each members as member (member.user_id)}
<li class="flex items-center justify-between gap-4 px-4 py-3">
<span class="text-text"
>{member.user.name} <span class="text-text-muted text-sm">({member.user.email})</span></span
<span class="text-text inline-flex items-center gap-2"
><Avatar name={member.user.name} url={member.user.avatar_url} size="size-7" />
{member.user.name}
<span class="text-text-muted text-sm">({member.user.email})</span></span
>
<div class="flex items-center gap-2">
{#if assignableRoles.length > 0}
+85 -2
View File
@@ -1,6 +1,8 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { authApi } from '$lib/api';
import Avatar from '$lib/components/Avatar.svelte';
import AvatarCropper from '$lib/components/AvatarCropper.svelte';
import Icon from '$lib/components/Icon.svelte';
import { auth } from '$lib/stores/auth.svelte';
@@ -11,6 +13,8 @@
let currentPassword = $state('');
let newPassword = $state('');
let deletePassword = $state('');
let pickedFile = $state<File | null>(null);
let avatarBusy = $state(false);
let error = $state('');
let notice = $state('');
@@ -34,6 +38,44 @@
if (updated) auth.setUser(updated);
}
function onPickFile(ev: Event) {
const input = ev.currentTarget as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (file) pickedFile = file;
}
async function onCropConfirm(blob: Blob) {
avatarBusy = true;
error = '';
notice = '';
try {
const data = await authApi.uploadAvatar(blob);
applyUser(data.user);
pickedFile = null;
notice = 'Аватар обновлён';
} catch (e) {
error = (e as Error).message;
} finally {
avatarBusy = false;
}
}
async function removeAvatar() {
avatarBusy = true;
error = '';
notice = '';
try {
const data = await authApi.removeAvatar();
applyUser(data.user);
notice = 'Аватар удалён';
} catch (e) {
error = (e as Error).message;
} finally {
avatarBusy = false;
}
}
async function saveName(ev: Event) {
ev.preventDefault();
error = '';
@@ -75,8 +117,7 @@
}
}
async function removeAccount() {
error = '';
async function removeAccount() { error = '';
if (!confirm('Удалить аккаунт со всем содержимым? Действие необратимо.')) return;
try {
await authApi.deleteAccount(deletePassword);
@@ -99,6 +140,40 @@
{#if error}<p class="text-danger mb-4 text-sm">{error}</p>{/if}
{#if notice}<p class="text-success mb-4 text-sm">{notice}</p>{/if}
<div class="border-border bg-bg-elevated mb-6 rounded-xl border p-4">
<h2 class="mb-3 font-semibold">Фото профиля</h2>
<div class="flex items-center gap-4">
<Avatar name={user?.name} url={user?.avatar_url} size="size-20" />
<div class="flex flex-wrap gap-2">
<label
class="bg-primary text-primary-fg inline-flex cursor-pointer items-center gap-1.5 rounded-lg px-4 py-2 text-sm"
>
<Icon name="photo_camera" class="size-4" />
{user?.avatar_url ? 'Заменить фото' : 'Загрузить фото'}
<input
type="file"
accept="image/*"
class="hidden"
disabled={avatarBusy}
onchange={onPickFile}
/>
</label>
{#if user?.avatar_url}
<button
type="button"
class="border-danger text-danger inline-flex items-center gap-1.5 rounded-lg border px-4 py-2 text-sm disabled:opacity-50"
disabled={avatarBusy}
onclick={removeAvatar}
>
<Icon name="delete" class="size-4" />
Удалить
</button>
{/if}
</div>
</div>
<p class="text-text-muted mt-2 text-xs">Квадратное изображение; можно выбрать область кадрирования.</p>
</div>
<div class="border-border bg-bg-elevated mb-6 rounded-xl border p-4">
<h2 class="mb-2 font-semibold">Идентификаторы</h2>
<ul class="text-text-muted space-y-1 text-sm">
@@ -224,3 +299,11 @@
Удалить аккаунт
</button>
</div>
{#if pickedFile}
<AvatarCropper
file={pickedFile}
onCancel={() => (pickedFile = null)}
onConfirm={onCropConfirm}
/>
{/if}