panelui-native 0.110.0 → 0.112.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/module/components/avatar-cropper/avatar-cropper-math.js +68 -28
- package/lib/module/components/avatar-cropper/avatar-cropper-math.js.map +1 -1
- package/lib/module/components/avatar-cropper/index.js +190 -24
- package/lib/module/components/avatar-cropper/index.js.map +1 -1
- package/lib/module/components/file-upload/file-upload-core.js +317 -0
- package/lib/module/components/file-upload/file-upload-core.js.map +1 -0
- package/lib/module/components/file-upload/index.js +1214 -0
- package/lib/module/components/file-upload/index.js.map +1 -0
- package/lib/module/icons/index.js +10 -0
- package/lib/module/icons/index.js.map +1 -1
- package/lib/module/index.js +2 -1
- package/lib/module/index.js.map +1 -1
- package/lib/typescript/src/components/avatar-cropper/avatar-cropper-math.d.ts +32 -10
- package/lib/typescript/src/components/avatar-cropper/avatar-cropper-math.d.ts.map +1 -1
- package/lib/typescript/src/components/avatar-cropper/index.d.ts +30 -3
- package/lib/typescript/src/components/avatar-cropper/index.d.ts.map +1 -1
- package/lib/typescript/src/components/file-upload/file-upload-core.d.ts +136 -0
- package/lib/typescript/src/components/file-upload/file-upload-core.d.ts.map +1 -0
- package/lib/typescript/src/components/file-upload/index.d.ts +265 -0
- package/lib/typescript/src/components/file-upload/index.d.ts.map +1 -0
- package/lib/typescript/src/icons/index.d.ts +2 -0
- package/lib/typescript/src/icons/index.d.ts.map +1 -1
- package/lib/typescript/src/index.d.ts +2 -1
- package/lib/typescript/src/index.d.ts.map +1 -1
- package/package.json +5 -1
- package/src/components/avatar-cropper/avatar-cropper-math.ts +78 -42
- package/src/components/avatar-cropper/index.tsx +251 -23
- package/src/components/file-upload/file-upload-core.ts +359 -0
- package/src/components/file-upload/index.tsx +1435 -0
- package/src/icons/index.tsx +4 -0
- package/src/index.ts +24 -0
|
@@ -0,0 +1,1435 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FileUpload — pick files and photos, check them, and run their uploads.
|
|
3
|
+
*
|
|
4
|
+
* ```tsx
|
|
5
|
+
* <FileUpload
|
|
6
|
+
* value={files}
|
|
7
|
+
* onValueChange={setFiles}
|
|
8
|
+
* sources={['camera', 'library', 'files']}
|
|
9
|
+
* accept={['image/*', 'application/pdf']}
|
|
10
|
+
* multiple
|
|
11
|
+
* maxFiles={5}
|
|
12
|
+
* maxSize={10 * 1024 * 1024}
|
|
13
|
+
* upload={(file, { signal, onProgress }) => send(file, { signal, onProgress })}
|
|
14
|
+
* >
|
|
15
|
+
* <FileUpload.Dropzone />
|
|
16
|
+
* <FileUpload.List />
|
|
17
|
+
* </FileUpload>
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* ## One component for the whole trip
|
|
21
|
+
*
|
|
22
|
+
* Choosing a document, choosing or taking a photo, and sending either of them
|
|
23
|
+
* somewhere are one flow from the user's side: they add things, watch them go,
|
|
24
|
+
* and fix the ones that failed. So the root owns all of it — the list of files,
|
|
25
|
+
* the rules they have to pass, and the upload queue — and the parts are only
|
|
26
|
+
* different ways of drawing that list. `Dropzone` and `Trigger` add to it,
|
|
27
|
+
* `List` draws it as rows, `Grid` draws it as photo tiles, and `useFileUpload()`
|
|
28
|
+
* hands the same state to anything drawn by hand.
|
|
29
|
+
*
|
|
30
|
+
* ## The upload belongs to the app
|
|
31
|
+
*
|
|
32
|
+
* The component never makes a request. `upload` is the app's function: it
|
|
33
|
+
* receives one file, an `AbortSignal` and an `onProgress` callback, and
|
|
34
|
+
* resolves when the server has the file. That keeps the storage provider, the
|
|
35
|
+
* auth headers and the retry policy where they already live, and leaves the
|
|
36
|
+
* component with the part every app repeats — running at most `concurrency`
|
|
37
|
+
* at once, showing progress, and wiring cancel, retry and remove to the right
|
|
38
|
+
* file. The status of every file lives in `value`, so a form can read whether
|
|
39
|
+
* everything has finished without asking the component.
|
|
40
|
+
*
|
|
41
|
+
* ## Native modules are optional
|
|
42
|
+
*
|
|
43
|
+
* Each source reaches its Expo module only when it is used: `files` through
|
|
44
|
+
* `expo-document-picker`, `camera` and `library` through `expo-image-picker`,
|
|
45
|
+
* and resizing through `expo-image-manipulator`. An app that only takes
|
|
46
|
+
* documents never installs the camera module. A source whose module is
|
|
47
|
+
* missing reports an error with the install command rather than crashing.
|
|
48
|
+
*/
|
|
49
|
+
import {
|
|
50
|
+
Children,
|
|
51
|
+
cloneElement,
|
|
52
|
+
createContext,
|
|
53
|
+
forwardRef,
|
|
54
|
+
isValidElement,
|
|
55
|
+
useCallback,
|
|
56
|
+
useContext,
|
|
57
|
+
useEffect,
|
|
58
|
+
useMemo,
|
|
59
|
+
useRef,
|
|
60
|
+
useState,
|
|
61
|
+
type ReactElement,
|
|
62
|
+
type ReactNode,
|
|
63
|
+
} from 'react';
|
|
64
|
+
import {
|
|
65
|
+
AccessibilityInfo,
|
|
66
|
+
Image,
|
|
67
|
+
ScrollView,
|
|
68
|
+
View,
|
|
69
|
+
type LayoutChangeEvent,
|
|
70
|
+
type ViewProps,
|
|
71
|
+
} from 'react-native';
|
|
72
|
+
import Animated, { useAnimatedProps, useSharedValue, withTiming } from 'react-native-reanimated';
|
|
73
|
+
import Svg, { Circle } from 'react-native-svg';
|
|
74
|
+
import { tv } from 'tailwind-variants';
|
|
75
|
+
import { useCSSVariable } from 'uniwind';
|
|
76
|
+
import {
|
|
77
|
+
CameraIcon,
|
|
78
|
+
CheckCircleIcon,
|
|
79
|
+
FileIcon,
|
|
80
|
+
FolderIcon,
|
|
81
|
+
ImageIcon,
|
|
82
|
+
PlusIcon,
|
|
83
|
+
RotateCcwIcon,
|
|
84
|
+
TrashIcon,
|
|
85
|
+
UploadIcon,
|
|
86
|
+
VideoIcon,
|
|
87
|
+
XIcon,
|
|
88
|
+
} from '../../icons';
|
|
89
|
+
import { AnimatedPressable, type AnimatedPressableProps } from '../../primitives/animated-pressable';
|
|
90
|
+
import { useControllableState } from '../../primitives/controllable-state';
|
|
91
|
+
import { Text } from '../../primitives/text';
|
|
92
|
+
import { cn } from '../../utils/cn';
|
|
93
|
+
import { Attachment, type AttachmentState } from '../attachment';
|
|
94
|
+
import { useFieldLabelledBy } from '../field';
|
|
95
|
+
import { ImageViewer } from '../image-viewer';
|
|
96
|
+
import { Menu } from '../menu';
|
|
97
|
+
import {
|
|
98
|
+
createFileId,
|
|
99
|
+
describeRules,
|
|
100
|
+
extensionOf,
|
|
101
|
+
fitWithin,
|
|
102
|
+
formatFileSize,
|
|
103
|
+
isActive,
|
|
104
|
+
kindOf,
|
|
105
|
+
libraryMediaTypes,
|
|
106
|
+
nextToStart,
|
|
107
|
+
partitionFiles,
|
|
108
|
+
pickerTypes,
|
|
109
|
+
truncateMiddle,
|
|
110
|
+
type FileUploadFile,
|
|
111
|
+
type FileUploadKind,
|
|
112
|
+
type FileUploadRejection,
|
|
113
|
+
type FileUploadSource,
|
|
114
|
+
type FileUploadStatus,
|
|
115
|
+
} from './file-upload-core';
|
|
116
|
+
|
|
117
|
+
export {
|
|
118
|
+
describeRules as describeFileUploadRules,
|
|
119
|
+
formatFileSize,
|
|
120
|
+
type FileUploadFile,
|
|
121
|
+
type FileUploadKind,
|
|
122
|
+
type FileUploadRejection,
|
|
123
|
+
type FileUploadSource,
|
|
124
|
+
type FileUploadStatus,
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
// Optional dependencies
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
interface PickerAsset {
|
|
132
|
+
uri: string;
|
|
133
|
+
width?: number;
|
|
134
|
+
height?: number;
|
|
135
|
+
fileName?: string | null;
|
|
136
|
+
fileSize?: number | null;
|
|
137
|
+
mimeType?: string | null;
|
|
138
|
+
type?: string | null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
interface PickerResult {
|
|
142
|
+
canceled: boolean;
|
|
143
|
+
assets?: PickerAsset[] | null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
interface ImagePickerModule {
|
|
147
|
+
requestCameraPermissionsAsync(): Promise<{ granted: boolean }>;
|
|
148
|
+
launchCameraAsync(options: unknown): Promise<PickerResult>;
|
|
149
|
+
launchImageLibraryAsync(options: unknown): Promise<PickerResult>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
interface DocumentAsset {
|
|
153
|
+
uri: string;
|
|
154
|
+
name: string;
|
|
155
|
+
size?: number | null;
|
|
156
|
+
mimeType?: string | null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
interface DocumentPickerModule {
|
|
160
|
+
getDocumentAsync(options: unknown): Promise<{ canceled: boolean; assets?: DocumentAsset[] | null }>;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
interface ManipulatorContext {
|
|
164
|
+
resize(size: { width?: number; height?: number }): ManipulatorContext;
|
|
165
|
+
renderAsync(): Promise<{
|
|
166
|
+
saveAsync(options: { format?: string; compress?: number }): Promise<{
|
|
167
|
+
uri: string;
|
|
168
|
+
width: number;
|
|
169
|
+
height: number;
|
|
170
|
+
}>;
|
|
171
|
+
}>;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
interface ManipulatorModule {
|
|
175
|
+
ImageManipulator?: { manipulate(uri: string): ManipulatorContext };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/*
|
|
179
|
+
* Each `require` sits directly in its `try` block, which is what lets Metro
|
|
180
|
+
* bundle an app that does not have the package.
|
|
181
|
+
*/
|
|
182
|
+
function loadImagePicker(): ImagePickerModule | null {
|
|
183
|
+
try {
|
|
184
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
185
|
+
return require('expo-image-picker') as ImagePickerModule;
|
|
186
|
+
} catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function loadDocumentPicker(): DocumentPickerModule | null {
|
|
192
|
+
try {
|
|
193
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
194
|
+
return require('expo-document-picker') as DocumentPickerModule;
|
|
195
|
+
} catch {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function loadManipulator(): ManipulatorModule | null {
|
|
201
|
+
try {
|
|
202
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
203
|
+
return require('expo-image-manipulator') as ManipulatorModule;
|
|
204
|
+
} catch {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const MODULE_FOR: Record<FileUploadSource, string> = {
|
|
210
|
+
camera: 'expo-image-picker',
|
|
211
|
+
library: 'expo-image-picker',
|
|
212
|
+
files: 'expo-document-picker',
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
/** True when the module a source needs is installed. */
|
|
216
|
+
export function hasFileUploadSource(source: FileUploadSource): boolean {
|
|
217
|
+
return source === 'files' ? loadDocumentPicker() !== null : loadImagePicker() !== null;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// ---------------------------------------------------------------------------
|
|
221
|
+
// Types
|
|
222
|
+
// ---------------------------------------------------------------------------
|
|
223
|
+
|
|
224
|
+
/** What the upload handler is given besides the file. */
|
|
225
|
+
export interface FileUploadHandlerContext {
|
|
226
|
+
/** Aborted when the user cancels or removes the file. Pass it to `fetch`. */
|
|
227
|
+
signal: AbortSignal;
|
|
228
|
+
/** Report how far the upload is, 0–1. Calls are batched to one per frame. */
|
|
229
|
+
onProgress: (progress: number) => void;
|
|
230
|
+
/** Mark the bytes as sent and the server as still working on them. */
|
|
231
|
+
setProcessing: () => void;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Sends one file. Resolve when the server has it — the value is kept as the
|
|
236
|
+
* file's `response` — and throw to mark it failed; the error's message is shown
|
|
237
|
+
* on the row.
|
|
238
|
+
*/
|
|
239
|
+
export type FileUploadHandler = (
|
|
240
|
+
file: FileUploadFile,
|
|
241
|
+
context: FileUploadHandlerContext
|
|
242
|
+
) => Promise<unknown>;
|
|
243
|
+
|
|
244
|
+
/** How photos are prepared before they are added. */
|
|
245
|
+
export interface FileUploadImageOptions {
|
|
246
|
+
/** Scale photos wider than this down to it. Needs `expo-image-manipulator`. */
|
|
247
|
+
maxWidth?: number;
|
|
248
|
+
/** Scale photos taller than this down to it. Needs `expo-image-manipulator`. */
|
|
249
|
+
maxHeight?: number;
|
|
250
|
+
/** JPEG quality 0–1, for the picker and for a resized copy. Default 0.9. */
|
|
251
|
+
quality?: number;
|
|
252
|
+
/**
|
|
253
|
+
* Open the system's crop editor after a photo is chosen or taken, at this
|
|
254
|
+
* aspect ratio. Applies to a single photo only — the editor cannot run over
|
|
255
|
+
* a multiple selection. iOS crops to a square whatever the ratio.
|
|
256
|
+
*/
|
|
257
|
+
crop?: { aspect: [number, number] };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export interface FileUploadProps {
|
|
261
|
+
/** The files, controlled. */
|
|
262
|
+
value?: FileUploadFile[];
|
|
263
|
+
/** The files to start with, uncontrolled. */
|
|
264
|
+
defaultValue?: FileUploadFile[];
|
|
265
|
+
/** Called with the new list whenever a file is added, changes state or is removed. */
|
|
266
|
+
onValueChange?: (files: FileUploadFile[]) => void;
|
|
267
|
+
/**
|
|
268
|
+
* Where files can come from, in the order the chooser lists them. One source
|
|
269
|
+
* opens its picker straight away; more than one opens a sheet to choose from.
|
|
270
|
+
* Default `['library', 'files']`.
|
|
271
|
+
*/
|
|
272
|
+
sources?: FileUploadSource[];
|
|
273
|
+
/**
|
|
274
|
+
* Allowed types: MIME types (`application/pdf`), families (`image/*`) or
|
|
275
|
+
* extensions (`.pdf`). Everything when left out.
|
|
276
|
+
*/
|
|
277
|
+
accept?: string[];
|
|
278
|
+
/**
|
|
279
|
+
* Let the list hold more than one file. Without it the list holds one, and
|
|
280
|
+
* picking again replaces it — the shape of a profile photo or a single
|
|
281
|
+
* attachment field.
|
|
282
|
+
*/
|
|
283
|
+
multiple?: boolean;
|
|
284
|
+
/**
|
|
285
|
+
* How many files the list can hold, with `multiple`. Pickers are limited to
|
|
286
|
+
* what is left, and the add controls disable once it is reached.
|
|
287
|
+
*/
|
|
288
|
+
maxFiles?: number;
|
|
289
|
+
/**
|
|
290
|
+
* Largest allowed file, in bytes. Checked against the size the picker
|
|
291
|
+
* reports, after any resize; a file whose size is unknown passes.
|
|
292
|
+
*/
|
|
293
|
+
maxSize?: number;
|
|
294
|
+
/** Smallest allowed file, in bytes. */
|
|
295
|
+
minSize?: number;
|
|
296
|
+
/** An app-specific rule. Return a message to turn the file away. */
|
|
297
|
+
validate?: (file: FileUploadFile) => string | null | undefined;
|
|
298
|
+
/** Called with the files that were picked and turned away, and why. */
|
|
299
|
+
onReject?: (rejections: FileUploadRejection[]) => void;
|
|
300
|
+
/** Called when a picker cannot open — a missing module or a refused permission. */
|
|
301
|
+
onError?: (error: Error) => void;
|
|
302
|
+
/** Resize, compress or crop photos before they are added. */
|
|
303
|
+
image?: FileUploadImageOptions;
|
|
304
|
+
/** Sends one file. Without it files are only picked, and stay `idle`. */
|
|
305
|
+
upload?: FileUploadHandler;
|
|
306
|
+
/** How many uploads run at once. Default 2. */
|
|
307
|
+
concurrency?: number;
|
|
308
|
+
/**
|
|
309
|
+
* Queue files for upload as soon as they are added. Default true. Turn it off
|
|
310
|
+
* to send them later with `useFileUpload().upload()`.
|
|
311
|
+
*/
|
|
312
|
+
autoUpload?: boolean;
|
|
313
|
+
/** Called once per file when its upload resolves. */
|
|
314
|
+
onUploadComplete?: (file: FileUploadFile) => void;
|
|
315
|
+
/** Labels for the sources in the chooser. */
|
|
316
|
+
sourceLabels?: Partial<Record<FileUploadSource, string>>;
|
|
317
|
+
/** Nothing can be added, removed or retried. */
|
|
318
|
+
disabled?: boolean;
|
|
319
|
+
/** Draw the dropzone in its error state, for a form that failed validation. */
|
|
320
|
+
invalid?: boolean;
|
|
321
|
+
children?: ReactNode;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
interface FileUploadContextValue {
|
|
325
|
+
files: FileUploadFile[];
|
|
326
|
+
sources: FileUploadSource[];
|
|
327
|
+
sourceLabels: Record<FileUploadSource, string>;
|
|
328
|
+
accept?: string[];
|
|
329
|
+
maxFiles?: number;
|
|
330
|
+
maxSize?: number;
|
|
331
|
+
multiple: boolean;
|
|
332
|
+
disabled: boolean;
|
|
333
|
+
invalid: boolean;
|
|
334
|
+
canAddMore: boolean;
|
|
335
|
+
hasUpload: boolean;
|
|
336
|
+
rejections: FileUploadRejection[];
|
|
337
|
+
pick: (source: FileUploadSource) => Promise<void>;
|
|
338
|
+
remove: (id: string) => void;
|
|
339
|
+
cancel: (id: string) => void;
|
|
340
|
+
retry: (id: string) => void;
|
|
341
|
+
upload: (id?: string) => void;
|
|
342
|
+
clear: () => void;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const FileUploadContext = createContext<FileUploadContextValue | null>(null);
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* The state and actions of the nearest `FileUpload`, for drawing a part of it
|
|
349
|
+
* by hand — a single avatar slot, a counter, a submit button that waits for
|
|
350
|
+
* every upload.
|
|
351
|
+
*/
|
|
352
|
+
export function useFileUpload(): FileUploadContextValue {
|
|
353
|
+
const context = useContext(FileUploadContext);
|
|
354
|
+
if (!context) throw new Error('useFileUpload must be used inside <FileUpload>.');
|
|
355
|
+
return context;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const DEFAULT_SOURCES: FileUploadSource[] = ['library', 'files'];
|
|
359
|
+
|
|
360
|
+
const DEFAULT_LABELS: Record<FileUploadSource, string> = {
|
|
361
|
+
camera: 'Take photo',
|
|
362
|
+
library: 'Choose from library',
|
|
363
|
+
files: 'Browse files',
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
/** How long the chooser sheet takes to leave before a system picker opens over it. */
|
|
367
|
+
const CHOOSER_EXIT_MS = 320;
|
|
368
|
+
|
|
369
|
+
// ---------------------------------------------------------------------------
|
|
370
|
+
// Root
|
|
371
|
+
// ---------------------------------------------------------------------------
|
|
372
|
+
|
|
373
|
+
function FileUploadRoot({
|
|
374
|
+
value: valueProp,
|
|
375
|
+
defaultValue = [],
|
|
376
|
+
onValueChange,
|
|
377
|
+
sources: sourcesProp = DEFAULT_SOURCES,
|
|
378
|
+
accept,
|
|
379
|
+
multiple = false,
|
|
380
|
+
maxFiles: maxFilesProp,
|
|
381
|
+
maxSize,
|
|
382
|
+
minSize,
|
|
383
|
+
validate,
|
|
384
|
+
onReject,
|
|
385
|
+
onError,
|
|
386
|
+
image,
|
|
387
|
+
upload: uploadHandler,
|
|
388
|
+
concurrency = 2,
|
|
389
|
+
autoUpload = true,
|
|
390
|
+
onUploadComplete,
|
|
391
|
+
sourceLabels,
|
|
392
|
+
disabled = false,
|
|
393
|
+
invalid = false,
|
|
394
|
+
children,
|
|
395
|
+
}: FileUploadProps) {
|
|
396
|
+
const maxFiles = multiple ? maxFilesProp : 1;
|
|
397
|
+
const { value, setValue } = useControllableState<FileUploadFile[]>({
|
|
398
|
+
value: valueProp,
|
|
399
|
+
defaultValue,
|
|
400
|
+
onChange: onValueChange,
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
/*
|
|
404
|
+
* The list as this component last wrote it. Uploads report several changes
|
|
405
|
+
* inside one tick — a file starts, the next one queues, progress arrives —
|
|
406
|
+
* and a controlled owner has not re-rendered between them, so building each
|
|
407
|
+
* change on `value` would drop all but the last. Every change is built on
|
|
408
|
+
* this ref instead, and the ref takes the owner's value whenever it changes.
|
|
409
|
+
*/
|
|
410
|
+
const latest = useRef(value);
|
|
411
|
+
const seen = useRef(value);
|
|
412
|
+
if (value !== seen.current) {
|
|
413
|
+
seen.current = value;
|
|
414
|
+
latest.current = value;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const commit = useCallback(
|
|
418
|
+
(change: (files: FileUploadFile[]) => FileUploadFile[]) => {
|
|
419
|
+
const next = change(latest.current);
|
|
420
|
+
if (next === latest.current) return;
|
|
421
|
+
latest.current = next;
|
|
422
|
+
setValue(next);
|
|
423
|
+
},
|
|
424
|
+
[setValue]
|
|
425
|
+
);
|
|
426
|
+
|
|
427
|
+
const patch = useCallback(
|
|
428
|
+
(id: string, fields: Partial<FileUploadFile>) =>
|
|
429
|
+
commit((files) =>
|
|
430
|
+
files.some((file) => file.id === id)
|
|
431
|
+
? files.map((file) => (file.id === id ? { ...file, ...fields } : file))
|
|
432
|
+
: files
|
|
433
|
+
),
|
|
434
|
+
[commit]
|
|
435
|
+
);
|
|
436
|
+
|
|
437
|
+
const [rejections, setRejections] = useState<FileUploadRejection[]>([]);
|
|
438
|
+
|
|
439
|
+
// Callbacks read through a ref so the queue never runs a stale handler.
|
|
440
|
+
const handlers = useRef({ uploadHandler, onUploadComplete, onReject, onError, validate });
|
|
441
|
+
handlers.current = { uploadHandler, onUploadComplete, onReject, onError, validate };
|
|
442
|
+
|
|
443
|
+
// ---- upload queue -------------------------------------------------------
|
|
444
|
+
|
|
445
|
+
const jobs = useRef(new Map<string, AbortController>());
|
|
446
|
+
const pendingProgress = useRef(new Map<string, number>());
|
|
447
|
+
const frame = useRef<number | null>(null);
|
|
448
|
+
|
|
449
|
+
const flushProgress = useCallback(() => {
|
|
450
|
+
frame.current = null;
|
|
451
|
+
const pending = pendingProgress.current;
|
|
452
|
+
if (pending.size === 0) return;
|
|
453
|
+
pendingProgress.current = new Map();
|
|
454
|
+
commit((files) =>
|
|
455
|
+
files.map((file) =>
|
|
456
|
+
pending.has(file.id) && file.status === 'uploading'
|
|
457
|
+
? { ...file, progress: pending.get(file.id) }
|
|
458
|
+
: file
|
|
459
|
+
)
|
|
460
|
+
);
|
|
461
|
+
}, [commit]);
|
|
462
|
+
|
|
463
|
+
const pump = useCallback(() => {
|
|
464
|
+
const handler = handlers.current.uploadHandler;
|
|
465
|
+
if (!handler) return;
|
|
466
|
+
for (const id of nextToStart(latest.current, concurrency)) {
|
|
467
|
+
const file = latest.current.find((entry) => entry.id === id);
|
|
468
|
+
if (!file) continue;
|
|
469
|
+
const controller = new AbortController();
|
|
470
|
+
jobs.current.set(id, controller);
|
|
471
|
+
patch(id, { status: 'uploading', progress: 0, error: undefined });
|
|
472
|
+
|
|
473
|
+
const context: FileUploadHandlerContext = {
|
|
474
|
+
signal: controller.signal,
|
|
475
|
+
onProgress: (progress) => {
|
|
476
|
+
if (controller.signal.aborted) return;
|
|
477
|
+
pendingProgress.current.set(id, Math.min(1, Math.max(0, progress)));
|
|
478
|
+
frame.current ??= requestAnimationFrame(flushProgress);
|
|
479
|
+
},
|
|
480
|
+
setProcessing: () => {
|
|
481
|
+
if (controller.signal.aborted) return;
|
|
482
|
+
pendingProgress.current.delete(id);
|
|
483
|
+
patch(id, { status: 'processing', progress: 1 });
|
|
484
|
+
},
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
Promise.resolve()
|
|
488
|
+
.then(() => handler({ ...file, status: 'uploading', progress: 0 }, context))
|
|
489
|
+
.then(
|
|
490
|
+
(response) => {
|
|
491
|
+
if (controller.signal.aborted) return;
|
|
492
|
+
jobs.current.delete(id);
|
|
493
|
+
pendingProgress.current.delete(id);
|
|
494
|
+
patch(id, { status: 'done', progress: 1, response, error: undefined });
|
|
495
|
+
const done = latest.current.find((entry) => entry.id === id);
|
|
496
|
+
if (done) handlers.current.onUploadComplete?.(done);
|
|
497
|
+
},
|
|
498
|
+
(error: unknown) => {
|
|
499
|
+
if (controller.signal.aborted) return;
|
|
500
|
+
jobs.current.delete(id);
|
|
501
|
+
pendingProgress.current.delete(id);
|
|
502
|
+
patch(id, {
|
|
503
|
+
status: 'error',
|
|
504
|
+
error: error instanceof Error && error.message ? error.message : 'Upload failed',
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
}, [concurrency, flushProgress, patch]);
|
|
510
|
+
|
|
511
|
+
// Whatever changed the list — a pick, a finish, a retry — may have freed a
|
|
512
|
+
// slot or queued a file. Starting is idempotent, so running on every change
|
|
513
|
+
// is the whole scheduler.
|
|
514
|
+
useEffect(() => {
|
|
515
|
+
pump();
|
|
516
|
+
}, [value, pump, uploadHandler]);
|
|
517
|
+
|
|
518
|
+
useEffect(() => {
|
|
519
|
+
const running = jobs.current;
|
|
520
|
+
return () => {
|
|
521
|
+
for (const controller of running.values()) controller.abort();
|
|
522
|
+
running.clear();
|
|
523
|
+
if (frame.current !== null) cancelAnimationFrame(frame.current);
|
|
524
|
+
};
|
|
525
|
+
}, []);
|
|
526
|
+
|
|
527
|
+
const stop = useCallback((id: string) => {
|
|
528
|
+
jobs.current.get(id)?.abort();
|
|
529
|
+
jobs.current.delete(id);
|
|
530
|
+
pendingProgress.current.delete(id);
|
|
531
|
+
}, []);
|
|
532
|
+
|
|
533
|
+
const remove = useCallback(
|
|
534
|
+
(id: string) => {
|
|
535
|
+
stop(id);
|
|
536
|
+
setRejections([]);
|
|
537
|
+
commit((files) => files.filter((file) => file.id !== id));
|
|
538
|
+
},
|
|
539
|
+
[commit, stop]
|
|
540
|
+
);
|
|
541
|
+
|
|
542
|
+
const cancel = useCallback(
|
|
543
|
+
(id: string) => {
|
|
544
|
+
const file = latest.current.find((entry) => entry.id === id);
|
|
545
|
+
if (!file || !(isActive(file.status) || file.status === 'queued')) return;
|
|
546
|
+
stop(id);
|
|
547
|
+
patch(id, { status: 'canceled', progress: undefined });
|
|
548
|
+
},
|
|
549
|
+
[patch, stop]
|
|
550
|
+
);
|
|
551
|
+
|
|
552
|
+
const retry = useCallback(
|
|
553
|
+
(id: string) => {
|
|
554
|
+
if (!handlers.current.uploadHandler) return;
|
|
555
|
+
patch(id, { status: 'queued', progress: 0, error: undefined });
|
|
556
|
+
},
|
|
557
|
+
[patch]
|
|
558
|
+
);
|
|
559
|
+
|
|
560
|
+
const uploadNow = useCallback(
|
|
561
|
+
(id?: string) => {
|
|
562
|
+
if (!handlers.current.uploadHandler) return;
|
|
563
|
+
commit((files) =>
|
|
564
|
+
files.map((file) =>
|
|
565
|
+
(id === undefined || file.id === id) &&
|
|
566
|
+
(file.status === 'idle' || file.status === 'canceled' || file.status === 'error')
|
|
567
|
+
? { ...file, status: 'queued', progress: 0, error: undefined }
|
|
568
|
+
: file
|
|
569
|
+
)
|
|
570
|
+
);
|
|
571
|
+
},
|
|
572
|
+
[commit]
|
|
573
|
+
);
|
|
574
|
+
|
|
575
|
+
const clear = useCallback(() => {
|
|
576
|
+
for (const id of [...jobs.current.keys()]) stop(id);
|
|
577
|
+
setRejections([]);
|
|
578
|
+
commit(() => []);
|
|
579
|
+
}, [commit, stop]);
|
|
580
|
+
|
|
581
|
+
// ---- picking ------------------------------------------------------------
|
|
582
|
+
|
|
583
|
+
const report = useCallback((error: Error) => {
|
|
584
|
+
if (handlers.current.onError) handlers.current.onError(error);
|
|
585
|
+
else if (__DEV__) console.warn(`FileUpload: ${error.message}`);
|
|
586
|
+
}, []);
|
|
587
|
+
|
|
588
|
+
const pick = useCallback(
|
|
589
|
+
async (source: FileUploadSource) => {
|
|
590
|
+
if (disabled) return;
|
|
591
|
+
// A single-file upload replaces its file rather than filling up.
|
|
592
|
+
const replacing = !multiple;
|
|
593
|
+
const held = replacing ? 0 : latest.current.length;
|
|
594
|
+
const remaining = maxFiles === undefined ? undefined : Math.max(0, maxFiles - held);
|
|
595
|
+
if (remaining === 0) return;
|
|
596
|
+
const many = multiple && remaining !== 1;
|
|
597
|
+
const quality = image?.quality ?? 0.9;
|
|
598
|
+
const crop = !many ? image?.crop : undefined;
|
|
599
|
+
|
|
600
|
+
let picked: FileUploadFile[];
|
|
601
|
+
try {
|
|
602
|
+
if (source === 'files') {
|
|
603
|
+
const picker = loadDocumentPicker();
|
|
604
|
+
if (!picker) throw missing(source);
|
|
605
|
+
const result = await picker.getDocumentAsync({
|
|
606
|
+
type: pickerTypes(accept),
|
|
607
|
+
multiple: many,
|
|
608
|
+
copyToCacheDirectory: true,
|
|
609
|
+
});
|
|
610
|
+
if (result.canceled) return;
|
|
611
|
+
picked = (result.assets ?? []).map((asset) => fromDocument(asset));
|
|
612
|
+
} else {
|
|
613
|
+
const picker = loadImagePicker();
|
|
614
|
+
if (!picker) throw missing(source);
|
|
615
|
+
const options = {
|
|
616
|
+
mediaTypes: source === 'camera' ? ['images'] : libraryMediaTypes(accept),
|
|
617
|
+
allowsMultipleSelection: source === 'library' && many,
|
|
618
|
+
selectionLimit: many ? (remaining ?? 0) : 1,
|
|
619
|
+
orderedSelection: true,
|
|
620
|
+
allowsEditing: crop !== undefined,
|
|
621
|
+
aspect: crop?.aspect,
|
|
622
|
+
quality,
|
|
623
|
+
exif: false,
|
|
624
|
+
};
|
|
625
|
+
let result: PickerResult;
|
|
626
|
+
if (source === 'camera') {
|
|
627
|
+
const permission = await picker.requestCameraPermissionsAsync();
|
|
628
|
+
if (!permission.granted) {
|
|
629
|
+
throw new Error('Camera permission was refused. It can be turned on in Settings.');
|
|
630
|
+
}
|
|
631
|
+
result = await picker.launchCameraAsync(options);
|
|
632
|
+
} else {
|
|
633
|
+
result = await picker.launchImageLibraryAsync(options);
|
|
634
|
+
}
|
|
635
|
+
if (result.canceled) return;
|
|
636
|
+
picked = await Promise.all(
|
|
637
|
+
(result.assets ?? []).map((asset, index) =>
|
|
638
|
+
prepareImage(fromPickerAsset(asset, index), image, quality)
|
|
639
|
+
)
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
} catch (error) {
|
|
643
|
+
report(error instanceof Error ? error : new Error(String(error)));
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const { accepted, rejected } = partitionFiles(picked, held, {
|
|
648
|
+
accept,
|
|
649
|
+
maxSize,
|
|
650
|
+
minSize,
|
|
651
|
+
maxFiles,
|
|
652
|
+
validate: handlers.current.validate,
|
|
653
|
+
});
|
|
654
|
+
setRejections(rejected);
|
|
655
|
+
if (rejected.length > 0) {
|
|
656
|
+
handlers.current.onReject?.(rejected);
|
|
657
|
+
AccessibilityInfo.announceForAccessibility(rejected.map((entry) => entry.message).join(' '));
|
|
658
|
+
}
|
|
659
|
+
if (accepted.length === 0) return;
|
|
660
|
+
const status: FileUploadStatus =
|
|
661
|
+
handlers.current.uploadHandler && autoUpload ? 'queued' : 'idle';
|
|
662
|
+
const added = accepted.map((file) => ({ ...file, status }));
|
|
663
|
+
if (replacing) {
|
|
664
|
+
for (const file of latest.current) stop(file.id);
|
|
665
|
+
commit(() => added.slice(0, 1));
|
|
666
|
+
} else {
|
|
667
|
+
commit((files) => [...files, ...added]);
|
|
668
|
+
}
|
|
669
|
+
},
|
|
670
|
+
[accept, autoUpload, commit, disabled, image, maxFiles, maxSize, minSize, multiple, report, stop]
|
|
671
|
+
);
|
|
672
|
+
|
|
673
|
+
// A source whose picker could never return an allowed file is left out.
|
|
674
|
+
const sources = useMemo(
|
|
675
|
+
() =>
|
|
676
|
+
sourcesProp.filter((source) => {
|
|
677
|
+
if (source === 'files') return true;
|
|
678
|
+
const media = libraryMediaTypes(accept);
|
|
679
|
+
return source === 'camera' ? media.includes('images') : media.length > 0;
|
|
680
|
+
}),
|
|
681
|
+
[accept, sourcesProp]
|
|
682
|
+
);
|
|
683
|
+
|
|
684
|
+
const context = useMemo<FileUploadContextValue>(
|
|
685
|
+
() => ({
|
|
686
|
+
files: value,
|
|
687
|
+
sources,
|
|
688
|
+
sourceLabels: { ...DEFAULT_LABELS, ...sourceLabels },
|
|
689
|
+
accept,
|
|
690
|
+
maxFiles,
|
|
691
|
+
maxSize,
|
|
692
|
+
multiple,
|
|
693
|
+
disabled,
|
|
694
|
+
invalid,
|
|
695
|
+
canAddMore: !disabled && (!multiple || maxFiles === undefined || value.length < maxFiles),
|
|
696
|
+
hasUpload: uploadHandler !== undefined,
|
|
697
|
+
rejections,
|
|
698
|
+
pick,
|
|
699
|
+
remove,
|
|
700
|
+
cancel,
|
|
701
|
+
retry,
|
|
702
|
+
upload: uploadNow,
|
|
703
|
+
clear,
|
|
704
|
+
}),
|
|
705
|
+
[
|
|
706
|
+
accept,
|
|
707
|
+
cancel,
|
|
708
|
+
clear,
|
|
709
|
+
disabled,
|
|
710
|
+
invalid,
|
|
711
|
+
maxFiles,
|
|
712
|
+
maxSize,
|
|
713
|
+
multiple,
|
|
714
|
+
pick,
|
|
715
|
+
rejections,
|
|
716
|
+
remove,
|
|
717
|
+
retry,
|
|
718
|
+
sourceLabels,
|
|
719
|
+
sources,
|
|
720
|
+
uploadHandler,
|
|
721
|
+
uploadNow,
|
|
722
|
+
value,
|
|
723
|
+
]
|
|
724
|
+
);
|
|
725
|
+
|
|
726
|
+
return <FileUploadContext.Provider value={context}>{children}</FileUploadContext.Provider>;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function missing(source: FileUploadSource): Error {
|
|
730
|
+
const name = MODULE_FOR[source];
|
|
731
|
+
return new Error(`Adding from "${source}" needs ${name}. Install it with: npx expo install ${name}`);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
function fromDocument(asset: DocumentAsset): FileUploadFile {
|
|
735
|
+
const file = {
|
|
736
|
+
uri: asset.uri,
|
|
737
|
+
name: asset.name,
|
|
738
|
+
size: asset.size ?? undefined,
|
|
739
|
+
mimeType: asset.mimeType ?? undefined,
|
|
740
|
+
};
|
|
741
|
+
return { id: createFileId(), ...file, kind: kindOf(file), status: 'idle' };
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function fromPickerAsset(asset: PickerAsset, index: number): FileUploadFile {
|
|
745
|
+
const video = asset.type === 'video' || asset.mimeType?.startsWith('video/');
|
|
746
|
+
const fallbackExt = video ? 'mp4' : 'jpg';
|
|
747
|
+
const name = asset.fileName || `${video ? 'Video' : 'Photo'} ${timestamp()}${index ? `-${index + 1}` : ''}.${fallbackExt}`;
|
|
748
|
+
const mimeType = asset.mimeType ?? (video ? 'video/mp4' : extensionOf(name) === 'png' ? 'image/png' : 'image/jpeg');
|
|
749
|
+
return {
|
|
750
|
+
id: createFileId(),
|
|
751
|
+
uri: asset.uri,
|
|
752
|
+
name,
|
|
753
|
+
size: asset.fileSize ?? undefined,
|
|
754
|
+
mimeType,
|
|
755
|
+
width: asset.width,
|
|
756
|
+
height: asset.height,
|
|
757
|
+
kind: video ? 'video' : 'image',
|
|
758
|
+
status: 'idle',
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
function timestamp(): string {
|
|
763
|
+
const now = new Date();
|
|
764
|
+
const pad = (n: number) => String(n).padStart(2, '0');
|
|
765
|
+
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}.${pad(now.getMinutes())}.${pad(now.getSeconds())}`;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/** Scale a photo into `maxWidth`/`maxHeight`, when it is larger and the manipulator is installed. */
|
|
769
|
+
async function prepareImage(
|
|
770
|
+
file: FileUploadFile,
|
|
771
|
+
options: FileUploadImageOptions | undefined,
|
|
772
|
+
quality: number
|
|
773
|
+
): Promise<FileUploadFile> {
|
|
774
|
+
if (file.kind !== 'image' || !options || !file.width || !file.height) return file;
|
|
775
|
+
const target = fitWithin({ width: file.width, height: file.height }, options);
|
|
776
|
+
if (!target) return file;
|
|
777
|
+
const manipulator = loadManipulator()?.ImageManipulator;
|
|
778
|
+
if (!manipulator) {
|
|
779
|
+
if (__DEV__) {
|
|
780
|
+
console.warn('FileUpload: resizing photos needs expo-image-manipulator. Install it with: npx expo install expo-image-manipulator');
|
|
781
|
+
}
|
|
782
|
+
return file;
|
|
783
|
+
}
|
|
784
|
+
const rendered = await manipulator.manipulate(file.uri).resize({ width: target.width }).renderAsync();
|
|
785
|
+
const saved = await rendered.saveAsync({ format: 'jpeg', compress: quality });
|
|
786
|
+
const name = file.name.replace(/\.[^.]+$/, '') + '.jpg';
|
|
787
|
+
// The resized file's size is not reported; it is smaller than the original.
|
|
788
|
+
return { ...file, uri: saved.uri, width: saved.width, height: saved.height, name, size: undefined, mimeType: 'image/jpeg' };
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// ---------------------------------------------------------------------------
|
|
792
|
+
// Source chooser
|
|
793
|
+
// ---------------------------------------------------------------------------
|
|
794
|
+
|
|
795
|
+
const SOURCE_ICONS: Record<FileUploadSource, (color?: string) => ReactNode> = {
|
|
796
|
+
camera: (color) => <CameraIcon size={18} color={color} />,
|
|
797
|
+
library: (color) => <ImageIcon size={18} color={color} />,
|
|
798
|
+
files: (color) => <FolderIcon size={18} color={color} />,
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* Wraps one pressable. With one source the press opens its picker; with more,
|
|
803
|
+
* a sheet of the sources opens first, and the picker waits for it to leave so
|
|
804
|
+
* the two never animate over each other.
|
|
805
|
+
*/
|
|
806
|
+
function SourceChooser({ children }: { children: ReactElement<{ onPress?: (...args: unknown[]) => void }> }) {
|
|
807
|
+
const { sources, sourceLabels, pick, canAddMore } = useFileUpload();
|
|
808
|
+
const iconColor = useCSSVariable('--color-foreground');
|
|
809
|
+
const color = typeof iconColor === 'string' ? iconColor : undefined;
|
|
810
|
+
|
|
811
|
+
if (sources.length <= 1) {
|
|
812
|
+
const only = sources[0];
|
|
813
|
+
return cloneElement(children, {
|
|
814
|
+
onPress: (...args: unknown[]) => {
|
|
815
|
+
children.props.onPress?.(...args);
|
|
816
|
+
if (only && canAddMore) void pick(only);
|
|
817
|
+
},
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
if (!canAddMore) return children;
|
|
822
|
+
|
|
823
|
+
const choose = (source: FileUploadSource) => {
|
|
824
|
+
setTimeout(() => void pick(source), CHOOSER_EXIT_MS);
|
|
825
|
+
};
|
|
826
|
+
|
|
827
|
+
return (
|
|
828
|
+
<Menu presentation="bottom-sheet">
|
|
829
|
+
<Menu.Trigger>{children}</Menu.Trigger>
|
|
830
|
+
<Menu.Content>
|
|
831
|
+
{sources.map((source) => (
|
|
832
|
+
<Menu.Item key={source} icon={SOURCE_ICONS[source](color)} onSelect={() => choose(source)}>
|
|
833
|
+
{sourceLabels[source]}
|
|
834
|
+
</Menu.Item>
|
|
835
|
+
))}
|
|
836
|
+
</Menu.Content>
|
|
837
|
+
</Menu>
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// ---------------------------------------------------------------------------
|
|
842
|
+
// Trigger
|
|
843
|
+
// ---------------------------------------------------------------------------
|
|
844
|
+
|
|
845
|
+
export interface FileUploadTriggerProps {
|
|
846
|
+
/** One pressable — a Button, an icon button, an avatar. */
|
|
847
|
+
children: ReactElement;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Turns any pressable into the way files are added. With several sources it
|
|
852
|
+
* opens a sheet listing them; with one it opens that picker directly.
|
|
853
|
+
*/
|
|
854
|
+
function FileUploadTrigger({ children }: FileUploadTriggerProps) {
|
|
855
|
+
const { disabled, canAddMore } = useFileUpload();
|
|
856
|
+
const child = Children.only(children) as ReactElement<{ disabled?: boolean; onPress?: () => void }>;
|
|
857
|
+
const locked = disabled || !canAddMore;
|
|
858
|
+
return (
|
|
859
|
+
<SourceChooser>
|
|
860
|
+
{isValidElement(child) && locked ? cloneElement(child, { disabled: true }) : child}
|
|
861
|
+
</SourceChooser>
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// ---------------------------------------------------------------------------
|
|
866
|
+
// Dropzone
|
|
867
|
+
// ---------------------------------------------------------------------------
|
|
868
|
+
|
|
869
|
+
const dropzoneVariants = tv({
|
|
870
|
+
slots: {
|
|
871
|
+
root: 'items-center justify-center rounded-2xl border-2 border-dashed border-border bg-muted/40 px-6 py-7 active:bg-muted',
|
|
872
|
+
// The pressable animates its own opacity for press feedback, which would
|
|
873
|
+
// overwrite a dimming class on it — so the contents are what dim.
|
|
874
|
+
body: 'items-center gap-3',
|
|
875
|
+
badge: 'h-12 w-12 items-center justify-center rounded-full border border-border bg-background',
|
|
876
|
+
title: 'text-center text-base font-semibold text-foreground',
|
|
877
|
+
hint: 'text-center text-sm text-muted-foreground',
|
|
878
|
+
error: 'text-center text-sm text-destructive',
|
|
879
|
+
},
|
|
880
|
+
variants: {
|
|
881
|
+
invalid: { true: { root: 'border-destructive bg-destructive-subtle' } },
|
|
882
|
+
disabled: { true: { body: 'opacity-50' } },
|
|
883
|
+
},
|
|
884
|
+
});
|
|
885
|
+
|
|
886
|
+
export interface FileUploadDropzoneProps extends Omit<AnimatedPressableProps, 'children'> {
|
|
887
|
+
className?: string;
|
|
888
|
+
/** Headline. Default "Choose files", or "Choose a file" for a single file. */
|
|
889
|
+
title?: ReactNode;
|
|
890
|
+
/** The line under it. Written from `accept`, `maxSize` and `maxFiles` when left out. */
|
|
891
|
+
description?: ReactNode;
|
|
892
|
+
/** Replaces the upload glyph in the badge. */
|
|
893
|
+
icon?: ReactNode;
|
|
894
|
+
/** Draw the inside yourself. The press still opens the sources. */
|
|
895
|
+
children?: ReactNode;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* The large dashed area at the top of a form. Pressing anywhere on it adds
|
|
900
|
+
* files, and the line under the title says what is allowed before anybody
|
|
901
|
+
* picks something that is not. When a pick is turned away, the reason replaces
|
|
902
|
+
* that line until the next pick.
|
|
903
|
+
*/
|
|
904
|
+
const FileUploadDropzone = forwardRef<View, FileUploadDropzoneProps>(
|
|
905
|
+
({ className, title, description, icon, children, ...props }, ref) => {
|
|
906
|
+
const { accept, maxSize, maxFiles, multiple, disabled, invalid, canAddMore, rejections, files } =
|
|
907
|
+
useFileUpload();
|
|
908
|
+
const labelledBy = useFieldLabelledBy();
|
|
909
|
+
const primary = useCSSVariable('--color-foreground');
|
|
910
|
+
const full = multiple && maxFiles !== undefined && files.length >= maxFiles;
|
|
911
|
+
const first = rejections[0];
|
|
912
|
+
const rejected = first
|
|
913
|
+
? rejections.length > 1
|
|
914
|
+
? `${first.message} ${rejections.length - 1} more could not be added.`
|
|
915
|
+
: first.message
|
|
916
|
+
: null;
|
|
917
|
+
const slots = dropzoneVariants({ invalid: invalid || rejected !== null, disabled: disabled || full });
|
|
918
|
+
|
|
919
|
+
const heading = title ?? (multiple ? 'Choose files' : 'Choose a file');
|
|
920
|
+
const hint = full
|
|
921
|
+
? `${files.length} of ${maxFiles} added. Remove one to add another.`
|
|
922
|
+
: (description ?? describeRules({ accept, maxSize, maxFiles: multiple ? maxFiles : undefined }));
|
|
923
|
+
|
|
924
|
+
return (
|
|
925
|
+
<SourceChooser>
|
|
926
|
+
<AnimatedPressable
|
|
927
|
+
ref={ref}
|
|
928
|
+
accessibilityRole="button"
|
|
929
|
+
accessibilityLabel={[typeof heading === 'string' ? heading : null, typeof hint === 'string' ? hint : null]
|
|
930
|
+
.filter(Boolean)
|
|
931
|
+
.join('. ')}
|
|
932
|
+
accessibilityState={{ disabled: disabled || !canAddMore }}
|
|
933
|
+
accessibilityLabelledBy={labelledBy}
|
|
934
|
+
disabled={disabled || !canAddMore}
|
|
935
|
+
className={slots.root({ className })}
|
|
936
|
+
{...props}
|
|
937
|
+
>
|
|
938
|
+
<View className={slots.body()}>
|
|
939
|
+
{children ?? (
|
|
940
|
+
<>
|
|
941
|
+
<View className={slots.badge()}>
|
|
942
|
+
{icon ?? <UploadIcon size={22} color={typeof primary === 'string' ? primary : undefined} />}
|
|
943
|
+
</View>
|
|
944
|
+
<View className="gap-1">
|
|
945
|
+
{typeof heading === 'string' ? <Text className={slots.title()}>{heading}</Text> : heading}
|
|
946
|
+
{hint ? (
|
|
947
|
+
typeof hint === 'string' ? <Text className={slots.hint()}>{hint}</Text> : hint
|
|
948
|
+
) : null}
|
|
949
|
+
{rejected ? (
|
|
950
|
+
<Text className={slots.error()} accessibilityLiveRegion="polite">
|
|
951
|
+
{rejected}
|
|
952
|
+
</Text>
|
|
953
|
+
) : null}
|
|
954
|
+
</View>
|
|
955
|
+
</>
|
|
956
|
+
)}
|
|
957
|
+
</View>
|
|
958
|
+
</AnimatedPressable>
|
|
959
|
+
</SourceChooser>
|
|
960
|
+
);
|
|
961
|
+
}
|
|
962
|
+
);
|
|
963
|
+
FileUploadDropzone.displayName = 'FileUpload.Dropzone';
|
|
964
|
+
|
|
965
|
+
// ---------------------------------------------------------------------------
|
|
966
|
+
// Item and List
|
|
967
|
+
// ---------------------------------------------------------------------------
|
|
968
|
+
|
|
969
|
+
const ATTACHMENT_STATE: Record<FileUploadStatus, AttachmentState> = {
|
|
970
|
+
idle: 'idle',
|
|
971
|
+
queued: 'idle',
|
|
972
|
+
uploading: 'uploading',
|
|
973
|
+
processing: 'processing',
|
|
974
|
+
done: 'done',
|
|
975
|
+
error: 'error',
|
|
976
|
+
canceled: 'idle',
|
|
977
|
+
};
|
|
978
|
+
|
|
979
|
+
/** "PDF · 2.4 MB", "1.1 of 2.4 MB · 46%", "Waiting", "Upload failed". */
|
|
980
|
+
export function describeFileStatus(file: FileUploadFile): string {
|
|
981
|
+
const ext = extensionOf(file.name).toUpperCase();
|
|
982
|
+
const size = file.size !== undefined ? formatFileSize(file.size) : '';
|
|
983
|
+
const percent = `${Math.round((file.progress ?? 0) * 100)}%`;
|
|
984
|
+
switch (file.status) {
|
|
985
|
+
case 'queued':
|
|
986
|
+
return ['Waiting', size].filter(Boolean).join(' · ');
|
|
987
|
+
case 'uploading':
|
|
988
|
+
return file.size !== undefined
|
|
989
|
+
? `${formatFileSize(file.size * (file.progress ?? 0))} of ${size} · ${percent}`
|
|
990
|
+
: `Uploading · ${percent}`;
|
|
991
|
+
case 'processing':
|
|
992
|
+
return 'Processing…';
|
|
993
|
+
case 'done':
|
|
994
|
+
return [size, 'Uploaded'].filter(Boolean).join(' · ');
|
|
995
|
+
case 'error':
|
|
996
|
+
return file.error ?? 'Upload failed';
|
|
997
|
+
case 'canceled':
|
|
998
|
+
return ['Canceled', size].filter(Boolean).join(' · ');
|
|
999
|
+
default:
|
|
1000
|
+
return [ext, size].filter(Boolean).join(' · ');
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
function KindIcon({ kind, size = 18, color }: { kind: FileUploadKind; size?: number; color?: string }) {
|
|
1005
|
+
if (kind === 'image') return <ImageIcon size={size} color={color} />;
|
|
1006
|
+
if (kind === 'video') return <VideoIcon size={size} color={color} />;
|
|
1007
|
+
return <FileIcon size={size} color={color} />;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
export interface FileUploadItemProps {
|
|
1011
|
+
file: FileUploadFile;
|
|
1012
|
+
className?: string;
|
|
1013
|
+
/** Row density. */
|
|
1014
|
+
size?: 'default' | 'sm';
|
|
1015
|
+
/**
|
|
1016
|
+
* Longest name shown before it is shortened from the middle, keeping the
|
|
1017
|
+
* extension. Default 36.
|
|
1018
|
+
*/
|
|
1019
|
+
nameLength?: number;
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* One file as an Attachment row: a thumbnail or type icon, the name, a status
|
|
1024
|
+
* line, and the action that fits the state — cancel while it is moving, retry
|
|
1025
|
+
* when it failed or was stopped, remove otherwise.
|
|
1026
|
+
*/
|
|
1027
|
+
function FileUploadItem({ file, className, size = 'default', nameLength = 36 }: FileUploadItemProps) {
|
|
1028
|
+
const { remove, cancel, retry, disabled, hasUpload } = useFileUpload();
|
|
1029
|
+
const muted = useCSSVariable('--color-muted-foreground');
|
|
1030
|
+
const success = useCSSVariable('--color-success');
|
|
1031
|
+
const mutedColor = typeof muted === 'string' ? muted : undefined;
|
|
1032
|
+
const moving = isActive(file.status) || file.status === 'queued';
|
|
1033
|
+
const failed = file.status === 'error' || file.status === 'canceled';
|
|
1034
|
+
const status = describeFileStatus(file);
|
|
1035
|
+
|
|
1036
|
+
return (
|
|
1037
|
+
<Attachment
|
|
1038
|
+
state={ATTACHMENT_STATE[file.status]}
|
|
1039
|
+
progress={file.status === 'uploading' ? (file.progress ?? 0) : undefined}
|
|
1040
|
+
size={size}
|
|
1041
|
+
disabled={disabled}
|
|
1042
|
+
accessibilityLabel={`${file.name}, ${status}`}
|
|
1043
|
+
className={className}
|
|
1044
|
+
>
|
|
1045
|
+
{file.kind === 'image' ? (
|
|
1046
|
+
<Attachment.Media variant="image">
|
|
1047
|
+
<Image source={{ uri: file.uri }} className="h-full w-full" resizeMode="cover" />
|
|
1048
|
+
</Attachment.Media>
|
|
1049
|
+
) : (
|
|
1050
|
+
<Attachment.Media variant="icon">
|
|
1051
|
+
<KindIcon kind={file.kind} color={mutedColor} size={size === 'sm' ? 16 : 18} />
|
|
1052
|
+
</Attachment.Media>
|
|
1053
|
+
)}
|
|
1054
|
+
<Attachment.Content>
|
|
1055
|
+
{/* Shortened by hand: the shimmer a busy row draws cannot clip to one line. */}
|
|
1056
|
+
<Attachment.Title numberOfLines={1}>{truncateMiddle(file.name, nameLength)}</Attachment.Title>
|
|
1057
|
+
<Attachment.Description numberOfLines={file.status === 'error' ? 2 : 1}>
|
|
1058
|
+
{status}
|
|
1059
|
+
</Attachment.Description>
|
|
1060
|
+
</Attachment.Content>
|
|
1061
|
+
<Attachment.Actions>
|
|
1062
|
+
{file.status === 'done' ? (
|
|
1063
|
+
<View accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
|
|
1064
|
+
<CheckCircleIcon size={18} color={typeof success === 'string' ? success : undefined} />
|
|
1065
|
+
</View>
|
|
1066
|
+
) : null}
|
|
1067
|
+
{failed && hasUpload ? (
|
|
1068
|
+
<Attachment.Action
|
|
1069
|
+
accessibilityLabel={`Retry ${file.name}`}
|
|
1070
|
+
disabled={disabled}
|
|
1071
|
+
onPress={() => retry(file.id)}
|
|
1072
|
+
>
|
|
1073
|
+
<RotateCcwIcon size={16} color={mutedColor} />
|
|
1074
|
+
</Attachment.Action>
|
|
1075
|
+
) : null}
|
|
1076
|
+
<Attachment.Action
|
|
1077
|
+
accessibilityLabel={moving ? `Cancel upload of ${file.name}` : `Remove ${file.name}`}
|
|
1078
|
+
disabled={disabled}
|
|
1079
|
+
onPress={() => (moving ? cancel(file.id) : remove(file.id))}
|
|
1080
|
+
>
|
|
1081
|
+
{moving ? <XIcon size={16} color={mutedColor} /> : <TrashIcon size={16} color={mutedColor} />}
|
|
1082
|
+
</Attachment.Action>
|
|
1083
|
+
</Attachment.Actions>
|
|
1084
|
+
</Attachment>
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
export interface FileUploadListProps extends ViewProps {
|
|
1089
|
+
className?: string;
|
|
1090
|
+
/** Lay the files out as one scrolling strip of fixed-width rows, for a message composer. */
|
|
1091
|
+
horizontal?: boolean;
|
|
1092
|
+
/** Row density. */
|
|
1093
|
+
size?: 'default' | 'sm';
|
|
1094
|
+
/** Draw a row yourself. `FileUpload.Item` is the default. */
|
|
1095
|
+
renderItem?: (file: FileUploadFile) => ReactNode;
|
|
1096
|
+
/** Shown when the list is empty. Nothing by default. */
|
|
1097
|
+
empty?: ReactNode;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
/** Every file as a row, in the order it was added. */
|
|
1101
|
+
const FileUploadList = forwardRef<View, FileUploadListProps>(
|
|
1102
|
+
({ className, horizontal = false, size, renderItem, empty, ...props }, ref) => {
|
|
1103
|
+
const { files } = useFileUpload();
|
|
1104
|
+
if (files.length === 0) return empty ? <>{empty}</> : null;
|
|
1105
|
+
|
|
1106
|
+
const rows = files.map((file) =>
|
|
1107
|
+
renderItem ? (
|
|
1108
|
+
<View key={file.id}>{renderItem(file)}</View>
|
|
1109
|
+
) : (
|
|
1110
|
+
<FileUploadItem
|
|
1111
|
+
key={file.id}
|
|
1112
|
+
file={file}
|
|
1113
|
+
size={size}
|
|
1114
|
+
className={horizontal ? 'w-72' : undefined}
|
|
1115
|
+
nameLength={horizontal ? 16 : undefined}
|
|
1116
|
+
/>
|
|
1117
|
+
)
|
|
1118
|
+
);
|
|
1119
|
+
|
|
1120
|
+
if (horizontal) {
|
|
1121
|
+
return (
|
|
1122
|
+
<View ref={ref} className={className} {...props}>
|
|
1123
|
+
<ScrollView
|
|
1124
|
+
horizontal
|
|
1125
|
+
showsHorizontalScrollIndicator={false}
|
|
1126
|
+
contentContainerClassName="gap-2"
|
|
1127
|
+
>
|
|
1128
|
+
{rows}
|
|
1129
|
+
</ScrollView>
|
|
1130
|
+
</View>
|
|
1131
|
+
);
|
|
1132
|
+
}
|
|
1133
|
+
return (
|
|
1134
|
+
<View ref={ref} accessibilityRole="list" className={cn('gap-2', className)} {...props}>
|
|
1135
|
+
{rows}
|
|
1136
|
+
</View>
|
|
1137
|
+
);
|
|
1138
|
+
}
|
|
1139
|
+
);
|
|
1140
|
+
FileUploadList.displayName = 'FileUpload.List';
|
|
1141
|
+
|
|
1142
|
+
// ---------------------------------------------------------------------------
|
|
1143
|
+
// Grid
|
|
1144
|
+
// ---------------------------------------------------------------------------
|
|
1145
|
+
|
|
1146
|
+
const AnimatedCircle = Animated.createAnimatedComponent(Circle);
|
|
1147
|
+
|
|
1148
|
+
/** A ring that fills with upload progress, drawn over a tile's scrim. */
|
|
1149
|
+
function ProgressRing({ progress, size = 36 }: { progress: number; size?: number }) {
|
|
1150
|
+
const stroke = 3;
|
|
1151
|
+
const radius = (size - stroke) / 2;
|
|
1152
|
+
const circumference = 2 * Math.PI * radius;
|
|
1153
|
+
const shown = useSharedValue(progress);
|
|
1154
|
+
|
|
1155
|
+
useEffect(() => {
|
|
1156
|
+
shown.value = withTiming(progress, { duration: 180 });
|
|
1157
|
+
}, [progress, shown]);
|
|
1158
|
+
|
|
1159
|
+
const animatedProps = useAnimatedProps(() => ({
|
|
1160
|
+
strokeDashoffset: circumference * (1 - shown.value),
|
|
1161
|
+
}));
|
|
1162
|
+
|
|
1163
|
+
return (
|
|
1164
|
+
<Svg width={size} height={size} style={{ transform: [{ rotate: '-90deg' }] }}>
|
|
1165
|
+
<Circle cx={size / 2} cy={size / 2} r={radius} stroke="rgba(255,255,255,0.3)" strokeWidth={stroke} fill="none" />
|
|
1166
|
+
<AnimatedCircle
|
|
1167
|
+
cx={size / 2}
|
|
1168
|
+
cy={size / 2}
|
|
1169
|
+
r={radius}
|
|
1170
|
+
stroke="#fff"
|
|
1171
|
+
strokeWidth={stroke}
|
|
1172
|
+
strokeLinecap="round"
|
|
1173
|
+
strokeDasharray={`${circumference} ${circumference}`}
|
|
1174
|
+
animatedProps={animatedProps}
|
|
1175
|
+
fill="none"
|
|
1176
|
+
/>
|
|
1177
|
+
</Svg>
|
|
1178
|
+
);
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
function GridTile({
|
|
1182
|
+
file,
|
|
1183
|
+
size,
|
|
1184
|
+
cover,
|
|
1185
|
+
radius,
|
|
1186
|
+
}: {
|
|
1187
|
+
file: FileUploadFile;
|
|
1188
|
+
size: number;
|
|
1189
|
+
cover: boolean;
|
|
1190
|
+
radius: number;
|
|
1191
|
+
}) {
|
|
1192
|
+
const { remove, cancel, retry, disabled, hasUpload } = useFileUpload();
|
|
1193
|
+
const muted = useCSSVariable('--color-muted-foreground');
|
|
1194
|
+
const foreground = useCSSVariable('--color-foreground');
|
|
1195
|
+
const moving = isActive(file.status) || file.status === 'queued';
|
|
1196
|
+
const failed = file.status === 'error' || file.status === 'canceled';
|
|
1197
|
+
const status = describeFileStatus(file);
|
|
1198
|
+
|
|
1199
|
+
return (
|
|
1200
|
+
<View
|
|
1201
|
+
style={{ width: size, height: size }}
|
|
1202
|
+
className={cn(disabled && 'opacity-50')}
|
|
1203
|
+
accessibilityLabel={`${file.name}, ${status}`}>
|
|
1204
|
+
{file.kind === 'image' ? (
|
|
1205
|
+
<View style={{ borderRadius: radius }} className="h-full w-full overflow-hidden bg-muted">
|
|
1206
|
+
<ImageViewer.Trigger
|
|
1207
|
+
source={{ uri: file.uri }}
|
|
1208
|
+
width={file.width}
|
|
1209
|
+
height={file.height}
|
|
1210
|
+
alt={file.name}
|
|
1211
|
+
radius={radius}
|
|
1212
|
+
disabled={moving}
|
|
1213
|
+
className="h-full w-full"
|
|
1214
|
+
/>
|
|
1215
|
+
</View>
|
|
1216
|
+
) : (
|
|
1217
|
+
<View
|
|
1218
|
+
style={{ borderRadius: radius }}
|
|
1219
|
+
className="h-full w-full items-center justify-center gap-1.5 border border-border bg-muted px-2"
|
|
1220
|
+
>
|
|
1221
|
+
<KindIcon kind={file.kind} size={22} color={typeof muted === 'string' ? muted : undefined} />
|
|
1222
|
+
<Text numberOfLines={1} className="text-xs text-muted-foreground">
|
|
1223
|
+
{file.name}
|
|
1224
|
+
</Text>
|
|
1225
|
+
</View>
|
|
1226
|
+
)}
|
|
1227
|
+
|
|
1228
|
+
{moving || failed ? (
|
|
1229
|
+
<View
|
|
1230
|
+
pointerEvents="box-none"
|
|
1231
|
+
style={{ borderRadius: radius }}
|
|
1232
|
+
className="absolute inset-0 items-center justify-center bg-black/45"
|
|
1233
|
+
>
|
|
1234
|
+
{file.status === 'uploading' ? (
|
|
1235
|
+
<ProgressRing progress={file.progress ?? 0} />
|
|
1236
|
+
) : file.status === 'queued' || file.status === 'processing' ? (
|
|
1237
|
+
<Text className="text-xs font-medium text-white">
|
|
1238
|
+
{file.status === 'queued' ? 'Waiting' : 'Processing'}
|
|
1239
|
+
</Text>
|
|
1240
|
+
) : hasUpload ? (
|
|
1241
|
+
<AnimatedPressable
|
|
1242
|
+
accessibilityRole="button"
|
|
1243
|
+
accessibilityLabel={`Retry ${file.name}`}
|
|
1244
|
+
disabled={disabled}
|
|
1245
|
+
onPress={() => retry(file.id)}
|
|
1246
|
+
className="h-9 w-9 items-center justify-center rounded-full bg-white/20 active:bg-white/30"
|
|
1247
|
+
>
|
|
1248
|
+
<RotateCcwIcon size={18} color="#fff" />
|
|
1249
|
+
</AnimatedPressable>
|
|
1250
|
+
) : null}
|
|
1251
|
+
</View>
|
|
1252
|
+
) : null}
|
|
1253
|
+
|
|
1254
|
+
{cover ? (
|
|
1255
|
+
<View className="absolute bottom-1.5 left-1.5 rounded-full bg-background/90 px-2 py-0.5">
|
|
1256
|
+
<Text className="text-[11px] font-semibold text-foreground">Cover</Text>
|
|
1257
|
+
</View>
|
|
1258
|
+
) : null}
|
|
1259
|
+
|
|
1260
|
+
<AnimatedPressable
|
|
1261
|
+
accessibilityRole="button"
|
|
1262
|
+
accessibilityLabel={moving ? `Cancel upload of ${file.name}` : `Remove ${file.name}`}
|
|
1263
|
+
disabled={disabled}
|
|
1264
|
+
hitSlop={8}
|
|
1265
|
+
onPress={() => (moving ? cancel(file.id) : remove(file.id))}
|
|
1266
|
+
className="absolute right-1.5 top-1.5 h-6 w-6 items-center justify-center rounded-full border border-border bg-background active:bg-muted"
|
|
1267
|
+
>
|
|
1268
|
+
<XIcon size={12} color={typeof foreground === 'string' ? foreground : undefined} strokeWidth={2.5} />
|
|
1269
|
+
</AnimatedPressable>
|
|
1270
|
+
</View>
|
|
1271
|
+
);
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
export interface FileUploadGridProps extends ViewProps {
|
|
1275
|
+
className?: string;
|
|
1276
|
+
/** Tiles per row. Default 3. Ignored when `horizontal`. */
|
|
1277
|
+
columns?: number;
|
|
1278
|
+
/** Lay the tiles out as one scrolling strip. */
|
|
1279
|
+
horizontal?: boolean;
|
|
1280
|
+
/** Tile size in points, for a horizontal strip. Default 88. */
|
|
1281
|
+
tileSize?: number;
|
|
1282
|
+
/** Space between tiles, in points. Default 8. */
|
|
1283
|
+
gap?: number;
|
|
1284
|
+
/** Corner radius of a tile, in points. Default 12. */
|
|
1285
|
+
radius?: number;
|
|
1286
|
+
/** Mark the first photo as the cover. */
|
|
1287
|
+
cover?: boolean;
|
|
1288
|
+
/** Draw empty slots for the rest of `maxFiles`, so the limit can be seen. */
|
|
1289
|
+
placeholders?: boolean;
|
|
1290
|
+
/** Label of the add tile. Default "Add photo" or "Add photos". */
|
|
1291
|
+
addLabel?: string;
|
|
1292
|
+
/** Leave the add tile out — for a grid with its own Trigger elsewhere. */
|
|
1293
|
+
hideAdd?: boolean;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/**
|
|
1297
|
+
* Photos as square tiles, led by a tile that adds more. Each photo opens in
|
|
1298
|
+
* the full-screen viewer, carries its own remove button, and shows a ring
|
|
1299
|
+
* while it uploads. The add tile counts against `maxFiles`, so the limit is
|
|
1300
|
+
* visible before anybody hits it.
|
|
1301
|
+
*/
|
|
1302
|
+
const FileUploadGrid = forwardRef<View, FileUploadGridProps>(
|
|
1303
|
+
(
|
|
1304
|
+
{
|
|
1305
|
+
className,
|
|
1306
|
+
columns = 3,
|
|
1307
|
+
horizontal = false,
|
|
1308
|
+
tileSize = 88,
|
|
1309
|
+
gap = 8,
|
|
1310
|
+
radius = 12,
|
|
1311
|
+
cover = false,
|
|
1312
|
+
placeholders = false,
|
|
1313
|
+
addLabel,
|
|
1314
|
+
hideAdd = false,
|
|
1315
|
+
onLayout,
|
|
1316
|
+
...props
|
|
1317
|
+
},
|
|
1318
|
+
ref
|
|
1319
|
+
) => {
|
|
1320
|
+
const { files, maxFiles, multiple, canAddMore } = useFileUpload();
|
|
1321
|
+
const [width, setWidth] = useState(0);
|
|
1322
|
+
const background = useCSSVariable('--color-background');
|
|
1323
|
+
const muted = useCSSVariable('--color-muted-foreground');
|
|
1324
|
+
|
|
1325
|
+
const size = horizontal
|
|
1326
|
+
? tileSize
|
|
1327
|
+
: width > 0
|
|
1328
|
+
? Math.floor((width - gap * (columns - 1)) / columns)
|
|
1329
|
+
: 0;
|
|
1330
|
+
|
|
1331
|
+
const showAdd = !hideAdd && canAddMore;
|
|
1332
|
+
const slotCount =
|
|
1333
|
+
placeholders && maxFiles !== undefined
|
|
1334
|
+
? Math.max(0, maxFiles - files.length - (showAdd ? 1 : 0))
|
|
1335
|
+
: 0;
|
|
1336
|
+
// Empty slots only finish the current row; a page of them is noise.
|
|
1337
|
+
const filled = files.length + (showAdd ? 1 : 0);
|
|
1338
|
+
const rowRemainder = filled % columns === 0 ? 0 : columns - (filled % columns);
|
|
1339
|
+
const visibleSlots = horizontal ? slotCount : Math.min(slotCount, rowRemainder);
|
|
1340
|
+
|
|
1341
|
+
const label = addLabel ?? (multiple ? 'Add photos' : 'Add photo');
|
|
1342
|
+
const tiles: ReactNode[] = [];
|
|
1343
|
+
|
|
1344
|
+
if (showAdd && size > 0) {
|
|
1345
|
+
tiles.push(
|
|
1346
|
+
<SourceChooser key="add">
|
|
1347
|
+
<AnimatedPressable
|
|
1348
|
+
accessibilityRole="button"
|
|
1349
|
+
accessibilityLabel={
|
|
1350
|
+
maxFiles !== undefined ? `${label}, ${files.length} of ${maxFiles}` : label
|
|
1351
|
+
}
|
|
1352
|
+
style={{ width: size, height: size, borderRadius: radius }}
|
|
1353
|
+
className="items-center justify-center gap-1 border-2 border-dashed border-border bg-muted/40 active:bg-muted"
|
|
1354
|
+
>
|
|
1355
|
+
<View className="h-8 w-8 items-center justify-center rounded-full bg-foreground">
|
|
1356
|
+
<PlusIcon
|
|
1357
|
+
size={16}
|
|
1358
|
+
strokeWidth={2.5}
|
|
1359
|
+
color={typeof background === 'string' ? background : undefined}
|
|
1360
|
+
/>
|
|
1361
|
+
</View>
|
|
1362
|
+
{size >= 84 ? (
|
|
1363
|
+
<Text className="text-xs font-medium text-foreground" numberOfLines={1}>
|
|
1364
|
+
{label}
|
|
1365
|
+
</Text>
|
|
1366
|
+
) : null}
|
|
1367
|
+
{maxFiles !== undefined && multiple ? (
|
|
1368
|
+
<Text className="text-[11px] text-muted-foreground">
|
|
1369
|
+
{files.length}/{maxFiles}
|
|
1370
|
+
</Text>
|
|
1371
|
+
) : null}
|
|
1372
|
+
</AnimatedPressable>
|
|
1373
|
+
</SourceChooser>
|
|
1374
|
+
);
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
if (size > 0) {
|
|
1378
|
+
files.forEach((file, index) =>
|
|
1379
|
+
tiles.push(
|
|
1380
|
+
<GridTile key={file.id} file={file} size={size} cover={cover && index === 0} radius={radius} />
|
|
1381
|
+
)
|
|
1382
|
+
);
|
|
1383
|
+
for (let i = 0; i < visibleSlots; i += 1) {
|
|
1384
|
+
tiles.push(
|
|
1385
|
+
<View
|
|
1386
|
+
key={`slot-${i}`}
|
|
1387
|
+
accessibilityElementsHidden
|
|
1388
|
+
importantForAccessibility="no-hide-descendants"
|
|
1389
|
+
style={{ width: size, height: size, borderRadius: radius }}
|
|
1390
|
+
className="items-center justify-center border border-dashed border-border"
|
|
1391
|
+
>
|
|
1392
|
+
<ImageIcon size={18} color={typeof muted === 'string' ? muted : undefined} opacity={0.5} />
|
|
1393
|
+
</View>
|
|
1394
|
+
);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
const body = horizontal ? (
|
|
1399
|
+
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap }}>
|
|
1400
|
+
{tiles}
|
|
1401
|
+
</ScrollView>
|
|
1402
|
+
) : (
|
|
1403
|
+
<View className="flex-row flex-wrap" style={{ gap }}>
|
|
1404
|
+
{tiles}
|
|
1405
|
+
</View>
|
|
1406
|
+
);
|
|
1407
|
+
|
|
1408
|
+
return (
|
|
1409
|
+
<View
|
|
1410
|
+
ref={ref}
|
|
1411
|
+
className={className}
|
|
1412
|
+
onLayout={(event: LayoutChangeEvent) => {
|
|
1413
|
+
setWidth(event.nativeEvent.layout.width);
|
|
1414
|
+
onLayout?.(event);
|
|
1415
|
+
}}
|
|
1416
|
+
{...props}
|
|
1417
|
+
>
|
|
1418
|
+
<ImageViewer>{body}</ImageViewer>
|
|
1419
|
+
</View>
|
|
1420
|
+
);
|
|
1421
|
+
}
|
|
1422
|
+
);
|
|
1423
|
+
FileUploadGrid.displayName = 'FileUpload.Grid';
|
|
1424
|
+
|
|
1425
|
+
FileUploadRoot.displayName = 'FileUpload';
|
|
1426
|
+
FileUploadTrigger.displayName = 'FileUpload.Trigger';
|
|
1427
|
+
FileUploadItem.displayName = 'FileUpload.Item';
|
|
1428
|
+
|
|
1429
|
+
export const FileUpload = Object.assign(FileUploadRoot, {
|
|
1430
|
+
Trigger: FileUploadTrigger,
|
|
1431
|
+
Dropzone: FileUploadDropzone,
|
|
1432
|
+
List: FileUploadList,
|
|
1433
|
+
Item: FileUploadItem,
|
|
1434
|
+
Grid: FileUploadGrid,
|
|
1435
|
+
});
|