Upload files to "kronic-chat/js"

This commit is contained in:
2026-11-25 20:25:51 -06:00
parent cd886f490e
commit 2615897782
5 changed files with 1815 additions and 0 deletions
+76
View File
@@ -0,0 +1,76 @@
window.Kronick = window.Kronick || {};
Kronick.account = { user: null, rooms: [], groups: [] };
Kronick.loadAccountContext = async function loadAccountContext() {
const me = await fetch('/api/auth/me', { cache: 'no-store', credentials: 'same-origin' });
if (!me.ok) {
window.location.replace('/login');
return false;
}
const meData = await me.json();
Kronick.account.user = meData.user;
const roomsResponse = await fetch('/api/my/rooms', { cache: 'no-store', credentials: 'same-origin' });
if (!roomsResponse.ok) throw new Error('Could not load assigned rooms.');
const data = await roomsResponse.json();
Kronick.account.rooms = data.rooms || [];
Kronick.account.groups = data.groups || [];
const userInput = document.getElementById('userName');
if (userInput) {
userInput.value = Kronick.account.user.username;
userInput.readOnly = true;
userInput.title = 'Your account name is used for chat identity.';
}
const roomInput = document.getElementById('roomName');
const roomList = document.getElementById('savedRooms');
if (roomList) {
roomList.innerHTML = '';
Kronick.account.rooms.forEach(room => {
const option = document.createElement('option');
option.value = room.room_name;
option.label = `${room.group_name} — ${room.display_name || room.room_name}`;
roomList.appendChild(option);
});
}
if (roomInput) {
roomInput.placeholder = Kronick.account.rooms.length ? 'Choose an assigned room' : 'No rooms assigned';
roomInput.readOnly = Kronick.account.rooms.length === 0;
let selected = new URLSearchParams(location.search).get('room');
if (window.parent !== window) {
try { selected = new URLSearchParams(window.parent.location.search).get('room') || selected; } catch (_) {}
}
const valid = Kronick.account.rooms.find(r => r.room_name === selected);
if (selected) {
roomInput.value = valid ? valid.room_name : '';
roomInput.readOnly = true;
if (!valid) roomInput.placeholder = 'Selected room unavailable for this account';
} else if (Kronick.account.rooms.length === 1) {
roomInput.value = Kronick.account.rooms[0].room_name;
} else if (!Kronick.account.rooms.some(r => r.room_name === roomInput.value)) {
roomInput.value = '';
}
}
const join = document.getElementById('joinBtn');
if (join && (Kronick.account.rooms.length === 0 || (roomInput?.readOnly && !roomInput.value))) join.disabled = true;
const accountLabel = document.getElementById('accountLabel');
if (accountLabel) accountLabel.textContent = Kronick.account.user.username;
return true;
};
Kronick.logoutAccount = async function logoutAccount() {
try { await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' }); } catch (_) {}
window.location.replace('/login');
};
document.addEventListener('DOMContentLoaded', () => {
Kronick.loadAccountContext().catch(error => {
console.error('Account bootstrap failed:', error);
window.location.replace('/login');
});
});
window.logoutAccount = () => Kronick.logoutAccount();
+197
View File
@@ -0,0 +1,197 @@
window.Kronick = window.Kronick || {};
Kronick.state = Kronick.state || {};
const AUDIO_DEFAULTS = {
voiceActivationEnabled: true,
vadThreshold: -66,
vadHoldMs: 200,
noiseSuppressionEnabled: true,
noiseSuppressionMode: 'hybrid',
rnnoiseStrength: 100,
echoCancellation: true,
autoGainControl: true,
spatialAudioEnabled: true,
spatialWidth: 100,
spatialDepth: 100,
spatialFalloff: 100
};
const AUDIO_KEYS = {
voiceActivationEnabled: 'kronick_voice_activation_enabled',
vadThreshold: 'kronick_vad_threshold',
vadHoldMs: 'kronick_vad_hold',
noiseSuppressionEnabled: 'kronick_noise_suppression_enabled',
noiseSuppressionMode: 'kronick_noise_suppression_mode',
rnnoiseStrength: 'kronick_rnnoise_strength',
echoCancellation: 'kronick_echo_cancellation',
autoGainControl: 'kronick_auto_gain',
spatialAudioEnabled: 'kronick_spatial_audio_enabled',
spatialWidth: 'kronick_spatial_width',
spatialDepth: 'kronick_spatial_depth',
spatialFalloff: 'kronick_spatial_falloff'
};
function readBool(key, fallback) {
const value = localStorage.getItem(key);
return value === null ? fallback : value === 'true';
}
function readNumber(key, fallback) {
const value = Number(localStorage.getItem(key));
return Number.isFinite(value) ? value : fallback;
}
Kronick.loadAudioSettings = function loadAudioSettings() {
Kronick.state.voiceActivationEnabled = readBool(AUDIO_KEYS.voiceActivationEnabled, AUDIO_DEFAULTS.voiceActivationEnabled);
Kronick.state.vadThreshold = readNumber(AUDIO_KEYS.vadThreshold, AUDIO_DEFAULTS.vadThreshold);
Kronick.state.vadHoldMs = readNumber(AUDIO_KEYS.vadHoldMs, AUDIO_DEFAULTS.vadHoldMs);
Kronick.state.noiseSuppressionEnabled = readBool(AUDIO_KEYS.noiseSuppressionEnabled, AUDIO_DEFAULTS.noiseSuppressionEnabled);
Kronick.state.noiseSuppressionMode = localStorage.getItem(AUDIO_KEYS.noiseSuppressionMode) || AUDIO_DEFAULTS.noiseSuppressionMode;
Kronick.state.rnnoiseStrength = readNumber(AUDIO_KEYS.rnnoiseStrength, AUDIO_DEFAULTS.rnnoiseStrength);
Kronick.state.echoCancellation = readBool(AUDIO_KEYS.echoCancellation, AUDIO_DEFAULTS.echoCancellation);
Kronick.state.autoGainControl = readBool(AUDIO_KEYS.autoGainControl, AUDIO_DEFAULTS.autoGainControl);
Kronick.state.spatialAudioEnabled = readBool(AUDIO_KEYS.spatialAudioEnabled, AUDIO_DEFAULTS.spatialAudioEnabled);
Kronick.state.spatialWidth = readNumber(AUDIO_KEYS.spatialWidth, AUDIO_DEFAULTS.spatialWidth);
Kronick.state.spatialDepth = readNumber(AUDIO_KEYS.spatialDepth, AUDIO_DEFAULTS.spatialDepth);
Kronick.state.spatialFalloff = readNumber(AUDIO_KEYS.spatialFalloff, AUDIO_DEFAULTS.spatialFalloff);
};
Kronick.loadAudioSettings();
function saveSetting(stateKey, value) {
Kronick.state[stateKey] = value;
localStorage.setItem(AUDIO_KEYS[stateKey], String(value));
}
function bindCheckbox(id, stateKey, onChange) {
const input = document.getElementById(id);
if (!input) return;
input.checked = Boolean(Kronick.state[stateKey]);
input.addEventListener('change', () => {
saveSetting(stateKey, input.checked);
onChange?.(input.checked);
});
}
function bindRange(id, valueId, stateKey, formatter, onChange) {
const input = document.getElementById(id);
const value = document.getElementById(valueId);
if (!input) return;
input.value = Kronick.state[stateKey];
const render = () => {
const parsed = Number(input.value);
if (value) value.textContent = formatter(parsed);
saveSetting(stateKey, parsed);
onChange?.(parsed);
};
if (value) value.textContent = formatter(Number(input.value));
input.addEventListener('input', render);
}
Kronick.updateNoiseModeUi = function updateNoiseModeUi() {
const enabled = Boolean(Kronick.state.noiseSuppressionEnabled);
const select = document.getElementById('noiseSuppressionMode');
const strength = document.getElementById('rnnoiseStrengthControl');
const help = document.getElementById('noiseModeHelp');
const mode = enabled ? Kronick.state.noiseSuppressionMode : 'off';
if (select) {
select.disabled = !enabled;
if (enabled) select.value = Kronick.state.noiseSuppressionMode;
}
if (strength) {
strength.hidden = !enabled || !['rnnoise', 'hybrid'].includes(mode);
}
const descriptions = {
off: 'Noise filtering is bypassed. Echo cancellation and auto gain can still be controlled below.',
browser: 'Uses the browser/WebRTC noise filter. Lowest overhead and usually best for headsets.',
rnnoise: 'Uses the local RNNoise neural filter. Better for fans, HVAC and steady background noise.',
hybrid: 'Runs browser cleanup first, then RNNoise. Strongest filtering, but can be too aggressive on some microphones.'
};
if (help) help.textContent = descriptions[mode] || descriptions.hybrid;
};
Kronick.refreshSpatialAudio = function refreshSpatialAudio() {
if (!Kronick.state.participantPanners) return;
Kronick.state.participantPanners.forEach((panner, sid) => {
panner.rolloffFactor = Kronick.state.spatialAudioEnabled
? Math.max(0, Kronick.state.spatialFalloff / 100)
: 0;
if (typeof Kronick.updateSpatialAudioPosition === 'function') {
Kronick.updateSpatialAudioPosition(sid);
}
});
};
Kronick.updateVoiceMeter = function updateVoiceMeter(db) {
const fill = document.getElementById('voiceMeterFill');
const label = document.getElementById('voiceMeterDb');
const marker = document.getElementById('voiceThresholdMarker');
const min = -80;
const max = -10;
const clamped = Math.max(min, Math.min(max, Number.isFinite(db) ? db : min));
const percent = ((clamped - min) / (max - min)) * 100;
const thresholdPercent = ((Kronick.state.vadThreshold - min) / (max - min)) * 100;
if (fill) fill.style.width = `${percent}%`;
if (marker) marker.style.left = `${Math.max(0, Math.min(100, thresholdPercent))}%`;
if (label) label.textContent = Number.isFinite(db) && db > -79.9 ? `${db.toFixed(1)} dB` : '-∞ dB';
};
Kronick.initAudioSettings = function initAudioSettings() {
bindCheckbox('voiceActivationToggle', 'voiceActivationEnabled');
bindRange('vadThreshold', 'vadThresholdVal', 'vadThreshold', value => `${value} dB`, () => Kronick.updateVoiceMeter(Kronick.state.currentMicDb ?? -80));
bindRange('vadHold', 'vadHoldVal', 'vadHoldMs', value => `${value} ms`);
bindCheckbox('noiseSuppressionToggle', 'noiseSuppressionEnabled', Kronick.updateNoiseModeUi);
bindRange('rnnoiseStrength', 'rnnoiseStrengthVal', 'rnnoiseStrength', value => `${value}%`, value => {
const wet = Kronick.state.rnnoiseWetGain;
const dry = Kronick.state.rnnoiseDryGain;
if (!wet || !dry) return;
const mix = Math.max(0, Math.min(1, value / 100));
wet.gain.setTargetAtTime(mix, wet.context.currentTime, 0.015);
dry.gain.setTargetAtTime(1 - mix, dry.context.currentTime, 0.015);
});
bindCheckbox('echoCancellationToggle', 'echoCancellation');
bindCheckbox('autoGainToggle', 'autoGainControl');
const mode = document.getElementById('noiseSuppressionMode');
if (mode) {
mode.value = Kronick.state.noiseSuppressionMode;
mode.addEventListener('change', () => {
saveSetting('noiseSuppressionMode', mode.value);
Kronick.updateNoiseModeUi();
});
}
const applyButton = document.getElementById('applyAudioProcessingBtn');
if (applyButton) {
applyButton.addEventListener('click', async () => {
if (typeof Kronick.applyAudioProcessingSettings !== 'function') return;
applyButton.disabled = true;
const original = applyButton.textContent;
applyButton.textContent = 'Applying…';
try {
const applied = await Kronick.applyAudioProcessingSettings();
applyButton.textContent = applied ? 'Applied' : 'Saved for next join';
} catch (error) {
console.error('Could not apply audio processing settings:', error);
applyButton.textContent = 'Apply failed';
} finally {
window.setTimeout(() => {
applyButton.textContent = original;
applyButton.disabled = false;
}, 1200);
}
});
}
bindCheckbox('spatialAudioToggle', 'spatialAudioEnabled', Kronick.refreshSpatialAudio);
bindRange('spatialWidth', 'spatialWidthVal', 'spatialWidth', value => `${value}%`, Kronick.refreshSpatialAudio);
bindRange('spatialDepth', 'spatialDepthVal', 'spatialDepth', value => `${value}%`, Kronick.refreshSpatialAudio);
bindRange('spatialFalloff', 'spatialFalloffVal', 'spatialFalloff', value => `${value}%`, Kronick.refreshSpatialAudio);
Kronick.updateNoiseModeUi();
Kronick.updateVoiceMeter(-80);
};
+726
View File
@@ -0,0 +1,726 @@
window.Kronick = window.Kronick || {};
/*
* Helper to ensure a shared spatial AudioContext exists and is running
*/
Kronick.getSpatialAudioContext = function getSpatialAudioContext() {
if (!Kronick.state.audioCtx) {
Kronick.state.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (Kronick.state.audioCtx.state === 'suspended') {
Kronick.state.audioCtx.resume();
}
return Kronick.state.audioCtx;
};
/*
* Tear down only the local microphone processing graph.
*/
Kronick.cleanupLocalMicProcessing = function cleanupLocalMicProcessing() {
if (Kronick.state.rawMicStream) {
Kronick.state.rawMicStream.getTracks().forEach(track => track.stop());
Kronick.state.rawMicStream = null;
}
if (Kronick.state.processedAudioContext) {
Kronick.state.processedAudioContext.close().catch(() => {});
Kronick.state.processedAudioContext = null;
}
Kronick.state.rnnoiseNode = null;
Kronick.state.rnnoiseWetGain = null;
Kronick.state.rnnoiseDryGain = null;
Kronick.state.voiceGateNode = null;
Kronick.state.currentMicDb = -80;
if (typeof Kronick.updateVoiceMeter === 'function') {
Kronick.updateVoiceMeter(-80);
}
};
/*
* Rebuild the published microphone so suppression-system changes can be
* applied without leaving and rejoining the room.
*/
Kronick.applyAudioProcessingSettings = async function applyAudioProcessingSettings() {
const room = Kronick.state.room;
if (!room?.localParticipant) return false;
const oldTrack = Kronick.state.localMicTrack;
const wasEnabled = room.localParticipant.isMicrophoneEnabled !== false;
if (oldTrack) {
try {
await room.localParticipant.unpublishTrack(oldTrack, true);
} catch (error) {
console.debug('Old microphone track was already unpublished:', error);
}
}
Kronick.cleanupLocalMicProcessing();
const newTrack = await Kronick.createProcessedMicrophoneTrack();
const publishOptions = LivekitClient.Track?.Source?.Microphone
? { source: LivekitClient.Track.Source.Microphone }
: undefined;
await room.localParticipant.publishTrack(newTrack, publishOptions);
Kronick.state.localMicTrack = newTrack;
if (!wasEnabled && typeof newTrack.mute === 'function') {
await newTrack.mute();
}
return true;
};
/*
* Initialize dynamic RNNoise AudioWorklet & Mumble-style VAD pipeline
*/
Kronick.createProcessedMicrophoneTrack = async function createProcessedMicrophoneTrack(options = {}) {
const mode = options.noiseSuppressionMode
?? Kronick.state.noiseSuppressionMode
?? 'hybrid';
const suppressionEnabled = options.noiseSuppressionEnabled
?? Kronick.state.noiseSuppressionEnabled
?? true;
const effectiveMode = suppressionEnabled ? mode : 'off';
const useBrowserSuppression = ['browser', 'hybrid'].includes(effectiveMode);
const useRnnoise = ['rnnoise', 'hybrid'].includes(effectiveMode);
const constraints = {
echoCancellation: options.echoCancellation
?? Kronick.state.echoCancellation
?? true,
noiseSuppression: useBrowserSuppression,
autoGainControl: options.autoGainControl
?? Kronick.state.autoGainControl
?? true,
channelCount: 1,
sampleRate: 48000
};
const rawStream = await navigator.mediaDevices.getUserMedia({ audio: constraints });
const audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 48000 });
if (audioContext.state === 'suspended') {
await audioContext.resume();
}
const sourceNode = audioContext.createMediaStreamSource(rawStream);
const destinationNode = audioContext.createMediaStreamDestination();
const gateNode = audioContext.createGain();
gateNode.gain.value = Kronick.state.voiceActivationEnabled === false ? 1 : 0;
gateNode.connect(destinationNode);
Kronick.state.rnnoiseNode = null;
Kronick.state.rnnoiseWetGain = null;
Kronick.state.rnnoiseDryGain = null;
Kronick.state.voiceGateNode = gateNode;
if (useRnnoise) {
try {
await audioContext.audioWorklet.addModule('/js/rnnoise-worklet.js');
const rnnoiseNode = new AudioWorkletNode(audioContext, 'rnnoise-worklet');
const wasmResponse = await fetch('/rnnoise-wasm/rnnoise.wasm');
if (!wasmResponse.ok) {
throw new Error(`RNNoise WASM returned HTTP ${wasmResponse.status}`);
}
const wasmBytes = await wasmResponse.arrayBuffer();
rnnoiseNode.port.postMessage({ type: 'INIT_WASM', wasmBytes });
const wetGain = audioContext.createGain();
const dryGain = audioContext.createGain();
const mix = Math.max(0, Math.min(1, (Kronick.state.rnnoiseStrength ?? 100) / 100));
wetGain.gain.value = mix;
dryGain.gain.value = 1 - mix;
sourceNode.connect(rnnoiseNode);
rnnoiseNode.connect(wetGain);
sourceNode.connect(dryGain);
wetGain.connect(gateNode);
dryGain.connect(gateNode);
Kronick.state.rnnoiseNode = rnnoiseNode;
Kronick.state.rnnoiseWetGain = wetGain;
Kronick.state.rnnoiseDryGain = dryGain;
} catch (workletError) {
console.warn('RNNoise unavailable; falling back to the microphone stream:', workletError);
sourceNode.connect(gateNode);
}
} else {
sourceNode.connect(gateNode);
}
// Local VAD drives the actual outgoing gate and the sidebar activity meter.
const analyser = audioContext.createAnalyser();
analyser.fftSize = 512;
sourceNode.connect(analyser);
const audioData = new Float32Array(analyser.fftSize);
let lastSpokenTime = 0;
let lastMeterUpdate = 0;
const checkVadLevel = () => {
if (!Kronick.state.processedAudioContext || audioContext.state === 'closed') return;
analyser.getFloatTimeDomainData(audioData);
let sum = 0;
for (let i = 0; i < audioData.length; i++) {
sum += audioData[i] * audioData[i];
}
const rms = Math.sqrt(sum / audioData.length);
const db = 20 * Math.log10(rms || 1e-8);
const now = Date.now();
const threshold = Kronick.state.vadThreshold ?? -66;
const holdMs = Kronick.state.vadHoldMs ?? 200;
const voiceActivationEnabled = Kronick.state.voiceActivationEnabled !== false;
const isSpeaking = db > threshold;
if (isSpeaking) lastSpokenTime = now;
const activeVoice = !voiceActivationEnabled
|| isSpeaking
|| (now - lastSpokenTime < holdMs);
Kronick.state.isLocalVoiceActive = activeVoice;
Kronick.state.currentMicDb = db;
const targetGain = activeVoice ? 1 : 0;
gateNode.gain.setTargetAtTime(targetGain, audioContext.currentTime, activeVoice ? 0.008 : 0.025);
if (now - lastMeterUpdate >= 80 && typeof Kronick.updateVoiceMeter === 'function') {
Kronick.updateVoiceMeter(db);
lastMeterUpdate = now;
}
requestAnimationFrame(checkVadLevel);
};
Kronick.state.processedAudioContext = audioContext;
Kronick.state.rawMicStream = rawStream;
checkVadLevel();
const processedTrack = destinationNode.stream.getAudioTracks()[0];
return new LivekitClient.LocalAudioTrack(processedTrack);
};
/*
* Connect to the selected LiveKit room.
*/
Kronick.connect = async function connect() {
const roomName = document.getElementById('roomName')?.value.trim();
const userName = document.getElementById('userName')?.value.trim();
const avatarUrl = document.getElementById('avatarUrl')?.value.trim() || '';
if (window.parent !== window) {
let selected = new URLSearchParams(location.search).get('room');
try { selected = new URLSearchParams(window.parent.location.search).get('room') || selected; } catch (_) {}
if (selected && (roomName !== selected || !Kronick.account?.rooms?.some(r => r.room_name === selected))) {
alert('Wait for your assigned room to load or switch rooms from the main menu.');
return;
}
}
if (!roomName || !userName) {
alert('Choose an assigned room.');
return;
}
if (Kronick.state.room) {
console.warn('A LiveKit room is already active.');
return;
}
Kronick.state.currentRoomName = roomName;
Kronick.saveJoinInfo(roomName, userName, avatarUrl);
const { Room, RoomEvent } = LivekitClient;
Kronick.setStatus('Connecting...', 'connecting');
Kronick.setConnectionControls('connecting');
const room = new Room();
Kronick.state.room = room;
// Ensure state maps exist
Kronick.state.participantPanners = Kronick.state.participantPanners || new Map();
Kronick.state.participantAudioSources = Kronick.state.participantAudioSources || new Map();
Kronick.state.participantGainNodes = Kronick.state.participantGainNodes || new Map();
if (typeof Kronick.initScreenShare === 'function') {
Kronick.initScreenShare(room);
}
room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => {
if (track.kind !== 'audio') return;
if (
typeof Kronick.isScreenShareAudioPublication === 'function' &&
Kronick.isScreenShareAudioPublication(publication)
) {
return;
}
const audio = track.attach();
audio.id = `audio-${participant.sid}`;
audio.autoplay = true;
audio.playsInline = true;
// Do NOT mute this element. createMediaElementSource() reroutes its audio
// into the Web Audio graph; muting it can result in silence reaching the
// spatial panner on some browsers.
audio.muted = false;
audio.style.display = 'none';
audio.volume = 1;
document.body.appendChild(audio);
Kronick.state.participantAudioElements.set(participant.sid, audio);
const savedVolume = Kronick.getSavedVolume(participant.identity || participant.sid);
Kronick.updateVolumeSlider(participant.sid, savedVolume);
// Web Audio HRTF Spatial Panner Setup
try {
const ctx = Kronick.getSpatialAudioContext();
const sourceNode = ctx.createMediaElementSource(audio);
const gainNode = ctx.createGain();
const pannerNode = ctx.createPanner();
gainNode.gain.value = savedVolume;
pannerNode.panningModel = 'HRTF';
pannerNode.distanceModel = 'inverse';
pannerNode.refDistance = 1;
pannerNode.maxDistance = 1000;
pannerNode.rolloffFactor = Kronick.state.spatialAudioEnabled === false
? 0
: Math.max(0, (Kronick.state.spatialFalloff ?? 100) / 100);
sourceNode.connect(gainNode);
gainNode.connect(pannerNode);
pannerNode.connect(ctx.destination);
Kronick.state.participantAudioSources.set(participant.sid, sourceNode);
Kronick.state.participantGainNodes.set(participant.sid, gainNode);
Kronick.state.participantPanners.set(participant.sid, pannerNode);
if (typeof Kronick.updateSpatialAudioPosition === 'function') {
Kronick.updateSpatialAudioPosition(participant.sid);
}
} catch (spatialErr) {
console.warn('Failed to attach spatial audio panner for participant:', participant.identity, spatialErr);
}
});
room.on(RoomEvent.TrackUnsubscribed, (track, publication, participant) => {
if (
typeof Kronick.isScreenShareVideoPublication === 'function' &&
Kronick.isScreenShareVideoPublication(publication)
) {
return;
}
if (
typeof Kronick.isScreenShareAudioPublication === 'function' &&
Kronick.isScreenShareAudioPublication(publication)
) {
return;
}
track.detach().forEach(element => element.remove());
if (participant?.sid) {
Kronick.state.participantAudioElements.delete(participant.sid);
const panner = Kronick.state.participantPanners.get(participant.sid);
if (panner) {
panner.disconnect();
Kronick.state.participantPanners.delete(participant.sid);
}
const gain = Kronick.state.participantGainNodes?.get(participant.sid);
if (gain) {
gain.disconnect();
Kronick.state.participantGainNodes.delete(participant.sid);
}
const source = Kronick.state.participantAudioSources.get(participant.sid);
if (source) {
source.disconnect();
Kronick.state.participantAudioSources.delete(participant.sid);
}
}
});
room.on(RoomEvent.ParticipantConnected, participant => {
Kronick.renderParticipant(participant);
});
room.on(RoomEvent.ParticipantDisconnected, participant => {
Kronick.removeParticipant(participant);
});
room.on(RoomEvent.ActiveSpeakersChanged, speakers => {
Kronick.updateActiveSpeakers(speakers);
});
room.on(RoomEvent.DataReceived, (payload, participant, kind, topic) => {
let decodedData = '';
try {
decodedData = new TextDecoder().decode(payload);
} catch (error) {
console.warn('Could not decode LiveKit data:', error);
return;
}
// Native Kronic Media room playback uses a separate, versioned LiveKit topic.
if (topic === Kronick.roomPlaybackTopic) {
try {
Kronick.handleNativeRoomPlayback(JSON.parse(decodedData), participant);
} catch (error) {
console.warn('Bad native room playback message:', error);
}
return;
}
if (topic === Kronick.config.DATA_TOPIC_MEDIA) {
try {
const message = JSON.parse(decodedData);
Kronick.handleRoomMedia(message);
} catch (error) {
console.warn('Bad media message:', {
participant: participant?.identity,
data: decodedData,
error
});
}
return;
}
if (topic === Kronick.config.DATA_TOPIC_CHAT) {
try {
const message = JSON.parse(decodedData);
Kronick.receiveChatMessage(message);
} catch (error) {
console.warn('Bad chat message:', {
participant: participant?.identity,
data: decodedData,
error
});
}
}
});
room.on(RoomEvent.ParticipantMetadataChanged, (metadata, participant) => {
Kronick.updateParticipantAvatar(participant);
});
room.on(RoomEvent.Disconnected, () => {
Kronick.cleanupRoom();
Kronick.setStatus('Disconnected');
});
try {
const tokenResponse = await fetch('/api/account-token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({
room: roomName,
avatar: avatarUrl
})
});
let tokenData = {};
try {
tokenData = await tokenResponse.json();
} catch {
throw new Error('Token server returned an invalid response.');
}
if (!tokenResponse.ok) {
const detail =
typeof tokenData.detail === 'string'
? tokenData.detail
: tokenData.detail?.message || 'Room authentication failed.';
throw new Error(detail);
}
if (!tokenData?.token) {
throw new Error('Token server returned no token.');
}
await room.connect(Kronick.config.LIVEKIT_URL, tokenData.token);
if (typeof Kronick.updateDeleteRoomButton === 'function') {
Kronick.updateDeleteRoomButton(roomName, Boolean(tokenData.isOwner));
}
room.remoteParticipants.forEach(participant => {
Kronick.renderParticipant(participant);
});
/* Setup local processed audio with RNNoise filtering */
let microphoneEnabled = false;
try {
const localAudioTrack = await Kronick.createProcessedMicrophoneTrack();
const publishOptions = LivekitClient.Track?.Source?.Microphone
? { source: LivekitClient.Track.Source.Microphone }
: undefined;
await room.localParticipant.publishTrack(localAudioTrack, publishOptions);
Kronick.state.localMicTrack = localAudioTrack;
microphoneEnabled = true;
} catch (microphoneError) {
console.warn('Connected, but noise-suppressed microphone could not be enabled:', microphoneError);
}
Kronick.renderParticipant(room.localParticipant);
Kronick.setConnectionControls('connected');
if (typeof Kronick.updateScreenShareControls === 'function') {
Kronick.updateScreenShareControls();
}
const muteButton = document.getElementById('muteBtn');
if (muteButton) {
muteButton.innerText = microphoneEnabled ? 'Mute' : 'Enable Mic';
muteButton.classList.toggle('muted', !microphoneEnabled);
}
Kronick.setStatus(
microphoneEnabled
? `Connected to room: ${roomName}`
: `Connected to room: ${roomName} — microphone unavailable`,
microphoneEnabled ? 'connected' : 'connecting'
);
await Kronick.loadRoomChatHistory(roomName);
} catch (error) {
console.error('LiveKit connection failed:', error);
try {
room.disconnect();
} catch {
// Ignore disconnect failure.
}
if (Kronick.state.room === room) {
Kronick.cleanupRoom();
}
Kronick.setStatus(
error?.message ? `Connection failed: ${error.message}` : 'Connection failed. Check console.',
'error'
);
alert(error?.message || 'Unable to join the room.');
}
};
/*
* Update connection-related buttons.
*/
Kronick.setConnectionControls = function setConnectionControls(state) {
const joinButton = document.getElementById('joinBtn');
const muteButton = document.getElementById('muteBtn');
const leaveButton = document.getElementById('leaveBtn');
const screenShareButton = document.getElementById('screenShareBtn');
if (!joinButton || !muteButton || !leaveButton) return;
if (state === 'connecting') {
joinButton.disabled = true;
joinButton.innerText = 'Connecting...';
muteButton.disabled = true;
leaveButton.disabled = true;
if (screenShareButton) screenShareButton.disabled = true;
return;
}
if (state === 'connected') {
joinButton.disabled = true;
joinButton.innerText = 'Connected';
muteButton.disabled = false;
muteButton.innerText = 'Mute';
muteButton.classList.remove('muted');
leaveButton.disabled = false;
if (screenShareButton) screenShareButton.disabled = false;
return;
}
joinButton.disabled = false;
joinButton.innerText = 'Join Voice';
muteButton.disabled = true;
muteButton.innerText = 'Mute';
muteButton.classList.remove('muted');
leaveButton.disabled = true;
if (screenShareButton) {
screenShareButton.disabled = true;
screenShareButton.classList.remove('active');
const label = screenShareButton.querySelector('.button-label');
if (label) {
label.textContent = 'Share Screen';
} else {
screenShareButton.textContent = 'Share Screen';
}
}
};
/*
* Toggle the local microphone.
*/
Kronick.toggleMute = async function toggleMute() {
const room = Kronick.state.room;
if (!room?.localParticipant) return;
const muteButton = document.getElementById('muteBtn');
const currentlyEnabled = room.localParticipant.isMicrophoneEnabled;
if (muteButton) muteButton.disabled = true;
try {
await room.localParticipant.setMicrophoneEnabled(!currentlyEnabled);
const nowEnabled = room.localParticipant.isMicrophoneEnabled;
if (muteButton) {
muteButton.innerText = nowEnabled ? 'Mute' : 'Enable Mic';
muteButton.classList.toggle('muted', !nowEnabled);
}
Kronick.setStatus(
nowEnabled
? `Connected to room: ${Kronick.state.currentRoomName}`
: `Connected to room: ${Kronick.state.currentRoomName} — microphone muted`,
'connected'
);
} catch (error) {
console.error('Could not change microphone state:', error);
Kronick.setStatus(
`Connected to room: ${Kronick.state.currentRoomName} — microphone failed`,
'error'
);
} finally {
if (muteButton && Kronick.state.room) {
muteButton.disabled = false;
}
}
};
/*
* Disconnect from the room.
*/
Kronick.disconnect = function disconnect() {
const room = Kronick.state.room;
if (room) {
try {
room.disconnect();
} catch (error) {
console.error('Room disconnect failed:', error);
Kronick.cleanupRoom();
Kronick.setStatus('Disconnected');
}
return;
}
Kronick.cleanupRoom();
Kronick.setStatus('Disconnected');
};
/*
* Clean up every part of the active room.
*/
Kronick.cleanupRoom = function cleanupRoom() {
const activeRoom = Kronick.state.room;
if (activeRoom?.localParticipant?.isScreenShareEnabled) {
activeRoom.localParticipant
.setScreenShareEnabled(false)
.catch(error => console.debug('Screen share was already stopped:', error));
}
if (typeof Kronick.resetScreenShare === 'function') {
Kronick.resetScreenShare();
}
if (typeof Kronick.cleanupScreenShareListeners === 'function') {
Kronick.cleanupScreenShareListeners();
}
// Clean up local audio context and media streams
if (typeof Kronick.cleanupLocalMicProcessing === 'function') {
Kronick.cleanupLocalMicProcessing();
}
Kronick.state.localMicTrack = null;
// Clean up Web Audio Panners and Sources
if (Kronick.state.participantPanners) {
Kronick.state.participantPanners.forEach(panner => panner.disconnect());
Kronick.state.participantPanners.clear();
}
if (Kronick.state.participantGainNodes) {
Kronick.state.participantGainNodes.forEach(gain => gain.disconnect());
Kronick.state.participantGainNodes.clear();
}
if (Kronick.state.participantAudioSources) {
Kronick.state.participantAudioSources.forEach(source => source.disconnect());
Kronick.state.participantAudioSources.clear();
}
Kronick.state.participantStatsIntervals.forEach(interval => clearInterval(interval));
Kronick.state.participantStatsIntervals.clear();
Kronick.state.participantLevels.clear();
Kronick.state.participantRtts.clear();
Kronick.state.participantAudioElements.forEach(audio => {
try {
audio.pause();
} catch {
// Ignore audio cleanup failure.
}
audio.remove();
});
Kronick.state.participantAudioElements.clear();
document.querySelectorAll('audio[id^="audio-"]').forEach(audio => {
try {
audio.pause();
} catch {
// Ignore audio cleanup failure.
}
audio.remove();
});
const participantContainer = Kronick.getParticipantContainer();
if (participantContainer) {
participantContainer.innerHTML = '';
}
Kronick.state.nextTileX = 0;
Kronick.state.nextTileY = 0;
Kronick.showEmptyRoomMessage();
Kronick.setConnectionControls('disconnected');
if (typeof Kronick.updateDeleteRoomButton === 'function') {
Kronick.updateDeleteRoomButton('', false);
}
Kronick.state.room = null;
Kronick.state.currentRoomName = '';
};
+815
View File
@@ -0,0 +1,815 @@
window.Kronick = window.Kronick || {};
Kronick.getParticipantContainer =
function getParticipantContainer() {
return document.getElementById('participant-container');
};
Kronick.removeEmptyRoomMessage =
function removeEmptyRoomMessage() {
document.querySelector(
'#participant-container .empty-room-message'
)?.remove();
};
Kronick.showEmptyRoomMessage =
function showEmptyRoomMessage() {
const container = Kronick.getParticipantContainer();
if (!container) return;
if (
container.querySelector('.octagon')
|| container.querySelector('.empty-room-message')
) {
return;
}
const emptyMessage = document.createElement('div');
emptyMessage.className = 'empty-room-message';
emptyMessage.innerHTML = `
<div class="empty-room-icon">🎙️</div>
<h3>No participants connected</h3>
<p>Enter a room and display name, then join the voice channel.</p>
`;
container.appendChild(emptyMessage);
};
Kronick.getNextParticipantPosition =
function getNextParticipantPosition() {
const container = Kronick.getParticipantContainer();
const tileWidth = 340;
const tileHeight = 340;
const gap = 24;
const usableWidth = container?.clientWidth || window.innerWidth;
const position = {
x: Kronick.state.nextTileX,
y: Kronick.state.nextTileY
};
Kronick.state.nextTileX += tileWidth + gap;
if (
Kronick.state.nextTileX + tileWidth
> Math.max(tileWidth, usableWidth)
) {
Kronick.state.nextTileX = 0;
Kronick.state.nextTileY += tileHeight + gap;
}
return position;
};
Kronick.getAvatarFromMetadata =
function getAvatarFromMetadata(metadata) {
if (!metadata) return '';
try {
const parsed = JSON.parse(metadata);
return parsed.avatar || '';
} catch {
return '';
}
};
Kronick.updateSpatialAudioPosition =
function updateSpatialAudioPosition(sid) {
if (!Kronick.state?.participantPanners) return;
const panner = Kronick.state.participantPanners.get(sid);
if (!panner) return;
const container = Kronick.getParticipantContainer();
const tile = document.getElementById(`p-${sid}`);
if (!container || !tile) return;
const containerRect = container.getBoundingClientRect();
const tileRect = tile.getBoundingClientRect();
const containerCenterX = containerRect.left + containerRect.width / 2;
const containerCenterY = containerRect.top + containerRect.height / 2;
const tileCenterX = tileRect.left + tileRect.width / 2;
const tileCenterY = tileRect.top + tileRect.height / 2;
const normalizedX =
(tileCenterX - containerCenterX)
/ (containerRect.width / 2 || 1);
const normalizedY =
(tileCenterY - containerCenterY)
/ (containerRect.height / 2 || 1);
const spatialEnabled = Kronick.state.spatialAudioEnabled !== false;
const width = spatialEnabled
? (Kronick.state.spatialWidth ?? 100) / 100
: 0;
const depth = spatialEnabled
? (Kronick.state.spatialDepth ?? 100) / 100
: 0;
const x = normalizedX * 5 * width;
const y = -normalizedY * 2 * depth;
const z = spatialEnabled ? -2 * depth : 0;
panner.rolloffFactor = spatialEnabled
? Math.max(0, (Kronick.state.spatialFalloff ?? 100) / 100)
: 0;
const ctx = Kronick.state.audioCtx;
const currentTime = ctx ? ctx.currentTime : 0;
if (panner.positionX) {
panner.positionX.setValueAtTime(x, currentTime);
panner.positionY.setValueAtTime(y, currentTime);
panner.positionZ.setValueAtTime(z, currentTime);
} else if (panner.setPosition) {
panner.setPosition(x, y, z);
}
};
Kronick.renderParticipant =
function renderParticipant(participant) {
if (document.getElementById(`p-${participant.sid}`)) return;
Kronick.removeEmptyRoomMessage();
const div = document.createElement('div');
div.className = 'octagon participant-card';
div.id = `p-${participant.sid}`;
const identity = participant.identity || 'Unknown';
const participantKey = identity || participant.sid;
const isLocal = participant === Kronick.state.room?.localParticipant;
const avatar = Kronick.getAvatarFromMetadata(participant.metadata);
const savedPosition = Kronick.getSavedPosition(participantKey);
const position = savedPosition || Kronick.getNextParticipantPosition();
div.style.left = `${position.x}px`;
div.style.top = `${position.y}px`;
const avatarHtml = avatar
? `
<img
class="avatar"
src="${Kronick.escapeAttribute(avatar)}"
alt="${Kronick.escapeAttribute(identity)}"
onerror="this.style.display='none';"
>
`
: `
<div class="avatar-fallback">
${Kronick.escapeHtml(identity)}
</div>
`;
const volumeHtml = isLocal
? ''
: `
<div class="volume-overlay">
<span>Volume</span>
<input
id="volume-${participant.sid}"
type="range"
min="0"
max="100"
value="100"
aria-label="Volume for ${Kronick.escapeAttribute(identity)}"
>
</div>
`;
div.innerHTML = `
${avatarHtml}
<div class="name-overlay">
${Kronick.escapeHtml(identity)}
</div>
<div
class="stats-overlay"
id="stats-${participant.sid}"
>
RTT: -- ms | Level: 0%
</div>
${volumeHtml}
<div
class="meter-fill"
id="meter-${participant.sid}"
></div>
`;
Kronick.getParticipantContainer()?.appendChild(div);
if (!isLocal) {
const volumeSlider = document.getElementById(`volume-${participant.sid}`);
if (volumeSlider) {
const stopPropagation = event => event.stopPropagation();
volumeSlider.addEventListener('pointerdown', stopPropagation);
volumeSlider.addEventListener('mousedown', stopPropagation);
volumeSlider.addEventListener('click', stopPropagation);
volumeSlider.addEventListener('input', event => {
Kronick.setParticipantVolume(
participant.sid,
participantKey,
event.currentTarget.value
);
});
}
}
Kronick.makeDraggable(div, participantKey, participant.sid);
Kronick.makeParticipantResizable(div, participantKey, participant.sid);
Kronick.state.participantLevels.set(participant.sid, 0);
Kronick.state.participantRtts.set(participant.sid, '--');
if (!isLocal) {
const savedVolume = Kronick.getSavedVolume(participantKey);
Kronick.updateVolumeSlider(
participant.sid,
savedVolume
);
Kronick.setParticipantVolume(
participant.sid,
participantKey,
savedVolume * 100
);
}
Kronick.updateSpatialAudioPosition(participant.sid);
Kronick.updateParticipantStats(
participant
);
const interval = setInterval(async () => {
await Kronick.updateParticipantStats(participant);
}, 2000);
Kronick.state.participantStatsIntervals.set(participant.sid, interval);
};
Kronick.makeDraggable =
function makeDraggable(element, positionKey, sid) {
let isDragging = false;
let startMouseX = 0;
let startMouseY = 0;
let startLeft = 0;
let startTop = 0;
element.addEventListener('mousedown', event => {
if (event.button !== 0 || event.target.closest('input')) return;
isDragging = true;
startMouseX = event.clientX;
startMouseY = event.clientY;
startLeft = parseInt(element.style.left || '0', 10);
startTop = parseInt(element.style.top || '0', 10);
element.style.zIndex = '999';
document.body.classList.add('participant-dragging');
event.preventDefault();
});
document.addEventListener('mousemove', event => {
if (!isDragging) return;
const container = Kronick.getParticipantContainer();
const dx = event.clientX - startMouseX;
const dy = event.clientY - startMouseY;
// No boundary: the tile may go anywhere in the window. Only a small
// strip is kept on screen so it can always be grabbed back.
const rect = container
? container.getBoundingClientRect()
: {left: 0, top: 0};
const keep = 40;
const minLeft = keep - element.offsetWidth - rect.left;
const maxLeft = window.innerWidth - keep - rect.left;
const minTop = keep - element.offsetHeight - rect.top;
const maxTop = window.innerHeight - keep - rect.top;
const newLeft = Math.max(minLeft, Math.min(maxLeft, startLeft + dx));
const newTop = Math.max(minTop, Math.min(maxTop, startTop + dy));
element.style.left = `${newLeft}px`;
element.style.top = `${newTop}px`;
if (sid) Kronick.updateSpatialAudioPosition(sid);
});
document.addEventListener('mouseup', () => {
if (!isDragging) return;
isDragging = false;
element.style.zIndex = '';
document.body.classList.remove('participant-dragging');
Kronick.savePosition(positionKey, {
x: parseInt(element.style.left || '0', 10),
y: parseInt(element.style.top || '0', 10)
});
if (sid) Kronick.updateSpatialAudioPosition(sid);
});
};
Kronick.updateParticipantStats =
async function updateParticipantStats(participant) {
if (!participant) {
return;
}
/*
* LiveKit does not always expose the same stats path for
* local and remote participants. Try the public track API
* first, then the sender, then the underlying publisher PC
* as a guarded final fallback for our own participant.
*/
const publications = Array.from(
participant.getTrackPublications?.().values?.()
|| []
);
const publication =
publications.find(
pub =>
pub.track
&& (
pub.kind === 'audio'
|| pub.track.kind === 'audio'
)
)
|| publications.find(
pub => pub.track
);
const track =
publication?.track;
let stats =
null;
try {
if (
track
&& typeof track.getRTCStatsReport
=== 'function'
) {
stats =
await track.getRTCStatsReport();
}
if (
!stats
&& track?.sender
&& typeof track.sender.getStats
=== 'function'
) {
stats =
await track.sender.getStats();
}
/*
* Local participant fallback. LiveKit's internal PC
* shape can vary by version, so every access is guarded.
*/
const isLocal =
participant
=== Kronick.state.room
?.localParticipant;
if (
!stats
&& isLocal
) {
const publisher =
Kronick.state.room
?.engine
?.pcManager
?.publisher;
const pc =
publisher?._pc
|| publisher?.pc
|| publisher;
if (
pc
&& typeof pc.getStats
=== 'function'
) {
stats =
await pc.getStats();
}
}
let rtt =
null;
stats?.forEach?.(
report => {
if (
report.type
=== 'candidate-pair'
&& (
report.state
=== 'succeeded'
|| report.nominated
)
&& typeof report
.currentRoundTripTime
=== 'number'
) {
rtt =
report
.currentRoundTripTime;
}
if (
report.type
=== 'remote-inbound-rtp'
&& typeof report
.roundTripTime
=== 'number'
) {
rtt =
report.roundTripTime;
}
}
);
if (
rtt !== null
) {
Kronick.state
.participantRtts
.set(
participant.sid,
Math.round(
rtt * 1000
)
);
}
/*
* Keep our own level live even when the active-speaker
* event does not include the local participant.
*/
if (
typeof participant.audioLevel
=== 'number'
) {
Kronick.state
.participantLevels
.set(
participant.sid,
Math.round(
participant.audioLevel
* 100
)
);
}
} catch (err) {
console.debug(
'Participant RTT unavailable:',
participant.identity
|| participant.sid,
err
);
}
Kronick.updateStatsOverlay(
participant.sid
);
};
Kronick.updateActiveSpeakers =
function updateActiveSpeakers(speakers) {
document.querySelectorAll('.meter-fill').forEach(meter => {
meter.style.width = '0%';
});
document.querySelectorAll('.octagon').forEach(card => {
card.classList.remove('speaking');
});
Kronick.state.participantLevels.forEach((_, sid) => {
Kronick.state.participantLevels.set(sid, 0);
});
speakers.forEach(speaker => {
const level = Math.round((speaker.audioLevel || 0) * 100);
Kronick.state.participantLevels.set(speaker.sid, level);
const meter = document.getElementById(`meter-${speaker.sid}`);
const card = document.getElementById(`p-${speaker.sid}`);
if (meter) meter.style.width = `${level}%`;
if (card && level > 5) card.classList.add('speaking');
Kronick.updateStatsOverlay(speaker.sid);
});
};
Kronick.updateStatsOverlay =
function updateStatsOverlay(sid) {
const stats = document.getElementById(`stats-${sid}`);
if (!stats) return;
const rtt = Kronick.state.participantRtts.get(sid) || '--';
const level = Kronick.state.participantLevels.get(sid) || 0;
stats.textContent = `RTT: ${rtt} ms | Level: ${level}%`;
};
Kronick.setParticipantVolume =
function setParticipantVolume(sid, participantKey, value) {
const numericValue = Number(value);
if (!Number.isFinite(numericValue)) return;
const volume = Math.max(0, Math.min(1, numericValue / 100));
localStorage.setItem(
`volume-${participantKey}`,
String(volume)
);
const room = Kronick.state.room;
const participant = room?.remoteParticipants?.get(sid);
// 1) Ask LiveKit itself to apply the per-participant volume.
if (participant) {
try {
if (typeof participant.setVolume === 'function') {
participant.setVolume(volume);
}
} catch (error) {
console.warn(
'LiveKit participant volume failed:',
participantKey,
error
);
}
try {
const microphoneSource =
LivekitClient?.Track?.Source?.Microphone;
let micPublication = null;
if (
microphoneSource
&& typeof participant.getTrackPublication === 'function'
) {
micPublication = participant.getTrackPublication(
microphoneSource
);
}
if (!micPublication) {
const publications = Array.from(
participant.getTrackPublications().values()
);
micPublication = publications.find(publication =>
publication?.source === microphoneSource
|| publication?.track?.kind === 'audio'
);
}
const remoteTrack = micPublication?.track;
if (
remoteTrack
&& typeof remoteTrack.setVolume === 'function'
) {
remoteTrack.setVolume(volume);
}
} catch (error) {
console.warn(
'LiveKit track volume failed:',
participantKey,
error
);
}
}
// 2) Apply the same value to our WebAudio gain node.
const gainNode = Kronick.state.participantGainNodes?.get(sid);
if (gainNode) {
try {
const ctx = gainNode.context;
gainNode.gain.cancelScheduledValues(ctx.currentTime);
gainNode.gain.setValueAtTime(volume, ctx.currentTime);
} catch (error) {
console.warn(
'GainNode volume failed:',
participantKey,
error
);
}
}
// 3) Keep the attached HTML audio element in sync as a fallback.
const audio = Kronick.state.participantAudioElements?.get(sid);
if (audio) {
try {
audio.volume = volume;
audio.muted = volume === 0;
} catch (error) {
console.warn(
'Audio element volume failed:',
participantKey,
error
);
}
}
console.log('Participant volume applied:', {
sid,
participantKey,
volume,
livekitParticipant: Boolean(participant),
gain: gainNode ? gainNode.gain.value : null,
audioVolume: audio ? audio.volume : null,
audioMuted: audio ? audio.muted : null
});
};
Kronick.updateVolumeSlider =
function updateVolumeSlider(sid, volume) {
const slider = document.getElementById(`volume-${sid}`);
if (slider) {
slider.value = Math.round(volume * 100);
}
};
Kronick.updateParticipantAvatar =
function updateParticipantAvatar(participant) {
const card = document.getElementById(`p-${participant.sid}`);
if (!card) return;
const avatar = Kronick.getAvatarFromMetadata(participant.metadata);
const identity = participant.identity || 'Unknown';
card.querySelector('.avatar')?.remove();
card.querySelector('.avatar-fallback')?.remove();
const nameOverlay = card.querySelector('.name-overlay');
if (avatar) {
const img = document.createElement('img');
img.className = 'avatar';
img.src = avatar;
img.alt = identity;
img.onerror = () => {
img.style.display = 'none';
};
card.insertBefore(img, nameOverlay);
} else {
const fallback = document.createElement('div');
fallback.className = 'avatar-fallback';
fallback.textContent = identity;
card.insertBefore(fallback, nameOverlay);
}
};
Kronick.removeParticipant =
function removeParticipant(participant) {
document.getElementById(`p-${participant.sid}`)?.remove();
const interval = Kronick.state.participantStatsIntervals.get(participant.sid);
if (interval) {
clearInterval(interval);
Kronick.state.participantStatsIntervals.delete(participant.sid);
}
Kronick.state.participantLevels.delete(participant.sid);
Kronick.state.participantRtts.delete(participant.sid);
const audio = Kronick.state.participantAudioElements.get(participant.sid);
if (audio) {
try { audio.pause(); } catch {}
audio.remove();
}
Kronick.state.participantAudioElements.delete(participant.sid);
const panner = Kronick.state.participantPanners?.get(participant.sid);
if (panner) {
try { panner.disconnect(); } catch {}
Kronick.state.participantPanners.delete(participant.sid);
}
const gainNode = Kronick.state.participantGainNodes?.get(participant.sid);
if (gainNode) {
try { gainNode.disconnect(); } catch {}
Kronick.state.participantGainNodes.delete(participant.sid);
}
const sourceNode = Kronick.state.participantAudioSources?.get(participant.sid);
if (sourceNode) {
try { sourceNode.disconnect(); } catch {}
Kronick.state.participantAudioSources.delete(participant.sid);
}
Kronick.showEmptyRoomMessage();
};
window.addEventListener('resize', () => {
if (Kronick.state?.participantPanners) {
Kronick.state.participantPanners.forEach((_, sid) => {
Kronick.updateSpatialAudioPosition(sid);
});
}
});
Kronick.makeParticipantResizable =
function makeParticipantResizable(element, participantKey, sid) {
if (!element) return;
const storageKey = `participantSize-${participantKey}`;
try {
const saved = JSON.parse(localStorage.getItem(storageKey) || 'null');
if (saved?.width) element.style.width = `${saved.width}px`;
if (saved?.height) element.style.height = `${saved.height}px`;
} catch {}
const handle = document.createElement('div');
handle.className = 'participant-resize-handle';
handle.title = 'Resize avatar';
handle.setAttribute('aria-label', 'Resize participant avatar');
element.appendChild(handle);
let active = false;
let sx = 0;
let sy = 0;
let sw = 0;
let sh = 0;
handle.addEventListener('pointerdown', event => {
active = true;
sx = event.clientX;
sy = event.clientY;
const rect = element.getBoundingClientRect();
sw = rect.width;
sh = rect.height;
handle.setPointerCapture?.(event.pointerId);
event.stopPropagation();
event.preventDefault();
});
handle.addEventListener('pointermove', event => {
if (!active) return;
const maxW = Math.max(
180,
(Kronick.getParticipantContainer()?.clientWidth || window.innerWidth) - 20
);
const width = Math.min(
maxW,
Math.max(180, sw + event.clientX - sx)
);
const height = Math.min(
700,
Math.max(140, sh + event.clientY - sy)
);
element.style.width = `${width}px`;
element.style.height = `${height}px`;
if (sid) Kronick.updateSpatialAudioPosition(sid);
});
const stop = () => {
if (!active) return;
active = false;
localStorage.setItem(storageKey, JSON.stringify({
width: Math.round(element.getBoundingClientRect().width),
height: Math.round(element.getBoundingClientRect().height)
}));
if (sid) Kronick.updateSpatialAudioPosition(sid);
};
handle.addEventListener('pointerup', stop);
handle.addEventListener('pointercancel', stop);
};
+1
View File
@@ -0,0 +1 @@
(async()=>{try{const r=await fetch('/api/public/branding',{cache:'no-store'});if(!r.ok)return;const b=await r.json();const h=document.querySelector('.brand h1'),p=document.querySelector('.brand p');if(h)h.textContent=b.login_title||'Welcome';if(p)p.textContent=b.login_subtitle||'';if(b.name&&h){const s=document.createElement('div');s.textContent=b.name;h.before(s);}if(b.powered_by){const s=document.createElement('p');s.textContent='Powered by Kronic';s.style.textAlign='center';document.querySelector('.auth-card')?.append(s);}}catch(e){}})();