index
int64 0
0
| repo_id
stringlengths 21
232
| file_path
stringlengths 34
259
| content
stringlengths 1
14.1M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 | kubeflow_public_repos/pipelines/frontend/src/atoms | kubeflow_public_repos/pipelines/frontend/src/atoms/__snapshots__/Separator.test.tsx.snap | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Separator renders with the right styles by default 1`] = `
<span
style={
Object {
"display": "inline-block",
"minWidth": 10,
"width": 10,
}
}
/>
`;
exports[`Separator renders with the specified orientation 1`] = `
<span
style={
Object {
"display": "block",
"flexShrink": 0,
"height": 10,
"minHeight": 10,
}
}
/>
`;
exports[`Separator renders with the specified units 1`] = `
<span
style={
Object {
"display": "inline-block",
"minWidth": 123,
"width": 123,
}
}
/>
`;
| 200 |
0 | kubeflow_public_repos/pipelines/frontend/src/atoms | kubeflow_public_repos/pipelines/frontend/src/atoms/__snapshots__/MD2Tabs.test.tsx.snap | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Input gracefully handles an out of bound selectedTab value 1`] = `
<MD2Tabs
selectedTab={100}
tabs={
Array [
"tab1",
"tab2",
]
}
>
<div
className="tabs"
>
<div
className="indicator"
/>
<Separator
units={20}
>
<span
style={
Object {
"display": "inline-block",
"minWidth": 20,
"width": 20,
}
}
/>
</Separator>
<WithStyles(Tooltip)
key="0"
placement="top-start"
title=""
>
<Tooltip
TransitionComponent={[Function]}
classes={
Object {
"popper": "MuiTooltip-popper-1",
"popperInteractive": "MuiTooltip-popperInteractive-2",
"tooltip": "MuiTooltip-tooltip-3",
"tooltipPlacementBottom": "MuiTooltip-tooltipPlacementBottom-8",
"tooltipPlacementLeft": "MuiTooltip-tooltipPlacementLeft-5",
"tooltipPlacementRight": "MuiTooltip-tooltipPlacementRight-6",
"tooltipPlacementTop": "MuiTooltip-tooltipPlacementTop-7",
"touch": "MuiTooltip-touch-4",
}
}
disableFocusListener={false}
disableHoverListener={false}
disableTouchListener={false}
enterDelay={0}
enterTouchDelay={1000}
interactive={false}
leaveDelay={0}
leaveTouchDelay={1500}
placement="top-start"
theme={
Object {
"breakpoints": Object {
"between": [Function],
"down": [Function],
"keys": Array [
"xs",
"sm",
"md",
"lg",
"xl",
],
"only": [Function],
"up": [Function],
"values": Object {
"lg": 1280,
"md": 960,
"sm": 600,
"xl": 1920,
"xs": 0,
},
"width": [Function],
},
"direction": "ltr",
"mixins": Object {
"gutters": [Function],
"toolbar": Object {
"@media (min-width:0px) and (orientation: landscape)": Object {
"minHeight": 48,
},
"@media (min-width:600px)": Object {
"minHeight": 64,
},
"minHeight": 56,
},
},
"overrides": Object {},
"palette": Object {
"action": Object {
"active": "rgba(0, 0, 0, 0.54)",
"disabled": "rgba(0, 0, 0, 0.26)",
"disabledBackground": "rgba(0, 0, 0, 0.12)",
"hover": "rgba(0, 0, 0, 0.08)",
"hoverOpacity": 0.08,
"selected": "rgba(0, 0, 0, 0.14)",
},
"augmentColor": [Function],
"background": Object {
"default": "#fafafa",
"paper": "#fff",
},
"common": Object {
"black": "#000",
"white": "#fff",
},
"contrastThreshold": 3,
"divider": "rgba(0, 0, 0, 0.12)",
"error": Object {
"contrastText": "#fff",
"dark": "#d32f2f",
"light": "#e57373",
"main": "#f44336",
},
"getContrastText": [Function],
"grey": Object {
"100": "#f5f5f5",
"200": "#eeeeee",
"300": "#e0e0e0",
"400": "#bdbdbd",
"50": "#fafafa",
"500": "#9e9e9e",
"600": "#757575",
"700": "#616161",
"800": "#424242",
"900": "#212121",
"A100": "#d5d5d5",
"A200": "#aaaaaa",
"A400": "#303030",
"A700": "#616161",
},
"primary": Object {
"contrastText": "#fff",
"dark": "#303f9f",
"light": "#7986cb",
"main": "#3f51b5",
},
"secondary": Object {
"contrastText": "#fff",
"dark": "#c51162",
"light": "#ff4081",
"main": "#f50057",
},
"text": Object {
"disabled": "rgba(0, 0, 0, 0.38)",
"hint": "rgba(0, 0, 0, 0.38)",
"primary": "rgba(0, 0, 0, 0.87)",
"secondary": "rgba(0, 0, 0, 0.54)",
},
"tonalOffset": 0.2,
"type": "light",
},
"props": Object {},
"shadows": Array [
"none",
"0px 1px 3px 0px rgba(0,0,0,0.2),0px 1px 1px 0px rgba(0,0,0,0.14),0px 2px 1px -1px rgba(0,0,0,0.12)",
"0px 1px 5px 0px rgba(0,0,0,0.2),0px 2px 2px 0px rgba(0,0,0,0.14),0px 3px 1px -2px rgba(0,0,0,0.12)",
"0px 1px 8px 0px rgba(0,0,0,0.2),0px 3px 4px 0px rgba(0,0,0,0.14),0px 3px 3px -2px rgba(0,0,0,0.12)",
"0px 2px 4px -1px rgba(0,0,0,0.2),0px 4px 5px 0px rgba(0,0,0,0.14),0px 1px 10px 0px rgba(0,0,0,0.12)",
"0px 3px 5px -1px rgba(0,0,0,0.2),0px 5px 8px 0px rgba(0,0,0,0.14),0px 1px 14px 0px rgba(0,0,0,0.12)",
"0px 3px 5px -1px rgba(0,0,0,0.2),0px 6px 10px 0px rgba(0,0,0,0.14),0px 1px 18px 0px rgba(0,0,0,0.12)",
"0px 4px 5px -2px rgba(0,0,0,0.2),0px 7px 10px 1px rgba(0,0,0,0.14),0px 2px 16px 1px rgba(0,0,0,0.12)",
"0px 5px 5px -3px rgba(0,0,0,0.2),0px 8px 10px 1px rgba(0,0,0,0.14),0px 3px 14px 2px rgba(0,0,0,0.12)",
"0px 5px 6px -3px rgba(0,0,0,0.2),0px 9px 12px 1px rgba(0,0,0,0.14),0px 3px 16px 2px rgba(0,0,0,0.12)",
"0px 6px 6px -3px rgba(0,0,0,0.2),0px 10px 14px 1px rgba(0,0,0,0.14),0px 4px 18px 3px rgba(0,0,0,0.12)",
"0px 6px 7px -4px rgba(0,0,0,0.2),0px 11px 15px 1px rgba(0,0,0,0.14),0px 4px 20px 3px rgba(0,0,0,0.12)",
"0px 7px 8px -4px rgba(0,0,0,0.2),0px 12px 17px 2px rgba(0,0,0,0.14),0px 5px 22px 4px rgba(0,0,0,0.12)",
"0px 7px 8px -4px rgba(0,0,0,0.2),0px 13px 19px 2px rgba(0,0,0,0.14),0px 5px 24px 4px rgba(0,0,0,0.12)",
"0px 7px 9px -4px rgba(0,0,0,0.2),0px 14px 21px 2px rgba(0,0,0,0.14),0px 5px 26px 4px rgba(0,0,0,0.12)",
"0px 8px 9px -5px rgba(0,0,0,0.2),0px 15px 22px 2px rgba(0,0,0,0.14),0px 6px 28px 5px rgba(0,0,0,0.12)",
"0px 8px 10px -5px rgba(0,0,0,0.2),0px 16px 24px 2px rgba(0,0,0,0.14),0px 6px 30px 5px rgba(0,0,0,0.12)",
"0px 8px 11px -5px rgba(0,0,0,0.2),0px 17px 26px 2px rgba(0,0,0,0.14),0px 6px 32px 5px rgba(0,0,0,0.12)",
"0px 9px 11px -5px rgba(0,0,0,0.2),0px 18px 28px 2px rgba(0,0,0,0.14),0px 7px 34px 6px rgba(0,0,0,0.12)",
"0px 9px 12px -6px rgba(0,0,0,0.2),0px 19px 29px 2px rgba(0,0,0,0.14),0px 7px 36px 6px rgba(0,0,0,0.12)",
"0px 10px 13px -6px rgba(0,0,0,0.2),0px 20px 31px 3px rgba(0,0,0,0.14),0px 8px 38px 7px rgba(0,0,0,0.12)",
"0px 10px 13px -6px rgba(0,0,0,0.2),0px 21px 33px 3px rgba(0,0,0,0.14),0px 8px 40px 7px rgba(0,0,0,0.12)",
"0px 10px 14px -6px rgba(0,0,0,0.2),0px 22px 35px 3px rgba(0,0,0,0.14),0px 8px 42px 7px rgba(0,0,0,0.12)",
"0px 11px 14px -7px rgba(0,0,0,0.2),0px 23px 36px 3px rgba(0,0,0,0.14),0px 9px 44px 8px rgba(0,0,0,0.12)",
"0px 11px 15px -7px rgba(0,0,0,0.2),0px 24px 38px 3px rgba(0,0,0,0.14),0px 9px 46px 8px rgba(0,0,0,0.12)",
],
"shape": Object {
"borderRadius": 4,
},
"spacing": Object {
"unit": 8,
},
"transitions": Object {
"create": [Function],
"duration": Object {
"complex": 375,
"enteringScreen": 225,
"leavingScreen": 195,
"short": 250,
"shorter": 200,
"shortest": 150,
"standard": 300,
},
"easing": Object {
"easeIn": "cubic-bezier(0.4, 0, 1, 1)",
"easeInOut": "cubic-bezier(0.4, 0, 0.2, 1)",
"easeOut": "cubic-bezier(0.0, 0, 0.2, 1)",
"sharp": "cubic-bezier(0.4, 0, 0.6, 1)",
},
"getAutoHeightDuration": [Function],
},
"typography": Object {
"body1": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 400,
"lineHeight": "1.46429em",
},
"body1Next": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1rem",
"fontWeight": 400,
"letterSpacing": "0.00938em",
"lineHeight": 1.5,
},
"body2": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 500,
"lineHeight": "1.71429em",
},
"body2Next": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 400,
"letterSpacing": "0.01071em",
"lineHeight": 1.5,
},
"button": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 500,
"textTransform": "uppercase",
},
"buttonNext": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 500,
"letterSpacing": "0.02857em",
"lineHeight": 1.75,
"textTransform": "uppercase",
},
"caption": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.75rem",
"fontWeight": 400,
"lineHeight": "1.375em",
},
"captionNext": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.75rem",
"fontWeight": 400,
"letterSpacing": "0.03333em",
"lineHeight": 1.66,
},
"display1": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "2.125rem",
"fontWeight": 400,
"lineHeight": "1.20588em",
},
"display2": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "2.8125rem",
"fontWeight": 400,
"lineHeight": "1.13333em",
"marginLeft": "-.02em",
},
"display3": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "3.5rem",
"fontWeight": 400,
"letterSpacing": "-.02em",
"lineHeight": "1.30357em",
"marginLeft": "-.02em",
},
"display4": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "7rem",
"fontWeight": 300,
"letterSpacing": "-.04em",
"lineHeight": "1.14286em",
"marginLeft": "-.04em",
},
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": 14,
"fontWeightLight": 300,
"fontWeightMedium": 500,
"fontWeightRegular": 400,
"h1": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "6rem",
"fontWeight": 300,
"letterSpacing": "-0.01562em",
"lineHeight": 1,
},
"h2": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "3.75rem",
"fontWeight": 300,
"letterSpacing": "-0.00833em",
"lineHeight": 1,
},
"h3": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "3rem",
"fontWeight": 400,
"letterSpacing": "0em",
"lineHeight": 1.04,
},
"h4": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "2.125rem",
"fontWeight": 400,
"letterSpacing": "0.00735em",
"lineHeight": 1.17,
},
"h5": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1.5rem",
"fontWeight": 400,
"letterSpacing": "0em",
"lineHeight": 1.33,
},
"h6": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1.25rem",
"fontWeight": 500,
"letterSpacing": "0.0075em",
"lineHeight": 1.6,
},
"headline": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1.5rem",
"fontWeight": 400,
"lineHeight": "1.35417em",
},
"overline": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.75rem",
"fontWeight": 400,
"letterSpacing": "0.08333em",
"lineHeight": 2.66,
"textTransform": "uppercase",
},
"pxToRem": [Function],
"round": [Function],
"subheading": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1rem",
"fontWeight": 400,
"lineHeight": "1.5em",
},
"subtitle1": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1rem",
"fontWeight": 400,
"letterSpacing": "0.00938em",
"lineHeight": 1.75,
},
"subtitle2": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 500,
"letterSpacing": "0.00714em",
"lineHeight": 1.57,
},
"title": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1.3125rem",
"fontWeight": 500,
"lineHeight": "1.16667em",
},
"useNextVariants": false,
},
"zIndex": Object {
"appBar": 1100,
"drawer": 1200,
"mobileStepper": 1000,
"modal": 1300,
"snackbar": 1400,
"tooltip": 1500,
},
}
}
title=""
>
<RootRef
rootRef={[Function]}
>
<WithStyles(Button)
aria-describedby={null}
className="button active"
key="0"
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
title=""
>
<Button
aria-describedby={null}
className="button active"
classes={
Object {
"colorInherit": "MuiButton-colorInherit-30",
"contained": "MuiButton-contained-20",
"containedPrimary": "MuiButton-containedPrimary-21",
"containedSecondary": "MuiButton-containedSecondary-22",
"disabled": "MuiButton-disabled-29",
"extendedFab": "MuiButton-extendedFab-27",
"fab": "MuiButton-fab-26",
"flat": "MuiButton-flat-14",
"flatPrimary": "MuiButton-flatPrimary-15",
"flatSecondary": "MuiButton-flatSecondary-16",
"focusVisible": "MuiButton-focusVisible-28",
"fullWidth": "MuiButton-fullWidth-34",
"label": "MuiButton-label-10",
"mini": "MuiButton-mini-31",
"outlined": "MuiButton-outlined-17",
"outlinedPrimary": "MuiButton-outlinedPrimary-18",
"outlinedSecondary": "MuiButton-outlinedSecondary-19",
"raised": "MuiButton-raised-23",
"raisedPrimary": "MuiButton-raisedPrimary-24",
"raisedSecondary": "MuiButton-raisedSecondary-25",
"root": "MuiButton-root-9",
"sizeLarge": "MuiButton-sizeLarge-33",
"sizeSmall": "MuiButton-sizeSmall-32",
"text": "MuiButton-text-11",
"textPrimary": "MuiButton-textPrimary-12",
"textSecondary": "MuiButton-textSecondary-13",
}
}
color="default"
component="button"
disableFocusRipple={false}
disabled={false}
fullWidth={false}
mini={false}
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
size="medium"
title=""
type="button"
variant="text"
>
<WithStyles(ButtonBase)
aria-describedby={null}
className="MuiButton-root-9 MuiButton-text-11 MuiButton-flat-14 button active"
component="button"
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-28"
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
title=""
type="button"
>
<ButtonBase
aria-describedby={null}
centerRipple={false}
className="MuiButton-root-9 MuiButton-text-11 MuiButton-flat-14 button active"
classes={
Object {
"disabled": "MuiButtonBase-disabled-36",
"focusVisible": "MuiButtonBase-focusVisible-37",
"root": "MuiButtonBase-root-35",
}
}
component="button"
disableRipple={false}
disableTouchRipple={false}
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-28"
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
tabIndex="0"
title=""
type="button"
>
<button
aria-describedby={null}
className="MuiButtonBase-root-35 MuiButton-root-9 MuiButton-text-11 MuiButton-flat-14 button active"
disabled={false}
onBlur={[Function]}
onClick={[Function]}
onContextMenu={[Function]}
onFocus={[Function]}
onKeyDown={[Function]}
onKeyUp={[Function]}
onMouseDown={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onMouseUp={[Function]}
onTouchEnd={[Function]}
onTouchMove={[Function]}
onTouchStart={[Function]}
tabIndex="0"
title=""
type="button"
>
<span
className="MuiButton-label-10"
>
<span>
tab1
</span>
</span>
<NoSsr
defer={false}
fallback={null}
>
<WithStyles(TouchRipple)
center={false}
innerRef={[Function]}
>
<TouchRipple
center={false}
classes={
Object {
"child": "MuiTouchRipple-child-42",
"childLeaving": "MuiTouchRipple-childLeaving-43",
"childPulsate": "MuiTouchRipple-childPulsate-44",
"ripple": "MuiTouchRipple-ripple-39",
"ripplePulsate": "MuiTouchRipple-ripplePulsate-41",
"rippleVisible": "MuiTouchRipple-rippleVisible-40",
"root": "MuiTouchRipple-root-38",
}
}
>
<TransitionGroup
childFactory={[Function]}
className="MuiTouchRipple-root-38"
component="span"
enter={true}
exit={true}
>
<span
className="MuiTouchRipple-root-38"
/>
</TransitionGroup>
</TouchRipple>
</WithStyles(TouchRipple)>
</NoSsr>
</button>
</ButtonBase>
</WithStyles(ButtonBase)>
</Button>
</WithStyles(Button)>
</RootRef>
<Popper
className="MuiTooltip-popper-1"
disablePortal={false}
id={null}
open={false}
placement="top-start"
transition={true}
/>
</Tooltip>
</WithStyles(Tooltip)>
<WithStyles(Tooltip)
key="1"
placement="top-start"
title=""
>
<Tooltip
TransitionComponent={[Function]}
classes={
Object {
"popper": "MuiTooltip-popper-1",
"popperInteractive": "MuiTooltip-popperInteractive-2",
"tooltip": "MuiTooltip-tooltip-3",
"tooltipPlacementBottom": "MuiTooltip-tooltipPlacementBottom-8",
"tooltipPlacementLeft": "MuiTooltip-tooltipPlacementLeft-5",
"tooltipPlacementRight": "MuiTooltip-tooltipPlacementRight-6",
"tooltipPlacementTop": "MuiTooltip-tooltipPlacementTop-7",
"touch": "MuiTooltip-touch-4",
}
}
disableFocusListener={false}
disableHoverListener={false}
disableTouchListener={false}
enterDelay={0}
enterTouchDelay={1000}
interactive={false}
leaveDelay={0}
leaveTouchDelay={1500}
placement="top-start"
theme={
Object {
"breakpoints": Object {
"between": [Function],
"down": [Function],
"keys": Array [
"xs",
"sm",
"md",
"lg",
"xl",
],
"only": [Function],
"up": [Function],
"values": Object {
"lg": 1280,
"md": 960,
"sm": 600,
"xl": 1920,
"xs": 0,
},
"width": [Function],
},
"direction": "ltr",
"mixins": Object {
"gutters": [Function],
"toolbar": Object {
"@media (min-width:0px) and (orientation: landscape)": Object {
"minHeight": 48,
},
"@media (min-width:600px)": Object {
"minHeight": 64,
},
"minHeight": 56,
},
},
"overrides": Object {},
"palette": Object {
"action": Object {
"active": "rgba(0, 0, 0, 0.54)",
"disabled": "rgba(0, 0, 0, 0.26)",
"disabledBackground": "rgba(0, 0, 0, 0.12)",
"hover": "rgba(0, 0, 0, 0.08)",
"hoverOpacity": 0.08,
"selected": "rgba(0, 0, 0, 0.14)",
},
"augmentColor": [Function],
"background": Object {
"default": "#fafafa",
"paper": "#fff",
},
"common": Object {
"black": "#000",
"white": "#fff",
},
"contrastThreshold": 3,
"divider": "rgba(0, 0, 0, 0.12)",
"error": Object {
"contrastText": "#fff",
"dark": "#d32f2f",
"light": "#e57373",
"main": "#f44336",
},
"getContrastText": [Function],
"grey": Object {
"100": "#f5f5f5",
"200": "#eeeeee",
"300": "#e0e0e0",
"400": "#bdbdbd",
"50": "#fafafa",
"500": "#9e9e9e",
"600": "#757575",
"700": "#616161",
"800": "#424242",
"900": "#212121",
"A100": "#d5d5d5",
"A200": "#aaaaaa",
"A400": "#303030",
"A700": "#616161",
},
"primary": Object {
"contrastText": "#fff",
"dark": "#303f9f",
"light": "#7986cb",
"main": "#3f51b5",
},
"secondary": Object {
"contrastText": "#fff",
"dark": "#c51162",
"light": "#ff4081",
"main": "#f50057",
},
"text": Object {
"disabled": "rgba(0, 0, 0, 0.38)",
"hint": "rgba(0, 0, 0, 0.38)",
"primary": "rgba(0, 0, 0, 0.87)",
"secondary": "rgba(0, 0, 0, 0.54)",
},
"tonalOffset": 0.2,
"type": "light",
},
"props": Object {},
"shadows": Array [
"none",
"0px 1px 3px 0px rgba(0,0,0,0.2),0px 1px 1px 0px rgba(0,0,0,0.14),0px 2px 1px -1px rgba(0,0,0,0.12)",
"0px 1px 5px 0px rgba(0,0,0,0.2),0px 2px 2px 0px rgba(0,0,0,0.14),0px 3px 1px -2px rgba(0,0,0,0.12)",
"0px 1px 8px 0px rgba(0,0,0,0.2),0px 3px 4px 0px rgba(0,0,0,0.14),0px 3px 3px -2px rgba(0,0,0,0.12)",
"0px 2px 4px -1px rgba(0,0,0,0.2),0px 4px 5px 0px rgba(0,0,0,0.14),0px 1px 10px 0px rgba(0,0,0,0.12)",
"0px 3px 5px -1px rgba(0,0,0,0.2),0px 5px 8px 0px rgba(0,0,0,0.14),0px 1px 14px 0px rgba(0,0,0,0.12)",
"0px 3px 5px -1px rgba(0,0,0,0.2),0px 6px 10px 0px rgba(0,0,0,0.14),0px 1px 18px 0px rgba(0,0,0,0.12)",
"0px 4px 5px -2px rgba(0,0,0,0.2),0px 7px 10px 1px rgba(0,0,0,0.14),0px 2px 16px 1px rgba(0,0,0,0.12)",
"0px 5px 5px -3px rgba(0,0,0,0.2),0px 8px 10px 1px rgba(0,0,0,0.14),0px 3px 14px 2px rgba(0,0,0,0.12)",
"0px 5px 6px -3px rgba(0,0,0,0.2),0px 9px 12px 1px rgba(0,0,0,0.14),0px 3px 16px 2px rgba(0,0,0,0.12)",
"0px 6px 6px -3px rgba(0,0,0,0.2),0px 10px 14px 1px rgba(0,0,0,0.14),0px 4px 18px 3px rgba(0,0,0,0.12)",
"0px 6px 7px -4px rgba(0,0,0,0.2),0px 11px 15px 1px rgba(0,0,0,0.14),0px 4px 20px 3px rgba(0,0,0,0.12)",
"0px 7px 8px -4px rgba(0,0,0,0.2),0px 12px 17px 2px rgba(0,0,0,0.14),0px 5px 22px 4px rgba(0,0,0,0.12)",
"0px 7px 8px -4px rgba(0,0,0,0.2),0px 13px 19px 2px rgba(0,0,0,0.14),0px 5px 24px 4px rgba(0,0,0,0.12)",
"0px 7px 9px -4px rgba(0,0,0,0.2),0px 14px 21px 2px rgba(0,0,0,0.14),0px 5px 26px 4px rgba(0,0,0,0.12)",
"0px 8px 9px -5px rgba(0,0,0,0.2),0px 15px 22px 2px rgba(0,0,0,0.14),0px 6px 28px 5px rgba(0,0,0,0.12)",
"0px 8px 10px -5px rgba(0,0,0,0.2),0px 16px 24px 2px rgba(0,0,0,0.14),0px 6px 30px 5px rgba(0,0,0,0.12)",
"0px 8px 11px -5px rgba(0,0,0,0.2),0px 17px 26px 2px rgba(0,0,0,0.14),0px 6px 32px 5px rgba(0,0,0,0.12)",
"0px 9px 11px -5px rgba(0,0,0,0.2),0px 18px 28px 2px rgba(0,0,0,0.14),0px 7px 34px 6px rgba(0,0,0,0.12)",
"0px 9px 12px -6px rgba(0,0,0,0.2),0px 19px 29px 2px rgba(0,0,0,0.14),0px 7px 36px 6px rgba(0,0,0,0.12)",
"0px 10px 13px -6px rgba(0,0,0,0.2),0px 20px 31px 3px rgba(0,0,0,0.14),0px 8px 38px 7px rgba(0,0,0,0.12)",
"0px 10px 13px -6px rgba(0,0,0,0.2),0px 21px 33px 3px rgba(0,0,0,0.14),0px 8px 40px 7px rgba(0,0,0,0.12)",
"0px 10px 14px -6px rgba(0,0,0,0.2),0px 22px 35px 3px rgba(0,0,0,0.14),0px 8px 42px 7px rgba(0,0,0,0.12)",
"0px 11px 14px -7px rgba(0,0,0,0.2),0px 23px 36px 3px rgba(0,0,0,0.14),0px 9px 44px 8px rgba(0,0,0,0.12)",
"0px 11px 15px -7px rgba(0,0,0,0.2),0px 24px 38px 3px rgba(0,0,0,0.14),0px 9px 46px 8px rgba(0,0,0,0.12)",
],
"shape": Object {
"borderRadius": 4,
},
"spacing": Object {
"unit": 8,
},
"transitions": Object {
"create": [Function],
"duration": Object {
"complex": 375,
"enteringScreen": 225,
"leavingScreen": 195,
"short": 250,
"shorter": 200,
"shortest": 150,
"standard": 300,
},
"easing": Object {
"easeIn": "cubic-bezier(0.4, 0, 1, 1)",
"easeInOut": "cubic-bezier(0.4, 0, 0.2, 1)",
"easeOut": "cubic-bezier(0.0, 0, 0.2, 1)",
"sharp": "cubic-bezier(0.4, 0, 0.6, 1)",
},
"getAutoHeightDuration": [Function],
},
"typography": Object {
"body1": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 400,
"lineHeight": "1.46429em",
},
"body1Next": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1rem",
"fontWeight": 400,
"letterSpacing": "0.00938em",
"lineHeight": 1.5,
},
"body2": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 500,
"lineHeight": "1.71429em",
},
"body2Next": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 400,
"letterSpacing": "0.01071em",
"lineHeight": 1.5,
},
"button": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 500,
"textTransform": "uppercase",
},
"buttonNext": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 500,
"letterSpacing": "0.02857em",
"lineHeight": 1.75,
"textTransform": "uppercase",
},
"caption": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.75rem",
"fontWeight": 400,
"lineHeight": "1.375em",
},
"captionNext": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.75rem",
"fontWeight": 400,
"letterSpacing": "0.03333em",
"lineHeight": 1.66,
},
"display1": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "2.125rem",
"fontWeight": 400,
"lineHeight": "1.20588em",
},
"display2": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "2.8125rem",
"fontWeight": 400,
"lineHeight": "1.13333em",
"marginLeft": "-.02em",
},
"display3": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "3.5rem",
"fontWeight": 400,
"letterSpacing": "-.02em",
"lineHeight": "1.30357em",
"marginLeft": "-.02em",
},
"display4": Object {
"color": "rgba(0, 0, 0, 0.54)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "7rem",
"fontWeight": 300,
"letterSpacing": "-.04em",
"lineHeight": "1.14286em",
"marginLeft": "-.04em",
},
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": 14,
"fontWeightLight": 300,
"fontWeightMedium": 500,
"fontWeightRegular": 400,
"h1": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "6rem",
"fontWeight": 300,
"letterSpacing": "-0.01562em",
"lineHeight": 1,
},
"h2": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "3.75rem",
"fontWeight": 300,
"letterSpacing": "-0.00833em",
"lineHeight": 1,
},
"h3": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "3rem",
"fontWeight": 400,
"letterSpacing": "0em",
"lineHeight": 1.04,
},
"h4": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "2.125rem",
"fontWeight": 400,
"letterSpacing": "0.00735em",
"lineHeight": 1.17,
},
"h5": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1.5rem",
"fontWeight": 400,
"letterSpacing": "0em",
"lineHeight": 1.33,
},
"h6": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1.25rem",
"fontWeight": 500,
"letterSpacing": "0.0075em",
"lineHeight": 1.6,
},
"headline": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1.5rem",
"fontWeight": 400,
"lineHeight": "1.35417em",
},
"overline": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.75rem",
"fontWeight": 400,
"letterSpacing": "0.08333em",
"lineHeight": 2.66,
"textTransform": "uppercase",
},
"pxToRem": [Function],
"round": [Function],
"subheading": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1rem",
"fontWeight": 400,
"lineHeight": "1.5em",
},
"subtitle1": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1rem",
"fontWeight": 400,
"letterSpacing": "0.00938em",
"lineHeight": 1.75,
},
"subtitle2": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "0.875rem",
"fontWeight": 500,
"letterSpacing": "0.00714em",
"lineHeight": 1.57,
},
"title": Object {
"color": "rgba(0, 0, 0, 0.87)",
"fontFamily": "\\"Roboto\\", \\"Helvetica\\", \\"Arial\\", sans-serif",
"fontSize": "1.3125rem",
"fontWeight": 500,
"lineHeight": "1.16667em",
},
"useNextVariants": false,
},
"zIndex": Object {
"appBar": 1100,
"drawer": 1200,
"mobileStepper": 1000,
"modal": 1300,
"snackbar": 1400,
"tooltip": 1500,
},
}
}
title=""
>
<RootRef
rootRef={[Function]}
>
<WithStyles(Button)
aria-describedby={null}
className="button"
key="1"
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
title=""
>
<Button
aria-describedby={null}
className="button"
classes={
Object {
"colorInherit": "MuiButton-colorInherit-30",
"contained": "MuiButton-contained-20",
"containedPrimary": "MuiButton-containedPrimary-21",
"containedSecondary": "MuiButton-containedSecondary-22",
"disabled": "MuiButton-disabled-29",
"extendedFab": "MuiButton-extendedFab-27",
"fab": "MuiButton-fab-26",
"flat": "MuiButton-flat-14",
"flatPrimary": "MuiButton-flatPrimary-15",
"flatSecondary": "MuiButton-flatSecondary-16",
"focusVisible": "MuiButton-focusVisible-28",
"fullWidth": "MuiButton-fullWidth-34",
"label": "MuiButton-label-10",
"mini": "MuiButton-mini-31",
"outlined": "MuiButton-outlined-17",
"outlinedPrimary": "MuiButton-outlinedPrimary-18",
"outlinedSecondary": "MuiButton-outlinedSecondary-19",
"raised": "MuiButton-raised-23",
"raisedPrimary": "MuiButton-raisedPrimary-24",
"raisedSecondary": "MuiButton-raisedSecondary-25",
"root": "MuiButton-root-9",
"sizeLarge": "MuiButton-sizeLarge-33",
"sizeSmall": "MuiButton-sizeSmall-32",
"text": "MuiButton-text-11",
"textPrimary": "MuiButton-textPrimary-12",
"textSecondary": "MuiButton-textSecondary-13",
}
}
color="default"
component="button"
disableFocusRipple={false}
disabled={false}
fullWidth={false}
mini={false}
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
size="medium"
title=""
type="button"
variant="text"
>
<WithStyles(ButtonBase)
aria-describedby={null}
className="MuiButton-root-9 MuiButton-text-11 MuiButton-flat-14 button"
component="button"
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-28"
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
title=""
type="button"
>
<ButtonBase
aria-describedby={null}
centerRipple={false}
className="MuiButton-root-9 MuiButton-text-11 MuiButton-flat-14 button"
classes={
Object {
"disabled": "MuiButtonBase-disabled-36",
"focusVisible": "MuiButtonBase-focusVisible-37",
"root": "MuiButtonBase-root-35",
}
}
component="button"
disableRipple={false}
disableTouchRipple={false}
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-28"
onBlur={[Function]}
onClick={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
tabIndex="0"
title=""
type="button"
>
<button
aria-describedby={null}
className="MuiButtonBase-root-35 MuiButton-root-9 MuiButton-text-11 MuiButton-flat-14 button"
disabled={false}
onBlur={[Function]}
onClick={[Function]}
onContextMenu={[Function]}
onFocus={[Function]}
onKeyDown={[Function]}
onKeyUp={[Function]}
onMouseDown={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onMouseUp={[Function]}
onTouchEnd={[Function]}
onTouchMove={[Function]}
onTouchStart={[Function]}
tabIndex="0"
title=""
type="button"
>
<span
className="MuiButton-label-10"
>
<span>
tab2
</span>
</span>
<NoSsr
defer={false}
fallback={null}
>
<WithStyles(TouchRipple)
center={false}
innerRef={[Function]}
>
<TouchRipple
center={false}
classes={
Object {
"child": "MuiTouchRipple-child-42",
"childLeaving": "MuiTouchRipple-childLeaving-43",
"childPulsate": "MuiTouchRipple-childPulsate-44",
"ripple": "MuiTouchRipple-ripple-39",
"ripplePulsate": "MuiTouchRipple-ripplePulsate-41",
"rippleVisible": "MuiTouchRipple-rippleVisible-40",
"root": "MuiTouchRipple-root-38",
}
}
>
<TransitionGroup
childFactory={[Function]}
className="MuiTouchRipple-root-38"
component="span"
enter={true}
exit={true}
>
<span
className="MuiTouchRipple-root-38"
/>
</TransitionGroup>
</TouchRipple>
</WithStyles(TouchRipple)>
</NoSsr>
</button>
</ButtonBase>
</WithStyles(ButtonBase)>
</Button>
</WithStyles(Button)>
</RootRef>
<Popper
className="MuiTooltip-popper-1"
disablePortal={false}
id={null}
open={false}
placement="top-start"
transition={true}
/>
</Tooltip>
</WithStyles(Tooltip)>
</div>
</MD2Tabs>
`;
exports[`Input renders with the right styles by default 1`] = `
<div
className="tabs"
>
<div
className="indicator"
/>
<Separator
units={20}
/>
<WithStyles(Tooltip)
key="0"
placement="top-start"
title=""
>
<WithStyles(Button)
className="button active"
key="0"
onClick={[Function]}
>
<span>
tab1
</span>
</WithStyles(Button)>
</WithStyles(Tooltip)>
<WithStyles(Tooltip)
key="1"
placement="top-start"
title=""
>
<WithStyles(Button)
className="button"
key="1"
onClick={[Function]}
>
<span>
tab2
</span>
</WithStyles(Button)>
</WithStyles(Tooltip)>
</div>
`;
| 201 |
0 | kubeflow_public_repos/pipelines/frontend/src/atoms | kubeflow_public_repos/pipelines/frontend/src/atoms/__snapshots__/IconWithTooltip.test.tsx.snap | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`IconWithTooltip renders with height and weight 1`] = `
<svg
aria-describedby={null}
aria-hidden="true"
className="MuiSvgIcon-root-9"
focusable="false"
onBlur={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
role="presentation"
style={
Object {
"color": "green",
"height": 20,
"width": 20,
}
}
title="test icon tooltip"
viewBox="0 0 24 24"
>
<path
d="M0 0h24v24H0z"
fill="none"
/>
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"
/>
</svg>
`;
exports[`IconWithTooltip renders without height or weight 1`] = `
<svg
aria-describedby={null}
aria-hidden="true"
className="MuiSvgIcon-root-9"
focusable="false"
onBlur={[Function]}
onFocus={[Function]}
onMouseLeave={[Function]}
onMouseOver={[Function]}
onTouchEnd={[Function]}
onTouchStart={[Function]}
role="presentation"
style={
Object {
"color": "green",
"height": 16,
"width": 16,
}
}
title="test icon tooltip"
viewBox="0 0 24 24"
>
<path
d="M0 0h24v24H0z"
fill="none"
/>
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"
/>
</svg>
`;
| 202 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/MlmdUtils.ts | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Struct } from 'google-protobuf/google/protobuf/struct_pb';
import { getResourceStateText, ResourceType } from 'src/components/ResourceInfo';
import { logger } from 'src/lib/Utils';
import { isV2Pipeline } from 'src/lib/v2/WorkflowUtils';
import {
Api,
ArtifactCustomProperties,
ArtifactProperties,
ExecutionCustomProperties,
ExecutionProperties,
getResourceProperty,
getResourcePropertyViaFallBack,
} from 'src/mlmd/library';
import {
Artifact,
ArtifactType,
Context,
ContextType,
Event,
Execution,
GetArtifactsByIDRequest,
GetArtifactsByIDResponse,
GetArtifactTypesRequest,
GetArtifactTypesResponse,
GetContextByTypeAndNameRequest,
GetEventsByExecutionIDsRequest,
GetEventsByExecutionIDsResponse,
GetExecutionsByContextRequest,
} from 'src/third_party/mlmd';
import {
GetArtifactsByContextRequest,
GetContextsByExecutionRequest,
GetContextsByExecutionResponse,
GetContextTypeRequest,
GetContextTypeResponse,
} from 'src/third_party/mlmd/generated/ml_metadata/proto/metadata_store_service_pb';
import { Workflow } from 'src/third_party/mlmd/argo_template';
export const KFP_V2_RUN_CONTEXT_TYPE = 'system.PipelineRun';
export const EXECUTION_KEY_CACHED_EXECUTION_ID = 'cached_execution_id';
async function getContext({ type, name }: { type: string; name: string }): Promise<Context> {
if (type === '') {
throw new Error('Failed to getContext: type is empty.');
}
if (name === '') {
throw new Error('Failed to getContext: name is empty.');
}
const request = new GetContextByTypeAndNameRequest();
request.setTypeName(type);
request.setContextName(name);
try {
const res = await Api.getInstance().metadataStoreService.getContextByTypeAndName(request);
const context = res.getContext();
if (context == null) {
throw new Error('Cannot find specified context');
}
return context;
} catch (err) {
err.message = `Cannot find context with ${JSON.stringify(request.toObject())}: ` + err.message;
throw err;
}
}
/**
* @throws error when network error, or not found
*/
async function getTfxRunContext(argoWorkflowName: string): Promise<Context> {
// Context: https://github.com/kubeflow/pipelines/issues/6138
// Require TFX version to be >= 1.2.0.
return await getContext({ name: argoWorkflowName, type: 'pipeline_run' });
}
/**
* @throws error when network error, or not found
*/
async function getKfpRunContext(argoWorkflowName: string): Promise<Context> {
return await getContext({ name: argoWorkflowName, type: 'KfpRun' });
}
export async function getKfpV2RunContext(runID: string): Promise<Context> {
return await getContext({ name: runID, type: KFP_V2_RUN_CONTEXT_TYPE });
}
export async function getRunContext(workflow: Workflow, runID: string): Promise<Context> {
const workflowName = workflow?.metadata?.name || '';
if (isV2Pipeline(workflow)) {
return await getKfpV2RunContext(runID);
}
try {
return await getTfxRunContext(workflowName);
} catch (err) {
logger.warn(`Cannot find tfx run context (this is expected for non tfx runs)`, err);
return await getKfpRunContext(workflowName);
}
}
/**
* @throws error when network error
*/
export async function getExecutionsFromContext(context: Context): Promise<Execution[]> {
const request = new GetExecutionsByContextRequest();
request.setContextId(context.getId());
try {
const res = await Api.getInstance().metadataStoreService.getExecutionsByContext(request);
const list = res.getExecutionsList();
if (list == null) {
throw new Error('response.getExecutionsList() is empty');
}
return list;
} catch (err) {
err.message =
`Cannot find executions by context ${context.getId()} with name ${context.getName()}: ` +
err.message;
throw err;
}
}
export enum KfpExecutionProperties {
// kfp_pod_name is kept for backward compatibility.
// KFP v1 and TFX logs kfp_pod_name property, but KFP v2 logs pod_name.
KFP_POD_NAME = 'kfp_pod_name',
POD_NAME = 'pod_name',
DISPLAY_NAME = 'display_name',
TASK_NAME = 'task_name',
}
const EXECUTION_PROPERTY_REPOS = [ExecutionProperties, ExecutionCustomProperties];
export const ExecutionHelpers = {
getWorkspace(execution: Execution): string | number | undefined {
return (
getResourcePropertyViaFallBack(execution, EXECUTION_PROPERTY_REPOS, ['RUN_ID']) ||
getStringProperty(execution, ExecutionCustomProperties.WORKSPACE, true) ||
getStringProperty(execution, ExecutionProperties.PIPELINE_NAME) ||
undefined
);
},
getName(execution: Execution): string {
return `${getStringProperty(execution, KfpExecutionProperties.DISPLAY_NAME, true) ||
getStringProperty(execution, KfpExecutionProperties.TASK_NAME, true) ||
getStringProperty(execution, ExecutionProperties.NAME) ||
getStringProperty(execution, ExecutionProperties.COMPONENT_ID) ||
getStringProperty(execution, ExecutionCustomProperties.TASK_ID, true) ||
// TFX 1.2.0 executions do not have any of the above, adding pod name as a fallback name
getStringProperty(execution, KfpExecutionProperties.KFP_POD_NAME, true) ||
'(No name)'}`;
},
getState(execution: Execution): string | number | undefined {
return getResourceStateText({
resourceType: ResourceType.EXECUTION,
resource: execution,
typeName: 'Execution',
});
},
getKfpPod(execution: Execution): string | undefined {
return (
getStringProperty(execution, KfpExecutionProperties.POD_NAME, true) ||
getStringProperty(execution, KfpExecutionProperties.KFP_POD_NAME) ||
getStringProperty(execution, KfpExecutionProperties.KFP_POD_NAME, true) ||
undefined
);
},
};
export enum KfpArtifactProperties {
DISPLAY_NAME = 'display_name',
}
export const ArtifactHelpers = {
getName(a: Artifact): string {
const name =
getResourceProperty(a, KfpArtifactProperties.DISPLAY_NAME, true) ||
getResourceProperty(a, ArtifactProperties.NAME) ||
getResourceProperty(a, ArtifactCustomProperties.NAME, true) ||
'(No name)';
return `${name}`;
},
};
function getStringProperty(
resource: Artifact | Execution,
propertyName: string,
fromCustomProperties = false,
): string | undefined {
const value = getResourceProperty(resource, propertyName, fromCustomProperties);
return getStringValue(value);
}
function getStringValue(value?: string | number | Struct | null): string | undefined {
if (typeof value != 'string') {
return undefined;
}
return value;
}
export async function getEventByExecution(execution: Execution): Promise<Event[]> {
const executionId = execution.getId();
if (!executionId) {
throw new Error('Execution must have an ID');
}
const request = new GetEventsByExecutionIDsRequest().addExecutionIds(executionId);
let response: GetEventsByExecutionIDsResponse;
try {
response = await Api.getInstance().metadataStoreService.getEventsByExecutionIDs(request);
} catch (err) {
err.message = 'Failed to getEventsByExecutionIDs: ' + err.message;
throw err;
}
return response.getEventsList();
}
export async function getContextByExecution(
execution: Execution,
contextTypeName: string,
): Promise<Context | undefined> {
const contexts = await getContextsByExecution(execution);
const contextType = await getContextType(contextTypeName);
const result = contexts.filter(c => contextType && c.getTypeId() === contextType.getId());
if (result.length === 0) {
console.warn('No context is found for type name: ' + contextTypeName);
return;
}
if (result.length > 1) {
console.warn('Found more than one context for type name: ' + contextTypeName);
console.warn('Contexts: ');
contexts.forEach(c => console.warn(c));
return;
}
return result[0];
}
async function getContextsByExecution(execution: Execution): Promise<Context[]> {
const executionId = execution.getId();
if (!executionId) {
throw new Error('Execution must have an ID');
}
const request = new GetContextsByExecutionRequest().setExecutionId(executionId);
let response: GetContextsByExecutionResponse;
try {
response = await Api.getInstance().metadataStoreService.getContextsByExecution(request);
} catch (err) {
err.message = 'Failed to getContextsByExecution: ' + err.message;
throw err;
}
return response.getContextsList();
}
async function getContextType(contextTypeName: string): Promise<ContextType | undefined> {
const request = new GetContextTypeRequest();
if (contextTypeName) {
request.setTypeName(contextTypeName);
}
let response: GetContextTypeResponse;
try {
response = await Api.getInstance().metadataStoreService.getContextType(request);
} catch (err) {
err.message = 'Failed to getContextType: ' + err.message;
throw err;
}
return response.getContextType();
}
// An artifact which has associated event.
// You can retrieve artifact name from event.path.steps[0].key
export interface LinkedArtifact {
event: Event;
artifact: Artifact;
}
export function getStoreSessionInfoFromArtifact(artifact: LinkedArtifact): string | undefined {
return artifact.artifact
.getCustomPropertiesMap()
.get('store_session_info')
?.getStringValue();
}
export async function getLinkedArtifactsByEvents(events: Event[]): Promise<LinkedArtifact[]> {
const artifactIds = events
.filter(event => event.getArtifactId())
.map(event => event.getArtifactId());
const artifactsRequest = new GetArtifactsByIDRequest().setArtifactIdsList(artifactIds);
let artifactsRes: GetArtifactsByIDResponse;
try {
artifactsRes = await Api.getInstance().metadataStoreService.getArtifactsByID(artifactsRequest);
} catch (artifactsErr) {
artifactsErr.message = 'Failed to getArtifactsByID: ' + artifactsErr.message;
throw artifactsErr;
}
const artifactMap = new Map();
for (const [, artifactEntry] of Object.entries(artifactsRes.getArtifactsList())) {
artifactMap.set(artifactEntry.getId(), artifactEntry);
}
return events.map(event => {
const artifact = artifactMap.get(event.getArtifactId());
return { event: event, artifact: artifact };
});
}
export async function getLinkedArtifactsByExecution(
execution: Execution,
): Promise<LinkedArtifact[]> {
const event = await getEventByExecution(execution);
return getLinkedArtifactsByEvents(event);
}
export function filterEventWithInputArtifact(linkedArtifact: LinkedArtifact[]) {
return linkedArtifact.filter(obj => obj.event.getType() === Event.Type.INPUT);
}
export function filterEventWithOutputArtifact(linkedArtifact: LinkedArtifact[]) {
return linkedArtifact.filter(obj => obj.event.getType() === Event.Type.OUTPUT);
}
/**
* @throws error when network error or invalid data
*/
export async function getOutputArtifactsInExecution(execution: Execution): Promise<Artifact[]> {
const linkedArtifacts = await getLinkedArtifactsByExecution(execution);
return filterEventWithOutputArtifact(linkedArtifacts).map(
linkedArtifact => linkedArtifact.artifact,
);
}
export async function getOutputLinkedArtifactsInExecution(
execution: Execution,
): Promise<LinkedArtifact[]> {
const linkedArtifacts = await getLinkedArtifactsByExecution(execution);
return filterEventWithOutputArtifact(linkedArtifacts);
}
export async function getArtifactTypes(): Promise<ArtifactType[]> {
const request = new GetArtifactTypesRequest();
let res: GetArtifactTypesResponse;
try {
res = await Api.getInstance().metadataStoreService.getArtifactTypes(request);
} catch (err) {
err.message = 'Failed to getArtifactTypes: ' + err.message;
throw err;
}
return res.getArtifactTypesList();
}
export function filterArtifactsByType(
artifactTypeName: string,
artifactTypes: ArtifactType[],
artifacts: Artifact[],
): Artifact[] {
const artifactTypeIds = artifactTypes
.filter(artifactType => artifactType.getName() === artifactTypeName)
.map(artifactType => artifactType.getId());
return artifacts.filter(artifact => artifactTypeIds.includes(artifact.getTypeId()));
}
export function filterLinkedArtifactsByType(
artifactTypeName: string,
artifactTypes: ArtifactType[],
artifacts: LinkedArtifact[],
): LinkedArtifact[] {
const artifactTypeIds = artifactTypes
.filter(artifactType => artifactType.getName() === artifactTypeName)
.map(artifactType => artifactType.getId());
return artifacts.filter(x => artifactTypeIds.includes(x.artifact.getTypeId()));
}
export function getExecutionDisplayName(execution: Execution): string | undefined {
return execution
.getCustomPropertiesMap()
.get('display_name')
?.getStringValue();
}
export function getArtifactName(linkedArtifact: LinkedArtifact): string | undefined {
return getArtifactNameFromEvent(linkedArtifact.event);
}
export function getArtifactTypeName(
artifactTypes: ArtifactType[],
linkedArtifacts: LinkedArtifact[],
): string[] {
let artifactTypeNames: string[] = [];
if (artifactTypes && linkedArtifacts) {
Object.values(linkedArtifacts).forEach(linkedArtifact => {
const artifactType = artifactTypes.filter(
aType => aType.getId() === linkedArtifact.artifact.getTypeId(),
);
artifactTypeNames.push(
artifactType.length === 1 && artifactType[0].getName() ? artifactType[0].getName() : '-',
);
});
}
return artifactTypeNames;
}
export function getArtifactNameFromEvent(event: Event): string | undefined {
return event
.getPath()
?.getStepsList()[0]
.getKey();
}
export async function getArtifactsFromContext(context: Context): Promise<Artifact[]> {
const request = new GetArtifactsByContextRequest();
request.setContextId(context.getId());
try {
const res = await Api.getInstance().metadataStoreService.getArtifactsByContext(request);
const list = res.getArtifactsList();
if (list == null) {
throw new Error('response.getExecutionsList() is empty');
}
// Display name of artifact exists in getCustomPropertiesMap().get('display_name').getStringValue().
// Note that the actual artifact name is in Event which generates this artifact.
return list;
} catch (err) {
err.message =
`Cannot find executions by context ${context.getId()} with name ${context.getName()}: ` +
err.message;
throw err;
}
}
export async function getEventsByExecutions(executions: Execution[] | undefined): Promise<Event[]> {
if (!executions) {
return [];
}
const request = new GetEventsByExecutionIDsRequest();
for (let exec of executions) {
const execId = exec.getId();
if (!execId) {
throw new Error('Execution must have an ID');
}
request.addExecutionIds(execId);
}
let response: GetEventsByExecutionIDsResponse;
try {
response = await Api.getInstance().metadataStoreService.getEventsByExecutionIDs(request);
} catch (err) {
err.message = 'Failed to getEventsByExecutionIDs: ' + err.message;
throw err;
}
return response.getEventsList();
}
| 203 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageCardRow.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { Link } from 'react-router-dom';
import { classes, cssRaw } from 'typestyle';
import { LineageTypedResource } from './LineageTypes';
import { getResourceDescription, getResourceName } from './Utils';
import { Artifact } from 'src/third_party/mlmd';
cssRaw(`
.cardRow {
align-items: center;
border-bottom: 1px solid var(--grey-200);
display: flex;
height: 54px;
padding: 6px 0px;
position: relative;
}
.cardRow .noRadio {
height: 16px;
width: 16px;
}
.cardRow.clickTarget {
cursor: pointer;
}
.cardRow .form-radio-container {
position: relative;
}
.cardRow .form-radio {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
display: inline-block;
position: relative;
background-color: #fff;
border: 1px solid var(--grey-400);
color: var(--blue-500);
top: 0px;
height: 18px;
width: 18px;
border-radius: 50px;
cursor: pointer;
outline: none;
}
.cardRow .form-radio:checked {
border: 2px solid var(--blue-500);
}
.cardRow .form-radio:checked::before {
position: absolute;
border-radius: 50%;
top: 50%;
left: 50%;
content: '';
transform: translate(-50%, -50%);
padding: 5px;
display: block;
background: currentColor;
}
.cardRow .form-radio:hover {
background-color: var(--grey-100);
}
.cardRow .form-radio:checked {
background-color: #fff;
}
.cardRow .form-radio.hover-hint {
color: var(--grey-400);
left: 0;
opacity: 0;
position: absolute;
}
.cardRow.clickTarget:hover .form-radio.hover-hint {
opacity: 1;
}
.cardRow.clickTarget .form-radio.hover-hint:checked::before {
background: currentColor;
}
.cardRow.clickTarget .form-radio.hover-hint:checked {
border: 2px solid var(--grey-400);
}
.cardRow div {
display: inline-block;
vertical-align: middle;
}
.cardRow div input {
margin: 10px 10px 0 20px;
}
.cardRow .rowTitle {
font-size: 12px;
font-family: "PublicSans-SemiBold";
color: var(--grey-900);
letter-spacing: 0.2px;
line-height: 24px;
text-decoration: none;
text-overflow: ellipsis;
display: inline-block;
white-space: nowrap;
overflow: hidden;
}
.cardRow .rowTitle:hover {
text-decoration: underline;
color: var(--blue-600);
cursor: pointer;
}
.cardRow .rowDesc {
font-size: 11px;
color: var(--grey-600);
letter-spacing: 0.3px;
line-height: 12px;
}
.cardRow footer {
overflow: hidden;
}
.cardRow [class^='edge'] {
width: 8px;
height: 8px;
background-color: var(--grey-700);
border-radius: 2px;
position: absolute;
top: 50%;
transform: translateY(-50%) translateX(-50%);
}
.cardRow .edgeRight {
left: 100%;
}
.cardRow .edgeLeft {
left: 0;
}
.cardRow.lastRow {
border-bottom: 0px;
}
`);
const CLICK_TARGET_CSS_NAME = 'clickTarget';
interface LineageCardRowProps {
leftAffordance: boolean;
rightAffordance: boolean;
hideRadio: boolean;
isLastRow: boolean;
isTarget?: boolean;
typedResource: LineageTypedResource;
resourceDetailsRoute: string;
setLineageViewTarget?(artifact: Artifact): void;
}
export class LineageCardRow extends React.Component<LineageCardRowProps> {
private rowContainerRef: React.RefObject<HTMLDivElement> = React.createRef();
constructor(props: LineageCardRowProps) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
public checkEdgeAffordances(): JSX.Element[] {
const affItems = [];
this.props.leftAffordance && affItems.push(<div className='edgeLeft' key={'edgeLeft'} />);
this.props.rightAffordance && affItems.push(<div className='edgeRight' key={'edgeRight'} />);
return affItems;
}
public render(): JSX.Element {
const { isLastRow } = this.props;
const cardRowClasses = classes(
'cardRow',
isLastRow && 'lastRow',
this.canTarget() && 'clickTarget',
);
return (
<div className={cardRowClasses} ref={this.rowContainerRef} onClick={this.handleClick}>
{this.checkRadio()}
<footer>
<Link
className={'rowTitle'}
to={this.props.resourceDetailsRoute}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
>
{getResourceName(this.props.typedResource)}
</Link>
<p className='rowDesc'>{getResourceDescription(this.props.typedResource)}</p>
</footer>
{this.checkEdgeAffordances()}
</div>
);
}
private checkRadio(): JSX.Element {
if (this.props.hideRadio) {
return <div className='noRadio' />;
}
return (
<div className={'form-radio-container'}>
<input
type='radio'
className='form-radio'
name=''
value=''
onClick={this.handleClick}
checked={this.props.isTarget}
readOnly={true}
/>
<input
type='radio'
className='form-radio hover-hint'
name=''
value=''
onClick={this.handleClick}
checked={true}
readOnly={true}
/>
</div>
);
}
private handleClick() {
if (!this.props.setLineageViewTarget || !(this.props.typedResource.type === 'artifact')) return;
this.props.setLineageViewTarget(this.props.typedResource.resource as Artifact);
}
private handleMouseEnter = (e: React.MouseEvent<HTMLAnchorElement>) => {
if (!e || !e.target || !this.canTarget()) return;
const element = e.target as HTMLAnchorElement;
if (element.className.match(/\browTitle\b/)) {
this.showRadioHint(false);
}
};
private handleMouseLeave = (e: React.MouseEvent<HTMLAnchorElement>) => {
if (!e || !e.target || !this.canTarget()) return;
const element = e.target as HTMLAnchorElement;
if (element.className.match(/\browTitle\b/)) {
this.showRadioHint(true);
}
};
private showRadioHint = (show: boolean) => {
if (this.props.isTarget || !this.rowContainerRef.current) return;
const rowContainer = this.rowContainerRef.current;
if (show) {
if (!rowContainer.classList.contains(CLICK_TARGET_CSS_NAME)) {
rowContainer.classList.add(CLICK_TARGET_CSS_NAME);
}
} else {
if (rowContainer.classList.contains(CLICK_TARGET_CSS_NAME)) {
rowContainer.classList.remove(CLICK_TARGET_CSS_NAME);
}
}
};
private canTarget = () => {
const { isTarget, typedResource } = this.props;
return !isTarget && typedResource.type === 'artifact';
};
}
| 204 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/Utils.tsx | /*
* Copyright 2019,2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
ArtifactCustomProperties,
ArtifactProperties,
ExecutionCustomProperties,
ExecutionProperties,
} from './Api';
import { ArtifactTypeMap, ExecutionTypeMap } from './LineageApi';
import { Artifact, Execution, Value } from 'src/third_party/mlmd';
import { LineageTypedResource } from './LineageTypes';
import { Struct } from 'google-protobuf/google/protobuf/struct_pb';
import { ArtifactHelpers, ExecutionHelpers } from './MlmdUtils';
const ARTIFACT_FIELD_REPOS = [ArtifactProperties, ArtifactCustomProperties];
const EXECUTION_FIELD_REPOS = [ExecutionProperties, ExecutionCustomProperties];
type RepoType =
| typeof ArtifactCustomProperties
| typeof ArtifactProperties
| typeof ExecutionCustomProperties
| typeof ExecutionProperties;
export function getResourceProperty(
resource: Artifact | Execution,
propertyName: string,
fromCustomProperties = false,
): string | number | Struct | null {
const props = fromCustomProperties
? resource.getCustomPropertiesMap()
: resource.getPropertiesMap();
return (props && props.get(propertyName) && getMetadataValue(props.get(propertyName))) || null;
}
export function getResourcePropertyViaFallBack(
res: Artifact | Execution,
fieldRepos: RepoType[],
fields: string[],
): string {
const prop =
fields.reduce(
(value: string, field: string) =>
value ||
fieldRepos.reduce(
(v: string, repo: RepoType, isCustomProp) =>
v || // eslint-disable-next-line no-sequences
((field in repo && getResourceProperty(res, repo[field], !!isCustomProp)) as string),
'',
),
'',
) || '';
return prop as string;
}
export function getResourceName(typedResource: LineageTypedResource): string {
return typedResource.type === 'artifact'
? ArtifactHelpers.getName(typedResource.resource)
: ExecutionHelpers.getName(typedResource.resource);
}
/**
* Promisified sleep operation
* @param t Time to sleep for in ms
*/
export const sleep = (t: number): Promise<void> => new Promise(res => setTimeout(res, t));
export function getResourceDescription(typedResource: LineageTypedResource): string {
return getResourcePropertyViaFallBack(
typedResource.resource,
typedResource.type === 'artifact' ? ARTIFACT_FIELD_REPOS : EXECUTION_FIELD_REPOS,
['RUN_ID', 'RUN', 'PIPELINE_NAME', 'WORKSPACE'],
);
}
export function getTypeName(typeId: number, artifactTypes: ArtifactTypeMap): string {
return artifactTypes && artifactTypes.get(typeId!)
? artifactTypes.get(typeId!)!.getName()
: String(typeId);
}
export function getExecutionTypeName(typeId: number, executionTypes: ExecutionTypeMap): string {
return executionTypes && executionTypes.get(typeId!)
? executionTypes.get(typeId!)!.getName()
: String(typeId);
}
export function getMetadataValue(value?: Value): string | number | Struct | undefined {
if (!value) {
return '';
}
switch (value.getValueCase()) {
case Value.ValueCase.DOUBLE_VALUE:
return value.getDoubleValue();
case Value.ValueCase.INT_VALUE:
return value.getIntValue();
case Value.ValueCase.STRING_VALUE:
return value.getStringValue();
case Value.ValueCase.STRUCT_VALUE:
return value.getStructValue();
case Value.ValueCase.VALUE_NOT_SET:
return '';
}
return '';
}
| 205 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/EdgeLine.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
// @ts-ignore
import LineChart from 'react-svg-line-chart';
// How many pixels away from the point the curve should start at.
const HORIZONTAL_CONTROL_POINT_OFFSET = 30;
interface EdgeLineProps {
height: number;
width: number;
y1: number;
y4: number;
}
export const EdgeLine: React.FC<EdgeLineProps> = props => {
const { height, width, y1, y4 } = props;
return (
<LineChart
data={[
{ x: 0, y: y1 },
{ x: HORIZONTAL_CONTROL_POINT_OFFSET, y: y1 },
{ x: width - HORIZONTAL_CONTROL_POINT_OFFSET, y: y4 },
{ x: width, y: y4 },
]}
areaVisible={false}
axisVisible={false}
gridVisible={false}
labelsVisible={false}
pathColor={'#BDC1C6'}
pathVisible={true}
pathWidth={1}
pathOpacity={1}
pointsVisible={false}
viewBoxHeight={height}
viewBoxWidth={width}
pathSmoothing={0}
/>
);
};
| 206 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineChart.d.ts | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
declare module 'react-svg-line-chart';
| 207 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/MlmdUtils.test.ts | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Api } from 'src/mlmd/library';
import {
EXECUTION_KEY_CACHED_EXECUTION_ID,
filterLinkedArtifactsByType,
getArtifactName,
getArtifactTypeName,
getArtifactNameFromEvent,
getContextByExecution,
getRunContext,
getArtifactsFromContext,
getEventsByExecutions,
} from 'src/mlmd/MlmdUtils';
import { expectWarnings, testBestPractices } from 'src/TestUtils';
import {
Artifact,
ArtifactType,
Context,
ContextType,
Event,
Execution,
GetContextByTypeAndNameRequest,
GetContextByTypeAndNameResponse,
} from 'src/third_party/mlmd';
import {
GetArtifactsByContextRequest,
GetArtifactsByContextResponse,
GetContextsByExecutionRequest,
GetContextsByExecutionResponse,
GetContextTypeRequest,
GetContextTypeResponse,
GetEventsByExecutionIDsRequest,
GetEventsByExecutionIDsResponse,
} from 'src/third_party/mlmd/generated/ml_metadata/proto/metadata_store_service_pb';
import { Workflow, WorkflowSpec, WorkflowStatus } from 'third_party/argo-ui/argo_template';
testBestPractices();
const WORKFLOW_NAME = 'run-st448';
const RUN_ID = 'abcdefghijk';
const WORKFLOW_EMPTY: Workflow = {
metadata: {
name: WORKFLOW_NAME,
},
// there are many unrelated fields here, omit them
spec: {} as WorkflowSpec,
status: {} as WorkflowStatus,
};
const V2_CONTEXT = new Context();
V2_CONTEXT.setName(RUN_ID);
V2_CONTEXT.setType('system.PipelineRun');
const TFX_CONTEXT = new Context();
TFX_CONTEXT.setName('run-st448');
TFX_CONTEXT.setType('pipeline_run');
const V1_CONTEXT = new Context();
V1_CONTEXT.setName(WORKFLOW_NAME);
V1_CONTEXT.setType('KfpRun');
describe('MlmdUtils', () => {
describe('getContextByExecution', () => {
it('Found matching context', async () => {
const context1 = new Context().setId(1).setTypeId(10);
const context2 = new Context().setId(2).setTypeId(20);
const contextType = new ContextType().setName('type').setId(20);
mockGetContextType(contextType);
mockGetContextsByExecution([context1, context2]);
const execution = new Execution().setId(3);
const context = await getContextByExecution(execution, 'type');
expect(context).toEqual(context2);
});
it('No matching context', async () => {
const context1 = new Context().setId(1).setTypeId(10);
const context2 = new Context().setId(2).setTypeId(20);
const contextType = new ContextType().setName('type').setId(30);
mockGetContextType(contextType);
mockGetContextsByExecution([context1, context2]);
const execution = new Execution().setId(3);
const context = await getContextByExecution(execution, 'type');
expect(context).toBeUndefined();
});
it('More than 1 matching context', async () => {
const context1 = new Context().setId(1).setTypeId(20);
const context2 = new Context().setId(2).setTypeId(20);
const contextType = new ContextType().setName('type').setId(20);
mockGetContextType(contextType);
mockGetContextsByExecution([context1, context2]);
const execution = new Execution().setId(3);
const context = await getContextByExecution(execution, 'type');
// Although more than 1 matching context, this case is unexpected and result is omitted.
expect(context).toBeUndefined();
});
});
describe('getRunContext', () => {
it('gets KFP v2 context', async () => {
mockGetContextByTypeAndName([V2_CONTEXT]);
const context = await getRunContext(
{
...WORKFLOW_EMPTY,
metadata: {
...WORKFLOW_EMPTY.metadata,
annotations: { 'pipelines.kubeflow.org/v2_pipeline': 'true' },
},
},
RUN_ID,
);
expect(context).toEqual(V2_CONTEXT);
});
it('gets TFX context', async () => {
mockGetContextByTypeAndName([TFX_CONTEXT, V1_CONTEXT]);
const context = await getRunContext(WORKFLOW_EMPTY, RUN_ID);
expect(context).toEqual(TFX_CONTEXT);
});
it('gets KFP v1 context', async () => {
const verify = expectWarnings();
mockGetContextByTypeAndName([V1_CONTEXT]);
const context = await getRunContext(WORKFLOW_EMPTY, RUN_ID);
expect(context).toEqual(V1_CONTEXT);
verify();
});
it('throws error when not found', async () => {
const verify = expectWarnings();
mockGetContextByTypeAndName([]);
await expect(getRunContext(WORKFLOW_EMPTY, RUN_ID)).rejects.toThrow();
verify();
});
});
describe('getArtifactName', () => {
it('get the first key of steps list', () => {
const path = new Event.Path();
path.getStepsList().push(new Event.Path.Step().setKey('key1'));
path.getStepsList().push(new Event.Path.Step().setKey('key2'));
const event = new Event();
event.setPath(path);
const linkedArtifact = { event: event, artifact: new Artifact() };
expect(getArtifactName(linkedArtifact)).toEqual('key1');
});
});
describe('getArtifactTypeName', () => {
it('return artifactTypeName[]', () => {
const artifactTypes = [
new ArtifactType().setId(1).setName('metrics'),
new ArtifactType().setId(2).setName('markdown'),
];
const artifact1 = new Artifact();
artifact1.setTypeId(1);
const artifact2 = new Artifact();
artifact2.setTypeId(2);
const linkedArtifacts = [
{ event: new Event(), artifact: artifact1 },
{ event: new Event(), artifact: artifact2 },
];
expect(getArtifactTypeName(artifactTypes, linkedArtifacts)).toEqual(['metrics', 'markdown']);
});
});
describe('getArtifactNameFromEvent', () => {
it('get the first key of steps list', () => {
const path = new Event.Path();
path.getStepsList().push(new Event.Path.Step().setKey('key1'));
path.getStepsList().push(new Event.Path.Step().setKey('key2'));
const event = new Event();
event.setPath(path);
expect(getArtifactNameFromEvent(event)).toEqual('key1');
});
});
describe('getActifactsFromContext', () => {
it('returns list of artifacts', async () => {
const context = new Context();
context.setId(2);
const artifacts = [new Artifact().setId(10), new Artifact().setId(20)];
mockGetArtifactsByContext(context, artifacts);
const artifactResult = await getArtifactsFromContext(context);
expect(artifactResult).toEqual(artifacts);
});
});
describe('getEventsByExecutions', () => {
it('returns list of events', async () => {
const executions = [new Execution().setId(1), new Execution().setId(2)];
const events = [new Event().setExecutionId(1), new Event().setExecutionId(2)];
mockGetEventsByExecutions(executions, events);
const eventsResult = await getEventsByExecutions(executions);
expect(eventsResult).toEqual(events);
});
});
describe('filterLinkedArtifactsByType', () => {
it('filter input artifacts', () => {
const artifactTypeName = 'INPUT';
const artifactTypes = [
new ArtifactType().setId(1).setName('INPUT'),
new ArtifactType().setId(2).setName('OUTPUT'),
];
const inputArtifact = { artifact: new Artifact().setTypeId(1), event: new Event() };
const outputArtifact = { artifact: new Artifact().setTypeId(2), event: new Event() };
const artifacts = [inputArtifact, outputArtifact];
expect(filterLinkedArtifactsByType(artifactTypeName, artifactTypes, artifacts)).toEqual([
inputArtifact,
]);
});
it('filter output artifacts', () => {
const artifactTypeName = 'OUTPUT';
const artifactTypes = [
new ArtifactType().setId(1).setName('INPUT'),
new ArtifactType().setId(2).setName('OUTPUT'),
];
const inputArtifact = { artifact: new Artifact().setTypeId(1), event: new Event() };
const outputArtifact = { artifact: new Artifact().setTypeId(2), event: new Event() };
const artifacts = [inputArtifact, outputArtifact];
expect(filterLinkedArtifactsByType(artifactTypeName, artifactTypes, artifacts)).toEqual([
outputArtifact,
]);
});
});
});
function mockGetContextType(contextType: ContextType) {
jest
.spyOn(Api.getInstance().metadataStoreService, 'getContextType')
.mockImplementation((req: GetContextTypeRequest) => {
const response = new GetContextTypeResponse();
response.setContextType(contextType);
return response;
});
}
function mockGetContextsByExecution(contexts: Context[]) {
jest
.spyOn(Api.getInstance().metadataStoreService, 'getContextsByExecution')
.mockImplementation((req: GetContextsByExecutionRequest) => {
const response = new GetContextsByExecutionResponse();
response.setContextsList(contexts);
return response;
});
}
function mockGetContextByTypeAndName(contexts: Context[]) {
const getContextByTypeAndNameSpy = jest.spyOn(
Api.getInstance().metadataStoreService,
'getContextByTypeAndName',
);
getContextByTypeAndNameSpy.mockImplementation((req: GetContextByTypeAndNameRequest) => {
const response = new GetContextByTypeAndNameResponse();
const found = contexts.find(
context =>
context.getType() === req.getTypeName() && context.getName() === req.getContextName(),
);
response.setContext(found);
return response;
});
}
function mockGetArtifactsByContext(context: Context, artifacts: Artifact[]) {
jest
.spyOn(Api.getInstance().metadataStoreService, 'getArtifactsByContext')
.mockImplementation((req: GetArtifactsByContextRequest) => {
const response = new GetArtifactsByContextResponse();
if (req.getContextId() === context.getId()) {
response.setArtifactsList(artifacts);
}
return response;
});
}
function mockGetEventsByExecutions(executions: Execution[], events: Event[]) {
jest
.spyOn(Api.getInstance().metadataStoreService, 'getEventsByExecutionIDs')
.mockImplementation((req: GetEventsByExecutionIDsRequest) => {
const response = new GetEventsByExecutionIDsResponse();
const executionIds = executions.map(e => e.getId());
if (req.getExecutionIdsList().every((val, index) => val === executionIds[index])) {
response.setEventsList(events);
}
return response;
});
}
| 208 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/Css.test.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { spacing, _paddingInternal } from './Css';
import * as Css from './Css';
describe('Css', () => {
describe('padding', () => {
it('returns padding units in all directions by default', () => {
expect(_paddingInternal()).toEqual({
paddingBottom: spacing.base,
paddingLeft: spacing.base,
paddingRight: spacing.base,
paddingTop: spacing.base,
});
});
it('returns specified padding units in all directions', () => {
expect(_paddingInternal(100)).toEqual({
paddingBottom: 100,
paddingLeft: 100,
paddingRight: 100,
paddingTop: 100,
});
});
it('returns default units in specified directions', () => {
expect(_paddingInternal(undefined, 'lr')).toEqual({
paddingLeft: spacing.base,
paddingRight: spacing.base,
});
});
it('calls internal padding with the same arguments', () => {
const spy = jest.spyOn(Css, 'padding');
Css.padding(123, 'abcdefg');
expect(spy).toHaveBeenCalledWith(123, 'abcdefg');
});
});
});
| 209 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageActionBar.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import grey from '@material-ui/core/colors/grey';
import Button from '@material-ui/core/Button';
import ArrowRightAltIcon from '@material-ui/icons/ArrowRightAlt';
import ReplayIcon from '@material-ui/icons/Replay';
import { classes, stylesheet } from 'typestyle';
import { color, commonCss, fonts, padding } from './Css';
import { CSSProperties } from 'typestyle/lib/types';
import { getResourcePropertyViaFallBack } from './Utils';
import { Artifact } from 'src/third_party/mlmd';
import { ArtifactProperties, ArtifactCustomProperties } from './Api';
import { ArtifactHelpers } from './MlmdUtils';
const baseLinkButton: CSSProperties = {
backgroundColor: 'transparent',
border: 'none',
cursor: 'pointer',
display: 'inline',
margin: 0,
padding: 0,
};
const baseBreadcrumb = {
...baseLinkButton,
fontFamily: fonts.secondary,
fontWeight: 500,
};
const actionBarCss = stylesheet({
actionButton: {
color: color.strong,
},
workspace: {
...baseBreadcrumb,
fontStyle: 'italic',
},
workspaceSep: {
display: 'block',
color: '#3c3c3c',
$nest: {
'&::before': {
content: '""',
color: '#9f9f9f',
margin: '0 .75em',
border: '1px solid',
background: 'currentColor',
},
},
},
breadcrumbContainer: {
alignItems: 'center',
display: 'flex',
flexShrink: 1,
overflow: 'hidden',
},
breadcrumbInactive: {
color: color.grey,
...baseBreadcrumb,
$nest: {
'&:hover': {
textDecoration: 'underline',
},
},
},
breadcrumbActive: {
color: color.strong,
...baseBreadcrumb,
$nest: {
'&:hover': {
cursor: 'default',
},
},
},
breadcrumbSeparator: {
color: grey[400],
},
container: {
borderBottom: '1px solid ' + color.separator,
height: '48px',
justifyContent: 'space-between',
},
});
export interface LineageActionBarProps {
initialTarget?: Artifact;
setLineageViewTarget(artifact: Artifact): void;
}
export interface LineageActionBarState {
history: Artifact[];
}
const BreadcrumbSeparator: React.FC = () => (
<div className={classes(commonCss.flex)}>
<ArrowRightAltIcon className={classes(actionBarCss.breadcrumbSeparator, padding(10, 'lr'))} />
</div>
);
/** Shows the current navigation history and actions available to the Lineage Explorer. */
export class LineageActionBar extends React.Component<
LineageActionBarProps,
LineageActionBarState
> {
constructor(props: LineageActionBarProps) {
super(props);
this.reset = this.reset.bind(this);
this.pushHistory = this.pushHistory.bind(this);
this.state = {
history: [],
};
if (this.props.initialTarget) {
this.state.history.push(this.props.initialTarget);
}
}
public pushHistory(artifact: Artifact) {
this.setState({
history: [...this.state.history, artifact],
});
}
public render() {
const breadcrumbs: JSX.Element[] = [
<span className={classes(actionBarCss.workspace)} key='workspace'>
{getResourcePropertyViaFallBack(
this.state.history[0],
[ArtifactProperties, ArtifactCustomProperties],
['PIPELINE_NAME', 'WORKSPACE'],
)}
</span>,
<aside key='workspace-sep' className={actionBarCss.workspaceSep} />,
];
this.state.history.forEach((artifact: Artifact, index) => {
const isActive = index === this.state.history.length - 1;
const onBreadcrumbClicked = () => {
this.sliceHistory(index);
};
breadcrumbs.push(
<button
key={`breadcrumb-${index}`}
className={classes(
isActive ? actionBarCss.breadcrumbActive : actionBarCss.breadcrumbInactive,
)}
disabled={isActive}
onClick={onBreadcrumbClicked}
>
{ArtifactHelpers.getName(artifact)}
</button>,
);
if (!isActive) {
breadcrumbs.push(<BreadcrumbSeparator key={`separator-${index}`} />);
}
});
return (
<div className={classes(actionBarCss.container, padding(25, 'lr'), commonCss.flex)}>
<div className={classes(actionBarCss.breadcrumbContainer)}>{breadcrumbs}</div>
<div>
<Button
className={classes(actionBarCss.actionButton)}
disabled={false}
onClick={this.reset}
>
<ReplayIcon /> Reset
</Button>
</div>
</div>
);
}
private sliceHistory(index: number): void {
const history = this.state.history.slice(0, index + 1);
const targetArtifact = history[index];
const onHistoryChanged = this.props.setLineageViewTarget.bind(this, targetArtifact);
this.setState(
{
history,
},
onHistoryChanged,
);
}
private reset() {
this.sliceHistory(0);
}
}
| 210 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageTypes.ts | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This file provides common types used by the Lineage Explorer components
*/
import { Artifact, Execution } from 'src/third_party/mlmd';
export type LineageCardType = 'artifact' | 'execution';
export interface LineageRow {
prev?: boolean;
next?: boolean;
typedResource: LineageTypedResource;
resourceDetailsPageRoute: string;
}
export type LineageResource = Artifact | Execution;
export type LineageTypedResource =
| { type: 'artifact'; resource: Artifact }
| { type: 'execution'; resource: Execution };
export const DEFAULT_LINEAGE_CARD_TYPE = 'artifact' as LineageCardType;
| 211 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/Api.ts | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { MetadataStoreServicePromiseClient } from 'src/third_party/mlmd';
/** Known Artifact properties */
export enum ArtifactProperties {
ALL_META = '__ALL_META__',
CREATE_TIME = 'create_time',
DESCRIPTION = 'description',
NAME = 'name',
PIPELINE_NAME = 'pipeline_name',
VERSION = 'version',
}
/** Known Artifact custom properties */
export enum ArtifactCustomProperties {
WORKSPACE = '__kf_workspace__',
RUN = '__kf_run__',
NAME = 'name',
DISPLAY_NAME = 'display_name',
PIPELINE_NAME = 'pipeline_name', // TODO: Remove when switching to contexts
RUN_ID = 'run_id', // TODO: Remove when switching to contexts
}
/** Known Execution properties */
export enum ExecutionProperties {
NAME = 'name', // currently not available in api, use component_id instead
COMPONENT_ID = 'component_id',
PIPELINE_NAME = 'pipeline_name',
RUN_ID = 'run_id',
STATE = 'state',
}
/** Known Execution custom properties */
export enum ExecutionCustomProperties {
NAME = 'name',
WORKSPACE = '__kf_workspace__',
RUN = '__kf_run__',
RUN_ID = 'run_id', // TODO: Remove when switching to contexts
TASK_ID = 'task_id',
}
/** Format for a List request */
export interface ListRequest {
filter?: string;
orderAscending?: boolean;
pageSize?: number;
pageToken?: string;
sortBy?: string;
}
/**
* Class to wrap backend APIs.
*/
export class Api {
private static instance: Api;
private metadataServicePromiseClient = new MetadataStoreServicePromiseClient('', null, null);
/**
* Factory function to return an Api instance.
*/
public static getInstance(): Api {
if (!Api.instance) {
Api.instance = new Api();
}
return Api.instance;
}
get metadataStoreService() {
return this.metadataServicePromiseClient;
}
}
| 212 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageActionBar.test.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { mount, ReactWrapper, shallow, ShallowWrapper } from 'enzyme';
import { LineageActionBar, LineageActionBarProps, LineageActionBarState } from './LineageActionBar';
import { buildTestModel, testModel } from './TestUtils';
import { Artifact } from 'src/third_party/mlmd';
describe('LineageActionBar', () => {
let tree: ShallowWrapper;
const setLineageViewTarget = jest.fn();
const mountActionBar = (): ReactWrapper<
LineageActionBarProps,
LineageActionBarState,
LineageActionBar
> =>
mount(
<LineageActionBar initialTarget={testModel} setLineageViewTarget={setLineageViewTarget} />,
);
afterEach(() => {
tree.unmount();
setLineageViewTarget.mockReset();
});
it('Renders correctly for a given initial target', () => {
tree = shallow(<LineageActionBar initialTarget={testModel} setLineageViewTarget={jest.fn()} />);
expect(tree).toMatchSnapshot();
});
it('Does not update the LineageView target when the current breadcrumb is clicked', () => {
const tree = mountActionBar();
// There is one disabled button for the initially selected target.
expect(tree.state('history').length).toBe(1);
expect(setLineageViewTarget.mock.calls.length).toBe(0);
tree
.find('button')
.first()
.simulate('click');
expect(setLineageViewTarget.mock.calls.length).toBe(0);
expect(tree.state('history').length).toBe(1);
});
it('Updates the LineageView target model when an inactive breadcrumb is clicked', () => {
const tree = mountActionBar();
// Add a second artifact to the history state to make the first breadcrumb enabled.
tree.setState({
history: [testModel, buildTestModel()],
});
expect(tree.state('history').length).toBe(2);
tree.update();
expect(setLineageViewTarget.mock.calls.length).toBe(0);
tree
.find('button')
.first()
.simulate('click');
expect(setLineageViewTarget.mock.calls.length).toBe(1);
expect(tree).toMatchSnapshot();
});
it('Adds the artifact to the history state and DOM when pushHistory() is called', () => {
const tree = mountActionBar();
expect(tree.state('history').length).toBe(1);
tree.instance().pushHistory(new Artifact());
expect(tree.state('history').length).toBe(2);
tree.update();
expect(tree).toMatchSnapshot();
});
it('Sets history to the initial prop when the reset button is clicked', () => {
const tree = mountActionBar();
expect(tree.state('history').length).toBe(1);
tree.instance().pushHistory(buildTestModel());
tree.instance().pushHistory(buildTestModel());
expect(tree.state('history').length).toBe(3);
// Flush state to the DOM
tree.update();
const buttonWrappers = tree.find('button');
expect(buttonWrappers.length).toBe(4);
// The reset button is the last button on the action bar.
tree
.find('button')
.last()
.simulate('click');
expect(tree.state('history').length).toBe(1);
expect(tree).toMatchSnapshot();
});
});
| 213 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageCss.ts | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const px = (number: number): string => `${number}px`;
export const CARD_RADIUS = 6;
export const CARD_CONTAINER_BORDERS = 2;
export const CARD_TITLE_BASE_HEIGHT = 40;
export const CARD_TITLE_BORDER_BOTTOM_HEIGHT = 1;
export const CARD_TITLE_HEIGHT = CARD_TITLE_BASE_HEIGHT + CARD_TITLE_BORDER_BOTTOM_HEIGHT;
export const CARD_SPACER_HEIGHT = 24;
export const CARD_ROW_HEIGHT = 67;
| 214 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageCard.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { blue, grey } from '@material-ui/core/colors';
import * as React from 'react';
import { classes, stylesheet } from 'typestyle';
import { CSSProperties } from 'typestyle/lib/types';
import { LineageCardRow } from './LineageCardRow';
import { LineageRow, LineageCardType } from './LineageTypes';
import {
CARD_RADIUS,
CARD_SPACER_HEIGHT,
CARD_TITLE_BASE_HEIGHT,
CARD_TITLE_BORDER_BOTTOM_HEIGHT,
px,
} from './LineageCss';
import { Artifact } from 'src/third_party/mlmd';
const cardTitleBase: CSSProperties = {
borderTopLeftRadius: '4px',
borderTopRightRadius: '4px',
height: px(CARD_TITLE_BASE_HEIGHT),
};
interface LineageCardProps {
title: string;
type: LineageCardType;
rows: LineageRow[];
addSpacer: boolean;
isTarget?: boolean;
setLineageViewTarget?(artifact: Artifact): void;
}
export class LineageCard extends React.Component<LineageCardProps> {
public render(): JSX.Element {
const { title, type, rows, addSpacer, isTarget, setLineageViewTarget } = this.props;
const isExecution = type === 'execution';
const css = stylesheet({
addSpacer: {
marginTop: px(CARD_SPACER_HEIGHT),
},
cardContainer: {
background: 'white',
border: `1px solid ${grey[300]}`,
borderRadius: px(CARD_RADIUS),
$nest: {
h3: {
color: blue[600],
fontFamily: 'PublicSans-Medium',
fontSize: '9px',
letterSpacing: '0.8px',
lineHeight: '42px',
paddingLeft: '15px',
textAlign: 'left',
textTransform: 'uppercase',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
},
},
cardTitle: {
...cardTitleBase,
borderBottom: `${px(CARD_TITLE_BORDER_BOTTOM_HEIGHT)} solid ${grey[200]}`,
},
execution: {
background: '#2C4A6D',
border: '1px solid #CCE4FF',
$nest: {
h3: {
color: '#5DC2B8',
},
'.cardRow': {
borderBottom: '1px solid var(--grey-700)',
},
'.cardRow .rowTitle': {
color: 'white',
},
'.cardRow .rowDesc': {
color: 'var(--grey-500)',
},
".cardRow [class^='edge']": {
background: '#5DC2B8',
},
},
},
executionCardTitle: {
...cardTitleBase,
borderBottom: `${px(CARD_TITLE_BORDER_BOTTOM_HEIGHT)} solid transparent`,
},
target: {
border: `2px solid ${blue[500]}`,
},
});
const listCardRows = () =>
rows.map((r, i) => (
<LineageCardRow
key={i}
typedResource={r.typedResource}
resourceDetailsRoute={r.resourceDetailsPageRoute}
leftAffordance={!!r.prev}
rightAffordance={!!r.next}
isLastRow={i === rows.length - 1}
isTarget={isTarget}
hideRadio={isExecution}
setLineageViewTarget={setLineageViewTarget}
/>
));
const cardContainerClasses = classes(
css.cardContainer,
css[type], // css.execution
addSpacer ? css.addSpacer : '',
isTarget ? css.target : '',
);
return (
<div className={cardContainerClasses}>
<div className={classes(isExecution ? css.executionCardTitle : css.cardTitle)}>
<h3 title={title}>{title}</h3>
</div>
<div className='cardBody'>{listCardRows()}</div>
</div>
);
}
}
| 215 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/Css.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import createMuiTheme from '@material-ui/core/styles/createMuiTheme';
import { NestedCSSProperties } from 'typestyle/lib/types';
import { style, stylesheet, cssRaw } from 'typestyle';
cssRaw(`
.LineageExplorer {
--blue-50: #e8f0fe;
--blue-100: #d2e3fc;
--blue-200: #aecbfa;
--blue-300: #8ab4f8;
--blue-400: #669df6;
--blue-500: #1098f7;
--blue-600: #1098f7;
--blue-700: #1967d2;
--blue-800: #185abc;
--blue-900: #174ea6;
--red-50: #fce8e6;
--red-700: #c5221f;
--yellow-600: #f9ab00;
--green-500: #34a853;
--green-600: #1e8e3e;
--grey-50: #f8f9fa;
--grey-100: #f1f3f4;
--grey-200: #e8eaed;
--grey-300: #dadce0;
--grey-400: #bdc1c6;
--grey-500: #9aa0a6;
--grey-600: #80868b;
--grey-700: #5f6368;
--grey-800: #3c4043;
--grey-900: #202124;
--orange-500: #fa7b17;
--orange-700: #d56e0c;
--orange-900: #b06000;
--pink-500: #f538a0;
--pink-700: #c92786;
--purple-500: #a142f4;
--card-radius: 6px;
}
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
height: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0,0,0,.5);
box-shadow: 0 0 1px rgba(255,255,255,.5);
}
`);
cssRaw(`
@font-face {
font-family: 'PublicSans-Regular';
src: local('PublicSans-Regular'), local('PublicSans-Regular'), url(https://cdn.jsdelivr.net/npm/[email protected]/fonts/webfonts/PublicSans-Regular.woff) format('woff');
}
@font-face {
font-family: 'PublicSans-Medium';
src: local('PublicSans-Medium'), local('PublicSans-Medium'), url(https://cdn.jsdelivr.net/npm/[email protected]/fonts/webfonts/PublicSans-Medium.woff) format('woff');
}
@font-face {
font-family: 'PublicSans-SemiBold';
src: local('PublicSans-SemiBold'), local('PublicSans-SemiBold'), url(https://cdn.jsdelivr.net/npm/[email protected]/fonts/webfonts/PublicSans-SemiBold.woff) format('woff');
}
@font-face {
font-family: 'PublicSans-Bold';
src: local('PublicSans-Bold'), local('PublicSans-Bold'), url(https://cdn.jsdelivr.net/npm/[email protected]/fonts/webfonts/PublicSans-Bold.woff) format('woff');
}
`);
export const color = {
activeBg: '#eaf1fd',
alert: '#f9ab00', // Google yellow 600
background: '#fff',
blue: '#4285f4', // Google blue 500
disabledBg: '#ddd',
divider: '#e0e0e0',
errorBg: '#fbe9e7',
errorText: '#d50000',
foreground: '#000',
graphBg: '#f2f2f2',
grey: '#5f6368', // Google grey 500
inactive: '#5f6368',
lightGrey: '#eee', // Google grey 200
lowContrast: '#80868b', // Google grey 600
secondaryText: 'rgba(0, 0, 0, .88)',
separator: '#e8e8e8',
strong: '#202124', // Google grey 900
success: '#34a853',
successWeak: '#e6f4ea', // Google green 50
terminated: '#80868b',
theme: '#1a73e8',
themeDarker: '#0b59dc',
warningBg: '#f9f9e1',
warningText: '#ee8100',
weak: '#9aa0a6',
};
export const dimension = {
auto: 'auto',
base: 40,
jumbo: 64,
large: 48,
small: 36,
tiny: 24,
xlarge: 56,
xsmall: 32,
};
// tslint:disable:object-literal-sort-keys
export const zIndex = {
DROP_ZONE_OVERLAY: 1,
GRAPH_NODE: 1,
BUSY_OVERLAY: 2,
PIPELINE_SUMMARY_CARD: 2,
SIDE_PANEL: 2,
};
export const fontsize = {
small: 12,
base: 14,
medium: 16,
large: 18,
title: 18,
};
// tslint:enable:object-literal-sort-keys
const baseSpacing = 24;
export const spacing = {
base: baseSpacing,
units: (unit: number) => baseSpacing + unit * 4,
};
export const fonts = {
code: '"Source Code Pro", monospace',
main: '"Google Sans", "Helvetica Neue", sans-serif',
secondary: '"Roboto", "Helvetica Neue", sans-serif',
};
const palette = {
primary: {
dark: color.themeDarker,
main: color.theme,
},
secondary: {
main: 'rgba(0, 0, 0, .38)',
},
};
export const theme = createMuiTheme({
overrides: {
MuiButton: {
flat: {
fontSize: fontsize.base,
fontWeight: 'bold',
minHeight: dimension.tiny,
textTransform: 'none',
},
flatPrimary: {
border: '1px solid #ddd',
cursor: 'pointer',
fontSize: fontsize.base,
marginRight: 10,
textTransform: 'none',
},
flatSecondary: {
color: color.theme,
},
root: {
'&$disabled': {
backgroundColor: 'initial',
},
color: color.theme,
marginRight: 10,
padding: '0 8px',
},
},
MuiDialogActions: {
root: {
margin: 15,
},
},
MuiDialogTitle: {
root: {
fontSize: fontsize.large,
},
},
MuiFormControlLabel: {
root: {
marginLeft: 0,
},
},
MuiFormLabel: {
filled: {
marginLeft: 0,
marginTop: 0,
},
root: {
'&$focused': {
marginLeft: 0,
marginTop: 0,
},
fontSize: fontsize.base,
marginLeft: 5,
marginTop: -8,
},
},
MuiIconButton: {
root: {
padding: 9,
},
},
MuiInput: {
input: { padding: 0 },
root: { padding: 0 },
},
MuiInputAdornment: {
positionEnd: {
paddingRight: 0,
},
root: { padding: 0 },
},
MuiTooltip: {
tooltip: {
backgroundColor: '#666',
color: '#f1f1f1',
fontSize: 12,
},
},
},
palette,
typography: {
fontFamily: fonts.main,
fontSize: (fontsize.base + ' !important') as any,
useNextVariants: true,
},
});
export const commonCss = stylesheet({
absoluteCenter: {
left: 'calc(50% - 24px)',
position: 'absolute',
top: 'calc(50% - 24px)',
},
busyOverlay: {
backgroundColor: '#ffffffaa',
bottom: 0,
left: 0,
position: 'absolute',
right: 0,
top: 0,
zIndex: zIndex.BUSY_OVERLAY,
},
buttonAction: {
$nest: {
'&:disabled': {
backgroundColor: color.background,
},
'&:hover': {
backgroundColor: theme.palette.primary.dark,
},
},
backgroundColor: palette.primary.main,
color: 'white',
},
ellipsis: {
display: 'block',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
fit: {
bottom: 0,
height: '100%',
left: 0,
position: 'absolute',
right: 0,
top: 0,
width: '100%',
},
flex: {
alignItems: 'center !important',
display: 'flex !important',
flexShrink: 0,
},
flexColumn: {
display: 'flex !important',
flexDirection: 'column',
},
flexGrow: {
display: 'flex !important',
flexGrow: 1,
},
header: {
fontSize: fontsize.large,
fontWeight: 'bold',
paddingBottom: 16,
paddingTop: 20,
},
header2: {
fontSize: fontsize.medium,
fontWeight: 'bold',
paddingBottom: 16,
paddingTop: 20,
},
infoIcon: {
color: color.lowContrast,
height: 16,
width: 16,
},
link: {
$nest: {
'&:hover': {
color: color.theme,
textDecoration: 'underline',
},
},
color: color.strong,
cursor: 'pointer',
textDecoration: 'none',
},
noShrink: {
flexShrink: 0,
},
page: {
display: 'flex',
flexFlow: 'column',
flexGrow: 1,
overflow: 'auto',
},
pageOverflowHidden: {
display: 'flex',
flexFlow: 'column',
flexGrow: 1,
overflowX: 'auto',
overflowY: 'hidden',
},
prewrap: {
whiteSpace: 'pre-wrap',
},
scrollContainer: {
background: `linear-gradient(white 30%, rgba(255,255,255,0)),
linear-gradient(rgba(255,255,255,0), white 70%) 0 100%,
radial-gradient(farthest-corner at 50% 0, rgba(0,0,0,.2), rgba(0,0,0,0)),
radial-gradient(farthest-corner at 50% 100%, rgba(0,0,0,.2), rgba(0,0,0,0)) 0 100%`,
backgroundAttachment: 'local, local, scroll, scroll',
backgroundColor: 'white',
backgroundRepeat: 'no-repeat',
backgroundSize: '100% 40px, 100% 40px, 100% 2px, 100% 2px',
overflow: 'auto',
position: 'relative',
},
textField: {
display: 'flex',
height: 40,
marginBottom: 20,
marginTop: 15,
},
unstyled: {
color: 'inherit',
outline: 'none',
textDecoration: 'none',
},
});
export function _paddingInternal(units?: number, directions?: string): NestedCSSProperties {
units = units || baseSpacing;
directions = directions || 'blrt';
const rules: NestedCSSProperties = {};
if (directions.indexOf('b') > -1) {
rules.paddingBottom = units;
}
if (directions.indexOf('l') > -1) {
rules.paddingLeft = units;
}
if (directions.indexOf('r') > -1) {
rules.paddingRight = units;
}
if (directions.indexOf('t') > -1) {
rules.paddingTop = units;
}
return rules;
}
export function padding(units?: number, directions?: string): string {
return style(_paddingInternal(units, directions));
}
| 216 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/ControlledEdgeCanvas.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { classes } from 'typestyle';
import { edgeCanvasCss } from './EdgeCanvas';
import { EdgeLine } from './EdgeLine';
import {
CARD_ROW_HEIGHT,
CARD_CONTAINER_BORDERS,
CARD_SPACER_HEIGHT,
CARD_TITLE_HEIGHT,
} from './LineageCss';
export const CARD_OFFSET = CARD_SPACER_HEIGHT + CARD_TITLE_HEIGHT + CARD_CONTAINER_BORDERS;
interface ControlledEdgeCanvasProps {
// The edge is drawn over the card column and offset by the card width
cardWidth: number;
edgeWidth: number;
// If true edges are drawn from right to left.
reverseEdges: boolean;
// A list of output artifactIds
artifactIds: number[];
// Offset for the artifact edge lines in pixels.
offset: number;
// Top of the destination execution card relative to the top of the lineage card column.
top: number;
// Map from artifact id to card index.
artifactToCardMap: Map<number, number>;
outputExecutionToOutputArtifactMap: Map<number, number[]>;
}
/**
* A version of <EdgeCanvas/> that draws the lines connecting the edges of a list of vertically
* stacked output artifact cards <LineageCardColumn /> to the many output execution <LineageCard />
* elements in an adjacent <LineageCardColumn />.
*/
export class ControlledEdgeCanvas extends React.Component<ControlledEdgeCanvasProps> {
public render(): JSX.Element | null {
const { reverseEdges, edgeWidth } = this.props;
let viewHeight = 1;
const lastNode = reverseEdges ? 'y1' : 'y4';
const lastNodePositions = { y1: 0, y4: 0 };
if (this.props.offset) {
lastNodePositions[lastNode] += this.props.offset;
viewHeight += this.props.offset;
}
const edgeLines: JSX.Element[] = [];
this.props.artifactIds.forEach((artifactId, index) => {
if (index !== 0) {
let offset = CARD_OFFSET;
if (
this.props.artifactToCardMap.get(artifactId) !==
this.props.artifactToCardMap.get(artifactId - 1)
) {
offset += CARD_ROW_HEIGHT;
}
viewHeight += offset;
lastNodePositions[lastNode] += offset;
}
edgeLines.push(
<EdgeLine
height={viewHeight}
width={edgeWidth}
y1={lastNodePositions.y1}
y4={lastNodePositions.y4}
/>,
);
});
const css = edgeCanvasCss(
/* left= */ this.props.cardWidth,
/* top= */ this.props.top + CARD_TITLE_HEIGHT + CARD_ROW_HEIGHT / 2,
/* width= */ edgeWidth,
);
const edgeCanvasClasses = classes(css.edgeCanvas, reverseEdges && 'edgeCanvasReverse');
return <div className={edgeCanvasClasses}>{edgeLines}</div>;
}
}
| 217 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/TestUtils.ts | /*
* Copyright 2018,2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Artifact, Value } from 'src/third_party/mlmd';
import { ArtifactCustomProperties, ArtifactProperties } from './Api';
export const doubleValue = (number: number) => {
const value = new Value();
value.setDoubleValue(number);
return value;
};
export const intValue = (number: number) => {
const value = new Value();
value.setIntValue(number);
return value;
};
export const stringValue = (string: String) => {
const value = new Value();
value.setStringValue(String(string));
return value;
};
export const buildTestModel = () => {
const model = new Artifact();
model.setId(1);
model.setTypeId(1);
model.setUri('gs://my-bucket/mnist');
model.getPropertiesMap().set(ArtifactProperties.NAME, stringValue('test model'));
model.getPropertiesMap().set(ArtifactProperties.DESCRIPTION, stringValue('A really great model'));
model.getPropertiesMap().set(ArtifactProperties.VERSION, stringValue('v1'));
model
.getPropertiesMap()
.set(ArtifactProperties.CREATE_TIME, stringValue('2019-06-12T01:21:48.259263Z'));
model
.getPropertiesMap()
.set(
ArtifactProperties.ALL_META,
stringValue(
'{"hyperparameters": {"early_stop": true, ' +
'"layers": [10, 3, 1], "learning_rate": 0.5}, ' +
'"model_type": "neural network", ' +
'"training_framework": {"name": "tensorflow", "version": "v1.0"}}',
),
);
model
.getCustomPropertiesMap()
.set(ArtifactCustomProperties.WORKSPACE, stringValue('workspace-1'));
model.getCustomPropertiesMap().set(ArtifactCustomProperties.RUN, stringValue('1'));
return model;
};
export const testModel = buildTestModel();
| 218 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageCardColumn.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import grey from '@material-ui/core/colors/grey';
import React from 'react';
import { classes, stylesheet } from 'typestyle';
import { LineageCard } from './LineageCard';
import { LineageCardType, LineageRow } from './LineageTypes';
import { CARD_OFFSET, EdgeCanvas } from './EdgeCanvas';
import { Artifact } from 'src/third_party/mlmd';
import { ControlledEdgeCanvas } from './ControlledEdgeCanvas';
import { CARD_ROW_HEIGHT } from './LineageCss';
export interface CardDetails {
title: string;
elements: LineageRow[];
}
export interface LineageCardColumnProps {
type: LineageCardType;
title: string;
cards: CardDetails[];
connectedCards?: CardDetails[];
columnWidth: number;
columnPadding: number;
reverseBindings?: boolean;
skipEdgeCanvas?: boolean;
outputExecutionToOutputArtifactMap?: Map<number, number[]>;
setLineageViewTarget?(artifact: Artifact): void;
}
const NEXT_ITEM_SAME_CARD_OFFSET = CARD_ROW_HEIGHT;
const NEXT_ITEM_NEXT_CARD_OFFSET = CARD_ROW_HEIGHT + CARD_OFFSET;
export class LineageCardColumn extends React.Component<LineageCardColumnProps> {
public render(): JSX.Element | null {
const { columnPadding, type, title } = this.props;
const css = stylesheet({
mainColumn: {
display: 'inline-block',
justifyContent: 'center',
minHeight: '100%',
padding: `0 ${columnPadding}px`,
width: this.props.columnWidth,
boxSizing: 'border-box',
$nest: {
h2: {
color: grey[600],
fontFamily: 'PublicSans-Regular',
fontSize: '12px',
letterSpacing: '0.5px',
lineHeight: '40px',
textAlign: 'left',
textTransform: 'capitalize',
},
},
},
columnBody: {
position: 'relative',
width: '100%',
},
columnHeader: {
height: '40px',
margin: '10px 0px',
textAlign: 'left',
width: '100%',
},
});
return (
<div className={classes(css.mainColumn, type)}>
<div className={classes(css.columnHeader)}>
<h2>{title}</h2>
</div>
<div className={classes(css.columnBody)}>{this.drawColumnContent()}</div>
</div>
);
}
private jsxFromCardDetails(det: CardDetails, i: number): JSX.Element {
const isNotFirstEl = i > 0;
return (
<LineageCard
key={i}
title={det.title}
type={this.props.type}
addSpacer={isNotFirstEl}
rows={det.elements}
isTarget={/Target/i.test(this.props.title)}
setLineageViewTarget={this.props.setLineageViewTarget}
/>
);
}
private drawColumnContent(): JSX.Element {
const { cards, columnPadding, columnWidth, skipEdgeCanvas } = this.props;
const edgeWidth = columnPadding * 2;
const cardWidth = columnWidth - edgeWidth;
let edgeCanvases: JSX.Element[] = [];
if (this.props.outputExecutionToOutputArtifactMap && this.props.connectedCards) {
edgeCanvases = this.buildOutputExecutionToOutputArtifactEdgeCanvases(
this.props.outputExecutionToOutputArtifactMap,
cards,
this.props.connectedCards,
edgeWidth,
cardWidth,
);
} else {
edgeCanvases.push(
<EdgeCanvas
cardWidth={cardWidth}
edgeWidth={edgeWidth}
cards={cards}
reverseEdges={!!this.props.reverseBindings}
/>,
);
}
return (
<React.Fragment>
{skipEdgeCanvas ? null : edgeCanvases}
{cards.map(this.jsxFromCardDetails.bind(this))}
</React.Fragment>
);
}
private buildOutputExecutionToOutputArtifactEdgeCanvases(
outputExecutionToOutputArtifactMap: Map<number, number[]>,
artifactCards: CardDetails[],
executionCards: CardDetails[],
edgeWidth: number,
cardWidth: number,
): JSX.Element[] {
const edgeCanvases: JSX.Element[] = [];
const artifactIdToCardMap = new Map<number, number>();
artifactCards.forEach((card, index) => {
card.elements.forEach(row => {
artifactIdToCardMap.set(row.typedResource.resource.getId(), index);
});
});
const executionIdToCardMap = new Map<number, number>();
executionCards.forEach((card, index) => {
card.elements.forEach(row => {
executionIdToCardMap.set(row.typedResource.resource.getId(), index);
});
});
// Offset of the top of the card relative to the top of the column
let artifactOffset = 0;
let executionOffset = 0;
let artifactCardIndex: number | undefined;
let executionIndex = 0;
let executionCardIndex: number | undefined;
let previousExecutionCardIndex: number | undefined;
outputExecutionToOutputArtifactMap.forEach((artifactIds, executionId) => {
if (executionIndex > 0) {
executionCardIndex = executionIdToCardMap.get(executionId);
if (previousExecutionCardIndex === executionCardIndex) {
// Next execution is on the same card
executionOffset += NEXT_ITEM_SAME_CARD_OFFSET;
} else {
// Next execution is on the next card
executionOffset += NEXT_ITEM_NEXT_CARD_OFFSET;
}
}
edgeCanvases.push(
<ControlledEdgeCanvas
cardWidth={cardWidth}
edgeWidth={edgeWidth}
reverseEdges={!!this.props.reverseBindings}
artifactIds={artifactIds}
artifactToCardMap={artifactIdToCardMap}
offset={artifactOffset - executionOffset}
outputExecutionToOutputArtifactMap={outputExecutionToOutputArtifactMap}
top={executionOffset}
/>,
);
// Advance starting artifact offset.
artifactIds.forEach(artifactId => {
if (artifactCardIndex === null) {
artifactCardIndex = artifactIdToCardMap.get(artifactId) as number;
return;
}
const newArtifactIndex = artifactIdToCardMap.get(artifactId);
if (artifactCardIndex === newArtifactIndex) {
// Next artifact row is on the same card
artifactOffset += NEXT_ITEM_SAME_CARD_OFFSET;
} else {
// Next artifact row is on the next card
artifactOffset += NEXT_ITEM_NEXT_CARD_OFFSET;
}
artifactCardIndex = newArtifactIndex;
});
previousExecutionCardIndex = executionIdToCardMap.get(executionId);
executionIndex++;
});
return edgeCanvases;
}
}
| 219 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/EdgeCanvas.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { classes, stylesheet } from 'typestyle';
import {
CARD_ROW_HEIGHT,
CARD_CONTAINER_BORDERS,
CARD_SPACER_HEIGHT,
CARD_TITLE_HEIGHT,
px,
} from './LineageCss';
import { CardDetails } from './LineageCardColumn';
import { EdgeLine } from './EdgeLine';
export const CARD_OFFSET = CARD_SPACER_HEIGHT + CARD_TITLE_HEIGHT + CARD_CONTAINER_BORDERS;
export const edgeCanvasCss = (left: number, top: number, width: number) => {
return stylesheet({
edgeCanvas: {
border: 0,
display: 'block',
left,
transition: 'transform .25s',
overflow: 'visible',
position: 'absolute',
top: px(top),
width,
zIndex: -1,
$nest: {
'&.edgeCanvasReverse': {
left: 0,
transform: 'translateX(-100%)',
},
svg: {
display: 'block',
overflow: 'visible',
position: 'absolute',
},
},
},
});
};
export interface EdgeCanvasProps {
cards: CardDetails[];
// The edge is drawn over the card column and offset by the card width
cardWidth: number;
edgeWidth: number;
// If true edges are drawn from right to left.
reverseEdges: boolean;
}
/**
* Canvas that draws the lines connecting the edges of a list of vertically stacked cards in one
* <LineageCardColumn /> to the topmost <LineageCard /> in an adjacent <LineageCardColumn />.
*
* The adjacent column is assumed to be to right of the connecting cards unless `reverseEdges`
* is set to true.
*/
export class EdgeCanvas extends React.Component<EdgeCanvasProps> {
public render(): JSX.Element | null {
const { cards, reverseEdges, edgeWidth } = this.props;
let viewHeight = 1;
const lastNode = reverseEdges ? 'y1' : 'y4';
const lastNodePositions = { y1: 0, y4: 0 };
const edgeLines: JSX.Element[] = [];
cards.forEach((card, i) => {
card.elements.forEach((element, j) => {
if (!element.next) {
return;
}
edgeLines.push(
<EdgeLine
height={viewHeight}
width={edgeWidth}
y1={lastNodePositions.y1}
y4={lastNodePositions.y4}
/>,
);
viewHeight += CARD_ROW_HEIGHT;
lastNodePositions[lastNode] += CARD_ROW_HEIGHT;
});
viewHeight += CARD_OFFSET;
lastNodePositions[lastNode] += CARD_OFFSET;
});
const css = edgeCanvasCss(
/* left= */ this.props.cardWidth,
/* top= */ CARD_TITLE_HEIGHT + CARD_ROW_HEIGHT / 2,
/* width= */ edgeWidth,
);
const edgeCanvasClasses = classes(css.edgeCanvas, reverseEdges && 'edgeCanvasReverse');
return <div className={edgeCanvasClasses}>{edgeLines}</div>;
}
}
| 220 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/Api.test.ts | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Api } from './Api';
import { MetadataStoreServicePromiseClient } from 'src/third_party/mlmd';
describe('Api', () => {
it('Returns a singleton instance', () => {
const api = Api.getInstance();
expect(api).toBeInstanceOf(Api);
expect(api.metadataStoreService).toBeInstanceOf(MetadataStoreServicePromiseClient);
expect(api).toBe(Api.getInstance());
});
});
| 221 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/library.ts | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { LineageResource as LineageResourceType } from './LineageTypes';
export type LineageResource = LineageResourceType;
export {
Api,
ArtifactCustomProperties,
ArtifactProperties,
ExecutionProperties,
ExecutionCustomProperties,
} from './Api';
export { getArtifactTypes, getArtifactCreationTime } from './LineageApi';
export { LineageView } from './LineageView';
export {
getMetadataValue,
getResourceProperty,
getResourcePropertyViaFallBack,
getTypeName,
} from './Utils';
| 222 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageView.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// tslint:disable: object-literal-sort-keys
import groupBy from 'lodash.groupby';
import * as React from 'react';
import { classes, stylesheet } from 'typestyle';
import { commonCss, zIndex } from './Css';
import { LineageCardColumn, CardDetails } from './LineageCardColumn';
import { LineageActionBar } from './LineageActionBar';
import {
Artifact,
ArtifactType,
Event,
Execution,
ExecutionType,
GetArtifactsByIDRequest,
GetEventsByArtifactIDsRequest,
GetEventsByExecutionIDsRequest,
GetExecutionsByIDRequest,
MetadataStoreServicePromiseClient,
} from 'src/third_party/mlmd';
import { RefObject } from 'react';
import { getArtifactTypes, getExecutionTypes } from './LineageApi';
import { getExecutionTypeName, getTypeName } from './Utils';
import { Api } from './Api';
import { LineageResource } from './LineageTypes';
import CircularProgress from '@material-ui/core/CircularProgress';
import { ArtifactHelpers } from './MlmdUtils';
const isInputEvent = (event: Event) =>
[Event.Type.INPUT.valueOf(), Event.Type.DECLARED_INPUT.valueOf()].includes(event.getType());
const isOutputEvent = (event: Event) =>
[Event.Type.OUTPUT.valueOf(), Event.Type.DECLARED_OUTPUT.valueOf()].includes(event.getType());
/** Default size used when columnPadding prop is unset. */
const DEFAULT_COLUMN_PADDING = 40;
export interface LineageViewProps {
target: Artifact;
cardWidth?: number;
columnPadding?: number;
buildResourceDetailsPageRoute(resource: LineageResource, typeName: string): string;
}
interface LineageViewState {
loading: boolean;
// Dynamic value set to 1/5th of the view width.
columnWidth: number;
columnNames: string[];
columnTypes: string[];
artifactTypes?: Map<number, ArtifactType>;
executionTypes?: Map<number, ExecutionType>;
inputArtifacts: Artifact[];
inputExecutions: Execution[];
target: Artifact;
outputExecutions: Execution[];
outputArtifacts: Artifact[];
// A Map from output execution id to the list of output artifact ids it should be connected to.
// Used to construct the reverse bindings from the Output Artifacts column to the Output
// Executions column. This column is unique because the artifacts point to different
// executions instead of just one.
outputExecutionToOutputArtifactMap: Map<number, number[]>;
}
const LINEAGE_VIEW_CSS = stylesheet({
LineageExplorer: {
$nest: {
'&&': { flexFlow: 'row' },
},
position: 'relative',
background: '#F8F8F9',
zIndex: 0,
},
});
export class LineageView extends React.Component<LineageViewProps, LineageViewState> {
private readonly actionBarRef: React.Ref<LineageActionBar>;
private readonly containerRef: React.RefObject<HTMLDivElement> = React.createRef();
private readonly metadataStoreService: MetadataStoreServicePromiseClient;
private artifactTypes: Map<number, ArtifactType>;
private executionTypes: Map<number, ExecutionType>;
constructor(props: any) {
super(props);
this.metadataStoreService = Api.getInstance().metadataStoreService;
this.actionBarRef = React.createRef<LineageActionBar>();
this.state = {
loading: true,
columnWidth: 0,
columnNames: ['Input Artifact', '', 'Target', '', 'Output Artifact'],
columnTypes: ['ipa', 'ipx', 'target', 'opx', 'opa'],
inputArtifacts: [],
inputExecutions: [],
outputArtifacts: [],
outputExecutionToOutputArtifactMap: new Map<number, number[]>(),
outputExecutions: [],
target: props.target,
};
this.loadData = this.loadData.bind(this);
this.setTargetFromActionBar = this.setTargetFromActionBar.bind(this);
this.setTargetFromLineageCard = this.setTargetFromLineageCard.bind(this);
this.setColumnWidth = this.setColumnWidth.bind(this);
this.loadData(this.props.target.getId());
}
public componentDidMount(): void {
this.setColumnWidth();
window.addEventListener('resize', this.setColumnWidth);
}
public componentWillUnmount(): void {
window.removeEventListener('resize', this.setColumnWidth);
}
public render(): JSX.Element | null {
if (!this.artifactTypes || !this.state.columnWidth) {
return (
// Return an empty page to allow componentDidMount() to measure the flex container.
<div className={classes(commonCss.page)} ref={this.containerRef} />
);
}
const { columnNames } = this.state;
const columnPadding = this.props.columnPadding || DEFAULT_COLUMN_PADDING;
return (
<div className={classes(commonCss.page)} ref={this.containerRef}>
<LineageActionBar
ref={this.actionBarRef}
initialTarget={this.props.target}
setLineageViewTarget={this.setTargetFromActionBar}
/>
<div
className={classes(commonCss.page, LINEAGE_VIEW_CSS.LineageExplorer, 'LineageExplorer')}
>
{this.state.loading && (
<>
<div className={commonCss.busyOverlay} />
<CircularProgress
size={48}
className={commonCss.absoluteCenter}
style={{ zIndex: zIndex.BUSY_OVERLAY }}
/>
</>
)}
<LineageCardColumn
type='artifact'
cards={this.buildArtifactCards(this.state.inputArtifacts)}
title={`${columnNames[0]}`}
columnWidth={this.state.columnWidth}
columnPadding={columnPadding}
setLineageViewTarget={this.setTargetFromLineageCard}
/>
<LineageCardColumn
type='execution'
cards={this.buildExecutionCards(this.state.inputExecutions)}
columnPadding={columnPadding}
title={`${columnNames[1]}`}
columnWidth={this.state.columnWidth}
/>
<LineageCardColumn
type='artifact'
cards={this.buildArtifactCards([this.state.target], /* isTarget= */ true)}
columnPadding={columnPadding}
skipEdgeCanvas={true /* Canvas will be drawn by the next canvas's reverse edges. */}
title={`${columnNames[2]}`}
columnWidth={this.state.columnWidth}
/>
<LineageCardColumn
type='execution'
cards={this.buildExecutionCards(this.state.outputExecutions)}
columnPadding={columnPadding}
reverseBindings={true}
title={`${columnNames[3]}`}
columnWidth={this.state.columnWidth}
/>
<LineageCardColumn
type='artifact'
cards={this.buildArtifactCards(this.state.outputArtifacts)}
connectedCards={this.buildExecutionCards(this.state.outputExecutions)}
columnPadding={columnPadding}
columnWidth={this.state.columnWidth}
outputExecutionToOutputArtifactMap={this.state.outputExecutionToOutputArtifactMap}
reverseBindings={true}
setLineageViewTarget={this.setTargetFromLineageCard}
title={`${columnNames[4]}`}
/>
</div>
</div>
);
}
private buildArtifactCards(artifacts: Artifact[], isTarget: boolean = false): CardDetails[] {
const orderedCardsByType: CardDetails[] = [];
let currentType: number;
let currentTypeName: string;
let currentCard: CardDetails;
artifacts.forEach(artifact => {
if (!currentType || artifact.getTypeId() !== currentType) {
// Create a new card
currentType = artifact.getTypeId();
currentTypeName = getTypeName(Number(currentType), this.artifactTypes);
currentCard = {
title: currentTypeName,
elements: [],
};
orderedCardsByType.push(currentCard);
}
currentCard.elements.push({
typedResource: { type: 'artifact', resource: artifact },
resourceDetailsPageRoute: this.props.buildResourceDetailsPageRoute(
artifact,
currentTypeName,
),
prev: !isTarget || this.state.inputExecutions.length > 0,
next: !isTarget || this.state.outputExecutions.length > 0,
});
});
return orderedCardsByType;
}
private buildExecutionCards(executions: Execution[]): CardDetails[] {
const executionsByTypeId = groupBy(executions, e => e.getTypeId());
return Object.keys(executionsByTypeId).map(typeId => {
const executionTypeName = getExecutionTypeName(Number(typeId), this.executionTypes);
const executionsForType = executionsByTypeId[typeId];
return {
title: executionTypeName,
elements: executionsForType.map(execution => ({
typedResource: {
type: 'execution',
resource: execution,
},
resourceDetailsPageRoute: this.props.buildResourceDetailsPageRoute(
execution,
executionTypeName,
),
prev: true,
next: true,
})),
};
});
}
private async loadData(targetId: number): Promise<string> {
this.setState({
loading: true,
});
const [targetArtifactEvents, executionTypes, artifactTypes] = await Promise.all([
this.getArtifactEvents([targetId]),
getExecutionTypes(this.metadataStoreService),
getArtifactTypes(this.metadataStoreService),
]);
Object.assign(this, { artifactTypes, executionTypes });
const outputExecutionIds: number[] = [];
const inputExecutionIds: number[] = [];
for (const event of targetArtifactEvents) {
const executionId = event.getExecutionId();
if (isOutputEvent(event)) {
// The input executions column will show executions where the target
// was an output of the execution.
inputExecutionIds.push(executionId);
} else if (isInputEvent(event)) {
// The output executions column will show executions where the target
// was an input for the execution.
outputExecutionIds.push(executionId);
}
}
const [outputExecutions, inputExecutions] = await Promise.all([
this.getExecutions(outputExecutionIds),
this.getExecutions(inputExecutionIds),
]);
const [inputExecutionEvents, outputExecutionEvents] = await Promise.all([
this.getExecutionEvents(inputExecutionIds),
this.getExecutionEvents(outputExecutionIds),
]);
// Build the list of input artifacts for the input execution
const inputExecutionInputArtifactIds: number[] = [];
inputExecutionEvents.forEach(event => {
if (!isInputEvent(event)) {
return;
}
inputExecutionInputArtifactIds.push(event.getArtifactId());
});
// This map ensures that output artifacts are fetched in an order that is sorted by the
// connected output execution.
const outputExecutionToOutputArtifactMap: Map<number, number[]> = new Map();
const outputExecutionOutputArtifactIds: number[] = [];
outputExecutionEvents.forEach(event => {
if (!isOutputEvent(event)) {
return;
}
const executionId = event.getExecutionId();
if (!outputExecutionToOutputArtifactMap.get(executionId)) {
outputExecutionToOutputArtifactMap.set(executionId, []);
}
const artifactId = event.getArtifactId();
outputExecutionOutputArtifactIds.push(artifactId);
const artifacts = outputExecutionToOutputArtifactMap.get(executionId);
if (artifacts) {
artifacts.push(artifactId);
}
});
const [inputArtifacts, outputArtifacts] = await Promise.all([
this.getArtifacts(inputExecutionInputArtifactIds),
this.getArtifacts(outputExecutionOutputArtifactIds),
]);
this.setState({
loading: false,
inputArtifacts,
inputExecutions,
outputArtifacts,
outputExecutionToOutputArtifactMap,
outputExecutions,
});
return '';
}
// Updates the view and action bar when the target is set from a lineage card.
private setTargetFromLineageCard(target: Artifact): void {
const actionBarRefObject = this.actionBarRef as RefObject<LineageActionBar>;
if (!actionBarRefObject.current) {
return;
}
actionBarRefObject.current.pushHistory(target);
this.target = target;
}
// Updates the view when the target is changed from the action bar.
private setTargetFromActionBar(target: Artifact): void {
this.target = target;
}
private set target(target: Artifact) {
this.loadData(target.getId()).then(
() => {
// Target column should be updated in the same frame as other loaded data.
this.setState({
target,
});
},
error => {
console.error(
`Failed to load related data for artifact: ${ArtifactHelpers.getName(target)}. Details:`,
error,
);
this.setState({
loading: false,
});
},
);
}
private async getExecutions(executionIds: number[]): Promise<Execution[]> {
const request = new GetExecutionsByIDRequest();
request.setExecutionIdsList(executionIds);
const response = await this.metadataStoreService.getExecutionsByID(request);
return response.getExecutionsList();
}
private async getExecutionEvents(executionIds: number[]): Promise<Event[]> {
const request = new GetEventsByExecutionIDsRequest();
request.setExecutionIdsList(executionIds);
const response = await this.metadataStoreService.getEventsByExecutionIDs(request);
return response.getEventsList();
}
private async getArtifacts(artifactIds: number[]): Promise<Artifact[]> {
const request = new GetArtifactsByIDRequest();
request.setArtifactIdsList(artifactIds);
const response = await this.metadataStoreService.getArtifactsByID(request);
return response.getArtifactsList();
}
private async getArtifactEvents(artifactIds: number[]): Promise<Event[]> {
const request = new GetEventsByArtifactIDsRequest();
request.setArtifactIdsList(artifactIds);
const response = await this.metadataStoreService.getEventsByArtifactIDs(request);
return response.getEventsList();
}
private setColumnWidth(): void {
if (!this.containerRef || !this.containerRef.current) {
return;
}
this.setState({
columnWidth: this.containerRef.current.clientWidth / 5,
});
}
}
| 223 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/LineageApi.ts | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { formatDateString } from 'src/lib/Utils';
import {
ArtifactType,
Event,
ExecutionType,
GetEventsByArtifactIDsRequest,
GetExecutionTypesRequest,
GetArtifactTypesRequest,
MetadataStoreServicePromiseClient,
} from 'src/third_party/mlmd';
const EventType = Event.Type;
export type ArtifactTypeMap = Map<number, ArtifactType>;
export type ExecutionTypeMap = Map<number, ExecutionType>;
export async function getArtifactTypes(
metadataStoreService: MetadataStoreServicePromiseClient,
errorCallback?: (message: string) => void,
): Promise<ArtifactTypeMap> {
const response = await metadataStoreService.getArtifactTypes(new GetArtifactTypesRequest());
if (!response) {
if (errorCallback) {
errorCallback('Unable to retrieve Artifact Types, some features may not work.');
}
return new Map();
}
const artifactTypesMap = new Map<number, ArtifactType>();
(response!.getArtifactTypesList() || []).forEach((artifactType: ArtifactType) => {
artifactTypesMap.set(artifactType.getId()!, artifactType);
});
return artifactTypesMap;
}
export async function getExecutionTypes(
metadataStoreService: MetadataStoreServicePromiseClient,
errorCallback?: (message: string) => void,
): Promise<ExecutionTypeMap> {
const response = await metadataStoreService.getExecutionTypes(new GetExecutionTypesRequest());
if (!response) {
if (errorCallback) {
errorCallback('Unable to retrieve Execution Types, some features may not work.');
}
return new Map();
}
const executionTypesMap = new Map<number, ExecutionType>();
(response!.getExecutionTypesList() || []).forEach((executionType: ExecutionType) => {
executionTypesMap.set(executionType.getId()!, executionType);
});
return executionTypesMap;
}
export async function getArtifactCreationTime(
artifactId: number,
metadataStoreService: MetadataStoreServicePromiseClient,
errorCallback?: (message: string) => void,
): Promise<string> {
if (!artifactId) {
throw new Error('artifactId is empty');
}
const eventsRequest = new GetEventsByArtifactIDsRequest();
eventsRequest.setArtifactIdsList([artifactId]);
const response = await metadataStoreService.getEventsByArtifactIDs(eventsRequest);
if (!response) {
if (errorCallback) {
errorCallback(`Unable to retrieve Events for artifactId: ${artifactId}`);
}
return '';
}
const data = response.getEventsList().map(event => ({
time: event.getMillisecondsSinceEpoch(),
type: event.getType() || EventType.UNKNOWN,
}));
// The last output event is the event that produced current artifact.
const lastOutputEvent = data
.reverse()
.find(event => event.type === EventType.DECLARED_OUTPUT || event.type === EventType.OUTPUT);
if (lastOutputEvent && lastOutputEvent.time) {
return formatDateString(new Date(lastOutputEvent.time));
} else {
// No valid time found, just return empty
return '';
}
}
| 224 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/mlmd/Utils.test.ts | /*
* Copyright 2018,2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { doubleValue, intValue, stringValue } from './TestUtils';
import { Artifact, Value } from 'src/third_party/mlmd';
import { getMetadataValue, getResourceProperty } from './Utils';
describe('Utils', () => {
describe('getResourceProperty', () => {
it('returns null if resource has no properties', () => {
expect(getResourceProperty(new Artifact(), 'testPropName')).toBeNull();
});
it('returns null if resource has no custom properties', () => {
expect(getResourceProperty(new Artifact(), 'testCustomPropName', true)).toBeNull();
});
it('returns null if resource has no property with the provided name', () => {
const resource = new Artifact();
resource.getPropertiesMap().set('somePropName', doubleValue(123));
expect(getResourceProperty(resource, 'testPropName')).toBeNull();
});
it('returns if resource has no property with specified name if fromCustomProperties is false', () => {
const resource = new Artifact();
resource.getCustomPropertiesMap().set('testCustomPropName', doubleValue(123));
expect(
getResourceProperty(resource, 'testCustomPropName', /* fromCustomProperties= */ false),
).toBeNull();
});
it('returns if resource has no custom property with specified name if fromCustomProperties is true', () => {
const resource = new Artifact();
resource.getPropertiesMap().set('testPropName', doubleValue(123));
expect(
getResourceProperty(resource, 'testPropName', /* fromCustomProperties= */ true),
).toBeNull();
});
it('returns the value of the property with the provided name', () => {
const resource = new Artifact();
resource.getPropertiesMap().set('testPropName', doubleValue(123));
expect(getResourceProperty(resource, 'testPropName')).toEqual(123);
});
it('returns the value of the custom property with the provided name', () => {
const resource = new Artifact();
resource.getCustomPropertiesMap().set('testCustomPropName', stringValue('abc'));
expect(
getResourceProperty(resource, 'testCustomPropName', /* fromCustomProperties= */ true),
).toEqual('abc');
});
});
describe('getMetadataValue', () => {
it('returns a value of type double', () => {
expect(getMetadataValue(doubleValue(123))).toEqual(123);
});
it('returns a value of type int', () => {
expect(getMetadataValue(intValue(123))).toEqual(123);
});
it('returns a value of type string', () => {
expect(getMetadataValue(stringValue('abc'))).toEqual('abc');
});
it('returns an empty string if Value has no value', () => {
expect(getMetadataValue(new Value())).toEqual('');
});
});
});
| 225 |
0 | kubeflow_public_repos/pipelines/frontend/src/mlmd | kubeflow_public_repos/pipelines/frontend/src/mlmd/__snapshots__/LineageActionBar.test.tsx.snap | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`LineageActionBar Adds the artifact to the history state and DOM when pushHistory() is called 1`] = `
<LineageActionBar
initialTarget={
Object {
"array": Array [
1,
1,
"gs://my-bucket/mnist",
Array [],
Array [],
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": Object {
"4": Object {
"arrClean": false,
"arr_": Array [],
"map_": Object {
"__ALL_META__": Object {
"key": "__ALL_META__",
"value": Array [
,
,
"{\\"hyperparameters\\": {\\"early_stop\\": true, \\"layers\\": [10, 3, 1], \\"learning_rate\\": 0.5}, \\"model_type\\": \\"neural network\\", \\"training_framework\\": {\\"name\\": \\"tensorflow\\", \\"version\\": \\"v1.0\\"}}",
],
"valueWrapper": Object {
"array": Array [
,
,
"{\\"hyperparameters\\": {\\"early_stop\\": true, \\"layers\\": [10, 3, 1], \\"learning_rate\\": 0.5}, \\"model_type\\": \\"neural network\\", \\"training_framework\\": {\\"name\\": \\"tensorflow\\", \\"version\\": \\"v1.0\\"}}",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"create_time": Object {
"key": "create_time",
"value": Array [
,
,
"2019-06-12T01:21:48.259263Z",
],
"valueWrapper": Object {
"array": Array [
,
,
"2019-06-12T01:21:48.259263Z",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"description": Object {
"key": "description",
"value": Array [
,
,
"A really great model",
],
"valueWrapper": Object {
"array": Array [
,
,
"A really great model",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"name": Object {
"key": "name",
"value": Array [
,
,
"test model",
],
"valueWrapper": Object {
"array": Array [
,
,
"test model",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"version": Object {
"key": "version",
"value": Array [
,
,
"v1",
],
"valueWrapper": Object {
"array": Array [
,
,
"v1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
},
"valueCtor_": [Function],
},
"5": Object {
"arrClean": false,
"arr_": Array [],
"map_": Object {
"__kf_run__": Object {
"key": "__kf_run__",
"value": Array [
,
,
"1",
],
"valueWrapper": Object {
"array": Array [
,
,
"1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"__kf_workspace__": Object {
"key": "__kf_workspace__",
"value": Array [
,
,
"workspace-1",
],
"valueWrapper": Object {
"array": Array [
,
,
"workspace-1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
},
"valueCtor_": [Function],
},
},
}
}
setLineageViewTarget={[MockFunction]}
>
<div
className="container flex"
>
<div
className="breadcrumbContainer"
>
<span
className="workspace"
key="workspace"
>
workspace-1
</span>
<aside
className="workspaceSep"
key="workspace-sep"
/>
<button
className="breadcrumbInactive"
disabled={false}
key="breadcrumb-0"
onClick={[Function]}
>
test model
</button>
<BreadcrumbSeparator
key="separator-0"
>
<div
className="flex"
>
<pure(ArrowRightAltIcon)
className="breadcrumbSeparator"
>
<ArrowRightAltIcon
className="breadcrumbSeparator"
>
<WithStyles(SvgIcon)
className="breadcrumbSeparator"
>
<SvgIcon
className="breadcrumbSeparator"
classes={
Object {
"colorAction": "MuiSvgIcon-colorAction-33",
"colorDisabled": "MuiSvgIcon-colorDisabled-35",
"colorError": "MuiSvgIcon-colorError-34",
"colorPrimary": "MuiSvgIcon-colorPrimary-31",
"colorSecondary": "MuiSvgIcon-colorSecondary-32",
"fontSizeInherit": "MuiSvgIcon-fontSizeInherit-36",
"fontSizeLarge": "MuiSvgIcon-fontSizeLarge-38",
"fontSizeSmall": "MuiSvgIcon-fontSizeSmall-37",
"root": "MuiSvgIcon-root-30",
}
}
color="inherit"
component="svg"
fontSize="default"
viewBox="0 0 24 24"
>
<svg
aria-hidden="true"
className="MuiSvgIcon-root-30 breadcrumbSeparator"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M0 0h24v24H0z"
fill="none"
/>
<path
d="M16.01 11H4v2h12.01v3L20 12l-3.99-4z"
/>
</svg>
</SvgIcon>
</WithStyles(SvgIcon)>
</ArrowRightAltIcon>
</pure(ArrowRightAltIcon)>
</div>
</BreadcrumbSeparator>
<button
className="breadcrumbActive"
disabled={true}
key="breadcrumb-1"
onClick={[Function]}
>
(No name)
</button>
</div>
<div>
<WithStyles(Button)
className="actionButton"
disabled={false}
onClick={[Function]}
>
<Button
className="actionButton"
classes={
Object {
"colorInherit": "MuiButton-colorInherit-22",
"contained": "MuiButton-contained-12",
"containedPrimary": "MuiButton-containedPrimary-13",
"containedSecondary": "MuiButton-containedSecondary-14",
"disabled": "MuiButton-disabled-21",
"extendedFab": "MuiButton-extendedFab-19",
"fab": "MuiButton-fab-18",
"flat": "MuiButton-flat-6",
"flatPrimary": "MuiButton-flatPrimary-7",
"flatSecondary": "MuiButton-flatSecondary-8",
"focusVisible": "MuiButton-focusVisible-20",
"fullWidth": "MuiButton-fullWidth-26",
"label": "MuiButton-label-2",
"mini": "MuiButton-mini-23",
"outlined": "MuiButton-outlined-9",
"outlinedPrimary": "MuiButton-outlinedPrimary-10",
"outlinedSecondary": "MuiButton-outlinedSecondary-11",
"raised": "MuiButton-raised-15",
"raisedPrimary": "MuiButton-raisedPrimary-16",
"raisedSecondary": "MuiButton-raisedSecondary-17",
"root": "MuiButton-root-1",
"sizeLarge": "MuiButton-sizeLarge-25",
"sizeSmall": "MuiButton-sizeSmall-24",
"text": "MuiButton-text-3",
"textPrimary": "MuiButton-textPrimary-4",
"textSecondary": "MuiButton-textSecondary-5",
}
}
color="default"
component="button"
disableFocusRipple={false}
disabled={false}
fullWidth={false}
mini={false}
onClick={[Function]}
size="medium"
type="button"
variant="text"
>
<WithStyles(ButtonBase)
className="MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
component="button"
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-20"
onClick={[Function]}
type="button"
>
<ButtonBase
centerRipple={false}
className="MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
classes={
Object {
"disabled": "MuiButtonBase-disabled-28",
"focusVisible": "MuiButtonBase-focusVisible-29",
"root": "MuiButtonBase-root-27",
}
}
component="button"
disableRipple={false}
disableTouchRipple={false}
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-20"
onClick={[Function]}
tabIndex="0"
type="button"
>
<button
className="MuiButtonBase-root-27 MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
disabled={false}
onBlur={[Function]}
onClick={[Function]}
onContextMenu={[Function]}
onFocus={[Function]}
onKeyDown={[Function]}
onKeyUp={[Function]}
onMouseDown={[Function]}
onMouseLeave={[Function]}
onMouseUp={[Function]}
onTouchEnd={[Function]}
onTouchMove={[Function]}
onTouchStart={[Function]}
tabIndex="0"
type="button"
>
<span
className="MuiButton-label-2"
>
<pure(ReplayIcon)>
<ReplayIcon>
<WithStyles(SvgIcon)>
<SvgIcon
classes={
Object {
"colorAction": "MuiSvgIcon-colorAction-33",
"colorDisabled": "MuiSvgIcon-colorDisabled-35",
"colorError": "MuiSvgIcon-colorError-34",
"colorPrimary": "MuiSvgIcon-colorPrimary-31",
"colorSecondary": "MuiSvgIcon-colorSecondary-32",
"fontSizeInherit": "MuiSvgIcon-fontSizeInherit-36",
"fontSizeLarge": "MuiSvgIcon-fontSizeLarge-38",
"fontSizeSmall": "MuiSvgIcon-fontSizeSmall-37",
"root": "MuiSvgIcon-root-30",
}
}
color="inherit"
component="svg"
fontSize="default"
viewBox="0 0 24 24"
>
<svg
aria-hidden="true"
className="MuiSvgIcon-root-30"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M0 0h24v24H0z"
fill="none"
/>
<path
d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"
/>
</svg>
</SvgIcon>
</WithStyles(SvgIcon)>
</ReplayIcon>
</pure(ReplayIcon)>
Reset
</span>
<NoSsr
defer={false}
fallback={null}
>
<WithStyles(TouchRipple)
center={false}
innerRef={[Function]}
>
<TouchRipple
center={false}
classes={
Object {
"child": "MuiTouchRipple-child-43",
"childLeaving": "MuiTouchRipple-childLeaving-44",
"childPulsate": "MuiTouchRipple-childPulsate-45",
"ripple": "MuiTouchRipple-ripple-40",
"ripplePulsate": "MuiTouchRipple-ripplePulsate-42",
"rippleVisible": "MuiTouchRipple-rippleVisible-41",
"root": "MuiTouchRipple-root-39",
}
}
>
<TransitionGroup
childFactory={[Function]}
className="MuiTouchRipple-root-39"
component="span"
enter={true}
exit={true}
>
<span
className="MuiTouchRipple-root-39"
/>
</TransitionGroup>
</TouchRipple>
</WithStyles(TouchRipple)>
</NoSsr>
</button>
</ButtonBase>
</WithStyles(ButtonBase)>
</Button>
</WithStyles(Button)>
</div>
</div>
</LineageActionBar>
`;
exports[`LineageActionBar Renders correctly for a given initial target 1`] = `
<div
className="container flex"
>
<div
className="breadcrumbContainer"
>
<span
className="workspace"
key="workspace"
>
workspace-1
</span>
<aside
className="workspaceSep"
key="workspace-sep"
/>
<button
className="breadcrumbActive"
disabled={true}
key="breadcrumb-0"
onClick={[Function]}
>
test model
</button>
</div>
<div>
<WithStyles(Button)
className="actionButton"
disabled={false}
onClick={[Function]}
>
<pure(ReplayIcon) />
Reset
</WithStyles(Button)>
</div>
</div>
`;
exports[`LineageActionBar Sets history to the initial prop when the reset button is clicked 1`] = `
<LineageActionBar
initialTarget={
Object {
"array": Array [
1,
1,
"gs://my-bucket/mnist",
Array [],
Array [],
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": Object {
"4": Object {
"arrClean": false,
"arr_": Array [],
"map_": Object {
"__ALL_META__": Object {
"key": "__ALL_META__",
"value": Array [
,
,
"{\\"hyperparameters\\": {\\"early_stop\\": true, \\"layers\\": [10, 3, 1], \\"learning_rate\\": 0.5}, \\"model_type\\": \\"neural network\\", \\"training_framework\\": {\\"name\\": \\"tensorflow\\", \\"version\\": \\"v1.0\\"}}",
],
"valueWrapper": Object {
"array": Array [
,
,
"{\\"hyperparameters\\": {\\"early_stop\\": true, \\"layers\\": [10, 3, 1], \\"learning_rate\\": 0.5}, \\"model_type\\": \\"neural network\\", \\"training_framework\\": {\\"name\\": \\"tensorflow\\", \\"version\\": \\"v1.0\\"}}",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"create_time": Object {
"key": "create_time",
"value": Array [
,
,
"2019-06-12T01:21:48.259263Z",
],
"valueWrapper": Object {
"array": Array [
,
,
"2019-06-12T01:21:48.259263Z",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"description": Object {
"key": "description",
"value": Array [
,
,
"A really great model",
],
"valueWrapper": Object {
"array": Array [
,
,
"A really great model",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"name": Object {
"key": "name",
"value": Array [
,
,
"test model",
],
"valueWrapper": Object {
"array": Array [
,
,
"test model",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"version": Object {
"key": "version",
"value": Array [
,
,
"v1",
],
"valueWrapper": Object {
"array": Array [
,
,
"v1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
},
"valueCtor_": [Function],
},
"5": Object {
"arrClean": false,
"arr_": Array [],
"map_": Object {
"__kf_run__": Object {
"key": "__kf_run__",
"value": Array [
,
,
"1",
],
"valueWrapper": Object {
"array": Array [
,
,
"1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"__kf_workspace__": Object {
"key": "__kf_workspace__",
"value": Array [
,
,
"workspace-1",
],
"valueWrapper": Object {
"array": Array [
,
,
"workspace-1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
},
"valueCtor_": [Function],
},
},
}
}
setLineageViewTarget={[MockFunction]}
>
<div
className="container flex"
>
<div
className="breadcrumbContainer"
>
<span
className="workspace"
key="workspace"
>
workspace-1
</span>
<aside
className="workspaceSep"
key="workspace-sep"
/>
<button
className="breadcrumbActive"
disabled={true}
key="breadcrumb-0"
onClick={[Function]}
>
test model
</button>
</div>
<div>
<WithStyles(Button)
className="actionButton"
disabled={false}
onClick={[Function]}
>
<Button
className="actionButton"
classes={
Object {
"colorInherit": "MuiButton-colorInherit-22",
"contained": "MuiButton-contained-12",
"containedPrimary": "MuiButton-containedPrimary-13",
"containedSecondary": "MuiButton-containedSecondary-14",
"disabled": "MuiButton-disabled-21",
"extendedFab": "MuiButton-extendedFab-19",
"fab": "MuiButton-fab-18",
"flat": "MuiButton-flat-6",
"flatPrimary": "MuiButton-flatPrimary-7",
"flatSecondary": "MuiButton-flatSecondary-8",
"focusVisible": "MuiButton-focusVisible-20",
"fullWidth": "MuiButton-fullWidth-26",
"label": "MuiButton-label-2",
"mini": "MuiButton-mini-23",
"outlined": "MuiButton-outlined-9",
"outlinedPrimary": "MuiButton-outlinedPrimary-10",
"outlinedSecondary": "MuiButton-outlinedSecondary-11",
"raised": "MuiButton-raised-15",
"raisedPrimary": "MuiButton-raisedPrimary-16",
"raisedSecondary": "MuiButton-raisedSecondary-17",
"root": "MuiButton-root-1",
"sizeLarge": "MuiButton-sizeLarge-25",
"sizeSmall": "MuiButton-sizeSmall-24",
"text": "MuiButton-text-3",
"textPrimary": "MuiButton-textPrimary-4",
"textSecondary": "MuiButton-textSecondary-5",
}
}
color="default"
component="button"
disableFocusRipple={false}
disabled={false}
fullWidth={false}
mini={false}
onClick={[Function]}
size="medium"
type="button"
variant="text"
>
<WithStyles(ButtonBase)
className="MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
component="button"
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-20"
onClick={[Function]}
type="button"
>
<ButtonBase
centerRipple={false}
className="MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
classes={
Object {
"disabled": "MuiButtonBase-disabled-28",
"focusVisible": "MuiButtonBase-focusVisible-29",
"root": "MuiButtonBase-root-27",
}
}
component="button"
disableRipple={false}
disableTouchRipple={false}
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-20"
onClick={[Function]}
tabIndex="0"
type="button"
>
<button
className="MuiButtonBase-root-27 MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
disabled={false}
onBlur={[Function]}
onClick={[Function]}
onContextMenu={[Function]}
onFocus={[Function]}
onKeyDown={[Function]}
onKeyUp={[Function]}
onMouseDown={[Function]}
onMouseLeave={[Function]}
onMouseUp={[Function]}
onTouchEnd={[Function]}
onTouchMove={[Function]}
onTouchStart={[Function]}
tabIndex="0"
type="button"
>
<span
className="MuiButton-label-2"
>
<pure(ReplayIcon)>
<ReplayIcon>
<WithStyles(SvgIcon)>
<SvgIcon
classes={
Object {
"colorAction": "MuiSvgIcon-colorAction-33",
"colorDisabled": "MuiSvgIcon-colorDisabled-35",
"colorError": "MuiSvgIcon-colorError-34",
"colorPrimary": "MuiSvgIcon-colorPrimary-31",
"colorSecondary": "MuiSvgIcon-colorSecondary-32",
"fontSizeInherit": "MuiSvgIcon-fontSizeInherit-36",
"fontSizeLarge": "MuiSvgIcon-fontSizeLarge-38",
"fontSizeSmall": "MuiSvgIcon-fontSizeSmall-37",
"root": "MuiSvgIcon-root-30",
}
}
color="inherit"
component="svg"
fontSize="default"
viewBox="0 0 24 24"
>
<svg
aria-hidden="true"
className="MuiSvgIcon-root-30"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M0 0h24v24H0z"
fill="none"
/>
<path
d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"
/>
</svg>
</SvgIcon>
</WithStyles(SvgIcon)>
</ReplayIcon>
</pure(ReplayIcon)>
Reset
</span>
<NoSsr
defer={false}
fallback={null}
>
<WithStyles(TouchRipple)
center={false}
innerRef={[Function]}
>
<TouchRipple
center={false}
classes={
Object {
"child": "MuiTouchRipple-child-43",
"childLeaving": "MuiTouchRipple-childLeaving-44",
"childPulsate": "MuiTouchRipple-childPulsate-45",
"ripple": "MuiTouchRipple-ripple-40",
"ripplePulsate": "MuiTouchRipple-ripplePulsate-42",
"rippleVisible": "MuiTouchRipple-rippleVisible-41",
"root": "MuiTouchRipple-root-39",
}
}
>
<TransitionGroup
childFactory={[Function]}
className="MuiTouchRipple-root-39"
component="span"
enter={true}
exit={true}
>
<span
className="MuiTouchRipple-root-39"
/>
</TransitionGroup>
</TouchRipple>
</WithStyles(TouchRipple)>
</NoSsr>
</button>
</ButtonBase>
</WithStyles(ButtonBase)>
</Button>
</WithStyles(Button)>
</div>
</div>
</LineageActionBar>
`;
exports[`LineageActionBar Updates the LineageView target model when an inactive breadcrumb is clicked 1`] = `
<LineageActionBar
initialTarget={
Object {
"array": Array [
1,
1,
"gs://my-bucket/mnist",
Array [],
Array [],
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": Object {
"4": Object {
"arrClean": false,
"arr_": Array [],
"map_": Object {
"__ALL_META__": Object {
"key": "__ALL_META__",
"value": Array [
,
,
"{\\"hyperparameters\\": {\\"early_stop\\": true, \\"layers\\": [10, 3, 1], \\"learning_rate\\": 0.5}, \\"model_type\\": \\"neural network\\", \\"training_framework\\": {\\"name\\": \\"tensorflow\\", \\"version\\": \\"v1.0\\"}}",
],
"valueWrapper": Object {
"array": Array [
,
,
"{\\"hyperparameters\\": {\\"early_stop\\": true, \\"layers\\": [10, 3, 1], \\"learning_rate\\": 0.5}, \\"model_type\\": \\"neural network\\", \\"training_framework\\": {\\"name\\": \\"tensorflow\\", \\"version\\": \\"v1.0\\"}}",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"create_time": Object {
"key": "create_time",
"value": Array [
,
,
"2019-06-12T01:21:48.259263Z",
],
"valueWrapper": Object {
"array": Array [
,
,
"2019-06-12T01:21:48.259263Z",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"description": Object {
"key": "description",
"value": Array [
,
,
"A really great model",
],
"valueWrapper": Object {
"array": Array [
,
,
"A really great model",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"name": Object {
"key": "name",
"value": Array [
,
,
"test model",
],
"valueWrapper": Object {
"array": Array [
,
,
"test model",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"version": Object {
"key": "version",
"value": Array [
,
,
"v1",
],
"valueWrapper": Object {
"array": Array [
,
,
"v1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
},
"valueCtor_": [Function],
},
"5": Object {
"arrClean": false,
"arr_": Array [],
"map_": Object {
"__kf_run__": Object {
"key": "__kf_run__",
"value": Array [
,
,
"1",
],
"valueWrapper": Object {
"array": Array [
,
,
"1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
"__kf_workspace__": Object {
"key": "__kf_workspace__",
"value": Array [
,
,
"workspace-1",
],
"valueWrapper": Object {
"array": Array [
,
,
"workspace-1",
],
"arrayIndexOffset_": -1,
"convertedPrimitiveFields_": Object {},
"messageId_": undefined,
"pivot_": 1.7976931348623157e+308,
"wrappers_": null,
},
},
},
"valueCtor_": [Function],
},
},
}
}
setLineageViewTarget={[MockFunction]}
>
<div
className="container flex"
>
<div
className="breadcrumbContainer"
>
<span
className="workspace"
key="workspace"
>
workspace-1
</span>
<aside
className="workspaceSep"
key="workspace-sep"
/>
<button
className="breadcrumbActive"
disabled={true}
key="breadcrumb-0"
onClick={[Function]}
>
test model
</button>
</div>
<div>
<WithStyles(Button)
className="actionButton"
disabled={false}
onClick={[Function]}
>
<Button
className="actionButton"
classes={
Object {
"colorInherit": "MuiButton-colorInherit-22",
"contained": "MuiButton-contained-12",
"containedPrimary": "MuiButton-containedPrimary-13",
"containedSecondary": "MuiButton-containedSecondary-14",
"disabled": "MuiButton-disabled-21",
"extendedFab": "MuiButton-extendedFab-19",
"fab": "MuiButton-fab-18",
"flat": "MuiButton-flat-6",
"flatPrimary": "MuiButton-flatPrimary-7",
"flatSecondary": "MuiButton-flatSecondary-8",
"focusVisible": "MuiButton-focusVisible-20",
"fullWidth": "MuiButton-fullWidth-26",
"label": "MuiButton-label-2",
"mini": "MuiButton-mini-23",
"outlined": "MuiButton-outlined-9",
"outlinedPrimary": "MuiButton-outlinedPrimary-10",
"outlinedSecondary": "MuiButton-outlinedSecondary-11",
"raised": "MuiButton-raised-15",
"raisedPrimary": "MuiButton-raisedPrimary-16",
"raisedSecondary": "MuiButton-raisedSecondary-17",
"root": "MuiButton-root-1",
"sizeLarge": "MuiButton-sizeLarge-25",
"sizeSmall": "MuiButton-sizeSmall-24",
"text": "MuiButton-text-3",
"textPrimary": "MuiButton-textPrimary-4",
"textSecondary": "MuiButton-textSecondary-5",
}
}
color="default"
component="button"
disableFocusRipple={false}
disabled={false}
fullWidth={false}
mini={false}
onClick={[Function]}
size="medium"
type="button"
variant="text"
>
<WithStyles(ButtonBase)
className="MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
component="button"
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-20"
onClick={[Function]}
type="button"
>
<ButtonBase
centerRipple={false}
className="MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
classes={
Object {
"disabled": "MuiButtonBase-disabled-28",
"focusVisible": "MuiButtonBase-focusVisible-29",
"root": "MuiButtonBase-root-27",
}
}
component="button"
disableRipple={false}
disableTouchRipple={false}
disabled={false}
focusRipple={true}
focusVisibleClassName="MuiButton-focusVisible-20"
onClick={[Function]}
tabIndex="0"
type="button"
>
<button
className="MuiButtonBase-root-27 MuiButton-root-1 MuiButton-text-3 MuiButton-flat-6 actionButton"
disabled={false}
onBlur={[Function]}
onClick={[Function]}
onContextMenu={[Function]}
onFocus={[Function]}
onKeyDown={[Function]}
onKeyUp={[Function]}
onMouseDown={[Function]}
onMouseLeave={[Function]}
onMouseUp={[Function]}
onTouchEnd={[Function]}
onTouchMove={[Function]}
onTouchStart={[Function]}
tabIndex="0"
type="button"
>
<span
className="MuiButton-label-2"
>
<pure(ReplayIcon)>
<ReplayIcon>
<WithStyles(SvgIcon)>
<SvgIcon
classes={
Object {
"colorAction": "MuiSvgIcon-colorAction-33",
"colorDisabled": "MuiSvgIcon-colorDisabled-35",
"colorError": "MuiSvgIcon-colorError-34",
"colorPrimary": "MuiSvgIcon-colorPrimary-31",
"colorSecondary": "MuiSvgIcon-colorSecondary-32",
"fontSizeInherit": "MuiSvgIcon-fontSizeInherit-36",
"fontSizeLarge": "MuiSvgIcon-fontSizeLarge-38",
"fontSizeSmall": "MuiSvgIcon-fontSizeSmall-37",
"root": "MuiSvgIcon-root-30",
}
}
color="inherit"
component="svg"
fontSize="default"
viewBox="0 0 24 24"
>
<svg
aria-hidden="true"
className="MuiSvgIcon-root-30"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M0 0h24v24H0z"
fill="none"
/>
<path
d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"
/>
</svg>
</SvgIcon>
</WithStyles(SvgIcon)>
</ReplayIcon>
</pure(ReplayIcon)>
Reset
</span>
<NoSsr
defer={false}
fallback={null}
>
<WithStyles(TouchRipple)
center={false}
innerRef={[Function]}
>
<TouchRipple
center={false}
classes={
Object {
"child": "MuiTouchRipple-child-43",
"childLeaving": "MuiTouchRipple-childLeaving-44",
"childPulsate": "MuiTouchRipple-childPulsate-45",
"ripple": "MuiTouchRipple-ripple-40",
"ripplePulsate": "MuiTouchRipple-ripplePulsate-42",
"rippleVisible": "MuiTouchRipple-rippleVisible-41",
"root": "MuiTouchRipple-root-39",
}
}
>
<TransitionGroup
childFactory={[Function]}
className="MuiTouchRipple-root-39"
component="span"
enter={true}
exit={true}
>
<span
className="MuiTouchRipple-root-39"
/>
</TransitionGroup>
</TouchRipple>
</WithStyles(TouchRipple)>
</NoSsr>
</button>
</ButtonBase>
</WithStyles(ButtonBase)>
</Button>
</WithStyles(Button)>
</div>
</div>
</LineageActionBar>
`;
| 226 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Description.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import Markdown from 'markdown-to-jsx';
import { ExternalLink } from '../atoms/ExternalLink';
function preventEventBubbling(e: React.MouseEvent): void {
e.stopPropagation();
}
const renderExternalLink = (props: {}) => (
<ExternalLink {...props} onClick={preventEventBubbling} />
);
const options = {
overrides: { a: { component: renderExternalLink } },
disableParsingRawHTML: true,
};
const optionsForceInline = {
...options,
forceInline: true,
};
export const Description: React.FC<{ description: string; forceInline?: boolean }> = ({
description,
forceInline,
}) => {
return <Markdown options={forceInline ? optionsForceInline : options}>{description}</Markdown>;
};
| 227 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/NewRunParameters.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Button from '@material-ui/core/Button';
import InputAdornment from '@material-ui/core/InputAdornment';
import TextField from '@material-ui/core/TextField';
import * as React from 'react';
import { classes, stylesheet } from 'typestyle';
import { ApiParameter } from '../apis/pipeline';
import { color, commonCss, spacing } from '../Css';
import Editor from './Editor';
export interface NewRunParametersProps {
initialParams: ApiParameter[];
titleMessage: string;
handleParamChange: (index: number, value: string) => void;
}
const css = stylesheet({
button: {
margin: 0,
padding: '3px 5px',
},
key: {
color: color.strong,
flex: '0 0 50%',
fontWeight: 'bold',
maxWidth: 300,
},
nonEditableInput: {
color: color.secondaryText,
},
row: {
borderBottom: `1px solid ${color.divider}`,
display: 'flex',
padding: `${spacing.units(-5)}px ${spacing.units(-6)}px`,
},
textfield: {
maxWidth: 600,
},
});
class NewRunParameters extends React.Component<NewRunParametersProps> {
public render(): JSX.Element | null {
const { handleParamChange, initialParams, titleMessage } = this.props;
return (
<div>
<div className={commonCss.header}>Run parameters</div>
<div>{titleMessage}</div>
{!!initialParams.length && (
<div>
{initialParams.map((param, i) => {
return (
<ParamEditor
key={i}
id={`newRunPipelineParam${i}`}
onChange={(value: string) => handleParamChange(i, value)}
param={param}
/>
);
})}
</div>
)}
</div>
);
}
}
interface ParamEditorProps {
id: string;
onChange: (value: string) => void;
param: ApiParameter;
}
interface ParamEditorState {
isEditorOpen: boolean;
isInJsonForm: boolean;
isJsonField: boolean;
}
class ParamEditor extends React.Component<ParamEditorProps, ParamEditorState> {
public static getDerivedStateFromProps(
nextProps: ParamEditorProps,
prevState: ParamEditorState,
): { isInJsonForm: boolean; isJsonField: boolean } {
let isJson = true;
try {
const displayValue = JSON.parse(nextProps.param.value || '');
// Nulls, booleans, strings, and numbers can all be parsed as JSON, but we don't care
// about rendering. Note that `typeOf null` returns 'object'
if (displayValue === null || typeof displayValue !== 'object') {
throw new Error('Parsed JSON was neither an array nor an object. Using default renderer');
}
} catch (err) {
isJson = false;
}
return {
isInJsonForm: isJson,
isJsonField: prevState.isJsonField || isJson,
};
}
public state = {
isEditorOpen: false,
isInJsonForm: false,
isJsonField: false,
};
public render(): JSX.Element | null {
const { id, onChange, param } = this.props;
const onClick = () => {
if (this.state.isInJsonForm) {
const displayValue = JSON.parse(param.value || '');
if (this.state.isEditorOpen) {
onChange(JSON.stringify(displayValue) || '');
} else {
onChange(JSON.stringify(displayValue, null, 2) || '');
}
}
this.setState({
isEditorOpen: !this.state.isEditorOpen,
});
};
return (
<>
{this.state.isJsonField ? (
<TextField
id={id}
disabled={this.state.isEditorOpen}
variant='outlined'
label={param.name}
value={param.value || ''}
onChange={ev => onChange(ev.target.value || '')}
className={classes(commonCss.textField, css.textfield)}
InputProps={{
classes: { disabled: css.nonEditableInput },
endAdornment: (
<InputAdornment position='end'>
<Button className={css.button} color='secondary' onClick={onClick}>
{this.state.isEditorOpen ? 'Close Json Editor' : 'Open Json Editor'}
</Button>
</InputAdornment>
),
readOnly: false,
}}
/>
) : (
<TextField
id={id}
variant='outlined'
label={param.name}
value={param.value || ''}
onChange={ev => onChange(ev.target.value || '')}
className={classes(commonCss.textField, css.textfield)}
/>
)}
{this.state.isJsonField && this.state.isEditorOpen && (
<div className={css.row}>
<Editor
width='100%'
minLines={3}
maxLines={20}
mode='json'
theme='github'
highlightActiveLine={true}
showGutter={true}
readOnly={false}
onChange={text => onChange(text || '')}
value={param.value || ''}
/>
</div>
)}
</>
);
}
}
export default NewRunParameters;
| 228 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/LogViewer.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { List, AutoSizer, ListRowProps } from 'react-virtualized';
import { fontsize, fonts } from '../Css';
import { stylesheet } from 'typestyle';
import { OverscanIndicesGetter } from 'react-virtualized/dist/es/Grid';
const css = stylesheet({
a: {
$nest: {
'&:hover': {
color: '#bcdeff',
},
'&:visited': {
color: '#bc9fff',
},
},
color: '#96cbfe',
},
line: {
$nest: {
'&:hover': {
backgroundColor: '#333',
},
},
display: 'flex',
},
number: {
color: '#999',
flex: '40px 0 0',
paddingRight: 10,
textAlign: 'right',
userSelect: 'none',
},
root: {
// We cannot easily add padding here without breaking react-virtualized size calculation, for
// details: https://github.com/bvaughn/react-virtualized/issues/992
// Specifically, a complex solution was proposed in https://github.com/bvaughn/react-virtualized/issues/992#issuecomment-371145943.
// We may consider that later.
backgroundColor: '#222',
color: '#fff',
fontFamily: fonts.code,
fontSize: fontsize.small,
// This override and listContainerStyleOverride workarounds to allow horizontal scroll.
// Reference: https://github.com/bvaughn/react-virtualized/issues/1248
overflow: 'auto !important',
whiteSpace: 'pre',
},
});
const listContainerStyleOverride = {
overflow: 'visible',
};
interface LogViewerProps {
logLines: string[];
}
// Use the same amount of overscan above and below visible rows.
//
// Why:
// * Default behavior is that when we scroll to one direction, content off
// screen on the other direction is unmounted from browser immediately. This
// caused a bug when selecting lines + scrolling.
// * With new behavior implemented below: we are now overscanning on both
// directions disregard of which direction user is scrolling to, we can ensure
// lines not exceeding maximum overscanRowCount lines off screen are still
// selectable.
const overscanOnBothDirections: OverscanIndicesGetter = ({
direction, // One of "horizontal" or "vertical"
cellCount, // Number of rows or columns in the current axis
scrollDirection, // 1 (forwards) or -1 (backwards)
overscanCellsCount, // Maximum number of cells to over-render in either direction
startIndex, // Begin of range of visible cells
stopIndex, // End of range of visible cells
}) => {
return {
overscanStartIndex: Math.max(0, startIndex - overscanCellsCount),
overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount),
};
};
interface LogViewerState {
followNewLogs: boolean;
}
class LogViewer extends React.Component<LogViewerProps, LogViewerState> {
public state = {
followNewLogs: true,
};
private _rootRef = React.createRef<List>();
public componentDidMount(): void {
// Wait until the next frame to scroll to bottom, because doms haven't been
// rendered when running this.
setTimeout(() => {
this._scrollToEnd();
});
}
public componentDidUpdate(): void {
if (this.state.followNewLogs) {
this._scrollToEnd();
}
}
public render(): JSX.Element {
return (
<AutoSizer>
{({ height, width }) => (
<List
id='logViewer'
containerStyle={listContainerStyleOverride}
width={width}
height={height}
rowCount={this.props.logLines.length}
rowHeight={15}
className={css.root}
ref={this._rootRef}
overscanIndicesGetter={overscanOnBothDirections}
overscanRowCount={
400 /* make this large, so selecting maximum 400 lines is supported */
}
rowRenderer={this._rowRenderer.bind(this)}
onScroll={this.handleScroll}
/>
)}
</AutoSizer>
);
}
private handleScroll = (info: {
clientHeight: number;
scrollHeight: number;
scrollTop: number;
}) => {
const offsetTolerance = 20; // pixels
const isScrolledToBottom =
info.scrollHeight - info.scrollTop - info.clientHeight <= offsetTolerance;
if (isScrolledToBottom !== this.state.followNewLogs) {
this.setState({
followNewLogs: isScrolledToBottom,
});
}
};
private _scrollToEnd(): void {
const root = this._rootRef.current;
if (root) {
root.scrollToRow(this.props.logLines.length + 1);
}
}
private _rowRenderer(props: ListRowProps): React.ReactNode {
const { style, key, index } = props;
const line = this.props.logLines[index];
return (
<div key={key} className={css.line} style={style}>
<MemoedLogLine index={index} line={line} />
</div>
);
}
}
const LogLine: React.FC<{ index: number; line: string }> = ({ index, line }) => (
<>
<span className={css.number} style={getLineStyle(line)}>
{index + 1}
</span>
<span className={css.line} style={getLineStyle(line)}>
{parseLine(line).map((piece, p) => (
<span key={p}>{piece}</span>
))}
</span>
</>
);
// improve performance when rerendering, because we render a lot of logs
const MemoedLogLine = React.memo(LogLine);
function getLineStyle(line: string): React.CSSProperties {
const lineLowerCase = line.toLowerCase();
if (lineLowerCase.indexOf('error') > -1 || lineLowerCase.indexOf('fail') > -1) {
return {
backgroundColor: '#700000',
color: 'white',
};
} else if (lineLowerCase.indexOf('warn') > -1) {
return {
backgroundColor: '#545400',
color: 'white',
};
} else {
return {};
}
}
function parseLine(line: string): React.ReactNode[] {
// Linkify URLs starting with http:// or https://
// eslint-disable-next-line no-useless-escape
const urlPattern = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
let lastMatch = 0;
let match = urlPattern.exec(line);
const nodes = [];
while (match) {
// Append all text before URL match
nodes.push(<span>{line.substr(lastMatch, match.index)}</span>);
// Append URL via an anchor element
nodes.push(
<a href={match[0]} target='_blank' rel='noopener noreferrer' className={css.a}>
{match[0]}
</a>,
);
lastMatch = match.index + match[0].length;
match = urlPattern.exec(line);
}
// Append all text after final URL
nodes.push(<span>{line.substr(lastMatch)}</span>);
return nodes;
}
export default LogViewer;
| 229 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PipelinesDialogV2.tsx | /*
* Copyright 2023 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import { classes } from 'typestyle';
import { padding, commonCss } from 'src/Css';
import DialogContent from '@material-ui/core/DialogContent';
import ResourceSelector from 'src/pages/ResourceSelector';
import { Apis, PipelineSortKeys } from 'src/lib/Apis';
import { Column } from './CustomTable';
import { V2beta1Pipeline } from 'src/apisv2beta1/pipeline';
import Buttons from 'src/lib/Buttons';
import { PageProps } from 'src/pages/Page';
import MD2Tabs from 'src/atoms/MD2Tabs';
import Toolbar, { ToolbarActionMap } from 'src/components/Toolbar';
import { PipelineTabsHeaders, PipelineTabsTooltips } from 'src/pages/PrivateAndSharedPipelines';
import { BuildInfoContext } from 'src/lib/BuildInfo';
import { convertPipelineToResource } from 'src/lib/ResourceConverter';
enum NamespacedAndSharedTab {
NAMESPACED = 0,
SHARED = 1,
}
export interface PipelinesDialogV2Props extends PageProps {
open: boolean;
selectorDialog: string;
onClose: (confirmed: boolean, selectedPipeline?: V2beta1Pipeline) => void;
namespace: string | undefined; // use context or make it optional?
pipelineSelectorColumns: Column[];
toolbarActionMap?: ToolbarActionMap;
}
const PipelinesDialogV2: React.FC<PipelinesDialogV2Props> = (props): JSX.Element | null => {
const buildInfo = React.useContext(BuildInfoContext);
const [view, setView] = React.useState(NamespacedAndSharedTab.NAMESPACED);
const [unconfirmedSelectedPipeline, setUnconfirmedSelectedPipeline] = React.useState<
V2beta1Pipeline
>();
function getPipelinesList(): JSX.Element {
return (
<ResourceSelector
{...props}
filterLabel='Filter pipelines'
listApi={async (
page_token?: string,
page_size?: number,
sort_by?: string,
filter?: string,
) => {
const response = await Apis.pipelineServiceApiV2.listPipelines(
buildInfo?.apiServerMultiUser && view === NamespacedAndSharedTab.NAMESPACED
? props.namespace
: undefined,
page_token,
page_size,
sort_by,
filter,
);
return {
nextPageToken: response.next_page_token || '',
resources: response.pipelines?.map(p => convertPipelineToResource(p)) || [],
};
}}
columns={props.pipelineSelectorColumns}
emptyMessage='No pipelines found. Upload a pipeline and then try again.'
initialSortColumn={PipelineSortKeys.CREATED_AT}
selectionChanged={async (selectedId: string) => {
const selectedPipeline = await Apis.pipelineServiceApiV2.getPipeline(selectedId);
setUnconfirmedSelectedPipeline(selectedPipeline);
}}
/>
);
}
function getTabs(): JSX.Element | null {
if (!buildInfo?.apiServerMultiUser) {
return null;
}
return (
<MD2Tabs
tabs={[
{
header: PipelineTabsHeaders.PRIVATE,
tooltip: PipelineTabsTooltips.PRIVATE,
},
{
header: PipelineTabsHeaders.SHARED,
tooltip: PipelineTabsTooltips.SHARED,
},
]}
selectedTab={view}
onSwitch={tabSwitched}
/>
);
}
function tabSwitched(newTab: NamespacedAndSharedTab): void {
setUnconfirmedSelectedPipeline(undefined);
setView(newTab);
}
function closeAndResetState(): void {
props.onClose(false);
setUnconfirmedSelectedPipeline(undefined);
setView(NamespacedAndSharedTab.NAMESPACED);
}
const getToolbar = (): JSX.Element => {
let actions = new Buttons(props, () => {}).getToolbarActionMap();
if (props.toolbarActionMap) {
actions = props.toolbarActionMap;
}
return <Toolbar actions={actions} breadcrumbs={[]} pageTitle={'Choose a pipeline'} />;
};
return (
<Dialog
open={props.open}
classes={{ paper: props.selectorDialog }}
onClose={() => closeAndResetState()}
PaperProps={{ id: 'pipelineSelectorDialog' }}
>
<DialogContent>
{getToolbar()}
<div className={classes(commonCss.page, padding(20, 't'))}>
{getTabs()}
{view === NamespacedAndSharedTab.NAMESPACED && getPipelinesList()}
{view === NamespacedAndSharedTab.SHARED && getPipelinesList()}
</div>
</DialogContent>
<DialogActions>
<Button
id='cancelPipelineSelectionBtn'
onClick={() => closeAndResetState()}
color='secondary'
>
Cancel
</Button>
<Button
id='usePipelineBtn'
onClick={() => props.onClose(true, unconfirmedSelectedPipeline)}
color='secondary'
disabled={!unconfirmedSelectedPipeline}
>
Use this pipeline
</Button>
</DialogActions>
</Dialog>
);
};
export default PipelinesDialogV2;
| 230 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Router.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import Snackbar, { SnackbarProps } from '@material-ui/core/Snackbar';
import * as React from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';
import Compare from 'src/pages/Compare';
import FrontendFeatures from 'src/pages/FrontendFeatures';
import RunDetailsRouter from 'src/pages/RunDetailsRouter';
import { classes, stylesheet } from 'typestyle';
import Banner, { BannerProps } from 'src/components/Banner';
import { commonCss } from 'src/Css';
import { Deployments, KFP_FLAGS } from 'src/lib/Flags';
import Page404 from 'src/pages/404';
import AllExperimentsAndArchive, {
AllExperimentsAndArchiveTab,
} from 'src/pages/AllExperimentsAndArchive';
import AllRecurringRunsList from 'src/pages/AllRecurringRunsList';
import AllRunsAndArchive, { AllRunsAndArchiveTab } from 'src/pages/AllRunsAndArchive';
import ArtifactDetails from 'src/pages/ArtifactDetails';
import ArtifactListSwitcher from 'src/pages/ArtifactListSwitcher';
import ExecutionDetails from 'src/pages/ExecutionDetails';
import ExecutionListSwitcher from 'src/pages/ExecutionListSwitcher';
import ExperimentDetails from 'src/pages/ExperimentDetails';
import { GettingStarted } from 'src/pages/GettingStarted';
import NewExperiment from 'src/pages/NewExperiment';
import NewPipelineVersion from 'src/pages/NewPipelineVersion';
import NewRunSwitcher from 'src/pages/NewRunSwitcher';
import PipelineDetails from 'src/pages/PipelineDetails';
import PrivateAndSharedPipelines, {
PrivateAndSharedTab,
} from 'src/pages/PrivateAndSharedPipelines';
import RecurringRunDetailsRouter from 'src/pages/RecurringRunDetailsRouter';
import SideNav from './SideNav';
import Toolbar, { ToolbarProps } from './Toolbar';
import { BuildInfoContext } from 'src/lib/BuildInfo';
export type RouteConfig = {
path: string;
Component: React.ComponentType<any>;
view?: any;
notExact?: boolean;
};
const css = stylesheet({
dialog: {
minWidth: 250,
},
});
export enum QUERY_PARAMS {
cloneFromRun = 'cloneFromRun',
cloneFromRecurringRun = 'cloneFromRecurringRun',
experimentId = 'experimentId',
isRecurring = 'recurring',
firstRunInExperiment = 'firstRunInExperiment',
pipelineId = 'pipelineId',
pipelineVersionId = 'pipelineVersionId',
fromRunId = 'fromRun',
fromRecurringRunId = 'fromRecurringRun',
runlist = 'runlist',
view = 'view',
}
export enum RouteParams {
experimentId = 'eid',
pipelineId = 'pid',
pipelineVersionId = 'vid',
runId = 'rid',
recurringRunId = 'rrid',
// TODO: create one of these for artifact and execution?
ID = 'id',
executionId = 'executionid',
}
// tslint:disable-next-line:variable-name
export const RoutePrefix = {
ARTIFACT: '/artifact',
EXECUTION: '/execution',
RECURRING_RUN: '/recurringrun',
};
// tslint:disable-next-line:variable-name
export const RoutePage = {
ARCHIVED_RUNS: '/archive/runs',
ARCHIVED_EXPERIMENTS: '/archive/experiments',
ARTIFACTS: '/artifacts',
ARTIFACT_DETAILS: `/artifacts/:${RouteParams.ID}`,
COMPARE: `/compare`,
EXECUTIONS: '/executions',
EXECUTION_DETAILS: `/executions/:${RouteParams.ID}`,
EXPERIMENTS: '/experiments',
EXPERIMENT_DETAILS: `/experiments/details/:${RouteParams.experimentId}`,
NEW_EXPERIMENT: '/experiments/new',
NEW_PIPELINE_VERSION: '/pipeline_versions/new',
NEW_RUN: '/runs/new',
PIPELINES: '/pipelines',
PIPELINES_SHARED: '/shared/pipelines',
PIPELINE_DETAILS: `/pipelines/details/:${RouteParams.pipelineId}/version/:${RouteParams.pipelineVersionId}?`,
PIPELINE_DETAILS_NO_VERSION: `/pipelines/details/:${RouteParams.pipelineId}?`, // pipelineId is optional
RUNS: '/runs',
RUN_DETAILS: `/runs/details/:${RouteParams.runId}`,
RUN_DETAILS_WITH_EXECUTION: `/runs/details/:${RouteParams.runId}/execution/:${RouteParams.executionId}`,
RECURRING_RUNS: '/recurringruns',
RECURRING_RUN_DETAILS: `/recurringrun/details/:${RouteParams.recurringRunId}`,
START: '/start',
FRONTEND_FEATURES: '/frontend_features',
};
export const RoutePageFactory = {
artifactDetails: (artifactId: number) => {
return RoutePage.ARTIFACT_DETAILS.replace(`:${RouteParams.ID}`, '' + artifactId);
},
executionDetails: (executionId: number) => {
return RoutePage.EXECUTION_DETAILS.replace(`:${RouteParams.ID}`, '' + executionId);
},
pipelineDetails: (id: string) => {
return RoutePage.PIPELINE_DETAILS_NO_VERSION.replace(`:${RouteParams.pipelineId}`, id);
},
};
export const ExternalLinks = {
DOCUMENTATION: 'https://www.kubeflow.org/docs/pipelines/',
GITHUB: 'https://github.com/kubeflow/pipelines',
GITHUB_ISSUE: 'https://github.com/kubeflow/pipelines/issues/new/choose',
};
export interface DialogProps {
buttons?: Array<{ onClick?: () => any; text: string }>;
// TODO: This should be generalized to any react component.
content?: string;
onClose?: () => any;
open?: boolean;
title?: string;
}
interface RouteComponentState {
bannerProps: BannerProps;
dialogProps: DialogProps;
snackbarProps: SnackbarProps;
toolbarProps: ToolbarProps;
}
export interface RouterProps {
configs?: RouteConfig[]; // only used in tests
}
const DEFAULT_ROUTE =
KFP_FLAGS.DEPLOYMENT === Deployments.MARKETPLACE ? RoutePage.START : RoutePage.PIPELINES;
// This component is made as a wrapper to separate toolbar state for different pages.
const Router: React.FC<RouterProps> = ({ configs }) => {
const buildInfo = React.useContext(BuildInfoContext);
let routes: RouteConfig[] = configs || [
{ path: RoutePage.START, Component: GettingStarted },
{
Component: AllRunsAndArchive,
path: RoutePage.ARCHIVED_RUNS,
view: AllRunsAndArchiveTab.ARCHIVE,
},
{
Component: AllExperimentsAndArchive,
path: RoutePage.ARCHIVED_EXPERIMENTS,
view: AllExperimentsAndArchiveTab.ARCHIVE,
},
{ path: RoutePage.ARTIFACTS, Component: ArtifactListSwitcher },
{ path: RoutePage.ARTIFACT_DETAILS, Component: ArtifactDetails, notExact: true },
{ path: RoutePage.EXECUTIONS, Component: ExecutionListSwitcher },
{ path: RoutePage.EXECUTION_DETAILS, Component: ExecutionDetails },
{
Component: AllExperimentsAndArchive,
path: RoutePage.EXPERIMENTS,
view: AllExperimentsAndArchiveTab.EXPERIMENTS,
},
{ path: RoutePage.EXPERIMENT_DETAILS, Component: ExperimentDetails },
{ path: RoutePage.NEW_EXPERIMENT, Component: NewExperiment },
{ path: RoutePage.NEW_PIPELINE_VERSION, Component: NewPipelineVersion },
{ path: RoutePage.NEW_RUN, Component: NewRunSwitcher },
{
path: RoutePage.PIPELINES,
Component: PrivateAndSharedPipelines,
view: PrivateAndSharedTab.PRIVATE,
},
{
path: RoutePage.PIPELINES_SHARED,
Component: PrivateAndSharedPipelines,
view: PrivateAndSharedTab.SHARED,
},
{ path: RoutePage.PIPELINE_DETAILS, Component: PipelineDetails },
{ path: RoutePage.PIPELINE_DETAILS_NO_VERSION, Component: PipelineDetails },
{ path: RoutePage.RUNS, Component: AllRunsAndArchive, view: AllRunsAndArchiveTab.RUNS },
{ path: RoutePage.RECURRING_RUNS, Component: AllRecurringRunsList },
{ path: RoutePage.RECURRING_RUN_DETAILS, Component: RecurringRunDetailsRouter },
{ path: RoutePage.RUN_DETAILS, Component: RunDetailsRouter },
{ path: RoutePage.RUN_DETAILS_WITH_EXECUTION, Component: RunDetailsRouter },
{ path: RoutePage.COMPARE, Component: Compare },
{ path: RoutePage.FRONTEND_FEATURES, Component: FrontendFeatures },
];
if (!buildInfo?.apiServerMultiUser) {
routes = routes.filter(r => r.path !== RoutePage.PIPELINES_SHARED);
}
return (
// There will be only one instance of SideNav, throughout UI usage.
<SideNavLayout>
<Switch>
<Route
exact={true}
path={'/'}
render={({ ...props }) => <Redirect to={DEFAULT_ROUTE} {...props} />}
/>
{/* Normal routes */}
{routes.map((route, i) => {
const { path } = { ...route };
return (
// Setting a key here, so that two different routes are considered two instances from
// react. Therefore, they don't share toolbar state. This avoids many bugs like dangling
// network response handlers.
<Route
key={i}
exact={!route.notExact}
path={path}
render={props => <RoutedPage key={props.location.key} route={route} />}
/>
);
})}
{/* 404 */}
{
<Route>
<RoutedPage />
</Route>
}
</Switch>
</SideNavLayout>
);
};
class RoutedPage extends React.Component<{ route?: RouteConfig }, RouteComponentState> {
private childProps = {
toolbarProps: {
breadcrumbs: [{ displayName: '', href: '' }],
actions: {},
pageTitle: '',
} as ToolbarProps,
updateBanner: this._updateBanner.bind(this),
updateDialog: this._updateDialog.bind(this),
updateSnackbar: this._updateSnackbar.bind(this),
updateToolbar: this._updateToolbar.bind(this),
};
constructor(props: any) {
super(props);
this.state = {
bannerProps: {},
dialogProps: { open: false },
snackbarProps: { autoHideDuration: 5000, open: false },
toolbarProps: { breadcrumbs: [{ displayName: '', href: '' }], actions: [], ...props },
};
}
public render(): JSX.Element {
this.childProps.toolbarProps = this.state.toolbarProps;
const route = this.props.route;
return (
<div className={classes(commonCss.page)}>
<Route render={({ ...props }) => <Toolbar {...this.state.toolbarProps} {...props} />} />
{this.state.bannerProps.message && (
<Banner
message={this.state.bannerProps.message}
mode={this.state.bannerProps.mode}
additionalInfo={this.state.bannerProps.additionalInfo}
refresh={this.state.bannerProps.refresh}
showTroubleshootingGuideLink={true}
/>
)}
<Switch>
{route &&
(() => {
const { path, Component, ...otherProps } = { ...route };
return (
<Route
exact={!route.notExact}
path={path}
render={({ ...props }) => (
<Component {...props} {...this.childProps} {...otherProps} />
)}
/>
);
})()}
{/* 404 */}
{!!route && (
<Route render={({ ...props }) => <Page404 {...props} {...this.childProps} />} />
)}
</Switch>
<Snackbar
autoHideDuration={this.state.snackbarProps.autoHideDuration}
message={this.state.snackbarProps.message}
open={this.state.snackbarProps.open}
onClose={this._handleSnackbarClose.bind(this)}
/>
<Dialog
open={this.state.dialogProps.open !== false}
classes={{ paper: css.dialog }}
className='dialog'
onClose={() => this._handleDialogClosed()}
>
{this.state.dialogProps.title && (
<DialogTitle> {this.state.dialogProps.title}</DialogTitle>
)}
{this.state.dialogProps.content && (
<DialogContent className={commonCss.prewrap}>
{this.state.dialogProps.content}
</DialogContent>
)}
{this.state.dialogProps.buttons && (
<DialogActions>
{this.state.dialogProps.buttons.map((b, i) => (
<Button
key={i}
onClick={() => this._handleDialogClosed(b.onClick)}
className='dialogButton'
color='secondary'
>
{b.text}
</Button>
))}
</DialogActions>
)}
</Dialog>
</div>
);
}
private _updateDialog(dialogProps: DialogProps): void {
// Assuming components will want to open the dialog by defaut.
if (dialogProps.open === undefined) {
dialogProps.open = true;
}
this.setState({ dialogProps });
}
private _updateToolbar(newToolbarProps: Partial<ToolbarProps>): void {
const toolbarProps = Object.assign(this.state.toolbarProps, newToolbarProps);
this.setState({ toolbarProps });
}
private _updateBanner(bannerProps: BannerProps): void {
this.setState({ bannerProps });
}
private _updateSnackbar(snackbarProps: SnackbarProps): void {
snackbarProps.autoHideDuration =
snackbarProps.autoHideDuration || this.state.snackbarProps.autoHideDuration;
this.setState({ snackbarProps });
}
private _handleDialogClosed(onClick?: () => void): void {
this.setState({ dialogProps: { open: false } });
if (onClick) {
onClick();
}
if (this.state.dialogProps.onClose) {
this.state.dialogProps.onClose();
}
}
private _handleSnackbarClose(): void {
this.setState({ snackbarProps: { open: false, message: '' } });
}
}
// TODO: loading/error experience until backend is reachable
export default Router;
const SideNavLayout: React.FC<{}> = ({ children }) => (
<div className={classes(commonCss.page)}>
<div className={classes(commonCss.flexGrow)}>
<Route render={({ ...props }) => <SideNav page={props.location.pathname} {...props} />} />
{children}
</div>
</div>
);
| 231 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PipelineSpecTabContent.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import jsyaml from 'js-yaml';
import React from 'react';
import { isSafari } from 'src/lib/Utils';
import Editor from './Editor';
interface PipelineSpecTabContentProps {
templateString: string;
}
const editorHeightWidth = isSafari() ? '640px' : '100%';
export function PipelineSpecTabContent(props: PipelineSpecTabContentProps) {
return (
<Editor
value={jsyaml.safeDump(jsyaml.safeLoad(props.templateString || ''))}
// Render the yaml-formatted string in <PipelineSpecTabContent>
// V1(JSON-formatted):
// safeLoad() convert templateString to object first,
// safeDump() changes the object to yaml-formatted string
// V2(YAML-formatted):
// Still yaml format after safeLoad() and safeDump().
height={editorHeightWidth}
width={editorHeightWidth}
mode='yaml'
theme='github'
editorProps={{ $blockScrolling: true }}
readOnly={true}
highlightActiveLine={true}
showGutter={true}
/>
);
}
| 232 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PipelinesDialogV2.test.tsx | /*
* Copyright 2023 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { render, screen } from '@testing-library/react';
import PipelinesDialogV2, { PipelinesDialogV2Props } from './PipelinesDialogV2';
import { PageProps } from 'src/pages/Page';
import { Apis, PipelineSortKeys } from 'src/lib/Apis';
import { V2beta1Pipeline, V2beta1ListPipelinesResponse } from 'src/apisv2beta1/pipeline';
import TestUtils from 'src/TestUtils';
import { BuildInfoContext } from 'src/lib/BuildInfo';
function generateProps(): PipelinesDialogV2Props {
return {
...generatePageProps(),
open: true,
selectorDialog: '',
onClose: jest.fn(),
namespace: 'ns',
pipelineSelectorColumns: [
{
flex: 1,
label: 'Pipeline name',
sortKey: PipelineSortKeys.NAME,
},
{ label: 'Description', flex: 2 },
{ label: 'Uploaded on', flex: 1, sortKey: PipelineSortKeys.CREATED_AT },
],
};
}
function generatePageProps(): PageProps {
return {
history: {} as any,
location: '' as any,
match: {} as any,
toolbarProps: {} as any,
updateBanner: jest.fn(),
updateDialog: jest.fn(),
updateSnackbar: jest.fn(),
updateToolbar: jest.fn(),
};
}
const oldPipeline: V2beta1Pipeline = {
pipeline_id: 'old-run-pipeline-id',
display_name: 'old mock pipeline name',
};
const newPipeline: V2beta1Pipeline = {
pipeline_id: 'new-run-pipeline-id',
display_name: 'new mock pipeline name',
};
describe('PipelinesDialog', () => {
let listPipelineSpy: jest.SpyInstance<{}>;
beforeEach(() => {
jest.clearAllMocks();
listPipelineSpy = jest
.spyOn(Apis.pipelineServiceApiV2, 'listPipelines')
.mockImplementation((...args) => {
const response: V2beta1ListPipelinesResponse = {
pipelines: [oldPipeline, newPipeline],
total_size: 2,
};
return Promise.resolve(response);
});
});
afterEach(async () => {
jest.resetAllMocks();
});
it('it renders correctly in multi user mode', async () => {
const tree = render(
<BuildInfoContext.Provider value={{ apiServerMultiUser: true }}>
<PipelinesDialogV2 {...generateProps()} />
</BuildInfoContext.Provider>,
);
await TestUtils.flushPromises();
expect(listPipelineSpy).toHaveBeenCalledWith('ns', '', 10, 'created_at desc', '');
screen.getByText('old mock pipeline name');
screen.getByText('new mock pipeline name');
});
it('it renders correctly in single user mode', async () => {
const tree = render(
<BuildInfoContext.Provider value={{ apiServerMultiUser: false }}>
<PipelinesDialogV2 {...generateProps()} />
</BuildInfoContext.Provider>,
);
await TestUtils.flushPromises();
expect(listPipelineSpy).toHaveBeenCalledWith(undefined, '', 10, 'created_at desc', '');
screen.getByText('old mock pipeline name');
screen.getByText('new mock pipeline name');
});
});
| 233 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CollapseButton.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import CollapseButton from './CollapseButton';
import { shallow } from 'enzyme';
describe('CollapseButton', () => {
const compareComponent = {
collapseSectionsUpdate: jest.fn(),
state: {
collapseSections: {},
},
} as any;
afterEach(() => (compareComponent.state.collapseSections = {}));
it('initial render', () => {
const tree = shallow(
<CollapseButton
collapseSections={compareComponent.state.collapseSections}
collapseSectionsUpdate={compareComponent.collapseSectionsUpdate}
sectionName='testSection'
/>,
);
expect(tree).toMatchSnapshot();
});
it('renders the button collapsed if in collapsedSections', () => {
compareComponent.state.collapseSections.testSection = true;
const tree = shallow(
<CollapseButton
collapseSections={compareComponent.state.collapseSections}
collapseSectionsUpdate={compareComponent.collapseSectionsUpdate}
sectionName='testSection'
/>,
);
expect(tree).toMatchSnapshot();
});
it('collapses given section when clicked', () => {
const tree = shallow(
<CollapseButton
collapseSections={compareComponent.state.collapseSections}
collapseSectionsUpdate={compareComponent.collapseSectionsUpdate}
sectionName='testSection'
/>,
);
tree.find('WithStyles(Button)').simulate('click');
expect(compareComponent.collapseSectionsUpdate).toHaveBeenCalledWith({ testSection: true });
});
it('expands given section when clicked if it is collapsed', () => {
compareComponent.state.collapseSections.testSection = true;
const tree = shallow(
<CollapseButton
collapseSections={compareComponent.state.collapseSections}
collapseSectionsUpdate={compareComponent.collapseSectionsUpdate}
sectionName='testSection'
/>,
);
tree.find('WithStyles(Button)').simulate('click');
expect(compareComponent.collapseSectionsUpdate).toHaveBeenCalledWith({ testSection: false });
});
});
| 234 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/DetailsTable.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import DetailsTable from './DetailsTable';
import { render } from '@testing-library/react';
jest.mock('./Editor', () => {
return ({ value }: { value: string }) => <pre data-testid='Editor'>{value}</pre>;
});
describe('DetailsTable', () => {
it('shows no rows', () => {
const { container } = render(<DetailsTable fields={[]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div />
</div>
`);
});
it('shows one row', () => {
const { container } = render(<DetailsTable fields={[['key', 'value']]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<span
class="valueText"
>
value
</span>
</div>
</div>
</div>
`);
});
it('shows a row with a title', () => {
const { container } = render(<DetailsTable title='some title' fields={[['key', 'value']]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="header2"
>
some title
</div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<span
class="valueText"
>
value
</span>
</div>
</div>
</div>
`);
});
it('shows key and value for large values', () => {
const { container } = render(
<DetailsTable
fields={[
[
'key',
`Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen book. It has survived not only five
centuries, but also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with the release
of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions
of Lorem Ipsum.`,
],
]}
/>,
);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<span
class="valueText"
>
Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen book. It has survived not only five
centuries, but also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with the release
of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions
of Lorem Ipsum.
</span>
</div>
</div>
</div>
`);
});
it('shows key and value in row', () => {
const { container } = render(<DetailsTable fields={[['key', 'value']]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<span
class="valueText"
>
value
</span>
</div>
</div>
</div>
`);
});
it('shows key and JSON value in row', () => {
const { container } = render(
<DetailsTable fields={[['key', JSON.stringify([{ jsonKey: 'jsonValue' }])]]} />,
);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<pre
data-testid="Editor"
>
[
{
"jsonKey": "jsonValue"
}
]
</pre>
</div>
</div>
</div>
`);
});
it('does render arrays as JSON', () => {
const { container } = render(<DetailsTable fields={[['key', '[]']]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<pre
data-testid="Editor"
>
[]
</pre>
</div>
</div>
</div>
`);
});
it('does render empty object as JSON', () => {
const { container } = render(<DetailsTable fields={[['key', '{}']]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<pre
data-testid="Editor"
>
{}
</pre>
</div>
</div>
</div>
`);
});
it('does not render nulls as JSON', () => {
const { container } = render(<DetailsTable fields={[['key', 'null']]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<span
class="valueText"
>
null
</span>
</div>
</div>
</div>
`);
});
it('does not render numbers as JSON', () => {
const { container } = render(<DetailsTable fields={[['key', '10']]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<span
class="valueText"
>
10
</span>
</div>
</div>
</div>
`);
});
it('does not render strings as JSON', () => {
const { container } = render(<DetailsTable fields={[['key', '"some string"']]} />);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<span
class="valueText"
>
"some string"
</span>
</div>
</div>
</div>
`);
});
it('does not render booleans as JSON', () => {
const { container } = render(
<DetailsTable
fields={[
['key1', 'true'],
['key2', 'false'],
]}
/>,
);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key1
</span>
<span
class="valueText"
>
true
</span>
</div>
<div
class="row"
>
<span
class="key"
>
key2
</span>
<span
class="valueText"
>
false
</span>
</div>
</div>
</div>
`);
});
it('shows keys and values for multiple rows', () => {
const { container } = render(
<DetailsTable
fields={[
['key1', 'value1'],
['key2', JSON.stringify([{ jsonKey: 'jsonValue2' }])],
['key3', 'value3'],
['key4', 'value4'],
['key5', JSON.stringify({ jsonKey: { nestedJsonKey: 'jsonValue' } })],
['key6', 'value6'],
['key6', 'value7'],
['key', { key: 'foobar', bucket: 'bucket', endpoint: 's3.amazonaws.com' }],
]}
/>,
);
expect(container).toMatchInlineSnapshot(`
<div>
<div>
<div
class="row"
>
<span
class="key"
>
key1
</span>
<span
class="valueText"
>
value1
</span>
</div>
<div
class="row"
>
<span
class="key"
>
key2
</span>
<pre
data-testid="Editor"
>
[
{
"jsonKey": "jsonValue2"
}
]
</pre>
</div>
<div
class="row"
>
<span
class="key"
>
key3
</span>
<span
class="valueText"
>
value3
</span>
</div>
<div
class="row"
>
<span
class="key"
>
key4
</span>
<span
class="valueText"
>
value4
</span>
</div>
<div
class="row"
>
<span
class="key"
>
key5
</span>
<pre
data-testid="Editor"
>
{
"jsonKey": {
"nestedJsonKey": "jsonValue"
}
}
</pre>
</div>
<div
class="row"
>
<span
class="key"
>
key6
</span>
<span
class="valueText"
>
value6
</span>
</div>
<div
class="row"
>
<span
class="key"
>
key6
</span>
<span
class="valueText"
>
value7
</span>
</div>
<div
class="row"
>
<span
class="key"
>
key
</span>
<span
class="valueText"
>
[object Object]
</span>
</div>
</div>
</div>
`);
});
it('does render values with the provided valueComponent', () => {
const ValueComponent: React.FC<any> = ({ value, ...rest }) => (
<a data-testid='value-component' {...rest}>
{JSON.stringify(value)}
</a>
);
const { getByTestId } = render(
<DetailsTable
fields={[['key2', { key: 'foobar', bucket: 'bucket', endpoint: 's3.amazonaws.com' }]]}
valueComponent={ValueComponent}
valueComponentProps={{ extraprop: 'extra' }}
/>,
);
expect(getByTestId('value-component')).toMatchInlineSnapshot(`
<a
data-testid="value-component"
extraprop="extra"
>
{"key":"foobar","bucket":"bucket","endpoint":"s3.amazonaws.com"}
</a>
`);
});
});
| 235 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CollapseButtonSingle.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Button from '@material-ui/core/Button';
import ExpandedIcon from '@material-ui/icons/ArrowDropUp';
import { stylesheet, classes } from 'typestyle';
import { color, fontsize } from '../Css';
const css = stylesheet({
collapseBtn: {
color: color.strong,
fontSize: fontsize.title,
fontWeight: 'bold',
padding: 5,
},
collapsed: {
transform: 'rotate(180deg)',
},
icon: {
marginRight: 5,
transition: 'transform 0.3s',
},
});
interface CollapseButtonSingleProps {
collapseSection: boolean;
collapseSectionUpdate: (collapseSection: boolean) => void;
sectionName: string;
}
function CollapseButtonSingle(props: CollapseButtonSingleProps) {
const { collapseSection, collapseSectionUpdate, sectionName } = props;
return (
<div>
<Button
onClick={() => {
collapseSectionUpdate(!collapseSection);
}}
title='Expand/Collapse this section'
className={css.collapseBtn}
>
<ExpandedIcon className={classes(css.icon, collapseSection ? css.collapsed : '')} />
{sectionName}
</Button>
</div>
);
}
export default CollapseButtonSingle;
| 236 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PipelinesDialog.tsx | /*
* Copyright 2023 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import { classes } from 'typestyle';
import { padding, commonCss } from '../Css';
import DialogContent from '@material-ui/core/DialogContent';
import ResourceSelector from '../pages/ResourceSelector';
import { Apis, PipelineSortKeys } from '../lib/Apis';
import { Column } from './CustomTable';
import { ApiPipeline } from '../apis/pipeline';
import Buttons from '../lib/Buttons';
import { PageProps } from '../pages/Page';
import MD2Tabs from '../atoms/MD2Tabs';
import Toolbar, { ToolbarActionMap } from '../components/Toolbar';
import { PipelineTabsHeaders, PipelineTabsTooltips } from '../pages/PrivateAndSharedPipelines';
import { BuildInfoContext } from 'src/lib/BuildInfo';
enum NamespacedAndSharedTab {
NAMESPACED = 0,
SHARED = 1,
}
export interface PipelinesDialogProps extends PageProps {
open: boolean;
selectorDialog: string;
onClose: (confirmed: boolean, selectedPipeline?: ApiPipeline) => void;
namespace: string | undefined; // use context or make it optional?
pipelineSelectorColumns: Column[];
toolbarActionMap?: ToolbarActionMap;
}
const PipelinesDialog: React.FC<PipelinesDialogProps> = (props): JSX.Element | null => {
const buildInfo = React.useContext(BuildInfoContext);
const [view, setView] = React.useState(NamespacedAndSharedTab.NAMESPACED);
const [unconfirmedSelectedPipeline, setUnconfirmedSelectedPipeline] = React.useState<
ApiPipeline
>();
function getPipelinesList(): JSX.Element {
return (
<ResourceSelector
{...props}
filterLabel='Filter pipelines'
listApi={async (...args) => {
if (buildInfo?.apiServerMultiUser && view === NamespacedAndSharedTab.NAMESPACED) {
args.push('NAMESPACE');
args.push(props.namespace);
}
const response = await Apis.pipelineServiceApi.listPipelines(...args);
return {
nextPageToken: response.next_page_token || '',
resources: response.pipelines || [],
};
}}
columns={props.pipelineSelectorColumns}
emptyMessage='No pipelines found. Upload a pipeline and then try again.'
initialSortColumn={PipelineSortKeys.CREATED_AT}
selectionChanged={async (selectedId: string) => {
const selectedPipeline = await Apis.pipelineServiceApi.getPipeline(selectedId);
setUnconfirmedSelectedPipeline(selectedPipeline);
}}
/>
);
}
function getTabs(): JSX.Element | null {
if (!buildInfo?.apiServerMultiUser) {
return null;
}
return (
<MD2Tabs
tabs={[
{
header: PipelineTabsHeaders.PRIVATE,
tooltip: PipelineTabsTooltips.PRIVATE,
},
{
header: PipelineTabsHeaders.SHARED,
tooltip: PipelineTabsTooltips.SHARED,
},
]}
selectedTab={view}
onSwitch={tabSwitched}
/>
);
}
function tabSwitched(newTab: NamespacedAndSharedTab): void {
setUnconfirmedSelectedPipeline(undefined);
setView(newTab);
}
function closeAndResetState(): void {
props.onClose(false);
setUnconfirmedSelectedPipeline(undefined);
setView(NamespacedAndSharedTab.NAMESPACED);
}
const getToolbar = (): JSX.Element => {
let actions = new Buttons(props, () => {}).getToolbarActionMap();
if (props.toolbarActionMap) {
actions = props.toolbarActionMap;
}
return <Toolbar actions={actions} breadcrumbs={[]} pageTitle={'Choose a pipeline'} />;
};
return (
<Dialog
open={props.open}
classes={{ paper: props.selectorDialog }}
onClose={() => closeAndResetState()}
PaperProps={{ id: 'pipelineSelectorDialog' }}
>
<DialogContent>
{getToolbar()}
<div className={classes(commonCss.page, padding(20, 't'))}>
{getTabs()}
{view === NamespacedAndSharedTab.NAMESPACED && getPipelinesList()}
{view === NamespacedAndSharedTab.SHARED && getPipelinesList()}
</div>
</DialogContent>
<DialogActions>
<Button
id='cancelPipelineSelectionBtn'
onClick={() => closeAndResetState()}
color='secondary'
>
Cancel
</Button>
<Button
id='usePipelineBtn'
onClick={() => props.onClose(true, unconfirmedSelectedPipeline)}
color='secondary'
disabled={!unconfirmedSelectedPipeline}
>
Use this pipeline
</Button>
</DialogActions>
</Dialog>
);
};
export default PipelinesDialog;
| 237 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PipelinesDialog.test.tsx | /*
* Copyright 2023 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { render } from '@testing-library/react';
import PipelinesDialog, { PipelinesDialogProps } from './PipelinesDialog';
import { PageProps } from '../pages/Page';
import { Apis, PipelineSortKeys } from '../lib/Apis';
import { ApiListPipelinesResponse, ApiPipeline } from '../apis/pipeline';
import TestUtils from '../TestUtils';
import { BuildInfoContext } from '../lib/BuildInfo';
function generateProps(): PipelinesDialogProps {
return {
...generatePageProps(),
open: true,
selectorDialog: '',
onClose: jest.fn(),
namespace: 'ns',
pipelineSelectorColumns: [
{
flex: 1,
label: 'Pipeline name',
sortKey: PipelineSortKeys.NAME,
},
{ label: 'Description', flex: 2 },
{ label: 'Uploaded on', flex: 1, sortKey: PipelineSortKeys.CREATED_AT },
],
};
}
function generatePageProps(): PageProps {
return {
history: {} as any,
location: '' as any,
match: {} as any,
toolbarProps: {} as any,
updateBanner: jest.fn(),
updateDialog: jest.fn(),
updateSnackbar: jest.fn(),
updateToolbar: jest.fn(),
};
}
const oldPipeline = newMockPipeline();
const newPipeline = newMockPipeline();
function newMockPipeline(): ApiPipeline {
return {
id: 'run-pipeline-id',
name: 'mock pipeline name',
parameters: [],
default_version: {
id: 'run-pipeline-version-id',
name: 'mock pipeline version name',
},
};
}
describe('PipelinesDialog', () => {
let listPipelineSpy: jest.SpyInstance<{}>;
beforeEach(() => {
jest.clearAllMocks();
listPipelineSpy = jest
.spyOn(Apis.pipelineServiceApi, 'listPipelines')
.mockImplementation((...args) => {
const response: ApiListPipelinesResponse = {
pipelines: [oldPipeline, newPipeline],
total_size: 2,
};
return Promise.resolve(response);
});
});
afterEach(async () => {
jest.resetAllMocks();
});
it('it renders correctly in multi user mode', async () => {
const tree = render(
<BuildInfoContext.Provider value={{ apiServerMultiUser: true }}>
<PipelinesDialog {...generateProps()} />
</BuildInfoContext.Provider>,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('it renders correctly in single user mode', async () => {
const tree = render(
<BuildInfoContext.Provider value={{ apiServerMultiUser: false }}>
<PipelinesDialog {...generateProps()} />
</BuildInfoContext.Provider>,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
});
| 238 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Trigger.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Trigger from './Trigger';
import { shallow } from 'enzyme';
import { TriggerType, PeriodicInterval } from '../lib/TriggerUtils';
import { fireEvent, render, screen } from '@testing-library/react';
const PARAMS_DEFAULT = {
catchup: true,
maxConcurrentRuns: '10',
};
const PERIODIC_DEFAULT = {
end_time: undefined,
interval_second: (60 * 60).toString(),
start_time: undefined,
};
const CRON_DEFAULT = { cron: '0 0 * * * ?', end_time: undefined, start_time: undefined };
beforeAll(() => {
process.env.TZ = 'UTC';
});
describe('Trigger', () => {
// tslint:disable-next-line:variable-name
const RealDate = Date;
function mockDate(isoDate: any): void {
(global as any).Date = class extends RealDate {
constructor(...args: any[]) {
super();
if (args.length === 0) {
// Use mocked date when calling new Date()
return new RealDate(isoDate);
} else {
// Otherwise, use real Date constructor
return new (RealDate as any)(...args);
}
}
};
}
const now = new Date(2018, 11, 21, 7, 53);
mockDate(now);
const oneWeekLater = new Date(2018, 11, 28, 7, 53);
it('renders periodic schedule controls for initial render', () => {
const tree = shallow(<Trigger />);
expect(tree).toMatchSnapshot();
});
it('renders periodic schedule controls if the trigger type is CRON', () => {
const tree = shallow(<Trigger />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
expect(tree).toMatchSnapshot();
});
it('renders week days if the trigger type is CRON and interval is weekly', () => {
const tree = shallow(<Trigger />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
(tree.instance() as Trigger).handleChange('intervalCategory')({
target: { value: PeriodicInterval.WEEK },
});
expect(tree).toMatchSnapshot();
});
it('renders all week days enabled', () => {
const tree = shallow(<Trigger />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
(tree.instance() as Trigger).handleChange('intervalCategory')({
target: { value: PeriodicInterval.WEEK },
});
(tree.instance() as any)._toggleCheckAllDays();
expect(tree).toMatchSnapshot();
});
it('enables a single day on click', () => {
const tree = shallow(<Trigger />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
(tree.instance() as Trigger).handleChange('intervalCategory')({
target: { value: PeriodicInterval.WEEK },
});
(tree.instance() as any)._toggleDay(1);
(tree.instance() as any)._toggleDay(3);
expect(tree).toMatchSnapshot();
});
describe('max concurrent run', () => {
it('shows error message if the input is invalid (non-integer)', () => {
render(<Trigger />);
const maxConcurrenyParam = screen.getByDisplayValue('10');
fireEvent.change(maxConcurrenyParam, { target: { value: '10a' } });
screen.getByText('Invalid input. The maximum concurrent runs should be a positive integer.');
});
it('shows error message if the input is invalid (negative integer)', () => {
render(<Trigger />);
const maxConcurrenyParam = screen.getByDisplayValue('10');
fireEvent.change(maxConcurrenyParam, { target: { value: '-10' } });
screen.getByText('Invalid input. The maximum concurrent runs should be a positive integer.');
});
});
describe('interval trigger', () => {
it('builds an every-hour trigger by default', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: PERIODIC_DEFAULT,
},
});
});
it('builds trigger with a start time if the checkbox is checked', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: { ...PERIODIC_DEFAULT, start_time: now },
},
});
});
it('builds trigger with the entered start date/time', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
(tree.instance() as Trigger).handleChange('startDate')({ target: { value: '2018-11-23' } });
(tree.instance() as Trigger).handleChange('startTime')({ target: { value: '08:35' } });
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: {
...PERIODIC_DEFAULT,
start_time: new Date(2018, 10, 23, 8, 35),
},
},
});
});
it('builds trigger without the entered start date if no time is entered', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
(tree.instance() as Trigger).handleChange('startDate')({ target: { value: '2018-11-23' } });
(tree.instance() as Trigger).handleChange('startTime')({ target: { value: '' } });
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: PERIODIC_DEFAULT,
},
});
});
it('builds trigger without the entered start time if no date is entered', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
(tree.instance() as Trigger).handleChange('startDate')({ target: { value: '' } });
(tree.instance() as Trigger).handleChange('startTime')({ target: { value: '11:33' } });
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: PERIODIC_DEFAULT,
},
});
});
it('builds trigger with a date if both start and end checkboxes are checked', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
(tree.instance() as Trigger).handleChange('hasEndDate')({
target: { type: 'checkbox', checked: true },
});
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: { ...PERIODIC_DEFAULT, end_time: oneWeekLater, start_time: now },
},
});
});
it('resets trigger to no start date if it is added then removed', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: false },
});
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: PERIODIC_DEFAULT,
},
});
});
it('Show invalid start date/time format message if date has wrong format.', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
// Message is shown if the format is incorrect.
(tree.instance() as Trigger).handleChange('startDate')({
target: { value: 'this_is_not_valid_date_format' },
});
var messageBox = tree.find({ 'data-testid': 'startTimeMessage' });
expect(messageBox.text()).toEqual("Invalid start date or time, start time won't be set");
// Message is removed if the format is correct.
(tree.instance() as Trigger).handleChange('startDate')({
target: { value: '2021-01-01' },
});
messageBox = tree.find({ 'data-testid': 'startTimeMessage' });
expect(messageBox.text()).toEqual('');
});
it('Hide invalid start date/time format message if start time checkbox is not selected.', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
// Message is shown if the format is incorrect.
(tree.instance() as Trigger).handleChange('startDate')({
target: { value: 'this_is_not_valid_date_format' },
});
var messageBox = tree.find({ 'data-testid': 'startTimeMessage' });
expect(messageBox.text()).toEqual("Invalid start date or time, start time won't be set");
// Message is removed if checkbox is not selected.
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: false },
});
messageBox = tree.find({ 'data-testid': 'startTimeMessage' });
expect(messageBox.text()).toEqual('');
});
it('Show invalid end date/time format message if date has wrong format.', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasEndDate')({
target: { type: 'checkbox', checked: true },
});
// Message is shown if the time format is incorrect.
(tree.instance() as Trigger).handleChange('endTime')({
target: { value: 'this_is_not_valid_time_format' },
});
var messageBox = tree.find({ 'data-testid': 'endTimeMessage' });
expect(messageBox.text()).toEqual("Invalid end date or time, end time won't be set");
// Message is removed if the format is correct.
(tree.instance() as Trigger).handleChange('endTime')({
target: { value: '11:22' },
});
messageBox = tree.find({ 'data-testid': 'endTimeMessage' });
expect(messageBox.text()).toEqual('');
});
it('Hide invalid end date/time format message if start time checkbox is not selected.', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('hasEndDate')({
target: { type: 'checkbox', checked: true },
});
// Message is shown if the format is incorrect.
(tree.instance() as Trigger).handleChange('endTime')({
target: { value: 'this_is_not_valid_date_format' },
});
var messageBox = tree.find({ 'data-testid': 'endTimeMessage' });
expect(messageBox.text()).toEqual("Invalid end date or time, end time won't be set");
// Message is removed if checkbox is not selected.
(tree.instance() as Trigger).handleChange('hasEndDate')({
target: { type: 'checkbox', checked: false },
});
messageBox = tree.find({ 'data-testid': 'endTimeMessage' });
expect(messageBox.text()).toEqual('');
});
it('builds trigger with a weekly interval', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('intervalCategory')({
target: { value: PeriodicInterval.WEEK },
});
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: {
...PERIODIC_DEFAULT,
interval_second: (7 * 24 * 60 * 60).toString(),
},
},
});
});
it('builds trigger with an every-three-months interval', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('intervalCategory')({
target: { value: PeriodicInterval.MONTH },
});
(tree.instance() as Trigger).handleChange('intervalValue')({ target: { value: 3 } });
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
periodic_schedule: {
...PERIODIC_DEFAULT,
interval_second: (3 * 30 * 24 * 60 * 60).toString(),
},
},
});
});
it('builds trigger with the specified max concurrency setting', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('maxConcurrentRuns')({ target: { value: '3' } });
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
maxConcurrentRuns: '3',
trigger: {
periodic_schedule: PERIODIC_DEFAULT,
},
});
});
it('builds trigger with the specified catchup setting', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({
target: { value: TriggerType.INTERVALED },
});
(tree.instance() as Trigger).handleChange('catchup')({
target: { type: 'checkbox', checked: false },
});
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
catchup: false,
trigger: {
periodic_schedule: PERIODIC_DEFAULT,
},
});
});
it('inits with cloned initial props', () => {
const spy = jest.fn();
const startTime = new Date('2020-01-01T23:53:00.000Z');
shallow(
<Trigger
onChange={spy}
initialProps={{
maxConcurrentRuns: '3',
catchup: false,
trigger: {
periodic_schedule: {
interval_second: '' + 60 * 60 * 3, // 3 hours
start_time: startTime.toISOString() as any,
},
},
}}
/>,
);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenLastCalledWith({
catchup: false,
maxConcurrentRuns: '3',
trigger: {
periodic_schedule: {
end_time: undefined,
interval_second: '10800',
start_time: startTime,
},
},
});
});
});
describe('cron', () => {
it('builds a 1-hour cron trigger by default', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
cron_schedule: CRON_DEFAULT,
},
});
});
it('builds a 1-hour cron trigger with specified start date', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
(tree.instance() as Trigger).handleChange('hasStartDate')({
target: { type: 'checkbox', checked: true },
});
(tree.instance() as Trigger).handleChange('startDate')({ target: { value: '2018-03-23' } });
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
cron_schedule: {
...CRON_DEFAULT,
start_time: new Date('2018-03-23T07:53:00.000Z'),
cron: '0 53 * * * ?',
},
},
});
});
it('builds a daily cron trigger with specified end date/time', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
(tree.instance() as Trigger).handleChange('hasEndDate')({
target: { type: 'checkbox', checked: true },
});
(tree.instance() as Trigger).handleChange('intervalCategory')({
target: { value: PeriodicInterval.DAY },
});
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
cron_schedule: { ...CRON_DEFAULT, end_time: oneWeekLater, cron: '0 0 0 * * ?' },
},
});
});
it('builds a weekly cron trigger that runs every Monday, Friday, and Saturday', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
(tree.instance() as Trigger).handleChange('intervalCategory')({
target: { value: PeriodicInterval.WEEK },
});
(tree.instance() as any)._toggleCheckAllDays();
(tree.instance() as any)._toggleDay(1);
(tree.instance() as any)._toggleDay(5);
(tree.instance() as any)._toggleDay(6);
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
cron_schedule: { ...CRON_DEFAULT, cron: '0 0 0 ? * 1,5,6' },
},
});
});
it('builds a cron with the manually specified cron string, even if days are toggled', () => {
const spy = jest.fn();
const tree = shallow(<Trigger onChange={spy} />);
(tree.instance() as Trigger).handleChange('type')({ target: { value: TriggerType.CRON } });
(tree.instance() as Trigger).handleChange('intervalCategory')({
target: { value: PeriodicInterval.WEEK },
});
(tree.instance() as any)._toggleCheckAllDays();
(tree.instance() as any)._toggleDay(1);
(tree.instance() as any)._toggleDay(5);
(tree.instance() as any)._toggleDay(6);
(tree.instance() as Trigger).handleChange('editCron')({
target: { type: 'checkbox', checked: true },
});
(tree.instance() as Trigger).handleChange('cron')({
target: { value: 'oops this will break!' },
});
expect(spy).toHaveBeenLastCalledWith({
...PARAMS_DEFAULT,
trigger: {
cron_schedule: { ...CRON_DEFAULT, cron: 'oops this will break!' },
},
});
});
it('inits with cloned initial props', () => {
const spy = jest.fn();
const startTime = new Date('2020-01-01T00:00:00.000Z');
const endTime = new Date('2020-01-02T01:02:00.000Z');
shallow(
<Trigger
onChange={spy}
initialProps={{
maxConcurrentRuns: '4',
catchup: true,
trigger: {
cron_schedule: {
cron: '0 0 0 ? * 1,5,6',
start_time: startTime.toISOString() as any,
end_time: endTime.toISOString() as any,
},
},
}}
/>,
);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenLastCalledWith({
catchup: true,
maxConcurrentRuns: '4',
trigger: {
cron_schedule: {
cron: '0 0 0 ? * 1,5,6',
start_time: startTime,
end_time: endTime,
},
},
});
});
});
});
| 239 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/SideNav.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { mount, ReactWrapper, shallow, ShallowWrapper } from 'enzyme';
import * as React from 'react';
import { MemoryRouter, RouterProps } from 'react-router';
import { Apis } from '../lib/Apis';
import { LocalStorage } from '../lib/LocalStorage';
import { RoutePage } from './Router';
import { css, SideNav } from './SideNav';
import { GkeMetadata } from '../lib/GkeMetadata';
import { createMemoryHistory } from 'history';
import TestUtils from '../TestUtils';
const wideWidth = 1000;
const narrowWidth = 200;
const isCollapsed = (tree: ShallowWrapper<any>) =>
tree.find('WithStyles(IconButton)').hasClass(css.collapsedChevron);
const routerProps: RouterProps = { history: {} as any };
const defaultProps = {
...routerProps,
gkeMetadata: {},
buildInfo: {
apiServerCommitHash: '0a7b9e38f2b9bcdef4bbf3234d971e1635b50cd5',
apiServerTagName: '1.0.0',
apiServerReady: true,
buildDate: 'Tue Oct 23 14:23:53 UTC 2018',
frontendCommitHash: '302e93ce99099173f387c7e0635476fe1b69ea98',
frontendTagName: '1.0.0-rc1',
},
};
describe('SideNav', () => {
let tree: ReactWrapper | ShallowWrapper;
const consoleErrorSpy = jest.spyOn(console, 'error');
const checkHubSpy = jest.spyOn(Apis, 'isJupyterHubAvailable');
const localStorageHasKeySpy = jest.spyOn(LocalStorage, 'hasKey');
const localStorageIsCollapsedSpy = jest.spyOn(LocalStorage, 'isNavbarCollapsed');
beforeEach(() => {
jest.clearAllMocks();
consoleErrorSpy.mockImplementation(() => null);
checkHubSpy.mockImplementation(() => ({ ok: true }));
localStorageHasKeySpy.mockImplementation(() => false);
localStorageIsCollapsedSpy.mockImplementation(() => false);
});
afterEach(async () => {
// unmount() should be called before resetAllMocks() in case any part of the unmount life cycle
// depends on mocks/spies
await tree.unmount();
jest.resetAllMocks();
(window as any).innerWidth = wideWidth;
});
it('renders expanded state', () => {
localStorageHasKeySpy.mockImplementationOnce(() => false);
(window as any).innerWidth = wideWidth;
tree = shallow(<SideNav page={RoutePage.PIPELINES} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders collapsed state', () => {
localStorageHasKeySpy.mockImplementationOnce(() => false);
(window as any).innerWidth = narrowWidth;
tree = shallow(<SideNav page={RoutePage.PIPELINES} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders Pipelines as active page', () => {
tree = shallow(<SideNav page={RoutePage.PIPELINES} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders Pipelines as active when on PipelineDetails page', () => {
tree = shallow(<SideNav page={RoutePage.PIPELINE_DETAILS} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders experiments as active page', () => {
tree = shallow(<SideNav page={RoutePage.EXPERIMENTS} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders experiments as active when on ExperimentDetails page', () => {
tree = shallow(<SideNav page={RoutePage.EXPERIMENT_DETAILS} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders experiments as active page when on NewExperiment page', () => {
tree = shallow(<SideNav page={RoutePage.NEW_EXPERIMENT} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders experiments as active page when on Compare page', () => {
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders experiments as active page when on AllRuns page', () => {
tree = shallow(<SideNav page={RoutePage.RUNS} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders experiments as active page when on RunDetails page', () => {
tree = shallow(<SideNav page={RoutePage.RUN_DETAILS} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders experiments as active page when on RecurringRunDetails page', () => {
tree = shallow(<SideNav page={RoutePage.RECURRING_RUN_DETAILS} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders experiments as active page when on NewRun page', () => {
tree = shallow(<SideNav page={RoutePage.NEW_RUN} {...defaultProps} />);
expect(tree).toMatchSnapshot();
});
it('renders recurring runs as active page', () => {
tree = shallow(<SideNav page={RoutePage.RECURRING_RUNS} {...defaultProps} />);
expect(tree).toMatchInlineSnapshot(`
<div
className="root flexColumn noShrink"
id="sideNav"
>
<div
style={
Object {
"flexGrow": 1,
}
}
>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Pipeline List"
>
<Link
className="unstyled"
id="pipelinesBtn"
replace={false}
to="/pipelines"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<div
className="alignItems"
>
<PipelinesIcon
color="#9aa0a6"
/>
</div>
<span
className="label"
>
Pipelines
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Experiment List"
>
<Link
className="unstyled"
id="experimentsBtn"
replace={false}
to="/experiments"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<div
className="alignItems"
>
<ExperimentsIcon
color="#9aa0a6"
/>
</div>
<span
className="label"
>
Experiments
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Runs List"
>
<Link
className="unstyled"
id="runsBtn"
replace={false}
to="/runs"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<pure(DirectionsRunIcon) />
<span
className="label"
>
Runs
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Recurring Runs List"
>
<Link
className="unstyled"
id="recurringRunsBtn"
replace={false}
to="/recurringruns"
>
<WithStyles(Button)
className="button active"
>
<div
className="flex flex-row flex-shrink-0"
>
<pure(AlarmIcon) />
<span
className="label"
>
Recurring Runs
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Artifacts List"
>
<Link
className="unstyled"
id="artifactsBtn"
replace={false}
to="/artifacts"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<pure(BubbleChartIcon) />
<span
className="label"
>
Artifacts
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Executions List"
>
<Link
className="unstyled"
id="executionsBtn"
replace={false}
to="/executions"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<pure(PlayArrowIcon) />
<span
className="label"
>
Executions
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<hr
className="separator"
/>
<ExternalUri
collapsed={false}
icon={[Function]}
title="Documentation"
to="https://www.kubeflow.org/docs/pipelines/"
/>
<ExternalUri
collapsed={false}
icon={[Function]}
title="Github Repo"
to="https://github.com/kubeflow/pipelines"
/>
<hr
className="separator"
/>
<WithStyles(IconButton)
className="chevron"
onClick={[Function]}
>
<pure(ChevronLeftIcon) />
</WithStyles(IconButton)>
</div>
<div
className="infoVisible"
>
<WithStyles(Tooltip)
enterDelay={300}
placement="top-start"
title="Build date: 10/23/2018, Commit hash: 0a7b9e3"
>
<div
className="envMetadata"
>
<span>
Version:
</span>
<a
className="link unstyled"
href="https://www.github.com/kubeflow/pipelines/commit/0a7b9e38f2b9bcdef4bbf3234d971e1635b50cd5"
rel="noopener"
target="_blank"
>
1.0.0
</a>
</div>
</WithStyles(Tooltip)>
<WithStyles(Tooltip)
enterDelay={300}
placement="top-start"
title="Report an Issue"
>
<div
className="envMetadata"
>
<a
className="link unstyled"
href="https://github.com/kubeflow/pipelines/issues/new/choose"
rel="noopener"
target="_blank"
>
Report an Issue
</a>
</div>
</WithStyles(Tooltip)>
</div>
</div>
`);
});
it('renders jobs as active page when on JobDetails page', () => {
tree = shallow(<SideNav page={RoutePage.RECURRING_RUN_DETAILS} {...defaultProps} />);
expect(tree).toMatchInlineSnapshot(`
<div
className="root flexColumn noShrink"
id="sideNav"
>
<div
style={
Object {
"flexGrow": 1,
}
}
>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Pipeline List"
>
<Link
className="unstyled"
id="pipelinesBtn"
replace={false}
to="/pipelines"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<div
className="alignItems"
>
<PipelinesIcon
color="#9aa0a6"
/>
</div>
<span
className="label"
>
Pipelines
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Experiment List"
>
<Link
className="unstyled"
id="experimentsBtn"
replace={false}
to="/experiments"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<div
className="alignItems"
>
<ExperimentsIcon
color="#9aa0a6"
/>
</div>
<span
className="label"
>
Experiments
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Runs List"
>
<Link
className="unstyled"
id="runsBtn"
replace={false}
to="/runs"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<pure(DirectionsRunIcon) />
<span
className="label"
>
Runs
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Recurring Runs List"
>
<Link
className="unstyled"
id="recurringRunsBtn"
replace={false}
to="/recurringruns"
>
<WithStyles(Button)
className="button active"
>
<div
className="flex flex-row flex-shrink-0"
>
<pure(AlarmIcon) />
<span
className="label"
>
Recurring Runs
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Artifacts List"
>
<Link
className="unstyled"
id="artifactsBtn"
replace={false}
to="/artifacts"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<pure(BubbleChartIcon) />
<span
className="label"
>
Artifacts
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<div
className="indicator indicatorHidden"
/>
<WithStyles(Tooltip)
disableFocusListener={true}
disableHoverListener={true}
disableTouchListener={true}
enterDelay={300}
placement="right-start"
title="Executions List"
>
<Link
className="unstyled"
id="executionsBtn"
replace={false}
to="/executions"
>
<WithStyles(Button)
className="button"
>
<div
className="flex flex-row flex-shrink-0"
>
<pure(PlayArrowIcon) />
<span
className="label"
>
Executions
</span>
</div>
</WithStyles(Button)>
</Link>
</WithStyles(Tooltip)>
<hr
className="separator"
/>
<ExternalUri
collapsed={false}
icon={[Function]}
title="Documentation"
to="https://www.kubeflow.org/docs/pipelines/"
/>
<ExternalUri
collapsed={false}
icon={[Function]}
title="Github Repo"
to="https://github.com/kubeflow/pipelines"
/>
<hr
className="separator"
/>
<WithStyles(IconButton)
className="chevron"
onClick={[Function]}
>
<pure(ChevronLeftIcon) />
</WithStyles(IconButton)>
</div>
<div
className="infoVisible"
>
<WithStyles(Tooltip)
enterDelay={300}
placement="top-start"
title="Build date: 10/23/2018, Commit hash: 0a7b9e3"
>
<div
className="envMetadata"
>
<span>
Version:
</span>
<a
className="link unstyled"
href="https://www.github.com/kubeflow/pipelines/commit/0a7b9e38f2b9bcdef4bbf3234d971e1635b50cd5"
rel="noopener"
target="_blank"
>
1.0.0
</a>
</div>
</WithStyles(Tooltip)>
<WithStyles(Tooltip)
enterDelay={300}
placement="top-start"
title="Report an Issue"
>
<div
className="envMetadata"
>
<a
className="link unstyled"
href="https://github.com/kubeflow/pipelines/issues/new/choose"
rel="noopener"
target="_blank"
>
Report an Issue
</a>
</div>
</WithStyles(Tooltip)>
</div>
</div>
`);
});
it('show jupyterhub link if accessible', () => {
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
tree.setState({ jupyterHubAvailable: true });
expect(tree).toMatchSnapshot();
});
it('collapses if collapse state is true localStorage', () => {
localStorageIsCollapsedSpy.mockImplementationOnce(() => true);
localStorageHasKeySpy.mockImplementationOnce(() => true);
(window as any).innerWidth = wideWidth;
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(isCollapsed(tree)).toBe(true);
});
it('expands if collapse state is false in localStorage', () => {
localStorageIsCollapsedSpy.mockImplementationOnce(() => false);
localStorageHasKeySpy.mockImplementationOnce(() => true);
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(isCollapsed(tree)).toBe(false);
});
it('collapses if no collapse state in localStorage, and window is too narrow', () => {
localStorageIsCollapsedSpy.mockImplementationOnce(() => false);
localStorageHasKeySpy.mockImplementationOnce(() => false);
(window as any).innerWidth = narrowWidth;
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(isCollapsed(tree)).toBe(true);
});
it('expands if no collapse state in localStorage, and window is wide', () => {
localStorageIsCollapsedSpy.mockImplementationOnce(() => false);
localStorageHasKeySpy.mockImplementationOnce(() => false);
(window as any).innerWidth = wideWidth;
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(isCollapsed(tree)).toBe(false);
});
it('collapses if no collapse state in localStorage, and window goes from wide to narrow', () => {
localStorageIsCollapsedSpy.mockImplementationOnce(() => false);
localStorageHasKeySpy.mockImplementationOnce(() => false);
(window as any).innerWidth = wideWidth;
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(isCollapsed(tree)).toBe(false);
(window as any).innerWidth = narrowWidth;
const resizeEvent = new Event('resize');
window.dispatchEvent(resizeEvent);
expect(isCollapsed(tree)).toBe(true);
});
it('expands if no collapse state in localStorage, and window goes from narrow to wide', () => {
localStorageIsCollapsedSpy.mockImplementationOnce(() => false);
localStorageHasKeySpy.mockImplementationOnce(() => false);
(window as any).innerWidth = narrowWidth;
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(isCollapsed(tree)).toBe(true);
(window as any).innerWidth = wideWidth;
const resizeEvent = new Event('resize');
window.dispatchEvent(resizeEvent);
expect(isCollapsed(tree)).toBe(false);
});
it('saves state in localStorage if chevron is clicked', () => {
localStorageIsCollapsedSpy.mockImplementationOnce(() => false);
localStorageHasKeySpy.mockImplementationOnce(() => false);
const spy = jest.spyOn(LocalStorage, 'saveNavbarCollapsed');
(window as any).innerWidth = narrowWidth;
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(isCollapsed(tree)).toBe(true);
tree.find('WithStyles(IconButton)').simulate('click');
expect(spy).toHaveBeenCalledWith(false);
});
it('does not collapse if collapse state is saved in localStorage, and window resizes', () => {
localStorageIsCollapsedSpy.mockImplementationOnce(() => false);
localStorageHasKeySpy.mockImplementationOnce(() => true);
(window as any).innerWidth = wideWidth;
tree = shallow(<SideNav page={RoutePage.COMPARE} {...defaultProps} />);
expect(isCollapsed(tree)).toBe(false);
(window as any).innerWidth = narrowWidth;
const resizeEvent = new Event('resize');
window.dispatchEvent(resizeEvent);
expect(isCollapsed(tree)).toBe(false);
});
it('populates the display build information using the default props', async () => {
tree = TestUtils.mountWithRouter(<SideNav page={RoutePage.PIPELINES} {...defaultProps} />);
const instance = tree.find(SideNav).instance() as any;
expect(tree).toMatchSnapshot();
const buildInfo = defaultProps.buildInfo;
expect(instance._getBuildInfo()).toEqual({
tagName: buildInfo.apiServerTagName,
commitHash: buildInfo.apiServerCommitHash.substring(0, 7),
commitUrl:
'https://www.github.com/kubeflow/pipelines/commit/' + buildInfo.apiServerCommitHash,
date: new Date(buildInfo.buildDate).toLocaleDateString(),
});
});
it('display the correct GKE metadata', async () => {
const clusterName = 'some-cluster-name';
const projectId = 'some-project-id';
const gkeMetadata: GkeMetadata = { clusterName, projectId };
const newProps = {
...defaultProps,
gkeMetadata,
buildInfo: {},
};
tree = TestUtils.mountWithRouter(<SideNav page={RoutePage.PIPELINES} {...newProps} />);
expect(tree).toMatchSnapshot();
});
it('displays the frontend tag name if the api server hash is not returned', async () => {
const newProps = {
...defaultProps,
buildInfo: {
apiServerReady: true,
// No apiServerCommitHash or apiServerTagName
buildDate: 'Tue Oct 23 14:23:53 UTC 2018',
frontendCommitHash: '302e93ce99099173f387c7e0635476fe1b69ea98',
frontendTagName: '1.0.0',
},
};
tree = TestUtils.mountWithRouter(<SideNav page={RoutePage.PIPELINES} {...newProps} />);
const instance = tree.find(SideNav).instance() as any;
expect(instance._getBuildInfo()).toEqual(
expect.objectContaining({
commitHash: newProps.buildInfo.frontendCommitHash.substring(0, 7),
tagName: newProps.buildInfo.frontendTagName,
}),
);
});
it('uses the frontend commit hash for the link URL if the api server hash is not returned', async () => {
const newProps = {
...defaultProps,
buildInfo: {
apiServerReady: true,
// No apiServerCommitHash
buildDate: 'Tue Oct 23 14:23:53 UTC 2018',
frontendCommitHash: '302e93ce99099173f387c7e0635476fe1b69ea98',
},
};
tree = TestUtils.mountWithRouter(<SideNav page={RoutePage.PIPELINES} {...newProps} />);
const instance = tree.find(SideNav).instance() as any;
expect(instance._getBuildInfo()).toEqual(
expect.objectContaining({
commitUrl:
'https://www.github.com/kubeflow/pipelines/commit/' +
newProps.buildInfo.frontendCommitHash,
}),
);
});
it("displays 'unknown' if the frontend and api server tag names/commit hashes are not returned", async () => {
const newProps = {
...defaultProps,
buildInfo: {
apiServerReady: true,
// No apiServerCommitHash
buildDate: 'Tue Oct 23 14:23:53 UTC 2018',
// No frontendCommitHash
},
};
tree = TestUtils.mountWithRouter(<SideNav page={RoutePage.PIPELINES} {...newProps} />);
const instance = tree.find(SideNav).instance() as any;
expect(instance._getBuildInfo()).toEqual(
expect.objectContaining({
commitHash: 'unknown',
tagName: 'unknown',
}),
);
});
it('links to the github repo root if the frontend and api server commit hashes are not returned', async () => {
const newProps = {
...defaultProps,
buildInfo: {
apiServerReady: true,
// No apiServerCommitHash
buildDate: 'Tue Oct 23 14:23:53 UTC 2018',
// No frontendCommitHash
},
};
tree = TestUtils.mountWithRouter(<SideNav page={RoutePage.PIPELINES} {...newProps} />);
const instance = tree.find(SideNav).instance() as any;
expect(instance._getBuildInfo()).toEqual(
expect.objectContaining({
commitUrl: 'https://www.github.com/kubeflow/pipelines',
}),
);
});
it("displays 'unknown' if the date is not returned", async () => {
const newProps = {
...defaultProps,
buildInfo: {
apiServerCommitHash: '0a7b9e38f2b9bcdef4bbf3234d971e1635b50cd5',
apiServerReady: true,
// No buildDate
frontendCommitHash: '302e93ce99099173f387c7e0635476fe1b69ea98',
},
};
tree = TestUtils.mountWithRouter(<SideNav page={RoutePage.PIPELINES} {...newProps} />);
const instance = tree.find(SideNav).instance() as any;
expect(instance._getBuildInfo()).toEqual(
expect.objectContaining({
date: 'unknown',
}),
);
});
});
| 240 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/TwoLevelDropdown.test.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { render, screen, fireEvent } from '@testing-library/react';
import * as React from 'react';
import { testBestPractices } from 'src/TestUtils';
import TwoLevelDropdown, {
DropdownItem,
SelectedItem,
TwoLevelDropdownProps,
} from './TwoLevelDropdown';
testBestPractices();
describe('TwoLevelDropdown', () => {
const title = 'Dropdown title';
const items: DropdownItem[] = [
{
name: 'first',
subItems: [
{
name: 'second',
},
{
name: 'third',
secondaryName: 'fourth',
},
],
},
{
name: 'fifth',
subItems: [
{
name: 'sixth',
secondaryName: 'seventh',
},
],
},
];
const selectedItem: SelectedItem = { itemName: '', subItemName: '' };
const setSelectedItem: (selectedItem: SelectedItem) => void = jest.fn();
function generateProps(): TwoLevelDropdownProps {
return {
title,
items,
selectedItem,
setSelectedItem,
} as TwoLevelDropdownProps;
}
it('Render two-level dropdown', async () => {
render(<TwoLevelDropdown {...generateProps()} />);
screen.getByText(title);
});
it('Render two-level dropdown with selection', async () => {
const props: TwoLevelDropdownProps = generateProps();
props.selectedItem = {
itemName: 'first',
subItemName: 'second',
subItemSecondaryName: 'third',
} as SelectedItem;
render(<TwoLevelDropdown {...props} />);
expect(screen.queryByText(title)).toBeNull();
screen.getByText(/first/);
screen.getByText(/second/);
screen.getByText(/third/);
});
it('Two-level dropdown toggle behavior', async () => {
render(<TwoLevelDropdown {...generateProps()} />);
expect(screen.queryByText('first')).toBeNull();
// Display the dropdown
fireEvent.click(screen.getByText(title));
screen.getByText('first');
// Hide the dropdown
fireEvent.click(screen.getByText(title));
expect(screen.queryByText('first')).toBeNull();
// Display the dropdown again
fireEvent.click(screen.getByText(title));
screen.getByText('first');
// Click on dropdown text (not button) does not close dropdown
fireEvent.click(screen.getByText('first'));
screen.getByText('first');
// Click outside closes the dropdown
fireEvent.click(document.body);
expect(screen.queryByText('first')).toBeNull();
});
it('Two-level dropdown sub items display', async () => {
render(<TwoLevelDropdown {...generateProps()} />);
fireEvent.click(screen.getByText(title));
// First dropdown item
expect(screen.queryByText('second')).toBeNull();
fireEvent.mouseEnter(screen.getByText('first'));
screen.getByText('second');
fireEvent.mouseLeave(screen.getByText('first'));
expect(screen.queryByText('second')).toBeNull();
// Second dropdown item
expect(screen.queryByText(/sixth/)).toBeNull();
fireEvent.mouseEnter(screen.getByText('fifth'));
screen.getByText(/sixth/);
fireEvent.mouseLeave(screen.getByText('fifth'));
expect(screen.queryByText(/sixth/)).toBeNull();
});
it('Two-level dropdown sub item select no secondary name', async () => {
render(<TwoLevelDropdown {...generateProps()} />);
fireEvent.click(screen.getByText(title));
fireEvent.mouseEnter(screen.getByText('first'));
fireEvent.click(screen.getByText('second'));
expect(setSelectedItem).toHaveBeenCalledWith({ itemName: 'first', subItemName: 'second' });
});
it('Two-level dropdown sub item select with secondary name', async () => {
render(<TwoLevelDropdown {...generateProps()} />);
fireEvent.click(screen.getByText(title));
fireEvent.mouseEnter(screen.getByText('first'));
fireEvent.click(screen.getByText(/third/));
expect(setSelectedItem).toHaveBeenCalledWith({
itemName: 'first',
subItemName: 'third',
subItemSecondaryName: 'fourth',
});
});
});
| 241 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/MinioArtifactPreview.test.tsx | /*
* Copyright 2019-2020 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import MinioArtifactPreview from './MinioArtifactPreview';
import React from 'react';
import TestUtils from '../TestUtils';
import { act, render } from '@testing-library/react';
import { Apis } from '../lib/Apis';
describe('MinioArtifactPreview', () => {
const readFile = jest.spyOn(Apis, 'readFile');
beforeEach(() => {
jest.resetAllMocks();
readFile.mockResolvedValue('preview ...');
});
it('handles undefined artifact', () => {
const { container } = render(<MinioArtifactPreview value={undefined} />);
expect(container).toMatchInlineSnapshot(`<div />`);
});
it('handles null artifact', () => {
const { container } = render(<MinioArtifactPreview value={null as any} />);
expect(container).toMatchInlineSnapshot(`<div />`);
});
it('handles empty artifact', () => {
const { container } = render(<MinioArtifactPreview value={{} as any} />);
expect(container).toMatchInlineSnapshot(`<div />`);
});
it('handles invalid artifact: no bucket', () => {
const s3Artifact = {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: '',
endpoint: 'minio.kubeflow',
key: 'bar',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
};
const { container } = render(<MinioArtifactPreview value={s3Artifact} />);
expect(container).toMatchInlineSnapshot(`<div />`);
});
it('handles invalid artifact: no key', () => {
const s3Artifact = {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: 'foo',
endpoint: 'minio.kubeflow',
key: '',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
};
const { container } = render(<MinioArtifactPreview value={s3Artifact} />);
expect(container).toMatchInlineSnapshot(`<div />`);
});
it('handles string value', () => {
const { container } = render(<MinioArtifactPreview value='teststring' />);
expect(container).toMatchInlineSnapshot(`
<div>
teststring
</div>
`);
});
it('handles boolean value', () => {
const { container } = render(<MinioArtifactPreview value={false as any} />);
expect(container).toMatchInlineSnapshot(`
<div>
false
</div>
`);
});
it('handles s3 artifact', async () => {
const s3Artifact = {
key: 'bar',
s3Bucket: {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: 'foo',
endpoint: 's3.amazonaws.com',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
},
};
const { container } = render(<MinioArtifactPreview value={s3Artifact} />);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="root"
>
<div
class="topDiv"
>
<a
class="link"
href="artifacts/s3/foo/bar"
rel="noopener"
target="_blank"
title="s3://foo/bar"
>
s3://foo/bar
</a>
<span
class="separater"
/>
<a
class="link viewLink"
href="artifacts/get?source=s3&bucket=foo&key=bar"
rel="noopener"
target="_blank"
>
View All
</a>
</div>
<div
class="preview"
>
<small>
<pre>
preview ...
</pre>
</small>
</div>
</div>
</div>
`);
});
it('handles minio artifact', async () => {
const minioArtifact = {
key: 'bar',
s3Bucket: {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: 'foo',
endpoint: 'minio.kubeflow',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
},
};
const container = document.body.appendChild(document.createElement('div'));
await act(async () => {
render(<MinioArtifactPreview value={minioArtifact} />, { container });
});
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="root"
>
<div
class="topDiv"
>
<a
class="link"
href="artifacts/minio/foo/bar"
rel="noopener"
target="_blank"
title="minio://foo/bar"
>
minio://foo/bar
</a>
<span
class="separater"
/>
<a
class="link viewLink"
href="artifacts/get?source=minio&bucket=foo&key=bar"
rel="noopener"
target="_blank"
>
View All
</a>
</div>
<div
class="preview"
>
<small>
<pre>
preview ...
</pre>
</small>
</div>
</div>
</div>
`);
});
it('handles artifact with namespace', async () => {
const minioArtifact = {
key: 'bar',
s3Bucket: {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: 'foo',
endpoint: 'minio.kubeflow',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
},
};
const { container } = render(
<MinioArtifactPreview value={minioArtifact} namespace='namespace' />,
);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="root"
>
<div
class="topDiv"
>
<a
class="link"
href="artifacts/minio/foo/bar?namespace=namespace"
rel="noopener"
target="_blank"
title="minio://foo/bar"
>
minio://foo/bar
</a>
<span
class="separater"
/>
<a
class="link viewLink"
href="artifacts/get?source=minio&namespace=namespace&bucket=foo&key=bar"
rel="noopener"
target="_blank"
>
View All
</a>
</div>
<div
class="preview"
>
<small>
<pre>
preview ...
</pre>
</small>
</div>
</div>
</div>
`);
});
it('handles artifact cleanly even when fetch fails', async () => {
const minioArtifact = {
key: 'bar',
s3Bucket: {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: 'foo',
endpoint: 'minio.kubeflow',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
},
};
readFile.mockRejectedValue('unknown error');
const { container } = render(<MinioArtifactPreview value={minioArtifact} />);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="root"
>
<div
class="topDiv"
>
<a
class="link"
href="artifacts/minio/foo/bar"
rel="noopener"
target="_blank"
title="minio://foo/bar"
>
minio://foo/bar
</a>
<span
class="separater"
/>
<a
class="link viewLink"
href="artifacts/get?source=minio&bucket=foo&key=bar"
rel="noopener"
target="_blank"
>
View All
</a>
</div>
</div>
</div>
`);
});
it('handles artifact that previews fully', async () => {
const minioArtifact = {
key: 'bar',
s3Bucket: {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: 'foo',
endpoint: 'minio.kubeflow',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
},
};
const data = `012\n345\n678\n910`;
readFile.mockResolvedValue(data);
const { container, queryByText } = render(
<MinioArtifactPreview value={minioArtifact} maxbytes={data.length} />,
);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="root"
>
<div
class="topDiv"
>
<a
class="link"
href="artifacts/minio/foo/bar"
rel="noopener"
target="_blank"
title="minio://foo/bar"
>
minio://foo/bar
</a>
<span
class="separater"
/>
<a
class="link viewLink"
href="artifacts/get?source=minio&bucket=foo&key=bar"
rel="noopener"
target="_blank"
>
View All
</a>
</div>
<div
class="preview"
>
<small>
<pre>
012
345
678
910
</pre>
</small>
</div>
</div>
</div>
`);
});
it('handles artifact that previews with maxlines', async () => {
const minioArtifact = {
key: 'bar',
s3Bucket: {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: 'foo',
endpoint: 'minio.kubeflow',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
},
};
const data = `012\n345\n678\n910`;
readFile.mockResolvedValue(data);
const { container, queryByText } = render(
<MinioArtifactPreview value={minioArtifact} maxbytes={data.length} maxlines={2} />,
);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="root"
>
<div
class="topDiv"
>
<a
class="link"
href="artifacts/minio/foo/bar"
rel="noopener"
target="_blank"
title="minio://foo/bar"
>
minio://foo/bar
</a>
<span
class="separater"
/>
<a
class="link viewLink"
href="artifacts/get?source=minio&bucket=foo&key=bar"
rel="noopener"
target="_blank"
>
View All
</a>
</div>
<div
class="preview"
>
<small>
<pre>
012
345
...
</pre>
</small>
</div>
</div>
</div>
`);
expect(queryByText('View All')).toBeTruthy();
});
it('handles artifact that previews with maxbytes', async () => {
const minioArtifact = {
key: 'bar',
s3Bucket: {
accessKeySecret: { key: 'accesskey', optional: false, name: 'minio' },
bucket: 'foo',
endpoint: 'minio.kubeflow',
secretKeySecret: { key: 'secretkey', optional: false, name: 'minio' },
},
};
const data = `012\n345\n678\n910`;
readFile.mockResolvedValue(data);
const { container, queryByText } = render(
<MinioArtifactPreview value={minioArtifact} maxbytes={data.length - 5} />,
);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<div
class="root"
>
<div
class="topDiv"
>
<a
class="link"
href="artifacts/minio/foo/bar"
rel="noopener"
target="_blank"
title="minio://foo/bar"
>
minio://foo/bar
</a>
<span
class="separater"
/>
<a
class="link viewLink"
href="artifacts/get?source=minio&bucket=foo&key=bar"
rel="noopener"
target="_blank"
>
View All
</a>
</div>
<div
class="preview"
>
<small>
<pre>
012
345
67
...
</pre>
</small>
</div>
</div>
</div>
`);
expect(queryByText('View All')).toBeTruthy();
});
});
| 242 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/SidePanel.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Button from '@material-ui/core/Button';
import CircularProgress from '@material-ui/core/CircularProgress';
import CloseIcon from '@material-ui/icons/Close';
import Resizable from 're-resizable';
import Slide from '@material-ui/core/Slide';
import { color, commonCss, zIndex } from '../Css';
import { stylesheet } from 'typestyle';
const css = stylesheet({
closeButton: {
color: color.inactive,
margin: 15,
minHeight: 0,
minWidth: 0,
padding: 0,
},
nodeName: {
flexGrow: 1,
textAlign: 'center',
},
sidepane: {
backgroundColor: color.background,
borderLeft: 'solid 1px #ddd',
bottom: 0,
display: 'flex',
flexFlow: 'column',
position: 'absolute !important' as any,
right: 0,
top: 0,
zIndex: zIndex.SIDE_PANEL,
},
});
interface SidePanelProps {
isBusy?: boolean;
isOpen: boolean;
onClose: () => void;
title: string;
defaultWidth?: string | number;
}
class SidePanel extends React.Component<SidePanelProps> {
public render(): JSX.Element {
const { isBusy, isOpen, onClose, title, defaultWidth } = this.props;
return (
<Slide in={isOpen} direction='left'>
<Resizable
className={css.sidepane}
defaultSize={{ width: defaultWidth ? defaultWidth : '70%' }}
maxWidth='90%'
minWidth={100}
enable={{
bottom: false,
bottomLeft: false,
bottomRight: false,
left: true,
right: false,
top: false,
topLeft: false,
topRight: false,
}}
>
{isOpen && (
<div className={commonCss.page}>
<div className={commonCss.flex}>
<Button aria-label='close' className={css.closeButton} onClick={onClose}>
<CloseIcon />
</Button>
<div className={css.nodeName}>{title}</div>
</div>
<div className={commonCss.page}>
{isBusy === true && (
<CircularProgress size={30} className={commonCss.absoluteCenter} />
)}
<div className={commonCss.page}>{this.props.children}</div>
</div>
</div>
)}
</Resizable>
</Slide>
);
}
}
export default SidePanel;
| 243 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PodYaml.tsx | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as JsYaml from 'js-yaml';
import React from 'react';
import { Apis, JSONObject } from 'src/lib/Apis';
import { serviceErrorToString } from 'src/lib/Utils';
import Banner from './Banner';
import Editor from './Editor';
async function getPodYaml(name: string, namespace: string): Promise<string> {
const response = await Apis.getPodInfo(name, namespace);
return JsYaml.safeDump(reorderPodJson(response), { skipInvalid: true });
}
export const PodInfo: React.FC<{ name: string; namespace: string }> = ({ name, namespace }) => {
return (
<PodYaml
name={name}
namespace={namespace}
errorMessage='Failed to retrieve pod info. Possible reasons include cluster autoscaling, pod preemption or pod cleaned up by time to live configuration'
getYaml={getPodYaml}
/>
);
};
async function getPodEventsYaml(name: string, namespace: string): Promise<string> {
const response = await Apis.getPodEvents(name, namespace);
return JsYaml.safeDump(response, { skipInvalid: true });
}
export const PodEvents: React.FC<{
name: string;
namespace: string;
}> = ({ name, namespace }) => {
return (
<PodYaml
name={name}
namespace={namespace}
errorMessage='Failed to retrieve pod events. Possible reasons include cluster autoscaling, pod preemption or pod cleaned up by time to live configuration'
getYaml={getPodEventsYaml}
/>
);
};
const PodYaml: React.FC<{
name: string;
namespace: string;
errorMessage: string;
getYaml: (name: string, namespace: string) => Promise<string>;
}> = ({ name, namespace, getYaml, errorMessage }) => {
const [yaml, setYaml] = React.useState<string | undefined>(undefined);
const [error, setError] = React.useState<
| {
message: string;
additionalInfo: string;
}
| undefined
>(undefined);
const [refreshes, setRefresh] = React.useState(0);
React.useEffect(() => {
let aborted = false;
async function load() {
setYaml(undefined);
setError(undefined);
try {
const yaml = await getYaml(name, namespace);
if (!aborted) {
setYaml(yaml);
}
} catch (err) {
if (!aborted) {
setError({
message: errorMessage,
additionalInfo: await serviceErrorToString(err),
});
}
}
}
load();
return () => {
aborted = true;
};
}, [name, namespace, refreshes, getYaml, errorMessage]); // When refreshes change, request is fetched again.
return (
<>
{error && (
<Banner
message={error.message}
mode='warning'
additionalInfo={error.additionalInfo}
// Increases refresh counter, so it will automatically trigger a refetch.
refresh={() => setRefresh(refreshes => refreshes + 1)}
/>
)}
{!error && yaml && (
<Editor
value={yaml || ''}
height='100%'
width='100%'
mode='yaml'
theme='github'
editorProps={{ $blockScrolling: true }}
readOnly={true}
highlightActiveLine={true}
showGutter={true}
/>
)}
</>
);
};
function reorderPodJson(jsonData: JSONObject): JSONObject {
const orderedData = { ...jsonData };
if (jsonData.spec) {
// Deleting spec property and add it again moves spec to the last property in the JSON object.
delete orderedData.spec;
orderedData.spec = jsonData.spec;
}
return orderedData;
}
export const TEST_ONLY = {
PodYaml,
};
| 244 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/ResourceInfo.test.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { ResourceInfo, ResourceType } from './ResourceInfo';
import { getByTestId, render, screen } from '@testing-library/react';
import { Artifact, Value } from 'src/third_party/mlmd';
import { Struct } from 'google-protobuf/google/protobuf/struct_pb';
describe('ResourceInfo', () => {
it('renders metrics artifact', async () => {
const metrics = new Artifact();
metrics.setState(Artifact.State.LIVE);
metrics.getCustomPropertiesMap().set('name', new Value().setStringValue('metrics'));
metrics.getCustomPropertiesMap().set(
'confidenceMetrics',
new Value().setStructValue(
Struct.fromJavaScript({
list: [
{
confidenceThreshold: 2,
falsePositiveRate: 0,
recall: 0,
},
{
confidenceThreshold: 1,
falsePositiveRate: 0,
recall: 0.33962264150943394,
},
{
confidenceThreshold: 0.9,
falsePositiveRate: 0,
recall: 0.6037735849056604,
},
],
}),
),
);
render(
<ResourceInfo
resourceType={ResourceType.ARTIFACT}
resource={metrics}
typeName='System.ClassificationMetrics'
/>,
);
expect(screen.getByRole('heading', { level: 1 }).textContent).toEqual(
'System.ClassificationMetrics (Live)',
);
expect(screen.getAllByRole('heading', { level: 2 }).map(h => h.textContent))
.toMatchInlineSnapshot(`
Array [
"Properties",
"Custom Properties",
]
`);
const keyEquals = (key: string) => (property: HTMLElement) => {
return getByTestId(property, 'resource-info-property-key').textContent === key;
};
function value(property: HTMLElement): HTMLElement {
return getByTestId(property, 'resource-info-property-value');
}
const nameProperty = screen.getAllByTestId('resource-info-property').find(keyEquals('name'));
expect(nameProperty).toBeTruthy();
expect(value(nameProperty!).textContent).toEqual('metrics');
const confidenceMetricsProperty = screen
.getAllByTestId('resource-info-property')
.find(keyEquals('confidenceMetrics'));
expect(value(confidenceMetricsProperty!).children).toMatchInlineSnapshot(`
HTMLCollection [
<pre>
[
{
"confidenceThreshold": 2,
"falsePositiveRate": 0,
"recall": 0
},
{
"confidenceThreshold": 1,
"falsePositiveRate": 0,
"recall": 0.33962264150943394
},
{
"confidenceThreshold": 0.9,
"falsePositiveRate": 0,
"recall": 0.6037735849056604
}
]
</pre>,
]
`);
});
});
| 245 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Banner.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import ErrorIcon from '@material-ui/icons/Error';
import WarningIcon from '@material-ui/icons/Warning';
import InfoIcon from '@material-ui/icons/Info';
import { classes, stylesheet } from 'typestyle';
import { color, commonCss, spacing } from '../Css';
export type Mode = 'error' | 'warning' | 'info';
export const css = stylesheet({
banner: {
border: `1px solid ${color.divider}`,
boxSizing: 'border-box',
justifyContent: 'space-between',
margin: spacing.units(-1),
minHeight: '50px',
padding: spacing.units(-4),
},
bannerLeftAlign: {
marginLeft: 0,
},
button: {
color: color.secondaryText,
maxHeight: '32px',
minWidth: '75px',
},
detailsButton: {
backgroundColor: color.background,
},
icon: {
height: '18px',
padding: spacing.units(-4),
width: '18px',
},
message: {
alignItems: 'center',
display: 'flex',
},
refreshButton: {
backgroundColor: color.background,
},
troubleShootingLink: {
alignItems: 'center',
color: color.theme,
fontWeight: 'bold',
padding: spacing.units(-4),
},
});
export interface BannerProps {
additionalInfo?: string;
message?: string;
mode?: Mode;
showTroubleshootingGuideLink?: boolean;
refresh?: () => void;
isLeftAlign?: boolean;
}
interface BannerState {
dialogOpen: boolean;
}
class Banner extends React.Component<BannerProps, BannerState> {
constructor(props: any) {
super(props);
this.state = {
dialogOpen: false,
};
}
public render(): JSX.Element {
// Default to error styles.
let bannerModeCss = stylesheet({
mode: { backgroundColor: color.errorBg, color: color.errorText },
});
let bannerIcon = <ErrorIcon className={css.icon} />;
let dialogTitle = 'An error occurred';
let showTroubleshootingGuideLink = false;
let showRefreshButton = true;
let isLeftAlign = this.props.isLeftAlign || false;
switch (this.props.mode) {
case 'error':
bannerModeCss = stylesheet({
mode: { backgroundColor: color.errorBg, color: color.errorText },
});
bannerIcon = <ErrorIcon className={css.icon} />;
dialogTitle = 'An error occurred';
showTroubleshootingGuideLink = this.props.showTroubleshootingGuideLink || false;
break;
case 'warning':
bannerModeCss = stylesheet({
mode: { backgroundColor: color.warningBg, color: color.warningText },
});
bannerIcon = <WarningIcon className={css.icon} />;
dialogTitle = 'Warning';
break;
case 'info':
bannerModeCss = stylesheet({
mode: { backgroundColor: color.infoBg, color: color.infoText },
});
bannerIcon = <InfoIcon className={css.icon} />;
dialogTitle = 'Info';
showRefreshButton = false;
break;
default:
// Already set defaults above.
break;
}
return (
<div
className={classes(
commonCss.flex,
css.banner,
isLeftAlign && css.bannerLeftAlign,
bannerModeCss.mode,
)}
>
<div className={css.message}>
{bannerIcon}
{this.props.message}
</div>
<div className={commonCss.flex}>
{showTroubleshootingGuideLink && (
<a
className={css.troubleShootingLink}
href='https://www.kubeflow.org/docs/pipelines/troubleshooting'
>
Troubleshooting guide
</a>
)}
{this.props.additionalInfo && (
<Button
className={classes(css.button, css.detailsButton)}
onClick={this._showAdditionalInfo.bind(this)}
>
Details
</Button>
)}
{showRefreshButton && this.props.refresh && (
<Button
className={classes(css.button, css.refreshButton)}
onClick={this._refresh.bind(this)}
>
Refresh
</Button>
)}
</div>
{this.props.additionalInfo && (
<Dialog open={this.state.dialogOpen} onClose={this._dialogClosed.bind(this)}>
<DialogTitle>{dialogTitle}</DialogTitle>
<DialogContent className={commonCss.prewrap}>{this.props.additionalInfo}</DialogContent>
<DialogActions>
<Button id='dismissDialogBtn' onClick={this._dialogClosed.bind(this)}>
Dismiss
</Button>
</DialogActions>
</Dialog>
)}
</div>
);
}
private _dialogClosed(): void {
this.setState({ dialogOpen: false });
}
private _showAdditionalInfo(): void {
this.setState({ dialogOpen: true });
}
private _refresh(): void {
this.props.refresh!();
}
}
export default Banner;
| 246 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Router.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { shallow, mount } from 'enzyme';
import Router, { RouteConfig } from './Router';
import { Router as ReactRouter } from 'react-router';
import { Page } from '../pages/Page';
import { ToolbarProps } from './Toolbar';
import { createMemoryHistory } from 'history';
describe('Router', () => {
it('initial render', () => {
const tree = shallow(<Router />);
expect(tree).toMatchSnapshot();
});
it('does not share state between pages', () => {
class ApplePage extends Page<{}, {}> {
getInitialToolbarState(): ToolbarProps {
return {
pageTitle: 'Apple',
actions: {},
breadcrumbs: [],
};
}
async refresh() {}
render() {
return <div>apple</div>;
}
}
const configs: RouteConfig[] = [
{
path: '/apple',
Component: ApplePage,
},
{
path: '/pear',
Component: () => {
return <div>pear</div>;
},
},
];
const history = createMemoryHistory({
initialEntries: ['/apple'],
});
const tree = mount(
<ReactRouter history={history}>
<Router configs={configs} />
</ReactRouter>,
);
expect(tree.getDOMNode().querySelector('[data-testid=page-title]')!.textContent).toEqual(
'Apple',
);
// When visiting the second page, page title should be reset automatically.
history.push('/pear');
expect(tree.getDOMNode().querySelector('[data-testid=page-title]')!.textContent).toEqual('');
});
});
| 247 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PrivateSharedSelector.tsx | /*
* Copyright 2023 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { classes } from 'typestyle';
import Radio from '@material-ui/core/Radio';
import Tooltip from '@material-ui/core/Tooltip';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import { commonCss, padding } from '../Css';
import { PipelineTabsHeaders } from '../pages/PrivateAndSharedPipelines';
export interface PrivateSharedSelectorProps {
onChange: (isPrivate: boolean) => void;
}
export enum PipelineButtonTooltips {
PRIVATE = 'Only people who have access to this namespace will be able to view and use this pipeline.',
SHARED = 'Everyone in your organization will be able to view and use this pipeline.',
}
const PrivateSharedSelector: React.FC<PrivateSharedSelectorProps> = (props): JSX.Element | null => {
const [namespacedPipeline, setNamespacedPipeline] = React.useState(true);
React.useEffect(() => {
props.onChange(namespacedPipeline);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [namespacedPipeline]);
return (
<React.Fragment>
<div>Select if the new pipeline will be private or shared.</div>
<div className={classes(commonCss.flex, padding(10, 'b'))}>
<Tooltip title={PipelineButtonTooltips.PRIVATE} placement='top-start'>
<FormControlLabel
id='createNewPrivatePipelineBtn'
label={PipelineTabsHeaders.PRIVATE}
checked={namespacedPipeline === true}
control={<Radio color='primary' />}
onChange={() => {
setNamespacedPipeline(true);
}}
/>
</Tooltip>
<Tooltip title={PipelineButtonTooltips.SHARED} placement='top-start'>
<FormControlLabel
id='createNewSharedPipelineBtn'
label={PipelineTabsHeaders.SHARED}
checked={namespacedPipeline === false}
control={<Radio color='primary' />}
onChange={() => {
setNamespacedPipeline(false);
}}
/>
</Tooltip>
</div>
</React.Fragment>
);
};
export default PrivateSharedSelector;
| 248 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Banner.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { shallow } from 'enzyme';
import Banner, { css } from './Banner';
describe('Banner', () => {
it('defaults to error mode', () => {
const tree = shallow(<Banner message={'Some message'} />);
expect(tree).toMatchSnapshot();
});
it('uses error mode when instructed', () => {
const tree = shallow(<Banner message={'Some message'} mode={'error'} />);
expect(tree).toMatchSnapshot();
});
it('uses warning mode when instructed', () => {
const tree = shallow(<Banner message={'Some message'} mode={'warning'} />);
expect(tree).toMatchSnapshot();
});
it('uses info mode when instructed', () => {
const tree = shallow(<Banner message={'Some message'} mode={'info'} />);
expect(tree).toMatchSnapshot();
});
it('shows "Details" button and has dialog when there is additional info', () => {
const tree = shallow(<Banner message={'Some message'} additionalInfo={'More info'} />);
expect(tree).toMatchSnapshot();
});
it('shows "Refresh" button when passed a refresh function', () => {
const tree = shallow(
<Banner
message={'Some message'}
refresh={() => {
/* do nothing */
}}
/>,
);
expect(tree).toMatchSnapshot();
});
it('does not show "Refresh" button if mode is "info"', () => {
const tree = shallow(
<Banner
message={'Some message'}
mode={'info'}
refresh={() => {
/* do nothing */
}}
/>,
);
expect(tree.findWhere(el => el.text() === 'Refresh').exists()).toEqual(false);
});
it('shows troubleshooting link instructed by prop', () => {
const tree = shallow(
<Banner message='Some message' mode='error' showTroubleshootingGuideLink={true} />,
);
expect(tree).toMatchInlineSnapshot(`
<div
className="flex banner mode"
>
<div
className="message"
>
<pure(ErrorIcon)
className="icon"
/>
Some message
</div>
<div
className="flex"
>
<a
className="troubleShootingLink"
href="https://www.kubeflow.org/docs/pipelines/troubleshooting"
>
Troubleshooting guide
</a>
</div>
</div>
`);
});
it('does not show troubleshooting link if warning', () => {
const tree = shallow(
<Banner message='Some message' mode='warning' showTroubleshootingGuideLink={true} />,
);
expect(tree.findWhere(el => el.text() === 'Troubleshooting guide').exists()).toEqual(false);
});
it('opens details dialog when button is clicked', () => {
const tree = shallow(<Banner message='hello' additionalInfo='world' />);
tree
.find('WithStyles(Button)')
.at(0)
.simulate('click');
expect(tree.state()).toHaveProperty('dialogOpen', true);
});
it('closes details dialog when cancel button is clicked', () => {
const tree = shallow(<Banner message='hello' additionalInfo='world' />);
tree
.find('WithStyles(Button)')
.at(0)
.simulate('click');
expect(tree.state()).toHaveProperty('dialogOpen', true);
tree.find('#dismissDialogBtn').simulate('click');
expect(tree.state()).toHaveProperty('dialogOpen', false);
});
it('calls refresh callback', () => {
const spy = jest.fn();
const tree = shallow(<Banner message='hello' refresh={spy} />);
tree
.find('.' + css.refreshButton)
.at(0)
.simulate('click');
expect(spy).toHaveBeenCalled();
});
});
| 249 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Toolbar.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { shallow } from 'enzyme';
import { createBrowserHistory, createMemoryHistory } from 'history';
import Toolbar, { ToolbarActionMap } from './Toolbar';
import HelpIcon from '@material-ui/icons/Help';
import InfoIcon from '@material-ui/icons/Info';
const action1 = jest.fn();
const action2 = jest.fn();
const actions: ToolbarActionMap = {
action1: {
action: action1,
disabledTitle: 'test disabled title',
icon: HelpIcon,
id: 'test id',
title: 'test title',
tooltip: 'test tooltip',
},
action2: {
action: action2,
disabled: true,
disabledTitle: 'test disabled title2',
icon: InfoIcon,
id: 'test id2',
title: 'test title2',
tooltip: 'test tooltip2',
},
};
const breadcrumbs = [
{
displayName: 'test display name',
href: '/some/test/path',
},
{
displayName: 'test display name2',
href: '/some/test/path2',
},
];
const history = createBrowserHistory({});
describe('Toolbar', () => {
beforeAll(() => {
history.push('/pipelines');
});
it('renders nothing when there are no breadcrumbs or actions', () => {
const tree = shallow(<Toolbar breadcrumbs={[]} actions={{}} history={history} pageTitle='' />);
expect(tree).toMatchSnapshot();
});
it('renders without breadcrumbs and a string page title', () => {
const tree = shallow(
<Toolbar breadcrumbs={[]} actions={actions} history={history} pageTitle='test page title' />,
);
expect(tree).toMatchSnapshot();
});
it('renders without breadcrumbs and a component page title', () => {
const tree = shallow(
<Toolbar
breadcrumbs={[]}
actions={actions}
history={history}
pageTitle={<div id='myComponent'>test page title</div>}
/>,
);
expect(tree).toMatchSnapshot();
});
it('renders without breadcrumbs and one action', () => {
const singleAction = {
action1: {
action: action1,
disabledTitle: 'test disabled title',
icon: HelpIcon,
id: 'test id',
title: 'test title',
tooltip: 'test tooltip',
},
};
const tree = shallow(
<Toolbar
breadcrumbs={[]}
actions={singleAction}
history={history}
pageTitle='test page title'
/>,
);
expect(tree).toMatchSnapshot();
});
it('renders without actions and one breadcrumb', () => {
const tree = shallow(
<Toolbar
breadcrumbs={[breadcrumbs[0]]}
actions={{}}
history={history}
pageTitle='test page title'
/>,
);
expect(tree).toMatchSnapshot();
});
it('renders without actions, one breadcrumb, and a page name', () => {
const tree = shallow(
<Toolbar
breadcrumbs={[breadcrumbs[0]]}
actions={{}}
history={history}
pageTitle='test page title'
/>,
);
expect(tree).toMatchSnapshot();
});
it('renders without breadcrumbs and two actions', () => {
const tree = shallow(
<Toolbar breadcrumbs={[]} actions={actions} history={history} pageTitle='test page title' />,
);
expect(tree).toMatchSnapshot();
});
it('fires the right action function when button is clicked', () => {
const tree = shallow(
<Toolbar breadcrumbs={[]} actions={actions} history={history} pageTitle='test page title' />,
);
tree
.find('BusyButton')
.at(0)
.simulate('click');
expect(action1).toHaveBeenCalled();
action1.mockClear();
});
it('renders outlined action buttons', () => {
const outlinedActions = {
action1: {
action: jest.fn(),
id: 'test outlined id',
outlined: true,
title: 'test outlined title',
tooltip: 'test outlined tooltip',
},
};
const tree = shallow(
<Toolbar
breadcrumbs={breadcrumbs}
actions={outlinedActions}
pageTitle=''
history={history}
/>,
);
expect(tree).toMatchSnapshot();
});
it('renders primary action buttons', () => {
const primaryActions = {
action1: {
action: jest.fn(),
id: 'test primary id',
primary: true,
title: 'test primary title',
tooltip: 'test primary tooltip',
},
};
const tree = shallow(
<Toolbar breadcrumbs={breadcrumbs} actions={primaryActions} pageTitle='' history={history} />,
);
expect(tree).toMatchSnapshot();
});
it('renders primary action buttons without outline, even if outline is true', () => {
const outlinedPrimaryActions = {
action1: {
action: jest.fn(),
id: 'test id',
outlined: true,
primary: true,
title: 'test title',
tooltip: 'test tooltip',
},
};
const tree = shallow(
<Toolbar
breadcrumbs={breadcrumbs}
actions={outlinedPrimaryActions}
pageTitle=''
history={history}
/>,
);
expect(tree).toMatchSnapshot();
});
it('renders with two breadcrumbs and two actions', () => {
const tree = shallow(
<Toolbar breadcrumbs={breadcrumbs} actions={actions} pageTitle='' history={history} />,
);
expect(tree).toMatchSnapshot();
});
it('disables the back button when there is no browser history', () => {
// This test uses createMemoryHistory because createBroweserHistory returns a singleton, and
// there is no way to clear its entries which this test requires.
const emptyHistory = createMemoryHistory();
const tree = shallow(
<Toolbar breadcrumbs={breadcrumbs} actions={actions} history={emptyHistory} pageTitle='' />,
);
expect(tree).toMatchSnapshot();
});
});
| 250 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/NewRunParametersV2.test.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'jest';
import React from 'react';
import { testBestPractices } from 'src/TestUtils';
import { CommonTestWrapper } from 'src/TestWrapper';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { ParameterType_ParameterTypeEnum } from 'src/generated/pipeline_spec/pipeline_spec';
import NewRunParametersV2 from 'src/components/NewRunParametersV2';
testBestPractices();
describe('NewRunParametersV2', () => {
it('shows parameters', () => {
const props = {
titleMessage: 'Specify parameters required by the pipeline',
specParameters: {
strParam: {
parameterType: ParameterType_ParameterTypeEnum.STRING,
defaultValue: 'string value',
},
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
defaultValue: 123,
},
boolParam: {
parameterType: ParameterType_ParameterTypeEnum.BOOLEAN,
defaultValue: true,
},
},
clonedRuntimeConfig: {},
};
render(<NewRunParametersV2 {...props} />);
screen.getByText('Run parameters');
screen.getByText('Specify parameters required by the pipeline');
screen.getByText('strParam - string');
screen.getByDisplayValue('string value');
screen.getByText('boolParam - boolean');
screen.getByDisplayValue('true');
screen.getByText('intParam - integer');
screen.getByDisplayValue('123');
});
it('edits parameters', () => {
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
strParam: {
parameterType: ParameterType_ParameterTypeEnum.STRING,
defaultValue: 'string value',
},
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
defaultValue: 123,
},
boolParam: {
parameterType: ParameterType_ParameterTypeEnum.BOOLEAN,
defaultValue: true,
},
},
clonedRuntimeConfig: {},
};
render(<NewRunParametersV2 {...props} />);
const strParam = screen.getByDisplayValue('string value');
fireEvent.change(strParam, { target: { value: 'new string' } });
expect(strParam.closest('input').value).toEqual('new string');
const intParam = screen.getByDisplayValue('123');
fireEvent.change(intParam, { target: { value: 999 } });
expect(intParam.closest('input').value).toEqual('999');
const boolParam = screen.getByDisplayValue('true');
fireEvent.change(boolParam, { target: { value: false } });
expect(boolParam.closest('input').value).toEqual('false');
});
it('call convertInput function for string type with default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
strParam: {
parameterType: ParameterType_ParameterTypeEnum.STRING,
defaultValue: 'string value',
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props}></NewRunParametersV2>);
const strParam = screen.getByDisplayValue('string value');
fireEvent.change(strParam, { target: { value: 'new string' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
strParam: 'new string',
});
screen.getByDisplayValue('new string');
});
it('call convertInput function for string type without default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
strParam: {
parameterType: ParameterType_ParameterTypeEnum.STRING,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const strParam = screen.getByLabelText('strParam - string');
fireEvent.change(strParam, { target: { value: 'new string' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
strParam: 'new string',
});
screen.getByDisplayValue('new string');
});
it('call convertInput function for boolean type with default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
boolParam: {
parameterType: ParameterType_ParameterTypeEnum.BOOLEAN,
defaultValue: true,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const boolParam = screen.getByDisplayValue('true');
fireEvent.change(boolParam, { target: { value: 'false' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
boolParam: false,
});
screen.getByDisplayValue('false');
});
it('call convertInput function for boolean type without default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
boolParam: {
parameterType: ParameterType_ParameterTypeEnum.BOOLEAN,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const boolParam = screen.getByLabelText('boolParam - boolean');
fireEvent.change(boolParam, { target: { value: 'true' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
boolParam: true,
});
screen.getByDisplayValue('true');
});
it('call convertInput function for boolean type with invalid input (Uppercase)', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
boolParam: {
parameterType: ParameterType_ParameterTypeEnum.BOOLEAN,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const boolParam = screen.getByLabelText('boolParam - boolean');
fireEvent.change(boolParam, { target: { value: 'True' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
boolParam: null,
});
screen.getByDisplayValue('True');
});
it('call convertInput function for integer type with default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
defaultValue: 123,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const intParam = screen.getByDisplayValue('123');
fireEvent.change(intParam, { target: { value: '456' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
intParam: 456,
});
screen.getByDisplayValue('456');
});
it('call convertInput function for integer type without default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const intParam = screen.getByLabelText('intParam - integer');
fireEvent.change(intParam, { target: { value: '789' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
intParam: 789,
});
screen.getByDisplayValue('789');
});
it('call convertInput function for integer type with invalid input (float)', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const intParam = screen.getByLabelText('intParam - integer');
fireEvent.change(intParam, { target: { value: '7.89' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
intParam: null,
});
screen.getByDisplayValue('7.89');
});
it('call convertInput function for double type with default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
doubleParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_DOUBLE,
defaultValue: 1.23,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const doubleParam = screen.getByDisplayValue('1.23');
fireEvent.change(doubleParam, { target: { value: '4.56' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
doubleParam: 4.56,
});
screen.getByDisplayValue('4.56');
});
it('call convertInput function for double type without default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
doubleParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_DOUBLE,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const doubleParam = screen.getByLabelText('doubleParam - double');
fireEvent.change(doubleParam, { target: { value: '7.89' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
doubleParam: 7.89,
});
screen.getByDisplayValue('7.89');
});
it('call convertInput function for LIST type with default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
listParam: {
parameterType: ParameterType_ParameterTypeEnum.LIST,
defaultValue: [1, 2, 3],
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const listParam = screen.getByDisplayValue('[1,2,3]');
fireEvent.change(listParam, { target: { value: '[4,5,6]' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
listParam: [4, 5, 6],
});
screen.getByDisplayValue('[4,5,6]');
});
it('call convertInput function for LIST type without default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
listParam: {
parameterType: ParameterType_ParameterTypeEnum.LIST,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const listParam = screen.getByLabelText('listParam - list');
fireEvent.change(listParam, { target: { value: '[4,5,6]' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
listParam: [4, 5, 6],
});
screen.getByDisplayValue('[4,5,6]');
});
it('call convertInput function for LIST type with invalid input (invalid JSON form)', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
listParam: {
parameterType: ParameterType_ParameterTypeEnum.LIST,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const listParam = screen.getByLabelText('listParam - list');
fireEvent.change(listParam, { target: { value: '[4,5,6' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
listParam: null,
});
screen.getByDisplayValue('[4,5,6');
});
it('call convertInput function for STRUCT type with default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
structParam: {
parameterType: ParameterType_ParameterTypeEnum.STRUCT,
defaultValue: { A: 1, B: 2 },
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const structParam = screen.getByDisplayValue('{"A":1,"B":2}');
fireEvent.change(structParam, { target: { value: '{"C":3,"D":4}' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
structParam: { C: 3, D: 4 },
});
screen.getByDisplayValue('{"C":3,"D":4}');
});
it('call convertInput function for STRUCT type without default value', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
structParam: {
parameterType: ParameterType_ParameterTypeEnum.STRUCT,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const structParam = screen.getByLabelText('structParam - dict');
fireEvent.change(structParam, { target: { value: '{"A":1,"B":2}' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
structParam: { A: 1, B: 2 },
});
screen.getByDisplayValue('{"A":1,"B":2}');
});
it('call convertInput function for STRUCT type with invalid input (invalid JSON form)', () => {
const handleParameterChangeSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
structParam: {
parameterType: ParameterType_ParameterTypeEnum.STRUCT,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: handleParameterChangeSpy,
};
render(<NewRunParametersV2 {...props} />);
const structParam = screen.getByLabelText('structParam - dict');
fireEvent.change(structParam, { target: { value: '"A":1,"B":2' } });
expect(handleParameterChangeSpy).toHaveBeenCalledTimes(1);
expect(handleParameterChangeSpy).toHaveBeenLastCalledWith({
structParam: null,
});
screen.getByDisplayValue('"A":1,"B":2');
});
it('set input as valid type with valid default integer input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
defaultValue: 123,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
expect(setIsValidInputSpy).toHaveBeenCalledTimes(1);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(true);
screen.getByDisplayValue('123');
});
it('set input as invalid type with no default integer input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
expect(setIsValidInputSpy).toHaveBeenCalledTimes(1);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
});
it('show error message for invalid integer input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const intParam = screen.getByLabelText('intParam - integer');
fireEvent.change(intParam, { target: { value: '123b' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
screen.getByDisplayValue('123b');
screen.getByText('Invalid input. This parameter should be in integer type');
});
it('show error message for missing integer input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
defaultValue: 123,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const intParam = screen.getByDisplayValue('123');
fireEvent.change(intParam, { target: { value: '' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
screen.getByText('Missing parameter.');
});
it('show error message for invalid boolean input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
boolParam: {
parameterType: ParameterType_ParameterTypeEnum.BOOLEAN,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const boolParam = screen.getByLabelText('boolParam - boolean');
fireEvent.change(boolParam, { target: { value: '123' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
screen.getByDisplayValue('123');
screen.getByText('Invalid input. This parameter should be in boolean type');
});
it('set input as valid type with valid boolean input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
boolParam: {
parameterType: ParameterType_ParameterTypeEnum.BOOLEAN,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const boolParam = screen.getByLabelText('boolParam - boolean');
fireEvent.change(boolParam, { target: { value: 'true' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(true);
screen.getByDisplayValue('true');
});
it('show error message for invalid double input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
doubleParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_DOUBLE,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const doubleParam = screen.getByLabelText('doubleParam - double');
fireEvent.change(doubleParam, { target: { value: '123b' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
screen.getByDisplayValue('123b');
screen.getByText('Invalid input. This parameter should be in double type');
});
it('show error message for invalid list input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
listParam: {
parameterType: ParameterType_ParameterTypeEnum.LIST,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const listParam = screen.getByLabelText('listParam - list');
fireEvent.change(listParam, { target: { value: '123' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
screen.getByDisplayValue('123');
screen.getByText('Invalid input. This parameter should be in list type');
});
it('show error message for invalid list input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
listParam: {
parameterType: ParameterType_ParameterTypeEnum.LIST,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const listParam = screen.getByLabelText('listParam - list');
fireEvent.change(listParam, { target: { value: '[1,2,3' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
screen.getByDisplayValue('[1,2,3');
screen.getByText('Invalid input. This parameter should be in list type');
});
it('show error message for invalid struct input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
structParam: {
parameterType: ParameterType_ParameterTypeEnum.STRUCT,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const structParam = screen.getByLabelText('structParam - dict');
fireEvent.change(structParam, { target: { value: '123' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
screen.getByDisplayValue('123');
screen.getByText('Invalid input. This parameter should be in dict type');
});
it('show error message for invalid struct input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
structParam: {
parameterType: ParameterType_ParameterTypeEnum.STRUCT,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const structParam = screen.getByLabelText('structParam - dict');
fireEvent.change(structParam, { target: { value: '[1,2,3]' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(false);
screen.getByDisplayValue('[1,2,3]');
screen.getByText('Invalid input. This parameter should be in dict type');
});
it('set input as valid type with valid struct input', () => {
const setIsValidInputSpy = jest.fn();
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
structParam: {
parameterType: ParameterType_ParameterTypeEnum.STRUCT,
},
},
clonedRuntimeConfig: {},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: setIsValidInputSpy,
};
render(<NewRunParametersV2 {...props} />);
const structParam = screen.getByLabelText('structParam - dict');
fireEvent.change(structParam, { target: { value: '{"A":1,"B":2}' } });
expect(setIsValidInputSpy).toHaveBeenCalledTimes(2);
expect(setIsValidInputSpy).toHaveBeenLastCalledWith(true);
screen.getByDisplayValue('{"A":1,"B":2}');
});
it('show pipeline root from cloned RuntimeConfig', () => {
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
},
strParam: {
parameterType: ParameterType_ParameterTypeEnum.STRING,
},
},
clonedRuntimeConfig: {
parameters: { intParam: 123, strParam: 'string_value' },
pipeline_root: 'gs://dummy_pipeline_root',
},
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: jest.fn(),
};
render(<NewRunParametersV2 {...props} />);
screen.getByDisplayValue('gs://dummy_pipeline_root');
});
it('shows parameters from cloned RuntimeConfig', () => {
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
},
strParam: {
parameterType: ParameterType_ParameterTypeEnum.STRING,
},
},
clonedRuntimeConfig: { parameters: { intParam: 123, strParam: 'string_value' } },
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: jest.fn(),
};
render(<NewRunParametersV2 {...props} />);
screen.getByDisplayValue('123');
screen.getByDisplayValue('string_value');
});
it('edits parameters filled by cloned RuntimeConfig', () => {
const props = {
titleMessage: 'default Title',
pipelineRoot: 'default pipelineRoot',
specParameters: {
intParam: {
parameterType: ParameterType_ParameterTypeEnum.NUMBER_INTEGER,
},
strParam: {
parameterType: ParameterType_ParameterTypeEnum.STRING,
},
},
clonedRuntimeConfig: { parameters: { intParam: 123, strParam: 'string_value' } },
handlePipelineRootChange: jest.fn(),
handleParameterChange: jest.fn(),
setIsValidInput: jest.fn(),
};
render(<NewRunParametersV2 {...props} />);
const intParam = screen.getByDisplayValue('123');
fireEvent.change(intParam, { target: { value: '456' } });
screen.getByDisplayValue('456');
const strParam = screen.getByDisplayValue('string_value');
fireEvent.change(strParam, { target: { value: 'new_string' } });
screen.getByDisplayValue('new_string');
});
it('does not display any text fields if there are no parameters', () => {
const { container } = render(
<CommonTestWrapper>
<NewRunParametersV2
titleMessage='Specify parameters required by the pipeline'
specParameters={{}}
clonedRuntimeConfig={{}}
></NewRunParametersV2>
</CommonTestWrapper>,
);
expect(container.querySelector('input').type).toEqual('checkbox');
});
});
| 251 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Graph.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as dagre from 'dagre';
import * as React from 'react';
import { classes, stylesheet } from 'typestyle';
import { fontsize, color, fonts, zIndex } from '../Css';
import { Constants } from '../lib/Constants';
import Tooltip from '@material-ui/core/Tooltip';
interface Segment {
angle: number;
length: number;
x1: number;
x2: number;
y1: number;
y2: number;
}
interface Edge {
color?: string;
isPlaceholder?: boolean;
from: string;
segments: Segment[];
to: string;
}
const css = stylesheet({
arrowHead: {
borderColor: color.grey + ' transparent transparent transparent',
borderStyle: 'solid',
borderWidth: '7px 6px 0 6px',
content: `''`,
position: 'absolute',
},
icon: {
padding: '5px 7px 0px 7px',
},
label: {
color: color.strong,
flexGrow: 1,
fontFamily: fonts.secondary,
fontSize: 13,
fontWeight: 500,
lineHeight: '16px',
overflow: 'hidden',
padding: 10,
textOverflow: 'ellipsis',
},
line: {
position: 'absolute',
},
node: {
$nest: {
'&:hover': {
borderColor: color.theme,
},
},
backgroundColor: color.background,
border: 'solid 1px #d6d6d6',
borderRadius: 3,
boxSizing: 'content-box',
color: '#124aa4',
cursor: 'pointer',
display: 'flex',
fontSize: fontsize.medium,
margin: 10,
position: 'absolute',
zIndex: zIndex.GRAPH_NODE,
},
nodeSelected: {
border: `solid 2px ${color.theme}`,
},
placeholderNode: {
margin: 10,
position: 'absolute',
// TODO: can this be calculated?
transform: 'translate(71px, 14px)',
},
root: {
backgroundColor: color.graphBg,
borderLeft: 'solid 1px ' + color.divider,
flexGrow: 1,
overflow: 'auto',
position: 'relative',
},
});
interface GraphProps {
graph: dagre.graphlib.Graph;
onClick?: (id: string) => void;
selectedNodeId?: string;
}
interface GraphState {
hoveredNode?: string;
}
interface GraphErrorBoundaryProps {
onError?: (message: string, additionalInfo: string) => void;
}
class GraphErrorBoundary extends React.Component<GraphErrorBoundaryProps> {
state = {
hasError: false,
};
componentDidCatch(error: Error): void {
const message = 'There was an error rendering the graph.';
const additionalInfo = `${message} This is likely a bug in Kubeflow Pipelines. Error message: '${error.message}'.`;
if (this.props.onError) {
this.props.onError(message, additionalInfo);
}
this.setState({
hasError: true,
});
}
render() {
return this.state.hasError ? <div className={css.root} /> : this.props.children;
}
}
export class Graph extends React.Component<GraphProps, GraphState> {
private LEFT_OFFSET = 100;
private TOP_OFFSET = 44;
private EDGE_THICKNESS = 2;
private EDGE_X_BUFFER = Math.round(Constants.NODE_WIDTH / 6);
constructor(props: any) {
super(props);
this.state = {};
}
public render(): JSX.Element | null {
const { graph } = this.props;
if (!graph.nodes().length) {
return null;
}
dagre.layout(graph);
const displayEdges: Edge[] = [];
// Creates the lines that constitute the edges connecting the graph.
graph.edges().forEach(edgeInfo => {
const edge = graph.edge(edgeInfo);
const segments: Segment[] = [];
if (edge.points.length > 1) {
for (let i = 1; i < edge.points.length; i++) {
let xStart = edge.points[i - 1].x;
let yStart = edge.points[i - 1].y;
let xEnd = edge.points[i].x;
let yEnd = edge.points[i].y;
const downwardPointingSegment = yStart <= yEnd;
// Adjustments made to the start of the first segment for each edge to ensure that it
// begins at the bottom of the source node and that there are at least EDGE_X_BUFFER
// pixels between it and the right and left side of the node.
// Note that these adjustments may cause edges to overlap with nodes since we are
// deviating from the explicit layout provided by dagre.
if (i === 1) {
const sourceNode = graph.node(edgeInfo.v);
if (!sourceNode) {
throw new Error(`Graph definition is invalid. Cannot get node by '${edgeInfo.v}'.`);
}
// Set the edge's first segment to start at the bottom or top of the source node.
yStart = downwardPointingSegment
? sourceNode.y + sourceNode.height / 2 - 3
: sourceNode.y - sourceNode.height / 2;
xStart = this._ensureXIsWithinNode(sourceNode, xStart);
}
const finalSegment = i === edge.points.length - 1;
// Adjustments made to the end of the final segment for each edge to ensure that it ends
// at the top of the destination node and that there are at least EDGE_X_BUFFER pixels
// between it and the right and left side of the node. The adjustments are only needed
// when there are multiple inbound edges as dagre seems to always layout a single inbound
// edge so that it terminates at the center-top of the destination node. For this reason,
// placeholder nodes do not need adjustments since they always have only a single inbound
// edge.
// Note that these adjustments may cause edges to overlap with nodes since we are
// deviating from the explicit layout provided by dagre.
if (finalSegment) {
const destinationNode = graph.node(edgeInfo.w);
// Placeholder nodes never need adjustment because they always have only a single
// incoming edge.
if (!destinationNode.isPlaceholder) {
// Set the edge's final segment to terminate at the top or bottom of the destination
// node.
yEnd = downwardPointingSegment
? destinationNode.y - this.TOP_OFFSET + 5
: destinationNode.y + destinationNode.height / 2 + 3;
xEnd = this._ensureXIsWithinNode(destinationNode, xEnd);
}
}
// For the final segment of the edge, if the segment is diagonal, split it into a diagonal
// and a vertical piece so that all edges terminate with a vertical segment.
if (finalSegment && xStart !== xEnd) {
const yHalf = (yStart + yEnd) / 2;
this._addDiagonalSegment(segments, xStart, yStart, xEnd, yHalf);
// Vertical segment
if (downwardPointingSegment) {
segments.push({
angle: 270,
length: yEnd - yHalf,
x1: xEnd - 5,
x2: xEnd,
y1: yHalf + 4,
y2: yEnd,
});
} else {
segments.push({
angle: 90,
length: yHalf - yEnd,
x1: xEnd - 5,
x2: xEnd,
y1: yHalf - 4,
y2: yEnd,
});
}
} else {
this._addDiagonalSegment(segments, xStart, yStart, xEnd, yEnd);
}
}
}
displayEdges.push({
color: edge.color,
from: edgeInfo.v,
isPlaceholder: edge.isPlaceholder,
segments,
to: edgeInfo.w,
});
});
const { hoveredNode } = this.state;
const highlightNode = this.props.selectedNodeId || hoveredNode;
return (
<div className={css.root}>
{graph
.nodes()
.map(id => Object.assign(graph.node(id), { id }))
.map((node, i) => (
<div
className={classes(
node.isPlaceholder ? css.placeholderNode : css.node,
'graphNode',
node.id === this.props.selectedNodeId ? css.nodeSelected : '',
)}
key={i}
onMouseEnter={() => {
if (!this.props.selectedNodeId) {
this.setState({ hoveredNode: node.id });
}
}}
onMouseLeave={() => {
if (this.state.hoveredNode === node.id) {
this.setState({ hoveredNode: undefined });
}
}}
onClick={() =>
!node.isPlaceholder && this.props.onClick && this.props.onClick(node.id)
}
style={{
backgroundColor: node.bgColor,
left: node.x,
maxHeight: node.height,
minHeight: node.height,
top: node.y,
transition: 'left 0.5s, top 0.5s',
width: node.width,
}}
>
{!node.isPlaceholder && (
<Tooltip title={node.label} enterDelay={300}>
<div className={css.label}>{node.label}</div>
</Tooltip>
)}
<div className={css.icon} style={{ background: node.statusColoring }}>
{node.icon}
</div>
</div>
))}
{displayEdges.map((edge, i) => {
const edgeColor = this._getEdgeColor(edge, highlightNode);
const lastSegment = edge.segments[edge.segments.length - 1];
return (
<div key={i}>
{edge.segments.map((segment, l) => (
<div
className={css.line}
key={l}
style={{
backgroundColor: edgeColor,
height: this.EDGE_THICKNESS,
left: segment.x1 + this.LEFT_OFFSET,
top: segment.y1 + this.TOP_OFFSET,
transform: `rotate(${segment.angle}deg)`,
transition: 'left 0.5s, top 0.5s',
width: segment.length,
}}
/>
))}
{/* Arrowhead */}
{!edge.isPlaceholder && lastSegment.x2 !== undefined && lastSegment.y2 !== undefined && (
<div
className={css.arrowHead}
style={{
borderTopColor: edgeColor,
left: lastSegment.x2 + this.LEFT_OFFSET - 6,
top: lastSegment.y2 + this.TOP_OFFSET - 3,
transform: `rotate(${lastSegment.angle + 90}deg)`,
}}
/>
)}
</div>
);
})}
</div>
);
}
private _addDiagonalSegment(
segments: Segment[],
xStart: number,
yStart: number,
xEnd: number,
yEnd: number,
): void {
const xMid = (xStart + xEnd) / 2;
// The + 0.5 at the end of 'length' helps fill out the elbows of the edges.
const length = Math.sqrt(Math.pow(xStart - xEnd, 2) + Math.pow(yStart - yEnd, 2)) + 0.5;
const x1 = xMid - length / 2;
const y1 = (yStart + yEnd) / 2;
const angle = (Math.atan2(yStart - yEnd, xStart - xEnd) * 180) / Math.PI;
segments.push({
angle,
length,
x1,
x2: xEnd,
y1,
y2: yEnd,
});
}
/**
* Adjusts the x positioning of the start or end of an edge so that it is at least EDGE_X_BUFFER
* pixels in from the left and right.
* @param node the node where the edge is originating from or terminating at
* @param originalX the initial x position provided by dagre
*/
private _ensureXIsWithinNode(node: dagre.Node, originalX: number): number {
// If the original X value was too far to the right, move it EDGE_X_BUFFER pixels
// in from the left end of the node.
const rightmostAcceptableLoc = node.x + node.width - this.LEFT_OFFSET - this.EDGE_X_BUFFER;
if (rightmostAcceptableLoc <= originalX) {
return rightmostAcceptableLoc;
}
// If the original X value was too far to the left, move it EDGE_X_BUFFER pixels
// in from the left end of the node.
const leftmostAcceptableLoc = node.x - this.LEFT_OFFSET + this.EDGE_X_BUFFER;
if (leftmostAcceptableLoc >= originalX) {
return leftmostAcceptableLoc;
}
return originalX;
}
private _getEdgeColor(edge: Edge, highlightNode?: string): string {
if (highlightNode) {
if (edge.from === highlightNode) {
return color.theme;
}
if (edge.to === highlightNode) {
return color.themeDarker;
}
}
if (edge.isPlaceholder) {
return color.weak;
}
return color.grey;
}
}
const EnhancedGraph = (props: GraphProps & GraphErrorBoundaryProps) => (
<GraphErrorBoundary onError={props.onError}>
<Graph {...props} />
</GraphErrorBoundary>
);
EnhancedGraph.displayName = 'EnhancedGraph';
export default EnhancedGraph;
| 252 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/LogViewer.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { mount, shallow } from 'enzyme';
import LogViewer from './LogViewer';
describe('LogViewer', () => {
it('renders an empty container when no logs passed', () => {
expect(shallow(<LogViewer logLines={[]} />)).toMatchSnapshot();
});
it('renders one log line', () => {
const logLines = ['first line'];
const logViewer = new LogViewer({ logLines });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders two log lines', () => {
const logLines = ['first line', 'second line'];
const logViewer = new LogViewer({ logLines });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders one long line without breaking', () => {
const line =
`Lorem Ipsum is simply dummy text of the printing and typesetting` +
`industry. Lorem Ipsum has been the industry's standard dummy text ever` +
`since the 1500s, when an unknown printer took a galley of type and` +
`scrambled it to make a type specimen book. It has survived not only five` +
`centuries, but also the leap into electronic typesetting, remaining` +
`essentially unchanged. It was popularised in the 1960s with the release` +
`of Letraset sheets containing Lorem Ipsum passages, and more recently` +
`with desktop publishing software like Aldus PageMaker including versions` +
`of Lorem Ipsum.`;
const logViewer = new LogViewer({ logLines: [line] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders a multi-line log', () => {
const line = `Lorem Ipsum is simply dummy text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen book. It has survived not only five
centuries, but also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with the release
of Letraset sheets containing Lorem Ipsum passages, and more recently
with desktop publishing software like Aldus PageMaker including versions
of Lorem Ipsum.`;
const logViewer = new LogViewer({ logLines: line.split('\n') });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('linkifies standalone urls', () => {
const logLines = ['this string: http://path.com is a url'];
const logViewer = new LogViewer({ logLines });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('linkifies standalone https urls', () => {
const logLines = ['this string: https://path.com is a url'];
const logViewer = new LogViewer({ logLines });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('linkifies substring urls', () => {
const logLines = ['this string:http://path.com is a url'];
const logViewer = new LogViewer({ logLines });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('does not linkify non http/https urls', () => {
const logLines = ['this string: gs://path is a GCS path'];
const logViewer = new LogViewer({ logLines });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('scrolls to end after rendering', () => {
const spy = jest.spyOn(LogViewer.prototype as any, '_scrollToEnd');
const logs = 'this string: gs://path is a GCS path';
const tree = mount(<LogViewer logLines={[logs]} />);
tree.instance().componentDidUpdate!({}, {});
expect(spy).toHaveBeenCalled();
});
it('renders a row with given index as line number', () => {
const logViewer = new LogViewer({ logLines: ['line1', 'line2'] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders a row with error', () => {
const logViewer = new LogViewer({ logLines: ['line1 with error', 'line2'] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders a row with upper case error', () => {
const logViewer = new LogViewer({ logLines: ['line1 with ERROR', 'line2'] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders a row with error word as substring', () => {
const logViewer = new LogViewer({ logLines: ['line1 with errorWord', 'line2'] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders a row with warning', () => {
const logViewer = new LogViewer({ logLines: ['line1 with warning', 'line2'] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders a row with warn', () => {
const logViewer = new LogViewer({ logLines: ['line1 with warn', 'line2'] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders a row with upper case warning', () => {
const logViewer = new LogViewer({ logLines: ['line1 with WARNING', 'line2'] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders a row with warning word as substring', () => {
const logViewer = new LogViewer({ logLines: ['line1 with warning:something', 'line2'] });
const tree = mount((logViewer as any)._rowRenderer({ index: 0 })).getDOMNode();
expect(tree).toMatchSnapshot();
});
});
| 253 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CompareTable.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { shallow } from 'enzyme';
import CompareTable from './CompareTable';
import { render, screen } from '@testing-library/react';
// tslint:disable-next-line:no-console
const consoleErrorBackup = console.error;
let consoleSpy: jest.Mock;
const rows = [
['1', '2', '3'],
['4', '5', '6'],
['cell7', 'cell8', 'cell9'],
];
const xLabels = ['col1', 'col2', 'col3'];
const yLabels = ['row1', 'row2', 'row3'];
describe('CompareTable', () => {
beforeAll(() => {
consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => null);
});
afterAll(() => {
// tslint:disable-next-line:no-console
console.error = consoleErrorBackup;
});
it('renders no data', () => {
const tree = shallow(<CompareTable rows={[]} xLabels={[]} yLabels={[]} />);
expect(tree).toMatchSnapshot();
});
it('logs error if ylabels and rows have different lengths', () => {
shallow(<CompareTable rows={[rows[0], rows[1]]} xLabels={xLabels} yLabels={yLabels} />);
expect(consoleSpy).toHaveBeenCalledWith(
'Number of rows (2) should match the number of Y labels (3).',
);
});
it('renders one row with three columns', () => {
const tree = shallow(<CompareTable rows={rows} xLabels={xLabels} yLabels={yLabels} />);
expect(tree).toMatchSnapshot();
});
});
describe('CompareTable xParentLabels', () => {
const xParentLabels = [
{ colSpan: 2, label: 'parent1' },
{ colSpan: 1, label: 'parent2' },
];
it('Hide x-axis parent labels if xlabels and xparentlabels have different lengths', () => {
render(
<CompareTable
rows={rows}
xLabels={xLabels}
yLabels={yLabels}
xParentLabels={[xParentLabels[0]]}
/>,
);
expect(screen.queryByText(xParentLabels[0].label)).toBeNull();
});
it('X-axis parent labels present if xlabels and xparentlabels have appropriate lengths', () => {
render(
<CompareTable
rows={rows}
xLabels={xLabels}
yLabels={yLabels}
xParentLabels={xParentLabels}
/>,
);
screen.getByText(xParentLabels[0].label);
screen.getByText(xParentLabels[1].label);
});
});
| 254 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CustomTableNameColumn.tsx | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { CustomRendererProps } from './CustomTable';
import React from 'react';
import Tooltip from '@material-ui/core/Tooltip';
/**
* Common name custom renderer that shows a tooltip when hovered. The tooltip helps if there isn't
* enough space to show the entire name in limited space.
*/
export const NameWithTooltip: React.FC<CustomRendererProps<string>> = (
props: CustomRendererProps<string>,
) => {
return (
<Tooltip title={props.value || ''} enterDelay={300} placement='top-start'>
<span>{props.value || ''}</span>
</Tooltip>
);
};
| 255 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PrivateSharedSelector.test.tsx | /*
* Copyright 2023 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { BuildInfoContext } from '../lib/BuildInfo';
import PrivateSharedSelector, { PrivateSharedSelectorProps } from './PrivateSharedSelector';
import { PipelineTabsHeaders } from '../pages/PrivateAndSharedPipelines';
function generateProps(): PrivateSharedSelectorProps {
return {
onChange: jest.fn(),
};
}
describe('PrivateSharedSelector', () => {
it('it renders correctly', async () => {
const tree = render(<PrivateSharedSelector {...generateProps()} />);
expect(tree).toMatchSnapshot();
});
it('it changes checked input on click', async () => {
render(
<BuildInfoContext.Provider value={{ apiServerMultiUser: true }}>
<PrivateSharedSelector {...generateProps()} />
</BuildInfoContext.Provider>,
);
const privateInput = screen.getByLabelText(PipelineTabsHeaders.PRIVATE) as HTMLInputElement;
const sharedInput = screen.getByLabelText(PipelineTabsHeaders.SHARED) as HTMLInputElement;
expect(privateInput.checked).toBe(true);
expect(sharedInput.checked).toBe(false);
fireEvent.click(sharedInput);
expect(privateInput.checked).toBe(false);
expect(sharedInput.checked).toBe(true);
});
});
| 256 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PlotCard.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Button from '@material-ui/core/Button';
import CloseIcon from '@material-ui/icons/Close';
import Dialog from '@material-ui/core/Dialog';
import Paper from '@material-ui/core/Paper';
import PopOutIcon from '@material-ui/icons/Launch';
import Separator from '../atoms/Separator';
import Tooltip from '@material-ui/core/Tooltip';
import ViewerContainer, { componentMap } from '../components/viewers/ViewerContainer';
import { ViewerConfig } from '../components/viewers/Viewer';
import { color, fontsize } from '../Css';
import { stylesheet, classes } from 'typestyle';
const css = stylesheet({
dialogTitle: {
color: color.strong,
fontSize: fontsize.large,
width: '100%',
},
fullscreenCloseBtn: {
minHeight: 0,
minWidth: 0,
padding: 3,
},
fullscreenDialog: {
alignItems: 'center',
justifyContent: 'center',
minHeight: '80%',
minWidth: '80%',
padding: 20,
},
fullscreenViewerContainer: {
alignItems: 'center',
boxSizing: 'border-box',
display: 'flex',
flexFlow: 'column',
flexGrow: 1,
height: '100%',
justifyContent: 'center',
margin: 20,
overflow: 'auto',
width: '100%',
},
plotCard: {
flexShrink: 0,
margin: 20,
minWidth: 250,
padding: 20,
width: 'auto',
},
plotHeader: {
display: 'flex',
justifyContent: 'space-between',
overflow: 'hidden',
paddingBottom: 10,
},
plotTitle: {
color: color.strong,
fontSize: 12,
fontWeight: 'bold',
},
popoutIcon: {
fontSize: 18,
},
});
export interface PlotCardProps {
title: string;
configs: ViewerConfig[];
maxDimension?: number;
}
interface PlotCardState {
fullscreenDialogOpen: boolean;
}
class PlotCard extends React.Component<PlotCardProps, PlotCardState> {
constructor(props: any) {
super(props);
this.state = {
fullscreenDialogOpen: false,
};
}
public shouldComponentUpdate(nextProps: PlotCardProps, nextState: PlotCardState): boolean {
return (
JSON.stringify(nextProps) !== JSON.stringify(this.props) ||
nextState.fullscreenDialogOpen !== this.state.fullscreenDialogOpen
);
}
public render(): JSX.Element | null {
const { title, configs, maxDimension, ...otherProps } = this.props;
if (!configs || !configs.length) {
return null;
}
return (
<div>
<Paper {...otherProps} className={classes(css.plotCard, 'plotCard')}>
<div className={css.plotHeader}>
<div className={css.plotTitle} title={title}>
{title}
</div>
<div>
<Button
onClick={() => this.setState({ fullscreenDialogOpen: true })}
style={{ padding: 4, minHeight: 0, minWidth: 0 }}
className='popOutButton'
>
<Tooltip title='Pop out'>
<PopOutIcon classes={{ root: css.popoutIcon }} />
</Tooltip>
</Button>
</div>
</div>
<ViewerContainer configs={configs} maxDimension={maxDimension} />
</Paper>
<Dialog
open={!!this.state.fullscreenDialogOpen}
classes={{ paper: css.fullscreenDialog }}
onClose={() => this.setState({ fullscreenDialogOpen: false })}
>
<div className={css.dialogTitle}>
<Button
onClick={() => this.setState({ fullscreenDialogOpen: false })}
className={classes(css.fullscreenCloseBtn, 'fullscreenCloseButton')}
>
<CloseIcon />
</Button>
{componentMap[configs[0].type].prototype.getDisplayName()}
<Separator />
<span style={{ color: color.inactive }}>({title})</span>
</div>
<div className={css.fullscreenViewerContainer}>
<ViewerContainer configs={configs} />
</div>
</Dialog>
</div>
);
}
}
export default PlotCard;
| 257 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CollapseButtonSingle.test.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import CollapseButtonSingle from './CollapseButtonSingle';
describe('CollapseButtonSingle', () => {
const collapseSectionUpdateSpy = jest.fn();
it('Collapes an expanded section when clicked', () => {
render(
<CollapseButtonSingle
collapseSection={false}
collapseSectionUpdate={collapseSectionUpdateSpy}
sectionName='testSection'
/>,
);
fireEvent.click(screen.getByText('testSection'));
expect(collapseSectionUpdateSpy).toHaveBeenCalledWith(true);
});
it('Expands a collapsed section when clicked', () => {
render(
<CollapseButtonSingle
collapseSection={true}
collapseSectionUpdate={collapseSectionUpdateSpy}
sectionName='testSection'
/>,
);
fireEvent.click(screen.getByText('testSection'));
expect(collapseSectionUpdateSpy).toHaveBeenCalledWith(false);
});
});
| 258 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PodYaml.test.tsx | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { FC } from 'react';
import { PodInfo, PodEvents } from './PodYaml';
import { render, act, fireEvent } from '@testing-library/react';
import { Apis } from 'src/lib/Apis';
import TestUtils from 'src/TestUtils';
// Original ./Editor uses a complex external editor inside, we use a simple mock
// for testing instead.
jest.mock('./Editor', () => {
return ({ value }: { value: string }) => <pre data-testid='Editor'>{value}</pre>;
});
afterEach(async () => {
jest.resetAllMocks();
jest.restoreAllMocks();
});
describe('PodInfo', () => {
let podInfoSpy: any;
beforeEach(() => {
podInfoSpy = jest.spyOn(Apis, 'getPodInfo');
});
it('renders Editor with pod yaml', async () => {
podInfoSpy.mockImplementation(() =>
Promise.resolve({
kind: 'Pod',
metadata: {
name: 'test-pod',
},
}),
);
const { container } = render(<PodInfo name='test-pod' namespace='test-ns' />);
// Renders nothing when loading
expect(container).toMatchInlineSnapshot(`<div />`);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<pre
data-testid="Editor"
>
kind: Pod
metadata:
name: test-pod
</pre>
</div>
`);
});
it('renders pod yaml putting spec to the last section', async () => {
podInfoSpy.mockImplementation(() =>
Promise.resolve({
kind: 'Pod',
spec: {
property: 'value',
},
status: {
property: 'value2',
},
}),
);
const { container } = render(<PodInfo name='test-pod' namespace='test-ns' />);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<pre
data-testid="Editor"
>
kind: Pod
status:
property: value2
spec:
property: value
</pre>
</div>
`);
});
it('shows a warning banner when request fails', async () => {
podInfoSpy.mockImplementation(() => Promise.reject('Pod not found'));
const { getByText } = render(<PodInfo name='test-pod' namespace='test-ns' />);
await act(TestUtils.flushPromises);
getByText(
'Failed to retrieve pod info. Possible reasons include cluster autoscaling, pod preemption or pod cleaned up by time to live configuration',
);
});
it('can be retried when request fails', async () => {
// Network was bad initially
podInfoSpy.mockImplementation(() => Promise.reject('Network failed'));
const { getByText } = render(<PodInfo name='test-pod' namespace='test-ns' />);
await act(TestUtils.flushPromises);
// Now network gets healthy
podInfoSpy.mockImplementation(() =>
Promise.resolve({
kind: 'Pod',
}),
);
const refreshButton = getByText('Refresh');
fireEvent.click(refreshButton);
await act(TestUtils.flushPromises);
getByText('kind: Pod');
});
it('refreshes automatically when pod name or namespace changes', async () => {
// Now network gets healthy
podInfoSpy.mockImplementation(() =>
Promise.resolve({
metadata: { name: 'pod-1' },
}),
);
const { getByText, rerender } = render(<PodInfo name='test-pod-1' namespace='test-ns' />);
expect(podInfoSpy).toHaveBeenLastCalledWith('test-pod-1', 'test-ns');
await act(TestUtils.flushPromises);
getByText(/pod-1/);
podInfoSpy.mockImplementation(() =>
Promise.resolve({
metadata: { name: 'pod-2' },
}),
);
rerender(<PodInfo name='test-pod-2' namespace='test-ns' />);
expect(podInfoSpy).toHaveBeenLastCalledWith('test-pod-2', 'test-ns');
await act(TestUtils.flushPromises);
getByText(/pod-2/);
});
});
// PodEvents is very similar to PodInfo, so we only test different parts here.
describe('PodEvents', () => {
let podEventsSpy: any;
beforeEach(() => {
podEventsSpy = jest.spyOn(Apis, 'getPodEvents');
});
it('renders Editor with pod events yaml', async () => {
podEventsSpy.mockImplementation(() =>
Promise.resolve({
kind: 'EventList',
}),
);
const { container } = render(<PodEvents name='test-pod' namespace='test-ns' />);
await act(TestUtils.flushPromises);
expect(container).toMatchInlineSnapshot(`
<div>
<pre
data-testid="Editor"
>
kind: EventList
</pre>
</div>
`);
});
it('shows a warning banner when request fails', async () => {
podEventsSpy.mockImplementation(() => Promise.reject('Pod not found'));
const { getByText } = render(<PodEvents name='test-pod' namespace='test-ns' />);
await act(TestUtils.flushPromises);
getByText(
'Failed to retrieve pod events. Possible reasons include cluster autoscaling, pod preemption or pod cleaned up by time to live configuration',
);
});
});
| 259 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CompareTable.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { logger } from '../lib/Utils';
import { stylesheet, classes } from 'typestyle';
import { color } from '../Css';
const borderStyle = `1px solid ${color.divider}`;
const css = stylesheet({
cell: {
border: borderStyle,
borderCollapse: 'collapse',
padding: 5,
},
labelCell: {
backgroundColor: color.lightGrey,
fontWeight: 'bold',
maxWidth: 200,
minWidth: 50,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
root: {
border: borderStyle,
borderCollapse: 'collapse',
},
row: {
$nest: {
'&:hover': {
backgroundColor: '#f7f7f7',
},
},
},
});
export interface xParentLabel {
label: string;
colSpan: number;
}
export interface CompareTableProps {
rows: string[][];
xLabels: string[];
yLabels: string[];
xParentLabels?: xParentLabel[];
}
class CompareTable extends React.PureComponent<CompareTableProps> {
public render(): JSX.Element | null {
const { rows, xLabels, yLabels, xParentLabels } = this.props;
if (rows.length !== yLabels.length) {
logger.error(
`Number of rows (${rows.length}) should match the number of Y labels (${yLabels.length}).`,
);
}
const xParentLabelsLength =
xParentLabels &&
xParentLabels.reduce((length, xParentLabel) => length + xParentLabel.colSpan, 0);
if (xParentLabels && xParentLabelsLength !== xLabels.length) {
logger.error(
`Number of columns with data (${xLabels.length}) should match the aggregated length of parent columns (${xParentLabelsLength}).`,
);
}
if (!rows || rows.length === 0) {
return null;
}
return (
<table className={css.root}>
<tbody>
{xParentLabels && xParentLabelsLength === xLabels.length && (
<tr className={css.row}>
<td className={css.labelCell} />
{/* X parent labels row */}
{xParentLabels.map((parentLabel, i) => (
<td
key={i}
className={classes(css.cell, css.labelCell)}
title={parentLabel.label}
colSpan={parentLabel.colSpan}
>
{parentLabel.label}
</td>
))}
</tr>
)}
<tr className={css.row}>
<td className={css.labelCell} />
{/* X labels row */}
{xLabels.map((label, i) => (
<td key={i} className={classes(css.cell, css.labelCell)} title={label}>
{label}
</td>
))}
</tr>
{rows.map((row, i) => (
<tr key={i} className={css.row}>
{/* Y label */}
<td className={classes(css.cell, css.labelCell)} title={yLabels[i]}>
{yLabels[i]}
</td>
{/* Row cells */}
{row.map((cell, j) => (
<td key={j} className={css.cell} title={cell}>
{cell}
</td>
))}
</tr>
))}
</tbody>
</table>
);
}
}
export default CompareTable;
| 260 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/NewRunParameters.test.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { mount, shallow } from 'enzyme';
import NewRunParameters, { NewRunParametersProps } from './NewRunParameters';
describe('NewRunParameters', () => {
it('shows parameters', () => {
const props = {
handleParamChange: jest.fn(),
initialParams: [{ name: 'testParam', value: 'testVal' }],
titleMessage: 'Specify parameters required by the pipeline',
} as NewRunParametersProps;
expect(shallow(<NewRunParameters {...props} />)).toMatchSnapshot();
});
it('does not display any text fields if there are no parameters', () => {
const props = {
handleParamChange: jest.fn(),
initialParams: [],
titleMessage: 'This pipeline has no parameters',
} as NewRunParametersProps;
expect(shallow(<NewRunParameters {...props} />)).toMatchSnapshot();
});
it('clicking the open editor button for json parameters displays an editor', () => {
const handleParamChange = jest.fn();
const props = {
handleParamChange,
initialParams: [{ name: 'testParam', value: '{"test":"value"}' }],
titleMessage: 'Specify json parameters required by the pipeline',
} as NewRunParametersProps;
const tree = mount(<NewRunParameters {...props} />);
tree
.findWhere(el => el.text() === 'Open Json Editor')
.hostNodes()
.find('Button')
.simulate('click');
expect(handleParamChange).toHaveBeenCalledTimes(1);
expect(handleParamChange).toHaveBeenLastCalledWith(0, '{\n "test": "value"\n}');
expect(tree.find('Editor')).toMatchSnapshot();
});
it('fires handleParamChange callback on change', () => {
const handleParamChange = jest.fn();
const props = {
handleParamChange,
initialParams: [
{ name: 'testParam1', value: 'testVal1' },
{ name: 'testParam2', value: 'testVal2' },
],
titleMessage: 'Specify parameters required by the pipeline',
} as NewRunParametersProps;
const tree = mount(<NewRunParameters {...props} />);
tree
.find('input#newRunPipelineParam1')
.simulate('change', { target: { value: 'test param value' } });
expect(handleParamChange).toHaveBeenCalledTimes(1);
expect(handleParamChange).toHaveBeenLastCalledWith(1, 'test param value');
});
});
| 261 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/ArtifactLink.tsx | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import {
generateGcsConsoleUri,
generateS3ArtifactUrl,
generateMinioArtifactUrl,
} from '../lib/Utils';
/**
* A component that renders an artifact URL as clickable link if URL is correct
*/
export const ArtifactLink: React.FC<{ artifactUri?: string }> = ({ artifactUri }) => {
let clickableUrl: string | undefined;
if (artifactUri) {
if (artifactUri.startsWith('gs:')) {
const gcsConsoleUrl = generateGcsConsoleUri(artifactUri);
if (gcsConsoleUrl) {
clickableUrl = gcsConsoleUrl;
}
}
if (artifactUri.startsWith('s3:')) {
clickableUrl = generateS3ArtifactUrl(artifactUri);
} else if (artifactUri.startsWith('http:') || artifactUri.startsWith('https:')) {
clickableUrl = artifactUri;
} else if (artifactUri.startsWith('minio:')) {
clickableUrl = generateMinioArtifactUrl(artifactUri);
}
}
if (clickableUrl) {
// Opens in new window safely
return (
<a href={clickableUrl} target={'_blank'} rel='noreferrer noopener'>
{artifactUri}
</a>
);
} else {
return <>{artifactUri}</>;
}
};
| 262 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/ResourceInfo.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Struct } from 'google-protobuf/google/protobuf/struct_pb';
import * as React from 'react';
import { getMetadataValue } from 'src/mlmd/library';
import { Artifact, Execution } from 'src/third_party/mlmd';
import { stylesheet } from 'typestyle';
import { color, commonCss } from '../Css';
import { ArtifactLink } from './ArtifactLink';
export const css = stylesheet({
field: {
flexBasis: '300px',
marginBottom: '32px',
padding: '4px',
},
resourceInfo: {
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
},
term: {
color: color.grey,
fontSize: '12px',
letterSpacing: '0.2px',
lineHeight: '16px',
},
value: {
color: color.secondaryText,
fontSize: '14px',
letterSpacing: '0.2px',
lineHeight: '20px',
},
});
export enum ResourceType {
ARTIFACT = 'ARTIFACT',
EXECUTION = 'EXECUTION',
}
export interface ArtifactProps {
resourceType: ResourceType.ARTIFACT;
resource: Artifact;
typeName: string;
}
export interface ExecutionProps {
resourceType: ResourceType.EXECUTION;
resource: Execution;
typeName: string;
}
export type ResourceInfoProps = ArtifactProps | ExecutionProps;
export class ResourceInfo extends React.Component<ResourceInfoProps, {}> {
public render(): JSX.Element {
const { resource } = this.props;
const propertyMap = resource.getPropertiesMap();
const customPropertyMap = resource.getCustomPropertiesMap();
let resourceTitle = this.props.typeName;
const stateText = getResourceStateText(this.props);
if (stateText) {
resourceTitle = `${resourceTitle} (${stateText})`;
}
return (
<section>
<h1 className={commonCss.header}>{resourceTitle}</h1>
{(() => {
if (this.props.resourceType === ResourceType.ARTIFACT) {
return (
<>
<dt className={css.term}>URI</dt>
<dd className={css.value}>
<ArtifactLink artifactUri={this.props.resource.getUri()} />
</dd>
</>
);
}
return null;
})()}
<h2 className={commonCss.header2}>Properties</h2>
<dl className={css.resourceInfo}>
{propertyMap
.getEntryList()
// TODO: __ALL_META__ is something of a hack, is redundant, and can be ignored
.filter(k => k[0] !== '__ALL_META__')
.map(k => (
<div className={css.field} key={k[0]} data-testid='resource-info-property'>
<dt className={css.term} data-testid='resource-info-property-key'>
{k[0]}
</dt>
<dd className={css.value} data-testid='resource-info-property-value'>
{propertyMap && prettyPrintValue(getMetadataValue(propertyMap.get(k[0])))}
</dd>
</div>
))}
</dl>
<h2 className={commonCss.header2}>Custom Properties</h2>
<dl className={css.resourceInfo}>
{customPropertyMap.getEntryList().map(k => (
<div className={css.field} key={k[0]} data-testid='resource-info-property'>
<dt className={css.term} data-testid='resource-info-property-key'>
{k[0]}
</dt>
<dd className={css.value} data-testid='resource-info-property-value'>
{customPropertyMap &&
prettyPrintValue(getMetadataValue(customPropertyMap.get(k[0])))}
</dd>
</div>
))}
</dl>
</section>
);
}
}
function prettyPrintValue(
value: string | number | Struct | undefined,
): JSX.Element | number | string {
if (value == null) {
return '';
}
if (typeof value === 'string') {
return prettyPrintJsonValue(value);
}
if (typeof value === 'number') {
return value;
}
// value is Struct
const jsObject = value.toJavaScript();
// When Struct is converted to js object, it may contain a top level "struct"
// or "list" key depending on its type, but the key is meaningless and we can
// omit it in visualization.
return <pre>{JSON.stringify(jsObject?.struct || jsObject?.list || jsObject, null, 2)}</pre>;
}
function prettyPrintJsonValue(value: string): JSX.Element | string {
try {
const jsonValue = JSON.parse(value);
return <pre>{JSON.stringify(jsonValue, null, 2)}</pre>;
} catch {
// not JSON, return directly
return value;
}
}
// Get text representation of resource state.
// Works for both artifact and execution.
export function getResourceStateText(props: ResourceInfoProps): string | undefined {
if (props.resourceType === ResourceType.ARTIFACT) {
const state = props.resource.getState();
switch (state) {
case Artifact.State.UNKNOWN:
return undefined; // when state is not set, it defaults to UNKNOWN
case Artifact.State.PENDING:
return 'Pending';
case Artifact.State.LIVE:
return 'Live';
case Artifact.State.MARKED_FOR_DELETION:
return 'Marked for deletion';
case Artifact.State.DELETED:
return 'Deleted';
default:
throw new Error(`Impossible artifact state value: ${state}`);
}
} else {
// type == EXECUTION
const state = props.resource.getLastKnownState();
switch (state) {
case Execution.State.UNKNOWN:
return undefined;
case Execution.State.NEW:
return 'New';
case Execution.State.RUNNING:
return 'Running';
case Execution.State.COMPLETE:
return 'Complete';
case Execution.State.CANCELED:
return 'Canceled';
case Execution.State.FAILED:
return 'Failed';
case Execution.State.CACHED:
return 'Cached';
default:
throw new Error(`Impossible execution state value: ${state}`);
}
}
}
| 263 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/UploadPipelineDialog.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import BusyButton from '../atoms/BusyButton';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogTitle from '@material-ui/core/DialogTitle';
import Dropzone from 'react-dropzone';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Input from '../atoms/Input';
import InputAdornment from '@material-ui/core/InputAdornment';
import Radio from '@material-ui/core/Radio';
import { TextFieldProps } from '@material-ui/core/TextField';
import { padding, commonCss, zIndex, color } from '../Css';
import { stylesheet, classes } from 'typestyle';
import { ExternalLink } from '../atoms/ExternalLink';
import PrivateSharedSelector from './PrivateSharedSelector';
import { BuildInfoContext } from 'src/lib/BuildInfo';
const css = stylesheet({
dropOverlay: {
backgroundColor: color.lightGrey,
border: '2px dashed #aaa',
bottom: 0,
left: 0,
padding: '2.5em 0',
position: 'absolute',
right: 0,
textAlign: 'center',
top: 0,
zIndex: zIndex.DROP_ZONE_OVERLAY,
},
root: {
width: 500,
},
});
export enum ImportMethod {
LOCAL = 'local',
URL = 'url',
}
interface UploadPipelineDialogProps {
open: boolean;
onClose: (
confirmed: boolean,
name: string,
file: File | null,
url: string,
method: ImportMethod,
isPrivatePipeline: boolean,
description?: string,
) => Promise<boolean>;
}
interface UploadPipelineDialogState {
busy: boolean;
dropzoneActive: boolean;
file: File | null;
fileName: string;
fileUrl: string;
importMethod: ImportMethod;
uploadPipelineDescription: string;
uploadPipelineName: string;
isPrivatePipeline: boolean;
}
class UploadPipelineDialog extends React.Component<
UploadPipelineDialogProps,
UploadPipelineDialogState
> {
static contextType = BuildInfoContext;
private _dropzoneRef = React.createRef<Dropzone & HTMLDivElement>();
constructor(props: any) {
super(props);
this.state = {
busy: false,
dropzoneActive: false,
file: null,
fileName: '',
fileUrl: '',
importMethod: ImportMethod.LOCAL,
uploadPipelineDescription: '',
uploadPipelineName: '',
isPrivatePipeline: true,
};
}
public render(): JSX.Element {
const {
dropzoneActive,
file,
fileName,
fileUrl,
importMethod,
uploadPipelineName,
busy,
} = this.state;
return (
<Dialog
id='uploadDialog'
onClose={() => this._uploadDialogClosed(false)}
open={this.props.open}
classes={{ paper: css.root }}
>
<DialogTitle>Upload and name your pipeline</DialogTitle>
<div className={padding(20, 'lr')}>
{this.context?.apiServerMultiUser && (
<PrivateSharedSelector
onChange={val => {
this.setState({
isPrivatePipeline: val,
});
}}
></PrivateSharedSelector>
)}
<div>Upload a pipeline package file from your computer or import one using a URL.</div>
<div className={classes(commonCss.flex, padding(10, 'b'))}>
<FormControlLabel
id='uploadLocalFileBtn'
label='Upload a file'
checked={importMethod === ImportMethod.LOCAL}
control={<Radio color='primary' />}
onChange={() => this.setState({ importMethod: ImportMethod.LOCAL })}
/>
<FormControlLabel
id='uploadFromUrlBtn'
label='Import by URL'
checked={importMethod === ImportMethod.URL}
control={<Radio color='primary' />}
onChange={() => this.setState({ importMethod: ImportMethod.URL })}
/>
</div>
{importMethod === ImportMethod.LOCAL && (
<React.Fragment>
<Dropzone
id='dropZone'
disableClick={true}
onDrop={this._onDrop.bind(this)}
onDragEnter={this._onDropzoneDragEnter.bind(this)}
onDragLeave={this._onDropzoneDragLeave.bind(this)}
style={{ position: 'relative' }}
ref={this._dropzoneRef}
inputProps={{ tabIndex: -1 }}
>
{dropzoneActive && <div className={css.dropOverlay}>Drop files..</div>}
<div className={padding(10, 'b')}>You can also drag and drop the file here.</div>
<DocumentationCompilePipeline />
<Input
onChange={this.handleChange('fileName')}
value={fileName}
required={true}
label='File'
variant='outlined'
InputProps={{
endAdornment: (
<InputAdornment position='end'>
<Button
color='secondary'
onClick={() => this._dropzoneRef.current!.open()}
style={{ padding: '3px 5px', margin: 0, whiteSpace: 'nowrap' }}
>
Choose file
</Button>
</InputAdornment>
),
readOnly: true,
}}
/>
</Dropzone>
</React.Fragment>
)}
{importMethod === ImportMethod.URL && (
<React.Fragment>
<div className={padding(10, 'b')}>URL must be publicly accessible.</div>
<DocumentationCompilePipeline />
<Input
onChange={this.handleChange('fileUrl')}
value={fileUrl}
required={true}
label='URL'
variant='outlined'
/>
</React.Fragment>
)}
<Input
id='uploadFileName'
label='Pipeline name'
onChange={this.handleChange('uploadPipelineName')}
required={true}
value={uploadPipelineName}
variant='outlined'
/>
</div>
{/* <Input label='Pipeline description'
onChange={this.handleChange('uploadPipelineDescription')}
value={uploadPipelineDescription} multiline={true} variant='outlined' /> */}
<DialogActions>
<Button id='cancelUploadBtn' onClick={() => this._uploadDialogClosed.bind(this)(false)}>
Cancel
</Button>
<BusyButton
id='confirmUploadBtn'
onClick={() => this._uploadDialogClosed.bind(this)(true)}
title='Upload'
busy={busy}
disabled={
!uploadPipelineName || (importMethod === ImportMethod.LOCAL ? !file : !fileUrl)
}
/>
</DialogActions>
</Dialog>
);
}
public handleChange = (name: string) => (event: any) => {
this.setState({
[name]: (event.target as TextFieldProps).value,
} as any);
};
private _onDropzoneDragEnter(): void {
this.setState({ dropzoneActive: true });
}
private _onDropzoneDragLeave(): void {
this.setState({ dropzoneActive: false });
}
private _onDrop(files: File[]): void {
this.setState({
dropzoneActive: false,
file: files[0],
fileName: files[0].name,
// Suggest all characters left of first . as pipeline name
uploadPipelineName: files[0].name.split('.')[0],
});
}
private _uploadDialogClosed(confirmed: boolean): void {
this.setState({ busy: true }, async () => {
const success = await this.props.onClose(
confirmed,
this.state.uploadPipelineName,
this.state.file,
this.state.fileUrl.trim(),
this.state.importMethod,
this.state.isPrivatePipeline,
this.state.uploadPipelineDescription,
);
if (success) {
this.setState({
busy: false,
dropzoneActive: false,
file: null,
fileName: '',
fileUrl: '',
importMethod: ImportMethod.LOCAL,
uploadPipelineDescription: '',
uploadPipelineName: '',
});
} else {
this.setState({ busy: false });
}
});
}
}
export default UploadPipelineDialog;
export const DocumentationCompilePipeline: React.FC = () => (
<div className={padding(10, 'b')}>
For expected file format, refer to{' '}
<ExternalLink href='https://www.kubeflow.org/docs/components/pipelines/v2/compile-a-pipeline/'>
Compile Pipeline Documentation
</ExternalLink>
.
</div>
);
| 264 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/ExperimentList.tsx | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import CustomTable, { Column, CustomRendererProps, Row, ExpandState } from './CustomTable';
import * as React from 'react';
import { Link, RouteComponentProps } from 'react-router-dom';
import {
V2beta1ListExperimentsResponse,
V2beta1Experiment,
V2beta1ExperimentStorageState,
} from 'src/apisv2beta1/experiment';
import { errorToMessage } from 'src/lib/Utils';
import { RoutePage, RouteParams } from './Router';
import { commonCss } from 'src/Css';
import { Apis, ExperimentSortKeys, ListRequest } from 'src/lib/Apis';
import { V2beta1RunStorageState } from 'src/apisv2beta1/run';
import { V2beta1Filter, V2beta1PredicateOperation } from 'src/apisv2beta1/filter';
import RunList from 'src/pages/RunList';
import produce from 'immer';
import Tooltip from '@material-ui/core/Tooltip';
export interface ExperimentListProps extends RouteComponentProps {
namespace?: string;
storageState?: V2beta1ExperimentStorageState;
onError: (message: string, error: Error) => void;
}
interface DisplayExperiment extends V2beta1Experiment {
error?: string;
expandState?: ExpandState;
}
interface ExperimentListState {
displayExperiments: DisplayExperiment[];
}
export class ExperimentList extends React.PureComponent<ExperimentListProps, ExperimentListState> {
private _tableRef = React.createRef<CustomTable>();
constructor(props: any) {
super(props);
this.state = {
displayExperiments: [],
};
}
public render(): JSX.Element {
const columns: Column[] = [
{
customRenderer: this._nameCustomRenderer,
flex: 1,
label: 'Experiment name',
sortKey: ExperimentSortKeys.NAME,
},
{
flex: 2,
label: 'Description',
},
];
const rows: Row[] = this.state.displayExperiments.map(exp => {
return {
error: exp.error,
expandState: exp.expandState,
id: exp.experiment_id!,
otherFields: [exp.display_name!, exp.description!],
};
});
return (
<div>
<CustomTable
columns={columns}
rows={rows}
ref={this._tableRef}
disableSelection={true}
initialSortColumn={ExperimentSortKeys.CREATED_AT}
reload={this._loadExperiments.bind(this)}
toggleExpansion={this._toggleRowExpand.bind(this)}
getExpandComponent={this._getExpandedExperimentComponent.bind(this)}
filterLabel='Filter experiments'
emptyMessage='No archived experiments found.'
/>
</div>
);
}
public async refresh(): Promise<void> {
if (this._tableRef.current) {
await this._tableRef.current.reload();
}
}
public _nameCustomRenderer: React.FC<CustomRendererProps<string>> = (
props: CustomRendererProps<string>,
) => {
return (
<Tooltip title={props.value} enterDelay={300} placement='top-start'>
<Link
className={commonCss.link}
onClick={e => e.stopPropagation()}
to={RoutePage.EXPERIMENT_DETAILS.replace(':' + RouteParams.experimentId, props.id)}
>
{props.value}
</Link>
</Tooltip>
);
};
protected async _loadExperiments(request: ListRequest): Promise<string> {
let nextPageToken = '';
let displayExperiments: DisplayExperiment[];
if (this.props.storageState) {
try {
// Augment the request filter with the storage state predicate
const filter = JSON.parse(
decodeURIComponent(request.filter || '{"predicates": []}'),
) as V2beta1Filter;
filter.predicates = (filter.predicates || []).concat([
{
key: 'storage_state',
// Use EQUALS ARCHIVED or NOT EQUALS ARCHIVED to account for cases where the field
// is missing, in which case it should be counted as available.
operation:
this.props.storageState === V2beta1ExperimentStorageState.ARCHIVED
? V2beta1PredicateOperation.EQUALS
: V2beta1PredicateOperation.NOTEQUALS,
string_value: V2beta1ExperimentStorageState.ARCHIVED.toString(),
},
]);
request.filter = encodeURIComponent(JSON.stringify(filter));
} catch (err) {
const error = new Error(await errorToMessage(err));
this.props.onError('Error: failed to parse request filter: ', error);
return '';
}
}
try {
let response: V2beta1ListExperimentsResponse;
response = await Apis.experimentServiceApiV2.listExperiments(
request.pageToken,
request.pageSize,
request.sortBy,
request.filter,
this.props.namespace || undefined,
);
nextPageToken = response.next_page_token || '';
displayExperiments = response.experiments || [];
displayExperiments.forEach(exp => (exp.expandState = ExpandState.COLLAPSED));
this.setState({ displayExperiments });
} catch (err) {
const error = new Error(await errorToMessage(err));
this.props.onError('Error: failed to list experiments: ', error);
return '';
}
return nextPageToken;
}
private _toggleRowExpand(rowIndex: number): void {
const displayExperiments = produce(this.state.displayExperiments, draft => {
draft[rowIndex].expandState =
draft[rowIndex].expandState === ExpandState.COLLAPSED
? ExpandState.EXPANDED
: ExpandState.COLLAPSED;
});
this.setState({ displayExperiments });
}
private _getExpandedExperimentComponent(experimentIndex: number): JSX.Element {
const experiment = this.state.displayExperiments[experimentIndex];
const parentProps = { ...this.props, onError: () => null };
return (
<RunList
hideExperimentColumn={true}
experimentIdMask={experiment.experiment_id}
{...parentProps}
disablePaging={false}
noFilterBox={true}
storageState={
this.props.storageState === V2beta1ExperimentStorageState.ARCHIVED
? V2beta1RunStorageState.ARCHIVED
: V2beta1RunStorageState.AVAILABLE
}
disableSorting={true}
disableSelection={true}
/>
);
}
}
export default ExperimentList;
| 265 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/TwoLevelDropdown.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { Ref, useRef, useState } from 'react';
import { Button, Tooltip } from '@material-ui/core';
import { color } from 'src/Css';
import { classes, stylesheet } from 'typestyle';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
const css = stylesheet({
defaultFont: {
fontSize: '1rem',
},
dropdown: {
border: `1px solid ${color.lightGrey}`,
color: color.grey,
fontWeight: 400,
margin: 0,
},
dropdownMenu: {
display: 'block',
borderRadius: '5px',
border: `1px solid ${color.lightGrey}`,
margin: 0,
padding: '5px 0',
position: 'absolute',
top: '100%',
left: 0,
minWidth: '10rem',
cursor: 'pointer',
backgroundColor: color.background,
zIndex: 1,
},
dropdownElement: {
padding: '1rem',
position: 'relative',
$nest: {
'&:hover': {
backgroundColor: `${color.lightGrey}`,
},
},
},
textContainer: {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
maxWidth: '30rem',
overflow: 'hidden',
verticalAlign: 'top',
},
dropdownSubmenu: {
left: '100%',
// Offsets the dropdown menu vertical padding (5px) and border (1px).
top: '-6px',
},
inlineContainer: {
display: 'inline-block',
},
relativeContainer: {
position: 'relative',
},
});
const ChevronRightSmallIcon = () => <ChevronRightIcon className={classes(css.defaultFont)} />;
export interface SelectedItem {
itemName: string;
subItemName: string;
subItemSecondaryName?: string;
}
export interface DropdownSubItem {
name: string;
secondaryName?: string;
}
export interface DropdownItem {
name: string;
subItems: DropdownSubItem[];
}
interface DropdownButtonProps {
dropdownRef: Ref<HTMLDivElement>;
toggleDropdown: (e: React.MouseEvent) => void;
selectedItem: SelectedItem;
title: string;
}
function DropdownButton(props: DropdownButtonProps) {
const { dropdownRef, toggleDropdown, selectedItem, title } = props;
const dropdownTooltip: string =
selectedItem.itemName && selectedItem.subItemName
? `${selectedItem.itemName} > ${selectedItem.subItemName}` +
(selectedItem.subItemSecondaryName ? ` > ${selectedItem.subItemSecondaryName}` : '')
: title;
return (
<div className={classes(css.inlineContainer)} ref={dropdownRef}>
<Button onClick={toggleDropdown} className={classes(css.dropdown, css.textContainer)}>
<Tooltip title={dropdownTooltip} enterDelay={300} placement='top-start'>
<span className={classes(css.textContainer)}>
{selectedItem.itemName && selectedItem.subItemName ? (
<>
{selectedItem.itemName}
<ChevronRightSmallIcon />
{selectedItem.subItemName}
{selectedItem.subItemSecondaryName && (
<>
<ChevronRightSmallIcon />
{selectedItem.subItemSecondaryName}
</>
)}
</>
) : (
title
)}
</span>
</Tooltip>
<ArrowDropDownIcon />
</Button>
</div>
);
}
interface DropdownSubMenuProps {
subDropdownActive: number;
setSubDropdownActive: (subDropdownActive: number) => void;
subDropdownIndex: number;
item: DropdownItem;
deactivateDropdown: (selectedItem: SelectedItem) => void;
}
function DropdownSubMenu(props: DropdownSubMenuProps) {
const {
subDropdownActive,
setSubDropdownActive,
subDropdownIndex,
item,
deactivateDropdown,
} = props;
if (item.subItems.length === 0 || subDropdownActive !== subDropdownIndex) {
return <></>;
}
return (
<ul className={classes(css.dropdownSubmenu, css.dropdownMenu)}>
{item.subItems.map((subItem, subIndex) => (
<li
className={classes(css.dropdownElement)}
key={subIndex}
onClick={() => {
deactivateDropdown({
itemName: item.name,
subItemName: subItem.name,
subItemSecondaryName: subItem.secondaryName,
});
setSubDropdownActive(-1);
}}
>
<Tooltip
title={subItem.name + (subItem.secondaryName ? ` > ${subItem.secondaryName}` : '')}
enterDelay={300}
placement='top-start'
>
<span className={classes(css.textContainer, css.inlineContainer)}>
{subItem.name}
{subItem.secondaryName && (
<>
<ChevronRightSmallIcon />
{subItem.secondaryName}
</>
)}
</span>
</Tooltip>
</li>
))}
</ul>
);
}
interface DropdownMenuProps {
dropdownListRef: Ref<HTMLDivElement>;
dropdownActive: boolean;
items: DropdownItem[];
deactivateDropdown: (selectedItem: SelectedItem) => void;
}
function DropdownMenu(props: DropdownMenuProps) {
const { dropdownListRef, dropdownActive, items, deactivateDropdown } = props;
// Provides the index of the active sub-dropdown, or '-1' if none are active.
const [subDropdownActive, setSubDropdownActive] = useState<number>(-1);
if (items.length === 0 || !dropdownActive) {
return <></>;
}
return (
<div ref={dropdownListRef}>
<ul className={classes(css.dropdownMenu)}>
{items.map((item, index) => {
return (
<li
className={classes(css.dropdownElement)}
onMouseEnter={() => setSubDropdownActive(index)}
onMouseLeave={() => setSubDropdownActive(-1)}
key={index}
>
<Tooltip title={item.name} enterDelay={300} placement='top-start'>
<span className={classes(css.textContainer, css.inlineContainer)}>{item.name}</span>
</Tooltip>
<ChevronRightSmallIcon />
<DropdownSubMenu
subDropdownActive={subDropdownActive}
setSubDropdownActive={setSubDropdownActive}
subDropdownIndex={index}
item={item}
deactivateDropdown={deactivateDropdown}
/>
</li>
);
})}
</ul>
</div>
);
}
export interface TwoLevelDropdownProps {
title: string;
items: DropdownItem[];
selectedItem: SelectedItem;
setSelectedItem: (selectedItem: SelectedItem) => void;
}
function TwoLevelDropdown(props: TwoLevelDropdownProps) {
const { title, items, selectedItem, setSelectedItem } = props;
const [dropdownActive, setDropdownActive] = useState(false);
// Close dropdown if the user clicks outside of the dropdown button or main menu.
const dropdownRef = useRef<HTMLDivElement>(null);
const dropdownListRef = useRef<HTMLDivElement>(null);
window.addEventListener('click', (event: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node) &&
dropdownListRef.current &&
!dropdownListRef.current.contains(event.target as Node)
) {
setDropdownActive(false);
}
});
const toggleDropdown = (_: React.MouseEvent) => {
setDropdownActive(!dropdownActive);
};
const deactivateDropdown = (selectedItem: SelectedItem) => {
setSelectedItem(selectedItem);
setDropdownActive(false);
};
return (
<div className={classes(css.relativeContainer)}>
<DropdownButton
dropdownRef={dropdownRef}
toggleDropdown={toggleDropdown}
selectedItem={selectedItem}
title={title}
/>
<DropdownMenu
dropdownListRef={dropdownListRef}
dropdownActive={dropdownActive}
items={items}
deactivateDropdown={deactivateDropdown}
/>
</div>
);
}
export default TwoLevelDropdown;
| 266 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/ExperimentList.test.tsx | /*
* Copyright 2020 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import * as Utils from 'src/lib/Utils';
import { ExperimentList, ExperimentListProps } from './ExperimentList';
import TestUtils from 'src/TestUtils';
import { V2beta1ExperimentStorageState } from 'src/apisv2beta1/experiment';
import { V2beta1RunStorageState } from 'src/apisv2beta1/run';
import { ExpandState } from './CustomTable';
import { Apis, ExperimentSortKeys, ListRequest } from 'src/lib/Apis';
import { ReactWrapper, ShallowWrapper, shallow } from 'enzyme';
import { range } from 'lodash';
import { V2beta1Filter, V2beta1PredicateOperation } from 'src/apisv2beta1/filter';
class ExperimentListTest extends ExperimentList {
public _loadExperiments(request: ListRequest): Promise<string> {
return super._loadExperiments(request);
}
}
describe('ExperimentList', () => {
let tree: ShallowWrapper | ReactWrapper;
const onErrorSpy = jest.fn();
const listExperimentsSpy = jest.spyOn(Apis.experimentServiceApiV2, 'listExperiments');
const getExperimentSpy = jest.spyOn(Apis.experimentServiceApiV2, 'getExperiment');
// We mock this because it uses toLocaleDateString, which causes mismatches between local and CI
// test enviroments
const formatDateStringSpy = jest.spyOn(Utils, 'formatDateString');
const listRunsSpy = jest.spyOn(Apis.runServiceApiV2, 'listRuns');
function generateProps(): ExperimentListProps {
return {
history: {} as any,
location: { search: '' } as any,
match: '' as any,
onError: onErrorSpy,
};
}
function mockNExperiments(n: number): void {
getExperimentSpy.mockImplementation(id =>
Promise.resolve({
experiment_id: 'testexperiment' + id,
display_name: 'experiment with id: testexperiment' + id,
}),
);
listExperimentsSpy.mockImplementation(() =>
Promise.resolve({
experiments: range(1, n + 1).map(i => {
return {
experiment_id: 'testexperiment' + i,
display_name: 'experiment with id: testexperiment' + i,
};
}),
}),
);
}
beforeEach(() => {
formatDateStringSpy.mockImplementation((date?: Date) => {
return date ? '1/2/2019, 12:34:56 PM' : '-';
});
onErrorSpy.mockClear();
listExperimentsSpy.mockClear();
getExperimentSpy.mockClear();
});
afterEach(async () => {
// unmount() should be called before resetAllMocks() in case any part of the unmount life cycle
// depends on mocks/spies
if (tree) {
await tree.unmount();
}
jest.resetAllMocks();
});
it('renders the empty experience', () => {
expect(shallow(<ExperimentList {...generateProps()} />)).toMatchSnapshot();
});
it('renders the empty experience in ARCHIVED state', () => {
const props = generateProps();
props.storageState = V2beta1ExperimentStorageState.ARCHIVED;
expect(shallow(<ExperimentList {...props} />)).toMatchSnapshot();
});
it('loads experiments whose storage state is not ARCHIVED when storage state equals AVAILABLE', async () => {
mockNExperiments(1);
const props = generateProps();
props.storageState = V2beta1ExperimentStorageState.AVAILABLE;
tree = shallow(<ExperimentList {...props} />);
await (tree.instance() as ExperimentListTest)._loadExperiments({});
expect(listExperimentsSpy).toHaveBeenLastCalledWith(
undefined,
undefined,
undefined,
encodeURIComponent(
JSON.stringify({
predicates: [
{
key: 'storage_state',
operation: V2beta1PredicateOperation.NOTEQUALS,
string_value: V2beta1ExperimentStorageState.ARCHIVED.toString(),
},
],
} as V2beta1Filter),
),
undefined,
);
});
it('loads experiments whose storage state is ARCHIVED when storage state equals ARCHIVED', async () => {
mockNExperiments(1);
const props = generateProps();
props.storageState = V2beta1ExperimentStorageState.ARCHIVED;
tree = shallow(<ExperimentList {...props} />);
await (tree.instance() as ExperimentListTest)._loadExperiments({});
expect(listExperimentsSpy).toHaveBeenLastCalledWith(
undefined,
undefined,
undefined,
encodeURIComponent(
JSON.stringify({
predicates: [
{
key: 'storage_state',
operation: V2beta1PredicateOperation.EQUALS,
string_value: V2beta1ExperimentStorageState.ARCHIVED.toString(),
},
],
} as V2beta1Filter),
),
undefined,
);
});
it('augments request filter with storage state predicates', async () => {
mockNExperiments(1);
const props = generateProps();
props.storageState = V2beta1ExperimentStorageState.ARCHIVED;
tree = shallow(<ExperimentList {...props} />);
await (tree.instance() as ExperimentListTest)._loadExperiments({
filter: encodeURIComponent(
JSON.stringify({
predicates: [{ key: 'k', op: 'op', string_value: 'val' }],
}),
),
});
expect(listExperimentsSpy).toHaveBeenLastCalledWith(
undefined,
undefined,
undefined,
encodeURIComponent(
JSON.stringify({
predicates: [
{
key: 'k',
op: 'op',
string_value: 'val',
},
{
key: 'storage_state',
operation: V2beta1PredicateOperation.EQUALS,
string_value: V2beta1ExperimentStorageState.ARCHIVED.toString(),
},
],
} as V2beta1Filter),
),
undefined,
);
});
it('loads one experiment', async () => {
mockNExperiments(1);
const props = generateProps();
tree = shallow(<ExperimentList {...props} />);
await (tree.instance() as ExperimentListTest)._loadExperiments({});
expect(listExperimentsSpy).toHaveBeenLastCalledWith(
undefined,
undefined,
undefined,
undefined,
undefined,
);
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchSnapshot();
});
it('reloads the experiment when refresh is called', async () => {
mockNExperiments(0);
const props = generateProps();
tree = TestUtils.mountWithRouter(<ExperimentList {...props} />);
await (tree.instance() as ExperimentList).refresh();
tree.update();
expect(listExperimentsSpy).toHaveBeenCalledTimes(2);
expect(listExperimentsSpy).toHaveBeenLastCalledWith(
'',
10,
ExperimentSortKeys.CREATED_AT + ' desc',
'',
undefined,
);
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchSnapshot();
});
it('loads multiple experiments', async () => {
mockNExperiments(5);
const props = generateProps();
tree = shallow(<ExperimentList {...props} />);
await (tree.instance() as ExperimentListTest)._loadExperiments({});
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchSnapshot();
});
it('calls error callback when loading experiment fails', async () => {
TestUtils.makeErrorResponseOnce(
jest.spyOn(Apis.experimentServiceApiV2, 'listExperiments'),
'bad stuff happened',
);
const props = generateProps();
tree = shallow(<ExperimentList {...props} />);
await (tree.instance() as ExperimentListTest)._loadExperiments({});
expect(props.onError).toHaveBeenLastCalledWith(
'Error: failed to list experiments: ',
new Error('bad stuff happened'),
);
});
it('loads runs for a given experiment id when it is expanded', async () => {
listRunsSpy.mockImplementation(() => {});
mockNExperiments(1);
const props = generateProps();
tree = TestUtils.mountWithRouter(<ExperimentList {...props} />);
await (tree.instance() as ExperimentListTest)._loadExperiments({});
tree.update();
expect(props.onError).not.toHaveBeenCalled();
expect(tree.state()).toHaveProperty('displayExperiments', [
{
expandState: ExpandState.COLLAPSED,
experiment_id: 'testexperiment1',
display_name: 'experiment with id: testexperiment1',
},
]);
// Expand the first experiment
tree
.find('button[aria-label="Expand"]')
.at(0)
.simulate('click');
await listRunsSpy;
tree.update();
expect(tree.state()).toHaveProperty('displayExperiments', [
{
expandState: ExpandState.EXPANDED,
experiment_id: 'testexperiment1',
display_name: 'experiment with id: testexperiment1',
},
]);
expect(Apis.runServiceApiV2.listRuns).toHaveBeenCalledTimes(1);
expect(Apis.runServiceApiV2.listRuns).toHaveBeenLastCalledWith(
undefined,
'testexperiment1',
'',
10,
'created_at desc',
encodeURIComponent(
JSON.stringify({
predicates: [
{
key: 'storage_state',
operation: V2beta1PredicateOperation.NOTEQUALS,
string_value: V2beta1RunStorageState.ARCHIVED.toString(),
},
],
} as V2beta1Filter),
),
);
});
it('loads runs for a given experiment id with augumented storage state when it is expanded', async () => {
listRunsSpy.mockImplementation(() => {});
mockNExperiments(1);
const props = generateProps();
props.storageState = V2beta1ExperimentStorageState.ARCHIVED;
tree = TestUtils.mountWithRouter(<ExperimentList {...props} />);
await (tree.instance() as ExperimentListTest)._loadExperiments({});
tree.update();
expect(props.onError).not.toHaveBeenCalled();
expect(tree.state()).toHaveProperty('displayExperiments', [
{
expandState: ExpandState.COLLAPSED,
experiment_id: 'testexperiment1',
display_name: 'experiment with id: testexperiment1',
},
]);
// Expand the first experiment
tree
.find('button[aria-label="Expand"]')
.at(0)
.simulate('click');
await listRunsSpy;
tree.update();
expect(tree.state()).toHaveProperty('displayExperiments', [
{
expandState: ExpandState.EXPANDED,
experiment_id: 'testexperiment1',
display_name: 'experiment with id: testexperiment1',
},
]);
expect(Apis.runServiceApiV2.listRuns).toHaveBeenCalledTimes(1);
expect(Apis.runServiceApiV2.listRuns).toHaveBeenLastCalledWith(
undefined,
'testexperiment1',
'',
10,
'created_at desc',
encodeURIComponent(
JSON.stringify({
predicates: [
{
key: 'storage_state',
operation: V2beta1PredicateOperation.EQUALS,
string_value: V2beta1ExperimentStorageState.ARCHIVED.toString(),
},
],
} as V2beta1Filter),
),
);
});
});
| 267 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CustomTableRow.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Tooltip from '@material-ui/core/Tooltip';
import WarningIcon from '@material-ui/icons/WarningRounded';
import { Row, Column } from './CustomTable';
import { color, fonts, fontsize } from '../Css';
import { stylesheet } from 'typestyle';
export const css = stylesheet({
cell: {
$nest: {
'&:not(:nth-child(2))': {
color: color.inactive,
},
},
alignSelf: 'center',
borderBottom: 'initial',
color: color.foreground,
fontFamily: fonts.secondary,
fontSize: fontsize.base,
letterSpacing: 0.25,
marginRight: 20,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
icon: {
color: color.alert,
height: 18,
paddingRight: 4,
verticalAlign: 'sub',
width: 18,
},
row: {
$nest: {
'&:hover': {
backgroundColor: '#f3f3f3',
},
'&:hover a': {
color: color.linkLight,
},
},
borderBottom: '1px solid #ddd',
display: 'flex',
flexShrink: 0,
height: 40,
outline: 'none',
},
});
interface CustomTableRowProps {
row: Row;
columns: Column[];
}
function calculateColumnWidths(columns: Column[]): number[] {
const totalFlex = columns.reduce((total, c) => (total += c.flex || 1), 0);
return columns.map(c => ((c.flex || 1) / totalFlex) * 100);
}
// tslint:disable-next-line:variable-name
export const CustomTableRow: React.FC<CustomTableRowProps> = (props: CustomTableRowProps) => {
const { row, columns } = props;
const widths = calculateColumnWidths(columns);
return (
<React.Fragment>
{row.otherFields.map((cell, i) => (
<div key={i} style={{ width: widths[i] + '%' }} className={css.cell}>
{i === 0 && row.error && (
<Tooltip title={row.error}>
<WarningIcon className={css.icon} />
</Tooltip>
)}
{columns[i].customRenderer
? columns[i].customRenderer!({ value: cell, id: row.id })
: cell}
</div>
))}
</React.Fragment>
);
};
| 268 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Toolbar.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import { History } from 'history';
import * as React from 'react';
import { CSSProperties } from 'react';
import { Link } from 'react-router-dom';
import { classes, stylesheet } from 'typestyle';
import BusyButton from '../atoms/BusyButton';
import { color, commonCss, dimension, fonts, fontsize, spacing } from '../Css';
export interface ToolbarActionMap {
[key: string]: ToolbarActionConfig;
}
export interface ToolbarActionConfig {
action: () => void;
busy?: boolean;
disabled?: boolean;
disabledTitle?: string;
icon?: any;
id?: string;
outlined?: boolean;
primary?: boolean;
style?: CSSProperties;
title: string;
tooltip: string;
}
export interface Breadcrumb {
displayName: string;
href: string;
}
const backIconHeight = 24;
const css = stylesheet({
actions: {
display: 'flex',
marginRight: spacing.units(-2),
paddingTop: 25,
alignItems: 'center',
},
backIcon: {
fontSize: backIconHeight,
verticalAlign: 'bottom',
},
backLink: {
cursor: 'pointer',
marginRight: 10,
padding: 3,
},
breadcrumbs: {
color: color.inactive,
fontFamily: fonts.secondary,
fontSize: fontsize.small,
letterSpacing: 0.25,
margin: '10px 37px',
},
chevron: {
height: 12,
},
disabled: {
color: '#aaa',
},
enabled: {
color: color.foreground,
},
link: {
$nest: {
'&:hover': {
background: color.lightGrey,
},
},
borderRadius: 3,
padding: 3,
},
pageName: {
color: color.strong,
fontSize: fontsize.pageTitle,
lineHeight: '28px',
},
root: {
alignItems: 'center',
display: 'flex',
flexShrink: 0,
height: dimension.jumbo,
justifyContent: 'space-between',
},
topLevelToolbar: {
borderBottom: `1px solid ${color.lightGrey}`,
paddingBottom: 15,
paddingLeft: 20,
},
});
export interface ToolbarProps {
actions: ToolbarActionMap;
breadcrumbs: Breadcrumb[];
history?: History;
pageTitle: string | JSX.Element;
pageTitleTooltip?: string;
topLevelToolbar?: boolean;
}
class Toolbar extends React.Component<ToolbarProps> {
public render(): JSX.Element | null {
const { actions, breadcrumbs, pageTitle, pageTitleTooltip } = { ...this.props };
if (!actions.length && !breadcrumbs.length && !pageTitle) {
return null;
}
return (
<div
className={classes(css.root, this.props.topLevelToolbar !== false && css.topLevelToolbar)}
>
<div style={{ minWidth: 100 }}>
{/* Breadcrumb */}
<div className={classes(css.breadcrumbs, commonCss.flex)}>
{breadcrumbs.map((crumb, i) => (
<span className={commonCss.flex} key={i} title={crumb.displayName}>
{i !== 0 && <ChevronRightIcon className={css.chevron} />}
<Link
className={classes(commonCss.unstyled, commonCss.ellipsis, css.link)}
to={crumb.href}
>
{crumb.displayName}
</Link>
</span>
))}
</div>
<div className={commonCss.flex}>
{/* Back Arrow */}
{breadcrumbs.length > 0 && (
<Tooltip title={'Back'} enterDelay={300}>
<div>
{' '}
{/* Div needed because we sometimes disable a button within a tooltip */}
<IconButton
className={css.backLink}
disabled={this.props.history!.length < 2}
onClick={this.props.history!.goBack}
>
<ArrowBackIcon
className={classes(
css.backIcon,
this.props.history!.length < 2 ? css.disabled : css.enabled,
)}
/>
</IconButton>
</div>
</Tooltip>
)}
{/* Resource Name */}
<span
className={classes(css.pageName, commonCss.ellipsis)}
title={pageTitleTooltip}
data-testid='page-title' // TODO: use a proper h1 tag for page titles and let tests query this by h1.
>
{pageTitle}
</span>
</div>
</div>
{/* Actions / Buttons */}
<div className={css.actions}>
{Object.keys(actions).map((buttonKey, i) => {
const button = actions[buttonKey];
return (
<Tooltip
title={
button.disabled && button.disabledTitle ? button.disabledTitle : button.tooltip
}
enterDelay={300}
key={i}
>
<div style={button.style}>
{/* Extra level needed by tooltip when child is disabled */}
<BusyButton
id={button.id}
color='secondary'
onClick={button.action}
disabled={button.disabled}
title={button.title}
icon={button.icon}
busy={button.busy || false}
outlined={(button.outlined && !button.primary) || false}
className={button.primary ? commonCss.buttonAction : ''}
/>
</div>
</Tooltip>
);
})}
</div>
</div>
);
}
}
export default Toolbar;
| 269 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/NewRunParametersV2.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Button, Checkbox, FormControlLabel, InputAdornment, TextField } from '@material-ui/core';
import * as React from 'react';
import { useEffect, useState } from 'react';
import { PipelineSpecRuntimeConfig } from 'src/apis/run';
import { ExternalLink } from 'src/atoms/ExternalLink';
import { ParameterType_ParameterTypeEnum } from 'src/generated/pipeline_spec/pipeline_spec';
import { RuntimeParameters, SpecParameters } from 'src/pages/NewRunV2';
import { classes, stylesheet } from 'typestyle';
import { color, commonCss, spacing, padding } from '../Css';
import Editor from './Editor';
const css = stylesheet({
button: {
margin: 0,
padding: '3px 5px',
},
key: {
color: color.strong,
flex: '0 0 50%',
fontWeight: 'bold',
maxWidth: 300,
},
nonEditableInput: {
color: color.secondaryText,
},
row: {
borderBottom: `1px solid ${color.divider}`,
display: 'flex',
padding: `${spacing.units(-5)}px ${spacing.units(-6)}px`,
},
textfield: {
maxWidth: 600,
},
});
interface NewRunParametersProps {
titleMessage: string;
pipelineRoot?: string;
// ComponentInputsSpec_ParameterSpec
specParameters: SpecParameters;
clonedRuntimeConfig?: PipelineSpecRuntimeConfig;
handlePipelineRootChange?: (pipelineRoot?: string) => void;
handleParameterChange?: (parameters: RuntimeParameters) => void;
setIsValidInput?: (isValid: boolean) => void;
}
const protoMap = new Map<string, string>([
['NUMBER_DOUBLE', 'double'],
['NUMBER_INTEGER', 'integer'],
['STRING', 'string'],
['BOOLEAN', 'boolean'],
['LIST', 'list'],
['STRUCT', 'dict'],
]);
function convertInput(paramStr: string, paramType: ParameterType_ParameterTypeEnum): any {
if (paramStr === '' && paramType !== ParameterType_ParameterTypeEnum.STRING) {
return undefined;
}
switch (paramType) {
case ParameterType_ParameterTypeEnum.BOOLEAN:
if (paramStr === 'true' || paramStr === 'false') {
return paramStr === 'true';
}
return null;
case ParameterType_ParameterTypeEnum.STRING:
return paramStr;
case ParameterType_ParameterTypeEnum.NUMBER_INTEGER:
if (Number.isInteger(Number(paramStr))) {
return Number(paramStr);
}
return null;
case ParameterType_ParameterTypeEnum.NUMBER_DOUBLE:
if (!Number.isNaN(Number(paramStr))) {
return Number(paramStr);
}
return null;
case ParameterType_ParameterTypeEnum.LIST:
if (!paramStr.trim().startsWith('[')) {
return null;
}
try {
return JSON.parse(paramStr);
} catch (err) {
return null;
}
case ParameterType_ParameterTypeEnum.STRUCT:
if (!paramStr.trim().startsWith('{')) {
return null;
}
try {
return JSON.parse(paramStr);
} catch (err) {
return null;
}
default:
// TODO: (jlyaoyuli) Validate if the type of parameters matches the value
// If it doesn't throw an error message next to the TextField.
console.log('Unknown paramter type: ' + paramType);
return null;
}
}
function generateInputValidationErrMsg(
parametersInRealType: any,
paramType: ParameterType_ParameterTypeEnum,
) {
let errorMessage;
switch (parametersInRealType) {
case undefined:
errorMessage = 'Missing parameter.';
break;
// TODO(jlyaoyuli): tell the error difference between mismatch type or invalid JSON form.
case null:
errorMessage =
'Invalid input. This parameter should be in ' +
protoMap.get(ParameterType_ParameterTypeEnum[paramType]) +
' type';
break;
default:
errorMessage = null;
}
return errorMessage;
}
function convertNonUserInputParamToString(
specParameters: SpecParameters,
key: string,
value: any,
): string {
let paramStr;
if (!specParameters[key]) {
return '';
}
switch (specParameters[key].parameterType) {
case ParameterType_ParameterTypeEnum.STRUCT:
case ParameterType_ParameterTypeEnum.LIST:
paramStr = JSON.stringify(value);
break;
case ParameterType_ParameterTypeEnum.BOOLEAN:
case ParameterType_ParameterTypeEnum.NUMBER_INTEGER:
case ParameterType_ParameterTypeEnum.NUMBER_DOUBLE:
paramStr = value.toString();
break;
default:
paramStr = value;
}
return paramStr;
}
function NewRunParametersV2(props: NewRunParametersProps) {
const {
specParameters,
clonedRuntimeConfig,
handlePipelineRootChange,
handleParameterChange,
setIsValidInput,
} = props;
const [customPipelineRootChecked, setCustomPipelineRootChecked] = useState(false);
const [customPipelineRoot, setCustomPipelineRoot] = useState(props.pipelineRoot);
const [errorMessages, setErrorMessages] = useState<string[]>([]);
const [updatedParameters, setUpdatedParameters] = useState({});
useEffect(() => {
if (clonedRuntimeConfig && clonedRuntimeConfig.parameters) {
const clonedRuntimeParametersStr: RuntimeParameters = {};
// Convert cloned parameter to string type first to avoid error from convertInput
Object.entries(clonedRuntimeConfig.parameters).forEach(entry => {
clonedRuntimeParametersStr[entry[0]] = convertNonUserInputParamToString(
specParameters,
entry[0],
entry[1],
);
});
setUpdatedParameters(clonedRuntimeParametersStr);
// Directly using cloned paramters guarantees input is valid and no error message
setErrorMessages([]);
if (setIsValidInput) {
setIsValidInput(true);
}
if (clonedRuntimeConfig && handleParameterChange) {
handleParameterChange(clonedRuntimeConfig.parameters);
}
return;
}
// TODO(jlyaoyuli): If we have parameters from run, put original default value next to the paramKey
const runtimeParametersWithDefault: RuntimeParameters = {};
let allParamtersWithDefault = true;
let errMsg: string[] = [];
Object.keys(specParameters).forEach(key => {
if (specParameters[key].defaultValue) {
// TODO(zijianjoy): Make sure to consider all types of parameters.
// Convert default value to string type first to avoid error from convertInput
runtimeParametersWithDefault[key] = convertNonUserInputParamToString(
specParameters,
key,
specParameters[key].defaultValue,
);
} else {
allParamtersWithDefault = false;
errMsg[key] = 'Missing parameter.';
}
});
setUpdatedParameters(runtimeParametersWithDefault);
setErrorMessages(errMsg);
if (setIsValidInput) {
setIsValidInput(allParamtersWithDefault);
}
}, [clonedRuntimeConfig, specParameters, handleParameterChange, setIsValidInput]);
useEffect(() => {
if (clonedRuntimeConfig?.pipeline_root) {
setCustomPipelineRootChecked(true);
setCustomPipelineRoot(clonedRuntimeConfig.pipeline_root);
}
}, [clonedRuntimeConfig]);
return (
<div>
<div className={commonCss.header}>Pipeline Root</div>
<div>
Pipeline Root represents an artifact repository, refer to{' '}
<ExternalLink href='https://www.kubeflow.org/docs/components/pipelines/overview/pipeline-root/'>
Pipeline Root Documentation
</ExternalLink>
.
</div>
<div>
<FormControlLabel
label='Custom Pipeline Root'
control={
<Checkbox
color='primary'
checked={customPipelineRootChecked}
onChange={(event, checked) => {
setCustomPipelineRootChecked(checked);
if (!checked) {
setCustomPipelineRoot(undefined);
if (handlePipelineRootChange) {
handlePipelineRootChange(undefined);
}
}
}}
inputProps={{ 'aria-label': 'Set custom pipeline root.' }}
/>
}
/>
</div>
{customPipelineRootChecked && (
<TextField
id={'[pipeline-root]'}
variant='outlined'
label={'pipeline-root'}
value={customPipelineRoot || ''}
onChange={ev => {
setCustomPipelineRoot(ev.target.value);
if (handlePipelineRootChange) {
handlePipelineRootChange(ev.target.value);
}
}}
className={classes(commonCss.textField, css.textfield)}
/>
)}
<div className={commonCss.header}>Run parameters</div>
<div>{props.titleMessage}</div>
{!!Object.keys(specParameters).length && (
<div>
{Object.entries(specParameters).map(([k, v]) => {
const param = {
key: `${k} - ${protoMap.get(ParameterType_ParameterTypeEnum[v.parameterType])}`,
value: updatedParameters[k],
type: v.parameterType,
errorMsg: errorMessages[k],
};
return (
<div>
<ParamEditor
key={k}
id={k}
onChange={value => {
let allInputsValid: boolean = true;
let parametersInRealType: RuntimeParameters = {};
const nextUpdatedParameters: RuntimeParameters = {};
Object.assign(nextUpdatedParameters, updatedParameters);
nextUpdatedParameters[k] = value;
setUpdatedParameters(nextUpdatedParameters);
Object.entries(nextUpdatedParameters).forEach(([k1, paramStr]) => {
parametersInRealType[k1] = convertInput(
paramStr,
specParameters[k1].parameterType,
);
});
if (handleParameterChange) {
handleParameterChange(parametersInRealType);
}
errorMessages[k] = generateInputValidationErrMsg(
parametersInRealType[k],
specParameters[k].parameterType,
);
setErrorMessages(errorMessages);
Object.values(errorMessages).forEach(errorMessage => {
allInputsValid = allInputsValid && errorMessage === null;
});
if (setIsValidInput) {
setIsValidInput(allInputsValid);
}
}}
param={param}
/>
<div className={classes(padding(20, 'r'))} style={{ color: 'red' }}>
{param.errorMsg}
</div>
</div>
);
})}
</div>
)}
</div>
);
}
export default NewRunParametersV2;
interface Param {
key: string;
value: any;
type: ParameterType_ParameterTypeEnum;
errorMsg: string;
}
interface ParamEditorProps {
id: string;
onChange: (value: string) => void;
param: Param;
}
interface ParamEditorState {
isEditorOpen: boolean;
isInJsonForm: boolean;
isJsonField: boolean;
}
class ParamEditor extends React.Component<ParamEditorProps, ParamEditorState> {
public static getDerivedStateFromProps(
nextProps: ParamEditorProps,
prevState: ParamEditorState,
): { isInJsonForm: boolean; isJsonField: boolean } {
let isJson = true;
let paramType = nextProps.param.type;
switch (paramType) {
case ParameterType_ParameterTypeEnum.LIST:
case ParameterType_ParameterTypeEnum.STRUCT:
isJson = true;
break;
case ParameterType_ParameterTypeEnum.STRING:
case ParameterType_ParameterTypeEnum.BOOLEAN:
case ParameterType_ParameterTypeEnum.NUMBER_INTEGER:
case ParameterType_ParameterTypeEnum.NUMBER_DOUBLE:
isJson = false;
break;
default:
isJson = false;
}
return {
isInJsonForm: isJson,
isJsonField: prevState.isJsonField || isJson,
};
}
public state = {
isEditorOpen: false,
isInJsonForm: false,
isJsonField: false,
};
public render(): JSX.Element | null {
const { id, onChange, param } = this.props;
const onClick = () => {
if (this.state.isInJsonForm) {
let paramType = param.type;
let displayValue;
switch (paramType) {
case ParameterType_ParameterTypeEnum.LIST:
displayValue = JSON.parse(param.value || '[]');
break;
case ParameterType_ParameterTypeEnum.STRUCT:
displayValue = JSON.parse(param.value || '{}');
break;
default:
// TODO(jlyaoyuli): If the type from PipelineSpec is either LIST or STURCT,
// but the user-input or default value is invalid JSON form, show error message.
displayValue = JSON.parse('');
}
// TODO(zijianjoy): JSON format needs to be struct or list type.
if (this.state.isEditorOpen) {
onChange(JSON.stringify(displayValue) || '');
} else {
onChange(JSON.stringify(displayValue, null, 2) || '');
}
}
this.setState({
isEditorOpen: !this.state.isEditorOpen,
});
};
return (
<>
{this.state.isJsonField ? (
<TextField
id={id}
disabled={this.state.isEditorOpen}
variant='outlined'
label={param.key}
value={param.value || ''}
onChange={ev => onChange(ev.target.value || '')}
className={classes(commonCss.textField, css.textfield)}
InputProps={{
classes: { disabled: css.nonEditableInput },
endAdornment: (
<InputAdornment position='end'>
<Button className={css.button} color='secondary' onClick={onClick}>
{this.state.isEditorOpen ? 'Close Json Editor' : 'Open Json Editor'}
</Button>
</InputAdornment>
),
readOnly: false,
}}
/>
) : (
<TextField
id={id}
variant='outlined'
label={param.key}
//TODO(zijianjoy): Convert defaultValue to correct type.
value={param.value || ''}
onChange={ev => onChange(ev.target.value || '')}
className={classes(commonCss.textField, css.textfield)}
/>
)}
{this.state.isJsonField && this.state.isEditorOpen && (
<div className={css.row}>
<Editor
width='100%'
minLines={3}
maxLines={20}
mode='json'
theme='github'
highlightActiveLine={true}
showGutter={true}
readOnly={false}
onChange={text => onChange(text || '')}
value={param.value || ''}
/>
</div>
)}
</>
);
}
}
| 270 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Editor.test.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { mount } from 'enzyme';
import Editor from './Editor';
/*
These tests mimic https://github.com/securingsincity/react-ace/blob/master/tests/src/ace.spec.js
to ensure that editor properties (placeholder and value) can be properly
tested.
*/
describe('Editor', () => {
it('renders without a placeholder and value', () => {
const tree = mount(<Editor />);
expect(tree.html()).toMatchSnapshot();
});
it('renders with a placeholder', () => {
const placeholder = 'I am a placeholder.';
const tree = mount(<Editor placeholder={placeholder} />);
expect(tree.html()).toMatchSnapshot();
});
it('renders a placeholder that contains HTML', () => {
const placeholder = 'I am a placeholder with <strong>HTML</strong>.';
const tree = mount(<Editor placeholder={placeholder} />);
expect(tree.html()).toMatchSnapshot();
});
it('has its value set to the provided value', () => {
const value = 'I am a value.';
const tree = mount(<Editor value={value} />);
expect(tree).not.toBeNull();
const editor = (tree.instance() as any).editor;
expect(editor.getValue()).toBe(value);
});
});
| 271 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Trigger.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Button from '@material-ui/core/Button';
import Checkbox from '@material-ui/core/Checkbox';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import MenuItem from '@material-ui/core/MenuItem';
import * as React from 'react';
import { classes, stylesheet } from 'typestyle';
import { TriggerSchedule } from '../lib/TriggerUtils';
import { HelpButton } from '../atoms/HelpButton';
import { ExternalLink } from '../atoms/ExternalLink';
import Input from '../atoms/Input';
import Separator from '../atoms/Separator';
import { color, commonCss, padding } from '../Css';
import {
buildCron,
buildTrigger,
dateToPickerFormat,
PeriodicInterval,
pickersToDate,
triggers,
TriggerType,
parseTrigger,
ParsedTrigger,
} from '../lib/TriggerUtils';
import { logger } from 'src/lib/Utils';
type TriggerInitialProps = {
maxConcurrentRuns?: string;
catchup?: boolean;
trigger?: TriggerSchedule;
};
interface TriggerProps {
initialProps?: TriggerInitialProps;
onChange?: (config: {
trigger?: TriggerSchedule;
maxConcurrentRuns?: string;
catchup: boolean;
}) => void;
}
interface TriggerState {
cron: string;
editCron: boolean;
endDate: string;
endTime: string;
hasEndDate: boolean;
hasStartDate: boolean;
intervalCategory: PeriodicInterval;
intervalValue: number;
maxConcurrentRuns: string;
selectedDays: boolean[];
startDate: string;
startTime: string;
type: TriggerType;
catchup: boolean;
startTimeMessage: string;
endTimeMessage: string;
}
const css = stylesheet({
noMargin: {
margin: 0,
},
alert: {
color: color.alert,
},
});
export default class Trigger extends React.Component<TriggerProps, TriggerState> {
public state: TriggerState = (() => {
const { maxConcurrentRuns, catchup, trigger } =
this.props.initialProps || ({} as TriggerInitialProps);
let parsedTrigger: Partial<ParsedTrigger> = {};
try {
if (trigger) {
parsedTrigger = parseTrigger(trigger);
}
} catch (err) {
logger.warn('Failed to parse original trigger: ', trigger);
logger.warn(err);
}
const startDateTime = parsedTrigger.startDateTime ?? new Date();
const endDateTime =
parsedTrigger.endDateTime ??
new Date(
startDateTime.getFullYear(),
startDateTime.getMonth(),
startDateTime.getDate() + 7,
startDateTime.getHours(),
startDateTime.getMinutes(),
);
const [startDate, startTime] = dateToPickerFormat(startDateTime);
const [endDate, endTime] = dateToPickerFormat(endDateTime);
return {
catchup: catchup ?? true,
maxConcurrentRuns: maxConcurrentRuns || '10',
hasEndDate: !!parsedTrigger?.endDateTime,
endDate,
endTime,
hasStartDate: !!parsedTrigger?.startDateTime,
startDate,
startTime,
selectedDays: new Array(7).fill(true),
type: parsedTrigger.type ?? TriggerType.INTERVALED,
// cron state
editCron: parsedTrigger.type === TriggerType.CRON,
cron: parsedTrigger.cron || '',
// interval state
intervalCategory: parsedTrigger.intervalCategory ?? PeriodicInterval.HOUR,
intervalValue: parsedTrigger.intervalValue ?? 1,
startTimeMessage: '',
endTimeMessage: '',
};
})();
public componentDidMount(): void {
// TODO: This is called here because NewRun only updates its Trigger in state when onChange is
// called on the Trigger, which without this may never happen if a user doesn't interact with
// the Trigger. NewRun should probably keep the Trigger state and pass it down as a prop to this
this._updateTrigger();
}
public render(): JSX.Element {
const {
cron,
editCron,
endDate,
endTime,
hasEndDate,
hasStartDate,
intervalCategory,
intervalValue,
maxConcurrentRuns,
selectedDays,
startDate,
startTime,
type,
catchup,
startTimeMessage,
endTimeMessage,
} = this.state;
return (
<div>
<Input
select={true}
label='Trigger type'
required={true}
onChange={this.handleChange('type')}
value={type}
variant='outlined'
>
{Array.from(triggers.entries()).map((trigger, i) => (
<MenuItem key={i} value={trigger[0]}>
{trigger[1].displayName}
</MenuItem>
))}
</Input>
<div>
<Input
label='Maximum concurrent runs'
required={true}
onChange={this.handleChange('maxConcurrentRuns')}
value={maxConcurrentRuns}
variant='outlined'
/>
{!(Number.isInteger(Number(maxConcurrentRuns)) && Number(maxConcurrentRuns) > 0) && (
<div className={classes(padding(20, 'r'))} style={{ color: 'red' }}>
{'Invalid input. The maximum concurrent runs should be a positive integer.'}
</div>
)}
<div className={commonCss.flex}>
<FormControlLabel
control={
<Checkbox
checked={hasStartDate}
color='primary'
onClick={this.handleChange('hasStartDate')}
/>
}
label='Has start date'
/>
<Input
label='Start date'
type='date'
onChange={this.handleChange('startDate')}
value={startDate}
width={160}
variant='outlined'
InputLabelProps={{ classes: { outlined: css.noMargin }, shrink: true }}
style={{ visibility: hasStartDate ? 'visible' : 'hidden' }}
/>
<Separator />
<Input
label='Start time'
type='time'
onChange={this.handleChange('startTime')}
value={startTime}
width={120}
variant='outlined'
InputLabelProps={{ classes: { outlined: css.noMargin }, shrink: true }}
style={{ visibility: hasStartDate ? 'visible' : 'hidden' }}
/>
</div>
<div
data-testid='startTimeMessage'
className={css.alert}
style={{ visibility: hasStartDate ? 'visible' : 'hidden' }}
>
{startTimeMessage}
</div>
<div className={commonCss.flex}>
<FormControlLabel
control={
<Checkbox
checked={hasEndDate}
color='primary'
onClick={this.handleChange('hasEndDate')}
/>
}
label='Has end date'
/>
<Input
label='End date'
type='date'
onChange={this.handleChange('endDate')}
value={endDate}
width={160}
style={{ visibility: hasEndDate ? 'visible' : 'hidden' }}
InputLabelProps={{ classes: { outlined: css.noMargin }, shrink: true }}
variant='outlined'
/>
<Separator />
<Input
label='End time'
type='time'
onChange={this.handleChange('endTime')}
value={endTime}
width={120}
style={{ visibility: hasEndDate ? 'visible' : 'hidden' }}
InputLabelProps={{ classes: { outlined: css.noMargin }, shrink: true }}
variant='outlined'
/>
</div>
<div
data-testid='endTimeMessage'
className={css.alert}
style={{ visibility: hasEndDate ? 'visible' : 'hidden' }}
>
{endTimeMessage}
</div>
<span className={commonCss.flex}>
<FormControlLabel
control={
<Checkbox
checked={catchup}
color='primary'
onClick={this.handleChange('catchup')}
/>
}
label='Catchup'
/>
<HelpButton
helpText={
<div>
<p>
Whether the recurring run should catch up if behind schedule. Defaults to true.
</p>
<p>
For example, if the recurring run is paused for a while and re-enabled
afterwards. If catchup=true, the scheduler will catch up on (backfill) each
missed interval. Otherwise, it only schedules the latest interval if more than
one interval is ready to be scheduled.
</p>
<p>
Usually, if your pipeline handles backfill internally, you should turn catchup
off to avoid duplicate backfill.
</p>
</div>
}
/>
</span>
<span className={commonCss.flex}>
Run every
{type === TriggerType.INTERVALED && (
<div className={commonCss.flex}>
<Separator />
<Input
required={true}
type='number'
onChange={this.handleChange('intervalValue')}
value={intervalValue}
height={30}
width={65}
error={intervalValue < 1}
variant='outlined'
/>
</div>
)}
<Separator />
<Input
required={true}
select={true}
onChange={this.handleChange('intervalCategory')}
value={intervalCategory}
height={30}
width={95}
variant='outlined'
>
{Object.keys(PeriodicInterval).map((interval, i) => (
<MenuItem key={i} value={PeriodicInterval[interval]}>
{PeriodicInterval[interval] + (type === TriggerType.INTERVALED ? 's' : '')}
</MenuItem>
))}
</Input>
</span>
</div>
{type === TriggerType.CRON && (
<div>
{intervalCategory === PeriodicInterval.WEEK && (
<div>
<span>On:</span>
<FormControlLabel
control={
<Checkbox
checked={this._isAllDaysChecked()}
color='primary'
onClick={this._toggleCheckAllDays.bind(this)}
/>
}
label='All'
/>
<Separator />
{['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((day, i) => (
<Button
variant='fab'
mini={true}
key={i}
onClick={() => this._toggleDay(i)}
color={selectedDays[i] ? 'primary' : 'secondary'}
>
{day}
</Button>
))}
</div>
)}
<div className={commonCss.flex}>
<FormControlLabel
control={
<Checkbox
checked={editCron}
color='primary'
onClick={this.handleChange('editCron')}
/>
}
label={
<span>
Allow editing cron expression. (format is specified{' '}
<ExternalLink href='https://pkg.go.dev/github.com/robfig/cron#hdr-CRON_Expression_Format'>
here
</ExternalLink>
)
</span>
}
/>
</div>
<Input
label='cron expression'
onChange={this.handleChange('cron')}
value={cron}
width={300}
disabled={!editCron}
variant='outlined'
/>
<div>Note: Start and end dates/times are handled outside of cron.</div>
</div>
)}
</div>
);
}
public handleChange = (name: string) => (event: any) => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
// Make sure the desired field is set on the state object first, then
// use the state values to compute the new trigger
this.setState(
{
[name]: value,
} as any,
this._updateTrigger,
);
};
private _updateTrigger = () => {
const {
hasStartDate,
hasEndDate,
startDate,
startTime,
endDate,
endTime,
editCron,
intervalCategory,
intervalValue,
type,
cron,
selectedDays,
catchup,
} = this.state;
var startDateTime: Date | undefined = undefined;
var endDateTime: Date | undefined = undefined;
var startTimeMessage = '';
var endTimeMessage = '';
try {
if (hasStartDate) {
startDateTime = pickersToDate(hasStartDate, startDate, startTime);
}
} catch (e) {
if (e.message === 'Invalid picker format') {
startTimeMessage = "Invalid start date or time, start time won't be set";
} else {
throw e;
}
}
try {
if (hasEndDate) {
endDateTime = pickersToDate(hasEndDate, endDate, endTime);
}
} catch (e) {
if (e.message === 'Invalid picker format') {
endTimeMessage = "Invalid end date or time, end time won't be set";
} else {
throw e;
}
}
this.setState({
startTimeMessage: startTimeMessage,
endTimeMessage: endTimeMessage,
});
// TODO: Why build the cron string unless the TriggerType is not CRON?
// Unless cron editing is enabled, calculate the new cron string, set it in state,
// then use it to build new trigger object and notify the parent
this.setState(
{
cron: editCron ? cron : buildCron(startDateTime, intervalCategory, selectedDays),
},
() => {
const trigger = buildTrigger(
intervalCategory,
intervalValue,
startDateTime,
endDateTime,
type,
this.state.cron,
);
if (this.props.onChange) {
this.props.onChange({
catchup,
maxConcurrentRuns: trigger ? this.state.maxConcurrentRuns : undefined,
trigger,
});
}
},
);
};
private _isAllDaysChecked(): boolean {
return this.state.selectedDays.every(d => !!d);
}
private _toggleCheckAllDays(): void {
const isAllChecked = this._isAllDaysChecked();
this.state.selectedDays.forEach((d, i) => {
if (d !== !isAllChecked) {
this._toggleDay(i);
}
});
}
private _toggleDay(index: number): void {
const newDays = this.state.selectedDays;
newDays[index] = !newDays[index];
const startDate = pickersToDate(
this.state.hasStartDate,
this.state.startDate,
this.state.startTime,
);
const cron = buildCron(startDate, this.state.intervalCategory, this.state.selectedDays);
this.setState(
{
cron,
selectedDays: newDays,
},
this._updateTrigger,
);
}
}
| 272 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CustomTable.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { render, screen, fireEvent } from '@testing-library/react';
import * as React from 'react';
import CustomTable, { Column, ExpandState, Row, css } from './CustomTable';
import TestUtils from '../TestUtils';
import { V2beta1PredicateOperation } from '../apisv2beta1/filter';
import { shallow } from 'enzyme';
const props = {
columns: [],
orderAscending: true,
pageSize: 10,
reload: () => '' as any,
rows: [],
sortBy: 'asd',
};
const columns: Column[] = [
{
customRenderer: undefined,
label: 'col1',
},
{
customRenderer: undefined,
label: 'col2',
},
];
const rows: Row[] = [
{
id: 'row1',
otherFields: ['cell1', 'cell2'],
},
{
id: 'row2',
otherFields: ['cell1', 'cell2'],
},
];
// tslint:disable-next-line:no-console
const consoleErrorBackup = console.error;
let consoleSpy: jest.Mock;
class CustomTableTest extends CustomTable {
public _requestFilter(filterString?: string): Promise<void> {
return super._requestFilter(filterString);
}
}
describe('CustomTable', () => {
beforeAll(() => {
consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => null);
});
afterAll(() => {
// tslint:disable-next-line:no-console
console.error = consoleErrorBackup;
});
it('renders with default filter label', async () => {
const tree = shallow(<CustomTable {...props} />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders with provided filter label', async () => {
const tree = shallow(<CustomTable {...props} filterLabel='test filter label' />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders without filter box', async () => {
const tree = shallow(<CustomTable {...props} noFilterBox={true} />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders without rows or columns', async () => {
const tree = shallow(<CustomTable {...props} />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders empty message on no rows', async () => {
const tree = shallow(<CustomTable {...props} emptyMessage='test empty message' />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders some columns with equal widths without rows', async () => {
const tree = shallow(
<CustomTable {...props} columns={[{ label: 'col1' }, { label: 'col2' }]} />,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders without the checkboxes if disableSelection is true', async () => {
const tree = shallow(
<CustomTable {...props} rows={rows} columns={columns} disableSelection={true} />,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders some columns with descending sort order on first column', async () => {
const tree = shallow(
<CustomTable
{...props}
initialSortOrder='desc'
columns={[{ label: 'col1', sortKey: 'col1sortkey' }, { label: 'col2' }]}
/>,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders columns with specified widths', async () => {
const testcolumns = [
{
flex: 3,
label: 'col1',
},
{
flex: 1,
label: 'col2',
},
];
const tree = shallow(<CustomTable {...props} columns={testcolumns} />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('calls reload function with an empty page token to get rows', () => {
const reload = jest.fn();
shallow(<CustomTable {...props} reload={reload} />);
expect(reload).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: '',
});
});
it('calls reload function with sort key of clicked column, while keeping same page', () => {
const testcolumns = [
{
flex: 3,
label: 'col1',
sortKey: 'col1sortkey',
},
{
flex: 1,
label: 'col2',
sortKey: 'col2sortkey',
},
];
const reload = jest.fn();
const tree = shallow(<CustomTable {...props} reload={reload} columns={testcolumns} />);
expect(reload).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: 'col1sortkey desc',
});
tree
.find('WithStyles(TableSortLabel)')
.at(1)
.simulate('click');
expect(reload).toHaveBeenLastCalledWith({
filter: '',
orderAscending: true,
pageSize: 10,
pageToken: '',
sortBy: 'col2sortkey',
});
});
it('calls reload function with same sort key in reverse order if same column is clicked twice', () => {
const testcolumns = [
{
flex: 3,
label: 'col1',
sortKey: 'col1sortkey',
},
{
flex: 1,
label: 'col2',
sortKey: 'col2sortkey',
},
];
const reload = jest.fn();
const tree = shallow(<CustomTable {...props} reload={reload} columns={testcolumns} />);
expect(reload).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: 'col1sortkey desc',
});
tree
.find('WithStyles(TableSortLabel)')
.at(1)
.simulate('click');
expect(reload).toHaveBeenLastCalledWith({
filter: '',
orderAscending: true,
pageSize: 10,
pageToken: '',
sortBy: 'col2sortkey',
});
tree.setProps({ sortBy: 'col1sortkey' });
tree
.find('WithStyles(TableSortLabel)')
.at(1)
.simulate('click');
expect(reload).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: 'col2sortkey desc',
});
});
it('does not call reload if clicked column has no sort key', () => {
const testcolumns = [
{
flex: 3,
label: 'col1',
},
{
flex: 1,
label: 'col2',
},
];
const reload = jest.fn();
const tree = shallow(<CustomTable {...props} reload={reload} columns={testcolumns} />);
expect(reload).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: '',
});
tree
.find('WithStyles(TableSortLabel)')
.at(0)
.simulate('click');
expect(reload).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: '',
});
});
it('logs error if row has more cells than columns', () => {
shallow(<CustomTable {...props} rows={rows} />);
expect(consoleSpy).toHaveBeenLastCalledWith(
'Rows must have the same number of cells defined in columns',
);
});
it('logs error if row has fewer cells than columns', () => {
const testcolumns = [{ label: 'col1' }, { label: 'col2' }, { label: 'col3' }];
shallow(<CustomTable {...props} rows={rows} columns={testcolumns} />);
expect(consoleSpy).toHaveBeenLastCalledWith(
'Rows must have the same number of cells defined in columns',
);
});
it('renders some rows', async () => {
const tree = shallow(<CustomTable {...props} rows={rows} columns={columns} />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('starts out with no selected rows', () => {
const spy = jest.fn();
shallow(<CustomTable {...props} rows={rows} columns={columns} updateSelection={spy} />);
expect(spy).not.toHaveBeenCalled();
});
it('calls update selection callback when items are selected', () => {
const spy = jest.fn();
const tree = shallow(
<CustomTable {...props} rows={rows} columns={columns} updateSelection={spy} />,
);
tree
.find('.row')
.at(0)
.simulate('click', { stopPropagation: () => null });
expect(spy).toHaveBeenLastCalledWith(['row1']);
});
it('does not add items to selection when multiple rows are clicked', () => {
// Keeping track of selection is the parent's job.
const spy = jest.fn();
const tree = shallow(
<CustomTable {...props} rows={rows} columns={columns} updateSelection={spy} />,
);
tree
.find('.row')
.at(0)
.simulate('click', { stopPropagation: () => null });
tree
.find('.row')
.at(1)
.simulate('click', { stopPropagation: () => null });
expect(spy).toHaveBeenLastCalledWith(['row2']);
});
it('passes both selectedIds and the newly selected row to updateSelection when a row is clicked', () => {
// Keeping track of selection is the parent's job.
const selectedIds = ['previouslySelectedRow'];
const spy = jest.fn();
const tree = shallow(
<CustomTable
{...props}
selectedIds={selectedIds}
rows={rows}
columns={columns}
updateSelection={spy}
/>,
);
tree
.find('.row')
.at(0)
.simulate('click', { stopPropagation: () => null });
expect(spy).toHaveBeenLastCalledWith(['previouslySelectedRow', 'row1']);
});
it('does not call selectionCallback if disableSelection is true', () => {
const spy = jest.fn();
const tree = shallow(
<CustomTable
{...props}
rows={rows}
columns={columns}
updateSelection={spy}
disableSelection={true}
/>,
);
tree
.find('.row')
.at(0)
.simulate('click', { stopPropagation: () => null });
tree
.find('.row')
.at(1)
.simulate('click', { stopPropagation: () => null });
expect(spy).not.toHaveBeenCalled();
});
it('handles no updateSelection method being passed', () => {
const tree = shallow(<CustomTable {...props} rows={rows} columns={columns} />);
tree
.find('.row')
.at(0)
.simulate('click', { stopPropagation: () => null });
tree
.find('.columnName WithStyles(Checkbox)')
.at(0)
.simulate('change', {
target: { checked: true },
});
});
it('selects all items when head checkbox is clicked', () => {
const spy = jest.fn();
const tree = shallow(
<CustomTable {...props} rows={rows} columns={columns} updateSelection={spy} />,
);
tree
.find('.columnName WithStyles(Checkbox)')
.at(0)
.simulate('change', {
target: { checked: true },
});
expect(spy).toHaveBeenLastCalledWith(['row1', 'row2']);
});
it('unselects all items when head checkbox is clicked and all items are selected', () => {
const spy = jest.fn();
const tree = shallow(
<CustomTable {...props} rows={rows} columns={columns} updateSelection={spy} />,
);
tree
.find('.columnName WithStyles(Checkbox)')
.at(0)
.simulate('change', {
target: { checked: true },
});
expect(spy).toHaveBeenLastCalledWith(['row1', 'row2']);
tree
.find('.columnName WithStyles(Checkbox)')
.at(0)
.simulate('change', {
target: { checked: false },
});
expect(spy).toHaveBeenLastCalledWith([]);
});
it('selects all items if one item was checked then the head checkbox is clicked', () => {
const spy = jest.fn();
const tree = shallow(
<CustomTable {...props} rows={rows} columns={columns} updateSelection={spy} />,
);
tree
.find('.row')
.at(0)
.simulate('click', { stopPropagation: () => null });
tree
.find('.columnName WithStyles(Checkbox)')
.at(0)
.simulate('change', {
target: { checked: true },
});
expect(spy).toHaveBeenLastCalledWith(['row1', 'row2']);
});
it('deselects all other items if one item is selected in radio button mode', () => {
// Simulate that another row has already been selected. Just clicking another row first won't
// work here because the parent is where the selectedIds state is kept
const selectedIds = ['previouslySelectedRow'];
const spy = jest.fn();
const tree = shallow(
<CustomTable
{...props}
useRadioButtons={true}
selectedIds={selectedIds}
rows={rows}
columns={columns}
updateSelection={spy}
/>,
);
tree
.find('.row')
.at(0)
.simulate('click', { stopPropagation: () => null });
expect(spy).toHaveBeenLastCalledWith(['row1']);
});
it('disables previous and next page buttons if no next page token given', async () => {
const reloadResult = Promise.resolve('');
const spy = () => reloadResult;
const tree = shallow(<CustomTable {...props} rows={rows} columns={columns} reload={spy} />);
await TestUtils.flushPromises();
expect(tree.state()).toHaveProperty('maxPageIndex', 0);
expect(
tree
.find('WithStyles(IconButton)')
.at(0)
.prop('disabled'),
).toBeTruthy();
expect(
tree
.find('WithStyles(IconButton)')
.at(1)
.prop('disabled'),
).toBeTruthy();
});
it('enables next page button if next page token is given', async () => {
const reloadResult = Promise.resolve('some token');
const spy = () => reloadResult;
const tree = shallow(<CustomTable {...props} rows={rows} columns={columns} reload={spy} />);
await reloadResult;
expect(tree.state()).toHaveProperty('maxPageIndex', Number.MAX_SAFE_INTEGER);
expect(
tree
.find('WithStyles(IconButton)')
.at(0)
.prop('disabled'),
).toBeTruthy();
expect(
tree
.find('WithStyles(IconButton)')
.at(1)
.prop('disabled'),
).not.toBeTruthy();
});
it('calls reload with next page token when next page button is clicked', async () => {
const reloadResult = Promise.resolve('some token');
const spy = jest.fn(() => reloadResult);
const tree = shallow(<CustomTable {...props} rows={rows} columns={columns} reload={spy} />);
await TestUtils.flushPromises();
tree
.find('WithStyles(IconButton)')
.at(1)
.simulate('click');
expect(spy).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: 'some token',
sortBy: '',
});
});
it('renders new rows after clicking next page, and enables previous page button', async () => {
const reloadResult = Promise.resolve('some token');
const spy = jest.fn(() => reloadResult);
const tree = shallow(<CustomTable {...props} rows={[]} columns={columns} reload={spy} />);
await TestUtils.flushPromises();
tree
.find('WithStyles(IconButton)')
.at(1)
.simulate('click');
await TestUtils.flushPromises();
expect(spy).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: 'some token',
sortBy: '',
});
expect(tree.state()).toHaveProperty('currentPage', 1);
tree.setProps({ rows: [rows[1]] });
expect(tree).toMatchSnapshot();
expect(
tree
.find('WithStyles(IconButton)')
.at(0)
.prop('disabled'),
).not.toBeTruthy();
});
it('renders new rows after clicking previous page, and enables next page button', async () => {
const reloadResult = Promise.resolve('some token');
const spy = jest.fn(() => reloadResult);
const tree = shallow(<CustomTable {...props} rows={[]} columns={columns} reload={spy} />);
await reloadResult;
tree
.find('WithStyles(IconButton)')
.at(1)
.simulate('click');
await reloadResult;
tree
.find('WithStyles(IconButton)')
.at(0)
.simulate('click');
await TestUtils.flushPromises();
expect(spy).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: '',
});
tree.setProps({ rows });
expect(
tree
.find('WithStyles(IconButton)')
.at(0)
.prop('disabled'),
).toBeTruthy();
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('calls reload with a different page size, resets page token list when rows/page changes', async () => {
const reloadResult = Promise.resolve('some token');
const spy = jest.fn(() => reloadResult);
const tree = shallow(<CustomTable {...props} rows={[]} columns={columns} reload={spy} />);
tree.find('.' + css.rowsPerPage).simulate('change', { target: { value: 1234 } });
await TestUtils.flushPromises();
expect(spy).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 1234,
pageToken: '',
sortBy: '',
});
expect(tree.state()).toHaveProperty('tokenList', ['', 'some token']);
});
it('calls reload with a different page size, resets page token list when rows/page changes', async () => {
const reloadResult = Promise.resolve('');
const spy = jest.fn(() => reloadResult);
const tree = shallow(<CustomTable {...props} rows={[]} columns={columns} reload={spy} />);
tree.find('.' + css.rowsPerPage).simulate('change', { target: { value: 1234 } });
await reloadResult;
expect(spy).toHaveBeenLastCalledWith({
filter: '',
orderAscending: false,
pageSize: 1234,
pageToken: '',
sortBy: '',
});
expect(tree.state()).toHaveProperty('tokenList', ['']);
});
it('renders a collapsed row', async () => {
const row = { ...rows[0] };
row.expandState = ExpandState.COLLAPSED;
const tree = shallow(
<CustomTable {...props} rows={[row]} columns={columns} getExpandComponent={() => null} />,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders a collapsed row when selection is disabled', async () => {
const row = { ...rows[0] };
row.expandState = ExpandState.COLLAPSED;
const tree = shallow(
<CustomTable
{...props}
rows={[row]}
columns={columns}
getExpandComponent={() => null}
disableSelection={true}
/>,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders an expanded row', async () => {
const row = { ...rows[0] };
row.expandState = ExpandState.EXPANDED;
const tree = shallow(<CustomTable {...props} rows={[row]} columns={columns} />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('renders an expanded row with expanded component below it', async () => {
const row = { ...rows[0] };
row.expandState = ExpandState.EXPANDED;
const tree = shallow(
<CustomTable
{...props}
rows={[row]}
columns={columns}
getExpandComponent={() => <span>Hello World</span>}
/>,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('calls prop to toggle expansion', () => {
const row = { ...rows[0] };
const toggleSpy = jest.fn();
const stopPropagationSpy = jest.fn();
row.expandState = ExpandState.EXPANDED;
const tree = shallow(
<CustomTable
{...props}
rows={[row, row, row]}
columns={columns}
getExpandComponent={() => <span>Hello World</span>}
toggleExpansion={toggleSpy}
/>,
);
tree
.find('.' + css.expandButton)
.at(1)
.simulate('click', { stopPropagation: stopPropagationSpy });
expect(toggleSpy).toHaveBeenCalledWith(1);
expect(stopPropagationSpy).toHaveBeenCalledWith();
});
it('renders a table with sorting disabled', async () => {
const tree = shallow(
<CustomTable {...props} rows={rows} columns={columns} disableSorting={true} />,
);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
});
it('updates the filter string in state when the filter box input changes', async () => {
const tree = shallow(<CustomTable {...props} rows={rows} columns={columns} />);
(tree.instance() as CustomTable).handleFilterChange({ target: { value: 'test filter' } });
await TestUtils.flushPromises();
expect(tree.state('filterString')).toEqual('test filter');
expect(tree).toMatchSnapshot();
});
it('reloads the table with the encoded filter object', async () => {
const reload = jest.fn();
const tree = shallow(
<CustomTableTest {...props} reload={reload} rows={rows} columns={columns} />,
);
// lodash's debounce function doesn't play nice with Jest, so we skip the handleChange function
// and call _requestFilter directly.
(tree.instance() as CustomTableTest)._requestFilter('test filter');
const expectedEncodedFilter = encodeURIComponent(
JSON.stringify({
predicates: [
{
key: 'name',
operation: V2beta1PredicateOperation.ISSUBSTRING,
string_value: 'test filter',
},
],
}),
);
expect(tree.state('filterStringEncoded')).toEqual(expectedEncodedFilter);
expect(reload).toHaveBeenLastCalledWith({
filter: expectedEncodedFilter,
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: '',
});
});
it('uses an empty filter if requestFilter is called with no filter', async () => {
const tree = shallow(<CustomTableTest {...props} rows={rows} columns={columns} />);
(tree.instance() as CustomTableTest)._requestFilter();
expect(tree.state('filterStringEncoded')).toEqual('');
});
it('The initial filter string is called during first reload', async () => {
const reload = jest.fn();
render(
<CustomTable
{...props}
reload={reload}
rows={rows}
columns={columns}
initialFilterString={'test filter'}
/>,
);
const expectedEncodedFilter = encodeURIComponent(
JSON.stringify({
predicates: [
{
key: 'name',
operation: V2beta1PredicateOperation.ISSUBSTRING,
string_value: 'test filter',
},
],
}),
);
expect(reload).toHaveBeenLastCalledWith({
filter: expectedEncodedFilter,
orderAscending: false,
pageSize: 10,
pageToken: '',
sortBy: '',
});
});
it('The setFilterString method is called when the filter text is changed', async () => {
const setFilterString = jest.fn();
render(
<CustomTable {...props} rows={rows} columns={columns} setFilterString={setFilterString} />,
);
fireEvent.change(screen.getByLabelText('Filter'), { target: { value: 'test filter' } });
expect(setFilterString).toHaveBeenLastCalledWith('test filter');
});
});
| 273 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/DetailsTable.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'brace';
import 'brace/ext/language_tools';
import 'brace/mode/json';
import 'brace/theme/github';
import * as React from 'react';
import { stylesheet } from 'typestyle';
import { color, commonCss, spacing } from '../Css';
import { KeyValue } from '../lib/StaticGraphParser';
import Editor from './Editor';
export const css = stylesheet({
key: {
color: color.strong,
flex: '0 0 50%',
fontWeight: 'bold',
maxWidth: 300,
},
row: {
borderBottom: `1px solid ${color.divider}`,
display: 'flex',
padding: `${spacing.units(-5)}px ${spacing.units(-6)}px`,
},
valueJson: {
flexGrow: 1,
},
valueText: {
// flexGrow expands value text to full width.
flexGrow: 1,
// For current use-cases, value text shouldn't be very long. It will be not readable when it's long.
// Therefore, it's easier we just show it completely in the UX.
overflow: 'hidden',
// Sometimes, urls will be unbreakable for a long string. overflow-wrap: break-word
// allows breaking an url at middle of a word so it will not overflow and get hidden.
overflowWrap: 'break-word',
},
});
export interface ValueComponentProps<T> {
value?: string | T;
[key: string]: any;
}
interface DetailsTableProps<T> {
fields: Array<KeyValue<string | T>>;
title?: string;
valueComponent?: React.FC<ValueComponentProps<T>>;
valueComponentProps?: { [key: string]: any };
}
function isString(x: any): x is string {
return typeof x === 'string';
}
const DetailsTable = <T extends {}>(props: DetailsTableProps<T>) => {
const { fields, title, valueComponent: ValueComponent, valueComponentProps } = props;
return (
<React.Fragment>
{!!title && <div className={commonCss.header2}>{title}</div>}
<div>
{fields.map((f, i) => {
const [key, value] = f;
// only try to parse json if value is a string
if (isString(value)) {
try {
const parsedJson = JSON.parse(value);
// Nulls, booleans, strings, and numbers can all be parsed as JSON, but we don't care
// about rendering. Note that `typeOf null` returns 'object'
if (parsedJson === null || typeof parsedJson !== 'object') {
throw new Error(
'Parsed JSON was neither an array nor an object. Using default renderer',
);
}
return (
<div key={i} className={css.row}>
<span className={css.key}>{key}</span>
<Editor
width='100%'
minLines={3}
maxLines={20}
mode='json'
theme='github'
highlightActiveLine={true}
showGutter={true}
readOnly={true}
value={JSON.stringify(parsedJson, null, 2) || ''}
/>
</div>
);
} catch (err) {
// do nothing
}
}
// If a ValueComponent and a value is provided, render the value with
// the ValueComponent. Otherwise render the value as a string (empty string if null or undefined).
return (
<div key={i} className={css.row}>
<span className={css.key}>{key}</span>
<span className={css.valueText}>
{ValueComponent && value ? (
<ValueComponent value={value} {...valueComponentProps} />
) : (
`${value || ''}`
)}
</span>
</div>
);
})}
</div>
</React.Fragment>
);
};
export default DetailsTable;
| 274 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/MinioArtifactPreview.tsx | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { stylesheet } from 'typestyle';
import { color } from '../Css';
import { StorageService, StoragePath } from '../lib/WorkflowParser';
import { S3Artifact } from '../third_party/mlmd/argo_template';
import { isS3Endpoint } from '../lib/AwsHelper';
import { Apis } from '../lib/Apis';
import { ExternalLink } from '../atoms/ExternalLink';
import { ValueComponentProps } from './DetailsTable';
const css = stylesheet({
root: {
width: '100%',
},
preview: {
maxHeight: 250,
overflowY: 'auto',
padding: 3,
backgroundColor: color.lightGrey,
},
topDiv: {
display: 'flex',
justifyContent: 'space-between',
},
separater: {
width: 20, // There's minimum 20px separation between URI and view button.
display: 'inline-block',
},
viewLink: {
whiteSpace: 'nowrap',
},
});
/**
* Check if a javascript object is an argo S3Artifact object.
* @param value Any javascript object.
*/
export function isS3Artifact(value: any): value is S3Artifact {
return value && value.key && value.bucket;
}
export interface MinioArtifactPreviewProps extends ValueComponentProps<Partial<S3Artifact>> {
namespace?: string;
maxbytes?: number;
maxlines?: number;
}
function getStoragePath(value?: string | Partial<S3Artifact>) {
if (!value || typeof value === 'string') return;
const { key, s3Bucket } = value;
if (!s3Bucket || !key) return;
const { bucket, endpoint } = s3Bucket;
if (!bucket) return;
const source = isS3Endpoint(endpoint) ? StorageService.S3 : StorageService.MINIO;
return { source, bucket, key };
}
async function getPreview(
storagePath: StoragePath,
namespace: string | undefined,
maxbytes: number,
maxlines?: number,
): Promise<{ data: string; hasMore: boolean }> {
// TODO how to handle binary data (can probably use magic number to id common mime types)
let data = await Apis.readFile({ path: storagePath, namespace: namespace, peek: maxbytes + 1 });
// is preview === data and no maxlines
if (data.length <= maxbytes && !maxlines) {
return { data, hasMore: false };
}
// remove extra byte at the end (we requested maxbytes +1)
data = data.slice(0, maxbytes);
// check num lines
if (maxlines) {
data = data
.split('\n')
.slice(0, maxlines)
.join('\n')
.trim();
}
return { data: `${data}\n...`, hasMore: true };
}
/**
* A component that renders a preview to an artifact with a link to the full content.
*/
const MinioArtifactPreview: React.FC<MinioArtifactPreviewProps> = ({
value,
namespace,
maxbytes = 255,
maxlines,
}) => {
const [content, setContent] = React.useState<{ data: string; hasMore: boolean } | undefined>(
undefined,
);
const storagePath = getStoragePath(value);
const source = storagePath?.source;
const bucket = storagePath?.bucket;
const key = storagePath?.key;
React.useEffect(() => {
let cancelled = false;
if (source && bucket && key) {
getPreview({ source, bucket, key }, namespace, maxbytes, maxlines).then(
content => !cancelled && setContent(content),
error => console.error(error), // TODO error badge on link?
);
}
return () => {
cancelled = true;
};
}, [source, bucket, key, namespace, maxbytes, maxlines]);
if (!storagePath) {
// if value is undefined, null, or an invalid s3artifact object, don't render
if (value === null || value === undefined || typeof value === 'object') return null;
// otherwise render value as string (with default string method)
return <React.Fragment>{`${value}`}</React.Fragment>;
}
// TODO need to come to an agreement how to encode artifact info inside a url
// namespace is currently not supported
const linkText = Apis.buildArtifactLinkText(storagePath);
const artifactDownloadUrl = Apis.buildReadFileUrl({
path: storagePath,
namespace,
isDownload: true,
});
const artifactViewUrl = Apis.buildReadFileUrl({ path: storagePath, namespace });
// Opens in new window safely
// TODO use ArtifactLink instead (but it need to support namespace)
return (
<div className={css.root}>
<div className={css.topDiv}>
<ExternalLink href={artifactDownloadUrl} title={linkText}>
{linkText}
</ExternalLink>
<span className={css.separater}></span>
<ExternalLink href={artifactViewUrl} className={css.viewLink}>
View All
</ExternalLink>
</div>
{content?.data && (
<div className={css.preview}>
<small>
<pre>{content.data}</pre>
</small>
</div>
)}
</div>
);
};
export default MinioArtifactPreview;
| 275 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CollapseButton.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Button from '@material-ui/core/Button';
import ExpandedIcon from '@material-ui/icons/ArrowDropUp';
import { stylesheet, classes } from 'typestyle';
import { color, fontsize } from '../Css';
const css = stylesheet({
collapseBtn: {
color: color.strong,
fontSize: fontsize.title,
fontWeight: 'bold',
padding: 5,
},
collapsed: {
transform: 'rotate(180deg)',
},
icon: {
marginRight: 5,
transition: 'transform 0.3s',
},
});
interface CollapseButtonProps {
collapseSections: { [key: string]: boolean };
collapseSectionsUpdate: (collapseSections: { [key: string]: boolean }) => void;
sectionName: string;
}
class CollapseButton extends React.Component<CollapseButtonProps> {
public render(): JSX.Element {
const { collapseSections, collapseSectionsUpdate } = this.props;
const sectionName = this.props.sectionName;
return (
<div>
<Button
onClick={() => {
collapseSections[sectionName] = !collapseSections[sectionName];
collapseSectionsUpdate(collapseSections);
}}
title='Expand/Collapse this section'
className={css.collapseBtn}
>
<ExpandedIcon
className={classes(css.icon, collapseSections[sectionName] ? css.collapsed : '')}
/>
{sectionName}
</Button>
</div>
);
}
}
export default CollapseButton;
| 276 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Description.test.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { mount } from 'enzyme';
import { Description } from './Description';
describe('Description', () => {
describe('When in normal mode', () => {
it('renders empty string', () => {
const tree = mount(<Description description='' />).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders pure text', () => {
const tree = mount(<Description description='this is a line of pure text' />).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders raw link', () => {
const description = 'https://www.google.com';
const tree = mount(<Description description={description} />).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders markdown link', () => {
const description = '[google](https://www.google.com)';
const tree = mount(<Description description={description} />).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders paragraphs', () => {
const description = 'Paragraph 1\n' + '\n' + 'Paragraph 2';
const tree = mount(<Description description={description} />).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders markdown list as list', () => {
const description = `
* abc
* def`;
const tree = mount(<Description description={description} />).getDOMNode();
expect(tree).toMatchSnapshot();
});
});
describe('When in inline mode', () => {
it('renders paragraphs separated by space', () => {
const description = `
Paragraph 1
Paragraph 2
`;
const tree = mount(<Description description={description} forceInline={true} />).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders pure text', () => {
const tree = mount(
<Description description='this is a line of pure text' forceInline={true} />,
).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders raw link', () => {
const description = 'https://www.google.com';
const tree = mount(<Description description={description} forceInline={true} />).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders markdown link', () => {
const description = '[google](https://www.google.com)';
const tree = mount(<Description description={description} forceInline={true} />).getDOMNode();
expect(tree).toMatchSnapshot();
});
it('renders markdown list as pure text', () => {
const description = `
* abc
* def`;
const tree = mount(<Description description={description} forceInline={true} />).getDOMNode();
expect(tree).toMatchSnapshot();
});
});
});
| 277 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/ArtifactPreview.tsx | /**
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { useQuery } from 'react-query';
import { ExternalLink } from 'src/atoms/ExternalLink';
import { color } from 'src/Css';
import { Apis } from 'src/lib/Apis';
import WorkflowParser, { StoragePath } from 'src/lib/WorkflowParser';
import { stylesheet } from 'typestyle';
import Banner from './Banner';
import { ValueComponentProps } from './DetailsTable';
import { logger } from 'src/lib/Utils';
import { URIToSessionInfo } from './tabs/InputOutputTab';
const css = stylesheet({
root: {
width: '100%',
},
preview: {
maxHeight: 250,
overflowY: 'auto',
padding: 3,
backgroundColor: color.lightGrey,
},
topDiv: {
display: 'flex',
justifyContent: 'space-between',
},
separater: {
width: 20, // There's minimum 20px separation between URI and view button.
display: 'inline-block',
},
viewLink: {
whiteSpace: 'nowrap',
},
});
export interface ArtifactPreviewProps extends ValueComponentProps<string> {
namespace?: string;
sessionMap?: URIToSessionInfo;
maxbytes?: number;
maxlines?: number;
}
/**
* A component that renders a preview to an artifact with a link to the full content.
*/
const ArtifactPreview: React.FC<ArtifactPreviewProps> = ({
value,
namespace,
sessionMap,
maxbytes = 255,
maxlines = 20,
}) => {
let storage: StoragePath | undefined;
let providerInfo: string | undefined;
if (value) {
try {
providerInfo = sessionMap?.get(value);
storage = WorkflowParser.parseStoragePath(value);
} catch (error) {
logger.error(error);
}
}
const { isSuccess, isError, data, error } = useQuery<string, Error>(
['artifact_preview', { value, namespace, maxbytes, maxlines }],
() => getPreview(storage, providerInfo, namespace, maxbytes, maxlines),
{ staleTime: Infinity },
);
if (!storage) {
return (
<Banner message={'Can not retrieve storage path from artifact uri: ' + value} mode='info' />
);
}
const linkText = Apis.buildArtifactLinkText(storage);
const artifactDownloadUrl = Apis.buildReadFileUrl({
path: storage,
namespace,
isDownload: true,
});
const artifactViewUrl = Apis.buildReadFileUrl({ path: storage, namespace });
return (
<div className={css.root}>
<div className={css.topDiv}>
<ExternalLink download href={artifactDownloadUrl} title={linkText}>
{linkText}
</ExternalLink>
<span className={css.separater} />
<ExternalLink href={artifactViewUrl} className={css.viewLink}>
View All
</ExternalLink>
</div>
{isError && (
<Banner
message='Error in retrieving artifact preview.'
mode='error'
additionalInfo={error ? error.message : 'No error message'}
/>
)}
{isSuccess && data && (
<div className={css.preview}>
<small>
<pre>{data}</pre>
</small>
</div>
)}
</div>
);
};
export default ArtifactPreview;
async function getPreview(
storagePath: StoragePath | undefined,
providerInfo: string | undefined,
namespace: string | undefined,
maxbytes: number,
maxlines?: number,
): Promise<string> {
if (!storagePath) {
return ``;
}
// TODO how to handle binary data (can probably use magic number to id common mime types)
let data = await Apis.readFile({
path: storagePath,
providerInfo: providerInfo,
namespace: namespace,
peek: maxbytes + 1,
});
// is preview === data and no maxlines
if (data.length <= maxbytes && (!maxlines || data.split('\n').length < maxlines)) {
return data;
}
// remove extra byte at the end (we requested maxbytes +1)
data = data.slice(0, maxbytes);
// check num lines
if (maxlines) {
data = data
.split('\n')
.slice(0, maxlines)
.join('\n')
.trim();
}
return `${data}\n...`;
}
| 278 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/ArtifactPreview.test.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { CommonTestWrapper } from 'src/TestWrapper';
import { Apis } from '../lib/Apis';
import { testBestPractices } from '../TestUtils';
import ArtifactPreview from './ArtifactPreview';
testBestPractices();
describe('ArtifactPreview', () => {
it('handles undefined artifact', () => {
render(
<CommonTestWrapper>
<ArtifactPreview value={undefined} />
</CommonTestWrapper>,
);
screen.getByText('Can not retrieve storage path from artifact uri: undefined');
});
it('handles null artifact', () => {
render(
<CommonTestWrapper>
<ArtifactPreview value={null as any} />
</CommonTestWrapper>,
);
screen.getByText('Can not retrieve storage path from artifact uri: null');
});
it('handles unsupported path artifact', () => {
render(
<CommonTestWrapper>
<ArtifactPreview value={'i am random path'} />
</CommonTestWrapper>,
);
screen.getByText('Can not retrieve storage path from artifact uri: i am random path');
});
it('handles invalid artifact: no bucket', async () => {
jest.spyOn(Apis, 'readFile').mockRejectedValue(new Error('server error: no bucket'));
render(
<CommonTestWrapper>
<ArtifactPreview value={'minio://'} namespace={'kubeflow'} />
</CommonTestWrapper>,
);
await waitFor(() => screen.getByText('Error in retrieving artifact preview.'));
});
it('handles gcs artifact', async () => {
jest.spyOn(Apis, 'readFile').mockResolvedValue('gcs preview');
render(
<CommonTestWrapper>
<ArtifactPreview value={'gs://bucket/key'} />
</CommonTestWrapper>,
);
await waitFor(() => screen.getByText('gs://bucket/key'));
await waitFor(() => screen.getByText('gcs preview'));
});
it('handles minio artifact with namespace', async () => {
jest.spyOn(Apis, 'readFile').mockResolvedValueOnce('minio content');
render(
<CommonTestWrapper>
<ArtifactPreview value={'minio://bucket/key'} namespace={'kubeflow'} />
</CommonTestWrapper>,
);
await waitFor(() => screen.getByText('minio://bucket/key'));
await waitFor(() =>
expect(screen.getByText('View All').getAttribute('href')).toEqual(
'artifacts/get?source=minio&namespace=kubeflow&bucket=bucket&key=key',
),
);
});
it('handles artifact that previews with maxlines', async () => {
const data = `012\n345\n678\n910`;
jest.spyOn(Apis, 'readFile').mockResolvedValueOnce(data);
render(
<CommonTestWrapper>
<ArtifactPreview
value={'minio://bucket/key'}
namespace={'kubeflow'}
maxbytes={data.length}
maxlines={2}
/>
</CommonTestWrapper>,
);
await waitFor(() => screen.getByText('minio://bucket/key'));
await waitFor(() => screen.getByText(`012 345 ...`));
});
it('handles artifact that previews with maxbytes', async () => {
const data = `012\n345\n678\n910`;
jest.spyOn(Apis, 'readFile').mockResolvedValueOnce(data);
render(
<CommonTestWrapper>
<ArtifactPreview
value={'minio://bucket/key'}
namespace={'kubeflow'}
maxbytes={data.length - 5}
/>
</CommonTestWrapper>,
);
await waitFor(() => screen.getByText('minio://bucket/key'));
await waitFor(() => screen.getByText(`012 345 67 ...`));
});
});
| 279 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Metric.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { ApiRunMetric, RunMetricFormat } from '../apis/run';
import { MetricMetadata } from '../lib/RunUtils';
import { stylesheet } from 'typestyle';
import { logger } from '../lib/Utils';
import MetricUtils from '../lib/MetricUtils';
const css = stylesheet({
metricContainer: {
background: '#f6f7f9',
marginLeft: 6,
marginRight: 10,
},
metricFill: {
background: '#cbf0f8',
boxSizing: 'border-box',
color: '#202124',
fontFamily: 'Roboto',
fontSize: 13,
textIndent: 6,
},
});
interface MetricProps {
metadata?: MetricMetadata;
metric?: ApiRunMetric;
}
class Metric extends React.PureComponent<MetricProps> {
public render(): JSX.Element {
const { metric, metadata } = this.props;
if (!metric || metric.number_value === undefined) {
return <div />;
}
const displayString = MetricUtils.getMetricDisplayString(metric);
let width = '';
if (metric.format === RunMetricFormat.PERCENTAGE) {
width = `calc(${displayString})`;
} else {
// Non-percentage metrics must contain metadata
if (!metadata) {
return <div />;
}
const leftSpace = 6;
if (metadata.maxValue === 0 && metadata.minValue === 0) {
return <div style={{ paddingLeft: leftSpace }}>{displayString}</div>;
}
if (metric.number_value - metadata.minValue < 0) {
logger.error(
`Metric ${metadata.name}'s value:` +
` (${metric.number_value}) was lower than the supposed minimum of` +
` (${metadata.minValue})`,
);
return <div style={{ paddingLeft: leftSpace }}>{displayString}</div>;
}
if (metadata.maxValue - metric.number_value < 0) {
logger.error(
`Metric ${metadata.name}'s value:` +
` (${metric.number_value}) was greater than the supposed maximum of` +
` (${metadata.maxValue})`,
);
return <div style={{ paddingLeft: leftSpace }}>{displayString}</div>;
}
const barWidth =
((metric.number_value - metadata.minValue) / (metadata.maxValue - metadata.minValue)) * 100;
width = `calc(${barWidth}%)`;
}
return (
<div className={css.metricContainer}>
<div className={css.metricFill} style={{ width }} data-testid={'metric'}>
{displayString}
</div>
</div>
);
}
}
export default Metric;
| 280 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CustomTableRow.test.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { Column, Row } from './CustomTable';
import TestUtils from '../TestUtils';
import { shallow } from 'enzyme';
import { CustomTableRow } from './CustomTableRow';
describe('CustomTable', () => {
const props = {
columns: [],
row: [],
};
const columns: Column[] = [
{
customRenderer: undefined,
label: 'col1',
},
{
customRenderer: undefined,
label: 'col2',
},
];
const row: Row = {
id: 'row',
otherFields: ['cell1', 'cell2'],
};
it('renders some rows using a custom renderer', async () => {
columns[0].customRenderer = () => (<span>this is custom output</span>) as any;
const tree = shallow(<CustomTableRow {...props} row={row} columns={columns} />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
columns[0].customRenderer = undefined;
});
it('displays warning icon with tooltip if row has error', async () => {
row.error = 'dummy error';
const tree = shallow(<CustomTableRow {...props} row={row} columns={columns} />);
await TestUtils.flushPromises();
expect(tree).toMatchSnapshot();
row.error = undefined;
});
});
| 281 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/StaticNodeDetails.tsx | /*
* Copyright 2018-2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import DetailsTable from './DetailsTable';
import { classes, stylesheet } from 'typestyle';
import { commonCss, fontsize } from '../Css';
import { SelectedNodeInfo } from '../lib/StaticGraphParser';
export type nodeType = 'container' | 'resource' | 'dag' | 'unknown';
const css = stylesheet({
fontSizeTitle: {
fontSize: fontsize.title,
},
taskTitle: {
fontSize: fontsize.title,
fontWeight: 'bold',
paddingTop: 20,
},
});
interface StaticNodeDetailsProps {
nodeInfo: SelectedNodeInfo;
}
class StaticNodeDetails extends React.Component<StaticNodeDetailsProps> {
public render(): JSX.Element {
const nodeInfo = this.props.nodeInfo;
return (
<div>
{nodeInfo.nodeType === 'container' && (
<div>
<DetailsTable title='Input parameters' fields={nodeInfo.inputs} />
<DetailsTable title='Output parameters' fields={nodeInfo.outputs} />
<div className={classes(commonCss.header, css.fontSizeTitle)}>Arguments</div>
{nodeInfo.args.map((arg, i) => (
<div key={i} style={{ fontFamily: 'monospace' }}>
{arg}
</div>
))}
<div className={classes(commonCss.header, css.fontSizeTitle)}>Command</div>
{nodeInfo.command.map((c, i) => (
<div key={i} style={{ fontFamily: 'monospace' }}>
{c}
</div>
))}
<div className={classes(commonCss.header, css.fontSizeTitle)}>Image</div>
<div style={{ fontFamily: 'monospace' }}>{nodeInfo.image}</div>
<DetailsTable title='Volume Mounts' fields={nodeInfo.volumeMounts} />
</div>
)}
{nodeInfo.nodeType === 'resource' && (
<div>
<DetailsTable title='Input parameters' fields={nodeInfo.inputs} />
<DetailsTable title='Output parameters' fields={nodeInfo.outputs} />
<DetailsTable title='Manifest' fields={nodeInfo.resource} />
</div>
)}
{!!nodeInfo.condition && (
<div>
<div className={css.taskTitle}>Condition</div>
<div>Run when: {nodeInfo.condition}</div>
</div>
)}
</div>
);
}
}
export default StaticNodeDetails;
| 282 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/PlotCard.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { shallow } from 'enzyme';
import PlotCard from './PlotCard';
import { ViewerConfig, PlotType } from './viewers/Viewer';
describe('PlotCard', () => {
it('handles no configs', () => {
expect(shallow(<PlotCard title='' configs={[]} maxDimension={100} />)).toMatchSnapshot();
});
const config: ViewerConfig = { type: PlotType.CONFUSION_MATRIX };
it('renders on confusion matrix viewer card', () => {
const tree = shallow(<PlotCard title='test title' configs={[config]} maxDimension={100} />);
expect(tree).toMatchSnapshot();
});
it('pops out a full screen view of the viewer', () => {
const tree = shallow(<PlotCard title='' configs={[config]} maxDimension={100} />);
tree.find('.popOutButton').simulate('click');
expect(tree).toMatchSnapshot();
});
it('close button closes full screen dialog', () => {
const tree = shallow(<PlotCard title='' configs={[config]} maxDimension={100} />);
tree.find('.popOutButton').simulate('click');
tree.find('.fullscreenCloseButton').simulate('click');
expect(tree).toMatchSnapshot();
});
it('clicking outside full screen dialog closes it', () => {
const tree = shallow(<PlotCard title='' configs={[config]} maxDimension={100} />);
tree.find('.popOutButton').simulate('click');
tree.find('WithStyles(Dialog)').simulate('close');
expect(tree).toMatchSnapshot();
});
});
| 283 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Graph.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as dagre from 'dagre';
import * as React from 'react';
import { shallow, mount } from 'enzyme';
import EnhancedGraph, { Graph } from './Graph';
import SuccessIcon from '@material-ui/icons/CheckCircle';
import Tooltip from '@material-ui/core/Tooltip';
function newGraph(): dagre.graphlib.Graph {
const graph = new dagre.graphlib.Graph();
graph.setGraph({});
graph.setDefaultEdgeLabel(() => ({}));
return graph;
}
const testIcon = (
<Tooltip title='Test icon tooltip'>
<SuccessIcon />
</Tooltip>
);
const newNode = (label: string, isPlaceHolder?: boolean, color?: string, icon?: JSX.Element) => ({
bgColor: color,
height: 10,
icon: icon || testIcon,
isPlaceholder: isPlaceHolder || false,
label,
width: 10,
});
beforeEach(() => {
jest.restoreAllMocks();
});
describe('Graph', () => {
it('handles an empty graph', () => {
expect(shallow(<Graph graph={newGraph()} />)).toMatchSnapshot();
});
it('renders a graph with one node', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1'));
expect(shallow(<Graph graph={graph} />)).toMatchSnapshot();
});
it('renders a graph with two disparate nodes', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1'));
graph.setNode('node2', newNode('node2'));
expect(shallow(<Graph graph={graph} />)).toMatchSnapshot();
});
it('renders a graph with two connectd nodes', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1'));
graph.setNode('node2', newNode('node2'));
graph.setEdge('node1', 'node2');
expect(shallow(<Graph graph={graph} />)).toMatchSnapshot();
});
it('renders a graph with two connectd nodes in reverse order', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1'));
graph.setNode('node2', newNode('node2'));
graph.setEdge('node2', 'node1');
expect(shallow(<Graph graph={graph} />)).toMatchSnapshot();
});
it('renders a complex graph with six nodes and seven edges', () => {
const graph = newGraph();
graph.setNode('flipcoin1', newNode('flipcoin1'));
graph.setNode('tails1', newNode('tails1'));
graph.setNode('heads1', newNode('heads1'));
graph.setNode('flipcoin2', newNode('flipcoin2'));
graph.setNode('heads2', newNode('heads2'));
graph.setNode('tails2', newNode('tails2'));
graph.setEdge('flipcoin1', 'tails1');
graph.setEdge('flipcoin1', 'heads1');
graph.setEdge('tails1', 'flipcoin2');
graph.setEdge('tails1', 'heads2');
graph.setEdge('tails1', 'tails2');
graph.setEdge('flipcoin2', 'heads2');
graph.setEdge('flipcoin2', 'tails2');
expect(shallow(<Graph graph={graph} />)).toMatchSnapshot();
});
it('renders a graph with colored nodes', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1', false, 'red'));
graph.setNode('node2', newNode('node2', false, 'green'));
expect(shallow(<Graph graph={graph} />)).toMatchSnapshot();
});
it('renders a graph with colored edges', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1'));
graph.setNode('node2', newNode('node2'));
graph.setEdge('node1', 'node2', { color: 'red' });
expect(shallow(<Graph graph={graph} />)).toMatchSnapshot();
});
it('renders a graph with a placeholder node and edge', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1', false));
graph.setNode('node2', newNode('node2', true));
graph.setEdge('node1', 'node2', { isPlaceholder: true });
expect(shallow(<Graph graph={graph} />)).toMatchSnapshot();
});
it('calls onClick callback when node is clicked', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1'));
graph.setNode('node2', newNode('node2'));
graph.setEdge('node2', 'node1');
const spy = jest.fn();
const tree = shallow(<Graph graph={graph} onClick={spy} />);
tree
.find('.node')
.at(0)
.simulate('click');
expect(spy).toHaveBeenCalledWith('node1');
});
it('renders a graph with a selected node', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1'));
graph.setNode('node2', newNode('node2'));
graph.setEdge('node1', 'node2');
expect(shallow(<Graph graph={graph} selectedNodeId='node1' />)).toMatchSnapshot();
});
it('gracefully renders a graph with a selected node id that does not exist', () => {
const graph = newGraph();
graph.setNode('node1', newNode('node1'));
graph.setNode('node2', newNode('node2'));
graph.setEdge('node1', 'node2');
expect(shallow(<Graph graph={graph} selectedNodeId='node3' />)).toMatchSnapshot();
});
it('shows an error message when the graph is invalid', () => {
const consoleErrorSpy = jest.spyOn(console, 'error');
consoleErrorSpy.mockImplementation(() => null);
const graph = newGraph();
graph.setEdge('node1', 'node2');
const onError = jest.fn();
expect(mount(<EnhancedGraph graph={graph} onError={onError} />).html()).toMatchSnapshot();
expect(onError).toHaveBeenCalledTimes(1);
const [message, additionalInfo] = onError.mock.calls[0];
expect(message).toEqual('There was an error rendering the graph.');
expect(additionalInfo).toEqual(
"There was an error rendering the graph. This is likely a bug in Kubeflow Pipelines. Error message: 'Graph definition is invalid. Cannot get node by 'node1'.'.",
);
});
});
| 284 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/UploadPipelineDialog.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { shallow, ReactWrapper, ShallowWrapper } from 'enzyme';
import UploadPipelineDialog, { ImportMethod } from './UploadPipelineDialog';
import TestUtils from '../TestUtils';
describe('UploadPipelineDialog', () => {
let tree: ReactWrapper | ShallowWrapper;
afterEach(async () => {
// unmount() should be called before resetAllMocks() in case any part of the unmount life cycle
// depends on mocks/spies
await tree.unmount();
});
it('renders closed', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
expect(tree).toMatchSnapshot();
});
it('renders open', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
expect(tree).toMatchSnapshot();
});
it('renders an active dropzone', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
tree.setState({ dropzoneActive: true });
expect(tree).toMatchSnapshot();
});
it('renders with a selected file to upload', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
tree.setState({ fileToUpload: true });
expect(tree).toMatchSnapshot();
});
it('renders alternate UI for uploading via URL', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
tree.setState({ importMethod: ImportMethod.URL });
expect(tree).toMatchSnapshot();
});
it('calls close callback with null and empty string when canceled', () => {
const spy = jest.fn();
tree = shallow(<UploadPipelineDialog open={false} onClose={spy} />);
tree.find('#cancelUploadBtn').simulate('click');
expect(spy).toHaveBeenCalledWith(false, '', null, '', ImportMethod.LOCAL, true, '');
});
it('calls close callback with null and empty string when dialog is closed', () => {
const spy = jest.fn();
tree = shallow(<UploadPipelineDialog open={false} onClose={spy} />);
tree.find('WithStyles(Dialog)').simulate('close');
expect(spy).toHaveBeenCalledWith(false, '', null, '', ImportMethod.LOCAL, true, '');
});
it('calls close callback with file name, file object, and description when confirmed', () => {
const spy = jest.fn();
tree = shallow(<UploadPipelineDialog open={false} onClose={spy} />);
(tree.instance() as any)._dropzoneRef = { current: { open: () => null } };
(tree.instance() as UploadPipelineDialog).handleChange('uploadPipelineName')({
target: { value: 'test name' },
});
tree.find('#confirmUploadBtn').simulate('click');
expect(spy).toHaveBeenLastCalledWith(true, 'test name', null, '', ImportMethod.LOCAL, true, '');
});
it('calls close callback with trimmed file url and pipeline name when confirmed', () => {
const spy = jest.fn();
tree = shallow(<UploadPipelineDialog open={false} onClose={spy} />);
// Click 'Import by URL'
tree.find('#uploadFromUrlBtn').simulate('change');
(tree.instance() as UploadPipelineDialog).handleChange('fileUrl')({
target: { value: '\n https://www.google.com/test-file.txt ' },
});
(tree.instance() as UploadPipelineDialog).handleChange('uploadPipelineName')({
target: { value: 'test name' },
});
tree.find('#confirmUploadBtn').simulate('click');
expect(spy).toHaveBeenLastCalledWith(
true,
'test name',
null,
'https://www.google.com/test-file.txt',
ImportMethod.URL,
true,
'',
);
});
it('trims file extension for pipeline name suggestion', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
const file = { name: 'test_upload_file.tar.gz' };
tree.find('#dropZone').simulate('drop', [file]);
expect(tree.state()).toHaveProperty('dropzoneActive', false);
expect(tree.state()).toHaveProperty('uploadPipelineName', 'test_upload_file');
});
it('sets the import method based on which radio button is toggled', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
// Import method is LOCAL by default
expect(tree.state('importMethod')).toBe(ImportMethod.LOCAL);
// Click 'Import by URL'
tree.find('#uploadFromUrlBtn').simulate('change');
expect(tree.state('importMethod')).toBe(ImportMethod.URL);
// Click back to default, 'Upload a file'
tree.find('#uploadLocalFileBtn').simulate('change');
expect(tree.state('importMethod')).toBe(ImportMethod.LOCAL);
});
it('resets all state if the dialog is closed and the callback returns true', async () => {
const spy = jest.fn(() => true);
tree = shallow(<UploadPipelineDialog open={false} onClose={spy} />);
tree.setState({
busy: true,
dropzoneActive: true,
file: {},
fileName: 'test file name',
fileUrl: 'https://some.url.com',
importMethod: ImportMethod.URL,
uploadPipelineDescription: 'test description',
uploadPipelineName: 'test pipeline name',
});
tree.find('#confirmUploadBtn').simulate('click');
await TestUtils.flushPromises();
expect(tree.state('busy')).toBe(false);
expect(tree.state('dropzoneActive')).toBe(false);
expect(tree.state('file')).toBeNull();
expect(tree.state('fileName')).toBe('');
expect(tree.state('fileUrl')).toBe('');
expect(tree.state('importMethod')).toBe(ImportMethod.LOCAL);
expect(tree.state('uploadPipelineDescription')).toBe('');
expect(tree.state('uploadPipelineName')).toBe('');
});
it('does not reset the state if the dialog is closed and the callback returns false', async () => {
const spy = jest.fn(() => false);
tree = shallow(<UploadPipelineDialog open={false} onClose={spy} />);
tree.setState({
busy: true,
dropzoneActive: true,
file: {},
fileName: 'test file name',
fileUrl: 'https://some.url.com',
importMethod: ImportMethod.URL,
uploadPipelineDescription: 'test description',
uploadPipelineName: 'test pipeline name',
});
tree.find('#confirmUploadBtn').simulate('click');
await TestUtils.flushPromises();
expect(tree.state('dropzoneActive')).toBe(true);
expect(tree.state('file')).toEqual({});
expect(tree.state('fileName')).toBe('test file name');
expect(tree.state('fileUrl')).toBe('https://some.url.com');
expect(tree.state('importMethod')).toBe(ImportMethod.URL);
expect(tree.state('uploadPipelineDescription')).toBe('test description');
expect(tree.state('uploadPipelineName')).toBe('test pipeline name');
// 'busy' is set to false regardless upon the callback returning
expect(tree.state('busy')).toBe(false);
});
it('sets an active dropzone on drag', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
tree.find('#dropZone').simulate('dragEnter');
expect(tree.state()).toHaveProperty('dropzoneActive', true);
});
it('sets an inactive dropzone on drag leave', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
tree.find('#dropZone').simulate('dragLeave');
expect(tree.state()).toHaveProperty('dropzoneActive', false);
});
it('sets a file object on drop', () => {
tree = shallow(<UploadPipelineDialog open={false} onClose={jest.fn()} />);
const file = { name: 'test upload file' };
tree.find('#dropZone').simulate('drop', [file]);
expect(tree.state()).toHaveProperty('dropzoneActive', false);
expect(tree.state()).toHaveProperty('uploadPipelineName', file.name);
});
});
| 285 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/SideNav.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import ArtifactsIcon from '@material-ui/icons/BubbleChart';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import JupyterhubIcon from '@material-ui/icons/Code';
import DescriptionIcon from '@material-ui/icons/Description';
import OpenInNewIcon from '@material-ui/icons/OpenInNew';
import ExecutionsIcon from '@material-ui/icons/PlayArrow';
import DirectionsRun from '@material-ui/icons/DirectionsRun';
import * as React from 'react';
import { RouterProps } from 'react-router';
import { Link } from 'react-router-dom';
import { classes, stylesheet } from 'typestyle';
import { ExternalLinks, RoutePage, RoutePrefix } from '../components/Router';
import { commonCss, fontsize } from '../Css';
import ExperimentsIcon from '../icons/experiments';
import GitHubIcon from '../icons/GitHub-Mark-120px-plus.png';
import PipelinesIcon from '../icons/pipelines';
import { BuildInfo } from '../lib/Apis';
import { Deployments, KFP_FLAGS } from '../lib/Flags';
import { LocalStorage, LocalStorageKey } from '../lib/LocalStorage';
import { GkeMetadataContext, GkeMetadata } from 'src/lib/GkeMetadata';
import { Alarm } from '@material-ui/icons';
import { BuildInfoContext } from 'src/lib/BuildInfo';
export const tailwindcss = {
sideNavItem: 'flex flex-row flex-shrink-0',
};
export const sideNavColors = {
bg: '#f8fafb',
fgActive: '#0d6de7',
fgActiveInvisible: 'rgb(227, 233, 237, 0)',
fgDefault: '#9aa0a6',
hover: '#f1f3f4',
separator: '#bdc1c6',
sideNavBorder: '#e8eaed',
};
const COLLAPSED_SIDE_NAV_SIZE = 72;
const EXPANDED_SIDE_NAV_SIZE = 220;
export const css = stylesheet({
active: {
color: sideNavColors.fgActive + ' !important',
},
button: {
$nest: {
'&::hover': {
backgroundColor: sideNavColors.hover,
},
},
borderRadius: 0,
color: sideNavColors.fgDefault,
display: 'block',
fontSize: fontsize.medium,
fontWeight: 'bold',
height: 44,
marginBottom: 16,
maxWidth: EXPANDED_SIDE_NAV_SIZE,
overflow: 'hidden',
padding: '12px 10px 10px 26px',
textAlign: 'left',
textTransform: 'none',
transition: 'max-width 0.3s',
whiteSpace: 'nowrap',
width: EXPANDED_SIDE_NAV_SIZE,
},
chevron: {
color: sideNavColors.fgDefault,
marginLeft: 16,
padding: 6,
transition: 'transform 0.3s',
},
collapsedButton: {
maxWidth: COLLAPSED_SIDE_NAV_SIZE,
minWidth: COLLAPSED_SIDE_NAV_SIZE,
padding: '12px 10px 10px 26px',
},
collapsedChevron: {
transform: 'rotate(180deg)',
},
collapsedExternalLabel: {
// Hide text when collapsing, but do it with a transition of both height and
// opacity
height: 0,
opacity: 0,
},
collapsedLabel: {
// Hide text when collapsing, but do it with a transition
opacity: 0,
},
collapsedRoot: {
width: `${COLLAPSED_SIDE_NAV_SIZE}px !important`,
},
collapsedSeparator: {
margin: '20px !important',
},
envMetadata: {
color: sideNavColors.fgDefault,
marginBottom: 16,
marginLeft: 30,
},
icon: {
height: 20,
width: 20,
},
iconImage: {
opacity: 0.6, // Images are too colorful there by default, reduce their color.
},
indicator: {
borderBottom: '3px solid transparent',
borderLeft: `3px solid ${sideNavColors.fgActive}`,
borderTop: '3px solid transparent',
height: 42,
left: 0,
position: 'absolute',
zIndex: 1,
},
indicatorHidden: {
opacity: 0,
},
infoHidden: {
opacity: 0,
transition: 'opacity 0s',
transitionDelay: '0s',
// guarantees info doesn't affect layout when hidden
overflow: 'hidden',
height: 0,
},
infoVisible: {
opacity: 'initial',
transition: 'opacity 0.2s',
transitionDelay: '0.3s',
overflow: 'hidden',
},
label: {
fontSize: fontsize.base,
letterSpacing: 0.25,
marginLeft: 20,
transition: 'opacity 0.3s',
verticalAlign: 'super',
},
link: {
color: '#77abda',
},
openInNewTabIcon: {
height: 12,
marginBottom: 8,
marginLeft: 5,
width: 12,
},
root: {
background: sideNavColors.bg,
borderRight: `1px ${sideNavColors.sideNavBorder} solid`,
paddingTop: 15,
transition: 'width 0.3s',
width: EXPANDED_SIDE_NAV_SIZE,
},
separator: {
border: '0px none transparent',
borderTop: `1px solid ${sideNavColors.separator}`,
margin: 20,
},
});
interface DisplayBuildInfo {
commitHash: string;
commitUrl: string;
date: string;
tagName: string;
}
interface SideNavProps extends RouterProps {
page: string;
}
interface SideNavInternalProps extends SideNavProps {
gkeMetadata: GkeMetadata;
buildInfo: BuildInfo | undefined;
}
interface SideNavState {
collapsed: boolean;
jupyterHubAvailable: boolean;
manualCollapseState: boolean;
}
export class SideNav extends React.Component<SideNavInternalProps, SideNavState> {
private _isMounted = true;
private readonly _AUTO_COLLAPSE_WIDTH = 800;
private readonly _HUB_ADDRESS = '/hub/';
constructor(props: any) {
super(props);
const collapsed = LocalStorage.isNavbarCollapsed();
this.state = {
collapsed,
// Set jupyterHubAvailable to false so UI don't show Jupyter Hub link
jupyterHubAvailable: false,
manualCollapseState: LocalStorage.hasKey(LocalStorageKey.navbarCollapsed),
};
}
public async componentDidMount(): Promise<void> {
window.addEventListener('resize', this._maybeResize.bind(this));
this._maybeResize();
}
public componentWillUnmount(): void {
this._isMounted = false;
}
public render(): JSX.Element | null {
const page = this.props.page;
const displayBuildInfo: DisplayBuildInfo = this._getBuildInfo();
const { collapsed } = this.state;
const { gkeMetadata } = this.props;
const iconColor = {
active: sideNavColors.fgActive,
inactive: sideNavColors.fgDefault,
};
if (KFP_FLAGS.HIDE_SIDENAV) {
return null;
}
return (
<div
id='sideNav'
className={classes(
css.root,
commonCss.flexColumn,
commonCss.noShrink,
collapsed && css.collapsedRoot,
)}
>
<div style={{ flexGrow: 1 }}>
{KFP_FLAGS.DEPLOYMENT === Deployments.MARKETPLACE && (
<>
<div
className={classes(
css.indicator,
!page.startsWith(RoutePage.START) && css.indicatorHidden,
)}
/>
<Tooltip
title={'Getting Started'}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<Link id='gettingStartedBtn' to={RoutePage.START} className={commonCss.unstyled}>
<Button
className={classes(
css.button,
page.startsWith(RoutePage.START) && css.active,
collapsed && css.collapsedButton,
)}
>
<div className={tailwindcss.sideNavItem}>
<DescriptionIcon style={{ width: 20, height: 20 }} />
<span className={classes(collapsed && css.collapsedLabel, css.label)}>
Getting Started
</span>
</div>
</Button>
</Link>
</Tooltip>
</>
)}
<div
className={classes(
css.indicator,
!this._highlightPipelinesButton(page) && css.indicatorHidden,
)}
/>
<Tooltip
title={'Pipeline List'}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<Link id='pipelinesBtn' to={RoutePage.PIPELINES} className={commonCss.unstyled}>
<Button
className={classes(
css.button,
this._highlightPipelinesButton(page) && css.active,
collapsed && css.collapsedButton,
)}
>
<div className={tailwindcss.sideNavItem}>
<div className={classes({ alignItems: 'stretch' })}>
<PipelinesIcon
color={
this._highlightPipelinesButton(page) ? iconColor.active : iconColor.inactive
}
/>
</div>
<span className={classes(collapsed && css.collapsedLabel, css.label)}>
Pipelines
</span>
</div>
</Button>
</Link>
</Tooltip>
<div
className={classes(
css.indicator,
!this._highlightExperimentsButton(page) && css.indicatorHidden,
)}
/>
<Tooltip
title={'Experiment List'}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<Link id='experimentsBtn' to={RoutePage.EXPERIMENTS} className={commonCss.unstyled}>
<Button
className={classes(
css.button,
this._highlightExperimentsButton(page) && css.active,
collapsed && css.collapsedButton,
)}
>
<div className={tailwindcss.sideNavItem}>
<div className={classes({ alignItems: 'stretch' })}>
<ExperimentsIcon
color={
this._highlightExperimentsButton(page)
? iconColor.active
: iconColor.inactive
}
/>
</div>
<span className={classes(collapsed && css.collapsedLabel, css.label)}>
Experiments
</span>
</div>
</Button>
</Link>
</Tooltip>
<div
className={classes(
css.indicator,
!this._highlightRunsButton(page) && css.indicatorHidden,
)}
/>
<Tooltip
title={'Runs List'}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<Link id='runsBtn' to={RoutePage.RUNS} className={commonCss.unstyled}>
<Button
className={classes(
css.button,
this._highlightRunsButton(page) && css.active,
collapsed && css.collapsedButton,
)}
>
<div className={tailwindcss.sideNavItem}>
<DirectionsRun />
<span className={classes(collapsed && css.collapsedLabel, css.label)}>Runs</span>
</div>
</Button>
</Link>
</Tooltip>
<div
className={classes(
css.indicator,
!this._highlightRecurringRunsButton(page) && css.indicatorHidden,
)}
/>
<Tooltip
title={'Recurring Runs List'}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<Link
id='recurringRunsBtn'
to={RoutePage.RECURRING_RUNS}
className={commonCss.unstyled}
>
<Button
className={classes(
css.button,
this._highlightRecurringRunsButton(page) && css.active,
collapsed && css.collapsedButton,
)}
>
<div className={tailwindcss.sideNavItem}>
<Alarm />
<span className={classes(collapsed && css.collapsedLabel, css.label)}>
Recurring Runs
</span>
</div>
</Button>
</Link>
</Tooltip>
<div
className={classes(
css.indicator,
!this._highlightArtifactsButton(page) && css.indicatorHidden,
)}
/>
<Tooltip
title={'Artifacts List'}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<Link id='artifactsBtn' to={RoutePage.ARTIFACTS} className={commonCss.unstyled}>
<Button
className={classes(
css.button,
this._highlightArtifactsButton(page) && css.active,
collapsed && css.collapsedButton,
)}
>
<div className={tailwindcss.sideNavItem}>
<ArtifactsIcon />
<span className={classes(collapsed && css.collapsedLabel, css.label)}>
Artifacts
</span>
</div>
</Button>
</Link>
</Tooltip>
<div
className={classes(
css.indicator,
!this._highlightExecutionsButton(page) && css.indicatorHidden,
)}
/>
<Tooltip
title={'Executions List'}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<Link id='executionsBtn' to={RoutePage.EXECUTIONS} className={commonCss.unstyled}>
<Button
className={classes(
css.button,
this._highlightExecutionsButton(page) && css.active,
collapsed && css.collapsedButton,
)}
>
<div className={tailwindcss.sideNavItem}>
<ExecutionsIcon />
<span className={classes(collapsed && css.collapsedLabel, css.label)}>
Executions
</span>
</div>
</Button>
</Link>
</Tooltip>
{this.state.jupyterHubAvailable && (
<Tooltip
title={'Open Jupyter Notebook'}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<a
id='jupyterhubBtn'
href={this._HUB_ADDRESS}
className={commonCss.unstyled}
target='_blank'
rel='noopener'
>
<Button className={classes(css.button, collapsed && css.collapsedButton)}>
<div className={tailwindcss.sideNavItem}>
<JupyterhubIcon style={{ height: 20, width: 20 }} />
<span className={classes(collapsed && css.collapsedLabel, css.label)}>
Notebooks
</span>
<OpenInNewIcon className={css.openInNewTabIcon} />
</div>
</Button>
</a>
</Tooltip>
)}
<hr className={classes(css.separator, collapsed && css.collapsedSeparator)} />
<ExternalUri
title={'Documentation'}
to={ExternalLinks.DOCUMENTATION}
collapsed={collapsed}
icon={className => <DescriptionIcon className={className} />}
/>
<ExternalUri
title={'Github Repo'}
to={ExternalLinks.GITHUB}
collapsed={collapsed}
icon={className => (
<img src={GitHubIcon} className={classes(className, css.iconImage)} alt='Github' />
)}
/>
<hr className={classes(css.separator, collapsed && css.collapsedSeparator)} />
<IconButton
className={classes(css.chevron, collapsed && css.collapsedChevron)}
onClick={this._toggleNavClicked.bind(this)}
>
<ChevronLeftIcon />
</IconButton>
</div>
<div className={collapsed ? css.infoHidden : css.infoVisible}>
{gkeMetadata.clusterName && gkeMetadata.projectId && (
<Tooltip
title={`Cluster name: ${gkeMetadata.clusterName}, Project ID: ${gkeMetadata.projectId}`}
enterDelay={300}
placement='top-start'
>
<div className={css.envMetadata}>
<span>Cluster name: </span>
<a
href={`https://console.cloud.google.com/kubernetes/list?project=${gkeMetadata.projectId}&filter=name:${gkeMetadata.clusterName}`}
className={classes(css.link, commonCss.unstyled)}
rel='noopener'
target='_blank'
>
{gkeMetadata.clusterName}
</a>
</div>
</Tooltip>
)}
{displayBuildInfo && (
<Tooltip
title={`Build date: ${displayBuildInfo.date}, Commit hash: ${displayBuildInfo.commitHash}`}
enterDelay={300}
placement={'top-start'}
>
<div className={css.envMetadata}>
<span>Version: </span>
<a
href={displayBuildInfo.commitUrl}
className={classes(css.link, commonCss.unstyled)}
rel='noopener'
target='_blank'
>
{displayBuildInfo.tagName}
</a>
</div>
</Tooltip>
)}
<Tooltip title='Report an Issue' enterDelay={300} placement={'top-start'}>
<div className={css.envMetadata}>
<a
href={ExternalLinks.GITHUB_ISSUE}
className={classes(css.link, commonCss.unstyled)}
rel='noopener'
target='_blank'
>
Report an Issue
</a>
</div>
</Tooltip>
</div>
</div>
);
}
private _getBuildInfo(buildInfo = this.props.buildInfo): DisplayBuildInfo {
const commitHash = buildInfo?.apiServerCommitHash || buildInfo?.frontendCommitHash || '';
const tagName = buildInfo?.apiServerTagName || buildInfo?.frontendTagName || '';
return {
tagName: tagName || 'unknown',
commitHash: commitHash ? commitHash.substring(0, 7) : 'unknown',
commitUrl:
'https://www.github.com/kubeflow/pipelines' +
(commitHash && commitHash !== 'unknown' ? `/commit/${commitHash}` : ''),
date: buildInfo?.buildDate
? new Date(buildInfo?.buildDate).toLocaleDateString('en-US')
: 'unknown',
};
}
private _highlightPipelinesButton(page: string): boolean {
return page.startsWith(RoutePage.PIPELINES) || page.startsWith(RoutePage.PIPELINES_SHARED);
}
private _highlightExperimentsButton(page: string): boolean {
return page.startsWith(RoutePage.EXPERIMENTS) || page === RoutePage.ARCHIVED_EXPERIMENTS;
}
private _highlightRunsButton(page: string): boolean {
return (
page.startsWith(RoutePage.RUNS) ||
page.startsWith(RoutePage.COMPARE) ||
page === RoutePage.ARCHIVED_RUNS
);
}
private _highlightRecurringRunsButton(page: string): boolean {
return page.startsWith(RoutePage.RECURRING_RUNS) || page.startsWith(RoutePrefix.RECURRING_RUN);
}
private _highlightArtifactsButton(page: string): boolean {
return page.startsWith(RoutePrefix.ARTIFACT);
}
private _highlightExecutionsButton(page: string): boolean {
return page.startsWith(RoutePrefix.EXECUTION);
}
private _toggleNavClicked(): void {
this.setStateSafe(
{
collapsed: !this.state.collapsed,
manualCollapseState: true,
},
() => LocalStorage.saveNavbarCollapsed(this.state.collapsed),
);
this._toggleNavCollapsed();
}
private _toggleNavCollapsed(shouldCollapse?: boolean): void {
this.setStateSafe({
collapsed: shouldCollapse !== undefined ? shouldCollapse : !this.state.collapsed,
});
}
private _maybeResize(): void {
if (!this.state.manualCollapseState) {
this._toggleNavCollapsed(window.innerWidth < this._AUTO_COLLAPSE_WIDTH);
}
}
private setStateSafe(newState: Partial<SideNavState>, cb?: () => void): void {
if (this._isMounted) {
this.setState(newState as any, cb);
}
}
}
interface ExternalUriProps {
title: string;
to: string;
collapsed: boolean;
icon: (className: string) => React.ReactNode;
}
// tslint:disable-next-line:variable-name
const ExternalUri: React.FC<ExternalUriProps> = ({ title, to, collapsed, icon }) => (
<Tooltip
title={title}
enterDelay={300}
placement={'right-start'}
disableFocusListener={!collapsed}
disableHoverListener={!collapsed}
disableTouchListener={!collapsed}
>
<a href={to} className={commonCss.unstyled} target='_blank' rel='noopener noreferrer'>
<Button className={classes(css.button, collapsed && css.collapsedButton)}>
<div className={tailwindcss.sideNavItem}>
{icon(css.icon)}
<span className={classes(collapsed && css.collapsedLabel, css.label)}>{title}</span>
<OpenInNewIcon className={css.openInNewTabIcon} />
</div>
</Button>
</a>
</Tooltip>
);
const EnhancedSideNav: React.FC<SideNavProps> = props => {
const gkeMetadata = React.useContext(GkeMetadataContext);
const buildInfo = React.useContext(BuildInfoContext);
return <SideNav {...props} gkeMetadata={gkeMetadata} buildInfo={buildInfo} />;
};
export default EnhancedSideNav;
| 286 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/ReduceGraphSwitch.tsx | /*
* Copyright 2020 Arrikto Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Switch, { SwitchProps } from '@material-ui/core/Switch';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import { stylesheet } from 'typestyle';
import { ExternalLink } from '../atoms/ExternalLink';
import { CardTooltip } from '../atoms/CardTooltip';
const css = stylesheet({
reduceGraphPosition: {
position: 'absolute',
top: 0,
left: 0,
},
});
interface ReduceGraphSwitchProps extends SwitchProps {}
const ReduceGraphSwitch = (props: ReduceGraphSwitchProps) => {
return (
<div className={css.reduceGraphPosition}>
<CardTooltip
helpText={
<div>
<p>
Enables a{' '}
<ExternalLink href='https://en.wikipedia.org/wiki/Transitive_reduction'>
transitive reduction
</ExternalLink>{' '}
of the pipeline graph, hiding all the redundant edges. This option is just a
visualization helper and does not have any permanent effect on the pipeline itself.
</p>
<p>
Note that edges are removed regardless of their function in the pipeline, so the
reduced form might not provide enough details to understand how the pipeline really
behaves.
</p>
</div>
}
>
<FormGroup>
<FormControlLabel
control={<Switch color={'primary'} {...props} />}
label={'Simplify Graph'}
labelPlacement='end'
/>
</FormGroup>
</CardTooltip>
</div>
);
};
export default ReduceGraphSwitch;
| 287 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Metric.test.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import Metric from './Metric';
import { ReactWrapper, ShallowWrapper, shallow } from 'enzyme';
import { RunMetricFormat } from '../apis/run';
describe('Metric', () => {
let tree: ShallowWrapper | ReactWrapper;
const onErrorSpy = jest.fn();
beforeEach(() => {
onErrorSpy.mockClear();
});
afterEach(async () => {
// unmount() should be called before resetAllMocks() in case any part of the unmount life cycle
// depends on mocks/spies
if (tree) {
await tree.unmount();
}
jest.resetAllMocks();
});
it('renders an empty metric when there is no metric', () => {
tree = shallow(<Metric />);
expect(tree).toMatchSnapshot();
});
it('renders an empty metric when metric has no value', () => {
tree = shallow(<Metric metric={{}} />);
expect(tree).toMatchSnapshot();
});
it('renders a metric when metric has value and percentage format', () => {
tree = shallow(<Metric metric={{ format: RunMetricFormat.PERCENTAGE, number_value: 0.54 }} />);
expect(tree).toMatchSnapshot();
});
it('renders an empty metric when metric has no metadata and unspecified format', () => {
tree = shallow(<Metric metric={{ format: RunMetricFormat.UNSPECIFIED, number_value: 0.54 }} />);
expect(tree).toMatchSnapshot();
});
it('renders an empty metric when metric has no metadata and raw format', () => {
tree = shallow(<Metric metric={{ format: RunMetricFormat.RAW, number_value: 0.54 }} />);
expect(tree).toMatchSnapshot();
});
it('renders a metric when metric has max and min value of 0', () => {
tree = shallow(
<Metric
metadata={{ name: 'some metric', count: 1, maxValue: 0, minValue: 0 }}
metric={{ format: RunMetricFormat.RAW, number_value: 0.54 }}
/>,
);
expect(tree).toMatchSnapshot();
});
it('renders a metric and does not log an error when metric is between max and min value', () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
tree = shallow(
<Metric
metadata={{ name: 'some metric', count: 1, maxValue: 1, minValue: 0 }}
metric={{ format: RunMetricFormat.RAW, number_value: 0.54 }}
/>,
);
expect(consoleSpy).toHaveBeenCalledTimes(0);
expect(tree).toMatchSnapshot();
});
it('renders a metric and logs an error when metric has value less than min value', () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
tree = shallow(
<Metric
metadata={{ name: 'some metric', count: 1, maxValue: 1, minValue: 0 }}
metric={{ format: RunMetricFormat.RAW, number_value: -0.54 }}
/>,
);
expect(consoleSpy).toHaveBeenCalled();
expect(tree).toMatchSnapshot();
});
it('renders a metric and logs an error when metric has value greater than max value', () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
tree = shallow(
<Metric
metadata={{ name: 'some metric', count: 1, maxValue: 1, minValue: 0 }}
metric={{ format: RunMetricFormat.RAW, number_value: 2 }}
/>,
);
expect(consoleSpy).toHaveBeenCalled();
expect(tree).toMatchSnapshot();
});
});
| 288 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/Editor.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import AceEditor from 'react-ace';
// Modified AceEditor that supports HTML within provided placeholder. This is
// important because it allows for the usage of multi-line placeholders.
class Editor extends AceEditor {
public updatePlaceholder(): void {
const editor = this.editor;
const { placeholder } = this.props;
const showPlaceholder = !editor.session.getValue().length;
let node = editor.renderer.placeholderNode;
if (!showPlaceholder && node) {
editor.renderer.scroller.removeChild(editor.renderer.placeholderNode);
editor.renderer.placeholderNode = null;
} else if (showPlaceholder && !node) {
node = editor.renderer.placeholderNode = document.createElement('div');
node.innerHTML = placeholder || '';
node.className = 'ace_comment ace_placeholder';
node.style.padding = '0 9px';
node.style.position = 'absolute';
node.style.zIndex = '3';
editor.renderer.scroller.appendChild(node);
} else if (showPlaceholder && node) {
node.innerHTML = placeholder;
}
}
}
export default Editor;
| 289 |
0 | kubeflow_public_repos/pipelines/frontend/src | kubeflow_public_repos/pipelines/frontend/src/components/CustomTable.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import ArrowRight from '@material-ui/icons/ArrowRight';
import Checkbox, { CheckboxProps } from '@material-ui/core/Checkbox';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
import CircularProgress from '@material-ui/core/CircularProgress';
import FilterIcon from '@material-ui/icons/FilterList';
import IconButton from '@material-ui/core/IconButton';
import Input from '../atoms/Input';
import MenuItem from '@material-ui/core/MenuItem';
import Radio from '@material-ui/core/Radio';
import Separator from '../atoms/Separator';
import TableSortLabel from '@material-ui/core/TableSortLabel';
import TextField, { TextFieldProps } from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import { ListRequest } from '../lib/Apis';
import { classes, stylesheet } from 'typestyle';
import { fonts, fontsize, dimension, commonCss, color, padding, zIndex } from '../Css';
import { logger } from '../lib/Utils';
import { debounce } from 'lodash';
import { InputAdornment } from '@material-ui/core';
import { CustomTableRow } from './CustomTableRow';
import { V2beta1Filter, V2beta1PredicateOperation } from 'src/apisv2beta1/filter';
import { ApiFilter, PredicateOp } from 'src/apis/filter';
export enum ExpandState {
COLLAPSED,
EXPANDED,
NONE,
}
export interface Column {
flex?: number;
label: string;
sortKey?: string;
customRenderer?: React.FC<CustomRendererProps<any | undefined>>;
}
export interface CustomRendererProps<T> {
value?: T;
id: string;
}
export interface Row {
expandState?: ExpandState;
error?: string;
id: string;
otherFields: any[];
}
const rowHeight = 40;
export const css = stylesheet({
cell: {
$nest: {
'&:not(:nth-child(2))': {
color: color.inactive,
},
},
alignSelf: 'center',
borderBottom: 'initial',
color: color.foreground,
fontFamily: fonts.secondary,
fontSize: fontsize.base,
letterSpacing: 0.25,
marginRight: 20,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
columnName: {
color: '#1F1F1F',
fontSize: fontsize.small,
fontWeight: 'bold',
letterSpacing: 0.25,
marginRight: 20,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
emptyMessage: {
padding: 20,
textAlign: 'center',
},
expandButton: {
marginRight: 10,
padding: 3,
transition: 'transform 0.3s',
},
expandButtonExpanded: {
transform: 'rotate(90deg)',
},
expandButtonPlaceholder: {
width: 54,
},
expandableContainer: {
transition: 'margin 0.2s',
},
expandedContainer: {
borderRadius: 10,
boxShadow: '0 1px 2px 0 rgba(60,64,67,0.30), 0 1px 3px 1px rgba(60,64,67,0.15)',
margin: '16px 2px',
},
expandedRow: {
borderBottom: '1px solid transparent !important',
boxSizing: 'border-box',
height: '40px !important',
},
filterBorderRadius: {
borderRadius: 8,
},
filterBox: {
margin: '16px 0',
},
footer: {
borderBottom: '1px solid ' + color.divider,
fontFamily: fonts.secondary,
height: 40,
textAlign: 'right',
},
header: {
borderBottom: 'solid 1px ' + color.divider,
color: color.strong,
display: 'flex',
flex: '0 0 40px',
lineHeight: '40px', // must declare px
},
noLeftPadding: {
paddingLeft: 0,
},
noMargin: {
margin: 0,
},
row: {
$nest: {
'&:hover': {
backgroundColor: '#f3f3f3',
},
'&:hover a': {
color: color.linkLight,
cursor: 'pointer',
},
},
borderBottom: '1px solid #ddd',
display: 'flex',
flexShrink: 0,
height: rowHeight,
outline: 'none',
},
rowsPerPage: {
color: color.strong,
height: dimension.xsmall,
minWidth: dimension.base,
},
selected: {
backgroundColor: color.activeBg,
},
selectionToggle: {
marginRight: 12,
overflow: 'initial', // Resets overflow from 'hidden'
},
verticalAlignInitial: {
verticalAlign: 'initial',
},
});
interface CustomTableProps {
columns: Column[];
disablePaging?: boolean;
disableSelection?: boolean;
disableSorting?: boolean;
emptyMessage?: string;
filterLabel?: string;
getExpandComponent?: (index: number) => React.ReactNode;
initialSortColumn?: string;
initialSortOrder?: 'asc' | 'desc';
initialFilterString?: string;
isCalledByV1?: boolean;
setFilterString?: (filterString: string) => void;
noFilterBox?: boolean;
reload: (request: ListRequest) => Promise<string>;
rows: Row[];
selectedIds?: string[];
toggleExpansion?: (rowId: number) => void;
updateSelection?: (selectedIds: string[]) => void;
useRadioButtons?: boolean;
disableAdditionalSelection?: boolean;
}
interface CustomTableState {
currentPage: number;
filterString: string;
filterStringEncoded: string;
isBusy: boolean;
maxPageIndex: number;
sortOrder: 'asc' | 'desc';
pageSize: number;
sortBy: string;
tokenList: string[];
}
export default class CustomTable extends React.Component<CustomTableProps, CustomTableState> {
private _isMounted = true;
private _debouncedFilterRequest = debounce(
(filterString: string) => this._requestFilter(filterString),
300,
);
constructor(props: CustomTableProps) {
super(props);
this.state = {
currentPage: 0,
filterString: this.props.initialFilterString || '',
filterStringEncoded:
this.props.initialFilterString && this.props.isCalledByV1
? this._createAndEncodeFilterV1(this.props.initialFilterString)
: this.props.initialFilterString
? this._createAndEncodeFilterV2(this.props.initialFilterString)
: '',
isBusy: false,
maxPageIndex: Number.MAX_SAFE_INTEGER,
pageSize: 10,
sortBy:
props.initialSortColumn || (props.columns.length ? props.columns[0].sortKey || '' : ''),
sortOrder: props.initialSortOrder || 'desc',
tokenList: [''],
};
}
public handleSelectAllClick(event: React.ChangeEvent): void {
if (this.props.disableSelection === true) {
// This should be impossible to reach
return;
}
const selectedIds = (event.target as CheckboxProps).checked
? this.props.rows.map(v => v.id)
: [];
if (this.props.updateSelection) {
this.props.updateSelection(selectedIds);
}
}
public handleClick(e: React.MouseEvent, id: string): void {
if (this.props.disableSelection === true) {
return;
}
let newSelected = [];
if (this.props.useRadioButtons) {
newSelected = [id];
} else {
const selectedIds = this.props.selectedIds || [];
const selectedIndex = selectedIds.indexOf(id);
newSelected =
selectedIndex === -1
? selectedIds.concat(id)
: selectedIds.slice(0, selectedIndex).concat(selectedIds.slice(selectedIndex + 1));
}
if (this.props.updateSelection) {
this.props.updateSelection(newSelected);
}
e.stopPropagation();
}
public isSelected(id: string): boolean {
return !!this.props.selectedIds && this.props.selectedIds.indexOf(id) !== -1;
}
public componentDidMount(): void {
this._pageChanged(0);
}
public componentWillUnmount(): void {
this._isMounted = false;
this._debouncedFilterRequest.cancel();
}
public render(): JSX.Element {
const { filterString, pageSize, sortBy, sortOrder } = this.state;
const numSelected = (this.props.selectedIds || []).length;
const totalFlex = this.props.columns.reduce((total, c) => (total += c.flex || 1), 0);
const widths = this.props.columns.map(c => ((c.flex || 1) / totalFlex) * 100);
return (
<div className={commonCss.pageOverflowHidden}>
{/* Filter/Search bar */}
{!this.props.noFilterBox && (
<div>
<Input
id='tableFilterBox'
label={this.props.filterLabel || 'Filter'}
height={48}
maxWidth={'100%'}
className={css.filterBox}
InputLabelProps={{ classes: { root: css.noMargin } }}
onChange={this.handleFilterChange}
value={filterString}
variant='outlined'
InputProps={{
classes: {
notchedOutline: css.filterBorderRadius,
root: css.noLeftPadding,
},
startAdornment: (
<InputAdornment position='end'>
<FilterIcon style={{ color: color.lowContrast, paddingRight: 16 }} />
</InputAdornment>
),
}}
/>
</div>
)}
{/* Header */}
<div className={classes(css.header, this.props.disableSelection && padding(20, 'l'))}>
{// Called as function to avoid breaking shallow rendering tests.
HeaderRowSelectionSection({
disableSelection: this.props.disableSelection,
indeterminate: !!numSelected && numSelected < this.props.rows.length,
isSelected: !!numSelected && numSelected === this.props.rows.length,
onSelectAll: this.handleSelectAllClick.bind(this),
showExpandButton: !!this.props.getExpandComponent,
useRadioButtons: this.props.useRadioButtons,
disableAdditionalSelection: this.props.disableAdditionalSelection,
})}
{this.props.columns.map((col, i) => {
const isColumnSortable = !!this.props.columns[i].sortKey;
const isCurrentSortColumn = sortBy === this.props.columns[i].sortKey;
return (
<div
key={i}
style={{ width: widths[i] + '%' }}
className={css.columnName}
title={
// Browser shows an info popup on hover.
// It helps when there's not enough space for full text.
col.label
}
>
{this.props.disableSorting === true && col.label}
{!this.props.disableSorting && (
<Tooltip
title={isColumnSortable ? 'Sort' : 'Cannot sort by this column'}
enterDelay={300}
>
<TableSortLabel
active={isCurrentSortColumn}
className={commonCss.ellipsis}
direction={isColumnSortable ? sortOrder : undefined}
onClick={() => this._requestSort(this.props.columns[i].sortKey)}
>
{col.label}
</TableSortLabel>
</Tooltip>
)}
</div>
);
})}
</div>
{/* Body */}
<div className={commonCss.scrollContainer} style={{ minHeight: 60 }}>
{/* Busy experience */}
{this.state.isBusy && (
<React.Fragment>
<div className={commonCss.busyOverlay} />
<CircularProgress
size={25}
className={commonCss.absoluteCenter}
style={{ zIndex: zIndex.BUSY_OVERLAY }}
/>
</React.Fragment>
)}
{/* Empty experience */}
{this.props.rows.length === 0 && !!this.props.emptyMessage && !this.state.isBusy && (
<div className={css.emptyMessage}>{this.props.emptyMessage}</div>
)}
{this.props.rows.map((row, i) => {
if (row.otherFields.length !== this.props.columns.length) {
logger.error('Rows must have the same number of cells defined in columns');
return null;
}
const selected = this.isSelected(row.id);
return (
<div
className={classes(
css.expandableContainer,
row.expandState === ExpandState.EXPANDED && css.expandedContainer,
)}
key={i}
>
<div
role='checkbox'
aria-checked={selected}
tabIndex={-1}
className={classes(
'tableRow',
css.row,
this.props.disableSelection === true && padding(20, 'l'),
selected && css.selected,
row.expandState === ExpandState.EXPANDED && css.expandedRow,
)}
onClick={e => this.handleClick(e, row.id)}
>
{// Called as function to avoid breaking shallow rendering tests.
BodyRowSelectionSection({
disableSelection: this.props.disableSelection,
expandState: row.expandState,
isSelected: selected,
onExpand: e => this._expandButtonToggled(e, i),
showExpandButton: !!this.props.getExpandComponent,
useRadioButtons: this.props.useRadioButtons,
disableAdditionalSelection: this.props.disableAdditionalSelection,
})}
<CustomTableRow row={row} columns={this.props.columns} />
</div>
{row.expandState === ExpandState.EXPANDED && this.props.getExpandComponent && (
<div>{this.props.getExpandComponent(i)}</div>
)}
</div>
);
})}
</div>
{/* Footer */}
{!this.props.disablePaging && (
<div className={css.footer}>
<span className={padding(10, 'r')}>Rows per page:</span>
<TextField
select={true}
variant='standard'
className={css.rowsPerPage}
classes={{ root: css.verticalAlignInitial }}
InputProps={{ disableUnderline: true }}
onChange={this._requestRowsPerPage.bind(this)}
value={pageSize}
>
{[10, 20, 50, 100].map((size, i) => (
<MenuItem key={i} value={size}>
{size}
</MenuItem>
))}
</TextField>
<IconButton onClick={() => this._pageChanged(-1)} disabled={!this.state.currentPage}>
<ChevronLeft />
</IconButton>
<IconButton
onClick={() => this._pageChanged(1)}
disabled={this.state.currentPage >= this.state.maxPageIndex}
>
<ChevronRight />
</IconButton>
</div>
)}
</div>
);
}
public async reload(loadRequest?: ListRequest): Promise<string> {
// Override the current state with incoming request
const request: ListRequest = Object.assign(
{
filter: this.state.filterStringEncoded,
orderAscending: this.state.sortOrder === 'asc',
pageSize: this.state.pageSize,
pageToken: this.state.tokenList[this.state.currentPage],
sortBy: this.state.sortBy,
},
loadRequest,
);
let result = '';
try {
this.setStateSafe({
filterStringEncoded: request.filter,
isBusy: true,
pageSize: request.pageSize,
sortBy: request.sortBy,
sortOrder: request.orderAscending ? 'asc' : 'desc',
});
if (request.sortBy && !request.orderAscending) {
request.sortBy += ' desc';
}
result = await this.props.reload(request);
} finally {
this.setStateSafe({ isBusy: false });
}
return result;
}
public handleFilterChange = (event: any) => {
const value = event.target.value;
if (this.props.setFilterString) {
this.props.setFilterString(value || '');
}
// Set state here so that the UI will be updated even if the actual filter request is debounced
this.setStateSafe(
{ filterString: value } as any,
async () => await this._debouncedFilterRequest(value as string),
);
};
// Exposed for testing
protected async _requestFilter(filterString?: string): Promise<void> {
const filterStringEncoded =
filterString && this.props.isCalledByV1
? this._createAndEncodeFilterV1(filterString)
: filterString
? this._createAndEncodeFilterV2(filterString)
: '';
this.setStateSafe({ filterStringEncoded });
this._resetToFirstPage(await this.reload({ filter: filterStringEncoded }));
}
private _createAndEncodeFilterV1(filterString: string): string {
const filter: ApiFilter = {
predicates: [
{
// TODO: remove this hardcoding once more sophisticated filtering is supported
key: 'name',
op: PredicateOp.ISSUBSTRING,
string_value: filterString,
},
],
};
return encodeURIComponent(JSON.stringify(filter));
}
private _createAndEncodeFilterV2(filterString: string): string {
const filter: V2beta1Filter = {
predicates: [
{
// TODO: remove this hardcoding once more sophisticated filtering is supported
key: 'name',
operation: V2beta1PredicateOperation.ISSUBSTRING,
string_value: filterString,
},
],
};
return encodeURIComponent(JSON.stringify(filter));
}
private setStateSafe(newState: Partial<CustomTableState>, cb?: () => void): void {
if (this._isMounted) {
this.setState(newState as any, cb);
}
}
private _requestSort(sortBy?: string): void {
if (sortBy) {
// Set the sort column to the provided column if it's different, and
// invert the sort order it if it's the same column
const sortOrder =
this.state.sortBy === sortBy ? (this.state.sortOrder === 'asc' ? 'desc' : 'asc') : 'asc';
this.setStateSafe({ sortOrder, sortBy }, async () => {
this._resetToFirstPage(
await this.reload({ pageToken: '', orderAscending: sortOrder === 'asc', sortBy }),
);
});
}
}
private async _pageChanged(offset: number): Promise<void> {
let newCurrentPage = this.state.currentPage + offset;
let maxPageIndex = this.state.maxPageIndex;
newCurrentPage = Math.max(0, newCurrentPage);
newCurrentPage = Math.min(this.state.maxPageIndex, newCurrentPage);
const newPageToken = await this.reload({
pageToken: this.state.tokenList[newCurrentPage],
});
if (newPageToken) {
// If we're using the greatest yet known page, then the pageToken will be new.
if (newCurrentPage + 1 === this.state.tokenList.length) {
this.state.tokenList.push(newPageToken);
}
} else {
maxPageIndex = newCurrentPage;
}
this.setStateSafe({ currentPage: newCurrentPage, maxPageIndex });
}
private async _requestRowsPerPage(event: React.ChangeEvent): Promise<void> {
const pageSize = (event.target as TextFieldProps).value as number;
this._resetToFirstPage(await this.reload({ pageSize, pageToken: '' }));
}
private _resetToFirstPage(newPageToken?: string): void {
let maxPageIndex = Number.MAX_SAFE_INTEGER;
const newTokenList = [''];
if (newPageToken) {
newTokenList.push(newPageToken);
} else {
maxPageIndex = 0;
}
// Reset state, since this invalidates the token list and page counter calculations
this.setStateSafe({
currentPage: 0,
maxPageIndex,
tokenList: newTokenList,
});
}
private _expandButtonToggled(e: React.MouseEvent, rowIndex: number): void {
e.stopPropagation();
if (this.props.toggleExpansion) {
this.props.toggleExpansion(rowIndex);
}
}
}
interface SelectionSectionCommonProps {
disableSelection?: boolean;
isSelected: boolean;
showExpandButton: boolean;
useRadioButtons?: boolean;
}
interface HeaderRowSelectionSectionProps extends SelectionSectionCommonProps {
indeterminate?: boolean;
onSelectAll: React.ChangeEventHandler;
disableAdditionalSelection?: boolean;
}
const HeaderRowSelectionSection: React.FC<HeaderRowSelectionSectionProps> = ({
disableSelection,
indeterminate,
isSelected,
onSelectAll,
showExpandButton,
useRadioButtons,
disableAdditionalSelection,
}) => {
const nonEmpty = disableSelection !== true || showExpandButton;
if (!nonEmpty) {
return null;
}
return (
<div className={classes(css.columnName, css.cell, css.selectionToggle)}>
{/* If using checkboxes */}
{disableSelection !== true && useRadioButtons !== true && (
<Checkbox
indeterminate={indeterminate}
color='primary'
checked={isSelected}
onChange={onSelectAll}
disabled={indeterminate && disableAdditionalSelection}
/>
)}
{/* If using radio buttons */}
{disableSelection !== true && useRadioButtons && (
// Placeholder for radio button horizontal space.
<Separator orientation='horizontal' units={42} />
)}
{showExpandButton && <Separator orientation='horizontal' units={40} />}
</div>
);
};
interface BodyRowSelectionSectionProps extends SelectionSectionCommonProps {
expandState?: ExpandState;
onExpand: React.MouseEventHandler;
disableAdditionalSelection?: boolean;
}
const BodyRowSelectionSection: React.FC<BodyRowSelectionSectionProps> = ({
disableSelection,
expandState,
isSelected,
onExpand,
showExpandButton,
useRadioButtons,
disableAdditionalSelection,
}) => (
<>
{/* Expansion toggle button */}
{(disableSelection !== true || showExpandButton) && expandState !== ExpandState.NONE && (
<div className={classes(css.cell, css.selectionToggle)}>
{/* If using checkboxes */}
{disableSelection !== true && useRadioButtons !== true && (
<Checkbox
color='primary'
checked={isSelected}
disabled={!isSelected && disableAdditionalSelection}
/>
)}
{/* If using radio buttons */}
{disableSelection !== true && useRadioButtons && (
<Radio color='primary' checked={isSelected} />
)}
{showExpandButton && (
<IconButton
className={classes(
css.expandButton,
expandState === ExpandState.EXPANDED && css.expandButtonExpanded,
)}
onClick={onExpand}
aria-label='Expand'
>
<ArrowRight />
</IconButton>
)}
</div>
)}
{/* Placeholder for non-expandable rows */}
{expandState === ExpandState.NONE && <div className={css.expandButtonPlaceholder} />}
</>
);
| 290 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/navigators/PipelineVersionCard.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Button from '@material-ui/core/Button';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Paper from '@material-ui/core/Paper';
import Select from '@material-ui/core/Select';
import React, { useState } from 'react';
import { V2beta1Pipeline, V2beta1PipelineVersion } from 'src/apisv2beta1/pipeline';
import { Description } from 'src/components/Description';
import { commonCss } from 'src/Css';
import { formatDateString } from 'src/lib/Utils';
interface PipelineVersionCardProps {
pipeline: V2beta1Pipeline | null;
selectedVersion: V2beta1PipelineVersion | undefined;
versions: V2beta1PipelineVersion[];
handleVersionSelected: (versionId: string) => Promise<void>;
}
export function PipelineVersionCard({
pipeline,
selectedVersion,
versions,
handleVersionSelected,
}: PipelineVersionCardProps) {
const [summaryShown, setSummaryShown] = useState(false);
const createVersionUrl = () => {
return selectedVersion?.code_source_url;
};
return (
<>
{!!pipeline && summaryShown && (
<Paper className='absolute bottom-3 left-20 p-5 w-136 z-20'>
<div className='items-baseline flex justify-between'>
<div className={commonCss.header}>Static Pipeline Summary</div>
<Button onClick={() => setSummaryShown(false)} color='secondary'>
Hide
</Button>
</div>
<div className='text-gray-900 mt-5'>Pipeline ID</div>
<div>{pipeline.pipeline_id || 'Unable to obtain Pipeline ID'}</div>
{versions.length > 0 && (
<>
<div className='text-gray-900 mt-5'>
<form autoComplete='off'>
<FormControl>
<InputLabel>Version</InputLabel>
<Select
aria-label='version_selector'
data-testid='version_selector'
value={selectedVersion!.pipeline_version_id}
onChange={event => handleVersionSelected(event.target.value)}
inputProps={{ id: 'version-selector', name: 'selectedVersion' }}
>
{versions.map((v, _) => (
<MenuItem key={v.pipeline_version_id} value={v.pipeline_version_id}>
{v.display_name}
</MenuItem>
))}
</Select>
</FormControl>
</form>
</div>
<div className='text-blue-500 mt-5'>
<a href={createVersionUrl()} target='_blank' rel='noopener noreferrer'>
Version source
</a>
</div>
</>
)}
<div className='text-gray-900 mt-5'>Uploaded on</div>
<div>
{selectedVersion
? formatDateString(selectedVersion.created_at)
: formatDateString(pipeline.created_at)}
</div>
<div className='text-gray-900 mt-5'>Pipeline Description</div>
<Description description={pipeline.description || 'empty pipeline description'} />
{/* selectedVersion is always populated by either selected or pipeline default version if it exists */}
{selectedVersion && selectedVersion.description ? (
<>
<div className='text-gray-900 mt-5'>Version Description</div>
<Description description={selectedVersion.description} />
</>
) : null}
</Paper>
)}
{!summaryShown && (
<div className='flex absolute bottom-5 left-10 pb-5 pl-10 bg-transparent z-20'>
<Button onClick={() => setSummaryShown(!summaryShown)} color='secondary'>
Show Summary
</Button>
</div>
)}
</>
);
}
| 291 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/navigators/PipelineVersionCard.test.tsx | /*
* Copyright 2021 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { V2beta1Pipeline, V2beta1PipelineVersion } from 'src/apisv2beta1/pipeline';
import { testBestPractices } from 'src/TestUtils';
import { PipelineVersionCard } from './PipelineVersionCard';
const OLD_VERSION_NAME = 'old version';
const NEW_VERSION_NAME = 'new version';
const TEST_PIPELINE_ID = 'pipeline-id';
const OLD_TEST_PIPELINE_VERSION_ID = 'old-version-id';
const OLD_TEST_PIPELINE_VERSION: V2beta1PipelineVersion = {
created_at: new Date('2021-11-24T20:58:23.000Z'),
description: 'This is old version description.',
display_name: OLD_VERSION_NAME,
pipeline_id: TEST_PIPELINE_ID,
pipeline_version_id: OLD_TEST_PIPELINE_VERSION_ID,
};
const NEW_TEST_PIPELINE_VERSION_ID = 'new-version-id';
const NEW_TEST_PIPELINE_VERSION: V2beta1PipelineVersion = {
created_at: new Date('2021-12-24T20:58:23.000Z'),
description: 'This is new version description.',
display_name: NEW_VERSION_NAME,
pipeline_id: TEST_PIPELINE_ID,
pipeline_version_id: NEW_TEST_PIPELINE_VERSION_ID,
};
const TEST_PIPELINE_VERSIONS_LIST: V2beta1PipelineVersion[] = [
OLD_TEST_PIPELINE_VERSION,
NEW_TEST_PIPELINE_VERSION,
];
const TEST_PIPELINE: V2beta1Pipeline = {
created_at: new Date('2021-11-24T20:58:23.000Z'),
description: 'This is pipeline level description.',
display_name: 'v2_lightweight_python_functions_pipeline',
pipeline_id: TEST_PIPELINE_ID,
};
testBestPractices();
describe('PipelineVersionCard', () => {
it('makes Show Summary button visible by default', async () => {
render(
<PipelineVersionCard
pipeline={TEST_PIPELINE}
selectedVersion={OLD_TEST_PIPELINE_VERSION}
versions={TEST_PIPELINE_VERSIONS_LIST}
handleVersionSelected={versionId => {
return Promise.resolve();
}}
></PipelineVersionCard>,
);
screen.getByText('Show Summary');
expect(screen.queryByText('Hide')).toBeNull();
});
it('clicks to open and hide Summary', async () => {
render(
<PipelineVersionCard
pipeline={TEST_PIPELINE}
selectedVersion={OLD_TEST_PIPELINE_VERSION}
versions={TEST_PIPELINE_VERSIONS_LIST}
handleVersionSelected={versionId => {
return Promise.resolve();
}}
></PipelineVersionCard>,
);
userEvent.click(screen.getByText('Show Summary'));
expect(screen.queryByText('Show Summary')).toBeNull();
userEvent.click(screen.getByText('Hide'));
screen.getByText('Show Summary');
});
it('shows Summary and checks detail', async () => {
render(
<PipelineVersionCard
pipeline={TEST_PIPELINE}
selectedVersion={OLD_TEST_PIPELINE_VERSION}
versions={TEST_PIPELINE_VERSIONS_LIST}
handleVersionSelected={versionId => {
return Promise.resolve();
}}
></PipelineVersionCard>,
);
userEvent.click(screen.getByText('Show Summary'));
screen.getByText('Pipeline ID');
screen.getByText(TEST_PIPELINE_ID);
screen.getByText('Version');
screen.getByText(OLD_VERSION_NAME);
screen.getByText('Version source');
screen.getByText('Uploaded on');
screen.getByText('Pipeline Description');
screen.getByText('This is pipeline level description.');
screen.getByText('This is old version description.');
});
it('shows version list', async () => {
const { getByRole } = render(
<PipelineVersionCard
pipeline={TEST_PIPELINE}
selectedVersion={OLD_TEST_PIPELINE_VERSION}
versions={TEST_PIPELINE_VERSIONS_LIST}
handleVersionSelected={versionId => {
return Promise.resolve();
}}
></PipelineVersionCard>,
);
userEvent.click(screen.getByText('Show Summary'));
fireEvent.click(getByRole('button', { name: OLD_VERSION_NAME }));
fireEvent.click(getByRole('listbox'));
getByRole('option', { name: NEW_VERSION_NAME });
});
});
| 292 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/viewers/MetricsDropdown.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { useEffect, useState } from 'react';
import { color, commonCss, fontsize, zIndex } from 'src/Css';
import { classes, stylesheet } from 'typestyle';
import { LinkedArtifact, getArtifactName } from 'src/mlmd/MlmdUtils';
import TwoLevelDropdown, {
DropdownItem,
DropdownSubItem,
SelectedItem,
} from 'src/components/TwoLevelDropdown';
import {
ConfusionMatrixSection,
getHtmlViewerConfig,
getMarkdownViewerConfig,
} from 'src/components/viewers/MetricsVisualizations';
import PlotCard from 'src/components/PlotCard';
import { ViewerConfig } from 'src/components/viewers/Viewer';
import CircularProgress from '@material-ui/core/CircularProgress';
import Banner from 'src/components/Banner';
import { SelectedArtifact } from 'src/pages/CompareV2';
import { useQuery } from 'react-query';
import { errorToMessage, logger } from 'src/lib/Utils';
import { getExecutionDisplayName } from 'src/mlmd/MlmdUtils';
import {
metricsTypeToString,
ExecutionArtifact,
MetricsType,
RunArtifact,
compareCss,
} from 'src/lib/v2/CompareUtils';
const css = stylesheet({
leftCell: {
borderRight: `3px solid ${color.divider}`,
},
rightCell: {
borderLeft: `3px solid ${color.divider}`,
},
cell: {
borderCollapse: 'collapse',
padding: '1rem',
verticalAlign: 'top',
},
errorBanner: {
maxWidth: '40rem',
},
visualizationPlaceholder: {
width: '40rem',
height: '30rem',
backgroundColor: color.lightGrey,
borderRadius: '1rem',
margin: '1rem 0',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
visualizationPlaceholderText: {
fontSize: fontsize.medium,
textAlign: 'center',
padding: '2rem',
},
});
interface MetricsDropdownProps {
filteredRunArtifacts: RunArtifact[];
metricsTab: MetricsType;
selectedArtifacts: SelectedArtifact[];
updateSelectedArtifacts: (selectedArtifacts: SelectedArtifact[]) => void;
namespace?: string;
}
export default function MetricsDropdown(props: MetricsDropdownProps) {
const {
filteredRunArtifacts,
metricsTab,
selectedArtifacts,
updateSelectedArtifacts,
namespace,
} = props;
const [firstSelectedItem, setFirstSelectedItem] = useState<SelectedItem>(
selectedArtifacts[0].selectedItem,
);
const [secondSelectedItem, setSecondSelectedItem] = useState<SelectedItem>(
selectedArtifacts[1].selectedItem,
);
useEffect(() => {
setFirstSelectedItem(selectedArtifacts[0].selectedItem);
setSecondSelectedItem(selectedArtifacts[1].selectedItem);
}, [selectedArtifacts]);
const metricsTabText = metricsTypeToString(metricsTab);
const updateSelectedItemAndArtifact = (
setSelectedItem: (selectedItem: SelectedItem) => void,
panelIndex: number,
selectedItem: SelectedItem,
): void => {
setSelectedItem(selectedItem);
selectedArtifacts[panelIndex].selectedItem = selectedItem;
const linkedArtifact = getLinkedArtifactFromSelectedItem(filteredRunArtifacts, selectedItem);
selectedArtifacts[panelIndex].linkedArtifact = linkedArtifact;
updateSelectedArtifacts(selectedArtifacts);
};
const dropdownItems: DropdownItem[] = getDropdownItems(filteredRunArtifacts);
if (dropdownItems.length === 0) {
return <p>There are no {metricsTabText} artifacts available on the selected runs.</p>;
}
return (
<table>
<tbody>
<tr>
<td className={classes(css.cell, css.leftCell)}>
<TwoLevelDropdown
title={`Choose a first ${metricsTabText} artifact`}
items={dropdownItems}
selectedItem={firstSelectedItem}
setSelectedItem={updateSelectedItemAndArtifact.bind(null, setFirstSelectedItem, 0)}
/>
<VisualizationPanelItem
metricsTab={metricsTab}
metricsTabText={metricsTabText}
linkedArtifact={selectedArtifacts[0].linkedArtifact}
namespace={namespace}
/>
</td>
<td className={classes(css.cell, css.rightCell)}>
<TwoLevelDropdown
title={`Choose a second ${metricsTabText} artifact`}
items={dropdownItems}
selectedItem={secondSelectedItem}
setSelectedItem={updateSelectedItemAndArtifact.bind(null, setSecondSelectedItem, 1)}
/>
<VisualizationPanelItem
metricsTab={metricsTab}
metricsTabText={metricsTabText}
linkedArtifact={selectedArtifacts[1].linkedArtifact}
namespace={namespace}
/>
</td>
</tr>
</tbody>
</table>
);
}
interface VisualizationPlaceholderProps {
metricsTabText: string;
}
function VisualizationPlaceholder(props: VisualizationPlaceholderProps) {
const { metricsTabText } = props;
return (
<div className={classes(css.visualizationPlaceholder)}>
<p className={classes(css.visualizationPlaceholderText)}>
The selected {metricsTabText} will be displayed here.
</p>
</div>
);
}
interface VisualizationPanelItemProps {
metricsTab: MetricsType;
metricsTabText: string;
linkedArtifact: LinkedArtifact | undefined;
namespace: string | undefined;
}
function VisualizationPanelItem(props: VisualizationPanelItemProps) {
const { metricsTab, metricsTabText, linkedArtifact, namespace } = props;
const [errorMessage, setErrorMessage] = useState<string>('');
const [showError, setShowError] = useState<boolean>(false);
const { isLoading, isError, error, data: viewerConfigs } = useQuery<ViewerConfig[], Error>(
[
'viewerConfig',
{
artifact: linkedArtifact?.artifact.getId(),
namespace,
},
],
async () => {
let viewerConfigs: ViewerConfig[] = [];
if (linkedArtifact) {
try {
if (metricsTab === MetricsType.HTML) {
viewerConfigs = await getHtmlViewerConfig([linkedArtifact], namespace);
} else if (metricsTab === MetricsType.MARKDOWN) {
viewerConfigs = await getMarkdownViewerConfig([linkedArtifact], namespace);
}
} catch (err) {
throw err;
}
}
return viewerConfigs;
},
{ staleTime: Infinity },
);
useEffect(() => {
if (isLoading) {
return;
}
if (isError) {
(async function() {
const updatedMessage = await errorToMessage(error);
setErrorMessage(updatedMessage);
setShowError(true);
})();
} else {
setShowError(false);
}
}, [isLoading, isError, error, setErrorMessage, setShowError]);
if (!linkedArtifact) {
return <VisualizationPlaceholder metricsTabText={metricsTabText} />;
}
if (metricsTab === MetricsType.CONFUSION_MATRIX) {
return (
<React.Fragment key={linkedArtifact.artifact.getId()}>
<ConfusionMatrixSection artifact={linkedArtifact.artifact} />
</React.Fragment>
);
}
if (showError || isLoading) {
return (
<React.Fragment>
{showError && (
<div className={css.errorBanner}>
<Banner
message={`Error: failed loading ${metricsTabText} file.${errorMessage &&
' Click Details for more information.'}`}
mode='error'
additionalInfo={errorMessage}
isLeftAlign
/>
</div>
)}
{isLoading && (
<div className={compareCss.relativeContainer}>
<CircularProgress
size={25}
className={commonCss.absoluteCenter}
style={{ zIndex: zIndex.BUSY_OVERLAY }}
role='circularprogress'
/>
</div>
)}
</React.Fragment>
);
}
if (viewerConfigs && (metricsTab === MetricsType.HTML || metricsTab === MetricsType.MARKDOWN)) {
return <PlotCard configs={viewerConfigs} title={`Static ${metricsTabText}`} />;
}
return <></>;
}
const logDisplayNameWarning = (type: string, id: string) =>
logger.warn(`Failed to fetch the display name of the ${type} with the following ID: ${id}`);
// Group each artifact name with its parent execution name.
function getDropdownSubLinkedArtifacts(linkedArtifacts: LinkedArtifact[], subItemName: string) {
const executionLinkedArtifacts: DropdownSubItem[] = [];
for (const linkedArtifact of linkedArtifacts) {
const artifactName = getArtifactName(linkedArtifact);
const artifactId = linkedArtifact.artifact.getId().toString();
if (!artifactName) {
logDisplayNameWarning('artifact', artifactId);
}
executionLinkedArtifacts.push({
name: subItemName,
secondaryName: artifactName || artifactId,
} as DropdownSubItem);
}
return executionLinkedArtifacts;
}
// Combine execution names and artifact names into the same dropdown sub item list.
function getDropdownSubItems(executionArtifacts: ExecutionArtifact[]) {
const subItems: DropdownSubItem[] = [];
for (const executionArtifact of executionArtifacts) {
const executionName = getExecutionDisplayName(executionArtifact.execution);
const executionId = executionArtifact.execution.getId().toString();
if (!executionName) {
logDisplayNameWarning('execution', executionId);
}
const executionLinkedArtifacts: DropdownSubItem[] = getDropdownSubLinkedArtifacts(
executionArtifact.linkedArtifacts,
executionName || executionId,
);
subItems.push(...executionLinkedArtifacts);
}
return subItems;
}
function getDropdownItems(filteredRunArtifacts: RunArtifact[]) {
const dropdownItems: DropdownItem[] = [];
for (const runArtifact of filteredRunArtifacts) {
const runName = runArtifact.run.display_name;
if (!runName) {
logDisplayNameWarning('run', runArtifact.run.run_id!);
continue;
}
const subItems: DropdownSubItem[] = getDropdownSubItems(runArtifact.executionArtifacts);
if (subItems.length > 0) {
dropdownItems.push({
name: runName,
subItems,
} as DropdownItem);
}
}
return dropdownItems;
}
function getLinkedArtifactFromSelectedItem(
filteredRunArtifacts: RunArtifact[],
selectedItem: SelectedItem,
): LinkedArtifact | undefined {
const filteredRunArtifact = filteredRunArtifacts.find(
runArtifact => runArtifact.run.display_name === selectedItem.itemName,
);
const executionArtifact = filteredRunArtifact?.executionArtifacts.find(executionArtifact => {
const executionText: string =
getExecutionDisplayName(executionArtifact.execution) ||
executionArtifact.execution.getId().toString();
return executionText === selectedItem.subItemName;
});
const linkedArtifact = executionArtifact?.linkedArtifacts.find(linkedArtifact => {
const linkedArtifactText: string =
getArtifactName(linkedArtifact) || linkedArtifact.artifact.getId().toString();
return linkedArtifactText === selectedItem.subItemSecondaryName;
});
return linkedArtifact;
}
| 293 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/viewers/ViewerContainer.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { shallow } from 'enzyme';
import ViewerContainer from './ViewerContainer';
import { PlotType } from './Viewer';
describe('ViewerContainer', () => {
it('does not break on empty configs', () => {
const tree = shallow(<ViewerContainer configs={[]} />);
expect(tree).toMatchSnapshot();
});
Object.keys(PlotType).map(type =>
it('renders a viewer of type ' + type, () => {
const tree = shallow(<ViewerContainer configs={[{ type: PlotType[type] }]} />);
expect(tree).toMatchSnapshot();
}),
);
});
| 294 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/viewers/VisualizationCreator.tsx | /*
* Copyright 2019 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import 'brace';
import BusyButton from '../../atoms/BusyButton';
import FormControl from '@material-ui/core/FormControl';
import Input from '../../atoms/Input';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import Editor from '../Editor';
import Viewer, { ViewerConfig } from './Viewer';
import { ApiVisualizationType } from '../../apis/visualization';
import 'brace/ext/language_tools';
import 'brace/mode/json';
import 'brace/mode/python';
import 'brace/theme/github';
import Button from '@material-ui/core/Button';
export interface VisualizationCreatorConfig extends ViewerConfig {
allowCustomVisualizations?: boolean;
// Whether there is currently a visualization being generated or not.
isBusy?: boolean;
// Function called to generate a visualization.
onGenerate?: (visualizationArguments: string, source: string, type: ApiVisualizationType) => void;
// Facilitate testing by not collapsing by default.
collapsedInitially?: boolean;
}
interface VisualizationCreatorProps {
configs: VisualizationCreatorConfig[];
maxWidth?: number;
}
interface VisualizationCreatorState {
expanded: boolean;
// arguments is expected to be a JSON object in string form.
arguments: string;
code: string;
source: string;
selectedType?: ApiVisualizationType;
}
class VisualizationCreator extends Viewer<VisualizationCreatorProps, VisualizationCreatorState> {
public state: VisualizationCreatorState = {
expanded: !this.props.configs[0]?.collapsedInitially,
arguments: '',
code: '',
source: '',
};
public getDisplayName(): string {
return 'Visualization Creator';
}
public render(): JSX.Element | null {
const { configs } = this.props;
const config = configs[0];
const { arguments: _arguments, code, source, selectedType } = this.state;
if (!config) {
return null;
}
const { allowCustomVisualizations = false, isBusy = false, onGenerate } = config;
// Only allow a visualization to be generated if one is not already being
// generated (as indicated by the isBusy tag), and if there is an source
// provided, and a visualization type is selected, and a onGenerate function
// is provided.
const hasSourceAndSelectedType = source.length > 0 && !!selectedType;
const isCustomTypeAndHasCode = selectedType === ApiVisualizationType.CUSTOM && code.length > 0;
const canGenerate =
!isBusy && !!onGenerate && (hasSourceAndSelectedType || isCustomTypeAndHasCode);
const argumentsPlaceholder = this.getArgumentPlaceholderForType(selectedType);
if (!this.state.expanded) {
return (
<Button variant='text' onClick={this.handleExpansion}>
create visualizations manually
</Button>
);
}
return (
<div
style={{
width: this.props.maxWidth || 600,
}}
>
<FormControl style={{ width: '100%' }}>
<InputLabel htmlFor='visualization-type-selector'>Type</InputLabel>
<Select
value={selectedType}
inputProps={{
id: 'visualization-type-selector',
name: 'Visualization Type',
}}
style={{
minHeight: 60,
width: '100%',
}}
onChange={(e: React.ChangeEvent<{ name?: string; value: unknown }>) => {
this.setState({ selectedType: e.target.value as ApiVisualizationType });
}}
disabled={isBusy}
>
{this.getAvailableTypes(allowCustomVisualizations).map((key: string) => (
<MenuItem key={key} value={ApiVisualizationType[key]}>
{ApiVisualizationType[key]}
</MenuItem>
))}
</Select>
</FormControl>
<Input
label='Source'
variant={'outlined'}
value={source}
disabled={isBusy}
placeholder='File path or path pattern of data within GCS.'
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
this.setState({ source: e.target.value })
}
/>
{selectedType === ApiVisualizationType.CUSTOM && (
<div>
<InputLabel>Custom Visualization Code</InputLabel>
<Editor
placeholder='Python code that will be run to generate visualization.<br><br>To access the source value (if provided), reference the variable "source".<br>To access any provided arguments, reference the variable "variables" (it is a dict object).'
width='100%'
height='175px'
mode='python'
theme='github'
value={code}
onChange={(value: string) => this.setState({ code: value })}
editorProps={{ $blockScrolling: true }}
enableLiveAutocompletion={true}
enableBasicAutocompletion={true}
highlightActiveLine={true}
showGutter={true}
/>
</div>
)}
{!!selectedType && (
<div>
<InputLabel>Arguments (Optional)</InputLabel>
<Editor
placeholder={argumentsPlaceholder}
height={`${argumentsPlaceholder.split('<br>').length * 14}px`}
width='100%'
mode='json'
theme='github'
value={_arguments}
onChange={(value: string) => this.setState({ arguments: value })}
editorProps={{ $blockScrolling: true }}
highlightActiveLine={true}
showGutter={true}
/>
</div>
)}
<BusyButton
title='Generate Visualization'
busy={isBusy}
disabled={!canGenerate}
onClick={() => {
if (onGenerate && selectedType) {
const specifiedArguments: any = JSON.parse(_arguments || '{}');
if (selectedType === ApiVisualizationType.CUSTOM) {
specifiedArguments.code = code.split('\n');
}
onGenerate(JSON.stringify(specifiedArguments), source, selectedType);
}
}}
/>
</div>
);
}
/*
Due to the swagger API definition generation, enum value that include
an _ (underscore) remove all _ from the enum key. Additionally, due to the
manner in which TypeScript is compiled to Javascript, enums are duplicated
iff they included an _ in the proto file. This filters out those duplicate
keys that are generated by the complication from TypeScript to JavaScript.
For example:
export enum ApiVisualizationType {
ROCCURVE = <any> 'ROC_CURVE'
}
Object.keys(ApiVisualizationType) = ['ROCCURVE', 'ROC_CURVE'];
Additional details can be found here:
https://www.typescriptlang.org/play/#code/KYOwrgtgBAggDgSwGoIM5gIYBsEC8MAuCA9iACoCecwUA3gLABQUUASgPIDCnAqq0gFEoAXigAeDCAoA+AOQdOAfV78BsgDRMAvkyYBjUqmJZgAOizEA5gAp4yNJhz4ipStQCUAbiA
*/
private getAvailableTypes(allowCustomVisualizations: boolean): string[] {
return Object.keys(ApiVisualizationType)
.map((key: string) => key.replace('_', ''))
.filter((key: string, i: number, arr: string[]) => {
const isDuplicate = arr.indexOf(key) !== i;
const isCustom = key === 'CUSTOM';
const isTFMA = key === 'TFMA';
return !isDuplicate && (allowCustomVisualizations || !isCustom) && !isTFMA;
});
}
private getArgumentPlaceholderForType(type: ApiVisualizationType | undefined): string {
let placeholder = 'Arguments, provided as JSON, to be used during visualization generation.';
switch (type) {
case ApiVisualizationType.ROCCURVE:
// These arguments are not yet used as the ROC curve visualization is
// still based on the Kubeflow Pipelines component.
// placeholder = `{
// \t"y_true": array,
// \t"y_score": array,
// \t"pos_label": number | string | null,
// \t"sample_weight": array | null,
// \t"drop_intermediate": boolean | null,
// \t"is_generated": boolean | null,
// }`;
placeholder = `{
\t"is_generated": boolean | null,
\t"target_lambda": string | null,
\t"trueclass": string | null,
\t"true_score_column": string | null
}`;
break;
case ApiVisualizationType.TFDV:
placeholder = '{}';
break;
case ApiVisualizationType.TFMA:
placeholder = `{
\t"slicing_column: string | null
}`;
break;
case ApiVisualizationType.TABLE:
placeholder = '{\n\t"headers": array\n}';
break;
case ApiVisualizationType.CUSTOM:
placeholder = '{\n\t"key": any\n}';
break;
}
return (
placeholder
// Replaces newline escape character with HTML break so placeholder can
// support multiple lines.
// eslint-disable-next-line no-control-regex
.replace(new RegExp('\n', 'g'), '<br>')
// Replaces tab escape character with 4 blank spaces so placeholder can
// support indentation.
// eslint-disable-next-line no-control-regex
.replace(new RegExp('\t', 'g'), '    ')
);
}
private handleExpansion = () => {
this.setState({
expanded: true,
});
};
}
export default VisualizationCreator;
| 295 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/viewers/MetricsVisualizations.test.tsx | /*
* Copyright 2022 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import * as React from 'react';
import { CommonTestWrapper } from 'src/TestWrapper';
import { testBestPractices } from 'src/TestUtils';
import { Artifact, Event } from 'src/third_party/mlmd';
import { LinkedArtifact } from 'src/mlmd/MlmdUtils';
import { Struct, Value } from 'google-protobuf/google/protobuf/struct_pb';
import {
ConfidenceMetricsFilter,
ConfidenceMetricsSection,
ConfidenceMetricsSectionProps,
} from './MetricsVisualizations';
import { FullArtifactPath, FullArtifactPathMap, RocCurveColorMap } from 'src/lib/v2/CompareUtils';
import { lineColors } from 'src/components/viewers/ROCCurve';
import TestUtils from 'src/TestUtils';
import * as rocCurveHelper from './ROCCurveHelper';
testBestPractices();
describe('ConfidenceMetricsSection', () => {
const setSelectedIdsSpy = jest.fn();
const setSelectedIdColorMapSpy = jest.fn();
const setLineColorsStackSpy = jest.fn();
function newMockEvent(artifactId: number, executionId: number, displayName?: string): Event {
const event = new Event();
event.setArtifactId(artifactId);
event.setExecutionId(executionId);
event.setType(Event.Type.OUTPUT);
if (displayName) {
const path = new Event.Path();
const step = new Event.Path.Step();
step.setKey(displayName);
path.addSteps(step);
event.setPath(path);
}
return event;
}
function newMockArtifact(id: number, displayName?: string): Artifact {
const artifact = new Artifact();
artifact.setId(id);
const customPropertiesMap: Map<string, Value> = new Map();
const confidenceMetrics: Value = new Value();
confidenceMetrics.setStructValue(
Struct.fromJavaScript({
list: [
{
confidenceThreshold: 2,
falsePositiveRate: 0,
recall: 0,
},
{
confidenceThreshold: 1,
falsePositiveRate: 0,
recall: 0.33962264150943394,
},
{
confidenceThreshold: 0.9,
falsePositiveRate: 0,
recall: 0.6037735849056604,
},
],
}),
);
customPropertiesMap.set('confidenceMetrics', confidenceMetrics);
if (displayName) {
const displayNameValue = new Value();
displayNameValue.setStringValue(displayName);
customPropertiesMap.set('display_name', displayNameValue);
}
jest.spyOn(artifact, 'getCustomPropertiesMap').mockReturnValue(customPropertiesMap);
return artifact;
}
function newMockLinkedArtifact(
artifactId: number,
executionId: number,
displayName?: string,
): LinkedArtifact {
return {
artifact: newMockArtifact(artifactId, displayName),
event: newMockEvent(artifactId, executionId, displayName),
} as LinkedArtifact;
}
interface RocCurveData {
linkedArtifacts: LinkedArtifact[];
fullArtifactPathMap: FullArtifactPathMap;
selectedIds: string[];
}
function generateRocCurveDataByCount(count: number): RocCurveData {
const linkedArtifacts: LinkedArtifact[] = [];
const fullArtifactPathMap: FullArtifactPathMap = {};
const selectedIds: string[] = [];
for (let i = 0; i < count; i++) {
const rocCurveId: string = `${i}-${i}`;
linkedArtifacts.push(newMockLinkedArtifact(i, i, `artifact${i}`));
fullArtifactPathMap[`${i}-${i}`] = {
run: { name: `run${i}`, id: `${i}` },
execution: { name: `execution${i}`, id: `${i}` },
artifact: { name: `artifact${i}`, id: `${i}` },
};
if (i < 10) {
selectedIds.push(rocCurveId);
}
}
return {
linkedArtifacts,
fullArtifactPathMap,
selectedIds,
} as RocCurveData;
}
function generateProps(
selectedIds: string[],
linkedArtifacts?: LinkedArtifact[],
fullArtifactPathMap?: FullArtifactPathMap,
): ConfidenceMetricsSectionProps {
const lineColorsStack = [...lineColors].reverse();
const selectedIdColorMap: RocCurveColorMap = {};
// Note: Only 11 colors are available on the line colors stack, as UI limits selection to 10.
for (const selectedId of selectedIds) {
selectedIdColorMap[selectedId] = lineColorsStack.pop()!;
}
const props: ConfidenceMetricsSectionProps = {
linkedArtifacts: linkedArtifacts || [
newMockLinkedArtifact(1, 1, 'artifact1'),
newMockLinkedArtifact(2, 1, 'artifact2'),
newMockLinkedArtifact(4, 2, 'artifact3'),
],
filter: {
selectedIds,
setSelectedIds: setSelectedIdsSpy,
fullArtifactPathMap: fullArtifactPathMap || {
'1-1': {
run: {
name: 'run1',
id: '1',
},
execution: {
name: 'execution1',
id: '1',
},
artifact: {
name: 'artifact1',
id: '1',
},
} as FullArtifactPath,
'1-2': {
run: {
name: 'run1',
id: '1',
},
execution: {
name: 'Execution ID #1',
id: '1',
},
artifact: {
name: 'Artifact ID #2',
id: '2',
},
} as FullArtifactPath,
'2-4': {
run: {
name: 'Run ID #2',
id: '2',
},
execution: {
name: 'execution2',
id: '2',
},
artifact: {
name: 'artifact4',
id: '4',
},
} as FullArtifactPath,
},
selectedIdColorMap,
setSelectedIdColorMap: setSelectedIdColorMapSpy,
lineColorsStack,
setLineColorsStack: setLineColorsStackSpy,
} as ConfidenceMetricsFilter,
};
return props;
}
it('Render Confidence Metrics section with no selected artifacts', async () => {
render(
<CommonTestWrapper>
<ConfidenceMetricsSection {...generateProps([])} />
</CommonTestWrapper>,
);
await TestUtils.flushPromises();
screen.getByText('ROC Curve: no artifacts');
});
it('Render Confidence Metrics section with one selected artifact', async () => {
render(
<CommonTestWrapper>
<ConfidenceMetricsSection {...generateProps(['1-1'])} />
</CommonTestWrapper>,
);
await TestUtils.flushPromises();
screen.getByText('ROC Curve: artifact1');
});
it('Render Confidence Metrics section with multiple artifacts', async () => {
render(
<CommonTestWrapper>
<ConfidenceMetricsSection {...generateProps(['1-1', '1-2'])} />
</CommonTestWrapper>,
);
await TestUtils.flushPromises();
screen.getByText('ROC Curve: multiple artifacts');
});
it('Error in confidenceMetrics data format', async () => {
const validateConfidenceMetricsSpy = jest.spyOn(rocCurveHelper, 'validateConfidenceMetrics');
validateConfidenceMetricsSpy.mockReturnValue({
error: 'test error',
});
render(
<CommonTestWrapper>
<ConfidenceMetricsSection {...generateProps(['1-1', '1-2'])} />
</CommonTestWrapper>,
);
await TestUtils.flushPromises();
expect(validateConfidenceMetricsSpy).toHaveBeenCalledTimes(1);
screen.getByText(
"Error in artifact1 (artifact ID #1) artifact's confidenceMetrics data format.",
);
});
it('ROC Curve filter selection check all update', async () => {
render(
<CommonTestWrapper>
<ConfidenceMetricsSection {...generateProps(['1-1', '1-2'])} />
</CommonTestWrapper>,
);
await TestUtils.flushPromises();
// Only the selected items are checked.
const selectedCheckboxes = screen
.queryAllByRole('checkbox', { checked: true })
.filter(r => r.nodeName === 'INPUT');
expect(selectedCheckboxes).toHaveLength(2);
// Check all checkboxes (since the top row starts out indeterminate).
const checkboxes = screen.queryAllByRole('checkbox').filter(r => r.nodeName === 'INPUT');
fireEvent.click(checkboxes[0]);
expect(setSelectedIdsSpy).toHaveBeenLastCalledWith(['1-1', '1-2', '2-4']);
expect(setSelectedIdColorMapSpy).toHaveBeenLastCalledWith({
'1-1': '#4285f4',
'1-2': '#2b9c1e',
'2-4': '#e00000',
});
});
it('ROC Curve filter selection uncheck single update', async () => {
render(
<CommonTestWrapper>
<ConfidenceMetricsSection {...generateProps(['1-1', '1-2', '2-4'])} />
</CommonTestWrapper>,
);
await TestUtils.flushPromises();
// Only the selected items are checked.
const selectedCheckboxes = screen
.queryAllByRole('checkbox', { checked: true })
.filter(r => r.nodeName === 'INPUT');
expect(selectedCheckboxes).toHaveLength(4);
// Uncheck the first (non-"select all") checkbox.
const checkboxes = screen.queryAllByRole('checkbox').filter(r => r.nodeName === 'INPUT');
fireEvent.click(checkboxes[1]);
expect(setSelectedIdsSpy).toHaveBeenLastCalledWith(['1-2', '2-4']);
expect(setSelectedIdColorMapSpy).toHaveBeenLastCalledWith({
'1-2': '#2b9c1e',
'2-4': '#e00000',
});
expect(setLineColorsStackSpy).toBeCalledTimes(1);
});
it('ROC Curve show banner when selecting 10 runs', async () => {
const rocCurveData = generateRocCurveDataByCount(15);
render(
<CommonTestWrapper>
<ConfidenceMetricsSection
{...generateProps(
rocCurveData.selectedIds,
rocCurveData.linkedArtifacts,
rocCurveData.fullArtifactPathMap,
)}
/>
</CommonTestWrapper>,
);
await TestUtils.flushPromises();
// Only the selected items are checked.
let checkboxes = screen.queryAllByRole('checkbox').filter(r => r.nodeName === 'INPUT');
let selectedCheckboxes = screen
.queryAllByRole('checkbox', { checked: true })
.filter(r => r.nodeName === 'INPUT');
expect(checkboxes).toHaveLength(11);
expect(selectedCheckboxes).toHaveLength(11);
screen.getByText(
'You have reached the maximum number of ROC Curves (10) you can select at once.',
);
// Get the next page button as the last button.
const buttons = screen.queryAllByRole('button');
const nextPage = buttons[buttons.length - 1];
// Ensure none of the next page checkboxes are checked.
fireEvent.click(nextPage);
checkboxes = screen.queryAllByRole('checkbox').filter(r => r.nodeName === 'INPUT');
selectedCheckboxes = screen
.queryAllByRole('checkbox', { checked: true })
.filter(r => r.nodeName === 'INPUT');
expect(checkboxes).toHaveLength(6);
expect(selectedCheckboxes).toHaveLength(0);
// Selecting a disabled checkbox has no change.
fireEvent.click(checkboxes[1]);
expect(setSelectedIdsSpy).toHaveBeenLastCalledWith(rocCurveData.selectedIds);
});
it('Filter table is present with relevant rows', async () => {
render(
<CommonTestWrapper>
<ConfidenceMetricsSection {...generateProps([])} />
</CommonTestWrapper>,
);
await TestUtils.flushPromises();
// Test the header columns and some different rows
screen.getByText('Execution name > Artifact name');
screen.getByText('execution1 > artifact1');
screen.getByText('Run name');
screen.getByText('Run ID #2');
});
});
| 296 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/viewers/ConfusionMatrix.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { shallow } from 'enzyme';
import ConfusionMatrix, { ConfusionMatrixConfig } from './ConfusionMatrix';
import { PlotType } from './Viewer';
describe('ConfusionMatrix', () => {
it('does not break on empty data', () => {
const tree = shallow(<ConfusionMatrix configs={[]} />);
expect(tree).toMatchSnapshot();
});
const data = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
];
const config: ConfusionMatrixConfig = {
axes: ['test x axis', 'test y axis'],
data,
labels: ['label1', 'label2'],
type: PlotType.CONFUSION_MATRIX,
};
it('renders a basic confusion matrix', () => {
const tree = shallow(<ConfusionMatrix configs={[config]} />);
expect(tree).toMatchSnapshot();
});
it('does not break on asymetric data', () => {
const testConfig = { ...config };
testConfig.data = data.slice(1);
const tree = shallow(<ConfusionMatrix configs={[testConfig]} />);
expect(tree).toMatchSnapshot();
});
it('renders only one of the given list of configs', () => {
const tree = shallow(<ConfusionMatrix configs={[config, config, config]} />);
expect(tree).toMatchSnapshot();
});
it('renders a small confusion matrix snapshot, with no labels or footer', () => {
const tree = shallow(<ConfusionMatrix configs={[config]} maxDimension={100} />);
expect(tree).toMatchSnapshot();
});
it('activates row/column on cell hover', () => {
const tree = shallow(<ConfusionMatrix configs={[config]} />);
tree
.find('td')
.at(2)
.simulate('mouseOver');
expect(tree.state()).toHaveProperty('activeCell', [0, 0]);
});
it('returns a user friendly display name', () => {
expect(ConfusionMatrix.prototype.getDisplayName()).toBe('Confusion matrix');
});
});
| 297 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/viewers/HTMLViewer.test.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import { mount } from 'enzyme';
import HTMLViewer, { HTMLViewerConfig } from './HTMLViewer';
import { PlotType } from './Viewer';
describe('HTMLViewer', () => {
it('does not break on empty data', () => {
const tree = mount(<HTMLViewer configs={[]} />);
expect(tree).toMatchSnapshot();
});
const html = '<html><body><div>Hello World!</div></body></html>';
const config: HTMLViewerConfig = {
htmlContent: html,
type: PlotType.WEB_APP,
};
it('renders some basic HTML', () => {
const tree = mount(<HTMLViewer configs={[config]} />);
expect(tree).toMatchSnapshot();
});
it('renders a smaller snapshot version', () => {
const tree = mount(<HTMLViewer configs={[config]} maxDimension={100} />);
expect(tree).toMatchSnapshot();
});
it('uses srcdoc to insert HTML into the iframe', () => {
const tree = mount(<HTMLViewer configs={[config]} />);
expect((tree.instance() as any)._iframeRef.current.srcdoc).toEqual(html);
expect((tree.instance() as any)._iframeRef.current.src).toEqual('about:blank');
});
it('cannot be accessed from main frame of the other way around (no allow-same-origin)', () => {
const tree = mount(<HTMLViewer configs={[config]} />);
expect((tree.instance() as any)._iframeRef.current.window).toBeUndefined();
expect((tree.instance() as any)._iframeRef.current.document).toBeUndefined();
});
it('returns a user friendly display name', () => {
expect(HTMLViewer.prototype.getDisplayName()).toBe('Static HTML');
});
});
| 298 |
0 | kubeflow_public_repos/pipelines/frontend/src/components | kubeflow_public_repos/pipelines/frontend/src/components/viewers/Tensorboard.tsx | /*
* Copyright 2018 The Kubeflow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as React from 'react';
import BusyButton from '../../atoms/BusyButton';
import Button from '@material-ui/core/Button';
import Viewer, { ViewerConfig } from './Viewer';
import { Apis } from '../../lib/Apis';
import { commonCss, padding, color } from '../../Css';
import InputLabel from '@material-ui/core/InputLabel';
import Input from '@material-ui/core/Input';
import MenuItem from '@material-ui/core/MenuItem';
import ListSubheader from '@material-ui/core/ListSubheader';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import { classes, stylesheet } from 'typestyle';
export const css = stylesheet({
button: {
marginBottom: 20,
width: 150,
},
formControl: {
minWidth: 120,
},
select: {
minHeight: 50,
},
shortButton: {
width: 50,
},
warningText: {
color: color.warningText,
},
errorText: {
color: color.errorText,
},
});
export interface TensorboardViewerConfig extends ViewerConfig {
url: string;
namespace: string;
podTemplateSpec?: any; // JSON object of pod template spec
image?: string;
}
interface TensorboardViewerProps {
configs: TensorboardViewerConfig[];
// Interval in ms. If not specified, default to 5000.
intervalOfCheckingTensorboardPodStatus?: number;
}
interface TensorboardViewerState {
busy: boolean;
deleteDialogOpen: boolean;
podAddress: string;
tfImage: string;
// When podAddress is not null, we need to further tell whether the TensorBoard pod is accessible or not
tensorboardReady: boolean;
errorMessage?: string;
}
// TODO: bump default version when https://github.com/kubeflow/pipelines/issues/5521
// is resolved.
const DEFAULT_TF_IMAGE = 'tensorflow/tensorflow:2.2.2';
class TensorboardViewer extends Viewer<TensorboardViewerProps, TensorboardViewerState> {
timerID: NodeJS.Timeout;
constructor(props: any) {
super(props);
this.state = {
busy: false,
deleteDialogOpen: false,
podAddress: '',
tfImage: this._image() || DEFAULT_TF_IMAGE,
tensorboardReady: false,
errorMessage: undefined,
};
}
public getDisplayName(): string {
return 'Tensorboard';
}
public isAggregatable(): boolean {
return true;
}
public componentDidMount(): void {
this._checkTensorboardApp();
this.timerID = setInterval(
() => this._checkTensorboardPodStatus(),
this.props.intervalOfCheckingTensorboardPodStatus || 5000,
);
}
public componentWillUnmount(): void {
clearInterval(this.timerID);
}
public handleImageSelect = (e: React.ChangeEvent<{ name?: string; value: unknown }>): void => {
if (typeof e.target.value !== 'string') {
throw new Error('Invalid event value type, expected string');
}
this.setState({ tfImage: e.target.value });
};
public render(): JSX.Element {
return (
<div>
{this.state.errorMessage && <div className={css.errorText}>{this.state.errorMessage}</div>}
{this.state.podAddress && (
<div>
<div
className={padding(20, 'b')}
>{`Tensorboard ${this.state.tfImage} is running for this output.`}</div>
<a
href={makeProxyUrl(this.state.podAddress)}
target='_blank'
rel='noopener noreferrer'
className={commonCss.unstyled}
>
<Button
className={classes(commonCss.buttonAction, css.button)}
disabled={this.state.busy}
color={'primary'}
>
Open Tensorboard
</Button>
{this.state.tensorboardReady ? (
``
) : (
<div className={css.warningText}>
Tensorboard is starting, and you may need to wait for a few minutes.
</div>
)}
</a>
<div>
<Button
className={css.button}
disabled={this.state.busy}
id={'delete'}
title={`stop tensorboard and delete its instance`}
onClick={this._handleDeleteOpen}
color={'default'}
>
Stop Tensorboard
</Button>
<Dialog
open={this.state.deleteDialogOpen}
onClose={this._handleDeleteClose}
aria-labelledby='dialog-title'
>
<DialogTitle id='dialog-title'>{`Stop Tensorboard?`}</DialogTitle>
<DialogContent>
<DialogContentText>
You can stop the current running tensorboard. The tensorboard viewer will also
be deleted from your workloads.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
className={css.shortButton}
id={'cancel'}
autoFocus={true}
onClick={this._handleDeleteClose}
color='primary'
>
Cancel
</Button>
<BusyButton
className={classes(commonCss.buttonAction, css.shortButton)}
onClick={this._deleteTensorboard}
busy={this.state.busy}
color='primary'
title={`Stop`}
/>
</DialogActions>
</Dialog>
</div>
</div>
)}
{!this.state.podAddress && (
<div>
<div className={padding(30, 'b')}>
<FormControl className={css.formControl}>
<InputLabel htmlFor='viewer-tb-image-select'>TF Image</InputLabel>
<Select
className={css.select}
value={this.state.tfImage}
input={<Input id='viewer-tb-image-select' />}
onChange={this.handleImageSelect}
>
{this._image() && <MenuItem value={this._image()}>{this._image()}</MenuItem>}
<ListSubheader>Tensoflow 1.x</ListSubheader>
<MenuItem value={'tensorflow/tensorflow:1.7.1'}>TensorFlow 1.7.1</MenuItem>
<MenuItem value={'tensorflow/tensorflow:1.8.0'}>TensorFlow 1.8.0</MenuItem>
<MenuItem value={'tensorflow/tensorflow:1.9.0'}>TensorFlow 1.9.0</MenuItem>
<MenuItem value={'tensorflow/tensorflow:1.10.1'}>TensorFlow 1.10.1</MenuItem>
<MenuItem value={'tensorflow/tensorflow:1.11.0'}>TensorFlow 1.11.0</MenuItem>
<MenuItem value={'tensorflow/tensorflow:1.12.3'}>TensorFlow 1.12.3</MenuItem>
<MenuItem value={'tensorflow/tensorflow:1.13.2'}>TensorFlow 1.13.2</MenuItem>
<MenuItem value={'tensorflow/tensorflow:1.14.0'}>TensorFlow 1.14.0</MenuItem>
<MenuItem value={'tensorflow/tensorflow:1.15.5'}>TensorFlow 1.15.5</MenuItem>
<ListSubheader>TensorFlow 2.x</ListSubheader>
<MenuItem value={'tensorflow/tensorflow:2.0.4'}>TensorFlow 2.0.4</MenuItem>
<MenuItem value={'tensorflow/tensorflow:2.1.2'}>TensorFlow 2.1.2</MenuItem>
<MenuItem value={'tensorflow/tensorflow:2.2.2'}>TensorFlow 2.2.2</MenuItem>
</Select>
</FormControl>
</div>
<div>
<BusyButton
className={commonCss.buttonAction}
disabled={!this.state.tfImage}
onClick={this._startTensorboard}
busy={this.state.busy}
title={`Start ${this.props.configs.length > 1 ? 'Combined ' : ''}Tensorboard`}
/>
</div>
</div>
)}
</div>
);
}
private _handleDeleteOpen = () => {
this.setState({ deleteDialogOpen: true });
};
private _handleDeleteClose = () => {
this.setState({ deleteDialogOpen: false });
};
private _getNamespace(): string {
// TODO: We should probably check if all configs have the same namespace.
return this.props.configs[0]?.namespace || '';
}
private _buildUrl(): string {
const urls = this.props.configs.map(c => c.url).sort();
return urls.length === 1 ? urls[0] : urls.map((c, i) => `Series${i + 1}:` + c).join(',');
}
private _podTemplateSpec(): any | undefined {
const podTemplateSpec = this.props.configs[0]?.podTemplateSpec;
// TODO: how to handle multiple config with different pod template specs?
return podTemplateSpec || undefined;
}
private _image(): string | undefined {
return this.props.configs[0]?.image || undefined;
}
private async _checkTensorboardPodStatus(): Promise<void> {
// If pod address is not null and tensorboard pod doesn't seem to be read, pull status again
if (this.state.podAddress && !this.state.tensorboardReady) {
// Remove protocol prefix bofore ":" from pod address if any.
Apis.isTensorboardPodReady(makeProxyUrl(this.state.podAddress)).then(ready => {
this.setState(({ tensorboardReady }) => ({ tensorboardReady: tensorboardReady || ready }));
});
}
}
private async _checkTensorboardApp(): Promise<void> {
this.setState({ busy: true }, async () => {
try {
// TODO: parse tfImage here
const { podAddress, image } = await Apis.getTensorboardApp(
this._buildUrl(),
this._getNamespace(),
);
if (podAddress) {
this.setState({ busy: false, podAddress, tfImage: image });
} else {
// No existing pod
this.setState({ busy: false });
}
} catch (err) {
this.setState({ busy: false, errorMessage: err?.message || 'Unknown error' });
}
});
}
private _startTensorboard = async () => {
this.setState({ busy: true, errorMessage: undefined }, async () => {
try {
await Apis.startTensorboardApp({
logdir: this._buildUrl(),
namespace: this._getNamespace(),
image: this.state.tfImage,
podTemplateSpec: this._podTemplateSpec(),
});
this.setState({ busy: false, tensorboardReady: false }, () => {
this._checkTensorboardApp();
});
} catch (err) {
this.setState({ busy: false, errorMessage: err?.message || 'Unknown error' });
}
});
};
private _deleteTensorboard = async () => {
// delete the already opened Tensorboard, clear the podAddress recorded in frontend,
// and return to the select & start tensorboard page
this.setState({ busy: true, errorMessage: undefined }, async () => {
try {
await Apis.deleteTensorboardApp(this._buildUrl(), this._getNamespace());
this.setState({
busy: false,
deleteDialogOpen: false,
podAddress: '',
tensorboardReady: false,
});
} catch (err) {
this.setState({ busy: false, errorMessage: err?.message || 'Unknown error' });
}
});
};
}
function makeProxyUrl(podAddress: string) {
// Strip the protocol from the URL. This is a workaround for cloud shell
// incorrectly decoding the address and replacing the protocol's // with /.
// Pod address (after stripping protocol) is of the format
// <viewer_service_dns>.kubeflow.svc.cluster.local:6006/tensorboard/<viewer_name>/
// We use this pod address without encoding since encoded pod address failed to open the
// tensorboard instance on this pod.
// TODO: figure out why the encoded pod address failed to open the tensorboard.
return 'apis/v1beta1/_proxy/' + podAddress.replace(/(^\w+:|^)\/\//, '');
}
export default TensorboardViewer;
| 299 |