@laminapdf/viewer 0.2.0-alpha.5 → 0.2.0-alpha.6

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 (91) hide show
  1. package/README.md +43 -2
  2. package/dist/client.d.ts +33 -2
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +138 -19
  5. package/dist/client.js.map +1 -1
  6. package/dist/edit/session.d.ts +91 -0
  7. package/dist/edit/session.d.ts.map +1 -0
  8. package/dist/edit/session.js +179 -0
  9. package/dist/edit/session.js.map +1 -0
  10. package/dist/edit-log.d.ts +32 -0
  11. package/dist/edit-log.d.ts.map +1 -0
  12. package/dist/edit-log.js +74 -0
  13. package/dist/edit-log.js.map +1 -0
  14. package/dist/find/controller.d.ts +6 -0
  15. package/dist/find/controller.d.ts.map +1 -1
  16. package/dist/find/controller.js +69 -2
  17. package/dist/find/controller.js.map +1 -1
  18. package/dist/history/history.d.ts +9 -0
  19. package/dist/history/history.d.ts.map +1 -1
  20. package/dist/history/history.js.map +1 -1
  21. package/dist/index.d.ts +8 -5
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +2 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/layers/link-layer.d.ts +33 -0
  26. package/dist/layers/link-layer.d.ts.map +1 -1
  27. package/dist/layers/link-layer.js +251 -3
  28. package/dist/layers/link-layer.js.map +1 -1
  29. package/dist/layers/link-preview.d.ts +77 -0
  30. package/dist/layers/link-preview.d.ts.map +1 -0
  31. package/dist/layers/link-preview.js +202 -0
  32. package/dist/layers/link-preview.js.map +1 -0
  33. package/dist/layers/text-layer.d.ts +7 -3
  34. package/dist/layers/text-layer.d.ts.map +1 -1
  35. package/dist/layers/text-layer.js +3 -5
  36. package/dist/layers/text-layer.js.map +1 -1
  37. package/dist/layout/page-layout.d.ts +7 -0
  38. package/dist/layout/page-layout.d.ts.map +1 -1
  39. package/dist/layout/page-layout.js +15 -0
  40. package/dist/layout/page-layout.js.map +1 -1
  41. package/dist/protocol.d.ts +119 -1
  42. package/dist/protocol.d.ts.map +1 -1
  43. package/dist/protocol.js +17 -2
  44. package/dist/protocol.js.map +1 -1
  45. package/dist/thumbnails/strip.d.ts.map +1 -1
  46. package/dist/thumbnails/strip.js +34 -1
  47. package/dist/thumbnails/strip.js.map +1 -1
  48. package/dist/view/previews.d.ts +47 -0
  49. package/dist/view/previews.d.ts.map +1 -0
  50. package/dist/view/previews.js +97 -0
  51. package/dist/view/previews.js.map +1 -0
  52. package/dist/view/viewer.d.ts +84 -6
  53. package/dist/view/viewer.d.ts.map +1 -1
  54. package/dist/view/viewer.js +344 -12
  55. package/dist/view/viewer.js.map +1 -1
  56. package/dist/worker/document.d.ts +43 -5
  57. package/dist/worker/document.d.ts.map +1 -1
  58. package/dist/worker/document.js +72 -2
  59. package/dist/worker/document.js.map +1 -1
  60. package/dist/worker/edit.d.ts +35 -0
  61. package/dist/worker/edit.d.ts.map +1 -0
  62. package/dist/worker/edit.js +305 -0
  63. package/dist/worker/edit.js.map +1 -0
  64. package/dist/worker/find.d.ts +2 -2
  65. package/dist/worker/find.d.ts.map +1 -1
  66. package/dist/worker/find.js +3 -3
  67. package/dist/worker/find.js.map +1 -1
  68. package/dist/worker/fingerprint.d.ts +10 -0
  69. package/dist/worker/fingerprint.d.ts.map +1 -0
  70. package/dist/worker/fingerprint.js +42 -0
  71. package/dist/worker/fingerprint.js.map +1 -0
  72. package/dist/worker/methods.d.ts.map +1 -1
  73. package/dist/worker/methods.js +19 -0
  74. package/dist/worker/methods.js.map +1 -1
  75. package/dist/worker/navigation.d.ts +2 -2
  76. package/dist/worker/navigation.d.ts.map +1 -1
  77. package/dist/worker/navigation.js +3 -3
  78. package/dist/worker/navigation.js.map +1 -1
  79. package/dist/worker/recent-pages.d.ts +2 -0
  80. package/dist/worker/recent-pages.d.ts.map +1 -1
  81. package/dist/worker/recent-pages.js +15 -0
  82. package/dist/worker/recent-pages.js.map +1 -1
  83. package/dist/worker/session.d.ts +59 -0
  84. package/dist/worker/session.d.ts.map +1 -0
  85. package/dist/worker/session.js +152 -0
  86. package/dist/worker/session.js.map +1 -0
  87. package/dist/worker/text.d.ts +2 -2
  88. package/dist/worker/text.d.ts.map +1 -1
  89. package/dist/worker/text.js +5 -4
  90. package/dist/worker/text.js.map +1 -1
  91. package/package.json +8 -8
@@ -11,14 +11,15 @@
11
11
  import { pagePixels } from "@laminapdf/render";
12
12
  import { BitmapCache } from "../canvas/cache.js";
13
13
  import { CanvasPool } from "../canvas/pool.js";
14
+ import { EditSession } from "../edit/session.js";
14
15
  import { FindController } from "../find/controller.js";
15
- import { NavigationHistory } from "../history/history.js";
16
+ import { NavigationHistory, } from "../history/history.js";
16
17
  import { HighlightLayer } from "../layers/highlight-layer.js";
17
18
  import { LinkLayer } from "../layers/link-layer.js";
18
19
  import { TextLayer } from "../layers/text-layer.js";
19
- import { isRotation, PageLayout, rotated } from "../layout/page-layout.js";
20
+ import { isRotation, keptTop, PageLayout, rotated } from "../layout/page-layout.js";
20
21
  import { range } from "../layout/range.js";
21
- import { appearanceField, appearanceKey, renderKey, renderKeyFields, } from "../protocol.js";
22
+ import { appearanceField, appearanceKey, renderKeyFields, viewKey, } from "../protocol.js";
22
23
  import { backdropRatio, bounds, contains, lowScale, sharpScale, tilesFor } from "../render/tiles.js";
23
24
  import { destinationView } from "../zoom/destination.js";
24
25
  import { contentPosition, percentOfScale, pointAt, scaleFor, scrollToPoint, } from "../zoom/zoom.js";
@@ -82,6 +83,9 @@ export class Viewer {
82
83
  #highlights;
83
84
  /** The link layer, unless `links: false`. */
84
85
  #links;
86
+ /** The link previews' pictures, loaded with their code on the first preview (not at startup). */
87
+ #previews;
88
+ #loadingPreviews;
85
89
  /** Find in this viewer's document: query, options, matches, next and previous. */
86
90
  find;
87
91
  /**
@@ -89,6 +93,11 @@ export class Viewer {
89
93
  * `jumpToDestination` and find's matches record a jump; scrolling doesn't.
90
94
  */
91
95
  history;
96
+ /**
97
+ * The open document's edit session: its history, and edits, undo, redo and going to a step,
98
+ * each redrawing the pages it touched. One call runs at a time, in the order they were made.
99
+ */
100
+ edits;
92
101
  /** Pages kept mounted whatever the scroll (`keepMounted`): those a selection touches. */
93
102
  #pinned = new Set();
94
103
  #regions;
@@ -99,11 +108,21 @@ export class Viewer {
99
108
  #listeners = new Set();
100
109
  #events = new Map();
101
110
  #cleanup = [];
102
- #document;
111
+ /** The open document's ID (renders name it), or undefined before one opens. */
112
+ #documentId;
113
+ /** Counts `open`s: an edit answered for a document since replaced redraws nothing. */
114
+ #opens = 0;
103
115
  #sizes = [];
116
+ /** Each edited page's revision (`invalidate` bumps it), part of its bitmaps' cache keys. */
117
+ #revisions = new Map();
104
118
  #layout;
105
119
  #zoom;
106
120
  #rotation = 0;
121
+ /**
122
+ * Where the view goes once it has a size, when it was opened or restored without one (a hidden
123
+ * host ignores scrolling): the top of a new document, or a kept position.
124
+ */
125
+ #pending;
107
126
  #state;
108
127
  #frame;
109
128
  #settling;
@@ -173,6 +192,27 @@ export class Viewer {
173
192
  });
174
193
  this.addLayer(this.#highlights);
175
194
  this.#links = this.#linkLayer(options.links);
195
+ this.edits = this.#editSession();
196
+ }
197
+ /**
198
+ * The edit session over this view's calls, which follows a restarted worker: its replay tells
199
+ * the session its history (`edit`), and lost edits leave it empty.
200
+ */
201
+ #editSession() {
202
+ const edits = new EditSession({
203
+ applyEdit: (ops, call) => this.applyEdit(ops, call),
204
+ undoEdit: () => this.#editCall(() => this.#client.undoEdit()),
205
+ redoEdit: () => this.#editCall(() => this.#client.redoEdit()),
206
+ goToStep: (position) => this.#editCall(() => this.#client.goToStep(position)),
207
+ editHistory: () => this.#client.editHistory(),
208
+ });
209
+ this.#cleanup.push(this.#client.on("restarted", ({ reopened, edits: replay }) => {
210
+ if (reopened)
211
+ this.#reopened();
212
+ if (replay === "lost")
213
+ edits.reset(this.#client.document);
214
+ }), this.#client.on("edit", ({ history }) => edits.follow(history)));
215
+ return edits;
176
216
  }
177
217
  /** The scroll container (append it, or use {@link mount}). */
178
218
  get element() {
@@ -187,16 +227,22 @@ export class Viewer {
187
227
  open(document) {
188
228
  this.#unmountAll();
189
229
  this.#cache.clear();
190
- this.#document = document;
230
+ this.#previews?.clear();
231
+ this.#documentId = document.id;
232
+ this.#opens++;
233
+ this.#revisions = new Map();
191
234
  this.#pinned = new Set();
192
235
  this.#focusTarget = undefined;
193
236
  this.find.reset();
194
237
  this.history.reset();
195
- this.#text?.open(document);
238
+ this.edits.reset(document);
239
+ this.#text?.open();
196
240
  this.#sizes = document.pages.map((p) => ({ width: p.width, height: p.height }));
197
241
  this.#layout = undefined;
198
242
  this.#root.scrollTop = 0;
199
243
  this.#root.scrollLeft = 0;
244
+ // A hidden view keeps its old scroll: the new document starts at its top once it shows.
245
+ this.#pending = this.#sized() ? undefined : "top";
200
246
  this.#relayout(this.#viewport());
201
247
  this.#schedule();
202
248
  }
@@ -353,9 +399,153 @@ export class Viewer {
353
399
  this.#releaseCanvas(view);
354
400
  }
355
401
  }
402
+ this.#previews?.clear();
356
403
  this.#setState({ appearance });
357
404
  this.#schedule();
358
405
  }
406
+ /**
407
+ * Where `target` goes, as a picture for a link preview (R07): one render of the region around its
408
+ * point (or the top of its page) through the document worker, and the text of the lines it shows.
409
+ * The viewer keeps the last few (`PREVIEW_CACHE`) and closes them on a zoom, rotation or
410
+ * appearance change and when the document closes, so draw the bitmap at once and never close it.
411
+ * Rejects with `AbortError` when `signal` aborts or the pictures are cleared while it draws.
412
+ */
413
+ preview(target, options = {}) {
414
+ return this.#linkPreviews().then((previews) => previews.picture(target, options.signal ?? new AbortController().signal));
415
+ }
416
+ /** The pointer is over the link preview (`true`) or has left it: a hovered preview stays (WCAG 1.4.13). */
417
+ holdLinkPreview(held) {
418
+ this.#links?.hold(held);
419
+ }
420
+ /** Escape or Close on the link preview: it goes, and stays hidden until its link is left. */
421
+ dismissLinkPreview() {
422
+ this.#links?.dismiss();
423
+ }
424
+ /** Whether a link is previewed or focused, so {@link followLinkPreview} has one (`nav.follow-link`). */
425
+ canFollowLink() {
426
+ return this.#links?.canFollow() ?? false;
427
+ }
428
+ /** Follows the previewed link, else the focused one (`nav.follow-link`); `false` when there is neither. */
429
+ followLinkPreview() {
430
+ return this.#links?.follow() ?? false;
431
+ }
432
+ /**
433
+ * Draws `pages` again: an edit changed them. Their bitmaps go, here and in a thumbnail strip,
434
+ * and their layers read their text and links again; every other page keeps what it drew.
435
+ * `sizes` gives the pages whose displayed size in points changed (a quarter turn swaps width and
436
+ * height): the layout takes them, and the page at the top of the viewport stays there. A page in
437
+ * view keeps its old pixels until the new ones are drawn over them.
438
+ */
439
+ invalidate(pages, sizes) {
440
+ const count = this.#sizes.length;
441
+ const changed = new Set([...pages, ...(sizes?.keys() ?? [])].filter((p) => Number.isInteger(p) && p >= 0 && p < count));
442
+ if (changed.size === 0)
443
+ return;
444
+ const resized = new Set();
445
+ for (const [page, size] of sizes ?? []) {
446
+ const old = this.#sizes[page];
447
+ if (old === undefined || (old.width === size.width && old.height === size.height))
448
+ continue;
449
+ this.#sizes[page] = { width: size.width, height: size.height };
450
+ resized.add(page);
451
+ }
452
+ for (const page of changed) {
453
+ this.#revisions.set(page, (this.#revisions.get(page) ?? 0) + 1);
454
+ this.#cache.prune(page, () => false);
455
+ }
456
+ if (resized.size > 0)
457
+ this.#resize();
458
+ const { first, last } = this.#state.visibleRange;
459
+ for (const page of changed) {
460
+ const view = this.#pages.get(page);
461
+ if (view === undefined)
462
+ continue;
463
+ this.#redraw(view, resized.has(page) || page < first || page > last);
464
+ this.#remountLayers(view);
465
+ }
466
+ this.find.refresh([...changed]);
467
+ const list = [...changed].sort((a, b) => a - b);
468
+ this.#emit("invalidate", { pages: list.map((index) => ({ index, ...this.#sizes[index] })) });
469
+ this.#emit("renderstats", this.stats());
470
+ this.#schedule();
471
+ }
472
+ /**
473
+ * Applies `ops` to the open document through the client (`ViewerClient.applyEdit`) and redraws
474
+ * the pages they touched ({@link invalidate}): an edit on screen in one call. A failed edit
475
+ * changes nothing and redraws nothing.
476
+ */
477
+ applyEdit(ops, options) {
478
+ return this.#editCall(() => this.#client.applyEdit(ops, options));
479
+ }
480
+ /** Runs an edit session call and redraws the pages it touched, unless another document opened meanwhile. */
481
+ async #editCall(call) {
482
+ const opens = this.#opens;
483
+ const result = await call();
484
+ // Another document opened meanwhile: these pages aren't its pages.
485
+ if (this.#opens === opens) {
486
+ this.invalidate(result.pages.map((page) => page.index), new Map(result.pages.map((page) => [page.index, page])));
487
+ }
488
+ return result;
489
+ }
490
+ /**
491
+ * Every page's displayed size in points, as the view lays it out: the sizes the document opened
492
+ * with, and those edits gave since (`invalidate`). A thumbnail strip lays its pages out from it.
493
+ * With `documentId`, empty unless the view shows that document: a page count alone can't tell two
494
+ * documents apart.
495
+ */
496
+ pageSizes(documentId) {
497
+ if (documentId !== undefined && documentId !== this.#documentId)
498
+ return [];
499
+ return this.#sizes;
500
+ }
501
+ /**
502
+ * Where the reader is: the document point a gap below the viewport's top-left, the zoom and the
503
+ * rotation; `undefined` without a document. {@link restore} puts the view back there.
504
+ */
505
+ viewPosition() {
506
+ const pending = this.#pending;
507
+ if (pending === "top" && this.#sizes.length > 0) {
508
+ return { point: { page: 0, x: 0, y: 0 }, zoom: this.#zoom, rotation: this.#rotation };
509
+ }
510
+ if (pending !== undefined && pending !== "top")
511
+ return pending;
512
+ const place = this.#place();
513
+ return place === undefined ? undefined : { ...place, rotation: this.#rotation };
514
+ }
515
+ /**
516
+ * Puts the view at `position` (a {@link viewPosition} kept from an earlier visit), as a history
517
+ * jump from where the view is, so Back returns there. Its page is clamped to the document's and
518
+ * its point to the page. Called in the task that opened the document, before the next frame, it
519
+ * paints no other page first.
520
+ */
521
+ restore(position) {
522
+ if (this.#layout === undefined || this.#sizes.length === 0)
523
+ return;
524
+ // Hidden: it takes place once the view has a size (`#listenResize`).
525
+ if (!this.#sized()) {
526
+ const page = Math.min(this.#sizes.length - 1, Math.max(0, Math.trunc(position.point.page) || 0));
527
+ this.#pending = { ...position, point: { ...position.point, page } };
528
+ return;
529
+ }
530
+ this.#pending = undefined;
531
+ this.history.jump(() => {
532
+ const turned = isRotation(position.rotation) && position.rotation !== this.#rotation;
533
+ if (turned)
534
+ this.#rotation = position.rotation;
535
+ const clamp = (v) => (Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : 0);
536
+ const page = Math.min(this.#sizes.length - 1, Math.max(0, Math.trunc(position.point.page) || 0));
537
+ // The zoom is set before the scroll: #show only rezooms when the zoom changes.
538
+ this.#zoom = position.zoom;
539
+ this.#rezoom(undefined);
540
+ this.#show({ point: { page, x: clamp(position.point.x), y: clamp(position.point.y) }, zoom: position.zoom });
541
+ // As rotate() does: the layers follow once the pages are laid out for the new rotation.
542
+ if (turned) {
543
+ this.#text?.refresh();
544
+ this.#highlights.refresh();
545
+ this.#links?.refresh();
546
+ }
547
+ });
548
+ }
359
549
  /** The document point at viewport position (`x`, `y`) in CSS px. */
360
550
  pointAt(x, y) {
361
551
  const layout = this.#layout;
@@ -388,6 +578,7 @@ export class Viewer {
388
578
  dropped: this.#dropped,
389
579
  aborted: this.#aborted,
390
580
  cacheBytes: this.#cache.bytes,
581
+ previewBitmaps: this.#previews?.size ?? 0,
391
582
  pages,
392
583
  };
393
584
  }
@@ -399,6 +590,7 @@ export class Viewer {
399
590
  clearTimeout(this.#settling);
400
591
  this.#unmountAll();
401
592
  this.#cache.clear();
593
+ this.#previews?.clear();
402
594
  this.find.reset();
403
595
  this.#text?.destroy();
404
596
  this.#links?.destroy();
@@ -407,6 +599,24 @@ export class Viewer {
407
599
  this.#root.remove();
408
600
  }
409
601
  // --- internals ---
602
+ /**
603
+ * The link previews' pictures, drawn at this viewer's zoom, rotation and appearance. Their code
604
+ * loads on the first preview, so the reader's startup script doesn't carry it.
605
+ */
606
+ #linkPreviews() {
607
+ this.#loadingPreviews ??= import("./previews.js").then(({ LinkPreviews }) => {
608
+ this.#previews = new LinkPreviews({
609
+ client: this.#client,
610
+ size: (page) => this.#sizes[page],
611
+ rotation: () => this.#rotation,
612
+ percent: () => this.#state.percent,
613
+ appearance: () => this.#state.appearance,
614
+ dpr: () => this.#dpr(),
615
+ });
616
+ return this.#previews;
617
+ });
618
+ return this.#loadingPreviews;
619
+ }
410
620
  /** The link layer, added to every page, unless `links` is `false`. */
411
621
  #linkLayer(links) {
412
622
  if (links === false)
@@ -419,6 +629,8 @@ export class Viewer {
419
629
  pageCount: () => this.#sizes.length,
420
630
  goTo: (target) => this.jumpToDestination(target),
421
631
  goToPage: (page) => this.jumpToPage(page),
632
+ preview: (request) => this.#emit("linkpreview", request),
633
+ previewEnd: (anchor) => this.#emit("linkpreviewend", { anchor }),
422
634
  }, links === true || links === undefined ? {} : links);
423
635
  this.addLayer(layer);
424
636
  return layer;
@@ -486,12 +698,104 @@ export class Viewer {
486
698
  }
487
699
  this.#schedule();
488
700
  }
701
+ /**
702
+ * The worker restarted and opened the file again as it was, without the edits: the edited pages
703
+ * take their sizes from it and draw again (at a new revision, so no bitmap of theirs is reused).
704
+ */
705
+ #reopened() {
706
+ const document = this.#client.document;
707
+ if (document === undefined || document.pages.length !== this.#sizes.length)
708
+ return;
709
+ this.#documentId = document.id;
710
+ const edited = [...this.#revisions.keys()];
711
+ const sizes = new Map(edited.map((index) => [index, document.pages[index]]));
712
+ this.invalidate(edited, sizes);
713
+ }
714
+ /**
715
+ * Lays the pages out again after some changed size, keeping the page at the viewport's top where
716
+ * it is (scaled into its new height, if it is one that changed). A fixed zoom stays; a fit mode
717
+ * fits again, since a page turned a quarter can be wider than the window at the old scale.
718
+ */
719
+ #resize() {
720
+ const before = this.#layout;
721
+ if (before === undefined)
722
+ return;
723
+ const viewport = this.#viewport();
724
+ const scale = typeof this.#zoom === "string"
725
+ ? scaleFor(this.#zoom, this.#reference(), this.#rotation, viewport, this.#gap)
726
+ : before.scale;
727
+ const after = new PageLayout(this.#sizes, { scale, rotation: before.rotation, gap: this.#gap });
728
+ if (after.height > MAX_HEIGHT) {
729
+ // Past what browsers can scroll: the zoom is capped again.
730
+ this.#rezoom(undefined);
731
+ return;
732
+ }
733
+ const top = keptTop(before, after, this.#root.scrollTop);
734
+ this.#layout = after;
735
+ this.#spacer.style.height = `${after.height}px`;
736
+ this.#spacer.style.width = `${after.contentWidth(viewport.width)}px`;
737
+ this.#root.scrollTop = top;
738
+ if (scale !== before.scale) {
739
+ const percent = percentOfScale(scale);
740
+ this.#setState({ zoom: this.#zoom, percent });
741
+ this.#emit("zoomchange", { zoom: this.#zoom, percent });
742
+ this.#staleRenders();
743
+ }
744
+ }
745
+ /**
746
+ * Makes `view` draw its page again: its renders aborted (a late one is dropped), its tiles
747
+ * forgotten. A page in view at its old size keeps its pixels, and sharp tiles replace them; a
748
+ * page that changed size, or one outside the view, paints its quick pass first.
749
+ */
750
+ #redraw(view, repaint) {
751
+ this.#abort(view);
752
+ view.waiting = false;
753
+ view.tiles.clear();
754
+ // A page whose render failed tries again from the start.
755
+ if (repaint || view.state === "error") {
756
+ this.#releaseDetail(view);
757
+ view.painted = "";
758
+ view.state = "placeholder";
759
+ }
760
+ else {
761
+ view.detail?.tiles.clear();
762
+ if (view.state !== "placeholder")
763
+ view.state = "low";
764
+ }
765
+ }
766
+ /** Mounts `view`'s layers again, so they read its text and links again, at its size now. */
767
+ #remountLayers(view) {
768
+ const size = { width: this.#layout?.widths[view.index] ?? 0, height: this.#layout?.heights[view.index] ?? 0 };
769
+ for (const layer of this.#layers) {
770
+ const slot = this.#slot(view, layer.name);
771
+ layer.onUnmount?.(view.index, slot);
772
+ layer.onMount?.(view.index, slot);
773
+ layer.onZoom?.(view.index, slot, size);
774
+ }
775
+ }
489
776
  #scroll() {
490
777
  return { left: this.#root.scrollLeft, top: this.#root.scrollTop };
491
778
  }
492
779
  #viewport() {
493
780
  return { width: this.#root.clientWidth || 800, height: this.#root.clientHeight || 600 };
494
781
  }
782
+ /** Whether the view has a size (it is in a shown container), so it can scroll. */
783
+ #sized() {
784
+ return this.#root.clientWidth > 0 && this.#root.clientHeight > 0;
785
+ }
786
+ /** Puts a view that just got its size where it was opened or restored to. */
787
+ #showPending(pending) {
788
+ this.#pending = undefined;
789
+ this.#relayout(this.#viewport());
790
+ // The scroll kept while hidden is the last document's: the top first, so a restore's history
791
+ // jump leaves from page 1.
792
+ this.#root.scrollTop = 0;
793
+ this.#root.scrollLeft = 0;
794
+ if (pending === "top")
795
+ this.#schedule();
796
+ else
797
+ this.restore(pending);
798
+ }
495
799
  /** The text layer `option` asks for, or none (`false`); it reports the selection as an event too. */
496
800
  #textLayer(option) {
497
801
  if (option === false)
@@ -500,6 +804,7 @@ export class Viewer {
500
804
  root: this.#root,
501
805
  client: this.#client,
502
806
  rotation: () => this.#rotation,
807
+ points: (page) => this.#sizes[page],
503
808
  keepMounted: (pages) => this.keepMounted(pages),
504
809
  };
505
810
  const textOptions = option === true || option === undefined ? {} : option;
@@ -545,6 +850,8 @@ export class Viewer {
545
850
  this.#spacer.style.height = `${layout.height}px`;
546
851
  this.#spacer.style.width = `${layout.contentWidth(viewport.width)}px`;
547
852
  if (zoomed) {
853
+ // Pictures drawn at the old zoom or rotation would show the wrong size or turn.
854
+ this.#previews?.clear();
548
855
  const percent = percentOfScale(layout.scale);
549
856
  this.#setState({ pageCount: layout.pageCount, zoom: this.#zoom, percent, rotation: this.#rotation });
550
857
  this.#emit("zoomchange", { zoom: this.#zoom, percent });
@@ -565,8 +872,13 @@ export class Viewer {
565
872
  const scroll = scrollToPoint(after, viewport.width, point, at);
566
873
  this.#root.scrollTop = scroll.top;
567
874
  this.#root.scrollLeft = scroll.left;
568
- // Renders for the old geometry are stale: abort them (a page that failed gets another try);
569
- // the canvases stretch until the gesture settles and the new pass paints, so no page is sharp.
875
+ this.#staleRenders();
876
+ }
877
+ /**
878
+ * Renders for the old geometry are stale: abort them (a page that failed gets another try); the
879
+ * canvases stretch until the zoom settles and the new pass paints, so no page is sharp.
880
+ */
881
+ #staleRenders() {
570
882
  let unsharpened = false;
571
883
  for (const view of this.#pages.values()) {
572
884
  this.#abort(view);
@@ -593,7 +905,9 @@ export class Viewer {
593
905
  return;
594
906
  this.#frame = requestAnimationFrame(() => {
595
907
  this.#frame = undefined;
596
- this.#update();
908
+ // A view waiting for its size has only an old scroll to go by: it draws once it is placed.
909
+ if (this.#pending === undefined)
910
+ this.#update();
597
911
  });
598
912
  }
599
913
  /** The mounted range: visible ± margin pages, and at least a viewport above and below. */
@@ -815,7 +1129,11 @@ export class Viewer {
815
1129
  /** The tile `clip` of page `index` at `scale`: its render request and cache key. */
816
1130
  #tile(index, layout, scale, clip) {
817
1131
  const request = { page: index, scale, rotation: layout.rotation, clip, ...appearanceField(this.#state.appearance) };
818
- return { clip, request, key: renderKey(request, this.#document?.id ?? 0) };
1132
+ return { clip, request, key: this.#key(request) };
1133
+ }
1134
+ /** `request`'s cache key: the render key with its page's revision. */
1135
+ #key(request) {
1136
+ return viewKey(request, this.#documentId ?? 0, this.#revisions.get(request.page) ?? 0);
819
1137
  }
820
1138
  /** The device px per pt of a sharp tile: the layout's scale × the device pixel ratio. */
821
1139
  #fullScale(layout) {
@@ -886,7 +1204,7 @@ export class Viewer {
886
1204
  // A page in the margin gives its detail canvas back for the pages in view.
887
1205
  if (view !== undefined && priority === "prefetch")
888
1206
  this.#releaseDetail(view);
889
- if (view === undefined || this.#document === undefined || view.busy || view.waiting || view.state === "error") {
1207
+ if (view === undefined || this.#documentId === undefined || view.busy || view.waiting || view.state === "error") {
890
1208
  return;
891
1209
  }
892
1210
  if (!this.#readyForAppearance(view, priority) || this.#upToDate(view, priority, frame))
@@ -951,7 +1269,7 @@ export class Viewer {
951
1269
  rotation: layout.rotation,
952
1270
  ...appearanceField(this.#state.appearance),
953
1271
  };
954
- const low = await this.#bitmap(request, renderKey(request, this.#document?.id ?? 0), priority, signal);
1272
+ const low = await this.#bitmap(request, this.#key(request), priority, signal);
955
1273
  if (!live()) {
956
1274
  this.#drop(low);
957
1275
  return false;
@@ -1160,7 +1478,17 @@ export class Viewer {
1160
1478
  const cached = this.#cache.get(key);
1161
1479
  if (cached !== undefined && !isClosed(cached))
1162
1480
  return { bitmap: cached, owned: false };
1481
+ const revision = this.#revisions.get(request.page) ?? 0;
1163
1482
  const { bitmap } = await this.#client.render(request, { priority, signal });
1483
+ // The page was edited while this render waited: its pixels may be the old file's, and its key
1484
+ // names a revision nothing asks for again. The worker runs one call at a time and `invalidate`
1485
+ // runs only once the edit has answered, so an answer that comes after it, at the same
1486
+ // revision, drew the edited file; the worker's coalescing key needs no revision for the same
1487
+ // reason (no render can run across an edit).
1488
+ if ((this.#revisions.get(request.page) ?? 0) !== revision) {
1489
+ bitmap.close();
1490
+ throw new DOMException("the page changed while it rendered", "AbortError");
1491
+ }
1164
1492
  const kept = this.#cache.set(key, request.page, bitmap, this.#state.currentPage);
1165
1493
  return { bitmap, owned: !kept };
1166
1494
  }
@@ -1330,6 +1658,10 @@ export class Viewer {
1330
1658
  const resize = new ResizeObserver(() => {
1331
1659
  if (this.#layout === undefined)
1332
1660
  return;
1661
+ if (this.#pending !== undefined && this.#sized()) {
1662
+ this.#showPending(this.#pending);
1663
+ return;
1664
+ }
1333
1665
  if (typeof this.#zoom === "string")
1334
1666
  this.#rezoom(undefined);
1335
1667
  else