@mui/material/styles#useTheme JavaScript Examples
The following examples show how to use
@mui/material/styles#useTheme.
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: helpers.js From sampo-ui with MIT License | 6 votes |
getScreenSize = () => {
const theme = useTheme()
const xsScreen = useMediaQuery(theme.breakpoints.down('sm'))
const smScreen = useMediaQuery(theme.breakpoints.between('sm', 'md'))
const mdScreen = useMediaQuery(theme.breakpoints.between('md', 'lg'))
const lgScreen = useMediaQuery(theme.breakpoints.between('lg', 'xl'))
const xlScreen = useMediaQuery(theme.breakpoints.up('xl'))
let screenSize = ''
if (xsScreen) { screenSize = 'xs' }
if (smScreen) { screenSize = 'sm' }
if (mdScreen) { screenSize = 'md' }
if (lgScreen) { screenSize = 'lg' }
if (xlScreen) { screenSize = 'xl' }
return screenSize
}
Example #2
Source File: useWidth.js From react-saas-template with MIT License | 6 votes |
/**
* Be careful using this hook. It only works because the number of
* breakpoints in theme is static. It will break once you change the number of
* breakpoints. See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
*/
function useWidth() {
const theme = useTheme();
const keys = [...theme.breakpoints.keys].reverse();
return (
keys.reduce((output, key) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const matches = useMediaQuery(theme.breakpoints.up(key));
return !output && matches ? key : output;
}, null) || "xs"
);
}
Example #3
Source File: useResponsive.js From Django-REST-Framework-React-BoilerPlate with MIT License | 6 votes |
// ----------------------------------------------------------------------
export default function useResponsive(query, key, start, end) {
const theme = useTheme();
const mediaUp = useMediaQuery(theme.breakpoints.up(key));
const mediaDown = useMediaQuery(theme.breakpoints.down(key));
const mediaBetween = useMediaQuery(theme.breakpoints.between(start, end));
const mediaOnly = useMediaQuery(theme.breakpoints.only(key));
if (query === 'up') {
return mediaUp;
}
if (query === 'down') {
return mediaDown;
}
if (query === 'between') {
return mediaBetween;
}
if (query === 'only') {
return mediaOnly;
}
return null;
}
Example #4
Source File: index.js From fireact with MIT License | 5 votes |
Layout = ({drawerMenu, toolbarChildren, toolBarMenu, children}) => {
const theme = useTheme();
const [open, setOpen] = React.useState(false);
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
const [breadcrumb, setBreadcrumb] = useState([]);
return (
<Box sx={{ display: 'flex'}}>
<CssBaseline />
<AppBar position="fixed" open={open}>
<Toolbar>
<div style={{paddingRight: '20px', display: open?"none":"inline-flex"}}><Logo /></div>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
sx={{
marginRight: '36px',
...(open && { display: 'none' }),
}}
>
<MenuIcon />
</IconButton>
{toolbarChildren}
<div style={{
marginLeft: "auto",
marginRight: "0px",
}}>{toolBarMenu}</div>
</Toolbar>
</AppBar>
<Drawer
variant="permanent"
open={open}
>
<DrawerHeader>
{open && <div style={{marginLeft:'0px', marginRight:'auto', display:'inline-flex',alignItems: 'center', flexWrap: 'wrap',}}>
<div style={{display: 'inline-flex', paddingRight: '20px'}}>
<Logo />
</div>
<h2>FIREACT</h2>
</div>}
<IconButton onClick={handleDrawerClose}>
{theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
</IconButton>
</DrawerHeader>
<Divider />
{drawerMenu}
<Divider />
</Drawer>
<Box component="main" sx={{ flexGrow: 1, overflow:'hidden'}}>
<DrawerHeader />
<Box width={1} style={{position:"fixed", zIndex: '1200'}}>
<Paper square>
<Box p={2}>
<Breadcrumb links={breadcrumb} />
</Box>
</Paper>
</Box>
<div style={{position: 'relative'}}>
<Box mt={10} ml={3} mr={3} mb={3}>
<BreadcrumbContext.Provider value={{setBreadcrumb}}>
{children}
</BreadcrumbContext.Provider>
</Box>
</div>
</Box>
</Box>
);
}
Example #5
Source File: Logo.js From Django-REST-Framework-React-BoilerPlate with MIT License | 5 votes |
export default function Logo({ disabledLink = false, sx }) {
const theme = useTheme();
const PRIMARY_LIGHT = theme.palette.primary.light;
const PRIMARY_MAIN = theme.palette.primary.main;
const PRIMARY_DARK = theme.palette.primary.dark;
// OR
// const logo = <Box component="img" src="/static/logo.svg" sx={{ width: 40, height: 40, ...sx }} />
const logo = (
<Box sx={{ width: 40, height: 40, ...sx }}>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 512 512">
<defs>
<linearGradient id="BG1" x1="100%" x2="50%" y1="9.946%" y2="50%">
<stop offset="0%" stopColor={PRIMARY_DARK} />
<stop offset="100%" stopColor={PRIMARY_MAIN} />
</linearGradient>
<linearGradient id="BG2" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stopColor={PRIMARY_LIGHT} />
<stop offset="100%" stopColor={PRIMARY_MAIN} />
</linearGradient>
<linearGradient id="BG3" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stopColor={PRIMARY_LIGHT} />
<stop offset="100%" stopColor={PRIMARY_MAIN} />
</linearGradient>
</defs>
<g fill={PRIMARY_MAIN} fillRule="evenodd" stroke="none" strokeWidth="1">
<path
fill="url(#BG1)"
d="M183.168 285.573l-2.918 5.298-2.973 5.363-2.846 5.095-2.274 4.043-2.186 3.857-2.506 4.383-1.6 2.774-2.294 3.939-1.099 1.869-1.416 2.388-1.025 1.713-1.317 2.18-.95 1.558-1.514 2.447-.866 1.38-.833 1.312-.802 1.246-.77 1.18-.739 1.111-.935 1.38-.664.956-.425.6-.41.572-.59.8-.376.497-.537.69-.171.214c-10.76 13.37-22.496 23.493-36.93 29.334-30.346 14.262-68.07 14.929-97.202-2.704l72.347-124.682 2.8-1.72c49.257-29.326 73.08 1.117 94.02 40.927z"
/>
<path
fill="url(#BG2)"
d="M444.31 229.726c-46.27-80.956-94.1-157.228-149.043-45.344-7.516 14.384-12.995 42.337-25.267 42.337v-.142c-12.272 0-17.75-27.953-25.265-42.337C189.79 72.356 141.96 148.628 95.69 229.584c-3.483 6.106-6.828 11.932-9.69 16.996 106.038-67.127 97.11 135.667 184 137.278V384c86.891-1.611 77.962-204.405 184-137.28-2.86-5.062-6.206-10.888-9.69-16.994"
/>
<path
fill="url(#BG3)"
d="M450 384c26.509 0 48-21.491 48-48s-21.491-48-48-48-48 21.491-48 48 21.491 48 48 48"
/>
</g>
</svg>
</Box>
);
if (disabledLink) {
return <>{logo}</>;
}
return <RouterLink to="/">{logo}</RouterLink>;
}
Example #6
Source File: BaseOptionChart.js From Django-REST-Framework-React-BoilerPlate with MIT License | 5 votes |
// ----------------------------------------------------------------------
export function BaseOptionChartStyle() {
const theme = useTheme();
const background = {
backdropFilter: 'blur(6px)',
WebkitBackdropFilter: 'blur(6px)', // Fix on Mobile
backgroundColor: alpha(theme.palette.background.default, 0.72)
};
return (
<GlobalStyles
styles={{
'&.apexcharts-canvas': {
// Tooltip
'.apexcharts-xaxistooltip': {
...background,
border: 0,
boxShadow: theme.customShadows.z24,
color: theme.palette.text.primary,
borderRadius: Number(theme.shape.borderRadius) * 1.5,
'&:before': { borderBottomColor: 'transparent' },
'&:after': { borderBottomColor: alpha(theme.palette.background.default, 0.72) }
},
'.apexcharts-tooltip.apexcharts-theme-light': {
...background,
border: 0,
boxShadow: theme.customShadows.z24,
borderRadius: Number(theme.shape.borderRadius) * 1.5,
'& .apexcharts-tooltip-title': {
border: 0,
textAlign: 'center',
fontWeight: theme.typography.fontWeightBold,
backgroundColor: theme.palette.grey[500_16],
color: theme.palette.text[theme.palette.mode === 'light' ? 'secondary' : 'primary']
}
},
// Legend
'.apexcharts-legend': {
padding: 0
},
'.apexcharts-legend-series': {
display: 'flex !important',
alignItems: 'center'
},
'.apexcharts-legend-marker': {
marginRight: 8
},
'.apexcharts-legend-text': {
lineHeight: '18px',
textTransform: 'capitalize'
}
}
}}
/>
);
}
Example #7
Source File: InfoHeader.js From sampo-ui with MIT License | 4 votes |
InfoHeader = props => {
const handleAccordionChange = () => () => {
props.updateExpanded({
resultClass: props.resultClass,
pageType: props.pageType
})
}
const generateLabel = () => {
let label = ''
const data = props.instanceData
const hasData = data !== null && Object.values(data).length >= 1
if (hasData && data.prefLabel) {
if (Array.isArray(data.prefLabel)) {
label = data.prefLabel[0].prefLabel
} else {
label = data.prefLabel.prefLabel || data.prefLabel
}
}
return label
}
const getHeadingVariant = () => {
const { layoutConfig } = props
const { infoHeader } = layoutConfig
const theme = useTheme()
const defaultHeight = useMediaQuery(theme.breakpoints.up(layoutConfig.reducedHeightBreakpoint))
const variant = defaultHeight
? infoHeader.default.headingVariant
: infoHeader.reducedHeight.headingVariant
return variant
}
const classes = useStyles(props)
return (
<Box
sx={theme => ({
marginTop: theme.spacing(0.5),
marginLeft: theme.spacing(0.5),
marginRight: theme.spacing(0.5)
})}
>
<Accordion expanded={props.expanded} onChange={handleAccordionChange()}>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls='infoheader-content'
id='infoheader-header'
sx={theme => ({
paddingLeft: theme.spacing(1),
minHeight: props.layoutConfig.infoHeader.reducedHeight.height,
[theme.breakpoints.up(props.layoutConfig.reducedHeightBreakpoint)]: {
minHeight: props.layoutConfig.infoHeader.default.height
},
'& .MuiAccordionSummary-content': {
display: 'block',
marginTop: theme.spacing(0.5),
marginBottom: theme.spacing(0.5)
}
})}
>
<Box
sx={{
display: 'flex'
}}
>
<Typography
sx={{
flexShrink: 1
}}
component='h1'
variant={getHeadingVariant()}
>
{props.pageType === 'facetResults' &&
intl.get(`perspectives.${props.resultClass}.label`)}
{props.pageType === 'instancePage' &&
intl.get(`perspectives.${props.resultClass}.instancePage.label`)}
</Typography>
<Tooltip title={intl.get('infoHeader.toggleInstructions')}>
<IconButton
aria-label='toggle instructions'
className={classes.infoIconButton}
size='large'
sx={theme => ({
padding: 0,
marginLeft: '4px !important',
'& .MuiSvgIcon-root': {
fontSize: props.layoutConfig.infoHeader.reducedHeight.infoIconFontSize,
[theme.breakpoints.up(props.layoutConfig.reducedHeightBreakpoint)]: {
fontSize: props.layoutConfig.infoHeader.default.infoIconFontSize
}
}
})}
>
<InfoIcon className={classes.infoIcon} />
</IconButton>
</Tooltip>
</Box>
{props.pageType === 'instancePage' &&
<Typography
component='h1'
variant='h6'
sx={theme => ({
marginTop: theme.spacing(1),
height: 32,
overflow: 'auto'
})}
>
{generateLabel()}
</Typography>}
</AccordionSummary>
<AccordionDetails
// className={classes.expandedContent}
sx={theme => ({
paddingTop: 0,
paddingLeft: theme.spacing(1),
paddingBottom: theme.spacing(1),
marginBottom: theme.spacing(0),
height: props.layoutConfig.infoHeader.reducedHeight.expandedContentHeight,
overflow: 'auto',
display: 'block',
'& p, & ul': {
...theme.typography.body1,
fontSize: '0.8rem'
},
'& h6': {
...theme.typography.h6,
marginTop: 0,
marginBottom: 0
},
'& p:first-of-type': {
marginTop: 0
},
[theme.breakpoints.up(props.layoutConfig.reducedHeightBreakpoint)]: {
height: props.layoutConfig.infoHeader.default.expandedContentHeight,
'& p, & ul': {
fontSize: '1rem !important;'
}
}
})}
>
{props.pageType === 'facetResults' && intl.getHTML(`perspectives.${props.resultClass}.longDescription`)}
{props.pageType === 'instancePage' &&
<>
{intl.getHTML('instancePageGeneral.introduction',
{ entity: intl.get(`perspectives.${props.resultClass}.instancePage.label`) })}
{intl.getHTML(`perspectives.${props.resultClass}.instancePage.description`)}
{intl.getHTML('instancePageGeneral.repetition')}
</>}
</AccordionDetails>
</Accordion>
</Box>
)
}
Example #8
Source File: TopBar.js From sampo-ui with MIT License | 4 votes |
TopBar = props => {
const theme = useTheme()
// custom style function for utilizing React Router's isActive prop
const createAppBarButtonStyle = isActive => ({
whiteSpace: 'nowrap',
color: '#fff',
border: isActive ? '1px solid #fff' : `1px solid ${theme.palette.primary.main}`
})
const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null)
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl)
const { perspectives, currentLocale, availableLocales, rootUrl, layoutConfig } = props
const { topBar } = layoutConfig
const handleMobileMenuOpen = event => setMobileMoreAnchorEl(event.currentTarget)
const handleMobileMenuClose = () => setMobileMoreAnchorEl(null)
const federatedSearchMode = props.location.pathname.indexOf('federated-search') !== -1
let showSearchField = true
if (has(layoutConfig.topBar, 'showSearchField')) {
showSearchField = layoutConfig.topBar.showSearchField
}
// https://mui.com/guides/routing/#button
const AdapterLink = React.forwardRef((props, ref) =>
<Link ref={ref} {...props} role={undefined} />)
const AdapterNavLink = React.forwardRef((props, ref) =>
<NavLink ref={ref} {...props} role={undefined} />)
const getInternalLink = perspective => {
const searchMode = has(perspective, 'searchMode') ? perspective.searchMode : 'faceted-search'
let link = null
if (searchMode === 'dummy-internal') {
link = `${props.rootUrl}${perspective.internalLink}`
}
if (searchMode !== 'dummy-internal') {
link = `${props.rootUrl}/${perspective.id}/${searchMode}`
}
return link
}
const renderMobileMenuItem = perspective => {
if (has(perspective, 'externalUrl')) {
return (
<Box
component='a'
key={perspective.id}
href={perspective.externalUrl}
target='_blank'
rel='noopener noreferrer'
sx={{
textDecoration: 'none'
}}
>
<MenuItem>
{perspective.label
? perspective.label.toUpperCase()
: intl.get(`perspectives.${perspective.id}.label`).toUpperCase()}
</MenuItem>
</Box>
)
} else {
return (
<MenuItem
key={perspective.id}
component={AdapterLink}
to={getInternalLink(perspective)}
onClick={handleMobileMenuClose}
>
{intl.get(`perspectives.${perspective.id}.label`).toUpperCase()}
</MenuItem>
)
}
}
const renderDesktopTopMenuItem = perspective => {
if (has(perspective, 'externalUrl')) {
return (
<Box
component='a'
key={perspective.id}
href={perspective.externalUrl}
target='_blank'
rel='noopener noreferrer'
sx={{
textDecoration: 'none'
}}
>
<Button
sx={createAppBarButtonStyle(false)}
>
{perspective.label
? perspective.label
: intl.get(`perspectives.${perspective.id}.label`).toUpperCase()}
</Button>
</Box>
)
} else {
return (
<Button
key={perspective.id}
component={AdapterNavLink}
to={getInternalLink(perspective)}
isActive={(match, location) => location.pathname.includes(`/${perspective.id}/`)}
style={isActive => createAppBarButtonStyle(isActive)}
>
{intl.get(`perspectives.${perspective.id}.label`).toUpperCase()}
</Button>
)
}
}
const renderInfoItem = item => {
let jsx
if (item.externalLink) {
jsx = (
<Box
key={item.id}
href={intl.get(`topBar.info.${item.translatedUrl}`)}
target='_blank'
rel='noopener noreferrer'
sx={{
textDecoration: 'none'
}}
>
<MenuItem onClick={handleMobileMenuClose}>
{intl.get(`topBar.info.${item.translatedText}`).toUpperCase()}
</MenuItem>
</Box>
)
} else {
jsx = (
<MenuItem
key={item.id}
component={AdapterLink}
to={`${props.rootUrl}${item.internalLink}`}
onClick={handleMobileMenuClose}
>
{intl.get(`topBar.info.${item.translatedText}`).toUpperCase()}
</MenuItem>
)
}
return jsx
}
const renderMobileMenu = perspectives => {
const { topBar } = props.layoutConfig
const { infoDropdown } = topBar
return (
<Menu
anchorEl={mobileMoreAnchorEl}
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
open={isMobileMenuOpen}
onClose={handleMobileMenuClose}
>
{perspectives.map(perspective => perspective.hideTopPerspectiveButton ? null : renderMobileMenuItem(perspective))}
<Divider />
{renderMobileMenuItem({
id: 'feedback',
externalUrl: props.layoutConfig.topBar.feedbackLink,
label: intl.get('topBar.feedback')
})}
{infoDropdown.map(item => renderInfoItem(item))}
{topBar.externalInstructions && renderMobileMenuItem({
id: 'instructions',
externalUrl: intl.get('topBar.instructionsUrl'),
label: intl.get('topBar.instructions')
})}
{!topBar.externalInstructions &&
<MenuItem
key='instructions'
component={AdapterLink}
to={`${props.rootUrl}/instructions`}
onClick={handleMobileMenuClose}
>
{intl.get('topBar.instructions').toUpperCase()}
</MenuItem>}
</Menu>
)
}
return (
<>
<AppBar position='static'>
<Toolbar
disableGutters
sx={theme => ({
paddingLeft: theme.spacing(1.5),
paddingRight: theme.spacing(1.5)
})}
>
<Button
sx={theme => ({
paddingLeft: 0,
[theme.breakpoints.down('sm')]: {
minWidth: 48
}
})}
component={AdapterLink} to='/'
onClick={() => federatedSearchMode ? props.clientFSClearResults() : null}
>
{topBar.logoImage &&
<Box
component='img'
src={topBar.logoImage}
alt={`${intl.get('appTitle.short')} logo`}
sx={theme => ({
height: props.layoutConfig.topBar.logoImageReducedHeight || 23,
[theme.breakpoints.up(props.layoutConfig.reducedHeightBreakpoint)]: {
height: props.layoutConfig.topBar.logoImageHeight || 40
},
marginRight: theme.spacing(1)
})}
/>}
{!topBar.hideLogoText &&
<Typography
sx={theme => ({
color: '#fff',
background: theme.palette.primary.main,
whiteSpace: 'nowrap',
textTransform: props.layoutConfig.topBar.logoTextTransform,
[theme.breakpoints.down('md')]: {
fontSize: '1.5rem'
},
...(props.layoutConfig.topBar.hideLogoTextOnMobile && {
[theme.breakpoints.down('sm')]: {
display: 'none'
}
})
})}
variant='h5'
>
{props.screenSize === 'xs' ? intl.get('appTitle.mobile') : intl.get('appTitle.short')}
</Typography>}
</Button>
{topBar.logoImageSecondary &&
<a
href={topBar.logoImageSecondaryLink}
target='_blank'
rel='noopener noreferrer'
>
<Button>
<Box
component='img'
src={topBar.logoImageSecondary}
alt='logoSecondary'
sx={theme => ({
height: 26,
[theme.breakpoints.up('sm')]: {
height: 32
},
[theme.breakpoints.up(props.layoutConfig.reducedHeightBreakpoint)]: {
height: 52
}
})}
/>
</Button>
</a>}
{showSearchField &&
<TopBarSearchField
fetchFullTextResults={props.fetchFullTextResults}
clearResults={props.clearResults}
screenSize={props.screenSize}
rootUrl={rootUrl}
/>}
<Box sx={{ flexGrow: 1 }} />
<Box
sx={theme => ({
display: 'none',
[theme.breakpoints.up(props.layoutConfig.topBar.mobileMenuBreakpoint)]: {
display: 'flex'
}
})}
>
{perspectives.map((perspective, index) => perspective.hideTopPerspectiveButton ? null : renderDesktopTopMenuItem(perspective, index))}
<Box
sx={theme => ({
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
borderLeft: '2px solid white'
})}
/>
{renderDesktopTopMenuItem({
id: 'feedback',
externalUrl: props.layoutConfig.topBar.feedbackLink,
label: intl.get('topBar.feedback')
})}
<TopBarInfoButton rootUrl={props.rootUrl} layoutConfig={layoutConfig} />
{topBar.externalInstructions && renderDesktopTopMenuItem({
id: 'instructions',
externalUrl: intl.get('topBar.instructionsUrl'),
label: intl.get('topBar.instructions')
})}
{!topBar.externalInstructions &&
<Button
component={AdapterNavLink}
to={`${props.rootUrl}/instructions`}
isActive={(match, location) => location.pathname.startsWith(`${props.rootUrl}/instructions`)}
style={isActive => createAppBarButtonStyle(isActive)}
>
{intl.get('topBar.instructions')}
</Button>}
{props.layoutConfig.topBar.showLanguageButton &&
<TopBarLanguageButton
currentLocale={currentLocale}
availableLocales={availableLocales}
loadLocales={props.loadLocales}
location={props.location}
/>}
</Box>
<Box
component='a'
href='https://seco.cs.aalto.fi'
target='_blank'
rel='noopener noreferrer'
sx={theme => ({
marginLeft: theme.spacing(1),
[theme.breakpoints.down(props.layoutConfig.topBar.mobileMenuBreakpoint)]: {
display: 'none'
}
})}
>
<Button aria-label='link to Semantic Computing research group homepage'>
<Box
component='img'
src={secoLogo}
alt='Semantic Computing research group logo'
sx={theme => ({
height: 32,
[theme.breakpoints.up(props.layoutConfig.reducedHeightBreakpoint)]: {
height: 50
}
})}
/>
</Button>
</Box>
<Box
sx={theme => ({
display: 'flex',
[theme.breakpoints.up(props.layoutConfig.topBar.mobileMenuBreakpoint)]: {
display: 'none'
}
})}
>
{props.layoutConfig.topBar.showLanguageButton &&
<TopBarLanguageButton
currentLocale={currentLocale}
availableLocales={availableLocales}
loadLocales={props.loadLocales}
location={props.location}
/>}
<IconButton
aria-label='display more actions'
color='inherit'
edge='end'
onClick={handleMobileMenuOpen}
size='large'
>
<MoreIcon />
</IconButton>
</Box>
</Toolbar>
</AppBar>
{renderMobileMenu(perspectives)}
</>
)
}
Example #9
Source File: ResourcePage.jsx From Edlib with GNU General Public License v3.0 | 4 votes |
ResourcePage = ({ filters, showDeleteButton = false }) => {
const { t } = useTranslation();
const theme = useTheme();
const forceGridView = useMediaQuery(theme.breakpoints.down(1400));
const [filtersExpanded, setFiltersExpanded] = React.useState(false);
const [sortingOrder, setSortingOrder] = React.useState(useDefaultOrder());
const [page, setPage] = React.useState(0);
const [pageSize, setPageSize] = React.useState(40);
const [_isGridView, setIsGridView] = React.useState(false);
const filterUtils = FilterUtils(filters);
const isGridView = forceGridView || _isGridView;
const { error, loading, resources, pagination, refetch, filterCount } =
useGetResources(
React.useMemo(
() => ({
limit: pageSize,
offset: page * pageSize,
resourceCapabilities: ['view'],
orderBy: sortingOrder,
...(filters && filters.requestData),
}),
[page, sortingOrder, filters && filters.requestData, pageSize]
)
);
React.useEffect(() => {
setPage(0);
}, [sortingOrder, filters.requestData]);
const setSearch = React.useCallback(
(searchText) => {
filters.setSearchInput(searchText);
if (sortingOrder !== resourceOrders.RELEVANT_DESC) {
setSortingOrder(resourceOrders.RELEVANT_DESC);
}
},
[filters, sortingOrder, setSortingOrder]
);
const sortOrderDropDown = (
<FormControl variant="outlined">
<InputLabel>{t('Sortering')}</InputLabel>
<Select
MenuProps={{
style: { zIndex: 2051 },
anchorOrigin: {
vertical: 'bottom',
horizontal: 'center',
},
transformOrigin: {
vertical: 'top',
horizontal: 'center',
},
}}
value={sortingOrder}
onChange={(e) => setSortingOrder(e.target.value)}
label={getOrderText(t, sortingOrder)}
>
{[
resourceOrders.RELEVANT_DESC,
resourceOrders.VIEWS_DESC,
resourceOrders.VIEWS_ASC,
resourceOrders.UPDATED_AT_DESC,
resourceOrders.UPDATED_AT_ASC,
].map((value, index) => (
<MenuItem key={index} value={value}>
{getOrderText(t, value)}
</MenuItem>
))}
</Select>
</FormControl>
);
return (
<StyledResourcePage>
<Box
sx={[
{
backgroundColor: 'white',
boxShadow: '5px 0 5px 0 rgba(0, 0, 0, 0.16)',
overflowY: 'auto',
position: {
xs: 'absolute',
md: 'initial',
},
right: {
xs: '110%',
md: 'initial',
},
zIndex: {
xs: 2,
md: 'initial',
},
},
filtersExpanded && {
width: '100vw',
right: 'unset',
left: 0,
},
]}
>
<ResourceFilters filters={filters} filterCount={filterCount} />
</Box>
<Box
onClick={() => setFiltersExpanded(false)}
sx={[
{
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
zIndex: 1,
cursor: 'pointer',
},
filtersExpanded && {
display: {
xs: 'block',
md: 'none',
},
},
!filtersExpanded && {
display: 'none',
},
]}
/>
<div className="pageContent">
<div className="contentOptions">
<Box display="flex" paddingRight={1}>
<Box
paddingRight={1}
style={{
width: 400,
}}
>
<TextField
fullWidth
label={t('Søk')}
variant="outlined"
value={filters.searchInput}
onChange={(e) => setSearch(e.target.value)}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<Icon>
<SearchIcon />
</Icon>
</InputAdornment>
),
}}
/>
</Box>
<div
style={{
width: 200,
}}
>
<LanguageDropdown
language={
filters.languages.length !== 0
? filters.languages[0]
: null
}
setLanguage={(value) =>
filters.languages.setValue(
value ? [value] : []
)
}
/>
</div>
</Box>
<div>{sortOrderDropDown}</div>
</div>
<Box
pt={1}
sx={{
display: {
xs: 'block',
md: 'none',
},
}}
>
<Button
color="primary"
variant="contained"
onClick={() => setFiltersExpanded(!filtersExpanded)}
startIcon={<TuneIcon />}
>
{t('filter', { count: 2 })}
</Button>
</Box>
<Box
display="flex"
flexDirection="row"
justifyContent="space-between"
pt={1}
>
<Box>
<FilterChips
chips={filterUtils.getChipsFromFilters()}
/>
</Box>
<Box>
{!forceGridView && (
<IconButton
onClick={() => setIsGridView(!isGridView)}
size="large"
>
{isGridView ? <ListIcon /> : <ViewModuleIcon />}
</IconButton>
)}
</Box>
</Box>
<Content>
<div style={{ marginTop: 20 }}>
{loading && <Spinner />}
{error && <div>{t('Noe skjedde')}</div>}
{!loading && !error && resources && !isGridView && (
<ResourceTable
totalCount={pagination.totalCount}
resources={resources}
refetch={refetch}
showDeleteButton={showDeleteButton}
sortingOrder={sortingOrder}
setSortingOrder={setSortingOrder}
/>
)}
{!loading && !error && resources && isGridView && (
<CardView
totalCount={pagination.totalCount}
resources={resources}
refetch={refetch}
showDeleteButton={showDeleteButton}
/>
)}
</div>
{pagination && (
<PaginationWrapper>
<TablePagination
component="div"
count={pagination.totalCount}
page={page}
onPageChange={(e, page) => {
setPage(page);
}}
rowsPerPage={pageSize}
onRowsPerPageChange={(e, pageSize) => {
setPageSize(pageSize);
setPage(0);
}}
rowsPerPageOptions={[40]}
/>
</PaginationWrapper>
)}
</Content>
</div>
</StyledResourcePage>
);
}
Example #10
Source File: NavSection.js From Django-REST-Framework-React-BoilerPlate with MIT License | 4 votes |
function NavItem({ item, active }) {
const theme = useTheme();
const isActiveRoot = active(item.path);
const { title, path, icon, info, children } = item;
const [open, setOpen] = useState(isActiveRoot);
const handleOpen = () => {
setOpen((prev) => !prev);
};
const activeRootStyle = {
color: 'primary.main',
fontWeight: 'fontWeightMedium',
bgcolor: alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
};
const activeSubStyle = {
color: 'text.primary',
fontWeight: 'fontWeightMedium',
};
if (children) {
return (
<>
<ListItemStyle
onClick={handleOpen}
sx={{
...(isActiveRoot && activeRootStyle),
}}
>
<ListItemIconStyle>{icon && icon}</ListItemIconStyle>
<ListItemText disableTypography primary={title} />
{info && info}
<Iconify
icon={open ? 'eva:arrow-ios-downward-fill' : 'eva:arrow-ios-forward-fill'}
sx={{ width: 16, height: 16, ml: 1 }}
/>
</ListItemStyle>
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{children.map((item) => {
const { title, path } = item;
const isActiveSub = active(path);
return (
<ListItemStyle
key={title}
component={RouterLink}
to={path}
sx={{
...(isActiveSub && activeSubStyle),
}}
>
<ListItemIconStyle>
<Box
component="span"
sx={{
width: 4,
height: 4,
display: 'flex',
borderRadius: '50%',
alignItems: 'center',
justifyContent: 'center',
bgcolor: 'text.disabled',
transition: (theme) => theme.transitions.create('transform'),
...(isActiveSub && {
transform: 'scale(2)',
bgcolor: 'primary.main',
}),
}}
/>
</ListItemIconStyle>
<ListItemText disableTypography primary={title} />
</ListItemStyle>
);
})}
</List>
</Collapse>
</>
);
}
return (
<ListItemStyle
component={RouterLink}
to={path}
sx={{
...(isActiveRoot && activeRootStyle),
}}
>
<ListItemIconStyle>{icon && icon}</ListItemIconStyle>
<ListItemText disableTypography primary={title} />
{info && info}
</ListItemStyle>
);
}
Example #11
Source File: BaseOptionChart.js From Django-REST-Framework-React-BoilerPlate with MIT License | 4 votes |
export default function BaseOptionChart() {
const theme = useTheme();
const LABEL_TOTAL = {
show: true,
label: 'Total',
color: theme.palette.text.secondary,
...theme.typography.subtitle2
};
const LABEL_VALUE = {
offsetY: 8,
color: theme.palette.text.primary,
...theme.typography.h3
};
return {
// Colors
colors: [
theme.palette.primary.main,
theme.palette.chart.yellow[0],
theme.palette.chart.blue[0],
theme.palette.chart.violet[0],
theme.palette.chart.green[0],
theme.palette.chart.red[0]
],
// Chart
chart: {
toolbar: { show: false },
zoom: { enabled: false },
// animations: { enabled: false },
foreColor: theme.palette.text.disabled,
fontFamily: theme.typography.fontFamily
},
// States
states: {
hover: {
filter: {
type: 'lighten',
value: 0.04
}
},
active: {
filter: {
type: 'darken',
value: 0.88
}
}
},
// Fill
fill: {
opacity: 1,
gradient: {
type: 'vertical',
shadeIntensity: 0,
opacityFrom: 0.4,
opacityTo: 0,
stops: [0, 100]
}
},
// Datalabels
dataLabels: { enabled: false },
// Stroke
stroke: {
width: 3,
curve: 'smooth',
lineCap: 'round'
},
// Grid
grid: {
strokeDashArray: 3,
borderColor: theme.palette.divider
},
// Xaxis
xaxis: {
axisBorder: { show: false },
axisTicks: { show: false }
},
// Markers
markers: {
size: 0,
strokeColors: theme.palette.background.paper
},
// Tooltip
tooltip: {
x: {
show: false
}
},
// Legend
legend: {
show: true,
fontSize: 13,
position: 'top',
horizontalAlign: 'right',
markers: {
radius: 12
},
fontWeight: 500,
itemMargin: { horizontal: 12 },
labels: {
colors: theme.palette.text.primary
}
},
// plotOptions
plotOptions: {
// Bar
bar: {
columnWidth: '28%',
borderRadius: 4
},
// Pie + Donut
pie: {
donut: {
labels: {
show: true,
value: LABEL_VALUE,
total: LABEL_TOTAL
}
}
},
// Radialbar
radialBar: {
track: {
strokeWidth: '100%',
background: theme.palette.grey[500_16]
},
dataLabels: {
value: LABEL_VALUE,
total: LABEL_TOTAL
}
},
// Radar
radar: {
polygons: {
fill: { colors: ['transparent'] },
strokeColors: theme.palette.divider,
connectorColors: theme.palette.divider
}
},
// polarArea
polarArea: {
rings: {
strokeColor: theme.palette.divider
},
spokes: {
connectorColors: theme.palette.divider
}
}
},
// Responsive
responsive: [
{
// sm
breakpoint: theme.breakpoints.values.sm,
options: {
plotOptions: { bar: { columnWidth: '40%' } }
}
},
{
// md
breakpoint: theme.breakpoints.values.md,
options: {
plotOptions: { bar: { columnWidth: '32%' } }
}
}
]
};
}