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