Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add frontend support for cancellation #34

Open
wants to merge 1 commit into
base: 05-many-futures-b
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/chatbot/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl Chatbot {
///
/// Warning: may take a few seconds!
pub async fn query_chat(&mut self, messages: &[String], docs: &[String]) -> Vec<String> {
std::thread::sleep(Duration::from_secs(2));
tokio::time::sleep(Duration::from_secs(2)).await;
let most_recent = messages.last().unwrap();
let emoji = &self.emojis[self.emoji_counter];
self.emoji_counter = (self.emoji_counter + 1) % self.emojis.len();
Expand Down
12 changes: 11 additions & 1 deletion crates/server/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ <h1>ChatABC</h1>
<form id="input">
<input type="text" />
<input type="submit" />
<button id="cancel" type="button">Cancel</button>
<span id="spinner"></span>
</form>
<div id="messages"></div>
Expand All @@ -35,6 +36,7 @@ <h1>ChatABC</h1>
let msgContainer = document.getElementById("messages");
let textEl = document.querySelector("form input[type=text]");
let spinnerEl = document.getElementById("spinner");
let cancelEl = document.getElementById("cancel");

async function fetchChat(chat) {
spinnerEl.classList.add("active");
Expand All @@ -46,7 +48,13 @@ <h1>ChatABC</h1>
body: JSON.stringify(chat)
});
if (!response.ok) throw new Error(response.statusText);
return await response.json();
let json = await response.json();
if (json.type === "Success") {
return json;
} else {
alert("Cancelled");
throw new Error("Cancelled");
}
} finally {
spinnerEl.classList.remove("active");
textEl.removeAttribute("disabled");
Expand All @@ -65,11 +73,13 @@ <h1>ChatABC</h1>
event.preventDefault();
chat.messages.push(textEl.value);
textEl.value = "";
updateChat(chat);
fetchChat(chat).then(updateChat);
}

function main() {
document.getElementById("input").addEventListener("submit", onSubmit);
cancelEl.addEventListener("click", () => fetch("/cancel", {method: "post"}));
}

main();
Expand Down
Loading