-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFileField.tsx
More file actions
473 lines (445 loc) · 17.2 KB
/
Copy pathFileField.tsx
File metadata and controls
473 lines (445 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import React, { useRef, useState, useCallback } from 'react';
import { Button, EmptyValue } from '@object-ui/components';
import { useUpload } from '@object-ui/providers';
import { useObjectTranslation } from '@object-ui/i18n';
import { Upload, X, File as FileIcon, ImageIcon, Camera, Loader2 } from 'lucide-react';
import { FieldWidgetProps } from './types';
import { useUploadingSignal } from './useUploadingSignal';
/**
* Shared upload pipeline for the file widgets: validates size, uploads through
* the configured UploadProvider adapter (with progress), and merges results
* into the field value — append for `multiple`, replace otherwise. Extracted so
* the full-size FileField and the compact grid-cell {@link FileCell} stay
* behaviourally identical (same value shape, same error handling).
*/
function useFileUploads(opts: {
files: any[];
multiple: boolean;
maxSize?: number;
onChange: (value: any) => void;
}) {
const { files, multiple, maxSize, onChange } = opts;
const { upload } = useUpload();
const { t } = useObjectTranslation();
const [errors, setErrors] = useState<string[]>([]);
const [uploadProgress, setUploadProgress] = useState<Record<string, number>>({});
const [uploading, setUploading] = useState(false);
const processFiles = useCallback(async (selectedFiles: File[]) => {
if (selectedFiles.length === 0) return;
const newErrors: string[] = [];
const validFiles = selectedFiles.filter(file => {
if (maxSize && file.size > maxSize) {
const maxMB = (maxSize / (1024 * 1024)).toFixed(1);
newErrors.push(t('fields.file.exceedsMaxSize', {
defaultValue: `"${file.name}" exceeds max size (${maxMB} MB)`,
name: file.name, max: maxMB,
}));
return false;
}
return true;
});
setErrors(newErrors);
if (validFiles.length === 0) return;
setUploading(true);
try {
const fileObjects = await Promise.all(
validFiles.map(async (file) => {
try {
const result = await upload(file, {
onProgress: (ratio) =>
setUploadProgress((prev) => ({ ...prev, [file.name]: ratio })),
});
return {
// `file_id` is the storage id the backend keys attachments by
// (the adapter returns it as `meta.fileId`); surfacing it here
// lets callers that need the id — e.g. an action param POSTing
// `attachments: string[]` — recover it without a second lookup.
// Extra key; the record file-field value shape is unchanged.
file_id: (result.meta as { fileId?: string } | undefined)?.fileId,
name: result.name,
original_name: file.name,
size: result.size,
mime_type: result.mimeType,
url: result.url,
};
} catch (err) {
newErrors.push(t('fields.file.uploadFailed', {
defaultValue: `Failed to upload "${file.name}": ${(err as Error).message}`,
name: file.name, error: (err as Error).message,
}));
setErrors([...newErrors]);
return null;
}
}),
);
const successful = fileObjects.filter(Boolean) as any[];
if (successful.length === 0) return;
if (multiple) {
onChange([...files, ...successful]);
} else {
onChange(successful[0]);
}
} finally {
setUploading(false);
setUploadProgress({});
}
}, [files, multiple, onChange, maxSize, upload, t]);
return { processFiles, errors, uploading, uploadProgress };
}
/**
* FileField - File upload widget with drag-and-drop support
* Supports single and multiple file uploads with configurable accepted file types.
* L2: File size validation, per-file progress indicators, error messages.
*/
export function FileField({ value, onChange, field, readonly, onUploadingChange, ...props }: FieldWidgetProps<any>) {
const { t } = useObjectTranslation();
const inputRef = useRef<HTMLInputElement>(null);
const cameraRef = useRef<HTMLInputElement>(null);
const fileField = (field || (props as any).schema) as any;
const multiple = fileField?.multiple || false;
const accept = fileField?.accept ? fileField.accept.join(',') : undefined;
const maxSize = fileField?.maxSize as number | undefined; // bytes
/**
* Camera capture mode for mobile devices.
* - `'environment'` (back camera): photos of receipts, documents, products
* - `'user'` (front camera): selfies, profile pictures
* - `false`: disable the camera button entirely
* @default 'environment' when accept includes image/* on a touch device
*/
const captureMode = (fileField?.capture ?? null) as 'environment' | 'user' | false | null;
const acceptsImages = !accept || accept.split(',').some((t: string) =>
t.trim().startsWith('image/') || t.trim() === 'image/*' || t.trim().startsWith('.jp') || t.trim().startsWith('.png') || t.trim().startsWith('.gif') || t.trim().startsWith('.webp'),
);
// Auto-enable camera button on touch devices when image upload is permitted, unless explicitly disabled.
const isTouchDevice = typeof navigator !== 'undefined' && (navigator.maxTouchPoints > 0 || /Mobi|Android/i.test(navigator.userAgent));
const cameraEnabled = captureMode === false ? false : (captureMode ?? (acceptsImages && isTouchDevice ? 'environment' : null));
const [isDragOver, setIsDragOver] = useState(false);
const files = value ? (Array.isArray(value) ? value : [value]) : [];
const { processFiles, errors, uploading, uploadProgress } = useFileUploads({
files, multiple, maxSize, onChange,
});
useUploadingSignal(uploading, onUploadingChange);
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
}, []);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
const droppedFiles = Array.from(e.dataTransfer.files);
if (accept) {
const acceptedTypes = accept.split(',').map((t: string) => t.trim().toLowerCase());
const filtered = droppedFiles.filter(file => {
const parts = file.name.split('.');
const ext = parts.length > 1 ? '.' + parts.pop()?.toLowerCase() : '';
return acceptedTypes.some((t: string) =>
t === file.type || (ext && t === ext) || (t.endsWith('/*') && file.type.startsWith(t.replace('/*', '/')))
);
});
processFiles(filtered);
} else {
processFiles(droppedFiles);
}
}, [accept, processFiles]);
if (readonly) {
if (!value) return <EmptyValue />;
const readonlyFiles = Array.isArray(value) ? value : [value];
return (
<div className="flex flex-wrap gap-2">
{readonlyFiles.map((file: any, idx: number) => (
<span key={idx} className="text-sm truncate max-w-xs">
{file.name || file.original_name || t('fields.file.fileFallback', { defaultValue: 'File' })}
</span>
))}
</div>
);
}
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
processFiles(Array.from(e.target.files || []));
};
const handleRemove = (index: number) => {
if (multiple) {
const newFiles = files.filter((_: any, i: number) => i !== index);
onChange(newFiles.length > 0 ? newFiles : null);
} else {
onChange(null);
}
};
const isImage = (file: any) => {
const mime = file.mime_type || '';
return mime.startsWith('image/');
};
return (
<div className={props.className}>
<input
ref={inputRef}
type="file"
multiple={multiple}
accept={accept}
onChange={handleFileChange}
className="hidden"
/>
{cameraEnabled && (
<input
ref={cameraRef}
type="file"
accept="image/*"
capture={cameraEnabled}
onChange={handleFileChange}
className="hidden"
aria-label={t('fields.file.cameraCapture', { defaultValue: 'Camera capture' })}
data-testid="file-field-camera-input"
/>
)}
<div className="space-y-2">
{/* Drag-and-drop zone */}
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={() => inputRef.current?.click()}
className={`
flex flex-col items-center justify-center gap-2 p-6
border-2 border-dashed rounded-lg cursor-pointer
transition-colors duration-200
${isDragOver
? 'border-primary bg-primary/5 text-primary'
: 'border-muted-foreground/25 hover:border-primary/50 text-muted-foreground hover:text-foreground'}
`}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
inputRef.current?.click();
}
}}
>
<Upload className={`size-8 ${isDragOver ? 'text-primary' : 'text-muted-foreground'}`} />
<div className="text-center">
<p className="text-sm font-medium">
{isDragOver
? t('fields.file.dropFilesHere', { defaultValue: 'Drop files here' })
: t('fields.file.dragDropHere', { defaultValue: 'Drag & drop files here' })}
</p>
<p className="text-xs text-muted-foreground mt-1">
{cameraEnabled
? t('fields.file.browseHintCamera', { defaultValue: 'or click to browse • use the camera button below' })
: t('fields.file.browseHint', { defaultValue: 'or click to browse' })}
</p>
</div>
</div>
{cameraEnabled && (
<Button
type="button"
variant="outline"
size="sm"
className="w-full"
onClick={(e) => {
e.stopPropagation();
cameraRef.current?.click();
}}
data-testid="file-field-camera-button"
>
<Camera className="size-4 mr-2" />
{cameraEnabled === 'user'
? t('fields.file.takeSelfie', { defaultValue: 'Take selfie' })
: t('fields.file.takePhoto', { defaultValue: 'Take photo' })}
</Button>
)}
{/* Upload progress indicator */}
{uploading && (
<div className="flex items-center gap-2 text-xs text-muted-foreground" data-testid="file-field-uploading">
<Loader2 className="size-3 animate-spin" />
<span>
{(() => {
const keys = Object.keys(uploadProgress);
if (keys.length === 0) return t('fields.file.uploading', { defaultValue: 'Uploading…' });
const pct = Math.round(
(Object.values(uploadProgress).reduce((s, v) => s + v, 0) / keys.length) * 100,
);
return t('fields.file.uploadingPct', { defaultValue: `Uploading… (${pct}%)`, pct });
})()}
</span>
</div>
)}
{/* Validation errors */}
{errors.length > 0 && (
<div className="space-y-0.5">
{errors.map((err, i) => (
<p key={i} className="text-xs text-destructive">{err}</p>
))}
</div>
)}
{/* File list */}
{files.length > 0 && (
<div className="space-y-1">
{files.map((file: any, idx: number) => (
<div
key={idx}
className="flex items-center justify-between gap-2 p-2 bg-muted/50 rounded-md border"
>
<div className="flex items-center gap-2 flex-1 min-w-0">
{isImage(file) && file.url ? (
<img src={file.url} alt={file.name} className="size-8 object-cover rounded shrink-0" />
) : isImage(file) ? (
<ImageIcon className="size-4 text-muted-foreground shrink-0" />
) : (
<FileIcon className="size-4 text-muted-foreground shrink-0" />
)}
<span className="text-sm truncate">
{file.name || file.original_name || t('fields.file.fileFallback', { defaultValue: 'File' })}
</span>
{file.size && (
<span className="text-xs text-muted-foreground">
({(file.size / 1024).toFixed(1)} KB)
</span>
)}
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
handleRemove(idx);
}}
className="h-6 w-6 p-0"
>
<X className="size-3" />
</Button>
</div>
))}
</div>
)}
</div>
</div>
);
}
/**
* FileCell — compact upload control for a line-item grid cell (objectui#2360).
*
* Same value shape and upload pipeline as {@link FileField}, sized for a 32px
* grid row: existing files render as removable chips (image thumbnail / file
* icon + name) and a small button opens the native file picker. No
* drag-and-drop zone — a grid cell has no room for one; the per-row expand
* form still offers the full-size FileField.
*/
export function FileCell({
value,
onChange,
disabled,
multiple,
accept,
maxSize,
'aria-label': ariaLabel,
'data-cell': dataCell,
}: {
value: any;
onChange: (value: any) => void;
disabled?: boolean;
multiple?: boolean;
/** Comma-joined accept list for the native picker (e.g. `"image/*,.pdf"`). */
accept?: string;
/** Max file size in bytes (oversize picks are rejected with an inline error). */
maxSize?: number;
'aria-label'?: string;
/** Focus-grid coordinate (see GridField keyboard navigation). */
'data-cell'?: string;
}) {
const { t } = useObjectTranslation();
const inputRef = useRef<HTMLInputElement>(null);
const files = value ? (Array.isArray(value) ? value : [value]) : [];
const { processFiles, errors, uploading } = useFileUploads({
files, multiple: !!multiple, maxSize, onChange,
});
const removeAt = (index: number) => {
if (multiple) {
const next = files.filter((_: any, i: number) => i !== index);
onChange(next.length > 0 ? next : null);
} else {
onChange(null);
}
};
const isImage = (file: any) => String(file?.mime_type || '').startsWith('image/');
const nameOf = (file: any) =>
typeof file === 'string'
? file
: file?.name || file?.original_name || t('fields.file.fileFallback', { defaultValue: 'File' });
const showUpload = !disabled && !uploading && (multiple || files.length === 0);
return (
<div className="flex min-h-8 flex-wrap items-center gap-1 px-1 py-0.5">
<input
ref={inputRef}
type="file"
multiple={multiple}
accept={accept}
onChange={(e) => {
processFiles(Array.from(e.target.files || []));
e.target.value = ''; // allow re-picking the same file
}}
className="hidden"
/>
{files.map((file: any, idx: number) => (
<span
key={idx}
className="inline-flex max-w-40 items-center gap-1 rounded border bg-muted/50 px-1 py-0.5 text-xs"
title={nameOf(file)}
data-testid="file-cell-chip"
>
{isImage(file) && file.url ? (
<img src={file.url} alt={nameOf(file)} className="size-5 shrink-0 rounded object-cover" />
) : (
<FileIcon className="size-3 shrink-0 text-muted-foreground" />
)}
<span className="truncate">{nameOf(file)}</span>
{!disabled && (
<button
type="button"
className="shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground"
aria-label={t('fields.file.remove', { defaultValue: `Remove ${nameOf(file)}`, name: nameOf(file) })}
onClick={() => removeAt(idx)}
>
<X className="size-3" />
</button>
)}
</span>
))}
{uploading && (
<span
className="inline-flex items-center gap-1 text-xs text-muted-foreground"
data-testid="file-cell-uploading"
>
<Loader2 className="size-3.5 animate-spin" />
</span>
)}
{showUpload && (
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground"
onClick={() => inputRef.current?.click()}
aria-label={ariaLabel}
data-cell={dataCell}
disabled={disabled}
>
<Upload className="size-3.5" />
{files.length === 0 && t('fields.file.upload', { defaultValue: 'Upload' })}
</Button>
)}
{errors.length > 0 && (
<span className="w-full truncate text-[11px] text-destructive" title={errors.join('; ')}>
{errors[0]}
</span>
)}
</div>
);
}