init
No files matched your search
@@ -0,0 +1,93 @@
|
||||
import { safeDiagnostic } from './connection-diagnostics.mjs';
|
||||
import { loadProtocol, resetProtocol } from './protocol.mjs';
|
||||
import { loadWorkspace, resetWorkspace } from './workspace.mjs';
|
||||
const $ = id => document.getElementById(id);
|
||||
let csrf;
|
||||
document.querySelector('.skip-link').addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
const target = $('lab').hidden ? $('username') : document.querySelector('section[data-page]:not(#lab):not([hidden])');
|
||||
if (!target) return; if (target.tagName === 'SECTION') target.setAttribute('tabindex', '-1'); target.focus(); target.scrollIntoView({ block: 'start' });
|
||||
});
|
||||
let registering = false; let registrationEnabled = false; let ownerAvailable = false; let authBusy = false;
|
||||
const authChannel = typeof BroadcastChannel === 'function' ? new BroadcastChannel('voxharbor-auth') : null;
|
||||
authChannel?.addEventListener('message', () => { locked(); $('notice').textContent = 'Sign-in changed in another tab. Sign in to continue.'; });
|
||||
$('notice-dismiss').addEventListener('click', () => { $('notice').textContent = ''; });
|
||||
new MutationObserver(() => { $('notice-toast').hidden = !$('notice').textContent; }).observe($('notice'), { childList: true, characterData: true, subtree: true });
|
||||
function authMode() {
|
||||
$('welcome').dataset.authMode = registering ? 'register' : 'login'; $('auth-route').textContent = registering ? 'ACCOUNT / CREATE ACCOUNT' : 'ACCOUNT / SIGN IN';
|
||||
$('auth-title').textContent = registering ? 'Your own place on the dial.' : 'Welcome back.'; $('auth-eyebrow').textContent = registering ? 'CREATE ACCOUNT' : 'SIGN IN';
|
||||
$('auth-submit').textContent = registering ? 'Create account' : 'Sign in';
|
||||
$('auth-toggle').textContent = registering ? 'Already registered? Sign in' : 'Create an account';
|
||||
$('auth-toggle').hidden = !registrationEnabled;
|
||||
$('confirm-field').hidden = !registering; $('confirm-password').required = registering;
|
||||
$('password').autocomplete = registering ? 'new-password' : 'current-password';
|
||||
$('password').minLength = registering ? 16 : 0;
|
||||
$('auth-hint').textContent = registering ? 'Use 16–256 characters for your password. Keep it safe; password recovery is not available yet.' : 'Your identity and saved connections belong to your account.';
|
||||
}
|
||||
$('auth-toggle').addEventListener('click', () => { if (authBusy) return; registering = !registering; $('password').value = ''; $('confirm-password').value = ''; $('auth-status').textContent = ''; $('notice').textContent = ''; authMode(); });
|
||||
async function loadAuth() {
|
||||
try { const options = await api('/api/auth'); registrationEnabled = options.registrationEnabled; ownerAvailable = options.ownerAvailable; authMode(); $('auth-submit').disabled = false; }
|
||||
catch { $('auth-status').textContent = 'Sign-in is unavailable. Reload to try again.'; }
|
||||
}
|
||||
let sessionGeneration = 0;
|
||||
const evidence = { schema: 'voxharbor-diagnostics-v1', startedAt: new Date().toISOString(), events: [] };
|
||||
function record(type, data) {
|
||||
evidence.events.push({ at: new Date().toISOString(), type, data });
|
||||
if (evidence.events.length > 1000) evidence.events.shift();
|
||||
$('events').textContent = JSON.stringify(evidence.events.slice(-30), null, 2);
|
||||
}
|
||||
window.addEventListener('voxharbor-protocol-diagnostic', event => record('protocol', safeDiagnostic(event.detail)));
|
||||
for (const type of ['online', 'offline']) window.addEventListener(type, () => record('browser', { state: type }));
|
||||
document.addEventListener('visibilitychange', () => record('browser', { state: document.hidden ? 'hidden' : 'visible' }));
|
||||
async function api(path, body) {
|
||||
const response = await fetch(path, {
|
||||
signal: AbortSignal.timeout(15000), method: body === undefined ? 'GET' : 'POST',
|
||||
headers: body === undefined ? {} : { 'Content-Type': 'application/json', ...(csrf ? { 'X-CSRF-Token': csrf } : {}) },
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw Object.assign(new Error(data.error || `Request failed (${response.status})`), { status: response.status });
|
||||
return data;
|
||||
}
|
||||
function locked() {
|
||||
++sessionGeneration; registering = false; authMode(); $('auth-status').textContent = ''; $('password').value = ''; $('confirm-password').value = '';
|
||||
resetProtocol(); resetWorkspace(); csrf = undefined; $('account-label').textContent = 'Your account'; $('account-label').setAttribute('aria-label', 'Account settings'); $('own-initials').textContent = '—';
|
||||
evidence.events.length = 0; $('events').textContent = 'No connection diagnostics recorded.';
|
||||
$('login').hidden = false; $('lab').hidden = true; $('welcome').hidden = false;
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
window.addEventListener('voxharbor-owner-expired', () => {
|
||||
locked(); $('notice').textContent = 'Your session expired or was signed out. Sign in to reconnect.';
|
||||
});
|
||||
async function loadSession() {
|
||||
const generation = sessionGeneration;
|
||||
const data = await api('/api/session');
|
||||
if (generation !== sessionGeneration) return;
|
||||
csrf = data.csrf; $('account-label').textContent = data.user.username; $('account-label').setAttribute('aria-label', `Account settings for ${data.user.username}`); $('own-initials').textContent = [...data.user.username].slice(0, 2).join('').toUpperCase(); $('profile-account-name').textContent = data.user.username;
|
||||
$('login').hidden = true; $('lab').hidden = false; $('welcome').hidden = true;
|
||||
$('runtime').textContent = `${data.runtime.environment} · ${data.runtime.node} · ${data.runtime.sessionStore}`;
|
||||
record('runtime', { node: data.runtime.node, platform: data.runtime.platform, arch: data.runtime.arch, sessionStore: data.runtime.sessionStore });
|
||||
void loadProtocol(csrf); void loadWorkspace(csrf);
|
||||
}
|
||||
$('login').addEventListener('submit', async event => {
|
||||
event.preventDefault(); if (authBusy) return;
|
||||
if (registering && $('password').value !== $('confirm-password').value) { $('auth-status').textContent = 'Passwords do not match.'; return; }
|
||||
const button = $('auth-submit'); authBusy = true; button.disabled = true; $('auth-toggle').disabled = true; $('auth-status').textContent = '';
|
||||
try {
|
||||
await api(registering ? '/api/register' : '/api/login', { username: $('username').value, password: $('password').value }); $('password').value = ''; $('confirm-password').value = '';
|
||||
locked(); authChannel?.postMessage('changed'); await loadSession(); window.scrollTo(0, 0); $('notice').textContent = '';
|
||||
} catch (error) { $('auth-status').textContent = error.message; }
|
||||
finally { $('password').value = ''; $('confirm-password').value = ''; authBusy = false; button.disabled = false; $('auth-toggle').disabled = false; }
|
||||
});
|
||||
$('logout').addEventListener('click', async () => {
|
||||
resetProtocol();
|
||||
try { await api('/api/logout', {}); locked(); authChannel?.postMessage('changed'); $('notice').textContent = 'Signed out. Session revoked.'; }
|
||||
catch { locked(); $('notice').textContent = 'Connection stopped. Server sign-out could not be confirmed; retry when storage is available.'; }
|
||||
});
|
||||
$('download').addEventListener('click', () => {
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(evidence, null, 2)], { type: 'application/json' }));
|
||||
const link = document.createElement('a'); link.href = url; link.download = 'voxharbor-diagnostics.json'; link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
});
|
||||
void loadAuth();
|
||||
loadSession().catch(() => locked());
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,29 @@
|
||||
// Choices live only in this signed-in page, never in shared browser storage.
|
||||
export class AudioRecovery {
|
||||
constructor() { this.clear(); }
|
||||
clear() { this.pending = undefined; this.generation = (this.generation || 0) + 1; }
|
||||
interrupted(audio, resumeMicrophone, visible) {
|
||||
if (!audio) return;
|
||||
this.pending = !audio.outputMuted ? { microphone: !audio.muted && resumeMicrophone && visible } : undefined;
|
||||
}
|
||||
async restore({ visible, create, valid, output = '', microphone = '', resumeMicrophone, status }) {
|
||||
const choice = this.pending; this.pending = undefined;
|
||||
if (!choice || !visible) return;
|
||||
const generation = this.generation;
|
||||
const active = create();
|
||||
this.restoring = active;
|
||||
const current = () => generation === this.generation && valid(active);
|
||||
try {
|
||||
await active.listen(true);
|
||||
if (!current()) return;
|
||||
if (output && typeof active.context?.setSinkId === 'function') await active.context.setSinkId(output);
|
||||
if (!current()) return;
|
||||
if (choice.microphone && resumeMicrophone()) await active.microphone(microphone);
|
||||
if (current()) status(choice.microphone && !active.muted ? 'Listening and microphone resumed after reconnect.' : 'Listening resumed. Microphone remains off.');
|
||||
} catch {
|
||||
if (current()) { active.mute(); status('Audio could not resume automatically. Enable listening and the microphone to retry.'); }
|
||||
} finally {
|
||||
if (this.restoring === active) this.restoring = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// TeamSpeak channel_order is the preceding sibling's ID, not a numeric rank.
|
||||
export function orderChannels(channels) {
|
||||
const byId = new Map(channels.map(channel => [channel.id, channel]));
|
||||
const groups = new Map();
|
||||
for (const channel of channels) {
|
||||
const parent = channel.parentId && byId.has(channel.parentId) ? channel.parentId : 0;
|
||||
if (!groups.has(parent)) groups.set(parent, []);
|
||||
groups.get(parent).push(channel);
|
||||
}
|
||||
function siblings(group = []) {
|
||||
const ids = new Set(group.map(channel => channel.id));
|
||||
const links = new Map();
|
||||
const seen = new Set();
|
||||
const ordered = [];
|
||||
const sorted = [...group].sort((a, b) => a.id - b.id);
|
||||
for (const channel of sorted) {
|
||||
if (!links.has(channel.order)) links.set(channel.order, []);
|
||||
links.get(channel.order).push(channel);
|
||||
}
|
||||
const starts = [...sorted.filter(channel => !ids.has(channel.order)), ...sorted];
|
||||
for (const start of starts) {
|
||||
const queue = [start];
|
||||
while (queue.length) {
|
||||
const channel = queue.pop();
|
||||
if (seen.has(channel.id)) continue;
|
||||
seen.add(channel.id);
|
||||
ordered.push(channel);
|
||||
queue.push(...[...(links.get(channel.id) || [])].reverse());
|
||||
}
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
const visited = new Set();
|
||||
const result = [];
|
||||
const roots = [...siblings(groups.get(0)), ...channels];
|
||||
for (const root of roots) {
|
||||
const stack = [{ channel: root, depth: 0 }];
|
||||
while (stack.length) {
|
||||
const item = stack.pop();
|
||||
if (visited.has(item.channel.id)) continue;
|
||||
visited.add(item.channel.id);
|
||||
result.push(item);
|
||||
stack.push(...siblings(groups.get(item.channel.id)).reverse().map(channel => ({ channel, depth: Math.min(item.depth + 1, 10) })));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Explicit fields only: no URLs, close reasons, messages, account IDs or media.
|
||||
const numbers = new Set(['attempt', 'delay', 'closeCode', 'durationMs', 'lastMessageAgeMs', 'roundTripMs', 'channels', 'participants', 'sequence']);
|
||||
const words = new Set(['type', 'state', 'stage', 'code']);
|
||||
export function safeDiagnostic(input) {
|
||||
const result = {};
|
||||
for (const [key, value] of Object.entries(input || {})) {
|
||||
if (numbers.has(key) && Number.isFinite(value) && value >= 0) result[key] = value;
|
||||
if (words.has(key) && typeof value === 'string' && /^[a-z][a-z_]{0,63}$/.test(value)) result[key] = value;
|
||||
if (key === 'receivedState' && typeof value === 'boolean') result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
After Width: | Height: | Size: 162 B |
|
After Width: | Height: | Size: 243 B |
|
After Width: | Height: | Size: 806 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#171818"/><g fill="#ec8351"><rect x="14" y="20" width="4" height="24" rx="2"/><rect x="22" y="14" width="4" height="36" rx="2"/><rect x="30" y="18" width="4" height="28" rx="2"/><rect x="38" y="10" width="4" height="44" rx="2"/><rect x="46" y="23" width="4" height="18" rx="2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 415 B |
@@ -0,0 +1,93 @@
|
||||
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
After Width: | Height: | Size: 951 B |
|
After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M2.75 11V11.9166V19.25H6.41667V11H2.75ZM2.75 11V10.0833C2.75 7.89528 3.61919 5.79686 5.16637 4.24968C6.71354 2.70251 8.81196 1.83331 11 1.83331C13.188 1.83331 15.2865 2.70251 16.8336 4.24968C18.3808 5.79686 19.25 7.89528 19.25 10.0833V11M19.25 11V11.9166V19.25H15.5833V11H19.25Z" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke="#101212"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 477 B |
@@ -0,0 +1,4 @@
|
||||
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M11 1.83331C12.5188 1.83331 13.75 3.06453 13.75 4.58331V10.0833C13.75 11.6021 12.5188 12.8333 11 12.8333C9.48122 12.8333 8.25 11.6021 8.25 10.0833V4.58331C8.25 3.06453 9.48122 1.83331 11 1.83331Z" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke="#101212"/>
|
||||
<path d="M4.58333 9.16667V11C4.58333 12.7018 5.25937 14.3339 6.46273 15.5373C7.66609 16.7406 9.29819 17.4167 11 17.4167M11 17.4167C12.7018 17.4167 14.3339 16.7406 15.5373 15.5373M11 17.4167V20.1667M15.5373 15.5373C16.7406 14.3339 17.4167 12.7018 17.4167 11V9.16667M15.5373 15.5373L2.75 2.75M15.5373 15.5373L19.25 19.25" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke="#101212"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 799 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><g fill="#000"><rect x="14" y="20" width="4" height="24" rx="2"/><rect x="22" y="14" width="4" height="36" rx="2"/><rect x="30" y="18" width="4" height="28" rx="2"/><rect x="38" y="10" width="4" height="44" rx="2"/><rect x="46" y="23" width="4" height="18" rx="2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 359 B |
@@ -0,0 +1,4 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="dark light"><title>VoxHarbor · Voice console</title><meta name="theme-color" content="#171818"><meta name="application-name" content="VoxHarbor"><meta name="apple-mobile-web-app-title" content="VoxHarbor"><link rel="icon" href="/favicon.ico" sizes="16x16 32x32 48x48"><link rel="icon" href="/favicon.svg" type="image/svg+xml" sizes="any"><link rel="icon" href="/favicon-32x32.png" type="image/png" sizes="32x32"><link rel="icon" href="/favicon-16x16.png" type="image/png" sizes="16x16"><link rel="apple-touch-icon" href="/apple-touch-icon.png" sizes="180x180"><link rel="mask-icon" href="/icons/safari-pinned-tab.svg" color="#ec8351"><link rel="manifest" href="/site.webmanifest"><link rel="stylesheet" href="/style.css"><script type="module" src="/app.mjs"></script></head><body><a class="skip-link" href="#workspace-content">Skip to content</a><main><section class="welcome" id="welcome"><header class="account-header"><a class="brand" href="/">voxharbor</a><span id="auth-route" class="eyebrow">ACCOUNT / SIGN IN</span><span class="hint">Your private workspace</span></header><div class="welcome-copy"><div class="signin-copy"><p class="eyebrow">BROWSER VOICE / YOUR COMMUNITIES</p><h1>The room is ready.<br>Bring your voice.</h1><p>Connect to your TeamSpeak communities from your browser.<br>Your identity and destinations stay with your account.</p><div class="welcome-room"><p class="eyebrow">YOUR PLACE TO CONNECT</p><h2>Your rooms. Your people.</h2><p class="hint">Your microphone and listening start off.</p></div><p class="welcome-note">Your account / Your identity / Your saved destinations</p></div><div class="registration-copy"><section><p class="eyebrow">YOUR OWN DESTINATIONS</p><h2>Your rooms, remembered.</h2><p class="hint">Keep your connections and nickname in your account.</p></section><section><p class="eyebrow">YOUR OWN IDENTITY</p><h2>A familiar voice.</h2><p class="hint">Create or import your TeamSpeak identity after signing up.</p></section><p class="hint">Use 3–32 letters, numbers, underscores or hyphens for your username. Passwords need 16–256 characters.</p><p class="hint">Password recovery is not available. Keep your password safe.</p></div></div><form id="login"><p class="eyebrow" id="auth-eyebrow">SIGN IN</p><h2 id="auth-title">Welcome back.</h2><p class="hint">Use your account on this instance.</p><label for="username">Username</label><input id="username" autocomplete="username" placeholder="Your username" required minlength="3" maxlength="32" pattern="[a-zA-Z0-9][a-zA-Z0-9_-]{2,31}" autocapitalize="none" spellcheck="false"><label for="password">Password</label><input id="password" type="password" placeholder="Enter your password" autocomplete="current-password" required maxlength="256"><div id="confirm-field" hidden><label for="confirm-password">Confirm password</label><input id="confirm-password" type="password" autocomplete="new-password" maxlength="256"></div><button id="auth-submit" disabled>Sign in</button><button id="auth-toggle" type="button" class="quiet" hidden>Create an account</button><p id="auth-hint" class="hint">Loading sign-in options…</p><p id="auth-status" class="hint" role="status"></p><div class="auth-note hint">A VoxHarbor account is separate from a TeamSpeak identity.<br>Set up or import your identity after signing in.</div></form><footer class="account-footer"><span>VOXHARBOR / TEAMSPEAK 3</span><span>Your account / Your saved destinations</span></footer></section>
|
||||
<section id="lab" class="app-shell" hidden aria-label="Your TeamSpeak workspace"><header class="topbar"><a class="brand" href="#connections" data-route="connections"><span class="mark" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i></span>voxharbor</a><button id="settings-open" class="server-selector quiet" data-route="connections"><span id="server-name">Your destinations</span><span aria-hidden="true">⌄</span><span id="connection-badge" role="status">Offline</span></button><p id="page-breadcrumb" class="eyebrow">CONNECTIONS / SAVED DESTINATIONS</p><span id="server-address" class="sr-only">No server configured</span><nav class="top-actions" aria-label="Workspace"><button data-route="console" class="quiet">Console</button><button data-route="connections" class="quiet">Connections</button><button id="messages-nav" data-route="conversation" class="quiet">Messages</button><button data-route="identity" class="quiet">Identity</button><button id="account-label" class="quiet" data-route="profile">Your account</button></nav></header>
|
||||
<div id="session-ribbon" class="session-ribbon" hidden><span id="ribbon-status" role="status">Connected</span><span id="ribbon-audio">Microphone off</span><button id="ribbon-mute" class="secondary" hidden>Mute microphone</button><button class="quiet" data-route="console">Return to voice console ↗</button></div><section class="app-page destination-page" data-page="connections"><header class="page-heading"><div><p class="eyebrow">YOUR DESTINATIONS</p><h1 tabindex="-1">Pick up where you left off.</h1><p class="hint">One active server connection per account. Your saved destinations stay across sign-ins.</p></div><div class="row"><button id="connection-add">Add connection</button></div></header><aside id="identity-needed" class="callout" hidden><strong>Set up your voice identity</strong><p class="hint">Create or import a TeamSpeak identity once before connecting.</p><button data-route="identity" class="secondary">Set up identity ↗</button></aside><p id="workspace-readiness" role="status" class="hint">Loading connection capabilities…</p><p id="workspace-loading" role="status" class="hint">Loading your destinations…</p><div class="destination-table"><div class="destination-columns" aria-hidden="true"><span>SAVED CONNECTION</span><span>NICKNAME</span><span>STATUS</span><span>ACTIONS</span></div><div id="bookmarks" aria-label="Saved connections"></div></div><div id="recent-connection" class="settings-surface" hidden></div><p id="preferences-status" role="status" class="hint"></p><aside class="callout"><strong>Connections are private to your account</strong><p class="hint">Passwords stay encrypted on the backend. Saved destinations are kept across application updates.</p></aside></section><section class="app-page" data-page="connection" id="settings-dialog" hidden><header class="page-heading"><div><p class="eyebrow">YOUR DESTINATIONS / CONNECTION</p><h1 tabindex="-1">Find your frequency.</h1><p class="hint">Add a server, choose your nickname, and save the destination for next time.</p></div><div class="row"><button class="quiet" data-route="connections">← All connections</button></div></header><form id="connection-form"><div class="editor-grid"><section class="settings-surface" id="editor-primary"><label for="bookmark-name">Connection name</label><input id="bookmark-name" maxlength="80" placeholder="Give this destination a name" required><div class="host-fields"><div><label for="ts3-host">Server address</label><input id="ts3-host" maxlength="253" placeholder="Hostname or public IPv4 address" autocomplete="off" required></div><div><label for="ts3-port">Voice port</label><input id="ts3-port" type="number" min="1024" max="65535" value="9987" required></div></div><label for="ts3-nickname">Nickname</label><input id="ts3-nickname" maxlength="64" autocomplete="off" required><label for="ts3-password">Server password (optional)</label><input id="ts3-password" type="password" maxlength="256" autocomplete="off"><label class="checkbox-label"><input id="bookmark-passwords" type="checkbox" checked> Also remember entered passwords in this saved destination</label><p class="hint">The current connection is always encrypted for recovery. This choice controls whether its passwords are also kept with the saved destination.</p><div id="connection-requirement" class="callout"><p class="hint">Create or import your TeamSpeak identity before connecting.</p><button type="button" class="secondary" data-route="identity">Set up identity ↗</button></div><div class="editor-actions"><button id="editor-connect" type="submit">Save & connect</button><button id="bookmark-save" type="button" class="secondary" disabled>Save without connecting</button></div><p id="editor-status" class="hint" role="status"></p><p id="native-status" class="hint" role="status">Loading protocol capabilities…</p></section><aside><section class="settings-surface"><p class="eyebrow">DESTINATION CHANNEL / OPTIONAL</p><label for="ts3-channel">Channel ID</label><input id="ts3-channel" type="number" min="1" step="1" placeholder="Leave blank for the default channel" autocomplete="off"><label for="ts3-channel-password">Channel password</label><input id="ts3-channel-password" type="password" maxlength="256" autocomplete="off"><p class="hint field-note">Allowed voice ports: 1024–65535.<br>Your identity is reused for every connection.</p></section><aside class="callout"><strong>Editing a saved password?</strong><p class="hint">Leave it blank to keep it for the same destination. A password never follows an edited destination to another server.</p></aside><label class="checkbox-label"><input id="bookmark-clear-passwords" type="checkbox"> Remove passwords saved for this connection</label><button id="bookmark-delete" type="button" class="quiet danger" hidden>Delete saved connection</button><p id="ts3-destination" class="sr-only"></p><input id="connection-clear-passwords" type="checkbox" hidden></aside></div><div id="editor-mobile-actions"></div></form><button id="ts3-connectLine truncated
|
||||
</section><section class="app-page" data-page="conversation" hidden><header class="page-heading"><div><p class="eyebrow">DIRECT CONVERSATION</p><h1 tabindex="-1">A quieter channel.</h1><p class="hint">Private conversations stay attached to the intended participant and clear when you sign out.</p></div><div class="row"><button class="quiet" data-route="console">← Voice console</button></div></header><button id="direct-tools-toggle" class="quiet" aria-controls="direct-controls" aria-expanded="false">Participant controls</button><div class="direct-grid" id="direct-grid"><nav class="thread-list" aria-label="Conversations"><p class="eyebrow">CONVERSATIONS</p><div id="conversation-threads"></div><button class="quiet" data-return-scope="channel">Channel messages</button><button class="quiet" data-return-scope="server">Server messages</button></nav><div id="direct-chat-slot"></div><aside class="channel-detail" id="direct-controls"><p class="eyebrow">PARTICIPANT</p><h2 id="direct-name">Choose someone</h2><p id="direct-status" class="hint">Select a connected participant to start a private conversation.</p><label for="direct-volume">Playback volume</label><input id="direct-volume" type="range" min="0" max="200" value="100" disabled><p id="direct-volume-value" class="hint">100% / Range 0–200%</p><button id="direct-poke" class="full-width" disabled>Poke participant</button><p class="hint field-note">Server permissions apply. Unconfirmed messages are not resent.</p></aside></div></section><section class="app-page" data-page="audio" hidden><header class="page-heading"><div><p class="eyebrow">YOUR AUDIO</p><h1 tabindex="-1">Make the room sound right.</h1><p class="hint">Listening and microphone are independent. Adjust devices and transmission without leaving the room.</p></div><div class="row"><button class="quiet" data-route="console">← Voice console</button></div></header><div class="settings-columns"><section class="settings-surface"><label for="voice-input">Microphone</label><select id="voice-input"><option value="">System default</option></select><label for="voice-output">Audio output (where supported)</label><select id="voice-output" disabled><option value="">System default</option></select><p class="eyebrow mode-heading">TRANSMISSION MODE</p><div class="row mode-options"><button data-audio-mode="ptt">Push to talk</button><button data-audio-mode="vad">Voice activation</button></div><p class="hint">Hold Space to talk in push-to-talk mode. This page must have focus.</p><label for="voice-threshold">Voice activation threshold</label><input id="voice-threshold" type="range" min="1" max="150" value="25"><p class="hint">The threshold applies when voice activation is selected.</p></section><div><section class="settings-surface processing"><p class="eyebrow">BROWSER AUDIO PROCESSING</p><p>✓ Echo cancellation</p><p>✓ Noise suppression</p><p>✓ Automatic gain control</p><p class="hint">Requested when supported by the browser.</p></section><section class="settings-surface"><p class="eyebrow">AFTER RECONNECTION</p><label class="checkbox-label"><input id="voice-resume-mic" type="checkbox"> Resume my enabled microphone after automatic reconnect</label><p class="hint">Off by default. Listening resumes if it was enabled. Choices last until sign-out or reload. A held push-to-talk press is never restored.</p><button class="secondary full-width" data-route="console">Done</button></section></div></div><p class="hint">Hiding the page, device failure or a channel change stops transmission. Global shortcuts and reliable mobile background audio are unavailable.</p></section><section class="app-page" data-page="profile" hidden><header class="page-heading"><div><p class="eyebrow">YOUR ACCOUNT / PRESENCE</p><h1 tabindex="-1">Make yourself known.</h1><p class="hint">Manage your presence on the current server and your account session.</p></div><div class="row"></div></header><div class="editor-grid"><section class="settings-surface"><label for="profile-nickname">Nickname</label><input id="profile-nickname" maxlength="64" autocomplete="off"><button id="nickname-update" class="secondary">Update nickname</button><label for="away-message">Away message</label><input id="away-message" maxlength="250" placeholder="Back soon"><button id="away-toggle" class="secondary">Set away</button><p id="profile-status" role="status" class="hint"></p></section><aside><section class="channel-detail"><p class="eyebrow">SIGNED IN</p><h2 id="profile-account-name">Your account</h2><p class="hint">Your identity and destinations belong to this account.</p><button id="logout" class="full-width">Sign out</button></section><section class="settings-surface"><p class="eyebrow">APPEARANCE</p><button id="theme-toggle" class="quiet">Theme: system</button></section></aside></div></section><section class="app-page" data-page="diagnostics" hidden><header class="page-heading"><div><p class="eyebrow">CONNECTION / DIAGNOSTICS</p><h1 tabindex="-1">Know what happened.</h1><p clLine truncated
|
||||
@@ -0,0 +1,40 @@
|
||||
// Packet sequence numbers wrap at 65536. A talk spurt begins after 60 ms.
|
||||
export const sequenceDistance = (a, b) => ((a - b + 32768) & 65535) - 32768;
|
||||
export class JitterBuffer {
|
||||
constructor({ capacity = 12, prebuffer = 3, maxLoss = 3 } = {}) {
|
||||
this.capacity = capacity; this.prebuffer = prebuffer; this.maxLoss = maxLoss;
|
||||
this.packets = new Map(); this.expected = null; this.wait = 0; this.loss = 0;
|
||||
this.stats = { late: 0, duplicate: 0, overflow: 0, lost: 0, received: 0 };
|
||||
}
|
||||
clear() { this.packets.clear(); this.expected = null; this.wait = 0; this.loss = 0; }
|
||||
push(packet) {
|
||||
const id = packet.sequence;
|
||||
this.stats.received++;
|
||||
if (this.expected === null) { this.expected = id; this.wait = this.prebuffer; }
|
||||
const delta = sequenceDistance(id, this.expected);
|
||||
if (delta < 0) { this.stats.late++; return false; }
|
||||
if (this.packets.has(id)) { this.stats.duplicate++; return false; }
|
||||
if (delta >= this.capacity || this.packets.size >= this.capacity) {
|
||||
this.clear(); this.expected = id; this.wait = this.prebuffer;
|
||||
this.stats.overflow++;
|
||||
}
|
||||
this.packets.set(id, packet);
|
||||
return true;
|
||||
}
|
||||
pull() {
|
||||
if (this.expected === null) return { type: 'idle' };
|
||||
if (this.wait > 0) { this.wait--; return { type: 'wait' }; }
|
||||
const packet = this.packets.get(this.expected);
|
||||
this.packets.delete(this.expected);
|
||||
this.expected = (this.expected + 1) & 65535;
|
||||
if (packet) {
|
||||
this.loss = 0;
|
||||
if (packet.end) { this.clear(); return { type: 'end' }; }
|
||||
return { type: 'packet', packet };
|
||||
}
|
||||
this.stats.lost++; this.loss++;
|
||||
if (this.loss >= this.maxLoss) { this.clear(); return { type: 'end' }; }
|
||||
// The next packet may carry in-band FEC for exactly this missing packet.
|
||||
return { type: 'loss', next: this.packets.get(this.expected) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Reconnects carry only a saved-settings ID; credentials stay on the backend.
|
||||
const retryable = new Set(['connection_failed', 'handshake_timeout', 'server_initialization_timeout', 'protocol_network_error', 'native_protocol_failed', 'session_lease_lost', 'another_session_is_active', 'connection_rate_limit', 'owner_transport_timeout']);
|
||||
const advisory = new Set(['server_permission_or_command_error', 'subscription_unavailable', 'connection_settings_not_saved']);
|
||||
|
||||
export class ProtocolConnection {
|
||||
constructor({ url, session, socket = address => new WebSocket(address), phase = () => {}, event = () => {}, disconnected = () => {}, expired = () => {}, diagnostic = () => {},
|
||||
now = () => Date.now(), later = (fn, ms) => setTimeout(fn, ms), cancel = timer => clearTimeout(timer), random = Math.random }) {
|
||||
Object.assign(this, { url, session, createSocket: socket, phase, event, disconnected, expired, diagnostic, now, later, cancel, random });
|
||||
this.timers = new Set(); this.epoch = 0; this.desired = false; this.connected = false;
|
||||
this.lastAttempt = -Infinity; this.failures = 0;
|
||||
}
|
||||
timer(fn, delay) {
|
||||
const id = this.later(() => { this.timers.delete(id); fn(); }, delay);
|
||||
this.timers.add(id); return id;
|
||||
}
|
||||
clearTimers() { for (const id of this.timers) this.cancel(id); this.timers.clear(); }
|
||||
start(options) {
|
||||
this.stop();
|
||||
this.options = { connectionId: options.connectionId };
|
||||
this.desired = true; this.paused = false; this.failures = 0; this.lastAttempt = -Infinity;
|
||||
void this.attempt();
|
||||
}
|
||||
stop(reason = 'Owner stopped connection') {
|
||||
this.desired = false; this.paused = false; this.options = undefined; this.connected = false;
|
||||
++this.epoch; this.clearTimers();
|
||||
this.authAbort?.abort(); this.authAbort = undefined;
|
||||
const socket = this.socket; this.socket = undefined;
|
||||
if (socket?.readyState === 1) {
|
||||
try { socket.send(JSON.stringify({ type: 'disconnect', csrf: this.csrf })); } catch {}
|
||||
}
|
||||
try { socket?.close(1000, reason); } catch {}
|
||||
this.csrf = undefined; this.disconnected(); this.phase({ state: 'stopped' });
|
||||
}
|
||||
send(command) {
|
||||
if (!this.connected || this.socket?.readyState !== 1) return false;
|
||||
try { this.socket.send(JSON.stringify({ ...command, csrf: this.csrf })); return true; } catch { return false; }
|
||||
}
|
||||
voice(frame) {
|
||||
if (!this.connected || this.socket?.readyState !== 1 || this.socket.bufferedAmount > 4096) return false;
|
||||
try { this.socket.send(frame); return true; } catch { return false; }
|
||||
}
|
||||
offline() {
|
||||
if (!this.desired) return;
|
||||
this.clearTimers(); ++this.epoch;
|
||||
this.authAbort?.abort(); this.authAbort = undefined;
|
||||
const socket = this.socket; this.socket = undefined;
|
||||
try { socket?.close(4000, 'Network offline'); } catch {}
|
||||
this.connected = false; this.disconnected(); this.phase({ state: 'offline' });
|
||||
this.paused = true;
|
||||
}
|
||||
online() {
|
||||
if (!this.desired || !this.paused) return;
|
||||
this.paused = false; this.schedule();
|
||||
}
|
||||
schedule(code) {
|
||||
if (!this.desired || this.paused) return;
|
||||
if (this.failures >= 5) { this.stop(); this.phase({ state: 'failed', code: code || 'recovery_limit' }); return; }
|
||||
// At most five new handshakes per minute, below the server's six-per-minute gate.
|
||||
const delay = Math.max(12000 - (this.now() - this.lastAttempt), Math.min(30000, 1000 * 2 ** this.failures) + Math.floor(this.random() * 500),
|
||||
code === 'another_session_is_active' ? 36000 : 0, code === 'connection_rate_limit' ? 61000 : 0);
|
||||
this.diagnostic({ type: 'retry', attempt: this.failures, delay, ...(code ? { code } : {}) });
|
||||
this.phase({ state: 'retrying', delay, code });
|
||||
this.timer(() => { void this.attempt(); }, delay);
|
||||
}
|
||||
async attempt() {
|
||||
if (!this.desired || this.paused) return;
|
||||
this.clearTimers(); const epoch = ++this.epoch;
|
||||
this.connected = false; this.disconnected(); this.lastAttempt = this.now();
|
||||
this.diagnostic({ type: 'attempt', attempt: this.failures + 1 });
|
||||
this.phase({ state: 'connecting' });
|
||||
let auth; let authTimer;
|
||||
const controller = new AbortController(); this.authAbort = controller;
|
||||
try { auth = await Promise.race([this.session({ signal: controller.signal }), new Promise((_, reject) => {
|
||||
authTimer = this.timer(() => { controller.abort(); reject(new Error('Session check timed out')); }, 15000);
|
||||
})]); }
|
||||
catch (error) {
|
||||
if (epoch !== this.epoch || !this.desired) return;
|
||||
if ([401, 403].includes(error.status)) { this.stop(); this.phase({ state: 'expired' }); this.expired(); return; }
|
||||
this.failures++; this.schedule('session_unavailable'); return;
|
||||
}
|
||||
finally {
|
||||
this.cancel(authTimer); this.timers.delete(authTimer);
|
||||
if (this.authAbort === controller) this.authAbort = undefined;
|
||||
}
|
||||
if (epoch !== this.epoch || !this.desired || this.paused) return;
|
||||
this.csrf = auth.csrf;
|
||||
let socket;
|
||||
try { socket = this.createSocket(this.url); } catch { this.failures++; this.schedule('transport_unavailable'); return; }
|
||||
this.socket = socket; socket.binaryType = 'arraybuffer';
|
||||
const openedAt = this.now();
|
||||
let lastMessageAt = openedAt; let timeoutKind = 'handshake';
|
||||
let fault; let healthySince; let receivedState = false; let pong; let nonce = 0; let ended = false;
|
||||
const current = () => epoch === this.epoch && this.desired && !ended;
|
||||
const finish = (code = 1006) => {
|
||||
if (!current()) return;
|
||||
this.diagnostic({ type: 'transport_closed', closeCode: code, durationMs: this.now() - openedAt, lastMessageAgeMs: this.now() - lastMessageAt, receivedState, ...(fault ? { code: fault } : {}) });
|
||||
ended = true; this.clearTimers(); this.socket = undefined;
|
||||
this.connected = false; this.disconnected();
|
||||
if ([4401, 4403].includes(code)) { this.stop(); this.phase({ state: 'expired' }); this.expired(); return; }
|
||||
if ((fault && !retryable.has(fault)) || [1003, 1008].includes(code)) { this.stop(); this.phase({ state: 'failed', code: fault || 'transport_rejected' }); return; }
|
||||
if (receivedState && healthySince !== undefined && this.now() - healthySince >= 30000) this.failures = 0;
|
||||
else this.failures++;
|
||||
this.schedule(fault);
|
||||
};
|
||||
const abandon = () => {
|
||||
if (!current()) return;
|
||||
this.diagnostic({ type: 'timeout', stage: timeoutKind, lastMessageAgeMs: this.now() - lastMessageAt });
|
||||
try { socket.close(4000, 'Protocol response timeout'); } catch {}
|
||||
// A dead TCP transport can remain CLOSING. Do not wait indefinitely for close.
|
||||
finish();
|
||||
};
|
||||
let handshake = this.timer(abandon, 45000);
|
||||
const heartbeat = () => {
|
||||
if (!current() || socket.readyState !== 1) return;
|
||||
if (pong && this.now() - pong.at >= 15000) { timeoutKind = 'heartbeat'; abandon(); return; }
|
||||
if (!pong) {
|
||||
pong = { nonce: nonce++ % 0x100000000, at: this.now() };
|
||||
try { socket.send(JSON.stringify({ type: 'ping', csrf: this.csrf, nonce: pong.nonce })); } catch { abandon(); return; }
|
||||
}
|
||||
this.timer(heartbeat, 10000);
|
||||
};
|
||||
socket.addEventListener('open', () => {
|
||||
if (!current()) { try { socket.close(1000, 'Connection canceled'); } catch {} return; }
|
||||
try { socket.send(JSON.stringify({ type: 'connect', csrf: this.csrf, heartbeat: true, ...this.options })); } catch { abandon(); return; }
|
||||
this.timer(heartbeat, 10000);
|
||||
});
|
||||
socket.addEventListener('message', ({ data }) => {
|
||||
if (!current()) return;
|
||||
lastMessageAt = this.now();
|
||||
if (data instanceof ArrayBuffer) { if (this.connected) this.event(data); return; }
|
||||
let message; try { message = JSON.parse(data); } catch { return; }
|
||||
if (message.type === 'ts3_pong') { if (pong && message.nonce === pong.nonce) { this.diagnostic({ type: 'heartbeat', roundTripMs: this.now() - pong.at }); pong = undefined; } return; }
|
||||
if (message.type === 'ts3_status') {
|
||||
this.diagnostic({ type: 'protocol_status', stage: message.status });
|
||||
this.connected = message.status === 'connected';
|
||||
if (this.connected) { healthySince = this.now(); this.phase({ state: 'connected' }); }
|
||||
else {
|
||||
this.cancel(handshake); this.timers.delete(handshake); handshake = this.timer(abandon, 45000);
|
||||
this.disconnected(); this.phase({ state: 'connecting', status: message.status });
|
||||
}
|
||||
}
|
||||
if (message.type === 'ts3_state' && this.connected) {
|
||||
receivedState = true; this.cancel(handshake); this.timers.delete(handshake);
|
||||
}
|
||||
if (message.type === 'ts3_error') this.diagnostic({ type: 'protocol_error', code: message.code });
|
||||
if (message.type === 'ts3_error' && !advisory.has(message.code) && (!fault || retryable.has(fault))) fault = message.code;
|
||||
this.event(message);
|
||||
if (fault && !retryable.has(fault)) { try { socket.close(1000, 'Protocol recovery requires owner action'); } catch {} finish(1000); }
|
||||
});
|
||||
socket.addEventListener('close', ({ code }) => finish(code));
|
||||
socket.addEventListener('error', () => { this.diagnostic({ type: 'transport_error' }); /* close/watchdog owns the single retry path */ });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
/** @typedef {import('../src/protocol/types').ProtocolEvent} ProtocolEvent */
|
||||
import { VoiceAudio } from './voice.mjs';
|
||||
import { AudioRecovery } from './audio-recovery.mjs';
|
||||
import { ProtocolConnection } from './protocol-connection.mjs';
|
||||
const $ = id => document.getElementById(id);
|
||||
let csrf;
|
||||
let transport;
|
||||
let capabilities;
|
||||
let protocolLoadGeneration = 0;
|
||||
let identity;
|
||||
let connectionRequested = false;
|
||||
let connectionGeneration = 0;
|
||||
let connected = false;
|
||||
let audio;
|
||||
const audioRecovery = new AudioRecovery();
|
||||
let latestState;
|
||||
let speaking = new Set();
|
||||
const volumes = new Map();
|
||||
export function getParticipantVolume(id) { return volumes.get(id) ?? 1; }
|
||||
export function setParticipantVolume(id, value) {
|
||||
if (!Number.isInteger(id) || !Number.isFinite(value)) return;
|
||||
const volume = Math.max(0, Math.min(2, value)); volumes.set(id, volume); audio?.volume(id, volume);
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-volume', { detail: { id, volume } }));
|
||||
}
|
||||
const pendingCommands = new Map();
|
||||
let nextCommandId = 1;
|
||||
export function clientCommand(command) {
|
||||
if (!connected) return Promise.reject(new Error('Connect to the server first.'));
|
||||
if (pendingCommands.size >= 16) return Promise.reject(new Error('Wait for the current actions to finish.'));
|
||||
const requestId = nextCommandId++; if (nextCommandId > 0xffffffff) nextCommandId = 1;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => { pendingCommands.delete(requestId); reject(new Error('The server did not confirm this action. Check the current state before trying again.')); }, 16000);
|
||||
pendingCommands.set(requestId, { resolve, reject, timer, command });
|
||||
if (!transport.send({ type: 'command', requestId, command })) { clearTimeout(timer); pendingCommands.delete(requestId); reject(new Error('The connection ended before the action was sent.')); }
|
||||
});
|
||||
}
|
||||
export async function joinChannel(channelId, password = '') {
|
||||
await clientCommand({ type: 'join_channel', channelId, ...(password ? { password } : {}) });
|
||||
stopAudio();
|
||||
$('ts3-channel').value = String(channelId);
|
||||
}
|
||||
function cancelCommands() {
|
||||
for (const pending of pendingCommands.values()) { clearTimeout(pending.timer); pending.reject(new Error('The connection ended. The action was not retried.')); }
|
||||
pendingCommands.clear();
|
||||
}
|
||||
function sendCommand(command) {
|
||||
transport?.send(command);
|
||||
}
|
||||
function audioButtons() {
|
||||
$('voice-listen').disabled = !connected;
|
||||
$('voice-mic').disabled = !connected || !audio || audio.outputMuted;
|
||||
$('voice-listen').textContent = audio && !audio.outputMuted ? 'Stop listening' : 'Enable listening';
|
||||
$('voice-mic').textContent = audio && !audio.muted ? 'Mute microphone' : 'Enable microphone';
|
||||
$('voice-ptt').disabled = !audio || audio.muted || !audio.canSend || audio.mode !== 'ptt';
|
||||
$('voice-ptt').hidden = $('voice-mode').value !== 'ptt' || !audio || audio.muted;
|
||||
$('voice-transmission').hidden = !audio || audio.muted;
|
||||
const microphoneOn = Boolean(audio && !audio.muted); const listening = Boolean(audio && !audio.outputMuted);
|
||||
$('voice-mic').setAttribute('aria-pressed', String(microphoneOn)); $('voice-listen').setAttribute('aria-pressed', String(listening));
|
||||
$('voice-heading').textContent = microphoneOn ? $('voice-transmission').classList.contains('transmitting') ? 'On air.' : 'Ready to talk.' : 'Off air.';
|
||||
$('voice-description').textContent = microphoneOn ? 'Your microphone is ready. You control when you transmit.' : 'Your microphone is off. You choose when to join in.';
|
||||
$('room-listening-status').textContent = listening ? 'Listening on' : 'Listening off';
|
||||
$('ribbon-mute').hidden = !microphoneOn;
|
||||
$('ribbon-audio').textContent = `${listening ? 'Listening on' : 'Listening off'} / ${microphoneOn ? 'Microphone enabled' : 'Microphone off'}`;
|
||||
}
|
||||
function setupAudio() {
|
||||
if (audio) return;
|
||||
audio = new VoiceAudio(sendCommand, frame => transport?.voice(frame) ?? false);
|
||||
for (const [clientId, volume] of volumes) audio.volume(clientId, volume);
|
||||
audio.addEventListener('error', event => { stopAudio(); $('voice-status').textContent = event.detail; audioButtons(); });
|
||||
audio.addEventListener('transmitting', event => {
|
||||
$('voice-transmission').textContent = event.detail.active ? '● Transmitting' : 'Microphone idle';
|
||||
$('ribbon-audio').textContent = event.detail.active ? 'On air · Microphone transmitting' : audio && !audio.muted ? 'Microphone enabled' : 'Microphone off';
|
||||
$('voice-transmission').classList.toggle('transmitting', event.detail.active); $('voice-heading').textContent = event.detail.active ? 'On air.' : audio && !audio.muted ? 'Ready to talk.' : 'Off air.';
|
||||
});
|
||||
audio.addEventListener('speaking', event => {
|
||||
speaking = new Set(event.detail.ids);
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-speaking', { detail: [...speaking] }));
|
||||
});
|
||||
audio.addEventListener('stats', event => {
|
||||
const { lost, late, overflow, rejected } = event.detail;
|
||||
$('voice-quality').textContent = `Audio packets: ${lost} missing · ${late} late · ${overflow} queue resets · ${rejected} rejected`;
|
||||
});
|
||||
applyAudioSettings();
|
||||
updateCodec();
|
||||
}
|
||||
function updateCodec() {
|
||||
const own = latestState?.participants.find(client => client.id === latestState.ownClientId);
|
||||
const channel = latestState?.channels.find(channel => channel.id === own?.channelId);
|
||||
if (channel) audio?.channel(channel.codec);
|
||||
}
|
||||
function stopAudio({ recovery = false } = {}) {
|
||||
if (!recovery) audioRecovery.clear();
|
||||
audio?.stop(); audio = undefined; speaking.clear(); if (!recovery) { const ids = [...volumes.keys()]; volumes.clear(); for (const id of ids) window.dispatchEvent(new CustomEvent('voxharbor-volume', { detail: { id, volume: 1 } })); }
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-speaking', { detail: [] }));
|
||||
$('voice-status').textContent = recovery && audioRecovery.pending ? 'Connection interrupted. Your audio recovery choices will apply after reconnect.' : 'Listening and microphone are off.'; $('voice-quality').textContent = '';
|
||||
$('voice-transmission').textContent = 'Microphone off';
|
||||
$('voice-transmission').classList.remove('transmitting');
|
||||
audioButtons();
|
||||
}
|
||||
const errorMessages = {
|
||||
native_unavailable: 'The native protocol executable is not available in this deployment.',
|
||||
identity_required: 'Create or import an identity before connecting.',
|
||||
another_session_is_active: 'Another session for your account is active. Disconnect it first, or wait for its lease to expire.',
|
||||
connection_rate_limit: 'Connection limit reached. Wait one minute before trying again.',
|
||||
identity_storage_or_destination_error: 'Identity storage or destination validation failed. Check the encryption key, Redis and public server address.',
|
||||
handshake_timeout: 'The server handshake timed out. The result is inconclusive; check the voice port, firewall and server availability.',
|
||||
connection_failed: 'The full-client protocol connection failed. Check the voice port, server password and server availability.',
|
||||
server_rejected_connection: 'The server rejected the connection. Check its password, version and identity requirements.',
|
||||
server_permission_or_command_error: 'The server denied a command. Server permissions still apply.',
|
||||
session_lease_lost: 'Session ownership could not be renewed. The protocol connection was stopped.',
|
||||
packet_receive_window_exceeded: 'The incoming packet sequence exceeded the protocol receive window. The connection was stopped.',
|
||||
connection_required: 'Save your connection settings before connecting.',
|
||||
connection_settings_changed: 'Connection settings changed in another session. Reload and connect again.',
|
||||
connection_settings_not_saved: 'The server action succeeded, but its connection settings could not be saved. Save them before reconnecting.',
|
||||
packet_authentication_failed: 'A server packet failed authentication. The connection was stopped.',
|
||||
};
|
||||
async function request(path, input) {
|
||||
const response = await fetch(path, { signal: AbortSignal.timeout(15000), method: input === undefined ? 'GET' : 'POST',
|
||||
...(input === undefined ? {} : { headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf }, body: JSON.stringify(input) }) });
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) window.dispatchEvent(new Event('voxharbor-owner-expired'));
|
||||
const data = await response.json();
|
||||
throw new Error(data.error || 'Protocol operation failed');
|
||||
}
|
||||
return response;
|
||||
}
|
||||
function buttons() {
|
||||
const ready = capabilities?.nativeAvailable && capabilities?.identityEncryptionConfigured;
|
||||
$('identity-create').disabled = !ready || Boolean(identity);
|
||||
$('identity-import').disabled = !ready || Boolean(identity);
|
||||
$('identity-export').disabled = !ready || !identity;
|
||||
$('ts3-connect').disabled = !ready || !identity || connectionRequested;
|
||||
$('ts3-disconnect').disabled = !connectionRequested;
|
||||
for (const button of document.querySelectorAll('[data-disconnect]')) button.disabled = !connectionRequested;
|
||||
$('connection-requirement').hidden = Boolean(identity);
|
||||
$('identity-needed').hidden = !ready || Boolean(identity);
|
||||
$('workspace-readiness').textContent = !capabilities ? 'Loading connection capabilities…' : !ready ? 'The server connection service is unavailable. Please try again later.' : '';
|
||||
$('workspace-readiness').hidden = Boolean(ready);
|
||||
$('editor-connect').disabled = !ready || !identity || connectionRequested;
|
||||
document.querySelector('.identity-grid').hidden = Boolean(identity);
|
||||
window.dispatchEvent(new Event('voxharbor-capabilities'));
|
||||
}
|
||||
function showIdentity() {
|
||||
$('identity-status').textContent = identity ? `UID ${identity.uid} · security level ${identity.level}` : 'No identity stored. Create one once or import your existing identity.';
|
||||
buttons();
|
||||
}
|
||||
export async function loadProtocol(token) {
|
||||
const generation = ++protocolLoadGeneration;
|
||||
csrf = token;
|
||||
try {
|
||||
const nextCapabilities = await (await request('/api/protocol')).json();
|
||||
const nextIdentity = (await (await request('/api/identity')).json()).identity;
|
||||
if (generation !== protocolLoadGeneration) return;
|
||||
capabilities = nextCapabilities; identity = nextIdentity;
|
||||
$('native-status').textContent = !capabilities.nativeAvailable ? 'Native build unavailable' : !capabilities.identityEncryptionConfigured ? 'Configure the separate identity encryption key' : 'Protocol adapter ready · audio starts only when you enable it';
|
||||
showIdentity();
|
||||
} catch (error) { if (generation === protocolLoadGeneration) { $('native-status').textContent = error.message; $('workspace-readiness').hidden = false; $('workspace-readiness').textContent = 'Connection capabilities could not be loaded. Reload to try again.'; } }
|
||||
}
|
||||
export function resetProtocol() {
|
||||
++connectionGeneration; ++protocolLoadGeneration;
|
||||
cancelCommands();
|
||||
connected = false; stopAudio(); latestState = undefined;
|
||||
$('voice-resume-mic').checked = false; $('voice-mode').value = 'ptt'; $('voice-threshold').value = '25';
|
||||
$('voice-input').value = ''; $('voice-output').value = '';
|
||||
transport?.stop('Session ended'); transport = undefined;
|
||||
connectionRequested = false;
|
||||
identity = undefined; capabilities = undefined;
|
||||
csrf = undefined;
|
||||
$('ts3-password').value = '';
|
||||
$('ts3-channel-password').value = '';
|
||||
$('ts3-channels').replaceChildren();
|
||||
$('ts3-state-summary').textContent = ''; $('ts3-status').textContent = 'Not connected';
|
||||
$('identity-status').textContent = 'Loading identity…'; $('native-status').textContent = 'Loading protocol capabilities…';
|
||||
window.dispatchEvent(new Event('voxharbor-reset'));
|
||||
buttons();
|
||||
}
|
||||
$('identity-create').addEventListener('click', async () => {
|
||||
$('identity-create').disabled = true; const generation = protocolLoadGeneration;
|
||||
try {
|
||||
const result = (await (await request('/api/identity/create', {})).json()).identity;
|
||||
if (generation !== protocolLoadGeneration) return;
|
||||
identity = result;
|
||||
showIdentity();
|
||||
$('ts3-status').textContent = 'Identity encrypted and stored. The same identity will be reused.';
|
||||
} catch (error) { if (generation === protocolLoadGeneration) { $('ts3-status').textContent = error.message; buttons(); } }
|
||||
});
|
||||
$('identity-import').addEventListener('change', async event => {
|
||||
const generation = protocolLoadGeneration;
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
try {
|
||||
if (file.size > 16384) throw new Error('Identity file must be smaller than 16 KiB');
|
||||
const value = await file.text(); if (generation !== protocolLoadGeneration) return;
|
||||
const result = (await (await request('/api/identity/import', { value })).json()).identity;
|
||||
if (generation !== protocolLoadGeneration) return; identity = result;
|
||||
showIdentity();
|
||||
} catch (error) { if (generation === protocolLoadGeneration) $('ts3-status').textContent = error.message; }
|
||||
finally { if (generation === protocolLoadGeneration) event.target.value = ''; }
|
||||
});
|
||||
$('identity-export').addEventListener('click', async () => {
|
||||
const generation = protocolLoadGeneration;
|
||||
if (!window.confirm('Export the private TeamSpeak identity? Anyone holding this file can use your identity. Store the backup securely.')) return;
|
||||
try {
|
||||
const response = await request('/api/identity/export', {});
|
||||
const blob = await response.blob(); if (generation !== protocolLoadGeneration) return;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = 'VoxHarbor-identity.ini';
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
} catch (error) { if (generation === protocolLoadGeneration) $('ts3-status').textContent = error.message; }
|
||||
});
|
||||
function renderState(event) {
|
||||
const previousChannel = latestState?.participants.find(client => client.id === latestState.ownClientId)?.channelId;
|
||||
const ownChannel = event.participants.find(client => client.id === event.ownClientId)?.channelId;
|
||||
if (previousChannel && previousChannel !== ownChannel) stopAudio();
|
||||
latestState = event; updateCodec();
|
||||
$('ts3-state-summary').textContent = `${event.server.name} · ${event.channels.length} channels · ${event.participants.length} visible participants · event update ${event.sequence}`;
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-state', { detail: event }));
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-protocol-diagnostic', { detail: { type: 'state', channels: event.channels.length, participants: event.participants.length, sequence: event.sequence } }));
|
||||
}
|
||||
$('ts3-connect').addEventListener('click', async () => {
|
||||
if (connectionRequested) return;
|
||||
const host = $('ts3-host').value.trim(); const port = Number($('ts3-port').value);
|
||||
const nickname = $('ts3-nickname').value.trim();
|
||||
if (!/^[a-zA-Z0-9.-]{1,253}$/.test(host) || !Number.isInteger(port) || port < 1024 || port > 65535 || !nickname) {
|
||||
$('native-status').textContent = 'Enter a server hostname, a port from 1024 to 65535, and your nickname.'; return;
|
||||
}
|
||||
if (!transport) transport = new ProtocolConnection({
|
||||
url: `${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}/api/ts3`,
|
||||
session: async ({ signal }) => {
|
||||
const response = await fetch('/api/session', { signal });
|
||||
if (!response.ok) throw Object.assign(new Error('Session unavailable'), { status: response.status });
|
||||
const session = await response.json(); csrf = session.csrf; return session;
|
||||
},
|
||||
disconnected: () => {
|
||||
cancelCommands();
|
||||
audioRecovery.interrupted(audio, $('voice-resume-mic').checked, !document.hidden);
|
||||
connected = false; stopAudio({ recovery: true });
|
||||
if (latestState && !$('ts3-state-summary').textContent.includes('last received state')) $('ts3-state-summary').textContent += ' · disconnected (last received state)';
|
||||
},
|
||||
diagnostic: detail => window.dispatchEvent(new CustomEvent('voxharbor-protocol-diagnostic', { detail })),
|
||||
expired: () => window.dispatchEvent(new Event('voxharbor-owner-expired')),
|
||||
phase: ({ state, delay, code, status }) => {
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-protocol-diagnostic', { detail: { type: 'phase', state, ...(delay ? { delay } : {}), ...(code ? { code } : {}) } }));
|
||||
if (['stopped', 'failed', 'expired'].includes(state)) { audioRecovery.clear(); $('voice-status').textContent = 'Listening and microphone are off.'; }
|
||||
connectionRequested = Boolean(transport?.desired); connected = state === 'connected';
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-connection', { detail: { state, delay } }));
|
||||
buttons(); audioButtons();
|
||||
const messages = {
|
||||
stopped: 'Disconnected. Microphone and listening are off.',
|
||||
connecting: status ? `Connection: ${status.replaceAll('_', ' ')}…` : 'Opening authenticated protocol transport…',
|
||||
connected: 'Connected through the full TeamSpeak client protocol.',
|
||||
retrying: `Reconnecting in ${Math.ceil((delay || 0) / 1000)} seconds. Audio will resume according to your reconnect choices.`,
|
||||
offline: 'Network offline. Reconnection will resume when the network returns.',
|
||||
failed: errorMessages[code] || 'Automatic recovery stopped. Check the connection error, then connect again.',
|
||||
expired: 'Session expired or was signed out.',
|
||||
};
|
||||
$('ts3-status').textContent = messages[state] || state;
|
||||
},
|
||||
event: message => {
|
||||
if (message instanceof ArrayBuffer) { audio?.receive(message); return; }
|
||||
if (message.type === 'ts3_state') {
|
||||
renderState(message);
|
||||
void audioRecovery.restore({ visible: !document.hidden, create: () => { setupAudio(); return audio; },
|
||||
valid: active => audio === active && connected && !document.hidden,
|
||||
output: $('voice-output').value, microphone: $('voice-input').value,
|
||||
resumeMicrophone: () => $('voice-resume-mic').checked,
|
||||
status: text => { $('voice-status').textContent = text; audioButtons(); } });
|
||||
}
|
||||
else if (message.type === 'ts3_identity') { identity = { ...identity, uid: message.uid, level: message.level }; showIdentity(); }
|
||||
else if (message.type === 'ts3_audio_status') { audio?.permissions(message); audioButtons(); }
|
||||
else if (message.type === 'ts3_connection_saved') window.dispatchEvent(new CustomEvent('voxharbor-connection-saved', { detail: message.preferences }));
|
||||
else if (message.type === 'ts3_message') window.dispatchEvent(new CustomEvent('voxharbor-message', { detail: message }));
|
||||
else if (message.type === 'ts3_command_result') {
|
||||
const pending = pendingCommands.get(message.requestId); if (!pending) return;
|
||||
clearTimeout(pending.timer); pendingCommands.delete(message.requestId);
|
||||
if (message.ok) pending.resolve();
|
||||
else pending.reject(new Error(message.code === 'server_denied_command' ? `The server denied this action${Number.isInteger(message.serverError) ? ` (error ${message.serverError}${Number.isInteger(message.missingPermission) ? `, permission ${message.missingPermission}` : ''})` : ''}. Check your permissions and any required password.` : message.code === 'command_not_sent' ? 'The action was not sent. Its recipient or channel may have changed.' : 'The action could not be confirmed. Check the current server state.'));
|
||||
}
|
||||
else if (message.type === 'ts3_error') $('ts3-status').textContent = errorMessages[message.code] || `Protocol error: ${message.code}`;
|
||||
},
|
||||
});
|
||||
const generation = ++connectionGeneration;
|
||||
const input = { host, port, nickname, channelId: $('ts3-channel').value ? Number($('ts3-channel').value) : null };
|
||||
if ($('ts3-password').value) input.password = $('ts3-password').value;
|
||||
if ($('ts3-channel-password').value) input.channelPassword = $('ts3-channel-password').value;
|
||||
if ($('settings-dialog').dataset.bookmarkId) input.bookmarkId = $('settings-dialog').dataset.bookmarkId;
|
||||
if ($('connection-clear-passwords').checked) { input.password = ''; input.channelPassword = ''; }
|
||||
for (const id of ['ts3-password', 'ts3-channel-password']) { $(id).value = ''; } $('connection-clear-passwords').checked = false;
|
||||
connectionRequested = true; buttons();
|
||||
$('ts3-status').textContent = 'Saving encrypted connection settings…';
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-connection', { detail: { state: 'connecting' } }));
|
||||
try {
|
||||
const preferences = await (await request('/api/connection', input)).json();
|
||||
if (generation !== connectionGeneration || !csrf) return;
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-connection-saved', { detail: preferences }));
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-destination', { detail: preferences.connection }));
|
||||
transport.start({ connectionId: preferences.connection.id });
|
||||
} catch (error) {
|
||||
if (generation !== connectionGeneration) return;
|
||||
connectionRequested = false; buttons();
|
||||
$('ts3-status').textContent = error.message;
|
||||
$('native-status').textContent = error.message;
|
||||
window.dispatchEvent(new CustomEvent('voxharbor-connection', { detail: { state: 'failed' } }));
|
||||
} finally { input.password = ''; input.channelPassword = ''; }
|
||||
|
||||
});
|
||||
window.addEventListener('offline', () => transport?.offline());
|
||||
window.addEventListener('online', () => transport?.online());
|
||||
|
||||
async function devices() {
|
||||
if (!navigator.mediaDevices?.enumerateDevices) return;
|
||||
const entries = await navigator.mediaDevices.enumerateDevices();
|
||||
for (const [id, kind] of [['voice-input', 'audioinput'], ['voice-output', 'audiooutput']]) {
|
||||
const select = $(id); const previous = select.value;
|
||||
select.replaceChildren(new Option('System default', ''));
|
||||
for (const device of entries.filter(device => device.kind === kind && device.deviceId && device.deviceId !== 'default')) select.add(new Option(device.label || `${kind === 'audioinput' ? 'Microphone' : 'Speaker'} ${select.length}`, device.deviceId));
|
||||
if ([...select.options].some(option => option.value === previous)) select.value = previous;
|
||||
}
|
||||
}
|
||||
function applyAudioSettings() {
|
||||
if (!audio) { audioButtons(); return; }
|
||||
audio.mode = $('voice-mode').value;
|
||||
audio.threshold = Number($('voice-threshold').value) / 1000;
|
||||
audio.configure(); audioButtons();
|
||||
}
|
||||
$('voice-listen').addEventListener('click', async () => {
|
||||
audioRecovery.clear();
|
||||
$('voice-listen').disabled = true;
|
||||
setupAudio(); const active = audio;
|
||||
try {
|
||||
await active.listen(active.outputMuted);
|
||||
if (audio !== active) return;
|
||||
$('voice-status').textContent = audio.outputMuted ? 'Listening stopped. Microphone muted.' : 'Listening enabled. Microphone remains off until you enable it.';
|
||||
$('voice-output').disabled = typeof audio.context?.setSinkId !== 'function';
|
||||
await devices();
|
||||
} catch (error) { if (audio === active) { stopAudio(); $('voice-status').textContent = error.message; } }
|
||||
finally { audioButtons(); }
|
||||
});
|
||||
$('voice-mic').addEventListener('click', async () => {
|
||||
audioRecovery.clear();
|
||||
$('voice-mic').disabled = true;
|
||||
const active = audio;
|
||||
try {
|
||||
if (active.muted) await active.microphone($('voice-input').value);
|
||||
else active.mute();
|
||||
if (audio !== active) return;
|
||||
$('voice-status').textContent = audio.muted ? 'Microphone muted.' : audio.mode === 'ptt' ? 'Microphone ready. Hold the talk button or Space while this page has focus.' : 'Voice activation enabled. Speech above the threshold is transmitted when the server permits it.';
|
||||
await devices();
|
||||
} catch (error) { if (audio === active) { audio?.mute(); $('voice-status').textContent = error.name === 'NotAllowedError' ? 'Microphone permission was denied. Enable it in your browser, then try again.' : error.message; } }
|
||||
finally { audioButtons(); }
|
||||
});
|
||||
$('voice-resume-mic').addEventListener('change', () => {
|
||||
if (!$('voice-resume-mic').checked && audioRecovery.restoring) {
|
||||
audioRecovery.clear(); audio?.mute(); audioButtons();
|
||||
$('voice-status').textContent = 'Automatic microphone recovery cancelled. Enable the microphone to talk.';
|
||||
}
|
||||
});
|
||||
for (const id of ['voice-mode', 'voice-threshold']) $(id).addEventListener('change', applyAudioSettings);
|
||||
$('voice-input').addEventListener('change', async () => {
|
||||
audio?.mute(); audioButtons();
|
||||
$('voice-status').textContent = 'Input device changed. Enable the microphone to use it.';
|
||||
});
|
||||
$('voice-output').addEventListener('change', async () => {
|
||||
try {
|
||||
if (typeof audio?.context?.setSinkId !== 'function') throw new Error('Output selection is unavailable in this browser. Use system audio settings.');
|
||||
await audio.context.setSinkId($('voice-output').value);
|
||||
} catch (error) { $('voice-status').textContent = error.message; }
|
||||
});
|
||||
const releaseTalk = () => audio?.ptt(false);
|
||||
$('voice-ptt').addEventListener('pointerdown', event => { if (!$('voice-ptt').disabled) { event.target.setPointerCapture(event.pointerId); audio?.ptt(true); } });
|
||||
for (const type of ['keydown', 'keyup']) $('voice-ptt').addEventListener(type, event => {
|
||||
if (['Space', 'Enter'].includes(event.code)) { event.preventDefault(); audio?.ptt(type === 'keydown'); }
|
||||
});
|
||||
for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) $('voice-ptt').addEventListener(type, releaseTalk);
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.code !== 'Space' || event.repeat || /INPUT|TEXTAREA|SELECT|BUTTON/.test(event.target.tagName) || event.target.isContentEditable || audio?.mode !== 'ptt') return;
|
||||
event.preventDefault(); audio?.ptt(true);
|
||||
});
|
||||
document.addEventListener('keyup', event => { if (event.code === 'Space') releaseTalk(); });
|
||||
window.addEventListener('blur', releaseTalk);
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) { audioRecovery.clear(); audio?.mute(); audioButtons(); } });
|
||||
navigator.mediaDevices?.addEventListener('devicechange', () => { audioRecovery.clear(); audio?.mute(); audioButtons(); void devices().catch(() => {}); });
|
||||
$('ts3-disconnect').addEventListener('click', () => {
|
||||
++connectionGeneration; connectionRequested = false; buttons();
|
||||
transport?.stop();
|
||||
});
|
||||
window.addEventListener('pagehide', () => { ++connectionGeneration; transport?.stop('Page closed'); });
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"id": "/",
|
||||
"name": "VoxHarbor",
|
||||
"short_name": "VoxHarbor",
|
||||
"description": "A self-hosted TeamSpeak 3 web client.",
|
||||
"lang": "en",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#171818",
|
||||
"theme_color": "#171818",
|
||||
"icons": [
|
||||
{ "src": "/icons/app-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
|
||||
{ "src": "/icons/app-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
|
||||
{ "src": "/icons/app-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:400;font-display:swap;src:url('/fonts/ibm-plex-sans-regular.ttf') format('truetype')}
|
||||
@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:500;font-display:swap;src:url('/fonts/ibm-plex-sans-medium.ttf') format('truetype')}
|
||||
@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:600;font-display:swap;src:url('/fonts/ibm-plex-sans-semibold.ttf') format('truetype')}
|
||||
@font-face{font-family:'IBM Plex Mono';font-style:normal;font-weight:400;font-display:swap;src:url('/fonts/ibm-plex-mono-regular.ttf') format('truetype')}
|
||||
@font-face{font-family:'IBM Plex Mono';font-style:normal;font-weight:500;font-display:swap;src:url('/fonts/ibm-plex-mono-medium.ttf') format('truetype')}
|
||||
:root{font-family:'IBM Plex Sans',sans-serif;font-size:14px;line-height:1.5;color-scheme:dark;--bg:#171818;--panel:#222424;--strip:#2b2d2d;--field:#101111;--ink:#dad8cc;--muted:#96978f;--line:#3b3d3b;--accent:#ec8351;--on-accent:#211b16;--control:#dad8cc;--control-ink:#171818;--connected:#c1c99c;color:var(--ink);background:var(--bg)}
|
||||
:root[data-theme=light]{color-scheme:light;--bg:#ecebe4;--panel:#f5f4ef;--strip:#e2e1d8;--field:#fff;--ink:#252724;--muted:#65685e;--line:#cdcec4;--accent:#b94b1d;--on-accent:#fff;--control:#292d28;--control-ink:#faf9f1;--connected:#52642d}
|
||||
*{box-sizing:border-box}body{margin:0}button,input,select,textarea{font:inherit}button,a,input,select,textarea,summary{-webkit-tap-highlight-color:transparent}button{border:1px solid transparent;border-radius:6px;padding:12px 17px;min-height:44px;background:var(--accent);color:var(--on-accent);font-size:13px;font-weight:500;cursor:pointer;transition:background .15s,opacity .15s}button:hover:not(:disabled){filter:brightness(1.12)}button:disabled{opacity:.42;cursor:not-allowed}button.quiet{background:transparent;color:var(--muted);padding:10px 12px}button.quiet:hover:not(:disabled){color:var(--ink);background:var(--strip)}button.secondary{background:var(--control);color:var(--control-ink)}input,select,textarea{width:100%;min-width:0;border:1px solid transparent;border-radius:5px;background:var(--field);color:var(--ink);padding:12px 15px;min-height:44px;font-size:13px}input::placeholder,textarea::placeholder{color:var(--muted);opacity:1}input[type=range]{accent-color:var(--control);padding:0;cursor:pointer}input[type=checkbox]{accent-color:var(--accent);min-height:0;width:16px;height:16px;flex:none}input[type=file]{font-size:12px;border:1px solid var(--line)}input::file-selector-button{background:var(--control);color:var(--control-ink);border:0;border-radius:3px;padding:7px 12px;margin-right:10px}textarea{resize:vertical;min-height:65px;max-height:180px}label{display:block;margin:22px 0 8px;font-size:12px;color:var(--muted)}h1,h2,h3,p{margin:0 0 12px}h1,h2,h3{font-weight:400;line-height:1.15;letter-spacing:-.025em}h1{font-size:32px}h2{font-size:22px}h3{font-size:16px}a{color:inherit;text-decoration:none}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:4px}[hidden]{display:none!important}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.skip-link{position:fixed;left:16px;top:-80px;z-index:20;padding:12px;background:var(--control);color:var(--control-ink)}.skip-link:focus{top:12px}.brand{display:flex;align-items:center;gap:14px;font-size:24px;letter-spacing:-.6px;white-space:nowrap}.mark{display:flex;align-items:center;gap:3px;height:28px;color:var(--accent)}.mark i{display:block;width:3px;height:15px;background:currentColor}.mark i:nth-child(2){height:25px}.mark i:nth-child(3){height:19px}.mark i:nth-child(4){height:29px}.mark i:nth-child(5){height:11px}.eyebrow{font-family:'IBM Plex Mono',monospace;font-size:10px;font-weight:400;letter-spacing:.025em;color:var(--muted);line-height:1.6}.hint{font-size:12px;color:var(--muted);line-height:1.7;overflow-wrap:anywhere}.row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.full-width{width:100%}.connection-fields{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:12px}hr{border:0;border-top:1px solid var(--line);margin:28px 0}.welcome{max-width:1512px;min-height:100dvh;margin:auto;padding:32px;display:grid;grid-template-columns:1.2fr 1fr;column-gap:7%;grid-template-rows:auto 1fr auto}.account-header{grid-column:1/-1;display:flex;align-items:center;gap:100px;border-bottom:1px solid var(--line);padding:8px 4px 22px}.account-header .eyebrow{margin:0}.account-header>.hint{margin:0 5% 0 auto}.welcome-copy{background:var(--panel);border-radius:7px;margin:36px 0 46px;padding:48px 40px;display:flex;flex-direction:column;justify-content:center;min-height:570px}.welcome-copy>.eyebrow{color:var(--accent);margin-bottom:48px}.welcome h1{font-size:clamp(36px,3.4vw,52px);line-height:1.02;margin-bottom:30px}.welcome-copy>p:not(.eyebrow){color:var(--muted);line-height:1.9}.welcome-room{background:var(--strip);padding:30px;border-radius:5px;margin:48px 0 60px}.welcome-room h2{font-size:25px}.welcome-room .hint{margin:0}.welcome-copy .welcome-note{font-size:11px;margin-top:auto;margin-bottom:0}#login{width:100%;max-width:520px;align-self:center;padding:48px 8% 48px 0}#login>.eyebrow{color:var(--accent)}#login h2{font-size:32px;margin-bottom:8px}#login>label{margin-top:35px}#login button{width:100%;margin-top:40px}#login #auth-toggle{text-align:left;padding-left:0;margin:8px 0 26px;font-weight:400}#login .auth-note{border-top:1px solid var(--line);margin-top:32px;padding-top:22px;font-size:11px;line-height:2}.account-footer{grid-column:1/-1;display:flex;justify-content:space-between;border-top:1px solid var(--line);padding:23px 4px 6px;color:var(--muted);font-family:'IBM Plex Mono',monospace;font-size:9px}
|
||||
.topbar{grid-column:1/-1;display:flex;align-items:center;gap:28px;min-height:56px;padding-bottom:9px}.topbar .brand{min-width:250px}.server-selector{display:flex;align-items:center;gap:14px;min-width:0;max-width:40%;text-align:left}.server-selector #server-name{font-family:'IBM Plex Mono',monospace;font-size:10px;text-transform:uppercase;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:190px;color:var(--ink)}#connection-badge{font:9px 'IBM Plex Mono',monospace;text-transform:uppercase;white-space:nowrap}#connection-badge::before{content:'●';font-size:8px;margin-right:6px}#connection-badge[data-state=connected]{color:var(--connected)}#connection-badge[data-state=retrying],#connection-badge[data-state=failed]{color:var(--accent)}.top-actions{margin-left:auto;display:flex;align-items:center;gap:4px}.top-actions button{font-size:12px;padding-inline:8px}#account-label{margin-left:35px;color:var(--ink);max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.rooms-bar{grid-column:1/-1;background:var(--panel);border-radius:6px;display:flex;align-items:center;gap:14px;min-height:62px;padding:8px}.room-finder{font:9px 'IBM Plex Mono',monospace!important;flex:none}.room-finder span{margin-left:8px;font-size:17px}#room-tabs{list-style:none;display:flex;gap:6px;flex:1;overflow:auto;margin:0;padding:0;scrollbar-width:thin}#room-tabs li{flex:1;min-width:140px}#room-tabs button{width:100%;background:transparent;color:var(--muted);font-weight:400;text-align:left;white-space:nowrap;display:flex;align-items:center;justify-content:space-between;gap:14px;padding:12px 16px}#room-tabs button[aria-current=true]{background:var(--control);color:var(--control-ink)}#room-tabs .room-number{font-family:'IBM Plex Mono',monospace;font-size:10px}#quick-connect{font-size:11px;white-space:nowrap}.conversation{display:contents}.room-panel{grid-column:1;grid-row:3;background:var(--panel);border-radius:7px;padding:24px 20px 20px;display:flex;flex-direction:column;min-width:0}.channel-header{display:flex;justify-content:space-between;align-items:center;gap:16px;margin:0 0 20px}.channel-header h1{font-size:30px;margin-bottom:8px;overflow-wrap:anywhere}.channel-header .eyebrow{font-size:9px;margin:0;text-transform:uppercase}.room-audio-status{text-align:right;flex-shrink:0;font-size:12px;color:var(--accent)}.room-audio-status .hint{font-size:11px;margin:4px 0 0}.members{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px;flex:1;align-content:start;min-height:310px}.member{position:relative;background:var(--strip);border-radius:6px;padding:20px;min-width:0;display:flex;flex-direction:column;min-height:345px;border:1px solid transparent}.member.speaking{border-color:var(--accent)}.member-top{display:flex;align-items:center;justify-content:space-between;color:var(--muted);font:10px 'IBM Plex Mono',monospace;margin-bottom:24px}.member .member-info strong{display:block;font-size:20px;font-weight:400;overflow-wrap:anywhere;line-height:1.3;margin-bottom:16px}.member-info .hint{font:10px 'IBM Plex Mono',monospace;display:block;min-height:16px}.member-info .hint::before{content:'▪';margin-right:8px;color:var(--muted)}.member.speaking .hint,.member.speaking .hint::before{color:var(--accent)}.member-mix{display:flex;justify-content:space-between;gap:8px;min-height:125px;margin-top:14px}.volume-value{font-family:'IBM Plex Mono',monospace;font-size:37px;line-height:1}.volume-value small{font-size:8px;display:block;color:var(--muted);margin-top:10px}.volume-label{font-size:12px;color:var(--muted);margin-top:30px}.fader{position:relative;min-width:68px;width:40%;display:flex;justify-content:center;background:repeating-linear-gradient(to bottom,transparent 0 15px,var(--line) 15px 16px) left center/20px calc(100% - 22px) no-repeat}.fader input{writing-mode:vertical-lr;direction:rtl;appearance:none;width:7px;min-height:0;height:124px;background:var(--field);padding:0;flex:none;margin:0 8px 0 0;border-radius:5px}.fader input::-webkit-slider-thumb{appearance:none;width:38px;height:29px;border-radius:4px;background:linear-gradient(to bottom,var(--control) 0 47%,#53554e 47% 53%,var(--control) 53% 100%);border:0;box-shadow:0 0 0 1px #17181830}.fader input::-moz-range-thumb{width:38px;height:29px;border:0;border-radius:4px;background:var(--control)}.fader-scale{display:flex;flex-direction:column;justify-content:space-between;font:9px 'IBM Plex Mono',monospace;color:var(--muted);padding:0 0 0 8px}.member-actions{margin-top:auto;padding-top:16px;border-top:1px solid var(--line);display:flex;gap:12px}.member-actions button{font-size:11px;min-height:32px;padding:4px 0;flex:1;text-align:left}.member-actions button:first-child{color:var(--ink)}.room-empty{grid-column:1/-1;align-self:center;padding:55px 15px;text-align:center}.room-empty h2{font-size:28px}.room-empty button{margin-top:20px}.channel-footer{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:20px;min-height:30px}.channel-footLine truncated
|
||||
/* The application shell contains separate pages; voice remains live when navigating. */
|
||||
.app-shell{max-width:1600px;margin:auto;padding:24px 32px 12px;min-height:100dvh}.topbar{border-bottom:1px solid var(--line);padding-bottom:18px;margin-bottom:24px;gap:18px}.topbar .brand{min-width:210px}.page-breadcrumb{margin:0}.topbar>.eyebrow{margin:0;flex:1}.top-actions{flex:none}.top-actions button[aria-current=page]{color:var(--ink);background:var(--panel)}#account-label{margin-left:12px}.app-shell:not([data-page=console]) .server-selector{display:none}.app-shell[data-page=console] #page-breadcrumb{display:none}.session-ribbon{display:flex;gap:20px;align-items:center;padding:10px 18px;background:var(--strip);border-radius:5px;font-size:11px;margin-bottom:12px}.session-ribbon button{margin-left:auto;min-height:32px;font-size:11px;padding:4px 8px}#ribbon-status{color:var(--connected)}#ribbon-audio{color:var(--muted)}.app-page{padding:30px 40px 40px;min-height:calc(100dvh - 175px)}.page-heading{display:flex;align-items:center;justify-content:space-between;gap:24px;margin:0 0 48px}.page-heading .eyebrow{color:var(--accent);margin-bottom:12px}.page-heading h1{font-size:34px;margin-bottom:12px}.page-heading .hint{margin:0}.page-heading>.row{flex-shrink:0}.page-heading button{min-width:160px}.settings-surface{padding:30px;background:var(--panel);border-radius:6px;margin:0 0 24px}.settings-surface>label:first-child{margin-top:0}.settings-surface>button{margin-top:22px}.editor-grid{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(280px,1fr);gap:24px;align-items:start}.host-fields{display:grid;grid-template-columns:1fr 160px;gap:22px}.editor-actions{display:flex;gap:22px;margin-top:36px}.editor-actions>button{flex:1}.editor-actions+p{margin-top:16px}#native-status{font-size:11px;margin:12px 0 0;color:var(--muted)}.field-note{margin-top:40px!important}.callout{border-left:2px solid var(--accent);padding:18px 20px;background:var(--strip);border-radius:0 5px 5px 0;margin:22px 0}.callout strong{font-size:13px;font-weight:400}.callout .hint{margin:7px 0 0}.callout button{margin-top:16px}.danger{color:var(--accent)!important}.destination-table{background:var(--panel);padding:24px 30px;border-radius:6px;min-height:290px}.destination-columns,.destination-row{display:grid;grid-template-columns:minmax(200px,2fr) minmax(80px,.8fr) minmax(110px,.8fr) minmax(200px,1.2fr);gap:24px;align-items:center}.destination-columns{font:9px 'IBM Plex Mono',monospace;color:var(--muted);border-bottom:1px solid var(--line);padding-bottom:18px}.destination-row{padding:28px 0;border-bottom:1px solid var(--line)}.destination-row:last-child{border-bottom:0}.destination-row h2{font-size:21px;margin-bottom:10px;overflow-wrap:anywhere}.destination-row p{font-size:11px;margin:0}.destination-nickname{font-size:13px;overflow-wrap:anywhere}.destination-state{font-size:12px;color:var(--muted)}.destination-state.is-active{color:var(--connected)}.destination-row .row{gap:8px;justify-content:flex-end}.destination-row button{font-size:12px;min-width:65px}.destination-row button.secondary{min-width:105px}.destinations-empty{padding:50px 16px;text-align:center}.destinations-empty button{margin-top:20px}.destinations-empty h2{font-size:27px}#recent-connection{display:flex;align-items:center;justify-content:space-between;margin-top:24px;gap:20px}#recent-connection h2{font-size:20px}#recent-connection p{margin-bottom:5px}.identity-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px}.identity-grid h2{font-size:28px;margin:20px 0}.identity-grid .hint{max-width:430px;min-height:48px}.identity-grid button{width:100%}.identity-ready .row{margin:28px 0}#identity-status{font:14px/1.9 'IBM Plex Mono',monospace;overflow-wrap:anywhere;background:var(--field);padding:20px;border-radius:4px}.identity-ready>.hint{margin:0}.settings-columns{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(280px,1fr);gap:24px}.settings-columns .settings-surface{margin-bottom:24px}.processing{background:var(--control);color:var(--control-ink)}.processing .eyebrow,.processing .hint{color:inherit}.processing>p:not(.eyebrow):not(.hint){margin:26px 0;font-size:13px}.processing>.hint{margin-top:42px;font-size:11px}.mode-heading{margin-top:34px}.mode-options{margin:26px 0 24px}.mode-options button{flex:1;background:var(--control);color:var(--control-ink)}.mode-options button[aria-pressed=true]{background:var(--accent);color:var(--on-accent)}.checkbox-label{display:flex;align-items:start;gap:10px;font-size:12px;line-height:1.7}.checkbox-label input{margin-top:3px}.section-title{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-bottom:18px;border-bottom:1px solid var(--line);margin-bottom:8px}.section-title h2{font-size:16px;margin:0}.section-title span{font:10px 'IBM Plex Mono',monospace;color:var(--muted)}.channel-browser{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(280px,1fr);gap:24px;align-items:start;margin-top:30px}.channel-browser .settings-surface{padding:24px}.channel-detail{background:var(--control);color:var(--control-ink);Line truncated
|
||||
.console-page{display:grid;grid-template-columns:minmax(0,2.5fr) minmax(305px,1fr);grid-template-rows:auto minmax(480px,auto) auto;gap:20px;min-height:calc(100dvh - 165px)}.console-page .rooms-bar{grid-column:1/-1;grid-row:1}.console-page .room-panel{grid-column:1;grid-row:2}.console-page .voice-dock{grid-column:2;grid-row:2}#console-chat-slot{display:contents}.console-page .chat-panel{grid-column:1/-1;grid-row:3}#room-tabs li{max-width:240px;min-width:120px}.room-finder{font-size:10px!important}#quick-connect{margin-left:auto}.mixer-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;margin:-4px 0 14px}.mixer-toolbar .hint{margin:0;font-size:10px}.mixer-toolbar button{font-size:11px;min-height:34px;padding:4px 8px}.members{max-height:520px;overflow:auto;min-height:320px;scrollbar-width:thin}.member{min-height:330px}.member-top{margin-bottom:24px}.member-info .hint{overflow-wrap:anywhere}.members.compact-members{display:flex;flex-direction:column;gap:8px;align-items:stretch}.compact-members .member{min-height:100px;display:grid;grid-template-columns:30px minmax(100px,1fr) 160px 130px;gap:16px;align-items:center}.compact-members .member-top{margin:0}.compact-members .member-info strong{font-size:17px;margin-bottom:8px}.compact-members .member-mix{min-height:0;align-items:center;margin:0;gap:10px}.compact-members .volume-value{font-size:22px}.compact-members .volume-value small,.compact-members .volume-label,.compact-members .fader-scale{display:none}.compact-members .fader{background:none;min-width:0;width:100%}.compact-members .fader input{writing-mode:horizontal-tb;direction:ltr;appearance:auto;width:100%;height:26px;margin:0}.compact-members .fader input::-webkit-slider-thumb{appearance:auto;width:auto;height:auto;background:none;box-shadow:none}.compact-members .member-actions{margin:0;padding:0;border:0;gap:8px}.compact-members .member-actions button{min-height:44px}.voice-heading{margin-bottom:24px}.voice-dock>h2{margin-bottom:18px}.voice-switches{margin:12px 0 16px}.voice-switches #voice-mic::before{content:'';width:22px;height:22px;background:url('/icons/microphone.svg') center no-repeat}.voice-switches #voice-listen::before{content:'';width:22px;height:22px;background:url('/icons/headphones.svg') center no-repeat}.voice-dock .disconnect-button{margin-top:12px}.voice-transmission{clear:both}.chat-tabs{display:flex;align-items:center;gap:6px;min-width:0}.chat-tabs button{max-width:240px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:400}.chat-tabs button[aria-pressed=true]{color:var(--ink)}.chat-header #poke-open{font-size:11px}.console-footer{display:flex;padding-top:18px;border-top:1px solid var(--line);margin-top:24px}.console-footer>div{line-height:1.7}.console-footer>button{flex:none}.direct-grid{display:grid;grid-template-columns:230px minmax(0,1fr) 290px;gap:24px;min-height:550px}.thread-list{background:var(--panel);padding:24px 16px;border-radius:6px}.thread{display:block;text-align:left;width:100%;background:transparent;color:var(--ink);padding:14px;margin:8px 0}.thread[aria-pressed=true]{background:var(--strip)}.thread strong{display:block;font-size:14px;font-weight:400;overflow-wrap:anywhere}.thread .hint{display:block;font-size:10px;margin-top:4px}.thread-list>button{display:block;width:100%;text-align:left;font-size:12px}#direct-chat-slot{min-width:0}#direct-chat-slot .chat-panel{height:100%;display:flex;flex-direction:column;padding:28px}#direct-chat-slot .chat-header{align-items:start;flex-wrap:wrap}#direct-chat-slot .chat-header h2{display:none}#direct-chat-slot .chat-tabs{display:none}#direct-chat-slot .chat-header>p{margin:0 auto;font-size:10px}#direct-chat-slot #chat-context{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto;white-space:normal;font-size:15px;color:var(--ink);display:block;padding-bottom:20px}#direct-chat-slot .chat-body{display:flex;flex-direction:column;flex:1}#direct-chat-slot .message-history{flex:1;min-height:240px}#direct-chat-slot .messages{max-height:360px}#direct-chat-slot .message{display:block;padding:15px 0;border-top:1px solid var(--line)}#direct-chat-slot .message-heading{flex-direction:row;justify-content:space-between;margin-bottom:12px}#direct-chat-slot .message-heading strong{max-width:80%;white-space:normal}#direct-chat-slot .composer-actions .hint{display:none}.direct-grid .channel-detail{position:static}.direct-grid label{margin-top:40px}.direct-grid #direct-poke{margin-top:30px}.direct-grid #direct-volume{padding:0;background:transparent;accent-color:#171818}
|
||||
dialog{padding:28px;width:480px;max-width:calc(100vw - 32px);max-height:90dvh;border:1px solid var(--line);border-radius:8px;background:var(--bg);color:var(--ink);box-shadow:0 20px 90px #0006}dialog::backdrop{background:#0b0d0bbd;backdrop-filter:blur(4px)}.dialog-heading{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-bottom:24px}.dialog-heading h2{margin:0}.dialog-heading button{flex:none}#confirm-description{font-size:14px;line-height:1.8;color:var(--muted);margin-bottom:26px}#poke-recipient{overflow-wrap:anywhere;font-size:19px}#poke-status{font-size:12px;margin:18px 0}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.6 'IBM Plex Mono',monospace;max-height:520px;overflow:auto;background:var(--field);padding:22px}.notice-toast{position:fixed;right:20px;top:20px;z-index:20;max-width:min(520px,calc(100vw - 32px));display:flex;align-items:start;gap:8px;border:1px solid var(--line);border-left:3px solid var(--accent);border-radius:6px;background:var(--panel);padding:6px;box-shadow:0 8px 40px #0005}#notice{margin:0;padding:10px 8px 10px 12px;font-size:12px}#notice-dismiss{flex:none;min-width:44px;min-height:44px;padding:8px}.signin-copy{display:contents}.registration-copy{display:none}.signin-copy>.eyebrow{color:var(--accent);margin-bottom:48px}.signin-copy>p:not(.eyebrow){color:var(--muted);line-height:1.9}.welcome[data-auth-mode=register] .welcome-copy{grid-column:2;grid-row:2;min-height:0;align-self:center;background:transparent;padding:0 24px;margin:40px 0}.welcome[data-auth-mode=register] .signin-copy{display:none}.welcome[data-auth-mode=register] .registration-copy{display:block}.registration-copy section{background:var(--strip);border-radius:5px;padding:26px;margin-bottom:20px}.registration-copy h2{font-size:22px}.registration-copy .eyebrow{color:var(--accent)}.welcome[data-auth-mode=register] #login{grid-column:1;grid-row:2;background:var(--panel);border-radius:7px;padding:34px;max-width:none;margin:40px 0}
|
||||
@media(max-width:1200px){.topbar{flex-wrap:wrap;gap:12px}.topbar .brand{min-width:170px}.top-actions{margin-left:auto}#account-label{max-width:150px}.topbar>.eyebrow{font-size:9px}.app-page{padding:24px 12px 36px}.direct-grid{grid-template-columns:190px minmax(0,1fr) 240px;gap:16px}.destination-columns,.destination-row{grid-template-columns:minmax(170px,1.6fr) 90px 100px minmax(180px,1.2fr);gap:16px}.console-page{grid-template-columns:minmax(0,2fr) 300px}.members{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.member{padding:16px;min-height:320px}.member-info strong{font-size:19px!important}.compact-members .member{grid-template-columns:22px minmax(85px,1fr) 100px}.compact-members .member-actions{grid-column:2/4}.chat-header h2{min-width:140px}.voice-dock{padding:24px 20px 12px}.page-heading{margin-bottom:34px}}
|
||||
@media(max-width:900px){.app-shell{padding:18px}.topbar>.eyebrow{display:none}.topbar .brand{min-width:0}.top-actions{width:100%;padding-top:8px;justify-content:flex-end;border-top:1px solid var(--line)}.server-selector{margin-left:auto;max-width:65%}.app-shell:not([data-page=console]) .top-actions{width:auto;border-top:0}#account-label{max-width:120px;margin-left:0}.editor-grid,.settings-columns,.channel-browser{grid-template-columns:minmax(0,1.3fr) minmax(250px,1fr);gap:18px}.settings-surface,.channel-detail{padding:24px}.host-fields{grid-template-columns:1fr 105px;gap:12px}.editor-actions{flex-direction:column;gap:12px}.direct-grid{grid-template-columns:180px minmax(0,1fr)}.direct-grid>.channel-detail{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr;gap:12px;align-items:center}.direct-grid>.channel-detail .field-note{grid-column:1/-1}.direct-grid>.channel-detail h2,.direct-grid>.channel-detail p{margin:0}.direct-grid>.channel-detail label{margin:0}.destination-nickname{display:none}.destination-columns,.destination-row{grid-template-columns:minmax(180px,1.7fr) 100px minmax(160px,1fr)}.destination-columns>span:nth-child(2){display:none}.destination-row button.secondary{min-width:85px}.destination-table{padding:20px}.console-page{grid-template-columns:minmax(0,1fr) 280px;gap:14px}.room-panel{padding:20px 14px}.room-audio-status{display:none}.channel-header h1{font-size:25px}.member-info strong{font-size:17px!important}.fader{min-width:58px}.fader-scale{font-size:8px;padding-left:2px}.member{padding:14px}.member-mix{gap:3px}.volume-value{font-size:30px}.chat-body{grid-template-columns:1.2fr 1fr;gap:16px}.message{display:block}.message-heading{margin-bottom:8px}.composer-actions .hint{display:none}.composer-actions{justify-content:flex-end}.page-heading h1{font-size:30px}.page-heading>.row button{min-width:0}.session-ribbon{flex-wrap:wrap;gap:4px 16px}.session-ribbon button{margin-left:auto}.console-footer{font-size:8px;gap:14px}.channel-result{padding:12px 8px;gap:10px}.channel-result>.hint{max-width:90px}.channel-result strong{font-size:14px}.welcome{padding:24px;grid-template-columns:1.1fr 1fr;column-gap:6%}.account-header{gap:40px}.account-header>.hint{display:none}.welcome-copy{min-height:600px;padding:32px 24px}.signin-copy>.eyebrow{margin-bottom:35px;font-size:9px}.welcome h1{font-size:36px}.signin-copy>p:not(.eyebrow){font-size:13px}.welcome-room{padding:24px;margin:30px 0}#login{padding:40px 0}#login h2{font-size:29px}}
|
||||
@media(max-width:660px){.app-shell{padding:16px 14px 0}.app-page{padding:14px 2px 24px;min-height:calc(100dvh - 180px)}.topbar{padding:0 0 12px;margin-bottom:20px;gap:10px}.topbar .brand{font-size:22px}.mark{gap:2px}.mark i{width:2px}.topbar .server-selector{max-width:55%;padding:4px 0;gap:6px}.server-selector #server-name{max-width:90px;font-size:8px}#connection-badge{font-size:8px}.top-actions{gap:0;justify-content:space-between;width:100%!important;border-top:1px solid var(--line)!important;padding-top:6px}.top-actions button{font-size:11px;min-height:44px;padding:8px 7px}#account-label{max-width:100px}.page-heading{display:block;margin-bottom:28px}.page-heading .eyebrow{font-size:9px}.page-heading h1{font-size:30px}.page-heading>.row{margin-top:20px}.page-heading button{min-width:0;min-height:44px}.editor-grid,.settings-columns,.identity-grid,.channel-browser{display:flex;flex-direction:column;gap:0}.editor-grid>*,.settings-columns>*,.channel-browser>*{width:100%}.editor-grid>aside{display:flex;flex-direction:column}.editor-grid .settings-surface{order:1}.editor-grid>aside .settings-surface{margin-bottom:0}.settings-surface{padding:24px 20px;margin-bottom:18px}.host-fields{grid-template-columns:1fr 100px}.callout{padding:16px;margin:18px 0}.field-note{margin-top:26px!important}.identity-grid .settings-surface{width:100%}.identity-grid h2{font-size:25px}.destination-columns{display:none}.destination-table{padding:4px 20px;min-height:0}.destination-row{display:grid;grid-template-columns:1fr auto;gap:16px;padding:23px 0}.destination-row>div:first-child{grid-column:1/-1}.destination-row h2{font-size:21px}.destination-row .row{gap:4px}.destination-row button{min-height:44px;font-size:11px}.destination-state{font-size:11px}.destination-nickname{display:none}.destinations-empty{padding:36px 4px}.destinations-empty h2{font-size:26px}#recent-connection{display:block}#recent-connection button{margin-top:18px}.channel-browser{margin-top:22px}.channel-browser>.settings-surface{padding:18px 12px}.channel-detail{position:static;padding:24px}.channel-detail h2{margin-top:20px;font-size:26px}#ts3-channels{max-height:340px;min-height:100px}.channel-result{gap:8px;padding:12px 8px}.channel-result strong{font-size:14px}.channel-result>.hint{font-size:9px;max-width:83px}#ts3-channels li[data-depth="1"]{padding-left:10px}#ts3-channels li[data-depth="2"],#ts3-channels li[data-depth="3"],#ts3-channels li[data-depth="4"]{padding-left:20px}.channel-detail li button{min-height:44px}.console-page{display:flex;flex-direction:column;gap:16px;min-height:0}.rooms-bar{gap:3px;padding:5px;min-height:54px}.room-finder{font-size:8px!important;padding:8px!important}.rooms-bar #quick-connect{display:none}#room-tabs li{min-width:135px}#room-tabs button{padding:10px 12px;font-size:12px}.room-panel{padding:20px 14px 14px}.channel-header{margin-bottom:14px}.channel-header h1{font-size:26px}.channel-header .eyebrow{font-size:8px}.mixer-toolbar{margin-bottom:8px}.mixer-toolbar button{display:none}.mixer-toolbar .hint{font-size:9px}.members,.members.compact-members{display:flex;flex-wrap:nowrap;flex-direction:column;align-items:stretch;gap:10px;min-height:0;max-height:460px}.member,.compact-members .member{width:100%;min-height:130px;display:grid;grid-template-columns:20px minmax(0,1fr) 95px;grid-template-rows:auto auto;column-gap:8px;padding:14px}.member-top,.compact-members .member-top{font-size:8px;grid-column:1;grid-row:1;margin:4px 0 0}.member .member-info,.compact-members .member-info{grid-column:2;grid-row:1}.member .member-info strong,.compact-members .member-info strong{font-size:15px!important;margin-bottom:8px}.member-info .hint{font-size:9px}.member-mix,.compact-members .member-mix{grid-column:3;grid-row:1;min-height:0;flex-direction:column;margin:0;gap:4px;align-items:stretch}.volume-value,.compact-members .volume-value{font-size:20px}.volume-value small,.volume-label,.fader-scale{display:none}.fader{width:100%;min-width:0;background:none;padding:0}.fader input,.compact-members .fader input{writing-mode:horizontal-tb;direction:ltr;appearance:auto;width:100%;height:24px;margin:0}.fader input::-webkit-slider-thumb{appearance:auto;width:auto;height:auto;background:none;box-shadow:none}.member-actions,.compact-members .member-actions{grid-column:2/4;grid-row:2;gap:20px;padding:0;margin-top:4px;border:0}.member-actions button,.compact-members .member-actions button{flex:none;min-height:44px;font-size:11px;padding:4px}.channel-footer{gap:8px;margin-top:14px;align-items:start}.channel-footer>.hint{max-width:60%;font-size:10px}.channel-footer button{font-size:10px}.chat-panel{padding:18px 14px;min-height:280px}.chat-header{gap:3px;flex-wrap:wrap;margin-bottom:14px}.chat-header h2{font-size:8px;min-width:86px}.chat-header button{font-size:11px;min-height:44px;padding:8px 6px}.chat-tabs{gap:0}.chat-tabs button{max-width:130px}.chat-header>p{display:none}.chat-body{grid-template-columns:1fr;gap:16px}.message-history{min-height:95px}.messages{mLine truncated
|
||||
@media(prefers-reduced-motion:reduce){*{transition:none!important;scroll-behavior:auto!important}}
|
||||
|
||||
.page-heading h1:focus{outline:none}.app-shell[data-connection=retrying] .console-footer,.app-shell[data-connection=failed] .console-footer{color:var(--accent)}
|
||||
|
||||
.skip-link:not(:focus){clip-path:inset(50%)}.channel-detail #browse-participants{max-height:240px;overflow:auto;scrollbar-width:thin}.channel-browser>.channel-detail{max-height:calc(100dvh - 180px);overflow:auto;scrollbar-width:thin}#ribbon-mute{margin-left:0;background:var(--control);color:var(--control-ink)}
|
||||
@media(max-width:660px){.channel-browser>.channel-detail{max-height:none}.top-actions button{padding-inline:5px;font-size:10px}.session-ribbon #ribbon-mute{width:auto}.session-ribbon>button:last-child{width:auto;margin-left:auto}}
|
||||
|
||||
#direct-chat-slot #poke-open{display:none}#conversation-threads{max-height:450px;overflow:auto;scrollbar-width:thin}.composer-actions{justify-content:flex-end}.app-page>label{margin-top:0}.direct-grid .chat-empty{top:75px;font-size:13px}
|
||||
@media(max-width:660px){#conversation-threads{max-height:145px}}
|
||||
|
||||
#direct-tools-toggle{display:none}#editor-mobile-actions:empty{display:none}
|
||||
@media(max-width:660px){#editor-mobile-actions{padding:20px;background:var(--panel);border-radius:6px;margin-top:18px}.editor-actions{margin-top:0}#direct-tools-toggle{display:block;margin:-10px 0 20px;padding-inline:0}.direct-grid>.thread-list{order:0}.direct-grid>#direct-chat-slot{order:2}.direct-grid>.channel-detail{display:none;order:1}.direct-grid.show-direct-controls>.channel-detail{display:block}}
|
||||
@@ -0,0 +1,44 @@
|
||||
Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic,
|
||||
Jean-Marc Valin, Timothy B. Terriberry,
|
||||
CSIRO, Gregory Maxwell, Mark Borgerding,
|
||||
Erik de Castro Lopo, Mozilla, Amazon
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
- Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
- Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
- Neither the name of Internet Society, IETF or IETF Trust, nor the
|
||||
names of specific contributors, may be used to endorse or promote
|
||||
products derived from this software without specific prior written
|
||||
permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
|
||||
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
Opus is subject to the royalty-free patent licenses which are
|
||||
specified at:
|
||||
|
||||
Xiph.Org Foundation:
|
||||
https://datatracker.ietf.org/ipr/1524/
|
||||
|
||||
Microsoft Corporation:
|
||||
https://datatracker.ietf.org/ipr/1914/
|
||||
|
||||
Broadcom Corporation:
|
||||
https://datatracker.ietf.org/ipr/1526/
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 openclaw
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"package": "libopus-wasm",
|
||||
"version": "0.3.0",
|
||||
"generatedSha256": "0041fc800ccd26f56b27eaeb1834c8c6854e5167d48cd628a4f98ec5b590c6f1",
|
||||
"licenseSource": "https://github.com/xiph/opus/blob/v1.6.1/COPYING",
|
||||
"note": "The unchanged upstream-generated WASM includes published upstream compiler/assertion build paths; no owner configuration is embedded."
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# Third-party notices
|
||||
|
||||
This package builds and distributes WebAssembly generated from Xiph.Org's
|
||||
`libopus`.
|
||||
|
||||
## libopus
|
||||
|
||||
- Source: https://github.com/xiph/opus
|
||||
- Release source: https://downloads.xiph.org/releases/opus/
|
||||
- License: BSD-style license, see the upstream source archive for the full text.
|
||||
|
||||
The JavaScript and TypeScript wrapper code in this repository is MIT licensed.
|
||||
@@ -0,0 +1,666 @@
|
||||
import createLibopusModule from "./generated/libopus.generated.mjs";
|
||||
export const Application = {
|
||||
Voip: 2048,
|
||||
Audio: 2049,
|
||||
RestrictedLowDelay: 2051,
|
||||
};
|
||||
export const Signal = {
|
||||
Auto: -1000,
|
||||
Voice: 3001,
|
||||
Music: 3002,
|
||||
};
|
||||
export const Bitrate = {
|
||||
Auto: -1000,
|
||||
Max: -1,
|
||||
};
|
||||
export const Bandwidth = {
|
||||
Narrowband: 1101,
|
||||
Mediumband: 1102,
|
||||
Wideband: 1103,
|
||||
Superwideband: 1104,
|
||||
Fullband: 1105,
|
||||
};
|
||||
export const EncoderCtl = {
|
||||
SetApplication: 4000,
|
||||
SetBitrate: 4002,
|
||||
SetMaxBandwidth: 4004,
|
||||
SetVbr: 4006,
|
||||
SetBandwidth: 4008,
|
||||
SetComplexity: 4010,
|
||||
SetInBandFec: 4012,
|
||||
SetPacketLossPercent: 4014,
|
||||
SetDtx: 4016,
|
||||
SetVbrConstraint: 4020,
|
||||
SetForceChannels: 4022,
|
||||
SetSignal: 4024,
|
||||
SetLsbDepth: 4036,
|
||||
SetExpertFrameDuration: 4040,
|
||||
SetPredictionDisabled: 4042,
|
||||
SetPhaseInversionDisabled: 4046,
|
||||
};
|
||||
export const DecoderCtl = {
|
||||
SetGain: 4034,
|
||||
SetPhaseInversionDisabled: 4046,
|
||||
};
|
||||
const DEFAULT_CHANNELS = 2;
|
||||
const DEFAULT_FRAME_DURATION_MS = 20;
|
||||
const MAX_PACKET_DURATION_MS = 120;
|
||||
const DEFAULT_MAX_PACKET_BYTES = 4000;
|
||||
const MAX_I32 = 0x7fff_ffff;
|
||||
const DEFAULT_SAMPLE_RATE = 48_000;
|
||||
const DECODER_INTEGER_CTL_REQUESTS = new Set(Object.values(DecoderCtl));
|
||||
const ENCODER_INTEGER_CTL_REQUESTS = new Set(Object.values(EncoderCtl));
|
||||
const ENCODE_FRAME_DURATIONS_MS = [2.5, 5, 10, 20, 40, 60];
|
||||
const VALID_SAMPLE_RATES = [8000, 12000, 16000, 24000, 48000];
|
||||
let modulePromise;
|
||||
export async function loadLibopus() {
|
||||
const module = await getModule();
|
||||
return { version: module.UTF8ToString(module._oc_get_version_string()) };
|
||||
}
|
||||
export async function createEncoder(options = {}) {
|
||||
const module = await getModule();
|
||||
return new WasmOpusEncoder(module, normalizeEncoderOptions(options));
|
||||
}
|
||||
export async function createDecoder(options = {}) {
|
||||
const module = await getModule();
|
||||
return new WasmOpusDecoder(module, normalizeDecoderOptions(options));
|
||||
}
|
||||
export async function getPacketInfo(packet, options = {}) {
|
||||
const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
|
||||
validateCodecOptions({ channels: DEFAULT_CHANNELS, sampleRate });
|
||||
if (packet.byteLength === 0) {
|
||||
throw new RangeError("packet must not be empty");
|
||||
}
|
||||
const module = await getModule();
|
||||
const packetPtr = checkedMalloc(module, packet.byteLength);
|
||||
try {
|
||||
module.HEAPU8.set(packet, packetPtr);
|
||||
const decodedSamples = module._oc_packet_validate_decode(packetPtr, packet.byteLength, sampleRate);
|
||||
if (decodedSamples < 0) {
|
||||
throw createOpusError(module, decodedSamples, "getPacketInfo");
|
||||
}
|
||||
const frames = module._oc_packet_parse(packetPtr, packet.byteLength);
|
||||
if (frames < 0) {
|
||||
throw createOpusError(module, frames, "getPacketInfo");
|
||||
}
|
||||
const samples = module._oc_packet_get_nb_samples(packetPtr, packet.byteLength, sampleRate);
|
||||
if (samples < 0) {
|
||||
throw createOpusError(module, samples, "getPacketInfo");
|
||||
}
|
||||
const channels = module._oc_packet_get_nb_channels(packetPtr);
|
||||
if (channels !== 1 && channels !== 2) {
|
||||
throw new OpusError(channels, `libopus getPacketInfo failed (${channels}): invalid channel count`);
|
||||
}
|
||||
const bandwidth = module._oc_packet_get_bandwidth(packetPtr);
|
||||
if (bandwidth < 0) {
|
||||
throw createOpusError(module, bandwidth, "getPacketInfo");
|
||||
}
|
||||
validateBandwidth(bandwidth, "packet bandwidth");
|
||||
return {
|
||||
bandwidth: bandwidth,
|
||||
channels,
|
||||
durationMs: (samples / sampleRate) * 1000,
|
||||
frames,
|
||||
samples,
|
||||
samplesPerFrame: module._oc_packet_get_samples_per_frame(packetPtr, sampleRate),
|
||||
sampleRate,
|
||||
};
|
||||
}
|
||||
finally {
|
||||
module._free(packetPtr);
|
||||
}
|
||||
}
|
||||
class WasmOpusEncoder {
|
||||
application;
|
||||
channels;
|
||||
frameSize;
|
||||
sampleRate;
|
||||
#freed = false;
|
||||
#module;
|
||||
#packetBytes = 0;
|
||||
#packetPtr = 0;
|
||||
#pcmBytes = 0;
|
||||
#pcmPtr = 0;
|
||||
#ptr;
|
||||
constructor(module, options) {
|
||||
this.#module = module;
|
||||
this.application = options.application;
|
||||
this.channels = options.channels;
|
||||
this.frameSize = options.frameSize;
|
||||
this.sampleRate = options.sampleRate;
|
||||
const errorPtr = module._malloc(4);
|
||||
try {
|
||||
const ptr = module._oc_create_encoder(options.sampleRate, options.channels, options.application, errorPtr);
|
||||
const error = module.HEAP32[errorPtr >> 2] ?? 0;
|
||||
if (!ptr || error !== 0) {
|
||||
throw createOpusError(module, error, "createEncoder");
|
||||
}
|
||||
this.#ptr = ptr;
|
||||
}
|
||||
finally {
|
||||
module._free(errorPtr);
|
||||
}
|
||||
let configured = false;
|
||||
try {
|
||||
this.setBitrate(options.bitrate);
|
||||
this.setComplexity(options.complexity);
|
||||
this.setDtx(options.dtx);
|
||||
this.setFec(options.fec);
|
||||
if (options.maxBandwidth !== undefined) {
|
||||
this.setMaxBandwidth(options.maxBandwidth);
|
||||
}
|
||||
this.setPacketLossPercent(options.packetLossPercent);
|
||||
this.setSignal(options.signal);
|
||||
if (options.vbr !== undefined) {
|
||||
this.setVbr(options.vbr);
|
||||
}
|
||||
if (options.vbrConstraint !== undefined) {
|
||||
this.setVbrConstraint(options.vbrConstraint);
|
||||
}
|
||||
configured = true;
|
||||
}
|
||||
finally {
|
||||
if (!configured) {
|
||||
this.free();
|
||||
}
|
||||
}
|
||||
}
|
||||
encode(pcm, options = {}) {
|
||||
this.#assertLive();
|
||||
const frameSize = options.frameSize ?? this.frameSize;
|
||||
validateEncodeFrameSize(frameSize, this.sampleRate, "frameSize");
|
||||
const pcmBytes = toUint8Array(pcm);
|
||||
const expectedBytes = frameSize * this.channels * 2;
|
||||
if (pcmBytes.byteLength !== expectedBytes) {
|
||||
throw new RangeError(`PCM frame has ${pcmBytes.byteLength} bytes; expected ${expectedBytes} for ${frameSize} samples and ${this.channels} channel(s)`);
|
||||
}
|
||||
const maxPacketBytes = options.maxPacketBytes ?? DEFAULT_MAX_PACKET_BYTES;
|
||||
validateIntegerRange(maxPacketBytes, 1, MAX_I32, "maxPacketBytes");
|
||||
const pcmPtr = this.#ensurePcmBytes(pcmBytes.byteLength);
|
||||
const packetPtr = this.#ensurePacketBytes(maxPacketBytes);
|
||||
this.#module.HEAPU8.set(pcmBytes, pcmPtr);
|
||||
const encodedBytes = this.#module._oc_encode(this.#ptr, pcmPtr, frameSize, packetPtr, maxPacketBytes);
|
||||
if (encodedBytes < 0) {
|
||||
throw createOpusError(this.#module, encodedBytes, "encode");
|
||||
}
|
||||
return this.#module.HEAPU8.slice(packetPtr, packetPtr + encodedBytes);
|
||||
}
|
||||
encodeFloat(pcm, options = {}) {
|
||||
this.#assertLive();
|
||||
const frameSize = options.frameSize ?? this.frameSize;
|
||||
validateEncodeFrameSize(frameSize, this.sampleRate, "frameSize");
|
||||
const expectedSamples = frameSize * this.channels;
|
||||
if (pcm.length !== expectedSamples) {
|
||||
throw new RangeError(`Float32 PCM frame has ${pcm.length} samples; expected ${expectedSamples} for ${frameSize} samples and ${this.channels} channel(s)`);
|
||||
}
|
||||
const maxPacketBytes = options.maxPacketBytes ?? DEFAULT_MAX_PACKET_BYTES;
|
||||
validateIntegerRange(maxPacketBytes, 1, MAX_I32, "maxPacketBytes");
|
||||
const pcmPtr = this.#ensurePcmBytes(pcm.byteLength);
|
||||
const packetPtr = this.#ensurePacketBytes(maxPacketBytes);
|
||||
this.#module.HEAPF32.set(pcm, pcmPtr >> 2);
|
||||
const encodedBytes = this.#module._oc_encode_float(this.#ptr, pcmPtr, frameSize, packetPtr, maxPacketBytes);
|
||||
if (encodedBytes < 0) {
|
||||
throw createOpusError(this.#module, encodedBytes, "encodeFloat");
|
||||
}
|
||||
return this.#module.HEAPU8.slice(packetPtr, packetPtr + encodedBytes);
|
||||
}
|
||||
encodeFrames(frames, options = {}) {
|
||||
return frames.map((frame) => this.encode(frame, options));
|
||||
}
|
||||
encodeFloatFrames(frames, options = {}) {
|
||||
return frames.map((frame) => this.encodeFloat(frame, options));
|
||||
}
|
||||
encoderCtl(request, value) {
|
||||
this.#assertLive();
|
||||
validateInteger(request, "request");
|
||||
validateInteger(value, "value");
|
||||
if (!ENCODER_INTEGER_CTL_REQUESTS.has(request)) {
|
||||
throw new RangeError("encoderCtl only supports integer setter requests");
|
||||
}
|
||||
this.#check(this.#module._oc_encoder_ctl(this.#ptr, request, value), "encoderCtl");
|
||||
}
|
||||
setBitrate(bitrate) {
|
||||
this.encoderCtl(EncoderCtl.SetBitrate, normalizeBitrate(bitrate));
|
||||
}
|
||||
getBitrate() {
|
||||
this.#assertLive();
|
||||
const bitrate = this.#module._oc_encoder_ctl_get_bitrate(this.#ptr);
|
||||
if (bitrate < 0) {
|
||||
throw createOpusError(this.#module, bitrate, "getBitrate");
|
||||
}
|
||||
return bitrate;
|
||||
}
|
||||
getLookahead() {
|
||||
this.#assertLive();
|
||||
const lookahead = this.#module._oc_encoder_ctl_get_lookahead(this.#ptr);
|
||||
if (lookahead < 0) {
|
||||
throw createOpusError(this.#module, lookahead, "getLookahead");
|
||||
}
|
||||
return lookahead;
|
||||
}
|
||||
getInDtx() {
|
||||
this.#assertLive();
|
||||
const inDtx = this.#module._oc_encoder_ctl_get_in_dtx(this.#ptr);
|
||||
if (inDtx < 0) {
|
||||
throw createOpusError(this.#module, inDtx, "getInDtx");
|
||||
}
|
||||
return inDtx !== 0;
|
||||
}
|
||||
setComplexity(complexity) {
|
||||
validateIntegerRange(complexity, 0, 10, "complexity");
|
||||
this.encoderCtl(EncoderCtl.SetComplexity, complexity);
|
||||
}
|
||||
setDtx(enabled) {
|
||||
this.encoderCtl(EncoderCtl.SetDtx, enabled ? 1 : 0);
|
||||
}
|
||||
setFec(enabled) {
|
||||
this.encoderCtl(EncoderCtl.SetInBandFec, enabled ? 1 : 0);
|
||||
}
|
||||
setMaxBandwidth(bandwidth) {
|
||||
validateBandwidth(bandwidth, "maxBandwidth");
|
||||
this.encoderCtl(EncoderCtl.SetMaxBandwidth, bandwidth);
|
||||
}
|
||||
setPacketLossPercent(percentage) {
|
||||
validateIntegerRange(percentage, 0, 100, "packetLossPercent");
|
||||
this.encoderCtl(EncoderCtl.SetPacketLossPercent, percentage);
|
||||
}
|
||||
setSignal(signal) {
|
||||
if (!Object.values(Signal).includes(signal)) {
|
||||
throw new RangeError("signal must be Signal.Auto, Signal.Voice, or Signal.Music");
|
||||
}
|
||||
this.encoderCtl(EncoderCtl.SetSignal, signal);
|
||||
}
|
||||
setVbr(enabled) {
|
||||
this.encoderCtl(EncoderCtl.SetVbr, enabled ? 1 : 0);
|
||||
}
|
||||
setVbrConstraint(enabled) {
|
||||
this.encoderCtl(EncoderCtl.SetVbrConstraint, enabled ? 1 : 0);
|
||||
}
|
||||
free() {
|
||||
if (this.#freed) {
|
||||
return;
|
||||
}
|
||||
this.#freeScratch();
|
||||
this.#module._oc_destroy_encoder(this.#ptr);
|
||||
this.#freed = true;
|
||||
}
|
||||
[Symbol.dispose]() {
|
||||
this.free();
|
||||
}
|
||||
#assertLive() {
|
||||
if (this.#freed) {
|
||||
throw new Error("OpusEncoder has been freed");
|
||||
}
|
||||
}
|
||||
#check(code, operation) {
|
||||
if (code < 0) {
|
||||
throw createOpusError(this.#module, code, operation);
|
||||
}
|
||||
}
|
||||
#ensurePacketBytes(requiredBytes) {
|
||||
if (this.#packetPtr !== 0 && this.#packetBytes >= requiredBytes) {
|
||||
return this.#packetPtr;
|
||||
}
|
||||
const nextPtr = checkedMalloc(this.#module, requiredBytes);
|
||||
if (this.#packetPtr !== 0) {
|
||||
this.#module._free(this.#packetPtr);
|
||||
}
|
||||
this.#packetPtr = nextPtr;
|
||||
this.#packetBytes = requiredBytes;
|
||||
return this.#packetPtr;
|
||||
}
|
||||
#ensurePcmBytes(requiredBytes) {
|
||||
if (this.#pcmPtr !== 0 && this.#pcmBytes >= requiredBytes) {
|
||||
return this.#pcmPtr;
|
||||
}
|
||||
const nextPtr = checkedMalloc(this.#module, requiredBytes);
|
||||
if (this.#pcmPtr !== 0) {
|
||||
this.#module._free(this.#pcmPtr);
|
||||
}
|
||||
this.#pcmPtr = nextPtr;
|
||||
this.#pcmBytes = requiredBytes;
|
||||
return this.#pcmPtr;
|
||||
}
|
||||
#freeScratch() {
|
||||
if (this.#packetPtr !== 0) {
|
||||
this.#module._free(this.#packetPtr);
|
||||
}
|
||||
if (this.#pcmPtr !== 0) {
|
||||
this.#module._free(this.#pcmPtr);
|
||||
}
|
||||
this.#packetPtr = 0;
|
||||
this.#packetBytes = 0;
|
||||
this.#pcmPtr = 0;
|
||||
this.#pcmBytes = 0;
|
||||
}
|
||||
}
|
||||
class WasmOpusDecoder {
|
||||
channels;
|
||||
maxFrameSize;
|
||||
sampleRate;
|
||||
#freed = false;
|
||||
#module;
|
||||
#packetBytes = 0;
|
||||
#packetPtr = 0;
|
||||
#pcmBytes = 0;
|
||||
#pcmPtr = 0;
|
||||
#ptr;
|
||||
constructor(module, options) {
|
||||
this.#module = module;
|
||||
this.channels = options.channels;
|
||||
this.maxFrameSize = options.maxFrameSize;
|
||||
this.sampleRate = options.sampleRate;
|
||||
const errorPtr = module._malloc(4);
|
||||
try {
|
||||
const ptr = module._oc_create_decoder(options.sampleRate, options.channels, errorPtr);
|
||||
const error = module.HEAP32[errorPtr >> 2] ?? 0;
|
||||
if (!ptr || error !== 0) {
|
||||
throw createOpusError(module, error, "createDecoder");
|
||||
}
|
||||
this.#ptr = ptr;
|
||||
}
|
||||
finally {
|
||||
module._free(errorPtr);
|
||||
}
|
||||
}
|
||||
decode(packet, options = {}) {
|
||||
this.#assertLive();
|
||||
const frameSize = this.#resolveDecodeFrameSize(packet, options);
|
||||
const pcmBytes = frameSize * this.channels * 2;
|
||||
const pcmPtr = this.#ensurePcmBytes(pcmBytes);
|
||||
const { packetLength, packetPtr } = this.#copyPacket(packet, options.decodeFec);
|
||||
const decodedSamples = this.#module._oc_decode(this.#ptr, packetPtr, packetLength, pcmPtr, frameSize, options.decodeFec ? 1 : 0);
|
||||
if (decodedSamples < 0) {
|
||||
throw createOpusError(this.#module, decodedSamples, packet === null ? "decodePacketLoss" : "decode");
|
||||
}
|
||||
const sampleCount = decodedSamples * this.channels;
|
||||
return this.#module.HEAP16.slice(pcmPtr >> 1, (pcmPtr >> 1) + sampleCount);
|
||||
}
|
||||
decodeFloat(packet, options = {}) {
|
||||
this.#assertLive();
|
||||
const frameSize = this.#resolveDecodeFrameSize(packet, options);
|
||||
const pcmBytes = frameSize * this.channels * 4;
|
||||
const pcmPtr = this.#ensurePcmBytes(pcmBytes);
|
||||
const { packetLength, packetPtr } = this.#copyPacket(packet, options.decodeFec);
|
||||
const decodedSamples = this.#module._oc_decode_float(this.#ptr, packetPtr, packetLength, pcmPtr, frameSize, options.decodeFec ? 1 : 0);
|
||||
if (decodedSamples < 0) {
|
||||
throw createOpusError(this.#module, decodedSamples, packet === null ? "decodePacketLossFloat" : "decodeFloat");
|
||||
}
|
||||
const sampleCount = decodedSamples * this.channels;
|
||||
return this.#module.HEAPF32.slice(pcmPtr >> 2, (pcmPtr >> 2) + sampleCount);
|
||||
}
|
||||
decodeFrames(packets, options = {}) {
|
||||
return packets.map((packet) => this.decode(packet, options));
|
||||
}
|
||||
decodeFloatFrames(packets, options = {}) {
|
||||
return packets.map((packet) => this.decodeFloat(packet, options));
|
||||
}
|
||||
decodePacketLoss(frameSize = samplesForDuration(this.sampleRate, DEFAULT_FRAME_DURATION_MS)) {
|
||||
return this.decode(null, { frameSize });
|
||||
}
|
||||
decodePacketLossFloat(frameSize = samplesForDuration(this.sampleRate, DEFAULT_FRAME_DURATION_MS)) {
|
||||
return this.decodeFloat(null, { frameSize });
|
||||
}
|
||||
decoderCtl(request, value) {
|
||||
this.#assertLive();
|
||||
validateInteger(request, "request");
|
||||
validateInteger(value, "value");
|
||||
if (!DECODER_INTEGER_CTL_REQUESTS.has(request)) {
|
||||
throw new RangeError("decoderCtl only supports integer setter requests");
|
||||
}
|
||||
const code = this.#module._oc_decoder_ctl(this.#ptr, request, value);
|
||||
if (code < 0) {
|
||||
throw createOpusError(this.#module, code, "decoderCtl");
|
||||
}
|
||||
}
|
||||
free() {
|
||||
if (this.#freed) {
|
||||
return;
|
||||
}
|
||||
this.#freeScratch();
|
||||
this.#module._oc_destroy_decoder(this.#ptr);
|
||||
this.#freed = true;
|
||||
}
|
||||
[Symbol.dispose]() {
|
||||
this.free();
|
||||
}
|
||||
#assertLive() {
|
||||
if (this.#freed) {
|
||||
throw new Error("OpusDecoder has been freed");
|
||||
}
|
||||
}
|
||||
#copyPacket(packet, decodeFec) {
|
||||
if (packet === null) {
|
||||
if (decodeFec) {
|
||||
throw new RangeError("decodeFec requires a packet");
|
||||
}
|
||||
return { packetLength: 0, packetPtr: 0 };
|
||||
}
|
||||
if (packet.byteLength === 0) {
|
||||
throw new RangeError("packet must not be empty; use null or decodePacketLoss() for PLC");
|
||||
}
|
||||
const packetPtr = this.#ensurePacketBytes(packet.byteLength);
|
||||
this.#module.HEAPU8.set(packet, packetPtr);
|
||||
return { packetLength: packet.byteLength, packetPtr };
|
||||
}
|
||||
#ensurePacketBytes(requiredBytes) {
|
||||
if (this.#packetPtr !== 0 && this.#packetBytes >= requiredBytes) {
|
||||
return this.#packetPtr;
|
||||
}
|
||||
const nextPtr = checkedMalloc(this.#module, requiredBytes);
|
||||
if (this.#packetPtr !== 0) {
|
||||
this.#module._free(this.#packetPtr);
|
||||
}
|
||||
this.#packetPtr = nextPtr;
|
||||
this.#packetBytes = requiredBytes;
|
||||
return this.#packetPtr;
|
||||
}
|
||||
#ensurePcmBytes(requiredBytes) {
|
||||
if (this.#pcmPtr !== 0 && this.#pcmBytes >= requiredBytes) {
|
||||
return this.#pcmPtr;
|
||||
}
|
||||
const nextPtr = checkedMalloc(this.#module, requiredBytes);
|
||||
if (this.#pcmPtr !== 0) {
|
||||
this.#module._free(this.#pcmPtr);
|
||||
}
|
||||
this.#pcmPtr = nextPtr;
|
||||
this.#pcmBytes = requiredBytes;
|
||||
return this.#pcmPtr;
|
||||
}
|
||||
#freeScratch() {
|
||||
if (this.#packetPtr !== 0) {
|
||||
this.#module._free(this.#packetPtr);
|
||||
}
|
||||
if (this.#pcmPtr !== 0) {
|
||||
this.#module._free(this.#pcmPtr);
|
||||
}
|
||||
this.#packetPtr = 0;
|
||||
this.#packetBytes = 0;
|
||||
this.#pcmPtr = 0;
|
||||
this.#pcmBytes = 0;
|
||||
}
|
||||
#resolveDecodeFrameSize(packet, options) {
|
||||
const frameSize = packet === null || options.decodeFec
|
||||
? (options.frameSize ?? options.maxFrameSize ?? samplesForDuration(this.sampleRate, DEFAULT_FRAME_DURATION_MS))
|
||||
: (options.maxFrameSize ?? this.maxFrameSize);
|
||||
if (packet === null || options.decodeFec) {
|
||||
validatePlcFrameSize(frameSize, this.sampleRate, "frameSize");
|
||||
return frameSize;
|
||||
}
|
||||
validateDecodeCapacity(frameSize, this.sampleRate, "maxFrameSize");
|
||||
return frameSize;
|
||||
}
|
||||
}
|
||||
export class OpusError extends Error {
|
||||
code;
|
||||
codeName;
|
||||
operation;
|
||||
constructor(code, message, operation) {
|
||||
super(message);
|
||||
this.name = "OpusError";
|
||||
this.code = code;
|
||||
this.codeName = resolveOpusErrorCodeName(code);
|
||||
this.operation = operation;
|
||||
}
|
||||
}
|
||||
export const OpusErrorCode = {
|
||||
BadArg: -1,
|
||||
BufferTooSmall: -2,
|
||||
InternalError: -3,
|
||||
InvalidPacket: -4,
|
||||
Unimplemented: -5,
|
||||
InvalidState: -6,
|
||||
AllocFail: -7,
|
||||
};
|
||||
export function isOpusError(error) {
|
||||
if (error instanceof OpusError) {
|
||||
return true;
|
||||
}
|
||||
const candidate = error;
|
||||
return (Boolean(error) &&
|
||||
typeof error === "object" &&
|
||||
candidate.name === "OpusError" &&
|
||||
typeof candidate.message === "string" &&
|
||||
typeof candidate.code === "number" &&
|
||||
(typeof candidate.codeName === "string" || candidate.codeName === undefined) &&
|
||||
(typeof candidate.operation === "string" || candidate.operation === undefined));
|
||||
}
|
||||
async function getModule() {
|
||||
modulePromise ??= createLibopusModule();
|
||||
return await modulePromise;
|
||||
}
|
||||
function resolveOpusErrorCodeName(code) {
|
||||
for (const [name, value] of Object.entries(OpusErrorCode)) {
|
||||
if (value === code) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function createOpusError(module, code, operation) {
|
||||
const message = module.UTF8ToString(module._oc_strerror(code));
|
||||
return new OpusError(code, `libopus ${operation} failed (${code}): ${message}`, operation);
|
||||
}
|
||||
function toUint8Array(input) {
|
||||
return input instanceof Uint8Array
|
||||
? input
|
||||
: new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
|
||||
}
|
||||
function normalizeEncoderOptions(options) {
|
||||
const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
|
||||
const channels = options.channels ?? DEFAULT_CHANNELS;
|
||||
validateCodecOptions({ channels, sampleRate });
|
||||
const frameSize = options.frameSize ?? samplesForDuration(sampleRate, DEFAULT_FRAME_DURATION_MS);
|
||||
validateEncodeFrameSize(frameSize, sampleRate, "frameSize");
|
||||
if (options.maxBandwidth !== undefined) {
|
||||
validateBandwidth(options.maxBandwidth, "maxBandwidth");
|
||||
}
|
||||
const complexity = options.complexity ?? 10;
|
||||
validateIntegerRange(complexity, 0, 10, "complexity");
|
||||
const packetLossPercent = options.packetLossPercent ?? 0;
|
||||
validateIntegerRange(packetLossPercent, 0, 100, "packetLossPercent");
|
||||
const signal = options.signal ?? Signal.Auto;
|
||||
if (!Object.values(Signal).includes(signal)) {
|
||||
throw new RangeError("signal must be Signal.Auto, Signal.Voice, or Signal.Music");
|
||||
}
|
||||
return {
|
||||
application: options.application ?? Application.Audio,
|
||||
bitrate: normalizeBitrate(options.bitrate ?? 64_000),
|
||||
channels,
|
||||
complexity,
|
||||
dtx: options.dtx ?? false,
|
||||
fec: options.fec ?? false,
|
||||
frameSize,
|
||||
maxBandwidth: options.maxBandwidth,
|
||||
packetLossPercent,
|
||||
sampleRate,
|
||||
signal,
|
||||
vbr: options.vbr,
|
||||
vbrConstraint: options.vbrConstraint,
|
||||
};
|
||||
}
|
||||
function normalizeDecoderOptions(options) {
|
||||
const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
|
||||
const channels = options.channels ?? DEFAULT_CHANNELS;
|
||||
validateCodecOptions({ channels, sampleRate });
|
||||
const maxFrameSize = options.maxFrameSize ?? samplesForDuration(sampleRate, MAX_PACKET_DURATION_MS);
|
||||
validateDecodeCapacity(maxFrameSize, sampleRate, "maxFrameSize");
|
||||
return { channels, maxFrameSize, sampleRate };
|
||||
}
|
||||
function samplesForDuration(sampleRate, durationMs) {
|
||||
return (sampleRate / 1000) * durationMs;
|
||||
}
|
||||
function validateCodecOptions(options) {
|
||||
if (!VALID_SAMPLE_RATES.includes(options.sampleRate)) {
|
||||
throw new RangeError("sampleRate must be 8000, 12000, 16000, 24000, or 48000");
|
||||
}
|
||||
if (options.channels !== 1 && options.channels !== 2) {
|
||||
throw new RangeError("channels must be 1 or 2");
|
||||
}
|
||||
}
|
||||
function normalizeBitrate(bitrate) {
|
||||
if (bitrate === "auto") {
|
||||
return Bitrate.Auto;
|
||||
}
|
||||
if (bitrate === "max") {
|
||||
return Bitrate.Max;
|
||||
}
|
||||
if (bitrate === Bitrate.Auto || bitrate === Bitrate.Max) {
|
||||
return bitrate;
|
||||
}
|
||||
validatePositiveInteger(bitrate, "bitrate");
|
||||
return bitrate;
|
||||
}
|
||||
function validateBandwidth(bandwidth, name) {
|
||||
if (!Object.values(Bandwidth).includes(bandwidth)) {
|
||||
throw new RangeError(`${name} must be Bandwidth.Narrowband, Bandwidth.Mediumband, Bandwidth.Wideband, Bandwidth.Superwideband, or Bandwidth.Fullband`);
|
||||
}
|
||||
}
|
||||
function validateEncodeFrameSize(frameSize, sampleRate, name) {
|
||||
validateFrameSizeForDurations(frameSize, sampleRate, name, ENCODE_FRAME_DURATIONS_MS);
|
||||
}
|
||||
function validateDecodeCapacity(frameSize, sampleRate, name) {
|
||||
const maxFrameSize = samplesForDuration(sampleRate, MAX_PACKET_DURATION_MS);
|
||||
if (!Number.isInteger(frameSize) || frameSize <= 0 || frameSize > maxFrameSize) {
|
||||
throw new RangeError(`${name} must be an integer from 1 to ${maxFrameSize} samples at ${sampleRate} Hz`);
|
||||
}
|
||||
}
|
||||
function validatePlcFrameSize(frameSize, sampleRate, name) {
|
||||
const minFrameSize = samplesForDuration(sampleRate, 2.5);
|
||||
const maxFrameSize = samplesForDuration(sampleRate, MAX_PACKET_DURATION_MS);
|
||||
if (!Number.isInteger(frameSize) ||
|
||||
frameSize < minFrameSize ||
|
||||
frameSize > maxFrameSize ||
|
||||
frameSize % minFrameSize !== 0) {
|
||||
throw new RangeError(`${name} must be a multiple of ${minFrameSize} samples from ${minFrameSize} to ${maxFrameSize} at ${sampleRate} Hz`);
|
||||
}
|
||||
}
|
||||
function validateFrameSizeForDurations(frameSize, sampleRate, name, durationsMs) {
|
||||
const validFrameSizes = durationsMs.map((durationMs) => samplesForDuration(sampleRate, durationMs));
|
||||
if (!Number.isInteger(frameSize) || !validFrameSizes.includes(frameSize)) {
|
||||
throw new RangeError(`${name} must be one of ${validFrameSizes.join(", ")} samples at ${sampleRate} Hz`);
|
||||
}
|
||||
}
|
||||
function validateInteger(value, name) {
|
||||
if (!Number.isInteger(value)) {
|
||||
throw new RangeError(`${name} must be an integer`);
|
||||
}
|
||||
}
|
||||
function validatePositiveInteger(value, name) {
|
||||
if (!Number.isInteger(value) || value <= 0) {
|
||||
throw new RangeError(`${name} must be a positive integer`);
|
||||
}
|
||||
}
|
||||
function validateIntegerRange(value, min, max, name) {
|
||||
if (!Number.isInteger(value) || value < min || value > max) {
|
||||
throw new RangeError(`${name} must be an integer from ${min} to ${max}`);
|
||||
}
|
||||
}
|
||||
function checkedMalloc(module, bytes) {
|
||||
validateIntegerRange(bytes, 1, MAX_I32, "malloc size");
|
||||
const ptr = module._malloc(bytes);
|
||||
if (ptr === 0) {
|
||||
throw new Error(`WASM malloc failed for ${bytes} bytes`);
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Versioned binary transport; no tokens, passwords or identity material in audio frames.
|
||||
export const MAX_OPUS_PACKET = 1275;
|
||||
export function encodeVoice({ direction, clientId = 0, sequence = 0, codec = 4, whisper = false, data }) {
|
||||
if (!(data instanceof Uint8Array) || data.length > MAX_OPUS_PACKET || ![1, 2].includes(direction) || ![4, 5].includes(codec)) throw new Error('Invalid voice frame');
|
||||
const result = new Uint8Array(8 + data.length);
|
||||
const header = new DataView(result.buffer);
|
||||
result[0] = 1; result[1] = direction;
|
||||
header.setUint16(2, clientId); header.setUint16(4, sequence);
|
||||
result[6] = codec; result[7] = (data.length <= 1 ? 1 : 0) | (whisper ? 2 : 0);
|
||||
result.set(data, 8);
|
||||
return result;
|
||||
}
|
||||
export function decodeVoice(bytes, direction) {
|
||||
if (!(bytes instanceof Uint8Array) || bytes.length < 8 || bytes.length > 8 + MAX_OPUS_PACKET) throw new Error('Invalid voice frame size');
|
||||
const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
if (bytes[0] !== 1 || bytes[1] !== direction || ![4, 5].includes(bytes[6]) || bytes[7] & ~3 ||
|
||||
Boolean(bytes[7] & 1) !== (bytes.length <= 9) || (direction === 1 && (header.getUint16(2) !== 0 || bytes[7] & 2))) throw new Error('Invalid voice frame header');
|
||||
return { clientId: header.getUint16(2), sequence: header.getUint16(4), codec: bytes[6], end: Boolean(bytes[7] & 1), whisper: Boolean(bytes[7] & 2), data: bytes.subarray(8) };
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { createEncoder, createDecoder, getPacketInfo, Application, Signal } from './vendor/opus/index.js';
|
||||
import { JitterBuffer } from './jitter-buffer.mjs';
|
||||
import { encodeVoice, decodeVoice } from './voice-frame.mjs';
|
||||
|
||||
const speakers = new Map();
|
||||
const volumes = new Map();
|
||||
let encoder;
|
||||
let mode = 'ptt';
|
||||
let pressed = false;
|
||||
let muted = true;
|
||||
let outputMuted = true;
|
||||
let canSend = false;
|
||||
let codec = 4;
|
||||
let threshold = 0.025;
|
||||
let hangover = 0;
|
||||
let transmitting = false;
|
||||
let sequence = 0;
|
||||
let generation = 0;
|
||||
let pendingPackets = 0;
|
||||
let clock;
|
||||
let lastTick = 0;
|
||||
let reportTicks = 0;
|
||||
let rejected = 0;
|
||||
let currentSpeaking = '';
|
||||
function status(active) {
|
||||
if (transmitting === active) return;
|
||||
transmitting = active;
|
||||
postMessage({ type: 'transmitting', active });
|
||||
}
|
||||
function endTransmission() {
|
||||
hangover = 0;
|
||||
if (transmitting) {
|
||||
const frame = encodeVoice({ direction: 1, sequence: sequence++ & 65535, codec, data: new Uint8Array() });
|
||||
postMessage({ type: 'encoded', frame }, [frame.buffer]);
|
||||
}
|
||||
status(false);
|
||||
}
|
||||
function resetSpeakers() {
|
||||
generation++;
|
||||
for (const speaker of speakers.values()) speaker.decoder?.free();
|
||||
speakers.clear();
|
||||
}
|
||||
async function receive(frame) {
|
||||
if (outputMuted) return;
|
||||
const packet = decodeVoice(new Uint8Array(frame), 2);
|
||||
if (!packet.end && (await getPacketInfo(packet.data, { sampleRate: 48000 })).samples !== 960) { rejected++; return; }
|
||||
let speaker = speakers.get(packet.clientId);
|
||||
if (!speaker) {
|
||||
if (packet.end || speakers.size >= 32) { rejected++; return; }
|
||||
speaker = { queue: new JitterBuffer(), volume: volumes.get(packet.clientId) ?? 1, last: performance.now(), decoder: null, ready: null };
|
||||
speakers.set(packet.clientId, speaker);
|
||||
const currentGeneration = generation;
|
||||
speaker.ready = createDecoder({ sampleRate: 48000, channels: 2, maxFrameSize: 960 }).then(decoder => {
|
||||
if (generation !== currentGeneration || speakers.get(packet.clientId) !== speaker) { decoder.free(); return; }
|
||||
speaker.decoder = decoder;
|
||||
});
|
||||
}
|
||||
await speaker.ready;
|
||||
if (speakers.get(packet.clientId) !== speaker || !speaker.decoder || outputMuted) return;
|
||||
speaker.last = performance.now();
|
||||
speaker.queue.push(packet);
|
||||
}
|
||||
function tick() {
|
||||
const now = performance.now();
|
||||
// A suspended/background worker must never replay its backlog on resume.
|
||||
if (now - lastTick > 100) resetSpeakers();
|
||||
lastTick = now;
|
||||
if (outputMuted) return;
|
||||
const mix = new Float32Array(1920);
|
||||
const speaking = [];
|
||||
for (const [id, speaker] of speakers) {
|
||||
if (!speaker.decoder) continue;
|
||||
const item = speaker.queue.pull();
|
||||
let pcm;
|
||||
try {
|
||||
if (item.type === 'packet') pcm = speaker.decoder.decodeFloat(item.packet.data, { maxFrameSize: 960 });
|
||||
else if (item.type === 'loss') pcm = item.next && !item.next.end ? speaker.decoder.decodeFloat(item.next.data, { decodeFec: true, frameSize: 960, maxFrameSize: 960 }) : speaker.decoder.decodePacketLossFloat(960);
|
||||
} catch { rejected++; speaker.queue.clear(); }
|
||||
if (pcm) {
|
||||
speaking.push(id);
|
||||
for (let i = 0; i < Math.min(pcm.length, mix.length); i++) mix[i] += pcm[i] * speaker.volume;
|
||||
}
|
||||
if (now - speaker.last > 3000) { speaker.decoder.free(); speakers.delete(id); }
|
||||
}
|
||||
// Bound summed output when several speakers transmit together.
|
||||
for (let i = 0; i < mix.length; i++) mix[i] = Math.max(-1, Math.min(1, mix[i]));
|
||||
postMessage({ type: 'pcm', pcm: mix, at: Date.now() }, [mix.buffer]);
|
||||
const ids = speaking.sort((a, b) => a - b).join(',');
|
||||
if (ids !== currentSpeaking) { currentSpeaking = ids; postMessage({ type: 'speaking', ids: speaking }); }
|
||||
if (++reportTicks % 50 === 0) {
|
||||
const stats = { lost: 0, late: 0, overflow: 0, received: 0, rejected };
|
||||
for (const speaker of speakers.values()) for (const key of ['lost', 'late', 'overflow', 'received']) stats[key] += speaker.queue.stats[key];
|
||||
postMessage({ type: 'stats', ...stats, speakers: speakers.size });
|
||||
}
|
||||
}
|
||||
onmessage = async ({ data: event }) => {
|
||||
try {
|
||||
if (event.type === 'init') {
|
||||
encoder = await createEncoder({ sampleRate: 48000, channels: 1, application: Application.Voip, signal: Signal.Voice, frameSize: 960, bitrate: 32000, complexity: 5, fec: true, packetLossPercent: 10 });
|
||||
lastTick = performance.now();
|
||||
clock = setInterval(tick, 20);
|
||||
postMessage({ type: 'ready' });
|
||||
} else if (event.type === 'configure') {
|
||||
endTransmission();
|
||||
mode = event.mode; pressed = false; muted = event.muted; outputMuted = event.outputMuted;
|
||||
canSend = event.canSend; codec = event.codec; threshold = event.threshold;
|
||||
if (outputMuted) resetSpeakers();
|
||||
} else if (event.type === 'ptt') { pressed = Boolean(event.pressed); if (!pressed) endTransmission(); }
|
||||
else if (event.type === 'volume') {
|
||||
if (!volumes.has(event.clientId) && volumes.size >= 128) volumes.delete(volumes.keys().next().value);
|
||||
const volume = Math.max(0, Math.min(2, Number(event.volume) || 0));
|
||||
volumes.set(event.clientId, volume);
|
||||
const speaker = speakers.get(event.clientId); if (speaker) speaker.volume = volume;
|
||||
}
|
||||
else if (event.type === 'packet') {
|
||||
if (++pendingPackets > 64) { pendingPackets--; postMessage({ type: 'packet_ack' }); return; }
|
||||
try { await receive(event.frame); } catch { rejected++; }
|
||||
finally { pendingPackets--; postMessage({ type: 'packet_ack' }); }
|
||||
} else if (event.type === 'capture') {
|
||||
try {
|
||||
if (!encoder || muted || outputMuted || !canSend || ![4, 5].includes(codec) || Date.now() - event.at > 100) { endTransmission(); return; }
|
||||
let energy = 0;
|
||||
for (const value of event.pcm) energy += value * value;
|
||||
const level = Math.sqrt(energy / event.pcm.length);
|
||||
if (level >= threshold) hangover = 10;
|
||||
const active = mode === 'ptt' ? pressed : hangover-- > 0;
|
||||
if (!active) { endTransmission(); return; }
|
||||
const packet = encoder.encodeFloat(event.pcm, { maxPacketBytes: 1275 });
|
||||
const frame = encodeVoice({ direction: 1, sequence: sequence++ & 65535, codec, data: packet });
|
||||
postMessage({ type: 'encoded', frame }, [frame.buffer]);
|
||||
status(true);
|
||||
} finally { postMessage({ type: 'capture_ack' }); }
|
||||
} else if (event.type === 'reset') { endTransmission(); resetSpeakers(); }
|
||||
else if (event.type === 'stop') { clearInterval(clock); endTransmission(); resetSpeakers(); encoder?.free(); close(); }
|
||||
} catch { postMessage({ type: 'error', code: 'audio_processing_failed' }); }
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
class VoxCapture extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super(); this.frame = new Float32Array(960); this.offset = 0; this.pending = 0; this.enabled = false;
|
||||
this.port.onmessage = ({ data }) => {
|
||||
if (data.type === 'ack') this.pending = Math.max(0, this.pending - 1);
|
||||
else if (data.type === 'enabled') { this.enabled = data.value; this.offset = 0; }
|
||||
};
|
||||
}
|
||||
process(inputs) {
|
||||
const input = inputs[0]?.[0];
|
||||
if (!input || !this.enabled) return true;
|
||||
for (const value of input) {
|
||||
this.frame[this.offset++] = value;
|
||||
if (this.offset === 960) {
|
||||
if (this.pending < 2) {
|
||||
const frame = this.frame;
|
||||
this.port.postMessage({ pcm: frame, at: currentTime }, [frame.buffer]);
|
||||
this.pending++;
|
||||
this.frame = new Float32Array(960);
|
||||
}
|
||||
this.offset = 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
class VoxPlayback extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super(); this.frames = []; this.offset = 0; this.enabled = true;
|
||||
this.port.onmessage = ({ data }) => {
|
||||
if (data.type === 'clear') { this.frames = []; this.offset = 0; }
|
||||
else if (data.pcm instanceof Float32Array && data.pcm.length === 1920) {
|
||||
// At most 80 ms after the jitter buffer. Drop old samples on overrun.
|
||||
if (this.frames.length >= 4) { this.frames = []; this.offset = 0; }
|
||||
this.frames.push(data.pcm);
|
||||
}
|
||||
};
|
||||
}
|
||||
process(_inputs, outputs) {
|
||||
const output = outputs[0];
|
||||
if (!output?.[0]) return true;
|
||||
for (let i = 0; i < output[0].length; i++) {
|
||||
const frame = this.frames[0];
|
||||
if (!frame) break;
|
||||
output[0][i] = frame[this.offset * 2];
|
||||
if (output[1]) output[1][i] = frame[this.offset * 2 + 1];
|
||||
if (++this.offset >= 960) { this.frames.shift(); this.offset = 0; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor('vox-capture', VoxCapture);
|
||||
registerProcessor('vox-playback', VoxPlayback);
|
||||
@@ -0,0 +1,134 @@
|
||||
|
||||
export class VoiceAudio extends EventTarget {
|
||||
constructor(sendCommand, sendFrame) {
|
||||
super(); this.sendCommand = sendCommand; this.sendFrame = sendFrame;
|
||||
this.muted = true; this.outputMuted = true; this.canSend = false;
|
||||
this.mode = 'ptt'; this.codec = 4; this.threshold = 0.025; this.packetPending = 0;
|
||||
this.inputDevice = ''; this.stopped = false;
|
||||
}
|
||||
event(type, detail) { if (!this.stopped) this.dispatchEvent(new CustomEvent(type, { detail })); }
|
||||
assertActive() { if (this.stopped) throw new DOMException('The audio connection ended.', 'AbortError'); }
|
||||
async start() {
|
||||
this.assertActive();
|
||||
if (this.starting) return this.starting;
|
||||
const operation = this.initialize(); this.starting = operation;
|
||||
try { await operation; } finally { if (this.starting === operation) this.starting = undefined; }
|
||||
}
|
||||
async initialize() {
|
||||
this.assertActive();
|
||||
if (this.context) { await this.context.resume(); return; }
|
||||
this.context = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
|
||||
if (this.context.sampleRate !== 48000 || !this.context.audioWorklet) throw new Error('This browser cannot create the required 48 kHz audio worklet.');
|
||||
await this.context.audioWorklet.addModule('/voice-worklet.mjs');
|
||||
this.assertActive();
|
||||
this.playback = new AudioWorkletNode(this.context, 'vox-playback', { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] });
|
||||
this.playback.connect(this.context.destination);
|
||||
this.worker = new Worker('/voice-worker.mjs', { type: 'module' });
|
||||
this.worker.onmessage = ({ data }) => {
|
||||
if (this.stopped) return;
|
||||
if (data.type === 'ready') this.ready?.();
|
||||
else if (data.type === 'encoded') {
|
||||
const sent = this.sendFrame(data.frame) !== false;
|
||||
if (!sent) this.ptt(false);
|
||||
} else if (data.type === 'pcm' && !this.outputMuted && Date.now() - data.at < 100 && this.context?.state === 'running') {
|
||||
this.playback.port.postMessage({ pcm: data.pcm }, [data.pcm.buffer]);
|
||||
} else if (data.type === 'packet_ack') this.packetPending = Math.max(0, this.packetPending - 1);
|
||||
else if (data.type === 'capture_ack') this.capture?.port.postMessage({ type: 'ack' });
|
||||
else if (data.type === 'error') { this.mute(); this.event('error', 'Audio processing failed. Microphone stopped; reconnect audio to retry.'); }
|
||||
else if (['speaking', 'transmitting', 'stats'].includes(data.type)) this.event(data.type, data);
|
||||
};
|
||||
this.worker.onerror = () => { this.mute(); this.event('error', 'The audio worker failed. Reconnect to restart it.'); };
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('Audio codec initialization timed out.')), 10000);
|
||||
this.ready = () => { clearTimeout(timer); resolve(); };
|
||||
this.cancelInitialization = () => { clearTimeout(timer); reject(new DOMException('The audio connection ended.', 'AbortError')); };
|
||||
this.worker.postMessage({ type: 'init' });
|
||||
});
|
||||
this.cancelInitialization = undefined;
|
||||
this.assertActive();
|
||||
for (const [clientId, volume] of this.gains || []) this.worker.postMessage({ type: 'volume', clientId, volume });
|
||||
this.context.onstatechange = () => {
|
||||
if (this.context?.state !== 'running') { this.ptt(false); this.mute(); this.clearPlayback(); this.event('error', 'Audio paused by the browser. Resume listening, then enable the microphone again.'); }
|
||||
};
|
||||
await this.context.resume();
|
||||
this.assertActive();
|
||||
}
|
||||
configure() {
|
||||
if (this.stopped) return;
|
||||
this.worker?.postMessage({ type: 'configure', mode: this.mode, muted: this.muted, outputMuted: this.outputMuted, canSend: this.canSend, codec: this.codec, threshold: this.threshold });
|
||||
this.capture?.port.postMessage({ type: 'enabled', value: !this.muted && this.canSend && !this.outputMuted });
|
||||
}
|
||||
sync() { if (this.stopped) return; this.sendCommand({ type: 'audio_state', inputMuted: this.muted, outputMuted: this.outputMuted }); this.configure(); }
|
||||
async listen(enabled) {
|
||||
if (enabled && ![4, 5].includes(this.codec)) throw new Error('This channel uses an unsupported codec. Join an Opus Voice or Opus Music channel.');
|
||||
if (enabled) await this.start();
|
||||
this.assertActive();
|
||||
this.outputMuted = !enabled;
|
||||
if (!enabled) this.mute();
|
||||
this.clearPlayback(); this.sync();
|
||||
}
|
||||
permissions(event) { this.canSend = event.canSend; this.configure(); }
|
||||
channel(codec) {
|
||||
if (this.codec === codec) return;
|
||||
this.codec = codec;
|
||||
this.mute(); this.worker?.postMessage({ type: 'reset' }); this.clearPlayback();
|
||||
if (![4, 5].includes(codec)) this.event('error', 'This channel uses a codec that is not supported yet. Join an Opus Voice or Opus Music channel.');
|
||||
}
|
||||
async microphone(deviceId = this.inputDevice) {
|
||||
this.assertActive();
|
||||
if (this.outputMuted) throw new Error('Enable listening before enabling your microphone.');
|
||||
if (![4, 5].includes(this.codec)) throw new Error('Microphone requires an Opus channel.');
|
||||
this.mute();
|
||||
const captureGeneration = this.captureGeneration;
|
||||
this.stream?.getTracks().forEach(track => track.stop());
|
||||
this.source?.disconnect(); this.capture?.disconnect();
|
||||
this.inputDevice = deviceId;
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: {
|
||||
...(deviceId ? { deviceId: { exact: deviceId } } : {}),
|
||||
channelCount: 1, sampleRate: 48000, echoCancellation: true, noiseSuppression: true, autoGainControl: true,
|
||||
}, video: false });
|
||||
if (this.stopped || this.outputMuted || captureGeneration !== this.captureGeneration) { stream.getTracks().forEach(track => track.stop()); return; }
|
||||
this.stream = stream;
|
||||
this.source = this.context.createMediaStreamSource(stream);
|
||||
this.capture = new AudioWorkletNode(this.context, 'vox-capture', { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1] });
|
||||
this.capture.port.onmessage = ({ data }) => {
|
||||
if (this.muted || !this.canSend || !this.context || typeof data.at !== 'number' || (this.context.currentTime - data.at) * 1000 > 100) { this.capture?.port.postMessage({ type: 'ack' }); return; }
|
||||
this.worker.postMessage({ type: 'capture', pcm: data.pcm, at: Date.now() }, [data.pcm.buffer]);
|
||||
};
|
||||
// The worklet emits silence. Its output keeps capture scheduled without local sidetone.
|
||||
this.source.connect(this.capture); this.capture.connect(this.context.destination);
|
||||
for (const track of stream.getAudioTracks()) {
|
||||
track.onended = () => { this.mute(); this.event('error', 'Microphone disconnected. Select a device and enable it again.'); };
|
||||
track.onmute = () => { this.ptt(false); this.mute(); this.event('error', 'Microphone input became unavailable.'); };
|
||||
}
|
||||
this.muted = false; this.sync();
|
||||
}
|
||||
mute() {
|
||||
this.captureGeneration = (this.captureGeneration || 0) + 1;
|
||||
this.muted = true;
|
||||
this.stream?.getAudioTracks().forEach(track => { track.enabled = false; });
|
||||
this.ptt(false); this.sync();
|
||||
}
|
||||
ptt(pressed) { this.worker?.postMessage({ type: 'ptt', pressed: !this.muted && this.canSend && pressed }); }
|
||||
volume(clientId, volume) {
|
||||
this.gains ||= new Map();
|
||||
if (!this.gains.has(clientId) && this.gains.size >= 128) this.gains.delete(this.gains.keys().next().value);
|
||||
volume = Math.max(0, Math.min(2, Number(volume) || 0)); this.gains.set(clientId, volume);
|
||||
this.worker?.postMessage({ type: 'volume', clientId, volume });
|
||||
}
|
||||
clearPlayback() { this.playback?.port.postMessage({ type: 'clear' }); }
|
||||
receive(frame) {
|
||||
if (!this.worker || this.outputMuted || this.packetPending >= 64) return;
|
||||
this.packetPending++;
|
||||
this.worker.postMessage({ type: 'packet', frame }, [frame]);
|
||||
}
|
||||
stop() {
|
||||
if (!this.stopped && (!this.muted || !this.outputMuted)) { this.muted = true; this.outputMuted = true; this.sync(); }
|
||||
this.stopped = true; this.mute();
|
||||
this.cancelInitialization?.(); this.cancelInitialization = undefined;
|
||||
this.stream?.getTracks().forEach(track => { track.onended = null; track.onmute = null; track.stop(); });
|
||||
this.source?.disconnect(); this.capture?.disconnect(); this.playback?.disconnect();
|
||||
this.worker?.terminate(); this.worker = null;
|
||||
if (this.context) { this.context.onstatechange = null; void this.context.close(); this.context = null; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export const pages = new Set(['connections', 'connection', 'identity', 'console', 'channels', 'conversation', 'audio', 'profile', 'diagnostics']);
|
||||
export function resolvePage(hash) { const page = hash.replace(/^#/, ''); return pages.has(page) ? page : 'connections'; }
|
||||
export function sameDestination(a, b) { return Boolean(a && b && a.host === b.host && a.port === b.port); }
|
||||
export function recentChannels(channels, currentId, recentIds) {
|
||||
return [...new Set([currentId, ...recentIds])].map(id => channels.find(channel => channel.id === id)).filter(Boolean).slice(0, 4);
|
||||
}
|
||||
export function channelPath(channel, channels) {
|
||||
const byId = new Map(channels.map(item => [item.id, item])); const seen = new Set([channel.id]); const names = [];
|
||||
let parent = byId.get(channel.parentId);
|
||||
while (parent && !seen.has(parent.id)) { seen.add(parent.id); names.unshift(parent.name); parent = byId.get(parent.parentId); }
|
||||
return names.join(' / ');
|
||||
}
|
||||
export function matchesChannel(channel, channels, participants, query) {
|
||||
const needle = query.trim().toLocaleLowerCase();
|
||||
return !needle || [channel.name, channelPath(channel, channels), ...participants.filter(person => person.channelId === channel.id).map(person => person.name)].some(text => text.toLocaleLowerCase().includes(needle));
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
import { clientCommand, joinChannel, getParticipantVolume, setParticipantVolume } from './protocol.mjs';
|
||||
import { orderChannels } from './channel-order.mjs';
|
||||
import { resolvePage, recentChannels, channelPath, matchesChannel, sameDestination } from './workspace-model.mjs';
|
||||
const $ = id => document.getElementById(id);
|
||||
let selected, state, previousOwnChannel, privatePeer, privatePeerUid, workspaceCsrf, preferences, selectedBookmark;
|
||||
let connected = false, connectionActive = false, sequence = 0, sending = false, workspaceEpoch = 0, preferenceBusy = false;
|
||||
let activeSpeakers = new Set(); const messages = []; const drafts = new Map(); let draftKey; const threads = new Map(); const unread = new Map(); let recent = [];
|
||||
let page = 'connections', editorDirty = false, routeGeneration = 0, signedIn = false;
|
||||
let theme = 'system'; const themes = ['system', 'light', 'dark'];
|
||||
const pageCopy = { connections: 'CONNECTIONS / SAVED DESTINATIONS', connection: 'CONNECTIONS / EDIT DESTINATION', identity: 'ACCOUNT / TEAMSPEAK IDENTITY', console: 'VOICE CONSOLE', channels: 'WORKSPACE / FIND A CHANNEL', conversation: 'CONVERSATION / PRIVATE', audio: 'AUDIO / PREFERENCES', profile: 'ACCOUNT / PRESENCE', diagnostics: 'CONNECTION / DIAGNOSTICS' };
|
||||
async function workspaceApi(path, body) {
|
||||
const response = await fetch(path, { signal: AbortSignal.timeout(15000), method: body === undefined ? 'GET' : 'POST', ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': workspaceCsrf }, body: JSON.stringify(body) }) });
|
||||
if (response.status === 401) window.dispatchEvent(new Event('voxharbor-owner-expired'));
|
||||
const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Workspace storage is unavailable.'); return result;
|
||||
}
|
||||
let confirmResolve;
|
||||
function confirmAction(title, description, accept = 'Continue') {
|
||||
if (confirmResolve) return Promise.resolve(false);
|
||||
$('confirm-title').textContent = title; $('confirm-description').textContent = description; $('confirm-accept').textContent = accept;
|
||||
$('confirm-dialog').showModal(); return new Promise(resolve => { confirmResolve = resolve; });
|
||||
}
|
||||
function finishConfirm(value) { const resolve = confirmResolve; confirmResolve = undefined; $('confirm-dialog').close(); resolve?.(value); }
|
||||
$('confirm-form').addEventListener('submit', event => { event.preventDefault(); finishConfirm(true); });
|
||||
$('confirm-cancel').addEventListener('click', () => finishConfirm(false));
|
||||
$('confirm-dialog').addEventListener('cancel', event => { event.preventDefault(); finishConfirm(false); });
|
||||
async function navigate(next, { replace = false, fromHistory = false, force = false } = {}) {
|
||||
next = resolvePage('#' + next); const generation = ++routeGeneration;
|
||||
if (!signedIn) return;
|
||||
if (!force && page === 'connection' && next !== page && editorDirty && !await confirmAction('Discard unsaved changes?', 'Your saved connection has not changed. Leave this editor and discard the changes?', 'Discard changes')) {
|
||||
if (fromHistory) history.replaceState(null, '', '#' + page); return;
|
||||
}
|
||||
if (generation !== routeGeneration) return;
|
||||
if (page === 'connection' && next !== page) { clearEditorSecrets(); editorDirty = false; }
|
||||
page = next;
|
||||
if (page === 'conversation' && privatePeer && connected && $('chat-scope').querySelector('option[value=private]')) $('chat-scope').value = 'private';
|
||||
if (page === 'console' && scope() === 'private') { $('chat-scope').value = 'channel'; renderMessages(); }
|
||||
for (const section of document.querySelectorAll('section[data-page]:not(#lab)')) section.hidden = section.dataset.page !== page;
|
||||
$('lab').dataset.page = page; $('page-breadcrumb').textContent = pageCopy[page];
|
||||
for (const button of document.querySelectorAll('.top-actions [data-route]')) { if (button.dataset.route === page) button.setAttribute('aria-current', 'page'); else button.removeAttribute('aria-current'); }
|
||||
(page === 'conversation' ? $('direct-chat-slot') : $('console-chat-slot')).append($('chat-panel'));
|
||||
$('session-ribbon').hidden = !connectionActive || page === 'console';
|
||||
if (!fromHistory && location.hash !== '#' + page) history[replace ? 'replaceState' : 'pushState'](null, '', '#' + page);
|
||||
document.title = `VoxHarbor · ${pageCopy[page].split(' / ').at(-1).toLowerCase()}`;
|
||||
document.querySelector('.skip-link').href = page === 'console' ? '#workspace-content' : `#page-${page}`;
|
||||
const section = document.querySelector(`section[data-page="${page}"]:not(#lab)`); section.id ||= `page-${page}`;
|
||||
window.scrollTo(0, 0); section.querySelector('h1')?.focus({ preventScroll: true });
|
||||
if (page === 'channels') renderBrowser(); if (page === 'conversation') renderMessages();
|
||||
}
|
||||
window.addEventListener('hashchange', () => void navigate(resolvePage(location.hash), { fromHistory: true }));
|
||||
for (const button of document.querySelectorAll('[data-route]')) button.addEventListener('click', event => { event.preventDefault(); void navigate(button.dataset.route); });
|
||||
function clearEditorSecrets() { $('ts3-password').value = ''; $('ts3-channel-password').value = ''; $('bookmark-clear-passwords').checked = false; $('connection-clear-passwords').checked = false; }
|
||||
function applyConnection(connection) {
|
||||
delete $('settings-dialog').dataset.bookmarkId; clearEditorSecrets();
|
||||
$('ts3-host').value = connection?.host || ''; $('ts3-port').value = String(connection?.port || 9987); $('ts3-nickname').value = connection?.nickname || preferences?.nickname || '';
|
||||
$('ts3-channel').value = connection?.channelId ? String(connection.channelId) : '';
|
||||
$('ts3-password').placeholder = connection?.hasPassword ? 'Saved on backend; leave blank to keep' : 'Optional';
|
||||
$('ts3-channel-password').placeholder = connection?.hasChannelPassword ? 'Saved on backend; leave blank to keep' : 'Optional';
|
||||
}
|
||||
async function editConnection(connection) {
|
||||
if (page === 'connection' && editorDirty && !await confirmAction('Discard unsaved changes?', 'Open another destination and discard the current edits?', 'Discard changes')) return;
|
||||
selectedBookmark = connection?.id && preferences?.bookmarks.some(item => item.id === connection.id) ? connection.id : undefined;
|
||||
applyConnection(connection); if (selectedBookmark) $('settings-dialog').dataset.bookmarkId = selectedBookmark;
|
||||
$('bookmark-name').value = connection?.name || ''; $('bookmark-delete').hidden = !selectedBookmark;
|
||||
$('bookmark-passwords').checked = true; $('editor-status').textContent = ''; editorDirty = false;
|
||||
await navigate('connection');
|
||||
}
|
||||
async function startConnection(connection, passwords = {}) {
|
||||
if ($('ts3-connect').disabled) { $('notice').textContent = 'Set up your identity before connecting, or wait for the current connection to finish.'; if (!connectionActive) await navigate('identity'); return; }
|
||||
if (connectionActive) return;
|
||||
applyConnection(connection); if (typeof passwords.password === 'string') $('ts3-password').value = passwords.password; if (typeof passwords.channelPassword === 'string') $('ts3-channel-password').value = passwords.channelPassword; $('server-name').textContent = connection.name || connection.host;
|
||||
if (preferences.bookmarks.some(item => item.id === connection.id)) $('settings-dialog').dataset.bookmarkId = connection.id;
|
||||
$('ts3-connect').click(); await navigate('console', { force: true });
|
||||
}
|
||||
function renderBookmarks() {
|
||||
if (!preferences) return;
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (const bookmark of preferences?.bookmarks || []) {
|
||||
const active = connectionActive && sameDestination(bookmark, preferences.connection);
|
||||
const row = node('article', undefined, 'destination-row');
|
||||
const info = node('div'); info.append(node('h2', bookmark.name), node('p', `${bookmark.host}:${bookmark.port}${bookmark.channelId ? ` · Channel ${bookmark.channelId}` : ''}`, 'hint'));
|
||||
row.append(info, node('span', bookmark.nickname, 'destination-nickname'), node('span', active ? $('connection-badge').textContent : 'Disconnected', `destination-state${active ? ' is-active' : ''}`));
|
||||
const actions = node('div', undefined, 'row');
|
||||
const connect = node('button', active ? connected ? 'Open console' : 'View connection' : 'Connect', 'secondary'); connect.disabled = !active && (connectionActive || !$('ts3-connect') || $('ts3-connect').disabled);
|
||||
connect.setAttribute('aria-label', `${active ? 'Open console for' : 'Connect to'} ${bookmark.name}`);
|
||||
connect.addEventListener('click', () => active ? navigate('console') : startConnection(bookmark));
|
||||
const edit = node('button', 'Edit', 'quiet'); edit.setAttribute('aria-label', `Edit ${bookmark.name}`); edit.addEventListener('click', () => void editConnection(bookmark)); actions.append(connect, edit);
|
||||
if (active) { const disconnect = node('button', 'Disconnect', 'quiet'); disconnect.addEventListener('click', () => $('ts3-disconnect').click()); actions.append(disconnect); }
|
||||
row.append(actions); fragment.append(row);
|
||||
}
|
||||
if (!fragment.childNodes.length) { const empty = node('div', undefined, 'destinations-empty'); empty.append(node('h2', 'Your next destination starts here.'), node('p', 'Save a server, nickname and optional channel. Come back to it whenever you sign in.', 'hint')); const add = node('button', 'Add your first connection'); add.addEventListener('click', () => void editConnection()); empty.append(add); fragment.append(empty); }
|
||||
$('bookmarks').replaceChildren(fragment);
|
||||
const last = preferences?.connection;
|
||||
$('recent-connection').hidden = !last || preferences.bookmarks.some(item => sameDestination(item, last));
|
||||
if (last) { const description = node('div'); description.append(node('p', 'LAST USED CONNECTION', 'eyebrow'), node('h2', `${last.host}:${last.port}`), node('p', last.nickname, 'hint')); const reconnect = node('button', connectionActive ? 'Open console' : 'Reconnect', 'secondary'); reconnect.disabled = !connectionActive && $('ts3-connect').disabled; reconnect.addEventListener('click', () => connectionActive ? navigate('console') : startConnection(last)); $('recent-connection').replaceChildren(description, reconnect); }
|
||||
$('workspace-loading').hidden = Boolean(preferences);
|
||||
if (connectionActive) $('preferences-status').textContent = 'One connection is active. Open its console or disconnect before connecting to another server.';
|
||||
}
|
||||
function applyTheme() { document.documentElement.dataset.theme = theme === 'system' ? 'dark' : theme; $('theme-toggle').textContent = `Theme: ${theme}`; }
|
||||
export async function loadWorkspace(token) {
|
||||
const epoch = ++workspaceEpoch; workspaceCsrf = token; preferences = undefined; signedIn = true; editorDirty = false;
|
||||
await navigate(resolvePage(location.hash), { replace: true, force: true });
|
||||
try {
|
||||
const value = await workspaceApi('/api/preferences'); if (epoch !== workspaceEpoch) return;
|
||||
preferences = value; theme = value.theme; applyTheme(); applyConnection(page === 'connection' ? undefined : value.connection); $('profile-nickname').value = value.nickname;
|
||||
$('bookmark-save').disabled = false; $('preferences-status').textContent = 'Your saved destinations are ready.'; renderBookmarks();
|
||||
} catch (error) { if (epoch === workspaceEpoch) { $('workspace-loading').textContent = 'Destinations could not be loaded. Reload to try again.'; $('preferences-status').textContent = error.message; } }
|
||||
}
|
||||
export function resetWorkspace() {
|
||||
++workspaceEpoch; signedIn = false; preferences = undefined; workspaceCsrf = undefined; selectedBookmark = undefined; preferenceBusy = false; editorDirty = false;
|
||||
clearEditorSecrets(); $('connection-form').reset(); $('profile-nickname').value = ''; $('bookmarks').replaceChildren(); $('workspace-loading').hidden = false; $('workspace-loading').textContent = 'Loading your destinations…'; $('recent-connection').hidden = true;
|
||||
$('editor-status').textContent = ''; $('preferences-status').textContent = ''; delete $('settings-dialog').dataset.bookmarkId;
|
||||
if (confirmResolve) finishConfirm(false); history.replaceState(null, '', '#connections');
|
||||
}
|
||||
async function savePreferences(value) {
|
||||
if (!preferences || preferenceBusy) throw new Error('Wait for your destinations to finish loading or saving.');
|
||||
const epoch = workspaceEpoch; preferenceBusy = true; $('bookmark-save').disabled = true;
|
||||
try { const result = await workspaceApi('/api/preferences', value); if (epoch !== workspaceEpoch) return; preferences = result; renderBookmarks(); return result; }
|
||||
finally { if (epoch === workspaceEpoch) { preferenceBusy = false; $('bookmark-save').disabled = false; } }
|
||||
}
|
||||
window.addEventListener('voxharbor-connection-saved', ({ detail }) => { if (!workspaceCsrf) return; preferences = detail; renderBookmarks(); });
|
||||
window.addEventListener('voxharbor-capabilities', renderBookmarks);
|
||||
function node(tag, text, className) { const element = document.createElement(tag); if (text !== undefined) element.textContent = text; if (className) element.className = className; return element; }
|
||||
function scope() { return $('chat-scope').value; }
|
||||
function own() { return state?.participants.find(client => client.id === state.ownClientId); }
|
||||
function scopeKey(message) { return message.target === 'private' || message.target === 'poke' ? `private:${message.peerUid || (message.peerId ?? message.clientId)}` : message.target === 'channel' ? `channel:${message.channelId}` : 'server'; }
|
||||
function activeKey() { return scope() === 'private' ? `private:${privatePeerUid || privatePeer}` : scope() === 'channel' ? `channel:${own()?.channelId}` : 'server'; }
|
||||
function renderMessages() {
|
||||
const nextDraftKey = activeKey();
|
||||
if (draftKey !== nextDraftKey) {
|
||||
if (draftKey) { if ($('message-input').value) drafts.set(draftKey, $('message-input').value); else drafts.delete(draftKey); }
|
||||
if (drafts.size > 40) drafts.delete(drafts.keys().next().value);
|
||||
$('message-input').value = drafts.get(nextDraftKey) || ''; draftKey = nextDraftKey;
|
||||
}
|
||||
const list = $('messages'); const oldScroll = list.scrollTop; const pinned = list.scrollHeight - list.scrollTop - list.clientHeight < 60;
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (const message of (page === 'conversation' && scope() !== 'private' ? [] : messages.filter(message => scopeKey(message) === activeKey()))) {
|
||||
const row = node('li', undefined, `message${message.outgoing ? ' own-message' : ''}`);
|
||||
row.dataset.message = String(message.id);
|
||||
const heading = node('div', undefined, 'message-heading');
|
||||
heading.append(node('strong', message.name), node('time', new Date(message.at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })));
|
||||
row.append(heading, node('p', message.message)); fragment.append(row);
|
||||
}
|
||||
list.replaceChildren(fragment);
|
||||
$('chat-empty').hidden = list.children.length > 0;
|
||||
$('chat-empty').replaceChildren(document.createTextNode(page === 'conversation' && scope() !== 'private' ? 'Choose a participant.' : 'No messages yet.'), node('span', page === 'conversation' && scope() !== 'private' ? 'Your private conversations appear here.' : 'Your conversation starts here.'));
|
||||
list.scrollTop = pinned ? list.scrollHeight : oldScroll;
|
||||
const channel = state?.channels.find(channel => channel.id === own()?.channelId);
|
||||
const peer = state?.participants.find(client => client.id === privatePeer && (!privatePeerUid || client.uid === privatePeerUid));
|
||||
$('chat-context').textContent = scope() === 'private' ? `Private conversation with ${peer?.name || 'a disconnected participant'}` : scope() === 'server' ? 'Visible to the server. Messages are not saved.' : channel ? `Current channel · ${channel.name}` : 'Messages stay in this browser session.';
|
||||
$('message-input').disabled = !connected || (scope() === 'private' && !peer);
|
||||
$('message-send').disabled = $('message-input').disabled || sending;
|
||||
for (const button of document.querySelectorAll('[data-chat-scope]')) button.setAttribute('aria-pressed', String(button.dataset.chatScope === scope()));
|
||||
$('private-chat').setAttribute('aria-pressed', String(scope() === 'private'));
|
||||
$('private-chat').textContent = scope() === 'private' && peer ? `Private · ${peer.name}` : 'Private';
|
||||
$('message-input').placeholder = scope() === 'private' ? `Message ${peer?.name || 'participant'}…` : scope() === 'server' ? 'Message the server…' : channel ? `Message ${channel.name}…` : 'Message this room…';
|
||||
renderThreads();
|
||||
$('poke-open').hidden = scope() !== 'private'; $('poke-open').disabled = !connected || !peer;
|
||||
}
|
||||
function appendMessage(message) {
|
||||
const duplicate = messages.some(previous => previous.outgoing !== message.outgoing && previous.clientId === message.clientId && scopeKey(previous) === scopeKey(message) && previous.message === message.message && Math.abs(previous.at - message.at) < 5000);
|
||||
if (duplicate) return;
|
||||
messages.push({ ...message, id: ++sequence }); if (messages.length > 200) messages.shift(); renderMessages();
|
||||
}
|
||||
function openPrivate(client) {
|
||||
unread.delete(client.uid || String(client.id));
|
||||
privatePeer = client.id;
|
||||
privatePeerUid = client.uid || undefined;
|
||||
let option = $('chat-scope').querySelector('option[value="private"]');
|
||||
if (!option) { option = new Option('', 'private'); $('chat-scope').add(option); }
|
||||
option.textContent = `Private · ${client.name}`; $('chat-scope').value = 'private';
|
||||
threads.set(client.uid || String(client.id), { ...client }); renderMessages(); void navigate('conversation').then(() => $('message-input').focus());
|
||||
}
|
||||
|
||||
function emptyRoom() {
|
||||
const empty = node('div', undefined, 'room-empty');
|
||||
empty.append(node('p', 'NO ROOM SELECTED', 'eyebrow'), node('h2', 'A little quieter here.'), node('p', 'Connect to your server to see rooms and people.', 'hint'));
|
||||
const button = node('button', 'Set up a connection ↗', 'secondary'); button.addEventListener('click', () => navigate('connections')); empty.append(button);
|
||||
$('member-list').replaceChildren(empty);
|
||||
}
|
||||
function renderChannel() {
|
||||
renderRooms();
|
||||
if (!state) return;
|
||||
const channel = state.channels.find(channel => channel.id === own()?.channelId);
|
||||
if (!channel) return;
|
||||
const current = channel.id === own()?.channelId;
|
||||
const peers = state.participants.filter(client => client.channelId === channel.id && client.id !== state.ownClientId);
|
||||
$('selected-channel-name').textContent = channel.name;
|
||||
$('selected-channel-topic').textContent = channel.topic || (current ? 'A place to catch up. Keep it kind.' : 'Select Join channel to move here.');
|
||||
$('channel-context').textContent = `${current ? 'Your room' : 'Channel preview'} / ${peers.length} ${peers.length === 1 ? 'other' : 'others'} / ${channel.codec === 4 || channel.codec === 5 ? 'Opus voice' : 'Unsupported audio codec'}`;
|
||||
$('join-selected').hidden = current; $('join-selected').disabled = !connected;
|
||||
$('subscription-toggle').hidden = false; $('subscription-toggle').disabled = !connected;
|
||||
$('subscription-toggle').textContent = channel.subscribed ? 'Subscribed / Unsubscribe' : 'Subscribe';
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (const [index, client] of peers.entries()) {
|
||||
const card = node('div', undefined, 'member'); card.dataset.member = String(client.id);
|
||||
card.classList.toggle('speaking', activeSpeakers.has(client.id));
|
||||
const top = node('div', undefined, 'member-top'); top.append(node('span', String(index + 1).padStart(2, '0'))); card.append(top);
|
||||
const baseStatus = client.awayMessage !== null && client.awayMessage !== undefined ? `Away${client.awayMessage ? ` · ${client.awayMessage}` : ''}` : client.outputMuted ? 'Output muted' : client.inputMuted ? 'Microphone muted' : 'Listening';
|
||||
const status = node('span', activeSpeakers.has(client.id) ? 'Speaking' : baseStatus, 'hint'); status.dataset.baseStatus = baseStatus;
|
||||
const info = node('div', undefined, 'member-info'); info.append(node('strong', client.name), status); card.append(info);
|
||||
const mix = node('div', undefined, 'member-mix'); const value = Math.round(getParticipantVolume(client.id) * 100);
|
||||
const readout = node('div'); const output = node('output', String(value), 'volume-value'); output.dataset.volumeReadout = String(client.id); output.append(node('small', 'PLAYBACK %'));
|
||||
readout.append(output, node('p', 'Volume', 'volume-label'));
|
||||
const fader = node('div', undefined, 'fader'); const volume = node('input'); volume.type = 'range'; volume.min = '0'; volume.max = '200'; volume.value = String(value); volume.disabled = !connected;
|
||||
volume.dataset.volumeClient = String(client.id); volume.setAttribute('aria-label', `Playback volume for ${client.name}`); volume.setAttribute('aria-valuetext', `${value} percent`);
|
||||
volume.addEventListener('input', () => setParticipantVolume(client.id, Number(volume.value) / 100));
|
||||
const scale = node('div', undefined, 'fader-scale'); scale.setAttribute('aria-hidden', 'true'); scale.append(node('span', '200'), node('span', '100'), node('span', '0'));
|
||||
fader.append(volume, scale); mix.append(readout, fader); card.append(mix);
|
||||
const actions = node('div', undefined, 'member-actions');
|
||||
const message = node('button', 'Message', 'quiet'); message.disabled = !connected; message.addEventListener('click', () => openPrivate(client));
|
||||
const poke = node('button', 'Poke', 'quiet'); poke.disabled = !connected; poke.addEventListener('click', () => { openPrivate(client); $('poke-open').click(); });
|
||||
actions.append(message, poke); card.append(actions); fragment.append(card);
|
||||
}
|
||||
if (!fragment.childNodes.length) {
|
||||
const empty = node('div', undefined, 'room-empty'); empty.append(node('p', current ? 'YOU’RE HERE' : 'ROOM PREVIEW', 'eyebrow'), node('h2', 'Room for conversation.'), node('p', 'No other visible participants in this channel.', 'hint')); fragment.append(empty);
|
||||
}
|
||||
const focused = document.activeElement?.dataset.volumeClient; const scroll = $('member-list').scrollTop;
|
||||
$('member-list').replaceChildren(fragment); $('member-list').scrollTop = scroll;
|
||||
if (focused) $('member-list').querySelector(`[data-volume-client="${focused}"]`)?.focus({ preventScroll: true });
|
||||
$('mixer-count').textContent = `${peers.length} ${peers.length === 1 ? 'participant' : 'participants'} · Playback volume 0–200%`;
|
||||
}
|
||||
window.addEventListener('voxharbor-volume', ({ detail }) => {
|
||||
for (const input of document.querySelectorAll('[data-volume-client]')) if (Number(input.dataset.volumeClient) === detail.id) { input.value = String(Math.round(detail.volume * 100)); input.setAttribute('aria-valuetext', `${input.value} percent`); }
|
||||
for (const output of document.querySelectorAll('[data-volume-readout]')) if (Number(output.dataset.volumeReadout) === detail.id) { output.replaceChildren(document.createTextNode(String(Math.round(detail.volume * 100))), node('small', 'PLAYBACK %')); }
|
||||
});
|
||||
|
||||
$('subscription-toggle').addEventListener('click', async () => {
|
||||
const channel = state?.channels.find(channel => channel.id === own()?.channelId); if (!channel) return;
|
||||
$('subscription-toggle').disabled = true;
|
||||
try { await clientCommand({ type: 'subscribe', channelId: channel.id, subscribed: !channel.subscribed }); }
|
||||
catch (error) { $('notice').textContent = error.message; }
|
||||
finally { renderChannel(); }
|
||||
});
|
||||
$('nickname-update').addEventListener('click', async () => {
|
||||
$('nickname-update').disabled = true;
|
||||
try { await clientCommand({ type: 'nickname', name: $('profile-nickname').value.trim() }); $('ts3-nickname').value = $('profile-nickname').value.trim(); $('profile-status').textContent = 'Nickname updated.'; }
|
||||
catch (error) { $('profile-status').textContent = error.message; }
|
||||
finally { $('nickname-update').disabled = !connected; }
|
||||
});
|
||||
$('away-toggle').addEventListener('click', async () => {
|
||||
$('away-toggle').disabled = true;
|
||||
try {
|
||||
if (new TextEncoder().encode($('away-message').value).length > 500) throw new Error('Keep the away message within 500 UTF-8 bytes.');
|
||||
await clientCommand({ type: 'away', away: own()?.awayMessage === null || own()?.awayMessage === undefined, message: $('away-message').value }); $('profile-status').textContent = 'Status updated.';
|
||||
}
|
||||
catch (error) { $('profile-status').textContent = error.message; }
|
||||
finally { $('away-toggle').disabled = !connected; }
|
||||
});
|
||||
$('poke-open').addEventListener('click', () => { const peer = state?.participants.find(client => client.id === privatePeer && (!privatePeerUid || client.uid === privatePeerUid)); if (!peer) return; $('poke-recipient').textContent = peer.name; $('poke-message').value = ''; $('poke-status').textContent = ''; $('poke-dialog').showModal(); });
|
||||
$('poke-form').addEventListener('submit', async event => {
|
||||
event.preventDefault(); const id = privatePeer; const uid = privatePeerUid;
|
||||
if (!connected || !state?.participants.some(client => client.id === id && (!uid || client.uid === uid))) { $('poke-status').textContent = 'This participant is no longer connected.'; return; }
|
||||
if (new TextEncoder().encode($('poke-message').value).length > 500) { $('poke-status').textContent = 'Keep the poke within 500 UTF-8 bytes.'; return; }
|
||||
let message = $('poke-message').value; $('poke-message').value = ''; $('poke-submit').disabled = true;
|
||||
try { await clientCommand({ type: 'poke', clientId: id, ...(uid ? { clientUid: uid } : {}), message }); $('poke-dialog').close(); $('message-status').textContent = 'Poke sent.'; }
|
||||
catch (error) { $('poke-status').textContent = error.message; }
|
||||
finally { message = ''; $('poke-submit').disabled = false; }
|
||||
});
|
||||
$('poke-dialog').addEventListener('close', () => { $('poke-message').value = ''; });
|
||||
for (const button of document.querySelectorAll('[data-chat-scope]')) button.addEventListener('click', () => { $('chat-scope').value = button.dataset.chatScope; $('chat-scope').dispatchEvent(new Event('change')); });
|
||||
$('chat-scope').addEventListener('change', () => { $('message-status').textContent = ''; renderMessages(); });
|
||||
$('message-form').addEventListener('submit', async event => {
|
||||
event.preventDefault(); if (sending) return; const message = $('message-input').value.trim(); if (!message) return;
|
||||
if (new TextEncoder().encode(message).length > 1000) { $('message-status').textContent = 'Message is too long. Keep it within 1,000 UTF-8 bytes.'; return; }
|
||||
const epoch = workspaceEpoch; const requestDraftKey = activeKey(); const target = scope(); const peerId = privatePeer; const peerUid = privatePeerUid; const channelId = own()?.channelId; const sender = own();
|
||||
sending = true; $('message-send').disabled = true; $('message-status').textContent = 'Sending…';
|
||||
try {
|
||||
await clientCommand({ type: 'text_message', target, ...(target === 'channel' ? { channelId } : {}), ...(target === 'private' ? { clientId: peerId, ...(peerUid ? { clientUid: peerUid } : {}) } : {}), message });
|
||||
if (epoch !== workspaceEpoch) return;
|
||||
appendMessage({ target, peerId, peerUid, channelId, clientId: sender.id, name: sender.name, message, outgoing: true, at: Date.now() });
|
||||
drafts.delete(requestDraftKey); if (activeKey() === requestDraftKey && $('message-input').value.trim() === message) $('message-input').value = ''; $('message-status').textContent = 'Sent.';
|
||||
} catch (error) { if (epoch === workspaceEpoch) $('message-status').textContent = error.message; }
|
||||
finally { if (epoch === workspaceEpoch) { sending = false; renderMessages(); } }
|
||||
});
|
||||
|
||||
function renderRooms() {
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (const channel of recentChannels(state?.channels || [], own()?.channelId, recent)) {
|
||||
const row = node('li'); const button = node('button', channel.name);
|
||||
button.setAttribute('aria-current', String(channel.id === own()?.channelId)); button.setAttribute('aria-label', `Preview channel ${channel.name}`);
|
||||
button.append(node('span', String(state.participants.filter(client => client.channelId === channel.id).length).padStart(2, '0'), 'room-number'));
|
||||
button.addEventListener('click', () => { selected = channel.id; void navigate('channels'); }); row.append(button); fragment.append(row);
|
||||
}
|
||||
if (!fragment.childNodes.length) fragment.append(node('li', 'Connect to find your rooms.', 'hint'));
|
||||
$('room-tabs').replaceChildren(fragment);
|
||||
}
|
||||
function renderBrowser() {
|
||||
const fragment = document.createDocumentFragment(); const query = $('channel-search').value; let count = 0;
|
||||
for (const { channel, depth } of orderChannels(state?.channels || [])) {
|
||||
if (!matchesChannel(channel, state.channels, state.participants, query)) continue;
|
||||
count++; const row = node('li'); row.dataset.channel = String(channel.id); row.dataset.depth = String(Math.min(depth, 4));
|
||||
const button = node('button', undefined, 'channel-result'); button.setAttribute('aria-label', `Preview ${channel.name}`); button.setAttribute('aria-pressed', String(selected === channel.id));
|
||||
const text = node('div'); text.append(node('strong', channel.name), node('span', channelPath(channel, state.channels) || 'Top-level channel', 'hint'));
|
||||
const people = state.participants.filter(person => person.channelId === channel.id);
|
||||
const matching = query.trim() ? people.filter(person => person.name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())).map(person => person.name).join(', ') : '';
|
||||
if (matching) text.append(node('span', `People: ${matching}`, 'hint'));
|
||||
button.append(text, node('span', `${people.length} ${people.length === 1 ? 'person' : 'people'}${channel.passwordProtected ? ' · Password' : ''}${channel.id === own()?.channelId ? ' · You’re here' : ''}`, 'hint'));
|
||||
button.addEventListener('click', () => { selected = channel.id; $('join-password').value = ''; $('join-status').textContent = ''; renderBrowser(); if (matchMedia('(max-width: 660px)').matches) $('channel-detail').scrollIntoView({ behavior: 'smooth', block: 'start' }); }); row.append(button); fragment.append(row);
|
||||
}
|
||||
const focus = document.activeElement?.closest('[data-channel]')?.dataset.channel; const scroll = $('ts3-channels').scrollTop;
|
||||
$('ts3-channels').replaceChildren(fragment); $('ts3-channels').scrollTop = scroll;
|
||||
if (focus) $('ts3-channels').querySelector(`[data-channel="${focus}"] button`)?.focus({ preventScroll: true });
|
||||
$('channel-count').textContent = `${count} / ${state?.channels.length || 0}`; $('tree-empty').hidden = Boolean(state?.channels.length); $('search-empty').hidden = !state || count > 0;
|
||||
const channel = state?.channels.find(channel => channel.id === selected);
|
||||
$('browse-channel-name').textContent = channel?.name || 'Choose a channel'; $('browse-channel-topic').textContent = channel?.topic || '';
|
||||
$('browse-channel-meta').textContent = channel ? `${channelPath(channel, state.channels) || 'Top-level channel'}${channel.passwordProtected ? ' / Password required' : ''}${!connected ? ' / Last received state' : ''}` : 'Select a room to preview its participants.';
|
||||
const people = document.createDocumentFragment();
|
||||
for (const person of state?.participants.filter(person => person.channelId === selected) || []) { const item = node('li', person.name); if (person.id !== state.ownClientId) { const message = node('button', 'Message', 'quiet'); message.disabled = !connected; message.addEventListener('click', () => openPrivate(person)); item.append(message); } people.append(item); }
|
||||
$('browse-participants').replaceChildren(people);
|
||||
$('join-form').hidden = !channel || channel.id === own()?.channelId; $('browse-return').hidden = !channel || channel.id !== own()?.channelId;
|
||||
$('join-password').hidden = !channel?.passwordProtected; $('join-password-label').hidden = !channel?.passwordProtected; $('join-password').required = Boolean(channel?.passwordProtected);
|
||||
$('join-submit').disabled = !connected; $('join-name').textContent = channel?.name || '';
|
||||
}
|
||||
function renderThreads() {
|
||||
const fragment = document.createDocumentFragment();
|
||||
const totalUnread = [...unread.values()].reduce((sum, count) => sum + count, 0); $('messages-nav').textContent = totalUnread ? `Messages (${totalUnread})` : 'Messages';
|
||||
const peers = state?.participants.filter(person => person.id !== state.ownClientId) || [];
|
||||
for (const person of peers) { const key = person.uid || String(person.id); if (!threads.has(key)) threads.set(key, person); }
|
||||
for (const [key, person] of threads) {
|
||||
const current = peers.find(peer => (peer.uid || String(peer.id)) === key);
|
||||
const button = node('button', undefined, 'thread'); button.append(node('strong', person.name), node('span', `${unread.get(key) ? `${unread.get(key)} unread · ` : ''}${current && connected ? 'Available · This session' : 'Disconnected · This session'}`, 'hint'));
|
||||
button.setAttribute('aria-pressed', String(Boolean(current && privatePeer === current.id))); button.disabled = !current || !connected;
|
||||
button.addEventListener('click', () => openPrivate(current)); fragment.append(button);
|
||||
}
|
||||
if (!fragment.childNodes.length) fragment.append(node('p', 'Connected participants will appear here.', 'hint'));
|
||||
$('conversation-threads').replaceChildren(fragment);
|
||||
const peer = state?.participants.find(person => person.id === privatePeer && (!privatePeerUid || person.uid === privatePeerUid));
|
||||
$('direct-name').textContent = peer?.name || 'Choose someone'; $('direct-status').textContent = peer ? state.channels.find(channel => channel.id === peer.channelId)?.name || 'Connected participant' : 'Choose a participant to start a private conversation.';
|
||||
$('direct-volume').disabled = !peer || !connected; $('direct-poke').disabled = !peer || !connected;
|
||||
$('direct-volume').value = String(Math.round(getParticipantVolume(peer?.id) * 100)); $('direct-volume-value').textContent = `${$('direct-volume').value}% / Range 0–200%`;
|
||||
if (page === 'conversation' && scope() !== 'private') { $('message-input').disabled = true; $('message-send').disabled = true; $('chat-context').textContent = 'Choose a participant to open a private conversation.'; }
|
||||
}
|
||||
$('direct-volume').addEventListener('input', () => { if (privatePeer) { setParticipantVolume(privatePeer, Number($('direct-volume').value) / 100); $('direct-volume-value').textContent = `${$('direct-volume').value}% / Range 0–200%`; } });
|
||||
$('ribbon-mute').addEventListener('click', () => { if ($('voice-mic').getAttribute('aria-pressed') === 'true') $('voice-mic').click(); });
|
||||
$('direct-poke').addEventListener('click', () => $('poke-open').click());
|
||||
for (const button of document.querySelectorAll('[data-return-scope]')) button.addEventListener('click', () => { $('chat-scope').value = button.dataset.returnScope; renderMessages(); void navigate('console'); });
|
||||
$('private-chat').addEventListener('click', () => { void navigate('conversation'); });
|
||||
$('channel-search').addEventListener('input', renderBrowser);
|
||||
$('join-selected').addEventListener('click', () => { selected = own()?.channelId; void navigate('channels'); });
|
||||
$('join-form').addEventListener('submit', async event => {
|
||||
event.preventDefault(); const id = selected; let password = $('join-password').value; $('join-password').value = ''; $('join-submit').disabled = true;
|
||||
try { await joinChannel(id, password); $('join-status').textContent = ''; await navigate('console'); }
|
||||
catch (error) { $('join-status').textContent = error.message; }
|
||||
finally { password = ''; $('join-submit').disabled = !connected; }
|
||||
});
|
||||
$('quick-connect').addEventListener('click', () => void navigate('connections'));
|
||||
$('connection-add').addEventListener('click', () => void editConnection());
|
||||
$('connection-form').addEventListener('input', () => { editorDirty = true; });
|
||||
async function saveEditor(connect) {
|
||||
if (!$('connection-form').reportValidity() || preferenceBusy) return;
|
||||
if (connect && ($('ts3-connect').disabled || connectionActive)) { $('editor-status').textContent = 'Set up your identity and disconnect any active server before connecting.'; return; }
|
||||
const epoch = workspaceEpoch; const id = selectedBookmark || crypto.randomUUID();
|
||||
const connectionPasswords = {}; if ($('ts3-password').value) connectionPasswords.password = $('ts3-password').value; if ($('ts3-channel-password').value) connectionPasswords.channelPassword = $('ts3-channel-password').value; if ($('bookmark-clear-passwords').checked) { connectionPasswords.password = ''; connectionPasswords.channelPassword = ''; }
|
||||
const bookmark = { id, name: $('bookmark-name').value.trim(), host: $('ts3-host').value.trim(), port: Number($('ts3-port').value), nickname: $('ts3-nickname').value.trim(), channelId: $('ts3-channel').value ? Number($('ts3-channel').value) : null };
|
||||
if ($('bookmark-passwords').checked) { if ($('ts3-password').value) bookmark.password = $('ts3-password').value; if ($('ts3-channel-password').value) bookmark.channelPassword = $('ts3-channel-password').value; }
|
||||
if ($('bookmark-clear-passwords').checked) { bookmark.password = ''; bookmark.channelPassword = ''; }
|
||||
$('editor-status').textContent = 'Saving your destination…'; $('editor-connect').disabled = true;
|
||||
try {
|
||||
const result = await savePreferences({ ...preferences, nickname: bookmark.nickname, theme, bookmarks: [...preferences.bookmarks.filter(item => item.id !== id), bookmark] });
|
||||
if (!result || epoch !== workspaceEpoch) return; editorDirty = false; selectedBookmark = id; clearEditorSecrets();
|
||||
$('editor-status').textContent = 'Connection saved.';
|
||||
if (connect) await startConnection(preferences.bookmarks.find(item => item.id === id), connectionPasswords); else await navigate('connections');
|
||||
} catch (error) { if (epoch === workspaceEpoch) $('editor-status').textContent = error.message; }
|
||||
finally { connectionPasswords.password = ''; connectionPasswords.channelPassword = ''; bookmark.password = ''; bookmark.channelPassword = ''; if (epoch === workspaceEpoch) $('editor-connect').disabled = $('ts3-connect').disabled; }
|
||||
}
|
||||
$('connection-form').addEventListener('submit', event => { event.preventDefault(); void saveEditor(true); });
|
||||
$('bookmark-save').addEventListener('click', () => void saveEditor(false));
|
||||
$('bookmark-delete').addEventListener('click', async () => {
|
||||
if (!selectedBookmark || !preferences || preferenceBusy) return;
|
||||
const id = selectedBookmark;
|
||||
if (!await confirmAction('Delete this saved connection?', 'This removes only the saved destination. Your account and TeamSpeak identity are kept.', 'Delete connection')) return;
|
||||
try { const result = await savePreferences({ ...preferences, bookmarks: preferences.bookmarks.filter(item => item.id !== id) }); if (!result) return; editorDirty = false; await navigate('connections'); }
|
||||
catch (error) { $('editor-status').textContent = error.message; }
|
||||
});
|
||||
$('mixer-layout').addEventListener('click', () => { const compact = $('mixer-layout').getAttribute('aria-pressed') !== 'true'; $('mixer-layout').setAttribute('aria-pressed', String(compact)); $('mixer-layout').textContent = compact ? 'Mixer view' : 'Compact view'; $('member-list').classList.toggle('compact-members', compact); });
|
||||
function syncAudioModes() { for (const button of document.querySelectorAll('[data-audio-mode]')) button.setAttribute('aria-pressed', String(button.dataset.audioMode === $('voice-mode').value)); }
|
||||
for (const button of document.querySelectorAll('[data-audio-mode]')) button.addEventListener('click', () => { $('voice-mode').value = button.dataset.audioMode; $('voice-mode').dispatchEvent(new Event('change')); });
|
||||
$('voice-mode').addEventListener('change', syncAudioModes); syncAudioModes();
|
||||
for (const button of document.querySelectorAll('[data-close]')) button.addEventListener('click', () => $(button.dataset.close).close());
|
||||
$('message-input').addEventListener('keydown', event => { if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); if (!$('message-send').disabled) $('message-form').requestSubmit(); } });
|
||||
$('theme-toggle').addEventListener('click', async () => { theme = themes[(themes.indexOf(theme) + 1) % themes.length]; applyTheme(); if (preferences) try { await savePreferences({ ...preferences, theme }); } catch (error) { $('notice').textContent = error.message; } });
|
||||
window.addEventListener('voxharbor-speaking', ({ detail }) => { activeSpeakers = new Set(detail); for (const card of $('member-list').querySelectorAll('[data-member]')) { const active = activeSpeakers.has(Number(card.dataset.member)); card.classList.toggle('speaking', active); const status = card.querySelector('[data-base-status]'); if (status) status.textContent = active ? 'Speaking' : status.dataset.baseStatus; } });
|
||||
window.addEventListener('voxharbor-state', ({ detail }) => {
|
||||
state = detail; const current = own()?.channelId;
|
||||
if (previousOwnChannel && previousOwnChannel !== current && scope() === 'channel') { $('message-input').value = ''; $('message-status').textContent = 'Channel changed. The previous draft was cleared.'; }
|
||||
if (previousOwnChannel !== current) recent = [current, ...recent].filter(Boolean).slice(0, 4);
|
||||
if (!selected || !state.channels.some(channel => channel.id === selected)) selected = current;
|
||||
previousOwnChannel = current; if (document.activeElement !== $('profile-nickname')) $('profile-nickname').value = own()?.name || '';
|
||||
$('away-toggle').textContent = own()?.awayMessage !== null && own()?.awayMessage !== undefined ? 'Return from away' : 'Set away';
|
||||
$('server-name').textContent = state.server.name; renderChannel(); renderBrowser(); renderMessages();
|
||||
});
|
||||
window.addEventListener('voxharbor-connection', ({ detail }) => {
|
||||
connected = detail.state === 'connected'; connectionActive = ['connected', 'connecting', 'retrying', 'offline'].includes(detail.state);
|
||||
$('lab').dataset.connection = detail.state;
|
||||
$('connection-badge').textContent = ({connected:'Connected',connecting:'Connecting',retrying:'Reconnecting',stopped:'Offline',offline:'Network offline',failed:'Connection failed',expired:'Signed out'})[detail.state] || detail.state;
|
||||
$('connection-badge').dataset.state = detail.state; $('ribbon-status').textContent = $('connection-badge').textContent;
|
||||
$('session-ribbon').hidden = !connectionActive || page === 'console'; $('nickname-update').disabled = !connected; $('away-toggle').disabled = !connected;
|
||||
if (!connected) { privatePeer = undefined; privatePeerUid = undefined; $('chat-scope').querySelector('option[value="private"]')?.remove(); if (scope() === 'private') $('chat-scope').value = 'channel'; $('message-input').value = ''; }
|
||||
if (detail.state === 'stopped') { messages.length = 0; drafts.clear(); draftKey = undefined; threads.clear(); unread.clear(); }
|
||||
if (['stopped','failed','expired'].includes(detail.state)) { state = undefined; selected = undefined; recent = []; emptyRoom(); $('selected-channel-name').textContent = 'Your place to talk.'; $('channel-context').textContent = 'READY WHEN YOU ARE'; $('subscription-toggle').hidden = true; }
|
||||
renderBookmarks(); renderChannel(); renderBrowser(); renderMessages();
|
||||
});
|
||||
window.addEventListener('voxharbor-message', ({ detail }) => {
|
||||
if ((detail.target === 'private' || detail.target === 'poke') && detail.clientId !== state?.ownClientId && !(page === 'conversation' && privatePeer === detail.clientId)) { const key = detail.uid || String(detail.clientId); unread.set(key, (unread.get(key) || 0) + 1); }
|
||||
const outgoing = detail.clientId === state?.ownClientId; const peerId = outgoing ? detail.targetClientId : detail.clientId;
|
||||
const peerUid = (outgoing ? detail.targetUid : detail.uid) || state?.participants.find(client => client.id === peerId)?.uid;
|
||||
appendMessage({ ...detail, peerId, peerUid, at: Date.now(), outgoing });
|
||||
if ((detail.target === 'private' || detail.target === 'poke') && scope() !== 'private') $('message-status').textContent = `New ${detail.target === 'poke' ? 'poke' : 'private message'} from ${detail.name}. Open Private to read it.`;
|
||||
});
|
||||
window.addEventListener('voxharbor-reset', () => { state = undefined; connected = false; connectionActive = false; selected = undefined; recent = []; privatePeer = undefined; privatePeerUid = undefined; previousOwnChannel = undefined; messages.length = 0; drafts.clear(); draftKey = undefined; threads.clear(); unread.clear(); sending = false; $('messages').replaceChildren(); $('message-input').value = ''; $('message-status').textContent = ''; $('channel-search').value = ''; $('away-message').value = ''; $('profile-status').textContent = ''; $('poke-message').value = ''; $('server-name').textContent = 'Your destinations'; $('session-ribbon').hidden = true; emptyRoom(); renderRooms(); renderBrowser(); renderMessages(); syncAudioModes(); for (const dialog of document.querySelectorAll('dialog[open]')) dialog.close(); });
|
||||
applyTheme();
|
||||
|
||||
const phoneLayout = matchMedia('(max-width: 660px)');
|
||||
function layoutEditorActions() { const target = phoneLayout.matches ? $('editor-mobile-actions') : $('editor-primary'); for (const element of [document.querySelector('.editor-actions'), $('editor-status'), $('native-status')]) target.append(element); }
|
||||
phoneLayout.addEventListener('change', layoutEditorActions); layoutEditorActions();
|
||||
$('direct-tools-toggle').addEventListener('click', () => { const expanded = $('direct-tools-toggle').getAttribute('aria-expanded') !== 'true'; $('direct-tools-toggle').setAttribute('aria-expanded', String(expanded)); $('direct-grid').classList.toggle('show-direct-controls', expanded); });
|
||||