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