mapcomplete/Logic/Web/Hash.ts

51 lines
1.3 KiB
TypeScript
Raw Normal View History

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
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-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 === "") {
window.location.hash = "";
return;
}
2021-01-08 18:02:07 +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-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
}