43 lines
1.5 KiB
TypeScript
43 lines
1.5 KiB
TypeScript
import { $Present, $Says, fromPresent, fromSays, Present, Says } from "../gen/simpleChatProtocol.js";
|
|
import { during, observe, P } from "../runtime/dataspace.js";
|
|
import { Assertion, Handle, Ref, Turn } from "../runtime/actor.js";
|
|
import { attachReadline } from './readline.js';
|
|
import { Embedded } from "@preserves/core";
|
|
|
|
export default function (t: Turn, ds_ptr: Embedded<Ref>) {
|
|
const ds = ds_ptr.embeddedValue;
|
|
|
|
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, P.rec($Present, P.bind()), during(async (_t, bindings) => {
|
|
const [username] = bindings as [string];
|
|
console.log(`${username} arrived`);
|
|
return (_t) => console.log(`${username} departed`);
|
|
}));
|
|
|
|
observe(t, ds, P.rec($Says, P.bind(), P.bind()), {
|
|
message(_t: Turn, bindings: Assertion): void {
|
|
const [who, what] = bindings as [string, string];
|
|
console.log(`${who}: ${what}`);
|
|
},
|
|
});
|
|
|
|
attachReadline(t, {
|
|
retract(t) { t.stopActor(); },
|
|
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 })));
|
|
}
|
|
},
|
|
});
|
|
}
|