2021-04-21 19:22:30 +00:00
|
|
|
import { $Present, $Says, asPresent, asSays, fromPresent, fromSays, Present, Says } from "../gen/simple-chat-protocol.js";
|
|
|
|
import { during, observe } from "../runtime/dataspace.js";
|
|
|
|
import { Assertion, Handle, Ref, Turn } from "../runtime/actor.js";
|
2021-04-16 18:58:22 +00:00
|
|
|
import { attachReadline } from './readline.js';
|
2021-05-17 13:13:55 +00:00
|
|
|
import { Embedded } from "@preserves/core";
|
2021-04-24 22:15:15 +00:00
|
|
|
|
2021-05-17 13:13:55 +00:00
|
|
|
export default function (t: Turn, ds_ptr: Embedded<Ref>) {
|
2021-04-24 22:15:15 +00:00
|
|
|
const ds = ds_ptr.embeddedValue;
|
2021-04-15 18:07:39 +00:00
|
|
|
|
|
|
|
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);
|
|
|
|
|
2021-04-19 11:00:08 +00:00
|
|
|
observe(t, ds, $Present, during(async (_t, e0) => {
|
2021-04-16 12:38:08 +00:00
|
|
|
const e = asPresent(e0);
|
|
|
|
console.log(`${e.username} arrived`);
|
|
|
|
return (_t) => console.log(`${e.username} departed`);
|
|
|
|
}));
|
2021-04-15 18:07:39 +00:00
|
|
|
|
2021-04-16 12:38:08 +00:00
|
|
|
observe(t, ds, $Says, {
|
|
|
|
message(_t: Turn, u0: Assertion): void {
|
|
|
|
const u = asSays(u0);
|
|
|
|
console.log(`${u.who}: ${u.what}`);
|
|
|
|
},
|
|
|
|
});
|
2021-04-15 18:07:39 +00:00
|
|
|
|
2021-04-16 18:58:22 +00:00
|
|
|
attachReadline(t, {
|
2021-04-21 19:22:30 +00:00
|
|
|
retract(t) { t.stopActor(); },
|
2021-04-16 18:58:22 +00:00
|
|
|
message(t, line: string) {
|
|
|
|
if (line.toLowerCase().startsWith('/nick ')) {
|
|
|
|
updateUsername(t, line.slice(5).trimLeft());
|
|
|
|
} else {
|
|
|
|
t.message(ds, fromSays(Says({ who: username, what: line })));
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
2021-04-15 18:07:39 +00:00
|
|
|
}
|