Overview

ws(url, config?) creates a managed WebSocket with optional auto-reconnect. It must be called in a component's outer function so cleanup (socket, timers, handlers) is registered on the host.

onSocket(handler, sockets) subscribes to one or more connections and unsubscribes on unmount. Prefer this over connection.__subscribe inside components.

ws vs onSocket

API
Role
Notes
ws(url, config?) Connection Returns WsConnection — send, status atom, connect/disconnect.
onSocket(fn, sockets) Subscribe Component-scoped message handler; auto-cleanup.

Simulated WebSocket message stream

In a real app, ws() connects to your WebSocket server and onSocket() delivers messages reactively. This demo simulates the same message-stream pattern with onInterval so no server is required.

import { html, atom, onInterval, renderApp } from 'mates';
// Real usage: import { ws, onSocket } from 'mates';
// const sock = ws('wss://example.com/chat', { reconnect: true });
// onSocket((data) => { ... }, [sock]);
// This demo simulates WebSocket messages with onInterval

const MOCK_MESSAGES = [
'Server: Connection established',
'Server: Heartbeat OK',
'Server: User #42 joined',
'Server: Data update received',
'Server: Processing complete',
];

const App = () => {
const messages = atom([]);
const connected = atom(true);
let i = 0;

onInterval(() => {
if (!connected()) return;
messages.set(prev => [
...prev.slice(-7),
{ text: MOCK_MESSAGES[i % MOCK_MESSAGES.length], time: new Date().toLocaleTimeString() }
]);
i++;
}, 1500);

return () => html`
<div class="m-col m-gap">
<div class="m-flex m-gap-sm m-items-center">
<span class="tag ${connected() ? 'tag-success' : 'tag-danger'}">
${connected() ? '● Connected' : '○ Disconnected'}
</span>
<button class="btn-ghost" @click=${() => connected.set(v => !v)}>
${connected() ? 'Disconnect' : 'Reconnect'}