2021-03-06 15:26:07 +01:00
|
|
|
import {ChatEvent, isChatEvent} from "./Api/Events/ChatEvent";
|
|
|
|
import {isIframeEventWrapper} from "./Api/Events/IframeEvent";
|
|
|
|
import {isUserInputChatEvent, UserInputChatEvent} from "./Api/Events/UserInputChatEvent";
|
|
|
|
import {Subject} from "rxjs";
|
2021-03-05 16:50:54 +01:00
|
|
|
|
2021-03-04 19:00:00 +01:00
|
|
|
interface WorkAdventureApi {
|
|
|
|
sendChatMessage(message: string, author: string): void;
|
2021-03-05 16:50:54 +01:00
|
|
|
onChatMessage(callback: (message: string) => void): void;
|
2021-03-04 19:00:00 +01:00
|
|
|
}
|
|
|
|
|
2021-03-05 16:50:54 +01:00
|
|
|
declare global {
|
|
|
|
// eslint-disable-next-line no-var
|
|
|
|
var WA: WorkAdventureApi
|
|
|
|
}
|
2021-03-04 19:00:00 +01:00
|
|
|
|
2021-03-06 15:26:07 +01:00
|
|
|
type ChatMessageCallback = (message: string) => void;
|
|
|
|
|
|
|
|
const userInputChatStream: Subject<UserInputChatEvent> = new Subject();
|
|
|
|
|
|
|
|
|
2021-03-04 19:00:00 +01:00
|
|
|
window.WA = {
|
|
|
|
/**
|
2021-03-05 16:50:54 +01:00
|
|
|
* Send a message in the chat.
|
2021-03-04 19:00:00 +01:00
|
|
|
* Only the local user will receive this message.
|
|
|
|
*/
|
|
|
|
sendChatMessage(message: string, author: string) {
|
|
|
|
window.parent.postMessage({
|
|
|
|
'type': 'chat',
|
|
|
|
'data': {
|
|
|
|
'message': message,
|
|
|
|
'author': author
|
2021-03-05 16:50:54 +01:00
|
|
|
} as ChatEvent
|
2021-03-04 19:00:00 +01:00
|
|
|
}, '*');
|
2021-03-05 16:50:54 +01:00
|
|
|
},
|
|
|
|
/**
|
|
|
|
* Listen to messages sent by the local user, in the chat.
|
|
|
|
*/
|
2021-03-06 15:26:07 +01:00
|
|
|
onChatMessage(callback: ChatMessageCallback): void {
|
|
|
|
userInputChatStream.subscribe((userInputChatEvent) => {
|
|
|
|
callback(userInputChatEvent.message);
|
|
|
|
});
|
2021-03-04 19:00:00 +01:00
|
|
|
}
|
|
|
|
}
|
2021-03-06 15:26:07 +01:00
|
|
|
|
|
|
|
window.addEventListener('message', message => {
|
|
|
|
if (message.source !== window.parent) {
|
|
|
|
console.log('MESSAGE SKIPPED!!!')
|
|
|
|
return; // Skip message in this event listener
|
|
|
|
}
|
|
|
|
|
|
|
|
const payload = message.data;
|
|
|
|
if (isIframeEventWrapper(payload)) {
|
|
|
|
if (payload.type === 'userInputChat' && isUserInputChatEvent(payload.data)) {
|
|
|
|
userInputChatStream.next(payload.data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ...
|
|
|
|
});
|