@talkjs/expo
Version:
Official TalkJS SDK for React Native (Expo)
122 lines (113 loc) • 3.41 kB
JavaScript
"use strict";
import { SELECT_CONVERSATION_EVENT, SEND_MESSAGE_EVENT } from './constants';
import { Subscription } from './EventSubscription';
export class TalkHandlers {
#subscriptions;
#handlers;
#injectJavaScript;
constructor(injectJavaScript) {
this.#handlers = {};
this.#subscriptions = {};
this.#injectJavaScript = injectJavaScript;
}
off(event) {
const subscription = this.#subscriptions[event];
if (subscription) {
subscription.unsubscribe();
}
}
add(event, object, handler) {
const subscription = new Subscription(this.#injectJavaScript);
this.#subscriptions[event] = subscription;
const variableName = subscription._variableName;
if (event === SEND_MESSAGE_EVENT) {
this.#handlers[variableName] = (eventObj, data) => {
let hasOverriden = false;
const override = params => {
if (hasOverriden) {
console.error('Cannot call SendMessageEvent.override asynchronously');
return;
}
hasOverriden = true;
const key = data['key'];
this.#injectJavaScript(`
window.overrides[${key}]({
text: ${JSON.stringify(params.text)},
custom: ${JSON.stringify(params.custom)},
cancel: ${JSON.stringify(params.cancel)}
});
delete window.overrides[${key}];
true;
`);
};
eventObj['override'] = override;
handler(eventObj);
if (!hasOverriden) {
// We call it ourselves, since override in the webview has a promise waiting.
// No need to wait for the 5 second timeout.
override({});
}
};
} else {
this.#handlers[variableName] = handler;
}
if (event === SELECT_CONVERSATION_EVENT) {
this.#injectJavaScript(`
${variableName} = ${object}.${event}((eventObj) => {
eventObj.preventDefault();
// Deselect the selected conversation.
${object}.select(null);
sendToReactNative("${event}", {id: "${variableName}", eventObj});
});
true;
`);
} else if (event === SEND_MESSAGE_EVENT) {
this.#injectJavaScript(`
window.overrides = {};
${variableName} = ${object}.${event}((eventObj) => {
const key = Date.now();
eventObj.override(new Promise((resolve) => {
window.overrides[key] = resolve;
}));
const data = { key };
sendToReactNative("${event}", {id: "${variableName}", eventObj, data });
});
true;
`);
} else {
this.#injectJavaScript(`
${variableName} = ${object}.${event}((eventObj) => {
sendToReactNative("${event}", {id: "${variableName}", eventObj});
});
true;
`);
}
return subscription;
}
process(webViewEvent) {
const {
id,
eventObj,
data
} = webViewEvent;
this.#handlers[id](eventObj, data);
}
}
export class CustomHandlers {
#handlers;
constructor() {
this.#handlers = {};
}
process(event, data) {
const handlers = this.#handlers[event] ?? [];
handlers.forEach(handler => handler(data));
}
add(event, handler) {
if (event in this.#handlers) {
this.#handlers[event].push(handler);
} else {
this.#handlers[event] = [handler];
}
}
}
//# sourceMappingURL=Handlers.js.map