@onekeyfe/react-native-image-crop-picker 6.7.0-alpha.418 → 6.7.0-alpha.422

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +12 -3
  2. package/lib/module/index.js +2 -14
  3. package/lib/module/index.js.map +1 -1
  4. package/lib/module/index.web.js +203 -0
  5. package/lib/module/index.web.js.map +1 -0
  6. package/lib/module/shared.js +19 -0
  7. package/lib/module/shared.js.map +1 -0
  8. package/lib/module/web/CropperView.js +570 -0
  9. package/lib/module/web/CropperView.js.map +1 -0
  10. package/lib/module/web/geometry.js +189 -0
  11. package/lib/module/web/geometry.js.map +1 -0
  12. package/lib/module/web/imageFormat.js +60 -0
  13. package/lib/module/web/imageFormat.js.map +1 -0
  14. package/lib/module/web/imageIO.js +153 -0
  15. package/lib/module/web/imageIO.js.map +1 -0
  16. package/lib/module/web/theme.js +98 -0
  17. package/lib/module/web/theme.js.map +1 -0
  18. package/lib/typescript/src/index.d.ts +4 -17
  19. package/lib/typescript/src/index.d.ts.map +1 -1
  20. package/lib/typescript/src/index.web.d.ts +18 -0
  21. package/lib/typescript/src/index.web.d.ts.map +1 -0
  22. package/lib/typescript/src/shared.d.ts +18 -0
  23. package/lib/typescript/src/shared.d.ts.map +1 -0
  24. package/lib/typescript/src/web/CropperView.d.ts +16 -0
  25. package/lib/typescript/src/web/CropperView.d.ts.map +1 -0
  26. package/lib/typescript/src/web/geometry.d.ts +53 -0
  27. package/lib/typescript/src/web/geometry.d.ts.map +1 -0
  28. package/lib/typescript/src/web/imageFormat.d.ts +3 -0
  29. package/lib/typescript/src/web/imageFormat.d.ts.map +1 -0
  30. package/lib/typescript/src/web/imageIO.d.ts +15 -0
  31. package/lib/typescript/src/web/imageIO.d.ts.map +1 -0
  32. package/lib/typescript/src/web/theme.d.ts +37 -0
  33. package/lib/typescript/src/web/theme.d.ts.map +1 -0
  34. package/package.json +6 -2
  35. package/src/index.tsx +16 -49
  36. package/src/index.web.tsx +288 -0
  37. package/src/shared.ts +51 -0
  38. package/src/web/CropperView.ts +725 -0
  39. package/src/web/geometry.ts +285 -0
  40. package/src/web/imageFormat.ts +63 -0
  41. package/src/web/imageIO.ts +178 -0
  42. package/src/web/theme.ts +130 -0
@@ -0,0 +1,725 @@
1
+ /// <reference lib="dom" />
2
+ import { ImageCropPickerError } from '../shared';
3
+ import {
4
+ INITIAL_STATE,
5
+ cropAspectRatio,
6
+ MAX_ZOOM,
7
+ MIN_ZOOM,
8
+ fitCropBox,
9
+ isSameState,
10
+ pan,
11
+ rescale,
12
+ rotateCounterclockwise,
13
+ scaleOf,
14
+ zoomAt,
15
+ } from './geometry';
16
+ import { resolveTheme } from './theme';
17
+
18
+ import type { ImageCropperAppearance } from '../ReactNativeImageCropPicker.nitro';
19
+ import type { CropState, Point, Rotation, Size } from './geometry';
20
+
21
+ // The web counterpart of ImageCropperViewController / ImageCropperActivity:
22
+ // the same header, crop area and Cancel / Confirm footer, drawn with the DOM.
23
+ // It adds a zoom toolbar, wheel and keyboard control for mouse users.
24
+ // Full screen on narrow or short windows, a centered panel otherwise.
25
+
26
+ export interface CropperViewOptions {
27
+ image: HTMLImageElement;
28
+ // Width / height of the crop box. Undefined keeps the image's own ratio,
29
+ // swapped on every quarter turn, like native without a target size.
30
+ aspectRatio?: number;
31
+ title?: string;
32
+ cancelText?: string;
33
+ confirmText?: string;
34
+ rotateButtonHidden?: boolean;
35
+ showGuidelines?: boolean;
36
+ circular?: boolean;
37
+ appearance?: ImageCropperAppearance;
38
+ }
39
+
40
+ export type CropperConfirmHandler<T> = (
41
+ state: CropState,
42
+ box: Size
43
+ ) => Promise<T>;
44
+
45
+ const STYLE_ELEMENT_ID = 'onekey-image-cropper-style';
46
+ const ZOOM_STEP = 1.25;
47
+ const SLIDER_STEPS = 1000;
48
+ const KEYBOARD_PAN = 10;
49
+ const KEYBOARD_PAN_FAST = 50;
50
+ const GUIDE_LINGER_MS = 400;
51
+ const ANIMATION_MS = 220;
52
+ // Above app overlays, which stay below 2^31.
53
+ const Z_INDEX = 2147483000;
54
+
55
+ const ICONS = {
56
+ // OneKey's RotateCounterclockwise, the same path the native screens draw.
57
+ rotate:
58
+ 'M6 5.426C7.628 3.919 9.484 3 12.028 3a9 9 0 1 1-8.487 12l-.334-.943 1.886-.666.333.942A7 7 0 1 0 12.029 5c-1.982 0-3.407.686-4.785 2H10v2H4V3h2v2.426Z',
59
+ zoomIn:
60
+ 'M12 10h3v2h-3v3h-2v-3H7v-2h3V7h2v3Z M11 3a8 8 0 0 1 8 8c0 1.849-.63 3.549-1.683 4.903L21.414 20 20 21.414l-4.097-4.097A7.962 7.962 0 0 1 11 19a8 8 0 1 1 0-16Zm0 2a6 6 0 1 0 0 12 6 6 0 0 0 0-12Z',
61
+ zoomOut:
62
+ 'M15 12H7v-2h8v2Z M11 3a8 8 0 0 1 8 8c0 1.849-.63 3.549-1.683 4.903L21.414 20 20 21.414l-4.097-4.097A7.962 7.962 0 0 1 11 19a8 8 0 1 1 0-16Zm0 2a6 6 0 1 0 0 12 6 6 0 0 0 0-12Z',
63
+ reset:
64
+ 'M5 12a7 7 0 0 0 7 7 7.15 7.15 0 0 0 4.955-2h-2.943v-2h6v6h-2v-2.257A9.148 9.148 0 0 1 12 21a9 9 0 0 1-9-9v-1h2v1Zm1-6.754A9.148 9.148 0 0 1 12 3a9 9 0 0 1 9 9v1h-2v-1a7 7 0 0 0-7-7 7.15 7.15 0 0 0-4.955 2H10v2H4V3h2v2.246Z',
65
+ } as const;
66
+
67
+ // Every size is `calc(N * var(--okicp-s))`, so `appearance.scale` scales the
68
+ // whole screen the way it scales the native metrics.
69
+ const STYLES = `
70
+ .okicp-root{position:fixed;inset:0;z-index:${Z_INDEX};display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.5);-webkit-tap-highlight-color:transparent;overscroll-behavior:contain;animation:okicp-fade .15s ease-out}
71
+ .okicp-panel{position:relative;display:flex;flex-direction:column;box-sizing:border-box;width:min(calc(560px * var(--okicp-s)),calc(100% - 48px));height:min(calc(760px * var(--okicp-s)),calc(100% - 48px));background:var(--okicp-bg);color:var(--okicp-title);border-radius:calc(16px * var(--okicp-s));overflow:hidden;outline:none;box-shadow:0 0 0 1px rgba(0,0,0,.06),0 24px 48px rgba(0,0,0,.24);animation:okicp-pop .18s cubic-bezier(.2,.9,.3,1)}
72
+ @media (max-width:639px),(max-height:559px){.okicp-panel{width:100%;height:100%;border-radius:0;box-shadow:none;padding:env(safe-area-inset-top) env(safe-area-inset-right) 0 env(safe-area-inset-left)}.okicp-footer{padding-bottom:max(calc(20px * var(--okicp-s)),calc(env(safe-area-inset-bottom) + 10px))}}
73
+ .okicp-header{position:relative;flex:none;display:flex;align-items:center;justify-content:center;height:calc(56px * var(--okicp-s));padding:0 calc(60px * var(--okicp-s))}
74
+ .okicp-title{margin:0;font-family:var(--okicp-title-font);font-size:calc(18px * var(--okicp-s));line-height:calc(28px * var(--okicp-s));font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
75
+ .okicp-icon{display:inline-flex;align-items:center;justify-content:center;flex:none;width:calc(40px * var(--okicp-s));height:calc(40px * var(--okicp-s));padding:0;border:0;border-radius:9999px;background:transparent;color:var(--okicp-icon);cursor:pointer;transition:background-color .12s,opacity .12s}
76
+ .okicp-icon svg{width:calc(24px * var(--okicp-s));height:calc(24px * var(--okicp-s));fill:currentColor}
77
+ .okicp-icon:hover{background:var(--okicp-cancel)}
78
+ .okicp-icon:active{background:var(--okicp-cancel-pressed)}
79
+ .okicp-icon:disabled{opacity:.3;cursor:default;background:transparent}
80
+ .okicp-header .okicp-icon{position:absolute;right:calc(12px * var(--okicp-s));top:50%;transform:translateY(-50%)}
81
+ .okicp-stage{position:relative;flex:1 1 auto;min-height:0;overflow:hidden;touch-action:none;user-select:none;-webkit-user-select:none;cursor:grab;outline:none}
82
+ .okicp-stage.okicp-dragging{cursor:grabbing}
83
+ .okicp-stage:focus-visible .okicp-box{outline:2px solid var(--okicp-title);outline-offset:3px}
84
+ .okicp-image{position:absolute;left:50%;top:50%;max-width:none;max-height:none;transform-origin:center;pointer-events:none;-webkit-user-drag:none;will-change:transform}
85
+ .okicp-animate .okicp-image{transition:transform ${ANIMATION_MS}ms cubic-bezier(.2,.8,.2,1)}
86
+ .okicp-box{position:absolute;left:50%;top:50%;box-sizing:border-box;border:1px solid var(--okicp-title);box-shadow:0 0 0 9999px var(--okicp-dim);pointer-events:none}
87
+ .okicp-circle{border-radius:50%;border-color:transparent}
88
+ .okicp-grid{position:absolute;inset:0;opacity:0;transition:opacity .2s;background-image:linear-gradient(rgba(255,255,255,.8),rgba(255,255,255,.8)),linear-gradient(rgba(255,255,255,.8),rgba(255,255,255,.8)),linear-gradient(rgba(255,255,255,.8),rgba(255,255,255,.8)),linear-gradient(rgba(255,255,255,.8),rgba(255,255,255,.8));background-size:1px 100%,1px 100%,100% 1px,100% 1px;background-position:33.333% 0,66.667% 0,0 33.333%,0 66.667%;background-repeat:no-repeat}
89
+ .okicp-guides .okicp-grid{opacity:1}
90
+ .okicp-toolbar{flex:none;display:flex;align-items:center;gap:calc(4px * var(--okicp-s));padding:calc(12px * var(--okicp-s)) calc(16px * var(--okicp-s)) 0}
91
+ .okicp-slider{flex:1;min-width:0;height:calc(40px * var(--okicp-s));margin:0 calc(4px * var(--okicp-s));accent-color:var(--okicp-confirm);cursor:pointer;background:transparent}
92
+ .okicp-footer{flex:none;display:flex;gap:calc(10px * var(--okicp-s));padding:calc(20px * var(--okicp-s))}
93
+ .okicp-button{position:relative;flex:1 1 0;min-width:0;display:inline-flex;align-items:center;justify-content:center;gap:calc(8px * var(--okicp-s));height:calc(50px * var(--okicp-s));padding:0 calc(21px * var(--okicp-s));border:0;border-radius:9999px;font-family:var(--okicp-button-font);font-size:calc(16px * var(--okicp-s));line-height:calc(24px * var(--okicp-s));font-weight:500;cursor:pointer;transition:background-color .12s,opacity .12s;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
94
+ .okicp-cancel{background:var(--okicp-cancel);color:var(--okicp-cancel-text)}
95
+ .okicp-cancel:active{background:var(--okicp-cancel-pressed)}
96
+ .okicp-confirm{background:var(--okicp-confirm);color:var(--okicp-confirm-text)}
97
+ .okicp-confirm:active{background:var(--okicp-confirm-pressed)}
98
+ .okicp-button:disabled{cursor:default}
99
+ .okicp-cancel:disabled{opacity:.5}
100
+ .okicp-button:focus-visible,.okicp-icon:focus-visible{outline:2px solid var(--okicp-title);outline-offset:2px}
101
+ .okicp-spinner{display:none;flex:none;width:calc(16px * var(--okicp-s));height:calc(16px * var(--okicp-s));border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:okicp-spin .7s linear infinite}
102
+ .okicp-processing .okicp-spinner{display:inline-block}
103
+ .okicp-processing .okicp-stage{pointer-events:none;cursor:default}
104
+ @keyframes okicp-spin{to{transform:rotate(360deg)}}
105
+ @keyframes okicp-fade{from{opacity:0}}
106
+ @keyframes okicp-pop{from{opacity:0;transform:scale(.96)}}
107
+ @media (prefers-reduced-motion:reduce){.okicp-root,.okicp-panel{animation:none}.okicp-animate .okicp-image{transition:none}}
108
+ `;
109
+
110
+ function ensureStyles(): void {
111
+ if (document.getElementById(STYLE_ELEMENT_ID)) {
112
+ return;
113
+ }
114
+ const style = document.createElement('style');
115
+ style.id = STYLE_ELEMENT_ID;
116
+ style.textContent = STYLES;
117
+ document.head.appendChild(style);
118
+ }
119
+
120
+ function element<K extends keyof HTMLElementTagNameMap>(
121
+ tag: K,
122
+ className?: string
123
+ ): HTMLElementTagNameMap[K] {
124
+ const node = document.createElement(tag);
125
+ if (className) {
126
+ node.className = className;
127
+ }
128
+ return node;
129
+ }
130
+
131
+ function iconButton(path: string, label: string): HTMLButtonElement {
132
+ const button = element('button', 'okicp-icon');
133
+ button.type = 'button';
134
+ button.setAttribute('aria-label', label);
135
+ button.title = label;
136
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
137
+ svg.setAttribute('viewBox', '0 0 24 24');
138
+ svg.setAttribute('aria-hidden', 'true');
139
+ const shape = document.createElementNS('http://www.w3.org/2000/svg', 'path');
140
+ shape.setAttribute('d', path);
141
+ shape.setAttribute('fill-rule', 'evenodd');
142
+ svg.appendChild(shape);
143
+ button.appendChild(svg);
144
+ return button;
145
+ }
146
+
147
+ function textButton(className: string, text: string): HTMLButtonElement {
148
+ const button = element('button', `okicp-button ${className}`);
149
+ button.type = 'button';
150
+ const label = element('span');
151
+ label.textContent = text;
152
+ button.append(element('span', 'okicp-spinner'), label);
153
+ return button;
154
+ }
155
+
156
+ function zoomToSlider(zoom: number): number {
157
+ return Math.round(
158
+ (Math.log(zoom / MIN_ZOOM) / Math.log(MAX_ZOOM / MIN_ZOOM)) * SLIDER_STEPS
159
+ );
160
+ }
161
+
162
+ function sliderToZoom(value: number): number {
163
+ return MIN_ZOOM * (MAX_ZOOM / MIN_ZOOM) ** (value / SLIDER_STEPS);
164
+ }
165
+
166
+ let titleIdCounter = 0;
167
+
168
+ export function presentCropper<T>(
169
+ options: CropperViewOptions,
170
+ onConfirm: CropperConfirmHandler<T>
171
+ ): Promise<T> {
172
+ return new Promise<T>((resolve, reject) => {
173
+ ensureStyles();
174
+ const theme = resolveTheme(options.appearance);
175
+ const imageSize: Size = {
176
+ width: options.image.naturalWidth,
177
+ height: options.image.naturalHeight,
178
+ };
179
+ const aspectFor = (rotation: Rotation) =>
180
+ cropAspectRatio({
181
+ image: imageSize,
182
+ rotation,
183
+ targetAspectRatio: options.aspectRatio,
184
+ circular: options.circular,
185
+ });
186
+ // Native hides the grid in circular mode.
187
+ const showGuidelines =
188
+ options.showGuidelines !== false && !options.circular;
189
+
190
+ let state: CropState = INITIAL_STATE;
191
+ // Cumulative CSS angle, so a turn from 270° to 0° keeps going
192
+ // counterclockwise instead of spinning back.
193
+ let visualRotation = 0;
194
+ let stageSize: Size = { width: 0, height: 0 };
195
+ let box: Size = { width: 0, height: 0 };
196
+ let processing = false;
197
+ let closed = false;
198
+ let animationTimer: ReturnType<typeof setTimeout> | undefined;
199
+ let guideTimer: ReturnType<typeof setTimeout> | undefined;
200
+ const pointers = new Map<number, Point>();
201
+ const previousFocus =
202
+ document.activeElement instanceof HTMLElement
203
+ ? document.activeElement
204
+ : null;
205
+
206
+ // DOM
207
+ const root = element('div', 'okicp-root');
208
+ const titleId = `okicp-title-${(titleIdCounter += 1)}`;
209
+ root.setAttribute('role', 'dialog');
210
+ root.setAttribute('aria-modal', 'true');
211
+ root.setAttribute('aria-labelledby', titleId);
212
+ root.style.setProperty('--okicp-s', String(theme.scale));
213
+ root.style.setProperty('--okicp-bg', theme.backgroundColor);
214
+ root.style.setProperty('--okicp-dim', theme.dimmedColor);
215
+ root.style.setProperty('--okicp-title', theme.titleColor);
216
+ root.style.setProperty('--okicp-icon', theme.iconColor);
217
+ root.style.setProperty('--okicp-cancel', theme.cancelButtonColor);
218
+ root.style.setProperty(
219
+ '--okicp-cancel-pressed',
220
+ theme.cancelButtonPressedColor
221
+ );
222
+ root.style.setProperty('--okicp-cancel-text', theme.cancelButtonTextColor);
223
+ root.style.setProperty('--okicp-confirm', theme.confirmButtonColor);
224
+ root.style.setProperty(
225
+ '--okicp-confirm-pressed',
226
+ theme.confirmButtonPressedColor
227
+ );
228
+ root.style.setProperty(
229
+ '--okicp-confirm-text',
230
+ theme.confirmButtonTextColor
231
+ );
232
+ root.style.setProperty(
233
+ '--okicp-title-font',
234
+ theme.titleFontFamily
235
+ ? `"${theme.titleFontFamily}", system-ui`
236
+ : 'inherit'
237
+ );
238
+ root.style.setProperty(
239
+ '--okicp-button-font',
240
+ theme.buttonFontFamily
241
+ ? `"${theme.buttonFontFamily}", system-ui`
242
+ : 'inherit'
243
+ );
244
+ root.style.colorScheme = theme.colorScheme;
245
+
246
+ const panel = element('div', 'okicp-panel');
247
+ panel.tabIndex = -1;
248
+
249
+ const header = element('header', 'okicp-header');
250
+ const title = element('h2', 'okicp-title');
251
+ title.id = titleId;
252
+ title.textContent = options.title || 'Crop image';
253
+ header.appendChild(title);
254
+ const rotateButton = iconButton(ICONS.rotate, 'Rotate');
255
+ if (!options.rotateButtonHidden) {
256
+ header.appendChild(rotateButton);
257
+ }
258
+
259
+ const stage = element('div', 'okicp-stage');
260
+ stage.tabIndex = 0;
261
+ stage.setAttribute('role', 'application');
262
+ stage.setAttribute(
263
+ 'aria-label',
264
+ 'Crop area. Drag or use arrow keys to move, scroll or + and - to zoom.'
265
+ );
266
+ const image = options.image;
267
+ image.className = 'okicp-image';
268
+ image.alt = '';
269
+ image.draggable = false;
270
+ image.style.width = `${imageSize.width}px`;
271
+ image.style.height = `${imageSize.height}px`;
272
+ image.style.marginLeft = `${-imageSize.width / 2}px`;
273
+ image.style.marginTop = `${-imageSize.height / 2}px`;
274
+ const cropBox = element(
275
+ 'div',
276
+ options.circular ? 'okicp-box okicp-circle' : 'okicp-box'
277
+ );
278
+ if (showGuidelines) {
279
+ cropBox.appendChild(element('div', 'okicp-grid'));
280
+ }
281
+ stage.append(image, cropBox);
282
+
283
+ const toolbar = element('div', 'okicp-toolbar');
284
+ const zoomOutButton = iconButton(ICONS.zoomOut, 'Zoom out');
285
+ const zoomInButton = iconButton(ICONS.zoomIn, 'Zoom in');
286
+ const resetButton = iconButton(ICONS.reset, 'Reset');
287
+ const slider = element('input', 'okicp-slider');
288
+ slider.type = 'range';
289
+ slider.min = '0';
290
+ slider.max = String(SLIDER_STEPS);
291
+ slider.step = '1';
292
+ slider.setAttribute('aria-label', 'Zoom');
293
+ toolbar.append(zoomOutButton, slider, zoomInButton, resetButton);
294
+
295
+ const footer = element('footer', 'okicp-footer');
296
+ const cancelButton = textButton(
297
+ 'okicp-cancel',
298
+ options.cancelText || 'Cancel'
299
+ );
300
+ const confirmButton = textButton(
301
+ 'okicp-confirm',
302
+ options.confirmText || 'Confirm'
303
+ );
304
+ footer.append(cancelButton, confirmButton);
305
+
306
+ panel.append(header, stage, toolbar, footer);
307
+ root.appendChild(panel);
308
+
309
+ // Rendering
310
+ const render = () => {
311
+ cropBox.style.width = `${box.width}px`;
312
+ cropBox.style.height = `${box.height}px`;
313
+ cropBox.style.marginLeft = `${-box.width / 2}px`;
314
+ cropBox.style.marginTop = `${-box.height / 2}px`;
315
+ const scale = box.width > 0 ? scaleOf(state, imageSize, box) : 0;
316
+ image.style.transform = `translate(${state.offsetX}px, ${
317
+ state.offsetY
318
+ }px) rotate(${-visualRotation}deg) scale(${scale})`;
319
+ slider.value = String(zoomToSlider(state.zoom));
320
+ zoomOutButton.disabled = processing || state.zoom <= MIN_ZOOM + 0.001;
321
+ zoomInButton.disabled = processing || state.zoom >= MAX_ZOOM - 0.001;
322
+ resetButton.disabled = processing || isSameState(state, INITIAL_STATE);
323
+ rotateButton.disabled = processing;
324
+ slider.disabled = processing;
325
+ cancelButton.disabled = processing;
326
+ confirmButton.disabled = processing || box.width === 0;
327
+ confirmButton.setAttribute('aria-busy', String(processing));
328
+ };
329
+
330
+ const animateNext = () => {
331
+ stage.classList.add('okicp-animate');
332
+ if (animationTimer) {
333
+ clearTimeout(animationTimer);
334
+ }
335
+ animationTimer = setTimeout(() => {
336
+ stage.classList.remove('okicp-animate');
337
+ }, ANIMATION_MS + 30);
338
+ };
339
+
340
+ const showGuides = (linger: boolean) => {
341
+ if (!showGuidelines) {
342
+ return;
343
+ }
344
+ stage.classList.add('okicp-guides');
345
+ if (guideTimer) {
346
+ clearTimeout(guideTimer);
347
+ guideTimer = undefined;
348
+ }
349
+ if (linger) {
350
+ guideTimer = setTimeout(() => {
351
+ stage.classList.remove('okicp-guides');
352
+ }, GUIDE_LINGER_MS);
353
+ }
354
+ };
355
+
356
+ const layout = () => {
357
+ const rect = stage.getBoundingClientRect();
358
+ const nextStage = { width: rect.width, height: rect.height };
359
+ if (
360
+ nextStage.width === stageSize.width &&
361
+ nextStage.height === stageSize.height
362
+ ) {
363
+ return;
364
+ }
365
+ stageSize = nextStage;
366
+ const nextBox = fitCropBox(stageSize, aspectFor(state.rotation));
367
+ state = rescale(state, box, nextBox, imageSize);
368
+ box = nextBox;
369
+ render();
370
+ };
371
+
372
+ const update = (next: CropState, animated = false) => {
373
+ if (animated) {
374
+ animateNext();
375
+ }
376
+ state = next;
377
+ render();
378
+ };
379
+
380
+ const anchorOf = (clientX: number, clientY: number): Point => {
381
+ const rect = stage.getBoundingClientRect();
382
+ return {
383
+ x: clientX - rect.left - rect.width / 2,
384
+ y: clientY - rect.top - rect.height / 2,
385
+ };
386
+ };
387
+
388
+ const zoomBy = (factor: number, anchor: Point = { x: 0, y: 0 }) => {
389
+ update(zoomAt(state, state.zoom * factor, anchor, imageSize, box), true);
390
+ };
391
+
392
+ const rotate = () => {
393
+ if (processing) {
394
+ return;
395
+ }
396
+ visualRotation += 90;
397
+ // An unlocked crop box swaps its ratio with the image.
398
+ const nextBox = fitCropBox(
399
+ stageSize,
400
+ aspectFor(((state.rotation + 90) % 360) as Rotation)
401
+ );
402
+ const rotated = rotateCounterclockwise(state, imageSize, nextBox);
403
+ box = nextBox;
404
+ update(rotated, true);
405
+ };
406
+
407
+ const reset = () => {
408
+ // Equivalent angle, so only position and zoom animate back.
409
+ visualRotation -= state.rotation;
410
+ if (visualRotation % 360 !== 0) {
411
+ visualRotation = Math.round(visualRotation / 360) * 360;
412
+ }
413
+ box = fitCropBox(stageSize, aspectFor(0));
414
+ update(INITIAL_STATE, true);
415
+ };
416
+
417
+ // Teardown
418
+ const resizeObserver =
419
+ typeof ResizeObserver === 'function'
420
+ ? new ResizeObserver(() => layout())
421
+ : undefined;
422
+
423
+ const close = () => {
424
+ if (closed) {
425
+ return;
426
+ }
427
+ closed = true;
428
+ resizeObserver?.disconnect();
429
+ window.removeEventListener('resize', layout);
430
+ if (animationTimer) {
431
+ clearTimeout(animationTimer);
432
+ }
433
+ if (guideTimer) {
434
+ clearTimeout(guideTimer);
435
+ }
436
+ root.remove();
437
+ previousFocus?.focus?.();
438
+ };
439
+
440
+ const cancel = () => {
441
+ if (processing || closed) {
442
+ return;
443
+ }
444
+ close();
445
+ reject(
446
+ new ImageCropPickerError(
447
+ 'E_PICKER_CANCELLED',
448
+ 'User cancelled image selection'
449
+ )
450
+ );
451
+ };
452
+
453
+ const confirm = () => {
454
+ if (processing || closed || box.width === 0) {
455
+ return;
456
+ }
457
+ processing = true;
458
+ panel.classList.add('okicp-processing');
459
+ render();
460
+ const finalState = state;
461
+ const finalBox = box;
462
+ // Let the spinner paint before the synchronous canvas work.
463
+ requestAnimationFrame(() => {
464
+ setTimeout(() => {
465
+ onConfirm(finalState, finalBox).then(
466
+ (result) => {
467
+ close();
468
+ resolve(result);
469
+ },
470
+ (error: unknown) => {
471
+ close();
472
+ reject(error);
473
+ }
474
+ );
475
+ }, 0);
476
+ });
477
+ };
478
+
479
+ // Pointer: one pointer pans, two pinch around their midpoint.
480
+ let lastMidpoint: Point | undefined;
481
+ let lastDistance = 0;
482
+ const pinchMetrics = () => {
483
+ const [a, b] = [...pointers.values()];
484
+ if (!a || !b) {
485
+ return undefined;
486
+ }
487
+ return {
488
+ midpoint: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 },
489
+ distance: Math.hypot(a.x - b.x, a.y - b.y),
490
+ };
491
+ };
492
+
493
+ stage.addEventListener('pointerdown', (event) => {
494
+ if (processing || (event.pointerType === 'mouse' && event.button !== 0)) {
495
+ return;
496
+ }
497
+ stage.setPointerCapture(event.pointerId);
498
+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
499
+ stage.classList.add('okicp-dragging');
500
+ stage.classList.remove('okicp-animate');
501
+ showGuides(false);
502
+ const pinch = pinchMetrics();
503
+ lastMidpoint = pinch?.midpoint;
504
+ lastDistance = pinch?.distance ?? 0;
505
+ });
506
+
507
+ stage.addEventListener('pointermove', (event) => {
508
+ const previous = pointers.get(event.pointerId);
509
+ if (!previous) {
510
+ return;
511
+ }
512
+ const current = { x: event.clientX, y: event.clientY };
513
+ pointers.set(event.pointerId, current);
514
+ if (pointers.size === 1) {
515
+ update(
516
+ pan(
517
+ state,
518
+ current.x - previous.x,
519
+ current.y - previous.y,
520
+ imageSize,
521
+ box
522
+ )
523
+ );
524
+ return;
525
+ }
526
+ const pinch = pinchMetrics();
527
+ if (!pinch || !lastMidpoint || lastDistance === 0) {
528
+ return;
529
+ }
530
+ let next = zoomAt(
531
+ state,
532
+ state.zoom * (pinch.distance / lastDistance),
533
+ anchorOf(pinch.midpoint.x, pinch.midpoint.y),
534
+ imageSize,
535
+ box
536
+ );
537
+ next = pan(
538
+ next,
539
+ pinch.midpoint.x - lastMidpoint.x,
540
+ pinch.midpoint.y - lastMidpoint.y,
541
+ imageSize,
542
+ box
543
+ );
544
+ lastMidpoint = pinch.midpoint;
545
+ lastDistance = pinch.distance;
546
+ update(next);
547
+ });
548
+
549
+ const endPointer = (event: PointerEvent) => {
550
+ if (!pointers.delete(event.pointerId)) {
551
+ return;
552
+ }
553
+ const pinch = pinchMetrics();
554
+ lastMidpoint = pinch?.midpoint;
555
+ lastDistance = pinch?.distance ?? 0;
556
+ if (pointers.size === 0) {
557
+ stage.classList.remove('okicp-dragging');
558
+ showGuides(true);
559
+ }
560
+ };
561
+ stage.addEventListener('pointerup', endPointer);
562
+ stage.addEventListener('pointercancel', endPointer);
563
+
564
+ // Trackpad pinch arrives as a ctrl+wheel event with small deltas.
565
+ stage.addEventListener(
566
+ 'wheel',
567
+ (event) => {
568
+ event.preventDefault();
569
+ if (processing) {
570
+ return;
571
+ }
572
+ const lineHeight = event.deltaMode === 1 ? 16 : 1;
573
+ const delta = event.deltaY * lineHeight;
574
+ const factor = Math.exp(-delta * (event.ctrlKey ? 0.01 : 0.0015));
575
+ stage.classList.remove('okicp-animate');
576
+ update(
577
+ zoomAt(
578
+ state,
579
+ state.zoom * factor,
580
+ anchorOf(event.clientX, event.clientY),
581
+ imageSize,
582
+ box
583
+ )
584
+ );
585
+ showGuides(true);
586
+ },
587
+ { passive: false }
588
+ );
589
+
590
+ stage.addEventListener('dblclick', (event) => {
591
+ if (processing) {
592
+ return;
593
+ }
594
+ if (state.zoom < 1.5) {
595
+ update(
596
+ zoomAt(
597
+ state,
598
+ 2,
599
+ anchorOf(event.clientX, event.clientY),
600
+ imageSize,
601
+ box
602
+ ),
603
+ true
604
+ );
605
+ } else {
606
+ update(zoomAt(state, MIN_ZOOM, { x: 0, y: 0 }, imageSize, box), true);
607
+ }
608
+ });
609
+
610
+ slider.addEventListener('input', () => {
611
+ stage.classList.remove('okicp-animate');
612
+ update(
613
+ zoomAt(
614
+ state,
615
+ sliderToZoom(Number(slider.value)),
616
+ { x: 0, y: 0 },
617
+ imageSize,
618
+ box
619
+ )
620
+ );
621
+ });
622
+
623
+ rotateButton.addEventListener('click', rotate);
624
+ zoomInButton.addEventListener('click', () => zoomBy(ZOOM_STEP));
625
+ zoomOutButton.addEventListener('click', () => zoomBy(1 / ZOOM_STEP));
626
+ resetButton.addEventListener('click', reset);
627
+ cancelButton.addEventListener('click', cancel);
628
+ confirmButton.addEventListener('click', confirm);
629
+
630
+ root.addEventListener('keydown', (event) => {
631
+ if (event.key === 'Escape') {
632
+ event.preventDefault();
633
+ cancel();
634
+ return;
635
+ }
636
+ if (event.key === 'Tab') {
637
+ // Keep focus inside the cropper.
638
+ const focusable = [
639
+ stage,
640
+ ...panel.querySelectorAll<HTMLElement>(
641
+ 'button:not(:disabled), input:not(:disabled)'
642
+ ),
643
+ ].filter((node) => node.isConnected && node.offsetParent !== null);
644
+ const first = focusable[0];
645
+ const last = focusable[focusable.length - 1];
646
+ if (!first || !last) {
647
+ return;
648
+ }
649
+ if (event.shiftKey && document.activeElement === first) {
650
+ event.preventDefault();
651
+ last.focus();
652
+ } else if (!event.shiftKey && document.activeElement === last) {
653
+ event.preventDefault();
654
+ first.focus();
655
+ } else if (!panel.contains(document.activeElement)) {
656
+ event.preventDefault();
657
+ first.focus();
658
+ }
659
+ return;
660
+ }
661
+ const target = event.target as HTMLElement | null;
662
+ if (target?.tagName === 'BUTTON' || target === slider) {
663
+ // Buttons and the slider handle their own keys.
664
+ return;
665
+ }
666
+ if (event.metaKey || event.ctrlKey || event.altKey) {
667
+ return;
668
+ }
669
+ const step = event.shiftKey ? KEYBOARD_PAN_FAST : KEYBOARD_PAN;
670
+ switch (event.key) {
671
+ case 'Enter':
672
+ event.preventDefault();
673
+ confirm();
674
+ break;
675
+ case 'ArrowLeft':
676
+ event.preventDefault();
677
+ update(pan(state, -step, 0, imageSize, box));
678
+ break;
679
+ case 'ArrowRight':
680
+ event.preventDefault();
681
+ update(pan(state, step, 0, imageSize, box));
682
+ break;
683
+ case 'ArrowUp':
684
+ event.preventDefault();
685
+ update(pan(state, 0, -step, imageSize, box));
686
+ break;
687
+ case 'ArrowDown':
688
+ event.preventDefault();
689
+ update(pan(state, 0, step, imageSize, box));
690
+ break;
691
+ case '+':
692
+ case '=':
693
+ event.preventDefault();
694
+ zoomBy(ZOOM_STEP);
695
+ break;
696
+ case '-':
697
+ case '_':
698
+ event.preventDefault();
699
+ zoomBy(1 / ZOOM_STEP);
700
+ break;
701
+ case 'r':
702
+ case 'R':
703
+ if (!options.rotateButtonHidden) {
704
+ event.preventDefault();
705
+ rotate();
706
+ }
707
+ break;
708
+ default:
709
+ break;
710
+ }
711
+ });
712
+
713
+ // Mount
714
+ document.body.appendChild(root);
715
+ if (resizeObserver) {
716
+ resizeObserver.observe(stage);
717
+ } else {
718
+ window.addEventListener('resize', layout);
719
+ }
720
+ layout();
721
+ // The panel takes focus so keys work at once without drawing the crop
722
+ // area's focus ring; Tab still reaches the crop area.
723
+ panel.focus({ preventScroll: true });
724
+ });
725
+ }