forked from connectrpc/examples-es
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebclient.ts
71 lines (56 loc) · 1.9 KB
/
webclient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { createPromiseClient } from "@connectrpc/connect";
import { createConnectTransport } from "@connectrpc/connect-web";
import { ElizaService } from "./gen/connectrpc/eliza/v1/eliza_connect.js";
import { IntroduceRequest } from "./gen/connectrpc/eliza/v1/eliza_pb.js";
let introFinished = false;
// Make the Eliza Service client
const client = createPromiseClient(
ElizaService,
createConnectTransport({
baseUrl: "http://localhost:3000",
})
);
// Query for the common elements and cache them.
const containerEl = document.getElementById(
"conversation-container"
) as HTMLDivElement;
const inputEl = document.getElementById("user-input") as HTMLInputElement;
// Add an event listener to the input so that the user can hit enter and click the Send button
document.getElementById("user-input")?.addEventListener("keyup", (event) => {
event.preventDefault();
if (event.key === "Enter") {
document.getElementById("send-button")?.click();
}
});
// Adds a node to the DOM representing the conversation with Eliza
function addNode(text: string, sender: string): void {
const divEl = document.createElement("div");
const pEl = document.createElement("p");
const respContainerEl = containerEl.appendChild(divEl);
respContainerEl.className = `${sender}-resp-container`;
const respTextEl = respContainerEl.appendChild(pEl);
respTextEl.className = "resp-text";
respTextEl.innerText = text;
}
async function send() {
const sentence = inputEl?.value ?? "";
addNode(sentence, "user");
inputEl.value = "";
if (introFinished) {
const response = await client.say({
sentence,
});
addNode(response.sentence, "eliza");
} else {
const request = new IntroduceRequest({
name: sentence,
});
for await (const response of client.introduce(request)) {
addNode(response.sentence, "eliza");
}
introFinished = true;
}
}
export function handleSend() {
send();
}