@material-ui/core#Tabs TypeScript Examples

The following examples show how to use @material-ui/core#Tabs. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppTabs.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
AppTabs = () => {
  const tabStyles = useTabStyles();
  const [selectedTab, setSelectedTab] = useRecoilState(selectedTabState);

  return (
    <Tabs value={selectedTab}>
      {tabList.map((tab: Tab, index: number) => (
        <Tab
          key={tab.name}
          label={tab.name}
          value={index}
          classes={tabStyles}
          icon={<tab.icon color={tab.color} />}
          onClick={() => setSelectedTab(index)}
        />
      ))}
    </Tabs>
  );
}
Example #2
Source File: ComponentTabs.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
ComponentTabs = (props: { title: string; tabs: TabType[] }) => {
  const { title, tabs } = props;

  const [value, setValue] = React.useState(0);

  const handleChange = (_event: any, newValue: number) => {
    setValue(newValue);
  };

  return (
    <InfoCard title={title}>
      <Tabs value={value} onChange={handleChange}>
        {tabs.map(t => (
          <Tab key={t.label} label={t.label} />
        ))}
      </Tabs>
      {tabs.map(({ Component }, idx) => (
        <div
          key={idx}
          {...(idx !== value ? { style: { display: 'none' } } : {})}
        >
          <Component />
        </div>
      ))}
    </InfoCard>
  );
}
Example #3
Source File: GraphiQLBrowser.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
GraphiQLBrowser = (props: GraphiQLBrowserProps) => {
  const { endpoints } = props;

  const classes = useStyles();
  const [tabIndex, setTabIndex] = useState(0);

  if (!endpoints.length) {
    return <Typography variant="h4">No endpoints available</Typography>;
  }

  const { id, fetcher } = endpoints[tabIndex];
  const storage = StorageBucket.forLocalStorage(`plugin/graphiql/data/${id}`);

  return (
    <div className={classes.root}>
      <Suspense fallback={<Progress />}>
        <Tabs
          classes={{ root: classes.tabs }}
          value={tabIndex}
          onChange={(_, value) => setTabIndex(value)}
          indicatorColor="primary"
        >
          {endpoints.map(({ title }, index) => (
            <Tab key={index} label={title} value={index} />
          ))}
        </Tabs>
        <Divider />
        <div className={classes.graphiQlWrapper}>
          <GraphiQL
            headerEditorEnabled
            key={tabIndex}
            fetcher={fetcher}
            storage={storage}
          />
        </div>
      </Suspense>
    </div>
  );
}
Example #4
Source File: Provider.tsx    From Demae with MIT License 6 votes vote down vote up
CapabilityTabs = ({ provider }: { provider: Provider }) => {
	const hisotry = useHistory()
	const providerCapabilities = provider.capabilities || []
	const capability: any = useCapability() || (providerCapabilities.length > 0 ? providerCapabilities[0] : "all")
	const capabilities: any[] = ["all"].concat(provider?.capabilities || [])
	const value = ["all"].concat(Capabilities).includes(capability) ? capabilities.indexOf(capability) : 0
	const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
		const capability = capabilities[newValue]
		hisotry.push(`/providers/${provider.id}?capability=${capability}`)
	};
	return (
		<>
			<Divider />
			<Tabs
				value={value}
				indicatorColor="primary"
				textColor="primary"
				variant="fullWidth"
				scrollButtons="auto"
				onChange={handleChange}
			>
				{
					capabilities.map(value => {
						return <Tab key={value} fullWidth label={TabLabel[value]} />
					})
				}
			</Tabs>
		</>
	)
}
Example #5
Source File: tabsUtil.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
TabsVertical = (props: {
  selected?: string,
  onClick?: (selected: string) => void;
  children?: any,
  TabsProps?: Partial<React.ComponentProps<typeof Tabs>>,
}) => {
  const classes = useStyles();
  return (
    <Tabs
      scrollButtons='off'
      variant='fullWidth'
      orientation='vertical'
      classes={{
        root: classes.expandHeight,
        indicator: classes.tabsIndicator,
        scroller: classNames(classes.tabsScroller, classes.expandHeight),
        flexContainer: classes.expandHeight,

      }}
      value={props.selected}
      onChange={props.onClick ? (e, postId) => props.onClick?.(postId) : undefined}
      // Used for shortening indicator size
      TabIndicatorProps={{ children: <span /> }}
      {...props.TabsProps}
    >
      {props.children}
    </Tabs>
  );
}
Example #6
Source File: TabsContainer.tsx    From bee-dashboard with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export default function SimpleTabs({ values, index, indexChanged }: Props): ReactElement {
  const classes = useStyles()
  const [value, setValue] = React.useState<number>(index || 0)

  const handleChange = (event: React.ChangeEvent<Record<string, never>>, newValue: number) => {
    if (indexChanged) indexChanged(newValue)
    else setValue(newValue)
  }

  const v = index !== undefined ? index : value

  return (
    <div className={classes.root}>
      <Tabs value={v} onChange={handleChange} variant="fullWidth">
        {values.map(({ label }, idx) => (
          <Tab key={idx} label={label} />
        ))}
      </Tabs>
      <div className={classes.content}>
        {values.map(({ component }, idx) => (
          <TabPanel key={idx} value={v} index={idx}>
            {component}
          </TabPanel>
        ))}
      </div>
    </div>
  )
}
Example #7
Source File: FileNavigation.tsx    From bee-dashboard with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export function FileNavigation({ active }: Props): ReactElement {
  const classes = useStyles()
  const navigate = useNavigate()

  function onChange(event: React.ChangeEvent<Record<string, never>>, newValue: number) {
    navigate(newValue === 1 ? ROUTES.DOWNLOAD : ROUTES.UPLOAD)
  }

  return (
    <div className={classes.root}>
      <Tabs value={active === 'UPLOAD' ? 0 : 1} onChange={onChange} variant="fullWidth">
        <Tab className={classes.leftTab} key="UPLOAD" label="Upload" />
        <Tab className={classes.rightTab} key="DOWNLOAD" label="Download" />
      </Tabs>
    </div>
  )
}
Example #8
Source File: DocumentTabs.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
DocumentTabs = ({
  docs,
  docIndex,
  height,
  setDocIndex,
}: TabProps) => {
  const { palette } = useTheme()
  return (
    <Tabs
      style={{ height, width: "12em" }}
      orientation="vertical"
      variant="scrollable"
      value={docIndex}
      onChange={(e, newIndex) => setDocIndex(newIndex)}
      scrollButtons="auto"
    >
      {docs.map(({ text, uri }, idx) => {
        return (
          <Tab
            style={{ borderBottom: `1px solid ${palette.grey[300]}` }}
            label={
              <DocumentTabLabel
                text={text}
                uri={uri}
                idx={idx}
                selectedIndex={docIndex}
              />
            }
            value={idx}
            key={idx}
          />
        )
      })}
    </Tabs>
  )
}
Example #9
Source File: DashboardSnapshotList.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
DashboardSnapshotList = ({ guid }: Props) => {
  const styles = useStyles();
  const newRelicDashboardAPI = useApi(newRelicDashboardApiRef);
  const { value, loading, error } = useAsync(async (): Promise<
    DashboardEntitySummary | undefined
  > => {
    const dashboardObject: Promise<DashboardEntitySummary | undefined> =
      newRelicDashboardAPI.getDashboardEntity(guid);
    return dashboardObject;
  }, [guid]);
  const [value1, setValue1] = useState<number>(0);
  const handleChange = ({}: React.ChangeEvent<{}>, newValue: number) => {
    setValue1(newValue);
  };

  if (loading) {
    return <Progress />;
  }
  if (error) {
    return <ErrorPanel title={error.name} defaultExpanded error={error} />;
  }
  return (
    <Grid container direction="column">
      <Tabs
        selectionFollowsFocus
        indicatorColor="primary"
        textColor="inherit"
        variant="scrollable"
        scrollButtons="auto"
        aria-label="scrollable auto tabs example"
        onChange={handleChange}
        value={value1}
        style={{ width: '100%' }}
      >
        {value?.getDashboardEntity?.data?.actor.entitySearch.results.entities?.map(
          (Entity: ResultEntity, index: number) => {
            return (
              <Tab
                label={Entity.name}
                className={styles.defaultTab}
                classes={{
                  selected: styles.selected,
                  root: styles.tabRoot,
                }}
                {...a11yProps(index)}
              />
            );
          },
        )}
      </Tabs>
      {value?.getDashboardEntity?.data?.actor.entitySearch.results.entities?.map(
        (Entity: ResultEntity, index: number) => {
          return (
            <TabPanel value1={value1} index={index}>
              <DashboardSnapshot
                name={Entity.name}
                permalink={Entity.permalink}
                guid={Entity.guid}
                duration={26297430000}
              />
            </TabPanel>
          );
        },
      )}
    </Grid>
  );
}
Example #10
Source File: Request.tsx    From dashboard with Apache License 2.0 5 votes vote down vote up
Request = ({
  requestBody,
  defaultRequestBody,
  setRequestBody,
}: Props) => {
  const [tab, setTab] = useState(0)

  return (
    <Card>
      <CardHeader
        title="Request Body"
        titleTypographyProps={{ variant: "subtitle1" }}
      />
      <CardContent>
        <Grid container direction={"row"}>
          <Grid item xs={2}>
            <Box p={2}>
              <Tabs
                orientation="vertical"
                aria-label="request type"
                value={tab}
                onChange={(e, v) => setTab(v)}
              >
                <Tab label="Formatted" />
                <Tab label="Raw" />
              </Tabs>
            </Box>
          </Grid>
          <Grid item xs={10}>
            <TabPanel value={tab} index={0}>
              <DocumentRequest
                defaultRequestBody={defaultRequestBody}
                requestBody={requestBody}
                setRequestBody={setRequestBody}
              />
            </TabPanel>
            <TabPanel value={tab} index={1}>
              <TextInput
                id="filled-textarea"
                label="Request body"
                placeholder="Request body"
                multiline
                minRows={10}
                maxRows={20}
                variant="outlined"
                value={requestBody}
                onChange={(e) => setRequestBody(e.target.value)}
              />
            </TabPanel>
          </Grid>
        </Grid>
      </CardContent>
    </Card>
  )
}
Example #11
Source File: AppTabBar.tsx    From homebase-app with MIT License 5 votes vote down vote up
AppTabBar: React.FC<{
  value: number;
  setValue: any;
  labels: string[];
  class1?: any;
  centered?: boolean;
}> = ({ value, setValue, labels, class1, centered }) => {
  const a11yProps = (index: any) => {
    return {
      id: `simple-tab-${index}`,
      "aria-controls": `simple-tabpanel-${index}`
    };
  };

  const handleChange = (event: React.ChangeEvent<any>, newValue: number) => {
    setValue(newValue);
  };

  const theme = useTheme();
  const isMobileSmall = useMediaQuery(theme.breakpoints.down("sm"));

  return (
    <StyledAppBar
      position="static"
      style={
        centered && !isMobileSmall
          ? { display: "grid", justifyContent: "center" }
          : undefined
      }
    >
      <Tabs
        value={value}
        onChange={handleChange}
        aria-label="simple tabs example"
        style={
          centered && !isMobileSmall
            ? { display: "flex", justifyContent: "center", marginLeft: 12 }
            : undefined
        }
      >
        {labels.map((label, i) => (
          <CustomTab
            label={label}
            {...a11yProps(i)}
            key={i}
            classes={!isMobileSmall ? class1 : undefined}
          />
        ))}
      </Tabs>
    </StyledAppBar>
  );
}
Example #12
Source File: Competitors.tsx    From clearflask with Apache License 2.0 5 votes vote down vote up
TableOfContents = (props: {}) => {
  const classes = useStyles();
  const [anchorId, setAnchorId] = useState<string>();

  var anchorSeen: boolean = !anchorId;

  return (
    <>
      <Typography component='div' variant='h6' className={classes.tocHeading}>Contents</Typography>
      <Scrollspy
        items={TableOfContentsAnchors.map(item => item.id)}
        componentTag='div'
        onUpdate={(el) => { setAnchorId(el?.id); }}
      >
        <Tabs
          orientation='vertical'
          indicatorColor='primary'
          value={anchorId || null}
          classes={{
            indicator: classes.tocIndicator,
          }}
          onChange={(e, newAnchorId) => {
            e.preventDefault();
            scrollToAnchorId(newAnchorId);
            return false;
          }}
        >
          {TableOfContentsAnchors.map(anchor => {
            const Icon = anchor.icon;

            if (!anchorSeen && anchor.id === anchorId) {
              anchorSeen = true;
            }

            return (
              <Tab
                className={classNames(classes.tocItem, !anchorSeen && classes.tocItemRead)}
                classes={{
                  wrapper: classes.tocItemWrapper,
                }}
                key={anchor.id}
                label={anchor.title}
                value={anchor.id}
                icon={(
                  <Icon
                    className={classes.tocItemIcon}
                    fontSize='inherit'
                  />
                )}
              />
            );
          })}
        </Tabs>
      </Scrollspy>
    </>
  );
}
Example #13
Source File: HubNavigationBar.tsx    From dashboard with Apache License 2.0 5 votes vote down vote up
export default function HubNavigationBar({
  handleChange,
  handleSearch,
  tabNumber,
}: Props) {
  let [searchString, setSearchString] = useState("")

  const NavItems = ["Hub Explore", "Hub List", "My Images", "My Favourites"]

  const SearchBar = styled.div`
    background-color: ${(props) => props.theme.palette.grey[100]};
    border-radius: 2px;
    cursor: pointer;
    min-width: 350px;
    display: flex;
  `

  const HubTabs = styled(Tabs)`
    flex-grow: 1;
  `

  const HubSearchIcon = styled(SearchIcon)`
    margin: 11px;
    margin-left: 20px;
  `

  const handleKeyPress = (event: KeyboardEvent<HTMLDivElement>) => {
    if (event.key === "Enter") handleSearch(searchString)
  }
  return (
    <AppBar elevation={0} position={"static"}>
      <Toolbar>
        <HubTabs
          value={tabNumber}
          onChange={handleChange}
          aria-label="simple tabs example"
          textColor="secondary"
          indicatorColor="secondary"
        >
          {NavItems.map((NavItem, idx) => (
            <Tab label={NavItem} {...a11yProps(idx)} />
          ))}
        </HubTabs>
        <SearchBar>
          <HubSearchIcon onClick={(e) => handleSearch(searchString)} />
          <InputBase
            onKeyPress={handleKeyPress}
            autoFocus={true} //todo this is a hack. It looses focus after setSearchString gets triggered
            value={searchString}
            onChange={(e) => setSearchString(e.target.value)}
            placeholder="Search"
            fullWidth={true}
          />
        </SearchBar>
      </Toolbar>
    </AppBar>
  )
}
Example #14
Source File: SearchType.Tabs.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
SearchTypeTabs = (props: SearchTypeTabsProps) => {
  const classes = useStyles();
  const { setPageCursor, setTypes, types } = useSearch();
  const { defaultValue, types: givenTypes } = props;

  const changeTab = (_: React.ChangeEvent<{}>, newType: string) => {
    setTypes(newType !== '' ? [newType] : []);
    setPageCursor(undefined);
  };

  // Handle any provided defaultValue
  useEffect(() => {
    if (defaultValue) {
      setTypes([defaultValue]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const definedTypes = [
    {
      value: '',
      name: 'All',
    },
    ...givenTypes,
  ];

  return (
    <Tabs
      className={classes.tabs}
      indicatorColor="primary"
      value={types.length === 0 ? '' : types[0]}
      onChange={changeTab}
    >
      {definedTypes.map((type, idx) => (
        <Tab
          key={idx}
          className={classes.tab}
          disableRipple
          label={type.name}
          value={type.value}
        />
      ))}
    </Tabs>
  );
}
Example #15
Source File: TablesTabBar.tsx    From SeeQR with MIT License 5 votes vote down vote up
StyledTabs = styled(Tabs)`
  background-color: ${greyPrimary};
  color: white;
  border-radius: 5px;
`
Example #16
Source File: DetailsDialog.tsx    From cognitive-search-static-web-apps-sample-ui with MIT License 5 votes vote down vote up
render(): JSX.Element {

        const state = this.props.state;

        return (
            <Dialog
                open={true}
                onClose={() => this.props.hideMe()}
                fullWidth={true}
                maxWidth="xl"
            >
                <DetailsDialogTitle>
                    {state.name}

                    <CloseButton onClick={() => this.props.hideMe()}>
                        <CloseIcon/>
                    </CloseButton>

                </DetailsDialogTitle>

                <DialogContent>

                    {!!state.errorMessage && (
                        <ErrorChip color="secondary" label={state.errorMessage} onDelete={() => state.HideError()} />
                    )}

                    <Tabs value={state.selectedTab}
                        onChange={(ev: React.ChangeEvent<{}>, val: DetailsTabEnum) => state.selectedTab = val}
                    >
                        <Tab label="Transcript"  />
                        <Tab label="Metadata" />
                        {!!state.coordinates && (<Tab label="Map" />)}
                    </Tabs>

                    <DetailsPaper>
                    
                        {state.selectedTab === DetailsTabEnum.Transcript && !state.inProgress && 
                            (<TranscriptViewer state={state}/>)
                        }

                        {state.selectedTab === DetailsTabEnum.Metadata && !state.inProgress &&
                            (<MetadataViewer state={state}/>)
                        }
                        
                        {state.selectedTab === DetailsTabEnum.Map && !state.inProgress &&
                            (<DetailsDialogMap name={state.name} coordinates={state.coordinates} azureMapSubscriptionKey={this.props.azureMapSubscriptionKey} />)
                        }

                    </DetailsPaper>

                    {!!state.inProgress && (<LinearProgress />)}
                    
                </DialogContent>

                <DetailsDialogActions/>

            </Dialog>
        );
    }
Example #17
Source File: ModeTabs.tsx    From prompts-ai with MIT License 5 votes vote down vote up
export default function ModeTabs() {
    const dispatch = useDispatch();
    const classes = useStyles();
    const tabIndex = useSelector(selectTabIndex);

    const handleTabIndexChange = (event: React.ChangeEvent<{}>, newValue: number) => {
        dispatch(updateTabIndex(newValue));
    };

    return (
        <div className={classes.root}>
            <AppBar position="static">
                <Grid
                    justify="space-between" // Add it here :)
                    alignItems="center"
                    container
                    spacing={1}
                >
                    <Grid item>
                        <Tabs value={tabIndex} onChange={handleTabIndexChange} aria-label="simple tabs example">
                            <Tab label="Simple" {...a11yProps(TabIndex.basic)} />
                            <Tab label="Examples" {...a11yProps(TabIndex.multipleExamples)} />
                            <Tab label="Variations" {...a11yProps(TabIndex.variations)} />
                            <Tab label="Conversations" {...a11yProps(TabIndex.conversations)} />
                        </Tabs>
                    </Grid>
                    <Hidden smDown>
                        <Grid item className={classes.additionalItemsGridItem}>
                            <CodeGeneratorButton/>
                        </Grid>
                    </Hidden>
                </Grid>
            </AppBar>
            <TabPanel value={tabIndex} index={TabIndex.basic}>
                <BasicTab/>
            </TabPanel>
            <TabPanel value={tabIndex} index={TabIndex.multipleExamples}>
                <ExamplesTab/>
            </TabPanel>
            <TabPanel value={tabIndex} index={TabIndex.variations}>
                <VariationsTab/>
            </TabPanel>
            <TabPanel value={tabIndex} index={TabIndex.conversations}>
                <ConversationsTab/>
            </TabPanel>
        </div>
    );
}
Example #18
Source File: InspectEntityDialog.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
/**
 * A dialog that lets users inspect the low level details of their entities.
 *
 * @public
 */
export function InspectEntityDialog(props: {
  open: boolean;
  entity: Entity;
  onClose: () => void;
}) {
  const classes = useStyles();
  const [activeTab, setActiveTab] = React.useState(0);

  useEffect(() => {
    setActiveTab(0);
  }, [props.open]);

  if (!props.entity) {
    return null;
  }

  return (
    <Dialog
      fullWidth
      maxWidth="xl"
      open={props.open}
      onClose={props.onClose}
      aria-labelledby="entity-inspector-dialog-title"
      PaperProps={{ className: classes.fullHeightDialog }}
    >
      <DialogTitle id="entity-inspector-dialog-title">
        Entity Inspector
      </DialogTitle>
      <DialogContent dividers>
        <div className={classes.root}>
          <Tabs
            orientation="vertical"
            variant="scrollable"
            value={activeTab}
            onChange={(_, newValue) => setActiveTab(newValue)}
            aria-label="Inspector options"
            className={classes.tabs}
          >
            <Tab label="Overview" {...a11yProps(0)} />
            <Tab label="Ancestry" {...a11yProps(1)} />
            <Tab label="Colocated" {...a11yProps(2)} />
            <Tab label="Raw JSON" {...a11yProps(3)} />
            <Tab label="Raw YAML" {...a11yProps(4)} />
          </Tabs>

          <TabPanel value={activeTab} index={0}>
            <OverviewPage entity={props.entity} />
          </TabPanel>
          <TabPanel value={activeTab} index={1}>
            <AncestryPage entity={props.entity} />
          </TabPanel>
          <TabPanel value={activeTab} index={2}>
            <ColocatedPage entity={props.entity} />
          </TabPanel>
          <TabPanel value={activeTab} index={3}>
            <JsonPage entity={props.entity} />
          </TabPanel>
          <TabPanel value={activeTab} index={4}>
            <YamlPage entity={props.entity} />
          </TabPanel>
        </div>
      </DialogContent>
      <DialogActions>
        <Button onClick={props.onClose} color="primary">
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #19
Source File: index.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
function GettingStartedCard() {
  const classes = useStyles();
  const [value, setValue] = useState(0);
  return (
    <InfoCard
      title="Get started"
      subheader={
        <Tabs
          value={value}
          indicatorColor="primary"
          textColor="primary"
          onChange={(_ev, newValue: number) => setValue(newValue)}
          aria-label="get started tabs"
          className={classes.tabs}
        >
          <Tab className={classes.tab} label="Use cases" />
          <Tab className={classes.tab} label="Setup" />
        </Tabs>
      }
      divider
      actions={
        <>
          <Grid container direction="row" justifyContent="flex-end">
            <Grid item>
              <Button
                component="a"
                href="https://github.com/spotify/lighthouse-audit-service"
                size="small"
                target="_blank"
              >
                Check out the README
              </Button>
            </Grid>
          </Grid>
        </>
      }
    >
      {value === 0 && <MarkdownContent content={USE_CASES} />}
      {value === 1 && <MarkdownContent content={SETUP} />}
    </InfoCard>
  );
}
Example #20
Source File: log.tsx    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
render(): React.ReactElement {
    return (
      <div className={classes(logDisplayClass)}>
        <Tabs
          value={this.state.value}
          variant="fullWidth"
          indicatorColor="primary"
          textColor="primary"
          onChange={(event, value) => this._onChange(event, value)}
        >
          <Tab label="Sync Log" className={classes(logDisplayTabClass)} />
          <Tab
            label="Conflicts"
            className={classes(logDisplayTabClass)}
            disabled={!this.state.conflict}
          />
        </Tabs>
        <SyncLog service={this.props.service} ref={this.SyncLogElement} />
        <ConflictList
          service={this.props.service}
          ref={this.ConflictListElement}
        />

        <Dialog
          open={this.state.dialog.open}
          onClose={() => this._onClose()}
          fullWidth
        >
          <DialogTitle>File Conflicts</DialogTitle>
          <DialogContent>
            <DialogContentText>{this.state.dialog.msg} </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => this._onClose()} color="primary">
              Cancel
            </Button>
            <Button onClick={() => this._onView()} color="primary" autoFocus>
              View Files
            </Button>
          </DialogActions>
        </Dialog>
      </div>
    );
  }
Example #21
Source File: ProfilePage.tsx    From frontend with Apache License 2.0 4 votes vote down vote up
ProfilePage = () => {
  const { enqueueSnackbar } = useSnackbar();
  const { user } = useUserState();
  const authDispatch = useUserDispatch();
  const projectDispatch = useProjectDispatch();
  const { selectedProjectId } = useProjectState();
  const [email, setEmail] = useState(user?.email);
  const [firstName, setFirstName] = useState(user?.firstName);
  const [lastName, setLastName] = useState(user?.lastName);
  const [password, setPassword] = useState("");
  const [tabIndex, setTabIndex] = React.useState(0);

  const handleUserUpdateSubmit = (event: FormEvent) => {
    event.preventDefault();
    if (user && firstName && lastName && email) {
      update(authDispatch, {
        firstName,
        lastName,
        email,
      })
        .then(() =>
          enqueueSnackbar("User updated", {
            variant: "success",
          })
        )
        .catch((err) =>
          enqueueSnackbar(err, {
            variant: "error",
          })
        );
    }
  };

  const handlePasswordUpdateSubmit = (event: FormEvent) => {
    event.preventDefault();
    if (user && password) {
      usersService
        .changePassword(password)
        .then((isChanged) => {
          setPassword("");
        })
        .then(() =>
          enqueueSnackbar("Password updated", {
            variant: "success",
          })
        )
        .catch((err) =>
          enqueueSnackbar(err, {
            variant: "error",
          })
        );
    }
  };

  const errorForTwoChar = "Enter at least two characters.";

  return (
    <Box m={2}>
      <Grid container spacing={1}>
        <Grid item xs={6}>
          <Grid container spacing={1}>
            <Grid item xs={12}>
              <ValidatorForm onSubmit={handleUserUpdateSubmit} instantValidate>
                <Card variant="outlined">
                  <CardHeader title={"User details"} />
                  <CardContent>
                    <Grid container spacing={2}>
                      <Grid item xs={6}>
                        <TextValidator
                          validators={["minStringLength:2"]}
                          errorMessages={[errorForTwoChar]}
                          id="firstName"
                          name="firstName"
                          value={firstName}
                          label={"First name"}
                          type="text"
                          variant="outlined"
                          required
                          fullWidth
                          inputProps={{
                            onChange: (event: any) =>
                              setFirstName(
                                (event.target as HTMLInputElement).value
                              ),
                            "data-testid": "firstName",
                          }}
                        />
                      </Grid>
                      <Grid item xs={6}>
                        <TextValidator
                          validators={["minStringLength:2"]}
                          errorMessages={[errorForTwoChar]}
                          id="lastName"
                          name="lastName"
                          value={lastName}
                          label={"Last name"}
                          type="text"
                          variant="outlined"
                          required
                          fullWidth
                          inputProps={{
                            onChange: (event: any) =>
                              setLastName(
                                (event.target as HTMLInputElement).value
                              ),
                            "data-testid": "lastName",
                          }}
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <TextValidator
                          validators={["isEmail"]}
                          errorMessages={["Enter valid email address"]}
                          id="email"
                          name="email"
                          value={email}
                          label={"Email address"}
                          type="text"
                          variant="outlined"
                          required
                          fullWidth
                          inputProps={{
                            onChange: (event: any) =>
                              setEmail(
                                (event.target as HTMLInputElement).value
                              ),
                            "data-testid": "email",
                          }}
                        />
                      </Grid>
                      <Grid item xs={12}>
                        <Select
                          id="role"
                          labelId="role"
                          displayEmpty
                          fullWidth
                          disabled
                          value={user?.role}
                        >
                          {Object.entries(Role).map(([key, value]) => (
                            <MenuItem key={key} value={key}>
                              {value}
                            </MenuItem>
                          ))}
                        </Select>
                      </Grid>
                    </Grid>
                  </CardContent>
                  <CardActions>
                    <Grid container justifyContent="center">
                      <Grid item>
                        <Button
                          type="submit"
                          color="primary"
                          variant="outlined"
                          data-testid="submit"
                        >
                          Update
                        </Button>
                      </Grid>
                    </Grid>
                  </CardActions>
                </Card>
              </ValidatorForm>
            </Grid>
            <Grid item xs={12}>
              <ValidatorForm
                onSubmit={handlePasswordUpdateSubmit}
                instantValidate
              >
                <Card variant="outlined">
                  <CardHeader title="Change password" />
                  <CardContent>
                    <Grid container spacing={2}>
                      <Grid item xs={12}>
                        <TextValidator
                          validators={["minStringLength:2"]}
                          errorMessages={[errorForTwoChar]}
                          id="password"
                          name="password"
                          value={password}
                          label={"New password"}
                          type="password"
                          variant="outlined"
                          required
                          fullWidth
                          inputProps={{
                            onChange: (event: any) =>
                              setPassword(
                                (event.target as HTMLInputElement).value
                              ),
                            "data-testid": "password",
                          }}
                        />
                      </Grid>
                    </Grid>
                  </CardContent>
                  <CardActions>
                    <Grid container justifyContent="center">
                      <Grid item>
                        <Button
                          type="submit"
                          color="primary"
                          variant="outlined"
                          data-testid="submit"
                        >
                          Update
                        </Button>
                      </Grid>
                    </Grid>
                  </CardActions>
                </Card>
              </ValidatorForm>
            </Grid>
          </Grid>
        </Grid>
        <Grid item xs={6}>
          <Grid container spacing={1}>
            <Grid item xs={12}>
              <Card variant="outlined">
                <CardHeader title={"Api key"} />
                <CardContent>
                  <Typography>{user?.apiKey}</Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12}>
              <Card variant="outlined">
                <CardHeader title={"Configuration examples"} />
                <CardContent>
                  <ProjectSelect
                    onProjectSelect={(id) => selectProject(projectDispatch, id)}
                  />
                  <Tabs
                    variant="fullWidth"
                    value={tabIndex}
                    indicatorColor="primary"
                    textColor="primary"
                    onChange={(
                      event: React.ChangeEvent<{}>,
                      newValue: number
                    ) => {
                      setTabIndex(newValue);
                    }}
                  >
                    <Tab label="Config file" />
                    <Tab label="ENV variables" />
                  </Tabs>
                  <div role="tabpanel" hidden={tabIndex !== 0}>
                    {tabIndex === 0 && (
                      <Box p={3}>
                        <TextField
                          id="configFile"
                          name="configFile"
                          variant="outlined"
                          disabled
                          value={`{
    "apiUrl": "${window._env_.REACT_APP_API_URL}",
    "apiKey": "${user?.apiKey}",
    "project": "${selectedProjectId ?? "Default project"}",
    "branchName": "master",
    "ciBuildId": "commit_sha",
    "enableSoftAssert": false
}`}
                          multiline
                          rows={8}
                          fullWidth
                          helperText="Save as vrt.json in project root. Could be overridden with ENV variables"
                        />
                      </Box>
                    )}
                  </div>
                  <div role="tabpanel" hidden={tabIndex !== 1}>
                    {tabIndex === 1 && (
                      <Box p={3}>
                        <TextField
                          id="envVariables"
                          name="envVariables"
                          variant="outlined"
                          disabled
                          value={`
  VRT_APIURL="${window._env_.REACT_APP_API_URL}"
  VRT_APIKEY="${user?.apiKey}"
  VRT_PROJECT="${selectedProjectId ?? "Default project"} "
  VRT_BRANCHNAME="master"
  VRT_CIBUILDID="commit_sha"
  VRT_ENABLESOFTASSERT=false
  `}
                          multiline
                          rows={8}
                          fullWidth
                          helperText="Add Environment variables inside CI environment"
                        />
                      </Box>
                    )}
                  </div>
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Box>
  );
}
Example #22
Source File: index.tsx    From firetable with Apache License 2.0 4 votes vote down vote up
export default function BasicCard({
  className,
  style,

  overline,
  title,
  imageSource,
  imageShape = "square",
  imageClassName,

  tabs,
  bodyContent,

  primaryButton,
  primaryLink,
  secondaryAction,
}: ICardProps) {
  const classes = useStyles();

  const [tab, setTab] = useState(0);

  const handleChangeTab = (event: React.ChangeEvent<{}>, newValue: number) =>
    setTab(newValue);

  return (
    <Card className={clsx(classes.root, className)} style={style}>
      <Grid
        container
        direction="column"
        wrap="nowrap"
        className={classes.container}
      >
        <Grid item xs className={classes.cardContentContainer}>
          <CardContent className={clsx(classes.container, classes.cardContent)}>
            <Grid
              container
              direction="column"
              wrap="nowrap"
              className={classes.container}
            >
              {(overline || title || imageSource) && (
                <Grid item className={classes.headerContainer}>
                  <Grid container spacing={3}>
                    <Grid item xs>
                      {overline && (
                        <Typography
                          variant="overline"
                          className={classes.overline}
                        >
                          {overline}
                        </Typography>
                      )}
                      {title && (
                        <Typography variant="h5" className={classes.title}>
                          {title}
                        </Typography>
                      )}
                    </Grid>

                    {imageSource && (
                      <Grid item>
                        <CardMedia
                          className={clsx(
                            classes.image,
                            imageShape === "circle" && classes.imageCircle,
                            imageClassName
                          )}
                          image={imageSource}
                          title={typeof title === "string" ? title : ""}
                        />
                      </Grid>
                    )}
                  </Grid>
                </Grid>
              )}

              {tabs && (
                <Grid item className={classes.tabsContainer}>
                  <Tabs
                    className={classes.tabs}
                    value={tab}
                    onChange={handleChangeTab}
                    indicatorColor="primary"
                    textColor="primary"
                    variant="fullWidth"
                    aria-label="full width tabs"
                  >
                    {tabs?.map((tab, index) => (
                      <Tab
                        key={`card-tab-${index}`}
                        className={classes.tab}
                        label={tab.label}
                        disabled={tab.disabled}
                        {...a11yProps(index)}
                      />
                    ))}
                  </Tabs>
                  <Divider className={clsx(classes.tabs, classes.tabDivider)} />
                </Grid>
              )}

              {(tabs || bodyContent) && (
                <Grid item xs className={classes.contentContainer}>
                  {tabs && (
                    <div className={classes.tabSection}>
                      {tabs[tab].content && Array.isArray(tabs[tab].content) ? (
                        <Grid
                          container
                          direction="column"
                          wrap="nowrap"
                          justify="space-between"
                          spacing={3}
                          className={classes.tabContentGrid}
                        >
                          {(tabs[tab].content as React.ReactNode[]).map(
                            (element, index) => (
                              <Grid item key={`tab-content-${index}`}>
                                {element}
                              </Grid>
                            )
                          )}
                        </Grid>
                      ) : (
                        tabs[tab].content
                      )}
                    </div>
                  )}

                  {bodyContent && Array.isArray(bodyContent) ? (
                    <Grid
                      container
                      direction="column"
                      wrap="nowrap"
                      justify="space-between"
                      className={classes.container}
                    >
                      {bodyContent.map((element, i) => (
                        <Grid item key={i}>
                          {element}
                        </Grid>
                      ))}
                    </Grid>
                  ) : (
                    bodyContent
                  )}
                </Grid>
              )}
            </Grid>
          </CardContent>
        </Grid>

        {(primaryButton || primaryLink || secondaryAction) && (
          <Grid item>
            <Divider className={classes.divider} />
            <CardActions className={classes.cardActions}>
              <Grid item>
                {primaryButton && (
                  <Button
                    {...primaryButton}
                    color={primaryButton.color || "primary"}
                    disabled={!!primaryButton.disabled}
                    endIcon={
                      primaryButton.endIcon === undefined ? (
                        <GoIcon />
                      ) : (
                        primaryButton.endIcon
                      )
                    }
                  >
                    {primaryButton.label}
                  </Button>
                )}
                {primaryLink && (
                  <Button
                    classes={{ label: classes.primaryLinkLabel }}
                    {...(primaryLink as any)}
                    color={primaryLink.color || "primary"}
                    component="a"
                    endIcon={
                      primaryLink.endIcon === undefined ? (
                        <GoIcon />
                      ) : (
                        primaryLink.endIcon
                      )
                    }
                  >
                    {primaryLink.label}
                  </Button>
                )}
              </Grid>
              {secondaryAction && <Grid item>{secondaryAction}</Grid>}
            </CardActions>
          </Grid>
        )}
      </Grid>
    </Card>
  );
}
Example #23
Source File: TableLogs.tsx    From firetable with Apache License 2.0 4 votes vote down vote up
export default function TableLogs() {
  const router = useRouter();
  const { tableState } = useFiretableContext();

  const classes = useStyles();
  const [panalOpen, setPanelOpen] = useState(false);
  const [buildURLConfigured, setBuildURLConfigured] = useState(true);
  const [tabIndex, setTabIndex] = React.useState(0);
  const snackLogContext = useSnackLogContext();

  useEffect(() => {
    checkBuildURL();
  }, []);

  const checkBuildURL = async () => {
    const settingsDoc = await db.doc("/_FIRETABLE_/settings").get();
    const ftBuildUrl = settingsDoc.get("ftBuildUrl");
    if (!ftBuildUrl) {
      setBuildURLConfigured(false);
    }
  };

  const tableCollection = decodeURIComponent(router.match.params.id);
  const ftBuildStreamID =
    "_FIRETABLE_/settings/" +
    `${isCollectionGroup() ? "groupSchema/" : "schema/"}` +
    tableCollection
      .split("/")
      .filter(function (_, i) {
        // replace IDs with subTables that appears at even indexes
        return i % 2 === 0;
      })
      .join("/subTables/");

  const [collectionState] = useCollection({
    path: `${ftBuildStreamID}/ftBuildLogs`,
    orderBy: [{ key: "startTimeStamp", direction: "desc" }],
    limit: 30,
  });
  const latestLog = collectionState?.documents?.[0];
  const latestStatus = latestLog?.status;
  const latestActiveLog =
    latestLog?.startTimeStamp > snackLogContext.latestBuildTimestamp
      ? latestLog
      : null;

  const handleTabChange = (event, newValue) => {
    setTabIndex(newValue);
  };

  return (
    <>
      <TableHeaderButton
        title="Build Logs"
        onClick={() => setPanelOpen(true)}
        icon={
          <>
            {latestStatus === "BUILDING" && <CircularProgress size={20} />}
            {latestStatus === "SUCCESS" && <SuccessIcon />}
            {latestStatus === "FAIL" && <FailIcon />}
            {!latestStatus && <LogsIcon />}
          </>
        }
      />

      {snackLogContext.isSnackLogOpen && (
        <SnackLog
          log={latestActiveLog}
          onClose={snackLogContext.closeSnackLog}
          onOpenPanel={() => {
            setPanelOpen(true);
          }}
        />
      )}

      {panalOpen && !!tableState && (
        <Modal
          onClose={() => {
            setPanelOpen(false);
          }}
          maxWidth="xl"
          fullWidth
          title={
            <>
              Build Logs <Chip label="ALPHA" size="small" />
            </>
          }
          children={
            <>
              {!latestStatus && buildURLConfigured && (
                <EmptyState
                  message="No Logs Found"
                  description={
                    "When you start building, your logs should be shown here shortly"
                  }
                />
              )}
              {!latestStatus && !buildURLConfigured && (
                <EmptyState
                  message="Need Configuration"
                  description={
                    <>
                      <Typography>
                        Function builder is not currently setup.{" "}
                      </Typography>
                      <Button
                        component={"a"}
                        href={routes.projectSettings}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        Go to Settings
                      </Button>
                    </>
                  }
                />
              )}
              {latestStatus && (
                <div className={classes.root}>
                  <Tabs
                    orientation="vertical"
                    variant="scrollable"
                    value={tabIndex}
                    onChange={handleTabChange}
                    className={classes.tabs}
                  >
                    {collectionState.documents?.map((logEntry, index) => (
                      <Tab
                        key={index}
                        label={
                          <Box className={classes.tab}>
                            <Box>
                              {moment(logEntry.startTimeStamp).format(
                                "MMMM D YYYY h:mm:ssa"
                              )}
                            </Box>
                            <Box>
                              {logEntry.status === "BUILDING" && (
                                <CircularProgress size={24} />
                              )}
                              {logEntry.status === "SUCCESS" && <SuccessIcon />}
                              {logEntry.status === "FAIL" && <FailIcon />}
                            </Box>
                          </Box>
                        }
                        {...a11yProps(index)}
                      />
                    ))}
                  </Tabs>
                  {collectionState.documents.map((logEntry, index) => (
                    <LogPanel
                      key={index}
                      value={tabIndex}
                      index={index}
                      logs={logEntry?.fullLog}
                      status={logEntry?.status}
                    />
                  ))}
                </div>
              )}
            </>
          }
        />
      )}
    </>
  );
}
Example #24
Source File: TokenDialog.tsx    From swap-ui with Apache License 2.0 4 votes vote down vote up
export default function TokenDialog({
  open,
  onClose,
  setMint,
}: {
  open: boolean;
  onClose: () => void;
  setMint: (mint: PublicKey) => void;
}) {
  const [tabSelection, setTabSelection] = useState(0);
  const [tokenFilter, setTokenFilter] = useState("");
  const filter = tokenFilter.toLowerCase();
  const styles = useStyles();
  const { swappableTokens, swappableTokensSollet, swappableTokensWormhole } =
    useSwappableTokens();
  const displayTabs = !useMediaQuery("(max-width:450px)");
  const selectedTokens =
    tabSelection === 0
      ? swappableTokens
      : tabSelection === 1
      ? swappableTokensWormhole
      : swappableTokensSollet;
  let tokens =
    tokenFilter === ""
      ? selectedTokens
      : selectedTokens.filter(
          (t) =>
            t.symbol.toLowerCase().startsWith(filter) ||
            t.name.toLowerCase().startsWith(filter) ||
            t.address.toLowerCase().startsWith(filter)
        );
  return (
    <Dialog
      open={open}
      onClose={onClose}
      scroll={"paper"}
      PaperProps={{
        style: {
          borderRadius: "10px",
          width: "420px",
        },
      }}
    >
      <DialogTitle style={{ fontWeight: "bold" }}>
        <Typography variant="h6" style={{ paddingBottom: "16px" }}>
          Select a token
        </Typography>
        <TextField
          className={styles.textField}
          placeholder={"Search name"}
          value={tokenFilter}
          fullWidth
          variant="outlined"
          onChange={(e) => setTokenFilter(e.target.value)}
        />
      </DialogTitle>
      <DialogContent className={styles.dialogContent} dividers={true}>
        <List disablePadding>
          {tokens.map((tokenInfo: TokenInfo) => (
            <TokenListItem
              key={tokenInfo.address}
              tokenInfo={tokenInfo}
              onClick={(mint) => {
                setMint(mint);
                onClose();
              }}
            />
          ))}
        </List>
      </DialogContent>
      {displayTabs && (
        <DialogActions>
          <Tabs
            value={tabSelection}
            onChange={(e, v) => setTabSelection(v)}
            classes={{
              indicator: styles.tabIndicator,
            }}
          >
            <Tab
              value={0}
              className={styles.tab}
              classes={{ selected: styles.tabSelected }}
              label="Main"
            />
            <Tab
              value={1}
              className={styles.tab}
              classes={{ selected: styles.tabSelected }}
              label="Wormhole"
            />
            <Tab
              value={2}
              className={styles.tab}
              classes={{ selected: styles.tabSelected }}
              label="Sollet"
            />
          </Tabs>
        </DialogActions>
      )}
    </Dialog>
  );
}
Example #25
Source File: ExperimentPageView.tsx    From abacus with GNU General Public License v2.0 4 votes vote down vote up
export default function ExperimentPageView({
  view,
  experimentId,
  debugMode,
}: {
  view: ExperimentView
  experimentId: number
  debugMode: boolean
}): JSX.Element {
  const classes = useStyles()

  const {
    isLoading: experimentIsLoading,
    data: experiment,
    error: experimentError,
    reloadRef: experimentReloadRef,
  } = useDataSource(
    () => (experimentId ? ExperimentsApi.findById(experimentId) : createUnresolvingPromise<Schemas.ExperimentFull>()),
    [experimentId],
  )
  useDataLoadingError(experimentError, 'Experiment')

  const {
    isLoading: metricsIsLoading,
    data: metrics,
    error: metricsError,
  } = useDataSource(() => MetricsApi.findAll(), [])
  useDataLoadingError(metricsError, 'Metrics')

  const {
    isLoading: segmentsIsLoading,
    data: segments,
    error: segmentsError,
  } = useDataSource(() => SegmentsApi.findAll(), [])
  useDataLoadingError(segmentsError, 'Segments')

  const { isLoading: tagsIsLoading, data: tags, error: tagsError } = useDataSource(() => TagsApi.findAll(), [])
  useDataLoadingError(tagsError, 'Tags')

  const {
    isLoading: analysesIsLoading,
    data: analyses,
    error: analysesError,
  } = useDataSource(async () => {
    if (!experimentId) {
      return createUnresolvingPromise<Schemas.Analysis[]>()
    }
    return AnalysesApi.findByExperimentId(experimentId)
  }, [experimentId])
  useDataLoadingError(analysesError, 'Analyses')

  const isLoading = or(experimentIsLoading, metricsIsLoading, segmentsIsLoading, tagsIsLoading, analysesIsLoading)

  const canEditInWizard = experiment && experiment.status === Schemas.Status.Staging

  const experimentIdSlug = createIdSlug(experimentId, experiment?.name || '')

  return (
    <Layout headTitle={`${experiment?.name ?? 'unknown'} - Experiment`}>
      <>
        <div className={classes.title}>
          <Typography className={classes.titleHeader} variant='h2'>
            Experiment:{' '}
            {experiment ? (
              <Tooltip title={experiment.name ?? ''}>
                <span className={classes.titleName}>{experiment.name}</span>
              </Tooltip>
            ) : (
              <Skeleton className={classes.titleNameSkeleton} variant='text' width={200} />
            )}
          </Typography>
        </div>
        <div className={classes.topBar}>
          <Tabs className={classes.topBarTabs} value={view}>
            <Tab
              className={classes.topBarTab}
              label='Overview'
              value={ExperimentView.Overview}
              component={Link}
              to={`/experiments/${experimentIdSlug}/overview`}
            />
            <Tab
              className={classes.topBarTab}
              label='Results'
              value={ExperimentView.Results}
              component={Link}
              to={`/experiments/${experimentIdSlug}/results`}
            />
            {debugMode && (
              <Tab
                className={classes.topBarTab}
                label='Debug'
                value={ExperimentView.Debug}
                component={Link}
                to={`/experiments/${experimentIdSlug}/debug`}
              />
            )}
            <Tab
              className={classes.topBarTab}
              label='Code Setup'
              value={ExperimentView.CodeSetup}
              component={Link}
              to={`/experiments/${experimentIdSlug}/code-setup`}
            />
          </Tabs>
          <div className={classes.topBarActions}>
            <ExperimentRunButton {...{ experiment, experimentReloadRef }} />{' '}
            <ExperimentDisableButton {...{ experiment, experimentReloadRef }} className={classes.disableButton} />
            <Tooltip title={canEditInWizard ? '' : 'Only available for staging experiments.'}>
              <span>
                <Button
                  variant='outlined'
                  color='primary'
                  component={Link}
                  to={`/experiments/${experimentIdSlug}/wizard-edit`}
                  disabled={!canEditInWizard}
                >
                  Edit In Wizard
                </Button>
              </span>
            </Tooltip>{' '}
            <Button variant='outlined' color='primary' component={Link} to={`/experiments/${experimentIdSlug}/clone`}>
              Clone
            </Button>
          </div>
        </div>
        {isLoading && <LinearProgress />}
        {experiment && metrics && segments && analyses && tags && (
          <>
            {view === ExperimentView.Overview && (
              <ExperimentDetails {...{ experiment, metrics, segments, tags, experimentReloadRef }} />
            )}
            {view === ExperimentView.Results && <ExperimentResults {...{ experiment, metrics, analyses, debugMode }} />}
            {view === ExperimentView.CodeSetup && <ExperimentCodeSetup />}
          </>
        )}
      </>
    </Layout>
  )
}
Example #26
Source File: OrderList.tsx    From ra-enterprise-demo with MIT License 4 votes vote down vote up
TabbedDatagrid: FC<TabbedDatagridProps> = props => {
    const listContext = useListContext();
    useDefineAppLocation('sales.commands');
    const { ids, filterValues, setFilters, displayedFilters } = listContext;
    const classes = useDatagridStyles();
    const isXSmall = useMediaQuery<Theme>(theme =>
        theme.breakpoints.down('xs')
    );
    const [ordered, setOrdered] = useState<Identifier[]>([] as Identifier[]);
    const [delivered, setDelivered] = useState<Identifier[]>(
        [] as Identifier[]
    );
    const [cancelled, setCancelled] = useState<Identifier[]>(
        [] as Identifier[]
    );
    const totals = useGetTotals(filterValues) as any;

    useEffect(() => {
        if (ids && ids !== filterValues.status) {
            switch (filterValues.status) {
                case 'ordered':
                    setOrdered(ids);
                    break;
                case 'delivered':
                    setDelivered(ids);
                    break;
                case 'cancelled':
                    setCancelled(ids);
                    break;
            }
        }
    }, [ids, filterValues.status]);

    const handleChange = useCallback(
        (event: ChangeEvent<unknown>, value: any) => {
            setFilters &&
                setFilters(
                    { ...filterValues, status: value },
                    displayedFilters
                );
        },
        [displayedFilters, filterValues, setFilters]
    );

    const theme = useTheme();
    const batchLevel =
        parseInt(localStorage.getItem('batchLevel') || '0', 0) || 0;
    const rowStyle = orderRowStyle(batchLevel, theme);

    const selectedIds =
        filterValues.status === 'ordered'
            ? ordered
            : filterValues.status === 'delivered'
            ? delivered
            : cancelled;

    return (
        <Fragment>
            <Tabs
                variant="fullWidth"
                centered
                value={filterValues.status}
                indicatorColor="primary"
                onChange={handleChange}
            >
                {tabs.map(choice => (
                    <Tab
                        key={choice.id}
                        label={
                            totals[choice.name]
                                ? `${choice.name} (${totals[choice.name]})`
                                : choice.name
                        }
                        value={choice.id}
                    />
                ))}
            </Tabs>
            <Divider />
            {isXSmall ? (
                <ListContextProvider
                    value={{ ...listContext, ids: selectedIds }}
                >
                    <MobileGrid {...props} ids={selectedIds} />
                </ListContextProvider>
            ) : (
                <div>
                    {filterValues.status === 'ordered' && (
                        <ListContextProvider
                            value={{ ...listContext, ids: ordered }}
                        >
                            <Datagrid
                                {...props}
                                optimized
                                rowClick="edit"
                                rowStyle={rowStyle}
                                data-testid="order-ordered-datagrid"
                            >
                                <DateField source="date" showTime />
                                <TextField source="reference" />
                                <CustomerReferenceField />
                                <ReferenceField
                                    source="customer_id"
                                    reference="customers"
                                    link={false}
                                    label="resources.commands.fields.address"
                                >
                                    <AddressField />
                                </ReferenceField>
                                <NbItemsField />
                                <NumberField
                                    source="total"
                                    options={{
                                        style: 'currency',
                                        currency: 'USD',
                                    }}
                                    className={classes.total}
                                />
                            </Datagrid>
                        </ListContextProvider>
                    )}
                    {filterValues.status === 'delivered' && (
                        <ListContextProvider
                            value={{ ...listContext, ids: delivered }}
                        >
                            <Datagrid {...props} rowClick="edit">
                                <DateField source="date" showTime />
                                <TextField source="reference" />
                                <CustomerReferenceField />
                                <ReferenceField
                                    source="customer_id"
                                    reference="customers"
                                    link={false}
                                    label="resources.commands.fields.address"
                                >
                                    <AddressField />
                                </ReferenceField>
                                <NbItemsField />
                                <NumberField
                                    source="total"
                                    options={{
                                        style: 'currency',
                                        currency: 'USD',
                                    }}
                                    className={classes.total}
                                />
                                <BooleanField source="returned" />
                            </Datagrid>
                        </ListContextProvider>
                    )}
                    {filterValues.status === 'cancelled' && (
                        <ListContextProvider
                            value={{ ...listContext, ids: cancelled }}
                        >
                            <Datagrid {...props} rowClick="edit">
                                <DateField source="date" showTime />
                                <TextField source="reference" />
                                <CustomerReferenceField />
                                <ReferenceField
                                    source="customer_id"
                                    reference="customers"
                                    link={false}
                                    label="resources.commands.fields.address"
                                >
                                    <AddressField />
                                </ReferenceField>
                                <NbItemsField />
                                <NumberField
                                    source="total"
                                    options={{
                                        style: 'currency',
                                        currency: 'USD',
                                    }}
                                    className={classes.total}
                                />
                                <BooleanField source="returned" />
                            </Datagrid>
                        </ListContextProvider>
                    )}
                </div>
            )}
        </Fragment>
    );
}
Example #27
Source File: ByteAtATime.tsx    From DamnVulnerableCryptoApp with MIT License 4 votes vote down vote up
ByteAtATime = (props: IChallengeProps) => {
  const classes = useStyles();

  const [requests, setRequests] = useState<IRequest[]>([]);
  const [selectedTab, setSelectedTab] = useState(0);
  const [selectedRow, setSelectedRow] = useState(-1);
  const [editedRequest, setEditedRequest] = useState("");

  const layoutContext = useContext(LayoutContext);

  const onTableRowSelected = (i: number) => {
    return (e: React.MouseEvent) => {
      setSelectedRow(i);
    };
  };


  const onTabChange = (event: React.ChangeEvent<{}>, newValue: number) => setSelectedTab(newValue);
  const onEditRequestChange = (event: React.ChangeEvent<HTMLInputElement>) => setEditedRequest(event.target.value);


  const onSubmitClicked = async () => {
    layoutContext.setLoading(true);
    ByteAtATimeService.submitRequest(editedRequest).then(resp => {
      layoutContext.setLoading(false);

      setRequests([...requests, resp]);

      // TODO: find a better way of doing this...
      const m = resp.rawResponse.match(/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/);
      if (m) props.setFlag(m[0]);


    }).catch(err => {
      layoutContext.setLoading(false);
      // TODO: HANDLE ERROR
      // error parsing the request...
    });


  };

  useEffect(() => {
    setRequests(defaultRequests);
    setSelectedRow(0);

  }, []);

  useEffect(() => {
    setEditedRequest(requests[selectedRow]?.rawContent);
    setSelectedTab(0);
  }, [selectedRow]);




  return (
    <Box>
      <Box textAlign="center">
        <img src={faklerLogo} className={classes.logo} />
      </Box>

      <Box mt={2} mb={4}>
        <Alert severity="info">
          A Fakler capture was shared online with you, take a look and have fun :)
      </Alert>
      </Box>

      <Typography variant="h4">Captured Packages</Typography>
      <TableContainer component={Paper} className={classes.requestsTable}>
        <Table>
          <TableHead>
            <TableRow>
              <StyledTableCell>#</StyledTableCell>
              <StyledTableCell>Status</StyledTableCell>
              <StyledTableCell>Method</StyledTableCell>
              <StyledTableCell>Protocol</StyledTableCell>
              <StyledTableCell>Host</StyledTableCell>
              <StyledTableCell>Url</StyledTableCell>

            </TableRow>
          </TableHead>
          <TableBody>
            {
              requests.map((c, i) => (
                <StyledTableRow key={i} onClick={onTableRowSelected(i)} selected={i === selectedRow}>
                  <StyledTableCell>{i}</StyledTableCell>
                  <StyledTableCell>{c.status}</StyledTableCell>
                  <StyledTableCell>{c.method}</StyledTableCell>
                  <StyledTableCell>{c.protocol}</StyledTableCell>
                  <StyledTableCell>{c.host}</StyledTableCell>
                  <StyledTableCell>{c.url}</StyledTableCell>
                </StyledTableRow>
              ))
            }
          </TableBody>
        </Table>
      </TableContainer>


      <Box mt={3}>
        <Tabs value={selectedTab} onChange={onTabChange} className={classes.tabs}>
          <Tab label="Request" icon={<ArrowForwardIcon />} />
          <Tab label="Response" icon={<ArrowBackIcon />} />
          <Tab label="Edit Request" icon={<EditIcon />} />
        </Tabs>
        <TabPanel index={0} selectedTabIndex={selectedTab} className={classes.tabPanel}>
          {<pre>{requests[selectedRow]?.rawContent}</pre>}
        </TabPanel>
        <TabPanel index={1} selectedTabIndex={selectedTab} className={classes.tabPanel}>
          {<pre>{requests[selectedRow]?.rawResponse}</pre>}
        </TabPanel>
        <TabPanel index={2} selectedTabIndex={selectedTab} className={classes.tabPanel}>
          <Box textAlign="right">
            <Button color="primary" type="submit" onClick={onSubmitClicked}>
              Send
            <SendIcon />
            </Button>
          </Box>
          <TextField multiline rows={16} fullWidth value={editedRequest} onChange={onEditRequestChange} className={classes.editRequestInput} />
        </TabPanel>


      </Box>
    </Box>

  );
}
Example #28
Source File: KeyDisclosure.tsx    From DamnVulnerableCryptoApp with MIT License 4 votes vote down vote up
KeyDisclosure = (props: IChallengeProps) => {

  const classes = useStyles();
  const [inboxUnlocked, setInboxUnlocked] = useState(false);
  const [mailboxKey, setMailboxKey] = useState("");
  const [emails, setEmails] = useState<IEmail[]>([]);
  const [selectedEmail, setSelectedEmail] = useState<IEmail>({} as IEmail);
  const layoutContext = useContext(LayoutContext);


  useEffect(() => {
    props.setWarning("This challenge is intended for you to go to the source code of the application and search for something. "
      + "So don't waste your time, go to the project's github page and start digging");
  }, []);

  useEffect(() => {
    setEmailDetails();
  }, [selectedEmail]);

  const onChangeOpenEmail = (mail: IEmail) => {

    return (e: React.MouseEvent) => {
      setSelectedEmail(mail);
    };
  };

  const emailEntry = (index: number, mail: IEmail) => {
    const from = mail.from.split("<")[0];
    const img = mail.from.startsWith("Fake Reporter") ? FakeReporterImg : DetectiveImg;

    return (
      <List key={index}>
        <ListItem button onClick={onChangeOpenEmail(mail)}>
          <ListItemAvatar>
            <Avatar>
              <img src={img} width="50" />
            </Avatar>
          </ListItemAvatar>
          <ListItemText primary={from} secondary={mail.subject} />
        </ListItem>
      </List>
    );
  };


  const setEmailDetails = () => {
    if (!selectedEmail?.from) return;

    const img = selectedEmail.from.startsWith("Fake Reporter") ? FakeReporterImg : DetectiveImg;

    return (
      <Box p={2}>
        <Box display="flex">
          <Avatar><img src={img} width="50" /></Avatar>
          <Box ml={1}>
            <Typography><strong>Subject:</strong> {selectedEmail.subject}</Typography>
            <Typography><small><strong>Date: </strong>{selectedEmail.date}</small></Typography>
          </Box>
        </Box>


        <Box className={classes.emailBody}>
          <Typography>{selectedEmail.body} </Typography>
        </Box>
      </Box>
    );
  };


  return (
    <Box id="key-disclosure-container" style={{ position: 'relative' }}>


      <KeyModal inboxUnlocked={inboxUnlocked} mailboxKey={mailboxKey} setSelectedEmail={setSelectedEmail}
        setEmails={setEmails} setInboxUnlocked={setInboxUnlocked} setMailboxKey={setMailboxKey} setFlag={props.setFlag} />

      <Box mt={2}>
        <AppBar position="static" className={classes.tabs}>
          <Tabs value={0}>
            <Tab label="Inbox" icon={<DraftsIcon />} />
            <Tab label="Stared" icon={<StarIcon />} />
            <Tab label="Drafts" icon={<InsertDriveFileIcon />} />
          </Tabs>
        </AppBar>



        <div role="tabpanel">
          <Box>
            <Grid container className={classes.mailbox} >
              <Grid item sm={4} className={classes.emailList}>
                {
                  emails.map((mail, i) => emailEntry(i, mail))
                }
              </Grid>
              <Grid item sm={8} className={classes.emailDetails}>{setEmailDetails()}</Grid>
            </Grid>
          </Box>
        </div>
      </Box>

    </Box >
  );
}
Example #29
Source File: comments_widget.tsx    From jupyter-extensions with Apache License 2.0 4 votes vote down vote up
render() {
    const activeTab = this.state.activeTab;
    const currFilePath = this.getCurrentFilePath();
    const currWidget = this.props.context.labShell.currentWidget;
    let file: NotebookFile | RegularFile;
    if (this.isNotebook(currWidget)) {
      file = new NotebookFile(currWidget);
    } else {
      file = new RegularFile(currWidget as IDocumentWidget);
    }
    const detachedCommentsList = this.state.detachedComments.map(
      (comment, index) => (
        <div key={index}>
          <Comment detachedComment={comment} file={file} />
          <Divider />
        </div>
      )
    );
    const numDetachedComments = this.state.detachedComments.length;
    const detachedLabel: string =
      'Detached (' + numDetachedComments.toString() + ')';
    const reviewCommentsList = this.state.reviewComments.map(
      (reviewCommentsArr, index) => (
        <div key={index}>
          <CodeReview
            reviewRequest={reviewCommentsArr[0]}
            commentsList={reviewCommentsArr[1]}
            file={file}
          />
          <NewCommentThread
            serverRoot={this.state.serverRoot}
            currFilePath={currFilePath}
            commentType="review"
            reviewHash={reviewCommentsArr[0].reviewHash}
          />
        </div>
      )
    );
    return (
      <ThemeProvider theme={theme}>
        <div className={localStyles.root}>
          <CssBaseline />
          {!this.state.errorMessage && (
            <Grid
              container
              direction="row"
              spacing={1}
              className={localStyles.header}
            >
              <Grid item>
                <CommentIcon color="primary" />
              </Grid>
              <Grid item>
                <Typography variant="h5">
                  Comments for {this.state.fileName}
                </Typography>
              </Grid>
            </Grid>
          )}

          <AppBar position="static">
            <Tabs
              value={activeTab}
              onChange={this.tabChange}
              indicatorColor="secondary"
              className={localStyles.tabs}
            >
              <Tab label="Code Reviews" value={0} />
              <Tab label={detachedLabel} value={1} />
            </Tabs>
          </AppBar>

          {this.state.errorMessage && (
            <Typography
              variant="subtitle1"
              className={localStyles.header}
              gutterBottom
            >
              {' '}
              {this.state.errorMessage}
            </Typography>
          )}
          {!this.state.errorMessage &&
            (this.state.activeTab === 0 ? (
              <>
                <List className={localStyles.commentsList}>
                  {reviewCommentsList}{' '}
                </List>
              </>
            ) : (
              <>
                <NewCommentThread
                  serverRoot={this.state.serverRoot}
                  currFilePath={currFilePath}
                  commentType="detached"
                />
                <List className={localStyles.commentsList}>
                  {' '}
                  {detachedCommentsList}{' '}
                </List>
              </>
            ))}
        </div>
      </ThemeProvider>
    );
  }