Files
mkdocs-material/src/assets/javascripts/observables/agent/location/hash/index.ts
2020-02-19 11:07:34 +01:00

70 lines
2.3 KiB
TypeScript

/*
* Copyright (c) 2016-2020 Martin Donath <martin.donath@squidfunk.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import { Observable, fromEvent } from "rxjs"
import { filter, map, share } from "rxjs/operators"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Retrieve location hash
*
* @return Location hash
*/
export function getLocationHash(): string {
return location.hash
}
/**
* Set location hash
*
* This will force a reset of the location hash, inducing an anchor jump if
* the hash matches the `id` of an element. It is implemented outside of the
* whole RxJS architecture using `setTimeout` to keep it plain and simple.
*
* @param value - Location hash
*/
export function setLocationHash(value: string): void {
location.hash = ""
setTimeout(() => {
location.hash = value
}, 1)
}
/* ------------------------------------------------------------------------- */
/**
* Watch location hash
*
* @return Location hash observable
*/
export function watchLocationHash(): Observable<string> {
return fromEvent<HashChangeEvent>(window, "hashchange")
.pipe(
map(getLocationHash),
filter(hash => hash.length > 0),
share()
)
}