UNPKG

lepont

Version:

A native <-> browser (webview) bridge library for react-native

82 lines 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); function useBridge(...options) { const [registry] = react_1.useState(() => new Registry()); react_1.useEffect(() => { registry.clear(); options.forEach(option => option(registry)); }, [registry, ...options]); return [registry.ref, registry.onMessage, { registry }]; } exports.useBridge = useBridge; class Registry { constructor() { this.webView = null; this.registry = {}; this.ref = (webView) => { this.webView = webView; }; this.clear = () => { this.registry = {}; }; this.onMessage = async (e) => { const data = JSON.parse(e.nativeEvent.data); const { id, message } = data; const { type, payload } = message; if (!type) { this.send({ type: 'result', id, message: { type, payload: undefined }, error: { message: `Message type cannot be empty: ${type} is given` } }); return; } const registrant = this.registry[type]; if (!registrant) { this.send({ type: 'result', id, message: { type, payload: undefined }, error: { message: `No entry for message type: ${type}` } }); return; } try { const res = await registrant(payload, this); this.send({ type: 'result', id, message: { type, payload: res } }); } catch (e) { this.send({ type: 'result', id, message: { type, payload: undefined }, error: { message: e.message } }); } }; } register(type, handler) { this.registry[type] = handler; } sendMessage(message) { this.send({ type: 'event', message }); } send(p) { if (!this.webView) { console.error('webView for lepont registry is not ready!'); return; } this.webView.injectJavaScript(`LePont.recv(${JSON.stringify(p)})`); } } exports.Registry = Registry; //# sourceMappingURL=index.js.map