This commit is contained in:
Tony Garnock-Jones 2021-04-15 20:14:49 +02:00
parent f35815d62a
commit 421ea699c7
1 changed files with 12 additions and 19 deletions

View File

@ -1,6 +1,6 @@
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 { Assertion, Handle, LocalAction, Ref, Turn } from "./actor.js";
import readline from 'readline';
export default function (t: Turn, ds: Ref) {
@ -13,21 +13,18 @@ export default function (t: Turn, ds: Ref) {
}
updateUsername(t, 'user' + process.pid);
const usermap = new Map<Handle, Present>();
const usermap = new Map<Handle, LocalAction>();
t.assert(ds, fromObserve(Observe({
label: $Present,
observer: t.ref({
assert(t: Turn, e0: Assertion, h: Handle): void {
assert(_t: Turn, e0: Assertion, h: Handle): void {
const e = asPresent(e0);
console.log(`${e.username} arrived`);
usermap.set(h, e);
usermap.set(h, (_t: Turn) => console.log(`${e.username} departed`));
},
retract(t: Turn, h: Handle): void {
const e = usermap.get(h);
if (e) {
usermap.delete(h);
console.log(`${e.username} departed`);
}
usermap.get(h)?.(t);
usermap.delete(h);
},
}),
})));
@ -35,26 +32,22 @@ export default function (t: Turn, ds: Ref) {
t.assert(ds, fromObserve(Observe({
label: $Says,
observer: t.ref({
message(t: Turn, u0: Assertion): void {
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()));
rl.on('line', (line: string) => t.freshen(t => {
if (line.toLowerCase().startsWith('/nick ')) {
updateUsername(t, line.slice(5).trimLeft());
} else {
sendUtterance(line);
t.message(ds, fromSays(Says({ who: username, what: line })));
}
});
}));
rl.on('close', () => t.freshen(t => t.quit()));
}