Inverted toggle logic and fixed ref counting of subscriptions

This commit is contained in:
squidfunk 2019-11-18 21:24:56 +01:00
parent a03fa479b8
commit b49ae6f679
8 changed files with 206 additions and 98 deletions

View File

@ -22,12 +22,7 @@
import { reduce, reverse } from "ramda" import { reduce, reverse } from "ramda"
import { Observable } from "rxjs" import { Observable } from "rxjs"
import { import { distinctUntilChanged, map, scan, shareReplay } from "rxjs/operators"
distinctUntilChanged,
map,
scan,
shareReplay
} from "rxjs/operators"
import { ViewportOffset, getElement } from "../../ui" import { ViewportOffset, getElement } from "../../ui"
@ -39,7 +34,7 @@ import { ViewportOffset, getElement } from "../../ui"
* Anchors * Anchors
*/ */
export interface Anchors { export interface Anchors {
past: HTMLAnchorElement[][] /* Past anchors */ done: HTMLAnchorElement[][] /* Read anchors */
next: HTMLAnchorElement[][] /* Next anchors */ next: HTMLAnchorElement[][] /* Next anchors */
} }
@ -101,7 +96,7 @@ export function resetAnchor(anchor: HTMLAnchorElement) {
* @param header - Header element * @param header - Header element
* @param options - Options * @param options - Options
* *
* @return Sidebar observable * @return Anchors observable
*/ */
export function watchAnchors( export function watchAnchors(
anchors: HTMLAnchorElement[], header: HTMLElement, { offset$ }: Options anchors: HTMLAnchorElement[], header: HTMLElement, { offset$ }: Options
@ -123,7 +118,7 @@ export function watchAnchors(
/* Build table to map anchor paths to vertical offsets */ /* Build table to map anchor paths to vertical offsets */
const table = new Map<HTMLAnchorElement[], number>() const table = new Map<HTMLAnchorElement[], number>()
reduce((path, [anchor, target]) => { reduce((path: HTMLAnchorElement[], [anchor, target]) => {
while (path.length) { while (path.length) {
const last = index.get(path[path.length - 1])! const last = index.get(path[path.length - 1])!
if (last.tagName >= target.tagName) if (last.tagName >= target.tagName)
@ -133,49 +128,46 @@ export function watchAnchors(
} }
table.set(reverse(path = [...path, anchor]), target.offsetTop) table.set(reverse(path = [...path, anchor]), target.offsetTop)
return path return path
}, [] as HTMLAnchorElement[], [...index]) }, [], [...index])
/* Compute partition of past and next anchors */ /* Compute partition of done and next anchors */
const partition$ = offset$ const partition$ = offset$
.pipe( .pipe(
scan(([past, next], { y }) => { scan(([done, next], { y }) => {
y = y + adjust
/* Look forward */ /* Look forward */
while (next.length) { while (next.length) {
const [, offset] = next[0] const [, offset] = next[0]
if (offset < y) { if (offset - adjust < y) {
past = [...past, next.shift()!] done = [...done, next.shift()!]
} else { } else {
break break
} }
} }
/* Look backward */ /* Look backward */
while (past.length) { while (done.length) {
const [, offset] = past[past.length - 1] const [, offset] = done[done.length - 1]
if (offset >= y) { if (offset - adjust >= y) {
next = [past.pop()!, ...next] next = [done.pop()!, ...next]
} else { } else {
break break
} }
} }
/* Return new partition */ /* Return partition */
return [past, next] return [done, next]
}, [[], [...table]]), }, [[], [...table]]),
distinctUntilChanged(([a0, a1], [b0, b1]) => { distinctUntilChanged((a, b) => a[0] === b[0] && a[1] === b[1])
return a0 === b0 && a1 === b1
})
) )
/* Extract anchors and return hot observable */ /* Extract anchors and return hot observable */
return partition$ return partition$
.pipe( .pipe(
map(([past, next]) => ({ map(([done, next]) => ({
past: past.map(([els]) => els), done: done.map(([els]) => els),
next: next.map(([els]) => els) next: next.map(([els]) => els)
})), })),
shareReplay(1) shareReplay({ bufferSize: 1, refCount: true })
) )
} }

View File

@ -104,6 +104,6 @@ export function watchContainer(
height, height,
active active
})), })),
shareReplay(1) shareReplay({ bufferSize: 1, refCount: true })
) )
} }

View File

@ -0,0 +1,46 @@
/*
* 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.
*/
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Set header shadow
*
* @param header - Header HTML element
* @param shadow - Shadow
*/
export function setHeaderShadow(
header: HTMLElement, shadow: boolean
): void {
header.setAttribute("data-md-state", shadow ? "shadow" : "")
}
/**
* Reset header
*
* @param header - Header HTML element
*/
export function resetHeader(header: HTMLElement): void {
header.removeAttribute("data-md-state")
}

View File

@ -108,7 +108,7 @@ export function watchSidebar(
.getPropertyValue("padding-top") .getPropertyValue("padding-top")
) )
/* Compute the sidebars's available height */ /* Compute the sidebar's available height */
const height$ = combineLatest(offset$, container$) const height$ = combineLatest(offset$, container$)
.pipe( .pipe(
map(([{ y }, { offset, height }]) => { map(([{ y }, { offset, height }]) => {
@ -127,6 +127,6 @@ export function watchSidebar(
return combineLatest(height$, lock$) return combineLatest(height$, lock$)
.pipe( .pipe(
map(([height, lock]) => ({ height, lock })), map(([height, lock]) => ({ height, lock })),
shareReplay(1) shareReplay({ bufferSize: 1, refCount: true })
) )
} }

View File

@ -20,32 +20,43 @@
* IN THE SOFTWARE. * IN THE SOFTWARE.
*/ */
import { animationFrameScheduler, interval, of } from "rxjs" import { difference } from "ramda"
import { concatMap, concatMapTo, filter, finalize, mapTo, mergeMap, skipUntil, startWith, switchMap, takeUntil, tap, throttleTime, windowToggle } from "rxjs/operators"
import { import {
fromContainer, distinctUntilKeyChanged,
fromSidebar, finalize,
map,
pairwise,
startWith
} from "rxjs/operators"
import {
resetAnchor,
resetSidebar,
setAnchorActive,
setAnchorBlur,
setHeaderShadow,
setSidebarHeight, setSidebarHeight,
setSidebarLock, setSidebarLock,
unsetSidebarHeight, watchAnchors,
unsetSidebarLock, watchContainer,
withToggle watchSidebar
} from "./component" } from "./component"
import { import {
fromMediaQuery,
fromViewportOffset,
fromViewportSize,
getElement, getElement,
withMediaQuery, getElements,
watchMedia,
watchViewportOffset,
watchViewportSize
} from "./ui" } from "./ui"
import { toggle } from "./utilities"
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
const offset$ = fromViewportOffset() const offset$ = watchViewportOffset()
const size$ = fromViewportSize() const size$ = watchViewportSize()
const screenAndAbove$ = fromMediaQuery("(min-width: 1220px)") const screen$ = watchMedia("(min-width: 1220px)")
const tabletAndAbove$ = fromMediaQuery("(min-width: 960px)") const tablet$ = watchMedia("(min-width: 960px)")
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
@ -59,55 +70,114 @@ document.documentElement.classList.add("js")
const container = getElement("[data-md-component=container]")! const container = getElement("[data-md-component=container]")!
const header = getElement("[data-md-component=header]")! const header = getElement("[data-md-component=header]")!
const container$ = watchContainer(container, header, { size$, offset$ })
const container$ = fromContainer(container, header, { size$, offset$ }) // Optimize anchor list candidates
const anchors = getElements<HTMLAnchorElement>("[data-md-component=toc] .md-nav__link")
// --- if (anchors.length)
tablet$
const nav = getElement("[data-md-component=navigation")!
fromSidebar(nav, { container$, offset$ })
.pipe( .pipe(
withMediaQuery(screenAndAbove$), toggle(() => watchAnchors(anchors, header, { offset$ })
concatMap(sidebar$ => sidebar$.pipe( .pipe(
startWith({ done: [], next: [] }),
pairwise(),
map(([a, b]) => {
const begin = Math.max(0, Math.min(b.done.length, a.done.length) - 1)
const end = Math.max(b.done.length, a.done.length)
return {
done: b.done.slice(begin, end + 1),
next: difference(b.next, a.next)
}
}),
finalize(() => { finalize(() => {
unsetSidebarHeight(nav) for (const anchor of anchors)
unsetSidebarLock(nav) resetAnchor(anchor)
}) })
)) )
)
)
.subscribe(({ done, next }) => {
/* Look backward */
for (const [i, [anchor]] of done.entries()) {
setAnchorBlur(anchor, true)
setAnchorActive(anchor, i === done.length - 1)
}
/* Look forward */
for (const [anchor] of next) {
setAnchorBlur(anchor, false)
setAnchorActive(anchor, false)
}
})
// TODO: this should be subscribed to a subject!
// const toggle = getElement<HTMLInputElement>("[data-md-toggle=search]")!
// fromEvent(toggle, "change")
// .subscribe(x2 => {
// console.log("toggle changed", x2)
// })
// const query = getElement("[data-md-component=query]")
// if (typeof query !== "undefined") {
// fromEvent(query, "focus")
// .pipe(
// )
// .subscribe(console.log)
// }
/* Component: header shadow toggle */ // - TODO: put this into a separate component
if (typeof header !== "undefined") {
container$
.pipe(
distinctUntilKeyChanged("active")
)
.subscribe(({ active }) => {
setHeaderShadow(header, active)
})
}
/* Component: sidebar with navigation */
const nav = getElement("[data-md-component=navigation")
if (typeof nav !== "undefined") {
screen$
.pipe(
toggle(() => watchSidebar(nav, { container$, offset$ })
.pipe(
finalize(() => {
resetSidebar(nav)
})
)
)
) )
.subscribe(({ height, lock }) => { .subscribe(({ height, lock }) => {
setSidebarHeight(nav, height) setSidebarHeight(nav, height)
setSidebarLock(nav, lock) setSidebarLock(nav, lock)
}) })
}
const toc = getElement("[data-md-component=toc")! /* Component: sidebar with table of contents (missing on 404 page) */
const toc = getElement("[data-md-component=toc")
fromSidebar(toc, { container$, offset$ }) if (typeof toc !== "undefined") {
tablet$
.pipe(
toggle(() => watchSidebar(toc, { container$, offset$ })
.pipe( .pipe(
withMediaQuery(tabletAndAbove$),
concatMap(sidebar$ => sidebar$.pipe(
finalize(() => { finalize(() => {
unsetSidebarHeight(toc) resetSidebar(toc)
unsetSidebarLock(toc)
}) })
)) )
)
) )
.subscribe(({ height, lock }) => { .subscribe(({ height, lock }) => {
setSidebarHeight(toc, height) setSidebarHeight(toc, height)
setSidebarLock(toc, lock) setSidebarLock(toc, lock)
}) })
}
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
export function app(config: any) { export function app(config: any) {
// TODO: console.log("called app")
let parent = container.parentElement as HTMLElement
const height = 0
// TODO: write a fromHeader (?) component observable which
// this fromHeader should take the container and ...?
// container$.subscribe()
// container padding = "with parent" + 30px (padding of container...)
} }

View File

@ -41,6 +41,6 @@ export function watchMedia(query: string): Observable<boolean> {
) )
.pipe( .pipe(
startWith(media.matches), startWith(media.matches),
shareReplay(1) shareReplay({ bufferSize: 1, refCount: true })
) )
} }

View File

@ -97,7 +97,7 @@ export function watchViewportOffset(): Observable<ViewportOffset> {
.pipe( .pipe(
map(getViewportOffset), map(getViewportOffset),
startWith(getViewportOffset()), startWith(getViewportOffset()),
shareReplay(1) shareReplay({ bufferSize: 1, refCount: true })
) )
} }
@ -111,6 +111,6 @@ export function watchViewportSize(): Observable<ViewportSize> {
.pipe( .pipe(
map(getViewportSize), map(getViewportSize),
startWith(getViewportSize()), startWith(getViewportSize()),
shareReplay(1) shareReplay({ bufferSize: 1, refCount: true })
) )
} }

View File

@ -20,8 +20,8 @@
* IN THE SOFTWARE. * IN THE SOFTWARE.
*/ */
import { Observable, OperatorFunction } from "rxjs" import { NEVER, Observable, OperatorFunction, pipe } from "rxjs"
import { filter, windowToggle } from "rxjs/operators" import { switchMap } from "rxjs/operators"
/* ---------------------------------------------------------------------------- /* ----------------------------------------------------------------------------
* Functions * Functions
@ -47,18 +47,18 @@ export function toArray<
* ------------------------------------------------------------------------- */ * ------------------------------------------------------------------------- */
/** /**
* Toggle emission from a source observable * Switch to another observable, if toggle is active
* *
* @template T - Observable value type * @template T - Observable value type
* *
* @param toggle$ - Toggle observable * @param project - Project function
* *
* @return Observable of source observables * @return Observable, if toggle is active
*/ */
export function toggle<T>( export function toggle<T>(
toggle$: Observable<boolean> project: () => Observable<T>
): OperatorFunction<T, Observable<T>> { ): OperatorFunction<boolean, T> {
const start$ = toggle$.pipe(filter(match => match === true)) return pipe(
const until$ = toggle$.pipe(filter(match => match === false)) switchMap(active => active ? project() : NEVER)
return windowToggle<T, boolean>(start$, () => until$) )
} }