@material-ui/core#Tab TypeScript Examples

The following examples show how to use @material-ui/core#Tab. 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: 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 #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: 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 #4
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 #5
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 #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: tabsUtil.tsx    From clearflask with Apache License 2.0 6 votes vote down vote up
TabFragment = (props: {
  value: any,
  children: React.ReactNode | ((tabProps: {
    indicator?: React.ReactNode,
    selectionFollowsFocus?: boolean,
  } & Pick<React.ComponentProps<typeof Tab>, 'fullWidth' | 'selected' | 'onChange' | 'textColor' | 'value'>) => React.ReactNode),
},
) => {
  const { value, children, ...tabProps } = props;

  const content = typeof children === 'function' ? children(tabProps) : children;
  return (
    <>
      {content}
    </>
  );
}
Example #8
Source File: AppTabs.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
tabList: readonly Tab[] = [
  {
    name: globalText.tabs.mods,
    component: ModsPage,
    icon: BuildIcon,
  },
  {
    name: globalText.tabs.logs,
    component: LogsPage,
    icon: DvrIcon,
  },
  {
    name: globalText.tabs.settings,
    component: SettingsPage,
    icon: SettingsIcon,
  },
] as const
Example #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: AppTabBar.tsx    From homebase-app with MIT License 5 votes vote down vote up
CustomTab = styled(Tab)({
  flex: 1
})
Example #15
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 #16
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 #17
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 #18
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 #19
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 #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: Home.tsx    From logo-generator with MIT License 4 votes vote down vote up
export default function ScrollableTabsButtonAuto() {
	const classes = useStyles();
	const [value, setValue] = React.useState(0);
	const [modalStyle] = React.useState(getModalStyle);
	const [openLogin, setOpenLogin] = React.useState(false);
	const [openSignUp, setOpenSignUp] = React.useState(false);
	const { currentUser, logout }:any= useAuth();
	const [error, setError] = React.useState('');
	const history = useHistory();
	const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);


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

	const handleMenuClick = (event: React.MouseEvent<HTMLButtonElement>) => {
		setAnchorEl(event.currentTarget);
	  };

	  const handleMenuClose = () => {
		setAnchorEl(null);
	  };

	async function handleLogout(){
		setError("")
		setAnchorEl(null)

		try{
			await logout();
			history.push('/')
		}catch {
			setError('Failed to log out')
		}
	}

	const handleOpen = () => {
		setOpenLogin(true);
	};
	
	const handleClose = () => {
		setOpenLogin(false);
	};

	const LoginBody = (
		<div style={modalStyle} className={classes.paper}>
		  <Login loginOpen={(value1:boolean, value2:boolean)=> {setOpenLogin(value1)
		   setOpenSignUp(value2)} }/>
		</div>
	);

	const signUpBody = (
		<div style={modalStyle} className={classes.paper}>
		  <SignUp signupOpen={(value1:boolean, value2:boolean)=> {setOpenSignUp(value1)
		   setOpenLogin(value2)}}/>
	    </div>
	);
	

	return (
		<div className={classes.root}>
            {/* <AppBar position="sticky" color="default">
                <Toolbar variant="dense">
                    <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
                     <MenuIcon />
                      </IconButton>
                    <Typography variant="h6" className={classes.title}>
                         Logo-Generator
                    </Typography>
                     <Button color="inherit">Login</Button>
					 <Button color="inherit">SignUp</Button>

                </Toolbar>
            </AppBar> */}

			<AppBar position="static" color="default">
			    <Toolbar variant="dense">
                    <Typography variant="h6" className={classes.title}>
                        Logo-Generator
                    </Typography>
	
				    {currentUser ?  <>
					                 <Button onClick={handleMenuClick}>{currentUser.displayName}
                                      <AccountCircleOutlinedIcon></AccountCircleOutlinedIcon>
                                     </Button>
									  <Menu
                                        id="simple-menu"
                                        anchorEl={anchorEl}
                                        keepMounted
                                        open={Boolean(anchorEl)}
                                        onClose={handleMenuClose}
                                      >
                                       <MenuItem onClick={handleMenuClose}>My Logos</MenuItem>
                                       <MenuItem onClick={handleLogout}>Logout</MenuItem>
                                       </Menu>
									</> 
							     : 
					                <>
                                      <Button color="inherit" onClick={handleOpen}>Login</Button>
					                    <Modal
                                         open={openLogin}
                                          onClose={handleClose}
                                        >
                                          {LoginBody}
                                        </Modal>

				                       <Button color="inherit" onClick={() => setOpenSignUp(true)}>SignUp</Button>
				                        <Modal
                                         open={openSignUp}
                                         onClose={() => setOpenSignUp(false)}
                                        >
                                         {signUpBody}
                                        </Modal>
					                </>
                    } 
                </Toolbar>

				<Tabs
					value={value}
					onChange={handleChange}
					indicatorColor="primary"
					textColor="primary"
					variant="scrollable"
				>
					<Tab label="GDG" {...a11yProps(0)} />
					<Tab label="DSC" {...a11yProps(1)} />
					<Tab label="WTM" {...a11yProps(2)} />
				</Tabs>
			</AppBar>
			<TabPanel value={value} index={0}>
				<GDGEditor />
			</TabPanel>
			<TabPanel value={value} index={1}>
				<DSCEditor />
			</TabPanel>
			<TabPanel value={value} index={2}>
				<WTMEditor />
			</TabPanel>
			<br></br>
			<br></br>
			<br></br>
			<br></br>
			<br></br>
			<BottomNavigation className={classes.stickToBottom}>
			<GitHubButton href="https://github.com/dscnsec/logo-generator" data-icon="octicon-star" data-size="large" data-show-count="true" aria-label="Star dscnsec/logo-generator on GitHub">Star</GitHubButton>
				
				<Typography>
				&nbsp;&middot;&nbsp;Created by&nbsp;
					<Link href="https://xprilion.com" target="_blank">
						@xprilion
					</Link>
				</Typography>
			</BottomNavigation>
		</div>
	);
}
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: index.tsx    From firetable with Apache License 2.0 4 votes vote down vote up
export default function Export() {
  const classes = useStyles();
  const [open, setOpen] = useState(false);
  const [mode, setMode] = useState<"Export" | "Download">("Export");
  const { tableState } = useFiretableContext();

  const query: any = useMemo(() => {
    let _query = isCollectionGroup()
      ? db.collectionGroup(tableState?.tablePath!)
      : db.collection(tableState?.tablePath!);
    // add filters
    tableState?.filters.forEach((filter) => {
      _query = _query.where(
        filter.key,
        filter.operator as firebase.default.firestore.WhereFilterOp,
        filter.value
      );
    });
    // optional order results
    if (tableState?.orderBy) {
      tableState?.orderBy?.forEach((orderBy) => {
        _query = _query.orderBy(orderBy.key, orderBy.direction);
      });
    }
    return _query.limit(10000);
  }, [tableState?.tablePath, tableState?.orderBy, tableState?.filters]);

  const handleClose = () => {
    setOpen(false);
    setMode("Export");
  };

  return (
    <>
      <TableHeaderButton
        title="Export/Download"
        onClick={() => setOpen(true)}
        icon={<ExportIcon />}
      />

      {open && (
        <TabContext value={mode}>
          <Modal
            onClose={handleClose}
            classes={{ paper: classes.paper }}
            title={mode}
            header={
              <>
                <DialogContentText>
                  {(tableState?.filters && tableState?.filters.length !== 0) ||
                  (tableState?.orderBy && tableState?.orderBy.length !== 0)
                    ? "The filters and sorting applied to the table will be used in the export"
                    : "No filters or sorting will be applied on the exported data"}
                </DialogContentText>

                <TabList
                  className={classes.tabs}
                  onChange={(_, v) => setMode(v)}
                  indicatorColor="primary"
                  textColor="primary"
                  variant="fullWidth"
                  aria-label="Modal tabs"
                  action={(actions) =>
                    setTimeout(() => actions?.updateIndicator(), 200)
                  }
                >
                  <Tab className={classes.tab} label="Export" value="Export" />
                  <Tab
                    className={classes.tab}
                    label="Download Attachments"
                    value="Download"
                  />
                </TabList>
                <Divider className={classes.divider} />
              </>
            }
          >
            <TabPanel value="Export" className={classes.tabPanel}>
              <ExportDetails query={query} closeModal={handleClose} />
            </TabPanel>

            <TabPanel value="Download" className={classes.tabPanel}>
              <DownloadDetails query={query} closeModal={handleClose} />
            </TabPanel>
          </Modal>
        </TabContext>
      )}
    </>
  );
}
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: TablesTabBar.tsx    From SeeQR with MIT License 4 votes vote down vote up
TablesTabs = ({
  tables,
  selectTable,
  selectedTable,
  selectedDb,
  setERView,
}: TablesTabBarProps) => {
  const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
    selectTable(tables[newValue]);
  };

  const tableIndex = tables.findIndex(
    ({ table_name }) => table_name === selectedTable?.table_name
  );
  
  const [active, setActive] = useState(true);

  const ErView = () => (
    <div>
      { active ? (
        <ERTables tables={tables} selectedDb={selectedDb} />
      ) : (
        <>
          <StyledTabs
            value={tableIndex}
            onChange={handleChange}
            indicatorColor="primary"
            variant="scrollable"
            scrollButtons="auto"
            aria-label="scrollable auto tabs example"
          >
            {tables.map(({ table_name: name }, index) => (
              <Tab label={name} {...a11yProps(index)} key={name} />
            ))}
            ;
          </StyledTabs>
          <br />
          <br />
          {tables.map((tableMap, index) => (
            <TabPanel
              value={tableIndex}
              index={index}
              key={tableMap.table_name}
            >
              <TableDetails table={tableMap} />
            </TabPanel>
          ))}
        </>
      )}
    </div>
  );


  const handleView = (e ,newActive) => {
    // force at least one selected view
    if (newActive !== null) {
      // set the new view to the currect view
      setActive(newActive);
    
      // disable the dummy data button when in ER View
      if (setERView) {
        if (active) setERView(newActive);
        else setERView(newActive);
      };
    }
  };

  const StyledToggleButtonGroup = styled(ToggleButtonGroup)`
  background-color: ${greenPrimary};
  margin-bottom: 10px;
  `;

  return (
    <div>
      <StyledToggleButtonGroup
        value={active}
        exclusive
        onChange={handleView}
        aria-label="active-view"
      >
        <ToggleButton value={true} aria-label="er">
          ER diagram
        </ToggleButton>
        <ToggleButton value={false} aria-label="table">
          Table
        </ToggleButton>
      </StyledToggleButtonGroup>
      {ErView()}
    </div>
  );
}
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: 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 #28
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 #29
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>

  );
}