feat(web): let users set their own photo on the account page
Pick a PNG/JPEG/WebP file, crop it to a square on a canvas (drag, wheel, slider or keyboard), export a 256x256 PNG and send it to Hub. Adds remove photo, error states, RU/EN copy and privacy policy text about the stored photo and 30-day backups. Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
This commit is contained in:
parent
a4cae66336
commit
76f8371a7e
10 changed files with 739 additions and 14 deletions
278
src/app.ts
278
src/app.ts
|
|
@ -9,7 +9,20 @@ import {
|
|||
ApiError,
|
||||
requestEmailCode,
|
||||
verifyEmailCode,
|
||||
uploadAvatar,
|
||||
removeAvatar,
|
||||
isOwnAvatar,
|
||||
} from "./api";
|
||||
import type { CropState } from "./crop";
|
||||
import {
|
||||
OUTPUT_SIDE,
|
||||
MAX_ZOOM,
|
||||
initialCrop,
|
||||
clampCrop,
|
||||
panBy,
|
||||
sourceRect,
|
||||
zoomTo,
|
||||
} from "./crop";
|
||||
|
||||
let savedLanguage: string | null | undefined;
|
||||
try {
|
||||
|
|
@ -53,6 +66,13 @@ let resendTimer: ReturnType<typeof setInterval> | undefined;
|
|||
let sessionState: "loading" | "ready" | "error" = "loading";
|
||||
let infoState: "loading" | "ready" | "error" = "loading";
|
||||
let logoutState: "idle" | "pending" | "error" = "idle";
|
||||
// Avatar editor state also lives outside the DOM, so a language switch keeps the crop.
|
||||
const AVATAR_VIEW = 280;
|
||||
const AVATAR_MAX_FILE = 10 * 1024 * 1024;
|
||||
const AVATAR_MAX_SIDE = 8192;
|
||||
let avatarBusy: "idle" | "saving" | "removing" = "idle";
|
||||
let avatarMessage: MessageKey | null = null;
|
||||
let avatarCrop: { bitmap: ImageBitmap; state: CropState } | null = null;
|
||||
const t = (key: MessageKey) => translate(language, key);
|
||||
const icon = (
|
||||
name:
|
||||
|
|
@ -214,7 +234,7 @@ function renderAccount() {
|
|||
return;
|
||||
}
|
||||
if (currentSession?.authenticated) {
|
||||
panel.innerHTML = `<div class="profile-heading"><div class="profile-avatar" id="profile-avatar" aria-hidden="true">V</div><div>${tr("profileTitle", "h2")}<p id="profile-name"></p></div></div>${tr("profileIntro", "p")}<dl class="profile-fields"><div><dt>${tr("handle")}</dt><dd id="profile-handle"></dd></div><div><dt>${tr("userId")}</dt><dd id="profile-id"></dd></div></dl><div class="profile-actions"><button class="button secondary" id="copy-id">${icon("copy", 17)}${tr("copy")}</button><button class="button quiet" id="logout" ${logoutState === "pending" ? "disabled" : ""}>${tr(logoutState === "pending" ? "loggingOut" : "logout")}</button></div><p class="form-message" id="profile-message" role="status"></p>`;
|
||||
panel.innerHTML = `<div class="profile-heading"><div class="profile-avatar" id="profile-avatar" aria-hidden="true">V</div><div>${tr("profileTitle", "h2")}<p id="profile-name"></p></div></div>${tr("profileIntro", "p")}<dl class="profile-fields"><div><dt>${tr("handle")}</dt><dd id="profile-handle"></dd></div><div><dt>${tr("userId")}</dt><dd id="profile-id"></dd></div></dl>${avatarBlock()}<div class="profile-actions"><button class="button secondary" id="copy-id">${icon("copy", 17)}${tr("copy")}</button><button class="button quiet" id="logout" ${logoutState === "pending" ? "disabled" : ""}>${tr(logoutState === "pending" ? "loggingOut" : "logout")}</button></div><p class="form-message" id="profile-message" role="status"></p>`;
|
||||
const user = currentSession.user;
|
||||
find("#profile-name", panel).textContent =
|
||||
user.display_name || t("profileFallback");
|
||||
|
|
@ -237,6 +257,7 @@ function renderAccount() {
|
|||
find("#profile-message", panel).textContent = t("copyError");
|
||||
}
|
||||
});
|
||||
setupAvatar(panel, user.avatar_url);
|
||||
find("#logout", panel).addEventListener("click", logout);
|
||||
if (logoutState === "error")
|
||||
find("#profile-message", panel).textContent = t("logoutError");
|
||||
|
|
@ -254,6 +275,259 @@ function renderAccount() {
|
|||
find("#retry-info", panel).addEventListener("click", refresh);
|
||||
renderEmail();
|
||||
}
|
||||
function avatarBlock(): string {
|
||||
return `<div class="avatar-block">${tr("avatarTitle", "h3")}${tr("avatarHint", "p", 'class="small"')}<div class="avatar-actions"><button class="button secondary" id="avatar-pick" type="button">${tr("avatarUpload")}</button><button class="button quiet" id="avatar-remove" type="button" hidden>${tr("avatarRemove")}</button></div><input id="avatar-file" type="file" accept="image/png,image/jpeg,image/webp" hidden><p class="form-message" id="avatar-message" role="status"></p><div id="avatar-editor"></div></div>`;
|
||||
}
|
||||
function avatarFailure(error: unknown): MessageKey {
|
||||
if (error instanceof ApiError) {
|
||||
if (error.detail === "too_large") return "avatarTooBig";
|
||||
if (error.detail === "unsupported_type" || error.detail === "type_mismatch")
|
||||
return "avatarBadType";
|
||||
if (error.detail === "bad_dimensions" || error.detail === "invalid_image")
|
||||
return "avatarBadImage";
|
||||
if (error.status === 429) return "avatarLimit";
|
||||
}
|
||||
return "avatarFailed";
|
||||
}
|
||||
function closeAvatarEditor() {
|
||||
avatarCrop?.bitmap.close();
|
||||
avatarCrop = null;
|
||||
}
|
||||
function setupAvatar(panel: Element, avatarUrl: string | null | undefined) {
|
||||
const pick = find<HTMLButtonElement>("#avatar-pick", panel);
|
||||
const remove = find<HTMLButtonElement>("#avatar-remove", panel);
|
||||
const input = find<HTMLInputElement>("#avatar-file", panel);
|
||||
const message = find("#avatar-message", panel);
|
||||
const busy = avatarBusy !== "idle";
|
||||
pick.disabled = busy;
|
||||
remove.hidden = !isOwnAvatar(avatarUrl);
|
||||
remove.disabled = busy;
|
||||
if (avatarBusy === "removing") remove.textContent = t("avatarRemoving");
|
||||
if (avatarMessage) message.textContent = t(avatarMessage);
|
||||
pick.addEventListener("click", () => input.click());
|
||||
input.addEventListener("change", async () => {
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
if (!file) return;
|
||||
avatarMessage = null;
|
||||
if (!["image/png", "image/jpeg", "image/webp"].includes(file.type))
|
||||
avatarMessage = "avatarBadType";
|
||||
else if (file.size > AVATAR_MAX_FILE) avatarMessage = "avatarTooBig";
|
||||
else {
|
||||
try {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
if (
|
||||
bitmap.width > AVATAR_MAX_SIDE ||
|
||||
bitmap.height > AVATAR_MAX_SIDE ||
|
||||
bitmap.width < 32 ||
|
||||
bitmap.height < 32
|
||||
) {
|
||||
bitmap.close();
|
||||
avatarMessage = "avatarBadImage";
|
||||
} else {
|
||||
closeAvatarEditor();
|
||||
avatarCrop = {
|
||||
bitmap,
|
||||
state: initialCrop(bitmap.width, bitmap.height),
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
avatarMessage = "avatarBadImage";
|
||||
}
|
||||
}
|
||||
renderAccount();
|
||||
if (avatarCrop)
|
||||
document.querySelector<HTMLElement>("#avatar-canvas")?.focus();
|
||||
});
|
||||
remove.addEventListener("click", removeOwnAvatar);
|
||||
if (avatarCrop) renderAvatarEditor(find("#avatar-editor", panel));
|
||||
}
|
||||
function renderAvatarEditor(host: Element) {
|
||||
const crop = avatarCrop;
|
||||
if (!crop) return;
|
||||
const saving = avatarBusy === "saving";
|
||||
host.innerHTML = `<div class="avatar-editor" role="group" aria-labelledby="avatar-editor-title">${tr("avatarEditorTitle", "h4").replace("<h4", '<h4 id="avatar-editor-title"')}<canvas id="avatar-canvas" class="avatar-canvas" width="${AVATAR_VIEW}" height="${AVATAR_VIEW}" tabindex="0" aria-label="${t("avatarCropLabel")}" aria-describedby="avatar-crop-help"></canvas>${tr("avatarCropHelp", "p", 'id="avatar-crop-help" class="small"')}<label class="avatar-zoom" for="avatar-zoom">${tr("avatarZoom", "span")}<input id="avatar-zoom" type="range" min="100" max="${MAX_ZOOM * 100}" step="5"></label><div class="avatar-actions"><button class="button primary" id="avatar-save" type="button">${tr(saving ? "avatarSaving" : "avatarSave")}</button><button class="button secondary" id="avatar-reset" type="button">${tr("avatarReset")}</button><button class="button quiet" id="avatar-cancel" type="button">${tr("avatarCancel")}</button></div></div>`;
|
||||
const canvas = find<HTMLCanvasElement>("#avatar-canvas", host);
|
||||
const zoom = find<HTMLInputElement>("#avatar-zoom", host);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return;
|
||||
const draw = () => {
|
||||
const { sx, sy, side } = sourceRect(crop.state);
|
||||
context.clearRect(0, 0, AVATAR_VIEW, AVATAR_VIEW);
|
||||
context.imageSmoothingQuality = "high";
|
||||
context.drawImage(
|
||||
crop.bitmap,
|
||||
sx,
|
||||
sy,
|
||||
side,
|
||||
side,
|
||||
0,
|
||||
0,
|
||||
AVATAR_VIEW,
|
||||
AVATAR_VIEW,
|
||||
);
|
||||
zoom.value = String(Math.round(crop.state.zoom * 100));
|
||||
};
|
||||
const set = (state: CropState) => {
|
||||
crop.state = state;
|
||||
draw();
|
||||
};
|
||||
draw();
|
||||
for (const control of host.querySelectorAll<HTMLButtonElement>("button"))
|
||||
control.disabled = saving;
|
||||
canvas.classList.toggle("disabled", saving);
|
||||
zoom.disabled = saving;
|
||||
let last: { x: number; y: number } | null = null;
|
||||
canvas.addEventListener("pointerdown", (event) => {
|
||||
if (saving) return;
|
||||
last = { x: event.clientX, y: event.clientY };
|
||||
canvas.setPointerCapture(event.pointerId);
|
||||
canvas.classList.add("dragging");
|
||||
});
|
||||
canvas.addEventListener("pointermove", (event) => {
|
||||
if (!last) return;
|
||||
const width = canvas.getBoundingClientRect().width || AVATAR_VIEW;
|
||||
set(
|
||||
panBy(crop.state, event.clientX - last.x, event.clientY - last.y, width),
|
||||
);
|
||||
last = { x: event.clientX, y: event.clientY };
|
||||
});
|
||||
const release = () => {
|
||||
last = null;
|
||||
canvas.classList.remove("dragging");
|
||||
};
|
||||
canvas.addEventListener("pointerup", release);
|
||||
canvas.addEventListener("pointercancel", release);
|
||||
canvas.addEventListener(
|
||||
"wheel",
|
||||
(event) => {
|
||||
event.preventDefault();
|
||||
if (saving) return;
|
||||
set(zoomTo(crop.state, crop.state.zoom - event.deltaY * 0.002));
|
||||
},
|
||||
{ passive: false },
|
||||
);
|
||||
canvas.addEventListener("keydown", (event) => {
|
||||
if (saving) return;
|
||||
const step = event.shiftKey ? 40 : 10;
|
||||
const moves: Record<string, [number, number]> = {
|
||||
ArrowLeft: [step, 0],
|
||||
ArrowRight: [-step, 0],
|
||||
ArrowUp: [0, step],
|
||||
ArrowDown: [0, -step],
|
||||
};
|
||||
const move = moves[event.key];
|
||||
if (move) set(panBy(crop.state, move[0], move[1], AVATAR_VIEW));
|
||||
else if (event.key === "+" || event.key === "=")
|
||||
set(zoomTo(crop.state, crop.state.zoom + 0.1));
|
||||
else if (event.key === "-" || event.key === "_")
|
||||
set(zoomTo(crop.state, crop.state.zoom - 0.1));
|
||||
else if (event.key === "Escape") {
|
||||
closeAvatarEditor();
|
||||
renderAccount();
|
||||
document.querySelector<HTMLElement>("#avatar-pick")?.focus();
|
||||
} else return;
|
||||
event.preventDefault();
|
||||
});
|
||||
zoom.addEventListener("input", () =>
|
||||
set(zoomTo(crop.state, Number(zoom.value) / 100)),
|
||||
);
|
||||
find("#avatar-reset", host).addEventListener("click", () =>
|
||||
set(initialCrop(crop.state.width, crop.state.height)),
|
||||
);
|
||||
find("#avatar-cancel", host).addEventListener("click", () => {
|
||||
closeAvatarEditor();
|
||||
avatarMessage = null;
|
||||
renderAccount();
|
||||
document.querySelector<HTMLElement>("#avatar-pick")?.focus();
|
||||
});
|
||||
find("#avatar-save", host).addEventListener("click", saveAvatar);
|
||||
}
|
||||
function cropToPng(crop: { bitmap: ImageBitmap; state: CropState }) {
|
||||
const out = document.createElement("canvas");
|
||||
out.width = OUTPUT_SIDE;
|
||||
out.height = OUTPUT_SIDE;
|
||||
const context = out.getContext("2d");
|
||||
if (!context) return Promise.resolve(null);
|
||||
const { sx, sy, side } = sourceRect(clampCrop(crop.state));
|
||||
context.imageSmoothingQuality = "high";
|
||||
context.drawImage(
|
||||
crop.bitmap,
|
||||
sx,
|
||||
sy,
|
||||
side,
|
||||
side,
|
||||
0,
|
||||
0,
|
||||
OUTPUT_SIDE,
|
||||
OUTPUT_SIDE,
|
||||
);
|
||||
return new Promise<Blob | null>((resolve) =>
|
||||
out.toBlob(resolve, "image/png"),
|
||||
);
|
||||
}
|
||||
function applyAvatarSession(url: string | null) {
|
||||
if (currentSession?.authenticated)
|
||||
currentSession = {
|
||||
...currentSession,
|
||||
user: { ...currentSession.user, avatar_url: url },
|
||||
};
|
||||
}
|
||||
/** A rejected request with 401 means the session ended: show the sign-in view. */
|
||||
function sessionEnded(error: unknown): boolean {
|
||||
if (!(error instanceof ApiError) || error.status !== 401) return false;
|
||||
currentSession = { authenticated: false };
|
||||
closeAvatarEditor();
|
||||
avatarBusy = "idle";
|
||||
avatarMessage = null;
|
||||
renderAccount();
|
||||
return true;
|
||||
}
|
||||
async function saveAvatar() {
|
||||
if (!currentSession?.authenticated || !avatarCrop || avatarBusy !== "idle")
|
||||
return;
|
||||
const csrf = currentSession.csrf_token;
|
||||
avatarBusy = "saving";
|
||||
avatarMessage = null;
|
||||
renderAccount();
|
||||
try {
|
||||
const blob = await cropToPng(avatarCrop);
|
||||
if (!blob) throw new Error("export_failed");
|
||||
const url = await uploadAvatar(blob, csrf, {
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
applyAvatarSession(url);
|
||||
closeAvatarEditor();
|
||||
avatarMessage = "avatarSaved";
|
||||
} catch (error) {
|
||||
if (sessionEnded(error)) return;
|
||||
avatarMessage = avatarFailure(error);
|
||||
}
|
||||
avatarBusy = "idle";
|
||||
renderAccount();
|
||||
document
|
||||
.querySelector<HTMLElement>(avatarCrop ? "#avatar-save" : "#avatar-pick")
|
||||
?.focus();
|
||||
}
|
||||
async function removeOwnAvatar() {
|
||||
if (!currentSession?.authenticated || avatarBusy !== "idle") return;
|
||||
const csrf = currentSession.csrf_token;
|
||||
avatarBusy = "removing";
|
||||
avatarMessage = null;
|
||||
renderAccount();
|
||||
try {
|
||||
applyAvatarSession(
|
||||
await removeAvatar(csrf, { signal: AbortSignal.timeout(15000) }),
|
||||
);
|
||||
avatarMessage = "avatarRemoved";
|
||||
} catch (error) {
|
||||
if (sessionEnded(error)) return;
|
||||
avatarMessage = avatarFailure(error);
|
||||
}
|
||||
avatarBusy = "idle";
|
||||
renderAccount();
|
||||
document.querySelector<HTMLElement>("#avatar-pick")?.focus();
|
||||
}
|
||||
function stopResendTimer() {
|
||||
clearInterval(resendTimer);
|
||||
resendTimer = undefined;
|
||||
|
|
@ -422,6 +696,8 @@ async function logout() {
|
|||
});
|
||||
currentSession = { authenticated: false };
|
||||
logoutState = "idle";
|
||||
closeAvatarEditor();
|
||||
avatarMessage = null;
|
||||
renderAccount();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue