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