@mui/material#Divider TypeScript Examples

The following examples show how to use @mui/material#Divider. 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: CodeExamples.tsx    From GTAV-NativeDB with MIT License 6 votes vote down vote up
function CodeExamples({ examples }: CodeExamplesProps) {
  const [language, setLanguage] = useState(examples[0].lang)
  
  const onTabChange = useCallback((e: SyntheticEvent<Element, Event>, language: string) => {
    setLanguage(language)
  }, [setLanguage])

  return (
    <TabContext value={language}>
      <TabList onChange={onTabChange} sx={{ pl: 0 }}>
        {examples.map(({ lang }) => (
          <Tab
            label={humanLangMap[lang] ?? lang}
            value={lang}
          />
        ))}
      </TabList>
      <Divider />
      {examples.map(({ lang, code }) => (
        <TabPanel value={lang} sx={{ p: 0 }}>
          <SyntaxHighlighter 
            language={langMap[lang] ?? lang} 
          >
            {code}
          </SyntaxHighlighter>
        </TabPanel>
      ))}
    </TabContext>
  )
}
Example #2
Source File: index.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
LogsView: FunctionComponent = () => {
  const onLogs = () => {
    ipcRenderer.send(IpcRequest.OpenLogsFolder);
  };
  return (
    <MainLayout>
      <Card>
        <CardTitle icon={<ListIcon />} title="Logs" />
        <Divider />
        <CardContent>
          <Button
            color="primary"
            size="large"
            variant="contained"
            onClick={onLogs}
          >
            Open logs folder
          </Button>
        </CardContent>
      </Card>
    </MainLayout>
  );
}
Example #3
Source File: TransferDetails.tsx    From abrechnung with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function TransferDetails({ group, transaction }) {
    return (
        <MobilePaper>
            <TransactionActions groupID={group.id} transaction={transaction} />
            <Divider sx={{ marginBottom: 1, marginTop: 1 }} />
            <Grid container>
                <Grid item xs={transaction.is_wip || transaction.files.length > 0 ? 6 : 12}>
                    <TransactionDescription group={group} transaction={transaction} />
                    <TransactionValue group={group} transaction={transaction} />
                    <TransactionBilledAt group={group} transaction={transaction} />

                    <TransactionCreditorShare
                        group={group}
                        transaction={transaction}
                        isEditing={transaction.is_wip}
                        label="From"
                    />

                    <TransactionDebitorShare
                        group={group}
                        transaction={transaction}
                        isEditing={transaction.is_wip}
                        label="To"
                    />
                </Grid>

                {(transaction.is_wip || transaction.files.length > 0) && (
                    <Grid item xs={6}>
                        <FileGallery transaction={transaction} />
                    </Grid>
                )}
            </Grid>
        </MobilePaper>
    );
}
Example #4
Source File: RewindApp.tsx    From rewind with MIT License 6 votes vote down vote up
function NormalView() {
  const { status } = useAppSelector((state) => state.backend);

  if (status !== "READY") {
    return <div>You should not be here</div>;
  }
  return (
    <Stack direction={"row"} sx={{ height: "100vh" }}>
      <LeftMenuSidebar />
      <Divider orientation={"vertical"} />
      <Box sx={{ flexGrow: 1, height: "100%" }}>
        <Switch>
          <Route exact path={"/home"} render={() => <HomeScreen />} />
          <Route exact path={"/analyzer"} render={() => <ConnectedAnalyzer />} />
        </Switch>
      </Box>
    </Stack>
  );
}
Example #5
Source File: AddToQueue.tsx    From multi-downloader-nx with MIT License 6 votes vote down vote up
AddToQueue: React.FC = () => {
  const [isOpen, setOpen] = React.useState(false);

  return <Box>
    <EpisodeListing />
    <Dialog open={isOpen} onClose={() => setOpen(false)} maxWidth='md'>
      <Box sx={{ border: '2px solid white', p: 2 }}>
        <SearchBox />
        <Divider variant='middle' className="divider-width" light sx={{ color: 'text.primary', fontSize: '1.2rem' }}>Options</Divider>
        <DownloadSelector onFinish={() => setOpen(false)} />
      </Box>
    </Dialog>
    <Button variant='contained' onClick={() => setOpen(true)}>
      <Add />
    </Button>
  </Box>
}
Example #6
Source File: ArtifactSlotDropdown.tsx    From genshin-optimizer with MIT License 6 votes vote down vote up
export default function ArtifactSlotDropdown({ slotKey = "", onChange, hasUnselect = false, ...props }: ArtifactSlotDropdownProps) {
  const { t } = useTranslation(["artifact", "ui"]);
  return <DropdownButton
    title={slotKey ? t(`artifact:slotName:${slotKey}`) : t('artifact:slot')}
    color={slotKey ? "success" : "primary"}
    startIcon={slotKey ? artifactSlotIcon(slotKey) : undefined}
    {...props}
  >
    {hasUnselect && <MenuItem selected={slotKey === ""} disabled={slotKey === ""} onClick={() => onChange("")} >
      <ListItemIcon>
        <Replay />
      </ListItemIcon>
      <ListItemText>
        {t`ui:unselect`}
      </ListItemText>
    </MenuItem>}
    {hasUnselect && <Divider />}
    {allSlotKeys.map(key =>
      <MenuItem key={key} selected={slotKey === key} disabled={slotKey === key} onClick={() => onChange(key)} >
        <ListItemIcon>
          {artifactSlotIcon(key)}
        </ListItemIcon>
        <ListItemText>
          {t(`artifact:slotName:${key}`)}
        </ListItemText>
      </MenuItem>)}
  </DropdownButton>
}
Example #7
Source File: hitComps.tsx    From usehooks-ts with MIT License 6 votes vote down vote up
HitElement: ComponentType<{ hit: Hit<BasicDoc> }> = ({ hit }) => (
  <ListItem
    button
    component={GatsbyLink}
    to={hit.path}
    className={classes.hit}
    key={hit.objectID}
  >
    <Typography className={classes.title} variant="h6" component="span">
      <Highlight attribute="title" hit={hit} />
      ()
    </Typography>
    <Typography variant="body2" color="textSecondary" component="span">
      <Highlight attribute="excerpt" hit={hit} />
    </Typography>
    <Divider />
  </ListItem>
)
Example #8
Source File: PageOptionsPanel.tsx    From mui-toolpad with MIT License 6 votes vote down vote up
export default function PageOptionsPanel() {
  const state = usePageEditorState();
  const pageNodeId = state.nodeId;
  const dom = useDom();

  const page = appDom.getNode(dom, pageNodeId, 'page');

  return (
    <div>
      <Stack spacing={1} alignItems="start">
        <Typography variant="subtitle1">Page:</Typography>
        <NodeNameEditor node={page} />
        <Button
          startIcon={<PageIcon />}
          color="inherit"
          component="a"
          href={`/app/${state.appId}/preview/pages/${pageNodeId}`}
        >
          Preview
        </Button>
        <Divider variant="middle" sx={{ alignSelf: 'stretch' }} />
        <Typography variant="subtitle1">Page State:</Typography>
        <UrlQueryEditor pageNodeId={pageNodeId} />
        <QueryStateEditor />
        <QueryEditor />
      </Stack>
    </div>
  );
}
Example #9
Source File: Config.tsx    From NekoMaid with MIT License 6 votes vote down vote up
Config: React.FC = () => {
  return <Box sx={{ minHeight: '100%', py: 3 }}>
    <Toolbar />
    <Container maxWidth={false}>
      <Grid container spacing={3}>
        {configs.map((it, i) => <Grid key={i} item lg={4} md={12} xl={6} xs={12}>
          <Card>
            <CardHeader title={it.title} />
            <Divider />
            <it.component />
          </Card>
        </Grid>)}
      </Grid>
    </Container>
  </Box>
}
Example #10
Source File: DetailsModal.tsx    From frontend with MIT License 6 votes vote down vote up
export default function DetailsModal({ campaign, onClose }: Props) {
  const { t } = useTranslation()

  return (
    <Dialog open scroll="body" onClose={onClose}>
      <DialogTitle>{t('Детайли на кампанията')}</DialogTitle>
      <Card>
        <Divider />
        <CardContent sx={{ p: 3 }}>
          <Typography variant="body1">
            {t('Заглавие')}: {campaign.title}
          </Typography>
          <Typography variant="body1">Слъг: {campaign.slug}</Typography>
          <Typography variant="body1">Целева сума: {campaign.targetAmount}</Typography>
          <Typography variant="body1">Стартова дата: {campaign.startDate}</Typography>
          <Typography variant="body1">Крайна Дата: {campaign.endDate}</Typography>
          <Typography variant="body1">Същество: {campaign.essence}</Typography>
          <Typography variant="body1">Тип на кампанията: {campaign.campaignTypeId}</Typography>
          <Typography variant="body1">Бенефициент: {campaign.beneficiaryId}</Typography>
          <Typography variant="body1">Кординатор: {campaign.coordinatorId}</Typography>
          <Typography variant="body1">Валута: {campaign.currency}</Typography>
          <Typography variant="body1">
            Описание: {campaign.description}
            {campaign.description}
            {campaign.description}
            {campaign.description}
          </Typography>
        </CardContent>
      </Card>
      <DialogActions>
        <Button variant="contained" onClick={onClose}>
          Затвори
        </Button>
      </DialogActions>
    </Dialog>
  )
}
Example #11
Source File: AppNavbar.tsx    From sapio-studio with Mozilla Public License 2.0 6 votes vote down vote up
export function AppNavbar(props: {
    relayout: () => void;
    contract: ContractModel;
    bitcoin_node_manager: BitcoinNodeManager;
}): JSX.Element {
    const dispatch = useDispatch();

    return (
        <Paper className="AppNavBar" square={true}>
            <List sx={{ textAlign: 'center' }}>
                <MainScreens></MainScreens>
            </List>
            <Divider />
            <List>
                <ContractMenu relayout={props.relayout} />
                <NodeMenu bitcoin_node_manager={props.bitcoin_node_manager} />
                <Simulator />
            </List>
            <Divider />
            <List>
                <SettingsMenuItem />
            </List>
            <Divider />
        </Paper>
    );
}
Example #12
Source File: ArrayOneOfPreview.tsx    From firecms with MIT License 5 votes vote down vote up
/**
 * @category Preview components
 */
export function ArrayOneOfPreview({
                                      name,
                                      value,
                                      property,
                                      size
                                  }: PreviewComponentProps<any[]>) {

    if (property.dataType !== "array")
        throw Error("Picked wrong preview component ArrayPreview");

    if (!property.oneOf) {
        throw Error(`You need to specify an 'of' or 'oneOf' prop (or specify a custom field) in your array property ${name}`);
    }

    const classes = useStyles();
    const values = value;

    if (!values) return null;

    const childSize: PreviewSize = size === "regular" ? "small" : "tiny";

    const typeField = property.oneOf.typeField ?? "type";
    const valueField = property.oneOf.valueField ?? "value";
    const properties = property.oneOf.properties;

    return (
        <div className={classes.array}>
            {values &&
            values.map((value, index) =>
                <React.Fragment key={"preview_array_" + value + "_" + index}>
                    <div className={classes.arrayItemBig}>
                        <ErrorBoundary>
                            {value && <PreviewComponent
                                name={name}
                                value={value[valueField]}
                                property={properties[value[typeField]] as Property<any>}
                                size={childSize}/>}
                        </ErrorBoundary>
                    </div>
                    {index < values.length - 1 && <Divider/>}
                </React.Fragment>
            )}
        </div>
    );
}
Example #13
Source File: GenerateCodePage.tsx    From GTAV-NativeDB with MIT License 5 votes vote down vote up
function GenerateCodePage() {
  const { language } = useParams<{ language: string }>()
  const history = useHistory()

  const onTabChange = useCallback((e: SyntheticEvent<Element, Event>, language: string) => {
    history.replace(language)
  }, [history])

  return (
    <Box sx={{ py: 2, overflow: 'hidden scroll', flexGrow: 1 }}>
      <Container maxWidth="lg">
        <Typography variant="h4" component="h1" gutterBottom>
          Generate Code
        </Typography>
        <Paper>
          <TabContext value={language}>
            <TabList onChange={onTabChange}>
              <Tab label="C++" value="cpp" />
              <Tab label="Rust" value="rs" />
              <Tab label="C# Enum" value="cs" />
              <Tab label="SHV.NET" value="shvdn" />
              <Tab label="RPH" value="rph" />
            </TabList>
            <Divider />
            <TabPanel value="cpp">
              <CPlusPlus />
            </TabPanel>
            <TabPanel value="rs">
              <Rust />
            </TabPanel>
            <TabPanel value="cs">
              <CSharpEnum />
            </TabPanel>
            <TabPanel value="shvdn">
              Soon&trade;
            </TabPanel>
            <TabPanel value="rph">
              Soon&trade;
            </TabPanel>
          </TabContext>
        </Paper>
      </Container>
    </Box>
  )
}
Example #14
Source File: index.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
SupportView: FunctionComponent = () => {
  return (
    <MainLayout>
      <Card>
        <CardTitle icon={<SettingsIcon />} title="Support" />
        <Divider />
        <CardContent sx={styles.listContainer}>
          <p>Need help? Confused? Join the Community!</p>
          <ul className="linksList">
            <li>
              <Button
                target="_blank"
                variant="contained"
                rel="noreferrer noreferrer"
                href="https://www.expresslrs.org/"
              >
                ExpressLRS Documentation
              </Button>
            </li>
            <li>
              <Button
                target="_blank"
                variant="contained"
                rel="noreferrer noreferrer"
                href="https://discord.gg/dS6ReFY"
              >
                Discord Chat
              </Button>
            </li>
            <li>
              <Button
                target="_blank"
                variant="contained"
                rel="noreferrer noreferrer"
                href="https://www.facebook.com/groups/636441730280366"
              >
                Facebook Group
              </Button>
            </li>
          </ul>
        </CardContent>
        <Divider />
        <CardTitle icon={<SettingsIcon />} title="Troubleshooting" />
        <Divider />
        <CardContent>
          <ClearPlatformioDependencies />
          <ClearFirmwareFiles />
        </CardContent>
        <Divider />
        <CardTitle icon={<SettingsIcon />} title="Legal disclaimer" />
        <Divider />
        <CardContent>
          <p>
            The use and operation of this type of device may require a license,
            and some countries may forbid its use. It is entirely up to the end
            user to ensure compliance with local regulations. This is
            experimental software / hardware and there is no guarantee of
            stability or reliability. USE AT YOUR OWN RISK.
          </p>
        </CardContent>
      </Card>
    </MainLayout>
  );
}
Example #15
Source File: TransactionListEntry.tsx    From abrechnung with GNU Affero General Public License v3.0 5 votes vote down vote up
export function TransactionListEntry({ group, transaction }) {
    const accounts = useRecoilValue(accountsSeenByUser(group.id));
    const accountNamesFromShares = (shares) => {
        return shares.map((s) => accounts.find((a) => a.id === parseInt(s))?.name).join(", ");
    };

    return (
        <>
            <ListItemLink to={`/groups/${group.id}/transactions/${transaction.id}`}>
                <ListItemAvatar sx={{ minWidth: { xs: "40px", md: "56px" } }}>
                    {transaction.type === "purchase" ? (
                        <Tooltip title="Purchase">
                            <PurchaseIcon color="primary" />
                        </Tooltip>
                    ) : transaction.type === "transfer" ? (
                        <Tooltip title="Money Transfer">
                            <TransferIcon color="primary" />
                        </Tooltip>
                    ) : (
                        <Tooltip title="Unknown Transaction Type">
                            <HelpOutline color="primary" />
                        </Tooltip>
                    )}
                </ListItemAvatar>
                <ListItemText
                    primary={
                        <>
                            {transaction.is_wip && (
                                <Chip color="info" variant="outlined" label="WIP" size="small" sx={{ mr: 1 }} />
                            )}
                            <Typography variant="body1" component="span">
                                {transaction.description}
                            </Typography>
                        </>
                    }
                    secondary={
                        <>
                            <Typography variant="body2" component="span" sx={{ color: "text.primary" }}>
                                by {accountNamesFromShares(Object.keys(transaction.creditor_shares))}, for{" "}
                                {accountNamesFromShares(Object.keys(transaction.debitor_shares))}
                            </Typography>
                            <br />
                            {DateTime.fromISO(transaction.billed_at).toLocaleString(DateTime.DATE_FULL)}
                        </>
                    }
                />
                <ListItemText>
                    <Typography align="right" variant="body2">
                        {transaction.value.toFixed(2)} {transaction.currency_symbol}
                        <br />
                        <Typography component="span" sx={{ typography: "body2", color: "text.secondary" }}>
                            last changed:{" "}
                            {DateTime.fromISO(transaction.last_changed).toLocaleString(DateTime.DATETIME_FULL)}
                        </Typography>
                    </Typography>
                </ListItemText>
            </ListItemLink>
            <Divider sx={{ display: { lg: "none" } }} component="li" />
        </>
    );
}
Example #16
Source File: LeftMenuSidebar.tsx    From rewind with MIT License 5 votes vote down vote up
export function LeftMenuSidebar() {
  // const LinkBehavior = React.forwardRef((props, ref) => <Link ref={ref} to="/" {...props} role={undefined} />);
  const dispatch = useAppDispatch();
  const pathname = useAppSelector((state) => state.router.location.pathname);

  const handleLinkClick = (to: string) => () => dispatch(push(to));
  const buttonColor = (name: string) => (name === pathname ? "primary" : "default");
  const updateState = useCheckForUpdate();

  return (
    <Stack
      sx={{
        width: (theme) => theme.spacing(10),
        paddingBottom: 2,
      }}
      gap={1}
      p={1}
      alignItems={"center"}
      component={"nav"}
    >
      <Box onClick={handleLinkClick("/home")} sx={{ cursor: "pointer" }}>
        <RewindLogo />
      </Box>
      <Divider orientation={"horizontal"} sx={{ borderWidth: 1, width: "80%" }} />
      <Tooltip title={"Overview"} placement={"right"}>
        <IconButton color={buttonColor("/home")} onClick={handleLinkClick("/home")}>
          <Home />
        </IconButton>
      </Tooltip>
      <Tooltip title={"Analyzer"} placement={"right"}>
        <IconButton
          // These are not centered
          onClick={handleLinkClick("/analyzer")}
          color={buttonColor("/analyzer")}
        >
          <FaMicroscope height={"0.75em"} />
        </IconButton>
      </Tooltip>
      {/*Nothing*/}
      <Box flexGrow={1} />
      {updateState.hasNewUpdate && (
        <Tooltip title={`New version ${updateState.latestVersion} available!`} placement={"right"}>
          <IconButton onClick={() => window.open(latestReleaseUrl)}>
            <Badge variant={"dot"} color={"error"}>
              <UpdateIcon />
            </Badge>
          </IconButton>
        </Tooltip>
      )}
    </Stack>
  );
}
Example #17
Source File: ContextMenu.tsx    From multi-downloader-nx with MIT License 5 votes vote down vote up
function ContextMenu<T extends HTMLElement, >(props: ContextMenuProps<T>) {
  const [anchor, setAnchor] = React.useState( { x: 0, y: 0 } );
  
  const [show, setShow] = React.useState(false);

  React.useEffect(() => {
    const { popupItem: ref } = props;
    if (ref.current === null)
      return;
    const listener = (ev: MouseEvent) => {
      ev.preventDefault();
      setAnchor({ x: ev.x + 10, y: ev.y + 10 });
      setShow(true);
    }
    ref.current.addEventListener('contextmenu', listener);

    return () => { 
      if (ref.current)
        ref.current.removeEventListener('contextmenu', listener)
    };
  }, [ props.popupItem ])

  return show ? <Box sx={{ zIndex: 9999, p: 1, background: 'rgba(0, 0, 0, 0.75)', backdropFilter: 'blur(5px)', position: 'fixed', left: anchor.x, top: anchor.y }}>
    <List sx={{ p: 0, m: 0 }}>
      {props.options.map((item, i) => {
        return item === 'divider' ? <Divider key={`ContextMenu_Divider_${i}_${item}`}/> : 
        <Button color='inherit' key={`ContextMenu_Value_${i}_${item}`} onClick={() => {
          item.onClick();
          setShow(false);
        }} sx={buttonSx}>
          {item.text}
        </Button>
      })}
      <Divider />
      <Button fullWidth color='inherit' onClick={() => setShow(false)} sx={buttonSx} >
        Close
      </Button>
    </List>
  </Box> : <></>
}
Example #18
Source File: Facet.tsx    From cli with Apache License 2.0 5 votes vote down vote up
FacetRenderer: FunctionComponent<FacetRendererProps> = (props) => {
  const {controller} = props;
  const [state, setState] = useState(controller.state);

  useEffect(
    () => controller.subscribe(() => setState(controller.state)),
    [controller]
  );

  const toggleSelect = (value: FacetValue) => {
    controller.toggleSelect(value);
  };

  const showMore = () => {
    controller.showMoreValues();
  };

  const showLess = () => {
    controller.showLessValues();
  };

  return (
    <Box mb={5} mr={3} p={1}>
      <Box pb={1}>
        <Typography variant="h6" component="h6">
          {props.title}
        </Typography>
      </Box>
      <Divider />
      <List dense>
        {state.values.map((value: FacetValue) => {
          const labelId = `checkbox-list-label-${value}`;

          return (
            <ListItem
              style={{padding: 0}}
              key={value.value}
              role={undefined}
              button
              onClick={() => toggleSelect(value)}
            >
              <Checkbox
                size="small"
                edge="start"
                checked={controller.isValueSelected(value)}
                tabIndex={-1}
                disableRipple
                inputProps={{'aria-labelledby': labelId}}
              />
              <ListItemText
                className="truncate inline"
                primary={`${value.value}`}
                secondary={`(${value.numberOfResults})`}
              />
            </ListItem>
          );
        })}
      </List>
      {state.canShowLessValues && (
        <Button size="small" onClick={() => showLess()}>
          Show Less
        </Button>
      )}
      {state.canShowMoreValues && (
        <Button size="small" onClick={() => showMore()}>
          Show More
        </Button>
      )}
    </Box>
  );
}
Example #19
Source File: CharacterSelectionModal.tsx    From genshin-optimizer with MIT License 5 votes vote down vote up
export function CharacterSelectionModal({ show, onHide, onSelect, filter = () => true, newFirst = false }: CharacterSelectionModalProps) {
  const sortKeys = useMemo(() => newFirst ? ["new", ...defaultSortKeys] : defaultSortKeys, [newFirst])
  const { database } = useContext(DatabaseContext)
  const { t } = useTranslation("page_character")

  const [sortBy, setsortBy] = useState(sortKeys[0])
  const [ascending, setascending] = useState(false)
  const [elementalFilter, setelementalFilter] = useState<ElementKey | "">("")
  const [weaponFilter, setweaponFilter] = useState<WeaponTypeKey | "">("")

  const characterSheets = usePromise(CharacterSheet.getAll, [])

  const [favesDirty, setFavesDirty] = useForceUpdate()
  useEffect(() => database.followAnyChar(setFavesDirty), [database, setFavesDirty])

  const [searchTerm, setSearchTerm] = useState("")
  const deferredSearchTerm = useDeferredValue(searchTerm)

  const sortConfigs = useMemo(() => characterSheets && characterSortConfigs(database, characterSheets), [database, characterSheets])
  const filterConfigs = useMemo(() => characterSheets && favesDirty && characterFilterConfigs(database, characterSheets), [favesDirty, database, characterSheets])
  const ownedCharacterKeyList = useMemo(() => characterSheets ? allCharacterKeys.filter(cKey => filter(database._getChar(cKey), characterSheets[cKey])) : [], [database, characterSheets, filter])
  const characterKeyList = useMemo(() => (characterSheets && sortConfigs && filterConfigs) ?
    ownedCharacterKeyList
      .filter(filterFunction({ element: elementalFilter, weaponType: weaponFilter, favorite: "yes", name: deferredSearchTerm }, filterConfigs))
      .sort(sortFunction(sortBy, ascending, sortConfigs) as (a: CharacterKey, b: CharacterKey) => number)
      .concat(
        ownedCharacterKeyList
          .filter(filterFunction({ element: elementalFilter, weaponType: weaponFilter, favorite: "no", name: deferredSearchTerm }, filterConfigs))
          .sort(sortFunction(sortBy, ascending, sortConfigs) as (a: CharacterKey, b: CharacterKey) => number)
      )
    : [],
    [characterSheets, elementalFilter, weaponFilter, sortBy, ascending, sortConfigs, filterConfigs, ownedCharacterKeyList, deferredSearchTerm])

  if (!characterSheets) return null
  return <ModalWrapper open={show} onClose={onHide} sx={{ "& .MuiContainer-root": { justifyContent: "normal" } }}>
    <CardDark>
      <CardContent sx={{ py: 1 }}>
        <Grid container spacing={1} >
          <Grid item>
            <WeaponToggle sx={{ height: "100%" }} onChange={setweaponFilter} value={weaponFilter} size="small" />
          </Grid>
          <Grid item>
            <ElementToggle sx={{ height: "100%" }} onChange={setelementalFilter} value={elementalFilter} size="small" />
          </Grid>
          <Grid item>
            <TextField
              autoFocus
              value={searchTerm}
              onChange={(e: ChangeEvent<HTMLTextAreaElement>) => setSearchTerm(e.target.value)}
              label={t("characterName")}
            />
          </Grid>

          <Grid item flexGrow={1} />

          <Grid item >
            <SortByButton sx={{ height: "100%" }}
              sortKeys={sortKeys} value={sortBy} onChange={setsortBy as any}
              ascending={ascending} onChangeAsc={setascending} />
          </Grid>
          <Grid item>
            <CloseButton onClick={onHide} />
          </Grid>
        </Grid>
      </CardContent>
      <Divider />
      <CardContent><Grid container spacing={1}>
        {characterKeyList.map(characterKey => <Grid item key={characterKey} xs={6} md={4} lg={3} >
          <CharacterBtn key={characterKey} characterKey={characterKey} characterSheet={characterSheets[characterKey]} onClick={() => { onHide(); onSelect?.(characterKey) }} />
        </Grid>)}
      </Grid></CardContent>
    </CardDark>
  </ModalWrapper>
}
Example #20
Source File: TLSCertificate.tsx    From console with GNU Affero General Public License v3.0 5 votes vote down vote up
TLSCertificate = ({
  classes,
  certificateInfo,
  onDelete = () => {},
}: ITLSCertificate) => {
  const certificates = certificateInfo.domains || [];
  return (
    <Chip
      key={certificateInfo.name}
      variant="outlined"
      color="primary"
      className={classes.certificateWrapper}
      label={
        <Container>
          <Grid item xs={1} className={classes.certificateIcon}>
            <CertificateIcon />
          </Grid>
          <Grid item xs={11} className={classes.certificateInfo}>
            <Typography variant="subtitle1" display="block" gutterBottom>
              {certificateInfo.name}
            </Typography>
            <Box className={classes.certificateExpiry}>
              <EventBusyIcon color="inherit" fontSize="small" />
              &nbsp;
              <span className={"label"}>Expiry:&nbsp;</span>
              <span>
                <Moment format="YYYY/MM/DD">{certificateInfo.expiry}</Moment>
              </span>
            </Box>
            <Divider />
            <br />
            <Box className={classes.certificateDomains}>
              <span className="label">{`${certificates.length} Domain (s):`}</span>
            </Box>
            <List className={classes.certificatesList}>
              {certificates.map((dom) => (
                <ListItem className={classes.certificatesListItem}>
                  <ListItemAvatar>
                    <LanguageIcon />
                  </ListItemAvatar>
                  <ListItemText primary={dom} />
                </ListItem>
              ))}
            </List>
          </Grid>
        </Container>
      }
      onDelete={onDelete}
    />
  );
}
Example #21
Source File: Dashboard.tsx    From NekoMaid with MIT License 5 votes vote down vote up
Players: React.FC<{ players?: CurrentStatus['players'] }> = React.memo(({ players }) => {
  const his = useHistory()
  const plugin = usePlugin()
  const globalData = useGlobalData()
  const [page, setPage] = useState(1)
  const [id, update] = useState(0)
  return <Card>
    <CardHeader title={lang.dashboard.onlinePlayers} />
    <Divider />
    <CardContent>
      {players?.length === 0
        ? <Empty />
        : <>
        <List sx={{ paddingTop: 0 }}>
          {players
            ? players.slice((page - 1) * 8, page * 8).map(p => {
              const name = typeof p === 'string' ? p : p.name
              return <Tooltip key={name} title={'IP: ' + ((p as any).ip || lang.unknown)}>
                <ListItem
                  secondaryAction={<>
                    <IconButton
                      edge='end'
                      size='small'
                      onClick={() => dialog(lang.dashboard.confirmKick(<span className='bold'>{name}</span>), lang.reason)
                        .then(it => it != null && plugin.emit('dashboard:kick', (res: boolean) => {
                          action(res)
                          if (!players) return
                          players.splice(players.indexOf(it!), 1)
                          update(id + 1)
                        }, name, it || null))
                      }
                    ><ExitToApp /></IconButton>
                    <IconButton edge='end' onClick={() => his.push('/NekoMaid/playerList/' + name)} size='small'><MoreHoriz /></IconButton>
                  </>
                  }
                >
                  <ListItemAvatar>
                    <Avatar
                      src={getSkin(globalData, name, true)}
                      imgProps={{ crossOrigin: 'anonymous', onClick () { his.push('/NekoMaid/playerList/' + name) }, style: { width: 40, height: 40 } }}
                      sx={{ cursor: 'pointer' }}
                      variant='rounded'
                    />
                  </ListItemAvatar>
                  <ListItemText primary={name} />
                </ListItem>
              </Tooltip>
            })
            : <LoadingList />
          }
        </List>
        {players && <Pagination
          page={page}
          onChange={(_, it) => setPage(it)}
          count={Math.max(Math.ceil(players.length / 8), 1)}
          sx={{ display: 'flex', justifyContent: 'flex-end' }}
        />}
      </>}
    </CardContent>
  </Card>
})
Example #22
Source File: Roles.tsx    From frontend with MIT License 5 votes vote down vote up
export default function Roles() {
  const [, { error }] = useField('roles')
  const { t } = useTranslation()

  return (
    <Grid container spacing={6} justifyContent="center">
      <Grid item xs={12} md={8}>
        <HeaderTypography>{t('support:steps.role.subtitle')}</HeaderTypography>
      </Grid>
      <Grid item xs={12} md={8}>
        <Typography variant="h5" paragraph>
          {t('support:steps.role.first-subtitle')}
        </Typography>
        <Divider />
        <div>
          <BankTransfer />
        </div>
      </Grid>
      <Grid item xs={12} md={8}>
        <Typography variant="h5" paragraph>
          {t('support:steps.role.second-subtitle')}
        </Typography>
        <Divider />
        <FormControl fullWidth required error={!!error} component="fieldset">
          <FormGroup>
            <Role name="roles.benefactor" label={t('support:steps.role.fields.benefactor.title')} />
            <Role label={t('support:steps.role.fields.volunteer.title')} name="roles.volunteer" />
            <Role
              label={t('support:steps.role.fields.associationMember.title')}
              name="roles.associationMember"
            />
            <Role label={t('support:steps.role.fields.partner.title')} name="roles.partner" />
            <Role label={t('support:steps.role.fields.company.title')} name="roles.company" />
          </FormGroup>
          {error && <FormHelperText>{t('validation:select-role')}</FormHelperText>}
        </FormControl>
      </Grid>
    </Grid>
  )
}
Example #23
Source File: AppNavbar.tsx    From sapio-studio with Mozilla Public License 2.0 5 votes vote down vote up
function NodeMenu(props: { bitcoin_node_manager: BitcoinNodeManager }) {
    const dispatch = useDispatch();
    const nodeRef = React.useRef<HTMLLIElement>(null);
    const [node_open, setNodeOpen] = React.useState(false);
    const close = () => setNodeOpen(false);

    return (
        <>
            <ListItem
                disableGutters
                button={false}
                key={'Bitcoin Node'}
                onClick={() => setNodeOpen(true)}
                ref={nodeRef}
            >
                <ListItemIcon></ListItemIcon>
                <ListItemText primary={'Bitcoin Node'} />
            </ListItem>
            <Menu
                anchorEl={nodeRef.current}
                anchorOrigin={{
                    vertical: 'center',
                    horizontal: 'right',
                }}
                keepMounted
                open={node_open}
                onClose={close}
            >
                <MenuItem
                    onClick={async () => {
                        close();
                        const addr =
                            await props.bitcoin_node_manager.get_new_address();
                        window.electron.write_clipboard(addr);
                    }}
                >
                    Get New Address to Clipboard
                </MenuItem>
                <MenuItem
                    onClick={() => {
                        close();
                        props.bitcoin_node_manager
                            .generate_blocks(10)
                            .catch((err) => console.error(err));
                    }}
                >
                    Generate 10 Blocks
                </MenuItem>
                <Divider />
                <MenuItem
                    onClick={() => {
                        close();
                        dispatch(toggle_status_bar());
                    }}
                >
                    Toggle Status
                </MenuItem>
            </Menu>
        </>
    );
}
Example #24
Source File: Drawer.tsx    From firecms with MIT License 4 votes vote down vote up
/**
 * Default drawer used in the CMS
 * @category Core
 */
export function Drawer({
                           logo,
                           closeDrawer
                       }: DrawerProps) {

    const classes = useStyles();

    const navigationContext = useNavigation();

    const {
        navigationEntries,
        groups
    }: TopNavigationResult = useMemo(() => computeTopNavigation(navigationContext, false), [navigationContext]);

    const ungroupedNavigationViews = Object.values(navigationEntries).filter(e => !e.group);

    const createNavigationListItem = useCallback((index: number, group: string, entry: TopNavigationEntry) =>
        <ListItem
            // @ts-ignore
            button
            key={`navigation_${index}`}
            component={NavLink}
            onClick={closeDrawer}
            // @ts-ignore
            style={({ isActive }) => ({
                fontWeight: isActive ? "600" : "500",
                background: isActive ? "rgba(128,128,128,0.1)" : "inherit"
            })}
            to={entry.url}
        >
            <Typography
                variant={"subtitle2"}
                sx={{
                    fontWeight: "inherit",
                    py: 0.5
                }}>
                {entry.name.toUpperCase()}
            </Typography>
        </ListItem>, [closeDrawer]);

    let logoComponent;
    if (logo) {
        logoComponent = <img className={classes.logo}
                             src={logo}
                             alt={"Logo"}/>;
    } else {
        logoComponent = <div className={classes.logo}>
            <FireCMSLogo/>
        </div>;
    }

    return <>

        <Link
            key={"breadcrumb-home"}
            color="inherit"
            onClick={closeDrawer}
            component={NavLink}

            to={navigationContext.homeUrl}>
            {logoComponent}
        </Link>

        <List>

            {groups.map((group) => (
                <React.Fragment
                    key={`drawer_group_${group}`}>
                    <Divider key={`divider_${group}`}/>
                    <Box pt={2} pl={2} pr={2} pb={0.5}>
                        <Typography variant={"caption"}
                                    color={"textSecondary"}
                                    className={"weight-500"}>
                            {group.toUpperCase()}
                        </Typography>
                    </Box>
                    {Object.values(navigationEntries)
                        .filter(e => e.group === group)
                        .map((view, index) => createNavigationListItem(index, group, view))}
                </React.Fragment>
            ))}

            {ungroupedNavigationViews.length > 0 &&
            <Divider key={"divider_ungrouped"}/>}

            {ungroupedNavigationViews.map((view, index) => createNavigationListItem(index, "none", view))}

        </List>

    </>;
}
Example #25
Source File: Filter.tsx    From Cromwell with MIT License 4 votes vote down vote up
render() {
    const { instanceSettings } = this.props;
    const { pluginSettings } = this.props.data ?? {};
    const { attributes, productCategory } = this.initialData ?? {};
    const { isMobileOpen, minPrice, maxPrice, collapsedItems, isLoading } = this.state;
    instanceSettings?.getInstance?.(this);

    if (isLoading) return (
      <div style={{ width: '100%', height: '100px' }}>
        <LoadBox size={60} />
      </div>
    );

    const isMobile = !instanceSettings?.disableMobile && this.props.isMobile;
    const pcCollapsedByDefault = pluginSettings?.collapsedByDefault ?? defaultSettings.collapsedByDefault
    const mobileCollapsedByDefault = pluginSettings?.mobileCollapsedByDefault ?? defaultSettings.mobileCollapsedByDefault;
    const _collapsedByDefault = isMobile ? mobileCollapsedByDefault : pcCollapsedByDefault;
    const productListId = instanceSettings?.listId ?? pluginSettings?.listId;

    if (this.collapsedByDefault !== _collapsedByDefault) {
      this.collapsedByDefault = _collapsedByDefault;
      this.setState({ collapsedItems: {} });
    }

    setListProps(productListId, productCategory, this.client, this.getFilterParams(), this.updateFilterMeta);

    const filterContent = (
      <div>
        {isMobile && (
          <div className="productFilter_mobileHeader">
            <p>Filter</p>
            <IconButton
              aria-label="Close filter"
              className="productFilter_mobileCloseBtn"
              onClick={this.handleMobileClose}>
              <CloseIcon />
            </IconButton>
          </div>
        )}
        {this.getFilterItem({
          title: 'Search',
          key: 'search',
          content: (
            <TextField
              style={{
                padding: '0 15px 15px 15px',
                width: '100%',
              }}
              placeholder="type to search..."
              variant="standard"
              onChange={e => this.onSearchChange(e.target.value)}
            />
          )
        })}
        {productCategory &&
          !!(productCategory.parent || productCategory.children?.length) &&
          this.getFilterItem({
            title: 'Categories',
            key: 'categories',
            content: (
              <div className={clsx('productFilter_categoryBox',
                'productFilter_styledScrollBar',
                'productFilter_list')}>
                {productCategory.parent && (
                  <Chip className="productFilter_category"
                    label={productCategory.parent.name}
                    onClick={this.handleCategoryClick(productCategory.parent)} />
                )}
                {productCategory && (
                  <Chip className="productFilter_category"
                    variant="outlined"
                    disabled
                    style={{ marginLeft: productCategory.parent ? '15px' : '' }}
                    label={productCategory.name}
                    onClick={this.handleCategoryClick(productCategory)} />
                )}
                {!!productCategory.children?.length && (
                  <>
                    {productCategory.children.map(child => (
                      <Chip key={child.id}
                        className="productFilter_category"
                        style={{ marginLeft: ((productCategory?.parent ? 15 : 0) + 15) + 'px' }}
                        label={child.name}
                        onClick={this.handleCategoryClick(child)} />
                    ))}
                  </>
                )}
              </div>
            )
          })}
        {this.getFilterItem({
          title: 'Price',
          key: 'price',
          content: (
            <Slider
              onChange={this.onPriceRangeChange}
              minPrice={minPrice}
              maxPrice={maxPrice}
            />
          )
        })}
        {attributes && (
          attributes.map(attr => {
            if (!attr.key || !attr.values) return null;
            const checked: string[] | undefined = this.checkedAttrs[attr.key];
            const numberOfChecked = () => checked ? checked.length : 0;
            const handleToggleAll = () => {
              if (attr.key && attr.values && attr.values?.length !== 0) {
                if (numberOfChecked() === attr.values?.length) {
                  this.handleSetAttribute(attr.key, [])
                } else {
                  this.handleSetAttribute(attr.key, attr.values.map(v => v.value))
                }
              }
            }
            if (collapsedItems[attr.key] === undefined) {
              collapsedItems[attr.key] = this.collapsedByDefault;
            }
            const isExpanded = !collapsedItems[attr.key];
            return (
              <Card key={attr.key} className="productFilter_card">
                <div className="productFilter_headerWrapper">
                  <CardHeader
                    className="productFilter_cardHeader"
                    avatar={
                      <Checkbox
                        color="primary"
                        onClick={handleToggleAll}
                        checked={numberOfChecked() === attr.values.length && attr.values.length !== 0}
                        indeterminate={numberOfChecked() !== attr.values.length && numberOfChecked() !== 0}
                        disabled={attr.values.length === 0}
                        inputProps={{ 'aria-label': 'all items selected' }}
                      />
                    }
                    title={attr.key}
                    subheader={`${numberOfChecked()}/${attr.values.length} selected`}
                  />
                  <IconButton
                    onClick={() => this.setState(prev => ({
                      collapsedItems: {
                        ...prev.collapsedItems,
                        [attr.key!]: !prev.collapsedItems[attr.key!]
                      }
                    }))}
                    className={clsx('productFilter_expand', {
                      'productFilter_expandOpen': isExpanded,
                    })}
                    aria-label="Toggle filter visibility"
                    aria-expanded={isExpanded}
                  >
                    <ExpandMoreIcon />
                  </IconButton>
                </div>
                <Collapse in={isExpanded} timeout="auto" unmountOnExit>
                  <Divider />
                  <List className={clsx('productFilter_list', 'productFilter_styledScrollBar')} dense component="div" role="list">
                    {attr.values.map((attrValue: TAttributeValue) => {
                      const value = attrValue.value
                      const labelId = `attribute-list-${attr.key}-${value}-label`;
                      return (
                        <ListItem key={value} role="listitem" button
                          onClick={() => {
                            const newChecked = checked ? [...checked] : [];
                            const currentIndex = newChecked.indexOf(value);
                            if (currentIndex === -1) {
                              newChecked.push(value);
                            } else {
                              newChecked.splice(currentIndex, 1);
                            }
                            this.handleSetAttribute(attr.key!, newChecked);
                          }}>
                          <ListItemIcon>
                            <Checkbox
                              color="primary"
                              checked={checked ? checked.indexOf(value) !== -1 : false}
                              tabIndex={-1}
                              disableRipple
                              inputProps={{ 'aria-labelledby': labelId }}
                            />
                          </ListItemIcon>
                          {attrValue.icon && (
                            <div
                              style={{ backgroundImage: `url(${attrValue.icon}` }}
                              className="productFilter_attrValueIcon"></div>
                          )}
                          <ListItemText id={labelId} primary={value} />
                        </ListItem>
                      );
                    })}
                    <ListItem />
                  </List>
                </Collapse>
              </Card>
            )
          })
        )}
      </div>
    );

    if (isMobile) {
      const onOpen = () => {

      }
      const mobileIconPosition = pluginSettings?.mobileIconPosition ?? defaultSettings.mobileIconPosition;

      return (
        <div>
          <IconButton
            aria-label="Open product filter"
            className="productFilter_mobileOpenBtn"
            style={{
              top: mobileIconPosition.top + 'px',
              left: mobileIconPosition.left + 'px'
            }}
            onClick={this.handleMobileOpen}>
            <FilterListIcon />
          </IconButton>
          <SwipeableDrawer
            open={isMobileOpen}
            onClose={this.handleMobileClose}
            onOpen={onOpen}
            classes={{ paper: 'productFilter_styledScrollBar' }}
          >
            <div className="productFilter_drawer">
              {filterContent}
            </div>
          </SwipeableDrawer>
        </div>
      );
    }

    return filterContent;
  }
Example #26
Source File: Desktop.tsx    From GTAV-NativeDB with MIT License 4 votes vote down vote up
function Desktop({ ...rest }: AppBarProps) {
  const stats = useStats()
  const [settingsOpen, setSettingsOpen] = useState(false)
  const settings = useAppBarSettings()

  const handleSettingsOpen = useCallback(() => {
    setSettingsOpen(true)
  }, [setSettingsOpen])

  const handleSettingsClose = useCallback(() => {
    setSettingsOpen(false)
  }, [setSettingsOpen])

  const actions: AppBarActionProps[] = useMemo(() => [
    ...(settings.actions ?? []),
    {
      text: 'Settings',
      desktopIcon: SettingsIcon,
      buttonProps: {
        onClick: handleSettingsOpen
      }
    },
    {
      text: 'View on Github',
      desktopIcon: GithubIcon,
      buttonProps: {
        href: 'https://github.com/DottieDot/GTAV-NativeDB',
        target: '_blank'
      }
    }
  ], [settings, handleSettingsOpen])

  return (
    <Box {...rest}>
      <SettingsDrawer open={settingsOpen} onClose={handleSettingsClose} />
      <MaterialAppBar position="sticky">
        <Toolbar>
          <Typography variant="h6" component="div">
            <Link
              to="/natives"
              color="inherit"
              underline="none"
              component={RouterLink}
            >
              {settings?.title ?? 'GTA V Native Reference'}
            </Link>
          </Typography>
          <Box
            sx={{ display: 'flex', flex: 1 }}
          >
            {settings.search && <DesktopSearch search={settings.search} />}
          </Box>
          <StatusButton />
          {actions.map(action => (
            <AppBarAction
              key={action.text}
              {...action}
            />
          ))}
        </Toolbar>
        <Divider variant="fullWidth" />
        <Toolbar variant="dense">
          <Typography variant="subtitle1">
            Namespaces:&nbsp;{stats.namespaces}&nbsp;{'| '}
            Natives:&nbsp;{stats.natives}&nbsp;{'| '}
            Comments:&nbsp;{stats.comments}&nbsp;{'| '}
            Known names:&nbsp;{stats.knownNames.confirmed} ({stats.knownNames.total})&nbsp;{'| '}
            <Link
              to="/generate-code"
              color="inherit"
              underline="hover"
              component={RouterLink}
            >
              Generate&nbsp;code
            </Link>
          </Typography>
        </Toolbar>
      </MaterialAppBar>
    </Box>
  )
}
Example #27
Source File: index.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 4 votes vote down vote up
Sidebar: FunctionComponent = () => {
  const location = useLocation();
  const configuratorActive =
    matchPath(location.pathname, '/configurator') !== null;
  const backpackActive = matchPath(location.pathname, '/backpack') !== null;
  // const settingsActive = matchPath(location.pathname, '/settings') !== null;
  const logsActive = matchPath(location.pathname, '/logs') !== null;
  const serialMonitorActive =
    matchPath(location.pathname, '/serial-monitor') !== null;
  const supportActive = matchPath(location.pathname, '/support') !== null;
  const { appStatus } = useAppState();

  const navigationEnabled = appStatus !== AppStatus.Busy;

  return (
    <Drawer sx={styles.drawer} variant="permanent">
      <Toolbar />
      <Divider />
      <Box sx={styles.drawerContainer}>
        <List>
          <ListItem
            component={Link}
            to="/configurator"
            selected={configuratorActive}
            sx={styles.menuItem}
            button
            disabled={!navigationEnabled}
          >
            <ListItemIcon>
              <BuildIcon />
            </ListItemIcon>
            <ListItemText primary="Configurator" />
          </ListItem>
          <ListItem
            component={Link}
            to="/backpack"
            selected={backpackActive}
            sx={styles.menuItem}
            button
            disabled={!navigationEnabled}
          >
            <ListItemIcon>
              <BackpackIcon />
            </ListItemIcon>
            <ListItemText primary="Backpack" />
          </ListItem>

          {/* <ListItem */}
          {/*  component={Link} */}
          {/*  to="/settings" */}
          {/*  selected={settingsActive} */}
          {/*  sx={styles.menuItem} */}
          {/*  button */}
          {/* > */}
          {/*  <ListItemIcon> */}
          {/*    <SettingsIcon /> */}
          {/*  </ListItemIcon> */}
          {/*  <ListItemText primary="Settings" /> */}
          {/* </ListItem> */}

          <ListItem
            component={Link}
            to="/logs"
            selected={logsActive}
            sx={styles.menuItem}
            button
            disabled={!navigationEnabled}
          >
            <ListItemIcon>
              <ListIcon />
            </ListItemIcon>
            <ListItemText primary="Logs" />
          </ListItem>

          <ListItem
            component={Link}
            to="/serial-monitor"
            selected={serialMonitorActive}
            sx={styles.menuItem}
            button
            disabled={!navigationEnabled}
          >
            <ListItemIcon>
              <DvrIcon />
            </ListItemIcon>
            <ListItemText primary="Serial Monitor" />
          </ListItem>

          <ListItem
            component={Link}
            to="/support"
            selected={supportActive}
            sx={styles.menuItem}
            button
            disabled={!navigationEnabled}
          >
            <ListItemIcon>
              <HelpIcon />
            </ListItemIcon>
            <ListItemText primary="Support" />
          </ListItem>
        </List>
      </Box>
    </Drawer>
  );
}
Example #28
Source File: BalanceHistoryGraph.tsx    From abrechnung with GNU Affero General Public License v3.0 4 votes vote down vote up
export default function BalanceHistoryGraph({ group, accountID }) {
    const theme: Theme = useTheme();
    const balanceHistory = useRecoilValue(accountBalanceHistory({ groupID: group.id, accountID: accountID }));
    const history = useHistory();

    const transactionMap = useRecoilValue(transactionByIDMap(group.id));
    const accountMap = useRecoilValue(accountByIDMap(group.id));

    const onClick = (evt) => {
        if (evt.activePayload.length > 0) {
            const payload = evt.activePayload[0].payload;
            if (payload.changeOrigin.type === "clearing") {
                history.push(`/groups/${group.id}/accounts/${payload.changeOrigin.id}`);
            } else {
                history.push(`/groups/${group.id}/transactions/${payload.changeOrigin.id}`);
            }
        }
    };

    const renderTooltip = ({ payload, label, active }) => {
        if (!active) {
            return null;
        }

        const changeOrigin = payload[0].payload.changeOrigin;

        const icon =
            changeOrigin.type === "clearing" ? (
                <ClearingAccountIcon color="primary" fontSize="small" />
            ) : transactionMap[changeOrigin.id].type === "purchase" ? (
                <PurchaseIcon color="primary" sx={{ fontSize: theme.typography.fontSize }} />
            ) : (
                <TransferIcon color="primary" fontSize="small" />
            );

        return (
            <Box
                sx={{
                    backgroundColor: theme.palette.background.paper,
                    borderColor: theme.palette.divider,
                    borderRadius: theme.shape.borderRadius,
                    borderWidth: "1px",
                    borderStyle: "solid",
                    padding: 2,
                }}
            >
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                    <Typography variant="body1" component="span">
                        {DateTime.fromSeconds(payload[0].payload.date).toISODate()} {icon}
                    </Typography>
                    <Typography
                        component="span"
                        sx={{ color: (theme) => balanceColor(payload[0].value, theme), ml: 2 }}
                    >
                        {payload[0].value} {group.currency_symbol}
                    </Typography>
                </div>
                <Divider />
                {payload[0].payload.changeOrigin.type === "clearing" ? (
                    <Typography variant="body1">{accountMap[payload[0].payload.changeOrigin.id].name}</Typography>
                ) : (
                    <Typography variant="body1">
                        {transactionMap[payload[0].payload.changeOrigin.id].description}
                    </Typography>
                )}
            </Box>
        );
    };

    return (
        <ResponsiveContainer width="100%" height={300}>
            <LineChart
                width={730}
                height={250}
                onClick={onClick}
                data={balanceHistory}
                margin={{
                    top: 5,
                    right: 30,
                    left: 20,
                    bottom: 5,
                }}
            >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis
                    dataKey="date"
                    stroke={theme.palette.text.primary}
                    type="number"
                    tickFormatter={(unixTime) => DateTime.fromSeconds(unixTime).toISODate()}
                    domain={["dataMin", "dataMax"]}
                />
                <YAxis
                    tickFormatter={(value) => value.toFixed(2)}
                    type="number"
                    unit={group.currency_symbol}
                    stroke={theme.palette.text.primary}
                />
                <Tooltip content={renderTooltip} />
                <Legend />
                <Line type="stepAfter" dataKey="balance" />
            </LineChart>
        </ResponsiveContainer>
    );
}
Example #29
Source File: EpisodeListing.tsx    From multi-downloader-nx with MIT License 4 votes vote down vote up
EpisodeListing: React.FC = () => {
  const [store, dispatch] = useStore();

  const [season, setSeason] = React.useState<'all'|string>('all');

  const seasons = React.useMemo(() => {
    const s: string[] = [];
    for (const {season} of store.episodeListing) {
      if (s.includes(season))
        continue;
      s.push(season);
    }
    return s;
  }, [ store.episodeListing ])

  const [selected, setSelected] = React.useState<string[]>([]);

  React.useEffect(() => {
    setSelected(parseSelect(store.downloadOptions.e));
  }, [ store.episodeListing ])

  const close = () => {
    dispatch({
      type: 'episodeListing',
      payload: []
    });
    dispatch({
      type: 'downloadOptions',
      payload: {
        ...store.downloadOptions,
        e: `${([...new Set([...parseSelect(store.downloadOptions.e), ...selected])]).join(',')}`
      }
    })
  }

  return <Dialog open={store.episodeListing.length > 0} onClose={close} scroll='paper' maxWidth='xl' sx={{ p: 2 }}>
      <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 200px 20px' }}>
        <Typography color='text.primary' variant="h5" sx={{ textAlign: 'center', alignItems: 'center', justifyContent: 'center', display: 'flex' }}>
          Episodes
        </Typography>
        <FormControl sx={{ mr: 2, mt: 2 }}>
          <InputLabel id='seasonSelectLabel'>Season</InputLabel>
          <Select labelId="seasonSelectLabel" label='Season' value={season} onChange={(e) => setSeason(e.target.value)}>
            <MenuItem value='all'>Show all Epsiodes</MenuItem>
            {seasons.map((a, index) => {
              return <MenuItem value={a} key={`MenuItem_SeasonSelect_${index}`}>
                {a}
              </MenuItem>
            })}
          </Select>
        </FormControl>
      </Box>
      <List>
        <ListItem sx={{ display: 'grid', gridTemplateColumns: '25px 1fr 5fr' }}>
          <Checkbox
            indeterminate={store.episodeListing.some(a => selected.includes(a.e)) && !store.episodeListing.every(a => selected.includes(a.e))}
            checked={store.episodeListing.every(a => selected.includes(a.e))}
            onChange={() => {
              if (selected.length > 0) {
                setSelected([]);
              } else {
                setSelected(store.episodeListing.map(a => a.e));
              }
            }}
          />
        </ListItem>
        {store.episodeListing.filter((a) => season === 'all' ? true : a.season === season).map((item, index, { length }) => {
          const e = isNaN(parseInt(item.e)) ? item.e : parseInt(item.e);
          const isSelected = selected.includes(e.toString());
          return <Box {...{ mouseData: isSelected }} key={`Episode_List_Item_${index}`} sx={{
              backdropFilter: isSelected ? 'brightness(1.5)' : '',
              '&:hover': {
                backdropFilter: 'brightness(1.5)'
              }
            }}
            onClick={() => {
              let arr: string[] = [];
              if (isSelected) {
                arr = [...selected.filter(a => a !== e.toString())];
              } else {
                arr = [...selected, e.toString()];
              }
              setSelected(arr.filter(a => a.length > 0));
            }}>
            <ListItem sx={{ display: 'grid', gridTemplateColumns: '25px 50px 1fr 5fr' }}>
              { isSelected ? <CheckBox /> : <CheckBoxOutlineBlank /> }
              <Typography color='text.primary' sx={{ textAlign: 'center' }}>
                {e}
              </Typography>
              <img style={{ width: 'inherit', maxHeight: '200px', minWidth: '150px' }} src={item.img}></img>
              <Box sx={{ display: 'flex', flexDirection: 'column', pl: 1 }}>
                <Box sx={{ display: 'grid', gridTemplateColumns: '1fr min-content' }}>
                  <Typography color='text.primary' variant="h5">
                    {item.name}
                  </Typography>
                  <Typography color='text.primary'>
                    {item.time.startsWith('00:') ? item.time.slice(3) : item.time}
                  </Typography>
                </Box>
                <Typography color='text.primary'>
                  {item.description}
                </Typography>
              </Box>
            </ListItem>
            {index < length - 1 && <Divider />}
          </Box>
        })}
      </List>
  </Dialog>
}