import { marked } from 'marked'; import DOMPurify from 'dompurify'; import { html, attribute, hydrate, list, text, id } from 'wirejs-dom/v2'; import { AuthenticatedContent } from 'wirejs-components'; import { Main } from '../layouts/main.js'; import { chat } from 'internal-api'; type RoomMessage = { username: string; body: string; }; async function Chat() { const self = html`
${list('messages', (message: RoomMessage) => html`${DOMPurify.sanitize(( marked.parse(`**${message.username}:** ${message.body}` ) as string))}`)}
{ event.preventDefault(); chat.publish(null, self.data.room, self.data.message); self.data.message = ''; }}>
${text('status', 'Connecting ...')}
{ event.preventDefault(); self.data.messages = []; self.disconnect(); self.data.status = `Connecting to "${self.data.room}" ...`; self.connect(); }}>Join another room: { const randomRoom = Math.random().toString(36).substring(2, 10); self.data.room = randomRoom; self.data.roomChangeForm.dispatchEvent(new Event('submit')); }} />
{ event.preventDefault(); self.data.countdownDisabled = true; chat.startCountdown(null, self.data.room, self.data.countdownSeconds); setTimeout(() => { self.data.countdownDisabled = false; }, self.data.countdownSeconds * 1000); }}>

A simple example of realtime messaging. Messages are 100% ephemeral. If you reload the page, messages are lost. If you're not connected when a message it sent, you won't receive it.

The countdown feature is a simple background job that sends a message every second until the countdown reaches zero.

`.extend(() => ({ disconnect() { // no implementation until connected }, async connect() { const roomStream = await chat.getRoom(null, self.data.room); self.disconnect = roomStream.subscribe({ onopen() { self.data.status = `Connected to "${self.data.room}".`; }, onmessage(message) { self.data.messages.push(message); }, onclose(reason) { if (reason !== 'unsubscribed') { self.data.status = 'Disconnected. (Refresh the page to reconnect.)'; } } }); } })) .onadd(async () => { self.connect(); }); return self; } async function App() { return html`

Realtime Demo

${await AuthenticatedContent({ authenticated: Chat, unauthenticated: () => html`

Sign in for the realtime demo.

` })}
`; } export async function generate() { return Main({ pageTitle: 'Welcome!', content: await App() }) } export function onload() { hydrate('app', App as any); }