novy-syndicate/src/chat-client-standalone.ts

61 lines
1.9 KiB
TypeScript

import { $Present, $Says, asPresent, asSays, fromPresent, fromSays, Present, Says } from "./gen/chat-protocol.js";
import { fromObserve, Observe } from "./gen/dataspace.js";
import { Assertion, Handle, Ref, Turn } from "./actor.js";
import readline from 'readline';
export default function (t: Turn, ds: Ref) {
let username = '';
let usernameHandle: Handle | undefined;
function updateUsername(t: Turn, u: string) {
username = u;
usernameHandle = t.replace(ds, usernameHandle, fromPresent(Present(username)));
}
updateUsername(t, 'user' + process.pid);
const usermap = new Map<Handle, Present>();
t.assert(ds, fromObserve(Observe({
label: $Present,
observer: t.ref({
assert(t: Turn, e0: Assertion, h: Handle): void {
const e = asPresent(e0);
console.log(`${e.username} arrived`);
usermap.set(h, e);
},
retract(t: Turn, h: Handle): void {
const e = usermap.get(h);
if (e) {
usermap.delete(h);
console.log(`${e.username} departed`);
}
},
}),
})));
t.assert(ds, fromObserve(Observe({
label: $Says,
observer: t.ref({
message(t: Turn, u0: Assertion): void {
const u = asSays(u0);
console.log(`${u.who}: ${u.what}`);
},
}),
})));
function sendUtterance(what: string) {
t.freshen(t => t.message(ds, fromSays(Says({ who: username, what }))));
}
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', (line: string) => {
if (line.startsWith('/nick ')) {
t.freshen(t => updateUsername(t, line.slice(5).trimLeft()));
} else {
sendUtterance(line);
}
});
rl.on('close', () => t.freshen(t => t.quit()));
}