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

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 +5 -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,285 @@
1
+ // Crop math for the web cropper. Pure functions, no DOM.
2
+ //
3
+ // Coordinates are CSS pixels relative to the center of the crop area. The
4
+ // crop box is fixed and centered; the image moves under it. `offsetX/Y` is the
5
+ // image center, `zoom` multiplies the scale at which the image just covers the
6
+ // crop box, and `rotation` counts quarter turns counterclockwise, like the
7
+ // native rotate button.
8
+
9
+ export interface Size {
10
+ width: number;
11
+ height: number;
12
+ }
13
+
14
+ export interface Point {
15
+ x: number;
16
+ y: number;
17
+ }
18
+
19
+ export type Rotation = 0 | 90 | 180 | 270;
20
+
21
+ export interface CropState {
22
+ rotation: Rotation;
23
+ zoom: number;
24
+ offsetX: number;
25
+ offsetY: number;
26
+ }
27
+
28
+ export interface Rect {
29
+ x: number;
30
+ y: number;
31
+ width: number;
32
+ height: number;
33
+ }
34
+
35
+ export const MIN_ZOOM = 1;
36
+ export const MAX_ZOOM = 8;
37
+ // Matches the native crop view padding.
38
+ export const CROP_BOX_PADDING = 20;
39
+ // Processed images are capped like native decoding.
40
+ export const MAX_OUTPUT_LONG_SIDE = 4096;
41
+
42
+ export const INITIAL_STATE: CropState = {
43
+ rotation: 0,
44
+ zoom: MIN_ZOOM,
45
+ offsetX: 0,
46
+ offsetY: 0,
47
+ };
48
+
49
+ export function clamp(value: number, min: number, max: number): number {
50
+ return Math.min(Math.max(value, min), max);
51
+ }
52
+
53
+ export function rotatedSize(image: Size, rotation: Rotation): Size {
54
+ return rotation % 180 === 0
55
+ ? image
56
+ : { width: image.height, height: image.width };
57
+ }
58
+
59
+ export interface CropAspectOptions {
60
+ image: Size;
61
+ rotation: Rotation;
62
+ // Width / height of the requested result, if any.
63
+ targetAspectRatio?: number;
64
+ circular?: boolean;
65
+ }
66
+
67
+ // The crop box ratio, as on iOS and Android: 1:1 in circular mode whatever
68
+ // the image or target, the target ratio when there is one, and otherwise the
69
+ // image's own ratio, swapped on every quarter turn.
70
+ export function cropAspectRatio({
71
+ image,
72
+ rotation,
73
+ targetAspectRatio,
74
+ circular,
75
+ }: CropAspectOptions): number {
76
+ if (circular) {
77
+ return 1;
78
+ }
79
+ if (targetAspectRatio !== undefined && targetAspectRatio > 0) {
80
+ return targetAspectRatio;
81
+ }
82
+ const size = rotatedSize(image, rotation);
83
+ return size.width / size.height;
84
+ }
85
+
86
+ // The largest box of `aspectRatio` (width / height) inside `area`, less the
87
+ // crop box padding on every side.
88
+ export function fitCropBox(area: Size, aspectRatio: number): Size {
89
+ const width = Math.max(area.width - CROP_BOX_PADDING * 2, 0);
90
+ const height = Math.max(area.height - CROP_BOX_PADDING * 2, 0);
91
+ if (width === 0 || height === 0 || !(aspectRatio > 0)) {
92
+ return { width: 0, height: 0 };
93
+ }
94
+ return width / height > aspectRatio
95
+ ? { width: height * aspectRatio, height }
96
+ : { width, height: width / aspectRatio };
97
+ }
98
+
99
+ // Screen pixels per image pixel at zoom 1: the image just covers the box.
100
+ export function coverScale(image: Size, box: Size, rotation: Rotation): number {
101
+ const size = rotatedSize(image, rotation);
102
+ if (size.width === 0 || size.height === 0) {
103
+ return 1;
104
+ }
105
+ return Math.max(box.width / size.width, box.height / size.height);
106
+ }
107
+
108
+ export function scaleOf(state: CropState, image: Size, box: Size): number {
109
+ return coverScale(image, box, state.rotation) * state.zoom;
110
+ }
111
+
112
+ // Keeps the zoom in range and the crop box inside the image.
113
+ export function constrain(state: CropState, image: Size, box: Size): CropState {
114
+ const zoom = clamp(state.zoom, MIN_ZOOM, MAX_ZOOM);
115
+ const scale = coverScale(image, box, state.rotation) * zoom;
116
+ const size = rotatedSize(image, state.rotation);
117
+ const maxX = Math.max((size.width * scale - box.width) / 2, 0);
118
+ const maxY = Math.max((size.height * scale - box.height) / 2, 0);
119
+ return {
120
+ rotation: state.rotation,
121
+ zoom,
122
+ offsetX: clamp(state.offsetX, -maxX, maxX),
123
+ offsetY: clamp(state.offsetY, -maxY, maxY),
124
+ };
125
+ }
126
+
127
+ export function pan(
128
+ state: CropState,
129
+ dx: number,
130
+ dy: number,
131
+ image: Size,
132
+ box: Size
133
+ ): CropState {
134
+ return constrain(
135
+ { ...state, offsetX: state.offsetX + dx, offsetY: state.offsetY + dy },
136
+ image,
137
+ box
138
+ );
139
+ }
140
+
141
+ // Zooms so the image point under `anchor` stays under it.
142
+ export function zoomAt(
143
+ state: CropState,
144
+ zoom: number,
145
+ anchor: Point,
146
+ image: Size,
147
+ box: Size
148
+ ): CropState {
149
+ const nextZoom = clamp(zoom, MIN_ZOOM, MAX_ZOOM);
150
+ const ratio = nextZoom / state.zoom;
151
+ return constrain(
152
+ {
153
+ rotation: state.rotation,
154
+ zoom: nextZoom,
155
+ offsetX: anchor.x - (anchor.x - state.offsetX) * ratio,
156
+ offsetY: anchor.y - (anchor.y - state.offsetY) * ratio,
157
+ },
158
+ image,
159
+ box
160
+ );
161
+ }
162
+
163
+ // Turns the image 90° counterclockwise around the crop box center. `box` is
164
+ // the crop box after the turn, which differs only when the aspect ratio is
165
+ // not locked.
166
+ export function rotateCounterclockwise(
167
+ state: CropState,
168
+ image: Size,
169
+ box: Size
170
+ ): CropState {
171
+ // A counterclockwise quarter turn on a y-down screen maps (x, y) to (y, -x).
172
+ return constrain(
173
+ {
174
+ rotation: ((state.rotation + 90) % 360) as Rotation,
175
+ zoom: state.zoom,
176
+ offsetX: state.offsetY,
177
+ offsetY: -state.offsetX,
178
+ },
179
+ image,
180
+ box
181
+ );
182
+ }
183
+
184
+ // Keeps the same part of the image in the crop box when the box is resized.
185
+ export function rescale(
186
+ state: CropState,
187
+ previousBox: Size,
188
+ box: Size,
189
+ image: Size
190
+ ): CropState {
191
+ if (previousBox.width === 0) {
192
+ return constrain(state, image, box);
193
+ }
194
+ const ratio = box.width / previousBox.width;
195
+ return constrain(
196
+ {
197
+ ...state,
198
+ offsetX: state.offsetX * ratio,
199
+ offsetY: state.offsetY * ratio,
200
+ },
201
+ image,
202
+ box
203
+ );
204
+ }
205
+
206
+ // The crop box in the rotated image's pixels, like the native `cropRect`.
207
+ export function cropRectOf(state: CropState, image: Size, box: Size): Rect {
208
+ const scale = scaleOf(state, image, box);
209
+ const size = rotatedSize(image, state.rotation);
210
+ const width = Math.max(Math.round(box.width / scale), 1);
211
+ const height = Math.max(Math.round(box.height / scale), 1);
212
+ return {
213
+ x: clamp(
214
+ Math.round(size.width / 2 + (-box.width / 2 - state.offsetX) / scale),
215
+ 0,
216
+ size.width - width
217
+ ),
218
+ y: clamp(
219
+ Math.round(size.height / 2 + (-box.height / 2 - state.offsetY) / scale),
220
+ 0,
221
+ size.height - height
222
+ ),
223
+ width,
224
+ height,
225
+ };
226
+ }
227
+
228
+ export interface OutputLimits {
229
+ targetSize?: Size;
230
+ maxWidth?: number;
231
+ maxHeight?: number;
232
+ }
233
+
234
+ // Native semantics: a target size is produced exactly, smaller crops are
235
+ // scaled up; without one the crop keeps its own pixels, capped at
236
+ // MAX_OUTPUT_LONG_SIDE. compressImageMaxWidth/Height then only shrink.
237
+ export function outputSizeOf(crop: Size, limits: OutputLimits): Size {
238
+ let width: number;
239
+ let height: number;
240
+ if (limits.targetSize) {
241
+ width = Math.round(limits.targetSize.width);
242
+ height = Math.round(limits.targetSize.height);
243
+ } else {
244
+ const fit = Math.min(
245
+ 1,
246
+ MAX_OUTPUT_LONG_SIDE / Math.max(crop.width, crop.height, 1)
247
+ );
248
+ width = Math.round(crop.width * fit);
249
+ height = Math.round(crop.height * fit);
250
+ }
251
+ return shrinkToFit(
252
+ { width: Math.max(width, 1), height: Math.max(height, 1) },
253
+ limits.maxWidth,
254
+ limits.maxHeight
255
+ );
256
+ }
257
+
258
+ export function shrinkToFit(
259
+ size: Size,
260
+ maxWidth?: number,
261
+ maxHeight?: number
262
+ ): Size {
263
+ const scale = Math.min(
264
+ maxWidth !== undefined && maxWidth > 0 ? maxWidth / size.width : 1,
265
+ maxHeight !== undefined && maxHeight > 0 ? maxHeight / size.height : 1,
266
+ 1
267
+ );
268
+ if (scale >= 1) {
269
+ return size;
270
+ }
271
+ return {
272
+ width: Math.max(Math.floor(size.width * scale), 1),
273
+ height: Math.max(Math.floor(size.height * scale), 1),
274
+ };
275
+ }
276
+
277
+ export function isSameState(a: CropState, b: CropState): boolean {
278
+ const epsilon = 0.5;
279
+ return (
280
+ a.rotation === b.rotation &&
281
+ Math.abs(a.zoom - b.zoom) < 0.001 &&
282
+ Math.abs(a.offsetX - b.offsetX) < epsilon &&
283
+ Math.abs(a.offsetY - b.offsetY) < epsilon
284
+ );
285
+ }
@@ -0,0 +1,63 @@
1
+ // Identifies an image format from its leading bytes, so a preserved original
2
+ // reports the MIME type of the data it returns rather than what the browser
3
+ // guessed from the file name (or nothing, when `File.type` is empty).
4
+
5
+ // Enough for every signature below; ISO BMFF brands sit at bytes 8...11.
6
+ export const IMAGE_HEADER_LENGTH = 32;
7
+
8
+ function startsWith(bytes: Uint8Array, signature: number[], offset = 0) {
9
+ if (bytes.length < offset + signature.length) {
10
+ return false;
11
+ }
12
+ return signature.every((byte, index) => bytes[offset + index] === byte);
13
+ }
14
+
15
+ function ascii(bytes: Uint8Array, start: number, end: number): string {
16
+ return String.fromCharCode(...bytes.subarray(start, end));
17
+ }
18
+
19
+ // HEIF-family brands, from the ISO BMFF `ftyp` box.
20
+ const HEIC_BRANDS = new Set(['heic', 'heix', 'heim', 'heis', 'hevc', 'hevx']);
21
+ const HEIF_BRANDS = new Set(['mif1', 'msf1', 'hevm', 'hevs']);
22
+ const AVIF_BRANDS = new Set(['avif', 'avis']);
23
+
24
+ export function detectImageMime(bytes: Uint8Array): string | undefined {
25
+ if (startsWith(bytes, [0xff, 0xd8, 0xff])) {
26
+ return 'image/jpeg';
27
+ }
28
+ if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
29
+ return 'image/png';
30
+ }
31
+ if (ascii(bytes, 0, 6) === 'GIF87a' || ascii(bytes, 0, 6) === 'GIF89a') {
32
+ return 'image/gif';
33
+ }
34
+ if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 12) === 'WEBP') {
35
+ return 'image/webp';
36
+ }
37
+ if (ascii(bytes, 4, 8) === 'ftyp') {
38
+ const brand = ascii(bytes, 8, 12);
39
+ if (HEIC_BRANDS.has(brand)) {
40
+ return 'image/heic';
41
+ }
42
+ if (HEIF_BRANDS.has(brand)) {
43
+ return 'image/heif';
44
+ }
45
+ if (AVIF_BRANDS.has(brand)) {
46
+ return 'image/avif';
47
+ }
48
+ return undefined;
49
+ }
50
+ if (ascii(bytes, 0, 2) === 'BM') {
51
+ return 'image/bmp';
52
+ }
53
+ if (
54
+ startsWith(bytes, [0x49, 0x49, 0x2a, 0x00]) ||
55
+ startsWith(bytes, [0x4d, 0x4d, 0x00, 0x2a])
56
+ ) {
57
+ return 'image/tiff';
58
+ }
59
+ if (startsWith(bytes, [0x00, 0x00, 0x01, 0x00])) {
60
+ return 'image/x-icon';
61
+ }
62
+ return undefined;
63
+ }
@@ -0,0 +1,178 @@
1
+ /// <reference lib="dom" />
2
+ import { ImageCropPickerError } from '../shared';
3
+ import { scaleOf } from './geometry';
4
+ import { IMAGE_HEADER_LENGTH } from './imageFormat';
5
+
6
+ import type { CropState, Size } from './geometry';
7
+
8
+ export const RESULT_MIME = 'image/jpeg';
9
+ // iOS default; react-native-image-crop-picker used it on the web too.
10
+ export const DEFAULT_QUALITY = 0.8;
11
+ // Same limit as native original selection.
12
+ export const MAX_INPUT_BYTES = 64 * 1024 * 1024;
13
+
14
+ // Result paths are object URLs, so clean/cleanSingle can release them the way
15
+ // native deletes its temporary files.
16
+ const resultUrls = new Set<string>();
17
+
18
+ export function createResultUrl(blob: Blob): string {
19
+ const url = URL.createObjectURL(blob);
20
+ resultUrls.add(url);
21
+ return url;
22
+ }
23
+
24
+ export function releaseResultUrl(url: string): void {
25
+ if (resultUrls.delete(url)) {
26
+ URL.revokeObjectURL(url);
27
+ }
28
+ }
29
+
30
+ export function releaseAllResultUrls(): void {
31
+ resultUrls.forEach((url) => URL.revokeObjectURL(url));
32
+ resultUrls.clear();
33
+ }
34
+
35
+ export function imageSizeOf(image: HTMLImageElement): Size {
36
+ return { width: image.naturalWidth, height: image.naturalHeight };
37
+ }
38
+
39
+ // Resolves once the image is decoded. Browsers apply EXIF orientation to
40
+ // both <img> and canvas drawing, so natural sizes are already upright.
41
+ export function loadImage(src: string): Promise<HTMLImageElement> {
42
+ return new Promise((resolve, reject) => {
43
+ const image = new Image();
44
+ if (/^https?:/i.test(src)) {
45
+ // Without CORS the canvas is tainted and the crop cannot be read back.
46
+ image.crossOrigin = 'anonymous';
47
+ }
48
+ image.decoding = 'async';
49
+ image.onload = () => {
50
+ if (image.naturalWidth > 0 && image.naturalHeight > 0) {
51
+ resolve(image);
52
+ } else {
53
+ reject(new Error('Image has no pixels'));
54
+ }
55
+ };
56
+ image.onerror = () => reject(new Error('Image failed to load'));
57
+ image.src = src;
58
+ });
59
+ }
60
+
61
+ function canvasToBlob(
62
+ canvas: HTMLCanvasElement,
63
+ quality: number
64
+ ): Promise<Blob> {
65
+ return new Promise((resolve, reject) => {
66
+ try {
67
+ canvas.toBlob(
68
+ (blob) => {
69
+ if (blob) {
70
+ resolve(blob);
71
+ } else {
72
+ reject(new Error('Canvas produced no data'));
73
+ }
74
+ },
75
+ RESULT_MIME,
76
+ quality
77
+ );
78
+ } catch (error) {
79
+ // SecurityError for a tainted canvas.
80
+ reject(error);
81
+ }
82
+ });
83
+ }
84
+
85
+ function createCanvas(size: Size): {
86
+ canvas: HTMLCanvasElement;
87
+ context: CanvasRenderingContext2D;
88
+ } {
89
+ const canvas = document.createElement('canvas');
90
+ canvas.width = size.width;
91
+ canvas.height = size.height;
92
+ const context = canvas.getContext('2d');
93
+ if (!context) {
94
+ throw new ImageCropPickerError(
95
+ 'E_CANNOT_SAVE_IMAGE',
96
+ 'Cannot create a canvas to save the image'
97
+ );
98
+ }
99
+ context.imageSmoothingEnabled = true;
100
+ context.imageSmoothingQuality = 'high';
101
+ return { canvas, context };
102
+ }
103
+
104
+ async function encode(
105
+ canvas: HTMLCanvasElement,
106
+ quality: number
107
+ ): Promise<Blob> {
108
+ try {
109
+ return await canvasToBlob(canvas, quality);
110
+ } catch {
111
+ throw new ImageCropPickerError(
112
+ 'E_CANNOT_SAVE_IMAGE',
113
+ 'Cannot save the cropped image'
114
+ );
115
+ }
116
+ }
117
+
118
+ // Draws what the crop box shows into an `output`-sized JPEG. Each axis is
119
+ // scaled on its own so a box a pixel off the target ratio still fills it.
120
+ export function renderCrop(
121
+ image: HTMLImageElement,
122
+ state: CropState,
123
+ box: Size,
124
+ output: Size,
125
+ quality: number
126
+ ): Promise<Blob> {
127
+ const { canvas, context } = createCanvas(output);
128
+ const imageSize = imageSizeOf(image);
129
+ const scale = scaleOf(state, imageSize, box);
130
+ context.translate(output.width / 2, output.height / 2);
131
+ context.scale(output.width / box.width, output.height / box.height);
132
+ context.translate(state.offsetX, state.offsetY);
133
+ context.rotate((-state.rotation * Math.PI) / 180);
134
+ context.scale(scale, scale);
135
+ context.drawImage(image, -imageSize.width / 2, -imageSize.height / 2);
136
+ return encode(canvas, quality);
137
+ }
138
+
139
+ // Re-encodes the whole image, for openPicker without cropping.
140
+ export function renderWhole(
141
+ image: HTMLImageElement,
142
+ output: Size,
143
+ quality: number
144
+ ): Promise<Blob> {
145
+ const { canvas, context } = createCanvas(output);
146
+ context.drawImage(image, 0, 0, output.width, output.height);
147
+ return encode(canvas, quality);
148
+ }
149
+
150
+ // The leading bytes of a file, for detectImageMime.
151
+ export function readImageHeader(blob: Blob): Promise<Uint8Array> {
152
+ return new Promise((resolve, reject) => {
153
+ const reader = new FileReader();
154
+ reader.onload = () => resolve(new Uint8Array(reader.result as ArrayBuffer));
155
+ reader.onerror = () => reject(reader.error);
156
+ reader.readAsArrayBuffer(blob.slice(0, IMAGE_HEADER_LENGTH));
157
+ });
158
+ }
159
+
160
+ // Base64 without the data: prefix, like native `data`.
161
+ export function blobToBase64(blob: Blob): Promise<string> {
162
+ return new Promise((resolve, reject) => {
163
+ const reader = new FileReader();
164
+ reader.onload = () => {
165
+ const result = String(reader.result ?? '');
166
+ resolve(result.slice(result.indexOf(',') + 1));
167
+ };
168
+ reader.onerror = () => reject(reader.error);
169
+ reader.readAsDataURL(blob);
170
+ });
171
+ }
172
+
173
+ export function normalizeQuality(quality: number | undefined): number {
174
+ if (quality === undefined || Number.isNaN(quality)) {
175
+ return DEFAULT_QUALITY;
176
+ }
177
+ return Math.min(Math.max(quality, 0), 1);
178
+ }
@@ -0,0 +1,130 @@
1
+ /// <reference lib="dom" />
2
+ import type {
3
+ ImageCropperAppearance,
4
+ ImageCropperColorScheme,
5
+ } from '../ReactNativeImageCropPicker.nitro';
6
+
7
+ // The same fallback palette as ios/ImageCropperTheme.swift and Android's
8
+ // ImageCropperTheme, so an app that passes no colors gets one look everywhere.
9
+ const PALETTES = {
10
+ light: {
11
+ backgroundColor: '#FFFFFF',
12
+ titleColor: '#000000DF',
13
+ iconColor: '#0000009B',
14
+ cancelButtonColor: '#0000000F',
15
+ cancelButtonPressedColor: '#0000001F',
16
+ cancelButtonTextColor: '#000000DF',
17
+ confirmButtonColor: '#000000DF',
18
+ confirmButtonPressedColor: '#0000009B',
19
+ confirmButtonTextColor: '#FFFFFFED',
20
+ },
21
+ dark: {
22
+ backgroundColor: '#0F0F0F',
23
+ titleColor: '#FFFFFFED',
24
+ iconColor: '#FFFFFFAF',
25
+ cancelButtonColor: '#FFFFFF12',
26
+ cancelButtonPressedColor: '#FFFFFF22',
27
+ cancelButtonTextColor: '#FFFFFFED',
28
+ confirmButtonColor: '#FFFFFFED',
29
+ confirmButtonPressedColor: '#FFFFFF72',
30
+ confirmButtonTextColor: '#000000DF',
31
+ },
32
+ } as const;
33
+
34
+ type PaletteKey = keyof (typeof PALETTES)['light'];
35
+
36
+ export type WebCropperTheme = Record<PaletteKey, string> & {
37
+ colorScheme: ImageCropperColorScheme;
38
+ // The area outside the crop box: the background at 70% opacity.
39
+ dimmedColor: string;
40
+ titleFontFamily?: string;
41
+ buttonFontFamily?: string;
42
+ scale: number;
43
+ };
44
+
45
+ const HEX_COLOR = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
46
+
47
+ function systemColorScheme(): ImageCropperColorScheme {
48
+ if (
49
+ typeof window !== 'undefined' &&
50
+ typeof window.matchMedia === 'function' &&
51
+ window.matchMedia('(prefers-color-scheme: dark)').matches
52
+ ) {
53
+ return 'dark';
54
+ }
55
+ return 'light';
56
+ }
57
+
58
+ // '#RGB' / '#RRGGBB' / '#RRGGBBAA' to [r, g, b, a] with a in 0...1.
59
+ export function parseHexColor(
60
+ value: string
61
+ ): [number, number, number, number] | undefined {
62
+ if (!HEX_COLOR.test(value)) {
63
+ return undefined;
64
+ }
65
+ let hex = value.slice(1);
66
+ if (hex.length === 3) {
67
+ hex = hex
68
+ .split('')
69
+ .map((char) => char + char)
70
+ .join('');
71
+ }
72
+ const r = parseInt(hex.slice(0, 2), 16);
73
+ const g = parseInt(hex.slice(2, 4), 16);
74
+ const b = parseInt(hex.slice(4, 6), 16);
75
+ const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
76
+ return [r, g, b, a];
77
+ }
78
+
79
+ // CSS reads '#RRGGBBAA' natively; rgba() keeps older engines working.
80
+ function toCssColor(value: string): string {
81
+ const rgba = parseHexColor(value);
82
+ if (!rgba) {
83
+ return value;
84
+ }
85
+ const [r, g, b, a] = rgba;
86
+ return `rgba(${r}, ${g}, ${b}, ${Number(a.toFixed(3))})`;
87
+ }
88
+
89
+ function withAlpha(value: string, alpha: number): string {
90
+ const rgba = parseHexColor(value);
91
+ if (!rgba) {
92
+ return value;
93
+ }
94
+ const [r, g, b] = rgba;
95
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
96
+ }
97
+
98
+ export function resolveTheme(
99
+ appearance: ImageCropperAppearance | undefined
100
+ ): WebCropperTheme {
101
+ const colorScheme = appearance?.colorScheme ?? systemColorScheme();
102
+ const palette = PALETTES[colorScheme];
103
+ const color = (key: PaletteKey) => {
104
+ const value = appearance?.[key];
105
+ return toCssColor(value && HEX_COLOR.test(value) ? value : palette[key]);
106
+ };
107
+ const backgroundColor = color('backgroundColor');
108
+ const scale = appearance?.scale;
109
+ return {
110
+ colorScheme,
111
+ backgroundColor,
112
+ titleColor: color('titleColor'),
113
+ iconColor: color('iconColor'),
114
+ cancelButtonColor: color('cancelButtonColor'),
115
+ cancelButtonPressedColor: color('cancelButtonPressedColor'),
116
+ cancelButtonTextColor: color('cancelButtonTextColor'),
117
+ confirmButtonColor: color('confirmButtonColor'),
118
+ confirmButtonPressedColor: color('confirmButtonPressedColor'),
119
+ confirmButtonTextColor: color('confirmButtonTextColor'),
120
+ dimmedColor: withAlpha(
121
+ appearance?.backgroundColor && HEX_COLOR.test(appearance.backgroundColor)
122
+ ? appearance.backgroundColor
123
+ : palette.backgroundColor,
124
+ 0.7
125
+ ),
126
+ titleFontFamily: appearance?.titleFontFamily || undefined,
127
+ buttonFontFamily: appearance?.buttonFontFamily || undefined,
128
+ scale: scale !== undefined && scale > 0 ? scale : 1,
129
+ };
130
+ }