Replaced operators: ajax -> fetch, pluck -> map

This commit is contained in:
squidfunk
2020-09-27 22:19:38 +02:00
parent 0c4ddfcd70
commit ab513f036e
32 changed files with 116 additions and 170 deletions

View File

@@ -22,7 +22,7 @@
import { Observable, Subject, fromEvent } from "rxjs"
import {
pluck,
map,
share,
switchMapTo,
tap,
@@ -90,7 +90,7 @@ export function watchWorker<T extends WorkerMessage>(
/* Intercept messages from worker-like objects */
const rx$ = fromEvent<MessageEvent>(worker, "message")
.pipe<T>(
pluck("data")
map(({ data }) => data)
)
/* Send and receive messages, return hot observable */

View File

@@ -33,7 +33,6 @@ import {
finalize,
map,
observeOn,
pluck,
switchMap,
tap
} from "rxjs/operators"
@@ -82,7 +81,7 @@ export function watchMain(
/* Compute necessary adjustment for header */
const adjust$ = header$
.pipe(
pluck("height"),
map(({ height }) => height),
distinctUntilChanged()
)

View File

@@ -26,7 +26,6 @@ import {
filter,
map,
mapTo,
pluck,
startWith,
switchMap
} from "rxjs/operators"
@@ -93,7 +92,7 @@ export function mountSearchResult(
return rx$
.pipe(
filter(isSearchResultMessage),
pluck("data"),
map(({ data }) => data),
applySearchResult(el, { query$, ready$, fetch$ }),
startWith([])
)

View File

@@ -36,7 +36,6 @@ import {
of,
NEVER
} from "rxjs"
import { ajax } from "rxjs/ajax"
import {
delay,
switchMap,
@@ -46,7 +45,6 @@ import {
observeOn,
take,
shareReplay,
pluck,
catchError,
map
} from "rxjs/operators"
@@ -94,7 +92,7 @@ import {
patchSource,
patchScripts
} from "patches"
import { isConfig, translate } from "utilities"
import { isConfig } from "utilities"
/* ------------------------------------------------------------------------- */
@@ -134,38 +132,6 @@ export function resetScrollLock(
window.scrollTo(0, value)
}
/* ----------------------------------------------------------------------------
* Helper functions
* ------------------------------------------------------------------------- */
/**
* Set up search index
*
* @param data - Search index
*
* @return Search index
*/
function setupSearchIndex( // Hack: move this outside here, temporarily...
{ config, docs, index }: SearchIndex
): SearchIndex {
/* Override default language with value from translation */
if (config.lang.length === 1 && config.lang[0] === "en")
config.lang = [translate("search.config.lang")]
/* Override default separator with value from translation */
if (config.separator === "[\\s\\-]+")
config.separator = translate("search.config.separator")
/* Set pipeline from translation */
const pipeline = translate("search.config.pipeline")
.split(/\s*,\s*/)
.filter(Boolean) as SearchIndexPipeline
/* Return search index after defaulting */
return { config, docs, index, pipeline }
}
/* ----------------------------------------------------------------------------
* Functions
* ------------------------------------------------------------------------- */
@@ -277,21 +243,11 @@ export function initialize(config: unknown) {
? from(index)
: base$
.pipe(
switchMap(base => ajax({
url: `${base}/search/search_index.json`,
responseType: "json",
withCredentials: true
})
.pipe<SearchIndex>(
pluck("response")
)
)
switchMap(base => fetch(`${base}/search/search_index.json`, {
credentials: "same-origin"
}).then(res => res.json())) // SearchIndex
)
)
.pipe(
map(setupSearchIndex),
shareReplay(1)
)
return of(setupSearchWorker(config.search.worker, {
base$, index$
@@ -396,19 +352,15 @@ export function initialize(config: unknown) {
config.features.includes("navigation.instant") &&
location.protocol !== "file:"
) {
const dom = new DOMParser()
/* Fetch sitemap and extract URL whitelist */
base$
.pipe(
switchMap(base => ajax({
url: `${base}/sitemap.xml`,
responseType: "document",
withCredentials: true
})
.pipe<Document>(
pluck("response")
)
),
switchMap(base => from(fetch(`${base}/sitemap.xml`)
.then(res => res.text())
.then(text => dom.parseFromString(text, "text/xml"))
)),
withLatestFrom(base$),
map(([document, base]) => {
const urls = getElements("loc", document)

View File

@@ -20,8 +20,7 @@
* IN THE SOFTWARE.
*/
import { NEVER, Observable, Subject, fromEvent, merge, of } from "rxjs"
import { ajax } from "rxjs//ajax"
import { NEVER, Observable, Subject, from, fromEvent, merge, of } from "rxjs"
import {
bufferCount,
catchError,
@@ -30,7 +29,6 @@ import {
distinctUntilKeyChanged,
filter,
map,
pluck,
sample,
share,
skip,
@@ -168,7 +166,7 @@ export function setupInstantLoading(
merge(push$, pop$)
.pipe(
distinctUntilChanged((prev, next) => prev.url.href === next.url.href),
pluck("url")
map(({ url }) => url)
)
.subscribe(location$)
@@ -177,11 +175,9 @@ export function setupInstantLoading(
.pipe(
distinctUntilKeyChanged("pathname"),
skip(1),
switchMap(url => ajax({
url: url.href,
responseType: "text",
withCredentials: true
})
switchMap(url => from(fetch(url.href, {
credentials: "same-origin"
}).then(res => res.text()))
.pipe(
catchError(() => {
setLocation(url)
@@ -205,7 +201,7 @@ export function setupInstantLoading(
const dom = new DOMParser()
ajax$
.pipe(
map(({ response }) => dom.parseFromString(response, "text/html"))
map(response => dom.parseFromString(response, "text/html"))
)
.subscribe(document$)

View File

@@ -82,7 +82,7 @@ export type SearchIndexPipeline = SearchIndexPipelineFn[]
export interface SearchIndex {
config: SearchIndexConfig /* Search index configuration */
docs: SearchIndexDocument[] /* Search index documents */
index?: object | string /* Prebuilt or serialized index */
index?: object /* Prebuilt index */
pipeline?: SearchIndexPipeline /* Search index pipeline */
}
@@ -204,13 +204,9 @@ export class Search {
this.add(doc)
})
/* Handle prebuilt or serialized index */
/* Handle prebuilt index */
} else {
this.index = lunr.Index.load(
typeof index === "string"
? JSON.parse(index)
: index
)
this.index = lunr.Index.load(index)
}
}

View File

@@ -20,6 +20,7 @@
* IN THE SOFTWARE.
*/
// @ts-ignore
import * as escapeHTML from "escape-html"
import { SearchIndexDocument } from "../_"

View File

@@ -30,13 +30,14 @@ import {
import { WorkerHandler, watchWorker } from "browser"
import { SearchIndex } from "../../_"
import { SearchIndex, SearchIndexPipeline } from "../../_"
import {
SearchMessage,
SearchMessageType,
SearchSetupMessage,
isSearchResultMessage
} from "../message"
import { translate } from "utilities"
/* ----------------------------------------------------------------------------
* Helper types
@@ -54,6 +55,38 @@ interface SetupOptions {
* Functions
* ------------------------------------------------------------------------- */
/**
* Set up search index
*
* @param data - Search index
*
* @return Search index
*/
function setupSearchIndex(
{ config, docs, index }: SearchIndex
): SearchIndex {
/* Override default language with value from translation */
if (config.lang.length === 1 && config.lang[0] === "en")
config.lang = [translate("search.config.lang")]
/* Override default separator with value from translation */
if (config.separator === "[\\s\\-]+")
config.separator = translate("search.config.separator")
/* Set pipeline from translation */
const pipeline = translate("search.config.pipeline")
.split(/\s*,\s*/)
.filter(Boolean) as SearchIndexPipeline
/* Return search index after defaulting */
return { config, docs, index, pipeline }
}
/* ----------------------------------------------------------------------------
* Helper functions
* ------------------------------------------------------------------------- */
/**
* Set up search web worker
*
@@ -92,7 +125,7 @@ export function setupSearchWorker(
.pipe(
map<SearchIndex, SearchSetupMessage>(data => ({
type: SearchMessageType.SETUP,
data
data: setupSearchIndex(data)
})),
observeOn(asyncScheduler)
)

View File

@@ -22,11 +22,7 @@
import "lunr"
import {
Search,
SearchIndex,
SearchIndexConfig
} from "../../_"
import { Search, SearchIndexConfig } from "../../_"
import {
SearchMessage,
SearchMessageType
@@ -63,20 +59,6 @@ let index: Search
* Helper functions
* ------------------------------------------------------------------------- */
/**
* Fetch search index from given URL
*
* @param url - Search index URL
*
* @return Promise resolving with search index
*/
async function fetchSearchIndex(url: string): Promise<SearchIndex> {
return fetch(url, {
credentials: "same-origin"
})
.then(res => res.json())
}
/**
* Fetch (= import) multi-language support through `lunr-languages`
*
@@ -143,13 +125,8 @@ export async function handler(
/* Search setup message */
case SearchMessageType.SETUP:
const data = typeof message.data === "string"
? await fetchSearchIndex(message.data)
: message.data
/* Set up search index with multi-language support */
await setupSearchLanguages(data.config)
index = new Search(data)
await setupSearchLanguages(message.data.config)
index = new Search(message.data)
return {
type: SearchMessageType.READY
}

View File

@@ -43,7 +43,7 @@ export const enum SearchMessageType {
*/
export interface SearchSetupMessage {
type: SearchMessageType.SETUP /* Message type */
data: SearchIndex | string /* Message data */
data: SearchIndex /* Message data */
}
/**

View File

@@ -21,9 +21,8 @@
*/
import { Repo, User } from "github-types"
import { Observable } from "rxjs"
import { ajax } from "rxjs/ajax"
import { filter, map, pluck } from "rxjs/operators"
import { Observable, from } from "rxjs"
import { filter, map } from "rxjs/operators"
import { round } from "utilities"
@@ -44,20 +43,17 @@ import { SourceFacts } from ".."
export function fetchSourceFactsFromGitHub(
user: string, repo?: string
): Observable<SourceFacts> {
return ajax({
url: typeof repo !== "undefined"
? `https://api.github.com/repos/${user}/${repo}`
: `https://api.github.com/users/${user}`,
responseType: "json"
})
const url = typeof repo !== "undefined"
? `https://api.github.com/repos/${user}/${repo}`
: `https://api.github.com/users/${user}`
return from(fetch(url).then(res => res.json()))
.pipe(
filter(({ status }) => status === 200),
pluck("response"),
map(data => {
map(({ response }) => {
/* GitHub repository */
if (typeof repo !== "undefined") {
const { stargazers_count, forks_count }: Repo = data
const { stargazers_count, forks_count }: Repo = response
return [
`${round(stargazers_count || 0)} Stars`,
`${round(forks_count || 0)} Forks`
@@ -65,7 +61,7 @@ export function fetchSourceFactsFromGitHub(
/* GitHub user/organization */
} else {
const { public_repos }: User = data
const { public_repos }: User = response
return [
`${round(public_repos || 0)} Repositories`
]

View File

@@ -21,9 +21,8 @@
*/
import { ProjectSchema } from "gitlab"
import { Observable } from "rxjs"
import { ajax } from "rxjs/ajax"
import { filter, map, pluck } from "rxjs/operators"
import { Observable, from } from "rxjs"
import { filter, map } from "rxjs/operators"
import { round } from "utilities"
@@ -44,13 +43,11 @@ import { SourceFacts } from ".."
export function fetchSourceFactsFromGitLab(
base: string, project: string
): Observable<SourceFacts> {
return ajax({
url: `https://${base}/api/v4/projects/${encodeURIComponent(project)}`,
responseType: "json"
})
const url = `https://${base}/api/v4/projects/${encodeURIComponent(project)}`
return from(fetch(url).then(res => res.json()))
.pipe(
filter(({ status }) => status === 200),
pluck("response"),
map(({ response }) => response),
map(({ star_count, forks_count }: ProjectSchema) => ([
`${round(star_count)} Stars`,
`${round(forks_count)} Forks`