@freightos/freightwind 2.1.3 → 2.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { forwardRef, useState, } from 'react';
4
+ import { useDirection } from '@radix-ui/react-direction';
5
+ import { cn } from '../lib/utils';
6
+ import { iconMap } from '../lib/icon-utils';
7
+ import { useStableId } from '../lib/use-stable-id';
8
+ import { hasValidExtension } from '../lib/file-extensions';
9
+ // ─── Defaults ─────────────────────────────────────────────────────────────────
10
+ const DEFAULT_LABELS = {
11
+ idleTitle: 'Upload your document',
12
+ idleSubtitle: 'Click or drag your file here',
13
+ uploading: 'Uploading…',
14
+ forbidden: {
15
+ multiple: { title: 'Oops!', subtitle: 'Too many files' },
16
+ type: { title: 'Oops!', subtitle: 'Unsupported file format' },
17
+ size: { title: 'Oops!', subtitle: 'File is too large' },
18
+ extension: { title: 'Oops!', subtitle: 'Invalid file extension' },
19
+ custom: { title: 'Oops!', subtitle: 'This file is not allowed' },
20
+ },
21
+ };
22
+ const identity = (k) => k;
23
+ // ─── Validation helpers ───────────────────────────────────────────────────────
24
+ const EXT_TO_MIME = {
25
+ '.pdf': ['application/pdf'],
26
+ '.png': ['image/png'],
27
+ '.jpg': ['image/jpeg'],
28
+ '.jpeg': ['image/jpeg'],
29
+ '.gif': ['image/gif'],
30
+ '.webp': ['image/webp'],
31
+ '.svg': ['image/svg+xml'],
32
+ '.xlsx': ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
33
+ '.xls': ['application/vnd.ms-excel'],
34
+ '.csv': ['text/csv', 'application/csv', 'text/plain'],
35
+ '.doc': ['application/msword'],
36
+ '.docx': ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
37
+ '.txt': ['text/plain'],
38
+ '.zip': ['application/zip', 'application/x-zip-compressed'],
39
+ };
40
+ function mimeMatchesAccept(mime, accept) {
41
+ return accept.some((rule) => {
42
+ if (rule.endsWith('/*'))
43
+ return mime.startsWith(rule.slice(0, -1));
44
+ if (rule.startsWith('.'))
45
+ return (EXT_TO_MIME[rule.toLowerCase()] ?? []).includes(mime);
46
+ return mime === rule;
47
+ });
48
+ }
49
+ function extMatchesAccept(filename, accept) {
50
+ const dot = filename.lastIndexOf('.');
51
+ if (dot < 0)
52
+ return false;
53
+ const ext = filename.slice(dot).toLowerCase();
54
+ return accept.some((rule) => rule.toLowerCase() === ext);
55
+ }
56
+ function fileMatchesAccept(file, accept) {
57
+ return mimeMatchesAccept(file.type, accept) || extMatchesAccept(file.name, accept);
58
+ }
59
+ function validateDragItems(items, { maxFiles, accept, alreadyHeld = 0 }) {
60
+ if (maxFiles != null && items.length + alreadyHeld > maxFiles)
61
+ return { ok: false, reason: 'multiple' };
62
+ if (accept && accept.length > 0) {
63
+ for (let i = 0; i < items.length; i++) {
64
+ const item = items[i];
65
+ if (!item || item.kind !== 'file')
66
+ continue;
67
+ if (!mimeMatchesAccept(item.type, accept))
68
+ return { ok: false, reason: 'type' };
69
+ }
70
+ }
71
+ return { ok: true };
72
+ }
73
+ function validatePickedFile(file, { accept, maxSize }) {
74
+ if (!hasValidExtension(file.name))
75
+ return { ok: false, reason: 'extension' };
76
+ if (accept && accept.length > 0 && !fileMatchesAccept(file, accept))
77
+ return { ok: false, reason: 'type' };
78
+ if (maxSize != null && file.size > maxSize)
79
+ return { ok: false, reason: 'size' };
80
+ return { ok: true };
81
+ }
82
+ // ─── Component ─────────────────────────────────────────────────────────────────
83
+ export const MultipleFilesUpload = forwardRef(function MultipleFilesUpload({ dataTestId, files = [], accept, maxFiles, maxSize, isDisabled = false, isFillContainer = false, labels, t = identity, onUpload, onRemove, onForbidden, ariaLabel, defaultUploading = false, defaultForbidden, className, ...rest }, ref) {
84
+ const inputId = useStableId('multi-upload');
85
+ const dir = useDirection();
86
+ const [isUploading, setIsUploading] = useState(defaultUploading);
87
+ const [forbiddenReason, setForbiddenReason] = useState(defaultForbidden ?? null);
88
+ const mergedLabels = { ...DEFAULT_LABELS, ...labels };
89
+ const mergedForbidden = { ...DEFAULT_LABELS.forbidden, ...(labels?.forbidden ?? {}) };
90
+ const fbCopy = mergedForbidden[forbiddenReason ?? 'multiple'];
91
+ const acceptAttr = accept?.join(',');
92
+ const hasFiles = files.length > 0;
93
+ const hasErrors = files.some((e) => e.status === 'error');
94
+ const handleDragEnter = (e) => {
95
+ if (isDisabled)
96
+ return;
97
+ e.preventDefault();
98
+ const result = validateDragItems(e.dataTransfer.items, { maxFiles, accept, alreadyHeld: files.length });
99
+ if (!result.ok) {
100
+ setForbiddenReason(result.reason);
101
+ onForbidden?.(result.reason);
102
+ }
103
+ };
104
+ const handleDragLeave = (e) => {
105
+ if (e.currentTarget.contains(e.relatedTarget))
106
+ return;
107
+ setForbiddenReason(null);
108
+ };
109
+ const handleDrop = (e) => {
110
+ if (isDisabled)
111
+ return;
112
+ e.preventDefault();
113
+ setForbiddenReason(null);
114
+ const dropped = Array.from(e.dataTransfer.files);
115
+ if (maxFiles != null && dropped.length + files.length > maxFiles) {
116
+ setForbiddenReason('multiple');
117
+ onForbidden?.('multiple');
118
+ return;
119
+ }
120
+ for (const f of dropped) {
121
+ const result = validatePickedFile(f, { accept, maxSize });
122
+ if (!result.ok) {
123
+ setForbiddenReason(result.reason);
124
+ onForbidden?.(result.reason);
125
+ return;
126
+ }
127
+ }
128
+ triggerUpload(dropped);
129
+ };
130
+ const handleNativeChange = (e) => {
131
+ const selected = Array.from(e.target.files ?? []);
132
+ e.target.value = '';
133
+ if (maxFiles != null && selected.length + files.length > maxFiles) {
134
+ setForbiddenReason('multiple');
135
+ onForbidden?.('multiple');
136
+ return;
137
+ }
138
+ for (const f of selected) {
139
+ const result = validatePickedFile(f, { accept, maxSize });
140
+ if (!result.ok) {
141
+ setForbiddenReason(result.reason);
142
+ onForbidden?.(result.reason);
143
+ return;
144
+ }
145
+ }
146
+ setForbiddenReason(null);
147
+ triggerUpload(selected);
148
+ };
149
+ const triggerUpload = (selected) => {
150
+ if (selected.length === 0)
151
+ return;
152
+ onUpload?.(selected, (v) => setIsUploading(v));
153
+ };
154
+ const handleRemoveClick = (e, file) => {
155
+ e.preventDefault();
156
+ e.stopPropagation();
157
+ onRemove?.(file);
158
+ };
159
+ const DocumentIcon = iconMap['document'];
160
+ const SpinnerIcon = iconMap['loading'];
161
+ const CheckIcon = iconMap['check-circled'];
162
+ const ErrorIcon = iconMap['clear-circled'];
163
+ const BlockIcon = iconMap['block'];
164
+ const TrashIcon = iconMap['trash'];
165
+ const renderDropzoneContent = () => {
166
+ if (isUploading) {
167
+ return (_jsx(SpinnerIcon, { size: "md", role: "status", "aria-label": t(mergedLabels.uploading), className: "animate-spin text-fds-blue-30 rtl:direction-[reverse]", "data-test-id": `${dataTestId}-uploading-indicator` }));
168
+ }
169
+ if (forbiddenReason) {
170
+ return (_jsxs(_Fragment, { children: [_jsx(BlockIcon, { size: "md", className: "shrink-0 text-fds-red-30", "aria-hidden": true, "data-test-id": `${dataTestId}-forbidden-icon` }), _jsxs("div", { className: "flex min-w-0 flex-col gap-fds-xs text-start", "aria-live": "polite", children: [_jsx("span", { className: "text-fds-sm font-fds-regular leading-fds-body text-fds-red-30", "data-test-id": `${dataTestId}-forbidden-title`, children: t(fbCopy?.title ?? '') }), _jsx("span", { className: "text-fds-xs font-fds-bold leading-fds-body text-fds-red-30", "data-test-id": `${dataTestId}-forbidden-subtitle`, children: t(fbCopy?.subtitle ?? '') })] })] }));
171
+ }
172
+ return (_jsxs(_Fragment, { children: [_jsx(DocumentIcon, { size: "md", className: "shrink-0 text-fds-gray-80 rtl:scale-x-[-1] dark:text-fds-gray-20", "aria-hidden": true, "data-test-id": `${dataTestId}-idle-icon` }), _jsxs("div", { className: "flex min-w-0 flex-col gap-fds-xs text-start", children: [_jsx("span", { className: "text-fds-sm font-fds-regular leading-fds-body text-fds-gray-80 dark:text-fds-gray-20", "data-test-id": `${dataTestId}-idle-title`, children: t(mergedLabels.idleTitle) }), _jsx("span", { className: "text-fds-xs font-fds-bold leading-fds-body text-fds-gray-80 dark:text-fds-gray-20", "data-test-id": `${dataTestId}-idle-subtitle`, children: t(mergedLabels.idleSubtitle) })] })] }));
173
+ };
174
+ const renderFileRow = (entry, index) => {
175
+ const isSuccess = entry.status === 'success';
176
+ const RowIcon = isSuccess ? CheckIcon : ErrorIcon;
177
+ const iconColor = isSuccess ? 'text-fds-green-30' : 'text-fds-red-30';
178
+ const textColor = isSuccess ? 'text-fds-blue-30' : 'text-fds-red-30';
179
+ return (_jsxs("div", { className: "flex h-[40px] w-full items-center gap-fds-sm", "data-test-id": `${dataTestId}-file-row-${index}`, children: [_jsx(RowIcon, { size: "sm", className: cn('shrink-0', iconColor), "aria-hidden": true, "data-test-id": `${dataTestId}-file-status-${index}` }), _jsx("span", { className: cn('min-w-0 flex-1 truncate text-fds-base font-fds-regular leading-fds-body', textColor), title: entry.file.name, "data-test-id": `${dataTestId}-filename-${index}`, children: entry.file.name }), !isDisabled && (_jsx("button", { type: "button", onClick: (e) => handleRemoveClick(e, entry.file), "aria-label": t(`Remove ${entry.file.name}`), "data-test-id": `${dataTestId}-trash-${index}`, className: "inline-flex h-[40px] w-[63px] shrink-0 items-center justify-center cursor-pointer text-fds-red-30 hover:bg-fds-red-05 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-fds-red-30 dark:hover:bg-fds-red-30/10", children: _jsx(TrashIcon, { size: "sm", "aria-hidden": true }) }))] }, `${entry.file.name}-${index}`));
180
+ };
181
+ const dropzoneBorderClass = forbiddenReason
182
+ ? 'upload-dash-fluid-red'
183
+ : isUploading
184
+ ? 'border border-solid border-fds-gray-30 dark:border-fds-gray-70'
185
+ : hasErrors && hasFiles
186
+ ? 'border border-solid border-fds-red-30 dark:border-fds-red-30'
187
+ : hasFiles
188
+ ? 'border border-solid border-fds-blue-30 dark:border-fds-blue-30'
189
+ : 'upload-dash-fluid';
190
+ const dropzoneHeight = isFillContainer ? 'h-[147px]' : 'h-[69px]';
191
+ return (_jsxs("div", { ref: ref, dir: dir, "data-test-id": dataTestId, "data-state": isUploading ? 'uploading' : hasErrors ? 'errors' : hasFiles ? 'success' : forbiddenReason ? 'forbidden' : 'default', className: cn('relative flex flex-col rounded-fds-md bg-white p-[24px] gap-[10px] dark:bg-fds-gray-95', isFillContainer ? 'w-full' : 'w-[433px]', isDisabled && 'pointer-events-none opacity-60', className), ...rest, children: [_jsxs("label", { htmlFor: inputId, "aria-label": ariaLabel ?? t(mergedLabels.idleTitle), "aria-disabled": isDisabled || undefined, "aria-busy": isUploading || undefined, className: cn('fw-base relative flex w-full cursor-pointer select-none items-center gap-fds-sm rounded-fds-md p-fds-lg transition-colors', 'bg-fds-gray-10 dark:bg-fds-gray-90', dropzoneHeight, dropzoneBorderClass, isDisabled && 'cursor-not-allowed', isUploading && 'cursor-uploading justify-center', forbiddenReason && 'cursor-not-allowed justify-center'), onDragEnter: handleDragEnter, onDragOver: (e) => e.preventDefault(), onDragLeave: handleDragLeave, onDrop: handleDrop, children: [_jsx("input", { id: inputId, type: "file", accept: acceptAttr, multiple: maxFiles == null || maxFiles > 1, disabled: isDisabled, className: "sr-only", onChange: handleNativeChange, "data-test-id": `${dataTestId}-input` }), renderDropzoneContent()] }), hasFiles && !isUploading && (_jsx("div", { className: "flex w-full flex-col", "data-test-id": `${dataTestId}-file-list`, children: files.map((entry, i) => renderFileRow(entry, i)) }))] }));
192
+ });
@@ -0,0 +1,330 @@
1
+ 'use client';
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { forwardRef, useState, } from 'react';
4
+ import { cva } from 'class-variance-authority';
5
+ import { useDirection } from '@radix-ui/react-direction';
6
+ import { cn } from '../lib/utils';
7
+ import { iconMap } from '../lib/icon-utils';
8
+ import { useStableId } from '../lib/use-stable-id';
9
+ import { hasValidExtension } from '../lib/file-extensions';
10
+ const uploadVariants = cva('fw-base group relative flex select-none rounded-fds-md outline-none transition-colors has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-fds-blue-30 has-[:focus-visible]:ring-offset-2', {
11
+ variants: {
12
+ variant: {
13
+ rectangle: 'items-center gap-fds-sm p-fds-lg',
14
+ square: 'h-[99px] w-[100px] flex-col items-center justify-center gap-[10px] px-[26px] py-[23px]',
15
+ 'square-lg': 'h-[238px] w-[285px] flex-col items-center justify-center gap-fds-lg p-fds-xl',
16
+ },
17
+ state: {
18
+ default: 'cursor-pointer justify-center bg-fds-gray-10 dark:bg-fds-gray-90',
19
+ forbidden: 'cursor-not-allowed justify-center bg-fds-gray-10 dark:bg-fds-gray-90',
20
+ uploading: 'cursor-uploading justify-center border border-solid border-fds-gray-30 bg-fds-gray-10 dark:border-fds-gray-70 dark:bg-fds-gray-90',
21
+ 'uploading-spinner': 'cursor-uploading justify-center border border-solid border-fds-gray-30 bg-fds-gray-10 dark:border-fds-gray-70 dark:bg-fds-gray-90',
22
+ success: 'cursor-pointer border border-solid border-fds-blue-30 bg-fds-gray-10 hover:border-fds-blue-40 dark:border-fds-blue-30 dark:bg-fds-gray-90',
23
+ error: 'cursor-not-allowed border border-solid border-fds-red-30 bg-fds-gray-10 dark:border-fds-red-30 dark:bg-fds-gray-90',
24
+ disabled: 'cursor-not-allowed-gray border border-solid border-fds-gray-30 bg-fds-gray-10 text-fds-gray-50 [&_*]:pointer-events-none dark:border-fds-gray-70 dark:bg-fds-gray-90 dark:text-fds-gray-50',
25
+ },
26
+ },
27
+ defaultVariants: { variant: 'rectangle', state: 'default' },
28
+ });
29
+ const DEFAULT_LABELS = {
30
+ idleTitle: 'Upload your document',
31
+ idleSubtitle: 'Click or drag your file here',
32
+ idleCompact: 'Upload',
33
+ idleDragDrop: 'Drag and drop your file',
34
+ uploading: 'Uploading…',
35
+ forbidden: {
36
+ multiple: { title: 'Oops!', subtitle: 'You can only drag one file', compact: 'Oops!' },
37
+ type: { title: 'Oops!', subtitle: 'Unsupported file format', compact: 'Oops!' },
38
+ size: { title: 'Oops!', subtitle: 'File is too large', compact: 'Oops!' },
39
+ extension: { title: 'Oops!', subtitle: 'Invalid file extension', compact: 'Oops!' },
40
+ custom: { title: 'Oops!', subtitle: 'This file is not allowed', compact: 'Oops!' },
41
+ },
42
+ };
43
+ const DEFAULT_ICONS = {
44
+ idleRectangle: 'document',
45
+ idleSquare: 'plus',
46
+ forbidden: 'block',
47
+ success: 'check-circled',
48
+ error: 'clear-circled',
49
+ uploading: 'loading',
50
+ remove: 'trash',
51
+ };
52
+ const identity = (k) => k;
53
+ function truncateMiddle(name, max) {
54
+ if (name.length <= max)
55
+ return name;
56
+ const dot = name.lastIndexOf('.');
57
+ const ext = dot > 0 ? name.slice(dot) : '';
58
+ const head = name.slice(0, Math.max(2, Math.floor((max - ext.length - 1) / 2)));
59
+ return `${head}…${ext || name.slice(-Math.max(2, Math.floor(max / 2)))}`;
60
+ }
61
+ function buildFileLabel(allFiles, isSquare) {
62
+ const names = allFiles.map((f) => f.name);
63
+ const tooltip = names.join('\n');
64
+ if (names.length === 1) {
65
+ return { display: isSquare ? truncateMiddle(names[0], 12) : names[0], tooltip };
66
+ }
67
+ const shown = names.slice(0, 2).map((n) => truncateMiddle(n, 12));
68
+ const extra = names.length - 2;
69
+ const display = shown.join(', ') + (extra > 0 ? `, +${extra}` : '');
70
+ return { display, tooltip };
71
+ }
72
+ const EXT_TO_MIME = {
73
+ '.pdf': ['application/pdf'],
74
+ '.png': ['image/png'],
75
+ '.jpg': ['image/jpeg'],
76
+ '.jpeg': ['image/jpeg'],
77
+ '.gif': ['image/gif'],
78
+ '.webp': ['image/webp'],
79
+ '.svg': ['image/svg+xml'],
80
+ '.xlsx': ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
81
+ '.xls': ['application/vnd.ms-excel'],
82
+ '.csv': ['text/csv', 'application/csv', 'text/plain'],
83
+ '.doc': ['application/msword'],
84
+ '.docx': ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
85
+ '.txt': ['text/plain'],
86
+ '.zip': ['application/zip', 'application/x-zip-compressed'],
87
+ };
88
+ function mimeMatchesAccept(mime, accept) {
89
+ return accept.some((rule) => {
90
+ if (rule.endsWith('/*'))
91
+ return mime.startsWith(rule.slice(0, -1));
92
+ if (rule.startsWith('.'))
93
+ return (EXT_TO_MIME[rule.toLowerCase()] ?? []).includes(mime);
94
+ return mime === rule;
95
+ });
96
+ }
97
+ function extMatchesAccept(filename, accept) {
98
+ const dot = filename.lastIndexOf('.');
99
+ if (dot < 0)
100
+ return false;
101
+ const ext = filename.slice(dot).toLowerCase();
102
+ return accept.some((rule) => rule.toLowerCase() === ext);
103
+ }
104
+ function fileMatchesAccept(file, accept) {
105
+ return mimeMatchesAccept(file.type, accept) || extMatchesAccept(file.name, accept);
106
+ }
107
+ function validateDragItems(items, { maxFiles, accept, alreadyHeld = 0 }) {
108
+ const limit = maxFiles ?? 1;
109
+ if (items.length + alreadyHeld > limit)
110
+ return { ok: false, reason: 'multiple' };
111
+ if (accept && accept.length > 0) {
112
+ for (let i = 0; i < items.length; i++) {
113
+ const item = items[i];
114
+ if (!item || item.kind !== 'file')
115
+ continue;
116
+ if (!mimeMatchesAccept(item.type, accept))
117
+ return { ok: false, reason: 'type' };
118
+ }
119
+ }
120
+ return { ok: true };
121
+ }
122
+ function validatePickedFile(file, { accept, maxSize }) {
123
+ if (!hasValidExtension(file.name))
124
+ return { ok: false, reason: 'extension' };
125
+ if (accept && accept.length > 0 && !fileMatchesAccept(file, accept)) {
126
+ return { ok: false, reason: 'type' };
127
+ }
128
+ if (maxSize != null && file.size > maxSize)
129
+ return { ok: false, reason: 'size' };
130
+ return { ok: true };
131
+ }
132
+ export const Upload = forwardRef(function Upload({ dataTestId, variant = 'rectangle', value, files: filesProp, maxFiles, accept, maxSize, isError = false, isDisabled = false, isFillContainer = false, labels, t = identity, onUpload, onRemove, onForbidden, ariaLabel, defaultUploading = false, defaultUploadProgress, defaultForbidden, uploadingStyle = 'progress', className, ...rest }, ref) {
133
+ const inputId = useStableId('upload');
134
+ const dir = useDirection();
135
+ const [forbiddenReason, setForbiddenReason] = useState(defaultForbidden ?? null);
136
+ const [isUploading, setIsUploading] = useState(defaultUploading);
137
+ const [uploadProgress, setUploadProgress] = useState(defaultUploadProgress ?? null);
138
+ const mergedLabels = { ...DEFAULT_LABELS, ...labels };
139
+ const mergedForbidden = {
140
+ ...DEFAULT_LABELS.forbidden,
141
+ ...(labels?.forbidden ?? {}),
142
+ };
143
+ const fbCopy = mergedForbidden[forbiddenReason ?? 'multiple'];
144
+ const allFiles = filesProp ?? (value ? [value] : []);
145
+ const hasFiles = allFiles.length > 0;
146
+ const effectiveState = isDisabled
147
+ ? 'disabled'
148
+ : forbiddenReason
149
+ ? 'forbidden'
150
+ : isUploading
151
+ ? uploadingStyle === 'spinner' ? 'uploading-spinner' : 'uploading'
152
+ : isError
153
+ ? 'error'
154
+ : hasFiles
155
+ ? 'success'
156
+ : 'default';
157
+ const isSquare = variant === 'square';
158
+ const isSquareLg = variant === 'square-lg';
159
+ const isSquareAny = isSquare || isSquareLg;
160
+ const isMultiple = maxFiles == null || maxFiles > 1;
161
+ const acceptAttr = accept?.join(',');
162
+ const triggerUpload = (selected) => {
163
+ if (selected.length === 0)
164
+ return;
165
+ onUpload?.(selected, (v, progress) => {
166
+ setIsUploading(v);
167
+ setUploadProgress(v && progress !== undefined ? progress : null);
168
+ });
169
+ };
170
+ const handleDragEnter = (e) => {
171
+ if (isDisabled)
172
+ return;
173
+ e.preventDefault();
174
+ const result = validateDragItems(e.dataTransfer.items, { maxFiles, accept: accept, alreadyHeld: allFiles.length });
175
+ if (!result.ok) {
176
+ setForbiddenReason(result.reason);
177
+ onForbidden?.(result.reason);
178
+ }
179
+ };
180
+ const handleDragLeave = (e) => {
181
+ if (e.currentTarget.contains(e.relatedTarget))
182
+ return;
183
+ setForbiddenReason(null);
184
+ };
185
+ const handleDrop = (e) => {
186
+ if (isDisabled)
187
+ return;
188
+ e.preventDefault();
189
+ setForbiddenReason(null);
190
+ const dropped = Array.from(e.dataTransfer.files);
191
+ const limit = maxFiles ?? 1;
192
+ if (dropped.length + allFiles.length > limit) {
193
+ setForbiddenReason('multiple');
194
+ onForbidden?.('multiple');
195
+ return;
196
+ }
197
+ for (const f of dropped) {
198
+ const result = validatePickedFile(f, { accept: accept, maxSize });
199
+ if (!result.ok) {
200
+ setForbiddenReason(result.reason);
201
+ onForbidden?.(result.reason);
202
+ return;
203
+ }
204
+ }
205
+ triggerUpload(dropped);
206
+ };
207
+ const handleNativeChange = (e) => {
208
+ const selected = Array.from(e.target.files ?? []);
209
+ e.target.value = '';
210
+ const limit = maxFiles ?? 1;
211
+ if (selected.length + allFiles.length > limit) {
212
+ setForbiddenReason('multiple');
213
+ onForbidden?.('multiple');
214
+ return;
215
+ }
216
+ for (const f of selected) {
217
+ const result = validatePickedFile(f, { accept: accept, maxSize });
218
+ if (!result.ok) {
219
+ setForbiddenReason(result.reason);
220
+ onForbidden?.(result.reason);
221
+ return;
222
+ }
223
+ }
224
+ setForbiddenReason(null);
225
+ triggerUpload(selected);
226
+ };
227
+ const handleRemoveClick = (e) => {
228
+ e.preventDefault();
229
+ e.stopPropagation();
230
+ onRemove?.();
231
+ };
232
+ const renderIdle = () => {
233
+ const idleIconName = isSquareAny ? DEFAULT_ICONS.idleSquare : DEFAULT_ICONS.idleRectangle;
234
+ const IconCmp = iconMap[idleIconName];
235
+ const tone = effectiveState === 'disabled'
236
+ ? 'text-fds-gray-50 dark:text-fds-gray-50'
237
+ : 'text-fds-gray-80 dark:text-fds-gray-20';
238
+ if (isSquareLg) {
239
+ return (_jsxs(_Fragment, { children: [_jsx(IconCmp, { className: cn('w-[40px] h-[40px]', tone), "aria-hidden": true, "data-test-id": `${dataTestId}-idle-icon` }), _jsx("span", { className: cn('text-fds-base font-fds-regular leading-fds-body text-center', tone), "data-test-id": `${dataTestId}-idle-compact`, children: t(mergedLabels.idleDragDrop) })] }));
240
+ }
241
+ if (!isSquare) {
242
+ return (_jsxs(_Fragment, { children: [_jsx(IconCmp, { size: "md", className: cn('shrink-0 rtl:scale-x-[-1]', tone), "aria-hidden": true, "data-test-id": `${dataTestId}-idle-icon` }), _jsxs("div", { className: "flex min-w-0 flex-col gap-fds-xs text-start", children: [_jsx("span", { className: cn('w-[130px] text-fds-sm font-fds-regular leading-fds-body', tone), "data-test-id": `${dataTestId}-idle-title`, children: t(mergedLabels.idleTitle) }), _jsx("span", { className: cn('w-[132px] text-fds-xs font-fds-bold leading-fds-body', tone), "data-test-id": `${dataTestId}-idle-subtitle`, children: t(mergedLabels.idleSubtitle) })] })] }));
243
+ }
244
+ return (_jsxs(_Fragment, { children: [_jsx(IconCmp, { className: cn('w-[18.67px] h-[18.67px]', tone), "aria-hidden": true, "data-test-id": `${dataTestId}-idle-icon` }), _jsx("span", { className: cn('w-12 text-fds-base font-fds-regular leading-fds-body', tone), "data-test-id": `${dataTestId}-idle-compact`, children: t(mergedLabels.idleCompact) })] }));
245
+ };
246
+ const renderForbidden = () => {
247
+ const IconCmp = iconMap[DEFAULT_ICONS.forbidden];
248
+ if (!isSquareAny) {
249
+ return (_jsxs(_Fragment, { children: [_jsx(IconCmp, { size: "md", className: "shrink-0 text-fds-red-30", "aria-hidden": true, "data-test-id": `${dataTestId}-forbidden-icon` }), _jsxs("div", { className: "flex min-w-0 flex-col gap-fds-xs text-start", "aria-live": "polite", children: [_jsx("span", { className: "w-[130px] text-fds-sm font-fds-regular leading-fds-body text-fds-red-30", "data-test-id": `${dataTestId}-forbidden-title`, children: t(fbCopy?.title ?? '') }), _jsx("span", { className: "w-[132px] text-fds-xs font-fds-bold leading-fds-body text-fds-red-30", "data-test-id": `${dataTestId}-forbidden-subtitle`, children: t(fbCopy?.subtitle ?? '') })] })] }));
250
+ }
251
+ return (_jsxs(_Fragment, { children: [_jsx(IconCmp, { size: "lg", className: "text-fds-red-30", "aria-hidden": true, "data-test-id": `${dataTestId}-forbidden-icon` }), _jsx("span", { className: "text-fds-base font-fds-regular leading-fds-body text-fds-red-30", "data-test-id": `${dataTestId}-forbidden-compact`, children: t(mergedLabels.idleCompact) })] }));
252
+ };
253
+ const renderUploading = () => {
254
+ const SpinnerIcon = iconMap[DEFAULT_ICONS.uploading];
255
+ if (uploadingStyle === 'spinner') {
256
+ return isSquareLg ? (_jsx(SpinnerIcon, { className: "w-10 h-10 animate-spin text-fds-blue-30 rtl:direction-[reverse]", role: "status", "aria-label": t(mergedLabels.uploading), "data-test-id": `${dataTestId}-uploading-indicator` })) : (_jsx(SpinnerIcon, { size: "lg", role: "status", "aria-label": t(mergedLabels.uploading), className: "animate-spin text-fds-blue-30 rtl:direction-[reverse]", "data-test-id": `${dataTestId}-uploading-indicator` }));
257
+ }
258
+ return (_jsxs("div", { className: "flex w-full flex-col gap-fds-sm", "data-test-id": `${dataTestId}-uploading-indicator`, children: [_jsx("span", { className: cn('font-fds-regular leading-fds-body text-fds-gray-80 dark:text-fds-gray-20', isSquareAny ? 'w-full text-fds-base' : 'w-[67px] text-fds-sm'), children: t(mergedLabels.uploading) }), _jsx("div", { className: cn('relative h-0.5 overflow-hidden rounded-[6px] bg-fds-gray-20 dark:bg-fds-gray-70', isSquareAny ? 'w-full' : 'w-[165px]'), role: "progressbar", "aria-valuenow": uploadProgress !== null ? Math.round(uploadProgress * 100) : undefined, "aria-valuemin": uploadProgress !== null ? 0 : undefined, "aria-valuemax": uploadProgress !== null ? 100 : undefined, "aria-label": t(mergedLabels.uploading), children: _jsx("div", { className: cn('absolute inset-y-0 start-0 rounded-[6px] bg-fds-green-30 upload-progress-bar', uploadProgress === null
259
+ ? 'w-1/2 animate-[uploading-progress_1.4s_ease-in-out_infinite]'
260
+ : 'transition-[width] duration-200 ease-in-out'), style: uploadProgress !== null ? { width: `${uploadProgress * 100}%` } : undefined }) })] }));
261
+ };
262
+ const renderFilled = (tone) => {
263
+ const tokenColor = tone === 'success'
264
+ ? 'text-fds-blue-30'
265
+ : tone === 'error'
266
+ ? 'text-fds-red-30'
267
+ : 'text-fds-gray-30 dark:text-fds-gray-50';
268
+ const accent = tone === 'success'
269
+ ? 'text-fds-green-30'
270
+ : tone === 'error'
271
+ ? 'text-fds-red-30'
272
+ : 'text-fds-gray-30 dark:text-fds-gray-50';
273
+ const StatusIcon = iconMap[tone === 'error' ? DEFAULT_ICONS.error : DEFAULT_ICONS.success];
274
+ const RemoveIcon = iconMap[DEFAULT_ICONS.remove];
275
+ const { display, tooltip } = buildFileLabel(allFiles, isSquareAny);
276
+ // square-lg error: special layout with large icon, truncated filenames + tooltip, and error text block
277
+ if (isSquareLg && tone === 'error') {
278
+ return (_jsxs(_Fragment, { children: [_jsx(StatusIcon, { className: "w-10 h-10 shrink-0 text-fds-red-30", "aria-hidden": true, "data-test-id": `${dataTestId}-status-icon` }), _jsx("span", { className: "w-full truncate text-center text-fds-xs font-fds-regular leading-fds-body text-fds-blue-30 cursor-default", title: tooltip, "data-test-id": `${dataTestId}-filename`, children: display }), _jsxs("div", { className: "flex w-full flex-col items-center gap-fds-xs text-center", "aria-live": "polite", children: [_jsx("span", { className: "text-fds-h6 font-fds-bold leading-fds-title text-fds-gray-80 dark:text-fds-gray-20", children: t('Error') }), _jsx("span", { className: "text-fds-xs font-fds-regular leading-fds-body text-fds-gray-80 dark:text-fds-gray-20", children: t('We were unable to read your information') }), _jsx("span", { className: "pointer-events-auto cursor-pointer! text-fds-xs font-fds-regular leading-fds-body text-fds-blue-30 underline", children: t('Try again by selecting another file') })] })] }));
279
+ }
280
+ const statusIconNode = tone === 'success' ? (isSquareAny
281
+ ? _jsx(StatusIcon, { size: "lg", className: cn('shrink-0', accent), "aria-hidden": true, "data-test-id": `${dataTestId}-status-icon` })
282
+ : _jsx(StatusIcon, { className: cn('shrink-0 w-[13.33px] h-[13.33px]', accent), "aria-hidden": true, "data-test-id": `${dataTestId}-status-icon` })) : tone === 'error' ? (isSquareAny
283
+ ? _jsx(StatusIcon, { size: "lg", className: cn('shrink-0', accent), "aria-hidden": true, "data-test-id": `${dataTestId}-status-icon` })
284
+ : _jsx(StatusIcon, { size: "sm", className: cn('shrink-0', accent), "aria-hidden": true, "data-test-id": `${dataTestId}-status-icon` })) : tone === 'disabled' ? (isSquareAny
285
+ ? _jsx(StatusIcon, { size: "lg", className: cn('shrink-0', accent), "aria-hidden": true, "data-test-id": `${dataTestId}-status-icon` })
286
+ : _jsx(StatusIcon, { size: "sm", className: cn('shrink-0', accent), "aria-hidden": true, "data-test-id": `${dataTestId}-status-icon` })) : (_jsx(StatusIcon, { size: isSquareAny ? 'md' : 'xs', className: cn('shrink-0', accent), "aria-hidden": true, "data-test-id": `${dataTestId}-status-icon` }));
287
+ return (_jsxs(_Fragment, { children: [statusIconNode, _jsx("span", { className: cn('truncate font-fds-regular leading-fds-body', isSquareAny && (tone === 'error' || tone === 'disabled') ? 'text-fds-base' : 'text-fds-sm', !isSquareAny && !isFillContainer && 'min-w-0 flex-1', !isSquareAny && isFillContainer && 'min-w-0', tokenColor, isSquareAny && 'w-full text-center'), title: tooltip, "data-test-id": `${dataTestId}-filename`, children: display }), !isSquareAny && hasFiles && tone !== 'disabled' && (_jsx("button", { type: "button", onClick: handleRemoveClick, "aria-label": t('Remove all files'), "data-test-id": `${dataTestId}-remove`, className: cn('inline-flex size-6 shrink-0 items-center justify-center rounded-fds-sm focus-visible:outline-none focus-visible:ring-2 cursor-pointer text-fds-red-30 hover:bg-fds-red-05 focus-visible:ring-fds-red-30 dark:hover:bg-fds-red-30/10', !isFillContainer && 'ms-auto'), children: _jsx(RemoveIcon, { size: "sm", "aria-hidden": true }) }))] }));
288
+ };
289
+ let body = null;
290
+ switch (effectiveState) {
291
+ case 'default':
292
+ body = renderIdle();
293
+ break;
294
+ case 'disabled':
295
+ body = hasFiles ? renderFilled('disabled') : renderIdle();
296
+ break;
297
+ case 'forbidden':
298
+ body = renderForbidden();
299
+ break;
300
+ case 'uploading':
301
+ case 'uploading-spinner':
302
+ body = renderUploading();
303
+ break;
304
+ case 'success':
305
+ body = renderFilled('success');
306
+ break;
307
+ case 'error':
308
+ body = (_jsx("div", { role: "alert", className: "contents", children: renderFilled('error') }));
309
+ break;
310
+ }
311
+ const isFilled = effectiveState === 'uploading' ||
312
+ effectiveState === 'uploading-spinner' ||
313
+ effectiveState === 'success' ||
314
+ effectiveState === 'error' ||
315
+ (effectiveState === 'disabled' && hasFiles);
316
+ const frameSize = isSquareAny
317
+ ? ''
318
+ : isFillContainer
319
+ ? (isFilled ? 'h-full w-full justify-center' : 'h-full w-full')
320
+ : 'h-[69px] w-[198px]';
321
+ return (_jsxs("label", { ref: ref, htmlFor: inputId, "data-test-id": dataTestId, "data-state": effectiveState, "data-variant": variant, "data-filled": hasFiles ? 'true' : 'false', dir: dir, "aria-label": ariaLabel ?? t(mergedLabels.idleTitle), "aria-disabled": isDisabled || undefined, "aria-busy": (effectiveState === 'uploading' || effectiveState === 'uploading-spinner') || undefined, className: cn(uploadVariants({ variant, state: effectiveState }), effectiveState === 'default' && (isSquareLg ? 'upload-dash-fluid' :
322
+ isSquare ? 'upload-dash-4-2-square' :
323
+ isFillContainer ? 'upload-dash-fluid' : 'upload-dash-4-2'), effectiveState === 'forbidden' && (isSquareLg ? 'upload-dash-fluid-red' :
324
+ isSquare ? 'h-[100px] gap-[4px] upload-dash-4-4' :
325
+ isFillContainer ? 'upload-dash-fluid-red' : 'upload-dash-4-2-red'), (effectiveState === 'uploading' || effectiveState === 'uploading-spinner') && isSquare && 'h-[100px] p-[11px]!', (effectiveState === 'uploading' || effectiveState === 'uploading-spinner') && isSquareLg && 'h-[238px]', effectiveState === 'success' && isSquare && 'h-[100px] gap-[4px]', effectiveState === 'error' && isSquare && 'h-[100px] gap-[4px] p-[11px]!',
326
+ // square-lg error: gray border (Figma spec) + allow retry clicks
327
+ effectiveState === 'error' && isSquareLg && 'border-fds-gray-30! dark:border-fds-gray-70! cursor-pointer!', effectiveState === 'disabled' && isSquare && hasFiles && 'h-[100px] gap-[4px] p-[11px]!', effectiveState === 'uploading-spinner' && !isSquareAny && 'py-3.5!', frameSize, className), onDragEnter: handleDragEnter, onDragOver: (e) => e.preventDefault(), onDragLeave: handleDragLeave, onDrop: handleDrop, ...rest, children: [_jsx("input", { id: inputId, type: "file", accept: acceptAttr, multiple: isMultiple, disabled: isDisabled, className: "sr-only", onChange: handleNativeChange, "data-test-id": `${dataTestId}-input` }), body] }));
328
+ });
329
+ export { uploadVariants };
330
+ export const SingleFileUpload = Upload;
package/dist/esm/index.js CHANGED
@@ -2,3 +2,6 @@
2
2
  export { cn } from './lib/utils';
3
3
  export { useStableId } from './lib/use-stable-id';
4
4
  export { iconMap, renderInputIcon } from './lib/icon-utils';
5
+ // Components
6
+ export { Upload, uploadVariants, SingleFileUpload } from './components/upload';
7
+ export { MultipleFilesUpload } from './components/multiple-files-upload';