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