@virtualstate/app-history
Version:
Native JavaScript [app-history](https://github.com/WICG/app-history) implementation
83 lines • 2.78 kB
JavaScript
import { AppHistoryLocation, AppLocationAwaitFinished, AppLocationTransitionURL } from "./location.js";
import { InvalidStateError } from "./app-history-errors.js";
/**
* @experimental
*/
export class AppHistoryHistory extends AppHistoryLocation {
#options;
#appHistory;
constructor(options) {
super(options);
this.#options = options;
this.#appHistory = options.appHistory;
}
get length() {
return this.#appHistory.entries().length;
}
scrollRestoration = "manual";
get state() {
return this.#appHistory.current.getState();
}
async back() {
const entries = this.#appHistory.entries();
const index = this.#appHistory.current?.index ?? -1;
const back = entries[index - 1];
if (!back)
throw new InvalidStateError("Cannot go back");
return this[AppLocationTransitionURL](back.url, () => this.#appHistory.back());
}
async forward() {
const entries = this.#appHistory.entries();
const index = this.#appHistory.current?.index ?? -1;
const forward = entries[index + 1];
if (!forward)
throw new InvalidStateError("Cannot go forward");
return this[AppLocationTransitionURL](forward.url, () => this.#appHistory.forward());
}
async go(delta) {
if (typeof delta !== "number" || delta === 0 || isNaN(delta)) {
return this[AppLocationAwaitFinished](this.#appHistory.reload());
}
const entries = this.#appHistory.entries();
const { current: { index } } = this.#appHistory;
const nextIndex = index + delta;
const nextEntry = entries[nextIndex];
if (!nextEntry) {
throw new Error(`Could not go ${delta}`);
}
const nextEntryKey = nextEntry.key;
return this[AppLocationAwaitFinished](this.#appHistory.goTo(nextEntryKey));
}
async replaceState(data, unused, url) {
if (url) {
return this[AppLocationTransitionURL](url, (url) => this.#appHistory.navigate(url.toString(), {
state: data,
replace: true
}));
}
else {
return this.#appHistory.updateCurrent({
state: data
});
}
}
async pushState(data, unused, url) {
if (url) {
return this[AppLocationTransitionURL](url, (url) => this.#appHistory.navigate(url.toString(), {
state: data
}));
}
else {
return this.#appHistory.updateCurrent({
state: data
});
}
}
}
/**
* @experimental
* @internal
*/
export class AppHistorySync extends AppHistoryHistory {
}
//# sourceMappingURL=history.js.map