Полный рефакторинг сервера и клиента, голосовые сообщения, аудио/видео, Docker

Сервер:
- Вынесена конфигурация в server/config.js (порт, размер файла из env)
- Вынесена аутентификация в server/auth.js (загрузка users.json, authenticate())
- Вынесено управление соединениями в server/clients.js (createJsonSender, broadcast, validateFile)
- server/server.js стал точкой входа — минимальный код

Клиент:
- Вынесены хуки: hooks/useWebSocket.js (WebSocket + auth), hooks/useChatMessages.js (сообщения + уведомления)
- Вынесены утилиты: utils/blob.js (base64 → Blob URL), utils/linkify.jsx (URL → ссылки), utils/notify.js (звук + favicon)

Новые функции:
- VoiceRecorder — запись голоса через MediaRecorder, отправка как файл
- Аудио/видео плеер в Message (audio/*, video/* с controls)
- URL linkification — http/https ссылки автоматически кликабельны
- Звуковое уведомление (Web Audio API) при сообщении на неактивной вкладке
- Красная точка на favicon при непрочитанных сообщениях

Инфраструктура:
- docker-entrypoint.sh: авто-перезапуск Node.js сервера при падении
- Обновлён README.md: новая структура проекта, список функций, примеры
- Кастомный тонкий скроллбар в Message.css
This commit is contained in:
Комаров Данил Анатольевич 6
2026-05-29 05:23:22 +03:00
parent 83ef0d5ab3
commit 63bf73d2c4
18 changed files with 760 additions and 485 deletions
+5 -66
View File
@@ -1,75 +1,14 @@
import React, { useState, useRef, useCallback, useEffect } from 'react';
import React from 'react';
import Login from './components/Login';
import Chat from './components/Chat';
const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8080';
import useWebSocket from './hooks/useWebSocket';
export default function App() {
const [loggedIn, setLoggedIn] = useState(false);
const [login, setLogin] = useState('');
const [error, setError] = useState('');
const wsRef = useRef(null);
const handleLogin = useCallback((userLogin, password) => {
setError('');
const ws = new WebSocket(WS_URL);
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'auth', login: userLogin, password }));
};
ws.onmessage = (event) => {
let msg;
try {
msg = JSON.parse(event.data);
} catch {
return;
}
if (msg.type === 'auth_result') {
if (msg.success) {
setLogin(userLogin);
setLoggedIn(true);
} else {
setError(msg.reason || 'Authentication failed');
ws.close();
}
}
};
ws.onerror = () => {
setError('Cannot connect to server');
};
ws.onclose = () => {
if (!loggedIn) {
setError('Connection closed');
}
};
wsRef.current = ws;
}, [loggedIn]);
const handleLogout = useCallback(() => {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
setLoggedIn(false);
setLogin('');
}, []);
useEffect(() => {
return () => {
if (wsRef.current) {
wsRef.current.close();
}
};
}, []);
const { login, loggedIn, error, ws, loginToServer, logout } = useWebSocket();
if (!loggedIn) {
return <Login onLogin={handleLogin} error={error} />;
return <Login onLogin={loginToServer} error={error} />;
}
return <Chat ws={wsRef.current} login={login} onLogout={handleLogout} />;
return <Chat ws={ws} login={login} onLogout={logout} />;
}
+4 -120
View File
@@ -1,126 +1,11 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import React from 'react';
import MessageList from './MessageList';
import MessageInput from './MessageInput';
import useChatMessages from '../hooks/useChatMessages';
import './Chat.css';
function setFavicon(hasNotification) {
const canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#4a9eff';
ctx.beginPath();
ctx.arc(16, 16, 14, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = '#fff';
ctx.font = 'bold 18px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('CH', 16, 16);
if (hasNotification) {
ctx.fillStyle = '#ff4444';
ctx.beginPath();
ctx.arc(26, 6, 5, 0, 2 * Math.PI);
ctx.fill();
ctx.strokeStyle = '#1a1a2e';
ctx.lineWidth = 2;
ctx.stroke();
}
let link = document.querySelector('link[rel="icon"]');
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = canvas.toDataURL();
}
export default function Chat({ ws, login, onLogout }) {
const [messages, setMessages] = useState([]);
const [connected, setConnected] = useState(true);
const [error, setError] = useState('');
const hasNotifRef = useRef(false);
const messagesRef = useRef(messages);
messagesRef.current = messages;
const addMessage = useCallback((msg) => {
setMessages(prev => [...prev, { ...msg, id: Date.now() + Math.random() }]);
if (
document.hidden &&
msg.from &&
msg.from !== login &&
(msg.type === 'text' || msg.type === 'file')
) {
if (!hasNotifRef.current) {
hasNotifRef.current = true;
setFavicon(true);
}
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
osc.frequency.value = 520;
gain.gain.value = 0.15;
osc.start();
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15);
osc.stop(ctx.currentTime + 0.15);
osc.onended = () => ctx.close();
} catch {}
}
}, [login]);
useEffect(() => {
setFavicon(false);
const onVisible = () => {
if (hasNotifRef.current) {
hasNotifRef.current = false;
setFavicon(false);
}
};
document.addEventListener('visibilitychange', onVisible);
return () => {
document.removeEventListener('visibilitychange', onVisible);
};
}, []);
useEffect(() => {
if (!ws) return;
ws.onmessage = (event) => {
let msg;
try {
msg = JSON.parse(event.data);
} catch {
return;
}
if (msg.type === 'text') {
addMessage(msg);
} else if (msg.type === 'file') {
addMessage(msg);
} else if (msg.type === 'system') {
addMessage(msg);
} else if (msg.type === 'error') {
setError(msg.message);
}
};
ws.onclose = () => {
setConnected(false);
setError('Connection lost');
};
ws.onerror = () => {
setConnected(false);
setError('Connection error');
};
}, [ws, addMessage]);
const { messages, connected, error } = useChatMessages(ws, login);
return (
<div className="chat-container">
@@ -128,8 +13,7 @@ export default function Chat({ ws, login, onLogout }) {
<h2>Chat room logged in as <strong>{login}</strong></h2>
<button className="logout-btn" onClick={onLogout}>Logout</button>
</div>
{error && !connected && <div className="chat-error">{error}</div>}
{error && connected && <div className="chat-notification">{error}</div>}
{error && <div className={connected ? 'chat-notification' : 'chat-error'}>{error}</div>}
<MessageList messages={messages} currentUser={login} />
<MessageInput ws={ws} />
</div>
+20
View File
@@ -127,3 +127,23 @@
font-size: 0.85rem;
margin-top: 0.3rem;
}
.message-audio, .message-video {
margin-top: 0.3rem;
}
.message-audio-player {
width: 100%;
height: 40px;
border-radius: 6px;
background: #1a1a2e;
}
.message-video-player {
width: 100%;
max-height: 300px;
border-radius: 8px;
display: block;
cursor: pointer;
background: #000;
}
+49 -81
View File
@@ -1,77 +1,35 @@
import React, { useMemo } from 'react';
import React, { useMemo, useState } from 'react';
import { linkifyText } from '../utils/linkify.jsx';
import { dataURLToBlobUrl } from '../utils/blob';
import './Message.css';
function formatTime(ts) {
const d = new Date(ts);
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
return new Date(ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
const URL_REGEX = /(https?:\/\/[^\s<]+[^\s<.,!?)}\]"'\\])/gi;
function linkifyText(text) {
const parts = [];
let lastIndex = 0;
let match;
URL_REGEX.lastIndex = 0;
while ((match = URL_REGEX.exec(text)) !== null) {
if (match.index > lastIndex) {
parts.push(text.slice(lastIndex, match.index));
}
parts.push(
<a key={match.index} href={match[0]} target="_blank" rel="noopener noreferrer">
{match[0]}
</a>
);
lastIndex = match.index + match[0].length;
}
if (lastIndex < text.length) {
parts.push(text.slice(lastIndex));
}
return parts.length ? parts : text;
}
function dataURLToBlobUrl(dataUrl) {
try {
const arr = dataUrl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
const n = bstr.length;
const u8arr = new Uint8Array(n);
for (let i = 0; i < n; i++) {
u8arr[i] = bstr.charCodeAt(i);
}
const blob = new Blob([u8arr], { type: mime });
return URL.createObjectURL(blob);
} catch {
return null;
}
}
const FILE_ICON = '\u{1F4CE}';
export default function Message({ message, isOwn }) {
const isImage = message.mime && message.mime.startsWith('image/');
const [videoExpanded, setVideoExpanded] = useState(false);
const mime = message.mime;
const isSystem = message.type === 'system';
const isFile = message.type === 'file';
const typeGroup = isFile
? mime?.startsWith('image/') ? 'image'
: mime?.startsWith('video/') ? 'video'
: mime?.startsWith('audio/') ? 'audio'
: 'file'
: null;
const blobUrl = useMemo(() => {
const fileUrl = useMemo(() => {
if (isFile && message.data) {
return dataURLToBlobUrl(`data:${message.mime};base64,${message.data}`);
return dataURLToBlobUrl(`data:${mime};base64,${message.data}`);
}
return null;
}, [isFile, message.data, message.mime]);
const downloadUrl = useMemo(() => {
if (isFile && message.data && !isImage) {
return dataURLToBlobUrl(`data:${message.mime};base64,${message.data}`);
}
return null;
}, [isFile, message.data, message.mime, isImage]);
}, [isFile, message.data, mime]);
if (isSystem) {
return (
<div className="message-system">
<span>{message.text}</span>
</div>
);
return <div className="message-system"><span>{message.text}</span></div>;
}
return (
@@ -82,31 +40,41 @@ export default function Message({ message, isOwn }) {
</div>
<div className="message-body">
{message.text && <p>{linkifyText(message.text)}</p>}
{isFile && isImage && blobUrl && (
<a href={blobUrl} target="_blank" rel="noreferrer">
<img
className="message-image"
src={blobUrl}
alt={message.filename}
/>
{isFile && typeGroup === 'image' && (fileUrl ? (
<a href={fileUrl} target="_blank" rel="noreferrer">
<img className="message-image" src={fileUrl} alt={message.filename} />
</a>
)}
{isFile && isImage && !blobUrl && (
<div className="message-file-error">Failed to load image</div>
)}
{isFile && !isImage && downloadUrl && (
<a
className="message-file-link"
href={downloadUrl}
download={message.filename}
>
<span className="file-icon">&#128206;</span>
) : <div className="message-file-error">Failed to load image</div>)}
{isFile && typeGroup === 'audio' && (fileUrl ? (
<div className="message-audio">
<audio controls src={fileUrl} className="message-audio-player" />
<a className="message-file-link" href={fileUrl} download={message.filename}>
<span className="file-icon">{FILE_ICON}</span>
{message.filename}
</a>
</div>
) : <div className="message-file-error">Failed to load audio</div>)}
{isFile && typeGroup === 'video' && (fileUrl ? (
<div className="message-video">
<video
className="message-video-player"
src={fileUrl}
controls={videoExpanded}
preload="metadata"
onClick={() => setVideoExpanded(true)}
/>
<a className="message-file-link" href={fileUrl} download={message.filename}>
<span className="file-icon">{FILE_ICON}</span>
{message.filename}
</a>
</div>
) : <div className="message-file-error">Failed to load video</div>)}
{isFile && typeGroup === 'file' && (fileUrl ? (
<a className="message-file-link" href={fileUrl} download={message.filename}>
<span className="file-icon">{FILE_ICON}</span>
{message.filename}
</a>
)}
{isFile && !isImage && !downloadUrl && (
<div className="message-file-error">Failed to load file</div>
)}
) : <div className="message-file-error">Failed to load file</div>)}
</div>
</div>
);
+21 -23
View File
@@ -1,11 +1,21 @@
import React, { useState, useRef } from 'react';
import VoiceRecorder from './VoiceRecorder';
import './MessageInput.css';
const MAX_FILE_SIZE = 10 * 1024 * 1024;
function readFileAsBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result.split(',')[1]);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
export default function MessageInput({ ws }) {
const [text, setText] = useState('');
const fileInputRef = useRef(null);
const fileRef = useRef(null);
const sendText = (e) => {
e.preventDefault();
@@ -14,35 +24,27 @@ export default function MessageInput({ ws }) {
setText('');
};
const handleFileSelect = (e) => {
const handleFileSelect = async (e) => {
const file = e.target.files[0];
e.target.value = '';
if (!file) return;
if (file.size > MAX_FILE_SIZE) {
alert('File too large. Maximum is 10 MB.');
e.target.value = '';
return;
}
const reader = new FileReader();
reader.onload = () => {
const base64 = reader.result.split(',')[1];
try {
const data = await readFileAsBase64(file);
ws.send(JSON.stringify({
type: 'file',
filename: file.name,
mime: file.type || 'application/octet-stream',
data: base64
data,
}));
};
reader.onerror = () => {
} catch {
alert('Failed to read file');
};
reader.readAsDataURL(file);
e.target.value = '';
};
const handleAttachClick = () => {
fileInputRef.current?.click();
}
};
return (
@@ -55,17 +57,13 @@ export default function MessageInput({ ws }) {
value={text}
onChange={(e) => setText(e.target.value)}
/>
<button type="button" className="attach-btn" onClick={handleAttachClick} title="Attach file">
<VoiceRecorder ws={ws} />
<button type="button" className="attach-btn" onClick={() => fileRef.current?.click()} title="Attach file">
&#128206;
</button>
<button type="submit" className="send-btn">Send</button>
</form>
<input
ref={fileInputRef}
type="file"
className="file-input-hidden"
onChange={handleFileSelect}
/>
<input ref={fileRef} type="file" className="file-input-hidden" onChange={handleFileSelect} />
</div>
);
}
+60
View File
@@ -0,0 +1,60 @@
.voice-recorder {
display: flex;
align-items: center;
gap: 0.4rem;
}
.voice-recorder-btn {
padding: 0.7rem;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 1.1rem;
transition: background 0.2s;
background: #2a2a4a;
line-height: 1;
}
.voice-recorder-btn:hover {
background: #3a3a5a;
}
.voice-recorder-btn.recording {
background: #5c1a1a;
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { box-shadow: 0 0 0 0 rgba(255, 60, 60, 0.5); }
50% { box-shadow: 0 0 0 6px rgba(255, 60, 60, 0); }
}
.voice-recorder-btn:disabled {
opacity: 0.5;
cursor: default;
}
.voice-recorder-indicator {
display: flex;
align-items: center;
gap: 0.3rem;
}
.voice-recorder-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #ff4444;
animation: blink 1s step-end infinite;
}
@keyframes blink {
50% { opacity: 0; }
}
.voice-recorder-timer {
font-size: 0.85rem;
color: #ff8a8a;
font-variant-numeric: tabular-nums;
min-width: 3em;
}
+141
View File
@@ -0,0 +1,141 @@
import React, { useState, useRef, useCallback, useEffect } from 'react';
import './VoiceRecorder.css';
function readFileAsBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result.split(',')[1]);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
function getSupportedMime() {
const types = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/ogg;codecs=opus',
'audio/ogg',
'audio/mp4',
];
return types.find(t => MediaRecorder.isTypeSupported(t)) || '';
}
function formatDuration(seconds) {
const m = String(Math.floor(seconds / 60)).padStart(2, '0');
const s = String(seconds % 60).padStart(2, '0');
return `${m}:${s}`;
}
export default function VoiceRecorder({ ws }) {
const [state, setState] = useState('idle');
const [duration, setDuration] = useState(0);
const mediaRecorderRef = useRef(null);
const chunksRef = useRef([]);
const streamRef = useRef(null);
const timerRef = useRef(null);
useEffect(() => {
return () => {
if (timerRef.current) clearInterval(timerRef.current);
if (streamRef.current) streamRef.current.getTracks().forEach(t => t.stop());
};
}, []);
const stopRecording = useCallback(() => {
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
mediaRecorderRef.current.stop();
}
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
if (streamRef.current) {
streamRef.current.getTracks().forEach(t => t.stop());
streamRef.current = null;
}
}, []);
const startRecording = useCallback(async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
streamRef.current = stream;
} catch {
alert('Microphone access denied');
return;
}
const mime = getSupportedMime();
chunksRef.current = [];
const recorder = new MediaRecorder(streamRef.current, mime ? { mimeType: mime } : {});
mediaRecorderRef.current = recorder;
recorder.ondataavailable = (e) => {
if (e.data.size > 0) chunksRef.current.push(e.data);
};
recorder.onstop = async () => {
setState('sending');
const blob = new Blob(chunksRef.current, { type: mime || 'audio/webm' });
const ext = mime.includes('mp4') ? '.mp4' : mime.includes('ogg') ? '.ogg' : '.webm';
const file = new File([blob], `voice${ext}`, { type: mime || 'audio/webm' });
try {
const data = await readFileAsBase64(file);
ws.send(JSON.stringify({
type: 'file',
filename: file.name,
mime: file.type,
data,
}));
} catch {
alert('Failed to send voice message');
}
setState('idle');
setDuration(0);
};
recorder.onerror = () => {
alert('Recording error');
setState('idle');
setDuration(0);
};
recorder.start(100);
setState('recording');
setDuration(0);
timerRef.current = setInterval(() => {
setDuration(prev => prev + 1);
}, 1000);
}, [ws]);
const handleClick = () => {
if (state === 'recording') {
stopRecording();
} else if (state === 'idle') {
startRecording();
}
};
return (
<div className={`voice-recorder ${state}`}>
{state === 'recording' && (
<div className="voice-recorder-indicator">
<span className="voice-recorder-dot" />
<span className="voice-recorder-timer">{formatDuration(duration)}</span>
</div>
)}
<button
type="button"
className={`voice-recorder-btn ${state}`}
onClick={handleClick}
disabled={state === 'sending'}
title={state === 'recording' ? 'Stop recording' : 'Record voice message'}
>
{state === 'sending' ? '...' : '\u{1F3A4}'}
</button>
</div>
);
}
+68
View File
@@ -0,0 +1,68 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { playBeep, drawFavicon } from '../utils/notify';
export default function useChatMessages(ws, login) {
const [messages, setMessages] = useState([]);
const [connected, setConnected] = useState(true);
const [error, setError] = useState('');
const hasNotifRef = useRef(false);
const addMessage = useCallback((msg) => {
setMessages(prev => [...prev, { ...msg, id: Date.now() + Math.random() }]);
if (
document.hidden &&
msg.from &&
msg.from !== login &&
(msg.type === 'text' || msg.type === 'file')
) {
if (!hasNotifRef.current) {
hasNotifRef.current = true;
drawFavicon(true);
}
playBeep();
}
}, [login]);
useEffect(() => {
drawFavicon(false);
const onVisible = () => {
if (hasNotifRef.current) {
hasNotifRef.current = false;
drawFavicon(false);
}
};
document.addEventListener('visibilitychange', onVisible);
return () => document.removeEventListener('visibilitychange', onVisible);
}, []);
useEffect(() => {
if (!ws) return;
ws.onmessage = (event) => {
let msg;
try {
msg = JSON.parse(event.data);
} catch {
return;
}
if (msg.type === 'text' || msg.type === 'file' || msg.type === 'system') {
addMessage(msg);
} else if (msg.type === 'error') {
setError(msg.message);
}
};
ws.onclose = () => {
setConnected(false);
setError('Connection lost');
};
ws.onerror = () => {
setConnected(false);
setError('Connection error');
};
}, [ws, addMessage]);
return { messages, connected, error };
}
+73
View File
@@ -0,0 +1,73 @@
import { useState, useRef, useCallback, useEffect } from 'react';
const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8080';
export default function useWebSocket() {
const [login, setLogin] = useState('');
const [loggedIn, setLoggedIn] = useState(false);
const [error, setError] = useState('');
const [ws, setWs] = useState(null);
const loggedInRef = useRef(false);
const loginToServer = useCallback((userLogin, password) => {
setError('');
const socket = new WebSocket(WS_URL);
socket.onopen = () => {
socket.send(JSON.stringify({ type: 'auth', login: userLogin, password }));
};
socket.onmessage = (event) => {
let msg;
try {
msg = JSON.parse(event.data);
} catch {
return;
}
if (msg.type === 'auth_result') {
if (msg.success) {
setLogin(userLogin);
setLoggedIn(true);
loggedInRef.current = true;
setWs(socket);
} else {
setError(msg.reason || 'Authentication failed');
socket.close();
}
}
};
socket.onerror = () => {
if (!loggedInRef.current) {
setError('Cannot connect to server');
}
};
socket.onclose = () => {
if (!loggedInRef.current) {
setError('Connection closed');
}
};
}, []);
const logout = useCallback(() => {
if (ws) {
ws.close();
}
setWs(null);
setLogin('');
setLoggedIn(false);
loggedInRef.current = false;
}, [ws]);
useEffect(() => {
return () => {
if (ws) {
ws.close();
}
};
}, [ws]);
return { login, loggedIn, error, ws, loginToServer, logout };
}
+16
View File
@@ -0,0 +1,16 @@
export function dataURLToBlobUrl(dataUrl) {
try {
const arr = dataUrl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
const n = bstr.length;
const u8arr = new Uint8Array(n);
for (let i = 0; i < n; i++) {
u8arr[i] = bstr.charCodeAt(i);
}
const blob = new Blob([u8arr], { type: mime });
return URL.createObjectURL(blob);
} catch {
return null;
}
}
+23
View File
@@ -0,0 +1,23 @@
const URL_REGEX = /(https?:\/\/[^\s<]+[^\s<.,!?)}\]"'\\])/gi;
export function linkifyText(text) {
const parts = [];
let lastIndex = 0;
let match;
URL_REGEX.lastIndex = 0;
while ((match = URL_REGEX.exec(text)) !== null) {
if (match.index > lastIndex) {
parts.push(text.slice(lastIndex, match.index));
}
parts.push(
<a key={match.index} href={match[0]} target="_blank" rel="noopener noreferrer">
{match[0]}
</a>
);
lastIndex = match.index + match[0].length;
}
if (lastIndex < text.length) {
parts.push(text.slice(lastIndex));
}
return parts.length ? parts : text;
}
+51
View File
@@ -0,0 +1,51 @@
export function playBeep() {
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
osc.frequency.value = 520;
gain.gain.value = 0.15;
osc.start();
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15);
osc.stop(ctx.currentTime + 0.15);
osc.onended = () => ctx.close();
} catch { /* audio not supported */ }
}
export function drawFavicon(hasNotification) {
const canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#4a9eff';
ctx.beginPath();
ctx.arc(16, 16, 14, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = '#fff';
ctx.font = 'bold 18px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('CH', 16, 16);
if (hasNotification) {
ctx.fillStyle = '#ff4444';
ctx.beginPath();
ctx.arc(26, 6, 5, 0, 2 * Math.PI);
ctx.fill();
ctx.strokeStyle = '#1a1a2e';
ctx.lineWidth = 2;
ctx.stroke();
}
let link = document.querySelector('link[rel="icon"]');
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = canvas.toDataURL();
}