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))}`)}
${text('status', 'Connecting ...')}
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);
}