novy-syndicate/src/examples/simple-chat.ts

43 lines
1.4 KiB
TypeScript

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";
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, $Present, during(async (_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}`);
},
});
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 })));
}
},
});
}