VueTube/NUXT/plugins/classes/backHander.js

56 lines
1.7 KiB
JavaScript
Raw Normal View History

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.
// Add a listener for the back button.
this.backHandler = CapacitorApp.addListener("backButton", this.back);
// Start garbage collection. Run every 5 minutes.
setInterval(() => {
this.garbageCollect();
}, 5 * 60 * 1000);
}
reset() {
this.backStack = [];
}
back({ canGoBack }) {
// 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
}
}