-
Notifications
You must be signed in to change notification settings - Fork 317
/
Copy pathContentPicker.js
1343 lines (1222 loc) · 40.2 KB
/
ContentPicker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @flow
* @file Content Picker Component
* @author Box
*/
import 'regenerator-runtime/runtime';
import React, { Component } from 'react';
import type { Node } from 'react';
import classNames from 'classnames';
import debounce from 'lodash/debounce';
import getProp from 'lodash/get';
import uniqueid from 'lodash/uniqueId';
import noop from 'lodash/noop';
import Header from '../common/header';
import SubHeader from '../common/sub-header/SubHeader';
import UploadDialog from '../common/upload-dialog';
import CreateFolderDialog from '../common/create-folder-dialog';
import Internationalize from '../common/Internationalize';
import makeResponsive from '../common/makeResponsive';
// $FlowFixMe TypeScript file
import ThemingStyles from '../common/theming';
import Pagination from '../../features/pagination';
import { isFocusableElement, isInputElement, focus } from '../../utils/dom';
import API from '../../api';
import Content from './Content';
import Footer from './Footer';
import {
CLIENT_NAME_CONTENT_PICKER,
DEFAULT_HOSTNAME_API,
DEFAULT_HOSTNAME_UPLOAD,
DEFAULT_PAGE_NUMBER,
DEFAULT_PAGE_SIZE,
DEFAULT_ROOT,
DEFAULT_SEARCH_DEBOUNCE,
DEFAULT_VIEW_FILES,
DEFAULT_VIEW_RECENTS,
ERROR_CODE_ITEM_NAME_INVALID,
ERROR_CODE_ITEM_NAME_TOO_LONG,
FIELD_NAME,
FIELD_PERMISSIONS_CAN_SHARE,
FIELD_SHARED_LINK,
SORT_ASC,
TYPE_FILE,
TYPE_FOLDER,
TYPE_WEBLINK,
TYPED_ID_FOLDER_PREFIX,
VIEW_ERROR,
VIEW_FOLDER,
VIEW_RECENTS,
VIEW_SEARCH,
VIEW_SELECTED,
} from '../../constants';
import { FILE_SHARED_LINK_FIELDS_TO_FETCH } from '../../utils/fields';
// $FlowFixMe TypeScript file
import type { Theme } from '../common/theming';
import type { ElementsXhrError } from '../../common/types/api';
import type {
View,
DefaultView,
StringAnyMap,
StringMap,
SortBy,
SortDirection,
Token,
Access,
BoxItemPermission,
BoxItem,
Collection,
} from '../../common/types/core';
import '../common/fonts.scss';
import '../common/base.scss';
import '../common/modal.scss';
import './ContentPicker.scss';
type Props = {
apiHost: string,
autoFocus: boolean,
canCreateNewFolder: boolean,
canSetShareAccess: boolean,
canUpload: boolean,
cancelButtonLabel?: string,
chooseButtonLabel?: string,
className: string,
clearSelectedItemsOnNavigation: boolean,
clientName: string,
contentUploaderProps: ContentUploaderProps,
currentFolderId?: string,
defaultView: DefaultView,
extensions: string[],
initialPage: number,
initialPageSize: number,
isHeaderLogoVisible?: boolean,
isLarge: boolean,
isPaginationVisible?: boolean,
isSmall: boolean,
isTouch: boolean,
language?: string,
logoUrl?: string,
maxSelectable: number,
measureRef?: Function,
messages?: StringMap,
onCancel: Function,
onChoose: Function,
renderCustomActionButtons?: ({
onCancel: Function,
onChoose: Function,
selectedCount: number,
selectedItems: BoxItem[],
}) => Node,
requestInterceptor?: Function,
responseInterceptor?: Function,
rootFolderId: string,
sharedLink?: string,
sharedLinkPassword?: string,
showSelectedButton: boolean,
sortBy: SortBy,
sortDirection: SortDirection,
theme?: Theme,
token: Token,
type: string,
uploadHost: string,
};
type State = {
currentCollection: Collection,
currentOffset: number,
currentPageSize: number,
errorCode: string,
focusedRow: number,
isCreateFolderModalOpen: boolean,
isLoading: boolean,
isUploadModalOpen: boolean,
rootName: string,
searchQuery: string,
selected: { [string]: BoxItem },
sortBy: SortBy,
sortDirection: SortDirection,
view: View,
};
const defaultType = `${TYPE_FILE},${TYPE_WEBLINK}`;
class ContentPicker extends Component<Props, State> {
id: string;
api: API;
state: State;
props: Props;
table: any;
rootElement: HTMLElement;
appElement: HTMLElement;
globalModifier: boolean;
firstLoad: boolean = true; // Keeps track of very 1st load
static defaultProps = {
type: defaultType,
rootFolderId: DEFAULT_ROOT,
onChoose: noop,
onCancel: noop,
initialPage: DEFAULT_PAGE_NUMBER,
initialPageSize: DEFAULT_PAGE_SIZE,
sortBy: FIELD_NAME,
sortDirection: SORT_ASC,
extensions: [],
maxSelectable: Infinity,
canUpload: true,
canSetShareAccess: true,
canCreateNewFolder: true,
autoFocus: false,
className: '',
apiHost: DEFAULT_HOSTNAME_API,
uploadHost: DEFAULT_HOSTNAME_UPLOAD,
clientName: CLIENT_NAME_CONTENT_PICKER,
defaultView: DEFAULT_VIEW_FILES,
contentUploaderProps: {},
showSelectedButton: true,
clearSelectedItemsOnNavigation: false,
isHeaderLogoVisible: true,
isPaginationVisible: true,
};
/**
* [constructor]
*
* @private
* @return {ContentPicker}
*/
constructor(props: Props) {
super(props);
const {
apiHost,
clientName,
initialPage,
initialPageSize,
language,
requestInterceptor,
responseInterceptor,
rootFolderId,
sharedLink,
sharedLinkPassword,
sortBy,
sortDirection,
token,
uploadHost,
} = props;
this.api = new API({
apiHost,
clientName,
id: `${TYPED_ID_FOLDER_PREFIX}${rootFolderId}`,
language,
requestInterceptor,
responseInterceptor,
sharedLink,
sharedLinkPassword,
token,
uploadHost,
});
this.id = uniqueid('bcp_');
this.state = {
sortBy,
sortDirection,
rootName: '',
currentCollection: {},
currentOffset: initialPageSize * (initialPage - 1),
currentPageSize: initialPageSize,
selected: {},
searchQuery: '',
view: VIEW_FOLDER,
isCreateFolderModalOpen: false,
isUploadModalOpen: false,
focusedRow: 0,
isLoading: false,
errorCode: '',
};
}
/**
* Destroys api instances
*
* @private
* @return {void}
*/
clearCache(): void {
this.api.destroy(true);
}
/**
* Cleanup
*
* @private
* @inheritdoc
* @return {void}
*/
componentWillUnmount() {
this.clearCache();
}
/**
* Fetches the root folder on load
*
* @private
* @inheritdoc
* @return {void}
*/
componentDidMount() {
const { defaultView, currentFolderId }: Props = this.props;
this.rootElement = ((document.getElementById(this.id): any): HTMLElement);
this.appElement = ((this.rootElement.firstElementChild: any): HTMLElement);
if (defaultView === DEFAULT_VIEW_RECENTS) {
this.showRecents();
} else {
this.fetchFolder(currentFolderId);
}
}
/**
* Fetches the current folder if different
* from what was already fetched before.
*
* @private
* @inheritdoc
* @return {void}
*/
componentDidUpdate({ currentFolderId: prevFolderId }: Props, prevState: State): void {
const { currentFolderId }: Props = this.props;
const {
currentCollection: { id },
}: State = prevState;
if (prevFolderId === currentFolderId) {
return;
}
if (typeof currentFolderId === 'string' && id !== currentFolderId) {
this.fetchFolder(currentFolderId);
}
}
/**
* Gets selected items from state.
* Clones values before returning so that
* object references are broken. Also cleans
* up the selected attribute since it was
* added by the file picker.
*
* @private
* @return {BoxItem[]}
*/
getSelectedItems = (): BoxItem[] => {
const { selected }: State = this.state;
return Object.keys(selected).map(key => {
const clone: BoxItem = { ...selected[key] };
delete clone.selected;
return clone;
});
};
/**
* Choose button action.
*
* @private
* @fires choose
* @return {void}
*/
choose = (): void => {
const { onChoose }: Props = this.props;
const results = this.getSelectedItems();
onChoose(results);
};
/**
* Deletes selected keys off of selected items in state.
*
* @private
* @return {void}
*/
deleteSelectedKeys = (): void => {
const { selected }: State = this.state;
// Clear out the selected field
Object.keys(selected).forEach(key => delete selected[key].selected);
};
/**
* Cancel button action
*
* @private
* @fires cancel
* @return {void}
*/
cancel = (): void => {
const { onCancel }: Props = this.props;
this.deleteSelectedKeys();
// Reset the selected state
this.setState({ selected: {} }, () => onCancel());
};
/**
* Resets the percentLoaded in the collection
* so that the loading bar starts showing
*
* @private
* @return {Collection}
*/
currentUnloadedCollection(): Collection {
const { currentCollection }: State = this.state;
return Object.assign(currentCollection, {
percentLoaded: 0,
});
}
/**
* Refreshing the item collection depending
* upon the view. Collection is gotten from cache.
* Navigation event is prevented.
*
* @private
* @return {void}
*/
refreshCollection = (): void => {
const {
currentCollection: { id },
view,
searchQuery,
}: State = this.state;
if (view === VIEW_FOLDER && id) {
this.fetchFolder(id, false);
} else if (view === VIEW_RECENTS) {
this.showRecents(false);
} else if (view === VIEW_SEARCH && searchQuery) {
this.search(searchQuery);
} else if (view === VIEW_SELECTED) {
this.showSelected();
} else {
throw new Error('Cannot refresh incompatible view!');
}
};
/**
* Network error callback
*
* @private
* @param {Error} error error object
* @return {void}
*/
errorCallback = (error: ElementsXhrError, code: string): void => {
this.setState({ view: VIEW_ERROR });
/* eslint-disable no-console */
console.error(error, code);
/* eslint-enable no-console */
};
/**
* Action performed when clicking on an item
*
* @private
* @param {Object|string} item - the clicked box item
* @return {void}
*/
onItemClick = (item: BoxItem | string): void => {
// If the id was passed in, just use that
if (typeof item === 'string') {
this.fetchFolder(item);
return;
}
// If the item was passed in
const { id, type }: BoxItem = item;
if (type === TYPE_FOLDER) {
this.fetchFolder(id);
}
};
/**
* Focuses the grid
*
* @private
* @return {void}
*/
finishNavigation(): void {
const { autoFocus }: Props = this.props;
const {
currentCollection: { percentLoaded },
}: State = this.state;
// If loading for the very first time, only allow focus if autoFocus is true
if (this.firstLoad && !autoFocus) {
this.firstLoad = false;
return;
}
// Don't focus the grid until its loaded and user is not already on an interactable element
if (percentLoaded === 100 && !isFocusableElement(document.activeElement)) {
focus(this.rootElement, '.bcp-item-row');
this.setState({ focusedRow: 0 });
}
this.firstLoad = false;
}
/**
* Folder fetch success callback
*
* @private
* @param {Object} collection item collection object
* @param {Boolean|void} triggerNavigationEvent - To focus the grid
* @return {void}
*/
fetchFolderSuccessCallback(collection: Collection, triggerNavigationEvent: boolean): void {
const { clearSelectedItemsOnNavigation, rootFolderId }: Props = this.props;
const { id, name }: Collection = collection;
const commonState = {
currentCollection: collection,
rootName: id === rootFolderId ? name : '',
};
// New folder state
const newState = clearSelectedItemsOnNavigation ? { ...commonState, selected: {} } : commonState;
// Close any open modals
this.closeModals();
// Deletes selected keys
if (clearSelectedItemsOnNavigation) {
this.deleteSelectedKeys();
}
if (triggerNavigationEvent) {
// Fire folder navigation event
this.setState(newState, this.finishNavigation);
} else {
this.setState(newState);
}
}
/**
* Fetches a folder, defaults to fetching root folder
*
* @private
* @param {string|void} [id] folder id
* @param {Boolean|void} [triggerNavigationEvent] - To focus the grid
* @return {void}
*/
fetchFolder = (id?: string, triggerNavigationEvent?: boolean = true): void => {
const { rootFolderId }: Props = this.props;
const {
currentCollection: { id: currentId },
currentOffset,
currentPageSize: limit,
searchQuery = '',
sortBy,
sortDirection,
}: State = this.state;
const folderId: string = typeof id === 'string' ? id : rootFolderId;
const hasFolderChanged = currentId && currentId !== folderId;
const hasSearchQuery = !!searchQuery.trim().length;
const offset = hasFolderChanged || hasSearchQuery ? 0 : currentOffset; // Reset offset on folder or mode change
// If we are navigating around, aka not first load
// then reset the focus to the root so that after
// the collection loads the activeElement is not the
// button that was clicked to fetch the folder
if (!this.firstLoad) {
this.rootElement.focus();
}
// Reset search state, the view and show busy indicator
this.setState({
searchQuery: '',
view: VIEW_FOLDER,
currentCollection: this.currentUnloadedCollection(),
currentOffset: offset,
});
// Fetch the folder using folder API
this.api.getFolderAPI().getFolder(
folderId,
limit,
offset,
sortBy,
sortDirection,
(collection: Collection) => {
this.fetchFolderSuccessCallback(collection, triggerNavigationEvent);
},
this.errorCallback,
{ forceFetch: true },
);
};
/**
* Recents fetch success callback
*
* @private
* @param {Object} collection item collection object
* @param {Boolean|void} [triggerNavigationEvent] To trigger navigate event
* @return {void}
*/
recentsSuccessCallback(collection: Collection, triggerNavigationEvent: boolean): void {
const newState = { currentCollection: collection };
if (triggerNavigationEvent) {
this.setState(newState, this.finishNavigation);
} else {
this.setState(newState);
}
}
/**
* Shows recents.
* We always try to force fetch recents.
*
* @private
* @param {Boolean|void} [triggerNavigationEvent] To trigger navigate event
* @param {Boolean|void} [forceFetch] To void cache
* @return {void}
*/
showRecents(triggerNavigationEvent: boolean = true): void {
const { rootFolderId }: Props = this.props;
// Reset search state, the view and show busy indicator
this.setState({
searchQuery: '',
view: VIEW_RECENTS,
currentCollection: this.currentUnloadedCollection(),
currentOffset: 0,
});
// Fetch the folder using folder API
this.api.getRecentsAPI().recents(
rootFolderId,
(collection: Collection) => {
this.recentsSuccessCallback(collection, triggerNavigationEvent);
},
this.errorCallback,
{ forceFetch: true },
);
}
/**
* Shows the selected items
*
* @private
* @return {void}
*/
showSelected = (): void => {
const { selected, sortBy, sortDirection }: State = this.state;
this.setState(
{
searchQuery: '',
view: VIEW_SELECTED,
currentCollection: {
sortBy,
sortDirection,
percentLoaded: 100,
items: Object.keys(selected).map(key => this.api.getCache().get(key)),
},
},
this.finishNavigation,
);
};
/**
* Search success callback
*
* @private
* @param {Object} collection item collection object
* @return {void}
*/
searchSuccessCallback = (collection: Collection): void => {
const { currentCollection }: State = this.state;
this.setState({
currentCollection: Object.assign(currentCollection, collection),
});
};
/**
* Debounced searching
*
* @private
* @param {string} id folder id
* @param {string} query search string
* @param {Boolean|void} [forceFetch] To void cache
* @return {void}
*/
debouncedSearch: Function = debounce((id: string, query: string): void => {
const { currentOffset, currentPageSize }: State = this.state;
this.api
.getSearchAPI()
.search(id, query, currentPageSize, currentOffset, this.searchSuccessCallback, this.errorCallback, {
forceFetch: true,
});
}, DEFAULT_SEARCH_DEBOUNCE);
/**
* Searches
*
* @private
* @param {string} query search string
* @return {void}
*/
search = (query: string): void => {
const { rootFolderId }: Props = this.props;
const {
currentCollection: { id },
currentOffset,
searchQuery,
}: State = this.state;
const folderId = typeof id === 'string' ? id : rootFolderId;
const trimmedQuery: string = query.trim();
if (!query) {
// Cancel the debounce so we don't search on a previous query
this.debouncedSearch.cancel();
// Query was cleared out, load the prior folder
// The prior folder is always the parent folder for search
this.setState({ currentOffset: 0 }, () => {
this.fetchFolder(folderId, false);
});
return;
}
if (!trimmedQuery) {
// Query now only has bunch of spaces
// do nothing and but update prior state
this.setState({
searchQuery: query,
});
return;
}
this.setState({
searchQuery: query,
view: VIEW_SEARCH,
currentCollection: this.currentUnloadedCollection(),
currentOffset: trimmedQuery === searchQuery ? currentOffset : 0,
});
this.debouncedSearch(folderId, query);
};
/**
* Uploads
*
* @private
* @param {File} file dom file object
* @return {void}
*/
upload = (): void => {
const {
currentCollection: { id, permissions },
}: State = this.state;
const { canUpload }: Props = this.props;
if (!id || !permissions) {
return;
}
const { can_upload: canUploadPermission }: BoxItemPermission = permissions;
if (!canUpload || !canUploadPermission) {
return;
}
this.setState({ isUploadModalOpen: true });
};
/**
* Upload success handler
*
* @private
* @param {File} file dom file object
* @return {void}
*/
uploadSuccessHandler = (): void => {
const {
currentCollection: { id },
}: State = this.state;
this.fetchFolder(id, false);
};
/**
* Creates a new folder
*
* @private
* @return {void}
*/
createFolder = (): void => {
this.createFolderCallback();
};
/**
* New folder callback
*
* @private
* @param {string} name - folder name
* @return {void}
*/
createFolderCallback = (name?: string): void => {
const { isCreateFolderModalOpen, currentCollection }: State = this.state;
const { canCreateNewFolder }: Props = this.props;
if (!canCreateNewFolder) {
return;
}
const { id, permissions }: Collection = currentCollection;
if (!id || !permissions) {
return;
}
const { can_upload }: BoxItemPermission = permissions;
if (!can_upload) {
return;
}
if (!isCreateFolderModalOpen || !name) {
this.setState({ isCreateFolderModalOpen: true, errorCode: '' });
return;
}
if (!name.trim()) {
this.setState({
errorCode: ERROR_CODE_ITEM_NAME_INVALID,
isLoading: false,
});
return;
}
if (name.length > 255) {
this.setState({
errorCode: ERROR_CODE_ITEM_NAME_TOO_LONG,
isLoading: false,
});
return;
}
this.setState({ isLoading: true });
this.api.getFolderAPI().create(
id,
name.trim(),
() => {
this.fetchFolder(id);
},
({ code }) => {
this.setState({
errorCode: code,
isLoading: false,
});
},
);
};
/**
* Selects or unselects an item
*
* @private
* @param {Object} item file or folder object
* @param {boolean} options.forceSharedLink Force a shared link if no link exists
* @return {void}
*/
select = (item: BoxItem, { forceSharedLink = true }: StringAnyMap = {}): void => {
const { canSetShareAccess, type: selectableType, maxSelectable }: Props = this.props;
const {
view,
selected,
currentCollection: { items = [] },
}: State = this.state;
const { id, type }: BoxItem = item;
if (!id || !type || selectableType.indexOf(type) === -1) {
return;
}
const selectedKeys: Array<string> = Object.keys(selected);
const selectedCount: number = selectedKeys.length;
const hasHitSelectionLimit: boolean = selectedCount === maxSelectable;
const isSingleFileSelection: boolean = maxSelectable === 1;
const cacheKey: string = this.api.getAPI(type).getCacheKey(id);
const existing: BoxItem = selected[cacheKey];
const existingFromCache: BoxItem = this.api.getCache().get(cacheKey);
const existInSelected = selectedKeys.indexOf(cacheKey) !== -1;
// Existing object could have mutated and we just need to update the
// reference in the selected map. In that case treat it like a new selection.
if (existing && existing === existingFromCache) {
// We are selecting the same item that was already
// selected. Unselect it in this case. Toggle case.
delete existing.selected;
delete selected[cacheKey];
} else {
// We are selecting a new item that was never
// selected before. However if we are in a single
// item selection mode, we should also unselect any
// prior item that was selected.
// Check if we hit the selection limit and if selection
// is not already currently in the selected data structure.
// Ignore when in single file selection mode.
if (hasHitSelectionLimit && !isSingleFileSelection && !existInSelected) {
return;
}
// Clear out the prior item for single file selection mode
if (selectedCount > 0 && isSingleFileSelection) {
const prior = selectedKeys[0]; // only one item
delete selected[prior].selected;
delete selected[prior];
}
// Select the new item
item.selected = true;
selected[cacheKey] = item;
// If can set share access, fetch the shared link properties of the item
// In the case where another item is selected, any in flight XHR will get
// cancelled
if (canSetShareAccess && forceSharedLink) {
this.fetchSharedLinkInfo(item);
}
}
const focusedRow = items.findIndex((i: BoxItem) => i.id === item.id);
this.setState({ selected, focusedRow }, () => {
if (view === VIEW_SELECTED) {
// Need to refresh the selected view
this.showSelected();
}
});
};
/**
* Fetch the shared link info
* @param {BoxItem} item - The item (folder, file, weblink)
* @returns {void}
*/
fetchSharedLinkInfo = (item: BoxItem): void => {
const { id, type }: BoxItem = item;
switch (type) {
case TYPE_FOLDER:
this.api.getFolderAPI().getFolderFields(id, this.handleSharedLinkSuccess, noop, {
fields: FILE_SHARED_LINK_FIELDS_TO_FETCH,
});
break;
case TYPE_FILE:
this.api
.getFileAPI()
.getFile(id, this.handleSharedLinkSuccess, noop, { fields: FILE_SHARED_LINK_FIELDS_TO_FETCH });
break;
case TYPE_WEBLINK:
this.api
.getWebLinkAPI()
.getWeblink(id, this.handleSharedLinkSuccess, noop, { fields: FILE_SHARED_LINK_FIELDS_TO_FETCH });
break;
default:
throw new Error('Unknown Type');
}
};
/**
* Handles the shared link info by either creating a share link using enterprise defaults if
* it does not already exist, otherwise update the item in the state currentCollection.
*
* @param {Object} item file or folder
* @returns {void}
*/
handleSharedLinkSuccess = async (item: BoxItem) => {
const { selected } = this.state;
const { id, type } = item;
// $FlowFixMe
const cacheKey = this.api.getAPI(type).getCacheKey(id);
let updatedItem = item;
// if there is no shared link, create one with enterprise default access
if (!item[FIELD_SHARED_LINK] && getProp(item, FIELD_PERMISSIONS_CAN_SHARE, false)) {
// $FlowFixMe
await this.api.getAPI(item.type).share(item, undefined, (sharedItem: BoxItem) => {
updatedItem = sharedItem;
});
}
this.updateItemInCollection(updatedItem);
if (updatedItem.selected && updatedItem !== selected[cacheKey]) {
this.select(updatedItem, { forceSharedLink: false });
}
};
/**
* Changes the share access of an item
*
* @private
* @param {string} access share access
* @param {Object} item file or folder object
* @return {void}
*/
changeShareAccess = (access: Access, item: BoxItem): void => {
const { canSetShareAccess }: Props = this.props;
if (!item || !canSetShareAccess) {
return;
}
const { permissions, type }: BoxItem = item;
if (!permissions || !type) {
return;
}
const { can_set_share_access }: BoxItemPermission = permissions;
if (!can_set_share_access) {
return;
}
this.api.getAPI(type).share(item, access, (updatedItem: BoxItem) => {
this.updateItemInCollection(updatedItem);
if (item.selected) {
this.select(updatedItem, { forceSharedLink: false });
}
});
};
/**
* Updates the BoxItem in the state's currentCollection
*
* @param {Object} item file or folder object
* @returns {void}