mapcomplete/Logic/Web/Hash.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

53 lines
1.4 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
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 if there is any
2021-01-08 18:02:07 +01:00
* @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
2021-03-12 14:14:56 +01:00
history.pushState({}, "")
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
}
2020-11-17 02:22:48 +01:00
return hash
}
}