panelui-native 0.109.0 → 0.111.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.
@@ -0,0 +1,1036 @@
1
+ /**
2
+ * AvatarCropper — frame a photo under a circle, and get that circle back as an
3
+ * image.
4
+ *
5
+ * ```tsx
6
+ * const cropper = useRef<AvatarCropperHandle>(null);
7
+ *
8
+ * <AvatarCropper ref={cropper} source={photo} className="flex-1">
9
+ * <AvatarCropper.Canvas />
10
+ * <View className="flex-row justify-between p-4">
11
+ * <AvatarCropper.Reset />
12
+ * <AvatarCropper.Rotate />
13
+ * </View>
14
+ * </AvatarCropper>
15
+ *
16
+ * const { uri } = await cropper.current!.crop({ size: 512 });
17
+ * ```
18
+ *
19
+ * ## The mask stays put; the photo moves
20
+ *
21
+ * The mask sits in the middle of the canvas and never moves. Dragging, pinching
22
+ * and turning all move the photo underneath it, which is what makes the result
23
+ * predictable: the image you get back is exactly what is inside the outline
24
+ * when you press Done. The photo is never allowed to leave part of the mask
25
+ * empty — let go past an edge, or zoom out too far, and it springs back to the
26
+ * nearest position that covers it. At an angle that takes extra zoom for a
27
+ * square mask, whose corners reach further than a circle does, so the minimum
28
+ * zoom follows the angle.
29
+ *
30
+ * ## One surface, three gestures at once
31
+ *
32
+ * Pan, pinch and rotation are recognised together, so a two-finger gesture can
33
+ * move, zoom and turn in one motion the way a photo on a table would. Zoom and
34
+ * turn happen about the point between the fingers, which keeps whatever is
35
+ * under them under them.
36
+ *
37
+ * ## The export is the same arithmetic, in pixels
38
+ *
39
+ * `crop()` turns the source by the photo's angle, cuts the square the mask
40
+ * covers and scales it to the size asked for, through the optional
41
+ * `expo-image-manipulator`. The source is redrawn upright first: a camera photo
42
+ * often stores its orientation as a flag rather than in its pixels, and the
43
+ * turn and the cut both work on the raw pixels. `getCrop()` returns the same
44
+ * rectangle without any dependency, for an app that crops on its server.
45
+ */
46
+ import {
47
+ createContext,
48
+ forwardRef,
49
+ useCallback,
50
+ useContext,
51
+ useEffect,
52
+ useImperativeHandle,
53
+ useMemo,
54
+ useRef,
55
+ useState,
56
+ type ReactNode,
57
+ type Ref,
58
+ } from 'react';
59
+ import {
60
+ Image,
61
+ View,
62
+ type AccessibilityActionEvent,
63
+ type LayoutChangeEvent,
64
+ type ViewProps,
65
+ } from 'react-native';
66
+ import { Gesture, GestureDetector } from 'react-native-gesture-handler';
67
+ import Animated, {
68
+ cancelAnimation,
69
+ runOnJS,
70
+ useAnimatedStyle,
71
+ useDerivedValue,
72
+ useSharedValue,
73
+ withSpring,
74
+ withTiming,
75
+ type SharedValue,
76
+ } from 'react-native-reanimated';
77
+ import Svg, { Path } from 'react-native-svg';
78
+ import { useCSSVariable } from 'uniwind';
79
+ import { RotateSquareIcon } from '../../icons';
80
+ import { cn } from '../../utils/cn';
81
+ import { Button, type ButtonProps } from '../button';
82
+ import {
83
+ IDENTITY,
84
+ baseSize,
85
+ coversMask,
86
+ maskPath,
87
+ nextQuarterTurn,
88
+ normalizeDegrees,
89
+ present,
90
+ rotateAbout,
91
+ settle,
92
+ sourceCrop,
93
+ zoomAbout,
94
+ type CropBounds,
95
+ type CropFrame,
96
+ type CropShape,
97
+ type CropState,
98
+ type Size,
99
+ type SourceCrop,
100
+ } from './avatar-cropper-math';
101
+
102
+ export type { CropShape as AvatarCropperShape, SourceCrop as AvatarCrop };
103
+
104
+ /** Where the photo settles after a gesture. Firm, so it lands without drifting. */
105
+ const SETTLE_SPRING = { damping: 34, stiffness: 320, mass: 1 } as const;
106
+
107
+ /** A quarter turn from the button. Long enough to read as a turn, not a jump. */
108
+ const TURN_DURATION = 260;
109
+
110
+ /** How far an accessibility zoom step goes. */
111
+ const ZOOM_STEP = 1.25;
112
+
113
+ /** How far a raw gesture may run past a bound before the rubber band stops it. */
114
+ const OVERSHOOT = 2;
115
+
116
+ // ---------------------------------------------------------------------------
117
+ // Optional dependencies
118
+ // ---------------------------------------------------------------------------
119
+
120
+ interface ManipulatorContext {
121
+ resize(size: { width?: number; height?: number }): ManipulatorContext;
122
+ rotate(degrees: number): ManipulatorContext;
123
+ crop(rect: { originX: number; originY: number; width: number; height: number }): ManipulatorContext;
124
+ renderAsync(): Promise<{
125
+ saveAsync(options: { format?: string; compress?: number }): Promise<AvatarCropResult>;
126
+ }>;
127
+ }
128
+
129
+ interface ManipulatorModule {
130
+ ImageManipulator?: { manipulate(uri: string): ManipulatorContext };
131
+ }
132
+
133
+ interface PickerAsset {
134
+ uri: string;
135
+ width: number;
136
+ height: number;
137
+ }
138
+
139
+ interface PickerModule {
140
+ requestCameraPermissionsAsync(): Promise<{ granted: boolean }>;
141
+ launchCameraAsync(options: unknown): Promise<{ canceled: boolean; assets?: PickerAsset[] | null }>;
142
+ launchImageLibraryAsync(
143
+ options: unknown
144
+ ): Promise<{ canceled: boolean; assets?: PickerAsset[] | null }>;
145
+ }
146
+
147
+ /**
148
+ * `expo-image-manipulator`, or null when it is not installed. Each `require`
149
+ * sits directly in its `try` block, which is what lets Metro bundle an app
150
+ * that does not have the package.
151
+ */
152
+ function loadManipulator(): ManipulatorModule | null {
153
+ try {
154
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
155
+ return require('expo-image-manipulator') as ManipulatorModule;
156
+ } catch {
157
+ return null;
158
+ }
159
+ }
160
+
161
+ /** `expo-image-picker`, or null when it is not installed. */
162
+ function loadPicker(): PickerModule | null {
163
+ try {
164
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
165
+ return require('expo-image-picker') as PickerModule;
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+
171
+ /** `react-native-view-shot`'s capture function, or null when it is not installed. */
172
+ function loadCapture(): ((view: unknown, options: unknown) => Promise<string>) | null {
173
+ try {
174
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
175
+ const mod = require('react-native-view-shot');
176
+ return (mod?.captureRef as (view: unknown, options: unknown) => Promise<string>) ?? null;
177
+ } catch {
178
+ return null;
179
+ }
180
+ }
181
+
182
+ /** True when `crop()` can write an image, because `expo-image-manipulator` is installed. */
183
+ export const hasAvatarCropperExport = loadManipulator()?.ImageManipulator != null;
184
+
185
+ /** A photo to crop, as the picker returns it. */
186
+ export interface AvatarCropperSource {
187
+ /** A local file or `data:` URI. */
188
+ uri: string;
189
+ /** Width in pixels, upright. Measured from the image when left out. */
190
+ width?: number;
191
+ /** Height in pixels, upright. Measured from the image when left out. */
192
+ height?: number;
193
+ }
194
+
195
+ export interface PickAvatarImageOptions {
196
+ /** Where the photo comes from. Default `'library'`. */
197
+ from?: 'library' | 'camera';
198
+ /** JPEG quality of the picked photo, 0–1. Default 1, since the crop compresses it again. */
199
+ quality?: number;
200
+ }
201
+
202
+ /**
203
+ * Let the user choose a photo or take one, ready to pass to `AvatarCropper`.
204
+ *
205
+ * Resolves `null` when the user cancels. Taking a photo asks for camera
206
+ * permission first and throws when it is refused, so the app can explain why
207
+ * nothing happened. Choosing from the library needs no permission. The
208
+ * picker's own editing is left off, because the cropper is the editor.
209
+ *
210
+ * Needs the optional `expo-image-picker`, and throws if it is not installed.
211
+ * In a development build the camera also needs the permission strings from
212
+ * that package's config plugin.
213
+ */
214
+ export async function pickAvatarImage({
215
+ from = 'library',
216
+ quality = 1,
217
+ }: PickAvatarImageOptions = {}): Promise<Required<AvatarCropperSource> | null> {
218
+ const picker = loadPicker();
219
+ if (!picker) {
220
+ throw new Error(
221
+ 'pickAvatarImage needs expo-image-picker. Install it with: npx expo install expo-image-picker'
222
+ );
223
+ }
224
+ const options = { mediaTypes: ['images'], allowsEditing: false, quality, exif: false };
225
+ let result: Awaited<ReturnType<PickerModule['launchImageLibraryAsync']>>;
226
+ if (from === 'camera') {
227
+ const permission = await picker.requestCameraPermissionsAsync();
228
+ if (!permission.granted) throw new Error('pickAvatarImage: camera permission was refused.');
229
+ result = await picker.launchCameraAsync(options);
230
+ } else {
231
+ result = await picker.launchImageLibraryAsync(options);
232
+ }
233
+ const asset = result.canceled ? undefined : result.assets?.[0];
234
+ return asset ? { uri: asset.uri, width: asset.width, height: asset.height } : null;
235
+ }
236
+
237
+ // ---------------------------------------------------------------------------
238
+ // Root
239
+ // ---------------------------------------------------------------------------
240
+
241
+ export interface AvatarCropResult {
242
+ /** The cropped image, written to the app's cache directory. */
243
+ uri: string;
244
+ width: number;
245
+ height: number;
246
+ }
247
+
248
+ export interface AvatarCropOptions {
249
+ /**
250
+ * Side of the image to write, in pixels. Default 1024. A crop with fewer
251
+ * pixels than this is written at its own size rather than scaled up.
252
+ */
253
+ size?: number;
254
+ /**
255
+ * Default `'jpeg'`, or `'png'` when `background` is `'transparent'` so the
256
+ * transparency survives. A crop with a background is written as PNG or
257
+ * JPEG, so `'webp'` is written as PNG there.
258
+ */
259
+ format?: 'jpeg' | 'png' | 'webp';
260
+ /** Quality, 0–1, for JPEG and WebP. Default 0.9. */
261
+ compress?: number;
262
+ }
263
+
264
+ export interface AvatarCropperHandle {
265
+ /**
266
+ * Write what the mask covers to a new square image. The image is square for
267
+ * every shape; draw it in a round `Avatar` to show it as a circle.
268
+ *
269
+ * Needs the optional `expo-image-manipulator`, and throws if it is not
270
+ * installed — use `getCrop()` then. A crop with part of `background` in it
271
+ * (only possible with `cover` off) is drawn and captured instead, and needs
272
+ * the optional `react-native-view-shot`.
273
+ */
274
+ crop(options?: AvatarCropOptions): Promise<AvatarCropResult>;
275
+ /**
276
+ * The rectangle the mask covers, in the source's pixels, after turning the
277
+ * source by `rotation` degrees clockwise. Null until the photo has been
278
+ * measured and laid out. With `cover` off it can reach past the turned
279
+ * image's edges; whatever lies outside is `background`.
280
+ */
281
+ getCrop(): SourceCrop | null;
282
+ /** Turn a quarter clockwise, or a quarter back with `-1`. */
283
+ rotate(direction?: 1 | -1): void;
284
+ /** Back to the photo centred, unzoomed and upright. */
285
+ reset(): void;
286
+ }
287
+
288
+ export interface AvatarCropperProps extends ViewProps {
289
+ /** The photo. Changing it starts the crop again from the centre. */
290
+ source: AvatarCropperSource;
291
+ /**
292
+ * The outline the photo is framed in. Default `'circle'`, which is how
293
+ * `Avatar` draws it. The image written out is square for every shape.
294
+ */
295
+ shape?: CropShape;
296
+ /** How far the photo can be zoomed past filling the mask. Default 5. */
297
+ maxZoom?: number;
298
+ /**
299
+ * Keep the photo covering the whole outline. Default true: let go past an
300
+ * edge, or zoom out too far, and it springs back to fill it.
301
+ *
302
+ * Set it to false to let the photo be zoomed out smaller than the outline,
303
+ * down to `minZoom`. The space around it is filled with `background`, on
304
+ * screen and in the image `crop()` writes.
305
+ */
306
+ cover?: boolean;
307
+ /**
308
+ * With `cover` off, how small the photo can get: its long side as a
309
+ * fraction of the outline's width. Default 0.5.
310
+ */
311
+ minZoom?: number;
312
+ /**
313
+ * What fills the outline around a photo smaller than it, with `cover` off.
314
+ * Any colour React Native accepts, or `'transparent'` — written out as PNG
315
+ * so it stays transparent. Default: the theme's background colour.
316
+ */
317
+ background?: string;
318
+ /** Space between the mask and the canvas's shorter side, in points. Default 24. */
319
+ inset?: number;
320
+ className?: string;
321
+ /** `AvatarCropper.Canvas` and any controls. Left out, the canvas alone. */
322
+ children?: ReactNode;
323
+ }
324
+
325
+ interface CropperContextValue {
326
+ shape: CropShape;
327
+ bounds: CropBounds;
328
+ /** The resolved fill around a photo smaller than the outline. */
329
+ fill: string;
330
+ /** A crop being drawn for capture, while `crop()` is waiting on it. */
331
+ stage: ExportJob | null;
332
+ inset: number;
333
+ source: AvatarCropperSource;
334
+ /** The source's upright size, once known. */
335
+ sourceSize: Size | null;
336
+ frame: CropFrame | null;
337
+ setCanvas(size: Size): void;
338
+ canvas: Size | null;
339
+ x: SharedValue<number>;
340
+ y: SharedValue<number>;
341
+ scale: SharedValue<number>;
342
+ rotation: SharedValue<number>;
343
+ settleNow(): void;
344
+ rotate(direction?: 1 | -1): void;
345
+ reset(): void;
346
+ zoomBy(factor: number): void;
347
+ /** A spoken summary of the crop, refreshed when a gesture settles. */
348
+ summary: string;
349
+ }
350
+
351
+ const CropperContext = createContext<CropperContextValue | null>(null);
352
+
353
+ function useCropper(part: string): CropperContextValue {
354
+ const context = useContext(CropperContext);
355
+ if (!context) throw new Error(`${part} must be rendered inside <AvatarCropper>.`);
356
+ return context;
357
+ }
358
+
359
+ function describe(state: CropState): string {
360
+ const zoom = `${Math.round(state.scale * 100)}% zoom`;
361
+ const angle = Math.round(normalizeDegrees(state.rotation));
362
+ return angle === 0 ? zoom : `${zoom}, turned ${angle} degrees`;
363
+ }
364
+
365
+ function AvatarCropperRoot(
366
+ {
367
+ source,
368
+ shape = 'circle',
369
+ maxZoom = 5,
370
+ cover = true,
371
+ minZoom = 0.5,
372
+ background,
373
+ inset = 24,
374
+ className,
375
+ children,
376
+ ...props
377
+ }: AvatarCropperProps,
378
+ ref: Ref<AvatarCropperHandle>
379
+ ) {
380
+ const x = useSharedValue(0);
381
+ const y = useSharedValue(0);
382
+ const scale = useSharedValue(1);
383
+ const rotation = useSharedValue(0);
384
+ const [canvas, setCanvasState] = useState<Size | null>(null);
385
+ const [measured, setMeasured] = useState<Size | null>(null);
386
+ const [summary, setSummary] = useState(describe(IDENTITY));
387
+ const [stage, setStage] = useState<ExportJob | null>(null);
388
+ const backgroundToken = useCSSVariable('--color-background');
389
+ const fill =
390
+ background ?? (typeof backgroundToken === 'string' ? backgroundToken : '#ffffff');
391
+ const bounds = useMemo<CropBounds>(
392
+ () => ({ shape, maxZoom, cover, minZoom }),
393
+ [shape, maxZoom, cover, minZoom]
394
+ );
395
+
396
+ const { uri, width, height } = source;
397
+ const sourceSize =
398
+ width && height && width > 0 && height > 0 ? { width, height } : measured;
399
+
400
+ // The picker reports the size; anything else is measured once per photo.
401
+ useEffect(() => {
402
+ setMeasured(null);
403
+ if (width && height) return;
404
+ let live = true;
405
+ Image.getSize(
406
+ uri,
407
+ (w, h) => {
408
+ if (live) setMeasured({ width: w, height: h });
409
+ },
410
+ () => {}
411
+ );
412
+ return () => {
413
+ live = false;
414
+ };
415
+ }, [uri, width, height]);
416
+
417
+ // A new photo starts again from the centre.
418
+ useEffect(() => {
419
+ x.value = 0;
420
+ y.value = 0;
421
+ scale.value = 1;
422
+ rotation.value = 0;
423
+ setSummary(describe(IDENTITY));
424
+ }, [uri, x, y, scale, rotation]);
425
+
426
+ const mask = canvas ? Math.max(0, Math.min(canvas.width, canvas.height) - inset * 2) : 0;
427
+ const frame = useMemo<CropFrame | null>(
428
+ () => (sourceSize && mask > 0 ? { mask, image: baseSize(sourceSize, mask) } : null),
429
+ [sourceSize?.width, sourceSize?.height, mask] // eslint-disable-line react-hooks/exhaustive-deps
430
+ );
431
+
432
+ const setCanvas = useCallback((size: Size) => {
433
+ setCanvasState((current) =>
434
+ current && current.width === size.width && current.height === size.height ? current : size
435
+ );
436
+ }, []);
437
+
438
+ const read = useCallback(
439
+ (): CropState => ({ x: x.value, y: y.value, scale: scale.value, rotation: rotation.value }),
440
+ [x, y, scale, rotation]
441
+ );
442
+
443
+ /** Animate to a state, settled against the bounds first. */
444
+ const animateTo = useCallback(
445
+ (target: CropState, timed: boolean) => {
446
+ if (!frame) return;
447
+ const next = settle(target, bounds, frame);
448
+ const run = (value: number) =>
449
+ timed ? withTiming(value, { duration: TURN_DURATION }) : withSpring(value, SETTLE_SPRING);
450
+ x.value = run(next.x);
451
+ y.value = run(next.y);
452
+ scale.value = run(next.scale);
453
+ rotation.value = run(next.rotation);
454
+ setSummary(describe(next));
455
+ },
456
+ [frame, bounds, x, y, scale, rotation]
457
+ );
458
+
459
+ const settleNow = useCallback(() => animateTo(read(), false), [animateTo, read]);
460
+
461
+ const rotate = useCallback(
462
+ (direction: 1 | -1 = 1) => {
463
+ const current = read();
464
+ const target = nextQuarterTurn(current.rotation, direction);
465
+ // Turn about the mask, so what is in it stays in it.
466
+ animateTo(rotateAbout(current, target - current.rotation, 0, 0), true);
467
+ },
468
+ [animateTo, read]
469
+ );
470
+
471
+ const reset = useCallback(() => {
472
+ // Unwind to the nearest whole turn rather than spinning back through
473
+ // every quarter turn taken to get here.
474
+ const turns = Math.round(rotation.value / 360) * 360;
475
+ animateTo({ ...IDENTITY, rotation: turns }, true);
476
+ }, [animateTo, rotation]);
477
+
478
+ const zoomBy = useCallback(
479
+ (factor: number) => animateTo(zoomAbout(read(), factor, 0, 0), false),
480
+ [animateTo, read]
481
+ );
482
+
483
+ const settled = useCallback(
484
+ (): CropState | null => (frame ? settle(read(), bounds, frame) : null),
485
+ [frame, bounds, read]
486
+ );
487
+
488
+ const getCrop = useCallback((): SourceCrop | null => {
489
+ const state = settled();
490
+ if (!state || !frame || !sourceSize) return null;
491
+ return sourceCrop(state, frame, sourceSize, coversMask(state, shape, frame));
492
+ }, [settled, frame, sourceSize, shape]);
493
+
494
+ useImperativeHandle(
495
+ ref,
496
+ (): AvatarCropperHandle => ({
497
+ getCrop,
498
+ rotate,
499
+ reset,
500
+ async crop({ size = 1024, format, compress = 0.9 } = {}) {
501
+ const state = settled();
502
+ const rect = getCrop();
503
+ if (!state || !frame || !rect || !sourceSize) {
504
+ throw new Error('AvatarCropper.crop: the photo has not been measured and laid out yet.');
505
+ }
506
+ const transparent = fill === 'transparent';
507
+ const output = format ?? (transparent ? 'png' : 'jpeg');
508
+ const side = Math.min(size, rect.width);
509
+
510
+ if (!coversMask(state, shape, frame)) {
511
+ // Part of the outline is background, which the manipulator cannot
512
+ // paint on a phone. Draw the crop as the screen does, off to one
513
+ // side, and capture that instead.
514
+ const capture = loadCapture();
515
+ if (!capture) {
516
+ throw new Error(
517
+ 'AvatarCropper.crop: a photo smaller than the outline is written with ' +
518
+ 'react-native-view-shot. Install it with: npx expo install react-native-view-shot'
519
+ );
520
+ }
521
+ return new Promise<AvatarCropResult>((resolve, reject) => {
522
+ setStage({
523
+ state,
524
+ side,
525
+ format: output === 'jpeg' ? 'jpg' : 'png',
526
+ compress,
527
+ capture,
528
+ resolve: (result) => {
529
+ setStage(null);
530
+ resolve(result);
531
+ },
532
+ reject: (error) => {
533
+ setStage(null);
534
+ reject(error);
535
+ },
536
+ });
537
+ });
538
+ }
539
+
540
+ const manipulator = loadManipulator()?.ImageManipulator;
541
+ if (!manipulator) {
542
+ throw new Error(
543
+ 'AvatarCropper.crop needs expo-image-manipulator. Install it with: ' +
544
+ 'npx expo install expo-image-manipulator — or use getCrop() to crop elsewhere.'
545
+ );
546
+ }
547
+ // Redraw upright first. The turn and the cut both read raw pixels,
548
+ // and a camera photo often keeps its orientation in a flag instead.
549
+ const context = manipulator.manipulate(uri).resize({ width: sourceSize.width });
550
+ if (rect.rotation !== 0) context.rotate(rect.rotation);
551
+ context.crop({
552
+ originX: rect.originX,
553
+ originY: rect.originY,
554
+ width: rect.width,
555
+ height: rect.height,
556
+ });
557
+ if (side < rect.width) context.resize({ width: side, height: side });
558
+ const rendered = await context.renderAsync();
559
+ return rendered.saveAsync({ format: output, compress });
560
+ },
561
+ }),
562
+ [getCrop, settled, rotate, reset, sourceSize, uri, frame, shape, fill]
563
+ );
564
+
565
+ const value: CropperContextValue = {
566
+ shape,
567
+ bounds,
568
+ fill,
569
+ stage,
570
+ inset,
571
+ source,
572
+ sourceSize,
573
+ frame,
574
+ canvas,
575
+ setCanvas,
576
+ x,
577
+ y,
578
+ scale,
579
+ rotation,
580
+ settleNow,
581
+ rotate,
582
+ reset,
583
+ zoomBy,
584
+ summary,
585
+ };
586
+
587
+ return (
588
+ <CropperContext.Provider value={value}>
589
+ <View className={cn('flex-1', className)} {...props}>
590
+ {children ?? <AvatarCropperCanvas />}
591
+ </View>
592
+ </CropperContext.Provider>
593
+ );
594
+ }
595
+
596
+ const AvatarCropperForwarded = forwardRef<AvatarCropperHandle, AvatarCropperProps>(
597
+ AvatarCropperRoot
598
+ );
599
+ AvatarCropperForwarded.displayName = 'AvatarCropper';
600
+
601
+ interface ExportJob {
602
+ state: CropState;
603
+ /** Side of the image to write, in pixels. */
604
+ side: number;
605
+ format: 'png' | 'jpg';
606
+ compress: number;
607
+ capture: (view: unknown, options: unknown) => Promise<string>;
608
+ resolve: (result: AvatarCropResult) => void;
609
+ reject: (error: unknown) => void;
610
+ }
611
+
612
+ /**
613
+ * The crop drawn on its own, for capture: a square of the background with the
614
+ * photo placed in it exactly as the canvas places it under the outline.
615
+ *
616
+ * It sits directly under the outline, at the outline's size, beneath the
617
+ * canvas's own drawing of the same thing — so it is never seen, whatever
618
+ * surrounds the cropper. The capture reads the view's own drawing, not what is
619
+ * on screen above it, and scales it to the size asked for.
620
+ */
621
+ function ExportStage({
622
+ job,
623
+ frame,
624
+ uri,
625
+ fill,
626
+ left,
627
+ top,
628
+ }: {
629
+ job: ExportJob;
630
+ frame: CropFrame;
631
+ uri: string;
632
+ fill: string;
633
+ left: number;
634
+ top: number;
635
+ }) {
636
+ const ref = useRef<View>(null);
637
+ const started = useRef(false);
638
+ const side = frame.mask;
639
+ const { width, height } = frame.image;
640
+ const { state } = job;
641
+
642
+ const capture = () => {
643
+ if (started.current) return;
644
+ started.current = true;
645
+ job
646
+ .capture(ref.current, {
647
+ format: job.format,
648
+ quality: job.compress,
649
+ result: 'tmpfile',
650
+ width: job.side,
651
+ height: job.side,
652
+ })
653
+ .then((uri) => job.resolve({ uri, width: job.side, height: job.side }))
654
+ .catch(job.reject);
655
+ };
656
+
657
+ return (
658
+ <View
659
+ ref={ref}
660
+ collapsable={false}
661
+ pointerEvents="none"
662
+ importantForAccessibility="no-hide-descendants"
663
+ accessibilityElementsHidden
664
+ style={{
665
+ position: 'absolute',
666
+ left,
667
+ top,
668
+ width: side,
669
+ height: side,
670
+ overflow: 'hidden',
671
+ backgroundColor: fill,
672
+ }}
673
+ >
674
+ <View
675
+ style={{
676
+ position: 'absolute',
677
+ left: (side - width) / 2,
678
+ top: (side - height) / 2,
679
+ width,
680
+ height,
681
+ transform: [
682
+ { translateX: state.x },
683
+ { translateY: state.y },
684
+ { rotate: `${state.rotation}deg` },
685
+ { scale: state.scale },
686
+ ],
687
+ }}
688
+ >
689
+ <Image
690
+ source={{ uri }}
691
+ style={{ width, height }}
692
+ resizeMode="cover"
693
+ onLoad={() => requestAnimationFrame(capture)}
694
+ onError={() => job.reject(new Error('AvatarCropper.crop: the photo failed to load.'))}
695
+ />
696
+ </View>
697
+ </View>
698
+ );
699
+ }
700
+
701
+ // ---------------------------------------------------------------------------
702
+ // Canvas
703
+ // ---------------------------------------------------------------------------
704
+
705
+ export interface AvatarCropperCanvasProps extends Omit<ViewProps, 'children'> {
706
+ className?: string;
707
+ /** What a screen reader calls the canvas. Default "Photo crop". */
708
+ accessibilityLabel?: string;
709
+ }
710
+
711
+ /**
712
+ * The photo under its mask, and the surface every gesture lands on. It fills
713
+ * the space it is given, and the mask is drawn as large as the shorter side
714
+ * allows, less the root's `inset`.
715
+ */
716
+ function AvatarCropperCanvas({
717
+ className,
718
+ accessibilityLabel = 'Photo crop',
719
+ onLayout,
720
+ ...props
721
+ }: AvatarCropperCanvasProps) {
722
+ const {
723
+ shape,
724
+ bounds,
725
+ fill,
726
+ stage,
727
+ source,
728
+ frame,
729
+ canvas,
730
+ setCanvas,
731
+ x,
732
+ y,
733
+ scale,
734
+ rotation,
735
+ settleNow,
736
+ rotate,
737
+ zoomBy,
738
+ summary,
739
+ } = useCropper('AvatarCropper.Canvas');
740
+
741
+ const scrimToken = useCSSVariable('--color-background');
742
+ const ringToken = useCSSVariable('--color-foreground');
743
+ const scrim = typeof scrimToken === 'string' ? scrimToken : '#0a0a0a';
744
+ const ring = typeof ringToken === 'string' ? ringToken : '#fafafa';
745
+
746
+ // How many of the three gestures are under way. The photo settles once the
747
+ // last of them lets go, not each time one does.
748
+ const active = useSharedValue(0);
749
+ const W = canvas?.width ?? 0;
750
+ const H = canvas?.height ?? 0;
751
+ const image = frame?.image ?? { width: 0, height: 0 };
752
+ const mask = frame?.mask ?? 0;
753
+
754
+ const shown = useDerivedValue((): CropState => {
755
+ const raw = { x: x.value, y: y.value, scale: scale.value, rotation: rotation.value };
756
+ return frame ? present(raw, bounds, frame) : raw;
757
+ });
758
+
759
+ const imageStyle = useAnimatedStyle(() => ({
760
+ transform: [
761
+ { translateX: shown.value.x },
762
+ { translateY: shown.value.y },
763
+ { rotate: `${shown.value.rotation}deg` },
764
+ { scale: shown.value.scale },
765
+ ],
766
+ }));
767
+
768
+ const gesture = useMemo(() => {
769
+ const begin = () => {
770
+ 'worklet';
771
+ if (active.value === 0) {
772
+ cancelAnimation(x);
773
+ cancelAnimation(y);
774
+ cancelAnimation(scale);
775
+ cancelAnimation(rotation);
776
+ }
777
+ active.value += 1;
778
+ };
779
+ const end = () => {
780
+ 'worklet';
781
+ active.value = Math.max(0, active.value - 1);
782
+ if (active.value === 0) runOnJS(settleNow)();
783
+ };
784
+ /** Keep a raw value from running away while it is rubber-banded. */
785
+ const bound = (state: CropState) => {
786
+ 'worklet';
787
+ if (!frame) return state;
788
+ // A guard against running away, not a bound: `present` does the bounding.
789
+ const lowest = 0.05;
790
+ const next = {
791
+ ...state,
792
+ scale: Math.min(Math.max(state.scale, lowest), bounds.maxZoom * OVERSHOOT),
793
+ };
794
+ const limit = Math.max(image.width, image.height) * next.scale;
795
+ next.x = Math.min(Math.max(next.x, -limit), limit);
796
+ next.y = Math.min(Math.max(next.y, -limit), limit);
797
+ return next;
798
+ };
799
+ const write = (state: CropState) => {
800
+ 'worklet';
801
+ const next = bound(state);
802
+ x.value = next.x;
803
+ y.value = next.y;
804
+ scale.value = next.scale;
805
+ rotation.value = next.rotation;
806
+ };
807
+ const current = (): CropState => {
808
+ 'worklet';
809
+ return { x: x.value, y: y.value, scale: scale.value, rotation: rotation.value };
810
+ };
811
+
812
+ const pan = Gesture.Pan()
813
+ .averageTouches(true)
814
+ .onBegin(() => {
815
+ 'worklet';
816
+ begin();
817
+ })
818
+ .onChange((event) => {
819
+ 'worklet';
820
+ const state = current();
821
+ write({ ...state, x: state.x + event.changeX, y: state.y + event.changeY });
822
+ })
823
+ .onFinalize(() => {
824
+ 'worklet';
825
+ end();
826
+ });
827
+
828
+ const pinch = Gesture.Pinch()
829
+ .onBegin(() => {
830
+ 'worklet';
831
+ begin();
832
+ })
833
+ .onChange((event) => {
834
+ 'worklet';
835
+ write(zoomAbout(current(), event.scaleChange, event.focalX - W / 2, event.focalY - H / 2));
836
+ })
837
+ .onFinalize(() => {
838
+ 'worklet';
839
+ end();
840
+ });
841
+
842
+ const turn = Gesture.Rotation()
843
+ .onBegin(() => {
844
+ 'worklet';
845
+ begin();
846
+ })
847
+ .onChange((event) => {
848
+ 'worklet';
849
+ write(
850
+ rotateAbout(
851
+ current(),
852
+ (event.rotationChange * 180) / Math.PI,
853
+ event.anchorX - W / 2,
854
+ event.anchorY - H / 2
855
+ )
856
+ );
857
+ })
858
+ .onFinalize(() => {
859
+ 'worklet';
860
+ end();
861
+ });
862
+
863
+ return Gesture.Simultaneous(pan, pinch, turn);
864
+ }, [active, x, y, scale, rotation, settleNow, frame, image.width, image.height, bounds, W, H]);
865
+
866
+ const onAccessibilityAction = useCallback(
867
+ (event: AccessibilityActionEvent) => {
868
+ switch (event.nativeEvent.actionName) {
869
+ case 'increment':
870
+ zoomBy(ZOOM_STEP);
871
+ break;
872
+ case 'decrement':
873
+ zoomBy(1 / ZOOM_STEP);
874
+ break;
875
+ case 'rotate':
876
+ rotate(1);
877
+ break;
878
+ }
879
+ },
880
+ [zoomBy, rotate]
881
+ );
882
+
883
+ const handleLayout = useCallback(
884
+ (event: Parameters<NonNullable<ViewProps['onLayout']>>[0]) => {
885
+ const { width, height } = (event as LayoutChangeEvent).nativeEvent.layout;
886
+ setCanvas({ width, height });
887
+ onLayout?.(event);
888
+ },
889
+ [setCanvas, onLayout]
890
+ );
891
+
892
+ const outline = W > 0 && mask > 0 ? maskPath(shape, W / 2, H / 2, mask) : '';
893
+
894
+ return (
895
+ <GestureDetector gesture={gesture}>
896
+ <View
897
+ className={cn('flex-1 overflow-hidden bg-background', className)}
898
+ onLayout={handleLayout}
899
+ accessible
900
+ accessibilityRole="adjustable"
901
+ accessibilityLabel={accessibilityLabel}
902
+ accessibilityHint="Drag to move the photo, pinch to zoom, and twist to turn it."
903
+ accessibilityValue={{ text: summary }}
904
+ accessibilityActions={[
905
+ { name: 'increment', label: 'Zoom in' },
906
+ { name: 'decrement', label: 'Zoom out' },
907
+ { name: 'rotate', label: 'Rotate' },
908
+ ]}
909
+ onAccessibilityAction={onAccessibilityAction}
910
+ {...props}
911
+ >
912
+ {stage && frame && W > 0 ? (
913
+ <ExportStage
914
+ job={stage}
915
+ frame={frame}
916
+ uri={source.uri}
917
+ fill={fill}
918
+ left={(W - mask) / 2}
919
+ top={(H - mask) / 2}
920
+ />
921
+ ) : null}
922
+ {!bounds.cover && frame && W > 0 && fill !== 'transparent' ? (
923
+ <View
924
+ pointerEvents="none"
925
+ style={{
926
+ position: 'absolute',
927
+ left: (W - mask) / 2,
928
+ top: (H - mask) / 2,
929
+ width: mask,
930
+ height: mask,
931
+ backgroundColor: fill,
932
+ }}
933
+ />
934
+ ) : null}
935
+ {frame && W > 0 ? (
936
+ <Animated.View
937
+ pointerEvents="none"
938
+ style={[
939
+ {
940
+ position: 'absolute',
941
+ left: (W - image.width) / 2,
942
+ top: (H - image.height) / 2,
943
+ width: image.width,
944
+ height: image.height,
945
+ },
946
+ imageStyle,
947
+ ]}
948
+ >
949
+ <Image
950
+ source={{ uri: source.uri }}
951
+ style={{ width: image.width, height: image.height }}
952
+ resizeMode="cover"
953
+ accessibilityIgnoresInvertColors
954
+ />
955
+ </Animated.View>
956
+ ) : null}
957
+ {outline ? (
958
+ <Svg width={W} height={H} style={{ position: 'absolute', left: 0, top: 0 }} pointerEvents="none">
959
+ <Path
960
+ d={`M0 0H${W}V${H}H0Z${outline}`}
961
+ fill={scrim}
962
+ fillOpacity={0.78}
963
+ fillRule="evenodd"
964
+ />
965
+ <Path d={outline} fill="none" stroke={ring} strokeOpacity={0.9} strokeWidth={1.5} />
966
+ </Svg>
967
+ ) : null}
968
+ </View>
969
+ </GestureDetector>
970
+ );
971
+ }
972
+ AvatarCropperCanvas.displayName = 'AvatarCropper.Canvas';
973
+
974
+ // ---------------------------------------------------------------------------
975
+ // Controls
976
+ // ---------------------------------------------------------------------------
977
+
978
+ export interface AvatarCropperRotateProps extends Omit<ButtonProps, 'onPress'> {
979
+ /** Which way a press turns the photo. Default `'clockwise'`. */
980
+ direction?: 'clockwise' | 'counterclockwise';
981
+ }
982
+
983
+ /** A quarter turn per press, about the middle of the mask. */
984
+ function AvatarCropperRotate({
985
+ direction = 'clockwise',
986
+ variant = 'secondary',
987
+ size = 'icon',
988
+ children,
989
+ accessibilityLabel,
990
+ ...props
991
+ }: AvatarCropperRotateProps) {
992
+ const { rotate } = useCropper('AvatarCropper.Rotate');
993
+ const clockwise = direction === 'clockwise';
994
+ return (
995
+ <Button
996
+ variant={variant}
997
+ size={size}
998
+ accessibilityLabel={
999
+ accessibilityLabel ?? (clockwise ? 'Rotate clockwise' : 'Rotate counterclockwise')
1000
+ }
1001
+ onPress={() => rotate(clockwise ? 1 : -1)}
1002
+ {...props}
1003
+ >
1004
+ {children ?? (
1005
+ <View style={clockwise ? undefined : { transform: [{ scaleX: -1 }] }}>
1006
+ <RotateSquareIcon size={20} />
1007
+ </View>
1008
+ )}
1009
+ </Button>
1010
+ );
1011
+ }
1012
+ AvatarCropperRotate.displayName = 'AvatarCropper.Rotate';
1013
+
1014
+ export type AvatarCropperResetProps = Omit<ButtonProps, 'onPress'>;
1015
+
1016
+ /** Back to the photo centred, unzoomed and upright. Labelled "Reset" unless given children. */
1017
+ function AvatarCropperReset({
1018
+ variant = 'ghost',
1019
+ size = 'sm',
1020
+ children = 'Reset',
1021
+ ...props
1022
+ }: AvatarCropperResetProps) {
1023
+ const { reset } = useCropper('AvatarCropper.Reset');
1024
+ return (
1025
+ <Button variant={variant} size={size} onPress={reset} {...props}>
1026
+ {children}
1027
+ </Button>
1028
+ );
1029
+ }
1030
+ AvatarCropperReset.displayName = 'AvatarCropper.Reset';
1031
+
1032
+ export const AvatarCropper = Object.assign(AvatarCropperForwarded, {
1033
+ Canvas: AvatarCropperCanvas,
1034
+ Rotate: AvatarCropperRotate,
1035
+ Reset: AvatarCropperReset,
1036
+ });