import { useEffect, useRef, useState } from "react"; import "./App.css"; /** Only dismiss on a genuine backdrop click, not a text-selection drag that * starts inside the dialog and releases over the backdrop. */ function useBackdropDismiss(onDismiss: () => void) { const mouseDownOnBackdrop = useRef(false); return { onMouseDown: (e: React.MouseEvent) => { mouseDownOnBackdrop.current = e.target === e.currentTarget; }, onClick: (e: React.MouseEvent) => { if (mouseDownOnBackdrop.current && e.target === e.currentTarget) onDismiss(); }, }; } import { AudioPlayer, MicCapture, SAMPLE_RATE, encodeWavStereo, hasNativeOutputPicker, listAudioInputDevices, listAudioOutputDevices, pickAudioOutputDevice, } from "./voice"; import { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n"; import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode"; import { SOUND_EVENTS, clearCustomSound, loadCustomSound, loadEventSoundEnabled, loadSoundsEnabled, loadSoundsVolume, playSound, saveCustomSound, saveEventSoundEnabled, saveSoundsEnabled, saveSoundsVolume, setSoundsOutputDevice, type SoundEventId, } from "./sounds"; import { parseSoundpack } from "./soundpack"; // In dev, the gateway runs standalone on its own port. In production it's // served from the same origin/port as the web app (single container behind a // reverse proxy), so derive the WebSocket URL from the current location. const GATEWAY_URL = import.meta.env.DEV ? "ws://localhost:8080" : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`; // 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"; /** 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; /** Opaque tsclientlib identity blob - null until the first successful connect generates one. */ blob: string | null; } // 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 id = crypto.randomUUID(); const identities: Identity[] = [{ id, name: "Standard", 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 Identity[]) : []; if (parsed.length > 0) return parsed; } catch { // fall through } return [{ id: crypto.randomUUID(), name: "Standard", 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 VAD_HANGOVER_KEY = "webspeak3:vad-hangover"; function loadBoolPref(key: string, fallback: boolean): boolean { const raw = localStorage.getItem(key); return raw === null ? fallback : raw === "1"; } 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; } function loadFavorites(): Favorite[] { try { const raw = localStorage.getItem(FAVORITES_KEY); return raw ? (JSON.parse(raw) as Favorite[]) : []; } catch { return []; } } const AWAY_PRESETS_KEY = "webspeak3:away-presets"; 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 []; } } const URL_REGEX = /https?:\/\/[^\s<>"]+/g; 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; } type ContactCategory = "acquaintance" | "blocked" | "friend"; interface Contact { uid: string; customName: string; category: ContactCategory; phoneticName: string; ignored: boolean; } const CONTACTS_KEY = "webspeak3:contacts"; 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 }; interface ClientInfo { id: number; channel: number; name: string; inputMuted: boolean; outputMuted: boolean; inputHardwareEnabled: boolean; away: boolean; awayMessage: string; isChannelCommander: boolean; country: string; uid: string; } 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; } function formatBytes(bytes: number): string { if (bytes < 1024) return `${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]}`; } 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 ( ); } function ClientIcon() { return ( ); } function ClientStatusIcons({ client }: { client: ClientInfo }) { const t = useT(); return ( {client.isChannelCommander && ⭐} {client.away && 💤} {(client.inputMuted || !client.inputHardwareEnabled) && 🔇} {client.outputMuted && 🔕} ); } function ServerIcon() { return ( ); } function ChannelTree({ channels, clients, parent, ownClientId, talkers, selected, onSelectItem, onSwitchChannel, onOpenPrivateChat, onPokeClient, onClientContextMenu, }: { channels: ChannelInfo[]; clients: ClientInfo[]; parent: number; ownClientId: number | null; talkers: Set; selected: SelectedItem | null; onSelectItem: (item: SelectedItem) => void; onSwitchChannel: (channelId: number) => void; onOpenPrivateChat: (clientId: number, clientName: string) => void; onPokeClient: (clientId: number, clientName: string) => void; onClientContextMenu: (e: React.MouseEvent, clientId: number, clientName: string, isSelf: boolean) => void; }) { const t = useT(); const children = channels.filter((c) => c.parent === parent).sort((a, b) => a.order - b.order); if (children.length === 0) return null; return (
    {children.map((channel) => (
  • onSelectItem({ type: "channel", id: channel.id })} onDoubleClick={() => onSwitchChannel(channel.id)} title={t("tree.clickToSelect")} > {channel.name} {channel.hasPassword && 🔒}
      {clients .filter((c) => c.channel === channel.id) .map((c) => (
    • onOpenPrivateChat(c.id, c.name)} onContextMenu={(e) => onClientContextMenu(e, c.id, c.name, c.id === ownClientId)} title={c.id === ownClientId ? undefined : `${t("tree.privateChatWith")} ${c.name}`} > {countryFlag(c.country) && {countryFlag(c.country)}} {c.name} {c.away && c.awayMessage && ( ({c.awayMessage}) )} {c.id !== ownClientId && ( )}
    • ))}
  • ))}
); } function InfoPanel({ selected, host, serverName, serverMaxClients, serverVersion, serverLicense, totalClientCount, channels, clients, onShowServerConnectionInfo, onEditServer, }: { selected: SelectedItem | null; host: string; serverName: string; serverMaxClients: number; serverVersion: string; serverLicense: string; totalClientCount: number; channels: ChannelInfo[]; clients: ClientInfo[]; onShowServerConnectionInfo: () => void; onEditServer: () => void; }) { const t = useT(); if (!selected || selected.type === "server") { return (
{serverName || host}
{t("info.address")} {host}
{serverVersion && (
{t("info.version")} {serverVersion}
)} {serverLicense && (
{t("info.license")} {serverLicense}
)}
{t("info.currentClients")} {totalClientCount} / {serverMaxClients || "∞"}
{t("info.currentChannels")} {channels.length}
); } const channel = channels.find((c) => c.id === selected.id); if (!channel) return
; const clientCount = clients.filter((c) => c.channel === channel.id).length; return (
{channel.name}
{channel.topic && (
{t("info.topic")} {channel.topic}
)}
{t("info.audioCodec")} {channel.codec}
{t("info.passwordProtected")} {channel.hasPassword ? t("info.yes") : t("info.no")}
{t("info.clients")} {clientCount} / {channel.maxClients ?? "∞"}
); } interface ChatEntry { from: string; message: string; /** Set for server-log notifications (join/leave/switch/etc.) so they render * without a "from:" prefix, like the native client's server tab. */ isLog?: boolean; } interface PmMessage { fromSelf: boolean; message: string; } interface PmThread { partnerId: number; partnerName: string; messages: PmMessage[]; unread: boolean; } type ActiveTab = "channel" | "server" | number; interface PokeNotice { id: number; from: string; message: string; } function ConnectDialog({ host, nickname, serverPassword, channelPassword, defaultChannel, expanded, connecting, identities, activeIdentityId, onHostChange, onNicknameChange, onServerPasswordChange, onChannelPasswordChange, onDefaultChannelChange, onActiveIdentityChange, onToggleExpanded, onConnect, onCancel, }: { host: string; nickname: string; serverPassword: string; channelPassword: string; defaultChannel: string; expanded: boolean; connecting: boolean; identities: Identity[]; activeIdentityId: string | null; onHostChange: (v: string) => void; onNicknameChange: (v: string) => void; onServerPasswordChange: (v: string) => void; onChannelPasswordChange: (v: string) => void; onDefaultChannelChange: (v: string) => void; onActiveIdentityChange: (id: string) => void; onToggleExpanded: () => void; onConnect: () => void; onCancel: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onCancel); return (
e.stopPropagation()}>
{t("connect.title")}
{expanded && (
)}
); } function FavoritesDialog({ favorites, prefillNew, onSave, onClose, }: { favorites: Favorite[]; prefillNew?: Omit; onSave: (favorites: Favorite[]) => void; onClose: () => void; }) { const t = useT(); const pendingNewRef = useRef( prefillNew ? { id: crypto.randomUUID(), bookmarkName: prefillNew.host || t("favorites.newFavoriteName"), ...prefillNew, } : null ); const [draft, setDraft] = useState(() => pendingNewRef.current ? [...favorites, pendingNewRef.current] : favorites.map((f) => ({ ...f })) ); const [selectedId, setSelectedId] = useState(() => pendingNewRef.current ? pendingNewRef.current.id : (favorites[0]?.id ?? null) ); const selected = draft.find((f) => f.id === selectedId) ?? null; const updateSelected = (patch: Partial) => { if (!selectedId) return; setDraft((prev) => prev.map((f) => (f.id === selectedId ? { ...f, ...patch } : f))); }; const handleNewFavorite = () => { const nf: Favorite = { id: crypto.randomUUID(), bookmarkName: t("favorites.newFavoriteName"), nickname: "", host: "", serverPassword: "", defaultChannel: "", defaultChannelPassword: "", }; setDraft((prev) => [...prev, nf]); setSelectedId(nf.id); }; const handleRemove = () => { if (!selectedId) return; setDraft((prev) => prev.filter((f) => f.id !== selectedId)); setSelectedId(null); }; const backdrop = useBackdropDismiss(onClose); return (
e.stopPropagation()}>
{t("favorites.title")}
{t("favorites.synced")}
{t("favorites.notLoggedIn")}
{t("favorites.local")}
    {draft.map((f) => (
  • setSelectedId(f.id)} > {f.bookmarkName || t("favorites.unnamed")}
  • ))}
); } function CollectedUrlsDialog({ urls, onClear, onClose, }: { urls: CollectedUrl[]; onClear: () => void; onClose: () => void; }) { const t = useT(); const [search, setSearch] = useState(""); const backdrop = useBackdropDismiss(onClose); const filtered = urls .filter((u) => u.url.toLowerCase().includes(search.toLowerCase())) .sort((a, b) => b.lastSeen - a.lastSeen); return (
e.stopPropagation()}>
{t("collectedUrls.title")}
{filtered.map((u) => ( ))}
{t("collectedUrls.url")} {t("collectedUrls.count")} {t("collectedUrls.lastSeen")} {t("collectedUrls.mentionedBy")}
{u.url} {u.count} {new Date(u.lastSeen).toLocaleString()} {u.lastSender}
); } function InviteFriendDialog({ host, channelId, onClose, }: { host: string; channelId: number | null; onClose: () => void; }) { const t = useT(); const [includeChannel, setIncludeChannel] = useState(false); const [copied, setCopied] = useState(false); const backdrop = useBackdropDismiss(onClose); const link = `ts3server://${host}${includeChannel && channelId !== null ? `?channel=${channelId}` : ""}`; return (
e.stopPropagation()}>
{t("inviteFriend.title")}
); } function ClientLogDialog({ entries, onClose }: { entries: ClientLogEntry[]; onClose: () => void }) { const t = useT(); const [enabledLevels, setEnabledLevels] = useState>(new Set(LOG_LEVELS)); const [search, setSearch] = useState(""); const [filter, setFilter] = useState(""); const [caseSensitive, setCaseSensitive] = useState(false); const backdrop = useBackdropDismiss(onClose); const listRef = useRef(null); const toggleLevel = (level: LogLevel) => { setEnabledLevels((prev) => { const next = new Set(prev); if (next.has(level)) next.delete(level); else next.add(level); return next; }); }; const matches = (message: string, needle: string) => caseSensitive ? message.includes(needle) : message.toLowerCase().includes(needle.toLowerCase()); const visible = entries .filter((e) => enabledLevels.has(e.level)) .filter((e) => !filter || matches(e.message, filter)); const handleMark = () => { if (!search) return; const idx = visible.findIndex((e) => matches(e.message, search)); if (idx >= 0) { const row = listRef.current?.querySelector(`[data-log-id="${visible[idx].id}"]`); row?.scrollIntoView({ block: "center" }); } }; return (
e.stopPropagation()}>
{t("clientLog.title")}
{LOG_LEVELS.map((level) => ( ))}
{visible.map((e) => (
{new Date(e.timestamp).toLocaleString()} {e.category} {t(`clientLog.level.${e.level}`)} {e.message}
))}
); } function ServerProtocolLogDialog({ lines, onClose, }: { lines: string[] | null; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); // The server may silently decline (e.g. missing b_virtualserver_log_view // permission) without ever replying - fall back to an error instead of // spinning forever. const [timedOut, setTimedOut] = useState(false); useEffect(() => { setTimedOut(false); if (lines) return; const id = window.setTimeout(() => setTimedOut(true), 6000); return () => window.clearTimeout(id); }, [lines]); return (
e.stopPropagation()}>
{t("serverProtocolLog.title")}
{!lines ? (
{timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")}
) : lines.length === 0 ? (
{t("serverProtocolLog.empty")}
) : (
{lines.map((line, i) => (
{line}
))}
)}
); } function WhisperHistoryDialog({ serverName, entries, onClear, onClose, }: { serverName: string; entries: WhisperLogEntry[]; onClear: () => void; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); return (
e.stopPropagation()}>
{t("whisperHistory.title", { server: serverName })}
{entries.length === 0 && (
{t("whisperHistory.empty")}
)} {entries.map((e) => (
{new Date(e.timestamp).toLocaleString()} {e.description}
))}
); } function WhisperListsDialog({ lists, hasCurrentSelection, onSave, onActivate, onDelete, onClose, }: { lists: WhisperList[]; hasCurrentSelection: boolean; onSave: (name: string) => void; onActivate: (list: WhisperList) => void; onDelete: (id: string) => void; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); const [nameDraft, setNameDraft] = useState(""); const handleSave = () => { const name = nameDraft.trim(); if (!name || !hasCurrentSelection) return; onSave(name); setNameDraft(""); }; return (
e.stopPropagation()}>
{t("whisperLists.title")}
setNameDraft(e.target.value)} />
    {lists.map((list) => (
  • {list.name} {t("whisperLists.itemDetail", { channels: String(list.channelNames.length), clients: String(list.clientNames.length), })}
  • ))} {lists.length === 0 &&
  • {t("whisperLists.empty")}
  • }
); } function ClientConnectionInfoDialog({ clientName, info, onClose, }: { clientName: string; info: ClientConnectionInfoData | null; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); // The server may silently decline (e.g. missing permission to view another // client's connection info) without ever replying - fall back to an error // instead of spinning forever. const [timedOut, setTimedOut] = useState(false); useEffect(() => { setTimedOut(false); if (info) return; const id = window.setTimeout(() => setTimedOut(true), 6000); return () => window.clearTimeout(id); }, [info, clientName]); return (
e.stopPropagation()}>
{t("connectionInfo.clientTitle", { name: clientName })}
{!info ? (
{timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")}
) : (
{t("connectionInfo.ping")} {info.pingMs != null ? `${info.pingMs.toFixed(1)} ms` : "-"} {t("connectionInfo.connectedSince")} {info.connectedSecs != null ? formatDurationSecs(info.connectedSecs) : "-"} {t("connectionInfo.ip")} {info.ip ?? "-"} {t("connectionInfo.packetLoss")} {info.packetLossPercent.toFixed(2)}% {t("connectionInfo.packetsSent")} {info.packetsSent.toLocaleString()} {t("connectionInfo.packetsReceived")} {info.packetsReceived.toLocaleString()} {t("connectionInfo.bytesSent")} {formatBytes(info.bytesSent)} {t("connectionInfo.bytesReceived")} {formatBytes(info.bytesReceived)}
)}
); } function ServerConnectionInfoDialog({ info, onClose, }: { info: ServerConnectionInfoData | null; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); // The server may silently decline (e.g. missing b_virtualserver_connectioninfo_view // permission) without ever replying - fall back to an error instead of spinning forever. const [timedOut, setTimedOut] = useState(false); useEffect(() => { setTimedOut(false); if (info) return; const id = window.setTimeout(() => setTimedOut(true), 6000); return () => window.clearTimeout(id); }, [info]); return (
e.stopPropagation()}>
{t("connectionInfo.serverTitle")}
{!info ? (
{timedOut ? t("connectionInfo.unavailable") : t("connectionInfo.loading")}
) : (
{t("connectionInfo.ping")} {info.pingMs.toFixed(1)} ms {t("connectionInfo.connectedSince")} {formatDurationSecs(info.connectedSecs)} {t("connectionInfo.packetLoss")} {info.packetLossPercent.toFixed(2)}% {t("connectionInfo.packetsSent")} {info.packetsSentTotal.toLocaleString()} {t("connectionInfo.packetsReceived")} {info.packetsReceivedTotal.toLocaleString()} {t("connectionInfo.bytesSent")} {formatBytes(info.bytesSentTotal)} {t("connectionInfo.bytesReceived")} {formatBytes(info.bytesReceivedTotal)} {t("connectionInfo.bandwidthSent")} {formatBytes(info.bandwidthSentLastSecond)}/s {t("connectionInfo.bandwidthReceived")} {formatBytes(info.bandwidthReceivedLastSecond)}/s
)}
); } function IdentitiesDialog({ identities, activeId, onActivate, onAdd, onRename, onDelete, onClose, }: { identities: Identity[]; activeId: string | null; onActivate: (id: string) => void; onAdd: () => void; onRename: (id: string, name: string) => void; onDelete: (id: string) => void; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); return (
e.stopPropagation()}>
{t("identities.title")}
    {identities.map((identity) => (
  • onActivate(identity.id)} title={t("identities.activate")} /> onRename(identity.id, e.target.value)} /> {identity.blob ? t("identities.generated") : t("identities.pending")}
  • ))}
); } function ContactsDialog({ contacts, onlineClients, onSave, onWhisper, onShow, onClose, }: { contacts: Contact[]; onlineClients: ClientInfo[]; onSave: (contacts: Contact[]) => void; onWhisper: (clientId: number) => void; onShow: (clientId: number) => void; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); const [draft, setDraft] = useState(() => contacts.map((c) => ({ ...c }))); const [selectedUid, setSelectedUid] = useState(draft[0]?.uid ?? null); const [addClientId, setAddClientId] = useState(""); const selected = draft.find((c) => c.uid === selectedUid) ?? null; const displayName = (c: Contact) => { const online = onlineClients.find((cl) => cl.uid === c.uid); return c.customName || online?.name || c.uid; }; const updateSelected = (patch: Partial) => { if (!selectedUid) return; setDraft((prev) => prev.map((c) => (c.uid === selectedUid ? { ...c, ...patch } : c))); }; const save = (next: Contact[]) => { setDraft(next); onSave(next); }; const handleAdd = () => { const client = onlineClients.find((c) => String(c.id) === addClientId); if (!client || !client.uid || draft.some((c) => c.uid === client.uid)) return; const contact: Contact = { uid: client.uid, customName: client.name, category: "acquaintance", phoneticName: "", ignored: false, }; save([...draft, contact]); setSelectedUid(contact.uid); setAddClientId(""); }; const handleRemove = () => { if (!selectedUid) return; save(draft.filter((c) => c.uid !== selectedUid)); setSelectedUid(null); }; const addableClients = onlineClients.filter( (c) => c.uid && !draft.some((contact) => contact.uid === c.uid) ); const selectedOnlineClient = selected ? onlineClients.find((c) => c.uid === selected.uid) : undefined; return (
e.stopPropagation()}>
{t("contacts.title")}
    {draft.map((c) => (
  • setSelectedUid(c.uid)} > {onlineClients.some((cl) => cl.uid === c.uid) && } {displayName(c)} {c.ignored && " đŸšĢ"}
  • ))} {draft.length === 0 &&
  • {t("contacts.empty")}
  • }
{(["acquaintance", "blocked", "friend"] as ContactCategory[]).map((cat) => ( ))}
); } function AwayDialog({ message, presets, onMessageChange, onOk, onSaveTemplate, onCancel, }: { message: string; presets: MessagePreset[]; onMessageChange: (v: string) => void; onOk: () => void; onSaveTemplate: () => void; onCancel: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onCancel); return (
e.stopPropagation()}>
{t("away.dialog.title")}
{t("away.dialog.message")}
onMessageChange(e.target.value)} onKeyDown={(e) => e.key === "Enter" && onOk()} />
); } const OPTIONS_SECTIONS = [ { id: "anwendung", icon: "🎧" }, { id: "wiedergabe", icon: "🔊" }, { id: "aufnahme", icon: "đŸŽ™ī¸" }, { id: "sounds", icon: "🔔" }, { id: "design", icon: "đŸ–Œī¸" }, { id: "erweiterungen", icon: "🧩" }, { id: "hotkeys", icon: "âŒ¨ī¸" }, { id: "whispern", icon: "đŸ¤Ģ" }, { id: "downloads", icon: "âŦ‡ī¸" }, { id: "chat", icon: "đŸ’Ŧ" }, { id: "sicherheit", icon: "đŸ›Ąī¸" }, { id: "nachrichten", icon: "🔤" }, { id: "meldungen", icon: "â„šī¸" }, ] as const; interface AudioSettings { outputDevices: MediaDeviceInfo[]; outputDeviceId: string; onOutputDeviceChange: (id: string, label?: string) => void; onRefreshOutputDevices: () => void; playbackVolume: number; onPlaybackVolumeChange: (v: number) => void; onPlayTestTone: () => void; inputDevices: MediaDeviceInfo[]; inputDeviceId: string; onInputDeviceChange: (id: string) => void; onRefreshInputDevices: () => void; micOn: boolean; micLevelRef: React.MutableRefObject; micTestOn: boolean; onToggleMicTest: () => void; vadThreshold: number; onVadThresholdChange: (v: number) => void; vadHangover: number; onVadHangoverChange: (v: number) => void; noiseSuppressionEnabled: boolean; onToggleNoiseSuppression: () => void; echoCancellationEnabled: boolean; onToggleEchoCancellation: () => void; } function MicLevelBar({ levelRef, active }: { levelRef: React.MutableRefObject; active: boolean }) { const [level, setLevel] = useState(0); useEffect(() => { if (!active) { setLevel(0); return; } let raf = 0; const tick = () => { setLevel(levelRef.current); raf = requestAnimationFrame(tick); }; raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf); }, [active, levelRef]); const pct = Math.min(100, Math.round((level / 0.2) * 100)); return (
); } function WiedergabePanel({ audio }: { audio: AudioSettings }) { const t = useT(); const volumeDb = Math.round(20 * Math.log10(audio.playbackVolume || 0.001) * 10) / 10; return ( <>

{t("playback.title")}

{t("playback.subtitle")}

  • {t("playback.default")}
{t("playback.quiet")} {t("playback.voiceVolume")} {t("playback.loud")}
audio.onPlaybackVolumeChange(Number(e.target.value))} /> {volumeDb > 0 ? "+" : ""} {volumeDb} dB
{t("playback.options")}
); } function AufnahmePanel({ audio }: { audio: AudioSettings }) { const t = useT(); return ( <>

{t("recording.title")}

{t("recording.subtitle")}

  • {t("playback.default")}
{t("recording.activation")}
audio.onVadThresholdChange(Number(e.target.value))} />
{t("recording.dsp")}
); } function AnwendungPanel() { const t = useT(); const { langPref, setLangPref } = useLanguage(); return ( <>

{t("app.title")}

{t("app.subtitle")}

); } function SoundsPanel() { const t = useT(); const [enabled, setEnabled] = useState(() => loadSoundsEnabled()); const [volume, setVolume] = useState(() => loadSoundsVolume()); const [customNames, setCustomNames] = useState>>({}); const [eventEnabled, setEventEnabled] = useState>(() => Object.fromEntries(SOUND_EVENTS.map((id) => [id, loadEventSoundEnabled(id)])) as Record ); const fileInputRef = useRef(null); const uploadTargetRef = useRef(null); const soundpackInputRef = useRef(null); const [soundpackResult, setSoundpackResult] = useState<{ matchedCount: number; unmatchedFiles: string[]; } | null>(null); useEffect(() => { let cancelled = false; (async () => { const entries = await Promise.all( SOUND_EVENTS.map(async (id) => [id, (await loadCustomSound(id))?.name] as const) ); if (cancelled) return; const next: Partial> = {}; for (const [id, name] of entries) if (name) next[id] = name; setCustomNames(next); })(); return () => { cancelled = true; }; }, []); const handleToggleEnabled = () => { const next = !enabled; setEnabled(next); saveSoundsEnabled(next); }; const handleVolumeChange = (v: number) => { setVolume(v); saveSoundsVolume(v); }; const handleToggleEventEnabled = (event: SoundEventId) => { const next = !eventEnabled[event]; setEventEnabled((prev) => ({ ...prev, [event]: next })); saveEventSoundEnabled(event, next); }; const handleUploadClick = (event: SoundEventId) => { uploadTargetRef.current = event; fileInputRef.current?.click(); }; const handleFileSelected = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; const event = uploadTargetRef.current; e.target.value = ""; if (!file || !event) return; await saveCustomSound(event, file); setCustomNames((prev) => ({ ...prev, [event]: file.name })); }; const handleReset = async (event: SoundEventId) => { await clearCustomSound(event); setCustomNames((prev) => { const next = { ...prev }; delete next[event]; return next; }); }; const handleImportSoundpackClick = () => soundpackInputRef.current?.click(); const handleSoundpackSelected = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; e.target.value = ""; if (!file) return; setSoundpackResult(null); const { matched, unmatchedFiles } = await parseSoundpack(file); for (const [event, sound] of Object.entries(matched) as [SoundEventId, { name: string; blob: Blob }][]) { await saveCustomSound(event, new File([sound.blob], sound.name, { type: sound.blob.type })); } setCustomNames((prev) => { const next = { ...prev }; for (const [event, sound] of Object.entries(matched) as [SoundEventId, { name: string; blob: Blob }][]) { next[event] = sound.name; } return next; }); setSoundpackResult({ matchedCount: Object.keys(matched).length, unmatchedFiles }); }; return ( <>

{t("sounds.title")}

{t("sounds.subtitle")}

{t("sounds.volume")} handleVolumeChange(Number(e.target.value))} /> {Math.round(volume * 100)}%
{soundpackResult && (

{t("sounds.importResult", { matched: String(soundpackResult.matchedCount), unmatched: String(soundpackResult.unmatchedFiles.length), })}

)} {SOUND_EVENTS.map((eventId) => ( ))}
handleToggleEventEnabled(eventId)} title={t("sounds.eventEnable")} /> {t(`sounds.event.${eventId}`)} {customNames[eventId] ? t("sounds.custom", { name: customNames[eventId]! }) : t("sounds.default")} {customNames[eventId] && }
void handleFileSelected(e)} /> void handleSoundpackSelected(e)} /> ); } function NachrichtenPanel() { const t = useT(); const [presets, setPresets] = useState(() => loadAwayPresets()); const [disconnectMessage, setDisconnectMessageState] = useState(() => loadDisconnectMessage()); const [newName, setNewName] = useState(""); const [newMessage, setNewMessage] = useState(""); const handleDisconnectMessageChange = (v: string) => { setDisconnectMessageState(v); saveDisconnectMessage(v); }; const handleAdd = () => { const name = newName.trim(); const message = newMessage.trim(); if (!name || !message) return; const next = [...presets, { name, message }]; setPresets(next); saveAwayPresets(next); setNewName(""); setNewMessage(""); }; const handleDelete = (index: number) => { const next = presets.filter((_, i) => i !== index); setPresets(next); saveAwayPresets(next); }; return ( <>

{t("nachrichten.title")}

{t("nachrichten.subtitle")}

{t("nachrichten.presetsTitle")}

{presets.map((preset, index) => ( ))}
{t("nachrichten.type")} {t("nachrichten.templateName")} {t("nachrichten.message")}
{t("nachrichten.type.away")} {preset.name} {preset.message}
{t("nachrichten.type.away")} setNewName(e.target.value)} placeholder={t("nachrichten.templateName")} /> setNewMessage(e.target.value)} placeholder={t("nachrichten.message")} onKeyDown={(e) => e.key === "Enter" && handleAdd()} />
); } function OptionsDialog({ section, onSectionChange, onClose, audio, }: { section: string; onSectionChange: (id: string) => void; onClose: () => void; audio: AudioSettings; }) { const t = useT(); const active = OPTIONS_SECTIONS.find((s) => s.id === section) ?? OPTIONS_SECTIONS[0]; const backdrop = useBackdropDismiss(onClose); return (
e.stopPropagation()}>
{t("options.title")}
{OPTIONS_SECTIONS.map((s) => ( ))}
{active.id === "anwendung" ? ( ) : active.id === "wiedergabe" ? ( ) : active.id === "aufnahme" ? ( ) : active.id === "sounds" ? ( ) : active.id === "nachrichten" ? ( ) : ( <>

{t(`options.section.${active.id}`)}

{t("options.notImplemented")}

)}
); } const SERVER_EDIT_TABS = ["host", "misc", "transmission", "antiflood", "security", "log"] as const; interface ServerEditPayload { name?: string; welcomeMessage?: string; password?: string; maxClients?: number; hostmessage?: string; hostmessageMode?: string; hostbannerUrl?: string; hostbannerGfxUrl?: string; hostbannerGfxIntervalSecs?: number; hostbannerMode?: string; hostbuttonTooltip?: string; hostbuttonUrl?: string; hostbuttonGfxUrl?: string; nickname?: string; phoneticName?: string; codecEncryptionMode?: string; } function ServerEditDialog({ serverName, welcomeMessage, hostbannerGfxUrl, onSave, onClose, }: { serverName: string; welcomeMessage: string; hostbannerGfxUrl: string; onSave: (payload: ServerEditPayload) => void; onClose: () => void; }) { const t = useT(); const backdrop = useBackdropDismiss(onClose); const [tab, setTab] = useState<(typeof SERVER_EDIT_TABS)[number]>("host"); const [name, setName] = useState(serverName); const [welcome, setWelcome] = useState(welcomeMessage); const [clearPassword, setClearPassword] = useState(false); const [password, setPassword] = useState(""); const [hostmessage, setHostmessage] = useState(""); const [hostmessageMode, setHostmessageMode] = useState(""); const [hostbannerUrl, setHostbannerUrl] = useState(""); const [bannerGfxUrl, setBannerGfxUrl] = useState(hostbannerGfxUrl); const [hostbannerGfxInterval, setHostbannerGfxInterval] = useState(""); const [hostbannerMode, setHostbannerMode] = useState(""); const [hostbuttonTooltip, setHostbuttonTooltip] = useState(""); const [hostbuttonUrl, setHostbuttonUrl] = useState(""); const [hostbuttonGfxUrl, setHostbuttonGfxUrl] = useState(""); const [maxClients, setMaxClients] = useState(""); const [nickname, setNickname] = useState(""); const [phoneticName, setPhoneticName] = useState(""); const [codecEncryptionMode, setCodecEncryptionMode] = useState(""); const handleSave = () => { const payload: ServerEditPayload = {}; if (name.trim() && name !== serverName) payload.name = name.trim(); if (welcome !== welcomeMessage) payload.welcomeMessage = welcome; if (clearPassword) payload.password = ""; else if (password) payload.password = password; if (hostmessage) payload.hostmessage = hostmessage; if (hostmessageMode) payload.hostmessageMode = hostmessageMode; if (hostbannerUrl) payload.hostbannerUrl = hostbannerUrl; if (bannerGfxUrl !== hostbannerGfxUrl) payload.hostbannerGfxUrl = bannerGfxUrl; if (hostbannerGfxInterval) payload.hostbannerGfxIntervalSecs = Number(hostbannerGfxInterval) || 0; if (hostbannerMode) payload.hostbannerMode = hostbannerMode; if (hostbuttonTooltip) payload.hostbuttonTooltip = hostbuttonTooltip; if (hostbuttonUrl) payload.hostbuttonUrl = hostbuttonUrl; if (hostbuttonGfxUrl) payload.hostbuttonGfxUrl = hostbuttonGfxUrl; if (maxClients) payload.maxClients = Number(maxClients) || 0; if (nickname) payload.nickname = nickname; if (phoneticName) payload.phoneticName = phoneticName; if (codecEncryptionMode) payload.codecEncryptionMode = codecEncryptionMode; onSave(payload); onClose(); }; return (
e.stopPropagation()}>
{t("serverEdit.title")}
{SERVER_EDIT_TABS.map((id) => ( ))}
{tab === "host" && ( <>