0
0
Fork 0
mirror of https://github.com/VueTubeApp/VueTube synced 2024-11-26 13:13:03 +00:00
VueTube/NUXT/plugins/classes/backHander.js

67 lines
2 KiB
JavaScript
Raw Normal View History

2022-05-02 04:01:48 +00:00
import { App as CapacitorApp } from "@capacitor/app";
import { Capacitor } from "@capacitor/core";
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.
if (Capacitor.getPlatform() != "web") this.startUp(); // Only run on native platforms.
2022-05-04 03:29:29 +00:00
}
startUp() {
this.reset();
2022-05-03 11:07:40 +00:00
// Add a listener for the back button.
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(() => {
() => {
this.garbageCollect;
};
2022-05-03 11:07:40 +00:00
}, 5 * 60 * 1000);
}
reset() {
this.backStack = [];
}
back({ canGoBack }) {
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
}
}