refactor(web): migrate to Bun and TypeScript with README screenshots

This commit is contained in:
Loki 2026-10-24 15:34:41 +02:00
parent 87372041dd
commit d6a9745df0
Signed by: boba
GPG key ID: 253067914055423B
28 changed files with 3152 additions and 386 deletions

338
src/app.ts Normal file
View file

@ -0,0 +1,338 @@
import type { Language, MessageKey } from "./i18n";
import type { Session } from "./api";
import { detectLanguage, translate } from "./i18n";
import { request, isSession, isInfo, safeAvatar, ApiError } from "./api";
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);
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 sessionState: "loading" | "ready" | "error" = "loading";
let infoState: "loading" | "ready" | "error" = "loading";
let logoutState: "idle" | "pending" | "error" = "idle";
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" 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" 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="client-section" 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" 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" 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" 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>`;
renderDiagram();
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();
});
});
}
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 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><div><dt>${tr("provider")}</dt><dd>GitHub</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>`;
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");
}
});
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 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);
}
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";
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";
infoState = "ready";
})
.catch(() => {
if (!currentController.signal.aborted) {
githubEnabled = 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;
document.title = t(accountPage ? "accountTitle" : "title");
find<HTMLMetaElement>('meta[name="description"]').content = t("description");
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 (accountPage) renderAccount();
else {
renderDiagram();
updateStatus();
}
}
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();
});