Refactored search observable integration

This commit is contained in:
squidfunk 2020-02-13 16:49:08 +01:00
parent d8829769f8
commit e0e559b429
22 changed files with 507 additions and 93 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

View File

@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 89 89">
<path d="M3.136,17.387l0,42.932l42.932,21.467l-42.932,-64.399Z" style="fill: white;"/>
<path d="M21.91,8l42.933,64.398l-18.775,9.388l-42.932,-64.399l18.774,-9.387Z" style="fill: white; fill-opacity: 0.5;" />
<path d="M67.535,17.387l-26.244,19.683l20.86,31.291l5.384,2.691l0,-53.665Z" style="fill: white;" />
<path d="M67.535,17.387l-27.262,18.156l21.878,32.818l5.384,2.691l0,-53.665Z" style="fill: white;" />
<path d="M67.535,17.387l0,53.666l18.774,-9.388l0,-53.665l-18.774,9.387Z" style="fill: white; fill-opacity:0.25;" />
</svg>

Before

Width:  |  Height:  |  Size: 500 B

After

Width:  |  Height:  |  Size: 501 B

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{
"assets/javascripts/bundle.js": "assets/javascripts/bundle.65b5374b.min.js",
"assets/javascripts/bundle.js.map": "assets/javascripts/bundle.65b5374b.min.js.map",
"assets/javascripts/bundle.js": "assets/javascripts/bundle.53f51356.min.js",
"assets/javascripts/bundle.js.map": "assets/javascripts/bundle.53f51356.min.js.map",
"assets/javascripts/worker/packer.js": "assets/javascripts/worker/packer.c14659e8.min.js",
"assets/javascripts/worker/packer.js.map": "assets/javascripts/worker/packer.c14659e8.min.js.map",
"assets/javascripts/worker/search.js": "assets/javascripts/worker/search.ce66ce8d.min.js",

View File

@ -110,9 +110,11 @@
{% include "partials/hero.html" with context %}
{% endif %}
{% endblock %}
{% if feature.tabs %}
{% include "partials/tabs.html" %}
{% endif %}
{% block tabs %}
{% if feature.tabs %}
{% include "partials/tabs.html" %}
{% endif %}
{% endblock %}
<main class="md-main" data-md-component="main">
<div class="md-main__inner md-grid">
{% block site_nav %}
@ -188,7 +190,7 @@
{% endblock %}
</div>
{% block scripts %}
<script src="{{ 'assets/javascripts/bundle.65b5374b.min.js' | url }}"></script>
<script src="{{ 'assets/javascripts/bundle.53f51356.min.js' | url }}"></script>
<script id="__lang" type="application/json">
{%- set translations = {} -%}
{%- for key in [

View File

@ -24,3 +24,4 @@ export * from "./anchor"
export * from "./header"
export * from "./main"
export * from "./search"
export * from "./toggle"

View File

@ -0,0 +1,43 @@
/*
* 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.
*/
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Set toggle
*
* Simulating a click event seems to be the most cross-browser compatible way
* of changing the value while also emitting a `change` event. Before, Material
* used `CustomEvent` to programmatically change the value of a toggle, but this
* is a much simpler and cleaner solution.
*
* @param el - Toggle element
* @param value - Toggle value
*/
export function setToggle(
el: HTMLInputElement, value: boolean
): void {
if (el.checked !== value)
el.click()
}

View File

@ -20,14 +20,20 @@
* IN THE SOFTWARE.
*/
import { keys } from "ramda"
import { NEVER, Observable, of } from "rxjs"
import { map, scan, shareReplay, switchMap } from "rxjs/operators"
import { getElement } from "observables"
/* ----------------------------------------------------------------------------
* Types
* ------------------------------------------------------------------------- */
/**
* Component types
* Component
*/
export type ComponentType =
export type Component =
| "container" /* Container */
| "header" /* Header */
| "header-title" /* Header title */
@ -41,14 +47,111 @@ export type ComponentType =
| "tabs" /* Tabs */
| "toc" /* Table of contents */
/* ------------------------------------------------------------------------- */
/**
* Component map
*/
export type ComponentMap = {
[P in Component]?: HTMLElement
}
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Component
*
* @template T - Data type
* Watch options
*/
export interface Component<T extends {}> {
type: ComponentType /* Component type */
data?: T /* Component data */
interface WatchOptions {
document$: Observable<Document> /* Document observable */
}
/* ----------------------------------------------------------------------------
* Data
* ------------------------------------------------------------------------- */
/**
* Component map observable
*/
let components$: Observable<ComponentMap>
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Watch components with given names
*
* This function returns an observable that will maintain bindings to the given
* components in-between document switches and update the document in-place.
*
* @param names - Component names
* @param options - Options
*
* @return Component map observable
*/
export function watchComponentMap(
names: Component[], { document$ }: WatchOptions
): Observable<ComponentMap> {
components$ = document$
.pipe(
/* Build component map */
map(document => names.reduce<ComponentMap>((components, name) => {
const el = getElement(`[data-md-component=${name}]`, document)
return {
...components,
...typeof el !== "undefined" ? { [name]: el } : {}
}
}, {})),
/* Re-compute component map on document switch */
scan((prev, next) => {
for (const name of keys(prev)) {
switch (name) {
/* Top-level components: update */
case "header-title":
case "container":
if (name in prev && typeof prev[name] !== "undefined") {
prev[name]!.replaceWith(next[name]!)
prev[name] = next[name]
}
break
/* All other components: rebind */
default:
prev[name] = getElement(`[data-md-component=${name}]`)
}
}
return prev
})
)
/* Return component map as hot observable */
return components$
.pipe(
shareReplay(1)
)
}
/**
* Retrieve a component
*
* @template T - Element type
*
* @param name - Component name
*
* @return Element observable
*/
export function useComponent<T extends HTMLElement>(
name: Component
): Observable<T> {
return components$
.pipe(
switchMap(components => {
return typeof components[name] !== "undefined"
? of(components[name] as T)
: NEVER
})
)
}

View File

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

View File

@ -67,9 +67,9 @@ export type Navigation =
* ------------------------------------------------------------------------- */
/**
* Options
* Mount options
*/
interface Options {
interface MountOptions {
main$: Observable<Main> /* Main area observable */
viewport$: Observable<Viewport> /* Viewport offset observable */
screen$: Observable<boolean> /* Screen media observable */
@ -87,7 +87,7 @@ interface Options {
* @return Operator function
*/
function mountNavigationBelowScreen(
_options: Options
_options: MountOptions
): OperatorFunction<HTMLElement, NavigationBelowScreen> {
return pipe(
map(el => getElements("nav", el)),
@ -108,7 +108,7 @@ function mountNavigationBelowScreen(
* @return Operator function
*/
function mountNavigationAboveScreen(
options: Options
options: MountOptions
): OperatorFunction<HTMLElement, NavigationAboveScreen> {
return pipe(
switchMap(el => watchSidebar(el, options)
@ -132,7 +132,7 @@ function mountNavigationAboveScreen(
* @return Operator function
*/
export function mountNavigation(
options: Options
options: MountOptions
): OperatorFunction<HTMLElement, Navigation> {
return pipe(
switchMap(el => options.screen$

View File

@ -20,34 +20,42 @@
* IN THE SOFTWARE.
*/
import { identity } from "ramda"
import { Observable, OperatorFunction, pipe } from "rxjs"
import {
distinctUntilChanged,
filter,
map,
shareReplay,
switchMap
} from "rxjs/operators"
import { Observable, OperatorFunction, combineLatest, pipe } from "rxjs"
import { map, shareReplay, switchMap } from "rxjs/operators"
import { SearchResult } from "modules"
import {
SearchQuery,
Viewport,
paintSearchResult,
watchElementOffset
WorkerHandler,
} from "observables"
import { SearchMessage } from "workers"
import { useComponent } from "../_"
import { mountSearchQuery } from "./query"
import { mountSearchReset } from "./reset"
import { mountSearchResult } from "./result"
/* ----------------------------------------------------------------------------
* Types
* ------------------------------------------------------------------------- */
/**
* Search
*/
export interface Search {
query: SearchQuery /* Search query */
result: SearchResult[] /* Search result list */
}
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Options
* Mount options
*/
interface Options {
query$: Observable<SearchQuery> /* Search query observable */
result$: Observable<SearchResult[]> /* Search result observable */
interface MountOptions {
viewport$: Observable<Viewport> /* Viewport observable */
}
@ -56,35 +64,43 @@ interface Options {
* ------------------------------------------------------------------------- */
/**
* Mount search result from source observable
* Mount search from source observable
*
* @param handler - Worker handler
* @param options - Options
*
* @return Operator function
* @return Search observable
*/
export function mountSearchResult(
{ query$, result$, viewport$ }: Options
): OperatorFunction<HTMLElement, SearchResult[]> {
export function mountSearch(
handler: WorkerHandler<SearchMessage>, { viewport$ }: MountOptions
): OperatorFunction<HTMLElement, Search> {
return pipe(
switchMap(el => {
const container = el.parentElement!
switchMap(() => {
/* Compute whether there are more search results to fetch */
const fetch$ = watchElementOffset(container, { viewport$ })
/* Mount search query */
const query$ = useComponent<HTMLInputElement>("search-query")
.pipe(
map(({ y }) => {
return y >= container.scrollHeight - container.offsetHeight - 16
}),
distinctUntilChanged(),
filter(identity)
mountSearchQuery(handler)
)
/* Paint search results */
return result$
/* Mount search reset */
const reset$ = useComponent<HTMLInputElement>("search-reset")
.pipe(
paintSearchResult(el, { query$, fetch$ })
mountSearchReset()
)
}),
shareReplay(1)
/* Mount search result */
const result$ = useComponent("search-result")
.pipe(
mountSearchResult(handler, { viewport$, query$ })
)
/* Combine into a single hot observable */
return combineLatest([query$, result$, reset$])
.pipe(
map(([query, result]) => ({ query, result })),
shareReplay(1)
)
})
)
}

View File

@ -0,0 +1,89 @@
/*
* 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 { OperatorFunction, pipe } from "rxjs"
import {
distinctUntilKeyChanged,
map,
switchMap,
withLatestFrom
} from "rxjs/operators"
import { setToggle } from "actions"
import {
SearchQuery,
WorkerHandler,
useToggle,
watchSearchQuery
} from "observables"
import {
SearchMessage,
SearchMessageType,
SearchQueryMessage
} from "workers"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Mount search query from source observable
*
* @param handler - Worker handler
*
* @return Operator function
*/
export function mountSearchQuery(
{ tx$ }: WorkerHandler<SearchMessage>
): OperatorFunction<HTMLInputElement, SearchQuery> {
const toggle$ = useToggle("search")
return pipe(
switchMap(el => {
const query$ = watchSearchQuery(el)
/* Subscribe worker to search query */
query$
.pipe(
distinctUntilKeyChanged("value"),
map<SearchQuery, SearchQueryMessage>(({ value }) => ({
type: SearchMessageType.QUERY,
data: value
}))
)
.subscribe(tx$)
/* Toggle search on focus */
query$
.pipe(
distinctUntilKeyChanged("focus"),
withLatestFrom(toggle$)
)
.subscribe(([{ focus }, toggle]) => {
if (focus)
setToggle(toggle, focus)
})
/* Return search query */
return query$
})
)
}

View File

@ -0,0 +1,52 @@
/*
* 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 { NEVER, OperatorFunction, pipe } from "rxjs"
import {
switchMap,
switchMapTo,
tap,
withLatestFrom
} from "rxjs/operators"
import { watchSearchReset } from "observables"
import { useComponent } from "../../_"
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Mount search reset from source observable
*
* @return Operator function
*/
export function mountSearchReset(): OperatorFunction<HTMLElement, never> {
const query$ = useComponent<HTMLElement>("search-query")
return pipe(
switchMap(watchSearchReset),
withLatestFrom(query$),
tap(([, el]) => el.focus()),
switchMapTo(NEVER)
)
}

View File

@ -0,0 +1,99 @@
/*
* 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 { identity } from "ramda"
import { Observable, OperatorFunction, pipe } from "rxjs"
import {
distinctUntilChanged,
filter,
map,
pluck,
shareReplay,
switchMap
} from "rxjs/operators"
import { SearchResult } from "modules"
import {
SearchQuery,
Viewport,
WorkerHandler,
paintSearchResult,
watchElementOffset
} from "observables"
import {
SearchMessage,
isSearchResultMessage
} from "workers"
/* ----------------------------------------------------------------------------
* Helper types
* ------------------------------------------------------------------------- */
/**
* Mount options
*/
interface MountOptions {
query$: Observable<SearchQuery> /* Search query observable */
viewport$: Observable<Viewport> /* Viewport observable */
}
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
/**
* Mount search result from source observable
*
* @param handler - Worker handler
* @param options - Options
*
* @return Operator function
*/
export function mountSearchResult(
{ rx$ }: WorkerHandler<SearchMessage>,
{ query$, viewport$ }: MountOptions
): OperatorFunction<HTMLElement, SearchResult[]> {
return pipe(
switchMap(el => {
const container = el.parentElement!
/* Compute whether there are more search results to fetch */
const fetch$ = watchElementOffset(container, { viewport$ })
.pipe(
map(({ y }) => {
return y >= container.scrollHeight - container.offsetHeight - 16
}),
distinctUntilChanged(),
filter(identity)
)
/* Paint search results */
return rx$
.pipe(
filter(isSearchResultMessage),
pluck("data"),
paintSearchResult(el, { query$, fetch$ })
)
}),
shareReplay(1)
)
}

View File

@ -33,16 +33,18 @@ import { PackerMessage } from "../message"
/**
* Setup packer web worker
*
* @param worker - Worker instance
* @param options - Options
* @param url - Worker url
*
* @return Worker handler
*/
export function setupPackerWorker(
worker: Worker
url: string
): WorkerHandler<PackerMessage> {
const worker = new Worker(url)
/* Create communication channels */
const tx$ = new Subject<PackerMessage>()
const rx$ = watchWorker(worker, { message$: tx$ })
const rx$ = watchWorker(worker, { tx$ })
/* Return worker handler */
return { tx$, rx$ }

View File

@ -20,21 +20,16 @@
* IN THE SOFTWARE.
*/
import { Observable, Subject } from "rxjs"
import { Subject } from "rxjs"
import { ajax } from "rxjs/ajax"
import { distinctUntilKeyChanged, map, pluck } from "rxjs/operators"
import { map, pluck } from "rxjs/operators"
import { SearchIndexOptions } from "modules"
import {
SearchQuery,
WorkerHandler,
watchWorker
} from "observables"
import { WorkerHandler, watchWorker } from "observables"
import {
SearchMessage,
SearchMessageType,
SearchQueryMessage,
SearchSetupMessage,
isSearchResultMessage
} from "../message"
@ -44,11 +39,10 @@ import {
* ------------------------------------------------------------------------- */
/**
* Options
* Setup options
*/
interface Options {
interface SetupOptions {
base: string /* Base url */
query$: Observable<SearchQuery> /* Search query observable */
}
/* ----------------------------------------------------------------------------
@ -64,7 +58,7 @@ interface Options {
* @return Worker handler
*/
export function setupSearchWorker(
url: string, { base, query$ }: Options
url: string, { base }: SetupOptions
): WorkerHandler<SearchMessage> {
const worker = new Worker(url)
const prefix = new URL(base, location.href)
@ -100,17 +94,6 @@ export function setupSearchWorker(
)
.subscribe(tx$.next.bind(tx$))
/* Subscribe to search query */
query$
.pipe(
distinctUntilKeyChanged("value"),
map<SearchQuery, SearchQueryMessage>(query => ({
type: SearchMessageType.QUERY,
data: query.value
}))
)
.subscribe(tx$.next.bind(tx$))
/* Return worker handler */
return { tx$, rx$ }
}

View File

@ -41,7 +41,7 @@
// Hack: putting the header on the GPU avoids unnecessary repaints
backface-visibility: hidden;
// Always show shadow, in case JavaScript is not available
// Always hide shadow, in case JavaScript is not available
.no-js & {
transition: none;
box-shadow: none;