@paperpic/core 0.1.0 → 0.3.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/dist/index.js CHANGED
@@ -1,4 +1,140 @@
1
- import { a as DEFAULT_SOFTNESS, c as prepareThreshold, d as scaleQuad, f as cropBox, i as DEFAULT_SENSITIVITY, l as estimateAspectRatio, r as adjustPixels, s as applyThreshold, t as applySteps, u as estimateOutputSize } from "./pipeline-MP1RPlXT.js";
1
+ import { C as zoomTo, D as cropBox, E as scaleQuad, S as zoomLimits, T as estimateOutputSize, _ as panBy, a as orientationSteps, b as setRotation, c as applyThreshold, d as createView, f as displayedSize, g as overflows, h as normalizeRotation, i as mirrorOrientation, l as prepareThreshold, m as frameToViewport, n as applySteps, o as DEFAULT_SENSITIVITY, p as fitView, r as isToneStep, s as DEFAULT_SOFTNESS, t as UPRIGHT, u as adjustPixels, v as resizeView, w as estimateAspectRatio, x as viewportToFrame, y as rotateView } from "./steps-DuGiMvk0.js";
2
+ // src/input/gestures.ts
3
+ const DOUBLE_TAP_TIME = 300;
4
+ const DOUBLE_TAP_DISTANCE = 30;
5
+ /** Zoom per wheel unit. Trackpad pinches arrive as a wheel with Ctrl, in much smaller steps. */
6
+ const WHEEL_SPEED = .002;
7
+ const PINCH_WHEEL_SPEED = .01;
8
+ const LINE_HEIGHT = 16;
9
+ /**
10
+ * Turns Pointer Events and the wheel into pan, zoom, tap and double tap.
11
+ */
12
+ function attachGestures(element, handlers) {
13
+ const pointers = /* @__PURE__ */ new Map();
14
+ let lastTap = null;
15
+ let travelled = 0;
16
+ const localPoint = (event) => {
17
+ const { left, top } = element.getBoundingClientRect();
18
+ return {
19
+ x: event.clientX - left,
20
+ y: event.clientY - top
21
+ };
22
+ };
23
+ const onPointerDown = (event) => {
24
+ if (event.pointerType === "mouse" && event.button !== 0) return;
25
+ pointers.set(event.pointerId, localPoint(event));
26
+ element.setPointerCapture(event.pointerId);
27
+ travelled = pointers.size === 1 ? 0 : 10;
28
+ };
29
+ const onPointerMove = (event) => {
30
+ const previous = pointers.get(event.pointerId);
31
+ if (!previous) return;
32
+ const point = localPoint(event);
33
+ if (pointers.size === 1) {
34
+ pointers.set(event.pointerId, point);
35
+ travelled += Math.hypot(point.x - previous.x, point.y - previous.y);
36
+ handlers.onPan(point.x - previous.x, point.y - previous.y);
37
+ return;
38
+ }
39
+ const other = [...pointers].find(([id]) => id !== event.pointerId)[1];
40
+ const before = Math.hypot(previous.x - other.x, previous.y - other.y);
41
+ const after = Math.hypot(point.x - other.x, point.y - other.y);
42
+ pointers.set(event.pointerId, point);
43
+ const center = {
44
+ x: (point.x + other.x) / 2,
45
+ y: (point.y + other.y) / 2
46
+ };
47
+ if (before > 0 && after > 0) handlers.onZoom(after / before, center);
48
+ handlers.onPan((point.x - previous.x) / 2, (point.y - previous.y) / 2);
49
+ };
50
+ const onPointerUp = (event) => {
51
+ if (!pointers.delete(event.pointerId) || pointers.size > 0 || travelled >= 10) return;
52
+ const point = localPoint(event);
53
+ if (handlers.onTap(point)) {
54
+ lastTap = null;
55
+ return;
56
+ }
57
+ if (lastTap && event.timeStamp - lastTap.time < DOUBLE_TAP_TIME && Math.hypot(point.x - lastTap.point.x, point.y - lastTap.point.y) < DOUBLE_TAP_DISTANCE) {
58
+ lastTap = null;
59
+ handlers.onDoubleTap(point);
60
+ } else lastTap = {
61
+ time: event.timeStamp,
62
+ point
63
+ };
64
+ };
65
+ const onPointerCancel = (event) => {
66
+ pointers.delete(event.pointerId);
67
+ lastTap = null;
68
+ };
69
+ const onWheel = (event) => {
70
+ event.preventDefault();
71
+ const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? LINE_HEIGHT : event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? element.clientHeight : 1;
72
+ const speed = event.ctrlKey ? PINCH_WHEEL_SPEED : WHEEL_SPEED;
73
+ handlers.onZoom(Math.exp(-event.deltaY * unit * speed), localPoint(event));
74
+ };
75
+ element.addEventListener("pointerdown", onPointerDown);
76
+ element.addEventListener("pointermove", onPointerMove);
77
+ element.addEventListener("pointerup", onPointerUp);
78
+ element.addEventListener("pointercancel", onPointerCancel);
79
+ let wheelZoom = false;
80
+ const setWheelZoom = (enabled) => {
81
+ if (enabled === wheelZoom) return;
82
+ wheelZoom = enabled;
83
+ if (enabled) element.addEventListener("wheel", onWheel, { passive: false });
84
+ else element.removeEventListener("wheel", onWheel);
85
+ };
86
+ return {
87
+ setWheelZoom,
88
+ detach: () => {
89
+ element.removeEventListener("pointerdown", onPointerDown);
90
+ element.removeEventListener("pointermove", onPointerMove);
91
+ element.removeEventListener("pointerup", onPointerUp);
92
+ element.removeEventListener("pointercancel", onPointerCancel);
93
+ setWheelZoom(false);
94
+ }
95
+ };
96
+ }
97
+ // src/input/keyboard.ts
98
+ const PAN_STEP = 40;
99
+ const COMMANDS = {
100
+ "+": { type: "zoomIn" },
101
+ "=": { type: "zoomIn" },
102
+ "-": { type: "zoomOut" },
103
+ "_": { type: "zoomOut" },
104
+ "0": { type: "fit" },
105
+ "ArrowLeft": {
106
+ type: "pan",
107
+ deltaX: PAN_STEP,
108
+ deltaY: 0
109
+ },
110
+ "ArrowRight": {
111
+ type: "pan",
112
+ deltaX: -40,
113
+ deltaY: 0
114
+ },
115
+ "ArrowUp": {
116
+ type: "pan",
117
+ deltaX: 0,
118
+ deltaY: PAN_STEP
119
+ },
120
+ "ArrowDown": {
121
+ type: "pan",
122
+ deltaX: 0,
123
+ deltaY: -40
124
+ },
125
+ "Escape": { type: "cancel" },
126
+ "Enter": { type: "apply" }
127
+ };
128
+ /** Finds the command for a key, leaving browser shortcuts such as Ctrl and + alone. */
129
+ function keyToCommand(event) {
130
+ if (event.altKey) return null;
131
+ if (event.ctrlKey || event.metaKey) {
132
+ const key = event.key.toLowerCase();
133
+ if (key === "z") return { type: event.shiftKey ? "redo" : "undo" };
134
+ return key === "y" ? { type: "redo" } : null;
135
+ }
136
+ return COMMANDS[event.key] ?? null;
137
+ }
2
138
  // src/pipeline/pixels.ts
3
139
  /**
4
140
  * Reads the part of an image that a plan asks for.
@@ -6,23 +142,33 @@ import { a as DEFAULT_SOFTNESS, c as prepareThreshold, d as scaleQuad, f as crop
6
142
  * @throws {Error} If the browser cannot hold that many pixels, or the image comes from another origin.
7
143
  */
8
144
  function readPixels(image, { region, width, height }) {
145
+ const tooLarge = `The browser could not read an image of ${width}×${height}. Set maxOutputSize to a smaller value.`;
9
146
  const canvas = document.createElement("canvas");
10
147
  canvas.width = width;
11
148
  canvas.height = height;
12
- const context = canvas.getContext("2d", { willReadFrequently: true });
13
- if (!context) throw new Error(`The browser could not read an image of ${width}×${height}. Set maxOutputSize to a smaller value.`);
14
- context.imageSmoothingQuality = "high";
15
- context.drawImage(image, region.x, region.y, region.width, region.height, 0, 0, width, height);
16
149
  try {
17
- return {
18
- data: context.getImageData(0, 0, width, height).data,
19
- width,
20
- height
21
- };
22
- } catch (cause) {
23
- throw new Error("The browser does not allow reading this image, because it comes from another origin. Serve it from the same origin, or pass it as a Blob or a File.", { cause });
150
+ const context = canvas.getContext("2d", { willReadFrequently: true });
151
+ if (!context) throw new Error(tooLarge);
152
+ context.imageSmoothingQuality = "high";
153
+ context.drawImage(image, region.x, region.y, region.width, region.height, 0, 0, width, height);
154
+ try {
155
+ return {
156
+ data: context.getImageData(0, 0, width, height).data,
157
+ width,
158
+ height
159
+ };
160
+ } catch (cause) {
161
+ throw new Error(cause.name === "SecurityError" ? "The browser does not allow reading this image, because it comes from another origin. Serve it from the same origin, or pass it as a Blob or a File." : tooLarge, { cause });
162
+ }
163
+ } finally {
164
+ releaseCanvas(canvas);
24
165
  }
25
166
  }
167
+ /** Frees the memory of a canvas at once. Some browsers, such as Safari on iOS, keep it for a while otherwise, and limit the total. */
168
+ function releaseCanvas(canvas) {
169
+ canvas.width = 0;
170
+ canvas.height = 0;
171
+ }
26
172
  /** Puts pixels on a new canvas. */
27
173
  function pixelsToCanvas({ data, width, height }) {
28
174
  const canvas = document.createElement("canvas");
@@ -31,132 +177,6 @@ function pixelsToCanvas({ data, width, height }) {
31
177
  canvas.getContext("2d")?.putImageData(new ImageData(data, width, height), 0, 0);
32
178
  return canvas;
33
179
  }
34
- // src/rotation.ts
35
- /**
36
- * Rounds an angle in degrees to the nearest multiple of 90 and wraps it into [0, 360).
37
- *
38
- * @throws {RangeError} If `degrees` is not a finite number.
39
- */
40
- function normalizeRotation(degrees) {
41
- if (!Number.isFinite(degrees)) throw new RangeError(`Rotation must be a finite number, got ${degrees}`);
42
- return (Math.round(degrees / 90) * 90 % 360 + 360) % 360;
43
- }
44
- // src/pipeline/operations.ts
45
- /** Whether a step changes only the tones. */
46
- function isToneStep(step) {
47
- return step.type === "threshold" || step.type === "adjust";
48
- }
49
- const UPRIGHT = {
50
- degrees: 0,
51
- mirrored: false
52
- };
53
- /** Mirrors an orientation left to right. A flip after a turn is the same as a flip before the opposite turn. */
54
- function mirrorOrientation({ degrees, mirrored }) {
55
- return {
56
- degrees: -degrees,
57
- mirrored: !mirrored
58
- };
59
- }
60
- /** The steps of an orientation, in the order it means: the flip, then the turn. */
61
- function orientationSteps({ degrees, mirrored }) {
62
- const rotation = normalizeRotation(degrees);
63
- return [...mirrored ? [{ type: "flip" }] : [], ...rotation === 0 ? [] : [{
64
- type: "rotate",
65
- rotation
66
- }]];
67
- }
68
- /** The steps that change the shape of the image. Turns and flips next to each other merge or cancel out. */
69
- function geometrySteps(operations) {
70
- const steps = [];
71
- let orientation = UPRIGHT;
72
- for (const operation of operations) if (operation.type === "rotate") orientation = {
73
- ...orientation,
74
- degrees: orientation.degrees + 90 * operation.direction
75
- };
76
- else if (operation.type === "flip") orientation = mirrorOrientation(orientation);
77
- else if (operation.type === "crop" || operation.type === "perspective") {
78
- steps.push(...orientationSteps(orientation), operation);
79
- orientation = UPRIGHT;
80
- }
81
- steps.push(...orientationSteps(orientation));
82
- return steps;
83
- }
84
- /** The threshold in effect: its last edit decides, wherever it is in the list. */
85
- function thresholdSetting(operations) {
86
- for (let index = operations.length - 1; index >= 0; index--) {
87
- const operation = operations[index];
88
- if (operation.type === "threshold") return {
89
- enabled: operation.enabled,
90
- sensitivity: operation.sensitivity,
91
- softness: operation.softness
92
- };
93
- }
94
- return {
95
- enabled: false,
96
- sensitivity: DEFAULT_SENSITIVITY,
97
- softness: DEFAULT_SOFTNESS
98
- };
99
- }
100
- /** The brightness and contrast in effect: their last edit decides, wherever it is in the list. */
101
- function adjustSetting(operations) {
102
- for (let index = operations.length - 1; index >= 0; index--) {
103
- const operation = operations[index];
104
- if (operation.type === "adjust") return {
105
- brightness: operation.brightness,
106
- contrast: operation.contrast
107
- };
108
- }
109
- return {
110
- brightness: 0,
111
- contrast: 0
112
- };
113
- }
114
- /**
115
- * The step that changes the tones, or `null` if there is none. A cleaned document has tones of its own,
116
- * so the threshold leaves out the brightness and contrast.
117
- */
118
- function toneStep(operations) {
119
- const { enabled, sensitivity, softness } = thresholdSetting(operations);
120
- if (enabled) return {
121
- type: "threshold",
122
- sensitivity,
123
- softness
124
- };
125
- const { brightness, contrast } = adjustSetting(operations);
126
- return brightness !== 0 || contrast !== 0 ? {
127
- type: "adjust",
128
- brightness,
129
- contrast
130
- } : null;
131
- }
132
- /**
133
- * Turns edits into the shortest list of steps, with the tones always last, so the result does not depend on when the user changed them.
134
- * A user who turns the image all the way around, or moves a slider back to 0, has changed nothing.
135
- */
136
- function toPipelineSteps(operations) {
137
- const steps = geometrySteps(operations);
138
- const tone = toneStep(operations);
139
- if (tone) steps.push(tone);
140
- return steps;
141
- }
142
- /** The index of the last edit that the preview computes. A flip is one of them, because the view matrix only turns. */
143
- function lastPixelEdit(operations) {
144
- return operations.map(({ type }) => type === "crop" || type === "perspective" || type === "flip").lastIndexOf(true);
145
- }
146
- /**
147
- * The rotation that goes in the view matrix: the one after the last edit that changes the pixels of the shape.
148
- * The rotations before that edit are already in the preview.
149
- */
150
- function trailingRotation(operations) {
151
- return normalizeRotation(operations.slice(lastPixelEdit(operations) + 1).reduce((total, operation) => total + (operation.type === "rotate" ? 90 * operation.direction : 0), 0));
152
- }
153
- /**
154
- * The steps that decide the shape on display. The last rotations are left out, because the view matrix does them,
155
- * and so are the tones, which a preview paints apart so that a slider can change them.
156
- */
157
- function toPreviewSteps(operations) {
158
- return geometrySteps(operations.slice(0, lastPixelEdit(operations) + 1));
159
- }
160
180
  // src/pipeline/read-plan.ts
161
181
  /** Takes a rectangle from the frame of an image turned clockwise back to the frame of the image. */
162
182
  function unrotateRect({ x, y, width, height }, rotation) {
@@ -310,6 +330,7 @@ function resultSize(image, steps) {
310
330
  }, remaining);
311
331
  }
312
332
  // src/pipeline/export.ts
333
+ /** The formats that editing can produce. */
313
334
  const ENCODABLE = /* @__PURE__ */ new Set([
314
335
  "image/jpeg",
315
336
  "image/png",
@@ -340,6 +361,7 @@ function encode(pixels, type, quality) {
340
361
  const canvas = pixelsToCanvas(pixels);
341
362
  return new Promise((resolve, reject) => {
342
363
  canvas.toBlob((blob) => {
364
+ releaseCanvas(canvas);
343
365
  if (blob) resolve(blob);
344
366
  else reject(/* @__PURE__ */ new Error(`The browser could not save an image of ${pixels.width}×${pixels.height}. Set maxOutputSize to a smaller value.`));
345
367
  }, type, quality);
@@ -369,1125 +391,1191 @@ async function exportImage(request) {
369
391
  type: blob.type
370
392
  };
371
393
  }
372
- // src/download.ts
373
- const DEFAULT_NAME = "image";
374
- const IMAGE_EXTENSION = /\.(?:jpe?g|png|webp|gif|avif|bmp|svg)$/i;
375
- const SAVABLE_TYPE = /^image\/(jpeg|png|webp|gif|avif|bmp)$/;
376
- /** The last part of a URL, or nothing for a URL that holds the data itself. */
377
- function nameInUrl(url) {
378
- if (/^(?:data|blob):/i.test(url)) return "";
379
- const name = url.split(/[?#]/)[0].split("/").pop();
380
- try {
381
- return decodeURIComponent(name);
382
- } catch {
383
- return name;
384
- }
385
- }
386
- /**
387
- * Chooses the name of a saved file: the one given, or the name of the file or the URL that was loaded, or `image`.
388
- * When the format of the image is known, the name ends in its extension, so a cleaned up `receipt.jpg` saves as `receipt.png`.
389
- *
390
- * @param image What gets saved: a URL or the result of an edit.
391
- * @param source What was loaded, which gives the name.
392
- * @param filename The name the consumer chose.
393
- */
394
- function downloadName(image, source, filename) {
395
- const original = source instanceof File ? source.name : typeof source === "string" ? nameInUrl(source) : "";
396
- const name = filename || original || DEFAULT_NAME;
397
- const type = typeof image === "string" ? typeFromUrl(image) : image.type;
398
- const subtype = type && SAVABLE_TYPE.exec(type)?.[1];
399
- if (!subtype) return name;
400
- const extension = subtype === "jpeg" ? "jpg" : subtype;
401
- return `${name.replace(IMAGE_EXTENSION, "") || DEFAULT_NAME}.${extension}`;
402
- }
403
- /** Makes the browser save a file, as a link with `download` would. */
404
- function saveFile(url, filename) {
405
- const link = document.createElement("a");
406
- link.href = url;
407
- link.download = filename;
408
- link.click();
409
- }
410
- // src/input/gestures.ts
411
- const DOUBLE_TAP_TIME = 300;
412
- const DOUBLE_TAP_DISTANCE = 30;
413
- /** Zoom per wheel unit. Trackpad pinches arrive as a wheel with Ctrl, in much smaller steps. */
414
- const WHEEL_SPEED = .002;
415
- const PINCH_WHEEL_SPEED = .01;
416
- const LINE_HEIGHT = 16;
417
- /**
418
- * Turns Pointer Events and the wheel into pan, zoom, tap and double tap.
419
- *
420
- * @returns The function that removes every listener.
421
- */
422
- function attachGestures(element, handlers) {
423
- const pointers = /* @__PURE__ */ new Map();
424
- let lastTap = null;
425
- let travelled = 0;
426
- const localPoint = (event) => {
427
- const { left, top } = element.getBoundingClientRect();
428
- return {
429
- x: event.clientX - left,
430
- y: event.clientY - top
431
- };
432
- };
433
- const onPointerDown = (event) => {
434
- if (event.pointerType === "mouse" && event.button !== 0) return;
435
- pointers.set(event.pointerId, localPoint(event));
436
- element.setPointerCapture(event.pointerId);
437
- travelled = pointers.size === 1 ? 0 : 10;
394
+ // src/pipeline/operations.ts
395
+ /** The steps that change the shape of the image. Turns and flips next to each other merge or cancel out. */
396
+ function geometrySteps(operations) {
397
+ const steps = [];
398
+ let orientation = UPRIGHT;
399
+ for (const operation of operations) if (operation.type === "rotate") orientation = {
400
+ ...orientation,
401
+ degrees: orientation.degrees + 90 * operation.direction
438
402
  };
439
- const onPointerMove = (event) => {
440
- const previous = pointers.get(event.pointerId);
441
- if (!previous) return;
442
- const point = localPoint(event);
443
- if (pointers.size === 1) {
444
- pointers.set(event.pointerId, point);
445
- travelled += Math.hypot(point.x - previous.x, point.y - previous.y);
446
- handlers.onPan(point.x - previous.x, point.y - previous.y);
447
- return;
448
- }
449
- const other = [...pointers].find(([id]) => id !== event.pointerId)[1];
450
- const before = Math.hypot(previous.x - other.x, previous.y - other.y);
451
- const after = Math.hypot(point.x - other.x, point.y - other.y);
452
- pointers.set(event.pointerId, point);
453
- const center = {
454
- x: (point.x + other.x) / 2,
455
- y: (point.y + other.y) / 2
403
+ else if (operation.type === "flip") orientation = mirrorOrientation(orientation);
404
+ else if (operation.type === "crop" || operation.type === "perspective") {
405
+ steps.push(...orientationSteps(orientation), operation);
406
+ orientation = UPRIGHT;
407
+ }
408
+ steps.push(...orientationSteps(orientation));
409
+ return steps;
410
+ }
411
+ /** The threshold in effect: its last edit decides, wherever it is in the list. */
412
+ function thresholdSetting(operations) {
413
+ for (let index = operations.length - 1; index >= 0; index--) {
414
+ const operation = operations[index];
415
+ if (operation.type === "threshold") return {
416
+ enabled: operation.enabled,
417
+ sensitivity: operation.sensitivity,
418
+ softness: operation.softness
456
419
  };
457
- if (before > 0 && after > 0) handlers.onZoom(after / before, center);
458
- handlers.onPan((point.x - previous.x) / 2, (point.y - previous.y) / 2);
420
+ }
421
+ return {
422
+ enabled: false,
423
+ sensitivity: DEFAULT_SENSITIVITY,
424
+ softness: DEFAULT_SOFTNESS
459
425
  };
460
- const onPointerUp = (event) => {
461
- if (!pointers.delete(event.pointerId) || pointers.size > 0 || travelled >= 10) return;
462
- const point = localPoint(event);
463
- if (handlers.onTap(point)) {
464
- lastTap = null;
465
- return;
466
- }
467
- if (lastTap && event.timeStamp - lastTap.time < DOUBLE_TAP_TIME && Math.hypot(point.x - lastTap.point.x, point.y - lastTap.point.y) < DOUBLE_TAP_DISTANCE) {
468
- lastTap = null;
469
- handlers.onDoubleTap(point);
470
- } else lastTap = {
471
- time: event.timeStamp,
472
- point
426
+ }
427
+ /** The brightness and contrast in effect: their last edit decides, wherever it is in the list. */
428
+ function adjustSetting(operations) {
429
+ for (let index = operations.length - 1; index >= 0; index--) {
430
+ const operation = operations[index];
431
+ if (operation.type === "adjust") return {
432
+ brightness: operation.brightness,
433
+ contrast: operation.contrast
473
434
  };
435
+ }
436
+ return {
437
+ brightness: 0,
438
+ contrast: 0
474
439
  };
475
- const onPointerCancel = (event) => {
476
- pointers.delete(event.pointerId);
477
- lastTap = null;
478
- };
479
- const onWheel = (event) => {
480
- if (!handlers.wheelZoom()) return;
481
- event.preventDefault();
482
- const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? LINE_HEIGHT : event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? element.clientHeight : 1;
483
- const speed = event.ctrlKey ? PINCH_WHEEL_SPEED : WHEEL_SPEED;
484
- handlers.onZoom(Math.exp(-event.deltaY * unit * speed), localPoint(event));
485
- };
486
- element.addEventListener("pointerdown", onPointerDown);
487
- element.addEventListener("pointermove", onPointerMove);
488
- element.addEventListener("pointerup", onPointerUp);
489
- element.addEventListener("pointercancel", onPointerCancel);
490
- element.addEventListener("wheel", onWheel, { passive: false });
491
- return () => {
492
- element.removeEventListener("pointerdown", onPointerDown);
493
- element.removeEventListener("pointermove", onPointerMove);
494
- element.removeEventListener("pointerup", onPointerUp);
495
- element.removeEventListener("pointercancel", onPointerCancel);
496
- element.removeEventListener("wheel", onWheel);
440
+ }
441
+ /**
442
+ * The step that changes the tones, or `null` if there is none. A cleaned document has tones of its own,
443
+ * so the threshold leaves out the brightness and contrast.
444
+ */
445
+ function toneStep(operations) {
446
+ const { enabled, sensitivity, softness } = thresholdSetting(operations);
447
+ if (enabled) return {
448
+ type: "threshold",
449
+ sensitivity,
450
+ softness
497
451
  };
452
+ const { brightness, contrast } = adjustSetting(operations);
453
+ return brightness !== 0 || contrast !== 0 ? {
454
+ type: "adjust",
455
+ brightness,
456
+ contrast
457
+ } : null;
498
458
  }
499
- // src/input/keyboard.ts
500
- const PAN_STEP = 40;
501
- const COMMANDS = {
502
- "+": { type: "zoomIn" },
503
- "=": { type: "zoomIn" },
504
- "-": { type: "zoomOut" },
505
- "_": { type: "zoomOut" },
506
- "0": { type: "fit" },
507
- "ArrowLeft": {
508
- type: "pan",
509
- deltaX: PAN_STEP,
510
- deltaY: 0
511
- },
512
- "ArrowRight": {
513
- type: "pan",
514
- deltaX: -40,
515
- deltaY: 0
516
- },
517
- "ArrowUp": {
518
- type: "pan",
519
- deltaX: 0,
520
- deltaY: PAN_STEP
521
- },
522
- "ArrowDown": {
523
- type: "pan",
524
- deltaX: 0,
525
- deltaY: -40
526
- },
527
- "Escape": { type: "cancel" },
528
- "Enter": { type: "apply" }
529
- };
530
- /** Finds the command for a key, leaving browser shortcuts such as Ctrl and + alone. */
531
- function keyToCommand(event) {
532
- if (event.altKey) return null;
533
- if (event.ctrlKey || event.metaKey) {
534
- const key = event.key.toLowerCase();
535
- if (key === "z") return { type: event.shiftKey ? "redo" : "undo" };
536
- return key === "y" ? { type: "redo" } : null;
537
- }
538
- return COMMANDS[event.key] ?? null;
459
+ /**
460
+ * Turns edits into the shortest list of steps, with the tones always last, so the result does not depend on when the user changed them.
461
+ * A user who turns the image all the way around, or moves a ruler back to 0, has changed nothing.
462
+ */
463
+ function toPipelineSteps(operations) {
464
+ const steps = geometrySteps(operations);
465
+ const tone = toneStep(operations);
466
+ if (tone) steps.push(tone);
467
+ return steps;
468
+ }
469
+ /** The index of the last edit that the preview computes. A flip is one of them, because the view matrix only turns. */
470
+ function lastPixelEdit(operations) {
471
+ return operations.map(({ type }) => type === "crop" || type === "perspective" || type === "flip").lastIndexOf(true);
539
472
  }
540
- // src/pipeline/photo-frame.ts
541
473
  /**
542
- * Follows crops, rotations and flips back to the photo, because estimating proportions needs its center.
543
- * After a perspective change that center no longer means anything, so the result counts as a new photo.
474
+ * The rotation that goes in the view matrix: the one after the last edit that changes the pixels of the shape.
475
+ * The rotations before that edit are already in the preview.
544
476
  */
545
- function photoFrame(image, steps) {
546
- let photo = {
547
- width: image.width,
548
- height: image.height
477
+ function trailingRotation(operations) {
478
+ const degrees = operations.slice(lastPixelEdit(operations) + 1).reduce((total, operation) => total + (operation.type === "rotate" ? 90 * operation.direction : 0), 0);
479
+ return normalizeRotation(degrees);
480
+ }
481
+ /**
482
+ * The steps that decide the shape on display. The last rotations are left out, because the view matrix does them,
483
+ * and so are the tones, which a preview paints apart so that a ruler can change them.
484
+ */
485
+ function toPreviewSteps(operations) {
486
+ return geometrySteps(operations.slice(0, lastPixelEdit(operations) + 1));
487
+ }
488
+ // src/tools/adjust.ts
489
+ /**
490
+ * Changes the brightness and contrast. They are a setting that runs after the shape, so its button opens a panel that
491
+ * chooses between them, with one ruler, and Done leaves one edit with both.
492
+ */
493
+ const adjustTool = {
494
+ id: "adjust",
495
+ actions: [{
496
+ id: "adjust",
497
+ run: (context) => context.openTool("adjust")
498
+ }]
499
+ };
500
+ /** Whether the brightness and contrast can change. A cleaned document has tones of its own, so they cannot. */
501
+ function canAdjust(operations) {
502
+ return !thresholdSetting(operations).enabled;
503
+ }
504
+ /** The edit that leaves the brightness and contrast at `setting`, or `null` if they already are. */
505
+ function adjustEdit(setting, operations) {
506
+ const current = adjustSetting(operations);
507
+ return setting.brightness !== current.brightness || setting.contrast !== current.contrast ? {
508
+ type: "adjust",
509
+ ...setting
510
+ } : null;
511
+ }
512
+ // src/tools/magnifier.ts
513
+ const MAGNIFIER_RADIUS = 56;
514
+ /** Places the magnifier above the finger, or below it at the top of the viewport, always on screen. */
515
+ function placeMagnifier(point, finger, viewport) {
516
+ const distance = 104;
517
+ const above = finger.y - distance;
518
+ const y = above >= MAGNIFIER_RADIUS ? above : finger.y + distance;
519
+ const limit = Math.max(MAGNIFIER_RADIUS, viewport.width - MAGNIFIER_RADIUS);
520
+ return {
521
+ point,
522
+ center: {
523
+ x: Math.min(limit, Math.max(MAGNIFIER_RADIUS, finger.x)),
524
+ y
525
+ },
526
+ radius: MAGNIFIER_RADIUS
549
527
  };
550
- let origin = {
551
- x: 0,
528
+ }
529
+ // src/tools/corners.ts
530
+ const INITIAL_INSET = .1;
531
+ /** The smallest selection, in image pixels. */
532
+ const MIN_SIDE = 16;
533
+ const SHIFT_STEP = 10;
534
+ const REVEAL_DIRECTIONS = {
535
+ ArrowLeft: {
536
+ x: -1,
552
537
  y: 0
553
- };
554
- let region = photo;
555
- for (const step of steps) switch (step.type) {
556
- case "rotate":
557
- for (let turns = step.rotation / 90; turns > 0; turns--) {
558
- origin = {
559
- x: photo.height - origin.y - region.height,
560
- y: origin.x
561
- };
562
- photo = {
563
- width: photo.height,
564
- height: photo.width
565
- };
566
- region = {
567
- width: region.height,
568
- height: region.width
569
- };
570
- }
571
- break;
572
- case "flip":
573
- origin = {
574
- x: photo.width - origin.x - region.width,
575
- y: origin.y
576
- };
577
- break;
578
- case "crop":
579
- origin = {
580
- x: origin.x + step.rect.x * region.width,
581
- y: origin.y + step.rect.y * region.height
582
- };
583
- region = {
584
- width: step.rect.width * region.width,
585
- height: step.rect.height * region.height
586
- };
587
- break;
588
- case "perspective":
589
- region = estimateOutputSize(scaleQuad(step.quad, region.width, region.height), region, { aspectRatio: step.aspectRatio });
590
- photo = region;
591
- origin = {
592
- x: 0,
593
- y: 0
594
- };
538
+ },
539
+ ArrowRight: {
540
+ x: 1,
541
+ y: 0
542
+ },
543
+ ArrowUp: {
544
+ x: 0,
545
+ y: -1
546
+ },
547
+ ArrowDown: {
548
+ x: 0,
549
+ y: 1
595
550
  }
596
- return {
597
- photo,
598
- origin
599
- };
551
+ };
552
+ const CORNER_LABELS = [
553
+ "cornerTopLeft",
554
+ "cornerTopRight",
555
+ "cornerBottomRight",
556
+ "cornerBottomLeft"
557
+ ];
558
+ function clamp(value, min, max) {
559
+ return Math.min(max, Math.max(min, value));
560
+ }
561
+ /** The corners of a rectangle. */
562
+ function rectangleCorners(left, top, right, bottom) {
563
+ return [
564
+ {
565
+ x: left,
566
+ y: top
567
+ },
568
+ {
569
+ x: right,
570
+ y: top
571
+ },
572
+ {
573
+ x: right,
574
+ y: bottom
575
+ },
576
+ {
577
+ x: left,
578
+ y: bottom
579
+ }
580
+ ];
581
+ }
582
+ /** Where the corners start: inside the image, a little in from its edges. Nothing covers them, because the toolbar hides while editing. */
583
+ function initialCorners(frame) {
584
+ const left = frame.width * INITIAL_INSET;
585
+ const top = frame.height * INITIAL_INSET;
586
+ return rectangleCorners(left, top, frame.width - left, frame.height - top);
587
+ }
588
+ /** Keeps the corners a rectangle inside the frame, which never turns inside out. */
589
+ const constrainToRectangle = (corners, index, point, frame) => {
590
+ const opposite = corners[(index + 2) % 4];
591
+ const isLeft = index === 0 || index === 3;
592
+ const isTop = index === 0 || index === 1;
593
+ const minWidth = Math.min(MIN_SIDE, frame.width);
594
+ const minHeight = Math.min(MIN_SIDE, frame.height);
595
+ const x = isLeft ? clamp(point.x, 0, opposite.x - minWidth) : clamp(point.x, opposite.x + minWidth, frame.width);
596
+ const y = isTop ? clamp(point.y, 0, opposite.y - minHeight) : clamp(point.y, opposite.y + minHeight, frame.height);
597
+ return rectangleCorners(isLeft ? x : opposite.x, isTop ? y : opposite.y, isLeft ? opposite.x : x, isTop ? opposite.y : y);
598
+ };
599
+ function isConvex(corners, minTurn) {
600
+ return corners.every((corner, index) => {
601
+ const next = corners[(index + 1) % 4];
602
+ const last = corners[(index + 2) % 4];
603
+ return (next.x - corner.x) * (last.y - next.y) - (next.y - corner.y) * (last.x - next.x) >= minTurn;
604
+ });
600
605
  }
601
- // src/pipeline/preview.ts
602
- /** The size of the copy that previews work on. It keeps each step well under a second on a phone. */
603
- const PREVIEW_PIXELS = 2e6;
604
606
  /**
605
- * Computes what the edits look like, on a small copy of the image.
606
- * The result reports the size at full resolution, so it paints at the same scale as the final image.
607
- * `steps` change the shape of the image, and `tone` changes its tones afterwards, or is `null` if nothing does.
607
+ * Keeps the corners a convex shape inside the frame, so they can always be straightened.
608
+ * A move that would break it slides along the side that still allows it, or stays where it was.
608
609
  */
609
- async function renderPreview(image, steps, tone, runner) {
610
- const plan = planRead(image, steps, { maxPixels: PREVIEW_PIXELS });
611
- const pixels = readPixels(image.element, plan);
612
- let canvas;
613
- let tint;
614
- const paint = ({ data, width, height }) => {
615
- canvas.getContext("2d")?.putImageData(new ImageData(data, width, height), 0, 0);
616
- };
617
- if (tone?.type === "threshold") {
618
- const prepared = await runner.prepare(pixels, plan.steps);
619
- canvas = pixelsToCanvas(applyThreshold(prepared, tone));
620
- tint = (next) => {
621
- if (next.type === "threshold") paint(applyThreshold(prepared, next));
622
- };
623
- } else {
624
- const shaped = plan.steps.length > 0 ? await runner.run(pixels, plan.steps) : pixels;
625
- if (tone?.type === "adjust") {
626
- canvas = pixelsToCanvas(adjustPixels(shaped, tone));
627
- tint = (next) => {
628
- if (next.type === "adjust") paint(adjustPixels(shaped, next));
629
- };
630
- } else canvas = pixelsToCanvas(shaped);
631
- }
632
- return {
633
- element: canvas,
634
- ...resultSize(image, steps),
635
- tint,
636
- release: () => {
637
- canvas.width = 0;
638
- canvas.height = 0;
610
+ const constrainToConvex = (corners, index, point, frame) => {
611
+ const previous = corners[index];
612
+ const x = clamp(point.x, 0, frame.width);
613
+ const y = clamp(point.y, 0, frame.height);
614
+ const minSide = Math.min(MIN_SIDE, frame.width, frame.height);
615
+ const candidates = [
616
+ {
617
+ x,
618
+ y
619
+ },
620
+ {
621
+ x,
622
+ y: previous.y
623
+ },
624
+ {
625
+ x: previous.x,
626
+ y
639
627
  }
628
+ ];
629
+ for (const candidate of candidates) {
630
+ const moved = corners.map((corner, position) => position === index ? candidate : corner);
631
+ if (isConvex(moved, minSide * minSide)) return moved;
632
+ }
633
+ return corners;
634
+ };
635
+ /** Dims what stays out of a selection, and outlines it so it shows on any image. */
636
+ function drawSelection(context, frame, selection) {
637
+ const trace = (points) => {
638
+ points.forEach(({ x, y }, index) => {
639
+ if (index === 0) context.moveTo(x, y);
640
+ else context.lineTo(x, y);
641
+ });
642
+ context.closePath();
640
643
  };
644
+ context.beginPath();
645
+ trace(frame);
646
+ trace(selection);
647
+ context.fillStyle = "rgb(0 0 0 / 50%)";
648
+ context.fill("evenodd");
649
+ context.beginPath();
650
+ trace(selection);
651
+ context.lineWidth = 3;
652
+ context.strokeStyle = "rgb(0 0 0 / 60%)";
653
+ context.stroke();
654
+ context.lineWidth = 1.5;
655
+ context.strokeStyle = "#fff";
656
+ context.stroke();
641
657
  }
642
- // src/pipeline/run.ts
643
- /** How long a worker can take to start before the main thread does the work instead. */
644
- const WORKER_START_LIMIT = 5e3;
645
658
  /**
646
- * Runs the pipeline in a worker, so large images do not freeze the page.
647
- * If a worker cannot start, for example because a Content Security Policy blocks it, the main thread does the work.
659
+ * The corner handles of a selection: elements that take the focus and work with a pointer and with the keyboard.
660
+ * A corner moves by dragging its handle, or by pressing the handle and then tapping the new place, which needs no drag.
648
661
  */
649
- var PipelineRunner = class {
650
- worker = null;
651
- jobs = /* @__PURE__ */ new Map();
652
- abandonStart = null;
653
- current = null;
654
- nextId = 0;
655
- destroyed = false;
656
- /** Runs the steps. The buffer of `source` is transferred to the worker, so it cannot be used afterwards. */
657
- async run(source, steps) {
658
- const worker = await this.ready();
659
- return worker ? this.send(worker, "pipeline", source, steps, (response) => response.result) : applySteps(source, steps);
660
- }
661
- /** Runs the steps and prepares a threshold on the result, which a slider can then change at once. The buffer is transferred too. */
662
- async prepare(source, steps) {
663
- const worker = await this.ready();
664
- return worker ? this.send(worker, "prepare", source, steps, (response) => response.prepared) : prepareThreshold(applySteps(source, steps));
662
+ var CornerEditor = class {
663
+ host;
664
+ constrain;
665
+ handles;
666
+ corners;
667
+ magnifier = null;
668
+ /** The corner that the next tap on the image moves. */
669
+ selected = null;
670
+ constructor(host, corners, constrain) {
671
+ this.host = host;
672
+ this.corners = corners;
673
+ this.constrain = constrain;
674
+ this.handles = CORNER_LABELS.map((label, index) => this.createHandle(label, index));
675
+ host.layer.append(...this.handles);
676
+ this.update();
665
677
  }
666
- async ready() {
667
- this.worker ??= this.start();
668
- const worker = await this.worker;
669
- if (this.destroyed) throw new Error("The viewer was destroyed while processing.");
670
- return worker;
678
+ /** The corners, in pixels of the frame. */
679
+ get points() {
680
+ return this.corners;
671
681
  }
672
- /** Stops the worker, even one still starting. A job in progress fails. */
673
- destroy() {
674
- this.destroyed = true;
675
- this.abandonStart?.();
676
- this.current?.terminate();
677
- this.current = null;
678
- this.rejectJobs(/* @__PURE__ */ new Error("The viewer was destroyed while processing."));
682
+ /** Takes the keyboard focus, without scrolling the page or the viewer. */
683
+ focus() {
684
+ this.handles[0].focus({ preventScroll: true });
679
685
  }
680
- /**
681
- * Waits for the worker to report that it loaded. Sending a job earlier would lose its pixels if the worker
682
- * turns out to be blocked, because they are transferred and not copied.
683
- */
684
- start() {
685
- return new Promise((resolve) => {
686
- let worker;
687
- try {
688
- worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
689
- } catch {
690
- resolve(null);
691
- return;
692
- }
693
- this.current = worker;
694
- let timer;
695
- const settle = (result) => {
696
- clearTimeout(timer);
697
- this.abandonStart = null;
698
- if (!result) {
699
- worker.terminate();
700
- this.current = null;
701
- }
702
- resolve(result);
703
- };
704
- timer = setTimeout(settle, WORKER_START_LIMIT, null);
705
- this.abandonStart = () => settle(null);
706
- worker.onerror = () => settle(null);
707
- worker.onmessage = () => {
708
- this.listen(worker);
709
- settle(worker);
710
- };
686
+ update() {
687
+ this.handles.forEach((handle, index) => {
688
+ const { x, y } = this.host.frameToViewport(this.corners[index]);
689
+ handle.style.left = `${x}px`;
690
+ handle.style.top = `${y}px`;
711
691
  });
712
692
  }
713
- listen(worker) {
714
- worker.onerror = (event) => {
715
- worker.terminate();
716
- this.current = null;
717
- this.worker = null;
718
- this.rejectJobs(/* @__PURE__ */ new Error(`The image could not be processed: ${event.message}`));
719
- };
720
- worker.onmessage = ({ data }) => {
721
- if ("ready" in data) return;
722
- const job = this.jobs.get(data.id);
723
- this.jobs.delete(data.id);
724
- if ("error" in data) job?.reject(new Error(data.error));
725
- else job?.resolve(data);
726
- };
727
- }
728
- rejectJobs(reason) {
729
- for (const job of this.jobs.values()) job.reject(reason);
730
- this.jobs.clear();
693
+ drawOverlay(context) {
694
+ const { width, height } = this.host.frameSize();
695
+ drawSelection(context, rectangleCorners(0, 0, width, height).map((point) => this.host.frameToViewport(point)), this.corners.map((point) => this.host.frameToViewport(point)));
696
+ if (this.magnifier) this.host.paintMagnifier(context, this.magnifier);
731
697
  }
732
- send(worker, operation, source, steps, pick) {
733
- return new Promise((resolve, reject) => {
734
- const id = this.nextId++;
735
- this.jobs.set(id, {
736
- resolve: (response) => resolve(pick(response)),
737
- reject
738
- });
739
- worker.postMessage({
740
- id,
741
- operation,
742
- source,
743
- steps
744
- }, [source.data.buffer]);
745
- });
698
+ /** Moves the selected corner to a point of the viewport. Returns whether a corner was selected. */
699
+ place(point) {
700
+ const index = this.selected;
701
+ if (index === null) return false;
702
+ this.select(null);
703
+ this.move(index, this.host.viewportToFrame(point));
704
+ this.announce(index);
705
+ return true;
746
706
  }
747
- };
748
- // src/render/load-image.ts
749
- /**
750
- * Loads an image from a URL or a file. It uses an image element, which respects the EXIF orientation and accepts every format the browser can show.
751
- *
752
- * @throws {Error} If the browser cannot load or decode the image.
753
- */
754
- async function loadImage(source) {
755
- const objectUrl = typeof source === "string" ? null : URL.createObjectURL(source);
756
- const release = () => {
757
- if (objectUrl) URL.revokeObjectURL(objectUrl);
758
- };
759
- const element = new Image();
760
- element.src = objectUrl ?? source;
761
- try {
762
- await element.decode();
763
- } catch (cause) {
764
- release();
765
- const name = typeof source === "string" ? `"${source}"` : "the given file";
766
- throw new Error(`Could not load the image from ${name}. Check that it exists and that it is an image format the browser supports.`, { cause });
707
+ /** Where zoom keeps its place: the selected corner, or else the focused one, in the viewport. `null` for neither. */
708
+ anchor() {
709
+ const focused = this.handles.findIndex((handle) => handle === document.activeElement);
710
+ const index = this.selected ?? (focused >= 0 ? focused : null);
711
+ return index === null ? null : this.host.frameToViewport(this.corners[index]);
767
712
  }
768
- if (element.naturalWidth === 0 || element.naturalHeight === 0) {
769
- release();
770
- throw new Error("The image has no size. If it is an SVG, give it width and height attributes.");
713
+ /** Lets go of the selected corner. Returns whether a corner was selected. */
714
+ deselect() {
715
+ const wasSelected = this.selected !== null;
716
+ this.select(null);
717
+ return wasSelected;
771
718
  }
772
- return {
773
- element,
774
- width: element.naturalWidth,
775
- height: element.naturalHeight,
776
- release
777
- };
778
- }
779
- // src/render/transform.ts
780
- const COSINES = {
781
- 0: 1,
782
- 90: 0,
783
- 180: -1,
784
- 270: 0
785
- };
786
- const SINES = {
787
- 0: 0,
788
- 90: 1,
789
- 180: 0,
790
- 270: -1
791
- };
792
- /** Computes the transform from image pixels to viewport pixels. Painting and pointer conversion both use it. */
793
- function computeTransform(view, image, viewport) {
794
- const cosine = COSINES[view.rotation] * view.zoom;
795
- const sine = SINES[view.rotation] * view.zoom;
796
- const centerX = viewport.width / 2 + view.panX;
797
- const centerY = viewport.height / 2 + view.panY;
798
- return [
799
- cosine,
800
- sine,
801
- -sine,
802
- cosine,
803
- centerX - (cosine * image.width - sine * image.height) / 2,
804
- centerY - (sine * image.width + cosine * image.height) / 2
805
- ];
806
- }
807
- // src/render/renderer.ts
808
- /** Paints scenes on a canvas and on the overlay above it. It decides nothing, and paints at most once per frame. */
809
- var Renderer = class {
810
- canvas;
811
- overlay;
812
- getScene;
813
- frame = null;
814
- pixelRatio = 1;
815
- viewport = {
816
- width: 0,
817
- height: 0
818
- };
819
- constructor(canvas, overlay, getScene) {
820
- this.canvas = canvas;
821
- this.overlay = overlay;
822
- this.getScene = getScene;
719
+ deactivate() {
720
+ this.select(null);
721
+ for (const handle of this.handles) handle.remove();
823
722
  }
824
- /** Sizes the canvases in device pixels, so they stay sharp on high density screens. */
825
- resize(viewport, pixelRatio) {
826
- this.viewport = viewport;
827
- this.pixelRatio = pixelRatio;
828
- for (const canvas of [this.canvas, this.overlay]) {
829
- canvas.width = Math.round(viewport.width * pixelRatio);
830
- canvas.height = Math.round(viewport.height * pixelRatio);
723
+ /** Selects a corner, or none with `null`, and tells the user what to do next. */
724
+ select(index) {
725
+ if (index === this.selected) return;
726
+ this.selected = index;
727
+ this.handles.forEach((handle, position) => handle.setAttribute("aria-pressed", String(position === index)));
728
+ if (index === null) {
729
+ this.host.setHint(null);
730
+ return;
831
731
  }
832
- this.requestPaint();
732
+ const labels = this.host.labels();
733
+ const text = labels.cornerSelected(labels[CORNER_LABELS[index]]);
734
+ this.host.setHint(text);
735
+ this.host.announce(text);
833
736
  }
834
- /** Schedules a paint for the next frame. Several calls in one frame paint once. */
835
- requestPaint() {
836
- this.frame ??= requestAnimationFrame(() => {
837
- this.frame = null;
838
- this.paint();
737
+ move(index, point) {
738
+ this.corners = this.constrain(this.corners, index, point, this.host.frameSize());
739
+ this.update();
740
+ this.host.requestPaint();
741
+ }
742
+ announce(index) {
743
+ const { x, y } = this.corners[index];
744
+ const labels = this.host.labels();
745
+ this.host.announce(labels.cornerMoved(labels[CORNER_LABELS[index]], Math.round(x), Math.round(y)));
746
+ }
747
+ createHandle(label, index) {
748
+ const handle = document.createElement("button");
749
+ handle.type = "button";
750
+ handle.className = "paperpic-handle";
751
+ handle.dataset.paperpicControl = label;
752
+ handle.setAttribute("aria-label", this.host.labels()[label]);
753
+ handle.setAttribute("aria-pressed", "false");
754
+ let grab = null;
755
+ let last = {
756
+ x: 0,
757
+ y: 0
758
+ };
759
+ let before = this.corners;
760
+ let travelled = 0;
761
+ let tapped = false;
762
+ const localPoint = (event) => {
763
+ const { left, top } = this.host.layer.getBoundingClientRect();
764
+ return {
765
+ x: event.clientX - left,
766
+ y: event.clientY - top
767
+ };
768
+ };
769
+ handle.addEventListener("pointerdown", (event) => {
770
+ event.stopPropagation();
771
+ handle.setPointerCapture(event.pointerId);
772
+ const { x, y } = this.host.frameToViewport(this.corners[index]);
773
+ const point = localPoint(event);
774
+ grab = {
775
+ x: point.x - x,
776
+ y: point.y - y
777
+ };
778
+ last = point;
779
+ before = this.corners;
780
+ travelled = 0;
781
+ tapped = false;
782
+ if (event.pointerType !== "mouse") {
783
+ this.setOthersHidden(handle, true);
784
+ this.showMagnifier(index, point);
785
+ }
839
786
  });
787
+ handle.addEventListener("pointermove", (event) => {
788
+ if (!grab) return;
789
+ const point = localPoint(event);
790
+ travelled += Math.hypot(point.x - last.x, point.y - last.y);
791
+ last = point;
792
+ this.move(index, this.host.viewportToFrame({
793
+ x: point.x - grab.x,
794
+ y: point.y - grab.y
795
+ }));
796
+ if (event.pointerType !== "mouse") this.showMagnifier(index, point);
797
+ });
798
+ const release = (event) => {
799
+ if (!grab) return;
800
+ grab = null;
801
+ this.magnifier = null;
802
+ this.setOthersHidden(handle, false);
803
+ if (travelled < 10) {
804
+ tapped = event.type === "pointerup";
805
+ this.corners = before;
806
+ this.update();
807
+ } else {
808
+ this.select(null);
809
+ this.announce(index);
810
+ }
811
+ this.host.requestPaint();
812
+ };
813
+ handle.addEventListener("pointerup", release);
814
+ handle.addEventListener("pointercancel", release);
815
+ handle.addEventListener("click", (event) => {
816
+ if (event.detail > 0 && !tapped) return;
817
+ tapped = false;
818
+ this.select(this.selected === index ? null : index);
819
+ });
820
+ handle.addEventListener("focus", () => this.host.reveal(this.corners[index]));
821
+ handle.addEventListener("keydown", (event) => {
822
+ const direction = REVEAL_DIRECTIONS[event.key];
823
+ if (!direction) return;
824
+ event.preventDefault();
825
+ event.stopPropagation();
826
+ const distance = event.shiftKey ? SHIFT_STEP : 1;
827
+ const position = this.host.frameToViewport(this.corners[index]);
828
+ this.move(index, this.host.viewportToFrame({
829
+ x: position.x + direction.x * distance,
830
+ y: position.y + direction.y * distance
831
+ }));
832
+ this.host.reveal(this.corners[index]);
833
+ this.announce(index);
834
+ });
835
+ return handle;
840
836
  }
841
- /** Cancels a pending paint. */
842
- destroy() {
843
- if (this.frame !== null) {
844
- cancelAnimationFrame(this.frame);
845
- this.frame = null;
846
- }
847
- }
848
- paint() {
849
- const scene = this.getScene();
850
- this.paintImage(scene);
851
- this.paintOverlay(scene);
852
- }
853
- paintImage(scene) {
854
- const context = this.canvas.getContext("2d");
855
- if (!context) return;
856
- context.setTransform(1, 0, 0, 1, 0, 0);
857
- context.clearRect(0, 0, this.canvas.width, this.canvas.height);
858
- if (!scene) return;
859
- const [a, b, c, d, e, f] = computeTransform(scene.view, scene.imageSize, this.viewport);
860
- const ratio = this.pixelRatio;
861
- context.setTransform(a * ratio, b * ratio, c * ratio, d * ratio, e * ratio, f * ratio);
862
- context.imageSmoothingEnabled = true;
863
- context.imageSmoothingQuality = "high";
864
- context.drawImage(scene.image, 0, 0, scene.imageSize.width, scene.imageSize.height);
837
+ setOthersHidden(handle, hidden) {
838
+ for (const other of this.handles) other.hidden = hidden && other !== handle;
865
839
  }
866
- paintOverlay(scene) {
867
- const context = this.overlay.getContext("2d");
868
- if (!context) return;
869
- context.setTransform(1, 0, 0, 1, 0, 0);
870
- context.clearRect(0, 0, this.overlay.width, this.overlay.height);
871
- if (scene?.drawOverlay) {
872
- context.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
873
- scene.drawOverlay(context);
874
- }
840
+ showMagnifier(index, finger) {
841
+ const { width, height } = this.host.layer.getBoundingClientRect();
842
+ this.magnifier = placeMagnifier(this.corners[index], finger, {
843
+ width,
844
+ height
845
+ });
846
+ this.host.requestPaint();
875
847
  }
876
848
  };
877
- // src/state/history.ts
878
- /** An empty history. */
879
- function createHistory() {
880
- return {
881
- done: [],
882
- undone: []
883
- };
884
- }
885
- /** Adds an edit. What could be redone is lost, as in any editor. */
886
- function addToHistory({ done }, item) {
887
- return {
888
- done: [...done, item],
889
- undone: []
890
- };
891
- }
892
- /** Moves the last edit to what can be redone. */
893
- function undoHistory(history) {
894
- const last = history.done.at(-1);
895
- return last === void 0 ? history : {
896
- done: history.done.slice(0, -1),
897
- undone: [...history.undone, last]
898
- };
899
- }
900
- /** Brings back the last edit undone. */
901
- function redoHistory(history) {
902
- const last = history.undone.at(-1);
903
- return last === void 0 ? history : {
904
- done: [...history.done, last],
905
- undone: history.undone.slice(0, -1)
906
- };
907
- }
908
- // src/state/view.ts
909
- const MAX_ZOOM = 8;
910
- /** A view of the whole image that nothing has measured yet. */
911
- function createView() {
912
- return {
913
- zoom: 1,
914
- panX: 0,
915
- panY: 0,
916
- rotation: 0,
917
- fit: "image"
918
- };
919
- }
920
- /** The size of the image as the user sees it, turned. */
921
- function displayedSize(image, rotation) {
922
- return rotation === 90 || rotation === 270 ? {
923
- width: image.height,
924
- height: image.width
925
- } : image;
926
- }
927
- /** Converts a position in the image as the user sees it, turned, to the viewport. */
928
- function frameToViewport(view, image, viewport, { x, y }) {
929
- const { width, height } = displayedSize(image, view.rotation);
930
- return {
931
- x: viewport.width / 2 + view.panX + (x - width / 2) * view.zoom,
932
- y: viewport.height / 2 + view.panY + (y - height / 2) * view.zoom
933
- };
934
- }
935
- /** Converts a position in the viewport to the image as the user sees it, turned. */
936
- function viewportToFrame(view, image, viewport, { x, y }) {
937
- const { width, height } = displayedSize(image, view.rotation);
849
+ /**
850
+ * The session of a tool that edits corners. Crop and Straighten differ only in how they constrain the corners, which
851
+ * goes to the editor, and in the edit that their corners mean, which `confirm` returns.
852
+ */
853
+ function cornerSession(editor, confirm) {
938
854
  return {
939
- x: (x - viewport.width / 2 - view.panX) / view.zoom + width / 2,
940
- y: (y - viewport.height / 2 - view.panY) / view.zoom + height / 2
855
+ anchor: () => editor.anchor(),
856
+ focus: () => editor.focus(),
857
+ update: () => editor.update(),
858
+ drawOverlay: (context) => editor.drawOverlay(context),
859
+ deactivate: () => editor.deactivate(),
860
+ tap: (point) => editor.place(point),
861
+ escape: () => editor.deselect(),
862
+ confirm
941
863
  };
942
864
  }
943
- function fitZoom(fit, image, viewport, rotation) {
944
- const { width, height } = displayedSize(image, rotation);
945
- const byWidth = viewport.width / width;
946
- const byHeight = viewport.height / height;
947
- switch (fit) {
948
- case "width": return byWidth;
949
- case "height": return byHeight;
950
- case "image": return Math.min(byWidth, byHeight);
865
+ // src/tools/crop.ts
866
+ /** Keeps a rectangle of the image, which the user adjusts by its corners. */
867
+ const cropTool = {
868
+ id: "crop",
869
+ hint: "cropHint",
870
+ actions: [{
871
+ id: "crop",
872
+ run: (context) => context.openTool("crop")
873
+ }],
874
+ activate(host) {
875
+ const frame = host.frameSize();
876
+ const editor = new CornerEditor(host, initialCorners(frame), constrainToRectangle);
877
+ return cornerSession(editor, () => {
878
+ const [topLeft, , bottomRight] = editor.points;
879
+ const rect = {
880
+ x: topLeft.x / frame.width,
881
+ y: topLeft.y / frame.height,
882
+ width: (bottomRight.x - topLeft.x) / frame.width,
883
+ height: (bottomRight.y - topLeft.y) / frame.height
884
+ };
885
+ return rect.width >= 1 && rect.height >= 1 ? null : {
886
+ type: "crop",
887
+ rect
888
+ };
889
+ });
951
890
  }
952
- }
953
- /** The zoom range for an image. Fitting a very small image can go over the usual maximum. */
954
- function zoomLimits(image, viewport, rotation) {
955
- return {
956
- min: Math.min(fitZoom("image", image, viewport, rotation), 1),
957
- max: Math.max(MAX_ZOOM, fitZoom("width", image, viewport, rotation), fitZoom("height", image, viewport, rotation))
958
- };
959
- }
891
+ };
892
+ // src/tools/flip.ts
893
+ /** Mirrors the image left to right, at once. A vertical flip is a flip and a half turn. */
894
+ const flipTool = {
895
+ id: "flip",
896
+ actions: [{
897
+ id: "flip",
898
+ run: (context) => context.addOperation({ type: "flip" })
899
+ }]
900
+ };
901
+ // src/tools/perspective.ts
902
+ /** Straightens a document, whose 4 corners the user places on the photo. */
903
+ const perspectiveTool = {
904
+ id: "perspective",
905
+ hint: "perspectiveHint",
906
+ actions: [{
907
+ id: "perspective",
908
+ run: (context) => context.openTool("perspective")
909
+ }],
910
+ activate(host) {
911
+ const frame = host.frameSize();
912
+ const editor = new CornerEditor(host, initialCorners(frame), constrainToConvex);
913
+ return cornerSession(editor, () => {
914
+ const corners = editor.points;
915
+ const [topLeft, topRight, bottomRight, bottomLeft] = corners;
916
+ if (topLeft.x === 0 && topLeft.y === 0 && topRight.x === frame.width && topRight.y === 0 && bottomRight.x === frame.width && bottomRight.y === frame.height && bottomLeft.x === 0 && bottomLeft.y === frame.height) return null;
917
+ const { photo, origin } = host.photoFrame();
918
+ const inPhoto = corners.map(({ x, y }) => ({
919
+ x: x + origin.x,
920
+ y: y + origin.y
921
+ }));
922
+ return {
923
+ type: "perspective",
924
+ quad: corners.map(({ x, y }) => ({
925
+ x: x / frame.width,
926
+ y: y / frame.height
927
+ })),
928
+ aspectRatio: host.aspectRatio() ?? estimateAspectRatio(inPhoto, photo)
929
+ };
930
+ });
931
+ }
932
+ };
933
+ // src/tools/rotate.ts
934
+ /** Turns the image a quarter turn to the left, at once, as photo galleries do. Four presses cover every turn. */
935
+ const rotateTool = {
936
+ id: "rotate",
937
+ actions: [{
938
+ id: "rotateLeft",
939
+ icon: "rotateDocument",
940
+ run: (context) => context.addOperation({
941
+ type: "rotate",
942
+ direction: -1
943
+ })
944
+ }]
945
+ };
946
+ // src/tools/threshold.ts
960
947
  /**
961
- * Keeps the image from leaving the viewport, and centers it along any side where it fits.
962
- * `sideMargin` is how far an image that overflows can go past its sides, so a toolbar over it never hides a part for good.
948
+ * Cleans up a document. It is a setting that always runs last, so its button opens a panel with a switch and the
949
+ * ruler of its sensitivity, and Done leaves one edit.
963
950
  */
964
- function clampPan(view, image, viewport, sideMargin = 0) {
965
- const { width, height } = displayedSize(image, view.rotation);
966
- const margin = overflows(view, image, viewport) ? sideMargin : 0;
967
- const limitX = Math.max(0, (width * view.zoom - viewport.width) / 2) + margin;
968
- const limitY = Math.max(0, (height * view.zoom - viewport.height) / 2);
951
+ const thresholdTool = {
952
+ id: "threshold",
953
+ actions: [{
954
+ id: "threshold",
955
+ run: (context) => context.openTool("threshold")
956
+ }]
957
+ };
958
+ /** What Clean up shows when it opens: turned on, so the preview shows what it does, with the sensitivity of the edits. */
959
+ function openThreshold(operations) {
969
960
  return {
970
- ...view,
971
- panX: Math.min(limitX, Math.max(-limitX, view.panX)),
972
- panY: Math.min(limitY, Math.max(-limitY, view.panY))
961
+ enabled: true,
962
+ sensitivity: thresholdSetting(operations).sensitivity
973
963
  };
974
964
  }
975
- /** Applies a fit. When the image overflows, it starts from its top left corner, where reading starts. */
976
- function fitView(view, fit, image, viewport) {
977
- const zoom = fitZoom(fit, image, viewport, view.rotation);
978
- return clampPan({
979
- ...view,
980
- zoom,
981
- fit,
982
- panX: Number.POSITIVE_INFINITY,
983
- panY: Number.POSITIVE_INFINITY
984
- }, image, viewport);
985
- }
986
- /**
987
- * Sets the zoom and keeps the image point under `point` in place.
988
- * A value out of range is clamped to the zoom limits.
989
- */
990
- function zoomTo(view, zoom, point, image, viewport, sideMargin = 0) {
991
- const { min, max } = zoomLimits(image, viewport, view.rotation);
992
- const next = Math.min(max, Math.max(min, zoom));
993
- const scale = next / view.zoom;
994
- const fromCenterX = point.x - viewport.width / 2;
995
- const fromCenterY = point.y - viewport.height / 2;
996
- return clampPan({
997
- ...view,
998
- zoom: next,
999
- fit: null,
1000
- panX: fromCenterX - (fromCenterX - view.panX) * scale,
1001
- panY: fromCenterY - (fromCenterY - view.panY) * scale
1002
- }, image, viewport, sideMargin);
1003
- }
1004
- /** Moves the image by a distance in CSS pixels. */
1005
- function panBy(view, deltaX, deltaY, image, viewport, sideMargin = 0) {
1006
- return clampPan({
1007
- ...view,
1008
- panX: view.panX + deltaX,
1009
- panY: view.panY + deltaY
1010
- }, image, viewport, sideMargin);
1011
- }
1012
- /** Sets the rotation, keeping the fit in effect if there is one. */
1013
- function setRotation(view, rotation, image, viewport) {
1014
- if (rotation === view.rotation) return view;
1015
- const rotated = {
1016
- ...view,
1017
- rotation,
1018
- panX: 0,
1019
- panY: 0
965
+ /** The edit of a setting of Clean up. `softness` is the option, which wins over the softness of the edits. */
966
+ function thresholdOperation(setting, operations, softness) {
967
+ return {
968
+ type: "threshold",
969
+ ...setting,
970
+ softness: softness ?? thresholdSetting(operations).softness
1020
971
  };
1021
- return view.fit ? fitView(rotated, view.fit, image, viewport) : clampPan(rotated, image, viewport);
1022
- }
1023
- /** Turns the view by a quarter turn. */
1024
- function rotateView(view, direction, image, viewport) {
1025
- return setRotation(view, normalizeRotation(view.rotation + 90 * direction), image, viewport);
1026
972
  }
1027
- /** Adapts the view to a new viewport size. */
1028
- function resizeView(view, image, viewport) {
1029
- return view.fit ? fitView(view, view.fit, image, viewport) : clampPan(view, image, viewport);
973
+ /** The edit that leaves Clean up at `setting`, or `null` if it already is. */
974
+ function thresholdEdit(setting, operations, softness) {
975
+ const current = thresholdSetting(operations);
976
+ return setting.enabled !== current.enabled || setting.sensitivity !== current.sensitivity ? thresholdOperation(setting, operations, softness) : null;
1030
977
  }
1031
- /** Whether the image is larger than the viewport, so there is something to pan. */
1032
- function overflows(view, image, viewport) {
1033
- const { width, height } = displayedSize(image, view.rotation);
1034
- const tolerance = .5;
1035
- return width * view.zoom > viewport.width + tolerance || height * view.zoom > viewport.height + tolerance;
1036
- }
1037
- // src/tools/adjust/index.ts
1038
978
  /**
1039
- * Changes the brightness and contrast. They are a setting that runs after the shape, so its button opens a panel that
1040
- * chooses between them, with one ruler, and Done leaves one edit with both.
979
+ * The edit that Done leaves in Clean up. A sensitivity that changes while Clean up stays off changes nothing on
980
+ * display, so it leaves none.
1041
981
  */
1042
- const adjustTool = {
1043
- id: "adjust",
1044
- actions: [{
1045
- id: "adjust",
1046
- run: (context) => context.openTool("adjust")
1047
- }]
1048
- };
1049
- // src/tools/magnifier.ts
1050
- const LENS_RADIUS = 56;
1051
- /** Places the lens above the finger, or below it at the top of the viewport, always on screen. */
1052
- function placeLens(point, finger, viewport) {
1053
- const distance = 104;
1054
- const above = finger.y - distance;
1055
- const y = above >= LENS_RADIUS ? above : finger.y + distance;
1056
- const limit = Math.max(LENS_RADIUS, viewport.width - LENS_RADIUS);
1057
- return {
1058
- point,
1059
- center: {
1060
- x: Math.min(limit, Math.max(LENS_RADIUS, finger.x)),
1061
- y
1062
- },
1063
- radius: LENS_RADIUS
1064
- };
982
+ function confirmThreshold(setting, operations, softness) {
983
+ return !setting.enabled && !thresholdSetting(operations).enabled ? null : thresholdEdit(setting, operations, softness);
1065
984
  }
1066
- // src/tools/corners.ts
1067
- const INITIAL_INSET = .1;
1068
- /** The smallest selection, in image pixels. */
1069
- const MIN_SIDE = 16;
1070
- const SHIFT_STEP = 10;
1071
- const REVEAL_DIRECTIONS = {
1072
- ArrowLeft: {
1073
- x: -1,
1074
- y: 0
1075
- },
1076
- ArrowRight: {
1077
- x: 1,
1078
- y: 0
1079
- },
1080
- ArrowUp: {
1081
- x: 0,
1082
- y: -1
1083
- },
1084
- ArrowDown: {
1085
- x: 0,
1086
- y: 1
1087
- }
1088
- };
1089
- const CORNER_LABELS = [
1090
- "cornerTopLeft",
1091
- "cornerTopRight",
1092
- "cornerBottomRight",
1093
- "cornerBottomLeft"
985
+ // src/tools/index.ts
986
+ /** Every tool, in the order the edit bar shows them. */
987
+ const TOOLS = [
988
+ cropTool,
989
+ perspectiveTool,
990
+ rotateTool,
991
+ flipTool,
992
+ adjustTool,
993
+ thresholdTool
1094
994
  ];
1095
- function clamp(value, min, max) {
1096
- return Math.min(max, Math.max(min, value));
1097
- }
1098
- /** The corners of a rectangle. */
1099
- function rectangleCorners(left, top, right, bottom) {
1100
- return [
1101
- {
1102
- x: left,
1103
- y: top
1104
- },
1105
- {
1106
- x: right,
1107
- y: top
1108
- },
1109
- {
1110
- x: right,
1111
- y: bottom
1112
- },
1113
- {
1114
- x: left,
1115
- y: bottom
1116
- }
1117
- ];
995
+ // src/options.ts
996
+ const DEFAULT_OPTIONS = {
997
+ alt: "",
998
+ aspectRatio: void 0,
999
+ download: false,
1000
+ editable: true,
1001
+ filename: void 0,
1002
+ icons: void 0,
1003
+ labels: void 0,
1004
+ maxOutputSize: void 0,
1005
+ output: void 0,
1006
+ softness: void 0,
1007
+ toolbar: true,
1008
+ tools: TOOLS.map(({ id }) => id),
1009
+ wheelZoom: true
1010
+ };
1011
+ const OPTION_NAMES = Object.keys(DEFAULT_OPTIONS);
1012
+ /** The options in use after a change. An option missing from `options` keeps its value, and `undefined` brings back its default. */
1013
+ function mergeOptions(current, options) {
1014
+ const next = { ...current };
1015
+ for (const name of OPTION_NAMES) if (name in options) Object.assign(next, { [name]: options[name] ?? DEFAULT_OPTIONS[name] });
1016
+ return next;
1118
1017
  }
1119
- /** Where the corners start: inside the image, a little in from its edges. Nothing covers them, because the toolbar hides while editing. */
1120
- function initialCorners(frame) {
1121
- const left = frame.width * INITIAL_INSET;
1122
- const top = frame.height * INITIAL_INSET;
1123
- return rectangleCorners(left, top, frame.width - left, frame.height - top);
1018
+ /**
1019
+ * Whether two values of an option are the same, looking one level into arrays and objects. Wrappers pass a new
1020
+ * `tools` or `output` with the same contents on every render, which must not count as a change.
1021
+ */
1022
+ function sameOption(a, b) {
1023
+ if (a === b) return true;
1024
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null || Array.isArray(a) !== Array.isArray(b)) return false;
1025
+ const keysA = Object.keys(a);
1026
+ const keysB = Object.keys(b);
1027
+ return keysA.length === keysB.length && keysA.every((key) => Object.is(a[key], b[key]));
1124
1028
  }
1125
- /** Keeps the corners a rectangle inside the frame, which never turns inside out. */
1126
- const constrainToRectangle = (corners, index, point, frame) => {
1127
- const opposite = corners[(index + 2) % 4];
1128
- const isLeft = index === 0 || index === 3;
1129
- const isTop = index === 0 || index === 1;
1130
- const minWidth = Math.min(MIN_SIDE, frame.width);
1131
- const minHeight = Math.min(MIN_SIDE, frame.height);
1132
- const x = isLeft ? clamp(point.x, 0, opposite.x - minWidth) : clamp(point.x, opposite.x + minWidth, frame.width);
1133
- const y = isTop ? clamp(point.y, 0, opposite.y - minHeight) : clamp(point.y, opposite.y + minHeight, frame.height);
1134
- return rectangleCorners(isLeft ? x : opposite.x, isTop ? y : opposite.y, isLeft ? opposite.x : x, isTop ? opposite.y : y);
1135
- };
1136
- function isConvex(corners, minTurn) {
1137
- return corners.every((corner, index) => {
1138
- const next = corners[(index + 1) % 4];
1139
- const last = corners[(index + 2) % 4];
1140
- return (next.x - corner.x) * (last.y - next.y) - (next.y - corner.y) * (last.x - next.x) >= minTurn;
1141
- });
1029
+ function assertInRange(name, value, valid, range) {
1030
+ if (value !== void 0 && value !== null && !valid(value)) throw new RangeError(`${name} must be ${range}, got ${value}`);
1142
1031
  }
1143
1032
  /**
1144
- * Keeps the corners a convex shape inside the frame, so they can always be straightened.
1145
- * A move that would break it slides along the side that still allows it, or stays where it was.
1033
+ * Checks the options that have a range, so that a wrong value fails where the app sets it, with a message that names
1034
+ * the option, and not later inside an edit.
1035
+ *
1036
+ * @throws {RangeError} If an option is out of its range.
1146
1037
  */
1147
- const constrainToConvex = (corners, index, point, frame) => {
1148
- const previous = corners[index];
1149
- const x = clamp(point.x, 0, frame.width);
1150
- const y = clamp(point.y, 0, frame.height);
1151
- const minSide = Math.min(MIN_SIDE, frame.width, frame.height);
1152
- const candidates = [
1153
- {
1154
- x,
1155
- y
1156
- },
1157
- {
1158
- x,
1159
- y: previous.y
1160
- },
1161
- {
1162
- x: previous.x,
1163
- y
1164
- }
1165
- ];
1166
- for (const candidate of candidates) {
1167
- const moved = corners.map((corner, position) => position === index ? candidate : corner);
1168
- if (isConvex(moved, minSide * minSide)) return moved;
1038
+ function validateOptions({ aspectRatio, maxOutputSize, output, softness }) {
1039
+ assertInRange("softness", softness, (value) => value >= 0 && value <= 1, "between 0 and 1");
1040
+ assertInRange("aspectRatio", aspectRatio, (value) => value > 0 && Number.isFinite(value), "width divided by height, such as 210 / 297 for A4");
1041
+ assertInRange("maxOutputSize", maxOutputSize, (value) => value > 0, "a positive number of pixels");
1042
+ assertInRange("output.quality", output?.quality, (value) => value >= 0 && value <= 1, "between 0 and 1");
1043
+ const type = output?.type;
1044
+ if (type !== void 0 && type !== null && !ENCODABLE.has(type)) throw new RangeError(`output.type must be ${[...ENCODABLE].map((name) => `'${name}'`).join(", ")}, got '${type}'`);
1045
+ }
1046
+ // src/pipeline/download.ts
1047
+ const DEFAULT_NAME = "image";
1048
+ const IMAGE_EXTENSION = /\.(?:jpe?g|png|webp|gif|avif|bmp|svg)$/i;
1049
+ const SAVABLE_TYPE = /^image\/(jpeg|png|webp|gif|avif|bmp)$/;
1050
+ /** The last part of a URL, or nothing for a URL that holds the data itself. */
1051
+ function nameInUrl(url) {
1052
+ if (/^(?:data|blob):/i.test(url)) return "";
1053
+ const name = url.split(/[?#]/)[0].split("/").pop();
1054
+ try {
1055
+ return decodeURIComponent(name);
1056
+ } catch {
1057
+ return name;
1169
1058
  }
1170
- return corners;
1171
- };
1172
- /** Dims what stays out of a selection, and outlines it so it shows on any image. */
1173
- function drawSelection(context, frame, selection) {
1174
- const trace = (points) => {
1175
- points.forEach(({ x, y }, index) => {
1176
- if (index === 0) context.moveTo(x, y);
1177
- else context.lineTo(x, y);
1178
- });
1179
- context.closePath();
1180
- };
1181
- context.beginPath();
1182
- trace(frame);
1183
- trace(selection);
1184
- context.fillStyle = "rgb(0 0 0 / 50%)";
1185
- context.fill("evenodd");
1186
- context.beginPath();
1187
- trace(selection);
1188
- context.lineWidth = 3;
1189
- context.strokeStyle = "rgb(0 0 0 / 60%)";
1190
- context.stroke();
1191
- context.lineWidth = 1.5;
1192
- context.strokeStyle = "#fff";
1193
- context.stroke();
1194
1059
  }
1195
1060
  /**
1196
- * The corner handles of a selection: elements that take the focus and work with a pointer and with the keyboard.
1197
- * A corner moves by dragging its handle, or by pressing the handle and then tapping the new place, which needs no drag.
1061
+ * Chooses the name of a saved file: the one given, or the name of the file or the URL that was loaded, or `image`.
1062
+ * When the format of the image is known, the name ends in its extension, so a cleaned up `receipt.jpg` saves as `receipt.png`.
1063
+ *
1064
+ * @param image What gets saved: a URL or the result of an edit.
1065
+ * @param source What was loaded, which gives the name.
1066
+ * @param filename The name the consumer chose.
1198
1067
  */
1199
- var CornerEditor = class {
1200
- host;
1201
- constrain;
1202
- handles;
1203
- corners;
1204
- lens = null;
1205
- /** The corner that the next tap on the image moves. */
1206
- selected = null;
1207
- constructor(host, corners, constrain) {
1208
- this.host = host;
1209
- this.corners = corners;
1210
- this.constrain = constrain;
1211
- this.handles = CORNER_LABELS.map((label, index) => this.createHandle(label, index));
1212
- host.layer.append(...this.handles);
1213
- this.update();
1214
- }
1215
- /** The corners, in pixels of the frame. */
1216
- get points() {
1217
- return this.corners;
1068
+ function downloadName(image, source, filename) {
1069
+ const original = source instanceof File ? source.name : typeof source === "string" ? nameInUrl(source) : "";
1070
+ const name = filename || original || DEFAULT_NAME;
1071
+ const type = typeof image === "string" ? typeFromUrl(image) : image.type;
1072
+ const subtype = type && SAVABLE_TYPE.exec(type)?.[1];
1073
+ if (!subtype) return name;
1074
+ const extension = subtype === "jpeg" ? "jpg" : subtype;
1075
+ return `${name.replace(IMAGE_EXTENSION, "") || DEFAULT_NAME}.${extension}`;
1076
+ }
1077
+ /** Makes the browser save a file, as a link with `download` would. */
1078
+ function saveFile(url, filename) {
1079
+ const link = document.createElement("a");
1080
+ link.href = url;
1081
+ link.download = filename;
1082
+ link.click();
1083
+ }
1084
+ // src/pipeline/load-image.ts
1085
+ /**
1086
+ * Loads an image from a URL or a file. It uses an image element, which respects the EXIF orientation and accepts every format the browser can show.
1087
+ *
1088
+ * @throws {Error} If the browser cannot load or decode the image.
1089
+ */
1090
+ async function loadImage(source) {
1091
+ const objectUrl = typeof source === "string" ? null : URL.createObjectURL(source);
1092
+ const release = () => {
1093
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
1094
+ };
1095
+ const element = new Image();
1096
+ element.src = objectUrl ?? source;
1097
+ try {
1098
+ await element.decode();
1099
+ } catch (cause) {
1100
+ release();
1101
+ const name = typeof source === "string" ? `"${source}"` : "the given file";
1102
+ throw new Error(`Could not load the image from ${name}. Check that it exists and that it is an image format the browser supports.`, { cause });
1218
1103
  }
1219
- /** Takes the keyboard focus, without scrolling the page or the viewer. */
1220
- focus() {
1221
- this.handles[0].focus({ preventScroll: true });
1104
+ if (element.naturalWidth === 0 || element.naturalHeight === 0) {
1105
+ release();
1106
+ throw new Error("The image has no size. If it is an SVG, give it width and height attributes.");
1222
1107
  }
1223
- update() {
1224
- this.handles.forEach((handle, index) => {
1225
- const { x, y } = this.host.frameToViewport(this.corners[index]);
1226
- handle.style.left = `${x}px`;
1227
- handle.style.top = `${y}px`;
1228
- });
1108
+ return {
1109
+ element,
1110
+ width: element.naturalWidth,
1111
+ height: element.naturalHeight,
1112
+ release
1113
+ };
1114
+ }
1115
+ // src/pipeline/photo-frame.ts
1116
+ /**
1117
+ * Follows crops, rotations and flips back to the photo, because estimating proportions needs its center.
1118
+ * After a perspective change that center no longer means anything, so the result counts as a new photo.
1119
+ */
1120
+ function photoFrame(image, steps) {
1121
+ let photo = {
1122
+ width: image.width,
1123
+ height: image.height
1124
+ };
1125
+ let origin = {
1126
+ x: 0,
1127
+ y: 0
1128
+ };
1129
+ let region = photo;
1130
+ for (const step of steps) switch (step.type) {
1131
+ case "rotate":
1132
+ for (let turns = step.rotation / 90; turns > 0; turns--) {
1133
+ origin = {
1134
+ x: photo.height - origin.y - region.height,
1135
+ y: origin.x
1136
+ };
1137
+ photo = {
1138
+ width: photo.height,
1139
+ height: photo.width
1140
+ };
1141
+ region = {
1142
+ width: region.height,
1143
+ height: region.width
1144
+ };
1145
+ }
1146
+ break;
1147
+ case "flip":
1148
+ origin = {
1149
+ x: photo.width - origin.x - region.width,
1150
+ y: origin.y
1151
+ };
1152
+ break;
1153
+ case "crop":
1154
+ origin = {
1155
+ x: origin.x + step.rect.x * region.width,
1156
+ y: origin.y + step.rect.y * region.height
1157
+ };
1158
+ region = {
1159
+ width: step.rect.width * region.width,
1160
+ height: step.rect.height * region.height
1161
+ };
1162
+ break;
1163
+ case "perspective":
1164
+ region = estimateOutputSize(scaleQuad(step.quad, region.width, region.height), region, { aspectRatio: step.aspectRatio });
1165
+ photo = region;
1166
+ origin = {
1167
+ x: 0,
1168
+ y: 0
1169
+ };
1229
1170
  }
1230
- drawOverlay(context) {
1231
- const { width, height } = this.host.frameSize();
1232
- drawSelection(context, rectangleCorners(0, 0, width, height).map((point) => this.host.frameToViewport(point)), this.corners.map((point) => this.host.frameToViewport(point)));
1233
- if (this.lens) this.host.paintLens(context, this.lens);
1171
+ return {
1172
+ photo,
1173
+ origin
1174
+ };
1175
+ }
1176
+ // src/pipeline/preview.ts
1177
+ /** The size of the copy that previews work on. It keeps each step well under a second on a phone. */
1178
+ const PREVIEW_PIXELS = 2e6;
1179
+ /**
1180
+ * Computes what the edits look like, on a small copy of the image.
1181
+ * The result reports the size at full resolution, so it paints at the same scale as the final image.
1182
+ * `steps` change the shape of the image, and `tone` changes its tones afterwards, or is `null` if nothing does.
1183
+ */
1184
+ async function renderPreview(image, steps, tone, runner) {
1185
+ const plan = planRead(image, steps, { maxPixels: PREVIEW_PIXELS });
1186
+ const pixels = readPixels(image.element, plan);
1187
+ let canvas;
1188
+ let tint;
1189
+ const paint = ({ data, width, height }) => {
1190
+ canvas.getContext("2d")?.putImageData(new ImageData(data, width, height), 0, 0);
1191
+ };
1192
+ if (tone?.type === "threshold") {
1193
+ const prepared = await runner.prepare(pixels, plan.steps);
1194
+ canvas = pixelsToCanvas(applyThreshold(prepared, tone));
1195
+ tint = (next) => {
1196
+ if (next.type === "threshold") paint(applyThreshold(prepared, next));
1197
+ };
1198
+ } else {
1199
+ const shaped = plan.steps.length > 0 ? await runner.run(pixels, plan.steps) : pixels;
1200
+ if (tone?.type === "adjust") {
1201
+ canvas = pixelsToCanvas(adjustPixels(shaped, tone));
1202
+ tint = (next) => {
1203
+ if (next.type === "adjust") paint(adjustPixels(shaped, next));
1204
+ };
1205
+ } else canvas = pixelsToCanvas(shaped);
1234
1206
  }
1235
- /** Moves the selected corner to a point of the viewport. Returns whether a corner was selected. */
1236
- place(point) {
1237
- const index = this.selected;
1238
- if (index === null) return false;
1239
- this.select(null);
1240
- this.move(index, this.host.viewportToFrame(point));
1241
- this.announce(index);
1242
- return true;
1207
+ return {
1208
+ element: canvas,
1209
+ ...resultSize(image, steps),
1210
+ tint,
1211
+ release: () => releaseCanvas(canvas)
1212
+ };
1213
+ }
1214
+ // src/pipeline/preview-queue.ts
1215
+ /**
1216
+ * Computes the previews of the edits, one at a time. While one is on its way, a newer one waits, and replaces any that
1217
+ * was already waiting, so a quick run of Undo or Flip reads the pixels twice and not once per press. It also repaints
1218
+ * the tones at most once per frame, because a ruler sends more `input` events than the screen has frames.
1219
+ */
1220
+ var PreviewQueue = class {
1221
+ host;
1222
+ id = 0;
1223
+ running = false;
1224
+ waiting = null;
1225
+ tintFrame = null;
1226
+ pendingTone = null;
1227
+ /** Whether a preview was asked for and has not arrived yet. */
1228
+ pending = false;
1229
+ constructor(host) {
1230
+ this.host = host;
1243
1231
  }
1244
- /** Where zoom keeps its place: the selected corner, or else the focused one, in the viewport. `null` for neither. */
1245
- anchor() {
1246
- const focused = this.handles.findIndex((handle) => handle === document.activeElement);
1247
- const index = this.selected ?? (focused >= 0 ? focused : null);
1248
- return index === null ? null : this.host.frameToViewport(this.corners[index]);
1232
+ /** Asks for the preview of these edits, which replaces any asked for before. */
1233
+ request(steps, tone) {
1234
+ const id = ++this.id;
1235
+ this.pending = true;
1236
+ if (this.running) {
1237
+ this.waiting = {
1238
+ id,
1239
+ steps,
1240
+ tone
1241
+ };
1242
+ return;
1243
+ }
1244
+ this.run(id, steps, tone);
1245
+ }
1246
+ /** Forgets every preview asked for, so none arrives, and any tones waiting for a frame. */
1247
+ forget() {
1248
+ this.id++;
1249
+ this.pending = false;
1250
+ this.cancelTint();
1251
+ }
1252
+ /** Repaints the tones on the next frame, with the latest ones. */
1253
+ scheduleTint(tone) {
1254
+ this.pendingTone = tone;
1255
+ this.tintFrame ??= requestAnimationFrame(() => {
1256
+ this.tintFrame = null;
1257
+ const latest = this.pendingTone;
1258
+ this.pendingTone = null;
1259
+ if (latest) this.host.tint(latest);
1260
+ });
1249
1261
  }
1250
- /** Lets go of the selected corner. Returns whether a corner was selected. */
1251
- deselect() {
1252
- const wasSelected = this.selected !== null;
1253
- this.select(null);
1254
- return wasSelected;
1262
+ cancelTint() {
1263
+ if (this.tintFrame !== null) {
1264
+ cancelAnimationFrame(this.tintFrame);
1265
+ this.tintFrame = null;
1266
+ }
1267
+ this.pendingTone = null;
1255
1268
  }
1256
- deactivate() {
1257
- this.select(null);
1258
- for (const handle of this.handles) handle.remove();
1269
+ /** Renders one preview, and then the one that waits, unless newer edits or `forget()` made it outdated. */
1270
+ async run(id, steps, tone) {
1271
+ this.running = true;
1272
+ try {
1273
+ await this.render(id, steps, tone);
1274
+ } finally {
1275
+ this.running = false;
1276
+ const waiting = this.waiting;
1277
+ this.waiting = null;
1278
+ if (waiting?.id === this.id) this.run(waiting.id, waiting.steps, waiting.tone);
1279
+ }
1259
1280
  }
1260
- /** Selects a corner, or none with `null`, and tells the user what to do next. */
1261
- select(index) {
1262
- if (index === this.selected) return;
1263
- this.selected = index;
1264
- this.handles.forEach((handle, position) => handle.setAttribute("aria-pressed", String(position === index)));
1265
- if (index === null) {
1266
- this.host.setHint(null);
1281
+ async render(id, steps, tone) {
1282
+ let preview;
1283
+ try {
1284
+ preview = await this.host.render(steps, tone);
1285
+ } catch (cause) {
1286
+ if (id === this.id) {
1287
+ this.pending = false;
1288
+ this.host.failed(cause);
1289
+ }
1267
1290
  return;
1268
1291
  }
1269
- const labels = this.host.labels();
1270
- const text = labels.cornerSelected(labels[CORNER_LABELS[index]]);
1271
- this.host.setHint(text);
1272
- this.host.announce(text);
1292
+ if (id !== this.id) {
1293
+ preview.release();
1294
+ return;
1295
+ }
1296
+ this.pending = false;
1297
+ this.host.ready(preview);
1273
1298
  }
1274
- move(index, point) {
1275
- this.corners = this.constrain(this.corners, index, point, this.host.frameSize());
1276
- this.update();
1277
- this.host.requestPaint();
1299
+ };
1300
+ // src/pipeline/runner.ts
1301
+ /** How long a worker can take to start before the main thread does the work instead. */
1302
+ const WORKER_START_LIMIT = 5e3;
1303
+ /**
1304
+ * Runs the pipeline in a worker, so large images do not freeze the page.
1305
+ * If a worker cannot start, for example because a Content Security Policy blocks it, the main thread does the work.
1306
+ */
1307
+ var PipelineRunner = class {
1308
+ worker = null;
1309
+ jobs = /* @__PURE__ */ new Map();
1310
+ abandonStart = null;
1311
+ current = null;
1312
+ nextId = 0;
1313
+ destroyed = false;
1314
+ /** Runs the steps. The buffer of `source` is transferred to the worker, so it cannot be used afterwards. */
1315
+ async run(source, steps) {
1316
+ const worker = await this.ready();
1317
+ return worker ? this.send(worker, "pipeline", source, steps, (response) => response.result) : applySteps(source, steps);
1278
1318
  }
1279
- announce(index) {
1280
- const { x, y } = this.corners[index];
1281
- const labels = this.host.labels();
1282
- this.host.announce(labels.cornerMoved(labels[CORNER_LABELS[index]], Math.round(x), Math.round(y)));
1319
+ /** Runs the steps and prepares a threshold on the result, which a ruler can then change at once. The buffer is transferred too. */
1320
+ async prepare(source, steps) {
1321
+ const worker = await this.ready();
1322
+ return worker ? this.send(worker, "prepare", source, steps, (response) => response.prepared) : prepareThreshold(applySteps(source, steps));
1283
1323
  }
1284
- createHandle(label, index) {
1285
- const handle = document.createElement("button");
1286
- handle.type = "button";
1287
- handle.className = "paperpic-handle";
1288
- handle.dataset.paperpicControl = label;
1289
- handle.setAttribute("aria-label", this.host.labels()[label]);
1290
- handle.setAttribute("aria-pressed", "false");
1291
- let grab = null;
1292
- let last = {
1293
- x: 0,
1294
- y: 0
1295
- };
1296
- let before = this.corners;
1297
- let travelled = 0;
1298
- let tapped = false;
1299
- const localPoint = (event) => {
1300
- const { left, top } = this.host.layer.getBoundingClientRect();
1301
- return {
1302
- x: event.clientX - left,
1303
- y: event.clientY - top
1324
+ async ready() {
1325
+ this.worker ??= this.start();
1326
+ const worker = await this.worker;
1327
+ if (this.destroyed) throw new Error("The viewer was destroyed while processing.");
1328
+ return worker;
1329
+ }
1330
+ /** Stops the worker, even one still starting. A job in progress fails. */
1331
+ destroy() {
1332
+ this.destroyed = true;
1333
+ this.abandonStart?.();
1334
+ this.current?.terminate();
1335
+ this.current = null;
1336
+ this.rejectJobs(/* @__PURE__ */ new Error("The viewer was destroyed while processing."));
1337
+ }
1338
+ /**
1339
+ * Waits for the worker to report that it loaded. Sending a job earlier would lose its pixels if the worker
1340
+ * turns out to be blocked, because they are transferred and not copied.
1341
+ */
1342
+ start() {
1343
+ return new Promise((resolve) => {
1344
+ let worker;
1345
+ try {
1346
+ worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
1347
+ } catch {
1348
+ resolve(null);
1349
+ return;
1350
+ }
1351
+ this.current = worker;
1352
+ let timer;
1353
+ const settle = (result) => {
1354
+ clearTimeout(timer);
1355
+ this.abandonStart = null;
1356
+ if (!result) {
1357
+ worker.terminate();
1358
+ this.current = null;
1359
+ }
1360
+ resolve(result);
1304
1361
  };
1305
- };
1306
- handle.addEventListener("pointerdown", (event) => {
1307
- event.stopPropagation();
1308
- handle.setPointerCapture(event.pointerId);
1309
- const { x, y } = this.host.frameToViewport(this.corners[index]);
1310
- const point = localPoint(event);
1311
- grab = {
1312
- x: point.x - x,
1313
- y: point.y - y
1362
+ timer = setTimeout(settle, WORKER_START_LIMIT, null);
1363
+ this.abandonStart = () => settle(null);
1364
+ worker.onerror = () => settle(null);
1365
+ worker.onmessage = () => {
1366
+ this.listen(worker);
1367
+ settle(worker);
1314
1368
  };
1315
- last = point;
1316
- before = this.corners;
1317
- travelled = 0;
1318
- tapped = false;
1319
- if (event.pointerType !== "mouse") {
1320
- this.setOthersHidden(handle, true);
1321
- this.showLens(index, point);
1322
- }
1323
- });
1324
- handle.addEventListener("pointermove", (event) => {
1325
- if (!grab) return;
1326
- const point = localPoint(event);
1327
- travelled += Math.hypot(point.x - last.x, point.y - last.y);
1328
- last = point;
1329
- this.move(index, this.host.viewportToFrame({
1330
- x: point.x - grab.x,
1331
- y: point.y - grab.y
1332
- }));
1333
- if (event.pointerType !== "mouse") this.showLens(index, point);
1334
1369
  });
1335
- const release = (event) => {
1336
- if (!grab) return;
1337
- grab = null;
1338
- this.lens = null;
1339
- this.setOthersHidden(handle, false);
1340
- if (travelled < 10) {
1341
- tapped = event.type === "pointerup";
1342
- this.corners = before;
1343
- this.update();
1344
- } else {
1345
- this.select(null);
1346
- this.announce(index);
1347
- }
1348
- this.host.requestPaint();
1370
+ }
1371
+ listen(worker) {
1372
+ worker.onerror = (event) => {
1373
+ worker.terminate();
1374
+ this.current = null;
1375
+ this.worker = null;
1376
+ this.rejectJobs(/* @__PURE__ */ new Error(`The image could not be processed: ${event.message}`));
1349
1377
  };
1350
- handle.addEventListener("pointerup", release);
1351
- handle.addEventListener("pointercancel", release);
1352
- handle.addEventListener("click", (event) => {
1353
- if (event.detail > 0 && !tapped) return;
1354
- tapped = false;
1355
- this.select(this.selected === index ? null : index);
1356
- });
1357
- handle.addEventListener("focus", () => this.host.reveal(this.corners[index]));
1358
- handle.addEventListener("keydown", (event) => {
1359
- const direction = REVEAL_DIRECTIONS[event.key];
1360
- if (!direction) return;
1361
- event.preventDefault();
1362
- event.stopPropagation();
1363
- const distance = event.shiftKey ? SHIFT_STEP : 1;
1364
- const position = this.host.frameToViewport(this.corners[index]);
1365
- this.move(index, this.host.viewportToFrame({
1366
- x: position.x + direction.x * distance,
1367
- y: position.y + direction.y * distance
1368
- }));
1369
- this.host.reveal(this.corners[index]);
1370
- this.announce(index);
1378
+ worker.onmessage = ({ data }) => {
1379
+ if ("ready" in data) return;
1380
+ const job = this.jobs.get(data.id);
1381
+ this.jobs.delete(data.id);
1382
+ if ("error" in data) job?.reject(new Error(data.error));
1383
+ else job?.resolve(data);
1384
+ };
1385
+ }
1386
+ rejectJobs(reason) {
1387
+ for (const job of this.jobs.values()) job.reject(reason);
1388
+ this.jobs.clear();
1389
+ }
1390
+ send(worker, operation, source, steps, pick) {
1391
+ return new Promise((resolve, reject) => {
1392
+ const id = this.nextId++;
1393
+ this.jobs.set(id, {
1394
+ resolve: (response) => resolve(pick(response)),
1395
+ reject
1396
+ });
1397
+ worker.postMessage({
1398
+ id,
1399
+ operation,
1400
+ source,
1401
+ steps
1402
+ }, [source.data.buffer]);
1371
1403
  });
1372
- return handle;
1373
1404
  }
1374
- setOthersHidden(handle, hidden) {
1375
- for (const other of this.handles) other.hidden = hidden && other !== handle;
1405
+ };
1406
+ // src/render/transform.ts
1407
+ const COSINES = {
1408
+ 0: 1,
1409
+ 90: 0,
1410
+ 180: -1,
1411
+ 270: 0
1412
+ };
1413
+ const SINES = {
1414
+ 0: 0,
1415
+ 90: 1,
1416
+ 180: 0,
1417
+ 270: -1
1418
+ };
1419
+ /**
1420
+ * Computes the transform from image pixels to viewport pixels, which paints the image and the magnifier. Pointer
1421
+ * positions convert through the frame instead, with `frameToViewport()` and `viewportToFrame()` of `state/view.ts`.
1422
+ */
1423
+ function computeTransform(view, image, viewport) {
1424
+ const cosine = COSINES[view.rotation] * view.zoom;
1425
+ const sine = SINES[view.rotation] * view.zoom;
1426
+ const centerX = viewport.width / 2 + view.panX;
1427
+ const centerY = viewport.height / 2 + view.panY;
1428
+ return [
1429
+ cosine,
1430
+ sine,
1431
+ -sine,
1432
+ cosine,
1433
+ centerX - (cosine * image.width - sine * image.height) / 2,
1434
+ centerY - (sine * image.width + cosine * image.height) / 2
1435
+ ];
1436
+ }
1437
+ // src/render/magnifier.ts
1438
+ /** How much larger the magnifier shows the image than the view does. */
1439
+ const MAGNIFIER_ZOOM = 3;
1440
+ /** Paints the image larger around a point, inside a circle with a cross at its center. */
1441
+ function paintMagnifier(context, { point, center, radius }, { view, image, viewport }) {
1442
+ const [a, b, c, d, e, f] = computeTransform(view, image, viewport);
1443
+ const target = frameToViewport(view, image, viewport, point);
1444
+ context.save();
1445
+ context.beginPath();
1446
+ context.arc(center.x, center.y, radius, 0, Math.PI * 2);
1447
+ context.clip();
1448
+ context.fillStyle = "#fff";
1449
+ context.fill();
1450
+ context.transform(a * MAGNIFIER_ZOOM, b * MAGNIFIER_ZOOM, c * MAGNIFIER_ZOOM, d * MAGNIFIER_ZOOM, center.x + (e - target.x) * MAGNIFIER_ZOOM, center.y + (f - target.y) * MAGNIFIER_ZOOM);
1451
+ context.drawImage(image.element, 0, 0, image.width, image.height);
1452
+ context.restore();
1453
+ context.beginPath();
1454
+ context.arc(center.x, center.y, radius, 0, Math.PI * 2);
1455
+ context.moveTo(center.x - 8, center.y);
1456
+ context.lineTo(center.x + 8, center.y);
1457
+ context.moveTo(center.x, center.y - 8);
1458
+ context.lineTo(center.x, center.y + 8);
1459
+ context.lineWidth = 2;
1460
+ context.strokeStyle = "#fff";
1461
+ context.stroke();
1462
+ }
1463
+ // src/render/renderer.ts
1464
+ /** Paints scenes on a canvas and on the overlay above it. It decides nothing, and paints at most once per frame. */
1465
+ var Renderer = class {
1466
+ canvas;
1467
+ overlay;
1468
+ getScene;
1469
+ frame = null;
1470
+ pixelRatio = 1;
1471
+ viewport = {
1472
+ width: 0,
1473
+ height: 0
1474
+ };
1475
+ constructor(canvas, overlay, getScene) {
1476
+ this.canvas = canvas;
1477
+ this.overlay = overlay;
1478
+ this.getScene = getScene;
1479
+ }
1480
+ /**
1481
+ * Sizes the canvases in device pixels, so they stay sharp on high density screens. A new size clears them, so the
1482
+ * caller paints with `paintNow()` before the browser shows the frame.
1483
+ */
1484
+ resize(viewport, pixelRatio) {
1485
+ this.viewport = viewport;
1486
+ this.pixelRatio = pixelRatio;
1487
+ const width = Math.round(viewport.width * pixelRatio);
1488
+ const height = Math.round(viewport.height * pixelRatio);
1489
+ for (const canvas of [this.canvas, this.overlay]) if (canvas.width !== width || canvas.height !== height) {
1490
+ canvas.width = width;
1491
+ canvas.height = height;
1492
+ }
1376
1493
  }
1377
- showLens(index, finger) {
1378
- const { width, height } = this.host.layer.getBoundingClientRect();
1379
- this.lens = placeLens(this.corners[index], finger, {
1380
- width,
1381
- height
1494
+ /**
1495
+ * Paints at once, and drops the paint scheduled for the next frame. A resize needs it: the observer of the size runs
1496
+ * after the frame callbacks, so a paint scheduled there would leave one frame blank.
1497
+ */
1498
+ paintNow() {
1499
+ if (this.frame !== null) {
1500
+ cancelAnimationFrame(this.frame);
1501
+ this.frame = null;
1502
+ }
1503
+ this.paint();
1504
+ }
1505
+ /** Schedules a paint for the next frame. Several calls in one frame paint once. */
1506
+ requestPaint() {
1507
+ this.frame ??= requestAnimationFrame(() => {
1508
+ this.frame = null;
1509
+ this.paint();
1382
1510
  });
1383
- this.host.requestPaint();
1384
1511
  }
1385
- };
1386
- // src/tools/index.ts
1387
- /** Every tool, in the order the edit bar shows them. */
1388
- const TOOLS = [
1389
- {
1390
- id: "crop",
1391
- hint: "cropHint",
1392
- actions: [{
1393
- id: "crop",
1394
- run: (context) => context.openTool("crop")
1395
- }],
1396
- activate(host) {
1397
- const frame = host.frameSize();
1398
- const editor = new CornerEditor(host, initialCorners(frame), constrainToRectangle);
1399
- return {
1400
- anchor: () => editor.anchor(),
1401
- focus: () => editor.focus(),
1402
- update: () => editor.update(),
1403
- drawOverlay: (context) => editor.drawOverlay(context),
1404
- deactivate: () => editor.deactivate(),
1405
- tap: (point) => editor.place(point),
1406
- escape: () => editor.deselect(),
1407
- confirm() {
1408
- const [topLeft, , bottomRight] = editor.points;
1409
- const rect = {
1410
- x: topLeft.x / frame.width,
1411
- y: topLeft.y / frame.height,
1412
- width: (bottomRight.x - topLeft.x) / frame.width,
1413
- height: (bottomRight.y - topLeft.y) / frame.height
1414
- };
1415
- return rect.width >= 1 && rect.height >= 1 ? null : {
1416
- type: "crop",
1417
- rect
1418
- };
1419
- }
1420
- };
1512
+ /** Cancels a pending paint. */
1513
+ destroy() {
1514
+ if (this.frame !== null) {
1515
+ cancelAnimationFrame(this.frame);
1516
+ this.frame = null;
1421
1517
  }
1422
- },
1423
- {
1424
- id: "perspective",
1425
- hint: "perspectiveHint",
1426
- actions: [{
1427
- id: "perspective",
1428
- run: (context) => context.openTool("perspective")
1429
- }],
1430
- activate(host) {
1431
- const frame = host.frameSize();
1432
- const editor = new CornerEditor(host, initialCorners(frame), constrainToConvex);
1433
- return {
1434
- anchor: () => editor.anchor(),
1435
- focus: () => editor.focus(),
1436
- update: () => editor.update(),
1437
- drawOverlay: (context) => editor.drawOverlay(context),
1438
- deactivate: () => editor.deactivate(),
1439
- tap: (point) => editor.place(point),
1440
- escape: () => editor.deselect(),
1441
- confirm() {
1442
- const corners = editor.points;
1443
- const [topLeft, topRight, bottomRight, bottomLeft] = corners;
1444
- if (topLeft.x === 0 && topLeft.y === 0 && topRight.x === frame.width && topRight.y === 0 && bottomRight.x === frame.width && bottomRight.y === frame.height && bottomLeft.x === 0 && bottomLeft.y === frame.height) return null;
1445
- const { photo, origin } = host.photoFrame();
1446
- const inPhoto = corners.map(({ x, y }) => ({
1447
- x: x + origin.x,
1448
- y: y + origin.y
1449
- }));
1450
- return {
1451
- type: "perspective",
1452
- quad: corners.map(({ x, y }) => ({
1453
- x: x / frame.width,
1454
- y: y / frame.height
1455
- })),
1456
- aspectRatio: host.aspectRatio() ?? estimateAspectRatio(inPhoto, photo)
1457
- };
1458
- }
1459
- };
1518
+ }
1519
+ paint() {
1520
+ const scene = this.getScene();
1521
+ this.paintImage(scene);
1522
+ this.paintOverlay(scene);
1523
+ }
1524
+ paintImage(scene) {
1525
+ const context = this.canvas.getContext("2d");
1526
+ if (!context) return;
1527
+ context.setTransform(1, 0, 0, 1, 0, 0);
1528
+ context.clearRect(0, 0, this.canvas.width, this.canvas.height);
1529
+ if (!scene) return;
1530
+ const [a, b, c, d, e, f] = computeTransform(scene.view, scene.imageSize, this.viewport);
1531
+ const ratio = this.pixelRatio;
1532
+ context.setTransform(a * ratio, b * ratio, c * ratio, d * ratio, e * ratio, f * ratio);
1533
+ context.imageSmoothingEnabled = true;
1534
+ context.imageSmoothingQuality = "high";
1535
+ context.drawImage(scene.image, 0, 0, scene.imageSize.width, scene.imageSize.height);
1536
+ }
1537
+ paintOverlay(scene) {
1538
+ const context = this.overlay.getContext("2d");
1539
+ if (!context) return;
1540
+ context.setTransform(1, 0, 0, 1, 0, 0);
1541
+ context.clearRect(0, 0, this.overlay.width, this.overlay.height);
1542
+ if (scene?.drawOverlay) {
1543
+ context.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
1544
+ scene.drawOverlay(context);
1460
1545
  }
1461
- },
1462
- {
1463
- id: "rotate",
1464
- actions: [{
1465
- id: "rotateLeft",
1466
- icon: "rotateDocument",
1467
- run: (context) => context.addOperation({
1468
- type: "rotate",
1469
- direction: -1
1470
- })
1471
- }]
1472
- },
1473
- {
1474
- id: "flip",
1475
- actions: [{
1476
- id: "flip",
1477
- run: (context) => context.addOperation({ type: "flip" })
1478
- }]
1479
- },
1480
- adjustTool,
1481
- {
1482
- id: "threshold",
1483
- actions: [{
1484
- id: "threshold",
1485
- run: (context) => context.openTool("threshold")
1486
- }]
1487
1546
  }
1488
- ];
1489
- /** The tools offered when the consumer does not choose. */
1490
- const ALL_TOOL_IDS = TOOLS.map(({ id }) => id);
1547
+ };
1548
+ // src/state/history.ts
1549
+ /** An empty history. */
1550
+ function createHistory() {
1551
+ return {
1552
+ done: [],
1553
+ undone: []
1554
+ };
1555
+ }
1556
+ /** Adds an edit. What could be redone is lost, as in any editor. */
1557
+ function addToHistory({ done }, item) {
1558
+ return {
1559
+ done: [...done, item],
1560
+ undone: []
1561
+ };
1562
+ }
1563
+ /** Moves the last edit to what can be redone. */
1564
+ function undoHistory(history) {
1565
+ const last = history.done.at(-1);
1566
+ return last === void 0 ? history : {
1567
+ done: history.done.slice(0, -1),
1568
+ undone: [...history.undone, last]
1569
+ };
1570
+ }
1571
+ /** Brings back the last edit undone. */
1572
+ function redoHistory(history) {
1573
+ const last = history.undone.at(-1);
1574
+ return last === void 0 ? history : {
1575
+ done: [...history.done, last],
1576
+ undone: history.undone.slice(0, -1)
1577
+ };
1578
+ }
1491
1579
  // src/ui/button.ts
1492
1580
  /**
1493
1581
  * Creates a button named for screen readers. `data-paperpic-control` holds its key in the labels, so CSS can target
@@ -1508,6 +1596,22 @@ function nameButton(button, label) {
1508
1596
  button.setAttribute("aria-label", label);
1509
1597
  button.title = label;
1510
1598
  }
1599
+ let trust;
1600
+ /**
1601
+ * Passes the markup of an icon through the `paperpic` policy of Trusted Types, in the browsers that have them, so the
1602
+ * viewer works under a Content Security Policy that requires them. The policy changes nothing: the markup is a built-in
1603
+ * icon, or one that the consumer vouches for.
1604
+ */
1605
+ function trustedMarkup(markup) {
1606
+ if (!trust) {
1607
+ trust = (html) => html;
1608
+ try {
1609
+ const policy = globalThis.trustedTypes?.createPolicy("paperpic", { createHTML: (html) => html });
1610
+ if (policy) trust = (html) => policy.createHTML(html);
1611
+ } catch {}
1612
+ }
1613
+ return trust(markup);
1614
+ }
1511
1615
  /** The markup of the icon that each button shows, so an icon that does not change is not parsed again. */
1512
1616
  const iconMarkup = /* @__PURE__ */ new WeakMap();
1513
1617
  /**
@@ -1519,7 +1623,7 @@ function setIcon(button, markup) {
1519
1623
  iconMarkup.set(button, markup);
1520
1624
  for (const child of Array.from(button.children)) if (child.classList.contains("paperpic-icon")) child.remove();
1521
1625
  const template = document.createElement("template");
1522
- template.innerHTML = markup;
1626
+ template.innerHTML = trustedMarkup(markup);
1523
1627
  const icon = template.content.firstElementChild;
1524
1628
  if (icon) {
1525
1629
  icon.classList.add("paperpic-icon");
@@ -1740,7 +1844,7 @@ var EditBar = class {
1740
1844
  adjustment = "brightness";
1741
1845
  /** A hint of the open tool that replaces its usual one, such as the next step after selecting a corner. */
1742
1846
  hintOverride = null;
1743
- cleanedUp = false;
1847
+ thresholdInEdits = false;
1744
1848
  canApply = false;
1745
1849
  busy = false;
1746
1850
  constructor(commands, tools, labels, icons = DEFAULT_ICONS) {
@@ -1932,16 +2036,18 @@ var EditBar = class {
1932
2036
  if (!visible) this.closeConfirmation(false);
1933
2037
  }
1934
2038
  /** Updates what the buttons allow, and what the panel of an open tool shows. */
1935
- update({ canUndo, canRedo, canApply, busy, canOpenTool, canZoomIn, canZoomOut, cleanedUp, threshold, adjustments }) {
2039
+ update({ canUndo, canRedo, canApply, busy, canOpenTool, canZoomIn, canZoomOut, thresholdInEdits, threshold, adjustments }) {
1936
2040
  this.canApply = canApply;
1937
2041
  this.busy = busy;
1938
- this.cleanedUp = cleanedUp;
2042
+ this.thresholdInEdits = thresholdInEdits;
1939
2043
  this.undoButton.setAttribute("aria-disabled", String(busy || !canUndo));
1940
2044
  this.redoButton.setAttribute("aria-disabled", String(busy || !canRedo));
1941
2045
  this.applyButton.setAttribute("aria-disabled", String(busy || !canApply));
1942
2046
  this.cancelButton.setAttribute("aria-disabled", String(busy));
1943
- this.zoomInButton.setAttribute("aria-disabled", String(!canZoomIn));
1944
- this.zoomOutButton.setAttribute("aria-disabled", String(!canZoomOut));
2047
+ this.updateView({
2048
+ canZoomIn,
2049
+ canZoomOut
2050
+ });
1945
2051
  const adjusted = !threshold.enabled && (adjustments.brightness !== 0 || adjustments.contrast !== 0);
1946
2052
  for (const { tool, button } of this.toolButtons) {
1947
2053
  button.setAttribute("aria-disabled", String(busy || tool.activate !== void 0 && !canOpenTool || tool.id === "adjust" && threshold.enabled));
@@ -1957,6 +2063,11 @@ var EditBar = class {
1957
2063
  }
1958
2064
  this.showPanel();
1959
2065
  }
2066
+ /** Updates the zoom buttons of an open tool, which a pan or a zoom changes. */
2067
+ updateView({ canZoomIn, canZoomOut }) {
2068
+ this.zoomInButton.setAttribute("aria-disabled", String(!canZoomIn));
2069
+ this.zoomOutButton.setAttribute("aria-disabled", String(!canZoomOut));
2070
+ }
1960
2071
  /** Cancels, asking first if there are changes to lose. */
1961
2072
  requestCancel(commands) {
1962
2073
  if (this.busy) return;
@@ -1985,7 +2096,7 @@ var EditBar = class {
1985
2096
  const id = this.activeTool?.id;
1986
2097
  const name = this.activeTool ? this.labels[this.activeTool.actions[0].id] : "";
1987
2098
  const hasCorners = id === "crop" || id === "perspective";
1988
- const hasSwitch = id === "threshold" && this.cleanedUp;
2099
+ const hasSwitch = id === "threshold" && this.thresholdInEdits;
1989
2100
  this.toolControls.setAttribute("aria-label", name);
1990
2101
  this.corners.hidden = !hasCorners;
1991
2102
  this.title.hidden = !hasCorners && !(id === "threshold" && !hasSwitch);
@@ -2133,12 +2244,24 @@ var Toolbar = class {
2133
2244
  setIcons(icons) {
2134
2245
  for (const [name, button] of Object.entries(this.buttons)) setIcon(button, icons[name]);
2135
2246
  }
2136
- /** Updates what the buttons show. */
2137
- update({ fit, canEdit, canZoomIn, canZoomOut, canRotate, canDownload }) {
2247
+ /** Shows or hides the bar. */
2248
+ setVisible(visible) {
2249
+ this.element.hidden = !visible;
2250
+ }
2251
+ /** Updates the buttons that follow the view, which a pan or a zoom changes. */
2252
+ updateView({ fit, canZoomIn, canZoomOut }) {
2138
2253
  this.buttons.zoomIn.setAttribute("aria-disabled", String(!canZoomIn));
2139
2254
  this.buttons.zoomOut.setAttribute("aria-disabled", String(!canZoomOut));
2140
2255
  this.buttons.fitWidth.setAttribute("aria-pressed", String(fit === "width"));
2141
2256
  this.buttons.fitHeight.setAttribute("aria-pressed", String(fit === "height"));
2257
+ }
2258
+ /** Updates what the buttons show. */
2259
+ update({ fit, canEdit, canZoomIn, canZoomOut, canRotate, canDownload }) {
2260
+ this.updateView({
2261
+ fit,
2262
+ canZoomIn,
2263
+ canZoomOut
2264
+ });
2142
2265
  this.buttons.edit.hidden = !canEdit;
2143
2266
  this.buttons.rotateLeft.hidden = !canRotate;
2144
2267
  this.buttons.rotateRight.hidden = !canRotate;
@@ -2161,24 +2284,8 @@ const NO_PREVIEW = JSON.stringify({
2161
2284
  steps: [],
2162
2285
  tone: null
2163
2286
  });
2164
- const LENS_ZOOM = 3;
2165
2287
  /** How close to the edge of the viewer a point can be and still count as on screen. */
2166
2288
  const REVEAL_MARGIN = 24;
2167
- const DEFAULT_OPTIONS = {
2168
- alt: "",
2169
- aspectRatio: void 0,
2170
- download: false,
2171
- editable: true,
2172
- filename: void 0,
2173
- icons: void 0,
2174
- labels: void 0,
2175
- maxOutputSize: void 0,
2176
- output: void 0,
2177
- softness: void 0,
2178
- toolbar: true,
2179
- tools: ALL_TOOL_IDS,
2180
- wheelZoom: true
2181
- };
2182
2289
  /**
2183
2290
  * A document image viewer and editor. It fills its container, which needs a height. Import the stylesheet once, from
2184
2291
  * `@paperpic/core/style.css`.
@@ -2199,6 +2306,7 @@ var PaperPic = class {
2199
2306
  toolbar;
2200
2307
  editBar;
2201
2308
  renderer;
2309
+ gestures;
2202
2310
  runner = new PipelineRunner();
2203
2311
  listeners = {
2204
2312
  apply: /* @__PURE__ */ new Set(),
@@ -2217,14 +2325,25 @@ var PaperPic = class {
2217
2325
  /** What the edits look like, while they need other pixels than the image. */
2218
2326
  preview = null;
2219
2327
  previewKey = NO_PREVIEW;
2220
- previewId = 0;
2221
- previewing = false;
2328
+ previewQueue = new PreviewQueue({
2329
+ render: (steps, tone) => renderPreview(this.image, steps, tone, this.runner),
2330
+ ready: (preview) => this.showPreview(preview),
2331
+ failed: (cause) => this.previewFailed(cause),
2332
+ tint: (tone) => {
2333
+ if (this.preview?.tint) {
2334
+ this.preview.tint(tone);
2335
+ this.renderer.requestPaint();
2336
+ }
2337
+ }
2338
+ });
2222
2339
  /** The open tool with a selection of its own, such as Crop. */
2223
2340
  session = null;
2224
2341
  /** The open Adjust or Clean up. */
2225
2342
  draft = null;
2226
2343
  loadStatus = "empty";
2227
2344
  loadId = 0;
2345
+ /** Changes when an edit ends without a trace, so an Apply that finishes afterwards knows that its edit is gone. */
2346
+ editId = 0;
2228
2347
  view = createView();
2229
2348
  viewport = {
2230
2349
  width: 0,
@@ -2238,6 +2357,7 @@ var PaperPic = class {
2238
2357
  /**
2239
2358
  * @param container The element to fill. It needs a height, or the viewer stays at its minimum height.
2240
2359
  * @throws {TypeError} If `container` is not an element. Create the instance once the element exists, such as on mount.
2360
+ * @throws {RangeError} If an option is out of its range, such as a `softness` of 2.
2241
2361
  *
2242
2362
  * @example
2243
2363
  * const pic = new PaperPic(container, {
@@ -2249,6 +2369,7 @@ var PaperPic = class {
2249
2369
  */
2250
2370
  constructor(container, options = {}) {
2251
2371
  if (!(container instanceof HTMLElement)) throw new TypeError("PaperPic needs an HTML element as its container. Create the instance once the element exists, such as on mount.");
2372
+ validateOptions(options);
2252
2373
  this.root = document.createElement("div");
2253
2374
  this.root.className = "paperpic";
2254
2375
  const stage = document.createElement("div");
@@ -2303,13 +2424,13 @@ var PaperPic = class {
2303
2424
  this.root.append(stage, this.editBar.element);
2304
2425
  container.append(this.root);
2305
2426
  this.renderer = new Renderer(this.canvas, overlay, () => this.scene());
2306
- this.cleanups.push(attachGestures(this.viewportElement, {
2427
+ this.gestures = attachGestures(this.viewportElement, {
2307
2428
  onPan: (deltaX, deltaY) => this.pan(deltaX, deltaY),
2308
2429
  onZoom: (factor, point) => this.zoomAround(this.view.zoom * factor, point),
2309
2430
  onTap: (point) => this.session?.handle.tap?.(point) ?? false,
2310
- onDoubleTap: (point) => this.toggleZoom(point),
2311
- wheelZoom: () => this.options.wheelZoom
2312
- }));
2431
+ onDoubleTap: (point) => this.toggleZoom(point)
2432
+ });
2433
+ this.cleanups.push(this.gestures.detach);
2313
2434
  const onKeyDown = (event) => {
2314
2435
  const command = keyToCommand(event);
2315
2436
  if (command && this.runKey(command, event.target)) event.preventDefault();
@@ -2329,37 +2450,54 @@ var PaperPic = class {
2329
2450
  });
2330
2451
  observer.observe(this.viewportElement);
2331
2452
  this.cleanups.push(() => observer.disconnect());
2332
- this.setOptions(options);
2453
+ this.changeOptions(options, true);
2333
2454
  this.measure();
2334
2455
  }
2335
2456
  /**
2336
2457
  * Changes only the options you pass, and `undefined` brings one back to its default. It does not emit `change`, so
2337
2458
  * two-way bindings do not loop.
2338
2459
  *
2460
+ * @throws {RangeError} If an option is out of its range, such as a `softness` of 2. No option changes then.
2461
+ *
2339
2462
  * @example
2340
2463
  * pic.setOptions({ editable: false })
2341
2464
  */
2342
2465
  setOptions(options) {
2466
+ this.changeOptions(options, false);
2467
+ }
2468
+ /**
2469
+ * Applies the options that changed. Options with the same values change nothing, so a wrapper can pass them all on
2470
+ * every render, and a message on screen stays. The constructor passes `initial` to set everything up.
2471
+ */
2472
+ changeOptions(options, initial) {
2343
2473
  if (this.destroyed) return;
2344
- const next = { ...this.options };
2345
- for (const name of Object.keys(DEFAULT_OPTIONS)) if (name in options) Object.assign(next, { [name]: options[name] ?? DEFAULT_OPTIONS[name] });
2346
- const wasEditable = this.options.editable;
2474
+ validateOptions(options);
2475
+ const previous = this.options;
2476
+ const next = mergeOptions(previous, options);
2477
+ const changed = (name) => initial || !sameOption(previous[name], next[name]);
2478
+ if (!("src" in options && options.src !== this.source) && !OPTION_NAMES.some(changed)) return;
2479
+ const wasEditable = previous.editable;
2347
2480
  this.options = next;
2348
- this.labels = {
2349
- ...DEFAULT_LABELS,
2350
- ...next.labels
2351
- };
2352
- this.toolbar.setLabels(this.labels);
2353
- this.editBar.setLabels(this.labels);
2354
- const icons = {
2355
- ...DEFAULT_ICONS,
2356
- ...next.icons
2357
- };
2358
- this.toolbar.setIcons(icons);
2359
- this.editBar.setIcons(icons);
2360
- this.editBar.setTools(next.tools);
2361
- this.viewportElement.setAttribute("aria-label", this.labels.viewer);
2362
- this.describeImage(next.alt);
2481
+ if (changed("wheelZoom")) this.gestures.setWheelZoom(next.wheelZoom);
2482
+ if (changed("labels")) {
2483
+ this.labels = {
2484
+ ...DEFAULT_LABELS,
2485
+ ...next.labels
2486
+ };
2487
+ this.toolbar.setLabels(this.labels);
2488
+ this.editBar.setLabels(this.labels);
2489
+ this.viewportElement.setAttribute("aria-label", this.labels.viewer);
2490
+ }
2491
+ if (changed("icons")) {
2492
+ const icons = {
2493
+ ...DEFAULT_ICONS,
2494
+ ...next.icons
2495
+ };
2496
+ this.toolbar.setIcons(icons);
2497
+ this.editBar.setIcons(icons);
2498
+ }
2499
+ if (changed("tools")) this.editBar.setTools(next.tools);
2500
+ if (changed("alt")) this.describeImage(next.alt);
2363
2501
  if (next.editable !== wasEditable) {
2364
2502
  this.leaveEdit();
2365
2503
  if (this.view.rotation !== 0) this.resetRotation();
@@ -2464,7 +2602,7 @@ var PaperPic = class {
2464
2602
  * is a flip and a half turn. It does nothing outside the edit mode, or while a tool is open.
2465
2603
  */
2466
2604
  flip() {
2467
- if (this.options.tools.includes("flip")) this.addOperation({ type: "flip" });
2605
+ this.addOperation({ type: "flip" });
2468
2606
  }
2469
2607
  /** Starts editing. It does nothing if the image is not ready or cannot be edited. */
2470
2608
  edit() {
@@ -2495,22 +2633,19 @@ var PaperPic = class {
2495
2633
  */
2496
2634
  openTool(id) {
2497
2635
  const tool = TOOLS.find((candidate) => candidate.id === id);
2498
- if (this.mode !== "edit" || this.busy || this.openToolId() || !tool || !this.options.tools.includes(id)) return;
2636
+ if (this.mode !== "edit" || this.busy || this.openToolId() || !tool) return;
2499
2637
  const hadFocus = this.hasFocus();
2500
- if (id === "adjust" || id === "threshold") {
2501
- const threshold = thresholdSetting(this.history.done);
2502
- if (id === "adjust" && threshold.enabled) return;
2503
- this.draft = id === "adjust" ? {
2638
+ if (id === "adjust") {
2639
+ if (!canAdjust(this.history.done)) return;
2640
+ this.draft = {
2504
2641
  tool: "adjust",
2505
2642
  setting: adjustSetting(this.history.done)
2506
- } : {
2507
- tool: "threshold",
2508
- setting: {
2509
- enabled: true,
2510
- sensitivity: threshold.sensitivity
2511
- }
2512
2643
  };
2513
- } else if (tool.activate && !this.previewing) this.session = {
2644
+ } else if (id === "threshold") this.draft = {
2645
+ tool: "threshold",
2646
+ setting: openThreshold(this.history.done)
2647
+ };
2648
+ else if (tool.activate && !this.previewQueue.pending) this.session = {
2514
2649
  tool,
2515
2650
  handle: tool.activate(this.toolHost())
2516
2651
  };
@@ -2565,17 +2700,13 @@ var PaperPic = class {
2565
2700
  });
2566
2701
  return;
2567
2702
  }
2568
- if (this.mode !== "edit" || this.busy || this.openToolId() || !this.options.tools.includes("threshold")) return;
2703
+ if (this.mode !== "edit" || this.busy || this.openToolId()) return;
2569
2704
  const current = thresholdSetting(this.history.done);
2570
- const next = {
2705
+ const edit = thresholdEdit({
2571
2706
  enabled: enabled ?? current.enabled,
2572
2707
  sensitivity: sensitivity ?? current.sensitivity
2573
- };
2574
- if (next.enabled !== current.enabled || next.sensitivity !== current.sensitivity) this.addOperation({
2575
- type: "threshold",
2576
- ...next,
2577
- softness: this.options.softness ?? current.softness
2578
- });
2708
+ }, this.history.done, this.options.softness);
2709
+ if (edit) this.addOperation(edit);
2579
2710
  }
2580
2711
  /**
2581
2712
  * Changes the brightness or the contrast, each from -1 to 1, where 0 leaves the image as it is. They run after the other edits.
@@ -2600,16 +2731,13 @@ var PaperPic = class {
2600
2731
  });
2601
2732
  return;
2602
2733
  }
2603
- if (!this.canAdjust()) return;
2734
+ if (this.mode !== "edit" || this.busy || this.openToolId() || !canAdjust(this.history.done)) return;
2604
2735
  const current = adjustSetting(this.history.done);
2605
- const next = {
2736
+ const edit = adjustEdit({
2606
2737
  brightness: brightness ?? current.brightness,
2607
2738
  contrast: contrast ?? current.contrast
2608
- };
2609
- if (next.brightness !== current.brightness || next.contrast !== current.contrast) this.addOperation({
2610
- type: "adjust",
2611
- ...next
2612
- });
2739
+ }, this.history.done);
2740
+ if (edit) this.addOperation(edit);
2613
2741
  }
2614
2742
  /** Discards the edits and goes back to viewing. It does not ask: the built-in Cancel button does that. */
2615
2743
  cancel() {
@@ -2635,6 +2763,8 @@ var PaperPic = class {
2635
2763
  const steps = toPipelineSteps(this.history.done);
2636
2764
  if (this.mode !== "edit" || this.busy || this.openToolId() || !image || steps.length === 0) return;
2637
2765
  const id = this.loadId;
2766
+ const edit = this.editId;
2767
+ const outdated = () => id !== this.loadId || edit !== this.editId;
2638
2768
  this.busy = true;
2639
2769
  this.applyFailed = false;
2640
2770
  this.showStatus();
@@ -2652,7 +2782,7 @@ var PaperPic = class {
2652
2782
  maxOutputSize: this.options.maxOutputSize
2653
2783
  });
2654
2784
  const loaded = await loadImage(exported.blob);
2655
- if (id !== this.loadId) {
2785
+ if (outdated()) {
2656
2786
  loaded.release();
2657
2787
  return;
2658
2788
  }
@@ -2668,12 +2798,15 @@ var PaperPic = class {
2668
2798
  this.emit("apply", exported);
2669
2799
  this.emit("change", this.getState());
2670
2800
  } catch (cause) {
2671
- if (id !== this.loadId) return;
2801
+ if (outdated()) return;
2672
2802
  this.busy = false;
2673
2803
  this.applyFailed = true;
2674
2804
  this.showStatus();
2675
2805
  this.refresh();
2676
- this.emit("error", { error: cause });
2806
+ this.emit("error", {
2807
+ error: cause,
2808
+ phase: "apply"
2809
+ });
2677
2810
  }
2678
2811
  }
2679
2812
  /**
@@ -2721,9 +2854,9 @@ var PaperPic = class {
2721
2854
  this.loadId++;
2722
2855
  for (const cleanup of this.cleanups) cleanup();
2723
2856
  this.closeTool();
2857
+ this.previewQueue.forget();
2724
2858
  this.renderer.destroy();
2725
2859
  this.runner.destroy();
2726
- this.previewId++;
2727
2860
  this.preview?.release();
2728
2861
  this.preview = null;
2729
2862
  this.image?.release();
@@ -2777,36 +2910,13 @@ var PaperPic = class {
2777
2910
  labels: () => this.labels,
2778
2911
  photoFrame: () => photoFrame(this.image, toPipelineSteps(this.history.done)),
2779
2912
  aspectRatio: () => this.options.aspectRatio,
2780
- paintLens: (context, lens) => this.paintLens(context, lens)
2913
+ paintMagnifier: (context, magnifier) => paintMagnifier(context, magnifier, {
2914
+ view: this.view,
2915
+ image: shown(),
2916
+ viewport: this.viewport
2917
+ })
2781
2918
  };
2782
2919
  }
2783
- /** Paints the image larger around a point, inside a circle. */
2784
- paintLens(context, { point, center, radius }) {
2785
- const shown = this.preview ?? this.image;
2786
- const [a, b, c, d, e, f] = computeTransform(this.view, shown, this.viewport);
2787
- const target = frameToViewport(this.view, shown, this.viewport, point);
2788
- context.save();
2789
- context.beginPath();
2790
- context.arc(center.x, center.y, radius, 0, Math.PI * 2);
2791
- context.clip();
2792
- context.fillStyle = "#fff";
2793
- context.fill();
2794
- context.transform(a * LENS_ZOOM, b * LENS_ZOOM, c * LENS_ZOOM, d * LENS_ZOOM, center.x + (e - target.x) * LENS_ZOOM, center.y + (f - target.y) * LENS_ZOOM);
2795
- context.drawImage(shown.element, 0, 0, shown.width, shown.height);
2796
- context.restore();
2797
- context.beginPath();
2798
- context.arc(center.x, center.y, radius, 0, Math.PI * 2);
2799
- context.moveTo(center.x - 8, center.y);
2800
- context.lineTo(center.x + 8, center.y);
2801
- context.moveTo(center.x, center.y - 8);
2802
- context.lineTo(center.x, center.y + 8);
2803
- context.lineWidth = 2;
2804
- context.strokeStyle = "#fff";
2805
- context.stroke();
2806
- }
2807
- canAdjust() {
2808
- return this.mode === "edit" && !this.busy && !this.openToolId() && this.options.tools.includes("adjust") && !thresholdSetting(this.history.done).enabled;
2809
- }
2810
2920
  /** The open tool, with a selection or a panel of settings of its own. */
2811
2921
  openToolId() {
2812
2922
  return this.session?.tool.id ?? this.draft?.tool ?? null;
@@ -2822,23 +2932,8 @@ var PaperPic = class {
2822
2932
  /** The edit that the open Adjust or Clean up would leave, or `null` if it changes nothing. */
2823
2933
  draftEdit() {
2824
2934
  const draft = this.draft;
2825
- if (draft?.tool === "adjust") {
2826
- const { brightness, contrast } = adjustSetting(this.history.done);
2827
- return draft.setting.brightness !== brightness || draft.setting.contrast !== contrast ? {
2828
- type: "adjust",
2829
- ...draft.setting
2830
- } : null;
2831
- }
2832
- if (draft?.tool === "threshold") {
2833
- const current = thresholdSetting(this.history.done);
2834
- const { enabled, sensitivity } = draft.setting;
2835
- return enabled !== current.enabled || enabled && sensitivity !== current.sensitivity ? {
2836
- type: "threshold",
2837
- enabled,
2838
- sensitivity,
2839
- softness: this.options.softness ?? current.softness
2840
- } : null;
2841
- }
2935
+ if (draft?.tool === "adjust") return adjustEdit(draft.setting, this.history.done);
2936
+ if (draft?.tool === "threshold") return confirmThreshold(draft.setting, this.history.done, this.options.softness);
2842
2937
  return null;
2843
2938
  }
2844
2939
  closeTool() {
@@ -2851,8 +2946,16 @@ var PaperPic = class {
2851
2946
  this.editBar.setActiveTool(null);
2852
2947
  if (hadFocus && this.options.toolbar) this.editBar.focus(id);
2853
2948
  }
2949
+ /**
2950
+ * Tells the listeners of an event. A listener that throws is the app failing, not the viewer, so the page gets its
2951
+ * error as any uncaught one, the other listeners still run, and it never looks like a failed load or Apply.
2952
+ */
2854
2953
  emit(name, payload) {
2855
- for (const listener of this.listeners[name]) listener(payload);
2954
+ for (const listener of this.listeners[name]) try {
2955
+ listener(payload);
2956
+ } catch (error) {
2957
+ reportError(error);
2958
+ }
2856
2959
  }
2857
2960
  hasFocus() {
2858
2961
  return this.root.contains(document.activeElement);
@@ -2862,6 +2965,7 @@ var PaperPic = class {
2862
2965
  if (hadFocus && this.options.toolbar) this.toolbar.focus();
2863
2966
  }
2864
2967
  async load(source) {
2968
+ if (this.destroyed) return;
2865
2969
  const id = ++this.loadId;
2866
2970
  this.source = source;
2867
2971
  this.setSaved(source);
@@ -2887,7 +2991,10 @@ var PaperPic = class {
2887
2991
  } catch (cause) {
2888
2992
  if (id !== this.loadId) return;
2889
2993
  this.setImage(null, "error");
2890
- this.emit("error", { error: cause });
2994
+ this.emit("error", {
2995
+ error: cause,
2996
+ phase: "load"
2997
+ });
2891
2998
  }
2892
2999
  }
2893
3000
  /** Changes what a download saves, and frees the address of the file it saved before. */
@@ -2906,8 +3013,9 @@ var PaperPic = class {
2906
3013
  this.showStatus();
2907
3014
  this.applyViewport();
2908
3015
  }
2909
- /** Ends the edit without a trace. In-progress work is ignored when it finishes, because a load changes `loadId`. */
3016
+ /** Ends the edit without a trace. An Apply in progress is ignored when it finishes, because `editId` changes. */
2910
3017
  leaveEdit() {
3018
+ this.editId++;
2911
3019
  this.closeTool();
2912
3020
  this.mode = "view";
2913
3021
  this.busy = false;
@@ -2944,11 +3052,7 @@ var PaperPic = class {
2944
3052
  type: "adjust",
2945
3053
  ...draft.setting
2946
3054
  });
2947
- if (draft?.tool === "threshold") operations.push({
2948
- type: "threshold",
2949
- ...draft.setting,
2950
- softness: this.options.softness ?? thresholdSetting(operations).softness
2951
- });
3055
+ if (draft?.tool === "threshold") operations.push(thresholdOperation(draft.setting, operations, this.options.softness));
2952
3056
  const tone = toneStep(operations);
2953
3057
  if (tone?.type === "threshold" && this.session?.tool.id === "perspective") return null;
2954
3058
  return tone ?? (draft?.tool === "adjust" ? {
@@ -2966,35 +3070,29 @@ var PaperPic = class {
2966
3070
  });
2967
3071
  if (key === this.previewKey) {
2968
3072
  this.syncRotation();
2969
- if (tone) this.preview?.tint?.(tone);
3073
+ if (tone) this.previewQueue.scheduleTint(tone);
2970
3074
  } else if (steps.length === 0 && !tone) this.setPreview(null);
2971
3075
  else {
2972
3076
  this.previewKey = key;
2973
- this.startPreview(steps, tone);
3077
+ this.previewQueue.request(steps, tone);
2974
3078
  }
2975
3079
  }
2976
- /** Computes the pixels of the edits. A result that arrives after newer edits is ignored. */
2977
- async startPreview(steps, tone) {
2978
- const id = ++this.previewId;
2979
- this.previewing = true;
2980
- try {
2981
- const preview = await renderPreview(this.image, steps, tone, this.runner);
2982
- if (id !== this.previewId) {
2983
- preview.release();
2984
- return;
2985
- }
2986
- this.setPreview(preview);
2987
- const latest = this.previewTone();
2988
- if (latest) preview.tint?.(latest);
2989
- this.emit("change", this.getState());
2990
- } catch (cause) {
2991
- if (id !== this.previewId) return;
2992
- this.previewing = false;
2993
- this.applyFailed = true;
2994
- this.showStatus();
2995
- this.refresh();
2996
- this.emit("error", { error: cause });
2997
- }
3080
+ /** Shows a preview that arrived, with the tones of the ruler, which may have moved while it was on its way. */
3081
+ showPreview(preview) {
3082
+ this.setPreview(preview);
3083
+ const latest = this.previewTone();
3084
+ if (latest) preview.tint?.(latest);
3085
+ this.emit("change", this.getState());
3086
+ }
3087
+ /** Keeps the edit open, and reports that its pixels could not be shown. */
3088
+ previewFailed(cause) {
3089
+ this.applyFailed = true;
3090
+ this.showStatus();
3091
+ this.refresh();
3092
+ this.emit("error", {
3093
+ error: cause,
3094
+ phase: "preview"
3095
+ });
2998
3096
  }
2999
3097
  /**
3000
3098
  * Changes the pixels on display. A new shape starts from a fitted view, and the same shape keeps the zoom, as when the threshold changes.
@@ -3002,11 +3100,11 @@ var PaperPic = class {
3002
3100
  */
3003
3101
  setPreview(preview) {
3004
3102
  const before = this.preview ?? this.image;
3103
+ this.previewQueue.cancelTint();
3005
3104
  if (!preview) {
3006
- this.previewId++;
3105
+ this.previewQueue.forget();
3007
3106
  this.previewKey = NO_PREVIEW;
3008
3107
  }
3009
- this.previewing = false;
3010
3108
  this.preview?.release();
3011
3109
  this.preview = preview;
3012
3110
  const after = this.preview ?? this.image;
@@ -3028,7 +3126,7 @@ var PaperPic = class {
3028
3126
  const text = this.busy ? this.labels.processing : this.applyFailed ? this.labels.applyError : texts[this.loadStatus];
3029
3127
  this.status.textContent = text;
3030
3128
  this.status.classList.toggle("paperpic-status-visible", text !== "");
3031
- this.root.setAttribute("aria-busy", String(this.busy || this.previewing || this.loadStatus === "loading"));
3129
+ this.root.setAttribute("aria-busy", String(this.busy || this.previewQueue.pending || this.loadStatus === "loading"));
3032
3130
  }
3033
3131
  /** How far past its sides the image can go, so the part under the toolbar can come out from behind it. Editing hides the toolbar. */
3034
3132
  toolbarClearance() {
@@ -3042,6 +3140,7 @@ var PaperPic = class {
3042
3140
  };
3043
3141
  this.renderer.resize(this.viewport, globalThis.devicePixelRatio || 1);
3044
3142
  this.applyViewport();
3143
+ this.renderer.paintNow();
3045
3144
  }
3046
3145
  /** The image on display, once the viewer has a size to show it in. A hidden container has none. */
3047
3146
  measuredImage() {
@@ -3052,40 +3151,61 @@ var PaperPic = class {
3052
3151
  if (image) this.view = resizeView(this.view, image, this.viewport);
3053
3152
  this.refresh();
3054
3153
  }
3055
- refresh() {
3154
+ /** Whether the zoom can go further in each direction, from the view on display. */
3155
+ canZoom() {
3056
3156
  const image = this.measuredImage();
3057
3157
  const limits = image && zoomLimits(image, this.viewport, this.view.rotation);
3158
+ return {
3159
+ canZoomIn: limits !== null && this.view.zoom < limits.max - ZOOM_TOLERANCE,
3160
+ canZoomOut: limits !== null && this.view.zoom > limits.min + ZOOM_TOLERANCE
3161
+ };
3162
+ }
3163
+ /** Makes the whole interface match the state: the bars, the mode and the view. */
3164
+ refresh() {
3058
3165
  const state = this.getState();
3059
- const canZoomIn = limits !== null && this.view.zoom < limits.max - ZOOM_TOLERANCE;
3060
- const canZoomOut = limits !== null && this.view.zoom > limits.min + ZOOM_TOLERANCE;
3166
+ const zoom = this.canZoom();
3061
3167
  this.toolbar.update({
3062
3168
  fit: this.view.fit,
3063
3169
  canEdit: this.options.editable && this.mode === "view" && this.loadStatus === "ready",
3064
- canZoomIn,
3065
- canZoomOut,
3170
+ ...zoom,
3066
3171
  canRotate: !this.options.editable,
3067
3172
  canDownload: this.options.download && this.mode === "view" && this.loadStatus === "ready"
3068
3173
  });
3069
- this.toolbar.element.hidden = !this.options.toolbar || this.mode === "edit";
3174
+ this.toolbar.setVisible(this.options.toolbar && this.mode === "view");
3070
3175
  this.editBar.setVisible(this.mode === "edit" && this.options.toolbar);
3071
3176
  this.editBar.update({
3072
3177
  ...state,
3073
- canOpenTool: !this.previewing,
3074
- canZoomIn,
3075
- canZoomOut,
3076
- cleanedUp: thresholdSetting(this.history.done).enabled
3178
+ canOpenTool: !this.previewQueue.pending,
3179
+ ...zoom,
3180
+ thresholdInEdits: thresholdSetting(this.history.done).enabled
3077
3181
  });
3078
- this.session?.handle.update();
3079
3182
  this.root.classList.toggle("paperpic-editing", this.mode === "edit");
3183
+ this.refreshView(zoom);
3184
+ }
3185
+ /**
3186
+ * Makes what follows the view match it: the zoom and fit buttons, the handles of an open tool, the cursor and the
3187
+ * image. A pan or a zoom needs nothing else, and it can come on every move of the pointer.
3188
+ */
3189
+ refreshView(zoom = this.canZoom()) {
3190
+ const image = this.measuredImage();
3191
+ this.toolbar.updateView({
3192
+ fit: this.view.fit,
3193
+ ...zoom
3194
+ });
3195
+ this.editBar.updateView(zoom);
3196
+ this.session?.handle.update();
3080
3197
  this.viewportElement.classList.toggle("paperpic-viewport-pannable", image !== null && overflows(this.view, image, this.viewport));
3081
3198
  this.renderer.requestPaint();
3082
3199
  }
3200
+ /** Shows another view. Returns whether it differs from the one on display. */
3083
3201
  commit(view) {
3084
3202
  const { zoom, panX, panY, rotation, fit } = this.view;
3085
- if (view.zoom === zoom && view.panX === panX && view.panY === panY && view.rotation === rotation && view.fit === fit) return;
3203
+ const sameState = view.zoom === zoom && view.rotation === rotation && view.fit === fit;
3204
+ if (sameState && view.panX === panX && view.panY === panY) return false;
3086
3205
  this.view = view;
3087
- this.refresh();
3088
- this.emit("change", this.getState());
3206
+ this.refreshView();
3207
+ if (!sameState) this.emit("change", this.getState());
3208
+ return true;
3089
3209
  }
3090
3210
  resetRotation() {
3091
3211
  this.view = {
@@ -3096,9 +3216,10 @@ var PaperPic = class {
3096
3216
  };
3097
3217
  this.applyViewport();
3098
3218
  }
3219
+ /** Moves the image. Returns whether it moved, which an image that fits, or one at its edge, does not. */
3099
3220
  pan(deltaX, deltaY) {
3100
3221
  const image = this.measuredImage();
3101
- if (image) this.commit(panBy(this.view, deltaX, deltaY, image, this.viewport, this.toolbarClearance()));
3222
+ return image !== null && this.commit(panBy(this.view, deltaX, deltaY, image, this.viewport, this.toolbarClearance()));
3102
3223
  }
3103
3224
  zoomAround(zoom, point) {
3104
3225
  const image = this.measuredImage();
@@ -3130,9 +3251,7 @@ var PaperPic = class {
3130
3251
  case "fit":
3131
3252
  this.fit("image");
3132
3253
  return true;
3133
- case "pan":
3134
- this.pan(command.deltaX, command.deltaY);
3135
- return true;
3254
+ case "pan": return this.pan(command.deltaX, command.deltaY);
3136
3255
  case "undo":
3137
3256
  this.undo();
3138
3257
  return editing;
@@ -3162,4 +3281,4 @@ var PaperPic = class {
3162
3281
  }
3163
3282
  }
3164
3283
  };
3165
- export { PaperPic, normalizeRotation };
3284
+ export { PaperPic };