/
ResultsTable.jsx
790 lines (753 loc) · 31 KB
/
ResultsTable.jsx
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
import React from 'react';
import { Link } from 'react-router-dom';
import {
TableContainer, Table, TableHead, TableBody, TableCell, TableRow,
Collapse, IconButton, Box, Paper, Tabs, Tab, Checkbox, TableSortLabel, Tooltip, Button,
} from '@material-ui/core';
import {
KeyboardArrowDown as KeyboardArrowDownIcon,
KeyboardArrowUp as KeyboardArrowUpIcon,
LocalOffer as LocalOfferIcon,
Link as LinkIcon,
AccountTreeRounded as TreeIcon,
Flag as FlagIcon,
ArrowForward as ForwardIcon,
Public as PublicIcon,
List as ListIcon,
Person as PersonIcon,
Home as HomeIcon,
Loyalty as LoyaltyIcon,
CompareArrows as CompareArrowsIcon,
Delete as DeleteIcon,
GetApp as DownloadIcon,
} from '@material-ui/icons'
import { Pagination } from '@material-ui/lab'
import {
map, startCase, get, without, uniq, includes, find, keys, values, isEmpty, filter, reject
} from 'lodash';
import {
BLUE, WHITE, DARKGRAY, COLOR_ROW_SELECTED, ORANGE, GREEN, EMPTY_VALUE
} from '../../common/constants';
import {
formatDate, formatDateTime, headFirst, isLoggedIn, defaultCreatePin, defaultDeletePin,
getCurrentUserUsername, isCurrentUserMemberOf, isAdminUser, currentUserHasAccess,
} from '../../common/utils';
import ReferenceChip from '../common/ReferenceChip';
import OwnerChip from '../common/OwnerChip';
import ReleasedChip from '../common/ReleasedChip';
import DownloadButton from '../common/DownloadButton';
import ToConceptLabel from '../mappings/ToConceptLabel';
import FromConceptLabel from '../mappings/FromConceptLabel';
import AllMappingsTables from '../mappings/AllMappingsTables';
import APIService from '../../services/APIService';
import PinIcon from '../common/PinIcon';
const TAG_ICON_STYLES = {width: '12px', marginRight: '2px', marginTop: '2px'}
const RESOURCE_DEFINITIONS = {
references: {
headBgColor: BLUE,
headTextColor: WHITE,
columns: [
{id: 'expression', label: 'Reference', value: 'expression', sortable: false, renderer: reference => <ReferenceChip {...reference} />},
],
},
concepts: {
headBgColor: BLUE,
headTextColor: WHITE,
columns: [
{id: 'owner', label: 'Owner', value: 'owner', sortOn: 'owner', renderer: concept => <OwnerChip ownerType={concept.owner_type} owner={concept.owner} />, essential: false},
{id: 'parent', label: 'Source', value: 'source', sortOn: 'source', essential: false},
{id: 'id', label: 'ID', value: 'id', sortOn: 'id'},
{id: 'name', label: 'Name', value: 'display_name', sortOn: 'name', renderer: concept => (concept.retired ? <span className='retired'>{concept.display_name}</span> : <span>{concept.display_name}</span>)},
{id: 'class', label: 'Class', value: 'concept_class', sortOn: 'concept_class'},
{id: 'datatype', label: 'Datatype', value: 'datatype', sortOn: 'datatype'},
{id: 'updatedOn', label: 'UpdatedOn', value: 'version_created_on', formatter: formatDate, sortOn: 'last_update'},
],
tabs: ['Mappings', 'Synonyms', 'Descriptions', 'History',],
expandible: true,
},
mappings: {
headBgColor: BLUE,
headTextColor: WHITE,
columns: [
{id: 'owner', label: 'Owner', value: 'owner', sortOn: 'owner', renderer: mapping => <OwnerChip ownerType={mapping.owner_type} owner={mapping.owner} />, essential: false},
{id: 'parent', label: 'Source', value: 'source', sortOn: 'source', essential: false},
{id: 'id', label: 'ID', value: 'id', sortOn: 'id'},
{id: 'from', label: 'From Concept', renderer: mapping => <FromConceptLabel {...mapping} noRedirect />},
{id: 'mapType', label: 'Type', value: 'map_type', sortOn: 'map_type'},
{id: 'to', label: 'To Concept', renderer: mapping => <ToConceptLabel {...mapping} noRedirect />},
{id: 'updatedOn', label: 'UpdatedOn', value: 'version_created_on', formatter: formatDate, sortOn: 'last_update'},
],
tabs: ['History',],
expandible: true,
},
sources: {
headBgColor: GREEN,
headTextColor: WHITE,
columns: [
{id: 'owner', label: 'Owner', value: 'owner', sortOn: 'owner', renderer: source => <OwnerChip ownerType={source.owner_type} owner={source.owner} />},
{id: 'id', label: 'ID', value: 'short_code', sortOn: 'mnemonic'},
{id: 'name', label: 'Name', value: 'name', sortOn: 'name'},
{id: 'sourceType', label: 'Type', value: 'source_type', sortOn: 'source_type'},
],
tags: [
{id: 'activeConcepts', value: 'active_concepts', label: 'Concepts', icon: <LocalOfferIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'concepts_url'},
{id: 'activeMappings', value: 'active_mappings', label: 'Mappings', icon: <LinkIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'mappings_url'},
{id: 'versions', value: 'versions', label: 'Versions', icon: <TreeIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'versions_url'},
],
tabs: ['Versions',],
expandible: true,
pinnable: true,
},
collections: {
headBgColor: GREEN,
headTextColor: WHITE,
columns: [
{id: 'owner', label: 'Owner', value: 'owner', sortOn: 'owner', renderer: coll => <OwnerChip ownerType={coll.owner_type} owner={coll.owner} />},
{id: 'id', label: 'ID', value: 'short_code', sortOn: 'mnemonic'},
{id: 'name', label: 'Name', value: 'name', sortOn: 'name'},
{id: 'collectionType', label: 'Type', value: 'collection_type', sortOn: 'collection_type'},
],
tags: [
{id: 'activeConcepts', value: 'active_concepts', label: 'Concepts', icon: <LocalOfferIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'concepts_url'},
{id: 'activeMappings', value: 'active_mappings', label: 'Mappings', icon: <LinkIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'mappings_url'},
{id: 'versions', value: 'versions', label: 'Versions', icon: <TreeIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'versions_url'},
],
tabs: ['Versions',],
expandible: true,
pinnable: true,
},
organizations: {
headBgColor: ORANGE,
headTextColor: WHITE,
columns: [
{id: 'id', label: 'ID', value: 'id', sortOn: 'mnemonic', renderer: org => <OwnerChip ownerType='Organization' owner={org.id} />},
{id: 'name', label: 'Name', value: 'name', sortOn: 'name'},
{id: 'createdOn', label: 'Created On', value: 'created_on', formatter: formatDate, sortOn: 'created_on'},
],
tags: [
{id: 'members', value: 'members', label: 'Members', icon: <PersonIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'url'},
{id: 'sources', value: 'public_sources', label: 'Public Sources', icon: <ListIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'sources_url'},
{id: 'collections', value: 'public_collections', label: 'Public Collections', icon: <LoyaltyIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'collections_url'},
],
expandible: false,
pinnable: true,
},
users: {
headBgColor: ORANGE,
headTextColor: WHITE,
columns: [
{id: 'username', label: 'Username', value: 'username', sortOn: 'username', renderer: user => <OwnerChip ownerType='user' owner={user.username} />},
{id: 'name', label: 'Name', value: 'name', sortOn: 'name'},
{id: 'createdOn', label: 'Joined On', value: 'created_on', formatter: formatDate, sortOn: 'date_joined'},
],
tags: [
{id: 'orgs', value: 'orgs', label: 'Organizations', icon: <HomeIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'organizations_url'},
{id: 'sources', value: 'public_sources', label: 'Public Sources', icon: <ListIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'sources_url'},
{id: 'collections', value: 'public_collections', label: 'Public Collections', icon: <LoyaltyIcon fontSize='small' style={TAG_ICON_STYLES} />, hrefAttr: 'collections_url'},
],
expandible: false,
},
}
const getValue = (item, column) => {
const value = get(item, column.value, '')
if(get(column, 'formatter') && value)
return column.formatter(value)
if(get(column, 'renderer'))
return column.renderer(item)
return value
}
const HistoryTable = ({ versions }) => {
return (
<Table size="small" aria-label="versions">
<TableHead>
<TableRow>
<TableCell align='center'>Version</TableCell>
<TableCell align='left'>Comment/Description</TableCell>
<TableCell align='left'>Created By</TableCell>
<TableCell align='left'>Created On</TableCell>
<TableCell />
</TableRow>
</TableHead>
<TableBody>
{
map(headFirst(versions), version => (
<TableRow hover key={version.uuid || version.id}>
<TableCell align='center'>
{ version.uuid || version.id }
</TableCell>
<TableCell align='left'>
{ version.update_comment || version.description }
</TableCell>
<TableCell align='left'>
{ version.version_created_by }
</TableCell>
<TableCell align='left'>
{ formatDateTime(version.version_created_on || version.created_at) }
</TableCell>
{
version.released ?
<TableCell align='center'><ReleasedChip /></TableCell> :
<TableCell />
}
</TableRow>
))
}
</TableBody>
</Table>
);
}
const LocalesTable = ({ locales, isDescription }) => {
const nameAttr = isDescription ? 'description' : 'name';
const typeAttr = isDescription ? 'description_type' : 'name_type';
return (
<Table size="small" aria-label="locales">
<TableHead>
<TableRow>
<TableCell align='right'>ID</TableCell>
<TableCell align='left'>Type</TableCell>
<TableCell align='left'>{startCase(nameAttr)}</TableCell>
<TableCell align='left'>External ID</TableCell>
</TableRow>
</TableHead>
<TableBody>
{
isEmpty(locales) ?
<TableRow colSpan='5'>
<TableCell colSpan='6' align='center'>No Records</TableCell>
</TableRow> :
map(locales, locale => (
<TableRow hover key={locale.uuid}>
<TableCell align='right' style={{width: '100px'}}>
<span className='flex-vertical-center'>
{
locale.locale_preferred &&
<span style={{marginRight: '5px'}}>
<Tooltip title={`Preferred ${nameAttr} for this locale`} placement='top-start'>
<FlagIcon color='secondary' fontSize='small' style={{width: '18px', marginTop: '4px'}}/>
</Tooltip>
</span>
}
{
locale.external_id &&
<span style={{marginRight: '5px'}}>
<Tooltip title={`External ID: ${locale.external_id}`} placement='top-start'>
<ForwardIcon
fontSize='small'
color='secondary'
style={{
border: '1px solid', borderRadius: '10px',
background: 'gray', color: 'white',
width: '18px',
height: '18px',
marginTop: '4px'
}}
/>
</Tooltip>
</span>
}
<span> { locale.uuid } </span>
</span>
</TableCell>
<TableCell align='left'>{ startCase(get(locale, typeAttr)) || EMPTY_VALUE }</TableCell>
<TableCell align='left' className='ellipsis-text'>
<span className='gray-italics-small'>{`[${locale.locale}]`}</span>
<span>{ get(locale, nameAttr) }</span>
</TableCell>
<TableCell align='left'>{ locale.external_id || EMPTY_VALUE }</TableCell>
</TableRow>
))
}
</TableBody>
</Table>
);
}
const ExpandibleRow = props => {
const {
item, resourceDefinition, resource, isSelected, isSelectable, onPinCreate, onPinDelete, pins,
nested, showPin, columns
} = props;
const [mappings, setMappings] = React.useState([]);
const [versions, setVersions] = React.useState([]);
const [names, setNames] = React.useState([]);
const [descriptions, setDescriptions] = React.useState([]);
const [open, setOpen] = React.useState(false);
const [pinned, setPin] = React.useState(() => includes(map(pins, 'resource_uri'), item.url));
const [tab, setTab] = React.useState(0);
const [selected, setSelected] = React.useState(isSelected);
const isConceptContainer = includes(['sources', 'collections'], resource);
const isPublic = includes(['view', 'edit'], get(item, 'public_access', '').toLowerCase()) && isConceptContainer;
const pinId = get(find(pins, {resource_uri: item.url}), 'id');
const columnsCount = get(columns, 'length', 1) +
(isConceptContainer ? 1 : 0) + //public column
(isSelectable ? 1 : 0) + // select column
((resourceDefinition.expandible || showPin) ? 1 : 0) + // expand icon column
(resourceDefinition.tags ? 1 : 0); //tags column
React.useEffect(() => setPin(includes(map(pins, 'resource_uri'), item.url)), [pins]);
React.useEffect(() => setSelected(isSelected), [isSelected]);
const onClick = event => {
if(!resourceDefinition.expandible)
return;
event.stopPropagation()
event.preventDefault()
setOpen(prevOpen => {
const newOpen = !prevOpen
if(newOpen) {
fetchVersions();
if(resource === 'concepts') {
fetchNames();
fetchDescriptions();
fetchMappings();
}
}
return newOpen
})
}
const getPinService = pinId => {
const username = get(props, 'match.params.user') || getCurrentUserUsername();
const orgId = get(props, 'match.params.org');
let service = null;
if(orgId && (isCurrentUserMemberOf(orgId) || isAdminUser()))
service = APIService.orgs(orgId)
else if(username && isLoggedIn())
service = APIService.users(username)
if(service) {
if(pinId)
return service.pins(pinId)
return service.pins()
}
}
const createPin = (resourceType, resourceId) => {
if(onPinCreate)
onPinCreate(resourceType, resourceId)
else
defaultCreatePin(resourceType, resourceId, getPinService())
}
const deletePin = pinId => {
if(onPinDelete)
onPinDelete(pinId)
else
defaultDeletePin(getPinService(pinId))
}
const onPinClick = event => {
if(!showPin)
return;
event.stopPropagation()
event.preventDefault()
pinned ? deletePin(pinId) : createPin(item.type, item.uuid);
return false;
}
const onRowClick = event => {
if(resource === 'references')
return
event.stopPropagation();
event.preventDefault()
window.open('#' + item.url, '_blank')
}
const handleTabChange = (event, newValue) => {
setTab(newValue);
};
const fetchVersions = () => {
if(item.url) {
APIService.new().overrideURL(item.url)
.appendToUrl('versions/')
.get()
.then(response => {
if(response.status === 200)
setVersions(response.data)
})
}
}
const fetchNames = () => {
if(item) {
APIService.new().overrideURL(item.url)
.appendToUrl('names/')
.get()
.then(response => {
if(response.status === 200)
setNames(response.data)
})
}
}
const fetchDescriptions = () => {
if(item) {
APIService.new().overrideURL(item.url)
.appendToUrl('descriptions/')
.get()
.then(response => {
if(response.status === 200)
setDescriptions(response.data)
})
}
}
const fetchMappings = () => {
if(item) {
APIService.new().overrideURL(item.url)
.appendToUrl('mappings/')
.get(null, null, {includeInverseMappings: true})
.then(response => {
if(response.status === 200)
setMappings(response.data)
})
}
}
const onCheckboxClick = event => {
setSelected(prevSelected => {
const newValue = !prevSelected;
props.onSelectChange(item.id, newValue)
return newValue;
})
event.stopPropagation();
event.preventDefault();
}
const getTab = label => {
return (
<Tab key={label} label={label} style={{fontSize: '12px', fontWeight: 'bold'}} />
)
}
const navigateTo = (event, url) => {
let _url = url;
if(!isConceptContainer)
_url = url.replace('/versions', '/history')
event.stopPropagation()
event.preventDefault()
window.open('#' + _url, '_blank')
}
return (
<React.Fragment>
<TableRow
hover
style={selected ? {backgroundColor: COLOR_ROW_SELECTED, cursor: 'pointer'} : {cursor: 'pointer'}}
onClick={onRowClick}>
{
isPublic &&
<TableCell align='center'>
<Tooltip title='Public'>
<span className='flex-vertical-center'>
<PublicIcon fontSize='small' />
</span>
</Tooltip>
</TableCell>
}
{
isSelectable &&
<TableCell>
<Checkbox checked={selected} onClick={onCheckboxClick} />
</TableCell>
}
{
map(columns, column => (
<TableCell key={column.id} align={column.align || 'left'}>
{ getValue(item, column) || 'None' }
</TableCell>
))
}
{
!isSelectable &&
<TableCell align='left' style={{width: '120px', padding: '2px'}}>
{
map(resourceDefinition.tags, tag => (
<Link key={tag.id} to='' onClick={event => navigateTo(event, get(item, tag.hrefAttr))}>
<Tooltip title={tag.label}>
<div style={{fontSize: '14px', lineHeight: '0px', marginBottom: '2px'}}>
<div className='flex-vertical-center'>
<span>{tag.icon}</span>
<span style={{padding: '2px'}}>{`${get(item, tag.value, '0').toLocaleString()}`}</span>
</div>
</div>
</Tooltip>
</Link>
))
}
</TableCell>
}
{
(resourceDefinition.expandible || showPin) &&
<TableCell align={nested ? 'center' : 'left'}>
{
resourceDefinition.expandible &&
<IconButton aria-label="expand row" size="small" onClick={onClick}>
{open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
</IconButton>
}
{
showPin &&
<IconButton aria-label="expand row" size="small" onClick={onPinClick}>
{<PinIcon fontSize="small" pinned={pinned ? pinned.toString() : undefined} />}
</IconButton>
}
</TableCell>
}
</TableRow>
{
resourceDefinition.expandible &&
<TableRow>
<TableCell style={{ padding: 0 }} colSpan={columnsCount}>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box margin={1}>
<Paper square style={{boxShadow: 'none', border: '1px solid lightgray'}}>
<Tabs
value={tab}
indicatorColor="primary"
textColor="primary"
onChange={handleTabChange}
>
{
map(resourceDefinition.tabs, label => getTab(label))
}
</Tabs>
{
tab === resourceDefinition.tabs.indexOf('Mappings') &&
<div style={{borderTop: '1px solid lightgray', maxHeight: '175px', overflow: 'auto'}}>
<AllMappingsTables mappings={mappings} concept={item.id}/>
</div>
}
{
tab === resourceDefinition.tabs.indexOf('Synonyms') &&
<div style={{borderTop: '1px solid lightgray', maxHeight: '175px', overflow: 'auto'}}>
<LocalesTable locales={names} />
</div>
}
{
tab === resourceDefinition.tabs.indexOf('Descriptions') &&
<div style={{borderTop: '1px solid lightgray', maxHeight: '175px', overflow: 'auto'}}>
<LocalesTable locales={descriptions} isDescription />
</div>
}
{
(
tab === resourceDefinition.tabs.indexOf('History') ||
tab === resourceDefinition.tabs.indexOf('Versions')
) &&
<div style={{borderTop: '1px solid lightgray', maxHeight: '175px', overflow: 'auto'}}>
<HistoryTable versions={versions} />
</div>
}
</Paper>
</Box>
</Collapse>
</TableCell>
</TableRow>
}
</React.Fragment>
)
}
const ResultsTable = (
{
resource, results, onPageChange, onSortChange, sortParams,
onPinCreate, onPinDelete, pins, nested, showPin, essentialColumns, onReferencesDelete,
isVersionedObject,
}
) => {
const resourceDefinition = RESOURCE_DEFINITIONS[resource];
const theadBgColor = get(resourceDefinition, 'headBgColor', BLUE);
const theadTextColor = get(resourceDefinition, 'headTextColor', WHITE);
const theadStyles = {
backgroundColor: theadBgColor,
border: `1px solid ${theadBgColor}`,
}
const isConceptContainer = includes(['sources', 'collections'], resource);
const shouldShowPin = showPin && resourceDefinition.pinnable;
const canRender = results.total && resourceDefinition;
const defaultOrderBy = get(find(resourceDefinition.columns, {sortOn: get(values(sortParams), '0', 'last_update')}), 'id', 'UpdateOn');
const defaultOrder = get(keys(sortParams), '0') === 'sortAsc' ? 'asc' : 'desc';
const [selectedList, setSelectedList] = React.useState([]);
const [orderBy, setOrderBy] = React.useState(defaultOrderBy)
const [order, setOrder] = React.useState(defaultOrder)
const hasAccess = currentUserHasAccess()
const isSourceChild = includes(['concepts', 'mappings'], resource);
const isSelectable = (resource === 'references' && hasAccess && isVersionedObject) ||
isSourceChild;
const onAllSelect = event => event.target.checked ?
setSelectedList(map(results.items, 'id')) :
setSelectedList([]);
const updateSelected = (id, selected) => selected ?
setSelectedList(uniq([...selectedList, id])) :
setSelectedList(without(selectedList, id));
const getOppositeOrder = order => order === 'asc' ? 'desc' : 'asc';
const onSort = (event, columnId) => {
let newOrder = 'desc';
if(orderBy === columnId)
newOrder = getOppositeOrder(order)
const sortOn = get(find(resourceDefinition.columns, {id: columnId}), 'sortOn', 'last_update')
let sortQuery = {sortDesc: sortOn}
if(newOrder === 'asc')
sortQuery = {sortAsc: sortOn}
setOrder(newOrder)
setOrderBy(columnId)
onSortChange(sortQuery)
}
const getSelectedItems = () => filter(results.items, item => includes(selectedList, item.id))
const shouldShowCompareOption = resource === 'concepts' && selectedList.length === 2;
const shouldShowDownloadOption = isSourceChild && selectedList.length > 0;
const shouldShowDeleteOption = resource === 'references' && hasAccess && selectedList.length > 0;
const columns = essentialColumns ?
reject(resourceDefinition.columns, c => c.essential === false) :
resourceDefinition.columns;
const columnsCount = get(columns, 'length', 1) + ((resourceDefinition.expandible || shouldShowPin) ? 2 : 1) + (isConceptContainer ? 1 : 0);
const selectionRowColumnsCount = (shouldShowCompareOption || shouldShowDeleteOption || shouldShowDownloadOption) ?
columnsCount - 2 :
columnsCount;
const onCompareClick = event => {
event.stopPropagation()
event.preventDefault()
const urls = map(getSelectedItems(), 'url')
if(urls.length == 2) {
const url = `#/concepts/compare?lhs=${urls[0]}&rhs=${urls[1]}`
window.open(url, '_blank')
}
}
const onReferenceDeleteClick = event => {
event.stopPropagation()
event.preventDefault()
const expressions = map(filter(results.items, item => includes(selectedList, item.id)), 'expression');
onReferencesDelete(expressions)
}
return (
<div className='col-sm-12 no-side-padding'>
{
canRender ?
<div className='col-sm-12 no-side-padding search-results'>
<TableContainer style={{borderRadius: '4px'}}>
<Table size='small'>
<TableHead style={theadStyles}>
{
selectedList.length > 0 &&
<TableRow colSpan={selectionRowColumnsCount} style={{backgroundColor: DARKGRAY, border: `1px solid ${DARKGRAY}`}}>
<TableCell colSpan={columnsCount} align='left' style={{color: WHITE}}>
<span style={{margin: '0 15px'}}>{selectedList.length} Selected</span>
<span style={{float: 'right'}}>
{
shouldShowDownloadOption &&
<DownloadButton
includeCSV
formats={['json']}
resource={getSelectedItems()}
buttonFunc={
attrs =>
<Button startIcon={<DownloadIcon fontSize='small' />} variant='contained' size='small' color='secondary' {...attrs}>
Download
</Button>
}
/>
}
{
shouldShowCompareOption &&
<Button
startIcon={<CompareArrowsIcon fontSize='small' />}
variant='contained'
size='small'
color='secondary'
onClick={onCompareClick}
style={{marginLeft: '10px'}}
>
Compare
</Button>
}
{
shouldShowDeleteOption &&
<Button
startIcon={<DeleteIcon fontSize='small' />}
variant='contained'
size='small'
color='secondary'
onClick={onReferenceDeleteClick}
style={{marginLeft: '10px'}}
>
Delete
</Button>
}
</span>
</TableCell>
</TableRow>
}
<TableRow>
{
isConceptContainer &&
<TableCell />
}
{
isSelectable &&
<TableCell>
<Checkbox style={{color: theadTextColor}} onChange={onAllSelect} />
</TableCell>
}
{
map(columns, column => {
const isSortable = column.sortable !== false;
return isSortable ? (
<TableCell
key={column.id}
sortDirection={orderBy === column.id ? order : false}
align={column.align || 'left'}
style={{color: theadTextColor}}>
<TableSortLabel
className='table-sort-label-white'
active={orderBy === column.id}
direction={orderBy === column.id ? order : 'desc'}
onClick={(event) => onSort(event, column.id)}
style={{color: theadTextColor}}
>
{ column.label }
</TableSortLabel>
</TableCell>
) : (
<TableCell key={column.id} align='left' style={{color: theadTextColor}}>
{column.label}
</TableCell>
)
})
}
{
!isSelectable &&
<TableCell />
}
{
(resourceDefinition.expandible || shouldShowPin) &&
<TableCell />
}
</TableRow>
</TableHead>
<TableBody>
{
map(results.items, item => (
<ExpandibleRow
key={item.uuid || item.id}
item={item}
resource={resource}
resourceDefinition={resourceDefinition}
isSelected={includes(selectedList, item.id)}
onSelectChange={updateSelected}
isSelectable={isSelectable}
onPinCreate={onPinCreate}
onPinDelete={onPinDelete}
pins={pins}
nested={nested}
showPin={shouldShowPin}
columns={columns}
/>
))
}
<TableRow colSpan={columnsCount}>
<TableCell colSpan={columnsCount} align='center' className='pagination-center'>
<Pagination
onChange={(event, page) => onPageChange(page)}
count={results.pages}
variant="outlined"
shape="rounded"
color="primary"
showFirstButton
showLastButton
page={results.pageNumber}
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
</div> :
<div style={{padding: '2px'}}>We found 0 {startCase(resource)}.</div>
}
</div>
)
}
export default ResultsTable