@embedpdf/plugin-search 3.0.0-next.2 → 3.0.0-next.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,349 +1,403 @@
1
- import { createCapabilityToken, definePlugin } from "@embedpdf/core";
2
- import { StageToken } from "@embedpdf/plugin-stage";
3
- import { applyRect, boundsOfRects, pageGeometry } from "@embedpdf/core-geometry";
4
- import { EngineError, EngineErrorCode, validateSearchQuery, validateSearchRegex } from "@embedpdf/engine-core/runtime";
5
- //#region src/capability.ts
6
- const EMPTY = [];
7
- /** The browser find-bar feel: hit at the top-middle, no zoom change. */
8
- const DEFAULT_REVEAL = {
9
- anchor: { y: .35 },
10
- behavior: "smooth"
1
+ import { i as SearchToken, n as validateSearchQuery, r as validateSearchRegex, t as SEARCH_DEFAULTS } from "./contract-uWSW5IYM.js";
2
+ import { PluginError, definePlugin, defineState, isPluginError, pageRefsEqual, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
3
+ import { StageToken } from "@embedpdf/plugin-stage/contract";
4
+ import { boundsOfRects } from "@embedpdf/core-geometry";
5
+ //#region src/model.ts
6
+ /**
7
+ * The search session: the query, the hits found so far (also grouped by
8
+ * page), the active hit, and progress. Every function below is a pure
9
+ * transition; the controller applies them with `ctx.state.update`.
10
+ */
11
+ /** The progress of no search, one object for every session that hasn't searched a page yet. */
12
+ const NO_PROGRESS = Object.freeze({
13
+ pagesSearched: 0,
14
+ pageCount: 0
15
+ });
16
+ const initialSearchModel = () => ({
17
+ query: null,
18
+ status: "idle",
19
+ operationId: null,
20
+ hits: [],
21
+ hitsByPage: {},
22
+ activeHitIndex: -1,
23
+ progress: NO_PROGRESS,
24
+ error: null
25
+ });
26
+ /** A new scan starts: everything from the previous session is dropped. */
27
+ const startSession = (_state, query, operationId) => ({
28
+ ...initialSearchModel(),
29
+ query,
30
+ status: "searching",
31
+ operationId
32
+ });
33
+ const sameProgress = (left, right) => left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;
34
+ /**
35
+ * A slice of hits arrived. The first hit becomes active so "1 of N" reads
36
+ * right; moving the camera is navigation's job, not the stream's. Progress
37
+ * with the same counts keeps its object: readers, and `onProgressChanged`,
38
+ * see a change only when the counts change.
39
+ */
40
+ function appendHits(state, hits, slice) {
41
+ const progress = sameProgress(state.progress, slice) ? state.progress : slice;
42
+ if (hits.length === 0) return progress === state.progress ? state : {
43
+ ...state,
44
+ progress
45
+ };
46
+ const hitsByPage = { ...state.hitsByPage };
47
+ for (const hit of hits) {
48
+ const pageObjectNumber = hit.page.objectNumber;
49
+ hitsByPage[pageObjectNumber] = [...hitsByPage[pageObjectNumber] ?? [], hit];
50
+ }
51
+ return {
52
+ ...state,
53
+ hits: [...state.hits, ...hits],
54
+ hitsByPage,
55
+ activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,
56
+ progress
57
+ };
58
+ }
59
+ const completeSession = (state) => ({
60
+ ...state,
61
+ status: "complete"
62
+ });
63
+ const cancelSession = (state) => ({
64
+ ...state,
65
+ status: "cancelled"
66
+ });
67
+ const failSession = (state, error) => ({
68
+ ...state,
69
+ status: "error",
70
+ error
71
+ });
72
+ const setActiveHit = (state, index) => state.activeHitIndex === index ? state : {
73
+ ...state,
74
+ activeHitIndex: index
11
75
  };
12
- /** Local engines reject a denied scope before the worker; cloud maps 403. */
13
- const isPermissionDenied = (err) => err instanceof Error && err.name === "PermissionDenied" || EngineError.is(err, EngineErrorCode.Forbidden);
76
+ const clearSession = (state) => state.status === "idle" ? state : initialSearchModel();
77
+ /**
78
+ * Where `hit` is in `hits`: the same object, or else the hit that covers the
79
+ * same characters of the same page, so a hit kept from before the search ran
80
+ * again still finds its place. -1 when it isn't there.
81
+ */
82
+ function indexOfHit(hits, hit) {
83
+ const same = hits.indexOf(hit);
84
+ if (same >= 0) return same;
85
+ return hits.findIndex((candidate) => candidate.start === hit.start && candidate.count === hit.count && pageRefsEqual(candidate.page, hit.page));
86
+ }
87
+ /**
88
+ * The pages that have at least one hit, in document order: `pages` is the
89
+ * document's page list, whose order moving a page changes (object numbers
90
+ * don't follow it).
91
+ */
92
+ const pagesWithHits = (state, pages) => pages.filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0).map((page) => page.ref);
93
+ //#endregion
94
+ //#region src/controller.ts
95
+ const EMPTY = Object.freeze([]);
96
+ const EMPTY_PAGES = Object.freeze([]);
97
+ /** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */
98
+ const RERUN_DELAY_MS = 250;
14
99
  /**
15
- * The search capability: a client-driven cursor loop over the engine's
16
- * budgeted slices. One generation counter arbitrates: a new `search()` (or
17
- * `clear()`, or a document mutation via `rerun()`) supersedes the running
18
- * loop, which aborts its in-flight slice and stops dispatching.
100
+ * The search controller. `search` runs on a `latest` lane (a newer search
101
+ * supersedes the older one, which can no longer publish); `findAll` runs on
102
+ * its own signal and never touches the session. Both share `collect`, the
103
+ * one cursor loop over the engine's budgeted slices.
19
104
  *
20
- * Rect conversion happens HERE, once per slice: the engine's PDF-space
21
- * line rects → content space through the same page geometry the selection
22
- * plugin uses, so search highlights and selection highlights are pixel-twins.
105
+ * The scan's own events (started, completed, cancelled, failed) fire where
106
+ * the scan reaches those points. The progress, active-hit and cleared events
107
+ * are derived from state changes, so they always agree with the getters.
23
108
  *
24
- * Stage integration is optional and additive: with a Stage present the scan
25
- * starts at the current page (viewport-first — the hits the user is looking
26
- * at arrive in the first slice) and `next()`/`prev()`/`goTo()` reveal the
27
- * hit's page. Without one, navigation still works; the host scrolls.
109
+ * The settings are read where they're used, never copied, so
110
+ * `updateSettings({ reveal })` applies to the next move at once.
28
111
  */
29
- function createSearchCapability(ctx, config = {}) {
30
- let generation = 0;
31
- let inflight = null;
32
- const toContent = (m, b) => applyRect(m, {
33
- x: b.left,
34
- y: b.bottom,
35
- width: b.right - b.left,
36
- height: b.top - b.bottom
112
+ function createSearchController(ctx) {
113
+ const settings = ctx.settings();
114
+ const session = ctx.latest("session");
115
+ const started = ctx.events.source();
116
+ const progressChanged = ctx.events.source();
117
+ const completed = ctx.events.source();
118
+ const cancelled = ctx.events.source();
119
+ const failed = ctx.events.source();
120
+ const activeHitChanged = ctx.events.source();
121
+ const cleared = ctx.events.source();
122
+ const state = () => ctx.state.get();
123
+ ctx.state.onChange(({ previous, next }) => {
124
+ if (previous.progress !== next.progress) progressChanged.emit({
125
+ ...next.progress,
126
+ hitCount: next.hits.length
127
+ });
128
+ if (previous.activeHitIndex !== next.activeHitIndex) activeHitChanged.emit({
129
+ index: next.activeHitIndex,
130
+ hit: next.hits[next.activeHitIndex] ?? null
131
+ });
132
+ if (previous.status !== "idle" && next.status === "idle") cleared.emit({});
37
133
  });
38
134
  function hitsFromSlice(slice) {
39
- const converters = /* @__PURE__ */ new Map();
40
- const converterFor = (pon) => {
41
- let conv = converters.get(pon);
42
- if (conv !== void 0) return conv;
43
- const layout = ctx.document()?.pages.find((p) => p.pageObjectNumber === pon);
44
- if (!layout) conv = null;
45
- else {
46
- const { pdfToContent } = pageGeometry({
47
- crop: layout.boxes.crop,
48
- rotation: layout.rotation,
49
- userUnit: layout.userUnit
50
- }, 1);
51
- conv = {
52
- pageIndex: layout.index,
53
- toRect: (b) => toContent(pdfToContent, b)
54
- };
55
- }
56
- converters.set(pon, conv);
57
- return conv;
58
- };
59
135
  const hits = [];
60
136
  for (const match of slice.matches) {
61
- const conv = converterFor(match.pageObjectNumber);
62
- if (!conv) continue;
137
+ const page = ctx.getPage(match.page);
138
+ if (!page) continue;
139
+ const segments = match.segments;
63
140
  hits.push({
64
- pon: match.pageObjectNumber,
65
- pageIndex: conv.pageIndex,
66
- charStart: match.charStart,
67
- charCount: match.charCount,
68
- rects: match.rects.map(conv.toRect),
141
+ page: match.page,
142
+ pageIndex: page.index,
143
+ start: match.start,
144
+ count: match.count,
145
+ segments,
146
+ ...segments.length ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? void 0 } : {},
69
147
  ...match.snippet ? { snippet: match.snippet } : {}
70
148
  });
71
149
  }
72
150
  return hits;
73
151
  }
74
152
  /**
75
- * THE MECHANISM — one cursor loop over the engine's budgeted slices,
76
- * shared by the session (`search`) and the session-free service
77
- * (`findAll`): permission fallback ('full' → 'rects' when snippets are
78
- * denied, unless the caller pinned a mode), restart-once on a stale
79
- * cursor, rect conversion per slice. Resolves true on exhaustion, false
80
- * when cancelled; throws on error.
153
+ * One cursor loop over budgeted slices: permission fallback (snippets → none
154
+ * when they are denied, unless pinned), restart-once on a stale cursor,
155
+ * projection per slice. Returns true on exhaustion, false when the signal
156
+ * aborted; throws on a real error (already a PluginError: ctx.doc is guarded).
81
157
  */
82
- async function collect(query, opts, sink) {
83
- const doc = ctx.doc;
84
- if (!doc) return false;
158
+ async function collect(query, options, sink) {
159
+ const { signal } = options;
85
160
  sink.onStart();
86
- let mode = opts.mode ?? "full";
87
- const modePinned = opts.mode !== void 0;
161
+ let snippets = options.snippets ?? true;
162
+ const snippetsPinned = options.snippets !== void 0;
88
163
  let cursor;
89
164
  let restarted = false;
90
165
  for (;;) {
166
+ if (signal?.aborted) return false;
91
167
  let slice;
168
+ const request = {
169
+ ...query,
170
+ snippets,
171
+ ...cursor !== void 0 ? { cursor } : options.from !== void 0 ? { from: options.from } : {}
172
+ };
92
173
  try {
93
- const request = {
94
- query,
95
- mode,
96
- ...cursor !== void 0 ? { cursor } : opts.startPage !== void 0 ? { startPage: opts.startPage } : {}
97
- };
98
- const pending = doc.search.query(request);
99
- sink.setInflight(pending);
100
- slice = await pending;
101
- } catch (err) {
102
- if (sink.isCancelled()) return false;
103
- if (!modePinned && mode === "full" && cursor === void 0 && isPermissionDenied(err)) {
104
- mode = "rects";
174
+ slice = await ctx.cancellable(signal, ctx.doc.with({ priority: "low" }).search.query(request));
175
+ } catch (error) {
176
+ if (signal?.aborted) return false;
177
+ if (!snippetsPinned && snippets && cursor === void 0 && isPluginError(error, "permission-denied")) {
178
+ snippets = false;
105
179
  continue;
106
180
  }
107
- if (cursor !== void 0 && !restarted && EngineError.is(err, EngineErrorCode.InvalidArg)) {
181
+ if (cursor !== void 0 && !restarted && isPluginError(error, "invalid-input")) {
108
182
  restarted = true;
109
183
  cursor = void 0;
110
184
  sink.onStart();
111
185
  continue;
112
186
  }
113
- throw err;
114
- }
115
- if (sink.isCancelled()) return false;
116
- sink.onSlice(hitsFromSlice(slice), slice.scannedPages, slice.totalPages);
117
- if (slice.nextCursor === null) {
118
- sink.setInflight(null);
119
- return true;
187
+ throw error;
120
188
  }
189
+ if (signal?.aborted) return false;
190
+ sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);
191
+ if (slice.nextCursor === null) return true;
121
192
  cursor = slice.nextCursor;
122
193
  }
123
194
  }
124
- /** THE SESSION — collect() with state as the sink, generation-guarded. */
125
- async function runSession(query, startPage) {
126
- const gen = ++generation;
127
- inflight?.abort("superseded");
128
- inflight = null;
129
- if (!ctx.doc) {
130
- ctx.dispatch({ type: "CLEAR" });
131
- return;
132
- }
133
- if (startPage === void 0) {
134
- const stage = ctx.tryGet(StageToken);
135
- if (stage) startPage = ctx.document()?.pages[stage.currentPage()]?.pageObjectNumber;
195
+ const viewportFirstPage = () => {
196
+ return ctx.tryGet(StageToken)?.getCurrentPage() ?? void 0;
197
+ };
198
+ async function search(query, options = {}) {
199
+ if (query.text.length === 0) {
200
+ clear();
201
+ return {
202
+ status: "complete",
203
+ hitCount: 0
204
+ };
136
205
  }
137
- try {
138
- if (await collect(query, { startPage }, {
139
- onStart: () => ctx.dispatch({
140
- type: "START",
141
- query
142
- }),
143
- onSlice: (hits, scanned, total) => ctx.dispatch({
144
- type: "APPEND",
145
- hits,
146
- scanned,
147
- total
206
+ ctx.assertAllowed("doc.text.search", "search");
207
+ const from = options.from === void 0 ? viewportFirstPage() : ctx.pageOf(options.from).ref;
208
+ let operationId = "";
209
+ return session.run(async (run) => {
210
+ operationId = run.id;
211
+ if (!await collect(query, {
212
+ from,
213
+ signal: run.signal
214
+ }, {
215
+ onStart: () => run.commit(() => {
216
+ ctx.state.update(startSession, query, run.id);
217
+ started.emit({ query });
148
218
  }),
149
- isCancelled: () => gen !== generation,
150
- setInflight: (pending) => {
151
- if (gen === generation) inflight = pending;
152
- }
153
- }) && gen === generation) ctx.dispatch({ type: "COMPLETE" });
154
- } catch (err) {
155
- if (gen !== generation) return;
156
- ctx.dispatch({
157
- type: "ERROR",
158
- message: err instanceof Error ? err.message : String(err)
219
+ onSlice: (hits, pagesSearched, pageCount) => run.commit(() => ctx.state.update(appendHits, hits, {
220
+ pagesSearched,
221
+ pageCount
222
+ }))
223
+ })) throw new PluginError("operation-cancelled", "search", "search aborted");
224
+ run.commit(() => {
225
+ ctx.state.update(completeSession);
226
+ completed.emit({ hitCount: state().hits.length });
159
227
  });
160
- }
228
+ return {
229
+ status: "complete",
230
+ hitCount: state().hits.length
231
+ };
232
+ }, options).catch((error) => {
233
+ if (isPluginError(error, "instance-closed")) return {
234
+ status: "cancelled",
235
+ hitCount: 0
236
+ };
237
+ if (isPluginError(error, "operation-cancelled")) {
238
+ const why = error.details?.reason ?? "cancelled";
239
+ const reason = why === "superseded" ? "superseded" : why === "cleared" ? "cleared" : "cancelled";
240
+ if (reason === "cancelled" && state().operationId === operationId) ctx.state.update(cancelSession);
241
+ cancelled.emit({ reason });
242
+ return {
243
+ status: reason === "superseded" ? "superseded" : "cancelled",
244
+ hitCount: state().hits.length
245
+ };
246
+ }
247
+ const info = toPluginErrorInfo(toPluginError("search", error));
248
+ if (state().operationId === operationId) ctx.state.update(failSession, info);
249
+ failed.emit({ error: info });
250
+ throw error;
251
+ });
252
+ }
253
+ function clear() {
254
+ session.cancel("cleared");
255
+ ctx.state.update(clearSession);
161
256
  }
162
- function goTo(index, reveal) {
163
- const { hits } = ctx.getState();
257
+ function goToHit(target, options) {
258
+ const { hits } = state();
164
259
  if (hits.length === 0) return null;
165
- const wrapped = (index % hits.length + hits.length) % hits.length;
166
- ctx.dispatch({
167
- type: "SET_ACTIVE",
168
- index: wrapped
169
- });
170
- const hit = hits[wrapped];
260
+ const index = typeof target === "number" ? (target % hits.length + hits.length) % hits.length : indexOfHit(hits, target);
261
+ if (index < 0) return null;
262
+ ctx.state.update(setActiveHit, index);
263
+ reveal(hits[index], options);
264
+ return hits[index];
265
+ }
266
+ function reveal(hit, options) {
171
267
  const arrival = {
172
- ...DEFAULT_REVEAL,
173
- ...config.reveal,
174
- ...reveal
268
+ ...settings.get().reveal,
269
+ ...options
175
270
  };
176
- ctx.tryGet(StageToken)?.reveal(hit.pageIndex, {
177
- rect: boundsOfRects(hit.rects) ?? void 0,
271
+ ctx.tryGet(StageToken)?.reveal(hit.page, {
272
+ rect: hit.bounds,
178
273
  anchor: arrival.anchor,
179
274
  behavior: arrival.behavior
180
275
  });
181
- return hit;
182
276
  }
183
- const clear = () => {
184
- generation++;
185
- inflight?.abort("cleared");
186
- inflight = null;
187
- ctx.dispatch({ type: "CLEAR" });
277
+ /**
278
+ * One page's hits, by the page's ref or index. A page that isn't in the
279
+ * document has none: a layer may read while its page is being deleted.
280
+ */
281
+ const hitsOn = (page) => {
282
+ const found = ctx.getPage(page);
283
+ return found ? state().hitsByPage[found.ref.objectNumber] ?? EMPTY : EMPTY;
188
284
  };
189
- return {
190
- search: (query, exec) => query.text.length === 0 ? clear() : void runSession(query, exec?.startPage),
191
- rerun: () => {
192
- const { query, status } = ctx.getState();
193
- if (query && status !== "idle") runSession(query);
285
+ const api = {
286
+ ...settings.api,
287
+ canSearch: (options) => ctx.allows("doc.text.search") && (!options?.snippets || ctx.allows("doc.text.copy")),
288
+ search,
289
+ refresh: (options) => {
290
+ const { query, status } = state();
291
+ if (!query || status === "idle") return Promise.resolve({
292
+ status: "complete",
293
+ hitCount: 0
294
+ });
295
+ return search(query, options);
194
296
  },
297
+ cancel: () => session.cancel("cancelled"),
195
298
  clear,
196
- next: () => goTo(ctx.getState().activeIndex + 1),
197
- prev: () => goTo(ctx.getState().activeIndex - 1),
198
- goTo,
199
- query: () => ctx.getState().query,
200
- findAll: async (query, opts = {}) => {
201
- if (!ctx.doc) return [];
202
- const all = [];
203
- const signal = opts.signal;
204
- let pending = null;
205
- const onAbort = () => pending?.abort(signal?.reason);
206
- signal?.addEventListener("abort", onAbort, { once: true });
207
- try {
208
- await collect(query, { mode: opts.mode }, {
209
- onStart: () => {
210
- all.length = 0;
211
- },
212
- onSlice: (hits) => all.push(...hits),
213
- isCancelled: () => signal?.aborted ?? false,
214
- setInflight: (p) => {
215
- pending = p;
216
- }
217
- });
218
- if (signal?.aborted) throw signal.reason ?? /* @__PURE__ */ new Error("findAll aborted");
219
- return all;
220
- } finally {
221
- signal?.removeEventListener("abort", onAbort);
222
- }
223
- },
224
- status: () => ctx.getState().status,
225
- hits: () => ctx.getState().hits,
226
- hitCount: () => ctx.getState().hits.length,
227
- activeIndex: () => ctx.getState().activeIndex,
228
- activeHit: () => {
229
- const { hits, activeIndex } = ctx.getState();
230
- return activeIndex >= 0 && activeIndex < hits.length ? hits[activeIndex] : null;
299
+ nextHit: (options) => goToHit(state().activeHitIndex + 1, options),
300
+ previousHit: (options) => goToHit(state().activeHitIndex - 1, options),
301
+ goToHit,
302
+ revealActiveHit: (options) => {
303
+ const hit = api.getActiveHit();
304
+ if (hit) reveal(hit, options);
231
305
  },
232
- hitsForPage: (pon) => {
233
- const { hits, hitsByPage } = ctx.getState();
234
- const indices = hitsByPage[pon];
235
- return indices?.length ? indices.map((i) => hits[i]) : EMPTY;
306
+ getQuery: () => state().query,
307
+ getStatus: () => state().status,
308
+ listHits: (filter) => filter?.page === void 0 ? state().hits : hitsOn(filter.page),
309
+ getHitCount: (page) => (page === void 0 ? state().hits : hitsOn(page)).length,
310
+ listPagesWithHits: () => state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,
311
+ getActiveHitIndex: () => state().activeHitIndex,
312
+ getActiveHit: () => state().hits[state().activeHitIndex] ?? null,
313
+ getProgress: () => state().progress,
314
+ getError: () => state().error,
315
+ findAll: async (query, options = {}) => {
316
+ ctx.assertAllowed("doc.text.search", "findAll");
317
+ const all = [];
318
+ if (!await collect(query, {
319
+ ...options.snippets !== void 0 ? { snippets: options.snippets } : {},
320
+ ...options.signal ? { signal: options.signal } : {}
321
+ }, {
322
+ onStart: () => {
323
+ all.length = 0;
324
+ },
325
+ onSlice: (hits) => all.push(...hits)
326
+ })) throw new PluginError("operation-cancelled", "search", "findAll aborted");
327
+ return all;
236
328
  },
237
- progress: () => ctx.getState().progress,
238
- errorMessage: () => ctx.getState().error
329
+ onStarted: started.on,
330
+ onProgressChanged: progressChanged.on,
331
+ onCompleted: completed.on,
332
+ onCancelled: cancelled.on,
333
+ onFailed: failed.on,
334
+ onActiveHitChanged: activeHitChanged.on,
335
+ onCleared: cleared.on
239
336
  };
240
- }
241
- //#endregion
242
- //#region src/types.ts
243
- const SearchToken = createCapabilityToken("search");
244
- //#endregion
245
- //#region src/effects.ts
246
- const RERUN_DELAY_MS = 250;
247
- function registerSearchEffects(ctx) {
248
- const doc = ctx.doc;
249
- if (!doc) return;
250
- let timer = null;
251
- const unsubscribe = doc.events.subscribe(() => {
252
- if (ctx.getState().status === "idle") return;
253
- if (timer !== null) clearTimeout(timer);
254
- timer = setTimeout(() => {
255
- timer = null;
256
- ctx.get(SearchToken).rerun();
257
- }, RERUN_DELAY_MS);
258
- });
259
- ctx.cleanup(() => {
260
- if (timer !== null) clearTimeout(timer);
261
- unsubscribe();
262
- });
263
- }
264
- //#endregion
265
- //#region src/reducer.ts
266
- const initialSearchState = () => ({
267
- query: null,
268
- status: "idle",
269
- hits: [],
270
- hitsByPage: {},
271
- activeIndex: -1,
272
- progress: {
273
- scanned: 0,
274
- total: 0
275
- },
276
- error: null
277
- });
278
- const searchReducer = (state, action) => {
279
- switch (action.type) {
280
- case "START": return {
281
- ...initialSearchState(),
282
- query: action.query,
283
- status: "searching"
284
- };
285
- case "APPEND": {
286
- if (action.hits.length === 0) return {
287
- ...state,
288
- progress: {
289
- scanned: action.scanned,
290
- total: action.total
291
- }
292
- };
293
- const hits = state.hits.concat(action.hits);
294
- const hitsByPage = { ...state.hitsByPage };
295
- for (let i = state.hits.length; i < hits.length; i++) {
296
- const pon = hits[i].pon;
297
- hitsByPage[pon] = (hitsByPage[pon] ?? []).concat(i);
298
- }
299
- return {
300
- ...state,
301
- hits,
302
- hitsByPage,
303
- activeIndex: state.activeIndex === -1 ? 0 : state.activeIndex,
304
- progress: {
305
- scanned: action.scanned,
306
- total: action.total
307
- }
308
- };
337
+ return {
338
+ api,
339
+ connect() {
340
+ let cancelRerun = null;
341
+ ctx.listen(ctx.doc.events, () => {
342
+ if (state().status === "idle") return;
343
+ cancelRerun?.();
344
+ cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {
345
+ cancelRerun = null;
346
+ api.refresh().catch(() => {});
347
+ });
348
+ });
309
349
  }
310
- case "COMPLETE": return {
311
- ...state,
312
- status: "complete"
313
- };
314
- case "ERROR": return {
315
- ...state,
316
- status: "error",
317
- error: action.message
318
- };
319
- case "SET_ACTIVE": return {
320
- ...state,
321
- activeIndex: action.index
322
- };
323
- case "CLEAR": return initialSearchState();
324
- default: return state;
325
- }
326
- };
350
+ };
351
+ }
327
352
  //#endregion
328
353
  //#region src/search.plugin.ts
329
354
  /**
330
- * Document text search over `doc.search` — the engine's budgeted,
331
- * cursor-resumable slices. Document-scoped; no pointer handling, so it
332
- * needs no interaction hub. The Stage is optional: when present, scans
333
- * start at the current page (viewport-first) and hit navigation reveals
334
- * the hit's page; without it the host owns scrolling.
355
+ * Document text search over the engine's budgeted, resumable slices.
356
+ * Document-scoped; no pointer handling. The stage is optional: with one,
357
+ * scans start at the current page and navigation reveals hits. `config` is
358
+ * the settings the app registers, over {@link SEARCH_DEFAULTS}.
335
359
  */
336
360
  const searchPlugin = (config) => definePlugin({
337
361
  id: "search",
338
362
  token: SearchToken,
339
363
  scope: "document",
340
364
  optional: [StageToken],
341
- initialState: initialSearchState,
342
- reduce: searchReducer,
343
- capability: (ctx) => createSearchCapability(ctx, config),
344
- effects: registerSearchEffects
365
+ state: initialSearchModel,
366
+ settings: {
367
+ defaults: SEARCH_DEFAULTS,
368
+ registered: config
369
+ },
370
+ create: createSearchController
371
+ });
372
+ //#endregion
373
+ //#region src/state.ts
374
+ /**
375
+ * The search page's State table as code: what `useSearchState()` returns, and
376
+ * the same fields in every other framework. The matches themselves are not
377
+ * here: `useSearchHits()` reads them, so a component that only shows the
378
+ * count doesn't re-render for every match that arrives.
379
+ */
380
+ const searchState = defineState(SearchToken, {
381
+ read: (search) => ({
382
+ query: search.getQuery(),
383
+ status: search.getStatus(),
384
+ hitCount: search.getHitCount(),
385
+ activeHitIndex: search.getActiveHitIndex(),
386
+ activeHit: search.getActiveHit(),
387
+ progress: search.getProgress(),
388
+ error: search.getError()
389
+ }),
390
+ empty: {
391
+ query: null,
392
+ status: "idle",
393
+ hitCount: 0,
394
+ activeHitIndex: -1,
395
+ activeHit: null,
396
+ progress: NO_PROGRESS,
397
+ error: null
398
+ }
345
399
  });
346
400
  //#endregion
347
- export { SearchToken, searchPlugin, validateSearchQuery, validateSearchRegex };
401
+ export { SEARCH_DEFAULTS, SearchToken, searchPlugin, searchState, validateSearchQuery, validateSearchRegex };
348
402
 
349
403
  //# sourceMappingURL=index.js.map