diff --git a/src/assets/javascripts/observables/agent/worker/index.ts b/src/assets/javascripts/observables/agent/worker/index.ts index 64c86d520..848c995df 100644 --- a/src/assets/javascripts/observables/agent/worker/index.ts +++ b/src/assets/javascripts/observables/agent/worker/index.ts @@ -20,7 +20,7 @@ * IN THE SOFTWARE. */ -import { Observable, Subject, fromEvent } from "rxjs" +import { Observable, Subject, fromEvent, fromEventPattern } from "rxjs" import { pluck, share, @@ -87,8 +87,10 @@ export function watchWorker( worker: Worker, { tx$ }: WatchOptions ): Observable { - /* Intercept messages from web worker */ - const rx$ = fromEvent(worker, "message") + /* Intercept messages from worker-like objects */ + const rx$ = fromEventPattern(next => + worker.addEventListener("message", next) + ) .pipe( pluck("data") ) diff --git a/src/assets/javascripts/workers/search/_/index.ts b/src/assets/javascripts/workers/search/_/index.ts index 7a7c7c00b..b9827d1f8 100644 --- a/src/assets/javascripts/workers/search/_/index.ts +++ b/src/assets/javascripts/workers/search/_/index.ts @@ -20,7 +20,7 @@ * IN THE SOFTWARE. */ -import { Subject } from "rxjs" +import { Subject, from } from "rxjs" import { ajax } from "rxjs/ajax" import { map, pluck } from "rxjs/operators" @@ -43,6 +43,7 @@ import { */ interface SetupOptions { base: string /* Base url */ + index?: Promise /* Promise resolving with index */ } /* ---------------------------------------------------------------------------- @@ -68,13 +69,18 @@ function resolve(base: URL | string, ...paths: string[]) { /** * Setup search web worker * + * This function will create a web worker to setup and query the search index + * which is done using `lunr`. The index can be passed explicitly in order to + * enable hacks like _localsearch_ via search index embedding as JSON. If no + * index is given, this function will load it from the default location. + * * @param url - Worker url * @param options - Options * * @return Worker handler */ export function setupSearchWorker( - url: string, { base }: SetupOptions + url: string, { base, index }: SetupOptions ): WorkerHandler { const worker = new Worker(url) const prefix = new URL(base, location.href) @@ -95,15 +101,22 @@ export function setupSearchWorker( }) ) - /* Fetch index and setup search worker */ - ajax({ - url: resolve(prefix, "search/search_index.json"), - responseType: "json", - withCredentials: true - }) - .pipe( - pluck("response"), - map(data => ({ + /* Fetch index if it wasn't passed explicitly */ + const index$ = typeof index !== "undefined" + ? from(index) + : ajax({ + url: resolve(prefix, "search/search_index.json"), + responseType: "json", + withCredentials: true + }) + .pipe( + pluck("response") + ) + + /* Send index to search worker */ + index$ + .pipe( + map(data => ({ type: SearchMessageType.SETUP, data }))