2020-11-17 02:22:48 +01:00
|
|
|
import {UIEventSource} from "../UIEventSource";
|
2021-01-06 02:21:50 +01:00
|
|
|
import {Utils} from "../../Utils";
|
2020-11-17 02:22:48 +01:00
|
|
|
|
2021-03-12 14:14:56 +01:00
|
|
|
/**
|
|
|
|
* Wrapper around the hash to create an UIEventSource from it
|
|
|
|
*/
|
2020-11-17 02:22:48 +01:00
|
|
|
export default class Hash {
|
2021-01-08 18:02:07 +01:00
|
|
|
|
|
|
|
public static hash: UIEventSource<string> = Hash.Get();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the current string, including the pound sign
|
|
|
|
* @constructor
|
|
|
|
*/
|
|
|
|
public static Current(): string {
|
|
|
|
if (Hash.hash.data === undefined || Hash.hash.data === "") {
|
|
|
|
return ""
|
|
|
|
} else {
|
|
|
|
return "#" + Hash.hash.data;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static Get(): UIEventSource<string> {
|
|
|
|
if (Utils.runningFromConsole) {
|
2021-01-06 02:21:50 +01:00
|
|
|
return new UIEventSource<string>(undefined);
|
|
|
|
}
|
2020-11-17 02:22:48 +01:00
|
|
|
const hash = new UIEventSource<string>(window.location.hash.substr(1));
|
|
|
|
hash.addCallback(h => {
|
2021-04-25 13:25:03 +02:00
|
|
|
console.trace("Hash was changed into ",h)
|
2021-01-08 18:02:07 +01:00
|
|
|
if (h === "undefined") {
|
|
|
|
console.warn("Got a literal 'undefined' as hash, ignoring")
|
|
|
|
h = undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (h === undefined || h === "") {
|
2021-01-06 02:09:04 +01:00
|
|
|
window.location.hash = "";
|
|
|
|
return;
|
|
|
|
}
|
2021-01-08 18:02:07 +01:00
|
|
|
|
2021-03-12 14:14:56 +01:00
|
|
|
history.pushState({}, "")
|
2021-01-06 02:09:04 +01:00
|
|
|
window.location.hash = "#" + h;
|
2020-11-17 02:22:48 +01:00
|
|
|
});
|
2021-01-08 18:02:07 +01:00
|
|
|
|
|
|
|
|
2020-11-17 02:22:48 +01:00
|
|
|
window.onhashchange = () => {
|
2021-01-08 18:02:07 +01:00
|
|
|
let newValue = window.location.hash.substr(1);
|
|
|
|
if (newValue === "") {
|
|
|
|
newValue = undefined;
|
|
|
|
}
|
|
|
|
hash.setData(newValue)
|
2020-11-17 02:22:48 +01:00
|
|
|
}
|
2021-03-12 14:52:34 +01:00
|
|
|
|
2021-03-13 17:25:44 +01:00
|
|
|
window.addEventListener('popstate', _ => {
|
2021-03-12 14:52:34 +01:00
|
|
|
let newValue = window.location.hash.substr(1);
|
|
|
|
if (newValue === "") {
|
|
|
|
newValue = undefined;
|
|
|
|
}
|
|
|
|
hash.setData(newValue)
|
|
|
|
})
|
2021-01-08 18:02:07 +01:00
|
|
|
|
2020-11-17 02:22:48 +01:00
|
|
|
return hash;
|
|
|
|
}
|
2021-01-08 18:02:07 +01:00
|
|
|
|
2020-11-17 02:22:48 +01:00
|
|
|
}
|