panelui-native 0.108.0 → 0.110.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.
Files changed (95) hide show
  1. package/lib/module/components/avatar-cropper/avatar-cropper-math.js +320 -0
  2. package/lib/module/components/avatar-cropper/avatar-cropper-math.js.map +1 -0
  3. package/lib/module/components/avatar-cropper/index.js +656 -0
  4. package/lib/module/components/avatar-cropper/index.js.map +1 -0
  5. package/lib/module/components/badge/index.js +85 -4
  6. package/lib/module/components/badge/index.js.map +1 -1
  7. package/lib/module/components/button/index.js +12 -0
  8. package/lib/module/components/button/index.js.map +1 -1
  9. package/lib/module/components/button-group/index.js +3 -0
  10. package/lib/module/components/button-group/index.js.map +1 -1
  11. package/lib/module/components/checkbox/index.js +54 -4
  12. package/lib/module/components/checkbox/index.js.map +1 -1
  13. package/lib/module/components/chip/index.js +23 -1
  14. package/lib/module/components/chip/index.js.map +1 -1
  15. package/lib/module/components/input/index.js +14 -0
  16. package/lib/module/components/input/index.js.map +1 -1
  17. package/lib/module/components/map/index.js +157 -5
  18. package/lib/module/components/map/index.js.map +1 -1
  19. package/lib/module/components/map/map-insets.js +174 -0
  20. package/lib/module/components/map/map-insets.js.map +1 -0
  21. package/lib/module/components/radio-group/index.js +49 -3
  22. package/lib/module/components/radio-group/index.js.map +1 -1
  23. package/lib/module/components/select/index.js +54 -2
  24. package/lib/module/components/select/index.js.map +1 -1
  25. package/lib/module/components/switch/index.js +42 -3
  26. package/lib/module/components/switch/index.js.map +1 -1
  27. package/lib/module/components/tabs/index.js +147 -1
  28. package/lib/module/components/tabs/index.js.map +1 -1
  29. package/lib/module/components/textarea/index.js +18 -0
  30. package/lib/module/components/textarea/index.js.map +1 -1
  31. package/lib/module/components/toggle-button/index.js +34 -2
  32. package/lib/module/components/toggle-button/index.js.map +1 -1
  33. package/lib/module/icons/index.js +6 -0
  34. package/lib/module/icons/index.js.map +1 -1
  35. package/lib/module/index.js +1 -0
  36. package/lib/module/index.js.map +1 -1
  37. package/lib/module/providers/panel-ui-provider.js +22 -10
  38. package/lib/module/providers/panel-ui-provider.js.map +1 -1
  39. package/lib/typescript/src/components/avatar-cropper/avatar-cropper-math.d.ts +98 -0
  40. package/lib/typescript/src/components/avatar-cropper/avatar-cropper-math.d.ts.map +1 -0
  41. package/lib/typescript/src/components/avatar-cropper/index.d.ts +168 -0
  42. package/lib/typescript/src/components/avatar-cropper/index.d.ts.map +1 -0
  43. package/lib/typescript/src/components/badge/index.d.ts +68 -0
  44. package/lib/typescript/src/components/badge/index.d.ts.map +1 -1
  45. package/lib/typescript/src/components/button/index.d.ts +12 -0
  46. package/lib/typescript/src/components/button/index.d.ts.map +1 -1
  47. package/lib/typescript/src/components/button-group/index.d.ts +9 -0
  48. package/lib/typescript/src/components/button-group/index.d.ts.map +1 -1
  49. package/lib/typescript/src/components/checkbox/index.d.ts +89 -0
  50. package/lib/typescript/src/components/checkbox/index.d.ts.map +1 -1
  51. package/lib/typescript/src/components/chip/index.d.ts +24 -0
  52. package/lib/typescript/src/components/chip/index.d.ts.map +1 -1
  53. package/lib/typescript/src/components/input/index.d.ts +30 -0
  54. package/lib/typescript/src/components/input/index.d.ts.map +1 -1
  55. package/lib/typescript/src/components/map/index.d.ts +67 -1
  56. package/lib/typescript/src/components/map/index.d.ts.map +1 -1
  57. package/lib/typescript/src/components/map/map-insets.d.ts +80 -0
  58. package/lib/typescript/src/components/map/map-insets.d.ts.map +1 -0
  59. package/lib/typescript/src/components/radio-group/index.d.ts +188 -1
  60. package/lib/typescript/src/components/radio-group/index.d.ts.map +1 -1
  61. package/lib/typescript/src/components/select/index.d.ts +9 -1
  62. package/lib/typescript/src/components/select/index.d.ts.map +1 -1
  63. package/lib/typescript/src/components/switch/index.d.ts +38 -0
  64. package/lib/typescript/src/components/switch/index.d.ts.map +1 -1
  65. package/lib/typescript/src/components/tabs/index.d.ts +10 -1
  66. package/lib/typescript/src/components/tabs/index.d.ts.map +1 -1
  67. package/lib/typescript/src/components/textarea/index.d.ts +18 -0
  68. package/lib/typescript/src/components/textarea/index.d.ts.map +1 -1
  69. package/lib/typescript/src/components/toggle-button/index.d.ts +24 -0
  70. package/lib/typescript/src/components/toggle-button/index.d.ts.map +1 -1
  71. package/lib/typescript/src/icons/index.d.ts +2 -0
  72. package/lib/typescript/src/icons/index.d.ts.map +1 -1
  73. package/lib/typescript/src/index.d.ts +8 -7
  74. package/lib/typescript/src/index.d.ts.map +1 -1
  75. package/lib/typescript/src/providers/panel-ui-provider.d.ts.map +1 -1
  76. package/package.json +9 -1
  77. package/src/components/avatar-cropper/avatar-cropper-math.ts +311 -0
  78. package/src/components/avatar-cropper/index.tsx +808 -0
  79. package/src/components/badge/index.tsx +30 -4
  80. package/src/components/button/index.tsx +9 -2
  81. package/src/components/button-group/index.tsx +1 -0
  82. package/src/components/checkbox/index.tsx +47 -3
  83. package/src/components/chip/index.tsx +5 -1
  84. package/src/components/input/index.tsx +6 -0
  85. package/src/components/map/index.tsx +215 -5
  86. package/src/components/map/map-insets.ts +169 -0
  87. package/src/components/radio-group/index.tsx +56 -4
  88. package/src/components/select/index.tsx +50 -1
  89. package/src/components/switch/index.tsx +16 -4
  90. package/src/components/tabs/index.tsx +61 -0
  91. package/src/components/textarea/index.tsx +6 -0
  92. package/src/components/toggle-button/index.tsx +16 -1
  93. package/src/icons/index.tsx +3 -0
  94. package/src/index.ts +24 -3
  95. package/src/providers/panel-ui-provider.tsx +21 -11
@@ -0,0 +1,808 @@
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
+ useState,
55
+ type ReactNode,
56
+ type Ref,
57
+ } from 'react';
58
+ import {
59
+ Image,
60
+ View,
61
+ type AccessibilityActionEvent,
62
+ type LayoutChangeEvent,
63
+ type ViewProps,
64
+ } from 'react-native';
65
+ import { Gesture, GestureDetector } from 'react-native-gesture-handler';
66
+ import Animated, {
67
+ cancelAnimation,
68
+ runOnJS,
69
+ useAnimatedStyle,
70
+ useDerivedValue,
71
+ useSharedValue,
72
+ withSpring,
73
+ withTiming,
74
+ type SharedValue,
75
+ } from 'react-native-reanimated';
76
+ import Svg, { Path } from 'react-native-svg';
77
+ import { useCSSVariable } from 'uniwind';
78
+ import { RotateSquareIcon } from '../../icons';
79
+ import { cn } from '../../utils/cn';
80
+ import { Button, type ButtonProps } from '../button';
81
+ import {
82
+ IDENTITY,
83
+ baseSize,
84
+ maskPath,
85
+ nextQuarterTurn,
86
+ normalizeDegrees,
87
+ present,
88
+ rotateAbout,
89
+ settle,
90
+ sourceCrop,
91
+ zoomAbout,
92
+ type CropFrame,
93
+ type CropShape,
94
+ type CropState,
95
+ type Size,
96
+ type SourceCrop,
97
+ } from './avatar-cropper-math';
98
+
99
+ export type { CropShape as AvatarCropperShape, SourceCrop as AvatarCrop };
100
+
101
+ /** Where the photo settles after a gesture. Firm, so it lands without drifting. */
102
+ const SETTLE_SPRING = { damping: 34, stiffness: 320, mass: 1 } as const;
103
+
104
+ /** A quarter turn from the button. Long enough to read as a turn, not a jump. */
105
+ const TURN_DURATION = 260;
106
+
107
+ /** How far an accessibility zoom step goes. */
108
+ const ZOOM_STEP = 1.25;
109
+
110
+ /** How far a raw gesture may run past a bound before the rubber band stops it. */
111
+ const OVERSHOOT = 2;
112
+
113
+ // ---------------------------------------------------------------------------
114
+ // Optional dependencies
115
+ // ---------------------------------------------------------------------------
116
+
117
+ interface ManipulatorContext {
118
+ resize(size: { width?: number; height?: number }): ManipulatorContext;
119
+ rotate(degrees: number): ManipulatorContext;
120
+ crop(rect: { originX: number; originY: number; width: number; height: number }): ManipulatorContext;
121
+ renderAsync(): Promise<{
122
+ saveAsync(options: { format?: string; compress?: number }): Promise<AvatarCropResult>;
123
+ }>;
124
+ }
125
+
126
+ interface ManipulatorModule {
127
+ ImageManipulator?: { manipulate(uri: string): ManipulatorContext };
128
+ }
129
+
130
+ interface PickerAsset {
131
+ uri: string;
132
+ width: number;
133
+ height: number;
134
+ }
135
+
136
+ interface PickerModule {
137
+ requestCameraPermissionsAsync(): Promise<{ granted: boolean }>;
138
+ launchCameraAsync(options: unknown): Promise<{ canceled: boolean; assets?: PickerAsset[] | null }>;
139
+ launchImageLibraryAsync(
140
+ options: unknown
141
+ ): Promise<{ canceled: boolean; assets?: PickerAsset[] | null }>;
142
+ }
143
+
144
+ /**
145
+ * `expo-image-manipulator`, or null when it is not installed. Each `require`
146
+ * sits directly in its `try` block, which is what lets Metro bundle an app
147
+ * that does not have the package.
148
+ */
149
+ function loadManipulator(): ManipulatorModule | null {
150
+ try {
151
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
152
+ return require('expo-image-manipulator') as ManipulatorModule;
153
+ } catch {
154
+ return null;
155
+ }
156
+ }
157
+
158
+ /** `expo-image-picker`, or null when it is not installed. */
159
+ function loadPicker(): PickerModule | null {
160
+ try {
161
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
162
+ return require('expo-image-picker') as PickerModule;
163
+ } catch {
164
+ return null;
165
+ }
166
+ }
167
+
168
+ /** True when `crop()` can write an image, because `expo-image-manipulator` is installed. */
169
+ export const hasAvatarCropperExport = loadManipulator()?.ImageManipulator != null;
170
+
171
+ /** A photo to crop, as the picker returns it. */
172
+ export interface AvatarCropperSource {
173
+ /** A local file or `data:` URI. */
174
+ uri: string;
175
+ /** Width in pixels, upright. Measured from the image when left out. */
176
+ width?: number;
177
+ /** Height in pixels, upright. Measured from the image when left out. */
178
+ height?: number;
179
+ }
180
+
181
+ export interface PickAvatarImageOptions {
182
+ /** Where the photo comes from. Default `'library'`. */
183
+ from?: 'library' | 'camera';
184
+ /** JPEG quality of the picked photo, 0–1. Default 1, since the crop compresses it again. */
185
+ quality?: number;
186
+ }
187
+
188
+ /**
189
+ * Let the user choose a photo or take one, ready to pass to `AvatarCropper`.
190
+ *
191
+ * Resolves `null` when the user cancels. Taking a photo asks for camera
192
+ * permission first and throws when it is refused, so the app can explain why
193
+ * nothing happened. Choosing from the library needs no permission. The
194
+ * picker's own editing is left off, because the cropper is the editor.
195
+ *
196
+ * Needs the optional `expo-image-picker`, and throws if it is not installed.
197
+ * In a development build the camera also needs the permission strings from
198
+ * that package's config plugin.
199
+ */
200
+ export async function pickAvatarImage({
201
+ from = 'library',
202
+ quality = 1,
203
+ }: PickAvatarImageOptions = {}): Promise<Required<AvatarCropperSource> | null> {
204
+ const picker = loadPicker();
205
+ if (!picker) {
206
+ throw new Error(
207
+ 'pickAvatarImage needs expo-image-picker. Install it with: npx expo install expo-image-picker'
208
+ );
209
+ }
210
+ const options = { mediaTypes: ['images'], allowsEditing: false, quality, exif: false };
211
+ let result: Awaited<ReturnType<PickerModule['launchImageLibraryAsync']>>;
212
+ if (from === 'camera') {
213
+ const permission = await picker.requestCameraPermissionsAsync();
214
+ if (!permission.granted) throw new Error('pickAvatarImage: camera permission was refused.');
215
+ result = await picker.launchCameraAsync(options);
216
+ } else {
217
+ result = await picker.launchImageLibraryAsync(options);
218
+ }
219
+ const asset = result.canceled ? undefined : result.assets?.[0];
220
+ return asset ? { uri: asset.uri, width: asset.width, height: asset.height } : null;
221
+ }
222
+
223
+ // ---------------------------------------------------------------------------
224
+ // Root
225
+ // ---------------------------------------------------------------------------
226
+
227
+ export interface AvatarCropResult {
228
+ /** The cropped image, written to the app's cache directory. */
229
+ uri: string;
230
+ width: number;
231
+ height: number;
232
+ }
233
+
234
+ export interface AvatarCropOptions {
235
+ /**
236
+ * Side of the image to write, in pixels. Default 1024. A crop with fewer
237
+ * pixels than this is written at its own size rather than scaled up.
238
+ */
239
+ size?: number;
240
+ /** Default `'jpeg'`. Use `'png'` to keep transparency out of the question entirely. */
241
+ format?: 'jpeg' | 'png' | 'webp';
242
+ /** Quality, 0–1, for JPEG and WebP. Default 0.9. */
243
+ compress?: number;
244
+ }
245
+
246
+ export interface AvatarCropperHandle {
247
+ /**
248
+ * Write what the mask covers to a new square image. The image is square for
249
+ * every shape; draw it in a round `Avatar` to show it as a circle.
250
+ *
251
+ * Needs the optional `expo-image-manipulator`, and throws if it is not
252
+ * installed — use `getCrop()` then.
253
+ */
254
+ crop(options?: AvatarCropOptions): Promise<AvatarCropResult>;
255
+ /**
256
+ * The rectangle the mask covers, in the source's pixels, after turning the
257
+ * source by `rotation` degrees clockwise. Null until the photo has been
258
+ * measured and laid out.
259
+ */
260
+ getCrop(): SourceCrop | null;
261
+ /** Turn a quarter clockwise, or a quarter back with `-1`. */
262
+ rotate(direction?: 1 | -1): void;
263
+ /** Back to the photo centred, unzoomed and upright. */
264
+ reset(): void;
265
+ }
266
+
267
+ export interface AvatarCropperProps extends ViewProps {
268
+ /** The photo. Changing it starts the crop again from the centre. */
269
+ source: AvatarCropperSource;
270
+ /**
271
+ * The outline the photo is framed in. Default `'circle'`, which is how
272
+ * `Avatar` draws it. The image written out is square for every shape.
273
+ */
274
+ shape?: CropShape;
275
+ /** How far the photo can be zoomed past filling the mask. Default 5. */
276
+ maxZoom?: number;
277
+ /** Space between the mask and the canvas's shorter side, in points. Default 24. */
278
+ inset?: number;
279
+ className?: string;
280
+ /** `AvatarCropper.Canvas` and any controls. Left out, the canvas alone. */
281
+ children?: ReactNode;
282
+ }
283
+
284
+ interface CropperContextValue {
285
+ shape: CropShape;
286
+ maxZoom: number;
287
+ inset: number;
288
+ source: AvatarCropperSource;
289
+ /** The source's upright size, once known. */
290
+ sourceSize: Size | null;
291
+ frame: CropFrame | null;
292
+ setCanvas(size: Size): void;
293
+ canvas: Size | null;
294
+ x: SharedValue<number>;
295
+ y: SharedValue<number>;
296
+ scale: SharedValue<number>;
297
+ rotation: SharedValue<number>;
298
+ settleNow(): void;
299
+ rotate(direction?: 1 | -1): void;
300
+ reset(): void;
301
+ zoomBy(factor: number): void;
302
+ /** A spoken summary of the crop, refreshed when a gesture settles. */
303
+ summary: string;
304
+ }
305
+
306
+ const CropperContext = createContext<CropperContextValue | null>(null);
307
+
308
+ function useCropper(part: string): CropperContextValue {
309
+ const context = useContext(CropperContext);
310
+ if (!context) throw new Error(`${part} must be rendered inside <AvatarCropper>.`);
311
+ return context;
312
+ }
313
+
314
+ function describe(state: CropState): string {
315
+ const zoom = `${Math.round(state.scale * 100)}% zoom`;
316
+ const angle = Math.round(normalizeDegrees(state.rotation));
317
+ return angle === 0 ? zoom : `${zoom}, turned ${angle} degrees`;
318
+ }
319
+
320
+ function AvatarCropperRoot(
321
+ {
322
+ source,
323
+ shape = 'circle',
324
+ maxZoom = 5,
325
+ inset = 24,
326
+ className,
327
+ children,
328
+ ...props
329
+ }: AvatarCropperProps,
330
+ ref: Ref<AvatarCropperHandle>
331
+ ) {
332
+ const x = useSharedValue(0);
333
+ const y = useSharedValue(0);
334
+ const scale = useSharedValue(1);
335
+ const rotation = useSharedValue(0);
336
+ const [canvas, setCanvasState] = useState<Size | null>(null);
337
+ const [measured, setMeasured] = useState<Size | null>(null);
338
+ const [summary, setSummary] = useState(describe(IDENTITY));
339
+
340
+ const { uri, width, height } = source;
341
+ const sourceSize =
342
+ width && height && width > 0 && height > 0 ? { width, height } : measured;
343
+
344
+ // The picker reports the size; anything else is measured once per photo.
345
+ useEffect(() => {
346
+ setMeasured(null);
347
+ if (width && height) return;
348
+ let live = true;
349
+ Image.getSize(
350
+ uri,
351
+ (w, h) => {
352
+ if (live) setMeasured({ width: w, height: h });
353
+ },
354
+ () => {}
355
+ );
356
+ return () => {
357
+ live = false;
358
+ };
359
+ }, [uri, width, height]);
360
+
361
+ // A new photo starts again from the centre.
362
+ useEffect(() => {
363
+ x.value = 0;
364
+ y.value = 0;
365
+ scale.value = 1;
366
+ rotation.value = 0;
367
+ setSummary(describe(IDENTITY));
368
+ }, [uri, x, y, scale, rotation]);
369
+
370
+ const mask = canvas ? Math.max(0, Math.min(canvas.width, canvas.height) - inset * 2) : 0;
371
+ const frame = useMemo<CropFrame | null>(
372
+ () => (sourceSize && mask > 0 ? { mask, image: baseSize(sourceSize, mask) } : null),
373
+ [sourceSize?.width, sourceSize?.height, mask] // eslint-disable-line react-hooks/exhaustive-deps
374
+ );
375
+
376
+ const setCanvas = useCallback((size: Size) => {
377
+ setCanvasState((current) =>
378
+ current && current.width === size.width && current.height === size.height ? current : size
379
+ );
380
+ }, []);
381
+
382
+ const read = useCallback(
383
+ (): CropState => ({ x: x.value, y: y.value, scale: scale.value, rotation: rotation.value }),
384
+ [x, y, scale, rotation]
385
+ );
386
+
387
+ /** Animate to a state, settled against the bounds first. */
388
+ const animateTo = useCallback(
389
+ (target: CropState, timed: boolean) => {
390
+ if (!frame) return;
391
+ const next = settle(target, shape, frame, maxZoom);
392
+ const run = (value: number) =>
393
+ timed ? withTiming(value, { duration: TURN_DURATION }) : withSpring(value, SETTLE_SPRING);
394
+ x.value = run(next.x);
395
+ y.value = run(next.y);
396
+ scale.value = run(next.scale);
397
+ rotation.value = run(next.rotation);
398
+ setSummary(describe(next));
399
+ },
400
+ [frame, shape, maxZoom, x, y, scale, rotation]
401
+ );
402
+
403
+ const settleNow = useCallback(() => animateTo(read(), false), [animateTo, read]);
404
+
405
+ const rotate = useCallback(
406
+ (direction: 1 | -1 = 1) => {
407
+ const current = read();
408
+ const target = nextQuarterTurn(current.rotation, direction);
409
+ // Turn about the mask, so what is in it stays in it.
410
+ animateTo(rotateAbout(current, target - current.rotation, 0, 0), true);
411
+ },
412
+ [animateTo, read]
413
+ );
414
+
415
+ const reset = useCallback(() => {
416
+ // Unwind to the nearest whole turn rather than spinning back through
417
+ // every quarter turn taken to get here.
418
+ const turns = Math.round(rotation.value / 360) * 360;
419
+ animateTo({ ...IDENTITY, rotation: turns }, true);
420
+ }, [animateTo, rotation]);
421
+
422
+ const zoomBy = useCallback(
423
+ (factor: number) => animateTo(zoomAbout(read(), factor, 0, 0), false),
424
+ [animateTo, read]
425
+ );
426
+
427
+ const getCrop = useCallback((): SourceCrop | null => {
428
+ if (!frame || !sourceSize) return null;
429
+ return sourceCrop(settle(read(), shape, frame, maxZoom), frame, sourceSize);
430
+ }, [frame, sourceSize, read, shape, maxZoom]);
431
+
432
+ useImperativeHandle(
433
+ ref,
434
+ (): AvatarCropperHandle => ({
435
+ getCrop,
436
+ rotate,
437
+ reset,
438
+ async crop({ size = 1024, format = 'jpeg', compress = 0.9 } = {}) {
439
+ const manipulator = loadManipulator()?.ImageManipulator;
440
+ if (!manipulator) {
441
+ throw new Error(
442
+ 'AvatarCropper.crop needs expo-image-manipulator. Install it with: ' +
443
+ 'npx expo install expo-image-manipulator — or use getCrop() to crop elsewhere.'
444
+ );
445
+ }
446
+ const rect = getCrop();
447
+ if (!rect || !sourceSize) {
448
+ throw new Error('AvatarCropper.crop: the photo has not been measured and laid out yet.');
449
+ }
450
+ // Redraw upright first. The turn and the cut both read raw pixels,
451
+ // and a camera photo often keeps its orientation in a flag instead.
452
+ const context = manipulator.manipulate(uri).resize({ width: sourceSize.width });
453
+ if (rect.rotation !== 0) context.rotate(rect.rotation);
454
+ context.crop({
455
+ originX: rect.originX,
456
+ originY: rect.originY,
457
+ width: rect.width,
458
+ height: rect.height,
459
+ });
460
+ if (size < rect.width) context.resize({ width: size, height: size });
461
+ const rendered = await context.renderAsync();
462
+ return rendered.saveAsync({ format, compress });
463
+ },
464
+ }),
465
+ [getCrop, rotate, reset, sourceSize, uri]
466
+ );
467
+
468
+ const value: CropperContextValue = {
469
+ shape,
470
+ maxZoom,
471
+ inset,
472
+ source,
473
+ sourceSize,
474
+ frame,
475
+ canvas,
476
+ setCanvas,
477
+ x,
478
+ y,
479
+ scale,
480
+ rotation,
481
+ settleNow,
482
+ rotate,
483
+ reset,
484
+ zoomBy,
485
+ summary,
486
+ };
487
+
488
+ return (
489
+ <CropperContext.Provider value={value}>
490
+ <View className={cn('flex-1', className)} {...props}>
491
+ {children ?? <AvatarCropperCanvas />}
492
+ </View>
493
+ </CropperContext.Provider>
494
+ );
495
+ }
496
+
497
+ const AvatarCropperForwarded = forwardRef<AvatarCropperHandle, AvatarCropperProps>(
498
+ AvatarCropperRoot
499
+ );
500
+ AvatarCropperForwarded.displayName = 'AvatarCropper';
501
+
502
+ // ---------------------------------------------------------------------------
503
+ // Canvas
504
+ // ---------------------------------------------------------------------------
505
+
506
+ export interface AvatarCropperCanvasProps extends Omit<ViewProps, 'children'> {
507
+ className?: string;
508
+ /** What a screen reader calls the canvas. Default "Photo crop". */
509
+ accessibilityLabel?: string;
510
+ }
511
+
512
+ /**
513
+ * The photo under its mask, and the surface every gesture lands on. It fills
514
+ * the space it is given, and the mask is drawn as large as the shorter side
515
+ * allows, less the root's `inset`.
516
+ */
517
+ function AvatarCropperCanvas({
518
+ className,
519
+ accessibilityLabel = 'Photo crop',
520
+ onLayout,
521
+ ...props
522
+ }: AvatarCropperCanvasProps) {
523
+ const {
524
+ shape,
525
+ maxZoom,
526
+ source,
527
+ frame,
528
+ canvas,
529
+ setCanvas,
530
+ x,
531
+ y,
532
+ scale,
533
+ rotation,
534
+ settleNow,
535
+ rotate,
536
+ zoomBy,
537
+ summary,
538
+ } = useCropper('AvatarCropper.Canvas');
539
+
540
+ const scrimToken = useCSSVariable('--color-background');
541
+ const ringToken = useCSSVariable('--color-foreground');
542
+ const scrim = typeof scrimToken === 'string' ? scrimToken : '#0a0a0a';
543
+ const ring = typeof ringToken === 'string' ? ringToken : '#fafafa';
544
+
545
+ // How many of the three gestures are under way. The photo settles once the
546
+ // last of them lets go, not each time one does.
547
+ const active = useSharedValue(0);
548
+ const W = canvas?.width ?? 0;
549
+ const H = canvas?.height ?? 0;
550
+ const image = frame?.image ?? { width: 0, height: 0 };
551
+ const mask = frame?.mask ?? 0;
552
+
553
+ const shown = useDerivedValue((): CropState => {
554
+ const raw = { x: x.value, y: y.value, scale: scale.value, rotation: rotation.value };
555
+ return frame ? present(raw, shape, frame, maxZoom) : raw;
556
+ });
557
+
558
+ const imageStyle = useAnimatedStyle(() => ({
559
+ transform: [
560
+ { translateX: shown.value.x },
561
+ { translateY: shown.value.y },
562
+ { rotate: `${shown.value.rotation}deg` },
563
+ { scale: shown.value.scale },
564
+ ],
565
+ }));
566
+
567
+ const gesture = useMemo(() => {
568
+ const begin = () => {
569
+ 'worklet';
570
+ if (active.value === 0) {
571
+ cancelAnimation(x);
572
+ cancelAnimation(y);
573
+ cancelAnimation(scale);
574
+ cancelAnimation(rotation);
575
+ }
576
+ active.value += 1;
577
+ };
578
+ const end = () => {
579
+ 'worklet';
580
+ active.value = Math.max(0, active.value - 1);
581
+ if (active.value === 0) runOnJS(settleNow)();
582
+ };
583
+ /** Keep a raw value from running away while it is rubber-banded. */
584
+ const bound = (state: CropState) => {
585
+ 'worklet';
586
+ if (!frame) return state;
587
+ const lowest = 1 / OVERSHOOT / 2;
588
+ const next = { ...state, scale: Math.min(Math.max(state.scale, lowest), maxZoom * OVERSHOOT) };
589
+ const limit = Math.max(image.width, image.height) * next.scale;
590
+ next.x = Math.min(Math.max(next.x, -limit), limit);
591
+ next.y = Math.min(Math.max(next.y, -limit), limit);
592
+ return next;
593
+ };
594
+ const write = (state: CropState) => {
595
+ 'worklet';
596
+ const next = bound(state);
597
+ x.value = next.x;
598
+ y.value = next.y;
599
+ scale.value = next.scale;
600
+ rotation.value = next.rotation;
601
+ };
602
+ const current = (): CropState => {
603
+ 'worklet';
604
+ return { x: x.value, y: y.value, scale: scale.value, rotation: rotation.value };
605
+ };
606
+
607
+ const pan = Gesture.Pan()
608
+ .averageTouches(true)
609
+ .onBegin(() => {
610
+ 'worklet';
611
+ begin();
612
+ })
613
+ .onChange((event) => {
614
+ 'worklet';
615
+ const state = current();
616
+ write({ ...state, x: state.x + event.changeX, y: state.y + event.changeY });
617
+ })
618
+ .onFinalize(() => {
619
+ 'worklet';
620
+ end();
621
+ });
622
+
623
+ const pinch = Gesture.Pinch()
624
+ .onBegin(() => {
625
+ 'worklet';
626
+ begin();
627
+ })
628
+ .onChange((event) => {
629
+ 'worklet';
630
+ write(zoomAbout(current(), event.scaleChange, event.focalX - W / 2, event.focalY - H / 2));
631
+ })
632
+ .onFinalize(() => {
633
+ 'worklet';
634
+ end();
635
+ });
636
+
637
+ const turn = Gesture.Rotation()
638
+ .onBegin(() => {
639
+ 'worklet';
640
+ begin();
641
+ })
642
+ .onChange((event) => {
643
+ 'worklet';
644
+ write(
645
+ rotateAbout(
646
+ current(),
647
+ (event.rotationChange * 180) / Math.PI,
648
+ event.anchorX - W / 2,
649
+ event.anchorY - H / 2
650
+ )
651
+ );
652
+ })
653
+ .onFinalize(() => {
654
+ 'worklet';
655
+ end();
656
+ });
657
+
658
+ return Gesture.Simultaneous(pan, pinch, turn);
659
+ }, [active, x, y, scale, rotation, settleNow, frame, image.width, image.height, maxZoom, W, H]);
660
+
661
+ const onAccessibilityAction = useCallback(
662
+ (event: AccessibilityActionEvent) => {
663
+ switch (event.nativeEvent.actionName) {
664
+ case 'increment':
665
+ zoomBy(ZOOM_STEP);
666
+ break;
667
+ case 'decrement':
668
+ zoomBy(1 / ZOOM_STEP);
669
+ break;
670
+ case 'rotate':
671
+ rotate(1);
672
+ break;
673
+ }
674
+ },
675
+ [zoomBy, rotate]
676
+ );
677
+
678
+ const handleLayout = useCallback(
679
+ (event: Parameters<NonNullable<ViewProps['onLayout']>>[0]) => {
680
+ const { width, height } = (event as LayoutChangeEvent).nativeEvent.layout;
681
+ setCanvas({ width, height });
682
+ onLayout?.(event);
683
+ },
684
+ [setCanvas, onLayout]
685
+ );
686
+
687
+ const outline = W > 0 && mask > 0 ? maskPath(shape, W / 2, H / 2, mask) : '';
688
+
689
+ return (
690
+ <GestureDetector gesture={gesture}>
691
+ <View
692
+ className={cn('flex-1 overflow-hidden bg-background', className)}
693
+ onLayout={handleLayout}
694
+ accessible
695
+ accessibilityRole="adjustable"
696
+ accessibilityLabel={accessibilityLabel}
697
+ accessibilityHint="Drag to move the photo, pinch to zoom, and twist to turn it."
698
+ accessibilityValue={{ text: summary }}
699
+ accessibilityActions={[
700
+ { name: 'increment', label: 'Zoom in' },
701
+ { name: 'decrement', label: 'Zoom out' },
702
+ { name: 'rotate', label: 'Rotate' },
703
+ ]}
704
+ onAccessibilityAction={onAccessibilityAction}
705
+ {...props}
706
+ >
707
+ {frame && W > 0 ? (
708
+ <Animated.View
709
+ pointerEvents="none"
710
+ style={[
711
+ {
712
+ position: 'absolute',
713
+ left: (W - image.width) / 2,
714
+ top: (H - image.height) / 2,
715
+ width: image.width,
716
+ height: image.height,
717
+ },
718
+ imageStyle,
719
+ ]}
720
+ >
721
+ <Image
722
+ source={{ uri: source.uri }}
723
+ style={{ width: image.width, height: image.height }}
724
+ resizeMode="cover"
725
+ accessibilityIgnoresInvertColors
726
+ />
727
+ </Animated.View>
728
+ ) : null}
729
+ {outline ? (
730
+ <Svg width={W} height={H} style={{ position: 'absolute', left: 0, top: 0 }} pointerEvents="none">
731
+ <Path
732
+ d={`M0 0H${W}V${H}H0Z${outline}`}
733
+ fill={scrim}
734
+ fillOpacity={0.78}
735
+ fillRule="evenodd"
736
+ />
737
+ <Path d={outline} fill="none" stroke={ring} strokeOpacity={0.9} strokeWidth={1.5} />
738
+ </Svg>
739
+ ) : null}
740
+ </View>
741
+ </GestureDetector>
742
+ );
743
+ }
744
+ AvatarCropperCanvas.displayName = 'AvatarCropper.Canvas';
745
+
746
+ // ---------------------------------------------------------------------------
747
+ // Controls
748
+ // ---------------------------------------------------------------------------
749
+
750
+ export interface AvatarCropperRotateProps extends Omit<ButtonProps, 'onPress'> {
751
+ /** Which way a press turns the photo. Default `'clockwise'`. */
752
+ direction?: 'clockwise' | 'counterclockwise';
753
+ }
754
+
755
+ /** A quarter turn per press, about the middle of the mask. */
756
+ function AvatarCropperRotate({
757
+ direction = 'clockwise',
758
+ variant = 'secondary',
759
+ size = 'icon',
760
+ children,
761
+ accessibilityLabel,
762
+ ...props
763
+ }: AvatarCropperRotateProps) {
764
+ const { rotate } = useCropper('AvatarCropper.Rotate');
765
+ const clockwise = direction === 'clockwise';
766
+ return (
767
+ <Button
768
+ variant={variant}
769
+ size={size}
770
+ accessibilityLabel={
771
+ accessibilityLabel ?? (clockwise ? 'Rotate clockwise' : 'Rotate counterclockwise')
772
+ }
773
+ onPress={() => rotate(clockwise ? 1 : -1)}
774
+ {...props}
775
+ >
776
+ {children ?? (
777
+ <View style={clockwise ? undefined : { transform: [{ scaleX: -1 }] }}>
778
+ <RotateSquareIcon size={20} />
779
+ </View>
780
+ )}
781
+ </Button>
782
+ );
783
+ }
784
+ AvatarCropperRotate.displayName = 'AvatarCropper.Rotate';
785
+
786
+ export type AvatarCropperResetProps = Omit<ButtonProps, 'onPress'>;
787
+
788
+ /** Back to the photo centred, unzoomed and upright. Labelled "Reset" unless given children. */
789
+ function AvatarCropperReset({
790
+ variant = 'ghost',
791
+ size = 'sm',
792
+ children = 'Reset',
793
+ ...props
794
+ }: AvatarCropperResetProps) {
795
+ const { reset } = useCropper('AvatarCropper.Reset');
796
+ return (
797
+ <Button variant={variant} size={size} onPress={reset} {...props}>
798
+ {children}
799
+ </Button>
800
+ );
801
+ }
802
+ AvatarCropperReset.displayName = 'AvatarCropper.Reset';
803
+
804
+ export const AvatarCropper = Object.assign(AvatarCropperForwarded, {
805
+ Canvas: AvatarCropperCanvas,
806
+ Rotate: AvatarCropperRotate,
807
+ Reset: AvatarCropperReset,
808
+ });