Moved header to observable

This commit is contained in:
squidfunk 2019-11-20 15:13:42 +01:00
parent e457d901b2
commit 89214b1897
12 changed files with 275 additions and 68 deletions

5
package-lock.json generated
View File

@ -2166,6 +2166,11 @@
"array-find-index": "^1.0.1" "array-find-index": "^1.0.1"
} }
}, },
"custom-event-polyfill": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/custom-event-polyfill/-/custom-event-polyfill-1.0.7.tgz",
"integrity": "sha512-TDDkd5DkaZxZFM8p+1I3yAlvM3rSr1wbrOliG4yJiwinMZN8z/iGL7BTlDkrJcYTmgUSb4ywVCc3ZaUtOtC76w=="
},
"cyclist": { "cyclist": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/cyclist/-/cyclist-1.0.1.tgz", "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-1.0.1.tgz",

View File

@ -30,6 +30,7 @@
}, },
"dependencies": { "dependencies": {
"clipboard": "^2.0.0", "clipboard": "^2.0.0",
"custom-event-polyfill": "^1.0.7",
"escape-html": "^1.0.3", "escape-html": "^1.0.3",
"js-cookie": "^2.2.1", "js-cookie": "^2.2.1",
"lunr": "^2.3.6", "lunr": "^2.3.6",

View File

@ -21,10 +21,11 @@
*/ */
import { reduce, reverse } from "ramda" import { reduce, reverse } from "ramda"
import { Observable } from "rxjs" import { Observable, combineLatest } from "rxjs"
import { distinctUntilChanged, map, scan, shareReplay } from "rxjs/operators" import { distinctUntilChanged, map, scan, shareReplay } from "rxjs/operators"
import { ViewportOffset, getElement } from "../../ui" import { ViewportOffset, getElement } from "../../ui"
import { Header } from "../header"
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* Types * Types
@ -43,10 +44,11 @@ export interface Anchors {
* ------------------------------------------------------------------------- */ * ------------------------------------------------------------------------- */
/** /**
* Options * Watch options
*/ */
interface Options { interface WatchOptions {
offset$: Observable<ViewportOffset> /* Viewport offset observable */ offset$: Observable<ViewportOffset> /* Viewport offset observable */
header$: Observable<Header> /* Header observable */
} }
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
@ -92,28 +94,21 @@ export function resetAnchor(anchor: HTMLAnchorElement) {
/** /**
* Create an observable to monitor all anchors in respect to viewport offset * Create an observable to monitor all anchors in respect to viewport offset
* *
* @param anchors - Anchor elements * @param els - Anchor elements
* @param header - Header element
* @param options - Options * @param options - Options
* *
* @return Anchors observable * @return Anchors observable
*/ */
export function watchAnchors( export function watchAnchors(
anchors: HTMLAnchorElement[], header: HTMLElement, { offset$ }: Options els: HTMLAnchorElement[], { offset$, header$ }: WatchOptions
): Observable<Anchors> { ): Observable<Anchors> {
/* Adjust for header offset if fixed */
const adjust = getComputedStyle(header)
.getPropertyValue("position") === "fixed"
? 18 + header.offsetHeight
: 18
/* Build index to map anchors to their targets */ /* Build index to map anchors to their targets */
const index = new Map<HTMLAnchorElement, HTMLElement>() const index = new Map<HTMLAnchorElement, HTMLElement>()
for (const anchor of anchors) { for (const el of els) {
const target = getElement(decodeURIComponent(anchor.hash)) const target = getElement(decodeURIComponent(el.hash))
if (typeof target !== "undefined") if (typeof target !== "undefined")
index.set(anchor, target) index.set(el, target)
} }
/* Build table to map anchor paths to vertical offsets */ /* Build table to map anchor paths to vertical offsets */
@ -130,10 +125,16 @@ export function watchAnchors(
return path return path
}, [], [...index]) }, [], [...index])
/* Compute partition of done and next anchors */ /* Compute necessary adjustment for header */
const partition$ = offset$ const adjust$ = header$
.pipe( .pipe(
scan(([done, next], { y }) => { map(header => 18 + header.height)
)
/* Compute partition of done and next anchors */
const partition$ = combineLatest(offset$, adjust$)
.pipe(
scan(([done, next], [{ y }, adjust]) => {
/* Look forward */ /* Look forward */
while (next.length) { while (next.length) {
@ -168,8 +169,8 @@ export function watchAnchors(
return partition$ return partition$
.pipe( .pipe(
map(([done, next]) => ({ map(([done, next]) => ({
done: done.map(([els]) => els), done: done.map(([anchors]) => anchors),
next: next.map(([els]) => els) next: next.map(([anchors]) => anchors)
})), })),
shareReplay({ bufferSize: 1, refCount: true }) shareReplay({ bufferSize: 1, refCount: true })
) )

View File

@ -21,9 +21,10 @@
*/ */
import { Observable, combineLatest } from "rxjs" import { Observable, combineLatest } from "rxjs"
import { distinctUntilChanged, map, shareReplay } from "rxjs/operators" import { distinctUntilChanged, map, pluck, shareReplay } from "rxjs/operators"
import { ViewportOffset, ViewportSize } from "../../ui" import { ViewportOffset, ViewportSize } from "../../ui"
import { Header } from "../header"
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* Types * Types
@ -43,11 +44,12 @@ export interface Container {
* ------------------------------------------------------------------------- */ * ------------------------------------------------------------------------- */
/** /**
* Options * Watch options
*/ */
interface Options { interface WatchOptions {
size$: Observable<ViewportSize> /* Viewport size observable */ size$: Observable<ViewportSize> /* Viewport size observable */
offset$: Observable<ViewportOffset> /* Viewport offset observable */ offset$: Observable<ViewportOffset> /* Viewport offset observable */
header$: Observable<Header> /* Header observable */
} }
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
@ -60,28 +62,27 @@ interface Options {
* The container represents the main content area including the sidebars (table * The container represents the main content area including the sidebars (table
* of contents and navigation), as well as the actual page content. * of contents and navigation), as well as the actual page content.
* *
* @param container - Container element * @param el - Container element
* @param header - Header element
* @param options - Options * @param options - Options
* *
* @return Container observable * @return Container observable
*/ */
export function watchContainer( export function watchContainer(
container: HTMLElement, header: HTMLElement, { size$, offset$ }: Options el: HTMLElement, { size$, offset$, header$ }: WatchOptions
): Observable<Container> { ): Observable<Container> {
/* Adjust for header offset if fixed */ /* Compute necessary adjustment for header */
const adjust = getComputedStyle(header) const adjust$ = header$
.getPropertyValue("position") === "fixed" .pipe(
? header.offsetHeight pluck("height")
: 0 )
/* Compute the container's visible height */ /* Compute the container's visible height */
const height$ = combineLatest(offset$, size$) const height$ = combineLatest(offset$, size$, adjust$)
.pipe( .pipe(
map(([{ y }, { height }]) => { map(([{ y }, { height }, adjust]) => {
const top = container.offsetTop const top = el.offsetTop
const bottom = container.offsetHeight + top const bottom = el.offsetHeight + top
return height return height
- Math.max(0, top - y, adjust) - Math.max(0, top - y, adjust)
- Math.max(0, height + y - bottom) - Math.max(0, height + y - bottom)
@ -90,17 +91,17 @@ export function watchContainer(
) )
/* Compute whether the viewport offset is past the container's top */ /* Compute whether the viewport offset is past the container's top */
const active$ = offset$ const active$ = combineLatest(offset$, adjust$)
.pipe( .pipe(
map(({ y }) => y >= container.offsetTop - adjust), map(([{ y }, adjust]) => y >= el.offsetTop - adjust),
distinctUntilChanged() distinctUntilChanged()
) )
/* Combine into a single hot observable */ /* Combine into a single hot observable */
return combineLatest(height$, active$) return combineLatest(height$, adjust$, active$)
.pipe( .pipe(
map(([height, active]) => ({ map(([height, adjust, active]) => ({
offset: container.offsetTop - adjust, offset: el.offsetTop - adjust,
height, height,
active active
})), })),

View File

@ -20,6 +20,21 @@
* IN THE SOFTWARE. * IN THE SOFTWARE.
*/ */
import { Observable, of } from "rxjs"
import { shareReplay } from "rxjs/operators"
/* ----------------------------------------------------------------------------
* Types
* ------------------------------------------------------------------------- */
/**
* Header
*/
export interface Header {
sticky: boolean /* Header stickyness */
height: number /* Header visible height */
}
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* Functions * Functions
* ------------------------------------------------------------------------- */ * ------------------------------------------------------------------------- */
@ -44,3 +59,28 @@ export function setHeaderShadow(
export function resetHeader(header: HTMLElement): void { export function resetHeader(header: HTMLElement): void {
header.removeAttribute("data-md-state") header.removeAttribute("data-md-state")
} }
/* ------------------------------------------------------------------------- */
/**
* Create an observable to monitor the header
*
* @param header - Header element
*
* @return Header observable
*/
export function watchHeader(
header: HTMLElement
): Observable<Header> {
const sticky = getComputedStyle(header)
.getPropertyValue("position") === "fixed"
/* Return header as hot observable */
return of({
sticky,
height: sticky ? header.offsetHeight : 0
})
.pipe(
shareReplay({ bufferSize: 1, refCount: true })
)
}

View File

@ -74,7 +74,7 @@ export function watchNavigationIndex(
} }
} }
/* Return navigation index */ /* Return navigation index as hot observable */
return of(index) return of(index)
.pipe( .pipe(
shareReplay({ bufferSize: 1, refCount: true }) shareReplay({ bufferSize: 1, refCount: true })

View File

@ -44,9 +44,9 @@ export interface Sidebar {
* ------------------------------------------------------------------------- */ * ------------------------------------------------------------------------- */
/** /**
* Options * Watch options
*/ */
interface Options { interface WatchOptions {
container$: Observable<Container> /* Container observable */ container$: Observable<Container> /* Container observable */
offset$: Observable<ViewportOffset> /* Viewport offset observable */ offset$: Observable<ViewportOffset> /* Viewport offset observable */
} }
@ -58,35 +58,35 @@ interface Options {
/** /**
* Set sidebar height * Set sidebar height
* *
* @param sidebar - Sidebar HTML element * @param el - Sidebar HTML element
* @param height - Sidebar height * @param height - Sidebar height
*/ */
export function setSidebarHeight( export function setSidebarHeight(
sidebar: HTMLElement, height: number el: HTMLElement, height: number
): void { ): void {
sidebar.style.height = `${height}px` el.style.height = `${height}px`
} }
/** /**
* Set sidebar lock * Set sidebar lock
* *
* @param sidebar - Sidebar HTML element * @param el - Sidebar HTML element
* @param lock - Whether the sidebar is locked * @param lock - Whether the sidebar is locked
*/ */
export function setSidebarLock( export function setSidebarLock(
sidebar: HTMLElement, lock: boolean el: HTMLElement, lock: boolean
): void { ): void {
sidebar.setAttribute("data-md-state", lock ? "lock" : "") el.setAttribute("data-md-state", lock ? "lock" : "")
} }
/** /**
* Reset sidebar * Reset sidebar
* *
* @param sidebar - Sidebar HTML element * @param el - Sidebar HTML element
*/ */
export function resetSidebar(sidebar: HTMLElement): void { export function resetSidebar(el: HTMLElement): void {
sidebar.removeAttribute("data-md-state") el.removeAttribute("data-md-state")
sidebar.style.height = "" el.style.height = ""
} }
/* ------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */
@ -94,18 +94,18 @@ export function resetSidebar(sidebar: HTMLElement): void {
/** /**
* Create an observable to monitor the sidebar * Create an observable to monitor the sidebar
* *
* @param sidebar - Sidebar element * @param el - Sidebar element
* @param options - Options * @param options - Options
* *
* @return Sidebar observable * @return Sidebar observable
*/ */
export function watchSidebar( export function watchSidebar(
sidebar: HTMLElement, { container$, offset$ }: Options el: HTMLElement, { container$, offset$ }: WatchOptions
): Observable<Sidebar> { ): Observable<Sidebar> {
/* Adjust for internal container offset */ /* Adjust for internal container offset */
const adjust = parseFloat( const adjust = parseFloat(
getComputedStyle(sidebar.parentElement!) getComputedStyle(el.parentElement!)
.getPropertyValue("padding-top") .getPropertyValue("padding-top")
) )

View File

@ -0,0 +1,23 @@
/*
* Copyright (c) 2016-2019 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 "custom-event-polyfill"

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2016-2019 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.
*/
/* ----------------------------------------------------------------------------
* Helper functions
* ------------------------------------------------------------------------- */
/**
* Check if browser supports the `<details>` tag
*
* As this polyfill is executed at the end of `<body>`, not all checks from the
* original source were necessary, so the script was stripped down a little.
*
* @see https://bit.ly/2O1teyP - Original source
*
* @return Test result
*/
function isSupported(): boolean {
const details = document.createElement("details")
if (!("open" in details))
return false
/* Insert summary and append element */
details.innerHTML = "<summary>_</summary>_"
details.style.display = "block"
document.body.appendChild(details)
/* Measure height difference */
const h0 = details.offsetHeight
details.open = true
const h1 = details.offsetHeight
/* Remove element and return test result */
document.body.removeChild(details)
return h1 - h0 !== 0
}
/* ----------------------------------------------------------------------------
* Polyfill
* ------------------------------------------------------------------------- */
/* Execute polyfill when DOM is available */
document.addEventListener("DOMContentLoaded", () => {
if (isSupported())
return
/* Indicate presence of details polyfill */
document.documentElement.classList.add("no-details")
/* Retrieve all summaries and polyfill open/close functionality */
const summaries = document.querySelectorAll("details > summary")
summaries.forEach(summary => {
summary.addEventListener("click", ev => {
const details = summary.parentNode as HTMLElement
if (details.hasAttribute("open")) {
details.removeAttribute("open")
} else {
details.setAttribute("open", "")
}
})
})
})

View File

@ -0,0 +1,24 @@
/*
* Copyright (c) 2016-2019 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 "./custom-event"
import "./details"

View File

@ -35,13 +35,14 @@ import { toArray } from "../../utilities"
* @template T - Element type * @template T - Element type
* *
* @param selector - Query selector * @param selector - Query selector
* @param node - Node of reference
* *
* @return HTML element * @return HTML element
*/ */
export function getElement<T extends HTMLElement>( export function getElement<T extends HTMLElement>(
selector: string selector: string, node: ParentNode = document
): T | undefined { ): T | undefined {
return document.querySelector<T>(selector) || undefined return node.querySelector<T>(selector) || undefined
} }
/** /**
@ -50,13 +51,14 @@ export function getElement<T extends HTMLElement>(
* @template T - Element type * @template T - Element type
* *
* @param selector - Query selector * @param selector - Query selector
* @param node - Node of reference
* *
* @return HTML elements * @return HTML elements
*/ */
export function getElements<T extends HTMLElement>( export function getElements<T extends HTMLElement>(
selector: string selector: string, node: ParentNode = document
): T[] { ): T[] {
return toArray(document.querySelectorAll<T>(selector)) return toArray(node.querySelectorAll<T>(selector))
} }
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
@ -68,13 +70,15 @@ export function getElements<T extends HTMLElement>(
* *
* @template T - Element type * @template T - Element type
* *
* @param node - Node of reference
*
* @return HTML element observable * @return HTML element observable
*/ */
export function withElement< export function withElement<T extends HTMLElement>(
T extends HTMLElement node: ParentNode = document
>(): OperatorFunction<string, T> { ): OperatorFunction<string, T> {
return pipe( return pipe(
map(selector => getElement<T>(selector)!), map(selector => getElement<T>(selector, node)!),
filter<T>(Boolean) filter<T>(Boolean)
) )
} }
@ -84,12 +88,14 @@ export function withElement<
* *
* @template T - Element type * @template T - Element type
* *
* @param node - Node of reference
*
* @return HTML elements observable * @return HTML elements observable
*/ */
export function withElements< export function withElements<T extends HTMLElement>(
T extends HTMLElement node: ParentNode = document
>(): OperatorFunction<string, T[]> { ): OperatorFunction<string, T[]> {
return pipe( return pipe(
map(selector => getElements<T>(selector)) map(selector => getElements<T>(selector, node))
) )
} }

25
typings/dom.d.ts vendored Normal file
View File

@ -0,0 +1,25 @@
/*
* Copyright (c) 2016-2019 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.
*/
interface CSSStyleDeclaration {
webkitOverflowScrolling: "touch" | ""
}