Unified components and observable structure

This commit is contained in:
squidfunk
2020-03-05 17:17:15 +01:00
parent 6e6868b8cd
commit 9738c12cc9
149 changed files with 11475 additions and 1095 deletions

View File

@@ -60,7 +60,7 @@ interface WatchOptions {
*
* @param options - Options
*
* @return Document switch observable
* @return Document observable
*/
export function watchDocumentSwitch(
{ location$ }: WatchOptions

View File

@@ -64,7 +64,7 @@ export function getElementOrThrow<T extends HTMLElement>(
/**
* Retrieve the currently active element
*
* @return Element
* @return Element or nothing
*/
export function getActiveElement(): HTMLElement | undefined {
return document.activeElement instanceof HTMLElement

View File

@@ -34,11 +34,9 @@ import { getActiveElement } from "../_"
*
* @param el - Element
* @param value - Whether the element should be focused
*
* @return Element offset
*/
export function setElementFocus(
el: HTMLElement, value: boolean = true
el: HTMLElement, value: boolean = true
): void {
if (value)
el.focus()

View File

@@ -25,5 +25,6 @@ export * from "./element"
export * from "./keyboard"
export * from "./location"
export * from "./media"
export * from "./toggle"
export * from "./viewport"
export * from "./worker"

View File

@@ -46,7 +46,7 @@ export interface Key {
*
* @return Test result
*/
export function isSusceptibleToKeyboard(el: HTMLElement) {
export function isSusceptibleToKeyboard(el: HTMLElement): boolean {
switch (el.tagName) {
/* Form elements */

View File

@@ -51,6 +51,40 @@ export function setLocation(url: URL): void {
/* ------------------------------------------------------------------------- */
/**
* Check whether a URL is an internal link or a file (except `.html`)
*
* @param url - URL or HTML anchor element
* @param ref - Reference URL
*
* @return Test result
*/
export function isLocationInternal(
url: URL | HTMLAnchorElement,
ref: URL | Location = location
): boolean {
return url.host === ref.host
&& /^(?:\/[\w-]+)*(?:\/?|\.html)$/i.test(url.pathname)
}
/**
* Check whether a URL is an anchor link on the current page
*
* @param url - URL or HTML anchor element
* @param ref - Reference URL
*
* @return Test result
*/
export function isLocationAnchor(
url: URL | HTMLAnchorElement,
ref: URL | Location = location
): boolean {
return url.pathname === ref.pathname
&& url.hash.length > 0
}
/* ------------------------------------------------------------------------- */
/**
* Watch location
*

View File

@@ -36,6 +36,22 @@ export function getLocationHash(): string {
return location.hash.substring(1)
}
/**
* Set location hash
*
* Setting a new fragment identifier via `location.hash` will have no effect
* if the value doesn't change. However, when a new fragment identifier is set,
* we want the browser to target the respective element at all times, which is
* why we use this dirty little trick.
*
* @param hash - Location hash
*/
export function setLocationHash(hash: string): void {
const el = document.createElement("a")
el.href = hash
el.click()
}
/* ------------------------------------------------------------------------- */
/**

View File

@@ -20,17 +20,10 @@
* IN THE SOFTWARE.
*/
import { NEVER, Observable, fromEvent, of } from "rxjs"
import {
distinctUntilChanged,
map,
shareReplay,
startWith,
switchMap,
take
} from "rxjs/operators"
import { Observable, fromEvent } from "rxjs"
import { map, startWith } from "rxjs/operators"
import { getElement } from "../agent"
import { getElementOrThrow } from "../element"
/* ----------------------------------------------------------------------------
* Types
@@ -43,92 +36,33 @@ export type Toggle =
| "drawer" /* Toggle for drawer */
| "search" /* Toggle for search */
/**
* Toggle map
*/
export type ToggleMap = {
[P in Toggle]?: HTMLInputElement
}
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Watch options
*/
interface WatchOptions {
document$: Observable<Document> /* Document observable */
}
/* ----------------------------------------------------------------------------
* Data
* ------------------------------------------------------------------------- */
/**
* Toggle map observable
* Toggle map
*/
let toggles$: Observable<ToggleMap>
const toggles: Record<Toggle, HTMLInputElement> = {
drawer: getElementOrThrow(`[data-md-toggle=drawer]`),
search: getElementOrThrow(`[data-md-toggle=search]`)
}
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Setup bindings to toggles with given names
* Retrieve the value of a toggle
*
* @param names - Toggle names
* @param options - Options
* @param name - Toggle
*
* @return Toggle value
*/
export function setupToggles(
names: Toggle[], { document$ }: WatchOptions
): void {
toggles$ = document$
.pipe(
/* Ignore document switches */
take(1),
/* Build toggle map */
map(document => names.reduce<ToggleMap>((toggles, name) => {
const el = getElement(`[data-md-toggle=${name}]`, document)
return {
...toggles,
...typeof el !== "undefined" ? { [name]: el } : {}
}
}, {})),
/* Convert to hot observable */
shareReplay(1)
)
export function getToggle(name: Toggle): boolean {
return toggles[name].checked
}
/**
* Retrieve a toggle
*
* The returned observable will only re-emit if the element changed, i.e. if
* it was replaced from a document which was switched to.
*
* @param name - Toggle name
*
* @return Element observable
*/
export function useToggle(
name: Toggle
): Observable<HTMLInputElement> {
return toggles$
.pipe(
switchMap(toggles => (
typeof toggles[name] !== "undefined"
? of(toggles[name]!)
: NEVER
)),
distinctUntilChanged()
)
}
/* ------------------------------------------------------------------------- */
/**
* Set toggle
*
@@ -137,14 +71,12 @@ export function useToggle(
* used `CustomEvent` to programmatically change the value of a toggle, but this
* is a much simpler and cleaner solution which doesn't require a polyfill.
*
* @param el - Toggle element
* @param name - Toggle
* @param value - Toggle value
*/
export function setToggle(
el: HTMLInputElement, value: boolean
): void {
if (el.checked !== value)
el.click()
export function setToggle(name: Toggle, value: boolean): void {
if (toggles[name].checked !== value)
toggles[name].click()
}
/* ------------------------------------------------------------------------- */
@@ -152,13 +84,12 @@ export function setToggle(
/**
* Watch toggle
*
* @param el - Toggle element
* @param name - Toggle
*
* @return Toggle observable
* @return Toggle value observable
*/
export function watchToggle(
el: HTMLInputElement
): Observable<boolean> {
export function watchToggle(name: Toggle): Observable<boolean> {
const el = toggles[name]
return fromEvent(el, "change")
.pipe(
map(() => el.checked),

View File

@@ -27,7 +27,8 @@ import {
shareReplay
} from "rxjs/operators"
import { Header } from "../../../header"
import { Header } from "components"
import {
ViewportOffset,
watchViewportOffset
@@ -54,9 +55,9 @@ export interface Viewport {
* ------------------------------------------------------------------------- */
/**
* Watch relative options
* Watch at options
*/
interface WatchRelativeOptions {
interface WatchAtOptions {
header$: Observable<Header> /* Header observable */
viewport$: Observable<Viewport> /* Viewport observable */
}
@@ -90,7 +91,7 @@ export function watchViewport(): Observable<Viewport> {
* @return Viewport observable
*/
export function watchViewportAt(
el: HTMLElement, { header$, viewport$ }: WatchRelativeOptions
el: HTMLElement, { header$, viewport$ }: WatchAtOptions
): Observable<Viewport> {
const offset$ = viewport$
.pipe(

View File

@@ -29,7 +29,7 @@ import {
switchMap
} from "rxjs/operators"
import { getElement } from "observables"
import { getElement } from "browser"
/* ----------------------------------------------------------------------------
* Types

View File

@@ -35,11 +35,13 @@ import {
Viewport,
getElement,
watchViewportAt
} from "observables"
} from "browser"
import { useComponent } from "../../_"
import { paintHeaderType } from "../paint"
import { watchHeader } from "../watch"
import {
applyHeaderType,
watchHeader
} from "../react"
/* ----------------------------------------------------------------------------
* Types
@@ -104,7 +106,7 @@ export function mountHeader(
return y >= hx.offsetHeight ? "page" : "site"
}),
distinctUntilChanged(),
paintHeaderType(title)
applyHeaderType(title)
)
),
startWith<HeaderType>("site")

View File

@@ -21,6 +21,5 @@
*/
export * from "./_"
export * from "./apply"
export * from "./paint"
export * from "./watch"
export * from "./react"
export * from "./set"

View File

@@ -1,63 +0,0 @@
/*
* 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 {
MonoTypeOperatorFunction,
animationFrameScheduler,
pipe
} from "rxjs"
import { finalize, observeOn, tap } from "rxjs/operators"
import { HeaderType } from "../_"
import {
resetHeaderTitleActive,
setHeaderTitleActive
} from "../apply"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Paint header title type
*
* @param el - Header title element
*
* @return Operator function
*/
export function paintHeaderType(
el: HTMLElement
): MonoTypeOperatorFunction<HeaderType> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(type => {
setHeaderTitleActive(el, type === "page")
}),
/* Reset on complete or error */
finalize(() => {
resetHeaderTitleActive(el)
})
)
}

View File

@@ -20,12 +20,28 @@
* IN THE SOFTWARE.
*/
import { Observable, of } from "rxjs"
import { distinctUntilKeyChanged, switchMap } from "rxjs/operators"
import {
MonoTypeOperatorFunction,
Observable,
animationFrameScheduler,
of,
pipe
} from "rxjs"
import {
distinctUntilKeyChanged,
finalize,
observeOn,
switchMap,
tap
} from "rxjs/operators"
import { Viewport } from "observables"
import { Viewport } from "browser"
import { Header } from "../_"
import { Header, HeaderType } from "../_"
import {
resetHeaderTitleActive,
setHeaderTitleActive
} from "../set"
/* ----------------------------------------------------------------------------
* Helper types
@@ -72,3 +88,30 @@ export function watchHeader(
})
)
}
/* ------------------------------------------------------------------------- */
/**
* Apply header title type
*
* @param el - Header title element
*
* @return Operator function
*/
export function applyHeaderType(
el: HTMLElement
): MonoTypeOperatorFunction<HeaderType> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(type => {
setHeaderTitleActive(el, type === "page")
}),
/* Reset on complete or error */
finalize(() => {
resetHeaderTitleActive(el)
})
)
}

View File

@@ -23,10 +23,10 @@
import { Observable, OperatorFunction, pipe } from "rxjs"
import { distinctUntilChanged, map, switchMap } from "rxjs/operators"
import { Viewport, watchViewportAt } from "observables"
import { Viewport, watchViewportAt } from "browser"
import { Header } from "../../header"
import { paintHero } from "../paint"
import { applyHero } from "../react"
/* ----------------------------------------------------------------------------
* Types
@@ -70,7 +70,7 @@ export function mountHero(
.pipe(
map(({ offset: { y } }) => ({ hidden: y >= 20 })),
distinctUntilChanged(),
paintHero(el)
applyHero(el)
)
)
)

View File

@@ -21,5 +21,5 @@
*/
export * from "./_"
export * from "./apply"
export * from "./paint"
export * from "./react"
export * from "./set"

View File

@@ -31,20 +31,20 @@ import { Hero } from "../_"
import {
resetHeroHidden,
setHeroHidden
} from "../apply"
} from "../set"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Paint hero
* Apply hero
*
* @param el - Hero element
*
* @return Operator function
*/
export function paintHero(
export function applyHero(
el: HTMLElement
): MonoTypeOperatorFunction<Hero> {
return pipe(

View File

@@ -23,12 +23,14 @@
import { Observable, OperatorFunction, Subject, pipe } from "rxjs"
import { distinctUntilKeyChanged, switchMap, tap } from "rxjs/operators"
import { Viewport } from "observables"
import { Viewport } from "browser"
import { useComponent } from "../../_"
import { Header } from "../../header"
import { paintHeaderShadow } from "../paint"
import { watchMain } from "../watch"
import {
applyHeaderShadow,
watchMain
} from "../react"
/* ----------------------------------------------------------------------------
* Types
@@ -82,7 +84,7 @@ export function mountMain(
switchMap(header => main$
.pipe(
distinctUntilKeyChanged("active"),
paintHeaderShadow(header)
applyHeaderShadow(header)
)
)
)

View File

@@ -21,6 +21,5 @@
*/
export * from "./_"
export * from "./apply"
export * from "./paint"
export * from "./watch"
export * from "./react"
export * from "./set"

View File

@@ -1,63 +0,0 @@
/*
* 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 {
MonoTypeOperatorFunction,
animationFrameScheduler,
pipe
} from "rxjs"
import { finalize, observeOn, tap } from "rxjs/operators"
import { Main } from "../_"
import {
resetHeaderShadow,
setHeaderShadow
} from "../apply"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Paint header shadow
*
* @param el - Header element
*
* @return Operator function
*/
export function paintHeaderShadow(
el: HTMLElement
): MonoTypeOperatorFunction<Main> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(({ active }) => {
setHeaderShadow(el, active)
}),
/* Reset on complete or error */
finalize(() => {
resetHeaderShadow(el)
})
)
}

View File

@@ -20,13 +20,30 @@
* IN THE SOFTWARE.
*/
import { Observable, combineLatest } from "rxjs"
import { distinctUntilChanged, map, pluck } from "rxjs/operators"
import {
MonoTypeOperatorFunction,
Observable,
animationFrameScheduler,
combineLatest,
pipe
} from "rxjs"
import {
distinctUntilChanged,
finalize,
map,
observeOn,
pluck,
tap
} from "rxjs/operators"
import { Viewport } from "observables"
import { Viewport } from "browser"
import { Header } from "../../header"
import { Main } from "../_"
import {
resetHeaderShadow,
setHeaderShadow
} from "../set"
/* ----------------------------------------------------------------------------
* Helper types
@@ -97,3 +114,30 @@ export function watchMain(
}))
)
}
/* ------------------------------------------------------------------------- */
/**
* Apply header shadow
*
* @param el - Header element
*
* @return Operator function
*/
export function applyHeaderShadow(
el: HTMLElement
): MonoTypeOperatorFunction<Main> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(({ active }) => {
setHeaderShadow(el, active)
}),
/* Reset on complete or error */
finalize(() => {
resetHeaderShadow(el)
})
)
}

View File

@@ -23,18 +23,18 @@
import { Observable, OperatorFunction, pipe } from "rxjs"
import { map, switchMap } from "rxjs/operators"
import { Viewport, getElements } from "observables"
import { Viewport, getElements } from "browser"
import { Header } from "../../header"
import { Main } from "../../main"
import {
Sidebar,
paintSidebar,
applySidebar,
watchSidebar
} from "../../shared"
import {
NavigationLayer,
paintNavigationLayer,
applyNavigationLayer,
watchNavigationLayer
} from "../layer"
@@ -102,7 +102,7 @@ export function mountNavigation(
if (screen) {
return watchSidebar(el, { main$, viewport$ })
.pipe(
paintSidebar(el, { header$ }),
applySidebar(el, { header$ }),
map(sidebar => ({ sidebar }))
)
@@ -111,7 +111,7 @@ export function mountNavigation(
const els = getElements("nav", el)
return watchNavigationLayer(els)
.pipe(
paintNavigationLayer(els),
applyNavigationLayer(els),
map(layer => ({ layer }))
)
}

View File

@@ -21,6 +21,5 @@
*/
export * from "./_"
export * from "./apply"
export * from "./paint"
export * from "./watch"
export * from "./react"
export * from "./set"

View File

@@ -1,83 +0,0 @@
/*
* 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 {
MonoTypeOperatorFunction,
animationFrameScheduler,
pipe
} from "rxjs"
import {
delay,
finalize,
observeOn,
tap
} from "rxjs/operators"
import { getElementOrThrow } from "observables"
import { NavigationLayer } from "../_"
import {
resetOverflowScrolling,
setOverflowScrolling
} from "../apply"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Paint navigation layer
*
* @param els - Navigation elements
*
* @return Operator function
*/
export function paintNavigationLayer(
els: HTMLElement[]
): MonoTypeOperatorFunction<NavigationLayer> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(({ prev }) => {
if (prev)
resetOverflowScrolling(prev)
}),
/* Wait until transition has finished */
delay(250),
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(({ next }) => {
setOverflowScrolling(next)
}),
/* Reset on complete or error */
finalize(() => {
for (const el of els)
resetOverflowScrolling(
getElementOrThrow(".md-nav__list", el)
)
})
)
}

View File

@@ -21,15 +21,30 @@
*/
import { findLast } from "ramda"
import { Observable, fromEvent, merge } from "rxjs"
import { map, scan } from "rxjs/operators"
import {
getElement,
getElementOrThrow
} from "observables"
MonoTypeOperatorFunction,
Observable,
animationFrameScheduler,
fromEvent,
merge,
pipe
} from "rxjs"
import {
delay,
finalize,
map,
observeOn,
scan,
tap
} from "rxjs/operators"
import { getElement, getElementOrThrow } from "browser"
import { NavigationLayer } from "../_"
import {
resetOverflowScrolling,
setOverflowScrolling
} from "../set"
/* ----------------------------------------------------------------------------
* Functions
@@ -76,3 +91,43 @@ export function watchNavigationLayer(
scan(({ next: prev }, { next }) => ({ prev, next }))
)
}
/* ------------------------------------------------------------------------- */
/**
* Apply navigation layer
*
* @param els - Navigation elements
*
* @return Operator function
*/
export function applyNavigationLayer(
els: HTMLElement[]
): MonoTypeOperatorFunction<NavigationLayer> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(({ prev }) => {
if (prev)
resetOverflowScrolling(prev)
}),
/* Wait until transition has finished */
delay(250),
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(({ next }) => {
setOverflowScrolling(next)
}),
/* Reset on complete or error */
finalize(() => {
for (const el of els)
resetOverflowScrolling(
getElementOrThrow(".md-nav__list", el)
)
})
)
}

View File

@@ -24,22 +24,17 @@ import { OperatorFunction, pipe } from "rxjs"
import {
distinctUntilKeyChanged,
map,
switchMap,
withLatestFrom
switchMap
} from "rxjs/operators"
import {
WorkerHandler,
setToggle,
useToggle
} from "observables"
import { WorkerHandler, setToggle } from "browser"
import {
SearchMessage,
SearchMessageType,
SearchQueryMessage
} from "workers"
import { watchSearchQuery } from "../watch"
import { watchSearchQuery } from "../react"
/* ----------------------------------------------------------------------------
* Types
@@ -79,7 +74,6 @@ interface MountOptions {
export function mountSearchQuery(
{ tx$ }: WorkerHandler<SearchMessage>, options: MountOptions = {}
): OperatorFunction<HTMLInputElement, SearchQuery> {
const toggle$ = useToggle("search")
return pipe(
switchMap(el => {
const query$ = watchSearchQuery(el, options)
@@ -98,12 +92,11 @@ export function mountSearchQuery(
/* Toggle search on focus */
query$
.pipe(
distinctUntilKeyChanged("focus"),
withLatestFrom(toggle$)
distinctUntilKeyChanged("focus")
)
.subscribe(([{ focus }, toggle]) => {
.subscribe(({ focus }) => {
if (focus)
setToggle(toggle, focus)
setToggle("search", focus)
})
/* Return search query */

View File

@@ -21,4 +21,4 @@
*/
export * from "./_"
export * from "./watch"
export * from "./react"

View File

@@ -28,7 +28,7 @@ import {
startWith
} from "rxjs/operators"
import { watchElementFocus } from "observables"
import { watchElementFocus } from "browser"
import { SearchQuery } from "../_"

View File

@@ -29,10 +29,10 @@ import {
tap
} from "rxjs/operators"
import { setElementFocus } from "observables"
import { setElementFocus } from "browser"
import { useComponent } from "../../../_"
import { watchSearchReset } from "../watch"
import { watchSearchReset } from "../react"
/* ----------------------------------------------------------------------------
* Functions

View File

@@ -21,4 +21,4 @@
*/
export * from "./_"
export * from "./watch"
export * from "./react"

View File

@@ -30,18 +30,15 @@ import {
switchMap
} from "rxjs/operators"
import { WorkerHandler, watchElementOffset } from "browser"
import { SearchResult } from "integrations/search"
import {
WorkerHandler,
watchElementOffset
} from "observables"
import {
SearchMessage,
isSearchResultMessage
} from "workers"
import { SearchQuery } from "../../query"
import { paintSearchResult } from "../paint"
import { applySearchResult } from "../react"
/* ----------------------------------------------------------------------------
* Helper types
@@ -83,12 +80,12 @@ export function mountSearchResult(
filter(identity)
)
/* Paint search results */
/* Apply search results */
return rx$
.pipe(
filter(isSearchResultMessage),
pluck("data"),
paintSearchResult(el, { query$, fetch$ })
applySearchResult(el, { query$, fetch$ })
)
})
)

View File

@@ -21,5 +21,5 @@
*/
export * from "./_"
export * from "./apply"
export * from "./paint"
export * from "./react"
export * from "./set"

View File

@@ -36,8 +36,8 @@ import {
withLatestFrom
} from "rxjs/operators"
import { getElementOrThrow } from "browser"
import { SearchResult } from "integrations/search"
import { getElementOrThrow } from "observables"
import { renderSearchResult } from "templates"
import { SearchQuery } from "../../query"
@@ -46,16 +46,16 @@ import {
resetSearchResultList,
resetSearchResultMeta,
setSearchResultMeta
} from "../apply"
} from "../set"
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Paint options
* Apply options
*/
interface PaintOptions {
interface ApplyOptions {
query$: Observable<SearchQuery> /* Search query observable */
fetch$: Observable<boolean> /* Result fetch observable */
}
@@ -65,7 +65,7 @@ interface PaintOptions {
* ------------------------------------------------------------------------- */
/**
* Paint search results
* Apply search results
*
* This function will perform a lazy rendering of the search results, depending
* on the vertical offset of the search result container. When the scroll offset
@@ -76,14 +76,14 @@ interface PaintOptions {
*
* @return Operator function
*/
export function paintSearchResult(
el: HTMLElement, { query$, fetch$ }: PaintOptions
export function applySearchResult(
el: HTMLElement, { query$, fetch$ }: ApplyOptions
): MonoTypeOperatorFunction<SearchResult[]> {
const list = getElementOrThrow(".md-search-result__list", el)
const meta = getElementOrThrow(".md-search-result__meta", el)
return pipe(
/* Paint search result metadata */
/* Apply search result metadata */
withLatestFrom(query$),
map(([result, query]) => {
if (query.value) {
@@ -94,7 +94,7 @@ export function paintSearchResult(
return result
}),
/* Paint search result list */
/* Apply search result list */
switchMap(result => fetch$
.pipe(

View File

@@ -21,6 +21,5 @@
*/
export * from "./_"
export * from "./apply"
export * from "./paint"
export * from "./watch"
export * from "./react"
export * from "./set"

View File

@@ -1,100 +0,0 @@
/*
* 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 {
MonoTypeOperatorFunction,
Observable,
animationFrameScheduler,
pipe
} from "rxjs"
import {
finalize,
map,
observeOn,
tap,
withLatestFrom
} from "rxjs/operators"
import { Header } from "../../../header"
import { Sidebar } from "../_"
import {
resetSidebarHeight,
resetSidebarLock,
resetSidebarOffset,
setSidebarHeight,
setSidebarLock,
setSidebarOffset
} from "../apply"
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Paint options
*/
interface PaintOptions {
header$: Observable<Header> /* Header observable */
}
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Paint sidebar
*
* @param el - Sidebar element
* @param options - Options
*
* @return Operator function
*/
export function paintSidebar(
el: HTMLElement, { header$ }: PaintOptions
): MonoTypeOperatorFunction<Sidebar> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
withLatestFrom(header$),
tap(([{ height, lock }, { height: offset }]) => {
setSidebarHeight(el, height)
setSidebarLock(el, lock)
/* Set offset in locked state depending on header height */
if (lock)
setSidebarOffset(el, offset)
else
resetSidebarOffset(el)
}),
/* Re-map to sidebar */
map(([sidebar]) => sidebar),
/* Reset on complete or error */
finalize(() => {
resetSidebarOffset(el)
resetSidebarHeight(el)
resetSidebarLock(el)
})
)
}

View File

@@ -20,18 +20,36 @@
* IN THE SOFTWARE.
*/
import { Observable, combineLatest } from "rxjs"
import {
MonoTypeOperatorFunction,
Observable,
animationFrameScheduler,
combineLatest,
pipe
} from "rxjs"
import {
distinctUntilChanged,
distinctUntilKeyChanged,
finalize,
map,
observeOn,
tap,
withLatestFrom
} from "rxjs/operators"
import { Viewport } from "observables"
import { Viewport } from "browser"
import { Header } from "../../../header"
import { Main } from "../../../main"
import { Sidebar } from "../_"
import {
resetSidebarHeight,
resetSidebarLock,
resetSidebarOffset,
setSidebarHeight,
setSidebarLock,
setSidebarOffset
} from "../set"
/* ----------------------------------------------------------------------------
* Helper types
@@ -45,6 +63,13 @@ interface WatchOptions {
viewport$: Observable<Viewport> /* Viewport observable */
}
/**
* Apply options
*/
interface ApplyOptions {
header$: Observable<Header> /* Header observable */
}
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
@@ -105,3 +130,44 @@ export function watchSidebar(
map(([height, lock]) => ({ height, lock }))
)
}
/* ------------------------------------------------------------------------- */
/**
* Apply sidebar
*
* @param el - Sidebar element
* @param options - Options
*
* @return Operator function
*/
export function applySidebar(
el: HTMLElement, { header$ }: ApplyOptions
): MonoTypeOperatorFunction<Sidebar> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
withLatestFrom(header$),
tap(([{ height, lock }, { height: offset }]) => {
setSidebarHeight(el, height)
setSidebarLock(el, lock)
/* Set offset in locked state depending on header height */
if (lock)
setSidebarOffset(el, offset)
else
resetSidebarOffset(el)
}),
/* Re-map to sidebar */
map(([sidebar]) => sidebar),
/* Reset on complete or error */
finalize(() => {
resetSidebarOffset(el)
resetSidebarHeight(el)
resetSidebarLock(el)
})
)
}

View File

@@ -23,10 +23,10 @@
import { Observable, OperatorFunction, of, pipe } from "rxjs"
import { distinctUntilChanged, map, switchMap } from "rxjs/operators"
import { Viewport, watchViewportAt } from "observables"
import { Viewport, watchViewportAt } from "browser"
import { Header } from "../../header"
import { paintTabs } from "../paint"
import { applyTabs } from "../react"
/* ----------------------------------------------------------------------------
* Types
@@ -77,7 +77,7 @@ export function mountTabs(
.pipe(
map(({ offset: { y } }) => ({ hidden: y >= 10 })),
distinctUntilChanged(),
paintTabs(el)
applyTabs(el)
)
/* [screen -]: Unmount tabs below screen breakpoint */

View File

@@ -21,5 +21,5 @@
*/
export * from "./_"
export * from "./apply"
export * from "./paint"
export * from "./react"
export * from "./set"

View File

@@ -31,20 +31,20 @@ import { Tabs } from "../_"
import {
resetTabsHidden,
setTabsHidden
} from "../apply"
} from "../set"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Paint tabs
* Apply tabs
*
* @param el - Tabs element
*
* @return Operator function
*/
export function paintTabs(
export function applyTabs(
el: HTMLElement
): MonoTypeOperatorFunction<Tabs> {
return pipe(

View File

@@ -29,18 +29,18 @@ import {
} from "rxjs"
import { map, switchMap } from "rxjs/operators"
import { Viewport, getElements } from "observables"
import { Viewport, getElements } from "browser"
import { Header } from "../../header"
import { Main } from "../../main"
import {
Sidebar,
paintSidebar,
applySidebar,
watchSidebar
} from "../../shared"
import {
AnchorList,
paintAnchorList,
applyAnchorList,
watchAnchorList
} from "../anchor"
@@ -107,16 +107,16 @@ export function mountTableOfContents(
if (tablet) {
const els = getElements<HTMLAnchorElement>(".md-nav__link", el)
/* Watch and paint sidebar */
/* Watch and apply sidebar */
const sidebar$ = watchSidebar(el, { main$, viewport$ })
.pipe(
paintSidebar(el, { header$ })
applySidebar(el, { header$ })
)
/* Watch and paint anchor list (scroll spy) */
/* Watch and apply anchor list (scroll spy) */
const anchors$ = watchAnchorList(els, { header$, viewport$ })
.pipe(
paintAnchorList(els)
applyAnchorList(els)
)
/* Combine into a single hot observable */

View File

@@ -21,6 +21,5 @@
*/
export * from "./_"
export * from "./apply"
export * from "./paint"
export * from "./watch"
export * from "./react"
export * from "./set"

View File

@@ -1,79 +0,0 @@
/*
* 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 {
MonoTypeOperatorFunction,
animationFrameScheduler,
pipe
} from "rxjs"
import { finalize, observeOn, tap } from "rxjs/operators"
import { AnchorList } from "../_"
import {
resetAnchorActive,
resetAnchorBlur,
setAnchorActive,
setAnchorBlur
} from "../apply"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Paint anchor list
*
* @param els - Anchor elements
*
* @return Operator function
*/
export function paintAnchorList(
els: HTMLAnchorElement[]
): MonoTypeOperatorFunction<AnchorList> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(({ prev, next }) => {
/* Look forward */
for (const [el] of next) {
resetAnchorActive(el)
resetAnchorBlur(el)
}
/* Look backward */
for (const [index, [el]] of prev.entries()) {
setAnchorActive(el, index === prev.length - 1)
setAnchorBlur(el, true)
}
}),
/* Reset on complete or error */
finalize(() => {
for (const el of els) {
resetAnchorActive(el)
resetAnchorBlur(el)
}
})
)
}

View File

@@ -21,21 +21,36 @@
*/
import { reverse } from "ramda"
import { Observable, combineLatest } from "rxjs"
import {
MonoTypeOperatorFunction,
Observable,
animationFrameScheduler,
combineLatest,
pipe
} from "rxjs"
import {
bufferCount,
distinctUntilChanged,
distinctUntilKeyChanged,
finalize,
map,
observeOn,
scan,
startWith,
switchMap
switchMap,
tap
} from "rxjs/operators"
import { Viewport, getElement } from "observables"
import { Viewport, getElement } from "browser"
import { Header } from "../../../header"
import { AnchorList } from "../_"
import {
resetAnchorActive,
resetAnchorBlur,
setAnchorActive,
setAnchorBlur
} from "../set"
/* ----------------------------------------------------------------------------
* Helper types
@@ -189,3 +204,44 @@ export function watchAnchorList(
})
)
}
/* ------------------------------------------------------------------------- */
/**
* Apply anchor list
*
* @param els - Anchor elements
*
* @return Operator function
*/
export function applyAnchorList(
els: HTMLAnchorElement[]
): MonoTypeOperatorFunction<AnchorList> {
return pipe(
/* Defer repaint to next animation frame */
observeOn(animationFrameScheduler),
tap(({ prev, next }) => {
/* Look forward */
for (const [el] of next) {
resetAnchorActive(el)
resetAnchorBlur(el)
}
/* Look backward */
prev.forEach(([el], index) => {
setAnchorActive(el, index === prev.length - 1)
setAnchorBlur(el, true)
})
}),
/* Reset on complete or error */
finalize(() => {
for (const el of els) {
resetAnchorActive(el)
resetAnchorBlur(el)
}
})
)
}

View File

@@ -33,7 +33,8 @@ import {
animationFrameScheduler,
fromEvent,
of,
NEVER
NEVER,
from
} from "rxjs"
import {
delay,
@@ -43,16 +44,8 @@ import {
withLatestFrom,
observeOn,
take,
mapTo,
shareReplay,
sample,
share,
map,
pluck,
debounceTime,
distinctUntilKeyChanged,
distinctUntilChanged,
bufferCount
share
} from "rxjs/operators"
import {
@@ -64,12 +57,9 @@ import {
watchLocation,
watchLocationHash,
watchViewport,
setupToggles,
useToggle,
getElement,
setViewportOffset,
ViewportOffset
} from "./observables"
isLocationInternal,
isLocationAnchor
} from "./browser"
import { setupSearchWorker } from "./workers"
import {
@@ -87,7 +77,9 @@ import {
mountSearchResult
} from "components"
import { setupClipboard } from "./integrations/clipboard"
import { setupDialog } from "integrations/dialog"
import { setupKeyboard } from "./integrations/keyboard"
import { setupInstantLoading } from "integrations/instant"
import {
patchTables,
patchDetails,
@@ -96,7 +88,6 @@ import {
patchScripts
} from "patches"
import { isConfig } from "utilities"
import { setupDialog } from "integrations/dialog"
/* ------------------------------------------------------------------------- */
@@ -156,16 +147,10 @@ export function initialize(config: unknown) {
const screen$ = watchMedia("(min-width: 1220px)")
/* Setup document observable */
const document$ = config.feature.instant
const document$ = config.features.includes("instant")
? watchDocument({ location$ })
: watchDocument()
/* Setup toggle bindings */
setupToggles([
"drawer", /* Toggle for drawer */
"search" /* Toggle for search */
], { document$ })
/* Setup component bindings */
setupComponents([
"container", /* Container */
@@ -178,14 +163,21 @@ export function initialize(config: unknown) {
"search-query", /* Search input */
"search-reset", /* Search reset */
"search-result", /* Search results */
"skip", /* Skip link */
"tabs", /* Tabs */
"toc" /* Table of contents */
], { document$ })
/* ----------------------------------------------------------------------- */
const worker = setupSearchWorker(config.worker.search, {
base: config.base, location$
// External index
const index = config.search && config.search.index
? config.search.index
: undefined
// TODO: pass URL config as first parameter, options as second
const worker = setupSearchWorker(config.url.worker.search, {
base: config.url.base, index, location$
})
/* ----------------------------------------------------------------------- */
@@ -209,7 +201,7 @@ export function initialize(config: unknown) {
const query$ = useComponent("search-query")
.pipe(
mountSearchQuery(worker),
shareReplay(1) // TODO: this must be put onto EVERY component!
shareReplay(1)
)
/* Mount search reset */
@@ -278,36 +270,26 @@ export function initialize(config: unknown) {
/* ----------------------------------------------------------------------- */
// Close drawer and search on hash change
// put into navigation...
// TODO: replace with popstate?
hash$.subscribe(() => {
useToggle("drawer").subscribe(el => {
setToggle(el, false)
})
})
// put into search...
hash$
.pipe(
switchMap(hash => useToggle("search")
.pipe(
filter(x => x.checked), // only active
tap(toggle => setToggle(toggle, false)),
delay(125), // ensure that it runs after the body scroll reset...
mapTo(hash)
)
)
)
.subscribe(hash => {
getElement(`[id="${hash}"]`)!.scrollIntoView()
})
// // put into search...
// hash$
// .pipe(
// switchMap(hash => useToggle("search")
// .pipe(
// filter(x => x.checked), // only active
// tap(toggle => setToggle(toggle, false)),
// delay(125), // ensure that it runs after the body scroll reset...
// mapTo(hash)
// )
// )
// )
// .subscribe(hash => {
// getElement(`[id="${hash}"]`)!.scrollIntoView()
// })
// Scroll lock // document -> document$ => { body } !?
// put into search...
const toggle$ = useToggle("search")
combineLatest([
toggle$.pipe(switchMap(watchToggle)),
watchToggle("search"),
tablet$,
])
.pipe(
@@ -329,34 +311,33 @@ export function initialize(config: unknown) {
/* ----------------------------------------------------------------------- */
/**
* Location change
*/
interface State {
url: URL
data?: ViewportOffset
}
function isInternalLink(el: HTMLAnchorElement | URL) {
return el.host === location.host && (
// TODO: Improve regex
!el.pathname || el.pathname === "/" || /\/[\w-]+(?:\/?|\.html)$/i.test(el.pathname) // TODO: provide some test cases
/* Intercept internal link clicks */
const link$ = fromEvent<MouseEvent>(document.body, "click")
.pipe(
filter(ev => !(ev.metaKey || ev.ctrlKey)),
switchMap(ev => {
if (ev.target instanceof HTMLElement) {
const el = ev.target.closest("a") // TODO: abstract as link click?
if (el && isLocationInternal(el)) {
if (!isLocationAnchor(el))
ev.preventDefault()
return of(el)
}
}
return NEVER
}),
share()
)
}
// on same page!
function isAnchorLink(el: HTMLAnchorElement | URL) {
return el.pathname === location.pathname && el.hash.length > 0
}
/* Always close drawer on click */
link$.subscribe(() => {
setToggle("drawer", false)
})
function compareState(
{ url: a }: State, { url: b }: State
) {
return a.href === b.href
}
// somehow call this setupNavigation ?
// instant loading
if (config.feature.instant) {
if (config.features.includes("instant")) {
/* Disable automatic scroll restoration, as it doesn't work nicely */
if ("scrollRestoration" in history)
@@ -370,167 +351,10 @@ export function initialize(config: unknown) {
for (const el of getElements<HTMLLinkElement>(selector))
el.href = el.href
/* Intercept internal link clicks */
const internal$ = fromEvent<MouseEvent>(document.body, "click")
.pipe(
filter(ev => !(ev.metaKey || ev.ctrlKey)),
switchMap(ev => {
if (ev.target instanceof HTMLElement) {
const el = ev.target.closest("a")
if (el && isInternalLink(el)) {
if (!isAnchorLink(el))
ev.preventDefault()
return of(el.href)
}
}
return NEVER
}),
distinctUntilChanged(),
map<string, State>(href => ({ url: new URL(href) })),
share()
)
/* Intercept internal links to dispatch */
const dispatch$ = internal$
.pipe(
filter(({ url }) => !isAnchorLink(url)),
share()
)
/* Intercept popstate events (history back and forward) */
const popstate$ = fromEvent<PopStateEvent>(window, "popstate")
.pipe(
filter(ev => ev.state !== null),
map<PopStateEvent, State>(ev => ({
url: new URL(location.href),
data: ev.state
})),
share()
)
/* Emit location change */
merge(dispatch$, popstate$)
.pipe(
pluck("url")
)
.subscribe(location$)
/* Add dispatched link to history */
internal$
.pipe(
// TODO: must start with the current location and ignore the first emission
distinctUntilChanged(compareState),
filter(({ url }) => !isAnchorLink(url))
)
.subscribe(({ url }) => {
// console.log(`History.Push ${url}`)
history.pushState({}, "", url.toString())
})
// special case
merge(internal$, popstate$)
.pipe(
bufferCount(2, 1),
// filter(([prev, next]) => {
// return prev.url.href.match(next.url.href) !== null
// && isAnchorLink(prev.url)
// })
)
.subscribe(([prev, next]) => {
console.log(`<- ${prev.url}`)
console.log(`-> ${next.url}`)
if (
prev.url.href.match(next.url.href) !== null &&
isAnchorLink(prev.url)
) {
// dialog$.next(`Potential Candidate: ${JSON.stringify(next.data)}`, ) // awesome debugging.
setViewportOffset(next.data || { y: 0 })
}
// console.log("Potential Candidate")
})
// .subscribe((x) => console.log(x[0].url.toString(), x[1].url.toString()))
// filter(([prev, next]) => {
// return prev.url.href.match(next.url.href) !== null
// && isAnchorLink(prev.url)
// }),
// map(([, next]) => next)
// // distinctUntilChanged(compareLocationChange),
// // filter(({ url }) => !isAnchorLink(url))
// )
// .subscribe(({ url }) => {
// console.log(`Restore ${url}`)
// })
/* Persist viewport offset in history before hash change */
viewport$
.pipe(
debounceTime(250),
distinctUntilKeyChanged("offset"),
)
.subscribe(({ offset }) => {
// console.log("Update", offset)
history.replaceState(offset, "")
})
/* */
merge(dispatch$, popstate$)
.pipe(
sample(document$),
withLatestFrom(document$),
)
.subscribe(([{ url, data }, { title, head }]) => {
console.log("Done", url.href, data)
// trigger custom event
document.dispatchEvent(new CustomEvent("DOMContentSwitch"))
// setDocumentTitle
document.title = title
// replace meta tags
for (const selector of [
`link[rel="canonical"]`,
`meta[name="author"]`,
`meta[name="description"]`
]) {
const next = getElement(selector, head)
const prev = getElement(selector, document.head)
if (
typeof next !== "undefined" &&
typeof prev !== "undefined"
) {
prev.replaceWith(next)
}
}
// search drawer close
useToggle("search").subscribe(el => {
setToggle(el, false)
})
// // TODO: this doesnt work as expected
if (url.hash) {
console.log("hash data?", data)
const a = document.createElement("a")
a.href = url.hash
a.click()
} else {
setViewportOffset(data || { y: 0 }) // push state!
}
})
// internal$.subscribe(({ url }) => {
// console.log(`Internal ${url}`)
// })
// dispatch$.subscribe(({ url }) => {
// console.log(`Dispatch ${url}`)
// })
popstate$.subscribe(({ url }) => {
console.log(`Popstate ${url.href}`, url)
setupInstantLoading({
document$, link$, location$, viewport$
})
}
/* ----------------------------------------------------------------------- */
@@ -550,26 +374,28 @@ export function initialize(config: unknown) {
/* ----------------------------------------------------------------------- */
const state = {
search$,
clipboard$,
location$,
hash$,
keyboard$,
dialog$,
/* Browser observables */
document$,
viewport$,
/* Component observables */
header$,
hero$,
main$,
navigation$,
toc$,
search$,
tabs$,
hero$,
// title$ // TODO: header title
toc$,
/* Integation observables */
clipboard$,
keyboard$,
dialog$
}
const { ...rest } = state
merge(...values(rest))
.subscribe() // potential memleak <-- use takeUntil
return {
// agent,
state
}
/* Subscribe to all observables */
merge(...values(state))
.subscribe()
return state
}

View File

@@ -24,7 +24,7 @@ import * as ClipboardJS from "clipboard"
import { NEVER, Observable, Subject, fromEventPattern } from "rxjs"
import { mapTo, share, tap } from "rxjs/operators"
import { getElements } from "observables"
import { getElements } from "browser"
import { renderClipboard } from "templates"
import { translate } from "utilities"
@@ -63,11 +63,11 @@ export function setupClipboard(
/* Inject 'copy-to-clipboard' buttons */
document$.subscribe(() => {
const blocks = getElements("pre > code")
for (const [index, block] of blocks.entries()) {
blocks.forEach((block, index) => {
const parent = block.parentElement!
parent.id = `__code_${index}`
parent.insertBefore(renderClipboard(parent.id), block)
}
})
})
/* Initialize and setup clipboard */

View File

@@ -0,0 +1,186 @@
/*
* 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, Subject, fromEvent, merge } from "rxjs"
import {
bufferCount,
debounceTime,
distinctUntilChanged,
distinctUntilKeyChanged,
filter,
map,
pluck,
sample,
share,
withLatestFrom
} from "rxjs/operators"
import {
Viewport,
ViewportOffset,
getElement,
isLocationAnchor,
setLocationHash,
setViewportOffset
} from "browser"
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* History state
*/
interface State {
url: URL /* State URL */
offset?: ViewportOffset /* State viewport offset */
}
/* ------------------------------------------------------------------------- */
/**
* Setup options
*/
interface SetupOptions {
document$: Observable<Document> /* Document observable */
viewport$: Observable<Viewport> /* Viewport observable */
link$: Observable<HTMLAnchorElement> /* Internal link observable */
location$: Subject<URL> /* Location subject */
}
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Setup instant loading
*
* @param options - Options
*
* @return TODO ?
*/
export function setupInstantLoading(
{ document$, viewport$, link$, location$ }: SetupOptions
) { // TODO: add return type
const state$ = link$
.pipe(
map(el => ({ url: new URL(el.href) })),
share<State>()
)
/* Intercept internal links to dispatch */
const push$ = state$
.pipe(
distinctUntilChanged((prev, next) => prev.url.href === next.url.href),
filter(({ url }) => !isLocationAnchor(url)),
share()
)
/* Intercept popstate events (history back and forward) */
const pop$ = fromEvent<PopStateEvent>(window, "popstate")
.pipe(
filter(ev => ev.state !== null),
map<PopStateEvent, State>(ev => ({
url: new URL(location.href),
offset: ev.state
})),
share()
)
/* Emit location change */
merge(push$, pop$)
.pipe(
pluck("url")
)
.subscribe(location$)
/* History: dispatch internal link */
push$.subscribe(({ url }) => {
history.pushState({}, "", url.toString())
})
/* History: debounce update of viewport offset */
viewport$
.pipe(
debounceTime(250),
distinctUntilKeyChanged("offset")
)
.subscribe(({ offset }) => {
history.replaceState(offset, "")
})
/* Apply viewport offset from history */
merge(state$, pop$)
.pipe(
bufferCount(2, 1),
filter(([prev, next]) => {
return prev.url.pathname === next.url.pathname
&& !isLocationAnchor(next.url)
}),
map(([, state]) => state)
)
.subscribe(({ offset }) => {
setViewportOffset(offset || { y: 0 })
})
/* Intercept actual instant loading */
const instant$ = merge(push$, pop$)
.pipe(
sample(document$)
)
// TODO: from here on, everything is beta.... ###############################
instant$.subscribe(({ url, offset }) => {
if (url.hash && !offset) {
console.log("set hash!")
setLocationHash(url.hash) // must delay, if search is open!
} else {
setViewportOffset(offset || { y: 0 })
}
})
instant$
.pipe(
withLatestFrom(document$)
)
.subscribe(([, { title, head }]) => {
document.dispatchEvent(new CustomEvent("DOMContentSwitch"))
document.title = title
/* Replace meta tags */
for (const selector of [
`link[rel="canonical"]`,
`meta[name="author"]`,
`meta[name="description"]`
]) {
const next = getElement(selector, head)
const prev = getElement(selector, document.head)
if (
typeof next !== "undefined" &&
typeof prev !== "undefined"
) {
prev.replaceWith(next)
}
}
})
}

View File

@@ -25,24 +25,22 @@ import {
filter,
map,
share,
switchMap,
withLatestFrom
} from "rxjs/operators"
import { useComponent } from "components"
import {
Key,
getActiveElement,
getElement,
getElements,
getToggle,
isSusceptibleToKeyboard,
setElementFocus,
setElementSelection,
setToggle,
useToggle,
watchKeyboard,
watchToggle
} from "observables"
watchKeyboard
} from "browser"
import { useComponent } from "components"
/* ----------------------------------------------------------------------------
* Types
@@ -88,18 +86,10 @@ export interface Keyboard extends Key {
* @return Keyboard observable
*/
export function setupKeyboard(): Observable<Keyboard> {
const toggle$ = useToggle("search")
const search$ = toggle$
.pipe(
switchMap(watchToggle)
)
/* Setup keyboard and determine mode */
const keyboard$ = watchKeyboard()
.pipe(
withLatestFrom(search$),
map(([key, toggle]): Keyboard => ({
mode: toggle ? "search" : "global",
map<Key, Keyboard>(key => ({
mode: getToggle("search") ? "search" : "global",
...key
})),
share()
@@ -110,12 +100,11 @@ export function setupKeyboard(): Observable<Keyboard> {
.pipe(
filter(({ mode }) => mode === "search"),
withLatestFrom(
toggle$,
useComponent("search-query"),
useComponent("search-result")
)
)
.subscribe(([key, toggle, query, result]) => {
.subscribe(([key, query, result]) => {
const active = getActiveElement()
switch (key.type) {
@@ -128,7 +117,7 @@ export function setupKeyboard(): Observable<Keyboard> {
/* Escape or Tab: close search */
case "Escape":
case "Tab":
setToggle(toggle, false)
setToggle("search", false)
setElementFocus(query, false)
break

View File

@@ -20,8 +20,6 @@
* IN THE SOFTWARE.
*/
import * as escapeRegExp from "escape-string-regexp"
import { SearchIndexConfig } from "../_"
import { SearchDocument } from "../document"
@@ -78,7 +76,9 @@ export function setupSearchHighlighter(
/* Create search term match expression */
const match = new RegExp(`(^|${config.separator})(${
escapeRegExp(query).replace(separator, "|")
query
.replace(/[|\\{}()[\]^$+*?.-]/g, "\\$&") // TODO: taken from escape-string-regexp
.replace(separator, "|")
})`, "img")
/* Highlight document */

View File

@@ -1,24 +0,0 @@
/*
* 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.
*/
export * from "./agent"
export * from "./toggle"

View File

@@ -33,7 +33,7 @@ import {
getElement,
getElements,
watchMedia
} from "observables"
} from "browser"
/* ----------------------------------------------------------------------------
* Helper types

View File

@@ -23,8 +23,8 @@
import { Observable } from "rxjs"
import { map, skip, withLatestFrom } from "rxjs/operators"
import { getElements } from "browser"
import { useComponent } from "components"
import { getElements } from "observables"
/* ----------------------------------------------------------------------------
* Helper types

View File

@@ -23,7 +23,7 @@
import { NEVER, Observable, fromEvent, iif, merge } from "rxjs"
import { map, mapTo, shareReplay, switchMap } from "rxjs/operators"
import { getElements } from "observables"
import { getElements } from "browser"
/* ----------------------------------------------------------------------------
* Helper types

View File

@@ -23,7 +23,7 @@
import { NEVER, Observable } from "rxjs"
import { catchError, map, switchMap } from "rxjs/operators"
import { getElementOrThrow, getElements } from "observables"
import { getElementOrThrow, getElements } from "browser"
import { renderSource } from "templates"
import { cache, hash } from "utilities"

View File

@@ -23,7 +23,7 @@
import { Observable } from "rxjs"
import { map } from "rxjs/operators"
import { getElements } from "observables"
import { getElements } from "browser"
import { renderTable } from "templates"
/* ----------------------------------------------------------------------------

View File

@@ -20,21 +20,46 @@
* IN THE SOFTWARE.
*/
import { SearchIndexConfig, SearchIndexOptions } from "integrations/search"
/* ----------------------------------------------------------------------------
* Types
* ------------------------------------------------------------------------- */
/**
* Feature flags
*/
export type Feature =
| "tabs" /* Tabs navigation */
| "instant" /* Instant loading
/* ------------------------------------------------------------------------- */
/**
* URL configuration
*/
export interface UrlConfig {
base: string /* Base URL */
worker: {
search: string /* Search worker URL */
}
}
/**
* Search configuration
*/
export interface SearchConfig {
index?: Promise<SearchIndexOptions>
query?: (value: string) => string
}
/**
* Configuration
*/
export interface Config {
base: string /* Base URL */
worker: {
search: string /* Search worker URL */
}
feature: {
instant: true /* Instant loading */
}
url: UrlConfig
features: Feature[] /* Feature flags */
search?: SearchConfig
}
/* ----------------------------------------------------------------------------
@@ -53,7 +78,8 @@ export interface Config {
*/
export function isConfig(config: any): config is Config {
return typeof config === "object"
&& typeof config.base === "string"
&& typeof config.worker === "object"
&& typeof config.worker.search === "string"
&& typeof config.url === "object"
&& typeof config.url.base === "string"
&& typeof config.url.worker === "object"
&& typeof config.url.worker.search === "string"
}

View File

@@ -20,7 +20,25 @@
* IN THE SOFTWARE.
*/
import { getElementOrThrow } from "observables"
import { getElementOrThrow } from "browser"
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Translation keys
*/
type TranslateKey =
| "clipboard.copy" /* Copy to clipboard */
| "clipboard.copied" /* Copied to clipboard */
| "search.config.lang" /* Search language */
| "search.config.pipeline" /* Search pipeline */
| "search.config.separator" /* Search separator */
| "search.result.placeholder" /* Type to start searching */
| "search.result.none" /* No matching documents */
| "search.result.one" /* 1 matching document */
| "search.result.other" /* # matching documents */
/* ----------------------------------------------------------------------------
* Data
@@ -43,7 +61,7 @@ let lang: Record<string, string>
*
* @return Translation
*/
export function translate(key: string, value?: string): string {
export function translate(key: TranslateKey, value?: string): string {
if (typeof lang === "undefined") {
const el = getElementOrThrow("#__lang")
lang = JSON.parse(el.innerText)

View File

@@ -28,15 +28,14 @@ import {
shareReplay,
switchMap,
take,
tap,
withLatestFrom
} from "rxjs/operators"
import { SearchIndexOptions } from "integrations/search"
import {
WorkerHandler,
watchWorker
} from "observables"
import { WorkerHandler, watchWorker } from "browser"
import { SearchIndexConfig, SearchIndexOptions } from "integrations/search"
import { translate } from "utilities"
import {
SearchMessage,
SearchMessageType,
@@ -119,11 +118,39 @@ export function setupSearchWorker(
})
.pipe<SearchIndexOptions>(
pluck("response")
))
)
)
)
/* Send index to worker */
function isConfigDefaultLang(config: SearchIndexConfig) {
return config.lang.length === 1 && config.lang[0] === "en"
}
function isConfigDefaultSeparator(config: SearchIndexConfig) {
return config.separator === "[\s\-]+"
}
index$
.pipe(
map(({ config, ...rest }) => ({
config: {
lang: isConfigDefaultLang(config)
? [translate("search.config.lang")]
: config.lang,
separator: isConfigDefaultSeparator(config)
? translate("search.config.separator")
: config.separator
},
pipeline: translate("search.config.pipeline")
.split(/\s*,\s*/)
.filter(Boolean) as any, // Hack
...rest
}))
)
// .subscribe(console.log)
// /* Send index to worker */
// index$
.pipe<SearchSetupMessage>(
map(data => ({
type: SearchMessageType.SETUP,