@etsoo/appscript
Version:
Applications shared TypeScript framework
90 lines (89 loc) • 2.57 kB
JavaScript
import { ExtendUtils } from "@etsoo/shared";
import { BridgeHostName } from "./IBridgeHost";
/**
* Flutter JavaScript Host
* https://inappwebview.dev/docs/javascript/communication/
*/
export class FlutterHost {
/**
* Constructor
* @param callHandler Call handler
*/
constructor(host) {
this.host = host;
/**
* Name
*/
this.name = BridgeHostName.Flutter;
/**
* Cached commands
*/
this.cachedCommands = {};
window.addEventListener("flutterInAppWebViewPlatformReady", (_event) => {
if (this.host.callHandler == null)
return;
for (const key in this.cachedCommands) {
// Args
const args = this.cachedCommands[key];
// Execute
this.host.callHandler(key, ...args);
// Remove the key
delete this.cachedCommands[key];
}
});
}
cacheCommand(name, ...args) {
this.cachedCommands[name] = args;
}
changeCulture(locale) {
if (this.host.callHandler)
this.host.callHandler("changeCulture", locale);
else
this.cacheCommand("changeCulture", locale);
}
closable() {
return false;
}
exit() {
if (this.host.callHandler)
this.host.callHandler("exit");
else
this.cacheCommand("exit");
}
async getLabels(...keys) {
// Try 500 miliseconds
let count = 5;
while (this.host.callHandler == null) {
count--;
await ExtendUtils.sleep(100);
if (count === 0)
break;
}
const init = {};
if (this.host.callHandler == null)
return init;
const result = (await this.host.callHandler("getLabels")) ?? {};
return keys.reduce((a, v) => ({
...a,
[v]: result[v] ?? ""
}), init);
}
getStartUrl() {
return this.startUrl;
}
loadApp(name, startUrl) {
this.startUrl = startUrl;
if (this.host.callHandler)
this.host.callHandler("loadApp", name, startUrl);
else
this.cacheCommand("loadApp", name, startUrl);
}
userAuthorization(authorized) {
if (this.host.callHandler)
this.host.callHandler("userAuthorization", authorized);
else
this.cacheCommand("userAuthorization", authorized);
}
onUpdate(func) { }
setTitle(title) { }
}