Files
faceclaw/app/apps/evenhub/webview.ios.ts
T

52 lines
2.8 KiB
TypeScript

import { EVENHUB_BRIDGE_INJECT_SCRIPT, buildFaceclawExtensionsScript, type EvenHubSession } from './session'
import { FACECLAW_VERSION } from '../../version'
import type { EvenHubWebView } from './webview'
declare const FaceclawEvenHubWebView: any
export const IOS_EVENHUB_TRANSPORT_SCRIPT = `
window.__faceclawEvenHub = { postMessage: function(name, args, id) {
window.webkit.messageHandlers.faceclaw.postMessage({kind:'call', name:name, args:args, id:id});
}};
(function() {
['log','warn','error'].forEach(function(level) {
var original = console[level];
console[level] = function() {
original.apply(console, arguments);
window.webkit.messageHandlers.faceclaw.postMessage({kind:'console', message:Array.prototype.map.call(arguments, String).join(' ').slice(0,4000)});
};
});
window.addEventListener('error', function(e) { console.error(e.message); });
window.addEventListener('unhandledrejection', function(e) { console.error(String(e.reason)); });
})();
`
export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
const host = FaceclawEvenHubWebView.new()
host.packageIdentifier = session.manifest.packageId
// The manager's close callback for the shown phone UI; the native back
// button hides the host itself and reports it as a 'hidden' event.
let onClose: (() => void) | null = null
host.eventHandler = (json: string) => {
try {
const event = JSON.parse(json)
if (event.kind === 'call' && typeof event.name === 'string' && typeof event.args === 'string' && Number.isSafeInteger(event.id))
session.handleBridgeCall(event.name, event.args, event.id)
else if (event.kind === 'loaded') session.webViewLoaded()
else if (event.kind === 'error') session.webViewFailed(String(event.message), event.fatal === true)
else if (event.kind === 'hidden') { const close = onClose; onClose = null; close?.() }
// 'notice': host-side events such as a blocked navigation, logged with the app's console.
else if (event.kind === 'console' || event.kind === 'notice') console.log(`[evenhub:${session.manifest.name}] ${event.message}`)
} catch (error) { console.warn(`EvenHub bridge: ${error}`) }
}
// Defer loading until manager.ts has attached the session/window handles.
const script = IOS_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`)
const loading = setTimeout(() => {
if (session.remoteUrl) host.startURLScript(session.remoteUrl, script)
else host.startEntrypointScript(session.distDir, session.manifest.entrypoint, script)
}, 0)
return { native: host, evaluateJs: js => host.evaluate(js),
destroy: () => { clearTimeout(loading); host.destroy() },
showOnPhone: close => { onClose = close; host.showOnPhone() },
hideOnPhone: () => { onClose = null; host.hideOnPhone() } }
}