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
848 lines
39 KiB
TypeScript
848 lines
39 KiB
TypeScript
import type { Language, MessageKey } from "./i18n";
|
|
import type { Session } from "./api";
|
|
import { detectLanguage, translate } from "./i18n";
|
|
import {
|
|
request,
|
|
isSession,
|
|
isInfo,
|
|
safeAvatar,
|
|
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 {
|
|
savedLanguage = localStorage.getItem("vnox-web-language");
|
|
} catch {
|
|
/* Storage is optional. */
|
|
}
|
|
let language = detectLanguage(
|
|
savedLanguage,
|
|
navigator.languages ?? [navigator.language],
|
|
);
|
|
const accountPage = /^\/account\/?$/.test(location.pathname);
|
|
const privacyPage = /^\/privacy\/?$/.test(location.pathname);
|
|
function find<T extends Element = HTMLElement>(
|
|
selector: string,
|
|
root: ParentNode = document,
|
|
): T {
|
|
const element = root.querySelector<T>(selector);
|
|
if (!element) throw new Error(`Missing required element: ${selector}`);
|
|
return element;
|
|
}
|
|
const main = find("main");
|
|
type Tab = "text" | "voice" | "theme";
|
|
type Theme = "light" | "dark" | "black" | "custom";
|
|
let activeTab: Tab = "text";
|
|
let activeTheme: Theme = "dark";
|
|
let controller: AbortController | undefined;
|
|
let currentSession: Session | null = null;
|
|
let githubEnabled = false;
|
|
let emailEnabled = false;
|
|
// Email sign-in form state. Kept outside the DOM so a language switch or a
|
|
// re-render does not lose what was typed.
|
|
let emailStep: "address" | "code" = "address";
|
|
let emailAddress = "";
|
|
let emailCode = "";
|
|
let emailBusy: "idle" | "sending" | "verifying" = "idle";
|
|
let emailMessage: MessageKey | null = null;
|
|
let emailField: "address" | "code" | null = null;
|
|
let resendUntil = 0;
|
|
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:
|
|
| "github"
|
|
| "voice"
|
|
| "mic"
|
|
| "chat"
|
|
| "external"
|
|
| "check"
|
|
| "copy"
|
|
| "back",
|
|
size = 20,
|
|
) => {
|
|
const paths = {
|
|
github:
|
|
'<path d="M9 19c-4 1-4-2-6-2m12 4v-3.4a3 3 0 0 0-.8-2.3c2.7-.3 5.5-1.3 5.5-6A4.7 4.7 0 0 0 18.4 6a4.4 4.4 0 0 0-.1-3.3s-1-.3-3.4 1.3a11.6 11.6 0 0 0-6.2 0C6.3 2.4 5.3 2.7 5.3 2.7A4.4 4.4 0 0 0 5.2 6 4.7 4.7 0 0 0 4 9.3c0 4.7 2.8 5.7 5.5 6a3 3 0 0 0-.8 2.3V21"/>',
|
|
voice:
|
|
'<path d="m11 5-5 4H3v6h3l5 4V5Z"/><path d="M15 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14"/>',
|
|
mic: '<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"/>',
|
|
chat: '<path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"/>',
|
|
external:
|
|
'<path d="M15 3h6v6m0-6L10 14"/><path d="M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5"/>',
|
|
check: '<path d="m5 12 4 4L19 6"/>',
|
|
copy: '<rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>',
|
|
back: '<path d="m12 19-7-7 7-7m-7 7h14"/>',
|
|
};
|
|
return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] ?? paths.chat}</svg>`;
|
|
};
|
|
const tr = (key: MessageKey, tag = "span", attrs = "") =>
|
|
`<${tag} data-i18n="${key}" ${attrs}>${t(key)}</${tag}>`;
|
|
const external = (href: string, key: MessageKey) =>
|
|
`<a class="text-link" href="${href}" target="_blank" rel="noopener noreferrer">${tr(key)}${icon("external", 15)}</a>`;
|
|
function landing() {
|
|
main.innerHTML = `
|
|
<section class="hero shell enter" aria-labelledby="hero-title">
|
|
<div class="hero-copy"><p class="development">${tr("development")}</p>${tr("heroTitle", "h1", 'id="hero-title"')}${tr("heroText", "p", 'class="hero-description"')}
|
|
<div class="hero-actions"><a class="button primary" href="/account">${tr("openCentral")}</a><a class="button quiet" href="#project">${tr("explore")}</a></div>${tr("earlyNote", "p", 'class="small hero-note"')}</div>
|
|
<div class="diagram-wrap"><div class="diagram-meta">${tr("diagramLabel")}<span class="diagram-dots" aria-hidden="true"><i></i><i></i><i></i></span></div>
|
|
<div class="product-diagram" data-preview-theme="dark"><div class="diagram-sidebar"><img src="/assets/vnox-mark.svg" alt="" width="32" height="32"><div class="diagram-community">${tr("community")}</div><div class="diagram-channel selected"># ${tr("general")}</div><div class="diagram-channel"># ${tr("ideas")}</div><div class="diagram-voice">${icon("voice", 16)}${tr("voiceRoom")}</div><div class="diagram-people"><span class="person-dot"></span>${tr("you")}<span class="person-dot second"></span>${tr("friend")}</div><div class="diagram-self"><span class="mini-avatar">V</span>${tr("you")}${icon("mic", 15)}</div></div>
|
|
<div class="diagram-main"><div class="diagram-header"># ${tr("general")}<span>${icon("chat", 17)}</span></div><div id="diagram-content"></div><div class="diagram-call"><span class="connection-dot"></span>${tr("voiceConnected")}${icon("mic", 16)}</div></div></div>
|
|
<div class="diagram-tabs" role="tablist" aria-label="${t("preview")}" data-i18n-aria="preview"><button role="tab" aria-selected="true" aria-controls="diagram-content" id="tab-text" data-tab="text">${tr("textTab")}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-voice" data-tab="voice" tabindex="-1">${tr("voiceTab")}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-theme" data-tab="theme" tabindex="-1">${tr("themeTab")}</button></div>${tr("diagramNote", "p", 'class="small diagram-note"')}
|
|
</div>
|
|
</section>
|
|
<section class="project-section shell reveal" id="project" aria-labelledby="project-title"><div class="section-intro">${tr("projectTitle", "h2", 'id="project-title"')}${tr("projectText", "p")}<div class="source-links">${external("https://git.wihuk.pro/boba/VNOX-Client", "clientCode")}${external("https://git.wihuk.pro/boba/VNOX-Server", "serverCode")}</div></div><div class="project-points"><article><div class="point-icon">${icon("chat", 24)}</div><div>${tr("projectNative", "h3")}${tr("projectNativeText", "p")}</div></article><article><div class="point-icon">${icon("voice", 24)}</div><div>${tr("projectServer", "h3")}${tr("projectServerText", "p")}</div></article><article><img src="/assets/vnox-mark.svg" alt="" width="40" height="40"><div>${tr("projectCentral", "h3")}${tr("projectCentralText", "p")}</div></article></div></section>
|
|
<section class="light-section shell reveal" id="light" aria-labelledby="light-title"><div class="light-intro">${tr("lightTitle", "h2", 'id="light-title"')}${tr("lightText", "p")}<div class="source-links"><a class="text-link" href="https://www.pcworld.com/article/3005317/discord-admits-windows-11-app-hogs-ram-tries-solving-it-with-auto-restarts.html" target="_blank" rel="noopener noreferrer">${tr("lightSource")}${icon("external", 15)}</a></div></div><div class="light-meters"><div class="meter vnox"><div class="meter-head">${tr("lightVnoxName")}<strong>${tr("lightAbout")} <span class="count" data-count="120">120</span> ${tr("lightUnit")}</strong></div><div class="meter-track" aria-hidden="true"><i data-w="9.1%"></i></div></div><div class="meter electron"><div class="meter-head">${tr("lightElectronName")}<strong>${tr("lightElectronValue")}</strong></div><div class="meter-track" aria-hidden="true"><i data-w="100%"></i></div></div>${tr("lightCaption", "p", 'class="small light-caption"')}</div></section>
|
|
<section class="client-section reveal" id="client" aria-labelledby="client-title"><div class="shell"><div class="client-heading">${tr("clientTitle", "h2", 'id="client-title"')}${tr("clientText", "p")}</div><figure class="client-image"><img src="/assets/client-settings.png" width="1280" height="800" alt="${t("clientScreenshot")}" data-i18n-alt="clientScreenshot" loading="lazy">${tr("screenshotCaption", "figcaption")}</figure><div class="client-details"><article>${tr("appearanceTitle", "h3")}${tr("appearanceText", "p")}</article><article>${tr("identityTitle", "h3")}${tr("identityText", "p")}</article></div></div></section>
|
|
<section class="roadmap shell reveal" id="roadmap" aria-labelledby="roadmap-title"><div class="roadmap-heading">${tr("roadmapTitle", "h2", 'id="roadmap-title"')}${tr("roadmapText", "p")}</div><div class="roadmap-columns"><article><h3><span class="connection-dot" aria-hidden="true"></span>${tr("available")}</h3><ul><li>${tr("availableOne")}</li><li>${tr("availableTwo")}</li><li>${tr("availableThree")}</li><li>${tr("availableFour")}</li><li>${tr("availableFive")}</li></ul></article><article><h3><span class="planned-dot" aria-hidden="true"></span>${tr("next")}</h3><ul><li>${tr("nextOne")}</li><li>${tr("nextTwo")}</li><li>${tr("nextThree")}</li></ul></article></div>${tr("downloadNote", "p", 'class="release-note"')}</section>
|
|
<section class="faq shell reveal" aria-labelledby="faq-title">${tr("faqTitle", "h2", 'id="faq-title"')}<div>${(["Server", "Central", "Release"] as const).map((key) => `<details><summary>${tr(`faq${key}`)}<span aria-hidden="true">+</span></summary>${tr(`faq${key}Answer`, "p")}</details>`).join("")}</div></section>
|
|
<section class="status-section shell reveal" aria-label="${t("statusNote")}" data-i18n-aria="statusNote"><div><span id="service-dot" class="status-dot"></span><p id="service-status" role="status">${t("statusLoading")}</p></div><a href="/account" class="text-link">${tr("openCentral")}${icon("external", 15)}</a></section>`;
|
|
main
|
|
.querySelectorAll<HTMLElement>("[data-w]")
|
|
.forEach((bar) => bar.style.setProperty("--w", bar.dataset.w ?? "0"));
|
|
renderDiagram();
|
|
initMotion();
|
|
main.querySelectorAll<HTMLElement>("[data-tab]").forEach((button) => {
|
|
button.addEventListener("click", () => {
|
|
activeTab = button.dataset.tab as Tab;
|
|
renderDiagram();
|
|
});
|
|
button.addEventListener("keydown", (event) => {
|
|
const tabs = [...main.querySelectorAll<HTMLElement>("[data-tab]")];
|
|
let index = tabs.indexOf(button);
|
|
if (event.key === "ArrowRight") index = (index + 1) % tabs.length;
|
|
else if (event.key === "ArrowLeft")
|
|
index = (index + tabs.length - 1) % tabs.length;
|
|
else if (event.key === "Home") index = 0;
|
|
else if (event.key === "End") index = tabs.length - 1;
|
|
else return;
|
|
event.preventDefault();
|
|
activeTab = tabs[index]!.dataset.tab as Tab;
|
|
renderDiagram();
|
|
tabs[index]!.focus();
|
|
});
|
|
});
|
|
}
|
|
/** Scroll reveal and the memory counter. Skipped when motion is reduced. */
|
|
function initMotion() {
|
|
const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
if (reduced || !("IntersectionObserver" in window)) return;
|
|
const targets = main.querySelectorAll<HTMLElement>(".reveal");
|
|
const counters = main.querySelectorAll<HTMLElement>("[data-count]");
|
|
document.documentElement.classList.add("motion");
|
|
counters.forEach((counter) => (counter.textContent = "0"));
|
|
const count = (counter: HTMLElement) => {
|
|
const goal = Number(counter.dataset.count);
|
|
const start = performance.now();
|
|
const step = (now: number) => {
|
|
const progress = Math.min((now - start) / 1400, 1);
|
|
counter.textContent = String(
|
|
Math.round(goal * (1 - Math.pow(1 - progress, 3))),
|
|
);
|
|
if (progress < 1) requestAnimationFrame(step);
|
|
};
|
|
requestAnimationFrame(step);
|
|
};
|
|
const observer = new IntersectionObserver(
|
|
(entries) => {
|
|
for (const entry of entries) {
|
|
if (!entry.isIntersecting) continue;
|
|
entry.target.classList.add("in");
|
|
entry.target
|
|
.querySelectorAll<HTMLElement>("[data-count]")
|
|
.forEach(count);
|
|
observer.unobserve(entry.target);
|
|
}
|
|
},
|
|
{ threshold: 0.2 },
|
|
);
|
|
targets.forEach((target) => observer.observe(target));
|
|
}
|
|
function renderDiagram() {
|
|
const content = document.querySelector("#diagram-content");
|
|
if (!content) return;
|
|
main.querySelectorAll<HTMLElement>("[data-tab]").forEach((button) => {
|
|
const active = button.dataset.tab === activeTab;
|
|
button.setAttribute("aria-selected", String(active));
|
|
button.tabIndex = active ? 0 : -1;
|
|
});
|
|
content.setAttribute("role", "tabpanel");
|
|
content.setAttribute("aria-labelledby", `tab-${activeTab}`);
|
|
if (activeTab === "text")
|
|
content.innerHTML = `<div class="illustration-chat"><div class="message-heading"><span class="chat-avatar">V</span><div>${tr("community", "strong")}<div class="message-lines" aria-hidden="true"><i></i><i></i></div></div></div>${tr("messageSample", "p")}<div class="illustration-composer" aria-hidden="true"><span>+</span><i></i>${icon("chat", 15)}</div>${tr("messageNote", "p", 'class="diagram-caption"')}</div>`;
|
|
if (activeTab === "voice")
|
|
content.innerHTML = `<div class="illustration-voice"><div class="voice-orbit"><span class="voice-avatar">V</span><div class="waveform" aria-hidden="true">${Array.from({ length: 11 }, () => "<i></i>").join("")}</div><span class="voice-avatar friend-avatar">${icon("voice", 30)}</span></div>${tr("voiceExplain", "p")}<div class="voice-controls" aria-hidden="true"><span>${icon("mic")}</span><span>${icon("voice")}</span></div>${tr("voiceCaption", "p", 'class="diagram-caption"')}</div>`;
|
|
if (activeTab === "theme") {
|
|
content.innerHTML = `<div class="illustration-themes">${tr("themeCaption", "h3")}<div class="theme-options" role="group" aria-label="${t("previewTheme")}" data-i18n-aria="previewTheme">${(["light", "dark", "black", "custom"] as const).map((theme) => `<button class="theme-option ${theme}" data-theme="${theme}" aria-pressed="${activeTheme === theme}"><span class="theme-sample" aria-hidden="true"><i></i><i></i><i></i></span>${tr(theme)}</button>`).join("")}</div></div>`;
|
|
content.querySelectorAll<HTMLElement>("[data-theme]").forEach((button) =>
|
|
button.addEventListener("click", () => {
|
|
activeTheme = button.dataset.theme as Theme;
|
|
find(".product-diagram").dataset.previewTheme = activeTheme;
|
|
content
|
|
.querySelectorAll<HTMLElement>("[data-theme]")
|
|
.forEach((item) =>
|
|
item.setAttribute("aria-pressed", String(item === button)),
|
|
);
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
function privacy() {
|
|
const sections = ["Collect", "Cookies", "Track", "Other", "Delete"] as const;
|
|
main.innerHTML = `<section class="privacy-section shell"><a href="/" class="text-link back-link">${icon("back", 17)}${tr("back")}</a>${tr("privacyTitle", "h1")}${tr("privacyUpdated", "p", 'class="small"')}${tr("privacyIntro", "p")}${sections.map((key) => `<div class="privacy-block">${tr(`privacy${key}Title` as MessageKey, "h2")}${tr(`privacy${key}Text` as MessageKey, "p")}</div>`).join("")}</section>`;
|
|
}
|
|
function account() {
|
|
main.innerHTML = `<section class="account-section shell"><a href="/" class="text-link back-link">${icon("back", 17)}${tr("back")}</a><div class="account-layout"><div class="account-intro"><img class="account-mark" src="/assets/vnox-mark.svg" alt="" width="76" height="76">${tr("accountHeading", "h1")}${tr("accountIntro", "p")}<div class="account-explanation">${tr("accountStage", "p")}</div></div><div id="account-content" class="account-panel" aria-live="polite"></div></div></section>`;
|
|
renderAccount();
|
|
}
|
|
function renderAccount() {
|
|
const panel = document.querySelector("#account-content");
|
|
if (!panel) return;
|
|
panel.replaceChildren();
|
|
if (sessionState === "loading") {
|
|
panel.innerHTML = `<div class="account-loading"><span class="loading-ring" aria-hidden="true"></span>${tr("sessionLoading", "p")}</div>`;
|
|
return;
|
|
}
|
|
if (sessionState === "error") {
|
|
panel.innerHTML = `${tr("accountError", "h2")}${tr("accountErrorText", "p")}<button class="button primary" id="retry-session">${tr("retry")}</button>`;
|
|
find("#retry-session", panel).addEventListener("click", refresh);
|
|
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>${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");
|
|
find("#profile-handle", panel).textContent = user.handle;
|
|
find("#profile-id", panel).textContent = user.user_id;
|
|
const avatar = safeAvatar(user.avatar_url);
|
|
if (avatar) {
|
|
const image = document.createElement("img");
|
|
image.src = avatar;
|
|
image.alt = "";
|
|
image.referrerPolicy = "no-referrer";
|
|
image.addEventListener("error", () => image.remove(), { once: true });
|
|
find("#profile-avatar", panel).append(image);
|
|
}
|
|
find("#copy-id", panel).addEventListener("click", async () => {
|
|
try {
|
|
await navigator.clipboard.writeText(user.user_id);
|
|
find("#profile-message", panel).textContent = t("copied");
|
|
} catch {
|
|
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");
|
|
return;
|
|
}
|
|
panel.innerHTML = `<div class="login-provider">${icon("github", 33)}</div>${tr("loginTitle", "h2")}${tr("loginText", "p")}<a class="button primary github-login ${githubEnabled ? "" : "unavailable"}" ${githubEnabled ? 'href="/v1/auth/github/start"' : 'aria-disabled="true" tabindex="-1"'}>${icon("github", 21)}${tr("loginButton")}</a><p id="login-availability" class="form-message" role="status"></p><button class="text-button" id="retry-info" ${infoState === "error" ? "" : "hidden"}>${tr("retry")}</button><div id="email-area"></div><div class="privacy-note">${icon("check", 16)}${tr("privacy", "p")}</div>`;
|
|
find("#login-availability", panel).textContent =
|
|
infoState === "loading"
|
|
? t("loginLoading")
|
|
: infoState === "error"
|
|
? t("loginUnavailable")
|
|
: githubEnabled
|
|
? ""
|
|
: t("loginDisabled");
|
|
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;
|
|
}
|
|
function tickResend() {
|
|
const button = document.querySelector<HTMLButtonElement>("#resend");
|
|
if (!button) return stopResendTimer();
|
|
const left = Math.max(0, Math.ceil((resendUntil - Date.now()) / 1000));
|
|
button.disabled = left > 0 || emailBusy !== "idle";
|
|
button.textContent =
|
|
left > 0
|
|
? t("emailResendIn").replace("{seconds}", String(left))
|
|
: t("emailResend");
|
|
if (left === 0) stopResendTimer();
|
|
}
|
|
const looksLikeEmail = (value: string) =>
|
|
value.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
|
|
function emailFailure(error: unknown, rejected: MessageKey): MessageKey {
|
|
if (error instanceof ApiError) {
|
|
if (error.status === 400) return rejected;
|
|
if (error.status === 429) return "emailTooMany";
|
|
}
|
|
return "emailFailed";
|
|
}
|
|
/** Draws the email form into #email-area. Hidden unless Hub reports email_auth: enabled. */
|
|
function renderEmail() {
|
|
const area = document.querySelector("#email-area");
|
|
if (!area) return;
|
|
stopResendTimer();
|
|
area.replaceChildren();
|
|
if (!emailEnabled) return;
|
|
const busy = emailBusy !== "idle";
|
|
const invalid = emailMessage !== null && emailField !== null;
|
|
const describedBy = 'aria-describedby="email-message"';
|
|
const aria = (field: "address" | "code") =>
|
|
invalid && emailField === field ? 'aria-invalid="true"' : "";
|
|
const stepHtml =
|
|
emailStep === "address"
|
|
? `<label for="email-input">${tr("emailLabel")}</label><input id="email-input" class="field" type="email" name="email" autocomplete="email" inputmode="email" autocapitalize="none" spellcheck="false" maxlength="254" required ${describedBy} ${aria("address")}><button class="button secondary" type="submit" id="email-submit" ${busy ? "disabled" : ""}>${t(emailBusy === "sending" ? "emailSending" : "emailSend")}</button>`
|
|
: `<p id="email-sent"></p><label for="code-input">${tr("codeLabel")}</label><input id="code-input" class="field code-field" type="text" name="code" inputmode="numeric" pattern="[0-9]*" autocomplete="one-time-code" autocapitalize="none" spellcheck="false" maxlength="8" required ${describedBy} ${aria("code")}><button class="button secondary" type="submit" id="email-submit" ${busy ? "disabled" : ""}>${t(emailBusy === "verifying" ? "codeVerifying" : "codeVerify")}</button><div class="email-actions"><button class="text-button" type="button" id="resend"></button><button class="text-button" type="button" id="change-email" ${busy ? "disabled" : ""}>${tr("emailChange")}</button></div>`;
|
|
area.innerHTML = `<div class="login-divider" role="separator"><span>${tr("emailOr")}</span></div><form class="email-form" id="email-form" novalidate aria-busy="${busy}">${tr("emailTitle", "h3")}${emailStep === "address" ? tr("emailText", "p", 'class="email-text"') : ""}${stepHtml}<p class="form-message" id="email-message" role="status" aria-live="polite"></p></form>`;
|
|
const form = find<HTMLFormElement>("#email-form", area);
|
|
find("#email-message", area).textContent = emailMessage
|
|
? t(emailMessage)
|
|
: "";
|
|
if (emailStep === "address") {
|
|
const input = find<HTMLInputElement>("#email-input", area);
|
|
input.value = emailAddress;
|
|
input.addEventListener("input", () => (emailAddress = input.value));
|
|
} else {
|
|
find("#email-sent", area).textContent = t("emailCodeSent").replace(
|
|
"{address}",
|
|
emailAddress.trim().toLowerCase(),
|
|
);
|
|
const input = find<HTMLInputElement>("#code-input", area);
|
|
input.value = emailCode;
|
|
input.addEventListener("input", () => {
|
|
input.value = input.value.replace(/\D/g, "").slice(0, 8);
|
|
emailCode = input.value;
|
|
});
|
|
find("#resend", area).addEventListener("click", () => submitEmail(true));
|
|
find("#change-email", area).addEventListener("click", () => {
|
|
emailStep = "address";
|
|
emailCode = "";
|
|
emailMessage = null;
|
|
emailField = null;
|
|
resendUntil = 0;
|
|
renderEmail();
|
|
find<HTMLInputElement>("#email-input").focus();
|
|
});
|
|
tickResend();
|
|
if (resendUntil > Date.now()) resendTimer = setInterval(tickResend, 1000);
|
|
}
|
|
form.addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
if (emailBusy === "idle")
|
|
void (emailStep === "address" ? submitEmail(false) : submitCode());
|
|
});
|
|
}
|
|
function focusEmailField() {
|
|
document
|
|
.querySelector<HTMLInputElement>(
|
|
emailStep === "address" ? "#email-input" : "#code-input",
|
|
)
|
|
?.focus();
|
|
}
|
|
async function submitEmail(resend: boolean) {
|
|
if (emailBusy !== "idle") return;
|
|
const address = emailAddress.trim();
|
|
if (!looksLikeEmail(address)) {
|
|
emailMessage = "emailInvalid";
|
|
emailField = "address";
|
|
renderEmail();
|
|
focusEmailField();
|
|
return;
|
|
}
|
|
emailAddress = address;
|
|
emailBusy = "sending";
|
|
emailMessage = null;
|
|
emailField = null;
|
|
renderEmail();
|
|
try {
|
|
const result = await requestEmailCode(address, language, {
|
|
signal: AbortSignal.timeout(30000),
|
|
});
|
|
emailStep = "code";
|
|
emailCode = "";
|
|
resendUntil = Date.now() + result.resendAfter * 1000;
|
|
emailMessage = resend ? "emailResent" : null;
|
|
emailField = null;
|
|
emailBusy = "idle";
|
|
renderEmail();
|
|
focusEmailField();
|
|
} catch (error) {
|
|
emailBusy = "idle";
|
|
emailMessage = emailFailure(error, "emailInvalid");
|
|
emailField = emailMessage === "emailInvalid" ? "address" : null;
|
|
// A failed resend keeps the code step; the old code stays usable until it expires.
|
|
renderEmail();
|
|
if (emailStep === "address") focusEmailField();
|
|
}
|
|
}
|
|
async function submitCode() {
|
|
if (emailBusy !== "idle") return;
|
|
if (!/^[0-9]{8}$/.test(emailCode)) {
|
|
emailMessage = "emailCodeShape";
|
|
emailField = "code";
|
|
renderEmail();
|
|
focusEmailField();
|
|
return;
|
|
}
|
|
emailBusy = "verifying";
|
|
emailMessage = null;
|
|
emailField = null;
|
|
renderEmail();
|
|
try {
|
|
currentSession = await verifyEmailCode(emailAddress, emailCode, {
|
|
signal: AbortSignal.timeout(30000),
|
|
});
|
|
emailStep = "address";
|
|
emailAddress = "";
|
|
emailCode = "";
|
|
emailBusy = "idle";
|
|
emailMessage = null;
|
|
logoutState = "idle";
|
|
renderAccount();
|
|
} catch (error) {
|
|
emailBusy = "idle";
|
|
emailCode = "";
|
|
emailMessage = emailFailure(error, "emailInvalidCode");
|
|
emailField = emailMessage === "emailInvalidCode" ? "code" : null;
|
|
renderEmail();
|
|
focusEmailField();
|
|
}
|
|
}
|
|
async function logout() {
|
|
if (!currentSession?.authenticated || logoutState === "pending") return;
|
|
const csrf = currentSession.csrf_token;
|
|
logoutState = "pending";
|
|
renderAccount();
|
|
try {
|
|
await request("/v1/auth/logout", {
|
|
method: "POST",
|
|
csrf,
|
|
signal: AbortSignal.timeout(15000),
|
|
});
|
|
currentSession = { authenticated: false };
|
|
logoutState = "idle";
|
|
closeAvatarEditor();
|
|
avatarMessage = null;
|
|
renderAccount();
|
|
} catch (error) {
|
|
if (error instanceof ApiError && error.status === 401) {
|
|
currentSession = { authenticated: false };
|
|
logoutState = "idle";
|
|
renderAccount();
|
|
} else {
|
|
logoutState = "error";
|
|
renderAccount();
|
|
}
|
|
}
|
|
}
|
|
function updateStatus() {
|
|
const status = document.querySelector("#service-status");
|
|
if (status) {
|
|
status.textContent = t(
|
|
infoState === "loading"
|
|
? "statusLoading"
|
|
: infoState === "ready"
|
|
? "statusReady"
|
|
: "statusUnavailable",
|
|
);
|
|
find("#service-dot").dataset.state = infoState;
|
|
}
|
|
}
|
|
async function refresh() {
|
|
controller?.abort();
|
|
controller = new AbortController();
|
|
const currentController = controller;
|
|
const signal = AbortSignal.any([
|
|
currentController.signal,
|
|
AbortSignal.timeout(15000),
|
|
]);
|
|
infoState = "loading";
|
|
if (accountPage) {
|
|
sessionState = "loading";
|
|
renderAccount();
|
|
} else updateStatus();
|
|
const info = request("/v1/info", { signal })
|
|
.then((value) => {
|
|
if (controller !== currentController) return;
|
|
if (!isInfo(value)) throw new Error("invalid_info");
|
|
githubEnabled = value.capabilities.github_auth === "enabled";
|
|
emailEnabled = value.capabilities.email_auth === "enabled";
|
|
infoState = "ready";
|
|
})
|
|
.catch(() => {
|
|
if (!currentController.signal.aborted) {
|
|
githubEnabled = false;
|
|
emailEnabled = false;
|
|
infoState = "error";
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (controller === currentController) {
|
|
updateStatus();
|
|
if (accountPage) renderAccount();
|
|
}
|
|
});
|
|
if (accountPage) {
|
|
await Promise.allSettled([
|
|
info,
|
|
request("/v1/auth/session", { signal })
|
|
.then((value) => {
|
|
if (controller !== currentController) return;
|
|
if (!isSession(value)) throw new Error("invalid_session");
|
|
currentSession = value;
|
|
sessionState = "ready";
|
|
})
|
|
.catch(() => {
|
|
if (!currentController.signal.aborted) sessionState = "error";
|
|
})
|
|
.finally(() => {
|
|
if (controller === currentController) renderAccount();
|
|
}),
|
|
]);
|
|
} else await info;
|
|
}
|
|
function setLanguage(next: Language) {
|
|
language = next;
|
|
try {
|
|
localStorage.setItem("vnox-web-language", next);
|
|
} catch {
|
|
/* No authentication data is persisted. */
|
|
}
|
|
document.documentElement.lang = next;
|
|
const pageTitle = t(
|
|
privacyPage ? "privacyTitle" : accountPage ? "accountTitle" : "title",
|
|
);
|
|
document.title = pageTitle;
|
|
find<HTMLMetaElement>('meta[name="description"]').content = t("description");
|
|
find<HTMLMetaElement>('meta[property="og:title"]').content = pageTitle;
|
|
find<HTMLMetaElement>('meta[property="og:description"]').content =
|
|
t("description");
|
|
find<HTMLMetaElement>('meta[property="og:locale"]').content =
|
|
next === "ru" ? "ru_RU" : "en_US";
|
|
find<HTMLMetaElement>('meta[property="og:locale:alternate"]').content =
|
|
next === "ru" ? "en_US" : "ru_RU";
|
|
document
|
|
.querySelectorAll<HTMLElement>("[data-i18n]")
|
|
.forEach(
|
|
(element) =>
|
|
(element.textContent = t(element.dataset.i18n as MessageKey)),
|
|
);
|
|
for (const [attribute, dataKey] of [
|
|
["aria-label", "i18nAria"],
|
|
["alt", "i18nAlt"],
|
|
] as const)
|
|
document
|
|
.querySelectorAll<HTMLElement>(
|
|
`[data-${attribute === "alt" ? "i18n-alt" : "i18n-aria"}]`,
|
|
)
|
|
.forEach((element) =>
|
|
element.setAttribute(
|
|
attribute,
|
|
t(element.dataset[dataKey] as MessageKey),
|
|
),
|
|
);
|
|
document
|
|
.querySelectorAll<HTMLElement>("[data-language]")
|
|
.forEach((button) =>
|
|
button.setAttribute(
|
|
"aria-pressed",
|
|
String(button.dataset.language === next),
|
|
),
|
|
);
|
|
if (privacyPage) return;
|
|
if (accountPage) renderAccount();
|
|
else {
|
|
renderDiagram();
|
|
updateStatus();
|
|
}
|
|
}
|
|
if (privacyPage) privacy();
|
|
else if (accountPage) account();
|
|
else landing();
|
|
document
|
|
.querySelectorAll<HTMLElement>("[data-language]")
|
|
.forEach((button) =>
|
|
button.addEventListener("click", () =>
|
|
setLanguage(button.dataset.language as Language),
|
|
),
|
|
);
|
|
setLanguage(language);
|
|
refresh();
|
|
window.addEventListener("pageshow", (event) => {
|
|
if (event.persisted) refresh();
|
|
});
|