@transferwise/components 46.97.5 → 46.98.1
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/build/alert/Alert.js +8 -0
- package/build/alert/Alert.js.map +1 -1
- package/build/alert/Alert.mjs +8 -0
- package/build/alert/Alert.mjs.map +1 -1
- package/build/common/closeButton/CloseButton.js +3 -1
- package/build/common/closeButton/CloseButton.js.map +1 -1
- package/build/common/closeButton/CloseButton.mjs +3 -1
- package/build/common/closeButton/CloseButton.mjs.map +1 -1
- package/build/dateInput/DateInput.js +4 -4
- package/build/dateInput/DateInput.js.map +1 -1
- package/build/dateInput/DateInput.mjs +4 -4
- package/build/dateInput/DateInput.mjs.map +1 -1
- package/build/dateLookup/DateLookup.js +4 -4
- package/build/dateLookup/DateLookup.js.map +1 -1
- package/build/dateLookup/DateLookup.mjs +4 -4
- package/build/dateLookup/DateLookup.mjs.map +1 -1
- package/build/dateLookup/dayCalendar/table/DayCalendarTable.js +3 -3
- package/build/dateLookup/dayCalendar/table/DayCalendarTable.js.map +1 -1
- package/build/dateLookup/dayCalendar/table/DayCalendarTable.mjs +3 -3
- package/build/dateLookup/dayCalendar/table/DayCalendarTable.mjs.map +1 -1
- package/build/i18n/cs.json +3 -2
- package/build/i18n/cs.json.js +3 -2
- package/build/i18n/cs.json.js.map +1 -1
- package/build/i18n/cs.json.mjs +3 -2
- package/build/i18n/cs.json.mjs.map +1 -1
- package/build/i18n/de.json +3 -2
- package/build/i18n/de.json.js +3 -2
- package/build/i18n/de.json.js.map +1 -1
- package/build/i18n/de.json.mjs +3 -2
- package/build/i18n/de.json.mjs.map +1 -1
- package/build/i18n/en.json +3 -2
- package/build/i18n/en.json.js +3 -2
- package/build/i18n/en.json.js.map +1 -1
- package/build/i18n/en.json.mjs +3 -2
- package/build/i18n/en.json.mjs.map +1 -1
- package/build/i18n/es.json +3 -2
- package/build/i18n/es.json.js +3 -2
- package/build/i18n/es.json.js.map +1 -1
- package/build/i18n/es.json.mjs +3 -2
- package/build/i18n/es.json.mjs.map +1 -1
- package/build/i18n/fr.json +3 -2
- package/build/i18n/fr.json.js +3 -2
- package/build/i18n/fr.json.js.map +1 -1
- package/build/i18n/fr.json.mjs +3 -2
- package/build/i18n/fr.json.mjs.map +1 -1
- package/build/i18n/hu.json +3 -2
- package/build/i18n/hu.json.js +3 -2
- package/build/i18n/hu.json.js.map +1 -1
- package/build/i18n/hu.json.mjs +3 -2
- package/build/i18n/hu.json.mjs.map +1 -1
- package/build/i18n/id.json +3 -2
- package/build/i18n/id.json.js +3 -2
- package/build/i18n/id.json.js.map +1 -1
- package/build/i18n/id.json.mjs +3 -2
- package/build/i18n/id.json.mjs.map +1 -1
- package/build/i18n/it.json +3 -2
- package/build/i18n/it.json.js +3 -2
- package/build/i18n/it.json.js.map +1 -1
- package/build/i18n/it.json.mjs +3 -2
- package/build/i18n/it.json.mjs.map +1 -1
- package/build/i18n/ja.json +3 -2
- package/build/i18n/ja.json.js +3 -2
- package/build/i18n/ja.json.js.map +1 -1
- package/build/i18n/ja.json.mjs +3 -2
- package/build/i18n/ja.json.mjs.map +1 -1
- package/build/i18n/nl.json +6 -5
- package/build/i18n/pl.json +3 -2
- package/build/i18n/pl.json.js +3 -2
- package/build/i18n/pl.json.js.map +1 -1
- package/build/i18n/pl.json.mjs +3 -2
- package/build/i18n/pl.json.mjs.map +1 -1
- package/build/i18n/pt.json +3 -2
- package/build/i18n/pt.json.js +3 -2
- package/build/i18n/pt.json.js.map +1 -1
- package/build/i18n/pt.json.mjs +3 -2
- package/build/i18n/pt.json.mjs.map +1 -1
- package/build/i18n/ro.json +3 -2
- package/build/i18n/ro.json.js +3 -2
- package/build/i18n/ro.json.js.map +1 -1
- package/build/i18n/ro.json.mjs +3 -2
- package/build/i18n/ro.json.mjs.map +1 -1
- package/build/i18n/ru.json +3 -2
- package/build/i18n/ru.json.js +3 -2
- package/build/i18n/ru.json.js.map +1 -1
- package/build/i18n/ru.json.mjs +3 -2
- package/build/i18n/ru.json.mjs.map +1 -1
- package/build/i18n/th.json +3 -2
- package/build/i18n/th.json.js +3 -2
- package/build/i18n/th.json.js.map +1 -1
- package/build/i18n/th.json.mjs +3 -2
- package/build/i18n/th.json.mjs.map +1 -1
- package/build/i18n/tr.json +3 -2
- package/build/i18n/tr.json.js +3 -2
- package/build/i18n/tr.json.js.map +1 -1
- package/build/i18n/tr.json.mjs +3 -2
- package/build/i18n/tr.json.mjs.map +1 -1
- package/build/i18n/zh-CN.json +3 -2
- package/build/i18n/zh-CN.json.js +3 -2
- package/build/i18n/zh-CN.json.js.map +1 -1
- package/build/i18n/zh-CN.json.mjs +3 -2
- package/build/i18n/zh-CN.json.mjs.map +1 -1
- package/build/i18n/zh-HK.json +3 -2
- package/build/i18n/zh-HK.json.js +3 -2
- package/build/i18n/zh-HK.json.js.map +1 -1
- package/build/i18n/zh-HK.json.mjs +3 -2
- package/build/i18n/zh-HK.json.mjs.map +1 -1
- package/build/image/Image.js +9 -10
- package/build/image/Image.js.map +1 -1
- package/build/image/Image.mjs +11 -11
- package/build/image/Image.mjs.map +1 -1
- package/build/index.js +0 -2
- package/build/index.js.map +1 -1
- package/build/index.mjs +0 -1
- package/build/index.mjs.map +1 -1
- package/build/main.css +16 -45
- package/build/moneyInput/MoneyInput.js +4 -8
- package/build/moneyInput/MoneyInput.js.map +1 -1
- package/build/moneyInput/MoneyInput.messages.js +3 -0
- package/build/moneyInput/MoneyInput.messages.js.map +1 -1
- package/build/moneyInput/MoneyInput.messages.mjs +3 -0
- package/build/moneyInput/MoneyInput.messages.mjs.map +1 -1
- package/build/moneyInput/MoneyInput.mjs +4 -8
- package/build/moneyInput/MoneyInput.mjs.map +1 -1
- package/build/phoneNumberInput/PhoneNumberInput.js +36 -2
- package/build/phoneNumberInput/PhoneNumberInput.js.map +1 -1
- package/build/phoneNumberInput/PhoneNumberInput.messages.js +6 -0
- package/build/phoneNumberInput/PhoneNumberInput.messages.js.map +1 -1
- package/build/phoneNumberInput/PhoneNumberInput.messages.mjs +6 -0
- package/build/phoneNumberInput/PhoneNumberInput.messages.mjs.map +1 -1
- package/build/phoneNumberInput/PhoneNumberInput.mjs +36 -2
- package/build/phoneNumberInput/PhoneNumberInput.mjs.map +1 -1
- package/build/snackbar/Snackbar.js +1 -1
- package/build/snackbar/Snackbar.js.map +1 -1
- package/build/snackbar/Snackbar.mjs +1 -1
- package/build/snackbar/Snackbar.mjs.map +1 -1
- package/build/styles/circularButton/CircularButton.css +1 -0
- package/build/styles/dateInput/DateInput.css +13 -0
- package/build/styles/main.css +16 -45
- package/build/styles/uploadInput/uploadItem/UploadItem.css +2 -1
- package/build/tabs/Tabs.js +3 -3
- package/build/tabs/Tabs.js.map +1 -1
- package/build/tabs/Tabs.mjs +3 -3
- package/build/tabs/Tabs.mjs.map +1 -1
- package/build/test-utils/assets/apple-pay-logo.svg +84 -0
- package/build/typeahead/Typeahead.js +2 -2
- package/build/typeahead/Typeahead.js.map +1 -1
- package/build/typeahead/Typeahead.mjs +2 -2
- package/build/typeahead/Typeahead.mjs.map +1 -1
- package/build/typeahead/typeaheadInput/TypeaheadInput.js +2 -2
- package/build/typeahead/typeaheadInput/TypeaheadInput.js.map +1 -1
- package/build/typeahead/typeaheadInput/TypeaheadInput.mjs +2 -2
- package/build/typeahead/typeaheadInput/TypeaheadInput.mjs.map +1 -1
- package/build/types/alert/Alert.d.ts.map +1 -1
- package/build/types/common/closeButton/CloseButton.d.ts +2 -0
- package/build/types/common/closeButton/CloseButton.d.ts.map +1 -1
- package/build/types/image/Image.d.ts +0 -1
- package/build/types/image/Image.d.ts.map +1 -1
- package/build/types/index.d.ts +0 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/moneyInput/MoneyInput.d.ts.map +1 -1
- package/build/types/moneyInput/MoneyInput.messages.d.ts +5 -0
- package/build/types/moneyInput/MoneyInput.messages.d.ts.map +1 -1
- package/build/types/phoneNumberInput/PhoneNumberInput.d.ts.map +1 -1
- package/build/types/phoneNumberInput/PhoneNumberInput.messages.d.ts +8 -0
- package/build/types/phoneNumberInput/PhoneNumberInput.messages.d.ts.map +1 -1
- package/build/types/test-utils/fake-data.d.ts +2 -0
- package/build/types/test-utils/fake-data.d.ts.map +1 -1
- package/build/types/test-utils/index.d.ts +6 -4
- package/build/types/test-utils/index.d.ts.map +1 -1
- package/build/types/upload/Upload.d.ts +1 -2
- package/build/types/upload/Upload.d.ts.map +1 -1
- package/build/types/upload/steps/processingStep/processingStep.d.ts +1 -3
- package/build/types/upload/steps/processingStep/processingStep.d.ts.map +1 -1
- package/build/types/uploadInput/UploadInput.d.ts.map +1 -1
- package/build/types/uploadInput/uploadItem/UploadItem.d.ts +1 -1
- package/build/types/uploadInput/uploadItem/UploadItem.d.ts.map +1 -1
- package/build/types/withDisplayFormat/WithDisplayFormat.d.ts.map +1 -1
- package/build/upload/Upload.js +29 -45
- package/build/upload/Upload.js.map +1 -1
- package/build/upload/Upload.mjs +29 -45
- package/build/upload/Upload.mjs.map +1 -1
- package/build/upload/steps/processingStep/processingStep.js +1 -3
- package/build/upload/steps/processingStep/processingStep.js.map +1 -1
- package/build/upload/steps/processingStep/processingStep.mjs +1 -3
- package/build/upload/steps/processingStep/processingStep.mjs.map +1 -1
- package/build/upload/steps/uploadImageStep/uploadImageStep.js +1 -1
- package/build/upload/steps/uploadImageStep/uploadImageStep.js.map +1 -1
- package/build/upload/steps/uploadImageStep/uploadImageStep.mjs +1 -1
- package/build/upload/steps/uploadImageStep/uploadImageStep.mjs.map +1 -1
- package/build/uploadInput/UploadInput.js +54 -6
- package/build/uploadInput/UploadInput.js.map +1 -1
- package/build/uploadInput/UploadInput.mjs +54 -6
- package/build/uploadInput/UploadInput.mjs.map +1 -1
- package/build/uploadInput/uploadItem/UploadItem.js +12 -6
- package/build/uploadInput/uploadItem/UploadItem.js.map +1 -1
- package/build/uploadInput/uploadItem/UploadItem.mjs +12 -6
- package/build/uploadInput/uploadItem/UploadItem.mjs.map +1 -1
- package/build/withDisplayFormat/WithDisplayFormat.js +3 -2
- package/build/withDisplayFormat/WithDisplayFormat.js.map +1 -1
- package/build/withDisplayFormat/WithDisplayFormat.mjs +3 -2
- package/build/withDisplayFormat/WithDisplayFormat.mjs.map +1 -1
- package/package.json +14 -17
- package/src/alert/Alert.spec.tsx +11 -0
- package/src/alert/Alert.story.tsx +23 -9
- package/src/alert/Alert.tsx +14 -1
- package/src/circularButton/CircularButton.css +1 -0
- package/src/circularButton/CircularButton.less +1 -0
- package/src/circularButton/CircularButton.tests.story.tsx +23 -0
- package/src/common/closeButton/CloseButton.spec.tsx +13 -1
- package/src/common/closeButton/CloseButton.tsx +3 -0
- package/src/dateInput/DateInput.css +13 -0
- package/src/dateInput/DateInput.less +20 -0
- package/src/dateInput/DateInput.tests.story.tsx +14 -3
- package/src/dateInput/DateInput.tsx +4 -4
- package/src/i18n/cs.json +3 -2
- package/src/i18n/de.json +3 -2
- package/src/i18n/en.json +3 -2
- package/src/i18n/es.json +3 -2
- package/src/i18n/fr.json +3 -2
- package/src/i18n/hu.json +3 -2
- package/src/i18n/id.json +3 -2
- package/src/i18n/it.json +3 -2
- package/src/i18n/ja.json +3 -2
- package/src/i18n/nl.json +6 -5
- package/src/i18n/pl.json +3 -2
- package/src/i18n/pt.json +3 -2
- package/src/i18n/ro.json +3 -2
- package/src/i18n/ru.json +3 -2
- package/src/i18n/th.json +3 -2
- package/src/i18n/tr.json +3 -2
- package/src/i18n/zh-CN.json +3 -2
- package/src/i18n/zh-HK.json +3 -2
- package/src/image/Image.spec.tsx +3 -3
- package/src/image/Image.tsx +10 -12
- package/src/index.ts +0 -2
- package/src/legacylistItem/LegacyListItem.story.tsx +5 -5
- package/src/legacylistItem/LegacyListItem.tests.story.tsx +6 -6
- package/src/main.css +16 -45
- package/src/main.less +0 -1
- package/src/moneyInput/MoneyInput.messages.ts +5 -0
- package/src/moneyInput/MoneyInput.spec.tsx +42 -5
- package/src/moneyInput/MoneyInput.story.tsx +11 -2
- package/src/moneyInput/MoneyInput.tsx +5 -7
- package/src/phoneNumberInput/PhoneNumberInput.messages.ts +8 -0
- package/src/phoneNumberInput/PhoneNumberInput.spec.tsx +77 -43
- package/src/phoneNumberInput/PhoneNumberInput.tsx +34 -2
- package/src/promoCard/__snapshots__/PromoCard.spec.tsx.snap +1 -0
- package/src/promoCard/__snapshots__/PromoCardGroup.spec.tsx.snap +2 -0
- package/src/ssr.spec.tsx +0 -1
- package/src/test-utils/assets/apple-pay-logo.svg +84 -0
- package/src/test-utils/fake-data.ts +5 -0
- package/src/test-utils/jest.setup.ts +0 -4
- package/src/typeahead/Typeahead.spec.tsx +182 -0
- package/src/typeahead/typeaheadInput/TypeaheadInput.spec.tsx +103 -0
- package/src/typeahead/util/highlight.spec.tsx +43 -0
- package/src/upload/Upload.spec.tsx +63 -0
- package/src/upload/Upload.story.tsx +0 -51
- package/src/upload/Upload.tests.story.tsx +93 -0
- package/src/upload/Upload.tsx +28 -49
- package/src/upload/steps/processingStep/processingStep.tsx +2 -7
- package/src/uploadInput/UploadInput.tsx +74 -10
- package/src/uploadInput/uploadItem/UploadItem.css +2 -1
- package/src/uploadInput/uploadItem/UploadItem.less +1 -1
- package/src/uploadInput/uploadItem/UploadItem.tsx +11 -6
- package/src/withDisplayFormat/WithDisplayFormat.spec.js +11 -15
- package/src/withDisplayFormat/WithDisplayFormat.tsx +3 -2
- package/build/selectOption/SelectOption.js +0 -131
- package/build/selectOption/SelectOption.js.map +0 -1
- package/build/selectOption/SelectOption.messages.js +0 -17
- package/build/selectOption/SelectOption.messages.js.map +0 -1
- package/build/selectOption/SelectOption.messages.mjs +0 -13
- package/build/selectOption/SelectOption.messages.mjs.map +0 -1
- package/build/selectOption/SelectOption.mjs +0 -127
- package/build/selectOption/SelectOption.mjs.map +0 -1
- package/build/styles/selectOption/SelectOption.css +0 -44
- package/build/types/selectOption/SelectOption.d.ts +0 -21
- package/build/types/selectOption/SelectOption.d.ts.map +0 -1
- package/build/types/selectOption/SelectOption.messages.d.ts +0 -12
- package/build/types/selectOption/SelectOption.messages.d.ts.map +0 -1
- package/build/types/selectOption/index.d.ts +0 -3
- package/build/types/selectOption/index.d.ts.map +0 -1
- package/src/selectOption/SelectOption.css +0 -44
- package/src/selectOption/SelectOption.less +0 -40
- package/src/selectOption/SelectOption.messages.ts +0 -12
- package/src/selectOption/SelectOption.spec.tsx +0 -83
- package/src/selectOption/SelectOption.story.tsx +0 -277
- package/src/selectOption/SelectOption.tsx +0 -151
- package/src/selectOption/index.ts +0 -2
- package/src/typeahead/Typeahead.rtl.spec.tsx +0 -54
- package/src/typeahead/Typeahead.spec.js +0 -404
- package/src/typeahead/typeaheadInput/TypeaheadInput.spec.js +0 -74
- package/src/typeahead/typeaheadOption/TypeaheadOption.spec.js +0 -75
- package/src/typeahead/util/highlight.spec.js +0 -34
|
@@ -75,6 +75,7 @@ const UploadInput = ({
|
|
|
75
75
|
nonLabelable: true
|
|
76
76
|
});
|
|
77
77
|
const [markedFileForDelete, setMarkedFileForDelete] = useState(null);
|
|
78
|
+
const [lastAttemptedDeleteId, setLastAttemptedDeleteId] = useState(null);
|
|
78
79
|
const [mounted, setMounted] = useState(false);
|
|
79
80
|
const {
|
|
80
81
|
formatMessage
|
|
@@ -223,6 +224,13 @@ const UploadInput = ({
|
|
|
223
224
|
});
|
|
224
225
|
const filesCount = fileRefs.length;
|
|
225
226
|
let next = uploadInputRef.current;
|
|
227
|
+
let focusTarget = 'button';
|
|
228
|
+
// If there will be no files left after deletion, focus the upload button
|
|
229
|
+
if (filesCount === 1) {
|
|
230
|
+
next = uploadInputRef.current;
|
|
231
|
+
setNextFocusable(next);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
226
234
|
if (filesCount > 1) {
|
|
227
235
|
const currentFileIndex = fileRefs.findIndex(file => file?.id === fileId);
|
|
228
236
|
const currentFileId = fileRefs?.[currentFileIndex]?.id;
|
|
@@ -233,14 +241,49 @@ const UploadInput = ({
|
|
|
233
241
|
} else {
|
|
234
242
|
next = fileRefs[currentFileIndex + 1];
|
|
235
243
|
}
|
|
244
|
+
// If next is an UploadItemRef, check if it has a URL (succeeded)
|
|
245
|
+
if (next && 'status' in next) {
|
|
246
|
+
// Find the file object for this ref
|
|
247
|
+
const fileObj = uploadedFiles.find(f => f.id === next?.id);
|
|
248
|
+
if (fileObj && (fileObj.status === Status.SUCCEEDED || fileObj.status === Status.DONE) && fileObj.url) {
|
|
249
|
+
focusTarget = 'link';
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
setNextFocusable(() => {
|
|
253
|
+
if (next && typeof next.focus === 'function') {
|
|
254
|
+
return {
|
|
255
|
+
ref: next,
|
|
256
|
+
target: focusTarget
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
return next;
|
|
260
|
+
});
|
|
236
261
|
}
|
|
237
|
-
setNextFocusable(next);
|
|
238
262
|
};
|
|
239
263
|
const handleRefocus = () => {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
264
|
+
const focusTarget = nextFocusable;
|
|
265
|
+
if (lastAttemptedDeleteId) {
|
|
266
|
+
setLastAttemptedDeleteId(null);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (focusTarget) {
|
|
270
|
+
// If there are no files left, focus the upload button
|
|
271
|
+
if (uploadedFiles.length === 0 && uploadInputRef.current && typeof uploadInputRef.current.focus === 'function') {
|
|
272
|
+
setTimeout(() => {
|
|
273
|
+
uploadInputRef.current.focus();
|
|
274
|
+
}, 0);
|
|
275
|
+
} else if (typeof focusTarget === 'object' && 'ref' in focusTarget && focusTarget.ref && typeof focusTarget.ref.focus === 'function') {
|
|
276
|
+
setTimeout(() => {
|
|
277
|
+
if (focusTarget.ref && typeof focusTarget.ref.focus === 'function') {
|
|
278
|
+
// @ts-expect-error: focus may not exist on all possible ref types, but is safe here
|
|
279
|
+
focusTarget.ref.focus(focusTarget.target);
|
|
280
|
+
}
|
|
281
|
+
}, 0);
|
|
282
|
+
} else if (focusTarget && typeof focusTarget.focus === 'function') {
|
|
283
|
+
setTimeout(() => {
|
|
284
|
+
focusTarget.focus();
|
|
285
|
+
}, 0);
|
|
286
|
+
}
|
|
244
287
|
}
|
|
245
288
|
};
|
|
246
289
|
return /*#__PURE__*/jsxs(Fragment, {
|
|
@@ -265,9 +308,13 @@ const UploadInput = ({
|
|
|
265
308
|
singleFileUpload: !multiple,
|
|
266
309
|
canDelete: (!!onDeleteFile || file.status === Status.FAILED) && (!file.status || !PROGRESS_STATUSES.has(file.status)),
|
|
267
310
|
onDelete: file.status === Status.FAILED ? async () => {
|
|
311
|
+
setLastAttemptedDeleteId(file.id);
|
|
268
312
|
await removeFile(file);
|
|
269
313
|
handleRefocus();
|
|
270
|
-
} : () =>
|
|
314
|
+
} : () => {
|
|
315
|
+
setLastAttemptedDeleteId(file.id);
|
|
316
|
+
setMarkedFileForDelete(file);
|
|
317
|
+
},
|
|
271
318
|
onDownload: onDownload,
|
|
272
319
|
onFocus: () => handleFocus(file.id)
|
|
273
320
|
}, file.id))
|
|
@@ -308,6 +355,7 @@ const UploadInput = ({
|
|
|
308
355
|
void removeFile(markedFileForDelete);
|
|
309
356
|
}
|
|
310
357
|
setMarkedFileForDelete(null);
|
|
358
|
+
setLastAttemptedDeleteId(null);
|
|
311
359
|
},
|
|
312
360
|
children: deleteConfirm?.confirmText || formatMessage(MESSAGES.deleteModalConfirmButtonText)
|
|
313
361
|
})]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UploadInput.mjs","sources":["../../src/uploadInput/UploadInput.tsx"],"sourcesContent":["import { clsx } from 'clsx';\nimport { useEffect, useRef, useState } from 'react';\nimport { useIntl } from 'react-intl';\n\nimport Button from '../button';\nimport { CommonProps, ControlType, Priority, Status } from '../common';\nimport { useInputAttributes } from '../inputs/contexts';\nimport Modal from '../modal';\nimport { isSizeValid } from '../upload/utils/isSizeValid';\nimport { isTypeValid } from '../upload/utils/isTypeValid';\n\nimport MESSAGES from './UploadInput.messages';\nimport { UploadedFile, UploadError, UploadResponse } from './types';\nimport UploadButton, { UploadButtonProps } from './uploadButton/UploadButton';\nimport { DEFAULT_SIZE_LIMIT, imageFileTypes } from './uploadButton/defaults';\nimport UploadItem, { UploadItemProps } from './uploadItem/UploadItem';\n\nexport type UploadInputProps = {\n /**\n * List of already existing, failed or in progress files\n */\n files?: readonly UploadedFile[];\n\n /**\n * The key of the file in the returned FormData object (default: file)\n */\n fileInputName?: string;\n\n /**\n * Callback that handles form submission\n *\n * @param formData\n */\n onUploadFile: (formData: FormData) => Promise<UploadResponse>;\n\n /**\n * Provide a callback if the file can be removed/deleted from the server\n * Your app is responsible for reloading the uploaded files list and updating the component to ensure that the file has in fact been deleted successfully\n *\n * @param id\n */\n onDeleteFile?: (id: string | number) => Promise<any>;\n\n /**\n * Provide a callback to trigger on validation error\n *\n * @param file\n */\n onValidationError?: (file: UploadedFile) => void;\n\n /**\n * Provide a callback to trigger on change whenever the files are updated\n *\n * @param files\n */\n onFilesChange?: (files: UploadedFile[]) => void;\n\n /**\n * Confirmation modal displayed on delete\n */\n deleteConfirm?: {\n /**\n * The title of the confirmation modal on delete\n */\n title?: string;\n\n /**\n * The body of the confirmation modal on delete\n */\n body?: React.ReactNode;\n\n /**\n * The confirm button text of the confirmation modal on delete\n */\n confirmText?: string;\n\n /**\n * The cancel button text of the confirmation modal on delete\n */\n cancelText?: string;\n };\n\n /**\n * Maximum number of files allowed, if provided, shows error below file item\n */\n maxFiles?: number;\n\n /**\n * Error message to show when the maximum number of files are uploaded already\n */\n maxFilesErrorMessage?: string;\n\n /**\n * Error message to show when files over a allowed size limit are uploaded\n */\n sizeLimitErrorMessage?: string;\n} & Pick<\n UploadButtonProps,\n 'disabled' | 'multiple' | 'fileTypes' | 'sizeLimit' | 'description' | 'id' | 'uploadButtonTitle'\n> & { onDownload?: UploadItemProps['onDownload'] } & CommonProps;\n\n/**\n * Interface representing a reference to an UploadItem component.\n * Provides a method to focus the UploadItem.\n */\ninterface UploadItemRef {\n /**\n * Focuses the UploadItem component.\n */\n focus: () => void;\n\n /**\n * Required id of the UploadItem component.\n */\n id: string | number;\n\n /**\n * Optional status of the UploadItem component.\n */\n status?: string;\n}\n\n/**\n * Generates a unique ID for a file based on its name, size, and the current timestamp\n */\nfunction generateFileId(file: File) {\n const { name, size } = file;\n const uploadTimeStamp = new Date().getTime();\n return `${name}_${size}_${uploadTimeStamp}`;\n}\n\n/**\n * The component allows users to upload files, manage the list of uploaded files,\n * and handle file validation and deletion.\n *\n * @param {UploadInputProps} props - The properties for the UploadInput component.\n *\n * @see {@link UploadInput} for further information.\n * @see {@link https://storybook.wise.design/?path=/docs/forms-uploadinput--docs|Storybook Wise Design}\n */\nconst UploadInput = ({\n files = [],\n fileInputName = 'file',\n className,\n deleteConfirm,\n disabled,\n multiple = false,\n fileTypes = imageFileTypes,\n sizeLimit = DEFAULT_SIZE_LIMIT,\n description,\n onUploadFile,\n onDeleteFile,\n onValidationError,\n onFilesChange,\n onDownload,\n maxFiles,\n maxFilesErrorMessage,\n id,\n sizeLimitErrorMessage,\n uploadButtonTitle,\n}: UploadInputProps) => {\n const inputAttributes = useInputAttributes({ nonLabelable: true });\n const [markedFileForDelete, setMarkedFileForDelete] = useState<UploadedFile | null>(null);\n const [mounted, setMounted] = useState(false);\n const { formatMessage } = useIntl();\n const uploadInputRef = useRef<HTMLInputElement | null>(null);\n let fileRefs: (HTMLDivElement | UploadItemRef | null)[] = [];\n\n const PROGRESS_STATUSES = new Set([Status.PENDING, Status.PROCESSING]);\n\n const [uploadedFiles, setUploadedFiles] = useState<readonly UploadedFile[]>(\n multiple || files.length === 0 ? files : [files[0]],\n );\n\n const uploadedFilesListReference = useRef(multiple || files.length === 0 ? files : [files[0]]);\n\n function updateFileList(updateFn: (list: readonly UploadedFile[]) => readonly UploadedFile[]) {\n setUploadedFiles(updateFn);\n uploadedFilesListReference.current = updateFn(uploadedFilesListReference.current);\n }\n\n function addFileToList(recentUploadedFile: UploadedFile) {\n updateFileList((list) => [...list, recentUploadedFile]);\n }\n\n function removeFileFromList(file: UploadedFile) {\n updateFileList((list) =>\n list.filter((fileInList) => file !== fileInList && file.id !== fileInList.id),\n );\n fileRefs = fileRefs.filter((ref) => ref && ref.id !== file.id);\n }\n\n function modifyFileInList(file: UploadedFile, updates: Partial<UploadedFile>) {\n updateFileList((list) =>\n list.map((fileInList) =>\n fileInList === file || fileInList.id === file.id ? { ...file, ...updates } : fileInList,\n ),\n );\n }\n\n const removeFile = async (file: UploadedFile) => {\n const { id, status } = file;\n fileRefs = fileRefs.filter((item) => item && item.id !== file.id);\n\n if (status === Status.FAILED) {\n removeFileFromList(file);\n return Promise.resolve();\n }\n\n if (onDeleteFile && id) {\n modifyFileInList(file, { status: Status.PROCESSING, error: undefined });\n\n return onDeleteFile(id)\n .then(() => {\n removeFileFromList(file);\n })\n .catch((error) => {\n modifyFileInList(file, { error: error as UploadError });\n });\n }\n };\n\n function handleFileUploadFailure(file: File, failureMessage: string) {\n const { name } = file;\n\n const failedUpload = {\n id: generateFileId(file),\n filename: name,\n status: Status.FAILED,\n error: failureMessage,\n };\n\n addFileToList(failedUpload);\n\n if (onValidationError) {\n onValidationError(failedUpload);\n }\n }\n\n function getNumberOfFilesUploaded() {\n const uploadInitiatedStatus = new Set([Status.SUCCEEDED, Status.PENDING]);\n const validFiles = uploadedFilesListReference.current.filter(\n (file) => file.status && uploadInitiatedStatus.has(file.status),\n );\n return validFiles.length;\n }\n\n function areMaximumFilesUploadedAlready() {\n if (!maxFiles) {\n return false;\n }\n\n const numberOfValidFiles = getNumberOfFilesUploaded();\n return numberOfValidFiles >= maxFiles;\n }\n\n const addFiles = (selectedFiles: FileList) => {\n for (let i = 0; i < selectedFiles.length; i += 1) {\n const file = selectedFiles.item(i);\n\n const formData = new FormData();\n\n if (file) {\n const allowedFileTypes = typeof fileTypes === 'string' ? fileTypes : fileTypes.join(',');\n\n if (!isTypeValid(file, allowedFileTypes)) {\n handleFileUploadFailure(file, formatMessage(MESSAGES.fileTypeNotSupported));\n continue;\n }\n\n if (!isSizeValid(file, sizeLimit * 1000)) {\n const failureMessage = sizeLimitErrorMessage || formatMessage(MESSAGES.fileIsTooLarge);\n handleFileUploadFailure(file, failureMessage);\n continue;\n }\n\n if (areMaximumFilesUploadedAlready()) {\n const failureMessage =\n maxFilesErrorMessage ||\n formatMessage(MESSAGES.maximumFilesAlreadyUploaded, { maxFilesAllowed: maxFiles });\n handleFileUploadFailure(file, failureMessage);\n continue;\n }\n\n const existingFile = uploadedFiles.find((f) => f.filename === file.name);\n if (existingFile) {\n removeFileFromList(existingFile);\n }\n\n formData.append(fileInputName, file);\n const pendingFile = {\n id: generateFileId(file),\n filename: file.name,\n status: Status.PENDING,\n };\n\n addFileToList(pendingFile);\n\n onUploadFile(formData)\n .then(({ id, url, error }: UploadResponse) => {\n modifyFileInList(pendingFile, { id, url, error, status: Status.SUCCEEDED });\n })\n .catch((error) => {\n modifyFileInList(pendingFile, { error: error as UploadError, status: Status.FAILED });\n });\n\n if (!multiple) {\n break;\n }\n }\n }\n };\n\n useEffect(() => {\n setMounted(true);\n }, []);\n\n useEffect(() => {\n if (onFilesChange && mounted) {\n onFilesChange([...uploadedFiles]);\n }\n }, [onFilesChange, uploadedFiles]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const [nextFocusable, setNextFocusable] = useState<HTMLDivElement | UploadItemRef | null>(\n uploadInputRef.current,\n );\n\n const handleFocus = (fileId: string | number) => {\n fileRefs = fileRefs.filter((ref) => {\n return ref && ref.id !== markedFileForDelete?.id;\n });\n\n const filesCount = fileRefs.length;\n let next: HTMLDivElement | UploadItemRef | null = uploadInputRef.current;\n\n if (filesCount > 1) {\n const currentFileIndex = fileRefs.findIndex((file) => file?.id === fileId);\n const currentFileId = fileRefs?.[currentFileIndex]?.id;\n const lastFileId = fileRefs?.[filesCount - 1]?.id;\n\n // if last file, select a previous one\n if (currentFileId === lastFileId) {\n next = fileRefs[filesCount - 2];\n } else {\n next = fileRefs[currentFileIndex + 1];\n }\n }\n setNextFocusable(next);\n };\n\n const handleRefocus = () => {\n if (nextFocusable && 'focus' in nextFocusable && typeof nextFocusable.focus === 'function') {\n setTimeout(() => {\n nextFocusable.focus();\n }, 0);\n }\n };\n\n return (\n <>\n <div\n role=\"group\"\n className={clsx('np-upload-input', className, { disabled })}\n {...inputAttributes}\n >\n <div\n className=\"np-upload-input__section\"\n aria-live=\"polite\"\n aria-relevant=\"all\"\n role=\"region\"\n >\n {uploadedFiles.map((file, index) => (\n <UploadItem\n key={file.id}\n ref={(el: UploadItemRef | null) => {\n if (\n el &&\n el.id !== markedFileForDelete?.id &&\n !fileRefs.some((ref) => ref && ref.id === el.id) &&\n el.status !== 'processing'\n ) {\n fileRefs.push(el);\n }\n }}\n file={file}\n singleFileUpload={!multiple}\n canDelete={\n (!!onDeleteFile || file.status === Status.FAILED) &&\n (!file.status || !PROGRESS_STATUSES.has(file.status))\n }\n onDelete={\n file.status === Status.FAILED\n ? async () => {\n await removeFile(file);\n handleRefocus();\n }\n : () => setMarkedFileForDelete(file)\n }\n onDownload={onDownload}\n onFocus={() => handleFocus(file.id)}\n />\n ))}\n </div>\n {(multiple || (!multiple && !uploadedFiles.length)) && (\n <div className=\"np-upload-input__section np-upload-input__section--uploader\">\n <UploadButton\n ref={uploadInputRef}\n id={id}\n uploadButtonTitle={uploadButtonTitle}\n disabled={areMaximumFilesUploadedAlready() || disabled}\n multiple={multiple}\n fileTypes={fileTypes}\n sizeLimit={sizeLimit}\n description={description}\n maxFiles={maxFiles}\n withEntries={Boolean(uploadedFiles.length)}\n onChange={addFiles}\n />\n </div>\n )}\n </div>\n <Modal\n title={\n deleteConfirm?.title !== undefined\n ? deleteConfirm.title\n : formatMessage(MESSAGES.deleteModalTitle)\n }\n body={\n deleteConfirm?.body !== undefined\n ? deleteConfirm.body\n : formatMessage(MESSAGES.deleteModalBody)\n }\n open={!!markedFileForDelete}\n footer={\n <>\n <Button\n block\n onClick={() => {\n setMarkedFileForDelete(null);\n }}\n >\n {deleteConfirm?.cancelText || formatMessage(MESSAGES.deleteModalCancelButtonText)}\n </Button>\n <Button\n block\n priority={Priority.SECONDARY}\n type={ControlType.NEGATIVE}\n tabIndex={markedFileForDelete ? 0 : -1}\n onClick={() => {\n if (markedFileForDelete) {\n void removeFile(markedFileForDelete);\n }\n setMarkedFileForDelete(null);\n }}\n >\n {deleteConfirm?.confirmText || formatMessage(MESSAGES.deleteModalConfirmButtonText)}\n </Button>\n </>\n }\n onUnmount={handleRefocus}\n onClose={() => {\n setMarkedFileForDelete(null);\n }}\n />\n </>\n );\n};\n\nexport default UploadInput;\n"],"names":["generateFileId","file","name","size","uploadTimeStamp","Date","getTime","UploadInput","files","fileInputName","className","deleteConfirm","disabled","multiple","fileTypes","imageFileTypes","sizeLimit","DEFAULT_SIZE_LIMIT","description","onUploadFile","onDeleteFile","onValidationError","onFilesChange","onDownload","maxFiles","maxFilesErrorMessage","id","sizeLimitErrorMessage","uploadButtonTitle","inputAttributes","useInputAttributes","nonLabelable","markedFileForDelete","setMarkedFileForDelete","useState","mounted","setMounted","formatMessage","useIntl","uploadInputRef","useRef","fileRefs","PROGRESS_STATUSES","Set","Status","PENDING","PROCESSING","uploadedFiles","setUploadedFiles","length","uploadedFilesListReference","updateFileList","updateFn","current","addFileToList","recentUploadedFile","list","removeFileFromList","filter","fileInList","ref","modifyFileInList","updates","map","removeFile","status","item","FAILED","Promise","resolve","error","undefined","then","catch","handleFileUploadFailure","failureMessage","failedUpload","filename","getNumberOfFilesUploaded","uploadInitiatedStatus","SUCCEEDED","validFiles","has","areMaximumFilesUploadedAlready","numberOfValidFiles","addFiles","selectedFiles","i","formData","FormData","allowedFileTypes","join","isTypeValid","MESSAGES","fileTypeNotSupported","isSizeValid","fileIsTooLarge","maximumFilesAlreadyUploaded","maxFilesAllowed","existingFile","find","f","append","pendingFile","url","useEffect","nextFocusable","setNextFocusable","handleFocus","fileId","filesCount","next","currentFileIndex","findIndex","currentFileId","lastFileId","handleRefocus","focus","setTimeout","_jsxs","_Fragment","children","role","clsx","_jsx","index","UploadItem","el","some","push","singleFileUpload","canDelete","onDelete","onFocus","UploadButton","withEntries","Boolean","onChange","Modal","title","deleteModalTitle","body","deleteModalBody","open","footer","Button","block","onClick","cancelText","deleteModalCancelButtonText","priority","Priority","SECONDARY","type","ControlType","NEGATIVE","tabIndex","confirmText","deleteModalConfirmButtonText","onUnmount","onClose"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6HA,SAASA,cAAcA,CAACC,IAAU,EAAA;EAChC,MAAM;IAAEC,IAAI;AAAEC,IAAAA;AAAM,GAAA,GAAGF,IAAI;EAC3B,MAAMG,eAAe,GAAG,IAAIC,IAAI,EAAE,CAACC,OAAO,EAAE;AAC5C,EAAA,OAAO,GAAGJ,IAAI,CAAA,CAAA,EAAIC,IAAI,CAAA,CAAA,EAAIC,eAAe,CAAE,CAAA;AAC7C;AAEA;;;;;;;;AAQG;AACGG,MAAAA,WAAW,GAAGA,CAAC;AACnBC,EAAAA,KAAK,GAAG,EAAE;AACVC,EAAAA,aAAa,GAAG,MAAM;EACtBC,SAAS;EACTC,aAAa;EACbC,QAAQ;AACRC,EAAAA,QAAQ,GAAG,KAAK;AAChBC,EAAAA,SAAS,GAAGC,cAAc;AAC1BC,EAAAA,SAAS,GAAGC,kBAAkB;EAC9BC,WAAW;EACXC,YAAY;EACZC,YAAY;EACZC,iBAAiB;EACjBC,aAAa;EACbC,UAAU;EACVC,QAAQ;EACRC,oBAAoB;EACpBC,EAAE;EACFC,qBAAqB;AACrBC,EAAAA;AACiB,CAAA,KAAI;EACrB,MAAMC,eAAe,GAAGC,kBAAkB,CAAC;AAAEC,IAAAA,YAAY,EAAE;AAAM,GAAA,CAAC;EAClE,MAAM,CAACC,mBAAmB,EAAEC,sBAAsB,CAAC,GAAGC,QAAQ,CAAsB,IAAI,CAAC;EACzF,MAAM,CAACC,OAAO,EAAEC,UAAU,CAAC,GAAGF,QAAQ,CAAC,KAAK,CAAC;EAC7C,MAA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AAEC,WAAW,CAACC,QAAS;AAC3BC,UAAAA,QAAQ,EAAE5H,mBAAmB,GAAG,CAAC,GAAG,EAAG;UACvCmH,OAAO,EAAEA,MAAK;AACZ,YAAA,IAAInH,mBAAmB,EAAE;cACvB,KAAKgC,UAAU,CAAChC,mBAAmB,CAAC;AACtC;YACAC,sBAAsB,CAAC,IAAI,CAAC;WAC5B;UAAAwF,QAAA,EAED9G,aAAa,EAAEkJ,WAAW,IAAIxH,aAAa,CAACwD,QAAQ,CAACiE,4BAA4B;AAAC,SAC7E,CACV;AAAA,OAAA,CACD;AACDC,MAAAA,SAAS,EAAE3C,aAAc;MACzB4C,OAAO,EAAEA,MAAK;QACZ/H,sBAAsB,CAAC,IAAI,CAAC;AAC9B;AAAE,KAEN,CAAA;AAAA,GAAA,CAAG;AAEP;;;;"}
|
|
1
|
+
{"version":3,"file":"UploadInput.mjs","sources":["../../src/uploadInput/UploadInput.tsx"],"sourcesContent":["import { clsx } from 'clsx';\nimport { useEffect, useRef, useState } from 'react';\nimport { useIntl } from 'react-intl';\n\nimport Button from '../button';\nimport { CommonProps, ControlType, Priority, Status } from '../common';\nimport { useInputAttributes } from '../inputs/contexts';\nimport Modal from '../modal';\nimport { isSizeValid } from '../upload/utils/isSizeValid';\nimport { isTypeValid } from '../upload/utils/isTypeValid';\n\nimport MESSAGES from './UploadInput.messages';\nimport { UploadedFile, UploadError, UploadResponse } from './types';\nimport UploadButton, { UploadButtonProps } from './uploadButton/UploadButton';\nimport { DEFAULT_SIZE_LIMIT, imageFileTypes } from './uploadButton/defaults';\nimport UploadItem, { UploadItemProps } from './uploadItem/UploadItem';\n\nexport type UploadInputProps = {\n /**\n * List of already existing, failed or in progress files\n */\n files?: readonly UploadedFile[];\n\n /**\n * The key of the file in the returned FormData object (default: file)\n */\n fileInputName?: string;\n\n /**\n * Callback that handles form submission\n *\n * @param formData\n */\n onUploadFile: (formData: FormData) => Promise<UploadResponse>;\n\n /**\n * Provide a callback if the file can be removed/deleted from the server\n * Your app is responsible for reloading the uploaded files list and updating the component to ensure that the file has in fact been deleted successfully\n *\n * @param id\n */\n onDeleteFile?: (id: string | number) => Promise<any>;\n\n /**\n * Provide a callback to trigger on validation error\n *\n * @param file\n */\n onValidationError?: (file: UploadedFile) => void;\n\n /**\n * Provide a callback to trigger on change whenever the files are updated\n *\n * @param files\n */\n onFilesChange?: (files: UploadedFile[]) => void;\n\n /**\n * Confirmation modal displayed on delete\n */\n deleteConfirm?: {\n /**\n * The title of the confirmation modal on delete\n */\n title?: string;\n\n /**\n * The body of the confirmation modal on delete\n */\n body?: React.ReactNode;\n\n /**\n * The confirm button text of the confirmation modal on delete\n */\n confirmText?: string;\n\n /**\n * The cancel button text of the confirmation modal on delete\n */\n cancelText?: string;\n };\n\n /**\n * Maximum number of files allowed, if provided, shows error below file item\n */\n maxFiles?: number;\n\n /**\n * Error message to show when the maximum number of files are uploaded already\n */\n maxFilesErrorMessage?: string;\n\n /**\n * Error message to show when files over a allowed size limit are uploaded\n */\n sizeLimitErrorMessage?: string;\n} & Pick<\n UploadButtonProps,\n 'disabled' | 'multiple' | 'fileTypes' | 'sizeLimit' | 'description' | 'id' | 'uploadButtonTitle'\n> & { onDownload?: UploadItemProps['onDownload'] } & CommonProps;\n\n/**\n * Interface representing a reference to an UploadItem component.\n * Provides a method to focus the UploadItem.\n */\ninterface UploadItemRef {\n /**\n * Focuses the UploadItem component.\n */\n focus: () => void;\n\n /**\n * Required id of the UploadItem component.\n */\n id: string | number;\n\n /**\n * Optional status of the UploadItem component.\n */\n status?: string;\n}\n\n/**\n * Generates a unique ID for a file based on its name, size, and the current timestamp\n */\nfunction generateFileId(file: File) {\n const { name, size } = file;\n const uploadTimeStamp = new Date().getTime();\n return `${name}_${size}_${uploadTimeStamp}`;\n}\n\n/**\n * The component allows users to upload files, manage the list of uploaded files,\n * and handle file validation and deletion.\n *\n * @param {UploadInputProps} props - The properties for the UploadInput component.\n *\n * @see {@link UploadInput} for further information.\n * @see {@link https://storybook.wise.design/?path=/docs/forms-uploadinput--docs|Storybook Wise Design}\n */\nconst UploadInput = ({\n files = [],\n fileInputName = 'file',\n className,\n deleteConfirm,\n disabled,\n multiple = false,\n fileTypes = imageFileTypes,\n sizeLimit = DEFAULT_SIZE_LIMIT,\n description,\n onUploadFile,\n onDeleteFile,\n onValidationError,\n onFilesChange,\n onDownload,\n maxFiles,\n maxFilesErrorMessage,\n id,\n sizeLimitErrorMessage,\n uploadButtonTitle,\n}: UploadInputProps) => {\n const inputAttributes = useInputAttributes({ nonLabelable: true });\n const [markedFileForDelete, setMarkedFileForDelete] = useState<UploadedFile | null>(null);\n const [lastAttemptedDeleteId, setLastAttemptedDeleteId] = useState<string | number | null>(null);\n const [mounted, setMounted] = useState(false);\n const { formatMessage } = useIntl();\n const uploadInputRef = useRef<HTMLInputElement | null>(null);\n let fileRefs: (HTMLDivElement | UploadItemRef | null)[] = [];\n\n const PROGRESS_STATUSES = new Set([Status.PENDING, Status.PROCESSING]);\n\n const [uploadedFiles, setUploadedFiles] = useState<readonly UploadedFile[]>(\n multiple || files.length === 0 ? files : [files[0]],\n );\n\n const uploadedFilesListReference = useRef(multiple || files.length === 0 ? files : [files[0]]);\n\n function updateFileList(updateFn: (list: readonly UploadedFile[]) => readonly UploadedFile[]) {\n setUploadedFiles(updateFn);\n uploadedFilesListReference.current = updateFn(uploadedFilesListReference.current);\n }\n\n function addFileToList(recentUploadedFile: UploadedFile) {\n updateFileList((list) => [...list, recentUploadedFile]);\n }\n\n function removeFileFromList(file: UploadedFile) {\n updateFileList((list) =>\n list.filter((fileInList) => file !== fileInList && file.id !== fileInList.id),\n );\n fileRefs = fileRefs.filter((ref) => ref && ref.id !== file.id);\n }\n\n function modifyFileInList(file: UploadedFile, updates: Partial<UploadedFile>) {\n updateFileList((list) =>\n list.map((fileInList) =>\n fileInList === file || fileInList.id === file.id ? { ...file, ...updates } : fileInList,\n ),\n );\n }\n\n const removeFile = async (file: UploadedFile) => {\n const { id, status } = file;\n fileRefs = fileRefs.filter((item) => item && item.id !== file.id);\n\n if (status === Status.FAILED) {\n removeFileFromList(file);\n return Promise.resolve();\n }\n\n if (onDeleteFile && id) {\n modifyFileInList(file, { status: Status.PROCESSING, error: undefined });\n\n return onDeleteFile(id)\n .then(() => {\n removeFileFromList(file);\n })\n .catch((error) => {\n modifyFileInList(file, { error: error as UploadError });\n });\n }\n };\n\n function handleFileUploadFailure(file: File, failureMessage: string) {\n const { name } = file;\n\n const failedUpload = {\n id: generateFileId(file),\n filename: name,\n status: Status.FAILED,\n error: failureMessage,\n };\n\n addFileToList(failedUpload);\n\n if (onValidationError) {\n onValidationError(failedUpload);\n }\n }\n\n function getNumberOfFilesUploaded() {\n const uploadInitiatedStatus = new Set([Status.SUCCEEDED, Status.PENDING]);\n const validFiles = uploadedFilesListReference.current.filter(\n (file) => file.status && uploadInitiatedStatus.has(file.status),\n );\n return validFiles.length;\n }\n\n function areMaximumFilesUploadedAlready() {\n if (!maxFiles) {\n return false;\n }\n\n const numberOfValidFiles = getNumberOfFilesUploaded();\n return numberOfValidFiles >= maxFiles;\n }\n\n const addFiles = (selectedFiles: FileList) => {\n for (let i = 0; i < selectedFiles.length; i += 1) {\n const file = selectedFiles.item(i);\n\n const formData = new FormData();\n\n if (file) {\n const allowedFileTypes = typeof fileTypes === 'string' ? fileTypes : fileTypes.join(',');\n\n if (!isTypeValid(file, allowedFileTypes)) {\n handleFileUploadFailure(file, formatMessage(MESSAGES.fileTypeNotSupported));\n continue;\n }\n\n if (!isSizeValid(file, sizeLimit * 1000)) {\n const failureMessage = sizeLimitErrorMessage || formatMessage(MESSAGES.fileIsTooLarge);\n handleFileUploadFailure(file, failureMessage);\n continue;\n }\n\n if (areMaximumFilesUploadedAlready()) {\n const failureMessage =\n maxFilesErrorMessage ||\n formatMessage(MESSAGES.maximumFilesAlreadyUploaded, { maxFilesAllowed: maxFiles });\n handleFileUploadFailure(file, failureMessage);\n continue;\n }\n\n const existingFile = uploadedFiles.find((f) => f.filename === file.name);\n if (existingFile) {\n removeFileFromList(existingFile);\n }\n\n formData.append(fileInputName, file);\n const pendingFile = {\n id: generateFileId(file),\n filename: file.name,\n status: Status.PENDING,\n };\n\n addFileToList(pendingFile);\n\n onUploadFile(formData)\n .then(({ id, url, error }: UploadResponse) => {\n modifyFileInList(pendingFile, { id, url, error, status: Status.SUCCEEDED });\n })\n .catch((error) => {\n modifyFileInList(pendingFile, { error: error as UploadError, status: Status.FAILED });\n });\n\n if (!multiple) {\n break;\n }\n }\n }\n };\n\n useEffect(() => {\n setMounted(true);\n }, []);\n\n useEffect(() => {\n if (onFilesChange && mounted) {\n onFilesChange([...uploadedFiles]);\n }\n }, [onFilesChange, uploadedFiles]); // eslint-disable-line react-hooks/exhaustive-deps\n\n type NextFocusable =\n | HTMLDivElement\n | UploadItemRef\n | { ref: HTMLDivElement | UploadItemRef; target: 'button' | 'link' }\n | null;\n\n const [nextFocusable, setNextFocusable] = useState<NextFocusable>(uploadInputRef.current);\n\n const handleFocus = (fileId: string | number) => {\n fileRefs = fileRefs.filter((ref) => {\n return ref && ref.id !== markedFileForDelete?.id;\n });\n\n const filesCount = fileRefs.length;\n let next: UploadItemRef | HTMLDivElement | null = uploadInputRef.current;\n let focusTarget: 'button' | 'link' = 'button';\n\n // If there will be no files left after deletion, focus the upload button\n if (filesCount === 1) {\n next = uploadInputRef.current;\n setNextFocusable(next);\n return;\n }\n\n if (filesCount > 1) {\n const currentFileIndex = fileRefs.findIndex((file) => file?.id === fileId);\n const currentFileId = fileRefs?.[currentFileIndex]?.id;\n const lastFileId = fileRefs?.[filesCount - 1]?.id;\n\n // if last file, select a previous one\n if (currentFileId === lastFileId) {\n next = fileRefs[filesCount - 2];\n } else {\n next = fileRefs[currentFileIndex + 1];\n }\n\n // If next is an UploadItemRef, check if it has a URL (succeeded)\n if (next && 'status' in next) {\n // Find the file object for this ref\n const fileObj = uploadedFiles.find((f) => f.id === next?.id);\n if (\n fileObj &&\n (fileObj.status === Status.SUCCEEDED || fileObj.status === Status.DONE) &&\n fileObj.url\n ) {\n focusTarget = 'link';\n }\n }\n setNextFocusable(() => {\n if (next && typeof (next as UploadItemRef).focus === 'function') {\n return { ref: next, target: focusTarget };\n }\n return next;\n });\n }\n };\n\n const handleRefocus = () => {\n const focusTarget = nextFocusable;\n if (lastAttemptedDeleteId) {\n setLastAttemptedDeleteId(null);\n return;\n }\n if (focusTarget) {\n // If there are no files left, focus the upload button\n if (\n uploadedFiles.length === 0 &&\n uploadInputRef.current &&\n typeof uploadInputRef.current.focus === 'function'\n ) {\n setTimeout(() => {\n uploadInputRef.current!.focus();\n }, 0);\n } else if (\n typeof focusTarget === 'object' &&\n 'ref' in focusTarget &&\n focusTarget.ref &&\n typeof focusTarget.ref.focus === 'function'\n ) {\n setTimeout(() => {\n if (focusTarget.ref && typeof (focusTarget.ref as UploadItemRef).focus === 'function') {\n // @ts-expect-error: focus may not exist on all possible ref types, but is safe here\n (focusTarget.ref as UploadItemRef).focus(focusTarget.target);\n }\n }, 0);\n } else if (focusTarget && typeof (focusTarget as UploadItemRef).focus === 'function') {\n setTimeout(() => {\n (focusTarget as UploadItemRef).focus();\n }, 0);\n }\n }\n };\n\n return (\n <>\n <div\n role=\"group\"\n className={clsx('np-upload-input', className, { disabled })}\n {...inputAttributes}\n >\n <div\n className=\"np-upload-input__section\"\n aria-live=\"polite\"\n aria-relevant=\"all\"\n role=\"region\"\n >\n {uploadedFiles.map((file, index) => (\n <UploadItem\n key={file.id}\n ref={(el: UploadItemRef | null) => {\n if (\n el &&\n el.id !== markedFileForDelete?.id &&\n !fileRefs.some((ref) => ref && ref.id === el.id) &&\n el.status !== 'processing'\n ) {\n fileRefs.push(el);\n }\n }}\n file={file}\n singleFileUpload={!multiple}\n canDelete={\n (!!onDeleteFile || file.status === Status.FAILED) &&\n (!file.status || !PROGRESS_STATUSES.has(file.status))\n }\n onDelete={\n file.status === Status.FAILED\n ? async () => {\n setLastAttemptedDeleteId(file.id);\n await removeFile(file);\n handleRefocus();\n }\n : () => {\n setLastAttemptedDeleteId(file.id);\n setMarkedFileForDelete(file);\n }\n }\n onDownload={onDownload}\n onFocus={() => handleFocus(file.id)}\n />\n ))}\n </div>\n {(multiple || (!multiple && !uploadedFiles.length)) && (\n <div className=\"np-upload-input__section np-upload-input__section--uploader\">\n <UploadButton\n ref={uploadInputRef}\n id={id}\n uploadButtonTitle={uploadButtonTitle}\n disabled={areMaximumFilesUploadedAlready() || disabled}\n multiple={multiple}\n fileTypes={fileTypes}\n sizeLimit={sizeLimit}\n description={description}\n maxFiles={maxFiles}\n withEntries={Boolean(uploadedFiles.length)}\n onChange={addFiles}\n />\n </div>\n )}\n </div>\n <Modal\n title={\n deleteConfirm?.title !== undefined\n ? deleteConfirm.title\n : formatMessage(MESSAGES.deleteModalTitle)\n }\n body={\n deleteConfirm?.body !== undefined\n ? deleteConfirm.body\n : formatMessage(MESSAGES.deleteModalBody)\n }\n open={!!markedFileForDelete}\n footer={\n <>\n <Button\n block\n onClick={() => {\n setMarkedFileForDelete(null);\n }}\n >\n {deleteConfirm?.cancelText || formatMessage(MESSAGES.deleteModalCancelButtonText)}\n </Button>\n <Button\n block\n priority={Priority.SECONDARY}\n type={ControlType.NEGATIVE}\n tabIndex={markedFileForDelete ? 0 : -1}\n onClick={() => {\n if (markedFileForDelete) {\n void removeFile(markedFileForDelete);\n }\n setMarkedFileForDelete(null);\n setLastAttemptedDeleteId(null);\n }}\n >\n {deleteConfirm?.confirmText || formatMessage(MESSAGES.deleteModalConfirmButtonText)}\n </Button>\n </>\n }\n onUnmount={handleRefocus}\n onClose={() => {\n setMarkedFileForDelete(null);\n }}\n />\n </>\n );\n};\n\nexport default UploadInput;\n"],"names":["generateFileId","file","name","size","uploadTimeStamp","Date","getTime","UploadInput","files","fileInputName","className","deleteConfirm","disabled","multiple","fileTypes","imageFileTypes","sizeLimit","DEFAULT_SIZE_LIMIT","description","onUploadFile","onDeleteFile","onValidationError","onFilesChange","onDownload","maxFiles","maxFilesErrorMessage","id","sizeLimitErrorMessage","uploadButtonTitle","inputAttributes","useInputAttributes","nonLabelable","markedFileForDelete","setMarkedFileForDelete","useState","lastAttemptedDeleteId","setLastAttemptedDeleteId","mounted","setMounted","formatMessage","useIntl","uploadInputRef","useRef","fileRefs","PROGRESS_STATUSES","Set","Status","PENDING","PROCESSING","uploadedFiles","setUploadedFiles","length","uploadedFilesListReference","updateFileList","updateFn","current","addFileToList","recentUploadedFile","list","removeFileFromList","filter","fileInList","ref","modifyFileInList","updates","map","removeFile","status","item","FAILED","Promise","resolve","error","undefined","then","catch","handleFileUploadFailure","failureMessage","failedUpload","filename","getNumberOfFilesUploaded","uploadInitiatedStatus","SUCCEEDED","validFiles","has","areMaximumFilesUploadedAlready","numberOfValidFiles","addFiles","selectedFiles","i","formData","FormData","allowedFileTypes","join","isTypeValid","MESSAGES","fileTypeNotSupported","isSizeValid","fileIsTooLarge","maximumFilesAlreadyUploaded","maxFilesAllowed","existingFile","find","f","append","pendingFile","url","useEffect","nextFocusable","setNextFocusable","handleFocus","fileId","filesCount","next","focusTarget","currentFileIndex","findIndex","currentFileId","lastFileId","fileObj","DONE","focus","target","handleRefocus","setTimeout","_jsxs","_Fragment","children","role","clsx","_jsx","index","UploadItem","el","some","push","singleFileUpload","canDelete","onDelete","onFocus","UploadButton","withEntries","Boolean","onChange","Modal","title","deleteModalTitle","body","deleteModalBody","open","footer","Button","block","onClick","cancelText","deleteModalCancelButtonText","priority","Priority","SECONDARY","type","ControlType","NEGATIVE","tabIndex","confirmText","deleteModalConfirmButtonText","onUnmount","onClose"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6HA,SAASA,cAAcA,CAACC,IAAU,EAAA;EAChC,MAAM;IAAEC,IAAI;AAAEC,IAAAA;AAAM,GAAA,GAAGF,IAAI;EAC3B,MAAMG,eAAe,GAAG,IAAIC,IAAI,EAAE,CAACC,OAAO,EAAE;AAC5C,EAAA,OAAO,GAAGJ,IAAI,CAAA,CAAA,EAAIC,IA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QAAQ,EAAEC,QAAQ,CAACC,SAAU;UAC7BC,IAAI,EAAEC,WAAW,CAACC,QAAS;AAC3BC,UAAAA,QAAQ,EAAElI,mBAAmB,GAAG,CAAC,GAAG,EAAG;UACvCyH,OAAO,EAAEA,MAAK;AACZ,YAAA,IAAIzH,mBAAmB,EAAE;cACvB,KAAKkC,UAAU,CAAClC,mBAAmB,CAAC;AACtC;YACAC,sBAAsB,CAAC,IAAI,CAAC;YAC5BG,wBAAwB,CAAC,IAAI,CAAC;WAC9B;UAAA2F,QAAA,EAEDpH,aAAa,EAAEwJ,WAAW,IAAI5H,aAAa,CAACwD,QAAQ,CAACqE,4BAA4B;AAAC,SAC7E,CACV;AAAA,OAAA,CACD;AACDC,MAAAA,SAAS,EAAE1C,aAAc;MACzB2C,OAAO,EAAEA,MAAK;QACZrI,sBAAsB,CAAC,IAAI,CAAC;AAC9B;AAAE,KAEN,CAAA;AAAA,GAAA,CAAG;AAEP;;;;"}
|
|
@@ -60,11 +60,15 @@ const UploadItem = /*#__PURE__*/React.forwardRef(({
|
|
|
60
60
|
const linkRef = React.useRef(null);
|
|
61
61
|
const buttonRef = React.useRef(null);
|
|
62
62
|
React.useImperativeHandle(ref, () => ({
|
|
63
|
-
focus:
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
} else {
|
|
67
|
-
|
|
63
|
+
focus: target => {
|
|
64
|
+
if (target === 'button' && buttonRef.current) {
|
|
65
|
+
buttonRef.current.focus();
|
|
66
|
+
} else if (target === 'link' && linkRef.current) {
|
|
67
|
+
linkRef.current.focus();
|
|
68
|
+
} else if (buttonRef.current) {
|
|
69
|
+
buttonRef.current.focus();
|
|
70
|
+
} else if (linkRef.current) {
|
|
71
|
+
linkRef.current.focus();
|
|
68
72
|
}
|
|
69
73
|
},
|
|
70
74
|
id: file.id,
|
|
@@ -193,7 +197,9 @@ const UploadItem = /*#__PURE__*/React.forwardRef(({
|
|
|
193
197
|
type: "button",
|
|
194
198
|
tabIndex: 0,
|
|
195
199
|
"data-testid": `${file.id}-${exports.TEST_IDS.action}`,
|
|
196
|
-
onClick: () => onDelete()
|
|
200
|
+
onClick: () => onDelete()
|
|
201
|
+
// @ts-expect-error: handleFocus is not a standard FocusEventHandler, but required for parent logic
|
|
202
|
+
,
|
|
197
203
|
onFocus: handleFocus,
|
|
198
204
|
children: /*#__PURE__*/jsxRuntime.jsx(icons.Bin, {
|
|
199
205
|
size: 16
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UploadItem.js","sources":["../../../src/uploadInput/uploadItem/UploadItem.tsx"],"sourcesContent":["import { Bin, CheckCircleFill, CrossCircleFill } from '@transferwise/icons';\nimport { clsx } from 'clsx';\nimport { forwardRef, useImperativeHandle, useRef } from 'react';\nimport { useIntl } from 'react-intl';\n\nimport Body from '../../body';\nimport { Size, Status, Typography } from '../../common';\nimport ProcessIndicator from '../../processIndicator/ProcessIndicator';\nimport { UploadedFile, UploadError } from '../types';\n\nimport MESSAGES from './UploadItem.messages';\nimport { UploadItemLink } from './UploadItemLink';\n\nexport type UploadItemProps = React.JSX.IntrinsicAttributes & {\n file: UploadedFile;\n /**\n * Is this Item part of a multiple- or single-file UploadInput\n */\n singleFileUpload: boolean;\n canDelete: boolean;\n onDelete: () => void;\n onFocus: () => void;\n\n /**\n * Callback to be called when the file link is clicked.\n * When provided, you need to manually trigger actions to load/download the file.\n *\n * @param file\n */\n onDownload?: (file: UploadedFile) => void;\n ref?: React.Ref<UploadItemRef>;\n};\ninterface UploadItemRef {\n /**\n * A method to set focus on the upload item.\n * @returns {void}\n */\n focus: () => void;\n\n /**\n * A required unique identifier for the upload item.\n */\n id: string | number;\n\n /**\n * An optional status of the upload item.\n */\n status?: string;\n}\n\nexport enum TEST_IDS {\n uploadItem = 'uploadItem',\n mediaBody = 'mediaBody',\n link = 'link',\n action = 'action',\n}\n\nconst UploadItem = forwardRef<UploadItemRef, UploadItemProps>(\n ({ file, canDelete, onDelete, onDownload, singleFileUpload, onFocus: handleFocus }, ref) => {\n const { formatMessage } = useIntl();\n const { status, filename, error, errors, url } = file;\n const linkRef = useRef<HTMLAnchorElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n\n useImperativeHandle<UploadItemRef, UploadItemRef>(ref, () => ({\n focus: (): void => {\n if (url) {\n linkRef.current?.focus();\n } else {\n buttonRef.current?.focus();\n }\n },\n id: file.id,\n status: file.status,\n }));\n\n const isSucceeded = [Status.SUCCEEDED, undefined].includes(status) && !!url;\n\n /**\n * We're temporarily reverting to the regular icon components,\n * until the StatusIcon receives 24px sizing. Some misalignment\n * to be expected.\n */\n const getIcon = () => {\n if (error || errors?.length || status === Status.FAILED) {\n return <CrossCircleFill size={24} className=\"emphasis--negative\" />;\n }\n\n let processIndicator: React.ReactNode;\n\n switch (status) {\n case Status.PROCESSING:\n case Status.PENDING:\n processIndicator = (\n <ProcessIndicator size={Size.EXTRA_SMALL} status={Status.PROCESSING} />\n );\n break;\n case Status.SUCCEEDED:\n case Status.DONE:\n default:\n processIndicator = <CheckCircleFill size={24} className=\"emphasis--positive\" />;\n }\n\n return processIndicator;\n };\n\n const getErrorMessage = (error?: UploadError) =>\n typeof error === 'object' ? error.message : error || formatMessage(MESSAGES.uploadingFailed);\n\n const getMultipleErrors = (errors?: UploadError[]) => {\n if (!errors?.length) {\n return null;\n }\n\n if (errors?.length === 1) {\n return getErrorMessage(errors[0]);\n }\n\n return (\n <ul className=\"np-upload-input-errors m-b-0\">\n {errors.map((error, index) => {\n // eslint-disable-next-line react/no-array-index-key\n return <li key={index}>{getErrorMessage(error)}</li>;\n })}\n </ul>\n );\n };\n\n const getDescription = () => {\n if (error || errors?.length || status === Status.FAILED) {\n return (\n <Body type={Typography.BODY_DEFAULT_BOLD} className=\"np-upload-input__text text-negative\">\n {errors?.length ? getMultipleErrors(errors) : getErrorMessage(error)}\n </Body>\n );\n }\n\n switch (status) {\n case Status.PENDING:\n return (\n <Body type={Typography.BODY_DEFAULT} className=\"np-upload-input__text\">\n {formatMessage(MESSAGES.uploading)}\n </Body>\n );\n case Status.PROCESSING:\n return <Body className=\"np-upload-input__text\">{formatMessage(MESSAGES.deleting)}</Body>;\n case Status.SUCCEEDED:\n case Status.DONE:\n default:\n return (\n <Body type={Typography.BODY_DEFAULT_BOLD} className=\"np-upload-input__text\">\n {formatMessage(MESSAGES.uploaded)}\n </Body>\n );\n }\n };\n\n const getTitle = () => {\n return filename || formatMessage(MESSAGES.uploadedFile);\n };\n\n const onDownloadFile = (event: React.MouseEvent): void => {\n if (onDownload) {\n event.preventDefault();\n onDownload(file);\n }\n };\n\n return (\n <div\n className={clsx('np-upload-input__item', { 'is-interactive': isSucceeded && url })}\n data-testid={`${file.id}-${TEST_IDS.uploadItem}`}\n >\n <UploadItemLink\n ref={linkRef}\n url={isSucceeded ? url : undefined}\n singleFileUpload={singleFileUpload}\n data-testid={`${file.id}-${TEST_IDS.link}`}\n onDownload={onDownloadFile}\n >\n <span className=\"np-upload-input__icon\">{getIcon()}</span>\n <div\n className=\"np-upload-input__item-content\"\n data-testid={`${file.id}-${TEST_IDS.mediaBody}`}\n >\n <Body type={Typography.BODY_LARGE} className=\"np-upload-input__title text-word-break\">\n {getTitle()}\n </Body>\n {getDescription()}\n </div>\n </UploadItemLink>\n {canDelete && (\n <div className=\"np-upload-input__item-action\">\n <button\n ref={buttonRef}\n aria-label={formatMessage(MESSAGES.removeFile, { filename })}\n className=\"np-upload-input__item-button\"\n type=\"button\"\n tabIndex={0}\n data-testid={`${file.id}-${TEST_IDS.action}`}\n onClick={() => onDelete()}\n onFocus={handleFocus}\n >\n <Bin size={16} />\n </button>\n </div>\n )}\n </div>\n );\n },\n);\n\nUploadItem.displayName = 'UploadItem';\n\nexport default UploadItem;\n"],"names":["TEST_IDS","UploadItem","forwardRef","file","canDelete","onDelete","onDownload","singleFileUpload","onFocus","handleFocus","ref","formatMessage","useIntl","status","filename","error","errors","url","linkRef","useRef","buttonRef","useImperativeHandle","focus","current","id","isSucceeded","Status","SUCCEEDED","undefined","includes","getIcon","length","FAILED","_jsx","CrossCircleFill","size","className","processIndicator","PROCESSING","PENDING","ProcessIndicator","Size","EXTRA_SMALL","DONE","CheckCircleFill","getErrorMessage","message","MESSAGES","uploadingFailed","getMultipleErrors","children","map","index","getDescription","Body","type","Typography","BODY_DEFAULT_BOLD","BODY_DEFAULT","uploading","deleting","uploaded","getTitle","uploadedFile","onDownloadFile","event","preventDefault","_jsxs","clsx","uploadItem","UploadItemLink","link","mediaBody","BODY_LARGE","removeFile","tabIndex","action","onClick","Bin","displayName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDYA;AAAZ,CAAA,UAAYA,QAAQ,EAAA;AAClBA,EAAAA,QAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzBA,EAAAA,QAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvBA,EAAAA,QAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACbA,EAAAA,QAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACnB,CAAC,EALWA,gBAAQ,KAARA,gBAAQ,GAKnB,EAAA,CAAA,CAAA;AAED,MAAMC,UAAU,gBAAGC,gBAAU,CAC3B,CAAC;EAAEC,IAAI;EAAEC,SAAS;EAAEC,QAAQ;EAAEC,UAAU;EAAEC,gBAAgB;AAAEC,EAAAA,OAAO,EAAEC;AAAa,CAAA,EAAEC,GAAG,KAAI;EACzF,MAAM;AAAEC,IAAAA;GAAe,GAAGC,iBAAO,EAAE;EACnC,MAAM;YAAEC,QAAM;IAAEC,QAAQ;IAAEC,KAAK;IAAEC,MAAM;AAAEC,IAAAA;AAAK,GAAA,GAAGd,IAAI;AACrD,EAAA,MAAMe,OAAO,GAAGC,YAAM,CAAoB,IAAI,CAAC;AAC/C,EAAA,MAAMC,SAAS,GAAGD,YAAM,CAAoB,IAAI,CAAC;EAEjDE,yBAAmB,CAA+BX,GAAG,EAAE,OAAO;IAC5DY,KAAK,EAAEA,MAAW;AAChB,MAAA,I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;SACb;OAAQ;AACV,KAAK,CACN;AAAA,GACE,CAAC;AAEV,CAAC;AAGHlC,UAAU,CAAC8E,WAAW,GAAG,YAAY;;;;"}
|
|
1
|
+
{"version":3,"file":"UploadItem.js","sources":["../../../src/uploadInput/uploadItem/UploadItem.tsx"],"sourcesContent":["import { Bin, CheckCircleFill, CrossCircleFill } from '@transferwise/icons';\nimport { clsx } from 'clsx';\nimport { forwardRef, useImperativeHandle, useRef } from 'react';\nimport { useIntl } from 'react-intl';\n\nimport Body from '../../body';\nimport { Size, Status, Typography } from '../../common';\nimport ProcessIndicator from '../../processIndicator/ProcessIndicator';\nimport { UploadedFile, UploadError } from '../types';\n\nimport MESSAGES from './UploadItem.messages';\nimport { UploadItemLink } from './UploadItemLink';\n\nexport type UploadItemProps = React.JSX.IntrinsicAttributes & {\n file: UploadedFile;\n /**\n * Is this Item part of a multiple- or single-file UploadInput\n */\n singleFileUpload: boolean;\n canDelete: boolean;\n onDelete: () => void;\n onFocus: (target?: 'button' | 'link') => void;\n\n /**\n * Callback to be called when the file link is clicked.\n * When provided, you need to manually trigger actions to load/download the file.\n *\n * @param file\n */\n onDownload?: (file: UploadedFile) => void;\n ref?: React.Ref<UploadItemRef>;\n};\ninterface UploadItemRef {\n /**\n * A method to set focus on the upload item.\n * @returns {void}\n */\n focus: () => void;\n\n /**\n * A required unique identifier for the upload item.\n */\n id: string | number;\n\n /**\n * An optional status of the upload item.\n */\n status?: string;\n}\n\nexport enum TEST_IDS {\n uploadItem = 'uploadItem',\n mediaBody = 'mediaBody',\n link = 'link',\n action = 'action',\n}\n\nconst UploadItem = forwardRef<UploadItemRef, UploadItemProps>(\n ({ file, canDelete, onDelete, onDownload, singleFileUpload, onFocus: handleFocus }, ref) => {\n const { formatMessage } = useIntl();\n const { status, filename, error, errors, url } = file;\n const linkRef = useRef<HTMLAnchorElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n\n useImperativeHandle<UploadItemRef, UploadItemRef>(ref, () => ({\n focus: (target?: 'button' | 'link'): void => {\n if (target === 'button' && buttonRef.current) {\n buttonRef.current.focus();\n } else if (target === 'link' && linkRef.current) {\n linkRef.current.focus();\n } else if (buttonRef.current) {\n buttonRef.current.focus();\n } else if (linkRef.current) {\n linkRef.current.focus();\n }\n },\n id: file.id,\n status: file.status,\n }));\n\n const isSucceeded = [Status.SUCCEEDED, undefined].includes(status) && !!url;\n\n /**\n * We're temporarily reverting to the regular icon components,\n * until the StatusIcon receives 24px sizing. Some misalignment\n * to be expected.\n */\n const getIcon = () => {\n if (error || errors?.length || status === Status.FAILED) {\n return <CrossCircleFill size={24} className=\"emphasis--negative\" />;\n }\n\n let processIndicator: React.ReactNode;\n\n switch (status) {\n case Status.PROCESSING:\n case Status.PENDING:\n processIndicator = (\n <ProcessIndicator size={Size.EXTRA_SMALL} status={Status.PROCESSING} />\n );\n break;\n case Status.SUCCEEDED:\n case Status.DONE:\n default:\n processIndicator = <CheckCircleFill size={24} className=\"emphasis--positive\" />;\n }\n\n return processIndicator;\n };\n\n const getErrorMessage = (error?: UploadError) =>\n typeof error === 'object' ? error.message : error || formatMessage(MESSAGES.uploadingFailed);\n\n const getMultipleErrors = (errors?: UploadError[]) => {\n if (!errors?.length) {\n return null;\n }\n\n if (errors?.length === 1) {\n return getErrorMessage(errors[0]);\n }\n\n return (\n <ul className=\"np-upload-input-errors m-b-0\">\n {errors.map((error, index) => {\n // eslint-disable-next-line react/no-array-index-key\n return <li key={index}>{getErrorMessage(error)}</li>;\n })}\n </ul>\n );\n };\n\n const getDescription = () => {\n if (error || errors?.length || status === Status.FAILED) {\n return (\n <Body type={Typography.BODY_DEFAULT_BOLD} className=\"np-upload-input__text text-negative\">\n {errors?.length ? getMultipleErrors(errors) : getErrorMessage(error)}\n </Body>\n );\n }\n\n switch (status) {\n case Status.PENDING:\n return (\n <Body type={Typography.BODY_DEFAULT} className=\"np-upload-input__text\">\n {formatMessage(MESSAGES.uploading)}\n </Body>\n );\n case Status.PROCESSING:\n return <Body className=\"np-upload-input__text\">{formatMessage(MESSAGES.deleting)}</Body>;\n case Status.SUCCEEDED:\n case Status.DONE:\n default:\n return (\n <Body type={Typography.BODY_DEFAULT_BOLD} className=\"np-upload-input__text\">\n {formatMessage(MESSAGES.uploaded)}\n </Body>\n );\n }\n };\n\n const getTitle = () => {\n return filename || formatMessage(MESSAGES.uploadedFile);\n };\n\n const onDownloadFile = (event: React.MouseEvent): void => {\n if (onDownload) {\n event.preventDefault();\n onDownload(file);\n }\n };\n\n return (\n <div\n className={clsx('np-upload-input__item', { 'is-interactive': isSucceeded && url })}\n data-testid={`${file.id}-${TEST_IDS.uploadItem}`}\n >\n <UploadItemLink\n ref={linkRef}\n url={isSucceeded ? url : undefined}\n singleFileUpload={singleFileUpload}\n data-testid={`${file.id}-${TEST_IDS.link}`}\n onDownload={onDownloadFile}\n >\n <span className=\"np-upload-input__icon\">{getIcon()}</span>\n <div\n className=\"np-upload-input__item-content\"\n data-testid={`${file.id}-${TEST_IDS.mediaBody}`}\n >\n <Body type={Typography.BODY_LARGE} className=\"np-upload-input__title text-word-break\">\n {getTitle()}\n </Body>\n {getDescription()}\n </div>\n </UploadItemLink>\n {canDelete && (\n <div className=\"np-upload-input__item-action\">\n <button\n ref={buttonRef}\n aria-label={formatMessage(MESSAGES.removeFile, { filename })}\n className=\"np-upload-input__item-button\"\n type=\"button\"\n tabIndex={0}\n data-testid={`${file.id}-${TEST_IDS.action}`}\n onClick={() => onDelete()}\n // @ts-expect-error: handleFocus is not a standard FocusEventHandler, but required for parent logic\n onFocus={handleFocus}\n >\n <Bin size={16} />\n </button>\n </div>\n )}\n </div>\n );\n },\n);\n\nUploadItem.displayName = 'UploadItem';\n\nexport default UploadItem;\n"],"names":["TEST_IDS","UploadItem","forwardRef","file","canDelete","onDelete","onDownload","singleFileUpload","onFocus","handleFocus","ref","formatMessage","useIntl","status","filename","error","errors","url","linkRef","useRef","buttonRef","useImperativeHandle","focus","target","current","id","isSucceeded","Status","SUCCEEDED","undefined","includes","getIcon","length","FAILED","_jsx","CrossCircleFill","size","className","processIndicator","PROCESSING","PENDING","ProcessIndicator","Size","EXTRA_SMALL","DONE","CheckCircleFill","getErrorMessage","message","MESSAGES","uploadingFailed","getMultipleErrors","children","map","index","getDescription","Body","type","Typography","BODY_DEFAULT_BOLD","BODY_DEFAULT","uploading","deleting","uploaded","getTitle","uploadedFile","onDownloadFile","event","preventDefault","_jsxs","clsx","uploadItem","UploadItemLink","link","mediaBody","BODY_LARGE","removeFile","tabIndex","action","onClick","Bin","displayName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDYA;AAAZ,CAAA,UAAYA,QAAQ,EAAA;AAClBA,EAAAA,QAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzBA,EAAAA,QAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvBA,EAAAA,QAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACbA,EAAAA,QAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACnB,CAAC,EALWA,gBAAQ,KAARA,gBAAQ,GAKnB,EAAA,CAAA,CAAA;AAED,MAAMC,UAAU,gBAAGC,gBAAU,CAC3B,CAAC;EAAEC,IAAI;EAAEC,SAAS;EAAEC,QAAQ;EAAEC,UAAU;EAAEC,gBAAgB;AAAEC,EAAAA,OAAO,EAAEC;AAAa,CAAA,EAAEC,GAAG,KAAI;EACzF,MAAM;AAAEC,IAAAA;GAAe,GAAGC,iBAAO,EAAE;EACnC,MAAM;YAAEC,QAAM;IAAEC,QAAQ;IAAEC,KAAK;IAAEC,MAAM;AAAEC,IAAAA;AAAK,GAAA,GAAGd,IAAI;AACrD,EAAA,MAAMe,OAAO,GAAGC,YAAM,CAAoB,IAAI,CAAC;AAC/C,EAAA,MAAMC,SAAS,GAAGD,YAAM,CAAoB,IAAI,CAAC;EAEjDE,yBAAmB,CAA+BX,GAAG,EAAE,OAAO;IAC5DY,KAAK,EAAGC,MAA0B,IAAU;AAC1C,MAAA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I,EAAC,QAAQ;AACboB,QAAAA,QAAQ,EAAE,CAAE;QACZ,aAAa,EAAA,CAAA,EAAGzE,IAAI,CAACsB,EAAE,IAAIzB,gBAAQ,CAAC6E,MAAM,CAAG,CAAA;AAC7CC,QAAAA,OAAO,EAAEA,MAAMzE,QAAQ;AACvB;AAAA;AACAG,QAAAA,OAAO,EAAEC,WAAY;QAAA0C,QAAA,eAErBjB,cAAA,CAAC6C,SAAG,EAAA;AAAC3C,UAAAA,IAAI,EAAE;SACb;OAAQ;AACV,KAAK,CACN;AAAA,GACE,CAAC;AAEV,CAAC;AAGHnC,UAAU,CAAC+E,WAAW,GAAG,YAAY;;;;"}
|
|
@@ -56,11 +56,15 @@ const UploadItem = /*#__PURE__*/forwardRef(({
|
|
|
56
56
|
const linkRef = useRef(null);
|
|
57
57
|
const buttonRef = useRef(null);
|
|
58
58
|
useImperativeHandle(ref, () => ({
|
|
59
|
-
focus:
|
|
60
|
-
if (
|
|
61
|
-
|
|
62
|
-
} else {
|
|
63
|
-
|
|
59
|
+
focus: target => {
|
|
60
|
+
if (target === 'button' && buttonRef.current) {
|
|
61
|
+
buttonRef.current.focus();
|
|
62
|
+
} else if (target === 'link' && linkRef.current) {
|
|
63
|
+
linkRef.current.focus();
|
|
64
|
+
} else if (buttonRef.current) {
|
|
65
|
+
buttonRef.current.focus();
|
|
66
|
+
} else if (linkRef.current) {
|
|
67
|
+
linkRef.current.focus();
|
|
64
68
|
}
|
|
65
69
|
},
|
|
66
70
|
id: file.id,
|
|
@@ -189,7 +193,9 @@ const UploadItem = /*#__PURE__*/forwardRef(({
|
|
|
189
193
|
type: "button",
|
|
190
194
|
tabIndex: 0,
|
|
191
195
|
"data-testid": `${file.id}-${TEST_IDS.action}`,
|
|
192
|
-
onClick: () => onDelete()
|
|
196
|
+
onClick: () => onDelete()
|
|
197
|
+
// @ts-expect-error: handleFocus is not a standard FocusEventHandler, but required for parent logic
|
|
198
|
+
,
|
|
193
199
|
onFocus: handleFocus,
|
|
194
200
|
children: /*#__PURE__*/jsx(Bin, {
|
|
195
201
|
size: 16
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UploadItem.mjs","sources":["../../../src/uploadInput/uploadItem/UploadItem.tsx"],"sourcesContent":["import { Bin, CheckCircleFill, CrossCircleFill } from '@transferwise/icons';\nimport { clsx } from 'clsx';\nimport { forwardRef, useImperativeHandle, useRef } from 'react';\nimport { useIntl } from 'react-intl';\n\nimport Body from '../../body';\nimport { Size, Status, Typography } from '../../common';\nimport ProcessIndicator from '../../processIndicator/ProcessIndicator';\nimport { UploadedFile, UploadError } from '../types';\n\nimport MESSAGES from './UploadItem.messages';\nimport { UploadItemLink } from './UploadItemLink';\n\nexport type UploadItemProps = React.JSX.IntrinsicAttributes & {\n file: UploadedFile;\n /**\n * Is this Item part of a multiple- or single-file UploadInput\n */\n singleFileUpload: boolean;\n canDelete: boolean;\n onDelete: () => void;\n onFocus: () => void;\n\n /**\n * Callback to be called when the file link is clicked.\n * When provided, you need to manually trigger actions to load/download the file.\n *\n * @param file\n */\n onDownload?: (file: UploadedFile) => void;\n ref?: React.Ref<UploadItemRef>;\n};\ninterface UploadItemRef {\n /**\n * A method to set focus on the upload item.\n * @returns {void}\n */\n focus: () => void;\n\n /**\n * A required unique identifier for the upload item.\n */\n id: string | number;\n\n /**\n * An optional status of the upload item.\n */\n status?: string;\n}\n\nexport enum TEST_IDS {\n uploadItem = 'uploadItem',\n mediaBody = 'mediaBody',\n link = 'link',\n action = 'action',\n}\n\nconst UploadItem = forwardRef<UploadItemRef, UploadItemProps>(\n ({ file, canDelete, onDelete, onDownload, singleFileUpload, onFocus: handleFocus }, ref) => {\n const { formatMessage } = useIntl();\n const { status, filename, error, errors, url } = file;\n const linkRef = useRef<HTMLAnchorElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n\n useImperativeHandle<UploadItemRef, UploadItemRef>(ref, () => ({\n focus: (): void => {\n if (url) {\n linkRef.current?.focus();\n } else {\n buttonRef.current?.focus();\n }\n },\n id: file.id,\n status: file.status,\n }));\n\n const isSucceeded = [Status.SUCCEEDED, undefined].includes(status) && !!url;\n\n /**\n * We're temporarily reverting to the regular icon components,\n * until the StatusIcon receives 24px sizing. Some misalignment\n * to be expected.\n */\n const getIcon = () => {\n if (error || errors?.length || status === Status.FAILED) {\n return <CrossCircleFill size={24} className=\"emphasis--negative\" />;\n }\n\n let processIndicator: React.ReactNode;\n\n switch (status) {\n case Status.PROCESSING:\n case Status.PENDING:\n processIndicator = (\n <ProcessIndicator size={Size.EXTRA_SMALL} status={Status.PROCESSING} />\n );\n break;\n case Status.SUCCEEDED:\n case Status.DONE:\n default:\n processIndicator = <CheckCircleFill size={24} className=\"emphasis--positive\" />;\n }\n\n return processIndicator;\n };\n\n const getErrorMessage = (error?: UploadError) =>\n typeof error === 'object' ? error.message : error || formatMessage(MESSAGES.uploadingFailed);\n\n const getMultipleErrors = (errors?: UploadError[]) => {\n if (!errors?.length) {\n return null;\n }\n\n if (errors?.length === 1) {\n return getErrorMessage(errors[0]);\n }\n\n return (\n <ul className=\"np-upload-input-errors m-b-0\">\n {errors.map((error, index) => {\n // eslint-disable-next-line react/no-array-index-key\n return <li key={index}>{getErrorMessage(error)}</li>;\n })}\n </ul>\n );\n };\n\n const getDescription = () => {\n if (error || errors?.length || status === Status.FAILED) {\n return (\n <Body type={Typography.BODY_DEFAULT_BOLD} className=\"np-upload-input__text text-negative\">\n {errors?.length ? getMultipleErrors(errors) : getErrorMessage(error)}\n </Body>\n );\n }\n\n switch (status) {\n case Status.PENDING:\n return (\n <Body type={Typography.BODY_DEFAULT} className=\"np-upload-input__text\">\n {formatMessage(MESSAGES.uploading)}\n </Body>\n );\n case Status.PROCESSING:\n return <Body className=\"np-upload-input__text\">{formatMessage(MESSAGES.deleting)}</Body>;\n case Status.SUCCEEDED:\n case Status.DONE:\n default:\n return (\n <Body type={Typography.BODY_DEFAULT_BOLD} className=\"np-upload-input__text\">\n {formatMessage(MESSAGES.uploaded)}\n </Body>\n );\n }\n };\n\n const getTitle = () => {\n return filename || formatMessage(MESSAGES.uploadedFile);\n };\n\n const onDownloadFile = (event: React.MouseEvent): void => {\n if (onDownload) {\n event.preventDefault();\n onDownload(file);\n }\n };\n\n return (\n <div\n className={clsx('np-upload-input__item', { 'is-interactive': isSucceeded && url })}\n data-testid={`${file.id}-${TEST_IDS.uploadItem}`}\n >\n <UploadItemLink\n ref={linkRef}\n url={isSucceeded ? url : undefined}\n singleFileUpload={singleFileUpload}\n data-testid={`${file.id}-${TEST_IDS.link}`}\n onDownload={onDownloadFile}\n >\n <span className=\"np-upload-input__icon\">{getIcon()}</span>\n <div\n className=\"np-upload-input__item-content\"\n data-testid={`${file.id}-${TEST_IDS.mediaBody}`}\n >\n <Body type={Typography.BODY_LARGE} className=\"np-upload-input__title text-word-break\">\n {getTitle()}\n </Body>\n {getDescription()}\n </div>\n </UploadItemLink>\n {canDelete && (\n <div className=\"np-upload-input__item-action\">\n <button\n ref={buttonRef}\n aria-label={formatMessage(MESSAGES.removeFile, { filename })}\n className=\"np-upload-input__item-button\"\n type=\"button\"\n tabIndex={0}\n data-testid={`${file.id}-${TEST_IDS.action}`}\n onClick={() => onDelete()}\n onFocus={handleFocus}\n >\n <Bin size={16} />\n </button>\n </div>\n )}\n </div>\n );\n },\n);\n\nUploadItem.displayName = 'UploadItem';\n\nexport default UploadItem;\n"],"names":["TEST_IDS","UploadItem","forwardRef","file","canDelete","onDelete","onDownload","singleFileUpload","onFocus","handleFocus","ref","formatMessage","useIntl","status","filename","error","errors","url","linkRef","useRef","buttonRef","useImperativeHandle","focus","current","id","isSucceeded","Status","SUCCEEDED","undefined","includes","getIcon","length","FAILED","_jsx","CrossCircleFill","size","className","processIndicator","PROCESSING","PENDING","ProcessIndicator","Size","EXTRA_SMALL","DONE","CheckCircleFill","getErrorMessage","message","MESSAGES","uploadingFailed","getMultipleErrors","children","map","index","getDescription","Body","type","Typography","BODY_DEFAULT_BOLD","BODY_DEFAULT","uploading","deleting","uploaded","getTitle","uploadedFile","onDownloadFile","event","preventDefault","_jsxs","clsx","uploadItem","UploadItemLink","link","mediaBody","BODY_LARGE","removeFile","tabIndex","action","onClick","Bin","displayName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAkDYA;AAAZ,CAAA,UAAYA,QAAQ,EAAA;AAClBA,EAAAA,QAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzBA,EAAAA,QAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvBA,EAAAA,QAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACbA,EAAAA,QAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACnB,CAAC,EALWA,QAAQ,KAARA,QAAQ,GAKnB,EAAA,CAAA,CAAA;AAED,MAAMC,UAAU,gBAAGC,UAAU,CAC3B,CAAC;EAAEC,IAAI;EAAEC,SAAS;EAAEC,QAAQ;EAAEC,UAAU;EAAEC,gBAAgB;AAAEC,EAAAA,OAAO,EAAEC;AAAa,CAAA,EAAEC,GAAG,KAAI;EACzF,MAAM;AAAEC,IAAAA;GAAe,GAAGC,OAAO,EAAE;EACnC,MAAM;IAAEC,MAAM;IAAEC,QAAQ;IAAEC,KAAK;IAAEC,MAAM;AAAEC,IAAAA;AAAK,GAAA,GAAGd,IAAI;AACrD,EAAA,MAAMe,OAAO,GAAGC,MAAM,CAAoB,IAAI,CAAC;AAC/C,EAAA,MAAMC,SAAS,GAAGD,MAAM,CAAoB,IAAI,CAAC;EAEjDE,mBAAmB,CAA+BX,GAAG,EAAE,OAAO;IAC5DY,KAAK,EAAEA,MAAW;AAChB,MAAA,IAAIL,GAAG,EAAE;AACPC,QAAAA,OAAO,CAACK,OAAO,EAAED,KAAK,EAAE;AAC1B,OAAC,MAAM;AACLF,QAAAA,SAAS,CAACG,OAAO,EAAED,KAAK,EAAE;AAC5B;KACD;IACDE,EAAE,EAAErB,IAAI,CAACqB,EAAE;IACXX,MAAM,EAAEV,IAAI,CAACU;A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,KAAA,EAAA;AACE/B,QAAAA,SAAS,EAAC,+BAA+B;QACzC,aAAa,EAAA,CAAA,EAAGjC,IAAI,CAACqB,EAAE,IAAIxB,QAAQ,CAACwE,SAAS,CAAG,CAAA;QAAAtB,QAAA,EAAA,cAEhDjB,GAAA,CAACqB,IAAI,EAAA;UAACC,IAAI,EAAEC,UAAU,CAACiB,UAAW;AAACrC,UAAAA,SAAS,EAAC,wCAAwC;UAAAc,QAAA,EAClFY,QAAQ;AAAE,SACP,CACN,EAACT,cAAc,EAAE;AAAA,OACd,CACP;AAAA,KAAgB,CAChB,EAACjD,SAAS,iBACR6B,GAAA,CAAA,KAAA,EAAA;AAAKG,MAAAA,SAAS,EAAC,8BAA8B;AAAAc,MAAAA,QAAA,eAC3CjB,GAAA,CAAA,QAAA,EAAA;AACEvB,QAAAA,GAAG,EAAEU,SAAU;AACf,QAAA,YAAA,EAAYT,aAAa,CAACoC,QAAQ,CAAC2B,UAAU,EAAE;AAAE5D,UAAAA;AAAU,SAAA,CAAE;AAC7DsB,QAAAA,SAAS,EAAC,8BAA8B;AACxCmB,QAAAA,IAAI,EAAC,QAAQ;AACboB,QAAAA,QAAQ,EAAE,CAAE;QACZ,aAAa,EAAA,CAAA,EAAGxE,IAAI,CAACqB,EAAE,IAAIxB,QAAQ,CAAC4E,MAAM,CAAG,CAAA;AAC7CC,QAAAA,OAAO,EAAEA,MAAMxE,QAAQ,EAAG;AAC1BG,QAAAA,OAAO,EAAEC,WAAY;QAAAyC,QAAA,eAErBjB,GAAA,CAAC6C,GAAG,EAAA;AAAC3C,UAAAA,IAAI,EAAE;SACb;OAAQ;AACV,KAAK,CACN;AAAA,GACE,CAAC;AAEV,CAAC;AAGHlC,UAAU,CAAC8E,WAAW,GAAG,YAAY;;;;"}
|
|
1
|
+
{"version":3,"file":"UploadItem.mjs","sources":["../../../src/uploadInput/uploadItem/UploadItem.tsx"],"sourcesContent":["import { Bin, CheckCircleFill, CrossCircleFill } from '@transferwise/icons';\nimport { clsx } from 'clsx';\nimport { forwardRef, useImperativeHandle, useRef } from 'react';\nimport { useIntl } from 'react-intl';\n\nimport Body from '../../body';\nimport { Size, Status, Typography } from '../../common';\nimport ProcessIndicator from '../../processIndicator/ProcessIndicator';\nimport { UploadedFile, UploadError } from '../types';\n\nimport MESSAGES from './UploadItem.messages';\nimport { UploadItemLink } from './UploadItemLink';\n\nexport type UploadItemProps = React.JSX.IntrinsicAttributes & {\n file: UploadedFile;\n /**\n * Is this Item part of a multiple- or single-file UploadInput\n */\n singleFileUpload: boolean;\n canDelete: boolean;\n onDelete: () => void;\n onFocus: (target?: 'button' | 'link') => void;\n\n /**\n * Callback to be called when the file link is clicked.\n * When provided, you need to manually trigger actions to load/download the file.\n *\n * @param file\n */\n onDownload?: (file: UploadedFile) => void;\n ref?: React.Ref<UploadItemRef>;\n};\ninterface UploadItemRef {\n /**\n * A method to set focus on the upload item.\n * @returns {void}\n */\n focus: () => void;\n\n /**\n * A required unique identifier for the upload item.\n */\n id: string | number;\n\n /**\n * An optional status of the upload item.\n */\n status?: string;\n}\n\nexport enum TEST_IDS {\n uploadItem = 'uploadItem',\n mediaBody = 'mediaBody',\n link = 'link',\n action = 'action',\n}\n\nconst UploadItem = forwardRef<UploadItemRef, UploadItemProps>(\n ({ file, canDelete, onDelete, onDownload, singleFileUpload, onFocus: handleFocus }, ref) => {\n const { formatMessage } = useIntl();\n const { status, filename, error, errors, url } = file;\n const linkRef = useRef<HTMLAnchorElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n\n useImperativeHandle<UploadItemRef, UploadItemRef>(ref, () => ({\n focus: (target?: 'button' | 'link'): void => {\n if (target === 'button' && buttonRef.current) {\n buttonRef.current.focus();\n } else if (target === 'link' && linkRef.current) {\n linkRef.current.focus();\n } else if (buttonRef.current) {\n buttonRef.current.focus();\n } else if (linkRef.current) {\n linkRef.current.focus();\n }\n },\n id: file.id,\n status: file.status,\n }));\n\n const isSucceeded = [Status.SUCCEEDED, undefined].includes(status) && !!url;\n\n /**\n * We're temporarily reverting to the regular icon components,\n * until the StatusIcon receives 24px sizing. Some misalignment\n * to be expected.\n */\n const getIcon = () => {\n if (error || errors?.length || status === Status.FAILED) {\n return <CrossCircleFill size={24} className=\"emphasis--negative\" />;\n }\n\n let processIndicator: React.ReactNode;\n\n switch (status) {\n case Status.PROCESSING:\n case Status.PENDING:\n processIndicator = (\n <ProcessIndicator size={Size.EXTRA_SMALL} status={Status.PROCESSING} />\n );\n break;\n case Status.SUCCEEDED:\n case Status.DONE:\n default:\n processIndicator = <CheckCircleFill size={24} className=\"emphasis--positive\" />;\n }\n\n return processIndicator;\n };\n\n const getErrorMessage = (error?: UploadError) =>\n typeof error === 'object' ? error.message : error || formatMessage(MESSAGES.uploadingFailed);\n\n const getMultipleErrors = (errors?: UploadError[]) => {\n if (!errors?.length) {\n return null;\n }\n\n if (errors?.length === 1) {\n return getErrorMessage(errors[0]);\n }\n\n return (\n <ul className=\"np-upload-input-errors m-b-0\">\n {errors.map((error, index) => {\n // eslint-disable-next-line react/no-array-index-key\n return <li key={index}>{getErrorMessage(error)}</li>;\n })}\n </ul>\n );\n };\n\n const getDescription = () => {\n if (error || errors?.length || status === Status.FAILED) {\n return (\n <Body type={Typography.BODY_DEFAULT_BOLD} className=\"np-upload-input__text text-negative\">\n {errors?.length ? getMultipleErrors(errors) : getErrorMessage(error)}\n </Body>\n );\n }\n\n switch (status) {\n case Status.PENDING:\n return (\n <Body type={Typography.BODY_DEFAULT} className=\"np-upload-input__text\">\n {formatMessage(MESSAGES.uploading)}\n </Body>\n );\n case Status.PROCESSING:\n return <Body className=\"np-upload-input__text\">{formatMessage(MESSAGES.deleting)}</Body>;\n case Status.SUCCEEDED:\n case Status.DONE:\n default:\n return (\n <Body type={Typography.BODY_DEFAULT_BOLD} className=\"np-upload-input__text\">\n {formatMessage(MESSAGES.uploaded)}\n </Body>\n );\n }\n };\n\n const getTitle = () => {\n return filename || formatMessage(MESSAGES.uploadedFile);\n };\n\n const onDownloadFile = (event: React.MouseEvent): void => {\n if (onDownload) {\n event.preventDefault();\n onDownload(file);\n }\n };\n\n return (\n <div\n className={clsx('np-upload-input__item', { 'is-interactive': isSucceeded && url })}\n data-testid={`${file.id}-${TEST_IDS.uploadItem}`}\n >\n <UploadItemLink\n ref={linkRef}\n url={isSucceeded ? url : undefined}\n singleFileUpload={singleFileUpload}\n data-testid={`${file.id}-${TEST_IDS.link}`}\n onDownload={onDownloadFile}\n >\n <span className=\"np-upload-input__icon\">{getIcon()}</span>\n <div\n className=\"np-upload-input__item-content\"\n data-testid={`${file.id}-${TEST_IDS.mediaBody}`}\n >\n <Body type={Typography.BODY_LARGE} className=\"np-upload-input__title text-word-break\">\n {getTitle()}\n </Body>\n {getDescription()}\n </div>\n </UploadItemLink>\n {canDelete && (\n <div className=\"np-upload-input__item-action\">\n <button\n ref={buttonRef}\n aria-label={formatMessage(MESSAGES.removeFile, { filename })}\n className=\"np-upload-input__item-button\"\n type=\"button\"\n tabIndex={0}\n data-testid={`${file.id}-${TEST_IDS.action}`}\n onClick={() => onDelete()}\n // @ts-expect-error: handleFocus is not a standard FocusEventHandler, but required for parent logic\n onFocus={handleFocus}\n >\n <Bin size={16} />\n </button>\n </div>\n )}\n </div>\n );\n },\n);\n\nUploadItem.displayName = 'UploadItem';\n\nexport default UploadItem;\n"],"names":["TEST_IDS","UploadItem","forwardRef","file","canDelete","onDelete","onDownload","singleFileUpload","onFocus","handleFocus","ref","formatMessage","useIntl","status","filename","error","errors","url","linkRef","useRef","buttonRef","useImperativeHandle","focus","target","current","id","isSucceeded","Status","SUCCEEDED","undefined","includes","getIcon","length","FAILED","_jsx","CrossCircleFill","size","className","processIndicator","PROCESSING","PENDING","ProcessIndicator","Size","EXTRA_SMALL","DONE","CheckCircleFill","getErrorMessage","message","MESSAGES","uploadingFailed","getMultipleErrors","children","map","index","getDescription","Body","type","Typography","BODY_DEFAULT_BOLD","BODY_DEFAULT","uploading","deleting","uploaded","getTitle","uploadedFile","onDownloadFile","event","preventDefault","_jsxs","clsx","uploadItem","UploadItemLink","link","mediaBody","BODY_LARGE","removeFile","tabIndex","action","onClick","Bin","displayName"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAkDYA;AAAZ,CAAA,UAAYA,QAAQ,EAAA;AAClBA,EAAAA,QAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzBA,EAAAA,QAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvBA,EAAAA,QAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACbA,EAAAA,QAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACnB,CAAC,EALWA,QAAQ,KAARA,QAAQ,GAKnB,EAAA,CAAA,CAAA;AAED,MAAMC,UAAU,gBAAGC,UAAU,CAC3B,CAAC;EAAEC,IAAI;EAAEC,SAAS;EAAEC,QAAQ;EAAEC,UAAU;EAAEC,gBAAgB;AAAEC,EAAAA,OAAO,EAAEC;AAAa,CAAA,EAAEC,GAAG,KAAI;EACzF,MAAM;AAAEC,IAAAA;GAAe,GAAGC,OAAO,EAAE;EACnC,MAAM;IAAEC,MAAM;IAAEC,QAAQ;IAAEC,KAAK;IAAEC,MAAM;AAAEC,IAAAA;AAAK,GAAA,GAAGd,IAAI;AACrD,EAAA,MAAMe,OAAO,GAAGC,MAAM,CAAoB,IAAI,CAAC;AAC/C,EAAA,MAAMC,SAAS,GAAGD,MAAM,CAAoB,IAAI,CAAC;EAEjDE,mBAAmB,CAA+BX,GAAG,EAAE,OAAO;IAC5DY,KAAK,EAAGC,MAA0B,IAAU;AAC1C,MAAA,IAAIA,MAAM,KAAK,QAAQ,IAAIH,SAAS,CAACI,OAAO,EAAE;AAC5CJ,QAAAA,SAAS,CAACI,OAAO,CAACF,KAAK,EAAE;OAC1B,MAAM,IAAIC,MAAM,KAAK,MAAM,IAAIL,OAAO,CAACM,OAAO,EAAE;AAC/CN,QAAAA,OAAO,CAACM,OAAO,CAACF,KAAK,EAAE;AACzB,OAAC,M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C,GAAG,EAAA;AAAC3C,UAAAA,IAAI,EAAE;SACb;OAAQ;AACV,KAAK,CACN;AAAA,GACE,CAAC;AAEV,CAAC;AAGHnC,UAAU,CAAC+E,WAAW,GAAG,YAAY;;;;"}
|
|
@@ -273,10 +273,11 @@ class WithDisplayFormat extends React__namespace.Component {
|
|
|
273
273
|
selectionEnd,
|
|
274
274
|
pastedLength
|
|
275
275
|
} = this.state;
|
|
276
|
-
const target = triggerEvent?.currentTarget;
|
|
277
276
|
const cursorPosition = getCursorPositionAfterKeystroke.default(action, selectionStart, selectionEnd, displayPattern, pastedLength);
|
|
278
277
|
setTimeout(() => {
|
|
279
|
-
|
|
278
|
+
if (triggerEvent) {
|
|
279
|
+
triggerEvent.target.setSelectionRange(cursorPosition, cursorPosition);
|
|
280
|
+
}
|
|
280
281
|
this.setState({
|
|
281
282
|
selectionStart: cursorPosition,
|
|
282
283
|
selectionEnd: cursorPosition
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WithDisplayFormat.js","sources":["../../src/withDisplayFormat/WithDisplayFormat.tsx"],"sourcesContent":["import * as React from 'react';\n\nimport { HistoryNavigator } from '../common';\nimport {\n formatWithPattern,\n getCountOfSymbolsInSelection,\n getCursorPositionAfterKeystroke,\n unformatWithPattern,\n getDistanceToPreviousSymbol,\n getDistanceToNextSymbol,\n} from '../common/textFormat';\nimport { InputProps } from '../inputs/Input';\nimport { TextAreaProps } from '../inputs/TextArea';\n\ntype HTMLTextElement = HTMLInputElement | HTMLTextAreaElement;\ntype TextElementProps = InputProps | TextAreaProps;\n\nexport type EventType =\n | 'KeyDown'\n | 'Paste'\n | 'Cut'\n | 'Undo'\n | 'Redo'\n | 'Backspace'\n | 'Delete'\n | 'Initial';\n\ninterface WithDisplayFormatState {\n value: string;\n historyNavigator: HistoryNavigator;\n prevDisplayPattern: string;\n triggerType: EventType;\n triggerEvent: React.KeyboardEvent<HTMLTextElement> | null;\n pastedLength: number;\n selectionStart: number;\n selectionEnd: number;\n}\n\nexport interface WithDisplayFormatProps<T extends TextElementProps = TextElementProps>\n extends Pick<\n TextElementProps,\n | 'className'\n | 'disabled'\n | 'id'\n | 'maxLength'\n | 'minLength'\n | 'name'\n | 'placeholder'\n | 'readOnly'\n | 'required'\n | 'inputMode'\n > {\n value?: string;\n displayPattern: string;\n /**\n * autocomplete hides our form help so we need to disable it when help text\n * is present. Chrome ignores autocomplete=off, the only way to disable it is\n * to provide an 'invalid' value, for which 'disabled' serves.\n */\n autoComplete?: TextElementProps['autoComplete'] | 'disabled';\n onChange?: (value: string) => void;\n onBlur?: (value: string) => void;\n onFocus?: (value: string) => void;\n render: (renderProps: T) => React.JSX.Element;\n}\n\nclass WithDisplayFormat<T extends TextElementProps> extends React.Component<\n WithDisplayFormatProps<T>,\n WithDisplayFormatState\n> {\n declare props: WithDisplayFormatProps<T> &\n Required<Pick<WithDisplayFormatProps<T>, keyof typeof WithDisplayFormat.defaultProps>>;\n static defaultProps = {\n autoComplete: 'off',\n displayPattern: '',\n value: '',\n };\n\n constructor(props: WithDisplayFormatProps) {\n super(props);\n const unformattedValue = unformatWithPattern(props.value ?? '', props.displayPattern);\n this.state = {\n value: formatWithPattern(unformattedValue, props.displayPattern),\n historyNavigator: new HistoryNavigator(),\n prevDisplayPattern: props.displayPattern,\n triggerType: 'Initial',\n triggerEvent: null,\n selectionStart: 0,\n selectionEnd: 0,\n pastedLength: 0,\n };\n }\n\n static getDerivedStateFromProps(\n { displayPattern }: WithDisplayFormatProps,\n { prevDisplayPattern = displayPattern, value, historyNavigator }: WithDisplayFormatState,\n ) {\n if (prevDisplayPattern !== displayPattern) {\n const unFormattedValue = unformatWithPattern(value, prevDisplayPattern);\n historyNavigator.reset();\n\n return {\n prevDisplayPattern: displayPattern,\n value: formatWithPattern(unFormattedValue, displayPattern),\n triggerType: null,\n triggerEvent: null,\n pastedLength: 0,\n };\n }\n return null;\n }\n\n getUserAction = (unformattedValue: string): EventType | string => {\n const { triggerEvent, triggerType, value } = this.state;\n const { displayPattern } = this.props;\n\n if (triggerEvent) {\n if (triggerType === 'Paste' || triggerType === 'Cut') {\n return triggerType;\n }\n\n if ((triggerEvent.ctrlKey || triggerEvent.metaKey) && triggerEvent.key === 'z') {\n return triggerEvent.shiftKey ? 'Redo' : 'Undo';\n }\n\n // Detect mouse event redo\n if (triggerEvent.ctrlKey && triggerEvent.key === 'd') {\n return 'Delete';\n }\n\n // Android Fix.\n if (\n typeof triggerEvent.key === 'undefined' &&\n unformattedValue.length <= unformatWithPattern(value, displayPattern).length\n ) {\n return 'Backspace';\n }\n return triggerEvent.key;\n }\n // triggerEvent can be null only in case of \"autofilling\" (via password manager extension or browser build-in one) events\n return 'Paste';\n };\n\n resetEvent = () => {\n this.setState({\n triggerType: 'Initial',\n triggerEvent: null,\n pastedLength: 0,\n });\n };\n\n detectUndoRedo = (event: React.KeyboardEvent<HTMLTextElement>) => {\n if ((event.ctrlKey || event.metaKey) && event.key === 'z') {\n return event.shiftKey ? 'Redo' : 'Undo';\n }\n return null;\n };\n\n handleOnKeyDown: React.KeyboardEventHandler<HTMLTextElement> = (event) => {\n event.persist();\n const { selectionStart, selectionEnd } = event.currentTarget;\n const { historyNavigator } = this.state;\n const { displayPattern } = this.props;\n\n // Unfortunately Undo and Redo don't trigger OnChange event so we need to handle some value logic here.\n let newFormattedValue = '';\n\n if (this.detectUndoRedo(event) === 'Undo') {\n newFormattedValue = formatWithPattern(historyNavigator.undo().toString(), displayPattern);\n this.setState({ value: newFormattedValue, triggerType: 'Undo' });\n } else if (this.detectUndoRedo(event) === 'Redo') {\n newFormattedValue = formatWithPattern(historyNavigator.redo().toString(), displayPattern);\n this.setState({ value: newFormattedValue, triggerType: 'Redo' });\n } else {\n this.setState({\n triggerEvent: event,\n triggerType: 'KeyDown',\n selectionStart: selectionStart ?? 0,\n selectionEnd: selectionEnd ?? 0,\n });\n }\n };\n\n handleOnPaste: React.ClipboardEventHandler<HTMLTextElement> = (event) => {\n const { displayPattern } = this.props;\n const pastedLength = unformatWithPattern(\n event.clipboardData.getData('Text'),\n displayPattern,\n ).length;\n\n this.setState({ triggerType: 'Paste', pastedLength });\n };\n\n handleOnCut: React.ClipboardEventHandler<HTMLTextElement> = () => {\n this.setState({ triggerType: 'Cut' });\n };\n\n isKeyAllowed = (action: EventType | string) => {\n const { displayPattern } = this.props;\n const symbolsInPattern = displayPattern.split('').filter((character) => character !== '*');\n\n return !symbolsInPattern.includes(action);\n };\n\n handleOnChange: React.ChangeEventHandler<HTMLTextElement> = (event) => {\n const { historyNavigator, triggerType } = this.state;\n const { displayPattern, onChange } = this.props;\n const { value } = event.target;\n let unformattedValue = unformatWithPattern(value, displayPattern);\n const action = this.getUserAction(unformattedValue);\n if (!this.isKeyAllowed(action) || triggerType === 'Undo' || triggerType === 'Redo') {\n return;\n }\n\n if (action === 'Backspace' || action === 'Delete') {\n unformattedValue = this.handleDelete(unformattedValue, action);\n }\n\n const newFormattedValue = formatWithPattern(unformattedValue, displayPattern);\n historyNavigator.add(unformattedValue);\n\n this.handleCursorPositioning(action);\n\n this.setState({ value: newFormattedValue }, () => {\n this.resetEvent();\n if (onChange) {\n const broadcastValue = unformatWithPattern(newFormattedValue, displayPattern);\n onChange(broadcastValue);\n }\n });\n };\n\n handleOnBlur: React.FocusEventHandler<HTMLTextElement> = (event) => {\n this.props.onBlur?.(unformatWithPattern(event.target.value, this.props.displayPattern));\n };\n\n handleOnFocus: React.FocusEventHandler<HTMLTextElement> = (event) => {\n const { displayPattern, onFocus } = this.props;\n if (onFocus) {\n this.handleOnChange(event);\n onFocus(unformatWithPattern(event.target.value, displayPattern));\n }\n };\n\n handleDelete = (unformattedValue: string, action: EventType) => {\n const { displayPattern } = this.props;\n const { selectionStart, selectionEnd } = this.state;\n const newStack = [...unformattedValue];\n if (selectionStart === selectionEnd) {\n let startPosition =\n selectionStart - getCountOfSymbolsInSelection(0, selectionStart, displayPattern);\n let toDelete = 0;\n\n let count = getDistanceToNextSymbol(selectionStart, displayPattern);\n if (action === 'Backspace') {\n startPosition -= 1;\n count = getDistanceToPreviousSymbol(selectionStart, displayPattern);\n }\n\n if (startPosition >= 0 && count) {\n toDelete = 1;\n }\n\n newStack.splice(startPosition, toDelete);\n }\n\n return newStack.join('');\n };\n\n handleCursorPositioning = (action: string) => {\n const { displayPattern } = this.props;\n const { triggerEvent, selectionStart, selectionEnd, pastedLength } = this.state;\n const target = triggerEvent?.currentTarget;\n\n const cursorPosition = getCursorPositionAfterKeystroke(\n action,\n selectionStart,\n selectionEnd,\n displayPattern,\n pastedLength,\n );\n\n setTimeout(() => {\n target?.setSelectionRange(cursorPosition, cursorPosition);\n this.setState({ selectionStart: cursorPosition, selectionEnd: cursorPosition });\n }, 0);\n };\n\n render() {\n const {\n inputMode,\n className,\n id,\n name,\n placeholder,\n readOnly,\n required,\n minLength,\n maxLength,\n disabled,\n autoComplete,\n } = this.props;\n const { value } = this.state;\n const renderProps: TextElementProps = {\n inputMode,\n className,\n id,\n name,\n placeholder,\n readOnly,\n required,\n minLength,\n maxLength,\n disabled,\n autoComplete,\n value,\n onFocus: this.handleOnFocus,\n onBlur: this.handleOnBlur,\n onPaste: this.handleOnPaste,\n onKeyDown: this.handleOnKeyDown,\n onChange: this.handleOnChange,\n onCut: this.handleOnCut,\n };\n return this.props.render(renderProps as T);\n }\n}\n\nexport default WithDisplayFormat;\n"],"names":["WithDisplayFormat","React","Component","defaultProps","autoComplete","displayPattern","value","constructor","props","unformattedValue","unformatWithPattern","state","formatWithPattern","historyNavigator","HistoryNavigator","prevDisplayPattern","triggerType","triggerEvent","selectionStart","selectionEnd","pastedLength","getDerivedStateFromProps","unFormattedValue","reset","getUserAction","ctrlKey","metaKey","key","shiftKey","length","resetEvent","setState","detectUndoRedo","event","handleOnKeyDown","persist","currentTarget","newFormattedValue","undo","toString","redo","handleOnPaste","clipboardData","getData","handleOnCut","isKeyAllowed","action","symbolsInPattern","split","filter","character","includes","handleOnChange","onChange","target","handleDelete","add","handleCursorPositioning","broadcastValue","handleOnBlur","onBlur","handleOnFocus","onFocus","newStack","startPosition","getCountOfSymbolsInSelection","toDelete","count","getDistanceToNextSymbol","getDistanceToPreviousSymbol","splice","join","cursorPosition","getCursorPositionAfterKeystroke","setTimeout","setSelectionRange","render","inputMode","className","id","name","placeholder","readOnly","required","minLength","maxLength","disabled","renderProps","onPaste","onKeyDown","onCut"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,MAAMA,iBAA8C,SAAQC,gBAAK,CAACC,SAGjE,CAAA;AAGC,EAAA,OAAOC,YAAY,GAAG;AACpBC,IAAAA,YAAY,EAAE,KAAK;AACnBC,IAAAA,cAAc,EAAE,EAAE;AAClBC,IAAAA,KAAK,EAAE;GACR;EAEDC,WAAAA,CAAYC,KAA6B,EAAA;IACvC,KAAK,CAACA,KAAK,CAAC;AACZ,IAAA,MAAMC,gBAAgB,GAAGC,2BAAmB,CAACF,KAAK,CAACF,KAAK,IAAI,EAAE,EAAEE,KAAK,CAACH,cAAc,CAAC;IACrF,IAAI,CAACM,KAAK,GAAG;MACXL,KAAK,EAAEM,yBAAiB,CAACH,gBAAgB,EAAED,KAAK,CAACH,cAAc,CAAC;AAChEQ,MAAAA,gBAAgB,EAAE,IAAIC,wBAAgB,EAAE;MACxCC,kBAAkB,EAAEP,KAAK,CAACH,cAAc;AACxCW,MAAAA,WAAW,EAAE,SAAS;AACtBC,MAAAA,YAAY,EAAE,IAAI;AAClBC,MAAAA,cAAc,EAAE,CAAC;AACjBC,MAAAA,YAAY,EAAE,CAAC;AACfC,MAAAA,YAAY,EAAE;KACf;AACH;AAEA,EAAA,OAAOC,wBAAwBA,CAC7B;AAAEhB,IAAAA;AAAwC,GAAA,EAC1C;AAAEU,IAAAA,kBAAkB,GAAGV,cAAc;IAAEC,KAAK;AAAEO,IAAAA;AAA0C,GAAA,EAAA;IAExF,IAAIE,kBAAkB,KAAKV,cAAc,EAAE;AACzC,MAAA,MAAMiB,gB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3,"file":"WithDisplayFormat.js","sources":["../../src/withDisplayFormat/WithDisplayFormat.tsx"],"sourcesContent":["import * as React from 'react';\n\nimport { HistoryNavigator } from '../common';\nimport {\n formatWithPattern,\n getCountOfSymbolsInSelection,\n getCursorPositionAfterKeystroke,\n unformatWithPattern,\n getDistanceToPreviousSymbol,\n getDistanceToNextSymbol,\n} from '../common/textFormat';\nimport { InputProps } from '../inputs/Input';\nimport { TextAreaProps } from '../inputs/TextArea';\n\ntype HTMLTextElement = HTMLInputElement | HTMLTextAreaElement;\ntype TextElementProps = InputProps | TextAreaProps;\n\nexport type EventType =\n | 'KeyDown'\n | 'Paste'\n | 'Cut'\n | 'Undo'\n | 'Redo'\n | 'Backspace'\n | 'Delete'\n | 'Initial';\n\ninterface WithDisplayFormatState {\n value: string;\n historyNavigator: HistoryNavigator;\n prevDisplayPattern: string;\n triggerType: EventType;\n triggerEvent: React.KeyboardEvent<HTMLTextElement> | null;\n pastedLength: number;\n selectionStart: number;\n selectionEnd: number;\n}\n\nexport interface WithDisplayFormatProps<T extends TextElementProps = TextElementProps>\n extends Pick<\n TextElementProps,\n | 'className'\n | 'disabled'\n | 'id'\n | 'maxLength'\n | 'minLength'\n | 'name'\n | 'placeholder'\n | 'readOnly'\n | 'required'\n | 'inputMode'\n > {\n value?: string;\n displayPattern: string;\n /**\n * autocomplete hides our form help so we need to disable it when help text\n * is present. Chrome ignores autocomplete=off, the only way to disable it is\n * to provide an 'invalid' value, for which 'disabled' serves.\n */\n autoComplete?: TextElementProps['autoComplete'] | 'disabled';\n onChange?: (value: string) => void;\n onBlur?: (value: string) => void;\n onFocus?: (value: string) => void;\n render: (renderProps: T) => React.JSX.Element;\n}\n\nclass WithDisplayFormat<T extends TextElementProps> extends React.Component<\n WithDisplayFormatProps<T>,\n WithDisplayFormatState\n> {\n declare props: WithDisplayFormatProps<T> &\n Required<Pick<WithDisplayFormatProps<T>, keyof typeof WithDisplayFormat.defaultProps>>;\n static defaultProps = {\n autoComplete: 'off',\n displayPattern: '',\n value: '',\n };\n\n constructor(props: WithDisplayFormatProps) {\n super(props);\n const unformattedValue = unformatWithPattern(props.value ?? '', props.displayPattern);\n this.state = {\n value: formatWithPattern(unformattedValue, props.displayPattern),\n historyNavigator: new HistoryNavigator(),\n prevDisplayPattern: props.displayPattern,\n triggerType: 'Initial',\n triggerEvent: null,\n selectionStart: 0,\n selectionEnd: 0,\n pastedLength: 0,\n };\n }\n\n static getDerivedStateFromProps(\n { displayPattern }: WithDisplayFormatProps,\n { prevDisplayPattern = displayPattern, value, historyNavigator }: WithDisplayFormatState,\n ) {\n if (prevDisplayPattern !== displayPattern) {\n const unFormattedValue = unformatWithPattern(value, prevDisplayPattern);\n historyNavigator.reset();\n\n return {\n prevDisplayPattern: displayPattern,\n value: formatWithPattern(unFormattedValue, displayPattern),\n triggerType: null,\n triggerEvent: null,\n pastedLength: 0,\n };\n }\n return null;\n }\n\n getUserAction = (unformattedValue: string): EventType | string => {\n const { triggerEvent, triggerType, value } = this.state;\n const { displayPattern } = this.props;\n\n if (triggerEvent) {\n if (triggerType === 'Paste' || triggerType === 'Cut') {\n return triggerType;\n }\n\n if ((triggerEvent.ctrlKey || triggerEvent.metaKey) && triggerEvent.key === 'z') {\n return triggerEvent.shiftKey ? 'Redo' : 'Undo';\n }\n\n // Detect mouse event redo\n if (triggerEvent.ctrlKey && triggerEvent.key === 'd') {\n return 'Delete';\n }\n\n // Android Fix.\n if (\n typeof triggerEvent.key === 'undefined' &&\n unformattedValue.length <= unformatWithPattern(value, displayPattern).length\n ) {\n return 'Backspace';\n }\n return triggerEvent.key;\n }\n // triggerEvent can be null only in case of \"autofilling\" (via password manager extension or browser build-in one) events\n return 'Paste';\n };\n\n resetEvent = () => {\n this.setState({\n triggerType: 'Initial',\n triggerEvent: null,\n pastedLength: 0,\n });\n };\n\n detectUndoRedo = (event: React.KeyboardEvent<HTMLTextElement>) => {\n if ((event.ctrlKey || event.metaKey) && event.key === 'z') {\n return event.shiftKey ? 'Redo' : 'Undo';\n }\n return null;\n };\n\n handleOnKeyDown: React.KeyboardEventHandler<HTMLTextElement> = (event) => {\n event.persist();\n const { selectionStart, selectionEnd } = event.currentTarget;\n const { historyNavigator } = this.state;\n const { displayPattern } = this.props;\n\n // Unfortunately Undo and Redo don't trigger OnChange event so we need to handle some value logic here.\n let newFormattedValue = '';\n\n if (this.detectUndoRedo(event) === 'Undo') {\n newFormattedValue = formatWithPattern(historyNavigator.undo().toString(), displayPattern);\n this.setState({ value: newFormattedValue, triggerType: 'Undo' });\n } else if (this.detectUndoRedo(event) === 'Redo') {\n newFormattedValue = formatWithPattern(historyNavigator.redo().toString(), displayPattern);\n this.setState({ value: newFormattedValue, triggerType: 'Redo' });\n } else {\n this.setState({\n triggerEvent: event,\n triggerType: 'KeyDown',\n selectionStart: selectionStart ?? 0,\n selectionEnd: selectionEnd ?? 0,\n });\n }\n };\n\n handleOnPaste: React.ClipboardEventHandler<HTMLTextElement> = (event) => {\n const { displayPattern } = this.props;\n const pastedLength = unformatWithPattern(\n event.clipboardData.getData('Text'),\n displayPattern,\n ).length;\n\n this.setState({ triggerType: 'Paste', pastedLength });\n };\n\n handleOnCut: React.ClipboardEventHandler<HTMLTextElement> = () => {\n this.setState({ triggerType: 'Cut' });\n };\n\n isKeyAllowed = (action: EventType | string) => {\n const { displayPattern } = this.props;\n const symbolsInPattern = displayPattern.split('').filter((character) => character !== '*');\n\n return !symbolsInPattern.includes(action);\n };\n\n handleOnChange: React.ChangeEventHandler<HTMLTextElement> = (event) => {\n const { historyNavigator, triggerType } = this.state;\n const { displayPattern, onChange } = this.props;\n const { value } = event.target;\n let unformattedValue = unformatWithPattern(value, displayPattern);\n const action = this.getUserAction(unformattedValue);\n if (!this.isKeyAllowed(action) || triggerType === 'Undo' || triggerType === 'Redo') {\n return;\n }\n\n if (action === 'Backspace' || action === 'Delete') {\n unformattedValue = this.handleDelete(unformattedValue, action);\n }\n\n const newFormattedValue = formatWithPattern(unformattedValue, displayPattern);\n historyNavigator.add(unformattedValue);\n\n this.handleCursorPositioning(action);\n\n this.setState({ value: newFormattedValue }, () => {\n this.resetEvent();\n if (onChange) {\n const broadcastValue = unformatWithPattern(newFormattedValue, displayPattern);\n onChange(broadcastValue);\n }\n });\n };\n\n handleOnBlur: React.FocusEventHandler<HTMLTextElement> = (event) => {\n this.props.onBlur?.(unformatWithPattern(event.target.value, this.props.displayPattern));\n };\n\n handleOnFocus: React.FocusEventHandler<HTMLTextElement> = (event) => {\n const { displayPattern, onFocus } = this.props;\n if (onFocus) {\n this.handleOnChange(event);\n onFocus(unformatWithPattern(event.target.value, displayPattern));\n }\n };\n\n handleDelete = (unformattedValue: string, action: EventType) => {\n const { displayPattern } = this.props;\n const { selectionStart, selectionEnd } = this.state;\n const newStack = [...unformattedValue];\n if (selectionStart === selectionEnd) {\n let startPosition =\n selectionStart - getCountOfSymbolsInSelection(0, selectionStart, displayPattern);\n let toDelete = 0;\n\n let count = getDistanceToNextSymbol(selectionStart, displayPattern);\n if (action === 'Backspace') {\n startPosition -= 1;\n count = getDistanceToPreviousSymbol(selectionStart, displayPattern);\n }\n\n if (startPosition >= 0 && count) {\n toDelete = 1;\n }\n\n newStack.splice(startPosition, toDelete);\n }\n\n return newStack.join('');\n };\n\n handleCursorPositioning = (action: string) => {\n const { displayPattern } = this.props;\n const { triggerEvent, selectionStart, selectionEnd, pastedLength } = this.state;\n\n const cursorPosition = getCursorPositionAfterKeystroke(\n action,\n selectionStart,\n selectionEnd,\n displayPattern,\n pastedLength,\n );\n\n setTimeout(() => {\n if (triggerEvent) {\n (triggerEvent.target as HTMLTextElement).setSelectionRange(cursorPosition, cursorPosition);\n }\n this.setState({ selectionStart: cursorPosition, selectionEnd: cursorPosition });\n }, 0);\n };\n\n render() {\n const {\n inputMode,\n className,\n id,\n name,\n placeholder,\n readOnly,\n required,\n minLength,\n maxLength,\n disabled,\n autoComplete,\n } = this.props;\n const { value } = this.state;\n const renderProps: TextElementProps = {\n inputMode,\n className,\n id,\n name,\n placeholder,\n readOnly,\n required,\n minLength,\n maxLength,\n disabled,\n autoComplete,\n value,\n onFocus: this.handleOnFocus,\n onBlur: this.handleOnBlur,\n onPaste: this.handleOnPaste,\n onKeyDown: this.handleOnKeyDown,\n onChange: this.handleOnChange,\n onCut: this.handleOnCut,\n };\n return this.props.render(renderProps as T);\n }\n}\n\nexport default WithDisplayFormat;\n"],"names":["WithDisplayFormat","React","Component","defaultProps","autoComplete","displayPattern","value","constructor","props","unformattedValue","unformatWithPattern","state","formatWithPattern","historyNavigator","HistoryNavigator","prevDisplayPattern","triggerType","triggerEvent","selectionStart","selectionEnd","pastedLength","getDerivedStateFromProps","unFormattedValue","reset","getUserAction","ctrlKey","metaKey","key","shiftKey","length","resetEvent","setState","detectUndoRedo","event","handleOnKeyDown","persist","currentTarget","newFormattedValue","undo","toString","redo","handleOnPaste","clipboardData","getData","handleOnCut","isKeyAllowed","action","symbolsInPattern","split","filter","character","includes","handleOnChange","onChange","target","handleDelete","add","handleCursorPositioning","broadcastValue","handleOnBlur","onBlur","handleOnFocus","onFocus","newStack","startPosition","getCountOfSymbolsInSelection","toDelete","count","getDistanceToNextSymbol","getDistanceToPreviousSymbol","splice","join","cursorPosition","getCursorPositionAfterKeystroke","setTimeout","setSelectionRange","render","inputMode","className","id","name","placeholder","readOnly","required","minLength","maxLength","disabled","renderProps","onPaste","onKeyDown","onCut"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,MAAMA,iBAA8C,SAAQC,gBAAK,CAACC,SAGjE,CAAA;AAGC,EAAA,OAAOC,YAAY,GAAG;AACpBC,IAAAA,YAAY,EAAE,KAAK;AACnBC,IAAAA,cAAc,EAAE,EAAE;AAClBC,IAAAA,KAAK,EAAE;GACR;EAEDC,WAAAA,CAAYC,KAA6B,EAAA;IACvC,KAAK,CAACA,KAAK,CAAC;AACZ,IAAA,MAAMC,gBAAgB,GAAGC,2BAAmB,CAACF,KAAK,C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,MAAAA;KACD,GAAG,IAAI,CAACI,KAAK;IACd,MAAM;AAAEF,MAAAA;KAAO,GAAG,IAAI,CAACK,KAAK;AAC5B,IAAA,MAAM4E,WAAW,GAAqB;MACpCV,SAAS;MACTC,SAAS;MACTC,EAAE;MACFC,IAAI;MACJC,WAAW;MACXC,QAAQ;MACRC,QAAQ;MACRC,SAAS;MACTC,SAAS;MACTC,QAAQ;MACRlF,YAAY;MACZE,KAAK;MACLwD,OAAO,EAAE,IAAI,CAACD,aAAa;MAC3BD,MAAM,EAAE,IAAI,CAACD,YAAY;MACzB6B,OAAO,EAAE,IAAI,CAAC/C,aAAa;MAC3BgD,SAAS,EAAE,IAAI,CAACvD,eAAe;MAC/BmB,QAAQ,EAAE,IAAI,CAACD,cAAc;MAC7BsC,KAAK,EAAE,IAAI,CAAC9C;KACb;AACD,IAAA,OAAO,IAAI,CAACpC,KAAK,CAACoE,MAAM,CAACW,WAAgB,CAAC;AAC5C;;;;;"}
|
|
@@ -249,10 +249,11 @@ class WithDisplayFormat extends React.Component {
|
|
|
249
249
|
selectionEnd,
|
|
250
250
|
pastedLength
|
|
251
251
|
} = this.state;
|
|
252
|
-
const target = triggerEvent?.currentTarget;
|
|
253
252
|
const cursorPosition = getCursorPositionAfterActionStroke(action, selectionStart, selectionEnd, displayPattern, pastedLength);
|
|
254
253
|
setTimeout(() => {
|
|
255
|
-
|
|
254
|
+
if (triggerEvent) {
|
|
255
|
+
triggerEvent.target.setSelectionRange(cursorPosition, cursorPosition);
|
|
256
|
+
}
|
|
256
257
|
this.setState({
|
|
257
258
|
selectionStart: cursorPosition,
|
|
258
259
|
selectionEnd: cursorPosition
|