@embedpdf/core-geometry 3.0.0-next.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.
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Copyright 2026 CloudPDF LTD
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use files in this distribution except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ https://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ -----------------------------------------------------------------------
16
+
17
+ Apache License
18
+ Version 2.0, January 2004
19
+ http://www.apache.org/licenses/
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/dist/index.cjs ADDED
@@ -0,0 +1,423 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/index.ts
3
+ /**
4
+ * The bounding box of a set of rects (null for the empty set). Space-
5
+ * agnostic: works on any y-down `{x,y,width,height}` rects — search hit
6
+ * bounds, selection line-merge unions, multi-quad annotation extents.
7
+ */
8
+ function boundsOfRects(rects) {
9
+ if (rects.length === 0) return null;
10
+ let x1 = Infinity;
11
+ let y1 = Infinity;
12
+ let x2 = -Infinity;
13
+ let y2 = -Infinity;
14
+ for (const r of rects) {
15
+ x1 = Math.min(x1, r.x);
16
+ y1 = Math.min(y1, r.y);
17
+ x2 = Math.max(x2, r.x + r.width);
18
+ y2 = Math.max(y2, r.y + r.height);
19
+ }
20
+ return {
21
+ x: x1,
22
+ y: y1,
23
+ width: x2 - x1,
24
+ height: y2 - y1
25
+ };
26
+ }
27
+ /**
28
+ * Intersection of two y-down rects — zero-sized (width/height 0, origin at
29
+ * the would-be corner) when disjoint, so callers can test `width > 0`
30
+ * without a null branch. Space-agnostic like {@link boundsOfRects}: view-px
31
+ * viewport ∩ footprint, page-point visibility ∩ tile footprints, ….
32
+ */
33
+ function intersectRects(a, b) {
34
+ const x = Math.max(a.x, b.x);
35
+ const y = Math.max(a.y, b.y);
36
+ return {
37
+ x,
38
+ y,
39
+ width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x),
40
+ height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y)
41
+ };
42
+ }
43
+ const NO_FRAME = {
44
+ top: 0,
45
+ right: 0,
46
+ bottom: 0,
47
+ left: 0
48
+ };
49
+ /** True for the quarter-turns that swap a page's width and height. */
50
+ function isQuarterTurn(rotation) {
51
+ return rotation === 90 || rotation === 270;
52
+ }
53
+ /**
54
+ * Compose two quarter-turn rotations (mod 360). THE way the shell resolves a
55
+ * page's TOTAL display rotation — `addRotations(page /Rotate, view rotation)`
56
+ * — so the wrap arithmetic is never hand-written (and drift) per call site.
57
+ */
58
+ function addRotations(a, b) {
59
+ return (a + b) % 360;
60
+ }
61
+ /**
62
+ * Snap a view-px value to the device pixel grid: round to a whole device pixel,
63
+ * back to view px. Used for a page's screen POSITION so a CSS-rotated page lands
64
+ * on the grid (no sub-pixel anti-aliased fringe). The shell never hand-rounds.
65
+ */
66
+ function snapToDevice(value, dpr) {
67
+ return Math.round(value * dpr) / dpr;
68
+ }
69
+ /** A page's on-screen footprint: width and height swapped for quarter-turns. */
70
+ function displaySize(content, rotation) {
71
+ return isQuarterTurn(rotation) ? {
72
+ width: content.height,
73
+ height: content.width
74
+ } : {
75
+ width: content.width,
76
+ height: content.height
77
+ };
78
+ }
79
+ /**
80
+ * The engine's `kind:'width'` height rule, replicated EXACTLY so the viewer can
81
+ * predict the rendered bitmap's height up front — the page box is sized to it,
82
+ * so the box matches the bitmap with no reflow and no 1px seam.
83
+ *
84
+ * Mirrors `PageRenderReader.resolveDeviceSize` (engine-services): we render the
85
+ * page UN-rotated (CSS applies the rotation), so there is no width/height swap
86
+ * here — `pageSize` is the page's own points. MUST stay in lockstep with that
87
+ * function; the round-trip test in the render plugin asserts they agree.
88
+ */
89
+ function deviceHeightForWidth(pageSize, deviceWidth) {
90
+ return Math.max(1, Math.round(deviceWidth * pageSize.height / pageSize.width));
91
+ }
92
+ /**
93
+ * Build a page's transform from its intrinsic size + the platform/view scale.
94
+ * `scale` is VIEW px per PDF point (the shell composes it: `viewUnitsPerPoint ×
95
+ * contentScale × zoom`); `dpr` is device px per view px. Device dimensions snap
96
+ * to the grid (crisp, no rotation fringe) and follow the engine's width rule
97
+ * (box == bitmap, no reflow).
98
+ */
99
+ function pageTransform(input) {
100
+ const { pageSize, rotation, scale, dpr } = input;
101
+ const deviceWidth = Math.max(1, Math.round(pageSize.width * scale * dpr));
102
+ const deviceHeight = deviceHeightForWidth(pageSize, deviceWidth);
103
+ const renderScale = deviceWidth / pageSize.width;
104
+ const content = {
105
+ width: deviceWidth / dpr,
106
+ height: deviceHeight / dpr
107
+ };
108
+ const viewScale = content.width / pageSize.width;
109
+ const baseScale = input.baseScale ?? scale;
110
+ const zoom = baseScale > 0 ? viewScale / baseScale : 1;
111
+ const footprint = displaySize(content, rotation);
112
+ const contentMat = [
113
+ viewScale,
114
+ 0,
115
+ 0,
116
+ viewScale,
117
+ 0,
118
+ 0
119
+ ];
120
+ const viewMat = rotateScaleMatrix(viewScale, content.width, content.height, rotation);
121
+ const invMat = invert(viewMat);
122
+ const pageToContent = (p) => applyPoint(contentMat, p);
123
+ const pageToView = (p) => applyPoint(viewMat, p);
124
+ const viewToPage = (p) => applyPoint(invMat, p);
125
+ const pageToViewRect = (r) => applyRect(viewMat, r);
126
+ const viewToPageRect = (r) => applyRect(invMat, r);
127
+ const cssMatrix = matrixToCss(viewMat);
128
+ return {
129
+ rotation,
130
+ viewWidth: footprint.width,
131
+ viewHeight: footprint.height,
132
+ contentWidth: content.width,
133
+ contentHeight: content.height,
134
+ deviceWidth,
135
+ deviceHeight,
136
+ renderScale,
137
+ viewScale,
138
+ baseScale,
139
+ zoom,
140
+ pageToContent,
141
+ pageToView,
142
+ pageToViewRect,
143
+ viewToPage,
144
+ viewToPageRect,
145
+ cssMatrix
146
+ };
147
+ }
148
+ /** The identity transform within a single space. */
149
+ function identity() {
150
+ return [
151
+ 1,
152
+ 0,
153
+ 0,
154
+ 1,
155
+ 0,
156
+ 0
157
+ ];
158
+ }
159
+ /**
160
+ * Compose two matrices: `compose(m, n)` applies `n` first, then `m` (matrix
161
+ * product `m · n`). The shared middle space `B` must line up, so the type system
162
+ * rejects composing mismatched hops.
163
+ */
164
+ function compose(m, n) {
165
+ const [a, b, c, d, e, f] = m;
166
+ const [a2, b2, c2, d2, e2, f2] = n;
167
+ return [
168
+ a * a2 + c * b2,
169
+ b * a2 + d * b2,
170
+ a * c2 + c * d2,
171
+ b * c2 + d * d2,
172
+ a * e2 + c * f2 + e,
173
+ b * e2 + d * f2 + f
174
+ ];
175
+ }
176
+ /** Invert a transform — `invert(pdfToView)` is `viewToPdf`, i.e. hit-testing for free. */
177
+ function invert(m) {
178
+ const [a, b, c, d, e, f] = m;
179
+ const det = a * d - b * c;
180
+ if (det === 0) throw new Error("Mat2D.invert: non-invertible matrix (det = 0)");
181
+ const ia = d / det;
182
+ const ib = -b / det;
183
+ const ic = -c / det;
184
+ const id = a / det;
185
+ return [
186
+ ia,
187
+ ib,
188
+ ic,
189
+ id,
190
+ -(ia * e + ic * f),
191
+ -(ib * e + id * f)
192
+ ];
193
+ }
194
+ /** Apply a transform to a point. */
195
+ function applyPoint(m, p) {
196
+ const [a, b, c, d, e, f] = m;
197
+ return {
198
+ x: a * p.x + c * p.y + e,
199
+ y: b * p.x + d * p.y + f
200
+ };
201
+ }
202
+ /**
203
+ * Apply a transform to a rect, returning the axis-aligned bounding box of the
204
+ * four transformed corners. EXACT for translate/scale/quarter-turn (every page
205
+ * transform `pageGeometry` produces); lossy under skew — use {@link applyQuad}
206
+ * for content that can be rotated off-axis.
207
+ */
208
+ function applyRect(m, r) {
209
+ const c0 = applyPoint(m, {
210
+ x: r.x,
211
+ y: r.y
212
+ });
213
+ const c1 = applyPoint(m, {
214
+ x: r.x + r.width,
215
+ y: r.y
216
+ });
217
+ const c2 = applyPoint(m, {
218
+ x: r.x,
219
+ y: r.y + r.height
220
+ });
221
+ const c3 = applyPoint(m, {
222
+ x: r.x + r.width,
223
+ y: r.y + r.height
224
+ });
225
+ const xs = [
226
+ c0.x,
227
+ c1.x,
228
+ c2.x,
229
+ c3.x
230
+ ];
231
+ const ys = [
232
+ c0.y,
233
+ c1.y,
234
+ c2.y,
235
+ c3.y
236
+ ];
237
+ const minX = Math.min(...xs);
238
+ const minY = Math.min(...ys);
239
+ return {
240
+ x: minX,
241
+ y: minY,
242
+ width: Math.max(...xs) - minX,
243
+ height: Math.max(...ys) - minY
244
+ };
245
+ }
246
+ /** Apply a transform to a quad, preserving orientation (maps the four points). */
247
+ function applyQuad(m, q) {
248
+ return {
249
+ p1: applyPoint(m, q.p1),
250
+ p2: applyPoint(m, q.p2),
251
+ p3: applyPoint(m, q.p3),
252
+ p4: applyPoint(m, q.p4)
253
+ };
254
+ }
255
+ /**
256
+ * A `Mat2D` IS a CSS `matrix()` — the six numbers are identical. Drop the result
257
+ * on a footprint-space layer (`transform`, `transform-origin: 0 0`) and place
258
+ * children in the source space; the rotation + scale are handled for free.
259
+ */
260
+ function matrixToCss(m) {
261
+ const [a, b, c, d, e, f] = m;
262
+ return `matrix(${a}, ${b}, ${c}, ${d}, ${e}, ${f})`;
263
+ }
264
+ /** Translate within a space. */
265
+ function translate(tx, ty) {
266
+ return [
267
+ 1,
268
+ 0,
269
+ 0,
270
+ 1,
271
+ tx,
272
+ ty
273
+ ];
274
+ }
275
+ /** Scale about the space origin. */
276
+ function scale(sx, sy) {
277
+ return [
278
+ sx,
279
+ 0,
280
+ 0,
281
+ sy,
282
+ 0,
283
+ 0
284
+ ];
285
+ }
286
+ /** Rotate about the space origin (radians; clockwise in y-down content space). */
287
+ function rotate(rad) {
288
+ const c = Math.cos(rad);
289
+ const s = Math.sin(rad);
290
+ return [
291
+ c,
292
+ s,
293
+ -s,
294
+ c,
295
+ 0,
296
+ 0
297
+ ];
298
+ }
299
+ /** Rotate about an arbitrary pivot: `T(c) · R(rad) · T(-c)`. */
300
+ function rotateAbout(c, rad) {
301
+ return compose(translate(c.x, c.y), compose(rotate(rad), translate(-c.x, -c.y)));
302
+ }
303
+ /** Scale about an arbitrary anchor: `T(a) · S(sx, sy) · T(-a)`. */
304
+ function scaleAbout(a, sx, sy) {
305
+ return compose(translate(a.x, a.y), compose(scale(sx, sy), translate(-a.x, -a.y)));
306
+ }
307
+ /** The rotation angle (radians) encoded in a matrix — `atan2(b, a)`. Positive is
308
+ * clockwise in y-down content space (the inverse of {@link rotate}). */
309
+ function angleOf(m) {
310
+ return Math.atan2(m[1], m[0]);
311
+ }
312
+ /**
313
+ * The page's scale + integer quarter-turn as a `Mat2D`: a content point maps to
314
+ * its place in the rotated DISPLAY box. `scale` is output units per content
315
+ * point; `boxW`/`boxH` are the UN-rotated content's extents in those same output
316
+ * units, and the offsets keep the footprint in the box's positive quadrant
317
+ * (origin at the box top-left).
318
+ *
319
+ * THE single encoding of the quarter-turn — `pageTransform` (view px),
320
+ * `pageGeometry` (the `content→view` hop), and `pageToWorld` (world units) all
321
+ * build on this one function, so the rotation can never drift between them.
322
+ */
323
+ function rotateScaleMatrix(scale, boxW, boxH, rotation) {
324
+ switch (rotation) {
325
+ case 90: return [
326
+ 0,
327
+ scale,
328
+ -scale,
329
+ 0,
330
+ boxH,
331
+ 0
332
+ ];
333
+ case 180: return [
334
+ -scale,
335
+ 0,
336
+ 0,
337
+ -scale,
338
+ boxW,
339
+ boxH
340
+ ];
341
+ case 270: return [
342
+ 0,
343
+ -scale,
344
+ scale,
345
+ 0,
346
+ 0,
347
+ boxW
348
+ ];
349
+ default: return [
350
+ scale,
351
+ 0,
352
+ 0,
353
+ scale,
354
+ 0,
355
+ 0
356
+ ];
357
+ }
358
+ }
359
+ /**
360
+ * PDF user space (y-up, origin = crop bottom-left) → content space (y-down,
361
+ * origin = crop top-left, unscaled points). THE single encoding of the engine→
362
+ * content y-flip + crop offset: `pageGeometry` composes its `pdfToContent` from
363
+ * this, and pure annotation geometry (content-space editing) reuses it too, so
364
+ * the rule can never be hand-written twice and drift.
365
+ */
366
+ function pdfToContentMatrix(crop) {
367
+ return [
368
+ 1,
369
+ 0,
370
+ 0,
371
+ -1,
372
+ -crop.left,
373
+ crop.top
374
+ ];
375
+ }
376
+ /**
377
+ * Build a page's space matrices from its crop box, rotation, and `userUnit` plus
378
+ * the viewer `zoom`. This is the ONE function that knows the y-flip, crop origin,
379
+ * `userUnit`, and rotation; everything else composes from its output. The engine
380
+ * never emits these — they bake in viewer state (zoom, later scroll/dpr) — so the
381
+ * boundary stays clean: engine owns `Pdf*` truth, the viewer composes the rest.
382
+ */
383
+ function pageGeometry(input, zoom) {
384
+ const { crop, rotation, userUnit } = input;
385
+ const s = zoom * userUnit;
386
+ const pdfToContent = pdfToContentMatrix(crop);
387
+ const contentToView = rotateScaleMatrix(s, (crop.right - crop.left) * s, (crop.top - crop.bottom) * s, rotation);
388
+ const pdfToView = compose(contentToView, pdfToContent);
389
+ return {
390
+ pdfToContent,
391
+ contentToView,
392
+ pdfToView,
393
+ viewToPdf: invert(pdfToView)
394
+ };
395
+ }
396
+ //#endregion
397
+ exports.NO_FRAME = NO_FRAME;
398
+ exports.addRotations = addRotations;
399
+ exports.angleOf = angleOf;
400
+ exports.applyPoint = applyPoint;
401
+ exports.applyQuad = applyQuad;
402
+ exports.applyRect = applyRect;
403
+ exports.boundsOfRects = boundsOfRects;
404
+ exports.compose = compose;
405
+ exports.deviceHeightForWidth = deviceHeightForWidth;
406
+ exports.displaySize = displaySize;
407
+ exports.identity = identity;
408
+ exports.intersectRects = intersectRects;
409
+ exports.invert = invert;
410
+ exports.isQuarterTurn = isQuarterTurn;
411
+ exports.matrixToCss = matrixToCss;
412
+ exports.pageGeometry = pageGeometry;
413
+ exports.pageTransform = pageTransform;
414
+ exports.pdfToContentMatrix = pdfToContentMatrix;
415
+ exports.rotate = rotate;
416
+ exports.rotateAbout = rotateAbout;
417
+ exports.rotateScaleMatrix = rotateScaleMatrix;
418
+ exports.scale = scale;
419
+ exports.scaleAbout = scaleAbout;
420
+ exports.snapToDevice = snapToDevice;
421
+ exports.translate = translate;
422
+
423
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * @embedpdf/core-geometry — the viewer's pure 2D coordinate primitives.\n *\n * The bottom of the pyramid: stage-core (layout), plugin-stage (`pageToWorld`),\n * and every framework adapter (`toPagePoint` hit-testing) all sit on these.\n * Zero dependencies, DOM-free, serializable — Rust-portable.\n *\n * The page-rotation transforms are the reason this package exists: the same\n * quarter-turn maps content↔box in BOTH directions, and that one rule must not\n * be hand-written (and drift, or be bug-fixed in only one of four adapters).\n */\n\nexport interface Point {\n x: number;\n y: number;\n}\nexport interface Size {\n width: number;\n height: number;\n}\n/** Viewer-side rect: top-left origin, y-down (view/page-point convention — NOT the\n * engine's bottom-left PDF rect). */\nexport interface Rect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/**\n * The bounding box of a set of rects (null for the empty set). Space-\n * agnostic: works on any y-down `{x,y,width,height}` rects — search hit\n * bounds, selection line-merge unions, multi-quad annotation extents.\n */\nexport function boundsOfRects(rects: readonly Rect[]): Rect | null {\n if (rects.length === 0) return null;\n let x1 = Infinity;\n let y1 = Infinity;\n let x2 = -Infinity;\n let y2 = -Infinity;\n for (const r of rects) {\n x1 = Math.min(x1, r.x);\n y1 = Math.min(y1, r.y);\n x2 = Math.max(x2, r.x + r.width);\n y2 = Math.max(y2, r.y + r.height);\n }\n return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 };\n}\n\n/**\n * Intersection of two y-down rects — zero-sized (width/height 0, origin at\n * the would-be corner) when disjoint, so callers can test `width > 0`\n * without a null branch. Space-agnostic like {@link boundsOfRects}: view-px\n * viewport ∩ footprint, page-point visibility ∩ tile footprints, ….\n */\nexport function intersectRects(a: Rect, b: Rect): Rect {\n const x = Math.max(a.x, b.x);\n const y = Math.max(a.y, b.y);\n return {\n x,\n y,\n width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x),\n height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y),\n };\n}\n\n/**\n * Quarter-turn display rotation, degrees clockwise. The viewer-side notion of a\n * page's on-screen rotation — the TOTAL = (document /Rotate + any view\n * rotation), resolved by the shell. Structurally identical to the engine's\n * `PageRotation`, so the two interoperate without this package depending on the\n * engine.\n */\nexport type PageRotation = 0 | 90 | 180 | 270;\n\n/**\n * Reserved chrome real estate around a page, one thickness per side (screen px\n * in the shell; world units in the pure layout). The page content sits inset\n * by these; the bands hold box-space chrome (labels, buttons, rails) that does\n * not rotate. The layout reserves the matching space so nothing overlaps.\n */\nexport interface PageFrame {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\nexport const NO_FRAME: PageFrame = { top: 0, right: 0, bottom: 0, left: 0 };\n\n/** True for the quarter-turns that swap a page's width and height. */\nexport function isQuarterTurn(rotation: PageRotation): boolean {\n return rotation === 90 || rotation === 270;\n}\n\n/**\n * Compose two quarter-turn rotations (mod 360). THE way the shell resolves a\n * page's TOTAL display rotation — `addRotations(page /Rotate, view rotation)`\n * — so the wrap arithmetic is never hand-written (and drift) per call site.\n */\nexport function addRotations(a: PageRotation, b: PageRotation): PageRotation {\n return ((a + b) % 360) as PageRotation;\n}\n\n/**\n * Snap a view-px value to the device pixel grid: round to a whole device pixel,\n * back to view px. Used for a page's screen POSITION so a CSS-rotated page lands\n * on the grid (no sub-pixel anti-aliased fringe). The shell never hand-rounds.\n */\nexport function snapToDevice(value: number, dpr: number): number {\n return Math.round(value * dpr) / dpr;\n}\n\n/** A page's on-screen footprint: width and height swapped for quarter-turns. */\nexport function displaySize(content: Size, rotation: PageRotation): Size {\n return isQuarterTurn(rotation)\n ? { width: content.height, height: content.width }\n : { width: content.width, height: content.height };\n}\n\n/**\n * The engine's `kind:'width'` height rule, replicated EXACTLY so the viewer can\n * predict the rendered bitmap's height up front — the page box is sized to it,\n * so the box matches the bitmap with no reflow and no 1px seam.\n *\n * Mirrors `PageRenderReader.resolveDeviceSize` (engine-services): we render the\n * page UN-rotated (CSS applies the rotation), so there is no width/height swap\n * here — `pageSize` is the page's own points. MUST stay in lockstep with that\n * function; the round-trip test in the render plugin asserts they agree.\n */\nexport function deviceHeightForWidth(pageSize: Size, deviceWidth: number): number {\n return Math.max(1, Math.round((deviceWidth * pageSize.height) / pageSize.width));\n}\n\n/**\n * The single per-page bridge between the viewer's three coordinate spaces. NB:\n * these are all VIEWER spaces — top-left origin, y-down. They are NOT the\n * engine's PDF user space (`Pdf*`, bottom-left origin, y-up); the engine→content\n * hop (the y-flip + crop offset) is a separate matrix (`pageGeometry`).\n *\n * content space page-local points, top-left, y-down — un-rotated page frame\n * view space platform logical px (web: CSS px) — layout, DOM, pointer events\n * device space physical pixels — the rendered bitmap\n *\n * PAGE-LOCAL by design: it knows this page's own box, NOT where the page sits in\n * the scene. Placement (camera/layout) stays on `VisiblePage.{x,y}` and positions\n * the page container; the transform converts everything INSIDE that container. So\n * it is camera/pan-invariant — it only changes on zoom / rotation / contentScale\n * / dpr, which makes it cheap to memoize.\n *\n * Every plugin and framework adapter consumes THIS — never `x * scale`, never\n * `pageToWorld()∘toScreen()`, never `* dpr`. New plugins (annotations, search,\n * forms) do no coordinate math; new platforms (iOS/Android) inject a different\n * `scale` and reuse all of it.\n */\nexport interface PageTransform {\n /**\n * The page's TOTAL display rotation (document /Rotate + any view rotation) —\n * the same value the transform's matrices were built from, exposed so\n * consumers that need the quarter-turn itself (an upright-placement rule, a\n * pointer sample) read it HERE instead of re-deriving it from the matrix.\n */\n readonly rotation: PageRotation;\n /** Display footprint in VIEW px (device-snapped) — the page container's size.\n * Width↔height already swapped for quarter-turns. */\n readonly viewWidth: number;\n readonly viewHeight: number;\n /** The UN-rotated content box in VIEW px — the size of the wrapper the bitmap\n * and content-space overlays live in (before the wrapper's CSS rotation). */\n readonly contentWidth: number;\n readonly contentHeight: number;\n /** Render the (un-rotated) bitmap at EXACTLY this — `viewport: {kind:'width', width: deviceWidth}`.\n * Integer device px; `deviceHeight` is the engine's exact derived height. */\n readonly deviceWidth: number;\n readonly deviceHeight: number;\n /** Device px per PDF point (uniform). */\n readonly renderScale: number;\n /** VIEW px per PDF point (uniform, device-snapped) — the one factor for\n * screen-constant chrome: content units = CSS px ÷ `viewScale`. */\n readonly viewScale: number;\n /**\n * View px per PDF point at 100% ZOOM — the page's physical baseline:\n * `viewUnitsPerPoint × userUnit` (web: 96/72 × `/UserUnit`, so 100% maps to\n * inches on screen, Acrobat-style). What \"100%\" MEANS for this page.\n */\n readonly baseScale: number;\n /**\n * The page's zoom RELATIVE to its 100% baseline (`viewScale / baseScale`,\n * dimensionless; exactly 1 at 100% for any `userUnit`). THE number\n * zoom-relative policies consume — e.g. the `/F` NoZoom exemption clamps\n * its body to `zoom ≤ 1`. Distinct from `viewScale` (a units conversion).\n */\n readonly zoom: number;\n /** Content point → UN-rotated content view px. For overlays INSIDE the rotated\n * content wrapper (markers, annotations) — they ride the wrapper's rotation,\n * so they place in content space and only scale here. */\n pageToContent(p: Point): Point;\n /** Content point → page-local view px in the DISPLAY box (rotation applied). For\n * footprint-space layers (outside the wrapper). */\n pageToView(p: Point): Point;\n /** Content rect → its axis-aligned view-px rect (exact for quarter-turns). */\n pageToViewRect(r: Rect): Rect;\n /** Inverse — display-box view px (box-local) → content point. Hit-testing. */\n viewToPage(p: Point): Point;\n /** Inverse of {@link pageToViewRect}: display-box view-px rect → its content\n * AABB (exact for quarter-turns). The visibility primitive — projecting a\n * viewport rect into page points is THIS, never per-adapter corner math. */\n viewToPageRect(r: Rect): Rect;\n /** CSS `matrix()` mapping content space → this page's display box. Drop it on\n * a footprint-space layer (`transform`, `transform-origin: 0 0`) and place\n * children in content points — rotation + scale handled for free. */\n readonly cssMatrix: string;\n}\n\n/**\n * Build a page's transform from its intrinsic size + the platform/view scale.\n * `scale` is VIEW px per PDF point (the shell composes it: `viewUnitsPerPoint ×\n * contentScale × zoom`); `dpr` is device px per view px. Device dimensions snap\n * to the grid (crisp, no rotation fringe) and follow the engine's width rule\n * (box == bitmap, no reflow).\n */\nexport function pageTransform(input: {\n /** Un-rotated page size in PDF points. */\n pageSize: Size;\n rotation: PageRotation;\n /** View px per PDF point = viewUnitsPerPoint × contentScale × zoom. */\n scale: number;\n /**\n * View px per PDF point at 100% zoom (`viewUnitsPerPoint × userUnit`) — the\n * page's physical baseline, so `zoom = viewScale / baseScale` reads as\n * \"percent of Acrobat's 100%\". Default = `scale`, i.e. zoom ≈ 1: headless /\n * standalone callers stay neutral unless they declare a baseline.\n */\n baseScale?: number;\n /** Device px per view px (web: devicePixelRatio). */\n dpr: number;\n}): PageTransform {\n const { pageSize, rotation, scale, dpr } = input;\n\n // Raster: pin the width (snapped to the device grid), derive the height with\n // the engine's exact rule → uniform scale, integer device px, box == bitmap.\n const deviceWidth = Math.max(1, Math.round(pageSize.width * scale * dpr));\n const deviceHeight = deviceHeightForWidth(pageSize, deviceWidth);\n const renderScale = deviceWidth / pageSize.width;\n\n // The un-rotated content box in VIEW px, taken from the snapped device dims so\n // every edge lands on a whole device pixel. The effective view scale is derived\n // from it (not the raw `scale`) so `pageToView(pageWidth) === content edge`.\n const content: Size = { width: deviceWidth / dpr, height: deviceHeight / dpr };\n const viewScale = content.width / pageSize.width;\n const baseScale = input.baseScale ?? scale;\n const zoom = baseScale > 0 ? viewScale / baseScale : 1;\n\n const footprint = displaySize(content, rotation);\n\n // The two affines this page needs, as Mat2D — the matrix is the source of\n // truth; the methods and `cssMatrix` below are sugar over it (so they can\n // never drift).\n // content point (top-left, y-down) → content view px: pure isotropic scale.\n const contentMat = [viewScale, 0, 0, viewScale, 0, 0] as Mat2D;\n // content point → display-box view px: scale + the page's quarter-turn, from\n // the shared builder (the one quarter-turn encoding).\n const viewMat = rotateScaleMatrix(viewScale, content.width, content.height, rotation);\n const invMat = invert(viewMat);\n\n const pageToContent = (p: Point): Point => applyPoint(contentMat, p);\n const pageToView = (p: Point): Point => applyPoint(viewMat, p);\n const viewToPage = (p: Point): Point => applyPoint(invMat, p);\n const pageToViewRect = (r: Rect): Rect => applyRect(viewMat, r);\n const viewToPageRect = (r: Rect): Rect => applyRect(invMat, r);\n const cssMatrix = matrixToCss(viewMat);\n\n return {\n rotation,\n viewWidth: footprint.width,\n viewHeight: footprint.height,\n contentWidth: content.width,\n contentHeight: content.height,\n deviceWidth,\n deviceHeight,\n renderScale,\n viewScale,\n baseScale,\n zoom,\n pageToContent,\n pageToView,\n pageToViewRect,\n viewToPage,\n viewToPageRect,\n cssMatrix,\n };\n}\n\n/* ────────────────────────────────────────────────────────────────────────────\n * Matrix-native geometry — the composable primitive under every space hop.\n *\n * A coordinate-space conversion is a 2D affine `Mat2D = [a,b,c,d,e,f]` (the same\n * six numbers as CSS `matrix()`, `CGAffineTransform`, and Android `Matrix`):\n *\n * x' = a·x + c·y + e\n * y' = b·x + d·y + f\n *\n * Three generic appliers + `compose` + `invert` are the ENTIRE runtime — they\n * never grow as spaces/shapes/directions multiply, and they port 1:1 to Rust /\n * Swift / Kotlin (every target has a native affine). Inverses (hit-testing) and\n * screen composition fall out for free; there is no per-space hand-rolled y-flip\n * to drift between adapters.\n * ──────────────────────────────────────────────────────────────────────────── */\n\n/**\n * The coordinate spaces a viewer touches. `pdf` is the engine's PDF user space\n * (y-up, origin at the crop box bottom-left); the rest are viewer-local, y-down.\n */\nexport type Space = 'pdf' | 'content' | 'view' | 'screen';\n\n/**\n * Phantom space brand. It is OPTIONAL so plain `{ x, y }` / `{ x, y, w, h }`\n * literals stay assignable day-to-day (terse), but a value EXPLICITLY tagged\n * with the wrong space is rejected — and `Mat2D<From, To>` enforces the hop at\n * the matrix, so you cannot `applyRect` a `pdf` rect with a `content→view`\n * matrix. The brand is type-only; it carries no runtime field.\n */\ninterface SpaceBrand<S extends Space> {\n readonly __space?: S;\n}\n\n/** A point tagged with its coordinate space. */\nexport type PointIn<S extends Space> = Point & SpaceBrand<S>;\n/**\n * An axis-aligned rect tagged with its space, as min-corner + positive extent:\n * `(x, y)` is the corner with the smallest coordinates and `(x+width, y+height)`\n * the largest. In `pdf` space (y-up) that corner is bottom-left (`x=left`,\n * `y=bottom`); in the y-down viewer spaces it is top-left.\n */\nexport type RectIn<S extends Space> = Rect & SpaceBrand<S>;\n\n/**\n * Four POSITIONAL points (no corner semantics) — the viewer twin of the engine's\n * `PdfQuad`. Use this (via {@link applyQuad}) for rotatable/skewed content where\n * an axis-aligned rect would lie.\n */\nexport interface Quad {\n p1: Point;\n p2: Point;\n p3: Point;\n p4: Point;\n}\n/** A quad tagged with its coordinate space. */\nexport type QuadIn<S extends Space> = Quad & SpaceBrand<S>;\n\n/**\n * A 2D affine transform from space `From` to space `To`, stored as the six\n * numbers `[a, b, c, d, e, f]`. The phantom `From`/`To` make the compiler track\n * which spaces a matrix bridges, so composition and application can only be\n * wired up in the one correct order.\n */\nexport type Mat2D<From extends Space = Space, To extends Space = Space> = readonly [\n number,\n number,\n number,\n number,\n number,\n number,\n] & {\n readonly __from?: From;\n readonly __to?: To;\n};\n\n/** The identity transform within a single space. */\nexport function identity<S extends Space>(): Mat2D<S, S> {\n return [1, 0, 0, 1, 0, 0] as Mat2D<S, S>;\n}\n\n/**\n * Compose two matrices: `compose(m, n)` applies `n` first, then `m` (matrix\n * product `m · n`). The shared middle space `B` must line up, so the type system\n * rejects composing mismatched hops.\n */\nexport function compose<A extends Space, B extends Space, C extends Space>(\n m: Mat2D<B, C>,\n n: Mat2D<A, B>,\n): Mat2D<A, C> {\n const [a, b, c, d, e, f] = m;\n const [a2, b2, c2, d2, e2, f2] = n;\n return [\n a * a2 + c * b2,\n b * a2 + d * b2,\n a * c2 + c * d2,\n b * c2 + d * d2,\n a * e2 + c * f2 + e,\n b * e2 + d * f2 + f,\n ] as Mat2D<A, C>;\n}\n\n/** Invert a transform — `invert(pdfToView)` is `viewToPdf`, i.e. hit-testing for free. */\nexport function invert<F extends Space, T extends Space>(m: Mat2D<F, T>): Mat2D<T, F> {\n const [a, b, c, d, e, f] = m;\n const det = a * d - b * c;\n if (det === 0) throw new Error('Mat2D.invert: non-invertible matrix (det = 0)');\n const ia = d / det;\n const ib = -b / det;\n const ic = -c / det;\n const id = a / det;\n return [ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)] as Mat2D<T, F>;\n}\n\n/** Apply a transform to a point. */\nexport function applyPoint<F extends Space, T extends Space>(\n m: Mat2D<F, T>,\n p: PointIn<F>,\n): PointIn<T> {\n const [a, b, c, d, e, f] = m;\n return { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f } as PointIn<T>;\n}\n\n/**\n * Apply a transform to a rect, returning the axis-aligned bounding box of the\n * four transformed corners. EXACT for translate/scale/quarter-turn (every page\n * transform `pageGeometry` produces); lossy under skew — use {@link applyQuad}\n * for content that can be rotated off-axis.\n */\nexport function applyRect<F extends Space, T extends Space>(\n m: Mat2D<F, T>,\n r: RectIn<F>,\n): RectIn<T> {\n const c0 = applyPoint(m, { x: r.x, y: r.y } as PointIn<F>);\n const c1 = applyPoint(m, { x: r.x + r.width, y: r.y } as PointIn<F>);\n const c2 = applyPoint(m, { x: r.x, y: r.y + r.height } as PointIn<F>);\n const c3 = applyPoint(m, { x: r.x + r.width, y: r.y + r.height } as PointIn<F>);\n const xs = [c0.x, c1.x, c2.x, c3.x];\n const ys = [c0.y, c1.y, c2.y, c3.y];\n const minX = Math.min(...xs);\n const minY = Math.min(...ys);\n return {\n x: minX,\n y: minY,\n width: Math.max(...xs) - minX,\n height: Math.max(...ys) - minY,\n } as RectIn<T>;\n}\n\n/** Apply a transform to a quad, preserving orientation (maps the four points). */\nexport function applyQuad<F extends Space, T extends Space>(\n m: Mat2D<F, T>,\n q: QuadIn<F>,\n): QuadIn<T> {\n return {\n p1: applyPoint(m, q.p1 as PointIn<F>),\n p2: applyPoint(m, q.p2 as PointIn<F>),\n p3: applyPoint(m, q.p3 as PointIn<F>),\n p4: applyPoint(m, q.p4 as PointIn<F>),\n } as QuadIn<T>;\n}\n\n/**\n * A `Mat2D` IS a CSS `matrix()` — the six numbers are identical. Drop the result\n * on a footprint-space layer (`transform`, `transform-origin: 0 0`) and place\n * children in the source space; the rotation + scale are handled for free.\n */\nexport function matrixToCss(m: Mat2D): string {\n const [a, b, c, d, e, f] = m;\n return `matrix(${a}, ${b}, ${c}, ${d}, ${e}, ${f})`;\n}\n\n/* ────────────────────────────────────────────────────────────────────────────\n * Same-space affine builders — generic, free-angle transforms WITHIN one space\n * (`Mat2D<S, S>`). The `rotateScaleMatrix` above is a quarter-turn, cross-space\n * builder for page layout; these are the arbitrary-angle primitives content\n * editing (annotation rotation/scale, future stamps/skew) composes from. They\n * never know about annotations — they are the bottom-of-the-pyramid matrix math,\n * so it isn't hand-rolled (and drift) in every plugin.\n *\n * Convention: a viewer content space is y-DOWN, so `rotate(rad)` —\n * `[cos, sin, -sin, cos, 0, 0]` — turns CLOCKWISE on screen (matching the\n * viewer's page-rotation direction). The PDF (y-up) flip, when one is needed,\n * is a separate hop applied once at the engine boundary.\n * ──────────────────────────────────────────────────────────────────────────── */\n\n/** Translate within a space. */\nexport function translate<S extends Space>(tx: number, ty: number): Mat2D<S, S> {\n return [1, 0, 0, 1, tx, ty] as Mat2D<S, S>;\n}\n\n/** Scale about the space origin. */\nexport function scale<S extends Space>(sx: number, sy: number): Mat2D<S, S> {\n return [sx, 0, 0, sy, 0, 0] as Mat2D<S, S>;\n}\n\n/** Rotate about the space origin (radians; clockwise in y-down content space). */\nexport function rotate<S extends Space>(rad: number): Mat2D<S, S> {\n const c = Math.cos(rad);\n const s = Math.sin(rad);\n return [c, s, -s, c, 0, 0] as Mat2D<S, S>;\n}\n\n/** Rotate about an arbitrary pivot: `T(c) · R(rad) · T(-c)`. */\nexport function rotateAbout<S extends Space>(c: PointIn<S>, rad: number): Mat2D<S, S> {\n return compose(translate<S>(c.x, c.y), compose(rotate<S>(rad), translate<S>(-c.x, -c.y)));\n}\n\n/** Scale about an arbitrary anchor: `T(a) · S(sx, sy) · T(-a)`. */\nexport function scaleAbout<S extends Space>(a: PointIn<S>, sx: number, sy: number): Mat2D<S, S> {\n return compose(translate<S>(a.x, a.y), compose(scale<S>(sx, sy), translate<S>(-a.x, -a.y)));\n}\n\n/** The rotation angle (radians) encoded in a matrix — `atan2(b, a)`. Positive is\n * clockwise in y-down content space (the inverse of {@link rotate}). */\nexport function angleOf(m: Mat2D): number {\n return Math.atan2(m[1], m[0]);\n}\n\n/**\n * The page's scale + integer quarter-turn as a `Mat2D`: a content point maps to\n * its place in the rotated DISPLAY box. `scale` is output units per content\n * point; `boxW`/`boxH` are the UN-rotated content's extents in those same output\n * units, and the offsets keep the footprint in the box's positive quadrant\n * (origin at the box top-left).\n *\n * THE single encoding of the quarter-turn — `pageTransform` (view px),\n * `pageGeometry` (the `content→view` hop), and `pageToWorld` (world units) all\n * build on this one function, so the rotation can never drift between them.\n */\nexport function rotateScaleMatrix(\n scale: number,\n boxW: number,\n boxH: number,\n rotation: PageRotation,\n): Mat2D {\n switch (rotation) {\n case 90:\n return [0, scale, -scale, 0, boxH, 0] as Mat2D;\n case 180:\n return [-scale, 0, 0, -scale, boxW, boxH] as Mat2D;\n case 270:\n return [0, -scale, scale, 0, 0, boxW] as Mat2D;\n default:\n return [scale, 0, 0, scale, 0, 0] as Mat2D;\n }\n}\n\n/**\n * The per-page geometry input. Structurally a subset of the engine's\n * `PageLayout` (so a layout can be passed straight in), but defined here to keep\n * this package dependency-free — the same reason {@link PageRotation} is a\n * structural twin of the engine's rotation.\n */\nexport interface PageGeometryInput {\n /** Effective crop box in PDF user space (y-up edges); origin preserved, so\n * `left`/`bottom` may be non-zero or negative. */\n crop: { left: number; bottom: number; right: number; top: number };\n /** Persistent page rotation (the document's `/Rotate`). */\n rotation: PageRotation;\n /** PDF `userUnit` (§14.11.6): scales PDF points into the layout. 1 for most docs. */\n userUnit: number;\n}\n\n/** The matrices bridging one page's spaces — every other matrix composes from these. */\nexport interface PageGeometry {\n /** PDF user space (y-up, crop-relative) → content space (y-down, crop top-left, unscaled points). */\n readonly pdfToContent: Mat2D<'pdf', 'content'>;\n /** Content → view: scale (zoom × userUnit) + the page's quarter-turn rotation. */\n readonly contentToView: Mat2D<'content', 'view'>;\n /** PDF → view, precomposed. */\n readonly pdfToView: Mat2D<'pdf', 'view'>;\n /** View → PDF, the inverse — hit-testing for free. */\n readonly viewToPdf: Mat2D<'view', 'pdf'>;\n}\n\n/**\n * PDF user space (y-up, origin = crop bottom-left) → content space (y-down,\n * origin = crop top-left, unscaled points). THE single encoding of the engine→\n * content y-flip + crop offset: `pageGeometry` composes its `pdfToContent` from\n * this, and pure annotation geometry (content-space editing) reuses it too, so\n * the rule can never be hand-written twice and drift.\n */\nexport function pdfToContentMatrix(crop: { left: number; top: number }): Mat2D<'pdf', 'content'> {\n return [1, 0, 0, -1, -crop.left, crop.top] as Mat2D<'pdf', 'content'>;\n}\n\n/**\n * Build a page's space matrices from its crop box, rotation, and `userUnit` plus\n * the viewer `zoom`. This is the ONE function that knows the y-flip, crop origin,\n * `userUnit`, and rotation; everything else composes from its output. The engine\n * never emits these — they bake in viewer state (zoom, later scroll/dpr) — so the\n * boundary stays clean: engine owns `Pdf*` truth, the viewer composes the rest.\n */\nexport function pageGeometry(input: PageGeometryInput, zoom: number): PageGeometry {\n const { crop, rotation, userUnit } = input;\n const s = zoom * userUnit; // view px per PDF point — userUnit folded in HERE, once\n\n // PDF user space (y-up, origin = crop bottom-left) → content (y-down, origin = crop top-left).\n const pdfToContent = pdfToContentMatrix(crop);\n\n // Content → view: scale + integer quarter-turn, from the shared builder (the\n // one quarter-turn encoding). `Wc`/`Hc` are the unrotated content's view-px\n // extents (the builder places the footprint in the box's positive quadrant).\n const Wc = (crop.right - crop.left) * s;\n const Hc = (crop.top - crop.bottom) * s;\n const contentToView = rotateScaleMatrix(s, Wc, Hc, rotation) as Mat2D<'content', 'view'>;\n\n const pdfToView = compose(contentToView, pdfToContent);\n return { pdfToContent, contentToView, pdfToView, viewToPdf: invert(pdfToView) };\n}\n"],"mappings":";;;;;;;AAkCA,SAAgB,cAAc,OAAqC;CACjE,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,IAAI,KAAK;CACT,IAAI,KAAK;CACT,IAAI,KAAK;CACT,IAAI,KAAK;CACT,KAAK,MAAM,KAAK,OAAO;EACrB,KAAK,KAAK,IAAI,IAAI,EAAE,CAAC;EACrB,KAAK,KAAK,IAAI,IAAI,EAAE,CAAC;EACrB,KAAK,KAAK,IAAI,IAAI,EAAE,IAAI,EAAE,KAAK;EAC/B,KAAK,KAAK,IAAI,IAAI,EAAE,IAAI,EAAE,MAAM;CAClC;CACA,OAAO;EAAE,GAAG;EAAI,GAAG;EAAI,OAAO,KAAK;EAAI,QAAQ,KA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