2022-05-02 04:01:48 +00:00
|
|
|
import { App as CapacitorApp } from "@capacitor/app";
|
2022-05-03 11:07:40 +00:00
|
|
|
import backType from "./backType";
|
2022-05-02 04:01:48 +00:00
|
|
|
export default class backHandler {
|
2022-05-03 11:07:40 +00:00
|
|
|
constructor() {
|
|
|
|
this.backStack = []; // This should only contain instances of backType. Any other type will be ignored.
|
2022-05-04 03:29:29 +00:00
|
|
|
this.startUp();
|
|
|
|
}
|
|
|
|
|
|
|
|
startUp() {
|
|
|
|
this.reset();
|
2022-05-03 11:07:40 +00:00
|
|
|
|
|
|
|
// Add a listener for the back button.
|
2022-05-04 03:29:29 +00:00
|
|
|
this.backHandler = CapacitorApp.addListener("backButton", (context) => { this.back(context) });
|
2022-05-03 11:07:40 +00:00
|
|
|
|
|
|
|
// Start garbage collection. Run every 5 minutes.
|
|
|
|
setInterval(() => {
|
2022-05-04 03:29:29 +00:00
|
|
|
() => { this.garbageCollect };
|
2022-05-03 11:07:40 +00:00
|
|
|
}, 5 * 60 * 1000);
|
|
|
|
}
|
|
|
|
|
|
|
|
reset() {
|
|
|
|
this.backStack = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
back({ canGoBack }) {
|
2022-05-04 03:29:29 +00:00
|
|
|
console.log("backStack", this.backStack)
|
2022-05-03 11:07:40 +00:00
|
|
|
// Check if backStack contains any backType objects. If so, call the goBack() function.
|
|
|
|
if (this.backStack.length > 0) {
|
|
|
|
// Loop through the backStack array.
|
|
|
|
let lastResult = false;
|
|
|
|
while (!lastResult && this.backStack.length > 0) {
|
|
|
|
const backAction = this.backStack.pop();
|
|
|
|
lastResult = backAction.goBack();
|
|
|
|
}
|
|
|
|
// Since a function was successfully called, no need to continue.
|
|
|
|
if (lastResult) return;
|
|
|
|
}
|
|
|
|
if (!canGoBack) {
|
|
|
|
// If we can't go back, then we should exit the app.
|
|
|
|
CapacitorApp.exitApp();
|
|
|
|
} else {
|
|
|
|
// If we can go back, then we should go back.
|
|
|
|
window.history.back();
|
2022-05-02 04:01:48 +00:00
|
|
|
}
|
2022-05-03 11:07:40 +00:00
|
|
|
}
|
2022-05-02 04:01:48 +00:00
|
|
|
|
2022-05-03 11:07:40 +00:00
|
|
|
addAction(callback) {
|
|
|
|
if (callback instanceof backType) {
|
|
|
|
this.backStack.push(callback);
|
|
|
|
} else {
|
|
|
|
throw new TypeError("backType object expected");
|
2022-05-02 04:01:48 +00:00
|
|
|
}
|
2022-05-03 11:07:40 +00:00
|
|
|
}
|
2022-05-02 04:01:48 +00:00
|
|
|
|
2022-05-03 11:07:40 +00:00
|
|
|
// Loops through the backStack array if array larger than 10. If backType.check() returns false, then remove it from the backStack array.
|
|
|
|
garbageCollect() {
|
|
|
|
if (this.backStack.length > 10) {
|
|
|
|
this.backStack = this.backStack.filter((backType) => backType.check());
|
2022-05-02 04:01:48 +00:00
|
|
|
}
|
2022-05-03 11:07:40 +00:00
|
|
|
}
|
|
|
|
}
|