import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode, } from "react"; import { identityUid } from "./identityUid"; import qrcode from "qrcode-generator"; import { useRegisterSW } from "virtual:pwa-register/react"; import "./App.css"; // After App.css: its :where() base variables have the same (zero) specificity. import "./styles/ide.css"; const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; /** Props for a modal dialog's backdrop. Dismisses on Escape or a genuine * backdrop click (not a text-selection drag that starts inside the dialog * and releases over the backdrop). Moves focus in on open unless an * autoFocus field already took it, keeps Tab inside, and hands focus back to * whatever had it before on close. */ function useBackdropDismiss(onDismiss: () => void) { const mouseDownOnBackdrop = useRef(false); const ref = useRef(null); useEffect(() => { const previous = document.activeElement as HTMLElement | null; const el = ref.current; if (el && !el.contains(document.activeElement)) el.querySelector(FOCUSABLE)?.focus(); return () => previous?.focus?.(); }, []); return { ref, role: "dialog", "aria-modal": true, onKeyDown: (e: React.KeyboardEvent) => { if (e.key === "Escape") { e.stopPropagation(); onDismiss(); return; } if (e.key !== "Tab") return; const items = [...e.currentTarget.querySelectorAll(FOCUSABLE)]; if (items.length === 0) return; const first = items[0]; const last = items[items.length - 1]; if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } }, onMouseDown: (e: React.MouseEvent) => { mouseDownOnBackdrop.current = e.target === e.currentTarget; }, onClick: (e: React.MouseEvent) => { if (mouseDownOnBackdrop.current && e.target === e.currentTarget) onDismiss(); }, }; } /** Callback ref for a dropdown menu: focus its first item when it opens. * Module-level so React calls it once per mount, not on every render. */ function focusFirstItem(el: HTMLElement | null) { el?.querySelector(FOCUSABLE)?.focus(); } /** onKeyDown for dropdown and context menus: Up/Down/Home/End move between * items, and Escape puts focus back on the button that opened the menu * before the window-level Escape listener closes it. */ function handleMenuKeyDown(e: React.KeyboardEvent) { if (e.key === "Escape") { e.currentTarget.parentElement?.querySelector(":scope > button[aria-expanded]")?.focus(); return; } // Arrows belong to sliders, text fields and selects (the volume slider). if ((e.target as HTMLElement).matches("input:not([type=checkbox]), select, textarea")) return; const items = [...e.currentTarget.querySelectorAll(FOCUSABLE)]; const i = items.indexOf(document.activeElement as HTMLElement); const next = e.key === "ArrowDown" ? items[(i + 1) % items.length] : e.key === "ArrowUp" ? items[(i - 1 + items.length) % items.length] : e.key === "Home" ? items[0] : e.key === "End" ? items[items.length - 1] : undefined; if (!next) return; e.preventDefault(); next.focus(); } /** onKeyDown for the tree panel (server row + channel tree): Up/Down/Home/End * walk the visible rows, Left goes to the parent row and Right into an open * channel. A channel row handles Left/Right itself first when it can * collapse or expand, and marks the event as handled. */ function handleTreeKeyDown(e: React.KeyboardEvent) { const row = e.target as HTMLElement; if (e.defaultPrevented || !row.classList.contains("ts-row")) return; const rows = [...e.currentTarget.querySelectorAll(".ts-row[tabindex]")]; const i = rows.indexOf(row); const next = e.key === "ArrowDown" ? rows[i + 1] : e.key === "ArrowUp" ? rows[i - 1] : e.key === "Home" ? rows[0] : e.key === "End" ? rows[rows.length - 1] : e.key === "ArrowLeft" ? (row.closest("ul")?.closest("li")?.querySelector(":scope > .ts-row") ?? rows[0]) : e.key === "ArrowRight" ? row.closest("li")?.querySelector(":scope > ul .ts-row") : undefined; if (next === undefined && !["ArrowDown", "ArrowUp", "ArrowRight"].includes(e.key)) return; e.preventDefault(); next?.focus(); } import { AudioPlayer, MicCapture, SAMPLE_RATE, encodeWavStereo, hasNativeOutputPicker, listAudioInputDevices, listAudioOutputDevices, pickAudioOutputDevice, } from "./voice"; import { createAec3, type Aec3Instance } from "./aec3"; import { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n"; import { StreamAccess, StreamMode, StreamPublisher, type PublishState, type StreamPublishOptions, } from "./publish"; import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream"; import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode"; import { DEFAULT_SYNC_SERVER, SYNC_CATEGORIES, accountInfo, changeSyncPassword, createSyncAccount, deleteSyncAccount, formatAccountNumber, getSyncStatus, loadSyncAccount, loginSyncAccount, logoutSyncAccount, normalizeAccountNumber, normalizePassword, recoveryText, resolveConflict, setSyncCategories, subscribeSyncStatus, syncErrorKey, syncLink, syncNow, type SyncCategory, } from "./sync"; import { SOUND_EVENTS, clearCustomSound, loadCustomSound, loadEventSoundEnabled, loadSoundsEnabled, loadSoundsVolume, playSound, setSoundStyle, saveCustomSound, saveEventSoundEnabled, saveSoundsEnabled, saveSoundsVolume, setSoundsOutputDevice, type SoundEventId, } from "./sounds"; import { parseSoundpack } from "./soundpack"; import { checkMasterPassword, isVaultUnlocked, removeMasterPassword, setMasterPassword } from "./vault"; import { BUILTIN_PACK, NO_SOUNDS_PACK, NOTIFICATION_TREE, deleteSoundPack, getNotificationSettings, importSoundPack, isSpecialKey, loadSoundPacks, notificationTextPositions, notify, packScript, runSoundScript, saveNotificationSettings, setNotificationPlaybackMuted, setSessionSoundPack, textPositionChoices, type NotificationNode, type NotificationOverride, type NotificationSettings, type SoundPack, } from "./notifications"; import { iconPackCss, loadIconPacks, loadSelectedIconPack, parseIconPack, saveIconPacks, saveSelectedIconPack, type IconPack, } from "./iconpack"; import { StillImg, clearStillCache } from "./lib/still"; import { DEFAULT_DOWNLOAD_SETTINGS, canPickFolder, clearDownloadDir, loadDownloadDir, loadDownloadSettings, pickDownloadDir, resolveSaveTarget, saveDownloadSettings, writeToTarget, type DownloadSettings, type SaveTarget, } from "./downloads"; import { DEFAULT_CHAT_SETTINGS, appendChatLog, capLines, loadChatSettings, readChatLog, saveChatSettings, type ChatSettings, } from "./chatlog"; import { ConnectionTabs, } from "./ConnectionTabs"; import { BARE_URL_REGEX, renderBbcode, wrapUrls } from "./lib/bbcode"; import { parseChannelName, spacerDisplayName } from "./lib/spacer"; import akimoPhoto from "./assets/akimo.jpg"; import { applyParkedGatewayEvent, emptyParkedState, sessionLabel, type ParkedSessionState, type SessionRecord, type SessionTabInfo, } from "./connectionSessions"; // In dev, the gateway runs standalone on its own port. In production it's // normally served from the same origin/port as the web app (single // container behind a reverse proxy), so the WebSocket URL is derived from // the current location by default. If the static frontend is hosted // separately from the gateway (e.g. a static host for the landing/app // bundle, with the gateway staying on your own server), set // VITE_GATEWAY_URL at build time to the gateway's public wss:// address // instead - the browser will still block a plain ws:// gateway from an // https:// page (mixed content), so that address needs real TLS. // Either way the gateway's WebSocketServer only listens on /ws (see // gateway/src/index.ts), so that path always gets appended here - a // VITE_GATEWAY_URL override only needs to name the host, not the path. const GATEWAY_URL = import.meta.env.DEV ? "ws://localhost:8080/ws" : import.meta.env.VITE_GATEWAY_URL ? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "")}/ws` : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`; // Same derivation as GATEWAY_URL above, but for a plain HTTP POST (the // feedback form) instead of the WebSocket - see gateway/src/index.ts's // /api/feedback handler. VITE_GATEWAY_URL names a WebSocket origin, so its // scheme has to be mapped back to http(s) here: fetch() refuses anything // else outright ("TypeError: unknown scheme"), so with VITE_GATEWAY_URL set // the form could not submit at all. const FEEDBACK_URL = import.meta.env.DEV ? "http://localhost:8080/api/feedback" : import.meta.env.VITE_GATEWAY_URL ? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "").replace(/^ws(s?):\/\//, "http$1://")}/api/feedback` : `${window.location.protocol}//${window.location.host}/api/feedback`; // News ticker: the instance's own gateway says whether it's on and adds its // own messages (gateway/src/news.ts); the central feed is fetched directly, // like the store. The demo has no gateway and only shows the central feed. const NEWS_CONFIG_URL = DEMO_MODE ? null : FEEDBACK_URL.replace(/\/api\/feedback$/, "/api/news"); const NEWS_FEED_URL = import.meta.env.DEV ? "http://localhost:8080/api/store/news" : import.meta.env.VITE_NEWS_URL || "https://gateway.webspeak3.de/api/store/news"; // Unlike GATEWAY_URL/FEEDBACK_URL above, the design store is NOT per-instance: // it's a single, centrally curated catalog run on the maintainer's own VPS // (see gateway/src/store.ts), so every build - official and self-hosted // Docker image alike - points at the same one by default, regardless of // which TS3/TeaSpeak gateway that build otherwise talks to. A self-hoster who // wants to run their own separate community store instead (their own // gateway's STORE_ENABLED=1) can override with VITE_STORE_URL at build time. // DEMO_MODE keeps the old same-origin derivation instead, which 404s on the // static demo host - the public demo has no write access to the real store. const STORE_URL = import.meta.env.DEV ? "http://localhost:8080/api/store/themes" : DEMO_MODE ? `${window.location.protocol}//${window.location.host}/api/store/themes` : import.meta.env.VITE_STORE_URL || "https://gateway.webspeak3.de/api/store/themes"; // Ko-fi page of the project (.github/FUNDING.yml). Unlike the feedback button // below this is not limited to the maintainer's own instance: it ships in // every build, the Docker image included. Self-hosters who would rather not // carry someone else's donation link can build with VITE_DONATE_URL= (empty) // to drop the button, or point it somewhere else. const DONATE_URL = import.meta.env.VITE_DONATE_URL ?? "https://ko-fi.com/moepchi"; // This file's frontend is deployed as multiple Cloudflare Pages projects // from the same repo/build (see mem:deployment) - only the maintainer's own // production instance talks to a gateway they actually operate and read // feedback from, so the "Feedback" menu entry only appears there. Every // other deployment (self-hosted forks, and the public demo - which has no // real gateway at all, see DEMO_MODE) simply never shows it. This is a UI // nicety, not a security boundary: the gateway's own FEEDBACK_ENABLED // opt-in (see gateway/src/index.ts) is what actually decides whether // submissions are accepted at all. const OWN_HOSTED_HOSTNAMES = new Set(["client.webspeak3.de"]); const IS_OWN_HOSTED_INSTANCE = !DEMO_MODE && OWN_HOSTED_HOSTNAMES.has(window.location.hostname); // Auto-connect from a share link (?connect=host[:port]&nickname=&channel=&token=, // see GitHub issue #10). Parsed once at module load and immediately stripped // from the URL via replaceState so a reload/refresh doesn't silently // reconnect off a stale link sitting in the address bar or browser history. const AUTO_CONNECT_FROM_URL = (() => { const params = new URLSearchParams(window.location.search); // The token may also sit in the fragment (#token=...), which - unlike the // query - never reaches server logs or Referer headers. const hashParams = new URLSearchParams(window.location.hash.slice(1)); const connectHost = params.get("connect"); if (!connectHost) return null; const target = { host: connectHost, nickname: params.get("nickname") || undefined, defaultChannel: params.get("channel") || undefined, privilegeKey: hashParams.get("token") || params.get("token") || undefined, }; for (const key of ["connect", "nickname", "channel", "token"]) params.delete(key); let hash = window.location.hash; if (hashParams.has("token")) { hashParams.delete("token"); hash = hashParams.size ? `#${hashParams}` : ""; } const rest = params.toString(); window.history.replaceState(null, "", window.location.pathname + (rest ? `?${rest}` : "") + hash); return target; })(); // A self-hosted build can also bake in a default server so the page // auto-connects with zero URL params at all - set via `docker compose build // --build-arg DEFAULT_SERVER=...` (see Dockerfile/README) or plain // VITE_DEFAULT_SERVER= at build time. The Docker image can set the same thing // at runtime instead (DEFAULT_SERVER/DEFAULT_CHANNEL env vars, issue #12): the // gateway passes them in as tags, which take precedence over the build // values. AUTO_CONNECT_FROM_URL above always wins when a share link is present. const runtimeConfig = (name: string) => document.querySelector(`meta[name="webspeak3-${name}"]`)?.content; const DEFAULT_SERVER = runtimeConfig("default-server") || import.meta.env.VITE_DEFAULT_SERVER || null; const DEFAULT_CHANNEL = runtimeConfig("default-channel") || import.meta.env.VITE_DEFAULT_CHANNEL || ""; // The gateway admin's ALLOWED_SERVERS (unless SERVER_PICKER=0): one server // locks the address field to it, several turn it into a dropdown. const SERVER_CHOICES = runtimeConfig("allowed-servers")?.split(",").filter(Boolean) ?? []; // Terms of use, own-hosted instance only (see TODO.md #2/#7.1). Versioned so // a rule change can re-surface the modal: bump TOS_VERSION and everyone who // accepted an older version is asked again. const TOS_VERSION = "v1"; const TOS_KEY = "webspeak3-tos-accepted"; function hasAcceptedToS(): boolean { return (localStorage.getItem(TOS_KEY) ?? "").startsWith(TOS_VERSION + ":"); } // One-time migration from the pre-rename "ts-web-client:*" localStorage // namespace so existing users don't lose their favorites/preferences. (function migrateLegacyStorageKeys() { const oldPrefix = "ts-web-client:"; const newPrefix = "webspeak3:"; for (const oldKey of Object.keys(localStorage).filter((k) => k.startsWith(oldPrefix))) { const newKey = newPrefix + oldKey.slice(oldPrefix.length); if (localStorage.getItem(newKey) === null) { localStorage.setItem(newKey, localStorage.getItem(oldKey)!); } localStorage.removeItem(oldKey); } })(); const LAST_HOST_KEY = "webspeak3:last-host"; const LAST_NICKNAME_KEY = "webspeak3:last-nickname"; // Privilege keys are one-shot grants, so they're no longer remembered across // reloads; drop what older versions stored in plain text. localStorage.removeItem("webspeak3:last-privilege-key"); const LAST_SERVER_TYPE_KEY = "webspeak3:last-server-type"; type ServerType = "teamspeak" | "teaspeak" | "auto" | "ts2"; function loadServerType(): ServerType { const raw = localStorage.getItem(LAST_SERVER_TYPE_KEY); return raw === "teamspeak" || raw === "teaspeak" || raw === "auto" || raw === "ts2" ? raw : "auto"; } // The gateway's feature list, readable before connecting. TeamSpeak 2 is // opt-in per gateway (ENABLE_TS2), so the connect dialog only offers it then. const FEATURES_URL = DEMO_MODE ? null : FEEDBACK_URL.replace(/\/api\/feedback$/, "/api/features"); let gatewayFeaturesPromise: Promise | null = null; function fetchGatewayFeatures(): Promise { if (!FEATURES_URL) return Promise.resolve([]); gatewayFeaturesPromise ??= fetch(FEATURES_URL) .then((r) => (r.ok ? r.json() : { features: [] })) .then((d) => (Array.isArray(d.features) ? d.features : [])) .catch(() => []); return gatewayFeaturesPromise; } /** Everything needed to (re)open a gateway connection for one session, kept * around per session id so a dropped socket — active tab or a parked * background one — can be silently reconnected. */ type ConnectParams = { host: string; nickname: string; serverPassword: string; channelPassword: string; defaultChannel: string; privilegeKey: string; /** TeamSpeak 2 registered account (anonymous when empty). */ loginName?: string; loginPassword?: string; serverType: ServerType; identityId: string | null; favoriteId: string | null; }; /** Identity persisted across sessions so the server sees the same client UID * each time, instead of a fresh one being generated per connection. */ const IDENTITY_KEY = "webspeak3:identity"; const IDENTITIES_KEY = "webspeak3:identities"; const ACTIVE_IDENTITY_KEY = "webspeak3:active-identity"; interface Identity { id: string; name: string; /** Per-identity nickname/phonetic nickname, like the native client - selecting * an identity in the connect dialog fills these in. Empty until first set. */ nickname: string; phoneticName: string; /** Opaque tsclientlib identity blob - null until the first successful connect generates one. */ blob: string | null; } // randomId() only exists in a secure context, so it is missing on a // plain-http origin - which is exactly how a self-hosted instance is reached // on a LAN before TLS is set up. It used to throw at module load and leave a // blank page; these ids are local identifiers, not secrets, so fall back. function randomId(): string { if (typeof crypto.randomUUID === "function") return crypto.randomUUID(); const bytes = new Uint8Array(16); crypto.getRandomValues(bytes); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join(""); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } // One-time migration from the old single flat identity key to a list of named // identities (so users can maintain more than one persona), and to seed a // default entry for users who never had one either. Runs once at module load. (function ensureIdentitiesSeeded() { if (localStorage.getItem(IDENTITIES_KEY) !== null) return; const legacyBlob = localStorage.getItem(IDENTITY_KEY); const legacyNickname = localStorage.getItem(LAST_NICKNAME_KEY) ?? ""; const id = randomId(); const identities: Identity[] = [ { id, name: "Standard", nickname: legacyNickname, phoneticName: "", blob: legacyBlob }, ]; localStorage.setItem(IDENTITIES_KEY, JSON.stringify(identities)); localStorage.setItem(ACTIVE_IDENTITY_KEY, id); localStorage.removeItem(IDENTITY_KEY); })(); function loadIdentities(): Identity[] { try { const raw = localStorage.getItem(IDENTITIES_KEY); const parsed = raw ? (JSON.parse(raw) as Partial[]) : []; if (parsed.length > 0) { // Backfill fields older saves (before per-identity nickname/phonetic // name existed) don't have. return parsed.map((i) => ({ id: i.id ?? randomId(), name: i.name ?? "Standard", nickname: i.nickname ?? "", phoneticName: i.phoneticName ?? "", blob: i.blob ?? null, })); } } catch { // fall through } return [{ id: randomId(), name: "Standard", nickname: "", phoneticName: "", blob: null }]; } const FAVORITES_KEY = "webspeak3:favorites"; const INPUT_DEVICE_KEY = "webspeak3:input-device"; const PLAYBACK_VOLUME_KEY = "webspeak3:playback-volume"; const NOISE_SUPPRESSION_KEY = "webspeak3:noise-suppression"; const ECHO_CANCELLATION_KEY = "webspeak3:echo-cancellation"; const AUTO_GAIN_CONTROL_KEY = "webspeak3:auto-gain-control"; const AUTO_VOLUME_KEY = "webspeak3:auto-volume"; const OWN_MIC_CLICKS_KEY = "webspeak3:own-mic-clicks"; const OTHER_MIC_CLICKS_KEY = "webspeak3:other-mic-clicks"; const AEC3_ENABLED_KEY = "webspeak3:aec3-enabled"; const VAD_HANGOVER_KEY = "webspeak3:vad-hangover"; const PUSH_TO_TALK_KEY = "webspeak3:push-to-talk"; const CONTINUOUS_KEY = "webspeak3:continuous-transmission"; const TYPING_ATTENUATION_KEY = "webspeak3:typing-attenuation"; const PTT_BINDING_KEY = "webspeak3:ptt-key"; const DESIGN_THEME_KEY = "webspeak3:design-theme"; // The user's actual pick - "standard" | "nova" | "pulse" | "ide" | "custom:". // DESIGN_THEME_KEY above keeps tracking just the resolved structural base, since a // couple of early call sites (e.g. the host-field default below) need that cheaply, // before customThemes is loaded. const DESIGN_SELECTION_KEY = "webspeak3:design-selection"; const CUSTOM_THEMES_KEY = "webspeak3:custom-themes"; type DesignTheme = "standard" | "nova" | "pulse" | "ide"; /** A user-authored theme package: a name, which built-in layout it behaves like * (Standard's plain chrome, Nova's collapsed menu/splash, Pulse's card/sidebar * layout or IDE), and raw CSS that gets injected while it's * active - free-form, so it can restyle or even reflow the existing markup * (e.g. via flex `order`, `display:none`, overlays). */ type CustomTheme = { id: string; name: string; baseTheme: DesignTheme; css: string; }; /** Metadata for one theme listed by GET /api/store/themes - deliberately * without `css`, so browsing the store doesn't pull every submission's full * stylesheet up front. The full package (matching CustomTheme's export * shape) is fetched separately per-id on install, see STORE_URL above. */ type StoreThemeSummary = { id: string; name: string; baseTheme: DesignTheme; author: string; description: string; hasScreenshot: boolean; rating: { average: number; count: number }; createdAt: string; }; // The operator's own admin token for publishing under a reserved author name // (see STORE_RESERVED_AUTHORS in gateway/src/index.ts) - kept in localStorage // so it only has to be entered once per browser, same idea as the last-used // connection fields above. const STORE_ADMIN_TOKEN_KEY = "webspeak3:store-admin-token"; // Mirrors the gateway's STORE_SCREENSHOT_MAX_DATA_URL_LENGTH - checked client-side // too so a rejected upload doesn't cost a round trip. const STORE_SCREENSHOT_MAX_DATA_URL_LENGTH = 400_000; function isDesignTheme(value: string): value is DesignTheme { return ( value === "standard" || value === "nova" || value === "pulse" || value === "ide" ); } function loadDesignTheme(): DesignTheme { const raw = localStorage.getItem(DESIGN_THEME_KEY); if (raw && isDesignTheme(raw)) return raw; return "standard"; } function resolveDesignThemeBase(selection: string, customThemes: CustomTheme[]): DesignTheme { if (selection.startsWith("custom:")) { // A removed base (e.g. the old GreenTeaSpeak theme) falls back to Standard. const base = customThemes.find((th) => `custom:${th.id}` === selection)?.baseTheme; return base && isDesignTheme(base) ? base : "standard"; } return isDesignTheme(selection) ? selection : "standard"; } function designThemeClassName(theme: DesignTheme): string { if (theme === "nova") return " ts-design-nova"; if (theme === "pulse") return " ts-design-pulse"; if (theme === "ide") return " ts-design-ide"; return ""; } function designThemeLabel(theme: DesignTheme, t: (key: string) => string): string { if (theme === "nova") return t("design.theme.nova"); if (theme === "pulse") return t("design.theme.pulse"); if (theme === "ide") return t("design.theme.ide"); return t("design.theme.standard"); } function loadCustomThemes(): CustomTheme[] { try { const raw = localStorage.getItem(CUSTOM_THEMES_KEY); if (!raw) return []; const parsed = JSON.parse(raw); if (!Array.isArray(parsed)) return []; return parsed.filter( (v): v is CustomTheme => v && typeof v.id === "string" && typeof v.name === "string" && isDesignTheme(v.baseTheme) && typeof v.css === "string" ); } catch { return []; } } function saveCustomThemes(list: CustomTheme[]) { localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(list)); } function loadDesignSelection(): string { const raw = localStorage.getItem(DESIGN_SELECTION_KEY); // A removed builtin (e.g. "greenteaspeak") falls back to Standard. return raw && (raw.startsWith("custom:") || isDesignTheme(raw)) ? raw : loadDesignTheme(); } function loadBoolPref(key: string, fallback: boolean): boolean { const raw = localStorage.getItem(key); return raw === null ? fallback : raw === "1"; } interface PttBinding { code: string; label: string; } function loadPttBinding(): PttBinding | null { try { const v = JSON.parse(localStorage.getItem(PTT_BINDING_KEY) ?? "null"); return v && typeof v.code === "string" && typeof v.label === "string" ? v : null; } catch { return null; } } function keyBindingLabel(e: KeyboardEvent): string { return e.key.length === 1 && e.key !== " " ? e.key.toUpperCase() : e.code; } function isTypingTarget(target: EventTarget | null): boolean { const el = target as HTMLElement | null; return !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)); } function loadNumberPref(key: string, fallback: number): number { const raw = localStorage.getItem(key); const parsed = raw === null ? NaN : Number(raw); return Number.isFinite(parsed) ? parsed : fallback; } interface Favorite { id: string; bookmarkName: string; nickname: string; host: string; serverPassword: string; defaultChannel: string; defaultChannelPassword: string; /** When true, ServerQuery clients appear in the channel tree. Default: false. */ showServerQueryClients: boolean; /** Overrides Options -> Meldungen's sound pack for this server; unset = that one. */ soundPack?: string; } function normalizeFavorite(raw: Partial & Pick): Favorite { return { id: raw.id, bookmarkName: typeof raw.bookmarkName === "string" ? raw.bookmarkName : "", nickname: typeof raw.nickname === "string" ? raw.nickname : "", host: typeof raw.host === "string" ? raw.host : "", serverPassword: typeof raw.serverPassword === "string" ? raw.serverPassword : "", defaultChannel: typeof raw.defaultChannel === "string" ? raw.defaultChannel : "", defaultChannelPassword: typeof raw.defaultChannelPassword === "string" ? raw.defaultChannelPassword : "", showServerQueryClients: raw.showServerQueryClients === true, ...(typeof raw.soundPack === "string" && raw.soundPack ? { soundPack: raw.soundPack } : {}), }; } function loadFavorites(): Favorite[] { try { const raw = localStorage.getItem(FAVORITES_KEY); if (!raw) return []; const parsed = JSON.parse(raw); if (!Array.isArray(parsed)) return []; return parsed .filter((v): v is Partial & Pick => v && typeof v.id === "string") .map(normalizeFavorite); } catch { return []; } } // Only Chromium hands out tab/system audio via getDisplayMedia; Firefox and // Safari return video only, so the button would just say "no audio" there. // userAgentData itself only exists in Chromium-based browsers. // Switched off for now (2026-10-03): clicks in the mix, and Edge delivers // Windows system audio as silence. Code stays; flip back once that's solved. const TAB_AUDIO_SUPPORTED = false && typeof navigator.mediaDevices?.getDisplayMedia === "function" && !!(navigator as Navigator & { userAgentData?: { brands: { brand: string }[] } }).userAgentData?.brands.some( (b) => b.brand === "Chromium" ); const AWAY_PRESETS_KEY = "webspeak3:away-presets"; /** "off" hides the server banner: it loads from whatever host the server * admin picked, which then sees the viewer's IP (review S12). */ const SERVER_BANNER_KEY = "webspeak3:server-banner"; const IDE_PIXEL_FONT_KEY = "webspeak3:ide-pixel-font"; // Off by default: an inline chat image loads from whatever host the sender picked. const CHAT_IMAGES_KEY = "webspeak3:chat-images"; const WHISPER_SETTINGS_KEY = "webspeak3:whisper-settings"; /** Options -> Whispern (TS3's "Whispereinstellungen"). */ interface WhisperSettings { /** allow/block: what applies to contacts without their own whisper setting. */ mode: "allow" | "block" | "blockAll"; sound: boolean; openHistory: boolean; /** Incoming entries leave the whisper history after this many minutes; 0 = never. */ clearAfterMin: number; } const DEFAULT_WHISPER_SETTINGS: WhisperSettings = { mode: "allow", sound: true, openHistory: true, clearAfterMin: 5 }; function loadWhisperSettings(): WhisperSettings { try { return { ...DEFAULT_WHISPER_SETTINGS, ...JSON.parse(localStorage.getItem(WHISPER_SETTINGS_KEY) ?? "{}") }; } catch { return DEFAULT_WHISPER_SETTINGS; } } const APP_SETTINGS_KEY = "webspeak3:app-settings"; /** Options -> Anwendung. Read on use, so the socket handlers need no refs. */ interface AppSettings { micOnServerSwitch: boolean; reconnectAfterSleep: boolean; middleClickQuickAccess: boolean; updateFavoriteNickname: boolean; autoOpenChannelChat: boolean; mutedTalkingSound: boolean; neverShowPokeDialog: boolean; } const DEFAULT_APP_SETTINGS: AppSettings = { micOnServerSwitch: true, reconnectAfterSleep: true, middleClickQuickAccess: true, updateFavoriteNickname: false, autoOpenChannelChat: false, mutedTalkingSound: false, neverShowPokeDialog: false, }; function loadAppSettings(): AppSettings { try { return { ...DEFAULT_APP_SETTINGS, ...JSON.parse(localStorage.getItem(APP_SETTINGS_KEY) ?? "{}") }; } catch { return DEFAULT_APP_SETTINGS; } } const SECURITY_SETTINGS_KEY = "webspeak3:security-settings"; const CHANNEL_PASSWORDS_KEY = "webspeak3:channel-passwords"; /** Options -> Sicherheit. */ interface SecuritySettings { saveChannelPasswords: boolean; clearCacheOnExit: boolean; clearUrlsOnExit: boolean; } const DEFAULT_SECURITY_SETTINGS: SecuritySettings = { saveChannelPasswords: false, clearCacheOnExit: false, clearUrlsOnExit: false, }; function loadSecuritySettings(): SecuritySettings { try { return { ...DEFAULT_SECURITY_SETTINGS, ...JSON.parse(localStorage.getItem(SECURITY_SETTINGS_KEY) ?? "{}") }; } catch { return DEFAULT_SECURITY_SETTINGS; } } /** Saved channel passwords: server host -> channel id -> password. */ function loadChannelPasswords(): Record> { try { return JSON.parse(localStorage.getItem(CHANNEL_PASSWORDS_KEY) ?? "{}"); } catch { return {}; } } function storedChannelPassword(host: string, channelId: number): string | undefined { return loadChannelPasswords()[host.trim().toLowerCase()]?.[channelId]; } /** null removes the entry. */ function storeChannelPassword(host: string, channelId: number, password: string | null): void { const all = loadChannelPasswords(); const key = host.trim().toLowerCase(); const server = { ...all[key] }; if (password === null) delete server[channelId]; else server[channelId] = password; all[key] = server; localStorage.setItem(CHANNEL_PASSWORDS_KEY, JSON.stringify(all)); } /** The service worker's CacheStorage; the app shell comes from the network until the worker refills it. */ async function clearBrowserCaches(): Promise { try { await Promise.all((await caches.keys()).map((key) => caches.delete(key))); } catch { // No CacheStorage (insecure context): nothing to clear. } } const TREE_OPTIONS_KEY = "webspeak3:tree-options"; /** Design tab -> "Channel Baum" and "GIF Animation" (TS3's options). */ interface TreeOptions { expandMode: "all" | "own"; /** Channel levels to expand with expandMode "all"; 0 = every level. */ expandDepth: number; clientsBelow: boolean; flags: boolean; groupIconsInMenus: boolean; commanderLamp: boolean; awayMessage: boolean; tooltips: boolean; animateAvatars: boolean; animateImages: boolean; } const DEFAULT_TREE_OPTIONS: TreeOptions = { expandMode: "all", expandDepth: 0, clientsBelow: false, flags: true, groupIconsInMenus: true, commanderLamp: false, awayMessage: true, tooltips: true, animateAvatars: true, animateImages: true, }; function loadTreeOptions(): TreeOptions { try { return { ...DEFAULT_TREE_OPTIONS, ...JSON.parse(localStorage.getItem(TREE_OPTIONS_KEY) ?? "{}") }; } catch { return DEFAULT_TREE_OPTIONS; } } /** Display prefs read deep in the tree; a context spares threading them through every level. */ const DisplayPrefsContext = createContext<{ tree: TreeOptions; setTree: (next: TreeOptions) => void; iconPacks: IconPack[]; iconPackId: string; setIconPackId: (id: string) => void; saveIconPacks: (packs: IconPack[]) => void; whisper: WhisperSettings; setWhisper: (next: WhisperSettings) => void; downloads: DownloadSettings; setDownloads: (next: DownloadSettings) => void; downloadDir: FileSystemDirectoryHandle | null; setDownloadDir: (dir: FileSystemDirectoryHandle | null) => void; chat: ChatSettings; setChat: (next: ChatSettings) => void; security: SecuritySettings; setSecurity: (next: SecuritySettings) => void; }>({ tree: DEFAULT_TREE_OPTIONS, setTree: () => {}, iconPacks: [], iconPackId: "", setIconPackId: () => {}, saveIconPacks: () => {}, whisper: DEFAULT_WHISPER_SETTINGS, setWhisper: () => {}, downloads: DEFAULT_DOWNLOAD_SETTINGS, setDownloads: () => {}, downloadDir: null, setDownloadDir: () => {}, chat: DEFAULT_CHAT_SETTINGS, setChat: () => {}, security: DEFAULT_SECURITY_SETTINGS, setSecurity: () => {}, }); const DISCONNECT_MESSAGE_KEY = "webspeak3:disconnect-message"; const COLLECTED_URLS_KEY = "webspeak3:collected-urls"; interface CollectedUrl { url: string; count: number; lastSeen: number; lastSender: string; } function loadCollectedUrls(): CollectedUrl[] { try { const raw = localStorage.getItem(COLLECTED_URLS_KEY); return raw ? (JSON.parse(raw) as CollectedUrl[]) : []; } catch { return []; } } type LogLevel = "critical" | "error" | "warning" | "info" | "debug"; interface ClientLogEntry { id: number; timestamp: number; category: string; level: LogLevel; message: string; } const LOG_LEVELS: LogLevel[] = ["critical", "error", "warning", "info", "debug"]; const MAX_LOG_ENTRIES = 500; interface WhisperLogEntry { id: number; timestamp: number; description: string; /** Someone whispered to us (as opposed to our own whisper target changes). */ incoming?: boolean; } interface BanListEntry { banId: number; ip: string; name: string; uid: string; lastNickname: string; created: string; durationSecs: number; invokerName: string; reason: string; enforcements: number; } interface ComplainListEntry { targetClientDbId: number; targetName: string; fromClientDbId: number; fromName: string; message: string; timestamp: string; } interface OfflineMessageListEntry { messageId: number; clientUid: string; subject: string; timestamp: string; isRead: boolean; } type ContactCategory = "acquaintance" | "blocked" | "friend"; interface Contact { uid: string; customName: string; category: ContactCategory; phoneticName: string; ignored: boolean; /** Incoming whispers from this contact; unset follows Options -> Whispern. */ whisper?: "allow" | "block"; } const CONTACTS_KEY = "webspeak3:contacts"; // Per-speaker playback volume by client UID (1 = unchanged), mixed in the // connector. Keyed by UID so it follows a person across servers and reconnects. const CLIENT_VOLUMES_KEY = "webspeak3:client-volumes"; function loadClientVolumes(): Record { try { const raw = localStorage.getItem(CLIENT_VOLUMES_KEY); return raw ? (JSON.parse(raw) as Record) : {}; } catch { return {}; } } function loadContacts(): Contact[] { try { const raw = localStorage.getItem(CONTACTS_KEY); return raw ? (JSON.parse(raw) as Contact[]) : []; } catch { return []; } } interface MessagePreset { name: string; message: string; } /** A saved whisper target selection. Channels/clients are matched by name when * activated (rather than by id), since ids are only stable for the current * connection - the same names are what a user would recognize across sessions. */ interface WhisperList { id: string; name: string; channelNames: string[]; clientNames: string[]; } const WHISPER_LISTS_KEY = "webspeak3:whisper-lists"; function loadWhisperLists(): WhisperList[] { try { const raw = localStorage.getItem(WHISPER_LISTS_KEY); return raw ? (JSON.parse(raw) as WhisperList[]) : []; } catch { return []; } } function loadAwayPresets(): MessagePreset[] { try { const raw = localStorage.getItem(AWAY_PRESETS_KEY); if (!raw) return []; const parsed = JSON.parse(raw) as unknown; if (!Array.isArray(parsed)) return []; // Older versions stored presets as plain strings (name == message) - migrate on read. return parsed.map((p) => (typeof p === "string" ? { name: p, message: p } : (p as MessagePreset))); } catch { return []; } } function saveAwayPresets(presets: MessagePreset[]): void { localStorage.setItem(AWAY_PRESETS_KEY, JSON.stringify(presets)); } function loadDisconnectMessage(): string { return localStorage.getItem(DISCONNECT_MESSAGE_KEY) ?? ""; } function saveDisconnectMessage(message: string): void { localStorage.setItem(DISCONNECT_MESSAGE_KEY, message); } type LogEntry = { text: string; kind: "info" | "error" }; interface ChannelInfo { id: number; parent: number; order: number; name: string; topic: string; codec: string; maxClients: number | null; hasPassword: boolean; } type SelectedItem = | { type: "server" } | { type: "channel"; id: number } | { type: "client"; id: number }; interface ClientInfo { id: number; channel: number; name: string; inputMuted: boolean; outputMuted: boolean; inputHardwareEnabled: boolean; away: boolean; awayMessage: string; isChannelCommander: boolean; country: string; uid: string; databaseId: number; channelGroup: number; serverGroups: number[]; hasTalkPower: boolean; /** TS6 Stream/Call broadcast running; absent on servers that don't report it. */ isStreaming?: boolean; /** ServerQuery client; filtered from the tree unless a favorite enables them. */ isQuery?: boolean; /** MD5 of the avatar, empty without one; missing from gateways before v0.15. */ avatarHash?: string; } interface GroupEntry { id: number; name: string; iconId: number; } interface PermissionOverviewEntry { name: string; description: string; value: number; negated: boolean; skip: boolean; } interface FileListEntry { path: string; name: string; size: number; isFile: boolean; timestamp: string; } interface PermissionCatalogEntry { id: number; name: string; description: string; } type PermScope = "server" | "channelgroup" | "channel" | "client" | "channelclient"; interface ClientConnectionInfoData { clientId: number; pingMs: number | null; connectedSecs: number | null; ip: string | null; packetsSent: number; bytesSent: number; packetsReceived: number; bytesReceived: number; packetLossPercent: number; } interface ServerConnectionInfoData { pingMs: number; connectedSecs: number; packetLossPercent: number; packetsSentTotal: number; bytesSentTotal: number; packetsReceivedTotal: number; bytesReceivedTotal: number; bandwidthSentLastSecond: number; bandwidthReceivedLastSecond: number; bandwidthSentLastMinute: number; bandwidthReceivedLastMinute: number; filetransferBandwidthSent: number; filetransferBandwidthReceived: number; filetransferBytesSent: number; filetransferBytesReceived: number; } function formatBytes(bytes: number): string { if (!Number.isFinite(bytes) || bytes < 0) return "0 B"; if (bytes < 1024) return `${Math.round(bytes)} B`; const units = ["KB", "MB", "GB", "TB"]; let value = bytes / 1024; let unitIndex = 0; while (value >= 1024 && unitIndex < units.length - 1) { value /= 1024; unitIndex++; } return `${value.toFixed(1)} ${units[unitIndex]}`; } /** Compact counts like GreenTeaSpeak (`772.92 k`) — avoids DE locale `772.920`. */ function formatCount(value: number): string { if (!Number.isFinite(value) || value < 0) return "0"; if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(2)} M`; if (value >= 1_000) return `${(value / 1_000).toFixed(2)} k`; return value.toFixed(value % 1 === 0 ? 0 : 2); } function formatRate(bytesPerSec: number): string { return `${formatBytes(bytesPerSec)}/s`; } /** Turns a base64-encoded file (as delivered by the "fileDownloadData" event) * into an actual browser download, without ever round-tripping through the * gateway's HTTP surface - it's all-in-memory via a Blob + object URL. */ function triggerBrowserDownload(filename: string, base64Data: string): void { downloadBlob(base64Blob(base64Data), filename); } function base64Blob(base64Data: string): Blob { const binary = atob(base64Data); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); return new Blob([bytes]); } /** One entry of the file transfer window (Options -> Download queue/limits). */ interface Transfer { id: number; dir: "up" | "down"; cid: number; path: string; name: string; size: number; done: number; status: "queued" | "running" | "done" | "error"; /** Downloads: picked at click time. */ target?: SaveTarget; /** Uploads. */ file?: File; } function FileTransfersWindow({ transfers, onClearFinished, onClose, }: { transfers: Transfer[]; onClearFinished: () => void; onClose: () => void; }) { const t = useT(); return (
{t("transfers.title")}
{transfers.length === 0 ? (

{t("transfers.empty")}

) : ( {transfers.map((x) => ( ))}
{x.dir === "down" ? "⬇" : "⬆"} {x.name} {formatBytes(x.done)} / {formatBytes(x.size)} {t(`transfers.status.${x.status}`)}
)}
); } function downloadBlob(blob: Blob, filename: string) { const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); // Revoking right after click() can cancel the download in some browsers. setTimeout(() => URL.revokeObjectURL(url), 60_000); } function formatDurationSecs(totalSeconds: number): string { const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = Math.floor(totalSeconds % 60); const pad = (n: number) => String(n).padStart(2, "0"); return hours > 0 ? `${hours}:${pad(minutes)}:${pad(seconds)}` : `${minutes}:${pad(seconds)}`; } /** Converts an ISO 3166-1 alpha-2 country code (e.g. "DE") to its flag emoji * via Unicode regional indicator symbols. Returns null for codes the server * doesn't report (empty string - common when geo-IP isn't configured). */ function countryFlag(code: string): string | null { if (!/^[A-Za-z]{2}$/.test(code)) return null; const codePoints = [...code.toUpperCase()].map((c) => 0x1f1e6 + c.charCodeAt(0) - 65); return String.fromCodePoint(...codePoints); } function ChannelIcon() { return ( ); } /** GTS2-style talk lamp: blue idle / green talking / muted mic. */ /** Red "off" badge in the lamp's bottom-right corner, shared by the mute icons. */ const OFF_BADGE = ( <> ); /** The status slot in front of a client's name. Like the native client, away * and mute replace the talk dot instead of being listed after the name. * Order as in TeamSpeak: away, sound muted, mic muted, talking/idle. */ function TalkLamp({ talking, inputMuted, inputHardwareEnabled, outputMuted = false, away = false, commander = false, }: { talking: boolean; inputMuted: boolean; inputHardwareEnabled: boolean; outputMuted?: boolean; away?: boolean; /** Channel commander: drawn as its own lamp when the design option asks for it. */ commander?: boolean; }) { const t = useT(); const { tree } = useContext(DisplayPrefsContext); const muted = inputMuted || !inputHardwareEnabled; const asCommander = commander && tree.commanderLamp; const icon = (title: string, packIcon: string, paths: React.ReactNode) => ( ); if (away) { return icon( t("tree.away"), "away", ); } if (outputMuted) { return icon( t("tree.soundMuted"), "soundMuted", <> {OFF_BADGE} ); } if (muted) { return icon( t("tree.micMuted"), inputMuted ? "micMuted" : "hardwareMicMuted", <> {OFF_BADGE} ); } if (talking) { return (