import { addRoomHost, announceRoom, createRoom, discoverLiveRooms, endRoom, getRoom, joinRoom, leaveRoom, listFollowDids, listRooms, removeRoomHost, setRoomOpenMic, touchRoom, ROOM_LIVE_TTL_MS, HttpMediaTokenProvider, LiveKitMediaController, OAuthClient, type BeachwaveRoom, type ChatMessage, type MediaParticipant, type MediaRoomState, type MediaSession, type ParticipantRole, type SpeakRequest } from '../sdk/index.js'; import { resolveMediaTokenEndpoint, resolveOAuthConfig, resolveRemoveEndpoint, resolveSpeakGrantEndpoint } from './config.js'; import { completeOAuthCallback, restoreAccount, signInWithAppPassword, startOAuthSignIn, startOfflineDemo, type Account } from './account.js'; const app = document.querySelector('#root'); if (!app) throw new Error('Missing #root element'); const oauth = new OAuthClient(resolveOAuthConfig()); // Lexicon method the server verifies service-auth tokens against. When the // deployer enables host-authority checks (BEACHWAVE_VERIFY_AUTH=1), the media // and moderation endpoints require a token minted for this method. const MODERATION_LXM = 'community.beachwave.moderate'; /** Mint a service-auth JWT for the current account, or null when unavailable. */ function getAuthToken(): Promise { return account ? account.serviceAuth(MODERATION_LXM) : Promise.resolve(null); } const mediaTokenEndpoint = resolveMediaTokenEndpoint(); const mediaController: LiveKitMediaController | undefined = mediaTokenEndpoint ? new LiveKitMediaController(new HttpMediaTokenProvider(mediaTokenEndpoint, getAuthToken), { grantEndpoint: resolveSpeakGrantEndpoint(), removeEndpoint: resolveRemoveEndpoint(), getAuthToken }) : undefined; const PENDING_ROOM_KEY = 'beachwave.pendingRoom'; const GITHUB_REPO_URL = 'https://github.com/quarterback/beachwave'; const TANGLED_REPO_URL = 'https://tangled.org/ronbronson.com/beachwave'; let account: Account | undefined; let rooms: BeachwaveRoom[] = []; let activeRoom: BeachwaveRoom | undefined; let mediaSession: MediaSession | undefined; let mediaUnsubscribers: Array<() => void> = []; // Controller in use for the active room — local for your own rooms, or pointed // at the host's deployment for a room discovered on another instance. let activeController: LiveKitMediaController | undefined; // Per-room speaker-moderation state, reset on each join/leave. let micOn = false; let speakRequested = false; let controlMode: 'speaker' | 'listener' | undefined; const pendingSpeakRequests = new Map(); // Host heartbeat: keep the room's lastActiveAt fresh while we're hosting, so it // doesn't linger as a ghost in discovery after the tab closes. const HEARTBEAT_MS = Math.floor(ROOM_LIVE_TTL_MS / 2); let heartbeatTimer: ReturnType | undefined; void boot(); async function boot(): Promise { const params = new URLSearchParams(window.location.search); rememberSharedRoom(params.get('room')); try { if (OAuthClient.isCallback(params)) { account = await completeOAuthCallback(oauth, params); clearCallbackParams(); } else { account = await restoreAccount(oauth); } } catch (error) { renderSignIn(describeError(error)); return; } if (account) { await renderApp(); } else { renderSignIn(); } } // --------------------------------------------------------------------------- // Sign-in screen // --------------------------------------------------------------------------- function renderSignIn(message = ''): void { const invited = Boolean(pendingSharedRoom()); app!.innerHTML = `
Beachwave
Live audio on the open protocol

Open the mic.
Own the room.

`; const status = app!.querySelector('#status')!; app!.querySelector('#oauth-form')!.addEventListener('submit', async (event) => { event.preventDefault(); const identifier = app!.querySelector('#identifier')!.value.trim(); if (!identifier) return; status.textContent = 'Redirecting to your ATProto authorization server…'; try { await startOAuthSignIn(oauth, identifier); } catch (error) { status.textContent = describeError(error); } }); app!.querySelector('#app-password-form')!.addEventListener('submit', async (event) => { event.preventDefault(); const identifier = app!.querySelector('#ap-identifier')!.value.trim(); const password = app!.querySelector('#ap-password')!.value; if (!identifier || !password) { status.textContent = 'Enter a handle and app password.'; return; } status.textContent = 'Signing in…'; try { account = await signInWithAppPassword(identifier, password); await renderApp(); } catch (error) { status.textContent = describeError(error); } }); app!.querySelector('#offline')!.addEventListener('click', async () => { account = startOfflineDemo(); await renderApp(); }); if (invited) { app!.querySelector('#signin')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); app!.querySelector('#identifier')?.focus(); } } // --------------------------------------------------------------------------- // Signed-in application // --------------------------------------------------------------------------- async function renderApp(): Promise { const current = account!; const modeBadge = current.kind === 'oauth' ? '' : `${current.kind === 'offline' ? 'Offline demo' : 'Dev session'}`; app!.innerHTML = `
Beachwave
${modeBadge}
GitHub repo ↗

Welcome back.

Start a room, or pick up where you left off.

${current.kind === 'offline' ? '' : ` `}
Start a room
${current.kind === 'offline' ? '' : ` `}

Your rooms

`; app!.querySelector('#identity-label')!.textContent = current.label; app!.querySelector('#identity-pds')!.textContent = current.pds ? new URL(current.pds).host : ''; app!.querySelector('#welcome')!.textContent = `Welcome back, ${friendlyName(current.label)}.`; app!.querySelector('#sign-out')!.addEventListener('click', handleSignOut); app!.querySelector('#refresh')!.addEventListener('click', () => void refreshRooms()); app!.querySelector('#refresh-live')?.addEventListener('click', () => void refreshDiscover()); app!.querySelector('#room-form')!.addEventListener('submit', handleCreate); await refreshRooms(); await renderPendingSharedRoom(); void refreshDiscover(); } /** Populate the "Live now" lobby with live rooms from accounts the viewer follows. */ async function refreshDiscover(): Promise { const current = account; if (!current || current.kind === 'offline') return; const section = app!.querySelector('#live-now'); const list = app!.querySelector('#live-rooms'); if (!section || !list) return; list.innerHTML = '

Looking for live rooms…

'; section.hidden = false; try { const follows = await listFollowDids(current.did); if (follows.length === 0) { section.hidden = true; return; } const live = (await discoverLiveRooms(current.client, follows)).filter((room) => room.authorDid !== current.did); if (live.length === 0) { list.innerHTML = '

No one you follow is live right now.

'; return; } list.replaceChildren(...live.map((room) => renderRoomCard(room, false))); } catch { // Discovery is best-effort; hide the lobby rather than show an error. section.hidden = true; } } async function handleCreate(event: SubmitEvent): Promise { event.preventDefault(); const title = app!.querySelector('#title')!.value; const description = app!.querySelector('#description')!.value; const announce = app!.querySelector('#announce')?.checked ?? false; setStatus('Publishing room record…'); try { const room = await createRoom(account!.client, { title, description, serviceEndpoint: window.location.origin }); await refreshRooms(); if (announce) { setStatus('Room created. Sharing to Bluesky…'); try { await shareRoom(room); setStatus('Room created and shared to your Bluesky feed.'); } catch (error) { setStatus(`Room created. Sharing to Bluesky failed: ${describeError(error)}`); } } else { setStatus('Room created.'); } } catch (error) { setStatus(describeError(error)); } } async function shareRoom(room: BeachwaveRoom): Promise { const url = roomUrl(room); const description = room.record.description?.trim() || 'Live audio room on ATProto — tap to join the conversation.'; await announceRoom(account!.client, { text: `${room.record.title} is live on Beachwave — join: ${url}`, url, // Carry a branded external-embed card so the post renders as a Beachwave // room on Bluesky instead of unfurling the generic site landing page. card: { title: `🎙 ${room.record.title} · live on Beachwave`, description } }); } async function refreshRooms(): Promise { try { rooms = await listRooms(account!.client); renderRooms(); } catch (error) { setStatus(describeError(error)); } } function renderRooms(): void { const container = app!.querySelector('#rooms')!; if (rooms.length === 0) { container.innerHTML = '

No live rooms yet. Create one to get started.

'; return; } container.replaceChildren(...rooms.map((room) => renderRoomCard(room, true))); } function renderRoomCard(room: BeachwaveRoom, owned: boolean): HTMLElement { const ended = room.record.status === 'ended'; const row = document.createElement('article'); row.className = `room-row${ended ? ' ended' : ''}`; const main = document.createElement('div'); main.className = 'room-row-main'; const top = document.createElement('div'); top.className = 'room-row-top'; const badge = document.createElement('span'); if (ended) { badge.className = 'pill-muted'; badge.textContent = 'ENDED'; } else { badge.className = 'pill-live'; badge.innerHTML = 'LIVE'; } top.append(badge); const title = document.createElement('div'); title.className = 'room-row-title'; title.textContent = room.record.title; // The AT URI is shown deliberately — a room is just a record in your repo. const uri = document.createElement('div'); uri.className = 'room-row-uri mono'; uri.textContent = room.uri; main.append(top, title, uri); const actions = document.createElement('div'); actions.className = 'room-row-actions'; const joinButton = document.createElement('button'); joinButton.type = 'button'; joinButton.textContent = 'Join audio'; joinButton.addEventListener('click', () => void handleJoin(room)); const copyButton = document.createElement('button'); copyButton.type = 'button'; copyButton.className = 'secondary'; copyButton.textContent = 'Copy link'; copyButton.addEventListener('click', () => void handleCopy(room)); actions.append(joinButton, copyButton); if (account!.kind !== 'offline') { const shareButton = document.createElement('button'); shareButton.type = 'button'; shareButton.className = 'secondary'; shareButton.textContent = 'Share'; shareButton.addEventListener('click', () => void handleShare(room)); actions.append(shareButton); } if (owned && canAdminister(room) && !ended) { const endButton = document.createElement('button'); endButton.type = 'button'; endButton.className = 'danger'; endButton.textContent = 'End room'; endButton.addEventListener('click', () => void handleEnd(room)); actions.append(endButton); } row.append(main, actions); return row; } async function handleJoin(room: BeachwaveRoom): Promise { try { const joined = await joinRoom(account!.client, room.uri); activeRoom = joined.room; const role = participantRole(joined.room); await leaveMedia(); const stage = app!.querySelector('#stage')!; stage.hidden = false; stage.classList.add('active'); stage.innerHTML = `
LIVE

connecting… · you joined as
`; stage.querySelector('#stage-title')!.textContent = activeRoom.record.title; stage.querySelector('#stage-role')!.textContent = role; stage.querySelector('#leave')!.addEventListener('click', () => void handleLeave()); stage.querySelector('#copy-room')!.addEventListener('click', () => void handleCopy(activeRoom!)); stage.scrollIntoView({ behavior: 'smooth', block: 'start' }); startHeartbeat(joined.room); await connectMedia(joined.livekitRoom, role); } catch (error) { setStatus(describeError(error)); } } async function connectMedia(livekitRoom: string, role: ParticipantRole): Promise { const media = app!.querySelector('#stage-media')!; const count = app!.querySelector('#stage-count')!; const controller = controllerFor(activeRoom); activeController = controller; if (!controller) { count.textContent = 'audio not configured'; media.innerHTML = `

Media handoff target: ${escapeHtml(livekitRoom)}. Configure a LiveKit token endpoint to connect audio and chat in-app.

`; return; } media.innerHTML = '

Connecting…

'; try { mediaSession = await controller.join({ livekitRoom, identity: account!.did, displayName: account!.label, role, roomUri: activeRoom?.uri }); // Reset per-room moderation state for this fresh session. controlMode = undefined; micOn = false; speakRequested = false; pendingSpeakRequests.clear(); media.innerHTML = ''; mediaUnsubscribers.push(mediaSession.subscribe(onRoomState)); mediaUnsubscribers.push(mediaSession.onChat(appendChatMessage)); mediaUnsubscribers.push(mediaSession.onSpeakRequest(handleSpeakRequest)); mediaUnsubscribers.push(mediaSession.onSpeakDecision(handleSpeakDecision)); mediaUnsubscribers.push(mediaSession.onRoleUpdate(handleRoleUpdate)); setupChatForm(); app!.querySelector('#chat')!.hidden = false; } catch (error) { count.textContent = ''; media.innerHTML = `

${escapeHtml(describeError(error))}

`; } } /** * Pick the media controller for a room. Your own rooms (and rooms hosted on this * deployment) use the local controller; a room discovered on another instance is * joined through the host's deployment, which holds that room's LiveKit project. */ function controllerFor(room: BeachwaveRoom | undefined): LiveKitMediaController | undefined { if (!room || account!.kind === 'offline') return undefined; const endpoint = room.record.serviceEndpoint; if (endpoint && !isSameOrigin(endpoint)) { const base = endpoint.replace(/\/+$/, ''); return new LiveKitMediaController(new HttpMediaTokenProvider(`${base}/api/token`, getAuthToken), { grantEndpoint: `${base}/api/grant-speak`, removeEndpoint: `${base}/api/remove-participant`, getAuthToken }); } return mediaController; } function isSameOrigin(url: string): boolean { try { return new URL(url).origin === window.location.origin; } catch { return true; } } function onRoomState(state: MediaRoomState): void { renderParticipants(state); updateAudioUnlock(state); renderControls(state); } /** * Render the bottom-row controls from current state. Idempotent by "mode" so the * frequent speaking-state updates don't rebuild the buttons — only a change in * publish permission (speaker ⇄ listener) swaps the controls. */ function renderControls(state: MediaRoomState): void { const media = app!.querySelector('#stage-media'); if (!media) return; const local = state.participants.find((participant) => participant.isLocal); const mode: 'speaker' | 'listener' = local?.canSpeak ? 'speaker' : 'listener'; if (mode === controlMode) return; controlMode = mode; media.replaceChildren(mode === 'speaker' ? buildMicControl() : buildRequestControl()); } function buildMicControl(): HTMLElement { const mic = document.createElement('button'); mic.type = 'button'; mic.className = 'btn-mic'; mic.textContent = micOn ? '🔇 Mute mic' : '🎙 Enable mic'; const applyMic = async (want: boolean): Promise => { try { await mediaSession!.setMicrophoneEnabled(want); micOn = want; mic.textContent = micOn ? '🔇 Mute mic' : '🎙 Unmute mic'; } catch (error) { // On mobile the auto-attempt can be rejected; the next tap is a gesture. micOn = false; mic.textContent = '🎙 Enable mic'; setStatus(describeError(error)); } }; mic.addEventListener('click', () => void applyMic(!micOn)); // Auto-enable on desktop; mobile falls back to a tap on the button. if (!micOn) void applyMic(true); return mic; } function buildRequestControl(): HTMLElement { const wrap = document.createElement('div'); wrap.className = 'request-control'; const button = document.createElement('button'); button.type = 'button'; button.className = 'btn-mic ghost'; const sync = (): void => { button.textContent = speakRequested ? '✋ Requested — waiting for host' : '✋ Request to speak'; button.disabled = speakRequested; }; button.addEventListener('click', async () => { if (speakRequested || !mediaSession) return; speakRequested = true; sync(); try { await mediaSession.requestToSpeak(); setStatus('Asked the host to speak.'); } catch (error) { speakRequested = false; sync(); setStatus(describeError(error)); } }); sync(); wrap.append(button); return wrap; } /** Host side: a listener asked to speak. */ function handleSpeakRequest(request: SpeakRequest): void { if (!activeRoom || !canAdminister(activeRoom)) return; if (request.identity === account!.did) return; pendingSpeakRequests.set(request.identity, request); renderRequests(); } /** Requester side: the host responded. */ function handleSpeakDecision(decision: { target: string; approved: boolean }): void { if (decision.target !== account!.did) return; if (decision.approved) { setStatus('You were approved to speak.'); } else { speakRequested = false; setStatus('Your request to speak was declined.'); if (mediaSession) renderControls(mediaSession.getState()); } } /** Someone changed your room role; re-read the record so the UI reflects it. */ async function handleRoleUpdate(target: string): Promise { if (target !== account!.did || !activeRoom) return; try { activeRoom = await getRoom(account!.client, activeRoom.uri); setStatus(canAdminister(activeRoom) ? 'You are now a room moderator.' : 'Your moderator role was removed.'); if (mediaSession) onRoomState(mediaSession.getState()); } catch { // Non-fatal; the role will be reflected on the next join. } } function renderRequests(): void { const section = app!.querySelector('#requests-section'); const list = app!.querySelector('#requests'); if (!section || !list) return; section.hidden = pendingSpeakRequests.size === 0; list.replaceChildren(...Array.from(pendingSpeakRequests.values()).map((request) => { const row = document.createElement('div'); row.className = 'request-row'; const name = document.createElement('span'); name.className = 'request-name'; name.textContent = request.name || shortDid(request.identity); const approve = document.createElement('button'); approve.type = 'button'; approve.className = 'btn-sm'; approve.textContent = 'Approve'; approve.addEventListener('click', () => void decideRequest(request, true)); const deny = document.createElement('button'); deny.type = 'button'; deny.className = 'btn-sm ghost'; deny.textContent = 'Deny'; deny.addEventListener('click', () => void decideRequest(request, false)); row.append(name, approve, deny); return row; })); } async function decideRequest(request: SpeakRequest, approved: boolean): Promise { pendingSpeakRequests.delete(request.identity); renderRequests(); try { if (approved) { await activeController!.grantSpeaker({ livekitRoom: activeRoom!.record.livekitRoom, identity: request.identity, roomUri: activeRoom!.uri }); } await mediaSession!.decideSpeak(request.identity, approved); setStatus(approved ? `Approved ${request.name || 'guest'} to speak.` : 'Request declined.'); } catch (error) { setStatus(describeError(error)); } } /** Show a tap-to-enable-audio control when the browser blocks playback (mobile/iOS). */ function updateAudioUnlock(state: MediaRoomState): void { const banner = app!.querySelector('#audio-unlock'); if (!banner) return; if (!state.audioBlocked) { banner.hidden = true; return; } banner.hidden = false; if (banner.childElementCount === 0) { const button = document.createElement('button'); button.type = 'button'; button.textContent = 'Tap to enable audio'; button.addEventListener('click', async () => { try { await mediaSession?.startAudio(); } catch (error) { setStatus(describeError(error)); } }); banner.append(button); } } function renderParticipants(state: MediaRoomState): void { const speakersEl = app!.querySelector('#speakers'); const listenersEl = app!.querySelector('#listeners'); const count = app!.querySelector('#stage-count'); if (!speakersEl || !listenersEl || !count) return; const speakers = state.participants.filter((p) => p.canSpeak); const listeners = state.participants.filter((p) => !p.canSpeak); const total = state.participants.length; count.textContent = `${total} ${total === 1 ? 'person' : 'people'} here`; const speakersLabel = app!.querySelector('#speakers-label'); if (speakersLabel) speakersLabel.textContent = `SPEAKERS · ${speakers.length}`; speakersEl.replaceChildren(...speakers.map((participant, index) => { const item = document.createElement('div'); item.className = `speaker${participant.isSpeaking ? ' speaking' : ''}`; const avatar = document.createElement('div'); avatar.className = `avatar av-${index % 4}${participant.isSpeaking ? ' ring' : ''}`; avatar.textContent = initials(participant.name || participant.identity); const name = document.createElement('div'); name.className = 'speaker-name'; name.textContent = participant.name || shortDid(participant.identity); const role = document.createElement('div'); role.className = `speaker-role${participant.isSpeaking ? ' live' : ''}`; role.textContent = roleLabel(participant); item.append(avatar, name, role); return item; })); const section = app!.querySelector('#listeners-section'); const listenersLabel = app!.querySelector('#listeners-label'); if (section) section.hidden = listeners.length === 0; if (listenersLabel) listenersLabel.textContent = `LISTENERS · ${listeners.length}`; listenersEl.replaceChildren(...listeners.map((participant) => { const item = document.createElement('div'); item.className = 'listener'; const avatar = document.createElement('div'); avatar.className = 'avatar muted'; avatar.textContent = initials(participant.name || participant.identity); const name = document.createElement('div'); name.className = 'listener-name'; name.textContent = participant.name || shortDid(participant.identity); item.append(avatar, name); const badge = listenerBadge(participant); if (badge) { const roleEl = document.createElement('div'); roleEl.className = 'speaker-role'; roleEl.textContent = badge; item.append(roleEl); } return item; })); renderModPanel(state); } /** * Room-level moderation, shown to admins only. Bulk controls plus one row per * person, so a host can manage a full room without hunting through the roster. */ function renderModPanel(state: MediaRoomState): void { const panel = app!.querySelector('#mod-panel'); if (!panel) return; const isAdmin = !!activeRoom && account!.kind !== 'offline' && !!activeController && canAdminister(activeRoom); if (!isAdmin) { panel.hidden = true; return; } panel.hidden = false; // Bulk controls. const bulk = app!.querySelector('#mod-bulk')!; bulk.replaceChildren(); const muteAllBtn = actionButton('Mute all', () => void muteAll()); bulk.append(muteAllBtn); if (isRoomOwner(activeRoom!)) { const open = activeRoom!.record.openMic === true; const toggle = actionButton(open ? 'Open mic: on' : 'Open mic: off', () => void toggleOpenMic(!open)); if (open) toggle.classList.add('on'); bulk.append(toggle); } // Per-person rows (everyone except yourself). const people = app!.querySelector('#mod-people')!; const others = state.participants.filter((p) => !p.isLocal); people.replaceChildren(...others.map((participant) => { const row = document.createElement('div'); row.className = 'mod-row'; const label = document.createElement('span'); label.className = 'mod-row-name'; label.textContent = participant.name || shortDid(participant.identity); const actions = hostActions(participant, participant.canSpeak); row.append(label); if (actions) row.append(actions); return row; })); if (others.length === 0) { const empty = document.createElement('p'); empty.className = 'muted-note'; empty.textContent = 'No one else is here yet.'; people.append(empty); } } async function muteAll(): Promise { if (!activeController || !activeRoom || !mediaSession) return; const targets = mediaSession.getState().participants.filter((p) => p.canSpeak && !p.isLocal && !isAdminDid(p.identity)); let moved = 0; for (const participant of targets) { try { await activeController.grantSpeaker({ livekitRoom: activeRoom.record.livekitRoom, identity: participant.identity, canPublish: false, roomUri: activeRoom.uri }); moved += 1; } catch { // continue with the rest } } setStatus(`Moved ${moved} ${moved === 1 ? 'speaker' : 'speakers'} to the audience.`); } async function toggleOpenMic(on: boolean): Promise { if (!activeRoom || !isRoomOwner(activeRoom)) return; try { activeRoom = await setRoomOpenMic(account!.client, activeRoom.uri, on); if (on && activeController && mediaSession) { const listeners = mediaSession.getState().participants.filter((p) => !p.canSpeak && !p.isLocal && !isAdminDid(p.identity)); for (const participant of listeners) { try { await activeController.grantSpeaker({ livekitRoom: activeRoom.record.livekitRoom, identity: participant.identity, canPublish: true, roomUri: activeRoom.uri }); } catch { // continue } } } setStatus(on ? 'Open mic on. Everyone can speak.' : 'Open mic off. New joiners listen and request.'); if (mediaSession) onRoomState(mediaSession.getState()); } catch (error) { setStatus(describeError(error)); } } /** Role text for a speaker card. */ function roleLabel(participant: MediaParticipant): string { if (participant.isSpeaking) return 'speaking'; if (activeRoom && participant.identity === activeRoom.authorDid) return 'host'; if (isModerator(participant.identity)) return 'moderator'; return participant.isLocal ? 'you' : 'speaker'; } /** Role text for a listener card, shown only for notable roles. */ function listenerBadge(participant: MediaParticipant): string { if (activeRoom && participant.identity === activeRoom.authorDid) return 'host'; if (isModerator(participant.identity)) return 'moderator'; return participant.isLocal ? 'you' : ''; } function isRoomOwner(room: BeachwaveRoom): boolean { return room.authorDid === account!.did; } function isModerator(did: string): boolean { return !!activeRoom && did !== activeRoom.authorDid && (activeRoom.record.hosts ?? []).includes(did); } /** Host-only moderation buttons for a remote participant (null otherwise). */ function hostActions(participant: MediaParticipant, isSpeaker: boolean): HTMLElement | null { if (participant.isLocal || account!.kind === 'offline' || !activeController) return null; if (!activeRoom || !canAdminister(activeRoom)) return null; const wrap = document.createElement('div'); wrap.className = 'host-actions'; wrap.append( isSpeaker ? actionButton('Move to audience', () => moderate('demote', participant)) : actionButton('Invite', () => moderate('invite', participant)) ); // Promoting a co-moderator writes the room record, so only the owner can do it. if (isRoomOwner(activeRoom) && participant.identity !== activeRoom.authorDid) { wrap.append( isModerator(participant.identity) ? actionButton('Remove mod', () => moderate('demote-mod', participant)) : actionButton('Make mod', () => moderate('promote-mod', participant)) ); } wrap.append(actionButton('Remove', () => moderate('remove', participant), true)); return wrap; } function actionButton(label: string, onClick: () => void, danger = false): HTMLButtonElement { const button = document.createElement('button'); button.type = 'button'; button.className = `mod-btn${danger ? ' danger' : ''}`; button.textContent = label; button.addEventListener('click', onClick); return button; } async function moderate( action: 'invite' | 'demote' | 'remove' | 'promote-mod' | 'demote-mod', participant: MediaParticipant ): Promise { if (!activeController || !activeRoom) return; const livekitRoom = activeRoom.record.livekitRoom; const who = participant.name || shortDid(participant.identity); try { if (action === 'invite') { await activeController.grantSpeaker({ livekitRoom, identity: participant.identity, canPublish: true, roomUri: activeRoom.uri }); await mediaSession?.decideSpeak(participant.identity, true); setStatus(`Invited ${who} to speak.`); } else if (action === 'demote') { await activeController.grantSpeaker({ livekitRoom, identity: participant.identity, canPublish: false, roomUri: activeRoom.uri }); setStatus(`Moved ${who} to the audience.`); } else if (action === 'remove') { await activeController.removeParticipant({ livekitRoom, identity: participant.identity, roomUri: activeRoom.uri }); setStatus(`Removed ${who}.`); } else if (action === 'promote-mod') { activeRoom = await addRoomHost(account!.client, activeRoom.uri, participant.identity); await mediaSession?.notifyRoleUpdate(participant.identity); setStatus(`Made ${who} a moderator.`); if (mediaSession) onRoomState(mediaSession.getState()); } else if (action === 'demote-mod') { activeRoom = await removeRoomHost(account!.client, activeRoom.uri, participant.identity); await mediaSession?.notifyRoleUpdate(participant.identity); setStatus(`Removed ${who} as moderator.`); if (mediaSession) onRoomState(mediaSession.getState()); } } catch (error) { setStatus(describeError(error)); } } function setupChatForm(): void { const form = app!.querySelector('#chat-form'); const input = app!.querySelector('#chat-input'); if (!form || !input) return; form.addEventListener('submit', async (event) => { event.preventDefault(); const text = input.value.trim(); if (!text || !mediaSession) return; input.value = ''; try { await mediaSession.sendChat(text); } catch (error) { setStatus(describeError(error)); } }); } function appendChatMessage(message: ChatMessage): void { const log = app!.querySelector('#chat-log'); if (!log) return; const item = document.createElement('li'); item.className = `chat-message${message.isLocal ? ' mine' : ''}`; const who = document.createElement('strong'); who.textContent = message.name || shortDid(message.from); const body = document.createElement('span'); body.textContent = message.text; item.append(who, body); log.append(item); log.scrollTop = log.scrollHeight; } function shortDid(did: string): string { return did.length > 16 ? `${did.slice(0, 12)}…${did.slice(-4)}` : did; } /** Two-letter avatar initials from a display name or handle/DID. */ function initials(value: string): string { const cleaned = value.replace(/^@/, '').replace(/^did:[a-z]+:/, '').trim(); const parts = cleaned.split(/[\s._@:-]+/).filter(Boolean); if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase(); return cleaned.slice(0, 2).toUpperCase() || '··'; } /** First label of a handle, capitalized — for the dashboard greeting. */ function friendlyName(label: string): string { const first = label.replace(/^@/, '').split(/[.\s@]/)[0] || label; return first.charAt(0).toUpperCase() + first.slice(1); } async function handleLeave(): Promise { stopHeartbeat(); await leaveMedia(); await leaveRoom(); activeRoom = undefined; controlMode = undefined; micOn = false; speakRequested = false; pendingSpeakRequests.clear(); const stage = app!.querySelector('#stage')!; stage.classList.remove('active'); stage.innerHTML = ''; stage.hidden = true; } /** Keep the room's heartbeat fresh while we host it (so discovery stays honest). */ function startHeartbeat(room: BeachwaveRoom): void { stopHeartbeat(); if (account!.kind === 'offline' || !canAdminister(room)) return; heartbeatTimer = setInterval(() => { void touchRoom(account!.client, room.uri).catch(() => {}); }, HEARTBEAT_MS); } function stopHeartbeat(): void { if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = undefined; } } async function leaveMedia(): Promise { for (const unsubscribe of mediaUnsubscribers) unsubscribe(); mediaUnsubscribers = []; activeController = undefined; if (mediaSession) { try { await mediaSession.leave(); } catch { // Best effort; the media session may already be gone. } mediaSession = undefined; } } async function handleShare(room: BeachwaveRoom): Promise { setStatus('Sharing to Bluesky…'); try { await shareRoom(room); setStatus('Shared to your Bluesky feed.'); } catch (error) { setStatus(describeError(error)); } } async function handleCopy(room: BeachwaveRoom): Promise { try { await navigator.clipboard.writeText(roomUrl(room)); setStatus('Copied room link.'); } catch { setStatus(roomUrl(room)); } } async function handleEnd(room: BeachwaveRoom): Promise { try { await endRoom(account!.client, room.uri); if (activeRoom?.uri === room.uri) await handleLeave(); setStatus('Room ended.'); await refreshRooms(); } catch (error) { setStatus(describeError(error)); } } async function handleSignOut(): Promise { stopHeartbeat(); await leaveMedia(); await account?.signOut(); account = undefined; activeRoom = undefined; rooms = []; forgetSharedRoom(); renderSignIn(); } // --------------------------------------------------------------------------- // Shared-room (invite link) handling // --------------------------------------------------------------------------- async function renderPendingSharedRoom(): Promise { const uri = pendingSharedRoom(); const section = app!.querySelector('#invite')!; section.hidden = true; if (!uri) return; // A shared link should land you in the room, not on the dashboard. Resolve the // record the link points at and open the live room directly. try { const room = await getRoom(account!.client, uri); forgetSharedRoom(); await handleJoin(room); } catch (error) { forgetSharedRoom(); setStatus(`Couldn't open the shared room: ${describeError(error)}`); } } function rememberSharedRoom(uri: string | null): void { if (uri && uri.startsWith('at://')) sessionStorage.setItem(PENDING_ROOM_KEY, uri); } function pendingSharedRoom(): string | undefined { return sessionStorage.getItem(PENDING_ROOM_KEY) ?? undefined; } function forgetSharedRoom(): void { sessionStorage.removeItem(PENDING_ROOM_KEY); } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function participantRole(room: BeachwaveRoom): ParticipantRole { if (canAdminister(room)) return 'host'; return room.record.openMic ? 'speaker' : 'listener'; } /** A DID that should never be auto-muted: the owner or a moderator. */ function isAdminDid(did: string): boolean { if (!activeRoom) return false; return did === activeRoom.authorDid || (activeRoom.record.hosts ?? []).includes(did); } function canAdminister(room: BeachwaveRoom): boolean { if (room.authorDid === account!.did) return true; return (room.record.hosts ?? []).includes(account!.did); } function roomUrl(room: BeachwaveRoom): string { const url = new URL(window.location.href); url.search = ''; url.searchParams.set('room', room.uri); return url.toString(); } function setStatus(message: string): void { const status = app!.querySelector('#status'); if (status) status.textContent = message; } function clearCallbackParams(): void { const url = new URL(window.location.href); url.search = ''; window.history.replaceState({}, '', url.toString()); } function describeError(error: unknown): string { return error instanceof Error ? error.message : String(error); } function escapeHtml(value: string): string { return value.replace(/[&<>"']/g, (char) => { switch (char) { case '&': return '&'; case '<': return '<'; case '>': return '>'; case '"': return '"'; default: return '''; } }); }