20251: Fix flaky collection file browser by using race-free state update callback
[arvados-workbench2.git] / src / views-components / data-explorer / renderers.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React from 'react';
6 import {
7     Grid,
8     Typography,
9     withStyles,
10     Tooltip,
11     IconButton,
12     Checkbox,
13     Chip
14 } from '@material-ui/core';
15 import { FavoriteStar, PublicFavoriteStar } from '../favorite-star/favorite-star';
16 import { Resource, ResourceKind, TrashableResource } from 'models/resource';
17 import {
18     FreezeIcon,
19     ProjectIcon,
20     FilterGroupIcon,
21     CollectionIcon,
22     ProcessIcon,
23     DefaultIcon,
24     ShareIcon,
25     CollectionOldVersionIcon,
26     WorkflowIcon,
27     RemoveIcon,
28     RenameIcon,
29     ActiveIcon,
30     SetupIcon,
31     InactiveIcon,
32 } from 'components/icon/icon';
33 import { formatDate, formatFileSize, formatTime } from 'common/formatters';
34 import { resourceLabel } from 'common/labels';
35 import { connect, DispatchProp } from 'react-redux';
36 import { RootState } from 'store/store';
37 import { getResource, filterResources } from 'store/resources/resources';
38 import { GroupContentsResource } from 'services/groups-service/groups-service';
39 import { getProcess, Process, getProcessStatus, getProcessStatusStyles, getProcessRuntime } from 'store/processes/process';
40 import { ArvadosTheme } from 'common/custom-theme';
41 import { compose, Dispatch } from 'redux';
42 import { WorkflowResource } from 'models/workflow';
43 import { ResourceStatus as WorkflowStatus } from 'views/workflow-panel/workflow-panel-view';
44 import { getUuidPrefix, openRunProcess } from 'store/workflow-panel/workflow-panel-actions';
45 import { openSharingDialog } from 'store/sharing-dialog/sharing-dialog-actions';
46 import { getUserFullname, getUserDisplayName, User, UserResource } from 'models/user';
47 import { toggleIsAdmin } from 'store/users/users-actions';
48 import { LinkClass, LinkResource } from 'models/link';
49 import { navigateTo, navigateToGroupDetails, navigateToUserProfile } from 'store/navigation/navigation-action';
50 import { withResourceData } from 'views-components/data-explorer/with-resources';
51 import { CollectionResource } from 'models/collection';
52 import { IllegalNamingWarning } from 'components/warning/warning';
53 import { loadResource } from 'store/resources/resources-actions';
54 import { BuiltinGroups, getBuiltinGroupUuid, GroupClass, GroupResource, isBuiltinGroup } from 'models/group';
55 import { openRemoveGroupMemberDialog } from 'store/group-details-panel/group-details-panel-actions';
56 import { setMemberIsHidden } from 'store/group-details-panel/group-details-panel-actions';
57 import { formatPermissionLevel } from 'views-components/sharing-dialog/permission-select';
58 import { PermissionLevel } from 'models/permission';
59 import { openPermissionEditContextMenu } from 'store/context-menu/context-menu-actions';
60 import { getUserUuid } from 'common/getuser';
61 import { VirtualMachinesResource } from 'models/virtual-machines';
62 import { CopyToClipboardSnackbar } from 'components/copy-to-clipboard-snackbar/copy-to-clipboard-snackbar';
63 import { ProjectResource } from 'models/project';
64 import { ProcessResource } from 'models/process';
65
66
67 const renderName = (dispatch: Dispatch, item: GroupContentsResource) => {
68     const navFunc = ("groupClass" in item && item.groupClass === GroupClass.ROLE ? navigateToGroupDetails : navigateTo);
69     return <Grid container alignItems="center" wrap="nowrap" spacing={16}>
70         <Grid item>
71             {renderIcon(item)}
72         </Grid>
73         <Grid item>
74             <Typography color="primary" style={{ width: 'auto', cursor: 'pointer' }} onClick={() => dispatch<any>(navFunc(item.uuid))}>
75                 {item.kind === ResourceKind.PROJECT || item.kind === ResourceKind.COLLECTION
76                     ? <IllegalNamingWarning name={item.name} />
77                     : null}
78                 {item.name}
79             </Typography>
80         </Grid>
81         <Grid item>
82             <Typography variant="caption">
83                 <FavoriteStar resourceUuid={item.uuid} />
84                 <PublicFavoriteStar resourceUuid={item.uuid} />
85                 {
86                     item.kind === ResourceKind.PROJECT && <FrozenProject item={item} />
87                 }
88             </Typography>
89         </Grid>
90     </Grid>;
91 };
92
93
94 const FrozenProject = (props: {item: ProjectResource}) => {
95     const [fullUsername, setFullusername] = React.useState<any>(null);
96     const getFullName = React.useCallback(() => {
97         if (props.item.frozenByUuid) {
98             setFullusername(<UserNameFromID uuid={props.item.frozenByUuid} />);
99         }
100     }, [props.item, setFullusername])
101
102     if (props.item.frozenByUuid) {
103
104         return <Tooltip onOpen={getFullName} enterDelay={500} title={<span>Project was frozen by {fullUsername}</span>}>
105             <FreezeIcon style={{ fontSize: "inherit" }}/>
106         </Tooltip>;
107     } else {
108         return null;
109     }
110 }
111
112 export const ResourceName = connect(
113     (state: RootState, props: { uuid: string }) => {
114         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
115         return resource;
116     })((resource: GroupContentsResource & DispatchProp<any>) => renderName(resource.dispatch, resource));
117
118     
119 const renderIcon = (item: GroupContentsResource) => {
120     switch (item.kind) {
121         case ResourceKind.PROJECT:
122             if (item.groupClass === GroupClass.FILTER) {
123                 return <FilterGroupIcon />;
124             }
125             return <ProjectIcon />;
126         case ResourceKind.COLLECTION:
127             if (item.uuid === item.currentVersionUuid) {
128                 return <CollectionIcon />;
129             }
130             return <CollectionOldVersionIcon />;
131         case ResourceKind.PROCESS:
132             return <ProcessIcon />;
133         case ResourceKind.WORKFLOW:
134             return <WorkflowIcon />;
135         default:
136             return <DefaultIcon />;
137     }
138 };
139
140 const renderDate = (date?: string) => {
141     return <Typography noWrap style={{ minWidth: '100px' }}>{formatDate(date)}</Typography>;
142 };
143
144 const renderWorkflowName = (item: WorkflowResource) =>
145     <Grid container alignItems="center" wrap="nowrap" spacing={16}>
146         <Grid item>
147             {renderIcon(item)}
148         </Grid>
149         <Grid item>
150             <Typography color="primary" style={{ width: '100px' }}>
151                 {item.name}
152             </Typography>
153         </Grid>
154     </Grid>;
155
156 export const ResourceWorkflowName = connect(
157     (state: RootState, props: { uuid: string }) => {
158         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
159         return resource;
160     })(renderWorkflowName);
161
162 const getPublicUuid = (uuidPrefix: string) => {
163     return `${uuidPrefix}-tpzed-anonymouspublic`;
164 };
165
166 const resourceShare = (dispatch: Dispatch, uuidPrefix: string, ownerUuid?: string, uuid?: string) => {
167     const isPublic = ownerUuid === getPublicUuid(uuidPrefix);
168     return (
169         <div>
170             {!isPublic && uuid &&
171                 <Tooltip title="Share">
172                     <IconButton onClick={() => dispatch<any>(openSharingDialog(uuid))}>
173                         <ShareIcon />
174                     </IconButton>
175                 </Tooltip>
176             }
177         </div>
178     );
179 };
180
181 export const ResourceShare = connect(
182     (state: RootState, props: { uuid: string }) => {
183         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
184         const uuidPrefix = getUuidPrefix(state);
185         return {
186             uuid: resource ? resource.uuid : '',
187             ownerUuid: resource ? resource.ownerUuid : '',
188             uuidPrefix
189         };
190     })((props: { ownerUuid?: string, uuidPrefix: string, uuid?: string } & DispatchProp<any>) =>
191         resourceShare(props.dispatch, props.uuidPrefix, props.ownerUuid, props.uuid));
192
193 // User Resources
194 const renderFirstName = (item: { firstName: string }) => {
195     return <Typography noWrap>{item.firstName}</Typography>;
196 };
197
198 export const ResourceFirstName = connect(
199     (state: RootState, props: { uuid: string }) => {
200         const resource = getResource<UserResource>(props.uuid)(state.resources);
201         return resource || { firstName: '' };
202     })(renderFirstName);
203
204 const renderLastName = (item: { lastName: string }) =>
205     <Typography noWrap>{item.lastName}</Typography>;
206
207 export const ResourceLastName = connect(
208     (state: RootState, props: { uuid: string }) => {
209         const resource = getResource<UserResource>(props.uuid)(state.resources);
210         return resource || { lastName: '' };
211     })(renderLastName);
212
213 const renderFullName = (dispatch: Dispatch, item: { uuid: string, firstName: string, lastName: string }, link?: boolean) => {
214     const displayName = (item.firstName + " " + item.lastName).trim() || item.uuid;
215     return link ? <Typography noWrap
216         color="primary"
217         style={{ 'cursor': 'pointer' }}
218         onClick={() => dispatch<any>(navigateToUserProfile(item.uuid))}>
219         {displayName}
220     </Typography> :
221         <Typography noWrap>{displayName}</Typography>;
222 }
223
224 export const UserResourceFullName = connect(
225     (state: RootState, props: { uuid: string, link?: boolean }) => {
226         const resource = getResource<UserResource>(props.uuid)(state.resources);
227         return { item: resource || { uuid: '', firstName: '', lastName: '' }, link: props.link };
228     })((props: { item: { uuid: string, firstName: string, lastName: string }, link?: boolean } & DispatchProp<any>) => renderFullName(props.dispatch, props.item, props.link));
229
230 const renderUuid = (item: { uuid: string }) =>
231     <Typography data-cy="uuid" noWrap>
232         {item.uuid}
233         {(item.uuid && <CopyToClipboardSnackbar value={item.uuid} />) || '-' }
234     </Typography>;
235
236 const renderUuidCopyIcon = (item: { uuid: string }) =>
237     <Typography data-cy="uuid" noWrap>
238         {(item.uuid && <CopyToClipboardSnackbar value={item.uuid} />) || '-' }
239     </Typography>;
240
241 export const ResourceUuid = connect((state: RootState, props: { uuid: string }) => (
242     getResource<UserResource>(props.uuid)(state.resources) || { uuid: '' }
243 ))(renderUuid);
244
245 const renderEmail = (item: { email: string }) =>
246     <Typography noWrap>{item.email}</Typography>;
247
248 export const ResourceEmail = connect(
249     (state: RootState, props: { uuid: string }) => {
250         const resource = getResource<UserResource>(props.uuid)(state.resources);
251         return resource || { email: '' };
252     })(renderEmail);
253
254 enum UserAccountStatus {
255     ACTIVE = 'Active',
256     INACTIVE = 'Inactive',
257     SETUP = 'Setup',
258     UNKNOWN = ''
259 }
260
261 const renderAccountStatus = (props: { status: UserAccountStatus }) =>
262     <Grid container alignItems="center" wrap="nowrap" spacing={8} data-cy="account-status">
263         <Grid item>
264             {(() => {
265                 switch (props.status) {
266                     case UserAccountStatus.ACTIVE:
267                         return <ActiveIcon style={{ color: '#4caf50', verticalAlign: "middle" }} />;
268                     case UserAccountStatus.SETUP:
269                         return <SetupIcon style={{ color: '#2196f3', verticalAlign: "middle" }} />;
270                     case UserAccountStatus.INACTIVE:
271                         return <InactiveIcon style={{ color: '#9e9e9e', verticalAlign: "middle" }} />;
272                     default:
273                         return <></>;
274                 }
275             })()}
276         </Grid>
277         <Grid item>
278             <Typography noWrap>
279                 {props.status}
280             </Typography>
281         </Grid>
282     </Grid>;
283
284 const getUserAccountStatus = (state: RootState, props: { uuid: string }) => {
285     const user = getResource<UserResource>(props.uuid)(state.resources);
286     // Get membership links for all users group
287     const allUsersGroupUuid = getBuiltinGroupUuid(state.auth.localCluster, BuiltinGroups.ALL);
288     const permissions = filterResources((resource: LinkResource) =>
289         resource.kind === ResourceKind.LINK &&
290         resource.linkClass === LinkClass.PERMISSION &&
291         resource.headUuid === allUsersGroupUuid &&
292         resource.tailUuid === props.uuid
293     )(state.resources);
294
295     if (user) {
296         return user.isActive ? { status: UserAccountStatus.ACTIVE } : permissions.length > 0 ? { status: UserAccountStatus.SETUP } : { status: UserAccountStatus.INACTIVE };
297     } else {
298         return { status: UserAccountStatus.UNKNOWN };
299     }
300 }
301
302 export const ResourceLinkTailAccountStatus = connect(
303     (state: RootState, props: { uuid: string }) => {
304         const link = getResource<LinkResource>(props.uuid)(state.resources);
305         return link && link.tailKind === ResourceKind.USER ? getUserAccountStatus(state, { uuid: link.tailUuid }) : { status: UserAccountStatus.UNKNOWN };
306     })(renderAccountStatus);
307
308 export const UserResourceAccountStatus = connect(getUserAccountStatus)(renderAccountStatus);
309
310 const renderIsHidden = (props: {
311     memberLinkUuid: string,
312     permissionLinkUuid: string,
313     visible: boolean,
314     canManage: boolean,
315     setMemberIsHidden: (memberLinkUuid: string, permissionLinkUuid: string, hide: boolean) => void
316 }) => {
317     if (props.memberLinkUuid) {
318         return <Checkbox
319             data-cy="user-visible-checkbox"
320             color="primary"
321             checked={props.visible}
322             disabled={!props.canManage}
323             onClick={(e) => {
324                 e.stopPropagation();
325                 props.setMemberIsHidden(props.memberLinkUuid, props.permissionLinkUuid, !props.visible);
326             }} />;
327     } else {
328         return <Typography />;
329     }
330 }
331
332 export const ResourceLinkTailIsVisible = connect(
333     (state: RootState, props: { uuid: string }) => {
334         const link = getResource<LinkResource>(props.uuid)(state.resources);
335         const member = getResource<Resource>(link?.tailUuid || '')(state.resources);
336         const group = getResource<GroupResource>(link?.headUuid || '')(state.resources);
337         const permissions = filterResources((resource: LinkResource) => {
338             return resource.linkClass === LinkClass.PERMISSION
339                 && resource.headUuid === link?.tailUuid
340                 && resource.tailUuid === group?.uuid
341                 && resource.name === PermissionLevel.CAN_READ;
342         })(state.resources);
343
344         const permissionLinkUuid = permissions.length > 0 ? permissions[0].uuid : '';
345         const isVisible = link && group && permissions.length > 0;
346         // Consider whether the current user canManage this resurce in addition when it's possible
347         const isBuiltin = isBuiltinGroup(link?.headUuid || '');
348
349         return member?.kind === ResourceKind.USER
350             ? { memberLinkUuid: link?.uuid, permissionLinkUuid, visible: isVisible, canManage: !isBuiltin }
351             : { memberLinkUuid: '', permissionLinkUuid: '', visible: false, canManage: false };
352     }, { setMemberIsHidden }
353 )(renderIsHidden);
354
355 const renderIsAdmin = (props: { uuid: string, isAdmin: boolean, toggleIsAdmin: (uuid: string) => void }) =>
356     <Checkbox
357         color="primary"
358         checked={props.isAdmin}
359         onClick={(e) => {
360             e.stopPropagation();
361             props.toggleIsAdmin(props.uuid);
362         }} />;
363
364 export const ResourceIsAdmin = connect(
365     (state: RootState, props: { uuid: string }) => {
366         const resource = getResource<UserResource>(props.uuid)(state.resources);
367         return resource || { isAdmin: false };
368     }, { toggleIsAdmin }
369 )(renderIsAdmin);
370
371 const renderUsername = (item: { username: string, uuid: string }) =>
372     <Typography noWrap>{item.username || item.uuid}</Typography>;
373
374 export const ResourceUsername = connect(
375     (state: RootState, props: { uuid: string }) => {
376         const resource = getResource<UserResource>(props.uuid)(state.resources);
377         return resource || { username: '', uuid: props.uuid };
378     })(renderUsername);
379
380 // Virtual machine resource
381
382 const renderHostname = (item: { hostname: string }) =>
383     <Typography noWrap>{item.hostname}</Typography>;
384
385 export const VirtualMachineHostname = connect(
386     (state: RootState, props: { uuid: string }) => {
387         const resource = getResource<VirtualMachinesResource>(props.uuid)(state.resources);
388         return resource || { hostname: '' };
389     })(renderHostname);
390
391 const renderVirtualMachineLogin = (login: { user: string }) =>
392     <Typography noWrap>{login.user}</Typography>
393
394 export const VirtualMachineLogin = connect(
395     (state: RootState, props: { linkUuid: string }) => {
396         const permission = getResource<LinkResource>(props.linkUuid)(state.resources);
397         const user = getResource<UserResource>(permission?.tailUuid || '')(state.resources);
398
399         return { user: user?.username || permission?.tailUuid || '' };
400     })(renderVirtualMachineLogin);
401
402 // Common methods
403 const renderCommonData = (data: string) =>
404     <Typography noWrap>{data}</Typography>;
405
406 const renderCommonDate = (date: string) =>
407     <Typography noWrap>{formatDate(date)}</Typography>;
408
409 export const CommonUuid = withResourceData('uuid', renderCommonData);
410
411 // Api Client Authorizations
412 export const TokenApiClientId = withResourceData('apiClientId', renderCommonData);
413
414 export const TokenApiToken = withResourceData('apiToken', renderCommonData);
415
416 export const TokenCreatedByIpAddress = withResourceData('createdByIpAddress', renderCommonDate);
417
418 export const TokenDefaultOwnerUuid = withResourceData('defaultOwnerUuid', renderCommonData);
419
420 export const TokenExpiresAt = withResourceData('expiresAt', renderCommonDate);
421
422 export const TokenLastUsedAt = withResourceData('lastUsedAt', renderCommonDate);
423
424 export const TokenLastUsedByIpAddress = withResourceData('lastUsedByIpAddress', renderCommonData);
425
426 export const TokenScopes = withResourceData('scopes', renderCommonData);
427
428 export const TokenUserId = withResourceData('userId', renderCommonData);
429
430 const clusterColors = [
431     ['#f44336', '#fff'],
432     ['#2196f3', '#fff'],
433     ['#009688', '#fff'],
434     ['#cddc39', '#fff'],
435     ['#ff9800', '#fff']
436 ];
437
438 export const ResourceCluster = (props: { uuid: string }) => {
439     const CLUSTER_ID_LENGTH = 5;
440     const pos = props.uuid.length > CLUSTER_ID_LENGTH ? props.uuid.indexOf('-') : 5;
441     const clusterId = pos >= CLUSTER_ID_LENGTH ? props.uuid.substring(0, pos) : '';
442     const ci = pos >= CLUSTER_ID_LENGTH ? (((((
443         (props.uuid.charCodeAt(0) * props.uuid.charCodeAt(1))
444         + props.uuid.charCodeAt(2))
445         * props.uuid.charCodeAt(3))
446         + props.uuid.charCodeAt(4))) % clusterColors.length) : 0;
447     return <span style={{
448         backgroundColor: clusterColors[ci][0],
449         color: clusterColors[ci][1],
450         padding: "2px 7px",
451         borderRadius: 3
452     }}>{clusterId}</span>;
453 };
454
455 // Links Resources
456 const renderLinkName = (item: { name: string }) =>
457     <Typography noWrap>{item.name || '-'}</Typography>;
458
459 export const ResourceLinkName = connect(
460     (state: RootState, props: { uuid: string }) => {
461         const resource = getResource<LinkResource>(props.uuid)(state.resources);
462         return resource || { name: '' };
463     })(renderLinkName);
464
465 const renderLinkClass = (item: { linkClass: string }) =>
466     <Typography noWrap>{item.linkClass}</Typography>;
467
468 export const ResourceLinkClass = connect(
469     (state: RootState, props: { uuid: string }) => {
470         const resource = getResource<LinkResource>(props.uuid)(state.resources);
471         return resource || { linkClass: '' };
472     })(renderLinkClass);
473
474 const getResourceDisplayName = (resource: Resource): string => {
475     if ((resource as UserResource).kind === ResourceKind.USER
476         && typeof (resource as UserResource).firstName !== 'undefined') {
477         // We can be sure the resource is UserResource
478         return getUserDisplayName(resource as UserResource);
479     } else {
480         return (resource as GroupContentsResource).name;
481     }
482 }
483
484 const renderResourceLink = (dispatch: Dispatch, item: Resource) => {
485     var displayName = getResourceDisplayName(item);
486
487     return <Typography noWrap color="primary" style={{ 'cursor': 'pointer' }} onClick={() => dispatch<any>(navigateTo(item.uuid))}>
488         {resourceLabel(item.kind, item && item.kind === ResourceKind.GROUP ? (item as GroupResource).groupClass || '' : '')}: {displayName || item.uuid}
489     </Typography>;
490 };
491
492 export const ResourceLinkTail = connect(
493     (state: RootState, props: { uuid: string }) => {
494         const resource = getResource<LinkResource>(props.uuid)(state.resources);
495         const tailResource = getResource<Resource>(resource?.tailUuid || '')(state.resources);
496
497         return {
498             item: tailResource || { uuid: resource?.tailUuid || '', kind: resource?.tailKind || ResourceKind.NONE }
499         };
500     })((props: { item: Resource } & DispatchProp<any>) =>
501         renderResourceLink(props.dispatch, props.item));
502
503 export const ResourceLinkHead = connect(
504     (state: RootState, props: { uuid: string }) => {
505         const resource = getResource<LinkResource>(props.uuid)(state.resources);
506         const headResource = getResource<Resource>(resource?.headUuid || '')(state.resources);
507
508         return {
509             item: headResource || { uuid: resource?.headUuid || '', kind: resource?.headKind || ResourceKind.NONE }
510         };
511     })((props: { item: Resource } & DispatchProp<any>) =>
512         renderResourceLink(props.dispatch, props.item));
513
514 export const ResourceLinkUuid = connect(
515     (state: RootState, props: { uuid: string }) => {
516         const resource = getResource<LinkResource>(props.uuid)(state.resources);
517         return resource || { uuid: '' };
518     })(renderUuid);
519
520 export const ResourceLinkHeadUuid = connect(
521     (state: RootState, props: { uuid: string }) => {
522         const link = getResource<LinkResource>(props.uuid)(state.resources);
523         const headResource = getResource<Resource>(link?.headUuid || '')(state.resources);
524
525         return headResource || { uuid: '' };
526     })(renderUuid);
527
528 export const ResourceLinkTailUuid = connect(
529     (state: RootState, props: { uuid: string }) => {
530         const link = getResource<LinkResource>(props.uuid)(state.resources);
531         const tailResource = getResource<Resource>(link?.tailUuid || '')(state.resources);
532
533         return tailResource || { uuid: '' };
534     })(renderUuid);
535
536 const renderLinkDelete = (dispatch: Dispatch, item: LinkResource, canManage: boolean) => {
537     if (item.uuid) {
538         return canManage ?
539             <Typography noWrap>
540                 <IconButton data-cy="resource-delete-button" onClick={() => dispatch<any>(openRemoveGroupMemberDialog(item.uuid))}>
541                     <RemoveIcon />
542                 </IconButton>
543             </Typography> :
544             <Typography noWrap>
545                 <IconButton disabled data-cy="resource-delete-button">
546                     <RemoveIcon />
547                 </IconButton>
548             </Typography>;
549     } else {
550         return <Typography noWrap></Typography>;
551     }
552 }
553
554 export const ResourceLinkDelete = connect(
555     (state: RootState, props: { uuid: string }) => {
556         const link = getResource<LinkResource>(props.uuid)(state.resources);
557         const isBuiltin = isBuiltinGroup(link?.headUuid || '') || isBuiltinGroup(link?.tailUuid || '');
558
559         return {
560             item: link || { uuid: '', kind: ResourceKind.NONE },
561             canManage: link && getResourceLinkCanManage(state, link) && !isBuiltin,
562         };
563     })((props: { item: LinkResource, canManage: boolean } & DispatchProp<any>) =>
564         renderLinkDelete(props.dispatch, props.item, props.canManage));
565
566 export const ResourceLinkTailEmail = connect(
567     (state: RootState, props: { uuid: string }) => {
568         const link = getResource<LinkResource>(props.uuid)(state.resources);
569         const resource = getResource<UserResource>(link?.tailUuid || '')(state.resources);
570
571         return resource || { email: '' };
572     })(renderEmail);
573
574 export const ResourceLinkTailUsername = connect(
575     (state: RootState, props: { uuid: string }) => {
576         const link = getResource<LinkResource>(props.uuid)(state.resources);
577         const resource = getResource<UserResource>(link?.tailUuid || '')(state.resources);
578
579         return resource || { username: '' };
580     })(renderUsername);
581
582 const renderPermissionLevel = (dispatch: Dispatch, link: LinkResource, canManage: boolean) => {
583     return <Typography noWrap>
584         {formatPermissionLevel(link.name as PermissionLevel)}
585         {canManage ?
586             <IconButton data-cy="edit-permission-button" onClick={(event) => dispatch<any>(openPermissionEditContextMenu(event, link))}>
587                 <RenameIcon />
588             </IconButton> :
589             ''
590         }
591     </Typography>;
592 }
593
594 export const ResourceLinkHeadPermissionLevel = connect(
595     (state: RootState, props: { uuid: string }) => {
596         const link = getResource<LinkResource>(props.uuid)(state.resources);
597         const isBuiltin = isBuiltinGroup(link?.headUuid || '') || isBuiltinGroup(link?.tailUuid || '');
598
599         return {
600             link: link || { uuid: '', name: '', kind: ResourceKind.NONE },
601             canManage: link && getResourceLinkCanManage(state, link) && !isBuiltin,
602         };
603     })((props: { link: LinkResource, canManage: boolean } & DispatchProp<any>) =>
604         renderPermissionLevel(props.dispatch, props.link, props.canManage));
605
606 export const ResourceLinkTailPermissionLevel = connect(
607     (state: RootState, props: { uuid: string }) => {
608         const link = getResource<LinkResource>(props.uuid)(state.resources);
609         const isBuiltin = isBuiltinGroup(link?.headUuid || '') || isBuiltinGroup(link?.tailUuid || '');
610
611         return {
612             link: link || { uuid: '', name: '', kind: ResourceKind.NONE },
613             canManage: link && getResourceLinkCanManage(state, link) && !isBuiltin,
614         };
615     })((props: { link: LinkResource, canManage: boolean } & DispatchProp<any>) =>
616         renderPermissionLevel(props.dispatch, props.link, props.canManage));
617
618 const getResourceLinkCanManage = (state: RootState, link: LinkResource) => {
619     const headResource = getResource<Resource>(link.headUuid)(state.resources);
620     // const tailResource = getResource<Resource>(link.tailUuid)(state.resources);
621     const userUuid = getUserUuid(state);
622
623     if (headResource && headResource.kind === ResourceKind.GROUP) {
624         return userUuid ? (headResource as GroupResource).writableBy?.includes(userUuid) : false;
625     } else {
626         // true for now
627         return true;
628     }
629 }
630
631 // Process Resources
632 const resourceRunProcess = (dispatch: Dispatch, uuid: string) => {
633     return (
634         <div>
635             {uuid &&
636                 <Tooltip title="Run process">
637                     <IconButton onClick={() => dispatch<any>(openRunProcess(uuid))}>
638                         <ProcessIcon />
639                     </IconButton>
640                 </Tooltip>}
641         </div>
642     );
643 };
644
645 export const ResourceRunProcess = connect(
646     (state: RootState, props: { uuid: string }) => {
647         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
648         return {
649             uuid: resource ? resource.uuid : ''
650         };
651     })((props: { uuid: string } & DispatchProp<any>) =>
652         resourceRunProcess(props.dispatch, props.uuid));
653
654 const renderWorkflowStatus = (uuidPrefix: string, ownerUuid?: string) => {
655     if (ownerUuid === getPublicUuid(uuidPrefix)) {
656         return renderStatus(WorkflowStatus.PUBLIC);
657     } else {
658         return renderStatus(WorkflowStatus.PRIVATE);
659     }
660 };
661
662 const renderStatus = (status: string) =>
663     <Typography noWrap style={{ width: '60px' }}>{status}</Typography>;
664
665 export const ResourceWorkflowStatus = connect(
666     (state: RootState, props: { uuid: string }) => {
667         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
668         const uuidPrefix = getUuidPrefix(state);
669         return {
670             ownerUuid: resource ? resource.ownerUuid : '',
671             uuidPrefix
672         };
673     })((props: { ownerUuid?: string, uuidPrefix: string }) => renderWorkflowStatus(props.uuidPrefix, props.ownerUuid));
674
675 export const ResourceContainerUuid = connect(
676     (state: RootState, props: { uuid: string }) => {
677         const process = getProcess(props.uuid)(state.resources)
678         return { uuid: process?.container?.uuid ? process?.container?.uuid : '' };
679     })((props: { uuid: string }) => renderUuid({ uuid: props.uuid }));
680
681 enum ColumnSelection {
682     OUTPUT_UUID = 'outputUuid',
683     LOG_UUID = 'logUuid'
684 }
685
686 const renderUuidLinkWithCopyIcon = (dispatch: Dispatch, item: ProcessResource, column: string) => {
687     const selectedColumnUuid = item[column]
688     return <Grid container alignItems="center" wrap="nowrap" >
689         <Grid item>
690             {selectedColumnUuid ? 
691                 <Typography color="primary" style={{ width: 'auto', cursor: 'pointer' }} noWrap 
692                     onClick={() => dispatch<any>(navigateTo(selectedColumnUuid))}>
693                     {selectedColumnUuid} 
694                 </Typography> 
695             : '-' }
696         </Grid>
697         <Grid item>
698             {selectedColumnUuid && renderUuidCopyIcon({ uuid: selectedColumnUuid })}
699         </Grid>
700     </Grid>;
701 };
702
703 export const ResourceOutputUuid = connect(
704     (state: RootState, props: { uuid: string }) => {
705         const resource = getResource<ProcessResource>(props.uuid)(state.resources);
706         return resource;
707     })((process: ProcessResource & DispatchProp<any>) => renderUuidLinkWithCopyIcon(process.dispatch, process, ColumnSelection.OUTPUT_UUID));
708
709 export const ResourceLogUuid = connect(
710     (state: RootState, props: { uuid: string }) => {
711         const resource = getResource<ProcessResource>(props.uuid)(state.resources);
712         return resource;
713     })((process: ProcessResource & DispatchProp<any>) => renderUuidLinkWithCopyIcon(process.dispatch, process, ColumnSelection.LOG_UUID));
714
715 export const ResourceParentProcess = connect(
716     (state: RootState, props: { uuid: string }) => {
717         const process = getProcess(props.uuid)(state.resources)
718         return { parentProcess: process?.containerRequest?.requestingContainerUuid || '' };
719     })((props: { parentProcess: string }) => renderUuid({uuid: props.parentProcess}));
720
721 export const ResourceModifiedByUserUuid = connect(
722     (state: RootState, props: { uuid: string }) => {
723         const process = getProcess(props.uuid)(state.resources)
724         return { userUuid: process?.containerRequest?.modifiedByUserUuid || '' };
725     })((props: { userUuid: string }) => renderUuid({uuid: props.userUuid}));
726
727     export const ResourceCreatedAtDate = connect(
728     (state: RootState, props: { uuid: string }) => {
729         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
730         return { date: resource ? resource.createdAt : '' };
731     })((props: { date: string }) => renderDate(props.date));
732     
733 export const ResourceLastModifiedDate = connect(
734     (state: RootState, props: { uuid: string }) => {
735         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
736         return { date: resource ? resource.modifiedAt : '' };
737     })((props: { date: string }) => renderDate(props.date));
738
739 export const ResourceTrashDate = connect(
740     (state: RootState, props: { uuid: string }) => {
741         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
742         return { date: resource ? resource.trashAt : '' };
743     })((props: { date: string }) => renderDate(props.date));
744
745 export const ResourceDeleteDate = connect(
746     (state: RootState, props: { uuid: string }) => {
747         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
748         return { date: resource ? resource.deleteAt : '' };
749     })((props: { date: string }) => renderDate(props.date));
750
751 export const renderFileSize = (fileSize?: number) =>
752     <Typography noWrap style={{ minWidth: '45px' }}>
753         {formatFileSize(fileSize)}
754     </Typography>;
755
756 export const ResourceFileSize = connect(
757     (state: RootState, props: { uuid: string }) => {
758         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
759
760         if (resource && resource.kind !== ResourceKind.COLLECTION) {
761             return { fileSize: '' };
762         }
763
764         return { fileSize: resource ? resource.fileSizeTotal : 0 };
765     })((props: { fileSize?: number }) => renderFileSize(props.fileSize));
766
767 const renderOwner = (owner: string) =>
768     <Typography noWrap>
769         {owner || '-'}
770     </Typography>;
771
772 export const ResourceOwner = connect(
773     (state: RootState, props: { uuid: string }) => {
774         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
775         return { owner: resource ? resource.ownerUuid : '' };
776     })((props: { owner: string }) => renderOwner(props.owner));
777
778 export const ResourceOwnerName = connect(
779     (state: RootState, props: { uuid: string }) => {
780         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
781         const ownerNameState = state.ownerName;
782         const ownerName = ownerNameState.find(it => it.uuid === resource!.ownerUuid);
783         return { owner: ownerName ? ownerName!.name : resource!.ownerUuid };
784     })((props: { owner: string }) => renderOwner(props.owner));
785
786 export const ResourceUUID = connect(
787     (state: RootState, props: { uuid: string }) => {
788         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
789         return { uuid: resource ? resource.uuid : '' };
790     })((props: { uuid: string }) => renderUuid({uuid: props.uuid}));
791
792 const renderVersion = (version: number) =>{
793     return <Typography>{version ?? '-'}</Typography>
794 }
795
796 export const ResourceVersion = connect(
797     (state: RootState, props: { uuid: string }) => {
798         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
799         return { version: resource ? resource.version: '' };
800     })((props: { version: number }) => renderVersion(props.version));
801     
802 const renderPortableDataHash = (portableDataHash:string | null) => 
803     <Typography noWrap>
804         {portableDataHash ? <>{portableDataHash}
805         <CopyToClipboardSnackbar value={portableDataHash} /></> : '-' }
806     </Typography>
807     
808 export const ResourcePortableDataHash = connect(
809     (state: RootState, props: { uuid: string }) => {
810         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
811         return { portableDataHash: resource ? resource.portableDataHash : '' };    
812     })((props: { portableDataHash: string }) => renderPortableDataHash(props.portableDataHash));
813
814
815 const renderFileCount = (fileCount: number) =>{
816     return <Typography>{fileCount ?? '-'}</Typography>
817 }
818
819 export const ResourceFileCount = connect(
820     (state: RootState, props: { uuid: string }) => {
821         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
822         return { fileCount: resource ? resource.fileCount: '' };
823     })((props: { fileCount: number }) => renderFileCount(props.fileCount));
824
825 const userFromID =
826     connect(
827         (state: RootState, props: { uuid: string }) => {
828             let userFullname = '';
829             const resource = getResource<GroupContentsResource & UserResource>(props.uuid)(state.resources);
830
831             if (resource) {
832                 userFullname = getUserFullname(resource as User) || (resource as GroupContentsResource).name;
833             }
834
835             return { uuid: props.uuid, userFullname };
836         });
837
838 const ownerFromResourceId =
839     compose(
840         connect((state: RootState, props: { uuid: string }) => {
841             const childResource = getResource<GroupContentsResource & UserResource>(props.uuid)(state.resources);
842             return { uuid: childResource ? (childResource as Resource).ownerUuid : '' };
843         }),
844         userFromID
845     );
846
847
848
849
850
851 const _resourceWithName =
852     withStyles({}, { withTheme: true })
853         ((props: { uuid: string, userFullname: string, dispatch: Dispatch, theme: ArvadosTheme }) => {
854             const { uuid, userFullname, dispatch, theme } = props;
855             if (userFullname === '') {
856                 dispatch<any>(loadResource(uuid, false));
857                 return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
858                     {uuid}
859                 </Typography>;
860             }
861
862             return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
863                 {userFullname} ({uuid})
864             </Typography>;
865         });
866
867 export const ResourceOwnerWithName = ownerFromResourceId(_resourceWithName);
868
869 export const ResourceWithName = userFromID(_resourceWithName);
870
871
872
873 export const UserNameFromID =
874     compose(userFromID)(
875         (props: { uuid: string, displayAsText?: string, userFullname: string, dispatch: Dispatch }) => {
876             const { uuid, userFullname, dispatch } = props;
877
878             if (userFullname === '') {
879                 dispatch<any>(loadResource(uuid, false));
880             }
881             return <span>
882                 {userFullname ? userFullname : uuid}
883             </span>;
884         });
885
886 export const ResponsiblePerson =
887     compose(
888         connect(
889             (state: RootState, props: { uuid: string, parentRef: HTMLElement | null }) => {
890                 let responsiblePersonName: string = '';
891                 let responsiblePersonUUID: string = '';
892                 let responsiblePersonProperty: string = '';
893
894                 if (state.auth.config.clusterConfig.Collections.ManagedProperties) {
895                     let index = 0;
896                     const keys = Object.keys(state.auth.config.clusterConfig.Collections.ManagedProperties);
897
898                     while (!responsiblePersonProperty && keys[index]) {
899                         const key = keys[index];
900                         if (state.auth.config.clusterConfig.Collections.ManagedProperties[key].Function === 'original_owner') {
901                             responsiblePersonProperty = key;
902                         }
903                         index++;
904                     }
905                 }
906
907                 let resource: Resource | undefined = getResource<GroupContentsResource & UserResource>(props.uuid)(state.resources);
908
909                 while (resource && resource.kind !== ResourceKind.USER && responsiblePersonProperty) {
910                     responsiblePersonUUID = (resource as CollectionResource).properties[responsiblePersonProperty];
911                     resource = getResource<GroupContentsResource & UserResource>(responsiblePersonUUID)(state.resources);
912                 }
913
914                 if (resource && resource.kind === ResourceKind.USER) {
915                     responsiblePersonName = getUserFullname(resource as UserResource) || (resource as GroupContentsResource).name;
916                 }
917
918                 return { uuid: responsiblePersonUUID, responsiblePersonName, parentRef: props.parentRef };
919             }),
920         withStyles({}, { withTheme: true }))
921         ((props: { uuid: string | null, responsiblePersonName: string, parentRef: HTMLElement | null, theme: ArvadosTheme }) => {
922             const { uuid, responsiblePersonName, parentRef, theme } = props;
923
924             if (!uuid && parentRef) {
925                 parentRef.style.display = 'none';
926                 return null;
927             } else if (parentRef) {
928                 parentRef.style.display = 'block';
929             }
930
931             if (!responsiblePersonName) {
932                 return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
933                     {uuid}
934                 </Typography>;
935             }
936
937             return <Typography style={{ color: theme.palette.primary.main }} inline noWrap>
938                 {responsiblePersonName} ({uuid})
939             </Typography>;
940         });
941
942 const renderType = (type: string, subtype: string) =>
943     <Typography noWrap>
944         {resourceLabel(type, subtype)}
945     </Typography>;
946
947 export const ResourceType = connect(
948     (state: RootState, props: { uuid: string }) => {
949         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
950         return { type: resource ? resource.kind : '', subtype: resource && resource.kind === ResourceKind.GROUP ? resource.groupClass : '' };
951     })((props: { type: string, subtype: string }) => renderType(props.type, props.subtype));
952
953 export const ResourceStatus = connect((state: RootState, props: { uuid: string }) => {
954     return { resource: getResource<GroupContentsResource>(props.uuid)(state.resources) };
955 })((props: { resource: GroupContentsResource }) =>
956     (props.resource && props.resource.kind === ResourceKind.COLLECTION)
957         ? <CollectionStatus uuid={props.resource.uuid} />
958         : <ProcessStatus uuid={props.resource.uuid} />
959 );
960
961 export const CollectionStatus = connect((state: RootState, props: { uuid: string }) => {
962     return { collection: getResource<CollectionResource>(props.uuid)(state.resources) };
963 })((props: { collection: CollectionResource }) =>
964     (props.collection.uuid !== props.collection.currentVersionUuid)
965         ? <Typography>version {props.collection.version}</Typography>
966         : <Typography>head version</Typography>
967 );
968
969 export const CollectionName = connect((state: RootState, props: { uuid: string, className?: string }) => {
970     return {
971                 collection: getResource<CollectionResource>(props.uuid)(state.resources),
972                 uuid: props.uuid,
973                 className: props.className,
974             };
975 })((props: { collection: CollectionResource, uuid: string, className?: string }) =>
976         <Typography className={props.className}>{props.collection?.name || props.uuid}</Typography>
977 );
978
979 export const ProcessStatus = compose(
980     connect((state: RootState, props: { uuid: string }) => {
981         return { process: getProcess(props.uuid)(state.resources) };
982     }),
983     withStyles({}, { withTheme: true }))
984     ((props: { process?: Process, theme: ArvadosTheme }) =>
985         props.process
986             ? <Chip label={getProcessStatus(props.process)}
987                 style={{
988                     height: props.theme.spacing.unit * 3,
989                     width: props.theme.spacing.unit * 12,
990                     ...getProcessStatusStyles(
991                         getProcessStatus(props.process), props.theme),
992                     fontSize: '0.875rem',
993                     borderRadius: props.theme.spacing.unit * 0.625,
994                 }}
995             />
996             : <Typography>-</Typography>
997         );
998
999 export const ProcessStartDate = connect(
1000     (state: RootState, props: { uuid: string }) => {
1001         const process = getProcess(props.uuid)(state.resources);
1002         return { date: (process && process.container) ? process.container.startedAt : '' };
1003     })((props: { date: string }) => renderDate(props.date));
1004
1005 export const renderRunTime = (time: number) =>
1006     <Typography noWrap style={{ minWidth: '45px' }}>
1007         {formatTime(time, true)}
1008     </Typography>;
1009
1010 interface ContainerRunTimeProps {
1011     process: Process;
1012 }
1013
1014 interface ContainerRunTimeState {
1015     runtime: number;
1016 }
1017
1018 export const ContainerRunTime = connect((state: RootState, props: { uuid: string }) => {
1019     return { process: getProcess(props.uuid)(state.resources) };
1020 })(class extends React.Component<ContainerRunTimeProps, ContainerRunTimeState> {
1021     private timer: any;
1022
1023     constructor(props: ContainerRunTimeProps) {
1024         super(props);
1025         this.state = { runtime: this.getRuntime() };
1026     }
1027
1028     getRuntime() {
1029         return this.props.process ? getProcessRuntime(this.props.process) : 0;
1030     }
1031
1032     updateRuntime() {
1033         this.setState({ runtime: this.getRuntime() });
1034     }
1035
1036     componentDidMount() {
1037         this.timer = setInterval(this.updateRuntime.bind(this), 5000);
1038     }
1039
1040     componentWillUnmount() {
1041         clearInterval(this.timer);
1042     }
1043
1044     render() {
1045         return this.props.process ? renderRunTime(this.state.runtime) : <Typography>-</Typography>;
1046     }
1047 });