translation-terrace/app/lib/conversation.ts

77 lines
2.3 KiB
TypeScript

import { Translator } from "../i18n/api";
export type Speaker = {
id: "host" | "guest",
language : string,
}
export class Message {
public translation? : string;
public onTextUpdate?: (message: Message) => void;
public onTextDone?: (message: Message) => Promise<void>;
public onTranslationDone?: (message: Message) => void;
constructor (public conversation : Conversation, public speaker : Speaker, public text? : string) {}
get otherSpeaker() {
return this.speaker.id === this.conversation.host.id ? this.conversation.guest : this.conversation.host
}
get otherLanguage() {
return this.otherSpeaker.language
}
public async translate() {
const translator = this.conversation.translator
if (!this.text) throw new Error("No text")
console.log("Translating from %s -> %s", this.speaker.language, this.otherSpeaker.language);
this.translation = await translator.translate(this.text, this.otherLanguage);
this.onTranslationDone && this.onTranslationDone(this)
}
}
type conversation_event_t = "add_message" | "translation_done"
type conversation_callback_t = (conversation : Conversation) => any;
export class Conversation extends Array<Message> {
public onAddMessage? : (conversation : Conversation) => any;
public onTranslationDone? : (conversation : Conversation) => any;
constructor (
public translator : Translator,
public host : Speaker,
public guest : Speaker,
) {
super();
}
public on(event : conversation_event_t, callback : conversation_callback_t) {
if (event === "add_message") {
this.onAddMessage = callback;
}
if (event === "translation_done") {
this.onTranslationDone = callback;
}
}
public addMessage(speaker : Speaker, text? : string) {
this.push(new Message(this, speaker, text));
}
public async translateMessage(i : number) {
if (!this[i]) throw new Error(`${i} is not a valid message number`);
console.log(`Translating sentence to %s: %s`, this[i].otherLanguage, this[i].text)
await this[i].translate();
}
get lastMessage() {
return this[this.length-1]
}
public async translateLast() {
return await this.translateMessage(this.length-1);
}
}