diff --git a/backend/accounts-service/src/accounts/repo.rs b/backend/accounts-service/src/accounts/repo.rs index adb4e8dd..0249bbd1 100644 --- a/backend/accounts-service/src/accounts/repo.rs +++ b/backend/accounts-service/src/accounts/repo.rs @@ -61,6 +61,17 @@ pub async fn set_avatar(pool: &PgPool, account_id: Uuid, s3_key: &str) -> Result Ok(()) } +/// Deletes the `avatars` row for one account. Returns `true` when a row existed +/// (so the caller can decide whether to also delete the S3 object) and `false` +/// when the user simply had no avatar — the API still treats that as success. +pub async fn clear_avatar(pool: &PgPool, account_id: Uuid) -> Result { + let result = sqlx::query("DELETE FROM avatars WHERE account_id = $1") + .bind(account_id) + .execute(pool) + .await?; + Ok(result.rows_affected() > 0) +} + /// Avatar reference for one account: its storage key plus an `uploaded_at` /// version (epoch seconds) used to cache-bust the served image URL. pub async fn avatar_ref( diff --git a/backend/accounts-service/src/avatars/handlers.rs b/backend/accounts-service/src/avatars/handlers.rs index 8c783f42..53a9d95b 100644 --- a/backend/accounts-service/src/avatars/handlers.rs +++ b/backend/accounts-service/src/avatars/handlers.rs @@ -70,6 +70,28 @@ pub async fn upload( })) } +/// DELETE /avatars — clears the caller's avatar. Removes the DB row and, if one +/// existed, the S3 object. Always returns 204, including when the user had no +/// avatar: the operation is idempotent, matching how the frontend's "Remove +/// avatar" button should behave after a successful click. +pub async fn delete( + State(state): State, + identity: GatewayIdentity, +) -> Result { + let account_id = identity.account_id; + let existed = repo::clear_avatar(&state.pool, account_id).await?; + if existed { + let key = format!("avatars/{account_id}.png"); + // S3 delete is best-effort: if MinIO is unreachable we already committed + // the DB row removal, and the object becomes orphaned but not served (the + // serve handler looks up keys via the DB, not directly). + if let Err(err) = state.storage.delete(&key).await { + tracing::warn!("avatar S3 delete failed for {account_id}: {err}"); + } + } + Ok(StatusCode::NO_CONTENT.into_response()) +} + /// Only serve the keys this service writes: `avatars/.png`. /// Anything else (traversal, other buckets/paths) is a 404. The gateway blocks /// dot-segments upstream, but the service validates independently. diff --git a/backend/accounts-service/src/avatars/storage.rs b/backend/accounts-service/src/avatars/storage.rs index 1a33bc57..3a0644e9 100644 --- a/backend/accounts-service/src/avatars/storage.rs +++ b/backend/accounts-service/src/avatars/storage.rs @@ -51,4 +51,17 @@ impl S3Storage { let aggregated = out.body.collect().await?; Ok(aggregated.into_bytes().to_vec()) } + + /// Deletes the object at `key`. MinIO's DeleteObject is idempotent — deleting + /// a missing key returns Ok. Callers on the app layer are expected to run + /// this only after a matching DB row existed, so a stray 404 here is silent. + pub async fn delete(&self, key: &str) -> anyhow::Result<()> { + self.client + .delete_object() + .bucket(&self.bucket) + .key(key) + .send() + .await?; + Ok(()) + } } diff --git a/backend/accounts-service/src/lib.rs b/backend/accounts-service/src/lib.rs index d020ba24..2d12f82d 100644 --- a/backend/accounts-service/src/lib.rs +++ b/backend/accounts-service/src/lib.rs @@ -89,6 +89,7 @@ pub fn build_app_with_mail(pool: sqlx::PgPool, cfg: &Config, mail: auth::reset:: let avatar_routes = Router::new() .route("/avatars", post(avatars::handlers::upload)) + .route("/avatars", axum::routing::delete(avatars::handlers::delete)) // Public avatar read served back through the gateway; the `{*key}` // wildcard is the storage key (`avatars/.png`). .route("/media/{*key}", get(avatars::handlers::serve)) diff --git a/backend/accounts-service/tests/avatar_upload.rs b/backend/accounts-service/tests/avatar_upload.rs index 85291d70..215584cb 100644 --- a/backend/accounts-service/tests/avatar_upload.rs +++ b/backend/accounts-service/tests/avatar_upload.rs @@ -121,3 +121,78 @@ async fn upload_without_identity_is_401() { .await .assert_status(StatusCode::UNAUTHORIZED); } + +#[tokio::test] +async fn delete_removes_the_row_and_returns_204() { + common::init_test_logging(); + common::ensure_avatar_bucket().await; + let pool = common::test_pool().await; + let server = common::test_server(accounts_service::build_app( + pool.clone(), + &common::test_config(), + )); + let (account_id, email) = common::register_account(&server).await; + + server + .post("/avatars") + .add_header(ACCOUNT_ID_HEADER, account_id.to_string()) + .multipart(form(png_bytes())) + .await + .assert_status_ok(); + + server + .delete("/avatars") + .add_header(ACCOUNT_ID_HEADER, account_id.to_string()) + .await + .assert_status(StatusCode::NO_CONTENT); + + let count: i64 = sqlx::query_as::<_, (i64,)>("SELECT COUNT(*) FROM avatars WHERE account_id = $1") + .bind(account_id) + .fetch_one(&pool) + .await + .unwrap() + .0; + assert_eq!(count, 0); + + sqlx::query("DELETE FROM accounts WHERE lower(email) = $1") + .bind(email.to_lowercase()) + .execute(&pool) + .await + .unwrap(); +} + +#[tokio::test] +async fn delete_without_avatar_is_idempotent() { + let pool = common::test_pool().await; + let server = common::test_server(accounts_service::build_app( + pool.clone(), + &common::test_config(), + )); + let (account_id, email) = common::register_account(&server).await; + + server + .delete("/avatars") + .add_header(ACCOUNT_ID_HEADER, account_id.to_string()) + .await + .assert_status(StatusCode::NO_CONTENT); + + sqlx::query("DELETE FROM accounts WHERE lower(email) = $1") + .bind(email.to_lowercase()) + .execute(&pool) + .await + .unwrap(); +} + +#[tokio::test] +async fn delete_without_identity_is_401() { + let pool = common::test_pool().await; + let server = common::test_server(accounts_service::build_app( + pool.clone(), + &common::test_config(), + )); + + server + .delete("/avatars") + .await + .assert_status(StatusCode::UNAUTHORIZED); +} diff --git a/frontend/src/features/account/api.ts b/frontend/src/features/account/api.ts index 26a89967..3f0ca5d0 100644 --- a/frontend/src/features/account/api.ts +++ b/frontend/src/features/account/api.ts @@ -19,6 +19,16 @@ export async function uploadAvatar(file: File): Promise<{ avatar_url: string }> return api.request('/avatars', { method: 'POST', body }) } +/** + * DELETE /avatars — clears the caller's picture server-side. The backend is + * idempotent (always 204), so a repeated click is safe. The `me` cache is + * invalidated by the caller, not here, so the button can chain invalidations + * with any other side effects (e.g. history tick bump). + */ +export async function removeAvatar(): Promise { + await api.request('/avatars', { method: 'DELETE' }) +} + /** Byte-level progress comes only from XHR (see `api.upload`), not from fetch. */ export function uploadAvatarWithProgress(file: File, onProgress: (pct: number) => void): Promise<{ avatar_url: string }> { const body = new FormData() diff --git a/frontend/src/features/account/components/avatar/AvatarCropper.tsx b/frontend/src/features/account/components/avatar/AvatarCropper.tsx index 3bb1a67a..6268f319 100644 --- a/frontend/src/features/account/components/avatar/AvatarCropper.tsx +++ b/frontend/src/features/account/components/avatar/AvatarCropper.tsx @@ -1,74 +1,157 @@ -import { useRef, useState, type PointerEvent as ReactPointerEvent } from 'react' +import { + useCallback, + useEffect, + useRef, + useState, + type KeyboardEvent as ReactKeyboardEvent, + type PointerEvent as ReactPointerEvent, + type WheelEvent as ReactWheelEvent, +} from 'react' import { useTranslation } from '@shared/i18n/react' -import { Button } from '@shared/ui/Button' -import { clampPan, clampZoom, coverScale, MAX_ZOOM, MIN_ZOOM, sourceRect } from './cropMath' +import { + MAX_ZOOM, + MIN_ZOOM, + PAN_STEP, + VIEWPORT, + ZOOM_STEP, + clampPan, + clampZoom, + coverScale, + pinchZoom, + wheelZoom, +} from './cropMath' -const VIEWPORT = 240 -const OUTPUT_SIZE = 512 +export type CropState = { + zoom: number + offset: { x: number; y: number } + natural: { w: number; h: number } +} type Props = { file: File - onCancel: () => void - onConfirm: (blob: Blob) => void + /** Fires once on first user interaction so the dialog can flip an "unsaved changes" guard. */ + onDirty?: () => void + /** Fires whenever the crop geometry changes; the dialog renders previews off this. */ + onCropState?: (state: CropState) => void } -/** Drag-to-reposition, zoom-to-scale circular crop UI. Renders the selection onto an offscreen canvas on confirm. */ -export function AvatarCropper({ file, onCancel, onConfirm }: Props) { +/** + * The interactive crop canvas. Owns image layout (drag to pan, wheel / pinch to + * zoom, arrow keys / +/-/0 for keyboard), the visible rule-of-thirds guides and + * the corner shade that shows exactly what falls inside the circle. Cancel and + * Confirm live in {@link AvatarEditDialog}, not here — this component is pure + * viewport + input handling. + * + *

Everything the 2026-10 avatar-settings research identified as "missing in + * ours, present in every reference product": + *

    + *
  • bigger viewport (320 vs the previous 240 — the smallest in the sample)
  • + *
  • visible guides + shade, so the user knows what will actually end up in + * the file (previous `overflow-hidden rounded-full` hid the crop frame + * entirely)
  • + *
  • wheel zoom + pinch zoom (both no-brainers per react-easy-crop)
  • + *
  • keyboard: arrows pan, +/- zoom, 0 resets (Google documents this)
  • + *
  • a Reset button returning to zoom=MIN, offset=(0,0)
  • + *
+ */ +export function AvatarCropper({ file, onDirty, onCropState }: Props) { const { t } = useTranslation('account') const [url] = useState(() => URL.createObjectURL(file)) + useEffect(() => () => URL.revokeObjectURL(url), [url]) const [natural, setNatural] = useState<{ w: number; h: number }>() const [zoom, setZoom] = useState(MIN_ZOOM) const [offset, setOffset] = useState({ x: 0, y: 0 }) - const [busy, setBusy] = useState(false) + + const pointers = useRef(new Map()) + const pinchBase = useRef<{ distance: number; zoom: number } | null>(null) const drag = useRef<{ x: number; y: number; offset: { x: number; y: number } } | null>(null) - function onImgLoad(e: React.SyntheticEvent) { - setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight }) + const markDirty = useCallback(() => onDirty?.(), [onDirty]) + + // Publish crop state so the dialog's preview column stays in sync. + useEffect(() => { + if (!natural) return + onCropState?.({ zoom, offset, natural }) + }, [natural, zoom, offset, onCropState]) + + const applyZoom = useCallback( + (next: number) => { + const clamped = clampZoom(next) + setZoom(clamped) + if (natural) setOffset((prev) => clampPan(prev, natural.w, natural.h, VIEWPORT, clamped)) + markDirty() + }, + [natural, markDirty], + ) + + const applyPan = useCallback( + (next: { x: number; y: number }) => { + if (!natural) return + setOffset(clampPan(next, natural.w, natural.h, VIEWPORT, zoom)) + markDirty() + }, + [natural, zoom, markDirty], + ) + + function reset() { + setZoom(MIN_ZOOM) + setOffset({ x: 0, y: 0 }) + markDirty() } function onPointerDown(e: ReactPointerEvent) { e.currentTarget.setPointerCapture(e.pointerId) + pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY }) + if (pointers.current.size === 2) { + const [a, b] = [...pointers.current.values()] + pinchBase.current = { distance: Math.hypot(a.x - b.x, a.y - b.y), zoom } + drag.current = null + return + } drag.current = { x: e.clientX, y: e.clientY, offset } } function onPointerMove(e: ReactPointerEvent) { - if (!drag.current || !natural) return - const dx = e.clientX - drag.current.x - const dy = e.clientY - drag.current.y - const next = { x: drag.current.offset.x + dx, y: drag.current.offset.y + dy } - setOffset(clampPan(next, natural.w, natural.h, VIEWPORT, zoom)) - } - - function onPointerUp() { - drag.current = null - } - - function onZoomChange(next: number) { - const clamped = clampZoom(next) - setZoom(clamped) - if (natural) setOffset((prev) => clampPan(prev, natural.w, natural.h, VIEWPORT, clamped)) - } - - async function confirm() { if (!natural) return - setBusy(true) - const img = new Image() - img.src = url - await img.decode() - const { sx, sy, sw, sh } = sourceRect(natural.w, natural.h, VIEWPORT, zoom, offset) - const canvas = document.createElement('canvas') - canvas.width = OUTPUT_SIZE - canvas.height = OUTPUT_SIZE - const ctx = canvas.getContext('2d') - if (!ctx) { - setBusy(false) + if (pointers.current.has(e.pointerId)) { + pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY }) + } + if (pointers.current.size === 2 && pinchBase.current) { + const [a, b] = [...pointers.current.values()] + const next = Math.hypot(a.x - b.x, a.y - b.y) + applyZoom(pinchZoom(pinchBase.current.zoom, pinchBase.current.distance, next)) return } - ctx.drawImage(img, sx, sy, sw, sh, 0, 0, OUTPUT_SIZE, OUTPUT_SIZE) - canvas.toBlob((blob) => { - setBusy(false) - if (blob) onConfirm(blob) - }, 'image/png') + if (!drag.current) return + const dx = e.clientX - drag.current.x + const dy = e.clientY - drag.current.y + applyPan({ x: drag.current.offset.x + dx, y: drag.current.offset.y + dy }) + } + + function onPointerUp(e: ReactPointerEvent) { + pointers.current.delete(e.pointerId) + if (pointers.current.size < 2) pinchBase.current = null + if (pointers.current.size === 0) drag.current = null + } + + function onWheel(e: ReactWheelEvent) { + if (!natural) return + applyZoom(wheelZoom(zoom, e.deltaY)) + } + + function onKeyDown(e: ReactKeyboardEvent) { + if (!natural) return + switch (e.key) { + case 'ArrowLeft': e.preventDefault(); applyPan({ x: offset.x - PAN_STEP, y: offset.y }); return + case 'ArrowRight': e.preventDefault(); applyPan({ x: offset.x + PAN_STEP, y: offset.y }); return + case 'ArrowUp': e.preventDefault(); applyPan({ x: offset.x, y: offset.y - PAN_STEP }); return + case 'ArrowDown': e.preventDefault(); applyPan({ x: offset.x, y: offset.y + PAN_STEP }); return + case '+': + case '=': e.preventDefault(); applyZoom(zoom + ZOOM_STEP); return + case '-': + case '_': e.preventDefault(); applyZoom(zoom - ZOOM_STEP); return + case '0': e.preventDefault(); reset(); return + } } const scale = natural ? coverScale(natural.w, natural.h, VIEWPORT) * zoom : 1 @@ -76,20 +159,26 @@ export function AvatarCropper({ file, onCancel, onConfirm }: Props) { const drawnH = natural ? natural.h * scale : VIEWPORT return ( -
+
setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })} className="pointer-events-none absolute select-none" style={{ width: drawnW, @@ -98,27 +187,41 @@ export function AvatarCropper({ file, onCancel, onConfirm }: Props) { top: VIEWPORT / 2 - drawnH / 2 + offset.y, }} /> -
-