42 lines
1.4 KiB
TypeScript
42 lines
1.4 KiB
TypeScript
import { $Present, $Says, asPresent, asSays, fromPresent, fromSays, Present, Says } from "./gen/simple-chat-protocol.js";
|
|
import { during, observe } from "./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);
|
|
|
|
observe(t, ds, $Present, during((_t, e0) => {
|
|
const e = asPresent(e0);
|
|
console.log(`${e.username} arrived`);
|
|
return (_t) => console.log(`${e.username} departed`);
|
|
}));
|
|
|
|
observe(t, ds, $Says, {
|
|
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 });
|
|
t.activeFacet.actor.atExit(_t => rl.close());
|
|
|
|
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.stopActor()));
|
|
}
|