673 lines
21 KiB
JavaScript
673 lines
21 KiB
JavaScript
// My INMU 前端:純 JS,沒有框架
|
|
const LANGS = ["zh-TW", "zh-CN", "ja", "ko", "en"];
|
|
const HTML_LANG = { "zh-TW": "zh-Hant-TW", "zh-CN": "zh-Hans-CN", ja: "ja", ko: "ko", en: "en" };
|
|
const DEFAULT_AVATAR = "/assets/avatar.svg";
|
|
|
|
const $ = (id) => document.getElementById(id);
|
|
const SITE_TITLE = document.title; // 伺服器會依 BETA 開關加上 (Beta)
|
|
// 伺服器填入的檔案版本,語言檔網址也帶上,改版後不會拿到快取的舊檔
|
|
const ASSET_V = document.querySelector('meta[name="asset-version"]')?.content || "";
|
|
const FACE = [0, 1].map((n) => `/assets/media/checkin-${n}.webp?v=${ASSET_V}`);
|
|
const SFX_MAX_MS = 1600; // 音效約 1.5 秒;ended 沒觸發(例如播放失敗)時的保險時間
|
|
const SUBMIT_MAX_BYTES = 5 * 1024 * 1024;
|
|
|
|
const state = {
|
|
lang: "zh-TW",
|
|
dict: {},
|
|
me: null,
|
|
today: null,
|
|
email: "",
|
|
cardBust: Date.now(),
|
|
resendTimer: null,
|
|
resetTimer: null,
|
|
};
|
|
|
|
// ---------- i18n ----------
|
|
|
|
function detectLang() {
|
|
const saved = localStorage.getItem("lang");
|
|
if (LANGS.includes(saved)) return saved;
|
|
for (const raw of navigator.languages || [navigator.language || ""]) {
|
|
const l = raw.toLowerCase();
|
|
if (/^zh-(tw|hk|mo|hant)/.test(l)) return "zh-TW";
|
|
if (l.startsWith("zh")) return "zh-CN";
|
|
if (l.startsWith("ja")) return "ja";
|
|
if (l.startsWith("ko")) return "ko";
|
|
if (l.startsWith("en")) return "en";
|
|
}
|
|
return "en";
|
|
}
|
|
|
|
async function loadLang(lang) {
|
|
const res = await fetch(`/assets/i18n/${lang}.json?v=${ASSET_V}`);
|
|
state.dict = await res.json();
|
|
state.lang = lang;
|
|
localStorage.setItem("lang", lang);
|
|
document.documentElement.lang = HTML_LANG[lang];
|
|
$("lang").value = lang;
|
|
document.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); });
|
|
document.querySelectorAll("[data-i18n-aria]").forEach((el) => {
|
|
el.setAttribute("aria-label", t(el.dataset.i18nAria));
|
|
});
|
|
}
|
|
|
|
function t(key, vars = {}) {
|
|
let s = state.dict[key] ?? key;
|
|
for (const [k, v] of Object.entries(vars)) s = s.replaceAll(`{${k}}`, v);
|
|
return s;
|
|
}
|
|
|
|
// ---------- API ----------
|
|
|
|
class ApiError extends Error {
|
|
constructor(code, status) { super(code); this.code = code; this.status = status; }
|
|
}
|
|
|
|
async function api(method, path, body) {
|
|
const opt = { method, headers: { "X-INMU": "1" }, credentials: "same-origin" };
|
|
if (body instanceof FormData) {
|
|
opt.body = body;
|
|
} else if (body !== undefined) {
|
|
opt.headers["Content-Type"] = "application/json";
|
|
opt.body = JSON.stringify(body);
|
|
}
|
|
let res;
|
|
try {
|
|
res = await fetch(path, opt);
|
|
} catch {
|
|
throw new ApiError("network", 0);
|
|
}
|
|
const data = await res.json().catch(() => ({}));
|
|
if (!res.ok) throw new ApiError(typeof data.detail === "string" ? data.detail : "unknown", res.status);
|
|
return data;
|
|
}
|
|
|
|
function errText(e) {
|
|
const key = `err.${e?.code || "unknown"}`;
|
|
return key in state.dict ? t(key) : t("err.unknown");
|
|
}
|
|
|
|
function showError(el, e) {
|
|
if (e) { el.textContent = errText(e); el.hidden = false; } else { el.hidden = true; }
|
|
}
|
|
|
|
function toast(msg) {
|
|
const el = $("toast");
|
|
el.textContent = msg;
|
|
el.hidden = false;
|
|
clearTimeout(toast.timer);
|
|
toast.timer = setTimeout(() => { el.hidden = true; }, 2500);
|
|
}
|
|
|
|
// ---------- 側邊欄:登入 / 個人資訊 ----------
|
|
|
|
// 特殊序號(管理員、含 114514 / 1919810)用背景色標示,顏色在 style.css 的 .uid.tier-*
|
|
function showUid(el, user) {
|
|
el.textContent = `UID ${user.uid_str}`;
|
|
el.className = user.uid_tier ? `uid tier-${user.uid_tier}` : "uid";
|
|
}
|
|
|
|
function renderSidebar() {
|
|
const me = state.me;
|
|
$("auth-box").hidden = !!me;
|
|
$("me-box").hidden = !me;
|
|
if (!me) return;
|
|
$("me-avatar").src = me.avatar_url || DEFAULT_AVATAR;
|
|
$("me-name").textContent = me.display_name;
|
|
showUid($("me-uid"), me);
|
|
$("me-link").href = `/u/${me.uid_str}`;
|
|
$("review-link").hidden = !me.is_admin;
|
|
if (me.is_admin) $("review-link").textContent = t("nav.review", { n: me.pending_reviews ?? 0 });
|
|
}
|
|
|
|
function showCodeStep(show) {
|
|
$("email-form").hidden = show;
|
|
$("code-form").hidden = !show;
|
|
showError($("auth-error"), null);
|
|
if (show) {
|
|
$("code-sent-msg").textContent = t("auth.sent", { email: state.email });
|
|
$("code").value = "";
|
|
$("code").focus();
|
|
}
|
|
}
|
|
|
|
function startResendCountdown(seconds) {
|
|
clearInterval(state.resendTimer);
|
|
const btn = $("resend");
|
|
let left = seconds;
|
|
const tick = () => {
|
|
btn.disabled = left > 0;
|
|
btn.textContent = left > 0 ? t("auth.resend_wait", { s: left }) : t("auth.resend");
|
|
if (left-- <= 0) clearInterval(state.resendTimer);
|
|
};
|
|
tick();
|
|
state.resendTimer = setInterval(tick, 1000);
|
|
}
|
|
|
|
async function sendCode() {
|
|
const r = await api("POST", "/api/auth/request-code", { email: state.email, lang: state.lang });
|
|
showCodeStep(true);
|
|
startResendCountdown(r.resend_in);
|
|
}
|
|
|
|
async function withBusy(button, fn) {
|
|
button.disabled = true;
|
|
try { await fn(); } finally { button.disabled = false; }
|
|
}
|
|
|
|
function bindAuth() {
|
|
$("email-form").addEventListener("submit", (ev) => {
|
|
ev.preventDefault();
|
|
state.email = $("email").value.trim();
|
|
withBusy(ev.submitter || $("email-form").querySelector("button"), async () => {
|
|
try { await sendCode(); } catch (e) { showError($("auth-error"), e); }
|
|
});
|
|
});
|
|
|
|
$("code-form").addEventListener("submit", (ev) => {
|
|
ev.preventDefault();
|
|
const code = $("code").value.replace(/\D/g, "");
|
|
withBusy(ev.submitter || $("code-form").querySelector("button[type=submit]"), async () => {
|
|
try {
|
|
const r = await api("POST", "/api/auth/verify", { email: state.email, code, lang: state.lang });
|
|
state.me = r.user;
|
|
clearInterval(state.resendTimer);
|
|
showCodeStep(false);
|
|
$("email").value = "";
|
|
if (r.user.lang !== state.lang) await loadLang(r.user.lang);
|
|
renderSidebar();
|
|
closeMenu();
|
|
await route();
|
|
} catch (e) {
|
|
showError($("auth-error"), e);
|
|
if (e.code === "expired" || e.code === "not_requested") $("code").value = "";
|
|
}
|
|
});
|
|
});
|
|
|
|
$("resend").addEventListener("click", async () => {
|
|
try { await sendCode(); } catch (e) { showError($("auth-error"), e); }
|
|
});
|
|
|
|
$("change-email").addEventListener("click", () => {
|
|
clearInterval(state.resendTimer);
|
|
showCodeStep(false);
|
|
$("email").focus();
|
|
});
|
|
|
|
$("logout").addEventListener("click", async () => {
|
|
try { await api("POST", "/api/auth/logout"); } catch { /* 已經登出也沒關係 */ }
|
|
state.me = null;
|
|
state.today = null;
|
|
renderSidebar();
|
|
await route();
|
|
});
|
|
|
|
$("guest-login").addEventListener("click", () => {
|
|
openMenu();
|
|
$("email").focus();
|
|
});
|
|
}
|
|
|
|
// ---------- 簽到 ----------
|
|
|
|
function showCheckinPart(part) {
|
|
for (const id of ["checkin-guest", "checkin-ready", "checkin-done"]) $(id).hidden = id !== part;
|
|
}
|
|
|
|
function statsText(d) {
|
|
return `${t("checkin.total", { n: d.total_days })} · ${t("checkin.streak", { n: d.streak })}`;
|
|
}
|
|
|
|
function renderToday(justChecked) {
|
|
const d = state.today;
|
|
if (!d.checked_in) {
|
|
$("checkin-face").src = FACE[0];
|
|
$("checkin-btn").classList.remove("pressed");
|
|
showCheckinPart("checkin-ready");
|
|
$("ready-stats").textContent = d.total_days ? statsText(d) : "";
|
|
} else {
|
|
showCheckinPart("checkin-done");
|
|
$("checkin-msg").textContent = justChecked ? t("checkin.success") : t("checkin.done_today");
|
|
const src = `${d.card_url}?v=${state.cardBust}`;
|
|
if ($("card-img").getAttribute("src") !== src) $("card-img").src = src;
|
|
$("download-btn").href = src;
|
|
$("download-btn").setAttribute("download", `inmu-${d.day}.png`);
|
|
$("done-stats").textContent = statsText(d);
|
|
}
|
|
startResetCountdown();
|
|
}
|
|
|
|
function fmtDuration(ms) {
|
|
const s = Math.max(0, Math.floor(ms / 1000));
|
|
const pad = (n) => String(n).padStart(2, "0");
|
|
return `${pad(Math.floor(s / 3600))}:${pad(Math.floor((s % 3600) / 60))}:${pad(s % 60)}`;
|
|
}
|
|
|
|
function startResetCountdown() {
|
|
clearInterval(state.resetTimer);
|
|
const el = $("next-reset");
|
|
if (!state.today) { el.hidden = true; return; }
|
|
const target = Date.parse(state.today.next_reset);
|
|
// 伺服器以台灣時間 04:00 換日,這裡換算成裝置的當地時間顯示
|
|
const when = new Intl.DateTimeFormat(HTML_LANG[state.lang], {
|
|
month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", hourCycle: "h23",
|
|
}).format(new Date(target));
|
|
el.hidden = false;
|
|
const tick = async () => {
|
|
const left = target - Date.now();
|
|
el.textContent = t("checkin.next", { time: when, t: fmtDuration(left) });
|
|
if (left <= 0) {
|
|
clearInterval(state.resetTimer);
|
|
await refreshToday(); // 換日了
|
|
}
|
|
};
|
|
tick();
|
|
state.resetTimer = setInterval(tick, 1000);
|
|
}
|
|
|
|
async function refreshToday() {
|
|
try {
|
|
state.today = await api("GET", "/api/checkin/today");
|
|
renderToday(false);
|
|
} catch (e) {
|
|
if (e.status === 401) { state.me = null; renderSidebar(); showGuest(); } else toast(errText(e));
|
|
}
|
|
}
|
|
|
|
function showGuest() {
|
|
clearInterval(state.resetTimer);
|
|
$("next-reset").hidden = true;
|
|
showCheckinPart("checkin-guest");
|
|
}
|
|
|
|
async function showCheckin() {
|
|
showView("view-checkin");
|
|
if (!state.me) return showGuest();
|
|
await refreshToday();
|
|
}
|
|
|
|
async function shareCard() {
|
|
const d = state.today;
|
|
const text = `${d.share_text} ${d.share_url}`;
|
|
try {
|
|
const blob = await fetch($("card-img").src).then((r) => r.blob());
|
|
const file = new File([blob], `inmu-${d.day}.png`, { type: "image/png" });
|
|
if (navigator.canShare && navigator.canShare({ files: [file] })) {
|
|
await navigator.share({ files: [file], text });
|
|
return;
|
|
}
|
|
if (navigator.share) {
|
|
await navigator.share({ text: d.share_text, url: d.share_url });
|
|
return;
|
|
}
|
|
} catch (e) {
|
|
if (e.name === "AbortError") return; // 使用者自己取消
|
|
}
|
|
try {
|
|
await navigator.clipboard.writeText(text);
|
|
toast(t("share.copied"));
|
|
} catch {
|
|
window.prompt("", text);
|
|
}
|
|
}
|
|
|
|
// 按下簽到時從按鈕中心噴出粒子(顏色對應主色與 UID 的三種顏色,夾幾個「1」呼應 0 → 1)
|
|
function burst(el) {
|
|
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
|
|
const r = el.getBoundingClientRect();
|
|
const cx = r.left + r.width / 2;
|
|
const cy = r.top + r.height / 2;
|
|
const colors = ["#f0a43a", "#f5c518", "#2f7beb", "#f07c2a", "#ffffff"];
|
|
const count = 28;
|
|
for (let i = 0; i < count; i++) {
|
|
const p = document.createElement("span");
|
|
const digit = i % 6 === 0;
|
|
p.className = digit ? "particle digit" : "particle";
|
|
if (digit) p.textContent = "1";
|
|
const angle = (i / count) * Math.PI * 2 + Math.random() * 0.5;
|
|
const dist = r.width * 0.55 + Math.random() * r.width * 0.7;
|
|
const size = digit ? 18 + Math.random() * 14 : 6 + Math.random() * 8;
|
|
p.style.cssText = [
|
|
`--x:${cx}px`, `--y:${cy}px`,
|
|
`--dx:${(Math.cos(angle) * dist).toFixed(1)}px`, `--dy:${(Math.sin(angle) * dist).toFixed(1)}px`,
|
|
`--s:${size.toFixed(1)}px`, `--c:${colors[i % colors.length]}`,
|
|
`--r:${Math.round(Math.random() * 360 - 180)}deg`, `--d:${(0.7 + Math.random() * 0.4).toFixed(2)}s`,
|
|
].join(";");
|
|
p.addEventListener("animationend", () => p.remove());
|
|
document.body.appendChild(p);
|
|
}
|
|
}
|
|
|
|
// 等音效播完(或保險時間到)
|
|
function waitSfx(sfx) {
|
|
return new Promise((resolve) => {
|
|
const done = () => { clearTimeout(timer); sfx.removeEventListener("ended", done); resolve(); };
|
|
const timer = setTimeout(done, SFX_MAX_MS);
|
|
sfx.addEventListener("ended", done);
|
|
});
|
|
}
|
|
|
|
// 先把小卡下載好,切換畫面時才不會看到空白
|
|
function preloadImage(src, maxMs = 6000) {
|
|
return new Promise((resolve) => {
|
|
const img = new Image();
|
|
const timer = setTimeout(resolve, maxMs);
|
|
img.onload = img.onerror = () => { clearTimeout(timer); resolve(); };
|
|
img.src = src;
|
|
});
|
|
}
|
|
|
|
function bindCheckin() {
|
|
const btn = $("checkin-btn");
|
|
const sfx = $("checkin-sfx");
|
|
btn.addEventListener("click", () => withBusy(btn, async () => {
|
|
// 0 → 1、播音效、噴粒子,同時送出簽到;音效播完而且小卡下載好才亮出小卡,並關掉音效
|
|
$("checkin-face").src = FACE[1];
|
|
btn.classList.remove("pressed");
|
|
void btn.offsetWidth; // 重新觸發動畫
|
|
btn.classList.add("pressed");
|
|
sfx.currentTime = 0;
|
|
sfx.play().catch(() => { /* 不能播就算了 */ });
|
|
burst(btn);
|
|
const sfxDone = waitSfx(sfx);
|
|
try {
|
|
const today = await api("POST", "/api/checkin");
|
|
await Promise.all([sfxDone, today.card_url ? preloadImage(`${today.card_url}?v=${state.cardBust}`) : null]);
|
|
sfx.pause();
|
|
state.today = today;
|
|
renderToday(!today.already);
|
|
loadMe(); // 更新側欄的天數
|
|
} catch (e) {
|
|
sfx.pause();
|
|
$("checkin-face").src = FACE[0];
|
|
btn.classList.remove("pressed");
|
|
toast(errText(e));
|
|
}
|
|
}));
|
|
$("share-btn").addEventListener("click", shareCard);
|
|
}
|
|
|
|
// ---------- 畫面切換 ----------
|
|
|
|
function showView(id) {
|
|
for (const v of ["view-checkin", "view-user", "view-upload", "view-review"]) $(v).hidden = v !== id;
|
|
if (id !== "view-checkin") clearInterval(state.resetTimer);
|
|
}
|
|
|
|
// ---------- 投稿迷因圖 ----------
|
|
|
|
function renderUploads(r) {
|
|
$("upload-quota").textContent = t("upload.remaining", { n: r.remaining, max: r.limit });
|
|
$("upload-pick").classList.toggle("busy", r.remaining <= 0);
|
|
const list = $("upload-list");
|
|
list.replaceChildren();
|
|
$("upload-empty").hidden = r.items.length > 0;
|
|
for (const it of r.items) {
|
|
const box = document.createElement("div");
|
|
box.className = "sub-item";
|
|
if (it.image_url) {
|
|
const img = document.createElement("img");
|
|
img.src = it.image_url;
|
|
img.alt = "";
|
|
img.loading = "lazy";
|
|
box.append(img);
|
|
}
|
|
const badge = document.createElement("span");
|
|
badge.className = `sub-status ${it.status}`;
|
|
badge.textContent = t(`upload.status.${it.status}`);
|
|
box.append(badge);
|
|
list.append(box);
|
|
}
|
|
}
|
|
|
|
async function refreshUploads() {
|
|
try {
|
|
renderUploads(await api("GET", "/api/submissions"));
|
|
} catch (e) {
|
|
showError($("upload-error"), e);
|
|
$("upload-pick").classList.remove("busy");
|
|
}
|
|
}
|
|
|
|
async function showUpload() {
|
|
showView("view-upload");
|
|
document.title = `${t("nav.upload")} · ${SITE_TITLE}`;
|
|
showError($("upload-error"), null);
|
|
if (!state.me) { location.replace("/"); return; }
|
|
await refreshUploads();
|
|
}
|
|
|
|
function bindUpload() {
|
|
$("upload-file").addEventListener("change", async (ev) => {
|
|
const files = [...ev.target.files];
|
|
ev.target.value = "";
|
|
if (!files.length) return;
|
|
$("upload-pick").classList.add("busy");
|
|
showError($("upload-error"), null);
|
|
let ok = 0;
|
|
for (const file of files) { // 一張一張傳,額度用完就停
|
|
if (file.size > SUBMIT_MAX_BYTES) { showError($("upload-error"), { code: "file_too_large" }); continue; }
|
|
const fd = new FormData();
|
|
fd.append("file", file);
|
|
try {
|
|
await api("POST", "/api/submissions", fd);
|
|
ok++;
|
|
} catch (e) {
|
|
showError($("upload-error"), e);
|
|
if (e.code === "quota_exceeded") break;
|
|
}
|
|
}
|
|
if (ok) toast(t("upload.done", { n: ok }));
|
|
await refreshUploads();
|
|
});
|
|
}
|
|
|
|
// ---------- 管理員審核(一張一張) ----------
|
|
|
|
async function loadReview() {
|
|
try {
|
|
const r = await api("GET", "/api/admin/submissions");
|
|
$("review-left").textContent = t("review.left", { n: r.pending });
|
|
state.me.pending_reviews = r.pending;
|
|
renderSidebar();
|
|
const it = r.item;
|
|
$("review-item").hidden = !it;
|
|
$("review-empty").hidden = !!it;
|
|
if (!it) return;
|
|
$("review-item").dataset.id = it.id;
|
|
$("review-img").src = it.image_url;
|
|
$("review-name").textContent = it.uploader.display_name;
|
|
$("review-name").href = `/u/${it.uploader.uid_str}`;
|
|
showUid($("review-uid"), it.uploader);
|
|
$("review-time").textContent = new Date(it.created_at).toLocaleString(HTML_LANG[state.lang]);
|
|
} catch (e) {
|
|
if (e.status === 401 || e.status === 403) { location.replace("/"); return; }
|
|
toast(errText(e));
|
|
}
|
|
}
|
|
|
|
async function showReview() {
|
|
showView("view-review");
|
|
document.title = `${t("review.heading")} · ${SITE_TITLE}`;
|
|
if (!state.me?.is_admin) { location.replace("/"); return; }
|
|
await loadReview();
|
|
}
|
|
|
|
function bindReview() {
|
|
const buttons = [$("review-approve"), $("review-reject")];
|
|
const decide = async (action) => {
|
|
const sid = $("review-item").dataset.id;
|
|
buttons.forEach((b) => { b.disabled = true; });
|
|
try {
|
|
await api("POST", `/api/admin/submissions/${sid}/${action}`);
|
|
toast(t(`review.${action}d`));
|
|
} catch (e) {
|
|
// 已經審過(例如另一個分頁)就直接跳下一張
|
|
if (e.code !== "already_reviewed" && e.code !== "not_found") toast(errText(e));
|
|
} finally {
|
|
buttons.forEach((b) => { b.disabled = false; });
|
|
}
|
|
await loadReview();
|
|
};
|
|
$("review-approve").addEventListener("click", () => decide("approve"));
|
|
$("review-reject").addEventListener("click", () => decide("reject"));
|
|
}
|
|
|
|
// ---------- 個人頁 ----------
|
|
|
|
async function showUser(uid) {
|
|
showView("view-user");
|
|
try {
|
|
const u = await api("GET", `/api/users/${uid}?lang=${state.lang}`);
|
|
$("user-card").hidden = false;
|
|
$("user-missing").hidden = true;
|
|
$("user-avatar").src = u.avatar_url || DEFAULT_AVATAR;
|
|
$("user-name").textContent = u.display_name;
|
|
showUid($("user-uid"), u);
|
|
$("user-stats").textContent = statsText(u);
|
|
const bio = $("user-bio");
|
|
if (u.bio_md.trim()) {
|
|
bio.innerHTML = u.bio_html; // 伺服器端已關閉原始 HTML
|
|
bio.classList.remove("empty");
|
|
} else {
|
|
bio.textContent = t("user.no_bio");
|
|
bio.classList.add("empty");
|
|
}
|
|
const joined = new Date(u.created_at).toLocaleDateString(HTML_LANG[state.lang]);
|
|
$("user-joined").textContent = t("user.joined", { d: joined });
|
|
document.title = `${u.display_name} · ${SITE_TITLE}`;
|
|
} catch {
|
|
$("user-card").hidden = true;
|
|
$("user-missing").hidden = false;
|
|
}
|
|
}
|
|
|
|
// ---------- 編輯個人資料 ----------
|
|
|
|
function bindProfile() {
|
|
const dialog = $("profile-dialog");
|
|
|
|
$("edit-profile").addEventListener("click", () => {
|
|
const me = state.me;
|
|
$("edit-avatar").src = me.avatar_url || DEFAULT_AVATAR;
|
|
$("edit-name").value = me.display_name;
|
|
$("edit-bio").value = me.bio_md;
|
|
setPreview(false);
|
|
showError($("profile-error"), null);
|
|
closeMenu();
|
|
dialog.showModal();
|
|
});
|
|
|
|
$("profile-cancel").addEventListener("click", () => dialog.close());
|
|
|
|
$("avatar-file").addEventListener("change", async (ev) => {
|
|
const file = ev.target.files[0];
|
|
ev.target.value = "";
|
|
if (!file) return;
|
|
if (file.size > 5 * 1024 * 1024) return showError($("profile-error"), { code: "file_too_large" });
|
|
const fd = new FormData();
|
|
fd.append("file", file);
|
|
try {
|
|
state.me = await api("PUT", "/api/me/avatar", fd);
|
|
state.cardBust = Date.now();
|
|
$("edit-avatar").src = state.me.avatar_url;
|
|
showError($("profile-error"), null);
|
|
renderSidebar();
|
|
} catch (e) {
|
|
showError($("profile-error"), e);
|
|
}
|
|
});
|
|
|
|
$("preview-toggle").addEventListener("click", async () => {
|
|
if (!$("edit-preview").hidden) return setPreview(false);
|
|
try {
|
|
const r = await api("POST", "/api/markdown", { md: $("edit-bio").value });
|
|
$("edit-preview").innerHTML = r.html;
|
|
setPreview(true);
|
|
} catch (e) {
|
|
showError($("profile-error"), e);
|
|
}
|
|
});
|
|
|
|
$("profile-form").addEventListener("submit", (ev) => {
|
|
ev.preventDefault();
|
|
withBusy($("profile-save"), async () => {
|
|
try {
|
|
state.me = await api("PATCH", "/api/me", {
|
|
display_name: $("edit-name").value,
|
|
bio_md: $("edit-bio").value,
|
|
});
|
|
state.cardBust = Date.now();
|
|
dialog.close();
|
|
toast(t("profile.saved"));
|
|
renderSidebar();
|
|
await route();
|
|
} catch (e) {
|
|
showError($("profile-error"), e);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function setPreview(on) {
|
|
$("edit-preview").hidden = !on;
|
|
$("edit-bio").hidden = on;
|
|
$("preview-toggle").textContent = on ? t("profile.edit_back") : t("profile.preview");
|
|
}
|
|
|
|
// ---------- 手機選單 ----------
|
|
|
|
function openMenu() { $("sidebar").classList.add("open"); }
|
|
function closeMenu() { $("sidebar").classList.remove("open"); }
|
|
|
|
// ---------- 啟動 ----------
|
|
|
|
async function loadMe() {
|
|
try {
|
|
state.me = await api("GET", "/api/me");
|
|
} catch {
|
|
state.me = null;
|
|
}
|
|
renderSidebar();
|
|
}
|
|
|
|
async function route() {
|
|
document.title = SITE_TITLE;
|
|
const m = location.pathname.match(/^\/u\/(\d+)$/);
|
|
if (m) return showUser(m[1]);
|
|
if (location.pathname === "/upload") return showUpload();
|
|
if (location.pathname === "/review") return showReview();
|
|
return showCheckin();
|
|
}
|
|
|
|
async function init() {
|
|
await loadLang(detectLang());
|
|
bindAuth();
|
|
bindCheckin();
|
|
bindProfile();
|
|
bindUpload();
|
|
bindReview();
|
|
|
|
$("menu-toggle").addEventListener("click", () => $("sidebar").classList.toggle("open"));
|
|
|
|
$("lang").addEventListener("change", async (ev) => {
|
|
await loadLang(ev.target.value);
|
|
if (state.me) {
|
|
try {
|
|
// 語言也會用在信件、小卡與分享文字,所以同步到伺服器
|
|
state.me = await api("PATCH", "/api/me", { lang: state.lang });
|
|
state.cardBust = Date.now();
|
|
} catch { /* 介面已經切換,伺服器同步失敗就算了 */ }
|
|
}
|
|
renderSidebar();
|
|
if (!$("code-form").hidden) $("code-sent-msg").textContent = t("auth.sent", { email: state.email });
|
|
await route();
|
|
});
|
|
|
|
await loadMe();
|
|
await route();
|
|
}
|
|
|
|
init();
|