mapcomplete/Logic/Web/Hash.ts

63 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-11-17 01:22:48 +00:00
import {UIEventSource} from "../UIEventSource";
2021-01-06 01:21:50 +00:00
import {Utils} from "../../Utils";
2020-11-17 01:22:48 +00:00
2021-03-12 13:14:56 +00:00
/**
* Wrapper around the hash to create an UIEventSource from it
*/
2020-11-17 01:22:48 +00:00
export default class Hash {
2021-01-08 17:02:07 +00: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 01:21:50 +00:00
return new UIEventSource<string>(undefined);
}
2020-11-17 01:22:48 +00:00
const hash = new UIEventSource<string>(window.location.hash.substr(1));
hash.addCallback(h => {
2021-01-08 17:02:07 +00:00
if (h === "undefined") {
console.warn("Got a literal 'undefined' as hash, ignoring")
h = undefined;
}
if (h === undefined || h === "") {
window.location.hash = "";
return;
}
2021-01-08 17:02:07 +00:00
2021-03-12 13:14:56 +00:00
history.pushState({}, "")
window.location.hash = "#" + h;
2020-11-17 01:22:48 +00:00
});
2021-01-08 17:02:07 +00:00
2020-11-17 01:22:48 +00:00
window.onhashchange = () => {
2021-01-08 17:02:07 +00:00
let newValue = window.location.hash.substr(1);
if (newValue === "") {
newValue = undefined;
}
hash.setData(newValue)
2020-11-17 01:22:48 +00:00
}
window.addEventListener('popstate', _ => {
let newValue = window.location.hash.substr(1);
if (newValue === "") {
newValue = undefined;
}
hash.setData(newValue)
})
2021-01-08 17:02:07 +00:00
2020-11-17 01:22:48 +00:00
return hash;
}
2021-01-08 17:02:07 +00:00
2020-11-17 01:22:48 +00:00
}