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