@transferwise/components 0.0.0-experimental-62a0fe9 → 0.0.0-experimental-c483cc2

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.
@@ -12,6 +12,36 @@ import { TEST_IDS as UPLOAD_ITEM_TEST_IDS } from './uploadItem/UploadItem';
12
12
 
13
13
  const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTimeAsync });
14
14
 
15
+ const deleteFileAndWaitForFocus = async (fileToDeleteTestId: string, nextFocusTestId: string) => {
16
+ const fileToDelete = screen.getByTestId(fileToDeleteTestId);
17
+ const nextFocus = screen.getByTestId(nextFocusTestId);
18
+
19
+ await act(async () => {
20
+ within(fileToDelete).getByLabelText('Remove file', { exact: false }).click();
21
+ await jest.runOnlyPendingTimersAsync();
22
+ });
23
+
24
+ await act(async () => {
25
+ const removeButton = screen.queryByText('Remove');
26
+ if (removeButton) {
27
+ removeButton.click();
28
+ await jest.runOnlyPendingTimersAsync();
29
+ }
30
+ });
31
+
32
+ await waitFor(() => {
33
+ expect(screen.queryByTestId(fileToDeleteTestId)).not.toBeInTheDocument();
34
+ });
35
+
36
+ await act(async () => {
37
+ await jest.runOnlyPendingTimersAsync();
38
+ });
39
+
40
+ await waitFor(() => {
41
+ expect(nextFocus).toHaveFocus();
42
+ });
43
+ };
44
+
15
45
  mockMatchMedia();
16
46
 
17
47
  describe('UploadInput', () => {
@@ -139,15 +169,21 @@ describe('UploadInput', () => {
139
169
  onFilesChange,
140
170
  });
141
171
 
142
- const fileToDelete = screen.getAllByTestId(UPLOAD_ITEM_TEST_IDS.uploadItem)[0];
143
- within(fileToDelete).getByLabelText('Remove file', { exact: false }).click();
172
+ const fileToDelete = screen.getByTestId('1-uploadItem');
144
173
  await act(async () => {
174
+ within(fileToDelete).getByLabelText('Remove file', { exact: false }).click();
145
175
  await jest.runOnlyPendingTimersAsync();
146
176
  });
147
177
 
148
- screen.getByText('Remove').click();
178
+ await act(async () => {
179
+ screen.getByText('Remove').click();
180
+ await jest.runOnlyPendingTimersAsync();
181
+ });
182
+
183
+ await waitFor(() => {
184
+ expect(screen.queryByTestId('1-uploadItem')).not.toBeInTheDocument();
185
+ });
149
186
 
150
- await waitForElementToBeRemoved(fileToDelete);
151
187
  expect(props.onDeleteFile).toHaveBeenCalledWith(files[0].id);
152
188
 
153
189
  expect(onFilesChange).toHaveBeenCalledTimes(2);
@@ -190,9 +226,9 @@ describe('UploadInput', () => {
190
226
  onFilesChange,
191
227
  });
192
228
 
193
- const fileToDelete = screen.getAllByTestId(UPLOAD_ITEM_TEST_IDS.uploadItem)[0];
194
- within(fileToDelete).getByLabelText('Remove file', { exact: false }).click();
229
+ const fileToDelete = screen.getByTestId('1-uploadItem');
195
230
  await act(async () => {
231
+ within(fileToDelete).getByLabelText('Remove file', { exact: false }).click();
196
232
  await jest.runOnlyPendingTimersAsync();
197
233
  });
198
234
 
@@ -212,6 +248,114 @@ describe('UploadInput', () => {
212
248
 
213
249
  expect(screen.queryByLabelText('Remove file ', { exact: false })).not.toBeInTheDocument();
214
250
  });
251
+
252
+ it('should focus the next item after a file is deleted', async () => {
253
+ const files = [
254
+ {
255
+ id: 1,
256
+ filename: 'Sales-2024-invoice.pdf',
257
+ status: Status.DONE,
258
+ },
259
+ {
260
+ id: 2,
261
+ filename: 'CoWork-0317-invoice.pdf',
262
+ status: Status.DONE,
263
+ },
264
+ {
265
+ id: 3,
266
+ filename: 'purchase-receipt.pdf',
267
+ status: Status.DONE,
268
+ },
269
+ ];
270
+
271
+ renderComponent({
272
+ ...props,
273
+ files,
274
+ multiple: true,
275
+ onFilesChange,
276
+ });
277
+
278
+ await deleteFileAndWaitForFocus('1-uploadItem', '2-action');
279
+ });
280
+
281
+ it('should focus the upload input after the last file is deleted', async () => {
282
+ const files = [
283
+ {
284
+ id: 1,
285
+ filename: 'Sales-2024-invoice.pdf',
286
+ status: Status.DONE,
287
+ },
288
+ {
289
+ id: 2,
290
+ filename: 'CoWork-0317-invoice.pdf',
291
+ status: Status.DONE,
292
+ },
293
+ {
294
+ id: 3,
295
+ filename: 'purchase-receipt.pdf',
296
+ status: Status.DONE,
297
+ },
298
+ ];
299
+
300
+ renderComponent({
301
+ ...props,
302
+ files,
303
+ multiple: true,
304
+ onFilesChange,
305
+ });
306
+
307
+ await deleteFileAndWaitForFocus('3-uploadItem', 'uploadInput');
308
+ });
309
+
310
+ it('should focus the upload input after the only file is deleted', async () => {
311
+ const singleFile = [
312
+ {
313
+ id: 3,
314
+ filename: 'purchase-receipt.pdf',
315
+ status: Status.DONE,
316
+ },
317
+ ];
318
+
319
+ renderComponent({
320
+ ...props,
321
+ files: singleFile,
322
+ multiple: true,
323
+ onFilesChange,
324
+ });
325
+
326
+ await deleteFileAndWaitForFocus('3-uploadItem', 'uploadInput');
327
+ });
328
+
329
+ it('should focus the third item, then the second and finally upload input', async () => {
330
+ const filesWithFailed = [
331
+ {
332
+ id: 1,
333
+ filename: 'Sales-2024-invoice.pdf',
334
+ status: Status.DONE,
335
+ },
336
+ {
337
+ id: 2,
338
+ filename: 'CoWork-0317-invoice.pdf',
339
+ status: Status.FAILED,
340
+ },
341
+ {
342
+ id: 3,
343
+ filename: 'purchase-receipt.pdf',
344
+ status: Status.DONE,
345
+ },
346
+ ];
347
+
348
+ renderComponent({
349
+ ...props,
350
+ files: filesWithFailed,
351
+ multiple: true,
352
+ onFilesChange,
353
+ });
354
+
355
+ await deleteFileAndWaitForFocus('3-uploadItem', 'uploadInput');
356
+ await deleteFileAndWaitForFocus('1-uploadItem', '2-action');
357
+ await deleteFileAndWaitForFocus('2-uploadItem', 'uploadInput');
358
+ });
215
359
  });
216
360
 
217
361
  describe('Max File Upload limit', () => {
@@ -1,5 +1,5 @@
1
1
  import { clsx } from 'clsx';
2
- import { useEffect, useRef, useState, useLayoutEffect } from 'react';
2
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
3
3
  import { useIntl } from 'react-intl';
4
4
 
5
5
  import Button from '../button';
@@ -99,16 +99,45 @@ export type UploadInputProps = {
99
99
  'disabled' | 'multiple' | 'fileTypes' | 'sizeLimit' | 'description' | 'id' | 'uploadButtonTitle'
100
100
  > & { onDownload?: UploadItemProps['onDownload'] } & CommonProps;
101
101
 
102
+ /**
103
+ * Interface representing a reference to an UploadItem component.
104
+ * Provides a method to focus the UploadItem.
105
+ */
102
106
  interface UploadItemRef {
107
+ /**
108
+ * Focuses the UploadItem component.
109
+ */
103
110
  focus: () => void;
104
111
  }
105
112
 
113
+ /**
114
+ * Represents the next item to focus on after an action is performed.
115
+ */
116
+ type NextFocusItem = {
117
+ /** The ID of the next item to focus on. If null, no specific item is targeted. */
118
+ focusId: number | null;
119
+ /** Indicates if the next item to focus on is the last item in the list. */
120
+ isLastItem: boolean;
121
+ };
122
+
123
+ /**
124
+ * Generates a unique ID for a file based on its name, size, and the current timestamp
125
+ */
106
126
  function generateFileId(file: File) {
107
127
  const { name, size } = file;
108
128
  const uploadTimeStamp = new Date().getTime();
109
129
  return `${name}_${size}_${uploadTimeStamp}`;
110
130
  }
111
131
 
132
+ /**
133
+ * The component allows users to upload files, manage the list of uploaded files,
134
+ * and handle file validation and deletion.
135
+ *
136
+ * @param {UploadInputProps} props - The properties for the UploadInput component.
137
+ *
138
+ * @see {@link UploadInput} for further information.
139
+ * @see {@link https://storybook.wise.design/?path=/docs/forms-uploadinput--docs|Storybook Wise Design}
140
+ */
112
141
  const UploadInput = ({
113
142
  files = [],
114
143
  fileInputName = 'file',
@@ -131,15 +160,15 @@ const UploadInput = ({
131
160
  uploadButtonTitle,
132
161
  }: UploadInputProps) => {
133
162
  const inputAttributes = useInputAttributes({ nonLabelable: true });
134
-
135
163
  const [markedFileForDelete, setMarkedFileForDelete] = useState<UploadedFile | null>(null);
136
- const [fileToRemoveIndex, setFileToRemoveIndex] = useState<number | null>(null);
164
+ const [nextFocusItem, setNextFocusItem] = useState<NextFocusItem | null>(null);
137
165
  const [mounted, setMounted] = useState(false);
138
166
  const { formatMessage } = useIntl();
139
167
  const itemRefs = useRef<(HTMLDivElement | UploadItemRef | null)[]>([]);
140
168
  const uploadInputRef = useRef<HTMLInputElement | null>(null);
141
169
 
142
170
  const PROGRESS_STATUSES = new Set([Status.PENDING, Status.PROCESSING]);
171
+ const FOCUS_TIMEOUT = 400;
143
172
 
144
173
  const [uploadedFiles, setUploadedFiles] = useState<readonly UploadedFile[]>(
145
174
  multiple || files.length === 0 ? files : [files[0]],
@@ -147,50 +176,64 @@ const UploadInput = ({
147
176
 
148
177
  const uploadedFilesListReference = useRef(multiple || files.length === 0 ? files : [files[0]]);
149
178
 
150
- function addFileToList(recentUploadedFile: UploadedFile) {
151
- function addToList(listToAddTo: readonly UploadedFile[]) {
152
- return [...listToAddTo, recentUploadedFile];
153
- }
154
-
155
- setUploadedFiles(addToList);
156
- uploadedFilesListReference.current = addToList(uploadedFilesListReference.current);
179
+ function updateFileList(updateFn: (list: readonly UploadedFile[]) => readonly UploadedFile[]) {
180
+ setUploadedFiles(updateFn);
181
+ uploadedFilesListReference.current = updateFn(uploadedFilesListReference.current);
157
182
  }
158
183
 
159
- const removeFileFromList = (file: UploadedFile) => {
160
- function filterOutFrom(listToFilterFrom: readonly UploadedFile[]) {
161
- return listToFilterFrom.filter(
162
- (fileInList) => file !== fileInList && file.id !== fileInList.id,
163
- );
164
- }
165
-
166
- setUploadedFiles(filterOutFrom);
167
- uploadedFilesListReference.current = filterOutFrom(uploadedFilesListReference.current);
168
- };
184
+ function addFileToList(recentUploadedFile: UploadedFile) {
185
+ updateFileList((list) => [...list, recentUploadedFile]);
186
+ }
169
187
 
170
- const modifyFileInList = (file: UploadedFile, updates: Partial<UploadedFile>) => {
171
- const updateListItem = (listToUpdate: readonly UploadedFile[]) =>
172
- listToUpdate.map((fileInList) => {
173
- return fileInList === file || fileInList.id === file.id
174
- ? { ...file, ...updates }
175
- : fileInList;
176
- });
188
+ function removeFileFromList(file: UploadedFile) {
189
+ updateFileList((list) =>
190
+ list.filter((fileInList) => file !== fileInList && file.id !== fileInList.id),
191
+ );
192
+ }
177
193
 
178
- setUploadedFiles(updateListItem);
179
- uploadedFilesListReference.current = updateListItem(uploadedFilesListReference.current);
180
- };
194
+ function modifyFileInList(file: UploadedFile, updates: Partial<UploadedFile>) {
195
+ updateFileList((list) =>
196
+ list.map((fileInList) =>
197
+ fileInList === file || fileInList.id === file.id ? { ...file, ...updates } : fileInList,
198
+ ),
199
+ );
200
+ }
181
201
 
182
- const [fileToRemove, setFileToRemove] = useState<UploadedFile | null>(null);
202
+ function focusNextItem(
203
+ focusId: number | null = null,
204
+ isLastItem = false,
205
+ timeout: number = FOCUS_TIMEOUT,
206
+ ) {
207
+ const nextFocusIdIndex = focusId
208
+ ? uploadedFilesListReference.current.findIndex((item: UploadedFile) => item.id === focusId)
209
+ : -1;
210
+
211
+ requestAnimationFrame(() => {
212
+ setTimeout(() => {
213
+ if (isLastItem || nextFocusIdIndex === -1) {
214
+ // If it's the last item or no next item, focus on the upload input reference
215
+ uploadInputRef.current?.focus();
216
+ } else {
217
+ const nextFocusElement = itemRefs.current[nextFocusIdIndex];
218
+ nextFocusElement?.focus();
219
+ }
220
+ }, timeout);
221
+ });
222
+ }
183
223
 
184
224
  const removeFile = (file: UploadedFile) => {
185
225
  const { id, status } = file;
186
226
  const index = uploadedFiles.findIndex((f) => f.id === file.id);
187
- setFileToRemoveIndex(index);
227
+ const isLastItem = index === uploadedFiles.length - 1;
228
+ const nextIndexId = uploadedFiles[index + 1]?.id as number;
229
+ const focusId = nextIndexId ?? null;
188
230
 
189
231
  if (status === Status.FAILED) {
190
232
  removeFileFromList(file);
191
- setFileToRemove(file);
233
+ setNextFocusItem({ focusId: focusId ?? null, isLastItem });
192
234
  } else if (onDeleteFile && id) {
193
235
  modifyFileInList(file, { status: Status.PROCESSING, error: undefined });
236
+ setNextFocusItem({ focusId, isLastItem });
194
237
 
195
238
  onDeleteFile(id)
196
239
  .then(() => {
@@ -198,9 +241,7 @@ const UploadInput = ({
198
241
  })
199
242
  .catch((error) => {
200
243
  modifyFileInList(file, { error: error as UploadError });
201
- })
202
- .finally(() => {
203
- setFileToRemove(file);
244
+ setNextFocusItem({ focusId, isLastItem });
204
245
  });
205
246
  }
206
247
  };
@@ -239,12 +280,10 @@ const UploadInput = ({
239
280
  return numberOfValidFiles >= maxFiles;
240
281
  }
241
282
 
242
- // One or more files selected, create entries for them
243
283
  const addFiles = (selectedFiles: FileList) => {
244
284
  for (let i = 0; i < selectedFiles.length; i += 1) {
245
285
  const file = selectedFiles.item(i);
246
286
 
247
- // Returning a FormData[] array instead of FileList so we can filter out incorrect files
248
287
  const formData = new FormData();
249
288
 
250
289
  if (file) {
@@ -253,14 +292,11 @@ const UploadInput = ({
253
292
 
254
293
  const allowedFileTypes = typeof fileTypes === 'string' ? fileTypes : fileTypes.join(',');
255
294
 
256
- // Check if file type is valid
257
295
  if (!isTypeValid(file, allowedFileTypes)) {
258
296
  handleFileUploadFailure(file, formatMessage(MESSAGES.fileTypeNotSupported));
259
297
  continue;
260
298
  }
261
299
 
262
- // Check if the filesize is valid
263
- // Convert to rough bytes
264
300
  if (!isSizeValid(file, sizeLimit * 1000)) {
265
301
  const failureMessage = sizeLimitErrorMessage || formatMessage(MESSAGES.fileIsTooLarge);
266
302
  handleFileUploadFailure(file, failureMessage);
@@ -275,14 +311,11 @@ const UploadInput = ({
275
311
  continue;
276
312
  }
277
313
 
278
- // Check if the file is already in the list
279
314
  const existingFile = uploadedFiles.find((f) => f.filename === file.name);
280
315
  if (existingFile) {
281
- // Remove the file from the list before adding it again
282
316
  removeFileFromList(existingFile);
283
317
  }
284
318
 
285
- // Add the file to the list
286
319
  formData.append(fileInputName, file);
287
320
  const pendingFile = {
288
321
  id: generateFileId(file),
@@ -292,10 +325,8 @@ const UploadInput = ({
292
325
 
293
326
  addFileToList(pendingFile);
294
327
 
295
- // Start uploading the file
296
328
  onUploadFile(formData)
297
329
  .then(({ id, url, error }: UploadResponse) => {
298
- // Replace the temporary id with the final one received from the API, and also set any errors
299
330
  modifyFileInList(pendingFile, { id, url, error, status: Status.SUCCEEDED });
300
331
  })
301
332
  .catch((error) => {
@@ -303,7 +334,6 @@ const UploadInput = ({
303
334
  });
304
335
 
305
336
  if (!multiple) {
306
- // Only upload a single file
307
337
  break;
308
338
  }
309
339
  }
@@ -311,20 +341,11 @@ const UploadInput = ({
311
341
  };
312
342
 
313
343
  useLayoutEffect(() => {
314
- if (fileToRemove && fileToRemoveIndex !== null) {
315
- requestAnimationFrame(() => {
316
- const nextFocusIndex = Math.min(fileToRemoveIndex, uploadedFiles.length - 1);
317
- if (itemRefs.current[nextFocusIndex]) {
318
- itemRefs.current[nextFocusIndex].focus(); // Focus the next UploadItem
319
- } else {
320
- // If there's only one item left, focus the UploadButton
321
- uploadInputRef.current?.focus();
322
- }
323
- });
324
- setFileToRemove(null); // Reset the state
325
- setFileToRemoveIndex(null); // Reset the index
344
+ if (nextFocusItem) {
345
+ focusNextItem(nextFocusItem.focusId, nextFocusItem.isLastItem);
326
346
  }
327
- }, [uploadedFiles, fileToRemove, fileToRemoveIndex, itemRefs, uploadInputRef]);
347
+ setNextFocusItem(null);
348
+ }, [nextFocusItem]);
328
349
 
329
350
  useEffect(() => {
330
351
  setMounted(true);
@@ -4,9 +4,8 @@ import { forwardRef, useImperativeHandle, useRef } from 'react';
4
4
  import { useIntl } from 'react-intl';
5
5
 
6
6
  import Body from '../../body';
7
- import { Size, Status, Typography, Sentiment } from '../../common';
7
+ import { Size, Status, Typography } from '../../common';
8
8
  import ProcessIndicator from '../../processIndicator/ProcessIndicator';
9
- import StatusIcon from '../../statusIcon/StatusIcon';
10
9
  import { UploadedFile, UploadError } from '../types';
11
10
 
12
11
  import MESSAGES from './UploadItem.messages';
@@ -38,6 +37,8 @@ interface UploadItemRef {
38
37
  export enum TEST_IDS {
39
38
  uploadItem = 'uploadItem',
40
39
  mediaBody = 'mediaBody',
40
+ link = 'link',
41
+ action = 'action',
41
42
  }
42
43
 
43
44
  const UploadItem = forwardRef<UploadItemRef, UploadItemProps>(
@@ -46,6 +47,7 @@ const UploadItem = forwardRef<UploadItemRef, UploadItemProps>(
46
47
  const { status, filename, error, errors, url } = file;
47
48
  const linkRef = useRef<HTMLAnchorElement>(null);
48
49
  const buttonRef = useRef<HTMLButtonElement>(null);
50
+ const isSucceeded = [Status.SUCCEEDED, undefined].includes(status) && !!url;
49
51
 
50
52
  useImperativeHandle<UploadItemRef, UploadItemRef>(ref, () => ({
51
53
  focus: (): void => {
@@ -57,8 +59,6 @@ const UploadItem = forwardRef<UploadItemRef, UploadItemProps>(
57
59
  },
58
60
  }));
59
61
 
60
- const isSucceeded = [Status.SUCCEEDED, undefined].includes(status) && !!url;
61
-
62
62
  /**
63
63
  * We're temporarily reverting to the regular icon components,
64
64
  * until the StatusIcon receives 24px sizing. Some misalignment
@@ -152,16 +152,20 @@ const UploadItem = forwardRef<UploadItemRef, UploadItemProps>(
152
152
  return (
153
153
  <div
154
154
  className={clsx('np-upload-input__item', { 'is-interactive': isSucceeded && url })}
155
- data-testid={TEST_IDS.uploadItem}
155
+ data-testid={`${file.id}-${TEST_IDS.uploadItem}`}
156
156
  >
157
157
  <UploadItemLink
158
158
  ref={linkRef}
159
159
  url={isSucceeded ? url : undefined}
160
160
  singleFileUpload={singleFileUpload}
161
+ data-testid={`${file.id}-${TEST_IDS.link}`}
161
162
  onDownload={onDownloadFile}
162
163
  >
163
164
  <span className="np-upload-input__icon">{getIcon()}</span>
164
- <div className="np-upload-input__item-content" data-testid={TEST_IDS.mediaBody}>
165
+ <div
166
+ className="np-upload-input__item-content"
167
+ data-testid={`${file.id}-${TEST_IDS.mediaBody}`}
168
+ >
165
169
  <Body type={Typography.BODY_LARGE} className="np-upload-input__title text-word-break">
166
170
  {getTitle()}
167
171
  </Body>
@@ -175,6 +179,8 @@ const UploadItem = forwardRef<UploadItemRef, UploadItemProps>(
175
179
  aria-label={formatMessage(MESSAGES.removeFile, { filename })}
176
180
  className="np-upload-input__item-button"
177
181
  type="button"
182
+ tabIndex={0}
183
+ data-testid={`${file.id}-${TEST_IDS.action}`}
178
184
  onClick={() => onDelete()}
179
185
  >
180
186
  <Bin size={16} />
@@ -10,7 +10,14 @@ type UploadItemLinkProps = PropsWithChildren<{
10
10
  export const UploadItemLink = forwardRef<HTMLAnchorElement | HTMLDivElement, UploadItemLinkProps>(
11
11
  ({ children, url, onDownload, singleFileUpload }, ref) => {
12
12
  if (!url) {
13
- return <div ref={ref as React.RefObject<HTMLDivElement>} className={clsx('np-upload-input__item-container')}>{children}</div>;
13
+ return (
14
+ <div
15
+ ref={ref as React.RefObject<HTMLDivElement>}
16
+ className={clsx('np-upload-input__item-container')}
17
+ >
18
+ {children}
19
+ </div>
20
+ );
14
21
  }
15
22
 
16
23
  return (
@@ -23,6 +30,7 @@ export const UploadItemLink = forwardRef<HTMLAnchorElement | HTMLDivElement, Upl
23
30
  'np-upload-input__item-link',
24
31
  singleFileUpload ? 'np-upload-input__item-link--single-file' : '',
25
32
  )}
33
+ tabIndex={0}
26
34
  onClick={onDownload}
27
35
  >
28
36
  {children}