54 lines
1.8 KiB
TypeScript
54 lines
1.8 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, LocalAction, 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, LocalAction>();
|
|
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, (_t: Turn) => console.log(`${e.username} departed`));
|
|
},
|
|
retract(t: Turn, h: Handle): void {
|
|
usermap.get(h)?.(t);
|
|
usermap.delete(h);
|
|
},
|
|
}),
|
|
})));
|
|
|
|
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}`);
|
|
},
|
|
}),
|
|
})));
|
|
|
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
|
|
rl.on('line', (line: string) => t.freshen(t => {
|
|
if (line.toLowerCase().startsWith('/nick ')) {
|
|
updateUsername(t, line.slice(5).trimLeft());
|
|
} else {
|
|
t.message(ds, fromSays(Says({ who: username, what: line })));
|
|
}
|
|
}));
|
|
|
|
rl.on('close', () => t.freshen(t => t.quit()));
|
|
}
|