@xh/hoist 90.0.0 → 90.1.0

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.
Files changed (172) hide show
  1. package/CHANGELOG.md +136 -54
  2. package/admin/columns/Tracking.ts +9 -3
  3. package/admin/tabs/activity/tracking/ActivityTrackingModel.ts +155 -47
  4. package/admin/tabs/activity/tracking/ActivityTrackingPanel.ts +25 -4
  5. package/admin/tabs/activity/tracking/chart/AggChartModel.ts +2 -3
  6. package/appcontainer/ImpersonationBarModel.ts +8 -5
  7. package/build/types/admin/tabs/activity/tracking/ActivityTrackingModel.d.ts +25 -5
  8. package/build/types/cmp/cubegrid/CubeGrid.d.ts +26 -0
  9. package/build/types/cmp/cubegrid/CubeGridModel.d.ts +103 -0
  10. package/build/types/cmp/cubegrid/CubeGridPivotModel.d.ts +181 -0
  11. package/build/types/cmp/cubegrid/Types.d.ts +85 -0
  12. package/build/types/cmp/cubegrid/index.d.ts +4 -0
  13. package/build/types/cmp/dataview/DataViewModel.d.ts +6 -10
  14. package/build/types/cmp/grid/GridModel.d.ts +8 -33
  15. package/build/types/cmp/grid/Types.d.ts +51 -1
  16. package/build/types/cmp/grid/columns/Column.d.ts +2 -1
  17. package/build/types/cmp/grid/columns/ColumnGroup.d.ts +6 -0
  18. package/build/types/cmp/grid/helpers/GridCountLabel.d.ts +6 -3
  19. package/build/types/cmp/grid/impl/ColumnWidthCalculator.d.ts +6 -0
  20. package/build/types/cmp/grid/impl/GridLikeModel.d.ts +3 -0
  21. package/build/types/cmp/grid/impl/MenuSupport.d.ts +13 -0
  22. package/build/types/cmp/pdfviewer/PdfViewer.d.ts +14 -0
  23. package/build/types/cmp/pdfviewer/PdfViewerModel.d.ts +150 -0
  24. package/build/types/cmp/pdfviewer/Types.d.ts +55 -0
  25. package/build/types/cmp/pdfviewer/impl/PdfFindInputModel.d.ts +14 -0
  26. package/build/types/cmp/pdfviewer/impl/PdfViewerToolbarModel.d.ts +34 -0
  27. package/build/types/cmp/pdfviewer/impl/ZoomOptions.d.ts +10 -0
  28. package/build/types/cmp/pdfviewer/index.d.ts +3 -0
  29. package/build/types/cmp/statcard/StatCard.d.ts +90 -0
  30. package/build/types/cmp/statcard/index.d.ts +1 -0
  31. package/build/types/cmp/store/StoreFilterField.d.ts +8 -9
  32. package/build/types/cmp/store/impl/StoreFilterFieldImplModel.d.ts +4 -4
  33. package/build/types/cmp/zoneGrid/ZoneGridModel.d.ts +6 -10
  34. package/build/types/core/types/Types.d.ts +6 -0
  35. package/build/types/data/Field.d.ts +8 -1
  36. package/build/types/data/Store.d.ts +12 -0
  37. package/build/types/data/cube/Cube.d.ts +2 -0
  38. package/build/types/data/cube/CubeField.d.ts +3 -2
  39. package/build/types/data/cube/Query.d.ts +66 -4
  40. package/build/types/data/cube/View.d.ts +82 -4
  41. package/build/types/data/cube/ViewRowData.d.ts +13 -0
  42. package/build/types/data/cube/aggregate/MedianAggregator.d.ts +19 -0
  43. package/build/types/data/cube/aggregate/SumIfSameAggregator.d.ts +30 -0
  44. package/build/types/data/cube/impl/RowCache.d.ts +5 -0
  45. package/build/types/data/cube/impl/RowDataGenerator.d.ts +26 -0
  46. package/build/types/data/cube/impl/ViewDiagnostics.d.ts +27 -0
  47. package/build/types/data/cube/pivot/PivotCellRow.d.ts +27 -0
  48. package/build/types/data/cube/pivot/PivotPath.d.ts +45 -0
  49. package/build/types/data/cube/pivot/impl/PivotCells.d.ts +111 -0
  50. package/build/types/data/cube/pivot/impl/PivotReference.d.ts +39 -0
  51. package/build/types/data/cube/pivot/impl/PivotStructure.d.ts +105 -0
  52. package/build/types/data/cube/row/BaseRow.d.ts +12 -0
  53. package/build/types/data/cube/row/LeafRow.d.ts +4 -4
  54. package/build/types/data/cube/row/ParentRow.d.ts +20 -4
  55. package/build/types/data/cube/row/RowUpdate.d.ts +2 -0
  56. package/build/types/data/index.d.ts +3 -0
  57. package/build/types/desktop/cmp/button/grid/ColAutosizeButton.d.ts +6 -3
  58. package/build/types/desktop/cmp/button/grid/ColChooserButton.d.ts +7 -3
  59. package/build/types/desktop/cmp/button/grid/ExpandToLevelButton.d.ts +6 -3
  60. package/build/types/desktop/cmp/button/grid/ExportButton.d.ts +6 -3
  61. package/build/types/desktop/cmp/grid/find/GridFindField.d.ts +8 -9
  62. package/build/types/desktop/cmp/grid/find/impl/GridFindFieldImplModel.d.ts +3 -4
  63. package/build/types/desktop/cmp/pdfviewer/impl/PdfViewerToolbar.d.ts +12 -0
  64. package/build/types/desktop/cmp/statcard/impl/StatCardInfoImpl.d.ts +12 -0
  65. package/build/types/dynamics/desktop.d.ts +2 -0
  66. package/build/types/dynamics/mobile.d.ts +1 -0
  67. package/build/types/icon/Icon.d.ts +12 -0
  68. package/build/types/kit/pdfjs/index.d.ts +23 -0
  69. package/build/types/kit/pdfjs/styles.d.ts +2 -0
  70. package/build/types/kit/swiper/index.d.ts +7 -7
  71. package/build/types/mobile/cmp/button/grid/ColAutosizeButton.d.ts +6 -3
  72. package/build/types/mobile/cmp/button/grid/ColChooserButton.d.ts +6 -3
  73. package/build/types/mobile/cmp/button/grid/ExpandCollapseButton.d.ts +4 -4
  74. package/build/types/mobile/cmp/button/grid/ExpandToLevelButton.d.ts +4 -4
  75. package/build/types/mobile/cmp/pdfviewer/impl/PdfViewerToolbar.d.ts +12 -0
  76. package/cmp/README.md +3 -0
  77. package/cmp/ag-grid/AgGrid.ts +25 -3
  78. package/cmp/cubegrid/CubeGrid.ts +60 -0
  79. package/cmp/cubegrid/CubeGridModel.ts +365 -0
  80. package/cmp/cubegrid/CubeGridPivotModel.ts +943 -0
  81. package/cmp/cubegrid/README.md +343 -0
  82. package/cmp/cubegrid/Types.ts +105 -0
  83. package/cmp/cubegrid/index.ts +10 -0
  84. package/cmp/dataview/DataViewModel.ts +13 -8
  85. package/cmp/grid/Grid.scss +21 -5
  86. package/cmp/grid/GridModel.ts +41 -47
  87. package/cmp/grid/Types.ts +58 -1
  88. package/cmp/grid/columns/Column.ts +3 -1
  89. package/cmp/grid/columns/ColumnGroup.ts +10 -0
  90. package/cmp/grid/helpers/GridCountLabel.ts +12 -5
  91. package/cmp/grid/impl/ColumnGroupHeader.ts +18 -4
  92. package/cmp/grid/impl/ColumnWidthCalculator.ts +24 -0
  93. package/cmp/grid/impl/GridLikeModel.ts +17 -0
  94. package/cmp/grid/impl/MenuSupport.ts +36 -20
  95. package/cmp/pdfviewer/PdfViewer.scss +48 -0
  96. package/cmp/pdfviewer/PdfViewer.ts +102 -0
  97. package/cmp/pdfviewer/PdfViewerModel.ts +641 -0
  98. package/cmp/pdfviewer/README.md +224 -0
  99. package/cmp/pdfviewer/Types.ts +72 -0
  100. package/cmp/pdfviewer/impl/PdfFindInputModel.ts +44 -0
  101. package/cmp/pdfviewer/impl/PdfViewerToolbarModel.ts +45 -0
  102. package/cmp/pdfviewer/impl/ZoomOptions.ts +36 -0
  103. package/cmp/pdfviewer/index.ts +9 -0
  104. package/cmp/statcard/StatCard.scss +181 -0
  105. package/cmp/statcard/StatCard.ts +320 -0
  106. package/cmp/statcard/index.ts +1 -0
  107. package/cmp/store/StoreFilterField.ts +8 -9
  108. package/cmp/store/impl/StoreFilterFieldImplModel.ts +14 -14
  109. package/cmp/zoneGrid/ZoneGridModel.ts +13 -8
  110. package/core/types/Types.ts +7 -0
  111. package/data/Field.ts +10 -0
  112. package/data/Store.ts +25 -2
  113. package/data/cube/Cube.ts +5 -0
  114. package/data/cube/CubeField.ts +5 -0
  115. package/data/cube/Query.ts +170 -17
  116. package/data/cube/README.md +77 -2
  117. package/data/cube/View.ts +211 -32
  118. package/data/cube/ViewRowData.ts +22 -0
  119. package/data/cube/aggregate/MedianAggregator.ts +88 -0
  120. package/data/cube/aggregate/SumIfSameAggregator.ts +128 -0
  121. package/data/cube/impl/RowCache.ts +32 -11
  122. package/data/cube/impl/RowDataGenerator.ts +96 -4
  123. package/data/cube/impl/ViewDiagnostics.ts +47 -0
  124. package/data/cube/pivot/PivotCellRow.ts +73 -0
  125. package/data/cube/pivot/PivotPath.ts +67 -0
  126. package/data/cube/pivot/impl/PivotCells.ts +538 -0
  127. package/data/cube/pivot/impl/PivotReference.ts +125 -0
  128. package/data/cube/pivot/impl/PivotStructure.ts +500 -0
  129. package/data/cube/row/BaseRow.ts +26 -0
  130. package/data/cube/row/LeafRow.ts +9 -8
  131. package/data/cube/row/ParentRow.ts +58 -25
  132. package/data/cube/row/RowUpdate.ts +8 -0
  133. package/data/index.ts +3 -0
  134. package/desktop/appcontainer/AppContainer.ts +5 -1
  135. package/desktop/cmp/button/grid/ColAutosizeButton.ts +21 -5
  136. package/desktop/cmp/button/grid/ColChooserButton.ts +11 -5
  137. package/desktop/cmp/button/grid/ExpandToLevelButton.ts +20 -5
  138. package/desktop/cmp/button/grid/ExportButton.ts +19 -7
  139. package/desktop/cmp/dash/canvas/DashCanvas.ts +26 -2
  140. package/desktop/cmp/grid/find/GridFindField.ts +8 -9
  141. package/desktop/cmp/grid/find/impl/GridFindFieldImplModel.ts +15 -16
  142. package/desktop/cmp/grid/impl/colchooser/ColChooserBucketModel.ts +1 -1
  143. package/desktop/cmp/pdfviewer/impl/PdfViewerToolbar.ts +190 -0
  144. package/desktop/cmp/statcard/impl/StatCardInfoImpl.ts +27 -0
  145. package/docs/README.md +6 -2
  146. package/docs/doc-registry.json +21 -5
  147. package/docs/upgrade-notes/v90-upgrade-notes.md +130 -0
  148. package/docs/version-compatibility.md +2 -1
  149. package/dynamics/desktop.ts +4 -0
  150. package/dynamics/mobile.ts +2 -0
  151. package/format/FormatNumber.ts +6 -2
  152. package/icon/Icon.ts +18 -0
  153. package/icon/index.ts +32 -0
  154. package/kit/README.md +2 -0
  155. package/kit/pdfjs/PdfJs.scss +25 -0
  156. package/kit/pdfjs/index.ts +103 -0
  157. package/kit/pdfjs/pdf_viewer.css +6481 -0
  158. package/kit/pdfjs/styles.ts +12 -0
  159. package/mcp/README.md +13 -0
  160. package/mcp/data/import-paths.ts +4 -8
  161. package/mcp/data/index-cache.ts +2 -1
  162. package/mcp/data/ts-registry.ts +8 -29
  163. package/mcp/util/paths.ts +26 -0
  164. package/mobile/appcontainer/AppContainer.ts +3 -1
  165. package/mobile/cmp/button/grid/ColAutosizeButton.ts +20 -5
  166. package/mobile/cmp/button/grid/ColChooserButton.ts +12 -5
  167. package/mobile/cmp/button/grid/ExpandCollapseButton.ts +10 -6
  168. package/mobile/cmp/button/grid/ExpandToLevelButton.ts +10 -6
  169. package/mobile/cmp/pdfviewer/impl/PdfViewerToolbar.ts +137 -0
  170. package/package.json +14 -8
  171. package/public/msal-redirect-bridge.min.js +1 -1
  172. package/styles/vars.scss +59 -0
@@ -0,0 +1,641 @@
1
+ /*
2
+ * This file belongs to Hoist, an application development toolkit
3
+ * developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
4
+ *
5
+ * Copyright © 2026 Extremely Heavy Industries Inc.
6
+ */
7
+ import type {LoadSpec, PersistOptions} from '@xh/hoist/core';
8
+ import {HoistModel, XH} from '@xh/hoist/core';
9
+ import type {PdfJs} from '@xh/hoist/kit/pdfjs';
10
+ import {loadPdfJsAsync} from '@xh/hoist/kit/pdfjs';
11
+ import {action, computed, observable, observableRef, runInAction} from '@xh/hoist/mobx';
12
+ import type {FetchOptions} from '@xh/hoist/svc';
13
+ import {downloadBlob, throwIf, withDefault} from '@xh/hoist/utils/js';
14
+ import {createObservableRef} from '@xh/hoist/utils/react';
15
+ import {clamp, isNumber, isString, sumBy, times} from 'lodash';
16
+ import type {PDFDocumentLoadingTask, PDFDocumentProxy} from 'pdfjs-dist/legacy/build/pdf.mjs';
17
+ import type {
18
+ EventBus,
19
+ PDFFindController,
20
+ PDFLinkService,
21
+ PDFViewer
22
+ } from 'pdfjs-dist/legacy/web/pdf_viewer.mjs';
23
+ import type {ReactNode} from 'react';
24
+ import type {PdfViewerToolbarModel} from './impl/PdfViewerToolbarModel';
25
+ import type {
26
+ PdfFindResult,
27
+ PdfScale,
28
+ PdfSource,
29
+ PdfViewerToolbarItem,
30
+ PdfViewerToolbarSpec
31
+ } from './Types';
32
+
33
+ export interface PdfViewerConfig {
34
+ /** The document to display. See {@link PdfViewerModel.setSource}. */
35
+ source?: PdfSource;
36
+
37
+ /** Filename for downloads. Defaults to the last segment of a URL source, or 'document.pdf'. */
38
+ filename?: string;
39
+
40
+ /** Initial zoom level. Default 'page-width'. */
41
+ scale?: PdfScale;
42
+
43
+ /** Toolbar items to display, or false to hide. Default true. See {@link PdfViewerToolbarSpec}. */
44
+ toolbar?: PdfViewerToolbarSpec;
45
+
46
+ /** Content to display when there is no document. Default 'No document to display.' */
47
+ emptyText?: ReactNode;
48
+
49
+ /** Options to persist the user's chosen zoom level. */
50
+ persistWith?: PersistOptions;
51
+
52
+ /** See {@link HoistBase.xhName}. */
53
+ xhName?: string;
54
+ }
55
+
56
+ export interface PdfViewerModelDefaults {
57
+ /** Default toolbar items for desktop apps. */
58
+ toolbar?: PdfViewerToolbarItem[];
59
+ /** Default toolbar items for mobile apps. */
60
+ mobileToolbar?: PdfViewerToolbarItem[];
61
+ }
62
+
63
+ /**
64
+ * Model for a {@link PdfViewer}, built on Mozilla's pdf.js. Loads a document from a URL, a
65
+ * {@link FetchOptions} object, or bytes held by the app, and exposes observable state and
66
+ * actions for page navigation, zoom, rotation, find, and download.
67
+ *
68
+ * Bind any of these to custom controls, or drive the viewer programmatically - the built-in
69
+ * toolbar is implemented entirely on this public API.
70
+ *
71
+ * Requires the app to add `pdfjs-dist` to its own dependencies. See the package README.
72
+ *
73
+ * @see PdfViewer
74
+ */
75
+ export class PdfViewerModel extends HoistModel implements PdfViewerToolbarModel {
76
+ /** App-level defaults for PdfViewerModel. Instance config takes precedence. */
77
+ static defaults: PdfViewerModelDefaults = {
78
+ toolbar: ['pageNav', '-', 'zoom', '-', 'find', 'filler', 'rotate', 'download'],
79
+ mobileToolbar: ['pageNav', 'filler', 'zoom', 'download']
80
+ };
81
+
82
+ /** The document being displayed. */
83
+ @observableRef accessor source: PdfSource = null;
84
+
85
+ /** The loaded pdf.js document, for direct access to its API. Null until loaded. */
86
+ @observableRef accessor pdfDocument: PDFDocumentProxy = null;
87
+
88
+ /** Current page number, from 1. Tracks scrolling - call {@link goToPage} to change. */
89
+ @observable accessor pageNumber: number = 1;
90
+
91
+ /** Requested zoom level - a preset or a number. Call {@link setScale} to change. */
92
+ @observable accessor scale: PdfScale;
93
+
94
+ /** Effective numeric scale, as resolved from {@link scale} for the current viewer size. */
95
+ @observable accessor currentScale: number = 1;
96
+
97
+ /** Page rotation in degrees - 0, 90, 180, or 270. */
98
+ @observable accessor rotation: number = 0;
99
+
100
+ /** Query of the current find, or '' if none. Call {@link findAsync} to change. */
101
+ @observable accessor findQuery: string = '';
102
+
103
+ /** Count of find matches across the document. */
104
+ @observable accessor findMatchCount: number = 0;
105
+
106
+ /** Index of the selected find match, from 1. Zero if no matches. */
107
+ @observable accessor findMatchNumber: number = 0;
108
+
109
+ filename: string;
110
+ emptyText: ReactNode;
111
+ toolbar: PdfViewerToolbarItem[];
112
+
113
+ get isPdfViewerModel(): boolean {
114
+ return true;
115
+ }
116
+
117
+ /** Number of pages in the loaded document. */
118
+ @computed
119
+ get pageCount(): number {
120
+ return this.pdfDocument?.numPages ?? 0;
121
+ }
122
+
123
+ /** True if a document is loaded and ready to display. */
124
+ @computed
125
+ get hasDocument(): boolean {
126
+ return !!this.pdfDocument;
127
+ }
128
+
129
+ /** True while a find is searching the document. */
130
+ @computed
131
+ get isFinding(): boolean {
132
+ return !!this.pendingFind;
133
+ }
134
+
135
+ /** True if a document is set, whether or not it has loaded. */
136
+ get hasSource(): boolean {
137
+ return this.source != null;
138
+ }
139
+
140
+ /** @internal - scroll container for the pdf.js viewer, set by the component. */
141
+ containerRef = createObservableRef<HTMLDivElement>();
142
+
143
+ private pdfJs: PdfJs = null;
144
+ private loadingTask: PDFDocumentLoadingTask = null;
145
+ private viewer: PDFViewer = null;
146
+ private linkService: PDFLinkService = null;
147
+ private findController: PDFFindController = null;
148
+ private eventBus: EventBus = null;
149
+ private eventsAbort: AbortController = null;
150
+ @observableRef private accessor pendingFind: PendingFind = null;
151
+
152
+ constructor(config: PdfViewerConfig = {}) {
153
+ super();
154
+ const {source = null, filename, scale, toolbar, emptyText, persistWith, xhName} = config;
155
+
156
+ this.xhName = xhName;
157
+ this.filename = filename ?? null;
158
+ this.scale = withDefault(scale, 'page-width');
159
+ this.toolbar = this.parseToolbar(withDefault(toolbar, true));
160
+ this.emptyText = withDefault(emptyText, 'No document to display.');
161
+
162
+ if (persistWith) {
163
+ this.persistWith = persistWith;
164
+ this.markPersist('scale');
165
+ }
166
+
167
+ this.source = source;
168
+
169
+ this.addReaction(
170
+ {
171
+ track: () => this.source,
172
+ run: source => {
173
+ if (this.pendingFind?.source !== source) this.settleFind('cancelled');
174
+ this.loadAsync()
175
+ // Load errors display inline - see `lastLoadException`.
176
+ .catchDefault({showAlert: false, logOnServer: false})
177
+ .then(() => {
178
+ if (!this.pdfDocument && this.pendingFind?.source === source) {
179
+ this.settleFind('cancelled');
180
+ }
181
+ });
182
+ },
183
+ fireImmediately: true
184
+ },
185
+ {
186
+ track: () => [this.containerRef.current, this.pdfDocument],
187
+ run: ([container, doc]) =>
188
+ this.syncViewer(container as HTMLDivElement, doc as PDFDocumentProxy)
189
+ }
190
+ );
191
+ }
192
+
193
+ //------------------
194
+ // Document
195
+ //------------------
196
+ /** Set the document to display. Pass null to clear. */
197
+ @action
198
+ setSource(source: PdfSource) {
199
+ this.source = source;
200
+ }
201
+
202
+ /** Download the loaded document. */
203
+ async downloadAsync() {
204
+ const {pdfDocument} = this;
205
+ if (!pdfDocument) return;
206
+
207
+ const data = await pdfDocument.getData();
208
+ downloadBlob(
209
+ new Blob([data as BlobPart], {type: 'application/pdf'}),
210
+ this.downloadFilename
211
+ );
212
+ }
213
+
214
+ /** Filename used by {@link downloadAsync}. */
215
+ get downloadFilename(): string {
216
+ if (this.filename) return this.filename;
217
+
218
+ const {source} = this,
219
+ url = isString(source) ? source : (source as FetchOptions)?.url,
220
+ lastSegment = isString(url) ? url.split(/[?#]/)[0].split('/').pop() : null;
221
+ if (lastSegment?.toLowerCase().endsWith('.pdf')) return decodeSegment(lastSegment);
222
+
223
+ return source instanceof File ? source.name : 'document.pdf';
224
+ }
225
+
226
+ //------------------
227
+ // Navigation
228
+ //------------------
229
+ /** Scroll to a page, from 1. Out-of-range values are clamped. */
230
+ goToPage(pageNumber: number) {
231
+ const {viewer, pageCount} = this;
232
+ if (!viewer || !pageCount) return;
233
+ viewer.currentPageNumber = clamp(Math.round(pageNumber), 1, pageCount);
234
+ }
235
+
236
+ nextPage() {
237
+ this.viewer?.nextPage();
238
+ }
239
+
240
+ previousPage() {
241
+ this.viewer?.previousPage();
242
+ }
243
+
244
+ get canGoNext(): boolean {
245
+ return this.pageNumber < this.pageCount;
246
+ }
247
+
248
+ get canGoPrevious(): boolean {
249
+ return this.pageNumber > 1;
250
+ }
251
+
252
+ //------------------
253
+ // Zoom and rotation
254
+ //------------------
255
+ /** Set the zoom level. */
256
+ @action
257
+ setScale(scale: PdfScale) {
258
+ this.scale = scale;
259
+ this.applyScale();
260
+ }
261
+
262
+ zoomIn() {
263
+ this.viewer?.increaseScale();
264
+ }
265
+
266
+ zoomOut() {
267
+ this.viewer?.decreaseScale();
268
+ }
269
+
270
+ /** Rotate all pages by the given number of degrees - a multiple of 90. Default 90. */
271
+ @action
272
+ rotate(degrees: number = 90) {
273
+ throwIf(
274
+ degrees % 90 !== 0,
275
+ `PdfViewerModel rotation must be a multiple of 90 - got ${degrees}.`
276
+ );
277
+ this.rotation = (((this.rotation + degrees) % 360) + 360) % 360;
278
+ if (this.viewer) this.viewer.pagesRotation = this.rotation;
279
+ }
280
+
281
+ //------------------
282
+ // Find
283
+ //------------------
284
+ /**
285
+ * Search the document for text, and resolve once every page has been searched. Sets
286
+ * {@link findQuery}, highlights all matches, and scrolls to the first match at or after the
287
+ * current page. Pass '' to clear the find.
288
+ *
289
+ * Each call runs a new search, even for an unchanged query. A call made before the document
290
+ * has loaded waits for it to load and display, then searches. A newer find, a source change,
291
+ * a failed load, or `destroy()` resolves a call still in progress as `cancelled`.
292
+ *
293
+ * The query stays set when the source changes, and runs again on the new document.
294
+ *
295
+ * Matching is case-insensitive and ignores diacritics. pdf.js normalizes quotes, ligatures,
296
+ * whitespace, and line breaks, but a match cannot span pages.
297
+ */
298
+ findAsync(query: string): Promise<PdfFindResult> {
299
+ query ??= '';
300
+ this.settleFind('cancelled');
301
+ runInAction(() => (this.findQuery = query));
302
+
303
+ if (!query || !this.hasSource) {
304
+ this.dispatchFind();
305
+ return Promise.resolve(emptyFindResult(query, query ? 'cancelled' : 'notFound'));
306
+ }
307
+
308
+ return new Promise(resolve => {
309
+ runInAction(() => {
310
+ this.pendingFind = {
311
+ query,
312
+ source: this.source,
313
+ resolve,
314
+ awaitingReset: false,
315
+ state: null
316
+ };
317
+ });
318
+ // A no-op until the viewer exists - onPagesInit() dispatches it then.
319
+ this.dispatchFind();
320
+ });
321
+ }
322
+
323
+ /** Clear the find query and its highlights. */
324
+ clearFind() {
325
+ this.findAsync('');
326
+ }
327
+
328
+ /** Select and scroll to the next match for {@link findQuery}. */
329
+ findNext() {
330
+ this.dispatchFind('again', false);
331
+ }
332
+
333
+ /** Select and scroll to the previous match for {@link findQuery}. */
334
+ findPrevious() {
335
+ this.dispatchFind('again', true);
336
+ }
337
+
338
+ //------------------
339
+ // Implementation
340
+ //------------------
341
+ override async doLoadAsync(loadSpec: LoadSpec) {
342
+ const {source} = this;
343
+ await this.closeDocumentAsync();
344
+ if (source == null || this.isObsolete(loadSpec)) return;
345
+
346
+ let pdfDocument: PDFDocumentProxy;
347
+ try {
348
+ this.pdfJs ??= await loadPdfJsAsync();
349
+ const data = await this.getDataAsync(source, loadSpec);
350
+ if (this.isObsolete(loadSpec)) return;
351
+
352
+ // Assigned synchronously, so a newer load or destroy() always finds and destroys it.
353
+ const {lib, worker, BinaryDataFactory} = this.pdfJs,
354
+ loadingTask = lib.getDocument({data, worker, BinaryDataFactory});
355
+ this.loadingTask = loadingTask;
356
+
357
+ pdfDocument = await loadingTask.promise;
358
+ } catch (e) {
359
+ // A newer load or destroy() cancels this one - not an error.
360
+ if (this.isObsolete(loadSpec)) return;
361
+ throw e;
362
+ }
363
+ if (this.isObsolete(loadSpec)) return;
364
+
365
+ runInAction(() => {
366
+ this.pdfDocument = pdfDocument;
367
+ this.pageNumber = 1;
368
+ this.rotation = 0;
369
+ this.findMatchCount = 0;
370
+ this.findMatchNumber = 0;
371
+ });
372
+ }
373
+
374
+ private isObsolete(loadSpec: LoadSpec): boolean {
375
+ return loadSpec.isStale || this.isDestroyed;
376
+ }
377
+
378
+ private async getDataAsync(source: PdfSource, loadSpec: LoadSpec): Promise<Uint8Array> {
379
+ // pdf.js transfers the buffer to its worker - copy app-owned bytes to leave them intact.
380
+ if (source instanceof Uint8Array) return source.slice();
381
+ if (source instanceof ArrayBuffer) return new Uint8Array(source.slice(0));
382
+ if (source instanceof Blob) return new Uint8Array(await source.arrayBuffer());
383
+
384
+ const opts = isString(source) ? {url: source} : source,
385
+ response = await XH.fetch(opts, {loadSpec});
386
+ return new Uint8Array(await response.arrayBuffer());
387
+ }
388
+
389
+ private async closeDocumentAsync() {
390
+ // Clear first, so the viewer releases the document before pdf.js destroys it.
391
+ runInAction(() => (this.pdfDocument = null));
392
+
393
+ const {loadingTask} = this;
394
+ this.loadingTask = null;
395
+ await loadingTask?.destroy();
396
+ }
397
+
398
+ private syncViewer(container: HTMLDivElement, doc: PDFDocumentProxy) {
399
+ if (this.viewer && this.viewer.container !== container) this.destroyViewer();
400
+ if (!container || !doc) {
401
+ this.viewer?.setDocument(null);
402
+ return;
403
+ }
404
+
405
+ if (!this.viewer) this.createViewer(container);
406
+ this.viewer.setDocument(doc);
407
+ this.linkService.setDocument(doc);
408
+ }
409
+
410
+ private createViewer(container: HTMLDivElement) {
411
+ const {EventBus, PDFFindController, PDFLinkService, PDFViewer, LinkTarget} =
412
+ this.pdfJs.viewer,
413
+ eventsAbort = new AbortController(),
414
+ {signal} = eventsAbort,
415
+ eventBus = new EventBus(),
416
+ linkService = new PDFLinkService({eventBus, externalLinkTarget: LinkTarget.BLANK}),
417
+ findController = new PDFFindController({eventBus, linkService}),
418
+ viewer = new PDFViewer({
419
+ container,
420
+ eventBus,
421
+ linkService,
422
+ findController,
423
+ removePageBorders: true
424
+ });
425
+
426
+ linkService.setViewer(viewer);
427
+
428
+ eventBus.on('pagesinit', () => this.onPagesInit(), {signal});
429
+ eventBus.on('pagechanging', e => this.onPageChanging(e), {signal});
430
+ eventBus.on('scalechanging', e => this.onScaleChanging(e), {signal});
431
+ eventBus.on('updatefindmatchescount', e => this.onFindMatchesCount(e), {signal});
432
+ eventBus.on('updatefindcontrolstate', e => this.onFindControlState(e), {signal});
433
+ eventBus.on('updatetextlayermatches', e => this.onTextLayerMatches(e), {signal});
434
+
435
+ this.viewer = viewer;
436
+ this.linkService = linkService;
437
+ this.findController = findController;
438
+ this.eventBus = eventBus;
439
+ this.eventsAbort = eventsAbort;
440
+ }
441
+
442
+ private destroyViewer() {
443
+ // Do not pass an `abortSignal` to PDFViewer for this. pdf.js would also abort its shared
444
+ // text selection listeners, breaking selection in any other viewer still mounted.
445
+ this.viewer?.setDocument(null);
446
+ this.eventsAbort?.abort();
447
+ this.viewer = null;
448
+ this.linkService = null;
449
+ this.findController = null;
450
+ this.eventBus = null;
451
+ this.eventsAbort = null;
452
+ }
453
+
454
+ private onPagesInit() {
455
+ this.applyScale();
456
+ if (this.rotation) this.viewer.pagesRotation = this.rotation;
457
+ // Run a find requested before load, or the current query again on a new document.
458
+ if (this.pendingFind) {
459
+ this.dispatchFind();
460
+ } else if (this.findQuery) {
461
+ this.findAsync(this.findQuery);
462
+ }
463
+ }
464
+
465
+ @action
466
+ private onPageChanging({pageNumber}) {
467
+ this.pageNumber = pageNumber;
468
+ }
469
+
470
+ @action
471
+ private onScaleChanging({scale, presetValue}) {
472
+ this.currentScale = scale;
473
+ if (!presetValue) this.scale = scale;
474
+ }
475
+
476
+ @action
477
+ private onFindMatchesCount({matchesCount}) {
478
+ this.findMatchCount = matchesCount?.total ?? 0;
479
+ this.findMatchNumber = matchesCount?.current ?? 0;
480
+ }
481
+
482
+ private onFindControlState(e) {
483
+ // A pending state carries the prior search's counts - dispatchFind() has already reset them.
484
+ const {FindState} = this.pdfJs.viewer;
485
+ if (e.state === FindState.PENDING) return;
486
+
487
+ this.onFindMatchesCount(e);
488
+
489
+ const {pendingFind} = this;
490
+ if (pendingFind && !pendingFind.awaitingReset && e.rawQuery === pendingFind.query) {
491
+ pendingFind.state = e.state;
492
+ this.checkFindDone();
493
+ }
494
+ }
495
+
496
+ private onTextLayerMatches({pageIndex}) {
497
+ const {pendingFind} = this;
498
+ if (!pendingFind) return;
499
+
500
+ // pdf.js signals all pages (-1) when it clears prior results to start a new search.
501
+ if (pageIndex === -1) {
502
+ pendingFind.awaitingReset = false;
503
+ } else {
504
+ this.checkFindDone();
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Settle the pending find once its result is final. pdf.js reports not found only after
510
+ * searching every page, but reports found at the first match - wait for all pages then,
511
+ * so the count is complete.
512
+ */
513
+ private checkFindDone() {
514
+ const {pendingFind, findController, pageCount} = this;
515
+ if (pendingFind?.state == null || !findController) return;
516
+
517
+ const {FindState} = this.pdfJs.viewer;
518
+ if (pendingFind.state === FindState.NOT_FOUND) {
519
+ this.settleFind('notFound');
520
+ return;
521
+ }
522
+
523
+ // Found with no selection - a query that normalizes to nothing, e.g. only diacritics.
524
+ const {pageMatches, selected} = findController;
525
+ if (selected.pageIdx < 0) {
526
+ this.settleFind('notFound');
527
+ return;
528
+ }
529
+
530
+ if (times(pageCount).every(i => pageMatches[i])) this.settleFind('found');
531
+ }
532
+
533
+ @action
534
+ private settleFind(status: PdfFindResult['status']) {
535
+ const {pendingFind, findController} = this;
536
+ if (!pendingFind) return;
537
+ this.pendingFind = null;
538
+
539
+ if (status !== 'found') {
540
+ pendingFind.resolve(emptyFindResult(pendingFind.query, status));
541
+ return;
542
+ }
543
+
544
+ const {pageMatches, selected} = findController,
545
+ {pageIdx, matchIdx} = selected;
546
+ pendingFind.resolve({
547
+ status,
548
+ query: pendingFind.query,
549
+ matchCount: sumBy(pageMatches, m => m?.length ?? 0),
550
+ matchNumber: sumBy(pageMatches.slice(0, pageIdx), m => m?.length ?? 0) + matchIdx + 1,
551
+ pageNumber: pageIdx + 1
552
+ });
553
+ }
554
+
555
+ private applyScale() {
556
+ const {viewer, scale} = this;
557
+ if (!viewer?.pagesCount) return;
558
+ if (isNumber(scale)) {
559
+ viewer.currentScale = scale;
560
+ } else {
561
+ viewer.currentScaleValue = scale;
562
+ }
563
+ }
564
+
565
+ private dispatchFind(type: '' | 'again' = '', findPrevious: boolean = false) {
566
+ const {eventBus, findQuery} = this;
567
+ if (!eventBus) return;
568
+
569
+ if (!findQuery) {
570
+ eventBus.dispatch('findbarclose', {source: this});
571
+ this.onFindMatchesCount({matchesCount: null});
572
+ return;
573
+ }
574
+
575
+ // A new search - clear the prior search's counts now, not when pdf.js first reports.
576
+ if (!type) {
577
+ this.onFindMatchesCount({matchesCount: null});
578
+ if (this.pendingFind) {
579
+ this.pendingFind.awaitingReset = true;
580
+ this.pendingFind.state = null;
581
+ }
582
+ }
583
+
584
+ eventBus.dispatch('find', {
585
+ source: this,
586
+ type,
587
+ query: findQuery,
588
+ caseSensitive: false,
589
+ entireWord: false,
590
+ highlightAll: true,
591
+ findPrevious,
592
+ matchDiacritics: false
593
+ });
594
+ }
595
+
596
+ /** @internal - called by the component when the viewer is resized or shown. */
597
+ onResize() {
598
+ // Re-fit for presets, which pdf.js does not do itself.
599
+ if (!isNumber(this.scale)) this.applyScale();
600
+ }
601
+
602
+ private parseToolbar(spec: PdfViewerToolbarSpec): PdfViewerToolbarItem[] {
603
+ if (spec === false) return null;
604
+ if (spec === true) {
605
+ const {defaults} = PdfViewerModel;
606
+ return XH.isMobileApp ? defaults.mobileToolbar : defaults.toolbar;
607
+ }
608
+ return spec;
609
+ }
610
+
611
+ override destroy() {
612
+ this.settleFind('cancelled');
613
+ this.destroyViewer();
614
+ this.closeDocumentAsync().catch(e => this.logError('Error closing document', e));
615
+ super.destroy();
616
+ }
617
+ }
618
+
619
+ interface PendingFind {
620
+ query: string;
621
+ /** Source when the find was requested - a change to another source cancels it. */
622
+ source: PdfSource;
623
+ resolve: (result: PdfFindResult) => void;
624
+ /** True from dispatch until pdf.js clears prior results, so their reports are ignored. */
625
+ awaitingReset: boolean;
626
+ /** Latest pdf.js `FindState` reported for this search, once it has started. */
627
+ state: number;
628
+ }
629
+
630
+ function emptyFindResult(query: string, status: PdfFindResult['status']): PdfFindResult {
631
+ return {status, query, matchCount: 0, matchNumber: 0, pageNumber: null};
632
+ }
633
+
634
+ /** Decode a URL path segment for use as a filename, leaving a malformed one as is. */
635
+ function decodeSegment(segment: string): string {
636
+ try {
637
+ return decodeURIComponent(segment);
638
+ } catch {
639
+ return segment;
640
+ }
641
+ }