@mui/material#Box TypeScript Examples

The following examples show how to use @mui/material#Box. 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: webTestApp.tsx    From rewind with MIT License 6 votes vote down vote up
export function WebTestApp() {
  const theater = useCommonManagers();
  const analyzer = useAnalysisApp();
  useEffect(() => {
    // theater.changeSkin(skin);
    analyzer.loadReplay(chosenReplayId);
  }, []);
  return (
    <Box sx={{ height: "100vh" }}>
      <Analyzer />
    </Box>
  );
}
Example #2
Source File: EXPCalc.tsx    From genshin-optimizer with MIT License 6 votes vote down vote up
function BookDisplay(props) {
  let { bookKey, value = 0, setValue, required = 0 } = props
  return <CardLight>
    <CardContent sx={{ py: 1 }}>
      <Typography>{booksData[bookKey].name}</Typography>
    </CardContent>
    <Divider />
    <CardContent>
      <Grid container>
        <Grid item xs={3}><ImgFullwidth src={booksData[bookKey].img} /></Grid>
        <Grid item xs={9}>
          <ButtonGroup sx={{ display: "flex" }}>
            <TextButton>Amount</TextButton>
            <CustomNumberInputButtonGroupWrapper sx={{ flexBasis: 30, flexGrow: 1 }}>
              <CustomNumberInput
                value={value}
                onChange={(val) => setValue(Math.max(val ?? 0, 0))}
                sx={{ px: 2 }}
              />
            </CustomNumberInputButtonGroupWrapper>
          </ButtonGroup>
          <Box display="flex" justifyContent="space-between" mt={1}>
            <Typography>Required:</Typography>
            <Typography><b ><ColorText color={required ? "success" : ""}>{required}</ColorText></b></Typography>
          </Box>
        </Grid>
      </Grid>
    </CardContent>
  </CardLight >
}
Example #3
Source File: index.tsx    From react-hook-form-mui with MIT License 6 votes vote down vote up
export default function Index() {
  const [values, setValues] = useState<FormProps>()
  const onSubmit = (data: FormProps) => {
    setValues(data)
  }
  let defaultValues: FormProps = { hallo: '' }
  return (
    <Box sx={{
      maxWidth: 300,
      margin: '30px auto 0 auto'
    }}>
      <FormContainer defaultValues={defaultValues} onSuccess={onSubmit}>
        <Stack direction={'column'}>
          <TextFieldElement name={'hallo'} label={'hallo'} /> <br />
          <TextFieldElement color={'primary'} name={'primary'} label={'Primary'} /><br />
          <TextFieldElement color={'secondary'} name={'secondary'} label={'Secondary'} />
          <br />
          <Button type={'submit'} variant={'contained'} color={'primary'}>Submit</Button>
        </Stack>
      </FormContainer>
      <div>
        Data:<br />
        {JSON.stringify(values)}
      </div>
    </Box>
  )
}
Example #4
Source File: ResultList.tsx    From cli with Apache License 2.0 6 votes vote down vote up
function FieldValue(props: FieldValueInterface) {
  return (
    <Box>
      <Typography
        color="textSecondary"
        style={{fontWeight: 'bold'}}
        variant="caption"
      >
        {props.caption}:&nbsp;
      </Typography>
      <Typography color="textSecondary" variant="caption">
        {props.value}
      </Typography>
    </Box>
  );
}
Example #5
Source File: ServiceProvider.tsx    From multi-downloader-nx with MIT License 6 votes vote down vote up
ServiceProvider: React.FC = ({ children }) => {
  const [ { service }, dispatch ] = useStore();

  const setService = (s: StoreState['service']) => {
    dispatch({
      type: 'service',
      payload: s
    });
  }

  return service === undefined ? 
    <Box>
      <Typography color="text.primary" variant='h3' sx={{ textAlign: 'center', mb: 5 }}>Please choose your service</Typography>
      <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
        <Button size='large' variant="contained" onClick={() => setService('funi')} >Funimation</Button>
        <Divider orientation='vertical' flexItem />
        <Button size='large' variant="contained" onClick={() => setService('crunchy')}>Crunchyroll</Button>
      </Box>
    </Box>
    : <serviceContext.Provider value={service}>
      {children}
    </serviceContext.Provider>;
}
Example #6
Source File: PlayBar.tsx    From rewind with MIT License 6 votes vote down vote up
function CurrentTime() {
  const analyzer = useAnalysisApp();
  const requestRef = useRef<number>();
  const timeRef = useRef<GameCurrentTimeHandle>(null);

  // const animate = () => {};

  useEffect(() => {
    // requestRef.current = requestAnimationFrame(animate);
    let last = -1;
    const requiredElapsed = 1000 / timeAnimateFPS;

    function animate(currentTimestamp: number) {
      const elapsed = currentTimestamp - last;
      if (elapsed > requiredElapsed) {
        if (timeRef.current) timeRef.current.updateTime(analyzer.gameClock.timeElapsedInMs);
        last = currentTimestamp;
      }
      requestRef.current = requestAnimationFrame(animate);
    }

    requestRef.current = requestAnimationFrame(animate);
    return () => {
      if (requestRef.current) cancelAnimationFrame(requestRef.current);
    };
  }, [analyzer]);
  return (
    // We MUST fix the width because the font is not monospace e.g. "111" is thinner than "000"
    // Also if the duration is more than an hour there will also be a slight shift
    <Box sx={{ width: "7em" }}>
      <BaseCurrentTime ref={timeRef} />
    </Box>
  );
}
Example #7
Source File: LibraryOptions.tsx    From Tachidesk-WebUI with Mozilla Public License 2.0 6 votes vote down vote up
function Options() {
    const [currentTab, setCurrentTab] = useState<number>(0);

    return (
        <Box>
            <Tabs
                key={currentTab}
                value={currentTab}
                variant="fullWidth"
                onChange={(e, newTab) => setCurrentTab(newTab)}
                indicatorColor="primary"
                textColor="primary"
            >
                <Tab label="Filter" value={0} />
                <Tab label="Sort" value={1} />
                <Tab label="Display" value={2} />
            </Tabs>
            {filtersTab(currentTab)}
            {sortsTab(currentTab)}
            {dispalyTab(currentTab)}
        </Box>
    );
}
Example #8
Source File: index.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
MainLayout: FunctionComponent = (props) => {
  const { children } = props;
  return (
    <Box component="main" sx={styles.root}>
      <Sidebar />
      <Box sx={styles.content}>
        <Header />
        <Container sx={styles.main}>{children}</Container>
      </Box>
    </Box>
  );
}
Example #9
Source File: LoadingScreen.tsx    From GTAV-NativeDB with MIT License 6 votes vote down vote up
LoadingPage = () => {
  return (
    <Box 
      sx={{
        p: 2,
        display: 'flex',
        flexDirection: 'column',
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Stack spacing={2}>
        <img 
          src="/splash.png" 
          alt="grand theft auto 5 logo" 
          height="225"
          style={{ objectFit: 'contain' }}
        />
        <Typography 
          variant="h2" 
          component="h1"
          align="center"
          gutterBottom
        >
          Loading Natives
        </Typography>
        <LinearProgress />
      </Stack>
    </Box>
  )
}
Example #10
Source File: BlogEntryPreview.tsx    From firecms with MIT License 6 votes vote down vote up
export function Images({ storagePaths }: { storagePaths: string[] }) {
    if (!storagePaths)
        return <></>;
    return <Box display="flex">
        {storagePaths.map((path, index) =>
            <Box p={2} m={1}
                 key={`images_${index}`}
                 style={{
                     width: 250,
                     height: 250
                 }}>
                <StorageImage storagePath={path}/>
            </Box>
        )}
    </Box>;
}
Example #11
Source File: PlayBar.tsx    From rewind with MIT License 5 votes vote down vote up
function AudioButton() {
  const [anchorEl, setAnchorEl] = useState(null);
  const open = Boolean(anchorEl);
  const handlePopOverOpen = (event: any) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };
  const { volume, muted } = useAudioSettings();
  const service = useAudioSettingsService();

  const handleClick = () => {
    service.toggleMuted();
  };
  return (
    <>
      <IconButton onClick={handlePopOverOpen}>{muted ? <VolumeOff /> : <VolumeUp />}</IconButton>
      <Popover
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "top",
          horizontal: "center",
        }}
        transformOrigin={{
          vertical: "bottom",
          horizontal: "center",
        }}
      >
        <Box width={256}>
          <BaseAudioSettingsPanel
            master={volume.master}
            music={volume.music}
            /* Currently it's disabled */
            effects={0}
            onMutedChange={(x) => service.setMuted(x)}
            onMasterChange={(x) => service.setMasterVolume(x)}
            onMusicChange={(x) => service.setMusicVolume(x)}
            onEffectsChange={(x) => service.setEffectsVolume(x)}
          />
        </Box>
      </Popover>
    </>
  );
}
Example #12
Source File: BlogEntryPreview.tsx    From firecms with MIT License 5 votes vote down vote up
/**
 * This is a sample view used to render the content of a blog entry.
 * It is bound to the data that is modified in the form.
 * @constructor
 */
export function BlogEntryPreview({ modifiedValues }: EntityCustomViewParams) {

    const storage = useStorageSource();

    const [headerUrl, setHeaderUrl] = useState<string | undefined>();
    useEffect(() => {
        if (modifiedValues?.header_image) {
            storage.getDownloadURL(modifiedValues.header_image)
                .then((res) => setHeaderUrl(res));
        }
    }, [storage, modifiedValues?.header_image]);

    return (
        <Box>

            {headerUrl && <img
                alt={"Header"}
                style={{
                    width: "100%",
                    maxHeight: "300px",
                    objectFit: "cover"
                }}
                src={headerUrl}
            />}

            <Container maxWidth={"md"} style={{
                alignItems: "center",
                justifyItems: "center",
                display: "flex",
                flexDirection: "column"
            }}>
                {modifiedValues?.name && <Typography variant={"h2"} style={{
                    marginTop: "40px",
                    marginBottom: "20px"
                }}>
                    {modifiedValues.name}
                </Typography>}

                {modifiedValues?.content && modifiedValues.content
                    .filter((e: any) => !!e)
                    .map(
                        (entry: any, index: number) => {
                            if (entry.type === "text")
                                return <Text key={`preview_text_${index}`}
                                             markdownText={entry.value}/>;
                            if (entry.type === "images")
                                return <Images key={`preview_images_${index}`}
                                               storagePaths={entry.value}/>;
                            if (entry.type === "products")
                                return <ProductGroupPreview
                                    key={`preview_products_${index}`}
                                    references={entry.value}/>;
                            return <ErrorView
                                error={"Unexpected value in blog entry"}/>
                        }
                    )}

            </Container>

        </Box>
    );

}
Example #13
Source File: SettingsModal.tsx    From rewind with MIT License 5 votes vote down vote up
export function SettingsModal() {
  const { onSettingsModalOpenChange, settingsModalOpen, opacity, onTabIndexChange, onOpacityChange, tabIndex } =
    useSettingsModalContext();
  const onClose = () => onSettingsModalOpenChange(false);

  return (
    <Modal
      open={settingsModalOpen}
      onClose={onClose}
      hideBackdrop={false}
      sx={{
        // We reduce the default backdrop from 0.5 alpha to 0.1 in order for the user to better see the background
        // behind the modal
        "& .MuiBackdrop-root": {
          backgroundColor: "rgba(0,0,0,0.1)",
        },
      }}
    >
      <Box
        sx={{
          position: "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: 800,
          maxWidth: "100%",
          height: 600,
          maxHeight: "100%",
        }}
      >
        <BaseSettingsModal
          opacity={opacity}
          tabIndex={tabIndex}
          onTabIndexChange={onTabIndexChange}
          onOpacityChange={onOpacityChange}
          onClose={onClose}
          tabs={[
            { label: "General", component: <GeneralSettings /> },
            {
              label: "Skins",
              component: <SkinsSettings />,
            },
          ]}
        />
      </Box>
    </Modal>
  );
}
Example #14
Source File: Style.tsx    From multi-downloader-nx with MIT License 5 votes vote down vote up
Style: React.FC = ({children}) => {
  return <ThemeProvider theme={makeTheme('dark')}>
    <Container sx={{ mt: 3 }} maxWidth='xl'>
      <Box sx={{ position: 'fixed', height: '100%', width: '100%', zIndex: -500, backgroundColor: 'rgb(0, 30, 60)', top: 0, left: 0 }}/>
      {children}
    </Container>
  </ThemeProvider>;
}
Example #15
Source File: QuerySummary.tsx    From cli with Apache License 2.0 5 votes vote down vote up
QuerySummaryRenderer: FunctionComponent<QuerySummaryProps> = (props) => {
  const {controller} = props;
  const [state, setState] = useState(controller.state);

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

  const renderNoResults = () => {
    return <Box mt={5}>No results</Box>;
  };

  const renderBold = (input: string) => {
    return (
      <Box component="span">
        <strong>{input}</strong>
      </Box>
    );
  };

  const renderRange = () => {
    return renderBold(` ${state.firstResult}-${state.lastResult}`);
  };

  const renderTotal = () => {
    return <Box component="span"> of {renderBold(state.total.toString())}</Box>;
  };

  const renderQuery = () => {
    if (state.hasQuery) {
      return <Box component="span"> for {renderBold(state.query)}</Box>;
    }
  };

  const renderDuration = () => {
    return ` in ${state.durationInSeconds} seconds`;
  };

  const renderHasResults = () => {
    return (
      <Box>
        <Box fontWeight="fontWeightBold">
          Results{renderRange()}
          {renderTotal()}
          {renderQuery()}
          {renderDuration()}
        </Box>
        <Divider />
      </Box>
    );
  };

  return !state.hasResults ? renderNoResults() : renderHasResults();
}
Example #16
Source File: Shared.tsx    From react-hook-form-mui with MIT License 5 votes vote down vote up
BoxMargin: FC = ({ children }) => {
  return (
    <Box sx={{
      marginY: 2
    }}>{children}</Box>
  )
}
Example #17
Source File: ArtifactCardNano.tsx    From genshin-optimizer with MIT License 5 votes vote down vote up
export default function ArtifactCardNano({ artifactId, slotKey: pSlotKey, mainStatAssumptionLevel = 0, showLocation = false, onClick, BGComponent = CardDark }: Data) {
  const art = useArtifact(artifactId)
  const sheet = usePromise(ArtifactSheet.get(art?.setKey), [art])
  const actionWrapperFunc = useCallback(children => <CardActionArea onClick={onClick} sx={{ height: "100%" }}>{children}</CardActionArea>, [onClick],)
  const theme = useTheme()
  if (!art) return <BGComponent sx={{ display: "flex", height: "100%", alignItems: "center", justifyContent: "center" }}>
    <Box component="img" src={Assets.slot[pSlotKey]} sx={{ width: "25%", height: "auto", opacity: 0.7 }} />
  </BGComponent>

  const { slotKey, rarity, level, mainStatKey, substats, location } = art
  const mainStatLevel = Math.max(Math.min(mainStatAssumptionLevel, rarity * 4), level)
  const mainStatUnit = KeyMap.unit(mainStatKey)
  const levelVariant = "roll" + (Math.floor(Math.max(level, 0) / 4) + 1)
  const element = allElementsWithPhy.find(ele => art.mainStatKey.includes(ele))
  const color = element ? alpha(theme.palette[element].main, 0.6) : alpha(theme.palette.secondary.main, 0.6)
  return <BGComponent sx={{ height: "100%" }}><ConditionalWrapper condition={!!onClick} wrapper={actionWrapperFunc}  >
    <Box display="flex" height="100%">
      <Box className={`grad-${rarity}star`} sx={{ position: "relative", flexGrow: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }} >
        <ArtifactSetSlotTooltip slotKey={slotKey} sheet={sheet}>
          <Box
            component="img"
            src={sheet?.slotIcons[slotKey] ?? ""}
            sx={{ m: -1, maxHeight: "110%", maxWidth: "110%" }}
          />
        </ArtifactSetSlotTooltip>
        <Box sx={{ position: "absolute", width: "100%", height: "100%", p: 0.5, opacity: 0.85, display: "flex", justifyContent: "space-between", pointerEvents: "none" }} >
          <Chip size="small" label={<strong>{` +${level}`}</strong>} color={levelVariant as any} />
          {showLocation && <Chip size="small" label={<LocationIcon location={location} />} color={"secondary"} sx={{
            overflow: "visible", ".MuiChip-label": {
              overflow: "visible"
            }
          }} />}
        </Box>
        {/* mainstats */}
        <Chip size="small" sx={{ position: "absolute", bottom: 0, mb: 1, backgroundColor: color }}
          label={<Typography variant="h6" sx={{ display: "flex", gap: 1, px: 1, zIndex: 1 }}>
            <BootstrapTooltip placement="top" title={<Typography>{KeyMap.getArtStr(mainStatKey)}</Typography>} disableInteractive>
              <span>{element ? uncoloredEleIcons[element] : StatIcon[mainStatKey]}</span>
            </BootstrapTooltip>
            <ColorText color={mainStatLevel !== level ? "warning" : undefined}>{cacheValueString(Artifact.mainStatValue(mainStatKey, rarity, mainStatLevel) ?? 0, KeyMap.unit(mainStatKey))}{mainStatUnit}</ColorText>
          </Typography>} />
      </Box>
      {/* substats */}
      <Box display="flex" flexDirection="column" justifyContent="space-between" sx={{ p: 1, }}>
        {substats.map((stat: ICachedSubstat, i: number) => <SubstatDisplay key={i + stat.key} stat={stat} />)}
      </Box>
    </Box>
  </ConditionalWrapper></BGComponent >
}
Example #18
Source File: SampleProductsView.tsx    From firecms with MIT License 5 votes vote down vote up
export function SampleProductsView({ entity, modifiedValues }: {
    entity?: Entity<Product>;
    modifiedValues?: EntityValues<Product>;
}) {

    const snackbarContext = useSnackbarController();

    const onClick = (event: React.MouseEvent) => {
        snackbarContext.open({
            type: "success",
            message: `Custom action for ${modifiedValues?.name}`
        });
    };

    const values = modifiedValues ? modifiedValues : {};

    return (
        <Box
            display="flex"
            width={"100%"}
            height={"100%"}>

            <Box m="auto"
                 display="flex"
                 flexDirection={"column"}
                 alignItems={"center"}
                 justifyItems={"center"}>

                <Box p={4}>
                    <p>
                        This is an example of a custom view added
                        as a panel to an entity schema.
                    </p>
                    <p>
                        Values in the form:
                    </p>

                    {values && <p style={{
                        color: "#fff",
                        padding: "8px",
                        fontSize: ".85em",
                        fontFamily: "monospace",
                        borderRadius: "4px",
                        backgroundColor: "#4e482f"
                    }}>
                        {JSON.stringify(values, null, 2)}
                    </p>}


                </Box>

                <Button onClick={onClick} color="primary">
                    Your action
                </Button>

            </Box>
        </Box>
    );

}
Example #19
Source File: TabTalent.tsx    From genshin-optimizer with MIT License 5 votes vote down vote up
function SkillDisplayCard({ talentKey, subtitle, onClickTitle }: SkillDisplayCardProps) {
  const { data, character: { talent }, characterSheet, characterDispatch } = useContext(DataContext)

  const actionWrapeprFunc = useCallback(
    children => <CardActionArea onClick={onClickTitle}>{children}</CardActionArea>,
    [onClickTitle],
  )

  let header: Displayable | null = null

  if (talentKey in talent) {
    const levelBoost = data.get(input.bonus[talentKey] as NumNode).value
    const level = data.get(input.total[talentKey]).value
    const asc = data.get(input.asc).value
    const setTalentLevel = (tKey, newTalentLevelKey) => {
      talent[tKey] = newTalentLevelKey
      characterDispatch({ talent })
    }
    header = <DropdownButton fullWidth title={`Talent Lv. ${level}`} color={levelBoost ? "info" : "primary"} sx={{ borderRadius: 0 }}>
      {range(1, talentLimits[asc]).map(i =>
        <MenuItem key={i} selected={talent[talentKey] === (i)} disabled={talent[talentKey] === (i)} onClick={() => setTalentLevel(talentKey, i)}>Talent Lv. {i + levelBoost}</MenuItem>)}
    </DropdownButton>
  }
  const talentSheet = characterSheet.getTalentOfKey(talentKey, data.get(input.charEle).value as ElementKey | undefined)

  // Hide header if the header matches the current talent
  const hideHeader = (section: DocumentSection): boolean => {
    let headerAction = section.header?.action
    if (headerAction && (typeof headerAction !== "string")) {
      const key: string = headerAction.props.children.props.key18
      return key.includes(talentKey)
    }
    return false
  }

  return <CardLight sx={{ height: "100%" }}>
    {header}
    <CardContent>
      <ConditionalWrapper condition={!!onClickTitle} wrapper={actionWrapeprFunc} >
        <Grid container sx={{ flexWrap: "nowrap" }}>
          <Grid item>
            <Box component="img" src={talentSheet?.img} sx={{ width: 60, height: "auto" }} />
          </Grid>
          <Grid item flexGrow={1} sx={{ pl: 1 }}>
            <Typography variant="h6">{talentSheet?.name}</Typography>
            <Typography variant="subtitle1">{subtitle}</Typography>
          </Grid>
        </Grid>
      </ConditionalWrapper>
      {/* Display document sections */}
      {talentSheet?.sections ? <DocumentDisplay sections={talentSheet.sections} hideDesc hideHeader={hideHeader} /> : null}
    </CardContent>
  </CardLight>
}
Example #20
Source File: TableStorageUpload.tsx    From firecms with MIT License 5 votes vote down vote up
export function StorageUploadProgress({
                                          storagePath,
                                          entry,
                                          metadata,
                                          onFileUploadComplete,
                                          size
                                      }: StorageUploadItemProps) {

    const storage = useStorageSource();

    const snackbarContext = useSnackbarController();

    const [error, setError] = React.useState<string>();
    const [loading, setLoading] = React.useState<boolean>(false);
    const mounted = React.useRef(false);

    const upload = useCallback((file: File, fileName?: string) => {

        setError(undefined);
        setLoading(true);

        storage.uploadFile({ file, fileName, path: storagePath, metadata })
            .then(async ({ path }) => {
                console.debug("Upload successful");
                await onFileUploadComplete(path, entry, metadata);
                if (mounted.current)
                    setLoading(false);
            })
            .catch((e) => {
                console.error("Upload error", e);
                if (mounted.current) {
                    setError(e.message);
                    setLoading(false);
                }
                snackbarContext.open({
                    type: "error",
                    title: "Error uploading file",
                    message: e.message
                });
            });
    }, [entry, metadata, onFileUploadComplete, snackbarContext, storage, storagePath]);

    useEffect(() => {
        mounted.current = true;
        if (entry.file)
            upload(entry.file, entry.fileName);
        return () => {
            mounted.current = false;
        };
    }, [entry.file, entry.fileName, upload]);

    const imageSize = useMemo(() => getThumbnailMeasure(size), [size]);

    return (

        <Box m={1} sx={{
            width: imageSize,
            height: imageSize
        }}>

            {loading && <Skeleton variant="rectangular" sx={{
                width: imageSize,
                height: imageSize
            }}/>}

            {error && <p>Error uploading file: {error}</p>}

        </Box>

    );

}