@embedpdf/plugin-search 3.0.0-next.22 → 3.0.0-next.23
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/{contract-6pr6LBhA.cjs → contract-BMKyZdwD.cjs} +2 -2
- package/dist/contract-BMKyZdwD.cjs.map +1 -0
- package/dist/{contract-B7maCczh.d.ts → contract-Cl2UZGHY.d.ts} +15 -13
- package/dist/{contract-DqeptOSn.d.cts → contract-DYeW6lpW.d.cts} +15 -13
- package/dist/{contract-uWSW5IYM.js → contract-MvB7O9LG.js} +2 -2
- package/dist/contract-MvB7O9LG.js.map +1 -0
- package/dist/contract.cjs +1 -1
- package/dist/contract.d.cts +2 -2
- package/dist/contract.d.ts +2 -2
- package/dist/contract.js +1 -1
- package/dist/index.cjs +12 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +12 -13
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- package/dist/contract-6pr6LBhA.cjs.map +0 -1
- package/dist/contract-uWSW5IYM.js.map +0 -1
|
@@ -16,7 +16,7 @@ const SearchToken = (0, _embedpdf_core.createCapabilityToken)("search", {
|
|
|
16
16
|
/** What the search settings are when the app registers none. */
|
|
17
17
|
const SEARCH_DEFAULTS = {
|
|
18
18
|
reveal: {
|
|
19
|
-
|
|
19
|
+
align: { y: .35 },
|
|
20
20
|
behavior: "smooth"
|
|
21
21
|
},
|
|
22
22
|
highlight: {
|
|
@@ -39,4 +39,4 @@ Object.defineProperty(exports, "SearchToken", {
|
|
|
39
39
|
}
|
|
40
40
|
});
|
|
41
41
|
|
|
42
|
-
//# sourceMappingURL=contract-
|
|
42
|
+
//# sourceMappingURL=contract-BMKyZdwD.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract-BMKyZdwD.cjs","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token — created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { SearchCapability } from './contract';\n\nexport const SearchToken = createCapabilityToken<SearchCapability>('search', {\n hint: \"add searchPlugin() from '@embedpdf/plugin-search' to your plugins list\",\n // Without a document, an adapter's stand-in rejects these with `not-ready`, as the\n // capability would; the type asks for every member that returns a promise.\n promises: {\n search: true,\n refresh: true,\n findAll: true,\n },\n});\n","import {\n type DeepPartial,\n type EventHook,\n type OperationOptions,\n type PageRef,\n type PluginErrorInfo,\n type SettingsApi,\n} from '@embedpdf/core';\nimport type { Rect } from '@embedpdf/core-geometry';\nimport type { RevealAlignment, ScrollBehaviorKind } from '@embedpdf/plugin-stage/contract';\nimport type {\n BlendMode,\n PdfTextSegment,\n SearchQuery,\n SearchSnippet,\n} from '@embedpdf/engine-core/runtime';\n\nexport { validateSearchQuery, validateSearchRegex } from '@embedpdf/engine-core/runtime';\nexport type {\n SearchQuery,\n SearchQueryIssue,\n SearchQueryValidation,\n SearchRegexValidation,\n SearchSnippet,\n} from '@embedpdf/engine-core/runtime';\n\n/**\n * One merged visual line of a match in page space, as the engine's layout\n * gives it (selection's `SelectionSegment` is the same line). `quad` is the\n * geometric authority, its corners named in the line's own frame; `rect` its\n * bounds; `advance` the reading direction along the baseline.\n */\nexport type TextSegment = PdfTextSegment;\n\n/**\n * One match. `page` is the durable page identity, `pageIndex` its display\n * index at the time of the match. `start`/`count` are a range of the page's\n * characters, so a hit goes straight to `selection.select(hit)` or a markup\n * annotation without re-searching.\n */\nexport interface SearchHit {\n readonly page: PageRef;\n readonly pageIndex: number;\n readonly start: number;\n readonly count: number;\n /** Visual-line segments in page space — the drawing input. */\n readonly segments: readonly TextSegment[];\n /** Union of the segments — the reveal target. Absent for matches with no drawable geometry. */\n readonly bounds?: Rect;\n readonly snippet?: SearchSnippet;\n}\n\n/**\n * `searching`: the scan is walking pages, hits are usable as they stream in.\n * `cancelled`: the scan was stopped by `cancel()`; the hits found so far stay.\n */\nexport type SearchStatus = 'idle' | 'searching' | 'complete' | 'cancelled' | 'error';\n\nexport interface SearchProgress {\n readonly pagesSearched: number;\n readonly pageCount: number;\n}\n\n// ── settings ──────────────────────────────────────────────────────────────\n\n/** How a match arrives in view when you move to it: forwarded to the Stage's positioned reveal. */\nexport interface SearchReveal {\n /** Where the match lands in the view: `{ y: 0.35 }` puts it 35% of the way down, like a browser's find bar. */\n readonly align: RevealAlignment;\n /** Glide there (`'smooth'`) or jump (`'instant'`). */\n readonly behavior: ScrollBehaviorKind;\n}\n\n/** The `reveal` setting for one call: what the call leaves out comes from the setting. */\nexport type SearchRevealOptions = Partial<SearchReveal>;\n\n/**\n * The search plugin's settings. `searchPlugin(config)` registers them over\n * {@link SEARCH_DEFAULTS}, and `updateSettings()` changes them for every\n * document while the app runs. The highlight's three can also come from CSS\n * (`--epdf-search-highlight`, `--epdf-search-highlight-active`,\n * `--epdf-search-blend-mode`), which wins over the setting.\n */\nexport interface SearchSettings {\n /** Where a match lands when `nextHit()`, `previousHit()` or `goToHit()` moves to it. */\n readonly reveal: SearchReveal;\n readonly highlight: {\n /** The highlight of every match. */\n readonly color: string;\n /** The highlight of the active match. */\n readonly activeColor: string;\n /**\n * `'multiply'` is a real highlighter: the text stays crisp through the\n * color and only the paper tints. On dark or scanned pages, where a\n * multiplied highlight disappears, use `'normal'` with translucent colors.\n */\n readonly blendMode: BlendMode;\n };\n}\n\n/** What the search settings are when the app registers none. */\nexport const SEARCH_DEFAULTS: SearchSettings = {\n reveal: { align: { y: 0.35 }, behavior: 'smooth' },\n highlight: { color: '#ffd500', activeColor: '#ff9632', blendMode: 'multiply' },\n};\n\n/** What `searchPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type SearchConfig = DeepPartial<SearchSettings>;\n\n// ── verbs ─────────────────────────────────────────────────────────────────\n\nexport interface SearchOptions extends OperationOptions {\n /**\n * Where to start: a page's ref or its index. Defaults to the Stage's\n * current page (viewport-first) when a Stage is installed.\n */\n readonly from?: PageRef | number;\n}\n\nexport interface SearchFindAllOptions extends OperationOptions {\n /**\n * Pin whether hits carry snippets. By default they do when the session may\n * copy text (`doc.text.copy`) and don't otherwise. `true` requires them:\n * without `doc.text.copy`, `findAll` refuses. Pass `false` when only\n * geometry is needed.\n */\n readonly snippets?: boolean;\n}\n\n/** What a `search()` resolved to: it finished, a newer search replaced it, or it was cancelled. */\nexport interface SearchResult {\n readonly status: 'complete' | 'superseded' | 'cancelled';\n readonly hitCount: number;\n}\n\nexport interface SearchHitFilter {\n /** One page's hits: its ref or its index. */\n readonly page?: PageRef | number;\n}\n\n// ── events ────────────────────────────────────────────────────────────────\n\nexport interface SearchStartedEvent {\n readonly query: SearchQuery;\n}\n/**\n * The search's progress changed: how many pages were searched, of how many,\n * and the matches found so far. The same values `getProgress()` and\n * `getHitCount()` return from then on.\n */\nexport interface SearchProgressChangedEvent extends SearchProgress {\n readonly hitCount: number;\n}\nexport interface SearchCompletedEvent {\n readonly hitCount: number;\n}\nexport interface SearchCancelledEvent {\n readonly reason: 'superseded' | 'cancelled' | 'cleared';\n}\nexport interface SearchFailedEvent {\n readonly error: PluginErrorInfo;\n}\nexport interface SearchActiveHitChangedEvent {\n readonly index: number;\n readonly hit: SearchHit | null;\n}\nexport type SearchClearedEvent = Record<string, never>;\n\n/**\n * The search plugin is a find service (`findAll`) plus one user-visible\n * search session per document (`search` and everything below it). The\n * sidebar, the highlight layer and next/previous render the session. Its\n * settings (`getSettings`, `updateSettings`, `resetSettings`,\n * `onSettingsChanged`) belong to the plugin, not to a document: a change\n * reaches every open document.\n */\nexport interface SearchCapability extends SettingsApi<SearchSettings> {\n /**\n * Would a search be served now: `doc.text.search`. With `snippets: true`\n * it also needs `doc.text.copy`, because a snippet reproduces document text.\n */\n canSearch(options?: { readonly snippets?: boolean }): boolean;\n\n // ── the session ─────────────────────────────────────────────────────────\n /**\n * Start a new search. A newer search supersedes and aborts a running one.\n * Hits stream into the session as they are found; the first hit becomes\n * active but the camera does not move until you navigate. Resolves when\n * the scan completes, is superseded, or is cancelled (also through\n * `options.signal`); rejects only on a real failure, `permission-denied`\n * without `doc.text.search`, or `not-found` for a `from` page that isn't in\n * the document. A refusal only rejects: the session stays as it was and no\n * event fires. An empty `query.text` is identical to `clear()`. Fires\n * `onStarted`, `onProgressChanged` as each slice of pages is searched, then\n * `onCompleted`, `onCancelled` or `onFailed`.\n */\n search(query: SearchQuery, options?: SearchOptions): Promise<SearchResult>;\n /**\n * Re-run the current query from scratch (the plugin does this itself after\n * document mutations). Rejects as `search()` does; the result is in the\n * state and the events.\n */\n refresh(options?: OperationOptions): Promise<void>;\n /** Stop the scan and keep the hits found so far. */\n cancel(): void;\n /** Stop the scan and drop the session. */\n clear(): void;\n\n /** Step to the next / previous hit, wrapping, and reveal it. */\n nextHit(options?: SearchRevealOptions): SearchHit | null;\n previousHit(options?: SearchRevealOptions): SearchHit | null;\n /**\n * Make a hit the active one and reveal it: the hit itself, such as the one\n * `<SearchLayer onHitClick>` hands you, or its index (which wraps). Returns\n * the hit, or null when there are no hits or the given one isn't among them.\n */\n goToHit(hit: SearchHit | number, options?: SearchRevealOptions): SearchHit | null;\n /** Bring the active hit back into view without changing it. */\n revealActiveHit(options?: SearchRevealOptions): void;\n\n getQuery(): SearchQuery | null;\n getStatus(): SearchStatus;\n /**\n * Hits found so far, or those on one page. Reference-stable (per page too)\n * until new hits land there. Empty for a page that isn't in the document,\n * so a layer that reads while its page is deleted still renders.\n */\n listHits(filter?: SearchHitFilter): readonly SearchHit[];\n /** How many hits were found so far, or on one page; 0 for a page that isn't in the document. */\n getHitCount(page?: PageRef | number): number;\n listPagesWithHits(): readonly PageRef[];\n /** `-1` when no hit is active. */\n getActiveHitIndex(): number;\n getActiveHit(): SearchHit | null;\n getProgress(): SearchProgress;\n getError(): PluginErrorInfo | null;\n\n // ── the service ─────────────────────────────────────────────────────────\n /**\n * Run a query to completion and return every hit, touching no session\n * state. Scans in natural page order; concurrent calls are independent.\n * Rejects `operation-cancelled` when `options.signal` aborts, and\n * `permission-denied` without `doc.text.search`, or without `doc.text.copy`\n * when `options.snippets` is `true`.\n */\n findAll(query: SearchQuery, options?: SearchFindAllOptions): Promise<readonly SearchHit[]>;\n\n readonly onStarted: EventHook<SearchStartedEvent>;\n /**\n * `getProgress()` changed: once per slice of pages a search gets through,\n * and back to none when a new search starts or the session is cleared.\n */\n readonly onProgressChanged: EventHook<SearchProgressChangedEvent>;\n readonly onCompleted: EventHook<SearchCompletedEvent>;\n readonly onCancelled: EventHook<SearchCancelledEvent>;\n readonly onFailed: EventHook<SearchFailedEvent>;\n readonly onActiveHitChanged: EventHook<SearchActiveHitChangedEvent>;\n readonly onCleared: EventHook<SearchClearedEvent>;\n}\n\nexport { SearchToken } from './token';\n"],"mappings":";;;;;AAMA,MAAa,eAAA,GAAA,eAAA,sBAAA,CAAsD,UAAU;CAC3E,MAAM;CAGN,UAAU;EACR,QAAQ;EACR,SAAS;EACT,SAAS;CACX;AACF,CAAC;;;;ACsFD,MAAa,kBAAkC;CAC7C,QAAQ;EAAE,OAAO,EAAE,GAAG,IAAK;EAAG,UAAU;CAAS;CACjD,WAAW;EAAE,OAAO;EAAW,aAAa;EAAW,WAAW;CAAW;AAC/E"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DeepPartial, EventHook, OperationOptions, PageRef, PluginErrorInfo, SettingsApi } from "@embedpdf/core";
|
|
2
|
-
import {
|
|
3
|
-
import { PdfTextSegment, SearchQuery, SearchQuery as SearchQuery$1, SearchQueryIssue, SearchQueryValidation, SearchRegexValidation, SearchSnippet, SearchSnippet as SearchSnippet$1, validateSearchQuery, validateSearchRegex } from "@embedpdf/engine-core/runtime";
|
|
2
|
+
import { RevealAlignment, ScrollBehaviorKind } from "@embedpdf/plugin-stage/contract";
|
|
3
|
+
import { BlendMode, PdfTextSegment, SearchQuery, SearchQuery as SearchQuery$1, SearchQueryIssue, SearchQueryValidation, SearchRegexValidation, SearchSnippet, SearchSnippet as SearchSnippet$1, validateSearchQuery, validateSearchRegex } from "@embedpdf/engine-core/runtime";
|
|
4
4
|
import { Rect } from "@embedpdf/core-geometry";
|
|
5
5
|
//#region src/token.d.ts
|
|
6
6
|
declare const SearchToken: import("@embedpdf/core").CapabilityToken<SearchCapability>;
|
|
@@ -42,14 +42,12 @@ interface SearchProgress {
|
|
|
42
42
|
/** How a match arrives in view when you move to it: forwarded to the Stage's positioned reveal. */
|
|
43
43
|
interface SearchReveal {
|
|
44
44
|
/** Where the match lands in the view: `{ y: 0.35 }` puts it 35% of the way down, like a browser's find bar. */
|
|
45
|
-
readonly
|
|
45
|
+
readonly align: RevealAlignment;
|
|
46
46
|
/** Glide there (`'smooth'`) or jump (`'instant'`). */
|
|
47
47
|
readonly behavior: ScrollBehaviorKind;
|
|
48
48
|
}
|
|
49
49
|
/** The `reveal` setting for one call: what the call leaves out comes from the setting. */
|
|
50
50
|
type SearchRevealOptions = Partial<SearchReveal>;
|
|
51
|
-
/** How the highlights mix with the page: a CSS `mix-blend-mode` keyword. */
|
|
52
|
-
type SearchBlendMode = 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' | 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity';
|
|
53
51
|
/**
|
|
54
52
|
* The search plugin's settings. `searchPlugin(config)` registers them over
|
|
55
53
|
* {@link SEARCH_DEFAULTS}, and `updateSettings()` changes them for every
|
|
@@ -70,7 +68,7 @@ interface SearchSettings {
|
|
|
70
68
|
* color and only the paper tints. On dark or scanned pages, where a
|
|
71
69
|
* multiplied highlight disappears, use `'normal'` with translucent colors.
|
|
72
70
|
*/
|
|
73
|
-
readonly blendMode:
|
|
71
|
+
readonly blendMode: BlendMode;
|
|
74
72
|
};
|
|
75
73
|
}
|
|
76
74
|
/** What the search settings are when the app registers none. */
|
|
@@ -86,8 +84,10 @@ interface SearchOptions extends OperationOptions {
|
|
|
86
84
|
}
|
|
87
85
|
interface SearchFindAllOptions extends OperationOptions {
|
|
88
86
|
/**
|
|
89
|
-
* Pin whether hits carry snippets. By default they do
|
|
90
|
-
*
|
|
87
|
+
* Pin whether hits carry snippets. By default they do when the session may
|
|
88
|
+
* copy text (`doc.text.copy`) and don't otherwise. `true` requires them:
|
|
89
|
+
* without `doc.text.copy`, `findAll` refuses. Pass `false` when only
|
|
90
|
+
* geometry is needed.
|
|
91
91
|
*/
|
|
92
92
|
readonly snippets?: boolean;
|
|
93
93
|
}
|
|
@@ -156,9 +156,10 @@ interface SearchCapability extends SettingsApi<SearchSettings> {
|
|
|
156
156
|
search(query: SearchQuery, options?: SearchOptions): Promise<SearchResult>;
|
|
157
157
|
/**
|
|
158
158
|
* Re-run the current query from scratch (the plugin does this itself after
|
|
159
|
-
* document mutations).
|
|
159
|
+
* document mutations). Rejects as `search()` does; the result is in the
|
|
160
|
+
* state and the events.
|
|
160
161
|
*/
|
|
161
|
-
refresh(options?: OperationOptions): Promise<
|
|
162
|
+
refresh(options?: OperationOptions): Promise<void>;
|
|
162
163
|
/** Stop the scan and keep the hits found so far. */
|
|
163
164
|
cancel(): void;
|
|
164
165
|
/** Stop the scan and drop the session. */
|
|
@@ -194,7 +195,8 @@ interface SearchCapability extends SettingsApi<SearchSettings> {
|
|
|
194
195
|
* Run a query to completion and return every hit, touching no session
|
|
195
196
|
* state. Scans in natural page order; concurrent calls are independent.
|
|
196
197
|
* Rejects `operation-cancelled` when `options.signal` aborts, and
|
|
197
|
-
* `permission-denied` without `doc.text.search
|
|
198
|
+
* `permission-denied` without `doc.text.search`, or without `doc.text.copy`
|
|
199
|
+
* when `options.snippets` is `true`.
|
|
198
200
|
*/
|
|
199
201
|
findAll(query: SearchQuery, options?: SearchFindAllOptions): Promise<readonly SearchHit[]>;
|
|
200
202
|
readonly onStarted: EventHook<SearchStartedEvent>;
|
|
@@ -210,5 +212,5 @@ interface SearchCapability extends SettingsApi<SearchSettings> {
|
|
|
210
212
|
readonly onCleared: EventHook<SearchClearedEvent>;
|
|
211
213
|
}
|
|
212
214
|
//#endregion
|
|
213
|
-
export {
|
|
214
|
-
//# sourceMappingURL=contract-
|
|
215
|
+
export { SearchSnippet$1 as C, validateSearchQuery as D, TextSegment as E, validateSearchRegex as O, SearchSettings as S, SearchStatus as T, SearchQueryValidation as _, SearchClearedEvent as a, SearchReveal as b, SearchFailedEvent as c, SearchHitFilter as d, SearchOptions as f, SearchQueryIssue as g, SearchQuery$1 as h, SearchCapability as i, SearchToken as k, SearchFindAllOptions as l, SearchProgressChangedEvent as m, SearchActiveHitChangedEvent as n, SearchCompletedEvent as o, SearchProgress as p, SearchCancelledEvent as r, SearchConfig as s, SEARCH_DEFAULTS as t, SearchHit as u, SearchRegexValidation as v, SearchStartedEvent as w, SearchRevealOptions as x, SearchResult as y };
|
|
216
|
+
//# sourceMappingURL=contract-Cl2UZGHY.d.ts.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DeepPartial, EventHook, OperationOptions, PageRef, PluginErrorInfo, SettingsApi } from "@embedpdf/core";
|
|
2
2
|
import { Rect } from "@embedpdf/core-geometry";
|
|
3
|
-
import {
|
|
4
|
-
import { PdfTextSegment, SearchQuery, SearchQuery as SearchQuery$1, SearchQueryIssue, SearchQueryValidation, SearchRegexValidation, SearchSnippet, SearchSnippet as SearchSnippet$1, validateSearchQuery, validateSearchRegex } from "@embedpdf/engine-core/runtime";
|
|
3
|
+
import { RevealAlignment, ScrollBehaviorKind } from "@embedpdf/plugin-stage/contract";
|
|
4
|
+
import { BlendMode, PdfTextSegment, SearchQuery, SearchQuery as SearchQuery$1, SearchQueryIssue, SearchQueryValidation, SearchRegexValidation, SearchSnippet, SearchSnippet as SearchSnippet$1, validateSearchQuery, validateSearchRegex } from "@embedpdf/engine-core/runtime";
|
|
5
5
|
//#region src/token.d.ts
|
|
6
6
|
declare const SearchToken: import("@embedpdf/core").CapabilityToken<SearchCapability>;
|
|
7
7
|
//#endregion
|
|
@@ -42,14 +42,12 @@ interface SearchProgress {
|
|
|
42
42
|
/** How a match arrives in view when you move to it: forwarded to the Stage's positioned reveal. */
|
|
43
43
|
interface SearchReveal {
|
|
44
44
|
/** Where the match lands in the view: `{ y: 0.35 }` puts it 35% of the way down, like a browser's find bar. */
|
|
45
|
-
readonly
|
|
45
|
+
readonly align: RevealAlignment;
|
|
46
46
|
/** Glide there (`'smooth'`) or jump (`'instant'`). */
|
|
47
47
|
readonly behavior: ScrollBehaviorKind;
|
|
48
48
|
}
|
|
49
49
|
/** The `reveal` setting for one call: what the call leaves out comes from the setting. */
|
|
50
50
|
type SearchRevealOptions = Partial<SearchReveal>;
|
|
51
|
-
/** How the highlights mix with the page: a CSS `mix-blend-mode` keyword. */
|
|
52
|
-
type SearchBlendMode = 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' | 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity';
|
|
53
51
|
/**
|
|
54
52
|
* The search plugin's settings. `searchPlugin(config)` registers them over
|
|
55
53
|
* {@link SEARCH_DEFAULTS}, and `updateSettings()` changes them for every
|
|
@@ -70,7 +68,7 @@ interface SearchSettings {
|
|
|
70
68
|
* color and only the paper tints. On dark or scanned pages, where a
|
|
71
69
|
* multiplied highlight disappears, use `'normal'` with translucent colors.
|
|
72
70
|
*/
|
|
73
|
-
readonly blendMode:
|
|
71
|
+
readonly blendMode: BlendMode;
|
|
74
72
|
};
|
|
75
73
|
}
|
|
76
74
|
/** What the search settings are when the app registers none. */
|
|
@@ -86,8 +84,10 @@ interface SearchOptions extends OperationOptions {
|
|
|
86
84
|
}
|
|
87
85
|
interface SearchFindAllOptions extends OperationOptions {
|
|
88
86
|
/**
|
|
89
|
-
* Pin whether hits carry snippets. By default they do
|
|
90
|
-
*
|
|
87
|
+
* Pin whether hits carry snippets. By default they do when the session may
|
|
88
|
+
* copy text (`doc.text.copy`) and don't otherwise. `true` requires them:
|
|
89
|
+
* without `doc.text.copy`, `findAll` refuses. Pass `false` when only
|
|
90
|
+
* geometry is needed.
|
|
91
91
|
*/
|
|
92
92
|
readonly snippets?: boolean;
|
|
93
93
|
}
|
|
@@ -156,9 +156,10 @@ interface SearchCapability extends SettingsApi<SearchSettings> {
|
|
|
156
156
|
search(query: SearchQuery, options?: SearchOptions): Promise<SearchResult>;
|
|
157
157
|
/**
|
|
158
158
|
* Re-run the current query from scratch (the plugin does this itself after
|
|
159
|
-
* document mutations).
|
|
159
|
+
* document mutations). Rejects as `search()` does; the result is in the
|
|
160
|
+
* state and the events.
|
|
160
161
|
*/
|
|
161
|
-
refresh(options?: OperationOptions): Promise<
|
|
162
|
+
refresh(options?: OperationOptions): Promise<void>;
|
|
162
163
|
/** Stop the scan and keep the hits found so far. */
|
|
163
164
|
cancel(): void;
|
|
164
165
|
/** Stop the scan and drop the session. */
|
|
@@ -194,7 +195,8 @@ interface SearchCapability extends SettingsApi<SearchSettings> {
|
|
|
194
195
|
* Run a query to completion and return every hit, touching no session
|
|
195
196
|
* state. Scans in natural page order; concurrent calls are independent.
|
|
196
197
|
* Rejects `operation-cancelled` when `options.signal` aborts, and
|
|
197
|
-
* `permission-denied` without `doc.text.search
|
|
198
|
+
* `permission-denied` without `doc.text.search`, or without `doc.text.copy`
|
|
199
|
+
* when `options.snippets` is `true`.
|
|
198
200
|
*/
|
|
199
201
|
findAll(query: SearchQuery, options?: SearchFindAllOptions): Promise<readonly SearchHit[]>;
|
|
200
202
|
readonly onStarted: EventHook<SearchStartedEvent>;
|
|
@@ -210,5 +212,5 @@ interface SearchCapability extends SettingsApi<SearchSettings> {
|
|
|
210
212
|
readonly onCleared: EventHook<SearchClearedEvent>;
|
|
211
213
|
}
|
|
212
214
|
//#endregion
|
|
213
|
-
export {
|
|
214
|
-
//# sourceMappingURL=contract-
|
|
215
|
+
export { SearchSnippet$1 as C, validateSearchQuery as D, TextSegment as E, validateSearchRegex as O, SearchSettings as S, SearchStatus as T, SearchQueryValidation as _, SearchClearedEvent as a, SearchReveal as b, SearchFailedEvent as c, SearchHitFilter as d, SearchOptions as f, SearchQueryIssue as g, SearchQuery$1 as h, SearchCapability as i, SearchToken as k, SearchFindAllOptions as l, SearchProgressChangedEvent as m, SearchActiveHitChangedEvent as n, SearchCompletedEvent as o, SearchProgress as p, SearchCancelledEvent as r, SearchConfig as s, SEARCH_DEFAULTS as t, SearchHit as u, SearchRegexValidation as v, SearchStartedEvent as w, SearchRevealOptions as x, SearchResult as y };
|
|
216
|
+
//# sourceMappingURL=contract-DYeW6lpW.d.cts.map
|
|
@@ -16,7 +16,7 @@ const SearchToken = createCapabilityToken("search", {
|
|
|
16
16
|
/** What the search settings are when the app registers none. */
|
|
17
17
|
const SEARCH_DEFAULTS = {
|
|
18
18
|
reveal: {
|
|
19
|
-
|
|
19
|
+
align: { y: .35 },
|
|
20
20
|
behavior: "smooth"
|
|
21
21
|
},
|
|
22
22
|
highlight: {
|
|
@@ -28,4 +28,4 @@ const SEARCH_DEFAULTS = {
|
|
|
28
28
|
//#endregion
|
|
29
29
|
export { SearchToken as i, validateSearchQuery as n, validateSearchRegex as r, SEARCH_DEFAULTS as t };
|
|
30
30
|
|
|
31
|
-
//# sourceMappingURL=contract-
|
|
31
|
+
//# sourceMappingURL=contract-MvB7O9LG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract-MvB7O9LG.js","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token — created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { SearchCapability } from './contract';\n\nexport const SearchToken = createCapabilityToken<SearchCapability>('search', {\n hint: \"add searchPlugin() from '@embedpdf/plugin-search' to your plugins list\",\n // Without a document, an adapter's stand-in rejects these with `not-ready`, as the\n // capability would; the type asks for every member that returns a promise.\n promises: {\n search: true,\n refresh: true,\n findAll: true,\n },\n});\n","import {\n type DeepPartial,\n type EventHook,\n type OperationOptions,\n type PageRef,\n type PluginErrorInfo,\n type SettingsApi,\n} from '@embedpdf/core';\nimport type { Rect } from '@embedpdf/core-geometry';\nimport type { RevealAlignment, ScrollBehaviorKind } from '@embedpdf/plugin-stage/contract';\nimport type {\n BlendMode,\n PdfTextSegment,\n SearchQuery,\n SearchSnippet,\n} from '@embedpdf/engine-core/runtime';\n\nexport { validateSearchQuery, validateSearchRegex } from '@embedpdf/engine-core/runtime';\nexport type {\n SearchQuery,\n SearchQueryIssue,\n SearchQueryValidation,\n SearchRegexValidation,\n SearchSnippet,\n} from '@embedpdf/engine-core/runtime';\n\n/**\n * One merged visual line of a match in page space, as the engine's layout\n * gives it (selection's `SelectionSegment` is the same line). `quad` is the\n * geometric authority, its corners named in the line's own frame; `rect` its\n * bounds; `advance` the reading direction along the baseline.\n */\nexport type TextSegment = PdfTextSegment;\n\n/**\n * One match. `page` is the durable page identity, `pageIndex` its display\n * index at the time of the match. `start`/`count` are a range of the page's\n * characters, so a hit goes straight to `selection.select(hit)` or a markup\n * annotation without re-searching.\n */\nexport interface SearchHit {\n readonly page: PageRef;\n readonly pageIndex: number;\n readonly start: number;\n readonly count: number;\n /** Visual-line segments in page space — the drawing input. */\n readonly segments: readonly TextSegment[];\n /** Union of the segments — the reveal target. Absent for matches with no drawable geometry. */\n readonly bounds?: Rect;\n readonly snippet?: SearchSnippet;\n}\n\n/**\n * `searching`: the scan is walking pages, hits are usable as they stream in.\n * `cancelled`: the scan was stopped by `cancel()`; the hits found so far stay.\n */\nexport type SearchStatus = 'idle' | 'searching' | 'complete' | 'cancelled' | 'error';\n\nexport interface SearchProgress {\n readonly pagesSearched: number;\n readonly pageCount: number;\n}\n\n// ── settings ──────────────────────────────────────────────────────────────\n\n/** How a match arrives in view when you move to it: forwarded to the Stage's positioned reveal. */\nexport interface SearchReveal {\n /** Where the match lands in the view: `{ y: 0.35 }` puts it 35% of the way down, like a browser's find bar. */\n readonly align: RevealAlignment;\n /** Glide there (`'smooth'`) or jump (`'instant'`). */\n readonly behavior: ScrollBehaviorKind;\n}\n\n/** The `reveal` setting for one call: what the call leaves out comes from the setting. */\nexport type SearchRevealOptions = Partial<SearchReveal>;\n\n/**\n * The search plugin's settings. `searchPlugin(config)` registers them over\n * {@link SEARCH_DEFAULTS}, and `updateSettings()` changes them for every\n * document while the app runs. The highlight's three can also come from CSS\n * (`--epdf-search-highlight`, `--epdf-search-highlight-active`,\n * `--epdf-search-blend-mode`), which wins over the setting.\n */\nexport interface SearchSettings {\n /** Where a match lands when `nextHit()`, `previousHit()` or `goToHit()` moves to it. */\n readonly reveal: SearchReveal;\n readonly highlight: {\n /** The highlight of every match. */\n readonly color: string;\n /** The highlight of the active match. */\n readonly activeColor: string;\n /**\n * `'multiply'` is a real highlighter: the text stays crisp through the\n * color and only the paper tints. On dark or scanned pages, where a\n * multiplied highlight disappears, use `'normal'` with translucent colors.\n */\n readonly blendMode: BlendMode;\n };\n}\n\n/** What the search settings are when the app registers none. */\nexport const SEARCH_DEFAULTS: SearchSettings = {\n reveal: { align: { y: 0.35 }, behavior: 'smooth' },\n highlight: { color: '#ffd500', activeColor: '#ff9632', blendMode: 'multiply' },\n};\n\n/** What `searchPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type SearchConfig = DeepPartial<SearchSettings>;\n\n// ── verbs ─────────────────────────────────────────────────────────────────\n\nexport interface SearchOptions extends OperationOptions {\n /**\n * Where to start: a page's ref or its index. Defaults to the Stage's\n * current page (viewport-first) when a Stage is installed.\n */\n readonly from?: PageRef | number;\n}\n\nexport interface SearchFindAllOptions extends OperationOptions {\n /**\n * Pin whether hits carry snippets. By default they do when the session may\n * copy text (`doc.text.copy`) and don't otherwise. `true` requires them:\n * without `doc.text.copy`, `findAll` refuses. Pass `false` when only\n * geometry is needed.\n */\n readonly snippets?: boolean;\n}\n\n/** What a `search()` resolved to: it finished, a newer search replaced it, or it was cancelled. */\nexport interface SearchResult {\n readonly status: 'complete' | 'superseded' | 'cancelled';\n readonly hitCount: number;\n}\n\nexport interface SearchHitFilter {\n /** One page's hits: its ref or its index. */\n readonly page?: PageRef | number;\n}\n\n// ── events ────────────────────────────────────────────────────────────────\n\nexport interface SearchStartedEvent {\n readonly query: SearchQuery;\n}\n/**\n * The search's progress changed: how many pages were searched, of how many,\n * and the matches found so far. The same values `getProgress()` and\n * `getHitCount()` return from then on.\n */\nexport interface SearchProgressChangedEvent extends SearchProgress {\n readonly hitCount: number;\n}\nexport interface SearchCompletedEvent {\n readonly hitCount: number;\n}\nexport interface SearchCancelledEvent {\n readonly reason: 'superseded' | 'cancelled' | 'cleared';\n}\nexport interface SearchFailedEvent {\n readonly error: PluginErrorInfo;\n}\nexport interface SearchActiveHitChangedEvent {\n readonly index: number;\n readonly hit: SearchHit | null;\n}\nexport type SearchClearedEvent = Record<string, never>;\n\n/**\n * The search plugin is a find service (`findAll`) plus one user-visible\n * search session per document (`search` and everything below it). The\n * sidebar, the highlight layer and next/previous render the session. Its\n * settings (`getSettings`, `updateSettings`, `resetSettings`,\n * `onSettingsChanged`) belong to the plugin, not to a document: a change\n * reaches every open document.\n */\nexport interface SearchCapability extends SettingsApi<SearchSettings> {\n /**\n * Would a search be served now: `doc.text.search`. With `snippets: true`\n * it also needs `doc.text.copy`, because a snippet reproduces document text.\n */\n canSearch(options?: { readonly snippets?: boolean }): boolean;\n\n // ── the session ─────────────────────────────────────────────────────────\n /**\n * Start a new search. A newer search supersedes and aborts a running one.\n * Hits stream into the session as they are found; the first hit becomes\n * active but the camera does not move until you navigate. Resolves when\n * the scan completes, is superseded, or is cancelled (also through\n * `options.signal`); rejects only on a real failure, `permission-denied`\n * without `doc.text.search`, or `not-found` for a `from` page that isn't in\n * the document. A refusal only rejects: the session stays as it was and no\n * event fires. An empty `query.text` is identical to `clear()`. Fires\n * `onStarted`, `onProgressChanged` as each slice of pages is searched, then\n * `onCompleted`, `onCancelled` or `onFailed`.\n */\n search(query: SearchQuery, options?: SearchOptions): Promise<SearchResult>;\n /**\n * Re-run the current query from scratch (the plugin does this itself after\n * document mutations). Rejects as `search()` does; the result is in the\n * state and the events.\n */\n refresh(options?: OperationOptions): Promise<void>;\n /** Stop the scan and keep the hits found so far. */\n cancel(): void;\n /** Stop the scan and drop the session. */\n clear(): void;\n\n /** Step to the next / previous hit, wrapping, and reveal it. */\n nextHit(options?: SearchRevealOptions): SearchHit | null;\n previousHit(options?: SearchRevealOptions): SearchHit | null;\n /**\n * Make a hit the active one and reveal it: the hit itself, such as the one\n * `<SearchLayer onHitClick>` hands you, or its index (which wraps). Returns\n * the hit, or null when there are no hits or the given one isn't among them.\n */\n goToHit(hit: SearchHit | number, options?: SearchRevealOptions): SearchHit | null;\n /** Bring the active hit back into view without changing it. */\n revealActiveHit(options?: SearchRevealOptions): void;\n\n getQuery(): SearchQuery | null;\n getStatus(): SearchStatus;\n /**\n * Hits found so far, or those on one page. Reference-stable (per page too)\n * until new hits land there. Empty for a page that isn't in the document,\n * so a layer that reads while its page is deleted still renders.\n */\n listHits(filter?: SearchHitFilter): readonly SearchHit[];\n /** How many hits were found so far, or on one page; 0 for a page that isn't in the document. */\n getHitCount(page?: PageRef | number): number;\n listPagesWithHits(): readonly PageRef[];\n /** `-1` when no hit is active. */\n getActiveHitIndex(): number;\n getActiveHit(): SearchHit | null;\n getProgress(): SearchProgress;\n getError(): PluginErrorInfo | null;\n\n // ── the service ─────────────────────────────────────────────────────────\n /**\n * Run a query to completion and return every hit, touching no session\n * state. Scans in natural page order; concurrent calls are independent.\n * Rejects `operation-cancelled` when `options.signal` aborts, and\n * `permission-denied` without `doc.text.search`, or without `doc.text.copy`\n * when `options.snippets` is `true`.\n */\n findAll(query: SearchQuery, options?: SearchFindAllOptions): Promise<readonly SearchHit[]>;\n\n readonly onStarted: EventHook<SearchStartedEvent>;\n /**\n * `getProgress()` changed: once per slice of pages a search gets through,\n * and back to none when a new search starts or the session is cleared.\n */\n readonly onProgressChanged: EventHook<SearchProgressChangedEvent>;\n readonly onCompleted: EventHook<SearchCompletedEvent>;\n readonly onCancelled: EventHook<SearchCancelledEvent>;\n readonly onFailed: EventHook<SearchFailedEvent>;\n readonly onActiveHitChanged: EventHook<SearchActiveHitChangedEvent>;\n readonly onCleared: EventHook<SearchClearedEvent>;\n}\n\nexport { SearchToken } from './token';\n"],"mappings":";;;;;AAMA,MAAa,cAAc,sBAAwC,UAAU;CAC3E,MAAM;CAGN,UAAU;EACR,QAAQ;EACR,SAAS;EACT,SAAS;CACX;AACF,CAAC;;;;ACsFD,MAAa,kBAAkC;CAC7C,QAAQ;EAAE,OAAO,EAAE,GAAG,IAAK;EAAG,UAAU;CAAS;CACjD,WAAW;EAAE,OAAO;EAAW,aAAa;EAAW,WAAW;CAAW;AAC/E"}
|
package/dist/contract.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_contract = require("./contract-
|
|
2
|
+
const require_contract = require("./contract-BMKyZdwD.cjs");
|
|
3
3
|
let _embedpdf_engine_core_runtime = require("@embedpdf/engine-core/runtime");
|
|
4
4
|
exports.SEARCH_DEFAULTS = require_contract.SEARCH_DEFAULTS;
|
|
5
5
|
exports.SearchToken = require_contract.SearchToken;
|
package/dist/contract.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent,
|
|
1
|
+
import { C as SearchSnippet, D as validateSearchQuery, E as TextSegment, O as validateSearchRegex, S as SearchSettings, T as SearchStatus, _ as SearchQueryValidation, a as SearchClearedEvent, b as SearchReveal, c as SearchFailedEvent, d as SearchHitFilter, f as SearchOptions, g as SearchQueryIssue, h as SearchQuery, i as SearchCapability, k as SearchToken, l as SearchFindAllOptions, m as SearchProgressChangedEvent, n as SearchActiveHitChangedEvent, o as SearchCompletedEvent, p as SearchProgress, r as SearchCancelledEvent, s as SearchConfig, t as SEARCH_DEFAULTS, u as SearchHit, v as SearchRegexValidation, w as SearchStartedEvent, x as SearchRevealOptions, y as SearchResult } from "./contract-DYeW6lpW.cjs";
|
|
2
|
+
export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent, SearchCancelledEvent, SearchCapability, SearchClearedEvent, SearchCompletedEvent, SearchConfig, SearchFailedEvent, SearchFindAllOptions, SearchHit, SearchHitFilter, SearchOptions, SearchProgress, SearchProgressChangedEvent, type SearchQuery, type SearchQueryIssue, type SearchQueryValidation, type SearchRegexValidation, SearchResult, SearchReveal, SearchRevealOptions, SearchSettings, type SearchSnippet, SearchStartedEvent, SearchStatus, SearchToken, TextSegment, validateSearchQuery, validateSearchRegex };
|
package/dist/contract.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent,
|
|
1
|
+
import { C as SearchSnippet, D as validateSearchQuery, E as TextSegment, O as validateSearchRegex, S as SearchSettings, T as SearchStatus, _ as SearchQueryValidation, a as SearchClearedEvent, b as SearchReveal, c as SearchFailedEvent, d as SearchHitFilter, f as SearchOptions, g as SearchQueryIssue, h as SearchQuery, i as SearchCapability, k as SearchToken, l as SearchFindAllOptions, m as SearchProgressChangedEvent, n as SearchActiveHitChangedEvent, o as SearchCompletedEvent, p as SearchProgress, r as SearchCancelledEvent, s as SearchConfig, t as SEARCH_DEFAULTS, u as SearchHit, v as SearchRegexValidation, w as SearchStartedEvent, x as SearchRevealOptions, y as SearchResult } from "./contract-Cl2UZGHY.js";
|
|
2
|
+
export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent, SearchCancelledEvent, SearchCapability, SearchClearedEvent, SearchCompletedEvent, SearchConfig, SearchFailedEvent, SearchFindAllOptions, SearchHit, SearchHitFilter, SearchOptions, SearchProgress, SearchProgressChangedEvent, type SearchQuery, type SearchQueryIssue, type SearchQueryValidation, type SearchRegexValidation, SearchResult, SearchReveal, SearchRevealOptions, SearchSettings, type SearchSnippet, SearchStartedEvent, SearchStatus, SearchToken, TextSegment, validateSearchQuery, validateSearchRegex };
|
package/dist/contract.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as SearchToken, n as validateSearchQuery, r as validateSearchRegex, t as SEARCH_DEFAULTS } from "./contract-
|
|
1
|
+
import { i as SearchToken, n as validateSearchQuery, r as validateSearchRegex, t as SEARCH_DEFAULTS } from "./contract-MvB7O9LG.js";
|
|
2
2
|
export { SEARCH_DEFAULTS, SearchToken, validateSearchQuery, validateSearchRegex };
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_contract = require("./contract-
|
|
2
|
+
const require_contract = require("./contract-BMKyZdwD.cjs");
|
|
3
3
|
let _embedpdf_core = require("@embedpdf/core");
|
|
4
4
|
let _embedpdf_plugin_stage_contract = require("@embedpdf/plugin-stage/contract");
|
|
5
5
|
let _embedpdf_core_geometry = require("@embedpdf/core-geometry");
|
|
@@ -152,15 +152,16 @@ function createSearchController(ctx) {
|
|
|
152
152
|
return hits;
|
|
153
153
|
}
|
|
154
154
|
/**
|
|
155
|
-
* One cursor loop over budgeted slices:
|
|
156
|
-
*
|
|
157
|
-
* projection per slice. Returns true on
|
|
158
|
-
* aborted; throws on a real error (already
|
|
155
|
+
* One cursor loop over budgeted slices: snippets when the session may copy
|
|
156
|
+
* text (unless pinned), falling back to none if the engine still denies them,
|
|
157
|
+
* restart-once on a stale cursor, projection per slice. Returns true on
|
|
158
|
+
* exhaustion, false when the signal aborted; throws on a real error (already
|
|
159
|
+
* a PluginError: ctx.doc is guarded).
|
|
159
160
|
*/
|
|
160
161
|
async function collect(query, options, sink) {
|
|
161
162
|
const { signal } = options;
|
|
162
163
|
sink.onStart();
|
|
163
|
-
let snippets = options.snippets ??
|
|
164
|
+
let snippets = options.snippets ?? ctx.allows("doc.text.copy");
|
|
164
165
|
const snippetsPinned = options.snippets !== void 0;
|
|
165
166
|
let cursor;
|
|
166
167
|
let restarted = false;
|
|
@@ -272,7 +273,7 @@ function createSearchController(ctx) {
|
|
|
272
273
|
};
|
|
273
274
|
ctx.tryGet(_embedpdf_plugin_stage_contract.StageToken)?.reveal(hit.page, {
|
|
274
275
|
rect: hit.bounds,
|
|
275
|
-
|
|
276
|
+
align: arrival.align,
|
|
276
277
|
behavior: arrival.behavior
|
|
277
278
|
});
|
|
278
279
|
}
|
|
@@ -288,13 +289,10 @@ function createSearchController(ctx) {
|
|
|
288
289
|
...settings.api,
|
|
289
290
|
canSearch: (options) => ctx.allows("doc.text.search") && (!options?.snippets || ctx.allows("doc.text.copy")),
|
|
290
291
|
search,
|
|
291
|
-
refresh: (options) => {
|
|
292
|
+
refresh: async (options) => {
|
|
292
293
|
const { query, status } = state();
|
|
293
|
-
if (!query || status === "idle") return
|
|
294
|
-
|
|
295
|
-
hitCount: 0
|
|
296
|
-
});
|
|
297
|
-
return search(query, options);
|
|
294
|
+
if (!query || status === "idle") return;
|
|
295
|
+
await search(query, options);
|
|
298
296
|
},
|
|
299
297
|
cancel: () => session.cancel("cancelled"),
|
|
300
298
|
clear,
|
|
@@ -316,6 +314,7 @@ function createSearchController(ctx) {
|
|
|
316
314
|
getError: () => state().error,
|
|
317
315
|
findAll: async (query, options = {}) => {
|
|
318
316
|
ctx.assertAllowed("doc.text.search", "findAll");
|
|
317
|
+
if (options.snippets) ctx.assertAllowed("doc.text.copy", "findAll");
|
|
319
318
|
const all = [];
|
|
320
319
|
if (!await collect(query, {
|
|
321
320
|
...options.snippets !== void 0 ? { snippets: options.snippets } : {},
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["StageToken","PluginError","SearchToken","StageToken","SEARCH_DEFAULTS","SearchToken"],"sources":["../src/model.ts","../src/controller.ts","../src/search.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The search session: the query, the hits found so far (also grouped by\n * page), the active hit, and progress. Every function below is a pure\n * transition; the controller applies them with `ctx.state.update`.\n */\nimport { pageRefsEqual, type PageRef, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport type { SearchHit, SearchProgress, SearchStatus } from './contract';\n\nexport interface SearchModel {\n /** The query being searched, as the engine matches it. Null when idle. */\n readonly query: SearchQuery | null;\n readonly status: SearchStatus;\n /** The run that owns the session, so a run that lost it (superseded, cleared) leaves it alone. */\n readonly operationId: string | null;\n readonly hits: readonly SearchHit[];\n /** Page object number → the hits on that page; a page's array is replaced only when it gains hits. */\n readonly hitsByPage: Readonly<Record<number, readonly SearchHit[]>>;\n /** Index into `hits`, -1 when no hit is active. */\n readonly activeHitIndex: number;\n readonly progress: SearchProgress;\n readonly error: PluginErrorInfo | null;\n}\n\n/** The progress of no search, one object for every session that hasn't searched a page yet. */\nexport const NO_PROGRESS: SearchProgress = Object.freeze({ pagesSearched: 0, pageCount: 0 });\n\nexport const initialSearchModel = (): SearchModel => ({\n query: null,\n status: 'idle',\n operationId: null,\n hits: [],\n hitsByPage: {},\n activeHitIndex: -1,\n progress: NO_PROGRESS,\n error: null,\n});\n\n/** A new scan starts: everything from the previous session is dropped. */\nexport const startSession = (\n _state: SearchModel,\n query: SearchQuery,\n operationId: string,\n): SearchModel => ({ ...initialSearchModel(), query, status: 'searching', operationId });\n\nconst sameProgress = (left: SearchProgress, right: SearchProgress): boolean =>\n left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;\n\n/**\n * A slice of hits arrived. The first hit becomes active so \"1 of N\" reads\n * right; moving the camera is navigation's job, not the stream's. Progress\n * with the same counts keeps its object: readers, and `onProgressChanged`,\n * see a change only when the counts change.\n */\nexport function appendHits(\n state: SearchModel,\n hits: readonly SearchHit[],\n slice: SearchProgress,\n): SearchModel {\n const progress = sameProgress(state.progress, slice) ? state.progress : slice;\n if (hits.length === 0) return progress === state.progress ? state : { ...state, progress };\n const hitsByPage: Record<number, readonly SearchHit[]> = { ...state.hitsByPage };\n for (const hit of hits) {\n const pageObjectNumber = hit.page.objectNumber;\n hitsByPage[pageObjectNumber] = [...(hitsByPage[pageObjectNumber] ?? []), hit];\n }\n return {\n ...state,\n hits: [...state.hits, ...hits],\n hitsByPage,\n activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,\n progress,\n };\n}\n\nexport const completeSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'complete',\n});\n\nexport const cancelSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'cancelled',\n});\n\nexport const failSession = (state: SearchModel, error: PluginErrorInfo): SearchModel => ({\n ...state,\n status: 'error',\n error,\n});\n\nexport const setActiveHit = (state: SearchModel, index: number): SearchModel =>\n state.activeHitIndex === index ? state : { ...state, activeHitIndex: index };\n\nexport const clearSession = (state: SearchModel): SearchModel =>\n state.status === 'idle' ? state : initialSearchModel();\n\n/**\n * Where `hit` is in `hits`: the same object, or else the hit that covers the\n * same characters of the same page, so a hit kept from before the search ran\n * again still finds its place. -1 when it isn't there.\n */\nexport function indexOfHit(hits: readonly SearchHit[], hit: SearchHit): number {\n const same = hits.indexOf(hit);\n if (same >= 0) return same;\n return hits.findIndex(\n (candidate) =>\n candidate.start === hit.start &&\n candidate.count === hit.count &&\n pageRefsEqual(candidate.page, hit.page),\n );\n}\n\n/**\n * The pages that have at least one hit, in document order: `pages` is the\n * document's page list, whose order moving a page changes (object numbers\n * don't follow it).\n */\nexport const pagesWithHits = (\n state: SearchModel,\n pages: readonly { readonly ref: PageRef }[],\n): readonly PageRef[] =>\n pages\n .filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0)\n .map((page) => page.ref);\n","import {\n PluginError,\n isPluginError,\n toPluginError,\n toPluginErrorInfo,\n type PluginContext,\n type LatestCancellation,\n type PageRef,\n} from '@embedpdf/core';\nimport { boundsOfRects } from '@embedpdf/core-geometry';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\nimport type { SearchQuery, SearchSlice } from '@embedpdf/engine-core/runtime';\nimport type {\n SearchActiveHitChangedEvent,\n SearchCancelledEvent,\n SearchCapability,\n SearchClearedEvent,\n SearchCompletedEvent,\n SearchFailedEvent,\n SearchHit,\n SearchOptions,\n SearchProgressChangedEvent,\n SearchResult,\n SearchRevealOptions,\n SearchSettings,\n SearchStartedEvent,\n} from './contract';\nimport {\n appendHits,\n cancelSession,\n clearSession,\n completeSession,\n failSession,\n indexOfHit,\n pagesWithHits,\n setActiveHit,\n startSession,\n type SearchModel,\n} from './model';\n\nconst EMPTY: readonly SearchHit[] = Object.freeze([]);\nconst EMPTY_PAGES: readonly PageRef[] = Object.freeze([]);\n\n/** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */\nconst RERUN_DELAY_MS = 250;\n\n/** How a `collect()` consumer observes the loop: the session updates state, findAll accumulates. */\ninterface CollectSink {\n /** Before the first slice, and again on a stale-cursor restart: reset any accumulation. */\n onStart(): void;\n onSlice(hits: readonly SearchHit[], pagesSearched: number, pageCount: number): void;\n}\n\n/**\n * The search controller. `search` runs on a `latest` lane (a newer search\n * supersedes the older one, which can no longer publish); `findAll` runs on\n * its own signal and never touches the session. Both share `collect`, the\n * one cursor loop over the engine's budgeted slices.\n *\n * The scan's own events (started, completed, cancelled, failed) fire where\n * the scan reaches those points. The progress, active-hit and cleared events\n * are derived from state changes, so they always agree with the getters.\n *\n * The settings are read where they're used, never copied, so\n * `updateSettings({ reveal })` applies to the next move at once.\n */\nexport function createSearchController(ctx: PluginContext<SearchModel, SearchSettings>) {\n const settings = ctx.settings();\n const session = ctx.latest('session');\n const started = ctx.events.source<SearchStartedEvent>();\n const progressChanged = ctx.events.source<SearchProgressChangedEvent>();\n const completed = ctx.events.source<SearchCompletedEvent>();\n const cancelled = ctx.events.source<SearchCancelledEvent>();\n const failed = ctx.events.source<SearchFailedEvent>();\n const activeHitChanged = ctx.events.source<SearchActiveHitChangedEvent>();\n const cleared = ctx.events.source<SearchClearedEvent>();\n\n const state = () => ctx.state.get();\n\n ctx.state.onChange(({ previous, next }) => {\n // A slice moves it forward; a new search or clear() puts it back to none.\n if (previous.progress !== next.progress) {\n progressChanged.emit({ ...next.progress, hitCount: next.hits.length });\n }\n if (previous.activeHitIndex !== next.activeHitIndex) {\n activeHitChanged.emit({\n index: next.activeHitIndex,\n hit: next.hits[next.activeHitIndex] ?? null,\n });\n }\n if (previous.status !== 'idle' && next.status === 'idle') cleared.emit({});\n });\n\n // ── projection: engine slice → page-space hits ───────────────────────────\n\n function hitsFromSlice(slice: SearchSlice): SearchHit[] {\n const hits: SearchHit[] = [];\n for (const match of slice.matches) {\n // A page that vanished mid-search (deleted) drops its hits.\n const page = ctx.getPage(match.page);\n if (!page) continue;\n // Segments arrive in page space, ready to draw.\n const segments = match.segments;\n hits.push({\n page: match.page,\n pageIndex: page.index,\n start: match.start,\n count: match.count,\n segments,\n ...(segments.length\n ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? undefined }\n : {}),\n ...(match.snippet ? { snippet: match.snippet } : {}),\n });\n }\n return hits;\n }\n\n // ── the mechanism ────────────────────────────────────────────────────────\n\n /**\n * One cursor loop over budgeted slices: permission fallback (snippets → none\n * when they are denied, unless pinned), restart-once on a stale cursor,\n * projection per slice. Returns true on exhaustion, false when the signal\n * aborted; throws on a real error (already a PluginError: ctx.doc is guarded).\n */\n async function collect(\n query: SearchQuery,\n options: { from?: PageRef; snippets?: boolean; signal?: AbortSignal },\n sink: CollectSink,\n ): Promise<boolean> {\n const { signal } = options;\n sink.onStart();\n\n let snippets = options.snippets ?? true;\n const snippetsPinned = options.snippets !== undefined;\n let cursor: string | undefined;\n let restarted = false;\n for (;;) {\n if (signal?.aborted) return false;\n let slice: SearchSlice;\n const request = {\n ...query,\n snippets,\n ...(cursor !== undefined\n ? { cursor }\n : options.from !== undefined\n ? { from: options.from }\n : {}),\n };\n try {\n // A scan nobody waits on, so it runs once the views' work is done.\n // Cancelling stops the engine working on the slice, not only the wait for it.\n slice = await ctx.cancellable(\n signal,\n ctx.doc.with({ priority: 'low' }).search.query(request),\n );\n } catch (error) {\n if (signal?.aborted) return false;\n // Snippets denied (no doc.text.copy)? Degrade to matches without them.\n if (\n !snippetsPinned &&\n snippets &&\n cursor === undefined &&\n isPluginError(error, 'permission-denied')\n ) {\n snippets = false;\n continue;\n }\n // A stale cursor rejects with InvalidArg: the document changed under the\n // loop. Position is lost, the query is not: restart once from scratch.\n if (cursor !== undefined && !restarted && isPluginError(error, 'invalid-input')) {\n restarted = true;\n cursor = undefined;\n sink.onStart();\n continue;\n }\n throw error;\n }\n if (signal?.aborted) return false;\n sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);\n if (slice.nextCursor === null) return true;\n cursor = slice.nextCursor;\n }\n }\n\n // ── the session ──────────────────────────────────────────────────────────\n\n const viewportFirstPage = (): PageRef | undefined => {\n const stage = ctx.tryGet(StageToken);\n return stage?.getCurrentPage() ?? undefined;\n };\n\n // Async so a refusal or a page that isn't in the document rejects, like any other failure,\n // before the session is touched. The run still starts synchronously, so a newer search\n // supersedes an older one in the order they were called.\n async function search(query: SearchQuery, options: SearchOptions = {}): Promise<SearchResult> {\n if (query.text.length === 0) {\n clear();\n return { status: 'complete', hitCount: 0 };\n }\n ctx.assertAllowed('doc.text.search', 'search');\n const from = options.from === undefined ? viewportFirstPage() : ctx.pageOf(options.from).ref;\n let operationId = '';\n return session\n .run(async (run) => {\n operationId = run.id;\n const complete = await collect(\n query,\n { from, signal: run.signal },\n {\n onStart: () =>\n run.commit(() => {\n ctx.state.update(startSession, query, run.id);\n started.emit({ query });\n }),\n onSlice: (hits, pagesSearched, pageCount) =>\n run.commit(() => ctx.state.update(appendHits, hits, { pagesSearched, pageCount })),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'search aborted');\n run.commit(() => {\n ctx.state.update(completeSession);\n completed.emit({ hitCount: state().hits.length });\n });\n return { status: 'complete', hitCount: state().hits.length } as SearchResult;\n }, options)\n .catch((error: unknown): SearchResult => {\n if (isPluginError(error, 'instance-closed')) return { status: 'cancelled', hitCount: 0 };\n if (isPluginError(error, 'operation-cancelled')) {\n const why = (error.details as LatestCancellation | undefined)?.reason ?? 'cancelled';\n const reason: SearchCancelledEvent['reason'] =\n why === 'superseded' ? 'superseded' : why === 'cleared' ? 'cleared' : 'cancelled';\n // A superseded or cleared run has already lost the session; a cancelled one keeps its hits.\n if (reason === 'cancelled' && state().operationId === operationId) {\n ctx.state.update(cancelSession);\n }\n cancelled.emit({ reason });\n return {\n status: reason === 'superseded' ? 'superseded' : 'cancelled',\n hitCount: state().hits.length,\n };\n }\n const info = toPluginErrorInfo(toPluginError('search', error));\n if (state().operationId === operationId) ctx.state.update(failSession, info);\n failed.emit({ error: info });\n throw error;\n });\n }\n\n function clear(): void {\n session.cancel('cleared');\n ctx.state.update(clearSession);\n }\n\n function goToHit(target: SearchHit | number, options?: SearchRevealOptions): SearchHit | null {\n const { hits } = state();\n if (hits.length === 0) return null;\n const index =\n typeof target === 'number'\n ? ((target % hits.length) + hits.length) % hits.length\n : indexOfHit(hits, target);\n if (index < 0) return null;\n ctx.state.update(setActiveHit, index);\n reveal(hits[index], options);\n return hits[index];\n }\n\n function reveal(hit: SearchHit, options?: SearchRevealOptions): void {\n // Positioned reveal: the hit (not just its page) arrives at the anchor —\n // the call's options over the `reveal` setting. Zoom never changes.\n const arrival = { ...settings.get().reveal, ...options };\n ctx.tryGet(StageToken)?.reveal(hit.page, {\n rect: hit.bounds,\n anchor: arrival.anchor,\n behavior: arrival.behavior,\n });\n }\n\n /**\n * One page's hits, by the page's ref or index. A page that isn't in the\n * document has none: a layer may read while its page is being deleted.\n */\n const hitsOn = (page: PageRef | number): readonly SearchHit[] => {\n const found = ctx.getPage(page);\n return found ? (state().hitsByPage[found.ref.objectNumber] ?? EMPTY) : EMPTY;\n };\n\n const api: SearchCapability = {\n ...settings.api,\n\n // The twin of search() and findAll(), which refuse without doc.text.search.\n // Snippets need doc.text.copy too, but a search without it still runs: its\n // matches come without snippets (see collect).\n canSearch: (options) =>\n ctx.allows('doc.text.search') && (!options?.snippets || ctx.allows('doc.text.copy')),\n\n search,\n refresh: (options) => {\n const { query, status } = state();\n if (!query || status === 'idle') return Promise.resolve({ status: 'complete', hitCount: 0 });\n return search(query, options);\n },\n cancel: () => session.cancel('cancelled'),\n clear,\n\n nextHit: (options) => goToHit(state().activeHitIndex + 1, options),\n previousHit: (options) => goToHit(state().activeHitIndex - 1, options),\n goToHit,\n revealActiveHit: (options) => {\n const hit = api.getActiveHit();\n if (hit) reveal(hit, options);\n },\n\n getQuery: () => state().query,\n getStatus: () => state().status,\n listHits: (filter) => (filter?.page === undefined ? state().hits : hitsOn(filter.page)),\n getHitCount: (page) => (page === undefined ? state().hits : hitsOn(page)).length,\n listPagesWithHits: () =>\n state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,\n getActiveHitIndex: () => state().activeHitIndex,\n getActiveHit: () => state().hits[state().activeHitIndex] ?? null,\n getProgress: () => state().progress,\n getError: () => state().error,\n\n // ── the service ──────────────────────────────────────────────────────\n findAll: async (query, options = {}) => {\n ctx.assertAllowed('doc.text.search', 'findAll');\n const all: SearchHit[] = [];\n const complete = await collect(\n query,\n {\n ...(options.snippets !== undefined ? { snippets: options.snippets } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n },\n {\n onStart: () => {\n all.length = 0;\n },\n onSlice: (hits) => all.push(...hits),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'findAll aborted');\n return all;\n },\n\n onStarted: started.on,\n onProgressChanged: progressChanged.on,\n onCompleted: completed.on,\n onCancelled: cancelled.on,\n onFailed: failed.on,\n onActiveHitChanged: activeHitChanged.on,\n onCleared: cleared.on,\n };\n\n return {\n api,\n connect() {\n // Every confirmed mutation (own or remote) invalidates cursors and can change\n // what is findable, so the running or finished session re-runs its query.\n let cancelRerun: (() => void) | null = null;\n ctx.listen(ctx.doc.events, () => {\n if (state().status === 'idle') return;\n cancelRerun?.();\n cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {\n cancelRerun = null;\n void api.refresh().catch(() => {\n /* surfaced through getStatus() and onFailed */\n });\n });\n });\n },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { SEARCH_DEFAULTS, SearchToken, type SearchConfig } from './contract';\nimport { createSearchController } from './controller';\nimport { initialSearchModel } from './model';\n\n/**\n * Document text search over the engine's budgeted, resumable slices.\n * Document-scoped; no pointer handling. The stage is optional: with one,\n * scans start at the current page and navigation reveals hits. `config` is\n * the settings the app registers, over {@link SEARCH_DEFAULTS}.\n */\nexport const searchPlugin = (config?: SearchConfig) =>\n definePlugin({\n id: 'search',\n token: SearchToken,\n scope: 'document',\n optional: [StageToken],\n state: initialSearchModel,\n settings: { defaults: SEARCH_DEFAULTS, registered: config },\n create: createSearchController,\n });\n","/**\n * The search page's State table as code: what `useSearchState()` returns, and\n * the same fields in every other framework. The matches themselves are not\n * here: `useSearchHits()` reads them, so a component that only shows the\n * count doesn't re-render for every match that arrives.\n */\nimport { defineState, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport { SearchToken, type SearchHit, type SearchProgress, type SearchStatus } from './contract';\nimport { NO_PROGRESS } from './model';\n\n/** The query, where the search is, how many hits it found, the active hit, and why it failed. */\nexport interface SearchState {\n /** What is searched for, or `null` before a search. */\n readonly query: SearchQuery | null;\n /** Where the search is: `idle`, `searching`, `complete`, `cancelled` or `error`. */\n readonly status: SearchStatus;\n /** How many hits were found so far. */\n readonly hitCount: number;\n /** The active hit's index, or `-1` when no hit is active. */\n readonly activeHitIndex: number;\n /** The active hit, or `null`. */\n readonly activeHit: SearchHit | null;\n /** How many pages the search went through, of how many. */\n readonly progress: SearchProgress;\n /** Why the search failed, or `null`. */\n readonly error: PluginErrorInfo | null;\n}\n\nexport const searchState = defineState(SearchToken, {\n read: (search): SearchState => ({\n query: search.getQuery(),\n status: search.getStatus(),\n hitCount: search.getHitCount(),\n activeHitIndex: search.getActiveHitIndex(),\n activeHit: search.getActiveHit(),\n progress: search.getProgress(),\n error: search.getError(),\n }),\n empty: {\n query: null,\n status: 'idle',\n hitCount: 0,\n activeHitIndex: -1,\n activeHit: null,\n progress: NO_PROGRESS,\n error: null,\n },\n});\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAa,cAA8B,OAAO,OAAO;CAAE,eAAe;CAAG,WAAW;AAAE,CAAC;AAE3F,MAAa,4BAAyC;CACpD,OAAO;CACP,QAAQ;CACR,aAAa;CACb,MAAM,CAAC;CACP,YAAY,CAAC;CACb,gBAAgB;CAChB,UAAU;CACV,OAAO;AACT;;AAGA,MAAa,gBACX,QACA,OACA,iBACiB;CAAE,GAAG,mBAAmB;CAAG;CAAO,QAAQ;CAAa;AAAY;AAEtF,MAAM,gBAAgB,MAAsB,UAC1C,KAAK,kBAAkB,MAAM,iBAAiB,KAAK,cAAc,MAAM;;;;;;;AAQzE,SAAgB,WACd,OACA,MACA,OACa;CACb,MAAM,WAAW,aAAa,MAAM,UAAU,KAAK,IAAI,MAAM,WAAW;CACxE,IAAI,KAAK,WAAW,GAAG,OAAO,aAAa,MAAM,WAAW,QAAQ;EAAE,GAAG;EAAO;CAAS;CACzF,MAAM,aAAmD,EAAE,GAAG,MAAM,WAAW;CAC/E,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,mBAAmB,IAAI,KAAK;EAClC,WAAW,oBAAoB,CAAC,GAAI,WAAW,qBAAqB,CAAC,GAAI,GAAG;CAC9E;CACA,OAAO;EACL,GAAG;EACH,MAAM,CAAC,GAAG,MAAM,MAAM,GAAG,IAAI;EAC7B;EACA,gBAAgB,MAAM,mBAAmB,KAAK,IAAI,MAAM;EACxD;CACF;AACF;AAEA,MAAa,mBAAmB,WAAqC;CACnE,GAAG;CACH,QAAQ;AACV;AAEA,MAAa,iBAAiB,WAAqC;CACjE,GAAG;CACH,QAAQ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,QAAQ,CAAC,CAAC,YAAY,CAE/B,CAAC;IACH,CAAC;GACH,CAAC;EACH;CACF;AACF;;;;;;;;;ACxWA,MAAa,gBAAgB,YAAA,GAAA,eAAA,aAAA,CACd;CACX,IAAI;CACJ,OAAOC,iBAAAA;CACP,OAAO;CACP,UAAU,CAACC,gCAAAA,UAAU;CACrB,OAAO;CACP,UAAU;EAAE,UAAUC,iBAAAA;EAAiB,YAAY;CAAO;CAC1D,QAAQ;AACV,CAAC;;;;;;;;;ACQH,MAAa,eAAA,GAAA,eAAA,YAAA,CAA0BC,iBAAAA,aAAa;CAClD,OAAO,YAAyB;EAC9B,OAAO,OAAO,SAAS;EACvB,QAAQ,OAAO,UAAU;EACzB,UAAU,OAAO,YAAY;EAC7B,gBAAgB,OAAO,kBAAkB;EACzC,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,OAAO,OAAO,SAAS;CACzB;CACA,OAAO;EACL,OAAO;EACP,QAAQ;EACR,UAAU;EACV,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,OAAO;CACT;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["StageToken","PluginError","SearchToken","StageToken","SEARCH_DEFAULTS","SearchToken"],"sources":["../src/model.ts","../src/controller.ts","../src/search.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The search session: the query, the hits found so far (also grouped by\n * page), the active hit, and progress. Every function below is a pure\n * transition; the controller applies them with `ctx.state.update`.\n */\nimport { pageRefsEqual, type PageRef, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport type { SearchHit, SearchProgress, SearchStatus } from './contract';\n\nexport interface SearchModel {\n /** The query being searched, as the engine matches it. Null when idle. */\n readonly query: SearchQuery | null;\n readonly status: SearchStatus;\n /** The run that owns the session, so a run that lost it (superseded, cleared) leaves it alone. */\n readonly operationId: string | null;\n readonly hits: readonly SearchHit[];\n /** Page object number → the hits on that page; a page's array is replaced only when it gains hits. */\n readonly hitsByPage: Readonly<Record<number, readonly SearchHit[]>>;\n /** Index into `hits`, -1 when no hit is active. */\n readonly activeHitIndex: number;\n readonly progress: SearchProgress;\n readonly error: PluginErrorInfo | null;\n}\n\n/** The progress of no search, one object for every session that hasn't searched a page yet. */\nexport const NO_PROGRESS: SearchProgress = Object.freeze({ pagesSearched: 0, pageCount: 0 });\n\nexport const initialSearchModel = (): SearchModel => ({\n query: null,\n status: 'idle',\n operationId: null,\n hits: [],\n hitsByPage: {},\n activeHitIndex: -1,\n progress: NO_PROGRESS,\n error: null,\n});\n\n/** A new scan starts: everything from the previous session is dropped. */\nexport const startSession = (\n _state: SearchModel,\n query: SearchQuery,\n operationId: string,\n): SearchModel => ({ ...initialSearchModel(), query, status: 'searching', operationId });\n\nconst sameProgress = (left: SearchProgress, right: SearchProgress): boolean =>\n left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;\n\n/**\n * A slice of hits arrived. The first hit becomes active so \"1 of N\" reads\n * right; moving the camera is navigation's job, not the stream's. Progress\n * with the same counts keeps its object: readers, and `onProgressChanged`,\n * see a change only when the counts change.\n */\nexport function appendHits(\n state: SearchModel,\n hits: readonly SearchHit[],\n slice: SearchProgress,\n): SearchModel {\n const progress = sameProgress(state.progress, slice) ? state.progress : slice;\n if (hits.length === 0) return progress === state.progress ? state : { ...state, progress };\n const hitsByPage: Record<number, readonly SearchHit[]> = { ...state.hitsByPage };\n for (const hit of hits) {\n const pageObjectNumber = hit.page.objectNumber;\n hitsByPage[pageObjectNumber] = [...(hitsByPage[pageObjectNumber] ?? []), hit];\n }\n return {\n ...state,\n hits: [...state.hits, ...hits],\n hitsByPage,\n activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,\n progress,\n };\n}\n\nexport const completeSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'complete',\n});\n\nexport const cancelSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'cancelled',\n});\n\nexport const failSession = (state: SearchModel, error: PluginErrorInfo): SearchModel => ({\n ...state,\n status: 'error',\n error,\n});\n\nexport const setActiveHit = (state: SearchModel, index: number): SearchModel =>\n state.activeHitIndex === index ? state : { ...state, activeHitIndex: index };\n\nexport const clearSession = (state: SearchModel): SearchModel =>\n state.status === 'idle' ? state : initialSearchModel();\n\n/**\n * Where `hit` is in `hits`: the same object, or else the hit that covers the\n * same characters of the same page, so a hit kept from before the search ran\n * again still finds its place. -1 when it isn't there.\n */\nexport function indexOfHit(hits: readonly SearchHit[], hit: SearchHit): number {\n const same = hits.indexOf(hit);\n if (same >= 0) return same;\n return hits.findIndex(\n (candidate) =>\n candidate.start === hit.start &&\n candidate.count === hit.count &&\n pageRefsEqual(candidate.page, hit.page),\n );\n}\n\n/**\n * The pages that have at least one hit, in document order: `pages` is the\n * document's page list, whose order moving a page changes (object numbers\n * don't follow it).\n */\nexport const pagesWithHits = (\n state: SearchModel,\n pages: readonly { readonly ref: PageRef }[],\n): readonly PageRef[] =>\n pages\n .filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0)\n .map((page) => page.ref);\n","import {\n PluginError,\n isPluginError,\n toPluginError,\n toPluginErrorInfo,\n type PluginContext,\n type LatestCancellation,\n type PageRef,\n} from '@embedpdf/core';\nimport { boundsOfRects } from '@embedpdf/core-geometry';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\nimport type { SearchQuery, SearchSlice } from '@embedpdf/engine-core/runtime';\nimport type {\n SearchActiveHitChangedEvent,\n SearchCancelledEvent,\n SearchCapability,\n SearchClearedEvent,\n SearchCompletedEvent,\n SearchFailedEvent,\n SearchHit,\n SearchOptions,\n SearchProgressChangedEvent,\n SearchResult,\n SearchRevealOptions,\n SearchSettings,\n SearchStartedEvent,\n} from './contract';\nimport {\n appendHits,\n cancelSession,\n clearSession,\n completeSession,\n failSession,\n indexOfHit,\n pagesWithHits,\n setActiveHit,\n startSession,\n type SearchModel,\n} from './model';\n\nconst EMPTY: readonly SearchHit[] = Object.freeze([]);\nconst EMPTY_PAGES: readonly PageRef[] = Object.freeze([]);\n\n/** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */\nconst RERUN_DELAY_MS = 250;\n\n/** How a `collect()` consumer observes the loop: the session updates state, findAll accumulates. */\ninterface CollectSink {\n /** Before the first slice, and again on a stale-cursor restart: reset any accumulation. */\n onStart(): void;\n onSlice(hits: readonly SearchHit[], pagesSearched: number, pageCount: number): void;\n}\n\n/**\n * The search controller. `search` runs on a `latest` lane (a newer search\n * supersedes the older one, which can no longer publish); `findAll` runs on\n * its own signal and never touches the session. Both share `collect`, the\n * one cursor loop over the engine's budgeted slices.\n *\n * The scan's own events (started, completed, cancelled, failed) fire where\n * the scan reaches those points. The progress, active-hit and cleared events\n * are derived from state changes, so they always agree with the getters.\n *\n * The settings are read where they're used, never copied, so\n * `updateSettings({ reveal })` applies to the next move at once.\n */\nexport function createSearchController(ctx: PluginContext<SearchModel, SearchSettings>) {\n const settings = ctx.settings();\n const session = ctx.latest('session');\n const started = ctx.events.source<SearchStartedEvent>();\n const progressChanged = ctx.events.source<SearchProgressChangedEvent>();\n const completed = ctx.events.source<SearchCompletedEvent>();\n const cancelled = ctx.events.source<SearchCancelledEvent>();\n const failed = ctx.events.source<SearchFailedEvent>();\n const activeHitChanged = ctx.events.source<SearchActiveHitChangedEvent>();\n const cleared = ctx.events.source<SearchClearedEvent>();\n\n const state = () => ctx.state.get();\n\n ctx.state.onChange(({ previous, next }) => {\n // A slice moves it forward; a new search or clear() puts it back to none.\n if (previous.progress !== next.progress) {\n progressChanged.emit({ ...next.progress, hitCount: next.hits.length });\n }\n if (previous.activeHitIndex !== next.activeHitIndex) {\n activeHitChanged.emit({\n index: next.activeHitIndex,\n hit: next.hits[next.activeHitIndex] ?? null,\n });\n }\n if (previous.status !== 'idle' && next.status === 'idle') cleared.emit({});\n });\n\n // ── projection: engine slice → page-space hits ───────────────────────────\n\n function hitsFromSlice(slice: SearchSlice): SearchHit[] {\n const hits: SearchHit[] = [];\n for (const match of slice.matches) {\n // A page that vanished mid-search (deleted) drops its hits.\n const page = ctx.getPage(match.page);\n if (!page) continue;\n // Segments arrive in page space, ready to draw.\n const segments = match.segments;\n hits.push({\n page: match.page,\n pageIndex: page.index,\n start: match.start,\n count: match.count,\n segments,\n ...(segments.length\n ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? undefined }\n : {}),\n ...(match.snippet ? { snippet: match.snippet } : {}),\n });\n }\n return hits;\n }\n\n // ── the mechanism ────────────────────────────────────────────────────────\n\n /**\n * One cursor loop over budgeted slices: snippets when the session may copy\n * text (unless pinned), falling back to none if the engine still denies them,\n * restart-once on a stale cursor, projection per slice. Returns true on\n * exhaustion, false when the signal aborted; throws on a real error (already\n * a PluginError: ctx.doc is guarded).\n */\n async function collect(\n query: SearchQuery,\n options: { from?: PageRef; snippets?: boolean; signal?: AbortSignal },\n sink: CollectSink,\n ): Promise<boolean> {\n const { signal } = options;\n sink.onStart();\n\n // A snippet reproduces document text, so ask for one only where copying is allowed:\n // the engine would refuse it, and the request would cost a round trip for nothing.\n let snippets = options.snippets ?? ctx.allows('doc.text.copy');\n const snippetsPinned = options.snippets !== undefined;\n let cursor: string | undefined;\n let restarted = false;\n for (;;) {\n if (signal?.aborted) return false;\n let slice: SearchSlice;\n const request = {\n ...query,\n snippets,\n ...(cursor !== undefined\n ? { cursor }\n : options.from !== undefined\n ? { from: options.from }\n : {}),\n };\n try {\n // A scan nobody waits on, so it runs once the views' work is done.\n // Cancelling stops the engine working on the slice, not only the wait for it.\n slice = await ctx.cancellable(\n signal,\n ctx.doc.with({ priority: 'low' }).search.query(request),\n );\n } catch (error) {\n if (signal?.aborted) return false;\n // Snippets denied although the session looked allowed to copy (its permissions\n // changed on the server)? Degrade to matches without them.\n if (\n !snippetsPinned &&\n snippets &&\n cursor === undefined &&\n isPluginError(error, 'permission-denied')\n ) {\n snippets = false;\n continue;\n }\n // A stale cursor rejects with InvalidArg: the document changed under the\n // loop. Position is lost, the query is not: restart once from scratch.\n if (cursor !== undefined && !restarted && isPluginError(error, 'invalid-input')) {\n restarted = true;\n cursor = undefined;\n sink.onStart();\n continue;\n }\n throw error;\n }\n if (signal?.aborted) return false;\n sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);\n if (slice.nextCursor === null) return true;\n cursor = slice.nextCursor;\n }\n }\n\n // ── the session ──────────────────────────────────────────────────────────\n\n const viewportFirstPage = (): PageRef | undefined => {\n const stage = ctx.tryGet(StageToken);\n return stage?.getCurrentPage() ?? undefined;\n };\n\n // Async so a refusal or a page that isn't in the document rejects, like any other failure,\n // before the session is touched. The run still starts synchronously, so a newer search\n // supersedes an older one in the order they were called.\n async function search(query: SearchQuery, options: SearchOptions = {}): Promise<SearchResult> {\n if (query.text.length === 0) {\n clear();\n return { status: 'complete', hitCount: 0 };\n }\n ctx.assertAllowed('doc.text.search', 'search');\n const from = options.from === undefined ? viewportFirstPage() : ctx.pageOf(options.from).ref;\n let operationId = '';\n return session\n .run(async (run) => {\n operationId = run.id;\n const complete = await collect(\n query,\n { from, signal: run.signal },\n {\n onStart: () =>\n run.commit(() => {\n ctx.state.update(startSession, query, run.id);\n started.emit({ query });\n }),\n onSlice: (hits, pagesSearched, pageCount) =>\n run.commit(() => ctx.state.update(appendHits, hits, { pagesSearched, pageCount })),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'search aborted');\n run.commit(() => {\n ctx.state.update(completeSession);\n completed.emit({ hitCount: state().hits.length });\n });\n return { status: 'complete', hitCount: state().hits.length } as SearchResult;\n }, options)\n .catch((error: unknown): SearchResult => {\n if (isPluginError(error, 'instance-closed')) return { status: 'cancelled', hitCount: 0 };\n if (isPluginError(error, 'operation-cancelled')) {\n const why = (error.details as LatestCancellation | undefined)?.reason ?? 'cancelled';\n const reason: SearchCancelledEvent['reason'] =\n why === 'superseded' ? 'superseded' : why === 'cleared' ? 'cleared' : 'cancelled';\n // A superseded or cleared run has already lost the session; a cancelled one keeps its hits.\n if (reason === 'cancelled' && state().operationId === operationId) {\n ctx.state.update(cancelSession);\n }\n cancelled.emit({ reason });\n return {\n status: reason === 'superseded' ? 'superseded' : 'cancelled',\n hitCount: state().hits.length,\n };\n }\n const info = toPluginErrorInfo(toPluginError('search', error));\n if (state().operationId === operationId) ctx.state.update(failSession, info);\n failed.emit({ error: info });\n throw error;\n });\n }\n\n function clear(): void {\n session.cancel('cleared');\n ctx.state.update(clearSession);\n }\n\n function goToHit(target: SearchHit | number, options?: SearchRevealOptions): SearchHit | null {\n const { hits } = state();\n if (hits.length === 0) return null;\n const index =\n typeof target === 'number'\n ? ((target % hits.length) + hits.length) % hits.length\n : indexOfHit(hits, target);\n if (index < 0) return null;\n ctx.state.update(setActiveHit, index);\n reveal(hits[index], options);\n return hits[index];\n }\n\n function reveal(hit: SearchHit, options?: SearchRevealOptions): void {\n // Positioned reveal: the hit (not just its page) arrives at the alignment —\n // the call's options over the `reveal` setting. Zoom never changes.\n const arrival = { ...settings.get().reveal, ...options };\n ctx.tryGet(StageToken)?.reveal(hit.page, {\n rect: hit.bounds,\n align: arrival.align,\n behavior: arrival.behavior,\n });\n }\n\n /**\n * One page's hits, by the page's ref or index. A page that isn't in the\n * document has none: a layer may read while its page is being deleted.\n */\n const hitsOn = (page: PageRef | number): readonly SearchHit[] => {\n const found = ctx.getPage(page);\n return found ? (state().hitsByPage[found.ref.objectNumber] ?? EMPTY) : EMPTY;\n };\n\n const api: SearchCapability = {\n ...settings.api,\n\n // The twin of search() and findAll(), which refuse without doc.text.search.\n // Snippets need doc.text.copy too, but a search without it still runs: its\n // matches come without snippets (see collect).\n canSearch: (options) =>\n ctx.allows('doc.text.search') && (!options?.snippets || ctx.allows('doc.text.copy')),\n\n search,\n refresh: async (options) => {\n const { query, status } = state();\n if (!query || status === 'idle') return;\n await search(query, options);\n },\n cancel: () => session.cancel('cancelled'),\n clear,\n\n nextHit: (options) => goToHit(state().activeHitIndex + 1, options),\n previousHit: (options) => goToHit(state().activeHitIndex - 1, options),\n goToHit,\n revealActiveHit: (options) => {\n const hit = api.getActiveHit();\n if (hit) reveal(hit, options);\n },\n\n getQuery: () => state().query,\n getStatus: () => state().status,\n listHits: (filter) => (filter?.page === undefined ? state().hits : hitsOn(filter.page)),\n getHitCount: (page) => (page === undefined ? state().hits : hitsOn(page)).length,\n listPagesWithHits: () =>\n state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,\n getActiveHitIndex: () => state().activeHitIndex,\n getActiveHit: () => state().hits[state().activeHitIndex] ?? null,\n getProgress: () => state().progress,\n getError: () => state().error,\n\n // ── the service ──────────────────────────────────────────────────────\n findAll: async (query, options = {}) => {\n ctx.assertAllowed('doc.text.search', 'findAll');\n // Snippets pinned on are a requirement: refuse here rather than ask the engine.\n if (options.snippets) ctx.assertAllowed('doc.text.copy', 'findAll');\n const all: SearchHit[] = [];\n const complete = await collect(\n query,\n {\n ...(options.snippets !== undefined ? { snippets: options.snippets } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n },\n {\n onStart: () => {\n all.length = 0;\n },\n onSlice: (hits) => all.push(...hits),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'findAll aborted');\n return all;\n },\n\n onStarted: started.on,\n onProgressChanged: progressChanged.on,\n onCompleted: completed.on,\n onCancelled: cancelled.on,\n onFailed: failed.on,\n onActiveHitChanged: activeHitChanged.on,\n onCleared: cleared.on,\n };\n\n return {\n api,\n connect() {\n // Every confirmed mutation (own or remote) invalidates cursors and can change\n // what is findable, so the running or finished session re-runs its query.\n let cancelRerun: (() => void) | null = null;\n ctx.listen(ctx.doc.events, () => {\n if (state().status === 'idle') return;\n cancelRerun?.();\n cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {\n cancelRerun = null;\n void api.refresh().catch(() => {\n /* surfaced through getStatus() and onFailed */\n });\n });\n });\n },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { SEARCH_DEFAULTS, SearchToken, type SearchConfig } from './contract';\nimport { createSearchController } from './controller';\nimport { initialSearchModel } from './model';\n\n/**\n * Document text search over the engine's budgeted, resumable slices.\n * Document-scoped; no pointer handling. The stage is optional: with one,\n * scans start at the current page and navigation reveals hits. `config` is\n * the settings the app registers, over {@link SEARCH_DEFAULTS}.\n */\nexport const searchPlugin = (config?: SearchConfig) =>\n definePlugin({\n id: 'search',\n token: SearchToken,\n scope: 'document',\n optional: [StageToken],\n state: initialSearchModel,\n settings: { defaults: SEARCH_DEFAULTS, registered: config },\n create: createSearchController,\n });\n","/**\n * The search page's State table as code: what `useSearchState()` returns, and\n * the same fields in every other framework. The matches themselves are not\n * here: `useSearchHits()` reads them, so a component that only shows the\n * count doesn't re-render for every match that arrives.\n */\nimport { defineState, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport { SearchToken, type SearchHit, type SearchProgress, type SearchStatus } from './contract';\nimport { NO_PROGRESS } from './model';\n\n/** The query, where the search is, how many hits it found, the active hit, and why it failed. */\nexport interface SearchState {\n /** What is searched for, or `null` before a search. */\n readonly query: SearchQuery | null;\n /** Where the search is: `idle`, `searching`, `complete`, `cancelled` or `error`. */\n readonly status: SearchStatus;\n /** How many hits were found so far. */\n readonly hitCount: number;\n /** The active hit's index, or `-1` when no hit is active. */\n readonly activeHitIndex: number;\n /** The active hit, or `null`. */\n readonly activeHit: SearchHit | null;\n /** How many pages the search went through, of how many. */\n readonly progress: SearchProgress;\n /** Why the search failed, or `null`. */\n readonly error: PluginErrorInfo | null;\n}\n\nexport const searchState = defineState(SearchToken, {\n read: (search): SearchState => ({\n query: search.getQuery(),\n status: search.getStatus(),\n hitCount: search.getHitCount(),\n activeHitIndex: search.getActiveHitIndex(),\n activeHit: search.getActiveHit(),\n progress: search.getProgress(),\n error: search.getError(),\n }),\n empty: {\n query: null,\n status: 'idle',\n hitCount: 0,\n activeHitIndex: -1,\n activeHit: null,\n prog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CACP,UAAU,CAACC,gCAAAA,UAAU;CACrB,OAAO;CACP,UAAU;EAAE,UAAUC,iBAAAA;EAAiB,YAAY;CAAO;CAC1D,QAAQ;AACV,CAAC;;;;;;;;;ACQH,MAAa,eAAA,GAAA,eAAA,YAAA,CAA0BC,iBAAAA,aAAa;CAClD,OAAO,YAAyB;EAC9B,OAAO,OAAO,SAAS;EACvB,QAAQ,OAAO,UAAU;EACzB,UAAU,OAAO,YAAY;EAC7B,gBAAgB,OAAO,kBAAkB;EACzC,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,OAAO,OAAO,SAAS;CACzB;CACA,OAAO;EACL,OAAO;EACP,QAAQ;EACR,UAAU;EACV,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,OAAO;CACT;AACF,CAAC"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as SearchSnippet, D as validateSearchQuery, E as TextSegment, O as validateSearchRegex, S as SearchSettings, T as SearchStatus, _ as SearchQueryValidation, a as SearchClearedEvent, b as SearchReveal, c as SearchFailedEvent, d as SearchHitFilter, f as SearchOptions, g as SearchQueryIssue, h as SearchQuery, i as SearchCapability, k as SearchToken, l as SearchFindAllOptions, m as SearchProgressChangedEvent, n as SearchActiveHitChangedEvent, o as SearchCompletedEvent, p as SearchProgress, r as SearchCancelledEvent, s as SearchConfig, t as SEARCH_DEFAULTS, u as SearchHit, v as SearchRegexValidation, w as SearchStartedEvent, x as SearchRevealOptions, y as SearchResult } from "./contract-DYeW6lpW.cjs";
|
|
2
2
|
import { PageRef, PluginErrorInfo } from "@embedpdf/core";
|
|
3
3
|
import { SearchQuery as SearchQuery$1 } from "@embedpdf/engine-core/runtime";
|
|
4
4
|
//#region src/model.d.ts
|
|
@@ -24,7 +24,7 @@ interface SearchModel {
|
|
|
24
24
|
* scans start at the current page and navigation reveals hits. `config` is
|
|
25
25
|
* the settings the app registers, over {@link SEARCH_DEFAULTS}.
|
|
26
26
|
*/
|
|
27
|
-
declare const searchPlugin: (config?: SearchConfig) => import("@embedpdf/core").
|
|
27
|
+
declare const searchPlugin: (config?: SearchConfig) => import("@embedpdf/core").PluginDefinition<SearchModel, SearchCapability, SearchSettings>;
|
|
28
28
|
//#endregion
|
|
29
29
|
//#region src/state.d.ts
|
|
30
30
|
/** The query, where the search is, how many hits it found, the active hit, and why it failed. */
|
|
@@ -46,5 +46,5 @@ interface SearchState {
|
|
|
46
46
|
}
|
|
47
47
|
declare const searchState: import("@embedpdf/core").StateDeclaration<SearchCapability, SearchState>;
|
|
48
48
|
//#endregion
|
|
49
|
-
export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent,
|
|
49
|
+
export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent, SearchCancelledEvent, SearchCapability, SearchClearedEvent, SearchCompletedEvent, SearchConfig, SearchFailedEvent, SearchFindAllOptions, SearchHit, SearchHitFilter, SearchOptions, SearchProgress, SearchProgressChangedEvent, type SearchQuery, type SearchQueryIssue, type SearchQueryValidation, type SearchRegexValidation, SearchResult, SearchReveal, SearchRevealOptions, SearchSettings, type SearchSnippet, SearchStartedEvent, type SearchState, SearchStatus, SearchToken, TextSegment, searchPlugin, searchState, validateSearchQuery, validateSearchRegex };
|
|
50
50
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as SearchSnippet, D as validateSearchQuery, E as TextSegment, O as validateSearchRegex, S as SearchSettings, T as SearchStatus, _ as SearchQueryValidation, a as SearchClearedEvent, b as SearchReveal, c as SearchFailedEvent, d as SearchHitFilter, f as SearchOptions, g as SearchQueryIssue, h as SearchQuery, i as SearchCapability, k as SearchToken, l as SearchFindAllOptions, m as SearchProgressChangedEvent, n as SearchActiveHitChangedEvent, o as SearchCompletedEvent, p as SearchProgress, r as SearchCancelledEvent, s as SearchConfig, t as SEARCH_DEFAULTS, u as SearchHit, v as SearchRegexValidation, w as SearchStartedEvent, x as SearchRevealOptions, y as SearchResult } from "./contract-Cl2UZGHY.js";
|
|
2
2
|
import { PageRef, PluginErrorInfo } from "@embedpdf/core";
|
|
3
3
|
import { SearchQuery as SearchQuery$1 } from "@embedpdf/engine-core/runtime";
|
|
4
4
|
//#region src/model.d.ts
|
|
@@ -24,7 +24,7 @@ interface SearchModel {
|
|
|
24
24
|
* scans start at the current page and navigation reveals hits. `config` is
|
|
25
25
|
* the settings the app registers, over {@link SEARCH_DEFAULTS}.
|
|
26
26
|
*/
|
|
27
|
-
declare const searchPlugin: (config?: SearchConfig) => import("@embedpdf/core").
|
|
27
|
+
declare const searchPlugin: (config?: SearchConfig) => import("@embedpdf/core").PluginDefinition<SearchModel, SearchCapability, SearchSettings>;
|
|
28
28
|
//#endregion
|
|
29
29
|
//#region src/state.d.ts
|
|
30
30
|
/** The query, where the search is, how many hits it found, the active hit, and why it failed. */
|
|
@@ -46,5 +46,5 @@ interface SearchState {
|
|
|
46
46
|
}
|
|
47
47
|
declare const searchState: import("@embedpdf/core").StateDeclaration<SearchCapability, SearchState>;
|
|
48
48
|
//#endregion
|
|
49
|
-
export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent,
|
|
49
|
+
export { SEARCH_DEFAULTS, SearchActiveHitChangedEvent, SearchCancelledEvent, SearchCapability, SearchClearedEvent, SearchCompletedEvent, SearchConfig, SearchFailedEvent, SearchFindAllOptions, SearchHit, SearchHitFilter, SearchOptions, SearchProgress, SearchProgressChangedEvent, type SearchQuery, type SearchQueryIssue, type SearchQueryValidation, type SearchRegexValidation, SearchResult, SearchReveal, SearchRevealOptions, SearchSettings, type SearchSnippet, SearchStartedEvent, type SearchState, SearchStatus, SearchToken, TextSegment, searchPlugin, searchState, validateSearchQuery, validateSearchRegex };
|
|
50
50
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as SearchToken, n as validateSearchQuery, r as validateSearchRegex, t as SEARCH_DEFAULTS } from "./contract-
|
|
1
|
+
import { i as SearchToken, n as validateSearchQuery, r as validateSearchRegex, t as SEARCH_DEFAULTS } from "./contract-MvB7O9LG.js";
|
|
2
2
|
import { PluginError, definePlugin, defineState, isPluginError, pageRefsEqual, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
|
|
3
3
|
import { StageToken } from "@embedpdf/plugin-stage/contract";
|
|
4
4
|
import { boundsOfRects } from "@embedpdf/core-geometry";
|
|
@@ -150,15 +150,16 @@ function createSearchController(ctx) {
|
|
|
150
150
|
return hits;
|
|
151
151
|
}
|
|
152
152
|
/**
|
|
153
|
-
* One cursor loop over budgeted slices:
|
|
154
|
-
*
|
|
155
|
-
* projection per slice. Returns true on
|
|
156
|
-
* aborted; throws on a real error (already
|
|
153
|
+
* One cursor loop over budgeted slices: snippets when the session may copy
|
|
154
|
+
* text (unless pinned), falling back to none if the engine still denies them,
|
|
155
|
+
* restart-once on a stale cursor, projection per slice. Returns true on
|
|
156
|
+
* exhaustion, false when the signal aborted; throws on a real error (already
|
|
157
|
+
* a PluginError: ctx.doc is guarded).
|
|
157
158
|
*/
|
|
158
159
|
async function collect(query, options, sink) {
|
|
159
160
|
const { signal } = options;
|
|
160
161
|
sink.onStart();
|
|
161
|
-
let snippets = options.snippets ??
|
|
162
|
+
let snippets = options.snippets ?? ctx.allows("doc.text.copy");
|
|
162
163
|
const snippetsPinned = options.snippets !== void 0;
|
|
163
164
|
let cursor;
|
|
164
165
|
let restarted = false;
|
|
@@ -270,7 +271,7 @@ function createSearchController(ctx) {
|
|
|
270
271
|
};
|
|
271
272
|
ctx.tryGet(StageToken)?.reveal(hit.page, {
|
|
272
273
|
rect: hit.bounds,
|
|
273
|
-
|
|
274
|
+
align: arrival.align,
|
|
274
275
|
behavior: arrival.behavior
|
|
275
276
|
});
|
|
276
277
|
}
|
|
@@ -286,13 +287,10 @@ function createSearchController(ctx) {
|
|
|
286
287
|
...settings.api,
|
|
287
288
|
canSearch: (options) => ctx.allows("doc.text.search") && (!options?.snippets || ctx.allows("doc.text.copy")),
|
|
288
289
|
search,
|
|
289
|
-
refresh: (options) => {
|
|
290
|
+
refresh: async (options) => {
|
|
290
291
|
const { query, status } = state();
|
|
291
|
-
if (!query || status === "idle") return
|
|
292
|
-
|
|
293
|
-
hitCount: 0
|
|
294
|
-
});
|
|
295
|
-
return search(query, options);
|
|
292
|
+
if (!query || status === "idle") return;
|
|
293
|
+
await search(query, options);
|
|
296
294
|
},
|
|
297
295
|
cancel: () => session.cancel("cancelled"),
|
|
298
296
|
clear,
|
|
@@ -314,6 +312,7 @@ function createSearchController(ctx) {
|
|
|
314
312
|
getError: () => state().error,
|
|
315
313
|
findAll: async (query, options = {}) => {
|
|
316
314
|
ctx.assertAllowed("doc.text.search", "findAll");
|
|
315
|
+
if (options.snippets) ctx.assertAllowed("doc.text.copy", "findAll");
|
|
317
316
|
const all = [];
|
|
318
317
|
if (!await collect(query, {
|
|
319
318
|
...options.snippets !== void 0 ? { snippets: options.snippets } : {},
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/model.ts","../src/controller.ts","../src/search.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The search session: the query, the hits found so far (also grouped by\n * page), the active hit, and progress. Every function below is a pure\n * transition; the controller applies them with `ctx.state.update`.\n */\nimport { pageRefsEqual, type PageRef, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport type { SearchHit, SearchProgress, SearchStatus } from './contract';\n\nexport interface SearchModel {\n /** The query being searched, as the engine matches it. Null when idle. */\n readonly query: SearchQuery | null;\n readonly status: SearchStatus;\n /** The run that owns the session, so a run that lost it (superseded, cleared) leaves it alone. */\n readonly operationId: string | null;\n readonly hits: readonly SearchHit[];\n /** Page object number → the hits on that page; a page's array is replaced only when it gains hits. */\n readonly hitsByPage: Readonly<Record<number, readonly SearchHit[]>>;\n /** Index into `hits`, -1 when no hit is active. */\n readonly activeHitIndex: number;\n readonly progress: SearchProgress;\n readonly error: PluginErrorInfo | null;\n}\n\n/** The progress of no search, one object for every session that hasn't searched a page yet. */\nexport const NO_PROGRESS: SearchProgress = Object.freeze({ pagesSearched: 0, pageCount: 0 });\n\nexport const initialSearchModel = (): SearchModel => ({\n query: null,\n status: 'idle',\n operationId: null,\n hits: [],\n hitsByPage: {},\n activeHitIndex: -1,\n progress: NO_PROGRESS,\n error: null,\n});\n\n/** A new scan starts: everything from the previous session is dropped. */\nexport const startSession = (\n _state: SearchModel,\n query: SearchQuery,\n operationId: string,\n): SearchModel => ({ ...initialSearchModel(), query, status: 'searching', operationId });\n\nconst sameProgress = (left: SearchProgress, right: SearchProgress): boolean =>\n left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;\n\n/**\n * A slice of hits arrived. The first hit becomes active so \"1 of N\" reads\n * right; moving the camera is navigation's job, not the stream's. Progress\n * with the same counts keeps its object: readers, and `onProgressChanged`,\n * see a change only when the counts change.\n */\nexport function appendHits(\n state: SearchModel,\n hits: readonly SearchHit[],\n slice: SearchProgress,\n): SearchModel {\n const progress = sameProgress(state.progress, slice) ? state.progress : slice;\n if (hits.length === 0) return progress === state.progress ? state : { ...state, progress };\n const hitsByPage: Record<number, readonly SearchHit[]> = { ...state.hitsByPage };\n for (const hit of hits) {\n const pageObjectNumber = hit.page.objectNumber;\n hitsByPage[pageObjectNumber] = [...(hitsByPage[pageObjectNumber] ?? []), hit];\n }\n return {\n ...state,\n hits: [...state.hits, ...hits],\n hitsByPage,\n activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,\n progress,\n };\n}\n\nexport const completeSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'complete',\n});\n\nexport const cancelSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'cancelled',\n});\n\nexport const failSession = (state: SearchModel, error: PluginErrorInfo): SearchModel => ({\n ...state,\n status: 'error',\n error,\n});\n\nexport const setActiveHit = (state: SearchModel, index: number): SearchModel =>\n state.activeHitIndex === index ? state : { ...state, activeHitIndex: index };\n\nexport const clearSession = (state: SearchModel): SearchModel =>\n state.status === 'idle' ? state : initialSearchModel();\n\n/**\n * Where `hit` is in `hits`: the same object, or else the hit that covers the\n * same characters of the same page, so a hit kept from before the search ran\n * again still finds its place. -1 when it isn't there.\n */\nexport function indexOfHit(hits: readonly SearchHit[], hit: SearchHit): number {\n const same = hits.indexOf(hit);\n if (same >= 0) return same;\n return hits.findIndex(\n (candidate) =>\n candidate.start === hit.start &&\n candidate.count === hit.count &&\n pageRefsEqual(candidate.page, hit.page),\n );\n}\n\n/**\n * The pages that have at least one hit, in document order: `pages` is the\n * document's page list, whose order moving a page changes (object numbers\n * don't follow it).\n */\nexport const pagesWithHits = (\n state: SearchModel,\n pages: readonly { readonly ref: PageRef }[],\n): readonly PageRef[] =>\n pages\n .filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0)\n .map((page) => page.ref);\n","import {\n PluginError,\n isPluginError,\n toPluginError,\n toPluginErrorInfo,\n type PluginContext,\n type LatestCancellation,\n type PageRef,\n} from '@embedpdf/core';\nimport { boundsOfRects } from '@embedpdf/core-geometry';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\nimport type { SearchQuery, SearchSlice } from '@embedpdf/engine-core/runtime';\nimport type {\n SearchActiveHitChangedEvent,\n SearchCancelledEvent,\n SearchCapability,\n SearchClearedEvent,\n SearchCompletedEvent,\n SearchFailedEvent,\n SearchHit,\n SearchOptions,\n SearchProgressChangedEvent,\n SearchResult,\n SearchRevealOptions,\n SearchSettings,\n SearchStartedEvent,\n} from './contract';\nimport {\n appendHits,\n cancelSession,\n clearSession,\n completeSession,\n failSession,\n indexOfHit,\n pagesWithHits,\n setActiveHit,\n startSession,\n type SearchModel,\n} from './model';\n\nconst EMPTY: readonly SearchHit[] = Object.freeze([]);\nconst EMPTY_PAGES: readonly PageRef[] = Object.freeze([]);\n\n/** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */\nconst RERUN_DELAY_MS = 250;\n\n/** How a `collect()` consumer observes the loop: the session updates state, findAll accumulates. */\ninterface CollectSink {\n /** Before the first slice, and again on a stale-cursor restart: reset any accumulation. */\n onStart(): void;\n onSlice(hits: readonly SearchHit[], pagesSearched: number, pageCount: number): void;\n}\n\n/**\n * The search controller. `search` runs on a `latest` lane (a newer search\n * supersedes the older one, which can no longer publish); `findAll` runs on\n * its own signal and never touches the session. Both share `collect`, the\n * one cursor loop over the engine's budgeted slices.\n *\n * The scan's own events (started, completed, cancelled, failed) fire where\n * the scan reaches those points. The progress, active-hit and cleared events\n * are derived from state changes, so they always agree with the getters.\n *\n * The settings are read where they're used, never copied, so\n * `updateSettings({ reveal })` applies to the next move at once.\n */\nexport function createSearchController(ctx: PluginContext<SearchModel, SearchSettings>) {\n const settings = ctx.settings();\n const session = ctx.latest('session');\n const started = ctx.events.source<SearchStartedEvent>();\n const progressChanged = ctx.events.source<SearchProgressChangedEvent>();\n const completed = ctx.events.source<SearchCompletedEvent>();\n const cancelled = ctx.events.source<SearchCancelledEvent>();\n const failed = ctx.events.source<SearchFailedEvent>();\n const activeHitChanged = ctx.events.source<SearchActiveHitChangedEvent>();\n const cleared = ctx.events.source<SearchClearedEvent>();\n\n const state = () => ctx.state.get();\n\n ctx.state.onChange(({ previous, next }) => {\n // A slice moves it forward; a new search or clear() puts it back to none.\n if (previous.progress !== next.progress) {\n progressChanged.emit({ ...next.progress, hitCount: next.hits.length });\n }\n if (previous.activeHitIndex !== next.activeHitIndex) {\n activeHitChanged.emit({\n index: next.activeHitIndex,\n hit: next.hits[next.activeHitIndex] ?? null,\n });\n }\n if (previous.status !== 'idle' && next.status === 'idle') cleared.emit({});\n });\n\n // ── projection: engine slice → page-space hits ───────────────────────────\n\n function hitsFromSlice(slice: SearchSlice): SearchHit[] {\n const hits: SearchHit[] = [];\n for (const match of slice.matches) {\n // A page that vanished mid-search (deleted) drops its hits.\n const page = ctx.getPage(match.page);\n if (!page) continue;\n // Segments arrive in page space, ready to draw.\n const segments = match.segments;\n hits.push({\n page: match.page,\n pageIndex: page.index,\n start: match.start,\n count: match.count,\n segments,\n ...(segments.length\n ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? undefined }\n : {}),\n ...(match.snippet ? { snippet: match.snippet } : {}),\n });\n }\n return hits;\n }\n\n // ── the mechanism ────────────────────────────────────────────────────────\n\n /**\n * One cursor loop over budgeted slices: permission fallback (snippets → none\n * when they are denied, unless pinned), restart-once on a stale cursor,\n * projection per slice. Returns true on exhaustion, false when the signal\n * aborted; throws on a real error (already a PluginError: ctx.doc is guarded).\n */\n async function collect(\n query: SearchQuery,\n options: { from?: PageRef; snippets?: boolean; signal?: AbortSignal },\n sink: CollectSink,\n ): Promise<boolean> {\n const { signal } = options;\n sink.onStart();\n\n let snippets = options.snippets ?? true;\n const snippetsPinned = options.snippets !== undefined;\n let cursor: string | undefined;\n let restarted = false;\n for (;;) {\n if (signal?.aborted) return false;\n let slice: SearchSlice;\n const request = {\n ...query,\n snippets,\n ...(cursor !== undefined\n ? { cursor }\n : options.from !== undefined\n ? { from: options.from }\n : {}),\n };\n try {\n // A scan nobody waits on, so it runs once the views' work is done.\n // Cancelling stops the engine working on the slice, not only the wait for it.\n slice = await ctx.cancellable(\n signal,\n ctx.doc.with({ priority: 'low' }).search.query(request),\n );\n } catch (error) {\n if (signal?.aborted) return false;\n // Snippets denied (no doc.text.copy)? Degrade to matches without them.\n if (\n !snippetsPinned &&\n snippets &&\n cursor === undefined &&\n isPluginError(error, 'permission-denied')\n ) {\n snippets = false;\n continue;\n }\n // A stale cursor rejects with InvalidArg: the document changed under the\n // loop. Position is lost, the query is not: restart once from scratch.\n if (cursor !== undefined && !restarted && isPluginError(error, 'invalid-input')) {\n restarted = true;\n cursor = undefined;\n sink.onStart();\n continue;\n }\n throw error;\n }\n if (signal?.aborted) return false;\n sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);\n if (slice.nextCursor === null) return true;\n cursor = slice.nextCursor;\n }\n }\n\n // ── the session ──────────────────────────────────────────────────────────\n\n const viewportFirstPage = (): PageRef | undefined => {\n const stage = ctx.tryGet(StageToken);\n return stage?.getCurrentPage() ?? undefined;\n };\n\n // Async so a refusal or a page that isn't in the document rejects, like any other failure,\n // before the session is touched. The run still starts synchronously, so a newer search\n // supersedes an older one in the order they were called.\n async function search(query: SearchQuery, options: SearchOptions = {}): Promise<SearchResult> {\n if (query.text.length === 0) {\n clear();\n return { status: 'complete', hitCount: 0 };\n }\n ctx.assertAllowed('doc.text.search', 'search');\n const from = options.from === undefined ? viewportFirstPage() : ctx.pageOf(options.from).ref;\n let operationId = '';\n return session\n .run(async (run) => {\n operationId = run.id;\n const complete = await collect(\n query,\n { from, signal: run.signal },\n {\n onStart: () =>\n run.commit(() => {\n ctx.state.update(startSession, query, run.id);\n started.emit({ query });\n }),\n onSlice: (hits, pagesSearched, pageCount) =>\n run.commit(() => ctx.state.update(appendHits, hits, { pagesSearched, pageCount })),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'search aborted');\n run.commit(() => {\n ctx.state.update(completeSession);\n completed.emit({ hitCount: state().hits.length });\n });\n return { status: 'complete', hitCount: state().hits.length } as SearchResult;\n }, options)\n .catch((error: unknown): SearchResult => {\n if (isPluginError(error, 'instance-closed')) return { status: 'cancelled', hitCount: 0 };\n if (isPluginError(error, 'operation-cancelled')) {\n const why = (error.details as LatestCancellation | undefined)?.reason ?? 'cancelled';\n const reason: SearchCancelledEvent['reason'] =\n why === 'superseded' ? 'superseded' : why === 'cleared' ? 'cleared' : 'cancelled';\n // A superseded or cleared run has already lost the session; a cancelled one keeps its hits.\n if (reason === 'cancelled' && state().operationId === operationId) {\n ctx.state.update(cancelSession);\n }\n cancelled.emit({ reason });\n return {\n status: reason === 'superseded' ? 'superseded' : 'cancelled',\n hitCount: state().hits.length,\n };\n }\n const info = toPluginErrorInfo(toPluginError('search', error));\n if (state().operationId === operationId) ctx.state.update(failSession, info);\n failed.emit({ error: info });\n throw error;\n });\n }\n\n function clear(): void {\n session.cancel('cleared');\n ctx.state.update(clearSession);\n }\n\n function goToHit(target: SearchHit | number, options?: SearchRevealOptions): SearchHit | null {\n const { hits } = state();\n if (hits.length === 0) return null;\n const index =\n typeof target === 'number'\n ? ((target % hits.length) + hits.length) % hits.length\n : indexOfHit(hits, target);\n if (index < 0) return null;\n ctx.state.update(setActiveHit, index);\n reveal(hits[index], options);\n return hits[index];\n }\n\n function reveal(hit: SearchHit, options?: SearchRevealOptions): void {\n // Positioned reveal: the hit (not just its page) arrives at the anchor —\n // the call's options over the `reveal` setting. Zoom never changes.\n const arrival = { ...settings.get().reveal, ...options };\n ctx.tryGet(StageToken)?.reveal(hit.page, {\n rect: hit.bounds,\n anchor: arrival.anchor,\n behavior: arrival.behavior,\n });\n }\n\n /**\n * One page's hits, by the page's ref or index. A page that isn't in the\n * document has none: a layer may read while its page is being deleted.\n */\n const hitsOn = (page: PageRef | number): readonly SearchHit[] => {\n const found = ctx.getPage(page);\n return found ? (state().hitsByPage[found.ref.objectNumber] ?? EMPTY) : EMPTY;\n };\n\n const api: SearchCapability = {\n ...settings.api,\n\n // The twin of search() and findAll(), which refuse without doc.text.search.\n // Snippets need doc.text.copy too, but a search without it still runs: its\n // matches come without snippets (see collect).\n canSearch: (options) =>\n ctx.allows('doc.text.search') && (!options?.snippets || ctx.allows('doc.text.copy')),\n\n search,\n refresh: (options) => {\n const { query, status } = state();\n if (!query || status === 'idle') return Promise.resolve({ status: 'complete', hitCount: 0 });\n return search(query, options);\n },\n cancel: () => session.cancel('cancelled'),\n clear,\n\n nextHit: (options) => goToHit(state().activeHitIndex + 1, options),\n previousHit: (options) => goToHit(state().activeHitIndex - 1, options),\n goToHit,\n revealActiveHit: (options) => {\n const hit = api.getActiveHit();\n if (hit) reveal(hit, options);\n },\n\n getQuery: () => state().query,\n getStatus: () => state().status,\n listHits: (filter) => (filter?.page === undefined ? state().hits : hitsOn(filter.page)),\n getHitCount: (page) => (page === undefined ? state().hits : hitsOn(page)).length,\n listPagesWithHits: () =>\n state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,\n getActiveHitIndex: () => state().activeHitIndex,\n getActiveHit: () => state().hits[state().activeHitIndex] ?? null,\n getProgress: () => state().progress,\n getError: () => state().error,\n\n // ── the service ──────────────────────────────────────────────────────\n findAll: async (query, options = {}) => {\n ctx.assertAllowed('doc.text.search', 'findAll');\n const all: SearchHit[] = [];\n const complete = await collect(\n query,\n {\n ...(options.snippets !== undefined ? { snippets: options.snippets } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n },\n {\n onStart: () => {\n all.length = 0;\n },\n onSlice: (hits) => all.push(...hits),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'findAll aborted');\n return all;\n },\n\n onStarted: started.on,\n onProgressChanged: progressChanged.on,\n onCompleted: completed.on,\n onCancelled: cancelled.on,\n onFailed: failed.on,\n onActiveHitChanged: activeHitChanged.on,\n onCleared: cleared.on,\n };\n\n return {\n api,\n connect() {\n // Every confirmed mutation (own or remote) invalidates cursors and can change\n // what is findable, so the running or finished session re-runs its query.\n let cancelRerun: (() => void) | null = null;\n ctx.listen(ctx.doc.events, () => {\n if (state().status === 'idle') return;\n cancelRerun?.();\n cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {\n cancelRerun = null;\n void api.refresh().catch(() => {\n /* surfaced through getStatus() and onFailed */\n });\n });\n });\n },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { SEARCH_DEFAULTS, SearchToken, type SearchConfig } from './contract';\nimport { createSearchController } from './controller';\nimport { initialSearchModel } from './model';\n\n/**\n * Document text search over the engine's budgeted, resumable slices.\n * Document-scoped; no pointer handling. The stage is optional: with one,\n * scans start at the current page and navigation reveals hits. `config` is\n * the settings the app registers, over {@link SEARCH_DEFAULTS}.\n */\nexport const searchPlugin = (config?: SearchConfig) =>\n definePlugin({\n id: 'search',\n token: SearchToken,\n scope: 'document',\n optional: [StageToken],\n state: initialSearchModel,\n settings: { defaults: SEARCH_DEFAULTS, registered: config },\n create: createSearchController,\n });\n","/**\n * The search page's State table as code: what `useSearchState()` returns, and\n * the same fields in every other framework. The matches themselves are not\n * here: `useSearchHits()` reads them, so a component that only shows the\n * count doesn't re-render for every match that arrives.\n */\nimport { defineState, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport { SearchToken, type SearchHit, type SearchProgress, type SearchStatus } from './contract';\nimport { NO_PROGRESS } from './model';\n\n/** The query, where the search is, how many hits it found, the active hit, and why it failed. */\nexport interface SearchState {\n /** What is searched for, or `null` before a search. */\n readonly query: SearchQuery | null;\n /** Where the search is: `idle`, `searching`, `complete`, `cancelled` or `error`. */\n readonly status: SearchStatus;\n /** How many hits were found so far. */\n readonly hitCount: number;\n /** The active hit's index, or `-1` when no hit is active. */\n readonly activeHitIndex: number;\n /** The active hit, or `null`. */\n readonly activeHit: SearchHit | null;\n /** How many pages the search went through, of how many. */\n readonly progress: SearchProgress;\n /** Why the search failed, or `null`. */\n readonly error: PluginErrorInfo | null;\n}\n\nexport const searchState = defineState(SearchToken, {\n read: (search): SearchState => ({\n query: search.getQuery(),\n status: search.getStatus(),\n hitCount: search.getHitCount(),\n activeHitIndex: search.getActiveHitIndex(),\n activeHit: search.getActiveHit(),\n progress: search.getProgress(),\n error: search.getError(),\n }),\n empty: {\n query: null,\n status: 'idle',\n hitCount: 0,\n activeHitIndex: -1,\n activeHit: null,\n progress: NO_PROGRESS,\n error: null,\n },\n});\n"],"mappings":";;;;;;;;;;;AA0BA,MAAa,cAA8B,OAAO,OAAO;CAAE,eAAe;CAAG,WAAW;AAAE,CAAC;AAE3F,MAAa,4BAAyC;CACpD,OAAO;CACP,QAAQ;CACR,aAAa;CACb,MAAM,CA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UAAU;EACV,OAAO;CACT;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/model.ts","../src/controller.ts","../src/search.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The search session: the query, the hits found so far (also grouped by\n * page), the active hit, and progress. Every function below is a pure\n * transition; the controller applies them with `ctx.state.update`.\n */\nimport { pageRefsEqual, type PageRef, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport type { SearchHit, SearchProgress, SearchStatus } from './contract';\n\nexport interface SearchModel {\n /** The query being searched, as the engine matches it. Null when idle. */\n readonly query: SearchQuery | null;\n readonly status: SearchStatus;\n /** The run that owns the session, so a run that lost it (superseded, cleared) leaves it alone. */\n readonly operationId: string | null;\n readonly hits: readonly SearchHit[];\n /** Page object number → the hits on that page; a page's array is replaced only when it gains hits. */\n readonly hitsByPage: Readonly<Record<number, readonly SearchHit[]>>;\n /** Index into `hits`, -1 when no hit is active. */\n readonly activeHitIndex: number;\n readonly progress: SearchProgress;\n readonly error: PluginErrorInfo | null;\n}\n\n/** The progress of no search, one object for every session that hasn't searched a page yet. */\nexport const NO_PROGRESS: SearchProgress = Object.freeze({ pagesSearched: 0, pageCount: 0 });\n\nexport const initialSearchModel = (): SearchModel => ({\n query: null,\n status: 'idle',\n operationId: null,\n hits: [],\n hitsByPage: {},\n activeHitIndex: -1,\n progress: NO_PROGRESS,\n error: null,\n});\n\n/** A new scan starts: everything from the previous session is dropped. */\nexport const startSession = (\n _state: SearchModel,\n query: SearchQuery,\n operationId: string,\n): SearchModel => ({ ...initialSearchModel(), query, status: 'searching', operationId });\n\nconst sameProgress = (left: SearchProgress, right: SearchProgress): boolean =>\n left.pagesSearched === right.pagesSearched && left.pageCount === right.pageCount;\n\n/**\n * A slice of hits arrived. The first hit becomes active so \"1 of N\" reads\n * right; moving the camera is navigation's job, not the stream's. Progress\n * with the same counts keeps its object: readers, and `onProgressChanged`,\n * see a change only when the counts change.\n */\nexport function appendHits(\n state: SearchModel,\n hits: readonly SearchHit[],\n slice: SearchProgress,\n): SearchModel {\n const progress = sameProgress(state.progress, slice) ? state.progress : slice;\n if (hits.length === 0) return progress === state.progress ? state : { ...state, progress };\n const hitsByPage: Record<number, readonly SearchHit[]> = { ...state.hitsByPage };\n for (const hit of hits) {\n const pageObjectNumber = hit.page.objectNumber;\n hitsByPage[pageObjectNumber] = [...(hitsByPage[pageObjectNumber] ?? []), hit];\n }\n return {\n ...state,\n hits: [...state.hits, ...hits],\n hitsByPage,\n activeHitIndex: state.activeHitIndex === -1 ? 0 : state.activeHitIndex,\n progress,\n };\n}\n\nexport const completeSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'complete',\n});\n\nexport const cancelSession = (state: SearchModel): SearchModel => ({\n ...state,\n status: 'cancelled',\n});\n\nexport const failSession = (state: SearchModel, error: PluginErrorInfo): SearchModel => ({\n ...state,\n status: 'error',\n error,\n});\n\nexport const setActiveHit = (state: SearchModel, index: number): SearchModel =>\n state.activeHitIndex === index ? state : { ...state, activeHitIndex: index };\n\nexport const clearSession = (state: SearchModel): SearchModel =>\n state.status === 'idle' ? state : initialSearchModel();\n\n/**\n * Where `hit` is in `hits`: the same object, or else the hit that covers the\n * same characters of the same page, so a hit kept from before the search ran\n * again still finds its place. -1 when it isn't there.\n */\nexport function indexOfHit(hits: readonly SearchHit[], hit: SearchHit): number {\n const same = hits.indexOf(hit);\n if (same >= 0) return same;\n return hits.findIndex(\n (candidate) =>\n candidate.start === hit.start &&\n candidate.count === hit.count &&\n pageRefsEqual(candidate.page, hit.page),\n );\n}\n\n/**\n * The pages that have at least one hit, in document order: `pages` is the\n * document's page list, whose order moving a page changes (object numbers\n * don't follow it).\n */\nexport const pagesWithHits = (\n state: SearchModel,\n pages: readonly { readonly ref: PageRef }[],\n): readonly PageRef[] =>\n pages\n .filter((page) => (state.hitsByPage[page.ref.objectNumber]?.length ?? 0) > 0)\n .map((page) => page.ref);\n","import {\n PluginError,\n isPluginError,\n toPluginError,\n toPluginErrorInfo,\n type PluginContext,\n type LatestCancellation,\n type PageRef,\n} from '@embedpdf/core';\nimport { boundsOfRects } from '@embedpdf/core-geometry';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\nimport type { SearchQuery, SearchSlice } from '@embedpdf/engine-core/runtime';\nimport type {\n SearchActiveHitChangedEvent,\n SearchCancelledEvent,\n SearchCapability,\n SearchClearedEvent,\n SearchCompletedEvent,\n SearchFailedEvent,\n SearchHit,\n SearchOptions,\n SearchProgressChangedEvent,\n SearchResult,\n SearchRevealOptions,\n SearchSettings,\n SearchStartedEvent,\n} from './contract';\nimport {\n appendHits,\n cancelSession,\n clearSession,\n completeSession,\n failSession,\n indexOfHit,\n pagesWithHits,\n setActiveHit,\n startSession,\n type SearchModel,\n} from './model';\n\nconst EMPTY: readonly SearchHit[] = Object.freeze([]);\nconst EMPTY_PAGES: readonly PageRef[] = Object.freeze([]);\n\n/** Reruns after document mutations are coalesced: a burst of events triggers one rescan. */\nconst RERUN_DELAY_MS = 250;\n\n/** How a `collect()` consumer observes the loop: the session updates state, findAll accumulates. */\ninterface CollectSink {\n /** Before the first slice, and again on a stale-cursor restart: reset any accumulation. */\n onStart(): void;\n onSlice(hits: readonly SearchHit[], pagesSearched: number, pageCount: number): void;\n}\n\n/**\n * The search controller. `search` runs on a `latest` lane (a newer search\n * supersedes the older one, which can no longer publish); `findAll` runs on\n * its own signal and never touches the session. Both share `collect`, the\n * one cursor loop over the engine's budgeted slices.\n *\n * The scan's own events (started, completed, cancelled, failed) fire where\n * the scan reaches those points. The progress, active-hit and cleared events\n * are derived from state changes, so they always agree with the getters.\n *\n * The settings are read where they're used, never copied, so\n * `updateSettings({ reveal })` applies to the next move at once.\n */\nexport function createSearchController(ctx: PluginContext<SearchModel, SearchSettings>) {\n const settings = ctx.settings();\n const session = ctx.latest('session');\n const started = ctx.events.source<SearchStartedEvent>();\n const progressChanged = ctx.events.source<SearchProgressChangedEvent>();\n const completed = ctx.events.source<SearchCompletedEvent>();\n const cancelled = ctx.events.source<SearchCancelledEvent>();\n const failed = ctx.events.source<SearchFailedEvent>();\n const activeHitChanged = ctx.events.source<SearchActiveHitChangedEvent>();\n const cleared = ctx.events.source<SearchClearedEvent>();\n\n const state = () => ctx.state.get();\n\n ctx.state.onChange(({ previous, next }) => {\n // A slice moves it forward; a new search or clear() puts it back to none.\n if (previous.progress !== next.progress) {\n progressChanged.emit({ ...next.progress, hitCount: next.hits.length });\n }\n if (previous.activeHitIndex !== next.activeHitIndex) {\n activeHitChanged.emit({\n index: next.activeHitIndex,\n hit: next.hits[next.activeHitIndex] ?? null,\n });\n }\n if (previous.status !== 'idle' && next.status === 'idle') cleared.emit({});\n });\n\n // ── projection: engine slice → page-space hits ───────────────────────────\n\n function hitsFromSlice(slice: SearchSlice): SearchHit[] {\n const hits: SearchHit[] = [];\n for (const match of slice.matches) {\n // A page that vanished mid-search (deleted) drops its hits.\n const page = ctx.getPage(match.page);\n if (!page) continue;\n // Segments arrive in page space, ready to draw.\n const segments = match.segments;\n hits.push({\n page: match.page,\n pageIndex: page.index,\n start: match.start,\n count: match.count,\n segments,\n ...(segments.length\n ? { bounds: boundsOfRects(segments.map((segment) => segment.rect)) ?? undefined }\n : {}),\n ...(match.snippet ? { snippet: match.snippet } : {}),\n });\n }\n return hits;\n }\n\n // ── the mechanism ────────────────────────────────────────────────────────\n\n /**\n * One cursor loop over budgeted slices: snippets when the session may copy\n * text (unless pinned), falling back to none if the engine still denies them,\n * restart-once on a stale cursor, projection per slice. Returns true on\n * exhaustion, false when the signal aborted; throws on a real error (already\n * a PluginError: ctx.doc is guarded).\n */\n async function collect(\n query: SearchQuery,\n options: { from?: PageRef; snippets?: boolean; signal?: AbortSignal },\n sink: CollectSink,\n ): Promise<boolean> {\n const { signal } = options;\n sink.onStart();\n\n // A snippet reproduces document text, so ask for one only where copying is allowed:\n // the engine would refuse it, and the request would cost a round trip for nothing.\n let snippets = options.snippets ?? ctx.allows('doc.text.copy');\n const snippetsPinned = options.snippets !== undefined;\n let cursor: string | undefined;\n let restarted = false;\n for (;;) {\n if (signal?.aborted) return false;\n let slice: SearchSlice;\n const request = {\n ...query,\n snippets,\n ...(cursor !== undefined\n ? { cursor }\n : options.from !== undefined\n ? { from: options.from }\n : {}),\n };\n try {\n // A scan nobody waits on, so it runs once the views' work is done.\n // Cancelling stops the engine working on the slice, not only the wait for it.\n slice = await ctx.cancellable(\n signal,\n ctx.doc.with({ priority: 'low' }).search.query(request),\n );\n } catch (error) {\n if (signal?.aborted) return false;\n // Snippets denied although the session looked allowed to copy (its permissions\n // changed on the server)? Degrade to matches without them.\n if (\n !snippetsPinned &&\n snippets &&\n cursor === undefined &&\n isPluginError(error, 'permission-denied')\n ) {\n snippets = false;\n continue;\n }\n // A stale cursor rejects with InvalidArg: the document changed under the\n // loop. Position is lost, the query is not: restart once from scratch.\n if (cursor !== undefined && !restarted && isPluginError(error, 'invalid-input')) {\n restarted = true;\n cursor = undefined;\n sink.onStart();\n continue;\n }\n throw error;\n }\n if (signal?.aborted) return false;\n sink.onSlice(hitsFromSlice(slice), slice.pagesSearched, slice.pageCount);\n if (slice.nextCursor === null) return true;\n cursor = slice.nextCursor;\n }\n }\n\n // ── the session ──────────────────────────────────────────────────────────\n\n const viewportFirstPage = (): PageRef | undefined => {\n const stage = ctx.tryGet(StageToken);\n return stage?.getCurrentPage() ?? undefined;\n };\n\n // Async so a refusal or a page that isn't in the document rejects, like any other failure,\n // before the session is touched. The run still starts synchronously, so a newer search\n // supersedes an older one in the order they were called.\n async function search(query: SearchQuery, options: SearchOptions = {}): Promise<SearchResult> {\n if (query.text.length === 0) {\n clear();\n return { status: 'complete', hitCount: 0 };\n }\n ctx.assertAllowed('doc.text.search', 'search');\n const from = options.from === undefined ? viewportFirstPage() : ctx.pageOf(options.from).ref;\n let operationId = '';\n return session\n .run(async (run) => {\n operationId = run.id;\n const complete = await collect(\n query,\n { from, signal: run.signal },\n {\n onStart: () =>\n run.commit(() => {\n ctx.state.update(startSession, query, run.id);\n started.emit({ query });\n }),\n onSlice: (hits, pagesSearched, pageCount) =>\n run.commit(() => ctx.state.update(appendHits, hits, { pagesSearched, pageCount })),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'search aborted');\n run.commit(() => {\n ctx.state.update(completeSession);\n completed.emit({ hitCount: state().hits.length });\n });\n return { status: 'complete', hitCount: state().hits.length } as SearchResult;\n }, options)\n .catch((error: unknown): SearchResult => {\n if (isPluginError(error, 'instance-closed')) return { status: 'cancelled', hitCount: 0 };\n if (isPluginError(error, 'operation-cancelled')) {\n const why = (error.details as LatestCancellation | undefined)?.reason ?? 'cancelled';\n const reason: SearchCancelledEvent['reason'] =\n why === 'superseded' ? 'superseded' : why === 'cleared' ? 'cleared' : 'cancelled';\n // A superseded or cleared run has already lost the session; a cancelled one keeps its hits.\n if (reason === 'cancelled' && state().operationId === operationId) {\n ctx.state.update(cancelSession);\n }\n cancelled.emit({ reason });\n return {\n status: reason === 'superseded' ? 'superseded' : 'cancelled',\n hitCount: state().hits.length,\n };\n }\n const info = toPluginErrorInfo(toPluginError('search', error));\n if (state().operationId === operationId) ctx.state.update(failSession, info);\n failed.emit({ error: info });\n throw error;\n });\n }\n\n function clear(): void {\n session.cancel('cleared');\n ctx.state.update(clearSession);\n }\n\n function goToHit(target: SearchHit | number, options?: SearchRevealOptions): SearchHit | null {\n const { hits } = state();\n if (hits.length === 0) return null;\n const index =\n typeof target === 'number'\n ? ((target % hits.length) + hits.length) % hits.length\n : indexOfHit(hits, target);\n if (index < 0) return null;\n ctx.state.update(setActiveHit, index);\n reveal(hits[index], options);\n return hits[index];\n }\n\n function reveal(hit: SearchHit, options?: SearchRevealOptions): void {\n // Positioned reveal: the hit (not just its page) arrives at the alignment —\n // the call's options over the `reveal` setting. Zoom never changes.\n const arrival = { ...settings.get().reveal, ...options };\n ctx.tryGet(StageToken)?.reveal(hit.page, {\n rect: hit.bounds,\n align: arrival.align,\n behavior: arrival.behavior,\n });\n }\n\n /**\n * One page's hits, by the page's ref or index. A page that isn't in the\n * document has none: a layer may read while its page is being deleted.\n */\n const hitsOn = (page: PageRef | number): readonly SearchHit[] => {\n const found = ctx.getPage(page);\n return found ? (state().hitsByPage[found.ref.objectNumber] ?? EMPTY) : EMPTY;\n };\n\n const api: SearchCapability = {\n ...settings.api,\n\n // The twin of search() and findAll(), which refuse without doc.text.search.\n // Snippets need doc.text.copy too, but a search without it still runs: its\n // matches come without snippets (see collect).\n canSearch: (options) =>\n ctx.allows('doc.text.search') && (!options?.snippets || ctx.allows('doc.text.copy')),\n\n search,\n refresh: async (options) => {\n const { query, status } = state();\n if (!query || status === 'idle') return;\n await search(query, options);\n },\n cancel: () => session.cancel('cancelled'),\n clear,\n\n nextHit: (options) => goToHit(state().activeHitIndex + 1, options),\n previousHit: (options) => goToHit(state().activeHitIndex - 1, options),\n goToHit,\n revealActiveHit: (options) => {\n const hit = api.getActiveHit();\n if (hit) reveal(hit, options);\n },\n\n getQuery: () => state().query,\n getStatus: () => state().status,\n listHits: (filter) => (filter?.page === undefined ? state().hits : hitsOn(filter.page)),\n getHitCount: (page) => (page === undefined ? state().hits : hitsOn(page)).length,\n listPagesWithHits: () =>\n state().hits.length ? pagesWithHits(state(), ctx.document()?.pages ?? []) : EMPTY_PAGES,\n getActiveHitIndex: () => state().activeHitIndex,\n getActiveHit: () => state().hits[state().activeHitIndex] ?? null,\n getProgress: () => state().progress,\n getError: () => state().error,\n\n // ── the service ──────────────────────────────────────────────────────\n findAll: async (query, options = {}) => {\n ctx.assertAllowed('doc.text.search', 'findAll');\n // Snippets pinned on are a requirement: refuse here rather than ask the engine.\n if (options.snippets) ctx.assertAllowed('doc.text.copy', 'findAll');\n const all: SearchHit[] = [];\n const complete = await collect(\n query,\n {\n ...(options.snippets !== undefined ? { snippets: options.snippets } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n },\n {\n onStart: () => {\n all.length = 0;\n },\n onSlice: (hits) => all.push(...hits),\n },\n );\n if (!complete) throw new PluginError('operation-cancelled', 'search', 'findAll aborted');\n return all;\n },\n\n onStarted: started.on,\n onProgressChanged: progressChanged.on,\n onCompleted: completed.on,\n onCancelled: cancelled.on,\n onFailed: failed.on,\n onActiveHitChanged: activeHitChanged.on,\n onCleared: cleared.on,\n };\n\n return {\n api,\n connect() {\n // Every confirmed mutation (own or remote) invalidates cursors and can change\n // what is findable, so the running or finished session re-runs its query.\n let cancelRerun: (() => void) | null = null;\n ctx.listen(ctx.doc.events, () => {\n if (state().status === 'idle') return;\n cancelRerun?.();\n cancelRerun = ctx.clock.after(RERUN_DELAY_MS, () => {\n cancelRerun = null;\n void api.refresh().catch(() => {\n /* surfaced through getStatus() and onFailed */\n });\n });\n });\n },\n };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { SEARCH_DEFAULTS, SearchToken, type SearchConfig } from './contract';\nimport { createSearchController } from './controller';\nimport { initialSearchModel } from './model';\n\n/**\n * Document text search over the engine's budgeted, resumable slices.\n * Document-scoped; no pointer handling. The stage is optional: with one,\n * scans start at the current page and navigation reveals hits. `config` is\n * the settings the app registers, over {@link SEARCH_DEFAULTS}.\n */\nexport const searchPlugin = (config?: SearchConfig) =>\n definePlugin({\n id: 'search',\n token: SearchToken,\n scope: 'document',\n optional: [StageToken],\n state: initialSearchModel,\n settings: { defaults: SEARCH_DEFAULTS, registered: config },\n create: createSearchController,\n });\n","/**\n * The search page's State table as code: what `useSearchState()` returns, and\n * the same fields in every other framework. The matches themselves are not\n * here: `useSearchHits()` reads them, so a component that only shows the\n * count doesn't re-render for every match that arrives.\n */\nimport { defineState, type PluginErrorInfo } from '@embedpdf/core';\nimport type { SearchQuery } from '@embedpdf/engine-core/runtime';\n\nimport { SearchToken, type SearchHit, type SearchProgress, type SearchStatus } from './contract';\nimport { NO_PROGRESS } from './model';\n\n/** The query, where the search is, how many hits it found, the active hit, and why it failed. */\nexport interface SearchState {\n /** What is searched for, or `null` before a search. */\n readonly query: SearchQuery | null;\n /** Where the search is: `idle`, `searching`, `complete`, `cancelled` or `error`. */\n readonly status: SearchStatus;\n /** How many hits were found so far. */\n readonly hitCount: number;\n /** The active hit's index, or `-1` when no hit is active. */\n readonly activeHitIndex: number;\n /** The active hit, or `null`. */\n readonly activeHit: SearchHit | null;\n /** How many pages the search went through, of how many. */\n readonly progress: SearchProgress;\n /** Why the search failed, or `null`. */\n readonly error: PluginErrorInfo | null;\n}\n\nexport const searchState = defineState(SearchToken, {\n read: (search): SearchState => ({\n query: search.getQuery(),\n status: search.getStatus(),\n hitCount: search.getHitCount(),\n activeHitIndex: search.getActiveHitIndex(),\n activeHit: search.getActiveHit(),\n progress: search.getProgress(),\n error: search.getError(),\n }),\n empty: {\n query: null,\n status: 'idle',\n hitCount: 0,\n activeHitIndex: -1,\n activeHit: null,\n progress: NO_PROGRESS,\n error: null,\n },\n});\n"],"mappings":";;;;;;;;;;;AA0BA,MAAa,cAA8B,OAAO,OAAO;CAAE,eAAe;CAAG,WAAW;AAAE,CAAC;AAE3F,MAAa,4BAAyC;CACpD,OAAO;CACP,QAAQ;CACR,aAAa;CACb,MAAM,CAAC;CACP,YAAY,CAAC;CACb,gBAAgB;CAChB,UAAU;CACV,OAAO;AACT;;AAGA,MAAa,gBACX,QACA,OACA,iBACiB;CAAE,GAAG,mBAAmB;CAAG;CAAO,QAAQ;CAAa;AAAY;AAEtF,MAAM,gBAAgB,MAAsB,UAC1C,KAAK,kBAAkB,MAAM,iBAAiB,KAAK,cAAc,MAAM;;;;;;;AAQzE,SAAgB,WACd,OACA,MACA,OACa;CACb,MAAM,WAAW,aAAa,MAAM,UAAU,KAAK,IAAI,MAAM,WAAW;CACxE,IAAI,KAAK,WAAW,GAAG,OAAO,aAAa,MAAM,WAAW,QAAQ;EAAE,GAAG;EAAO;CAAS;CACzF,MAAM,aAAmD,EAAE,GAAG,MAAM,WAAW;CAC/E,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,mBA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,IAAI,cAAmC;GACvC,IAAI,OAAO,IAAI,IAAI,cAAc;IAC/B,IAAI,MAAM,CAAC,CAAC,WAAW,QAAQ;IAC/B,cAAc;IACd,cAAc,IAAI,MAAM,MAAM,sBAAsB;KAClD,cAAc;KACd,IAAS,QAAQ,CAAC,CAAC,YAAY,CAE/B,CAAC;IACH,CAAC;GACH,CAAC;EACH;CACF;AACF;;;;;;;;;AC9WA,MAAa,gBAAgB,WAC3B,aAAa;CACX,IAAI;CACJ,OAAO;CACP,OAAO;CACP,UAAU,CAAC,UAAU;CACrB,OAAO;CACP,UAAU;EAAE,UAAU;EAAiB,YAAY;CAAO;CAC1D,QAAQ;AACV,CAAC;;;;;;;;;ACQH,MAAa,cAAc,YAAY,aAAa;CAClD,OAAO,YAAyB;EAC9B,OAAO,OAAO,SAAS;EACvB,QAAQ,OAAO,UAAU;EACzB,UAAU,OAAO,YAAY;EAC7B,gBAAgB,OAAO,kBAAkB;EACzC,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,OAAO,OAAO,SAAS;CACzB;CACA,OAAO;EACL,OAAO;EACP,QAAQ;EACR,UAAU;EACV,gBAAgB;EAChB,WAAW;EACX,UAAU;EACV,OAAO;CACT;AACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@embedpdf/plugin-search",
|
|
3
|
-
"version": "3.0.0-next.
|
|
3
|
+
"version": "3.0.0-next.23",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Document text search: drives the engine's budgeted search slices, converts match rects to content space, and integrates with the Stage for viewport-first scanning and reveal-on-navigate.",
|
|
6
6
|
"type": "module",
|
|
@@ -22,10 +22,10 @@
|
|
|
22
22
|
"dist"
|
|
23
23
|
],
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@embedpdf/core": "3.0.0-next.
|
|
26
|
-
"@embedpdf/
|
|
27
|
-
"@embedpdf/
|
|
28
|
-
"@embedpdf/engine-core": "3.0.0-next.
|
|
25
|
+
"@embedpdf/core": "3.0.0-next.23",
|
|
26
|
+
"@embedpdf/plugin-stage": "3.0.0-next.23",
|
|
27
|
+
"@embedpdf/core-geometry": "3.0.0-next.23",
|
|
28
|
+
"@embedpdf/engine-core": "3.0.0-next.23"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"typescript": "^5.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contract-6pr6LBhA.cjs","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token — created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { SearchCapability } from './contract';\n\nexport const SearchToken = createCapabilityToken<SearchCapability>('search', {\n hint: \"add searchPlugin() from '@embedpdf/plugin-search' to your plugins list\",\n // Without a document, an adapter's stand-in rejects these with `not-ready`, as the\n // capability would; the type asks for every member that returns a promise.\n promises: {\n search: true,\n refresh: true,\n findAll: true,\n },\n});\n","import {\n type DeepPartial,\n type EventHook,\n type OperationOptions,\n type PageRef,\n type PluginErrorInfo,\n type SettingsApi,\n} from '@embedpdf/core';\nimport type { Rect } from '@embedpdf/core-geometry';\nimport type { RevealAnchor, ScrollBehaviorKind } from '@embedpdf/plugin-stage/contract';\nimport type { PdfTextSegment, SearchQuery, SearchSnippet } from '@embedpdf/engine-core/runtime';\n\nexport { validateSearchQuery, validateSearchRegex } from '@embedpdf/engine-core/runtime';\nexport type {\n SearchQuery,\n SearchQueryIssue,\n SearchQueryValidation,\n SearchRegexValidation,\n SearchSnippet,\n} from '@embedpdf/engine-core/runtime';\n\n/**\n * One merged visual line of a match in page space, as the engine's layout\n * gives it (selection's `SelectionSegment` is the same line). `quad` is the\n * geometric authority, its corners named in the line's own frame; `rect` its\n * bounds; `advance` the reading direction along the baseline.\n */\nexport type TextSegment = PdfTextSegment;\n\n/**\n * One match. `page` is the durable page identity, `pageIndex` its display\n * index at the time of the match. `start`/`count` are a range of the page's\n * characters, so a hit goes straight to `selection.select(hit)` or a markup\n * annotation without re-searching.\n */\nexport interface SearchHit {\n readonly page: PageRef;\n readonly pageIndex: number;\n readonly start: number;\n readonly count: number;\n /** Visual-line segments in page space — the drawing input. */\n readonly segments: readonly TextSegment[];\n /** Union of the segments — the reveal target. Absent for matches with no drawable geometry. */\n readonly bounds?: Rect;\n readonly snippet?: SearchSnippet;\n}\n\n/**\n * `searching`: the scan is walking pages, hits are usable as they stream in.\n * `cancelled`: the scan was stopped by `cancel()`; the hits found so far stay.\n */\nexport type SearchStatus = 'idle' | 'searching' | 'complete' | 'cancelled' | 'error';\n\nexport interface SearchProgress {\n readonly pagesSearched: number;\n readonly pageCount: number;\n}\n\n// ── settings ──────────────────────────────────────────────────────────────\n\n/** How a match arrives in view when you move to it: forwarded to the Stage's positioned reveal. */\nexport interface SearchReveal {\n /** Where the match lands in the view: `{ y: 0.35 }` puts it 35% of the way down, like a browser's find bar. */\n readonly anchor: RevealAnchor;\n /** Glide there (`'smooth'`) or jump (`'instant'`). */\n readonly behavior: ScrollBehaviorKind;\n}\n\n/** The `reveal` setting for one call: what the call leaves out comes from the setting. */\nexport type SearchRevealOptions = Partial<SearchReveal>;\n\n/** How the highlights mix with the page: a CSS `mix-blend-mode` keyword. */\nexport type SearchBlendMode =\n | 'normal'\n | 'multiply'\n | 'screen'\n | 'overlay'\n | 'darken'\n | 'lighten'\n | 'color-dodge'\n | 'color-burn'\n | 'hard-light'\n | 'soft-light'\n | 'difference'\n | 'exclusion'\n | 'hue'\n | 'saturation'\n | 'color'\n | 'luminosity';\n\n/**\n * The search plugin's settings. `searchPlugin(config)` registers them over\n * {@link SEARCH_DEFAULTS}, and `updateSettings()` changes them for every\n * document while the app runs. The highlight's three can also come from CSS\n * (`--epdf-search-highlight`, `--epdf-search-highlight-active`,\n * `--epdf-search-blend-mode`), which wins over the setting.\n */\nexport interface SearchSettings {\n /** Where a match lands when `nextHit()`, `previousHit()` or `goToHit()` moves to it. */\n readonly reveal: SearchReveal;\n readonly highlight: {\n /** The highlight of every match. */\n readonly color: string;\n /** The highlight of the active match. */\n readonly activeColor: string;\n /**\n * `'multiply'` is a real highlighter: the text stays crisp through the\n * color and only the paper tints. On dark or scanned pages, where a\n * multiplied highlight disappears, use `'normal'` with translucent colors.\n */\n readonly blendMode: SearchBlendMode;\n };\n}\n\n/** What the search settings are when the app registers none. */\nexport const SEARCH_DEFAULTS: SearchSettings = {\n reveal: { anchor: { y: 0.35 }, behavior: 'smooth' },\n highlight: { color: '#ffd500', activeColor: '#ff9632', blendMode: 'multiply' },\n};\n\n/** What `searchPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type SearchConfig = DeepPartial<SearchSettings>;\n\n// ── verbs ─────────────────────────────────────────────────────────────────\n\nexport interface SearchOptions extends OperationOptions {\n /**\n * Where to start: a page's ref or its index. Defaults to the Stage's\n * current page (viewport-first) when a Stage is installed.\n */\n readonly from?: PageRef | number;\n}\n\nexport interface SearchFindAllOptions extends OperationOptions {\n /**\n * Pin whether hits carry snippets. By default they do, falling back to none\n * when snippets are denied; pass `false` when only geometry is needed.\n */\n readonly snippets?: boolean;\n}\n\n/** What a `search()` resolved to: it finished, a newer search replaced it, or it was cancelled. */\nexport interface SearchResult {\n readonly status: 'complete' | 'superseded' | 'cancelled';\n readonly hitCount: number;\n}\n\nexport interface SearchHitFilter {\n /** One page's hits: its ref or its index. */\n readonly page?: PageRef | number;\n}\n\n// ── events ────────────────────────────────────────────────────────────────\n\nexport interface SearchStartedEvent {\n readonly query: SearchQuery;\n}\n/**\n * The search's progress changed: how many pages were searched, of how many,\n * and the matches found so far. The same values `getProgress()` and\n * `getHitCount()` return from then on.\n */\nexport interface SearchProgressChangedEvent extends SearchProgress {\n readonly hitCount: number;\n}\nexport interface SearchCompletedEvent {\n readonly hitCount: number;\n}\nexport interface SearchCancelledEvent {\n readonly reason: 'superseded' | 'cancelled' | 'cleared';\n}\nexport interface SearchFailedEvent {\n readonly error: PluginErrorInfo;\n}\nexport interface SearchActiveHitChangedEvent {\n readonly index: number;\n readonly hit: SearchHit | null;\n}\nexport type SearchClearedEvent = Record<string, never>;\n\n/**\n * The search plugin is a find service (`findAll`) plus one user-visible\n * search session per document (`search` and everything below it). The\n * sidebar, the highlight layer and next/previous render the session. Its\n * settings (`getSettings`, `updateSettings`, `resetSettings`,\n * `onSettingsChanged`) belong to the plugin, not to a document: a change\n * reaches every open document.\n */\nexport interface SearchCapability extends SettingsApi<SearchSettings> {\n /**\n * Would a search be served now: `doc.text.search`. With `snippets: true`\n * it also needs `doc.text.copy`, because a snippet reproduces document text.\n */\n canSearch(options?: { readonly snippets?: boolean }): boolean;\n\n // ── the session ─────────────────────────────────────────────────────────\n /**\n * Start a new search. A newer search supersedes and aborts a running one.\n * Hits stream into the session as they are found; the first hit becomes\n * active but the camera does not move until you navigate. Resolves when\n * the scan completes, is superseded, or is cancelled (also through\n * `options.signal`); rejects only on a real failure, `permission-denied`\n * without `doc.text.search`, or `not-found` for a `from` page that isn't in\n * the document. A refusal only rejects: the session stays as it was and no\n * event fires. An empty `query.text` is identical to `clear()`. Fires\n * `onStarted`, `onProgressChanged` as each slice of pages is searched, then\n * `onCompleted`, `onCancelled` or `onFailed`.\n */\n search(query: SearchQuery, options?: SearchOptions): Promise<SearchResult>;\n /**\n * Re-run the current query from scratch (the plugin does this itself after\n * document mutations). Resolves and rejects as `search()` does.\n */\n refresh(options?: OperationOptions): Promise<SearchResult>;\n /** Stop the scan and keep the hits found so far. */\n cancel(): void;\n /** Stop the scan and drop the session. */\n clear(): void;\n\n /** Step to the next / previous hit, wrapping, and reveal it. */\n nextHit(options?: SearchRevealOptions): SearchHit | null;\n previousHit(options?: SearchRevealOptions): SearchHit | null;\n /**\n * Make a hit the active one and reveal it: the hit itself, such as the one\n * `<SearchLayer onHitClick>` hands you, or its index (which wraps). Returns\n * the hit, or null when there are no hits or the given one isn't among them.\n */\n goToHit(hit: SearchHit | number, options?: SearchRevealOptions): SearchHit | null;\n /** Bring the active hit back into view without changing it. */\n revealActiveHit(options?: SearchRevealOptions): void;\n\n getQuery(): SearchQuery | null;\n getStatus(): SearchStatus;\n /**\n * Hits found so far, or those on one page. Reference-stable (per page too)\n * until new hits land there. Empty for a page that isn't in the document,\n * so a layer that reads while its page is deleted still renders.\n */\n listHits(filter?: SearchHitFilter): readonly SearchHit[];\n /** How many hits were found so far, or on one page; 0 for a page that isn't in the document. */\n getHitCount(page?: PageRef | number): number;\n listPagesWithHits(): readonly PageRef[];\n /** `-1` when no hit is active. */\n getActiveHitIndex(): number;\n getActiveHit(): SearchHit | null;\n getProgress(): SearchProgress;\n getError(): PluginErrorInfo | null;\n\n // ── the service ─────────────────────────────────────────────────────────\n /**\n * Run a query to completion and return every hit, touching no session\n * state. Scans in natural page order; concurrent calls are independent.\n * Rejects `operation-cancelled` when `options.signal` aborts, and\n * `permission-denied` without `doc.text.search`.\n */\n findAll(query: SearchQuery, options?: SearchFindAllOptions): Promise<readonly SearchHit[]>;\n\n readonly onStarted: EventHook<SearchStartedEvent>;\n /**\n * `getProgress()` changed: once per slice of pages a search gets through,\n * and back to none when a new search starts or the session is cleared.\n */\n readonly onProgressChanged: EventHook<SearchProgressChangedEvent>;\n readonly onCompleted: EventHook<SearchCompletedEvent>;\n readonly onCancelled: EventHook<SearchCancelledEvent>;\n readonly onFailed: EventHook<SearchFailedEvent>;\n readonly onActiveHitChanged: EventHook<SearchActiveHitChangedEvent>;\n readonly onCleared: EventHook<SearchClearedEvent>;\n}\n\nexport { SearchToken } from './token';\n"],"mappings":";;;;;AAMA,MAAa,eAAA,GAAA,eAAA,sBAAA,CAAsD,UAAU;CAC3E,MAAM;CAGN,UAAU;EACR,QAAQ;EACR,SAAS;EACT,SAAS;CACX;AACF,CAAC;;;;ACoGD,MAAa,kBAAkC;CAC7C,QAAQ;EAAE,QAAQ,EAAE,GAAG,IAAK;EAAG,UAAU;CAAS;CAClD,WAAW;EAAE,OAAO;EAAW,aAAa;EAAW,WAAW;CAAW;AAC/E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contract-uWSW5IYM.js","names":[],"sources":["../src/token.ts","../src/contract.ts"],"sourcesContent":["/** The package token — created once here; `contract.ts` re-exports it and\n * `host-contract.ts` widens it. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { SearchCapability } from './contract';\n\nexport const SearchToken = createCapabilityToken<SearchCapability>('search', {\n hint: \"add searchPlugin() from '@embedpdf/plugin-search' to your plugins list\",\n // Without a document, an adapter's stand-in rejects these with `not-ready`, as the\n // capability would; the type asks for every member that returns a promise.\n promises: {\n search: true,\n refresh: true,\n findAll: true,\n },\n});\n","import {\n type DeepPartial,\n type EventHook,\n type OperationOptions,\n type PageRef,\n type PluginErrorInfo,\n type SettingsApi,\n} from '@embedpdf/core';\nimport type { Rect } from '@embedpdf/core-geometry';\nimport type { RevealAnchor, ScrollBehaviorKind } from '@embedpdf/plugin-stage/contract';\nimport type { PdfTextSegment, SearchQuery, SearchSnippet } from '@embedpdf/engine-core/runtime';\n\nexport { validateSearchQuery, validateSearchRegex } from '@embedpdf/engine-core/runtime';\nexport type {\n SearchQuery,\n SearchQueryIssue,\n SearchQueryValidation,\n SearchRegexValidation,\n SearchSnippet,\n} from '@embedpdf/engine-core/runtime';\n\n/**\n * One merged visual line of a match in page space, as the engine's layout\n * gives it (selection's `SelectionSegment` is the same line). `quad` is the\n * geometric authority, its corners named in the line's own frame; `rect` its\n * bounds; `advance` the reading direction along the baseline.\n */\nexport type TextSegment = PdfTextSegment;\n\n/**\n * One match. `page` is the durable page identity, `pageIndex` its display\n * index at the time of the match. `start`/`count` are a range of the page's\n * characters, so a hit goes straight to `selection.select(hit)` or a markup\n * annotation without re-searching.\n */\nexport interface SearchHit {\n readonly page: PageRef;\n readonly pageIndex: number;\n readonly start: number;\n readonly count: number;\n /** Visual-line segments in page space — the drawing input. */\n readonly segments: readonly TextSegment[];\n /** Union of the segments — the reveal target. Absent for matches with no drawable geometry. */\n readonly bounds?: Rect;\n readonly snippet?: SearchSnippet;\n}\n\n/**\n * `searching`: the scan is walking pages, hits are usable as they stream in.\n * `cancelled`: the scan was stopped by `cancel()`; the hits found so far stay.\n */\nexport type SearchStatus = 'idle' | 'searching' | 'complete' | 'cancelled' | 'error';\n\nexport interface SearchProgress {\n readonly pagesSearched: number;\n readonly pageCount: number;\n}\n\n// ── settings ──────────────────────────────────────────────────────────────\n\n/** How a match arrives in view when you move to it: forwarded to the Stage's positioned reveal. */\nexport interface SearchReveal {\n /** Where the match lands in the view: `{ y: 0.35 }` puts it 35% of the way down, like a browser's find bar. */\n readonly anchor: RevealAnchor;\n /** Glide there (`'smooth'`) or jump (`'instant'`). */\n readonly behavior: ScrollBehaviorKind;\n}\n\n/** The `reveal` setting for one call: what the call leaves out comes from the setting. */\nexport type SearchRevealOptions = Partial<SearchReveal>;\n\n/** How the highlights mix with the page: a CSS `mix-blend-mode` keyword. */\nexport type SearchBlendMode =\n | 'normal'\n | 'multiply'\n | 'screen'\n | 'overlay'\n | 'darken'\n | 'lighten'\n | 'color-dodge'\n | 'color-burn'\n | 'hard-light'\n | 'soft-light'\n | 'difference'\n | 'exclusion'\n | 'hue'\n | 'saturation'\n | 'color'\n | 'luminosity';\n\n/**\n * The search plugin's settings. `searchPlugin(config)` registers them over\n * {@link SEARCH_DEFAULTS}, and `updateSettings()` changes them for every\n * document while the app runs. The highlight's three can also come from CSS\n * (`--epdf-search-highlight`, `--epdf-search-highlight-active`,\n * `--epdf-search-blend-mode`), which wins over the setting.\n */\nexport interface SearchSettings {\n /** Where a match lands when `nextHit()`, `previousHit()` or `goToHit()` moves to it. */\n readonly reveal: SearchReveal;\n readonly highlight: {\n /** The highlight of every match. */\n readonly color: string;\n /** The highlight of the active match. */\n readonly activeColor: string;\n /**\n * `'multiply'` is a real highlighter: the text stays crisp through the\n * color and only the paper tints. On dark or scanned pages, where a\n * multiplied highlight disappears, use `'normal'` with translucent colors.\n */\n readonly blendMode: SearchBlendMode;\n };\n}\n\n/** What the search settings are when the app registers none. */\nexport const SEARCH_DEFAULTS: SearchSettings = {\n reveal: { anchor: { y: 0.35 }, behavior: 'smooth' },\n highlight: { color: '#ffd500', activeColor: '#ff9632', blendMode: 'multiply' },\n};\n\n/** What `searchPlugin(config)` takes: any of the settings, merged over the defaults. */\nexport type SearchConfig = DeepPartial<SearchSettings>;\n\n// ── verbs ─────────────────────────────────────────────────────────────────\n\nexport interface SearchOptions extends OperationOptions {\n /**\n * Where to start: a page's ref or its index. Defaults to the Stage's\n * current page (viewport-first) when a Stage is installed.\n */\n readonly from?: PageRef | number;\n}\n\nexport interface SearchFindAllOptions extends OperationOptions {\n /**\n * Pin whether hits carry snippets. By default they do, falling back to none\n * when snippets are denied; pass `false` when only geometry is needed.\n */\n readonly snippets?: boolean;\n}\n\n/** What a `search()` resolved to: it finished, a newer search replaced it, or it was cancelled. */\nexport interface SearchResult {\n readonly status: 'complete' | 'superseded' | 'cancelled';\n readonly hitCount: number;\n}\n\nexport interface SearchHitFilter {\n /** One page's hits: its ref or its index. */\n readonly page?: PageRef | number;\n}\n\n// ── events ────────────────────────────────────────────────────────────────\n\nexport interface SearchStartedEvent {\n readonly query: SearchQuery;\n}\n/**\n * The search's progress changed: how many pages were searched, of how many,\n * and the matches found so far. The same values `getProgress()` and\n * `getHitCount()` return from then on.\n */\nexport interface SearchProgressChangedEvent extends SearchProgress {\n readonly hitCount: number;\n}\nexport interface SearchCompletedEvent {\n readonly hitCount: number;\n}\nexport interface SearchCancelledEvent {\n readonly reason: 'superseded' | 'cancelled' | 'cleared';\n}\nexport interface SearchFailedEvent {\n readonly error: PluginErrorInfo;\n}\nexport interface SearchActiveHitChangedEvent {\n readonly index: number;\n readonly hit: SearchHit | null;\n}\nexport type SearchClearedEvent = Record<string, never>;\n\n/**\n * The search plugin is a find service (`findAll`) plus one user-visible\n * search session per document (`search` and everything below it). The\n * sidebar, the highlight layer and next/previous render the session. Its\n * settings (`getSettings`, `updateSettings`, `resetSettings`,\n * `onSettingsChanged`) belong to the plugin, not to a document: a change\n * reaches every open document.\n */\nexport interface SearchCapability extends SettingsApi<SearchSettings> {\n /**\n * Would a search be served now: `doc.text.search`. With `snippets: true`\n * it also needs `doc.text.copy`, because a snippet reproduces document text.\n */\n canSearch(options?: { readonly snippets?: boolean }): boolean;\n\n // ── the session ─────────────────────────────────────────────────────────\n /**\n * Start a new search. A newer search supersedes and aborts a running one.\n * Hits stream into the session as they are found; the first hit becomes\n * active but the camera does not move until you navigate. Resolves when\n * the scan completes, is superseded, or is cancelled (also through\n * `options.signal`); rejects only on a real failure, `permission-denied`\n * without `doc.text.search`, or `not-found` for a `from` page that isn't in\n * the document. A refusal only rejects: the session stays as it was and no\n * event fires. An empty `query.text` is identical to `clear()`. Fires\n * `onStarted`, `onProgressChanged` as each slice of pages is searched, then\n * `onCompleted`, `onCancelled` or `onFailed`.\n */\n search(query: SearchQuery, options?: SearchOptions): Promise<SearchResult>;\n /**\n * Re-run the current query from scratch (the plugin does this itself after\n * document mutations). Resolves and rejects as `search()` does.\n */\n refresh(options?: OperationOptions): Promise<SearchResult>;\n /** Stop the scan and keep the hits found so far. */\n cancel(): void;\n /** Stop the scan and drop the session. */\n clear(): void;\n\n /** Step to the next / previous hit, wrapping, and reveal it. */\n nextHit(options?: SearchRevealOptions): SearchHit | null;\n previousHit(options?: SearchRevealOptions): SearchHit | null;\n /**\n * Make a hit the active one and reveal it: the hit itself, such as the one\n * `<SearchLayer onHitClick>` hands you, or its index (which wraps). Returns\n * the hit, or null when there are no hits or the given one isn't among them.\n */\n goToHit(hit: SearchHit | number, options?: SearchRevealOptions): SearchHit | null;\n /** Bring the active hit back into view without changing it. */\n revealActiveHit(options?: SearchRevealOptions): void;\n\n getQuery(): SearchQuery | null;\n getStatus(): SearchStatus;\n /**\n * Hits found so far, or those on one page. Reference-stable (per page too)\n * until new hits land there. Empty for a page that isn't in the document,\n * so a layer that reads while its page is deleted still renders.\n */\n listHits(filter?: SearchHitFilter): readonly SearchHit[];\n /** How many hits were found so far, or on one page; 0 for a page that isn't in the document. */\n getHitCount(page?: PageRef | number): number;\n listPagesWithHits(): readonly PageRef[];\n /** `-1` when no hit is active. */\n getActiveHitIndex(): number;\n getActiveHit(): SearchHit | null;\n getProgress(): SearchProgress;\n getError(): PluginErrorInfo | null;\n\n // ── the service ─────────────────────────────────────────────────────────\n /**\n * Run a query to completion and return every hit, touching no session\n * state. Scans in natural page order; concurrent calls are independent.\n * Rejects `operation-cancelled` when `options.signal` aborts, and\n * `permission-denied` without `doc.text.search`.\n */\n findAll(query: SearchQuery, options?: SearchFindAllOptions): Promise<readonly SearchHit[]>;\n\n readonly onStarted: EventHook<SearchStartedEvent>;\n /**\n * `getProgress()` changed: once per slice of pages a search gets through,\n * and back to none when a new search starts or the session is cleared.\n */\n readonly onProgressChanged: EventHook<SearchProgressChangedEvent>;\n readonly onCompleted: EventHook<SearchCompletedEvent>;\n readonly onCancelled: EventHook<SearchCancelledEvent>;\n readonly onFailed: EventHook<SearchFailedEvent>;\n readonly onActiveHitChanged: EventHook<SearchActiveHitChangedEvent>;\n readonly onCleared: EventHook<SearchClearedEvent>;\n}\n\nexport { SearchToken } from './token';\n"],"mappings":";;;;;AAMA,MAAa,cAAc,sBAAwC,UAAU;CAC3E,MAAM;CAGN,UAAU;EACR,QAAQ;EACR,SAAS;EACT,SAAS;CACX;AACF,CAAC;;;;ACoGD,MAAa,kBAAkC;CAC7C,QAAQ;EAAE,QAAQ,EAAE,GAAG,IAAK;EAAG,UAAU;CAAS;CAClD,WAAW;EAAE,OAAO;EAAW,aAAa;EAAW,WAAW;CAAW;AAC/E"}
|