index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MarkdownElement.js | import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { alpha, darken, styled } from '@mui/material/styles';
import {
brandingDarkTheme as darkTheme,
brandingLightTheme as lightTheme,
} from 'docs/src/modules/brandingTheme';
const Root = styled('div')(
({ theme }) => ({
...lightTheme.typography.body1,
lineHeight: 1.5625, // Increased compared to the 1.5 default to make the docs easier to read.
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
'& strong': {
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
},
wordBreak: 'break-word',
'& pre': {
lineHeight: 1.5, // Developers likes when the code is dense.
margin: theme.spacing(2, 'auto'),
padding: theme.spacing(2),
backgroundColor: '#0F1924', // a special, one-off, color tailored for the code blocks using MUI's branding theme blue palette as the starting point. It has a less saturaded color but still maintaining a bit of the blue tint.
color: '#f8f8f2',
colorScheme: 'dark',
borderRadius: `var(--muidocs-shape-borderRadius, ${
theme.shape?.borderRadius ?? lightTheme.shape.borderRadius
}px)`,
border: '1px solid',
borderColor: `var(--muidocs-palette-primaryDark-700, ${lightTheme.palette.primaryDark[700]})`,
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
fontSize: lightTheme.typography.pxToRem(13),
maxWidth: 'calc(100vw - 32px)',
maxHeight: '400px',
[lightTheme.breakpoints.up('md')]: {
maxWidth: 'calc(100vw - 32px - 16px)',
},
},
'& code': {
...lightTheme.typography.body2,
fontFamily: lightTheme.typography.fontFamilyCode,
fontWeight: 400,
WebkitFontSmoothing: 'subpixel-antialiased',
},
'& pre > code': {
// Reset for Safari
// https://github.com/necolas/normalize.css/blob/master/normalize.css#L102
fontSize: 'inherit',
},
// inline code block
'& :not(pre) > code': {
display: 'inline-block',
padding: '0 4px',
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
backgroundColor: `var(--muidocs-palette-grey-50, ${lightTheme.palette.grey[50]})`,
border: '1px solid',
borderColor: `var(--muidocs-palette-grey-200, ${lightTheme.palette.grey[200]})`,
borderRadius: 5,
fontSize: lightTheme.typography.pxToRem(13),
direction: 'ltr /*! @noflip */',
},
'& h1': {
...lightTheme.typography.h3,
fontSize: lightTheme.typography.pxToRem(36),
fontFamily: `"General Sans", ${lightTheme.typography.fontFamilySystem}`,
margin: '10px 0',
color: `var(--muidocs-palette-primaryDark-900, ${lightTheme.palette.primaryDark[900]})`,
fontWeight: 600,
letterSpacing: -0.2,
},
'& .description': {
...lightTheme.typography.subtitle1,
fontWeight: 400,
margin: '0 0 28px',
},
'& .component-tabs': {
margin: '0 0 40px',
},
'& h2': {
...lightTheme.typography.h5,
fontFamily: `"General Sans", ${lightTheme.typography.fontFamilySystem}`,
fontSize: theme.typography.pxToRem(26),
fontWeight: lightTheme.typography.fontWeightSemiBold,
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[900]})`,
margin: '40px 0 4px',
},
'& h3': {
...lightTheme.typography.h6,
fontFamily: `"General Sans", ${lightTheme.typography.fontFamilySystem}`,
fontSize: theme.typography.pxToRem(20),
fontWeight: lightTheme.typography.fontWeightSemiBold,
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[900]})`,
margin: '24px 0 4px',
},
'& h4': {
...lightTheme.typography.subtitle1,
fontFamily: `"General Sans", ${lightTheme.typography.fontFamilySystem}`,
fontWeight: lightTheme.typography.fontWeightSemiBold,
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[900]})`,
margin: '20px 0 6px',
},
'& h5': {
...lightTheme.typography.subtitle2,
fontFamily: `"General Sans", ${lightTheme.typography.fontFamilySystem}`,
fontWeight: lightTheme.typography.fontWeightSemiBold,
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[900]})`,
margin: '20px 0 8px',
},
'& p': {
marginTop: 0,
marginBottom: 16,
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[900]})`,
},
'& ul, & ol': {
paddingLeft: 30,
marginTop: 0,
marginBottom: 16,
'& ul, & ol': {
marginBottom: 6,
},
},
'& h1, & h2, & h3, & h4': {
display: 'flex',
alignItems: 'center',
gap: 6,
'& code': {
fontSize: 'inherit',
lineHeight: 'inherit',
// Remove scroll on small screens.
wordBreak: 'break-all',
},
'& .anchor-link': {
// To prevent the link to get the focus.
display: 'inline-flex',
visibility: 'hidden',
},
'& a:not(.anchor-link):hover': {
color: 'currentColor',
border: 'none',
boxShadow: '0 1px 0 0 currentColor',
textDecoration: 'none',
},
'& .anchor-link, & .comment-link': {
cursor: 'pointer',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
textAlign: 'center',
marginLeft: 4,
height: 26,
width: 26,
backgroundColor: `var(--muidocs-palette-primary-50, ${lightTheme.palette.primary[50]})`,
border: '1px solid',
borderColor: `var(--muidocs-palette-divider, ${lightTheme.palette.divider})`,
borderRadius: 8,
color: `var(--muidocs-palette-text-secondary, ${lightTheme.palette.text.secondary})`,
'&:hover': {
backgroundColor: alpha(lightTheme.palette.primary[100], 0.4),
borderColor: `var(--muidocs-palette-primary-100, ${lightTheme.palette.primary[100]})`,
color: `var(--muidocs-palette-primary-main, ${lightTheme.palette.primary.main})`,
},
'& svg': {
height: '14px',
width: '14px',
fill: 'currentColor',
pointerEvents: 'none',
},
},
'&:hover .anchor-link': {
visibility: 'visible',
},
'& .comment-link': {
display: 'none', // So we can have the comment button opt-in.
marginLeft: 'auto',
transition: theme.transitions.create('opacity', {
duration: theme.transitions.duration.shortest,
}),
'& svg': {
verticalAlign: 'middle',
fill: 'currentColor',
},
},
},
'& h1 code, & h2 code, & h3 code': {
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[900]})`,
},
'& h1 code': {
fontWeight: lightTheme.typography.fontWeightSemiBold,
},
'& h2 code': {
fontSize: lightTheme.typography.pxToRem(24),
fontWeight: lightTheme.typography.fontWeightSemiBold,
},
'& h3 code': {
fontSize: lightTheme.typography.pxToRem(18),
},
'& table': {
// Trade display table for scroll overflow
display: 'block',
wordBreak: 'normal',
overflowX: 'auto',
WebkitOverflowScrolling: 'touch',
borderCollapse: 'collapse',
marginBottom: '20px',
borderSpacing: 0,
'& .prop-name, & .prop-type, & .prop-default, & .slot-name, & .slot-defaultClass, & .slot-default':
{
fontWeight: 400,
fontFamily: lightTheme.typography.fontFamilyCode,
WebkitFontSmoothing: 'subpixel-antialiased',
fontSize: lightTheme.typography.pxToRem(13),
},
'& .required': {
color: '#006500',
},
'& .optional': {
color: '#45529f',
},
'& .prop-type, & .slot-defaultClass': {
color: '#932981',
},
'& .prop-default, & .slot-default': {
borderBottom: `1px dotted var(--muidocs-palette-divider, ${lightTheme.palette.divider})`,
},
},
'& td': {
...theme.typography.body2,
borderBottom: `1px solid var(--muidocs-palette-divider, ${lightTheme.palette.divider})`,
paddingRight: 20,
paddingTop: 16,
paddingBottom: 16,
color: `var(--muidocs-palette-text-secondary, ${lightTheme.palette.text.secondary})`,
},
'& td code': {
lineHeight: 1.6,
},
'& th': {
fontSize: theme.typography.pxToRem(14),
lineHeight: theme.typography.pxToRem(24),
fontWeight: 500,
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
whiteSpace: 'pre',
borderBottom: `1px solid var(--muidocs-palette-divider, ${lightTheme.palette.divider})`,
paddingRight: 20,
paddingTop: 12,
paddingBottom: 12,
},
'& blockquote': {
position: 'relative',
padding: '0 16px',
margin: 0,
borderLeft: '1.5px solid',
borderColor: `var(--muidocs-palette-grey-200, ${lightTheme.palette.grey[200]})`,
'& p': {
fontStyle: 'italic',
fontSize: theme.typography.pxToRem(13),
fontFamily: lightTheme.typography.fontFamilyCode,
fontWeight: lightTheme.typography.fontWeightMedium,
textIndent: 20,
},
':before': {
position: 'absolute',
content: 'open-quote',
color: `var(--muidocs-palette-grey-300, ${lightTheme.palette.grey[300]})`,
fontSize: '2.5rem',
top: 8,
marginLeft: -6,
lineHeight: 0.5,
},
},
'& .MuiCallout-root': {
display: 'flex',
gap: 12,
padding: '16px',
margin: '16px 0',
border: '1px solid',
color: `var(--muidocs-palette-text-secondary, ${lightTheme.palette.text.secondary})`,
borderColor: `var(--muidocs-palette-grey-100, ${lightTheme.palette.grey[100]})`,
borderRadius: `var(--muidocs-shape-borderRadius, ${
theme.shape?.borderRadius ?? lightTheme.shape.borderRadius
}px)`,
'&>code': {
height: 'fit-content',
backgroundColor: `var(--muidocs-palette-grey-100, ${lightTheme.palette.grey[100]})`,
borderColor: `var(--muidocs-palette-grey-300, ${lightTheme.palette.grey[300]})`,
},
'& .MuiCallout-content': {
minWidth: 0, // Allows content to shrink. Useful when callout contains code block
flexGrow: 1,
display: 'flex',
flexDirection: 'column',
gap: 6,
'&>p, ul': {
marginBottom: 0,
},
'& .MuiCode-root': {
'&>pre': {
margin: 0,
marginTop: 4,
},
},
'&>ul': {
paddingLeft: 22,
},
},
'&>svg': {
marginTop: 2,
width: 20,
height: 20,
flexShrink: 0,
},
'& > ul, & > p': {
'&:last-child': {
margin: 0,
},
},
'& ul, li, p': {
color: 'inherit',
},
'&.MuiCallout-error': {
color: `var(--muidocs-palette-error-900, ${lightTheme.palette.error[900]})`,
backgroundColor: `var(--muidocs-palette-error-50, ${lightTheme.palette.error[50]})`,
borderColor: `var(--muidocs-palette-error-100, ${lightTheme.palette.error[100]})`,
'& strong': {
color: `var(--muidocs-palette-error-800, ${lightTheme.palette.error[800]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-error-500, ${lightTheme.palette.error[600]})`,
},
'& a': {
color: `var(--muidocs-palette-error-800, ${lightTheme.palette.error[800]})`,
textDecorationColor: alpha(lightTheme.palette.error.main, 0.4),
'&:hover': {
textDecorationColor: 'inherit',
},
},
},
'&.MuiCallout-info': {
color: `var(--muidocs-palette-primary-900, ${lightTheme.palette.primary[900]})`,
backgroundColor: `var(--muidocs-palette-grey-50, ${lightTheme.palette.grey[50]})`,
borderColor: `var(--muidocs-palette-grey-100, ${lightTheme.palette.grey[100]})`,
'& strong': {
color: `var(--muidocs-palette-primary-800, ${lightTheme.palette.primary[800]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-grey-600, ${lightTheme.palette.grey[600]})`,
},
},
'&.MuiCallout-success': {
color: `var(--muidocs-palette-success-900, ${lightTheme.palette.success[900]})`,
backgroundColor: `var(--muidocs-palette-success-50, ${lightTheme.palette.success[50]})`,
borderColor: `var(--muidocs-palette-success-100, ${lightTheme.palette.success[100]})`,
'& strong': {
color: `var(--muidocs-palette-success-900, ${lightTheme.palette.success[900]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-success-600, ${lightTheme.palette.success[600]})`,
},
'& a': {
color: `var(--muidocs-palette-success-900, ${lightTheme.palette.success[900]})`,
textDecorationColor: alpha(lightTheme.palette.success.main, 0.4),
'&:hover': {
textDecorationColor: 'inherit',
},
},
},
'&.MuiCallout-warning': {
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[900]})`,
backgroundColor: alpha(lightTheme.palette.warning[50], 0.5),
borderColor: `var(--muidocs-palette-warning-200, ${lightTheme.palette.warning[200]})`,
'& strong': {
color: `var(--muidocs-palette-warning-800, ${lightTheme.palette.warning[800]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-warning-600, ${lightTheme.palette.warning[600]})`,
},
'& a': {
color: `var(--muidocs-palette-warning-800, ${lightTheme.palette.warning[800]})`,
textDecorationColor: alpha(lightTheme.palette.warning.main, 0.4),
'&:hover': {
textDecorationColor: 'inherit',
},
},
},
},
'& a, & a code': {
// Style taken from the Link component
color: `var(--muidocs-palette-primary-600, ${lightTheme.palette.primary[600]})`,
textDecoration: 'underline',
textDecorationColor: alpha(lightTheme.palette.primary.main, 0.4),
'&:hover': {
textDecorationColor: 'inherit',
},
},
'& a code': {
color: darken(lightTheme.palette.primary.main, 0.04),
},
'& img, & video': {
// Use !important so that inline style on <img> or <video> can't win.
// This avoid horizontal overflows on mobile.
maxWidth: '100% !important',
// Avoid the image to be fixed height, so it can respect the aspect ratio.
height: 'auto',
},
'& img': {
// Avoid layout jump
display: 'inline-block',
// Avoid very sharp edges
borderRadius: 2,
},
'& hr': {
height: 1,
margin: theme.spacing(5, 0),
border: 0,
flexShrink: 0,
backgroundColor: `var(--muidocs-palette-divider, ${lightTheme.palette.divider})`,
},
'& kbd.key': {
padding: 6,
display: 'inline-block',
whiteSpace: 'nowrap',
margin: '0 1px',
fontFamily: lightTheme.typography.fontFamilyCode,
fontSize: lightTheme.typography.pxToRem(11),
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
lineHeight: '10px',
verticalAlign: 'middle',
borderRadius: 6,
border: `1px solid var(--muidocs-palette-grey-300, ${lightTheme.palette.grey[300]})`,
backgroundColor: `var(--muidocs-palette-grey-50, ${lightTheme.palette.grey[50]})`,
boxShadow: `inset 0 -2px 0 var(--muidocs-palette-grey-200, ${lightTheme.palette.grey[200]})`,
},
'& details': {
marginBottom: theme.spacing(1.5),
padding: theme.spacing(0.5, 0, 0.5, 1),
'& pre': {
marginTop: theme.spacing(1),
},
},
'& summary': {
cursor: 'pointer',
},
'& .MuiCode-root': {
direction: 'ltr /*! @noflip */',
position: 'relative',
// Font size reset to fix a bug with Safari 16.0 when letterSpacing is set
fontSize: 10,
},
'& .MuiCode-copy': {
display: 'inline-flex',
flexDirection: 'row-reverse',
alignItems: 'center',
width: 26,
height: 26,
cursor: 'pointer',
position: 'absolute',
top: theme.spacing(1),
right: theme.spacing(1),
padding: theme.spacing(0.5),
fontFamily: 'inherit',
fontWeight: 500,
borderRadius: 6,
border: 'none',
backgroundColor: '#0F1924', // using the code block one-off background color (defined in line 23)
color: '#FFF',
transition: theme.transitions.create(['background', 'borderColor', 'display'], {
duration: theme.transitions.duration.shortest,
}),
'& svg': {
userSelect: 'none',
width: theme.typography.pxToRem(16),
height: theme.typography.pxToRem(16),
display: 'inline-block',
fill: 'currentcolor',
flexShrink: 0,
fontSize: '18px',
margin: 'auto',
opacity: 0.6,
},
'& .MuiCode-copied-icon': {
display: 'none',
},
'&:hover, &:focus': {
'& svg': {
opacity: 1,
},
backgroundColor: lightTheme.palette.primaryDark[500],
'& .MuiCode-copyKeypress': {
display: 'block',
// Approximate no hover capabilities with no keyboard
// https://github.com/w3c/csswg-drafts/issues/3871
'@media (any-hover: none)': {
display: 'none',
},
},
},
'& .MuiCode-copyKeypress': {
display: 'none',
position: 'absolute',
right: 26,
},
'&[data-copied]': {
// style of the button when it is in copied state.
borderColor: lightTheme.palette.primary[700],
color: '#fff',
backgroundColor: lightTheme.palette.primaryDark[600],
'& .MuiCode-copy-icon': {
display: 'none',
},
'& .MuiCode-copied-icon': {
display: 'block',
},
},
'&:focus-visible': {
outline: '2px solid',
outlineOffset: 2,
outlineColor: lightTheme.palette.primaryDark[500],
},
},
'& .MuiCode-copyKeypress': {
pointerEvents: 'none',
userSelect: 'none',
marginRight: theme.spacing(1.2),
marginBottom: theme.spacing(0.2),
whiteSpace: 'nowrap',
opacity: 0.6,
},
'& li': {
// tight lists https://spec.commonmark.org/0.30/#tight
marginBottom: 4,
'& pre': {
marginTop: theme.spacing(1),
},
// loose lists https://spec.commonmark.org/0.30/#loose
'& > p': {
marginBottom: theme.spacing(1),
},
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
color: 'rgb(255, 255, 255)',
'& :not(pre) > code': {
// inline code block
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
borderColor: alpha(darkTheme.palette.primaryDark[600], 0.6),
backgroundColor: `var(--muidocs-palette-grey-900, ${darkTheme.palette.grey[900]})`,
},
'& strong': {
color: `var(--muidocs-palette-grey-200, ${darkTheme.palette.grey[200]})`,
},
'& hr': {
backgroundColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
},
'& h1': {
color: `var(--muidocs-palette-grey-50, ${darkTheme.palette.grey[50]})`,
},
'& h2': {
color: `var(--muidocs-palette-grey-100, ${darkTheme.palette.grey[100]})`,
},
'& h3': {
color: `var(--muidocs-palette-grey-200, ${darkTheme.palette.grey[200]})`,
},
'& h4': {
color: `var(--muidocs-palette-grey-300, ${darkTheme.palette.grey[300]})`,
},
'& h5': {
color: `var(--muidocs-palette-grey-300, ${darkTheme.palette.grey[300]})`,
},
'& p, & ul, & ol': {
color: `var(--muidocs-palette-grey-400, ${darkTheme.palette.grey[400]})`,
},
'& h1, & h2, & h3, & h4': {
'&:hover .anchor-link, & .comment-link': {
color: `var(--muidocs-palette-primary-200, ${darkTheme.palette.primary[200]})`,
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
backgroundColor: alpha(darkTheme.palette.primary[900], 0.5),
'&:hover': {
borderColor: `var(--muidocs-palette-primary-900, ${darkTheme.palette.primary[900]})`,
backgroundColor: alpha(darkTheme.palette.primary[900], 0.6),
color: `var(--muidocs-palette-primary-100, ${darkTheme.palette.primary[100]})`,
},
},
},
'& h1 code, & h2 code, & h3 code': {
color: `var(--muidocs-palette-grey-100, ${darkTheme.palette.grey[100]})`,
},
'& table': {
'& .required': {
color: '#a5ffa5',
},
'& .optional': {
color: '#a5b3ff',
},
'& .prop-type, & .slot-defaultClass': {
color: '#ffb6ec',
},
'& .prop-default, & .slot-default': {
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
},
},
'& td': {
color: `var(--muidocs-palette-text-secondary, ${darkTheme.palette.text.secondary})`,
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
},
'& th': {
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
},
'& blockquote': {
borderColor: `var(--muidocs-palette-primaryDark-700, ${darkTheme.palette.primaryDark[700]})`,
':before': {
color: `var(--muidocs-palette-primaryDark-500, ${darkTheme.palette.primaryDark[500]})`,
},
},
'& .MuiCallout-root': {
borderColor: `var(--muidocs-palette-primaryDark-700, ${darkTheme.palette.primaryDark[700]})`,
'&>code': {
height: 'fit-content',
backgroundColor: `var(--muidocs-palette-primaryDark-600, ${lightTheme.palette.primaryDark[600]})`,
borderColor: `var(--muidocs-palette-primaryDark-500, ${lightTheme.palette.primaryDark[500]})`,
},
'&.MuiCallout-error': {
color: `var(--muidocs-palette-error-50, ${darkTheme.palette.error[50]})`,
backgroundColor: alpha(darkTheme.palette.error[700], 0.2),
borderColor: alpha(lightTheme.palette.error[600], 0.3),
'& strong': {
color: `var(--muidocs-palette-error-300, ${darkTheme.palette.error[300]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-error-500, ${darkTheme.palette.error[500]})`,
},
'& a': {
color: `var(--muidocs-palette-error-200, ${darkTheme.palette.error[200]})`,
},
},
'&.MuiCallout-info': {
color: `var(--muidocs-palette-primary-50, ${darkTheme.palette.primary[50]})`,
backgroundColor: alpha(darkTheme.palette.grey[700], 0.2),
borderColor: `var(--muidocs-palette-grey-800, ${darkTheme.palette.grey[800]})`,
'& strong': {
color: `var(--muidocs-palette-primary-200, ${darkTheme.palette.primary[200]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-grey-400, ${darkTheme.palette.grey[400]})`,
},
},
'&.MuiCallout-success': {
color: `var(--muidocs-palette-success-50, ${darkTheme.palette.success[50]})`,
backgroundColor: alpha(darkTheme.palette.success[700], 0.15),
borderColor: alpha(lightTheme.palette.success[600], 0.3),
'& strong': {
color: `var(--muidocs-palette-success-200, ${darkTheme.palette.success[200]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-success-500, ${darkTheme.palette.success[500]})`,
},
'& a': {
color: `var(--muidocs-palette-success-100, ${darkTheme.palette.success[100]})`,
},
},
'&.MuiCallout-warning': {
color: `var(--muidocs-palette-warning-50, ${darkTheme.palette.warning[50]})`,
backgroundColor: alpha(darkTheme.palette.warning[700], 0.15),
borderColor: alpha(darkTheme.palette.warning[600], 0.3),
'& strong': {
color: `var(--muidocs-palette-warning-200, ${darkTheme.palette.warning[200]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-warning-400, ${darkTheme.palette.warning[400]})`,
},
'& a': {
color: `var(--muidocs-palette-warning-100, ${darkTheme.palette.warning[100]})`,
},
},
},
'& a, & a code': {
color: `var(--muidocs-palette-primary-300, ${darkTheme.palette.primary[300]})`,
},
'& a code': {
color: `var(--muidocs-palette-primary-light, ${darkTheme.palette.primary.light})`,
},
'& kbd.key': {
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
backgroundColor: `var(--muidocs-palette-primaryDark-800, ${darkTheme.palette.primaryDark[800]})`,
border: `1px solid var(--muidocs-palette-primaryDark-600, ${darkTheme.palette.primaryDark[600]})`,
boxShadow: `inset 0 -2px 0 var(--muidocs-palette-primaryDark-700, ${darkTheme.palette.primaryDark[700]})`,
},
},
}),
);
const MarkdownElement = React.forwardRef(function MarkdownElement(props, ref) {
const { className, renderedMarkdown, ...other } = props;
const more = {};
if (typeof renderedMarkdown === 'string') {
// workaround for https://github.com/facebook/react/issues/17170
// otherwise we could just set `dangerouslySetInnerHTML={undefined}`
more.dangerouslySetInnerHTML = { __html: renderedMarkdown };
}
return <Root className={clsx('markdown-body', className)} {...more} {...other} ref={ref} />;
});
MarkdownElement.propTypes = {
className: PropTypes.string,
renderedMarkdown: PropTypes.string,
};
export default MarkdownElement;
| 5,300 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MarkdownLinks.js | import * as React from 'react';
import Router from 'next/router';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
export function samePageLinkNavigation(event) {
if (
event.defaultPrevented ||
event.button !== 0 || // ignore everything but left-click
event.metaKey ||
event.ctrlKey ||
event.altKey ||
event.shiftKey
) {
return true;
}
return false;
}
/**
* @param {MouseEvent} event
*/
function handleClick(event) {
let activeElement = event.target;
while (activeElement?.nodeType === Node.ELEMENT_NODE && activeElement.nodeName !== 'A') {
activeElement = activeElement.parentElement;
}
// Ignore non internal link clicks
if (
activeElement === null ||
activeElement.nodeName !== 'A' ||
activeElement.getAttribute('target') === '_blank' ||
activeElement.getAttribute('data-no-markdown-link') === 'true' ||
activeElement.getAttribute('href').indexOf('/') !== 0
) {
return;
}
// Ignore click meant for native link handling, e.g. open in new tab
if (samePageLinkNavigation(event)) {
return;
}
event.preventDefault();
const as = activeElement.getAttribute('href');
const canonicalPathname = pathnameToLanguage(as).canonicalPathname;
Router.push(canonicalPathname, as);
}
export default function MarkdownLinks() {
React.useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.addEventListener('click', handleClick);
};
}, []);
return null;
}
| 5,301 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MaterialDesignIcon.js | import * as React from 'react';
import { createSvgIcon } from '@mui/material/utils';
export default createSvgIcon(
<g fill="none" fillRule="evenodd">
<circle fill="#737373" cx="12" cy="12" r="12" />
<path fill="#BDBDBD" d="M4 4h16v16H4z" />
<path fill="#FFF" d="M12 20l8-16H4z" />
</g>,
'MaterialDesign',
);
| 5,302 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MaterialFreeTemplatesCollection.js | /* eslint-disable material-ui/no-hardcoded-labels */
import * as React from 'react';
import NextLink from 'next/link';
import { alpha } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import CardMedia from '@mui/material/CardMedia';
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Link from '@mui/material/Link';
import Visibility from '@mui/icons-material/Visibility';
import CodeRoundedIcon from '@mui/icons-material/CodeRounded';
import { useTranslate } from 'docs/src/modules/utils/i18n';
const sourcePrefix = `${process.env.SOURCE_CODE_REPO}/tree/v${process.env.LIB_VERSION}`;
function layouts(t) {
return [
{
title: t('dashboardTitle'),
description: t('dashboardDescr'),
src: '/static/images/templates/dashboard.png',
href: '/material-ui/getting-started/templates/dashboard/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/dashboard`,
},
{
title: t('signInTitle'),
description: t('signInDescr'),
src: '/static/images/templates/sign-in.png',
href: '/material-ui/getting-started/templates/sign-in/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/sign-in`,
},
{
title: t('signInSideTitle'),
description: t('signInSideDescr'),
src: '/static/images/templates/sign-in-side.png',
href: '/material-ui/getting-started/templates/sign-in-side/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/sign-in-side`,
},
{
title: t('signUpTitle'),
description: t('signUpDescr'),
src: '/static/images/templates/sign-up.png',
href: '/material-ui/getting-started/templates/sign-up/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/sign-up`,
},
{
title: t('blogTitle'),
description: t('blogDescr'),
src: '/static/images/templates/blog.png',
href: '/material-ui/getting-started/templates/blog/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/blog`,
},
{
title: t('checkoutTitle'),
description: t('checkoutDescr'),
src: '/static/images/templates/checkout.png',
href: '/material-ui/getting-started/templates/checkout/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/checkout`,
},
{
title: t('albumTitle'),
description: t('albumDescr'),
src: '/static/images/templates/album.png',
href: '/material-ui/getting-started/templates/album/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/album`,
},
{
title: t('pricingTitle'),
description: t('pricingDescr'),
src: '/static/images/templates/pricing.png',
href: '/material-ui/getting-started/templates/pricing/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/pricing`,
},
{
title: t('stickyFooterTitle'),
description: t('stickyFooterDescr'),
src: '/static/images/templates/sticky-footer.png',
href: '/material-ui/getting-started/templates/sticky-footer/',
source: `${sourcePrefix}/docs/data/material/getting-started/templates/sticky-footer`,
},
];
}
export default function Templates() {
const t = useTranslate();
return (
<Grid container spacing={2} sx={{ pt: 2, pb: 4 }}>
{layouts(t).map((layout) => (
<Grid item xs={12} sm={4} key={layout.title}>
<Card
variant="outlined"
sx={{
height: '100%',
background: 'background.paper',
borderColor: 'divider',
display: 'flex',
flexDirection: 'column',
}}
>
<Box
sx={{
overflow: 'auto',
position: 'relative',
borderBottom: '1px solid',
borderColor: 'divider',
}}
>
<CardMedia
component="a"
href={layout.href}
image={layout.src}
title={layout.title}
rel="nofollow"
target="_blank"
sx={{ height: 0, pt: '65%' }}
/>
<NextLink href={layout.href} passHref legacyBehavior>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<Link
tabIndex={-1}
aria-hidden
data-ga-event-category="material-ui-template"
data-ga-event-label={layout.title}
data-ga-event-action="preview-img"
sx={(theme) => ({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
gap: 1,
transition: '0.15s',
position: 'absolute',
width: '100%',
height: '100%',
top: 0,
left: 0,
bgcolor: alpha(theme.palette.primary[50], 0.5),
backdropFilter: 'blur(4px)',
opacity: 0,
'&:hover, &:focus': {
opacity: 1,
},
...theme.applyDarkStyles({
bgcolor: alpha(theme.palette.common.black, 0.8),
}),
})}
>
<Visibility />
<Typography
fontWeight="bold"
color="text.primary"
sx={{ textDecorationLine: 'underline' }}
>
View live preview
</Typography>
</Link>
</NextLink>
</Box>
<Box sx={{ p: 2, flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
<Typography component="h3" variant="subtitle1" fontWeight="bold" gutterBottom>
{layout.title}
</Typography>
<Typography variant="body2" color="text.secondary" mb={2}>
{layout.description}
</Typography>
<Button
component="a"
href={layout.source}
size="small"
fullWidth
variant="outlined"
color="secondary"
startIcon={<CodeRoundedIcon sx={{ mr: 0.5 }} />}
sx={{ mt: 'auto' }}
>
{t('sourceCode')}
</Button>
</Box>
</Card>
</Grid>
))}
</Grid>
);
}
| 5,303 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MaterialShowcase.js | import * as React from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Unstable_Grid2';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import Card from '@mui/material/Card';
import CardMedia from '@mui/material/CardMedia';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import GitHubIcon from '@mui/icons-material/GitHub';
import { alpha } from '@mui/material/styles';
import Link from 'docs/src/modules/components/Link';
import { useTranslate } from 'docs/src/modules/utils/i18n';
/**
* The app structure:
*
* {
* title: string;
* description: string;
* image?: string;
* link: string;
* source?: string;
* similarWebVisits?: number;
* dateAdded: string; // ISO 8601 format: YYYY-MM-DD
* }
*/
const appList = [
{
title: 'd-cide',
description:
'A progressive Web App to make rational decisions in workshops. ' +
'It uses Material UI with a neumorphic custom theme.',
image: 'dcide.jpg',
link: 'https://d-cide.me/',
source: 'https://github.com/cjoecker/d-cide',
dateAdded: '2020-07-01',
},
{
title: 'QuintoAndar',
description:
'QuintoAndar is a company that uses technology and ' +
'design to simplify the rental of residential real estate.',
image: 'quintoandar.jpg',
link: 'https://www.quintoandar.com.br/',
similarWebVisits: 8500,
dateAdded: '2019-05-08',
},
{
title: 'Bethesda.net',
description:
'The official site for Bethesda, publisher of Fallout, DOOM, Dishonored, ' +
'Skyrim, Wolfenstein, The Elder Scrolls, more. Your source for news, features & community.',
image: 'bethesda.jpg',
link: 'https://bethesda.net/',
similarWebVisits: 4000,
dateAdded: '2019-01-01',
},
{
title: 'OpenClassrooms',
description:
'OpenClassrooms is an online platform offering top quality, ' +
'education-to-employment programs and career coaching services for students worldwide. ',
image: 'openclassrooms.png',
link: 'https://openclassrooms.com/en/',
similarWebVisits: 6000,
dateAdded: '2018-01-24',
},
{
title: 'Codementor',
description:
'Codementor is the largest community for developer mentorship and an on-demand marketplace ' +
'for software developers. Get instant coding help, build projects faster, ' +
'and read programming tutorials from our community of developers.',
image: 'codementor.jpg',
link: 'https://www.codementor.io/',
similarWebVisits: 1500,
dateAdded: '2018-01-24',
},
{
title: 'BARKS',
description: 'Japan Music Network. 🇯🇵',
image: 'barks.jpg',
link: 'https://www.barks.jp/',
similarWebVisits: 3000,
dateAdded: '2019-01-01',
},
{
title: 'GovX',
description:
'Current & former uniformed professionals get exclusive access to deals ' +
'on gear, apparel, tickets, travel and more.',
image: 'govx.jpg',
link: 'https://www.govx.com/',
similarWebVisits: 2000,
dateAdded: '2018-01-31',
},
{
title: 'Hijup',
description: 'A pioneering Muslim Fashion e-commerce site.',
image: 'hijup.jpg',
link: 'https://www.hijup.com/',
similarWebVisits: 328,
dateAdded: '2018-01-18',
},
{
title: 'iFit',
description:
'Get the best personal training, right at home. Access hundreds of training programs, ' +
'unique health tips, and expert advice that will lead you to a healthier lifestyle.',
image: 'ifit.jpg',
link: 'https://www.ifit.com/',
similarWebVisits: 304,
dateAdded: '2019-01-01',
},
{
title: 'EQ3',
description: 'Modern Furniture & Accessories, designed in Canada, for everyday living.',
image: 'eq3.jpg',
link: 'https://www.eq3.com/ca/en',
similarWebVisits: 256,
dateAdded: '2018-01-24',
},
{
title: 'Housecall Pro',
description:
'The #1 rated mobile software to run your home service business. ' +
'Schedule, dispatch, GPS track employees, invoice, accept credit cards and get booked ' +
'online. The marketing website is also built with Material UI: https://www.housecallpro.com/',
image: 'housecall.jpg',
link: 'https://pro.housecallpro.com/pro/log_in',
similarWebVisits: 1800,
dateAdded: '2019-01-01',
},
{
title: 'VMware CloudHealth',
description:
'The most trusted cloud management platform that enables users to analyze and manage cloud ' +
'cost, usage and performance in one place. ' +
'(Used for the business application, but not the marketing website.)',
image: 'cloudhealth.jpg',
link: 'https://cloudhealth.vmware.com/',
similarWebVisits: 132,
dateAdded: '2018-01-27',
},
{
title: 'CityAds',
description:
'CityAds Media: global technology platform for online performance marketing ' +
'powered by big data',
image: 'cityads.jpg',
link: 'https://cityads.com/main',
similarWebVisits: 132,
dateAdded: '2019-01-01',
},
{
title: 'EOS Toolkit',
description:
'EOSToolkit is the premier free, open source interface for managing EOS ' +
'accounts. Create, transfer, stake, vote and more with Scatter!',
image: 'eostoolkit.jpg',
link: 'https://eostoolkit.io/',
source: 'https://github.com/eostoolkit/eostoolkit',
stars: 91,
dateAdded: '2019-01-01',
},
{
title: 'The Media Ant',
description:
"India's Largest online marketing service provider, " +
'with more than 200K advertising options, and more than 1M satisfied customers.',
image: 'themediaant.jpg',
link: 'https://www.themediaant.com/',
similarWebVisits: 90,
dateAdded: '2019-01-01',
},
{
title: 'Forex Bank',
description:
'Vi kan tilby kjapp og enkel valutaveksling, pengeoverføringer, samt kjøp av norsk veksel. ' +
'🇳🇴',
image: 'forex.jpg',
link: 'https://www.forex.no/',
similarWebVisits: 95,
dateAdded: '2018-01-24',
},
{
title: 'LocalMonero',
description:
'A safe and easy-to-use person-to-person platform to allow anyone ' +
'to trade their local currency for Monero, anywhere.',
image: 'localmonero.jpg',
link: 'https://localmonero.co/?rc=ogps',
dateAdded: '2018-01-04',
},
{
title: 'LessWrong',
description: 'LessWrong is a community blog devoted to the art of human rationality.',
image: 'lesswrong.jpg',
link: 'https://www.lesswrong.com/',
similarWebVisits: 1000,
dateAdded: '2018-01-28',
},
{
title: 'ODIGEO Connect',
description:
"Connect your hotel, B&B and apartment with Europe's #1 flight OTA " +
'and distribute it to millions of travellers.',
image: 'odigeo.jpg',
link: 'https://www.odigeoconnect.com/',
dateAdded: '2019-01-01',
},
{
title: 'comet',
description:
'Comet lets you track code, experiments, and results on ML projects. ' +
"It's fast, simple, and free for open source projects.",
image: 'comet.jpg',
link: 'https://www.comet.com/',
similarWebVisits: 180,
dateAdded: '2019-01-01',
},
{
title: 'Pointer',
description:
'Revestimentos cerâmicos para pisos e paredes com qualidade e design acessível. ' +
'A Pointer faz parte da Portobello e atua no Nordeste do Brasil. 🇧🇷',
image: 'pointer.jpg',
link: 'https://www.pointer.com.br/',
dateAdded: '2019-01-01',
},
{
title: 'Oneplanetcrowd',
description:
"Oneplanetcrowd is Europe's leading sustainable crowdfunding platform for People & Planet.",
image: 'oneplanetcrowd.jpg',
link: 'https://www.oneplanetcrowd.com/en',
dateAdded: '2019-01-01',
},
{
title: 'CollegeAI',
description:
'Get a college recommendation and your chances using the best college predictor. ' +
"Answer some questions and we'll calculate where you fit in best with our college finder " +
'and college matching tools. CollegeAI is an admissions and college counselor, college ' +
'planner, and college chance calculator.',
image: 'collegeai.jpg',
link: 'https://collegeai.com',
dateAdded: '2019-01-01',
},
{
title: 'react-admin',
description:
'The admin of an imaginary poster shop, used as a demo for the react-admin framework. ' +
'Uses many material-ui components, including tables, forms, snackbars, buttons, and ' +
'theming. The UI is responsive. The code is open-source!',
image: 'posters-galore.jpg',
link: 'https://marmelab.com/react-admin-demo/',
source: 'https://github.com/marmelab/react-admin',
dateAdded: '2018-01-21',
stars: 18500,
},
{
title: 'Builder Book',
description:
'Books to learn how to build full-stack, production-ready JavaScript web applications from scratch. ' +
'Learn React, Material UI, Next, Express, Mongoose, MongoDB, third party APIs, and more.',
image: 'builderbook.jpg',
link: 'https://builderbook.org/',
source: 'https://github.com/async-labs/builderbook',
stars: 3000,
dateAdded: '2018-01-05',
},
{
title: 'Commit Swimming',
description: 'The #1 workout journal for coaches and swimmers.',
image: 'commitswimming.jpg',
link: 'https://commitswimming.com/',
dateAdded: '2019-01-01',
},
{
title: 'EventHi',
description:
'Cannabis event platform to create and coordinate Cannabis events for the Cannabis ' +
'community. Use our easy ticketing system, sponsor, and sell merchandise.',
image: 'eventhi.jpg',
link: 'https://eventhi.io/',
dateAdded: '2019-01-01',
},
{
title: 'Iceberg Finder',
description:
'Whether spotting them from outer space, or standing on our coastline, ' +
'IcebergFinder.com is your premier place for finding bergs in Newfoundland and Labrador.',
image: 'icebergfinder.jpg',
link: 'https://icebergfinder.com/',
dateAdded: '2019-01-01',
},
{
title: 'MetaFact',
description:
"Metafact is a place to verify knowledge via the world's top experts. " +
"It's a platform to ask questions, learn the facts and share the truth.",
image: 'metafact.jpg',
link: 'https://metafact.io/',
dateAdded: '2019-01-01',
},
{
title: 'AudioNodes',
description:
'Modular audio production suite with multi-track audio mixing, audio effects, ' +
'parameter automation, MIDI editing, synthesis, cloud production, and more.',
image: 'audionodes.jpg',
link: 'https://www.audionodes.com/',
dateAdded: '2018-01-07',
},
{
title: 'SlidesUp',
description: 'SlidesUp is a platform to help conference organizers plan their events.',
image: 'slidesup.jpg',
link: 'https://slidesup.com/',
dateAdded: '2018-01-03',
},
{
title: 'Typekev',
description: 'The personal site of Kevin Gonzalez, featuring his witty chatbot.',
image: 'typekev.jpg',
link: 'https://typekev.com/',
source: 'https://github.com/typekev/typekev-site',
stars: 10,
dateAdded: '2018-01-23',
},
{
title: 'npm registry browser',
description:
'An open source web app that lets you search the npm registry ' +
'and browse packages details.',
image: 'npm-registry-browser.jpg',
link: 'https://topheman.github.io/npm-registry-browser/',
source: 'https://github.com/topheman/npm-registry-browser',
stars: 90,
dateAdded: '2018-01-15',
},
{
title: 'Snippets Chrome Extension',
description:
'An open source Chrome extension allowing you to import and execute JavaScript code ' +
'snippets from GitHub.',
image: 'snippets.jpg',
link: 'https://chrome.google.com/webstore/detail/snippets/dcibnkkafifbanoclgjbkmkbogijndin',
source: 'https://github.com/richardscarrott/snippets',
stars: 42,
dateAdded: '2018-01-19',
},
{
title: 'Tree',
description:
'An open source top 100 documentaries (personal opinion) app with React Hooks and Material UI.',
link: 'https://tree.valleyease.me/',
image: 'tree.jpg',
source: 'https://github.com/ValleyZw/tree',
stars: 24,
dateAdded: '2018-01-25',
},
{
title: 'TagSpaces',
description:
'TagSpaces is an offline, open source, file manager.' +
'It helps organizing your files and folders with tags and colors.',
image: 'tagspaces.jpg',
link: 'https://www.tagspaces.org/demo/',
source: 'https://github.com/tagspaces/tagspaces',
stars: 2500,
dateAdded: '2019-11-01',
},
{
title: 'HiFiveWork',
description: 'HiFiveWork, the cool tool for leave management',
image: 'hifivework.png',
link: 'https://hifivework.com/',
dateAdded: '2020-01-08',
},
{
title: 'FANSPO',
description: 'NBA trade machine and social analysis tools for the basketball community.',
image: 'tradenba.jpg',
link: 'https://fanspo.com/',
similarWebVisits: 417,
dateAdded: '2020-01-20',
},
{
title: 'Backstage',
description: 'Backstage is an open platform by Spotify for building developer portals.',
image: 'backstage.jpg',
link: 'https://backstage.io',
source: 'https://github.com/backstage/backstage',
stars: 14300,
dateAdded: '2020-08-31',
},
{
title: 'buybags',
description: 'buybags is a fashion shopping aggregator in Germany.',
image: 'buybags.jpg',
link: 'https://www.buybags.de/',
dateAdded: '2020-10-08',
},
{
title: 'react-admin CRM demo',
description: 'A full-featured Customer Relationship Management app',
image: 'atomiccrm.jpg',
link: 'https://marmelab.com/react-admin-crm/',
source: 'https://github.com/marmelab/react-admin/tree/master/examples/crm',
stars: 18500,
dateAdded: '2021-05-06',
},
{
title: 'Saleor Store Dashboard',
description: 'Dashboard application for Saleor headless e-commerce platform',
image: 'saleor.jpg',
link: 'https://demo.saleor.io/dashboard/',
source: 'https://github.com/saleor/saleor-dashboard',
stars: 15079,
similarWebVisits: 62,
dateAdded: '2022-02-05',
},
{
title: 'MQTT Explorer',
description:
'A comprehensive MQTT Client which visualizes broker traffic in a hierarchical view. ' +
'The protocol is used in many IoT and home automation scenarios, ' +
'making integrating new services dead easy.',
link: 'https://mqtt-explorer.com/',
source: 'https://github.com/thomasnordquist/MQTT-Explorer',
image: 'mqtt-explorer.png',
stars: 1600,
dateAdded: '2019-03-25',
},
{
title: 'refine FineFoods demo',
description: 'A full-featured Admin panel app',
image: 'refine-finefoods.png',
link: 'https://example.mui.admin.refine.dev/',
source: 'https://github.com/pankod/refine/tree/next/examples/fineFoods/admin/mui',
stars: 2415,
dateAdded: '2022-06-21',
},
];
function stableSort(array, cmp) {
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = cmp(a[0], b[0]);
if (order !== 0) {
return order;
}
return a[1] - b[1];
});
return stabilizedThis.map((el) => el[0]);
}
// Returns a function that sorts reverse numerically by value of `key`
function sortFactory(key) {
return function sortNumeric(a, b) {
if (b[key] < a[key]) {
return -1;
}
if (b[key] > a[key]) {
return 1;
}
return 0;
};
}
const sortFunctions = {
dateAdded: sortFactory('dateAdded'),
similarWebVisits: sortFactory('similarWebVisits'),
stars: sortFactory('stars'),
};
export default function Showcase() {
const [sortFunctionName, setSortFunctionName] = React.useState('similarWebVisits');
const sortFunction = sortFunctions[sortFunctionName];
const t = useTranslate();
const handleChangeSort = (event) => {
setSortFunctionName(event.target.value);
};
return (
<React.Fragment>
<ToggleButtonGroup
size="small"
color="primary"
value={sortFunctionName}
onChange={handleChangeSort}
exclusive
sx={{ mb: 3, display: 'flex', alignItems: 'center' }}
>
<Typography variant="body2" color="text.secondary" fontWeight={600} sx={{ mr: 1 }}>
{/* eslint-disable-next-line material-ui/no-hardcoded-labels */}
{'Sort by:'}
</Typography>
<ToggleButton value="similarWebVisits">{t('traffic')}</ToggleButton>
<ToggleButton value="dateAdded">{t('newest')}</ToggleButton>
<ToggleButton value="stars">{t('stars')}</ToggleButton>
</ToggleButtonGroup>
<Grid container spacing={3}>
{stableSort(
appList.filter((item) => item[sortFunctionName] !== undefined),
sortFunction,
).map((app) => (
<Grid key={app.title} item xs={12} sm={6}>
{app.image ? (
<Card
variant="outlined"
sx={(theme) => ({
height: '100%',
display: 'flex',
flexDirection: 'column',
p: 2,
gap: 2,
borderRadius: 1,
backgroundColor: `${alpha(theme.palette.grey[50], 0.4)}`,
borderColor: 'divider',
...theme.applyDarkStyles({
backgroundColor: `${alpha(theme.palette.primaryDark[700], 0.3)}`,
borderColor: 'divider',
}),
})}
>
<a href={app.link} rel="noopener nofollow noreferrer" target="_blank">
<CardMedia
component="img"
loading="lazy"
width="600"
height="450"
src={`/static/images/showcase/${app.image}`}
title={app.title}
sx={(theme) => ({
height: 'auto',
borderRadius: 0.5,
bgcolor: 'currentColor',
border: '1px solid',
borderColor: 'grey.100',
color: 'grey.100',
...theme.applyDarkStyles({
borderColor: 'grey.700',
color: 'primaryDark.900',
}),
})}
/>
</a>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
<Typography
component="h2"
variant="h6"
fontWeight={600}
sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
>
<span>{app.title}</span>
{app.source ? (
<IconButton
href={app.source}
target="_blank"
aria-label={`${app.title} ${t('sourceCode')}`}
>
<GitHubIcon fontSize="small" />
</IconButton>
) : null}
</Typography>
<Typography variant="body2" color="text.secondary">
{app.description}
</Typography>
<Typography variant="caption" display="block" color="text.secondary">
{app.dateAdded}
</Typography>
</Box>
</Card>
) : (
<Link
variant="body2"
target="_blank"
rel="noopener nofollow"
href={app.link}
gutterBottom
>
{t('visit')}
</Link>
)}
</Grid>
))}
</Grid>
</React.Fragment>
);
}
| 5,304 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MaterialUIDesignResources.js | import * as React from 'react';
import Grid from '@mui/material/Unstable_Grid2';
import InfoCard from 'docs/src/components/action/InfoCard';
const content = [
{
title: 'Material UI for Figma',
link: 'https://mui.com/store/items/figma-react/?utm_source=docs&utm_medium=referral&utm_campaign=installation-figma',
svg: (
<img
src={`/static/branding/design-kits/figma-logo.svg`}
alt="Figma logo"
loading="lazy"
width="36"
height="36"
/>
),
},
{
title: 'Material UI for Sketch',
link: 'https://mui.com/store/items/sketch-react/?utm_source=docs&utm_medium=referral&utm_campaign=installation-sketch',
svg: (
<img
src={`/static/branding/design-kits/sketch-logo.svg`}
alt="Sketch logo"
loading="lazy"
width="36"
height="36"
/>
),
},
{
title: 'Material UI for Adobe XD',
link: 'https://mui.com/store/items/adobe-xd-react/?utm_source=docs&utm_medium=referral&utm_campaign=installation-adobe-xd',
svg: (
<img
src={`/static/branding/design-kits/adobexd-logo.svg`}
alt="Adobe XD logo"
loading="lazy"
width="36"
height="36"
/>
),
},
];
export default function MaterialUIDesignResources() {
return (
<Grid container spacing={2}>
{content.map(({ svg, title, link }) => (
<Grid key={title} xs={12} sm={4}>
<InfoCard classNameTitle="algolia-lvl3" link={link} title={title} svg={svg} />
</Grid>
))}
</Grid>
);
}
| 5,305 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MaterialUIExampleCollection.js | import * as React from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Unstable_Grid2';
import Paper from '@mui/material/Paper';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import Link from '@mui/material/Link';
import ChevronRightRoundedIcon from '@mui/icons-material/ChevronRightRounded';
import CloudRoundedIcon from '@mui/icons-material/CloudRounded';
const examples = [
{
name: 'Next.js App Router',
label: 'View JS example',
tsLabel: 'View TS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs',
tsLink: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs-ts',
src: '/static/images/examples/next.svg',
},
{
name: 'Vite.js',
label: 'View JS example',
tsLabel: 'View TS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-vite',
tsLink: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-vite-ts',
src: '/static/images/examples/vite.svg',
},
{
name: 'Next.js Pages Router',
label: 'View JS example',
tsLabel: 'View TS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs-pages-router',
tsLink:
'https://github.com/mui/material-ui/tree/master/examples/material-ui-nextjs-pages-router-ts',
src: '/static/images/examples/next.svg',
},
{
name: 'Remix',
label: 'View TS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-remix-ts',
src: '/static/images/examples/remix.svg',
},
{
name: 'Tailwind CSS + CRA',
label: 'View TS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra-tailwind-ts',
src: '/static/images/examples/tailwindcss.svg',
},
{
name: 'Create React App',
label: 'View JS example',
tsLabel: 'View TS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra',
tsLink: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra-ts',
src: '/static/images/examples/cra.svg',
},
{
name: 'styled-components',
label: 'View JS example',
tsLabel: 'View TS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra-styled-components',
tsLink:
'https://github.com/mui/material-ui/tree/master/examples/material-ui-cra-styled-components-ts',
src: '/static/images/examples/styled.png',
},
{
name: 'Preact',
label: 'View JS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-preact',
src: '/static/images/examples/preact.svg',
},
{
name: 'CDN',
label: 'View JS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-via-cdn',
src: <CloudRoundedIcon />,
},
{
name: 'Express.js (server-rendered)',
label: 'View JS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-express-ssr',
src: '/static/images/examples/express.png',
},
{
name: 'Gatsby',
label: 'View JS example',
link: 'https://github.com/mui/material-ui/tree/master/examples/material-ui-gatsby',
src: '/static/images/examples/gatsby.svg',
},
];
export default function MaterialUIExampleCollection() {
return (
<Grid container spacing={2}>
{examples.map((example) => (
<Grid key={example.name} xs={12} sm={6}>
<Paper
variant="outlined"
sx={(theme) => ({
p: 2,
display: 'flex',
alignItems: 'center',
gap: 2,
background: `${(theme.vars || theme).palette.gradients.linearSubtle}`,
...theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
background: `${(theme.vars || theme).palette.gradients.linearSubtle}`,
borderColor: 'primaryDark.700',
}),
})}
>
<Avatar
alt={example.name}
imgProps={{
width: '38',
height: '38',
loading: 'lazy',
}}
{...(typeof example.src === 'string'
? { src: example.src }
: { children: example.src })}
/>
<div>
<Typography fontWeight="semiBold" className="algolia-lvl3">
{example.name}
</Typography>
<Box
data-ga-event-category="material-ui-example"
data-ga-event-label={example.name}
data-ga-event-action="click"
sx={{
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
mt: 0.2,
gap: 0.2,
}}
>
<Link
href={example.link}
variant="body2"
sx={{
'& > svg': { transition: '0.2s' },
'&:hover > svg': { transform: 'translateX(2px)' },
}}
>
{example.label}
<ChevronRightRoundedIcon fontSize="small" sx={{ verticalAlign: 'middle' }} />
</Link>
{!!example.tsLink && (
<React.Fragment>
<Typography
variant="caption"
sx={{
display: { xs: 'none', sm: 'block' },
opacity: 0.2,
mr: 0.75,
}}
>
•
</Typography>
<Link
href={example.tsLink}
variant="body2"
sx={{
'& > svg': { transition: '0.2s' },
'&:hover > svg': { transform: 'translateX(2px)' },
}}
>
{example.tsLabel}
<ChevronRightRoundedIcon fontSize="small" sx={{ verticalAlign: 'middle' }} />
</Link>
</React.Fragment>
)}
</Box>
</div>
</Paper>
</Grid>
))}
</Grid>
);
}
| 5,306 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MaterialYouUsageDemo.tsx | import * as React from 'react';
import { useTheme as md2UseTheme, alpha } from '@mui/material/styles';
import ReplayRoundedIcon from '@mui/icons-material/ReplayRounded';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import FormControl from '@mui/material/FormControl';
import FormLabel, { formLabelClasses } from '@mui/material/FormLabel';
import IconButton from '@mui/material/IconButton';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import Switch from '@mui/material/Switch';
import Typography from '@mui/material/Typography';
import {
extendTheme,
CssVarsProvider as MaterialYouCssVarsProvider,
useColorScheme,
} from '@mui/material-next/styles';
import BrandingProvider from 'docs/src/BrandingProvider';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
type Mode = 'light' | 'dark' | 'system';
const materialYouTheme = extendTheme();
const shallowEqual = (item1: { [k: string]: any }, item2: { [k: string]: any }) => {
let equal = true;
Object.entries(item1).forEach(([key, value]: [string, any]) => {
if (item2[key] !== value) {
equal = false;
}
});
return equal;
};
const defaultGetCodeBlock = (code: string) => code;
function createCode(
data: {
name: string;
props: Record<string, string | number | boolean>;
childrenAccepted?: boolean;
},
getCodeBlock = defaultGetCodeBlock,
) {
const { props: inProps, name, childrenAccepted } = data;
const closedJsx = childrenAccepted ? '>' : '/>';
let code = `<${name}`;
const props = Object.entries(inProps).sort((a, b) => a[0].localeCompare(b[0]));
if (!Object.keys(props).length) {
code = `${code} ${closedJsx}`;
} else {
let children = '';
props.forEach((prop) => {
if (prop[0] !== 'children' && prop[1] !== undefined) {
if (props.length <= 2) {
if (typeof prop[1] === 'boolean') {
code = `${code} ${prop[0]}${prop[1] ? '' : '={false}'}`;
} else if (typeof prop[1] === 'function') {
code = `${code} ${prop[0]}={${(prop[1] as Function).toString()}}`;
} else {
code = `${code} ${prop[0]}=${
typeof prop[1] === 'number' ? `{${prop[1]}}` : `"${prop[1]}"`
}`;
}
} else if (typeof prop[1] === 'function') {
code = `${code}\n ${prop[0]}={${(prop[1] as Function).toString()}}`;
} else if (typeof prop[1] === 'boolean') {
code = `${code}\n ${prop[0]}${prop[1] ? '' : '={false}'}`;
} else {
code = `${code}\n ${prop[0]}=${
typeof prop[1] === 'number' ? `{${prop[1]}}` : `"${prop[1]}"`
}`;
}
} else {
children = prop[1] as string;
}
});
if (children) {
code = `${code}${props.length > 2 ? `\n>` : '>'}\n ${children}\n</${name}>`;
} else {
code = `${code}${props.length > 2 ? `\n${closedJsx}` : `${childrenAccepted ? '>' : ' />'}`}`;
}
}
return getCodeBlock(code);
}
export const prependLinesSpace = (code: string, size: number = 2) => {
const newCode: string[] = [];
code.split('\n').forEach((line) => {
newCode.push(`${Array(size).fill(' ').join('')}${line}`);
});
return newCode.join('\n');
};
function ModeSwitcher({ md2Mode }: { md2Mode: Mode }) {
const { setMode } = useColorScheme();
React.useEffect(() => {
setMode(md2Mode);
}, [md2Mode, setMode]);
return null;
}
interface MaterialYouUsageDemoProps<ComponentProps> {
/**
* Name of the component to show in the code block.
*/
componentName: string;
/**
* For displaying the close bracket of the component in the code block.
* if `true`, shows '>' otherwise shows '/>'
*/
childrenAccepted?: boolean;
/**
* Configuration
*/
data: Array<{
/**
* Name of the prop, e.g. 'children'
*/
propName: Extract<keyof ComponentProps, string>;
/**
* The controller to be used:
* - `switch`: render the switch component for boolean
* - `color`: render the built-in color selector
* - `select`: render <select> with the specified options
* - `input`: render <input />
* - `radio`: render group of radios
*/
knob?:
| 'switch'
| 'color'
| 'select'
| 'input'
| 'radio'
| 'controlled'
| 'number'
| 'placement';
/**
* The options for these knobs: `select` and `radio`
*/
options?: Array<string>;
/**
* The labels for these knobs: `radio`
*/
labels?: Array<string>;
/**
* The default value to be used by the components.
* If exists, it will be injected to the `renderDemo` callback but it will not show
* in the code block.
*
* To make it appears in the code block, specified `codeBlockDisplay: true`
*/
defaultValue?: string | number | boolean;
/**
* If not specify (`undefined`), the prop displays when user change the value
* If `true`, the prop with defaultValue will always display in the code block.
* If `false`, the prop does not display in the code block.
*/
codeBlockDisplay?: boolean;
onChange?: (event: React.SyntheticEvent) => void;
}>;
/**
* A function to override the code block result.
*/
getCodeBlock?: (code: string, props: ComponentProps) => string;
renderDemo: (props: ComponentProps) => React.ReactElement;
}
export default function MaterialYouUsageDemo<T extends { [k: string]: any } = {}>({
componentName,
childrenAccepted = false,
data,
renderDemo,
getCodeBlock = defaultGetCodeBlock,
}: MaterialYouUsageDemoProps<T>) {
const initialProps = {} as { [k in keyof T]: any };
let demoProps = {} as { [k in keyof T]: any };
let codeBlockProps = {} as { [k in keyof T]: any };
data.forEach((p) => {
demoProps[p.propName] = p.defaultValue;
if (p.codeBlockDisplay) {
initialProps[p.propName] = p.defaultValue;
}
if (!p.knob) {
codeBlockProps[p.propName] = p.defaultValue;
}
});
const [props, setProps] = React.useState<T>(initialProps as T);
demoProps = { ...demoProps, ...props };
codeBlockProps = { ...props, ...codeBlockProps };
data.forEach((p) => {
if (p.codeBlockDisplay === false) {
delete codeBlockProps[p.propName];
}
});
const md2Theme = md2UseTheme();
return (
<Box
sx={{
flexGrow: 1,
maxWidth: '100%',
display: 'flex',
flexDirection: { xs: 'column', md: 'row' },
'& .markdown-body pre': {
margin: 0,
borderRadius: 'md',
},
}}
>
<Box
sx={{ display: 'flex', flexDirection: 'column', flexGrow: 999, minWidth: 0, p: 3, gap: 3 }}
>
<Box
sx={{
flexGrow: 1,
m: 'auto',
display: 'flex',
alignItems: 'center',
}}
>
<MaterialYouCssVarsProvider theme={materialYouTheme}>
<ModeSwitcher md2Mode={md2Theme.palette.mode} />
{renderDemo(demoProps)}
</MaterialYouCssVarsProvider>
</Box>
<BrandingProvider mode="dark">
<HighlightedCode
code={createCode(
{
name: componentName,
props: codeBlockProps,
childrenAccepted,
},
(code) => getCodeBlock(code, demoProps),
)}
language="jsx"
sx={{ display: { xs: 'none', md: 'block' } }}
/>
</BrandingProvider>
</Box>
<Box
sx={(theme) => ({
flexShrink: 0,
gap: 2,
borderLeft: '1px solid',
borderColor: theme.palette.grey[200],
background: alpha(theme.palette.grey[50], 0.5),
minWidth: '250px',
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
borderColor: alpha(theme.palette.grey[900], 0.8),
backgroundColor: alpha(theme.palette.grey[900], 0.3),
},
})}
>
<Box
sx={{
px: 3,
py: 2,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Typography
id="usage-props"
component="h3"
fontWeight="600"
sx={{ scrollMarginTop: 160, fontFamily: 'General Sans' }}
>
Playground
</Typography>
<IconButton
aria-label="Reset all"
size="small"
onClick={() => setProps(initialProps as T)}
sx={{
visibility: !shallowEqual(props, initialProps) ? 'visible' : 'hidden',
}}
>
<ReplayRoundedIcon />
</IconButton>
</Box>
<Divider sx={{ opacity: 0.5 }} />
<Box
sx={{
p: 3,
display: 'flex',
flexDirection: 'column',
gap: 2,
[`& .${formLabelClasses.root}`]: {
fontWeight: 'lg',
},
}}
>
{data.map(({ propName, knob, options = [], defaultValue, onChange }) => {
const resolvedValue = props[propName] ?? defaultValue;
if (!knob) {
return null;
}
if (knob === 'switch') {
return (
<FormControl
key={propName}
size="small"
sx={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<FormLabel
sx={{
textTransform: 'capitalize',
fontWeight: 'medium',
fontSize: '0.875rem',
color: 'text.secondary',
}}
>
{propName}
</FormLabel>
<Switch
size="small"
checked={Boolean(resolvedValue)}
onChange={(event) => {
setProps((latestProps) => ({
...latestProps,
[propName]: event.target.checked,
}));
onChange?.(event);
}}
/>
</FormControl>
);
}
if (knob === 'select') {
return (
<FormControl key={propName} size="small">
<FormLabel
sx={{
textTransform: 'capitalize',
fontWeight: 'medium',
fontSize: '0.875rem',
mb: 0.5,
}}
>
{propName}
</FormLabel>
<Select
placeholder="Select a variant..."
value={(resolvedValue || 'none') as string}
onChange={(event) => {
setProps((latestProps) => ({
...latestProps,
[propName]: event.target.value,
}));
onChange?.(event as React.SyntheticEvent);
}}
>
{options.map((value) => (
<MenuItem key={value} value={value}>
{value}
</MenuItem>
))}
</Select>
</FormControl>
);
}
return null;
})}
</Box>
</Box>
</Box>
);
}
| 5,307 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MuiProductSelector.tsx | import * as React from 'react';
import { alpha } from '@mui/material/styles';
import Box, { BoxProps } from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import IconImage from 'docs/src/components/icon/IconImage';
import ROUTES from 'docs/src/route';
import Link from 'docs/src/modules/components/Link';
import PageContext from 'docs/src/modules/components/PageContext';
interface ProductSubMenuProp extends BoxProps {
icon: React.ReactNode;
name: React.ReactNode;
description: React.ReactNode;
chip?: React.ReactNode;
}
function ProductSubMenu(props: ProductSubMenuProp) {
const { icon, name, description, chip, sx = [], ...other } = props;
return (
<Box
{...other}
sx={[
{
width: '100%',
display: 'flex',
alignItems: 'center',
gap: 2,
},
...(Array.isArray(sx) ? sx : [sx]),
]}
>
<Box
sx={[
(theme) => ({
'& circle': {
fill: (theme.vars || theme).palette.grey[100],
},
}),
(theme) =>
theme.applyDarkStyles({
'& circle': {
fill: (theme.vars || theme).palette.primaryDark[700],
},
}),
]}
>
{icon}
</Box>
<Box sx={{ flexGrow: 1 }}>
<Typography color="text.primary" variant="body2" fontWeight="700">
{name}
</Typography>
<Typography color="text.secondary" variant="body2">
{description}
</Typography>
</Box>
{chip}
</Box>
);
}
const products = [
{
name: 'Material UI',
href: ROUTES.materialDocs,
id: 'material-ui',
},
{
name: 'Joy UI',
href: ROUTES.joyDocs,
id: 'joy-ui',
},
{
name: 'Base UI',
href: ROUTES.baseDocs,
id: 'base-ui',
},
{
name: 'MUI System',
href: ROUTES.systemDocs,
id: 'system',
},
];
export default function MuiProductSelector() {
const pageContext = React.useContext(PageContext);
return (
<React.Fragment>
<Box
component="li"
role="none"
sx={(theme) => ({
p: 2,
pr: 3,
borderBottom: '1px solid',
borderColor: 'grey.100',
...theme.applyDarkStyles({
borderColor: alpha(theme.palette.primary[100], 0.08),
}),
})}
>
<ProductSubMenu
role="menuitem"
icon={<IconImage name="product-core" />}
name="MUI Core"
description="Ready-to-use foundational React components, free forever."
/>
<Box sx={{ ml: '36px', pl: 2, pt: 1.5, position: 'relative' }}>
<Stack
direction={{ xs: 'column', sm: 'row' }}
alignItems="flex-start"
spacing={1}
sx={{
'& > .MuiChip-root': {
position: 'initial',
'&:hover': {
'& .product-description': {
opacity: 1,
},
},
},
}}
>
{products.map((product) => (
<Chip
key={product.name}
color={pageContext.productId === product.id ? 'primary' : undefined}
variant={pageContext.productId === product.id ? 'filled' : 'outlined'}
component={Link}
href={product.href}
label={product.name}
clickable
size="small"
/>
))}
</Stack>
</Box>
</Box>
<li role="none">
<Link
href={ROUTES.advancedComponents}
sx={[
{
p: 2,
pr: 3,
borderBottom: '1px solid',
borderColor: 'grey.100',
width: '100%',
'&:hover': {
backgroundColor: 'grey.50',
},
},
(theme) =>
theme.applyDarkStyles({
borderColor: alpha(theme.palette.primary[100], 0.08),
'&:hover': {
backgroundColor: alpha(theme.palette.primaryDark[700], 0.4),
},
}),
]}
>
<ProductSubMenu
role="menuitem"
icon={<IconImage name="product-advanced" />}
name="MUI X"
description="Advanced and powerful components for complex use cases."
/>
</Link>
</li>
<li role="none">
<Link
href={ROUTES.toolpadDocs}
sx={[
{
p: 2,
pr: 3,
borderBottom: '1px solid',
borderColor: 'grey.100',
width: '100%',
'&:hover': {
backgroundColor: 'grey.50',
},
},
(theme) =>
theme.applyDarkStyles({
borderColor: alpha(theme.palette.primary[100], 0.08),
'&:hover': {
backgroundColor: alpha(theme.palette.primaryDark[700], 0.4),
},
}),
]}
>
<ProductSubMenu
role="menuitem"
icon={<IconImage name="product-toolpad" />}
name="MUI Toolpad"
description="Low-code admin builder."
chip={<Chip size="small" label="Beta" color="primary" variant="outlined" />}
/>
</Link>
</li>
</React.Fragment>
);
}
| 5,308 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/Notifications.js | import * as React from 'react';
import { styled } from '@mui/material/styles';
import NotificationsNoneRoundedIcon from '@mui/icons-material/NotificationsNoneRounded';
import Tooltip from '@mui/material/Tooltip';
import CircularProgress from '@mui/material/CircularProgress';
import IconButton from '@mui/material/IconButton';
import Badge from '@mui/material/Badge';
import Typography from '@mui/material/Typography';
import Popper from '@mui/material/Popper';
import Grow from '@mui/material/Grow';
import MuiPaper from '@mui/material/Paper';
import { ClickAwayListener } from '@mui/base/ClickAwayListener';
import MuiList from '@mui/material/List';
import MuiListItem from '@mui/material/ListItem';
import MuiDivider from '@mui/material/Divider';
import { getCookie } from 'docs/src/modules/utils/helpers';
import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n';
async function fetchNotifications() {
if (process.env.NODE_ENV === 'development') {
const items = (await import('../../../notifications.json')).default;
return items;
}
const response = await fetch(
'https://raw.githubusercontent.com/mui/material-ui/master/docs/notifications.json',
);
return response.json();
}
const Paper = styled(MuiPaper)({
transformOrigin: 'top right',
backgroundImage: 'none',
});
const List = styled(MuiList)(({ theme }) => ({
width: theme.spacing(40),
maxHeight: 540,
overflow: 'auto',
padding: theme.spacing(1, 0),
}));
const ListItem = styled(MuiListItem)({
display: 'flex',
flexDirection: 'column',
});
const Loading = styled('div')(({ theme }) => ({
display: 'flex',
justifyContent: 'center',
margin: theme.spacing(3, 0),
}));
const Divider = styled(MuiDivider)(({ theme }) => ({
margin: theme.spacing(1, 0),
}));
export default function Notifications() {
const [open, setOpen] = React.useState(false);
const [tooltipOpen, setTooltipOpen] = React.useState(false);
const anchorRef = React.useRef(null);
const t = useTranslate();
const userLanguage = useUserLanguage();
const [{ lastSeen, messages }, setNotifications] = React.useState({
lastSeen: undefined,
messages: undefined,
});
const messageList = messages
? messages
.filter((message) => {
if (
message.userLanguage &&
message.userLanguage !== userLanguage &&
message.userLanguage !== navigator.language.substring(0, 2)
) {
return false;
}
return true;
})
.reverse()
: null;
const handleToggle = () => {
setOpen((prevOpen) => !prevOpen);
setTooltipOpen(false);
if (process.env.NODE_ENV === 'development') {
// Skip last seen logic in dev to make editing notifications easier.
return;
}
if (messageList && messageList.length > 0) {
const newLastSeen = messageList[0].id;
setNotifications((notifications) => {
if (newLastSeen !== notifications.lastSeen) {
return {
messages: notifications.messages,
lastSeen: newLastSeen,
};
}
return notifications;
});
document.cookie = `lastSeenNotification=${newLastSeen};path=/;max-age=31536000`;
}
};
React.useEffect(() => {
let active = true;
// Prevent search engines from indexing the notification.
if (/glebot/.test(navigator.userAgent) || messages) {
return undefined;
}
// Soften the pressure on the main thread
// and create some distraction.
const timeout = setTimeout(async () => {
const notifications = await fetchNotifications().catch(() => {
// Swallow the exceptions, e.g. rate limit
return [];
});
if (active) {
// Permanent notifications
const filteredNotifications = [
/* {
id: 0,
title: "Let's translate!",
text: '<a style="color: inherit;" target="_blank" rel="noopener" data-ga-event-category="l10n" data-ga-event-action="notification" data-ga-event-label="zh" href="https://crowdin.com/project/material-ui-docs">帮助 MUI 将文档翻译成中文</a>. 🇨🇳',
userLanguage: 'zh',
}, */
{
id: 1,
text: 'You can <a style="color: inherit;" target="_blank" rel="noopener" href="https://twitter.com/MUI_hq">follow us on Twitter</a> or subscribe on <a style="color: inherit;" target="_blank" rel="noopener" href="/blog/">our blog</a> to receive exclusive tips and updates about MUI and the React ecosystem.',
},
// Only 3
...notifications.splice(-3),
];
const seen = getCookie('lastSeenNotification');
const lastSeenNotification = seen === undefined ? 0 : parseInt(seen, 10);
setNotifications({
messages: filteredNotifications,
lastSeen: lastSeenNotification,
});
}
}, 1500);
return () => {
clearTimeout(timeout);
active = false;
};
}, [messages]);
return (
<React.Fragment>
<Tooltip
open={tooltipOpen}
title={t('toggleNotifications')}
enterDelay={300}
onOpen={() => {
setTooltipOpen(!open);
}}
onClose={() => {
setTooltipOpen(false);
}}
>
<IconButton
color="primary"
ref={anchorRef}
aria-controls={open ? 'notifications-popup' : undefined}
aria-haspopup="true"
aria-label={`${
messageList
? messageList.reduce(
(count, message) => (message.id > lastSeen ? count + 1 : count),
0,
)
: 0
} ${t('toggleNotifications')}`}
data-ga-event-category="AppBar"
data-ga-event-action="toggleNotifications"
onClick={handleToggle}
>
<Badge
color="error"
badgeContent={
messageList
? messageList.reduce(
(count, message) => (message.id > lastSeen ? count + 1 : count),
0,
)
: 0
}
>
<NotificationsNoneRoundedIcon fontSize="small" />
</Badge>
</IconButton>
</Tooltip>
<Popper
id="notifications-popup"
anchorEl={anchorRef.current}
open={open}
placement="bottom-end"
transition
disablePortal
role={undefined}
>
{({ TransitionProps }) => (
<ClickAwayListener
onClickAway={() => {
setOpen(false);
}}
>
<Grow in={open} {...TransitionProps}>
<Paper
sx={(theme) => ({
mt: 0.5,
border: '1px solid',
borderColor: 'grey.200',
boxShadow: `0px 4px 20px rgba(170, 180, 190, 0.3)`,
...theme.applyDarkStyles({
borderColor: 'primaryDark.700',
boxShadow: `0px 4px 20px rgba(0, 0, 0, 0.5)`,
}),
})}
>
<List>
{messageList ? (
messageList.map((message, index) => (
<React.Fragment key={message.id}>
<ListItem alignItems="flex-start">
<Typography gutterBottom>
<span
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: message.title }}
/>
</Typography>
<Typography gutterBottom variant="body2" color="text.secondary">
<span
id="notification-message"
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: message.text }}
/>
</Typography>
{message.date && (
<Typography variant="caption" color="text.secondary">
{new Date(message.date).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
})}
</Typography>
)}
</ListItem>
{index < messageList.length - 1 ? <Divider /> : null}
</React.Fragment>
))
) : (
<Loading>
<CircularProgress size={32} />
</Loading>
)}
</List>
</Paper>
</Grow>
</ClickAwayListener>
)}
</Popper>
</React.Fragment>
);
}
| 5,309 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/PageContext.tsx | import * as React from 'react';
import type { MuiPage } from 'docs/src/MuiPage';
import type { MuiProductId } from 'docs/src/modules/utils/getProductInfoFromUrl';
const PageContext = React.createContext<{
activePage: MuiPage | null;
pages: MuiPage[];
productId: MuiProductId;
}>(undefined!);
if (process.env.NODE_ENV !== 'production') {
PageContext.displayName = 'PageContext';
}
export default PageContext;
| 5,310 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ReactRunner.tsx | import * as React from 'react';
import { useRunner } from 'react-runner';
interface ReactRunnerProps {
code: string;
scope: {
process: {};
import: {};
};
onError: (error: string | null) => {};
}
// The docs https://github.com/nihgwu/react-runner
export default function ReactRunner(props: ReactRunnerProps) {
const { code, scope: scopeProp, onError } = props;
let scope = scopeProp;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
scope = React.useMemo(() => {
const handler = {
get() {
throw new Error(
[
'A demo tries to access process.x in ReactRunner. This is not supported.',
'If you do not need to show the source, you can set "hideToolbar": true to solve the issue.',
].join('\n'),
);
},
};
return {
...scopeProp,
process: new Proxy(scopeProp.process, handler),
};
}, [scopeProp]);
}
const { element, error } = useRunner({
code,
scope,
});
React.useEffect(() => {
onError(error);
}, [error, onError]);
return element;
}
| 5,311 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/RichMarkdownElement.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { useTranslate, useUserLanguage } from 'docs/src/modules/utils/i18n';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
import HighlightedCodeWithTabs from 'docs/src/modules/components/HighlightedCodeWithTabs';
import Demo from 'docs/src/modules/components/Demo';
function noComponent(moduleID) {
return function NoComponent() {
throw new Error(`No demo component provided for '${moduleID}'`);
};
}
export default function RichMarkdownElement(props) {
const {
activeTab,
demoComponents,
demos = {},
disableAd,
localizedDoc,
renderedMarkdownOrDemo,
srcComponents,
theme,
WrapperComponent: Wrapper,
wrapperProps,
} = props;
const userLanguage = useUserLanguage();
const t = useTranslate();
if (typeof renderedMarkdownOrDemo === 'string') {
return (
<Wrapper {...wrapperProps}>
<MarkdownElement renderedMarkdown={renderedMarkdownOrDemo} />
</Wrapper>
);
}
if (renderedMarkdownOrDemo.component) {
const name = renderedMarkdownOrDemo.component;
const Component = srcComponents?.[name];
if (Component === undefined) {
throw new Error(`No component found at the path 'docs/src/${name}`);
}
const additionalProps = {};
if (name === 'modules/components/ComponentPageTabs.js') {
additionalProps.activeTab = activeTab;
}
return (
<Wrapper {...wrapperProps}>
<Component {...renderedMarkdownOrDemo} {...additionalProps} markdown={localizedDoc} />
</Wrapper>
);
}
if (renderedMarkdownOrDemo.type === 'codeblock') {
return (
<Wrapper {...wrapperProps}>
<HighlightedCodeWithTabs
tabs={renderedMarkdownOrDemo.data}
storageKey={
renderedMarkdownOrDemo.storageKey && `codeblock-${renderedMarkdownOrDemo.storageKey}`
}
/>
</Wrapper>
);
}
const name = renderedMarkdownOrDemo.demo;
const demo = demos?.[name];
if (demo === undefined) {
const errorMessage = [
`Missing demo: ${name}. You can use one of the following:`,
Object.keys(demos),
].join('\n');
if (userLanguage === 'en') {
throw new Error(errorMessage);
}
if (process.env.NODE_ENV !== 'production') {
console.error(errorMessage);
}
const warnIcon = (
<span role="img" aria-label={t('emojiWarning')}>
⚠️
</span>
);
return (
<div>
{/* eslint-disable-next-line material-ui/no-hardcoded-labels */}
{warnIcon} Missing demo `{name}` {warnIcon}
</div>
);
}
const splitLocationBySlash = localizedDoc.location.split('/');
splitLocationBySlash.pop();
const fileNameWithLocation = `${splitLocationBySlash.join('/')}/${name}`;
return (
<Demo
{...wrapperProps}
mode={theme.palette.mode}
demo={{
raw: demo.raw,
js: demoComponents[demo.module] ?? noComponent(demo.module),
scope: demos.scope,
jsxPreview: demo.jsxPreview,
tailwindJsxPreview: demo.tailwindJsxPreview,
cssJsxPreview: demo.cssJsxPreview,
rawTS: demo.rawTS,
tsx: demoComponents[demo.moduleTS] ?? null,
rawTailwind: demo.rawTailwind,
rawTailwindTS: demo.rawTailwindTS,
jsTailwind: demoComponents[demo.moduleTailwind] ?? null,
tsxTailwind: demoComponents[demo.moduleTSTailwind] ?? null,
rawCSS: demo.rawCSS,
rawCSSTS: demo.rawCSSTS,
jsCSS: demoComponents[demo.moduleCSS] ?? null,
tsxCSS: demoComponents[demo.moduleTSCSS] ?? null,
gaLabel: fileNameWithLocation.replace(/^\/docs\/data\//, ''),
}}
disableAd={disableAd}
demoOptions={renderedMarkdownOrDemo}
githubLocation={`${process.env.SOURCE_CODE_REPO}/blob/v${process.env.LIB_VERSION}${fileNameWithLocation}`}
/>
);
}
RichMarkdownElement.propTypes = {
activeTab: PropTypes.string,
demoComponents: PropTypes.any,
demos: PropTypes.any,
disableAd: PropTypes.bool,
localizedDoc: PropTypes.any,
renderedMarkdownOrDemo: PropTypes.oneOfType([
PropTypes.string,
PropTypes.shape({ component: PropTypes.any, demo: PropTypes.any }),
]),
srcComponents: PropTypes.any,
theme: PropTypes.object,
WrapperComponent: PropTypes.elementType,
wrapperProps: PropTypes.object,
};
| 5,312 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/SketchIcon.js | import * as React from 'react';
import { createSvgIcon } from '@mui/material/utils';
export default createSvgIcon(
<g fillRule="nonzero" fill="none">
<path fill="#FDB300" d="M5.24 2.7L12 2l6.76.7L24 9.48 12 23 0 9.49z" />
<path fill="#EA6C00" d="M4.85 9l7.13 14L0 9zM19.1 9l-7.12 14L23.95 9z" />
<path fill="#FDAD00" d="M4.85 9H19.1l-7.12 14z" />
<g>
<path fill="#FDD231" d="M11.98 2l-6.75.65-.38 6.34zM11.98 2l6.75.65.37 6.34z" />
<path fill="#FDAD00" d="M23.95 9l-5.22-6.35.37 6.34zM0 9l5.23-6.35-.38 6.34z" />
<path fill="#FEEEB7" d="M11.98 2L4.85 9H19.1z" />
</g>
</g>,
'Sketch',
);
| 5,313 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/SkipLink.tsx | import * as React from 'react';
import MuiLink from '@mui/material/Link';
import { styled } from '@mui/material/styles';
import { useTranslate } from 'docs/src/modules/utils/i18n';
const StyledLink = styled(MuiLink)(({ theme }) => ({
position: 'fixed',
padding: theme.spacing(1, 2),
backgroundColor: (theme.vars || theme).palette.primary[50],
border: '1px solid',
borderColor: (theme.vars || theme).palette.primary[100],
color: (theme.vars || theme).palette.primary[600],
outlineOffset: 5,
outlineColor: (theme.vars || theme).palette.primary[300],
borderRadius: theme.shape.borderRadius,
left: theme.spacing(2),
zIndex: theme.zIndex.tooltip + 1,
top: theme.spacing(-10),
transition: theme.transitions.create('top', {
easing: theme.transitions.easing.easeIn,
duration: theme.transitions.duration.leavingScreen,
}),
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[100],
color: (theme.vars || theme).palette.primary[700],
},
'&:focus': {
top: theme.spacing(2),
transition: theme.transitions.create('top', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
'@media (prefers-reduced-motion: reduce)': {
transition: theme.transitions.create('opacity'),
opacity: 0,
'&:focus': {
top: theme.spacing(2),
opacity: 1,
transition: theme.transitions.create('opacity'),
},
},
'@media print': {
display: 'none',
},
...theme.applyDarkStyles({
backgroundColor: (theme.vars || theme).palette.primaryDark[600],
borderColor: (theme.vars || theme).palette.primaryDark[400],
color: (theme.vars || theme).palette.grey[100],
outlineColor: (theme.vars || theme).palette.primary[500],
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primaryDark[500],
color: (theme.vars || theme).palette.grey[50],
},
}),
}));
export default function SkipLink() {
const t = useTranslate();
return <StyledLink href="#main-content">{t('appFrame.skipToContent')}</StyledLink>;
}
| 5,314 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ThemeContext.js | import * as React from 'react';
import PropTypes from 'prop-types';
import {
ThemeProvider as MdThemeProvider,
createTheme as createMdTheme,
} from '@mui/material/styles';
import { deepmerge } from '@mui/utils';
import useMediaQuery from '@mui/material/useMediaQuery';
import { enUS, zhCN, ptBR } from '@mui/material/locale';
import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/material/utils';
import { getCookie } from 'docs/src/modules/utils/helpers';
import useLazyCSS from 'docs/src/modules/utils/useLazyCSS';
import { useUserLanguage } from 'docs/src/modules/utils/i18n';
import {
getDesignTokens,
getThemedComponents,
getMetaThemeColor,
} from 'docs/src/modules/brandingTheme';
const languageMap = {
en: enUS,
zh: zhCN,
pt: ptBR,
};
const themeInitialOptions = {
dense: false,
direction: 'ltr',
paletteColors: {},
spacing: 8, // spacing unit
paletteMode: 'light',
};
export const highDensity = {
components: {
MuiButton: {
defaultProps: {
size: 'small',
},
},
MuiFilledInput: {
defaultProps: {
margin: 'dense',
},
},
MuiFormControl: {
defaultProps: {
margin: 'dense',
},
},
MuiFormHelperText: {
defaultProps: {
margin: 'dense',
},
},
MuiIconButton: {
defaultProps: {
size: 'small',
},
},
MuiInputBase: {
defaultProps: {
margin: 'dense',
},
},
MuiInputLabel: {
defaultProps: {
margin: 'dense',
},
},
MuiListItem: {
defaultProps: {
dense: true,
},
},
MuiOutlinedInput: {
defaultProps: {
margin: 'dense',
},
},
MuiFab: {
defaultProps: {
size: 'small',
},
},
MuiTable: {
defaultProps: {
size: 'small',
},
},
MuiTextField: {
defaultProps: {
margin: 'dense',
},
},
MuiToolbar: {
defaultProps: {
variant: 'dense',
},
},
},
};
export const DispatchContext = React.createContext(() => {
throw new Error('Forgot to wrap component in `ThemeProvider`');
});
if (process.env.NODE_ENV !== 'production') {
DispatchContext.displayName = 'ThemeDispatchContext';
}
export function ThemeProvider(props) {
const { children } = props;
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)', { noSsr: true });
const preferredMode = prefersDarkMode ? 'dark' : 'light';
const [themeOptions, dispatch] = React.useReducer(
(state, action) => {
switch (action.type) {
case 'SET_SPACING':
return {
...state,
spacing: action.payload,
};
case 'INCREASE_SPACING': {
return {
...state,
spacing: state.spacing + 1,
};
}
case 'DECREASE_SPACING': {
return {
...state,
spacing: state.spacing - 1,
};
}
case 'SET_DENSE':
return {
...state,
dense: action.payload,
};
case 'RESET_DENSITY':
return {
...state,
dense: themeInitialOptions.dense,
spacing: themeInitialOptions.spacing,
};
case 'RESET_COLORS':
return {
...state,
paletteColors: themeInitialOptions.paletteColors,
};
case 'CHANGE':
return {
...state,
paletteMode: action.payload.paletteMode || state.paletteMode,
direction: action.payload.direction || state.direction,
paletteColors: action.payload.paletteColors || state.paletteColors,
};
default:
throw new Error(`Unrecognized type ${action.type}`);
}
},
{ ...themeInitialOptions, paletteMode: 'light' },
);
const userLanguage = useUserLanguage();
const { dense, direction, paletteColors, paletteMode, spacing } = themeOptions;
useLazyCSS('/static/styles/prism-okaidia.css', '#prismjs');
useEnhancedEffect(() => {
const nextPaletteColors = JSON.parse(getCookie('paletteColors') || 'null');
let nextPaletteMode = preferredMode; // syncing with homepage, can be removed once all pages are migrated to CSS variables
try {
nextPaletteMode = localStorage.getItem('mui-mode') ?? preferredMode;
} catch (error) {
// mainly thrown when cookies are disabled.
}
if (nextPaletteMode === 'system') {
nextPaletteMode = preferredMode;
}
dispatch({
type: 'CHANGE',
payload: { paletteColors: nextPaletteColors, paletteMode: nextPaletteMode },
});
}, [preferredMode]);
useEnhancedEffect(() => {
document.body.dir = direction;
}, [direction]);
useEnhancedEffect(() => {
// To support light and dark mode images in the docs
if (paletteMode === 'dark') {
document.body.classList.remove('mode-light');
document.body.classList.add('mode-dark');
} else {
document.body.classList.remove('mode-dark');
document.body.classList.add('mode-light');
}
const metas = document.querySelectorAll('meta[name="theme-color"]');
metas.forEach((meta) => {
meta.setAttribute('content', getMetaThemeColor(paletteMode));
});
}, [paletteMode]);
const theme = React.useMemo(() => {
const brandingDesignTokens = getDesignTokens(paletteMode);
const nextPalette = deepmerge(brandingDesignTokens.palette, paletteColors);
let nextTheme = createMdTheme(
{
direction,
...brandingDesignTokens,
palette: {
...nextPalette,
mode: paletteMode,
},
// v5 migration
props: {
MuiBadge: {
overlap: 'rectangular',
},
},
spacing,
},
dense ? highDensity : null,
{
components: {
MuiCssBaseline: {
defaultProps: {
// TODO: Material UI v6, makes this the default
enableColorScheme: true,
},
},
},
},
languageMap[userLanguage],
);
nextTheme = deepmerge(nextTheme, getThemedComponents(nextTheme));
return nextTheme;
}, [dense, direction, paletteColors, paletteMode, spacing, userLanguage]);
React.useEffect(() => {
// Expose the theme as a global variable so people can play with it.
window.theme = theme;
window.createTheme = createMdTheme;
}, [theme]);
// TODO: remove MdThemeProvider, top level layout should render the default theme.
return (
<MdThemeProvider theme={theme}>
<DispatchContext.Provider value={dispatch}>{children}</DispatchContext.Provider>
</MdThemeProvider>
);
}
ThemeProvider.propTypes = {
children: PropTypes.node,
};
/**
* @returns {(nextOptions: Partial<typeof themeInitialOptions>) => void}
*/
export function useChangeTheme() {
const dispatch = React.useContext(DispatchContext);
return React.useCallback((options) => dispatch({ type: 'CHANGE', payload: options }), [dispatch]);
}
| 5,315 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ThemeViewer.tsx | import * as React from 'react';
import clsx from 'clsx';
import { styled, alpha, lighten } from '@mui/material/styles';
import Box from '@mui/material/Box';
import ExpandIcon from '@mui/icons-material/ExpandMore';
import CollapseIcon from '@mui/icons-material/ChevronRight';
import { TreeView } from '@mui/x-tree-view/TreeView';
import { TreeItem as MuiTreeItem, treeItemClasses } from '@mui/x-tree-view/TreeItem';
import { blue, blueDark } from 'docs/src/modules/brandingTheme';
function getType(value: any) {
if (Array.isArray(value)) {
return 'array';
}
if (value === null) {
return 'null';
}
if (/^(#|rgb|rgba|hsl|hsla)/.test(value)) {
return 'color';
}
return typeof value;
}
/**
* @param {unknown} value
* @param {ReturnType<typeof getType>} type
*/
function getLabel(value: any, type: string) {
switch (type) {
case 'array':
return `Array(${value.length})`;
case 'null':
return 'null';
case 'undefined':
return 'undefined';
case 'function':
return `f ${value.name}()`;
case 'object':
return 'Object';
case 'string':
return `"${value}"`;
case 'symbol':
return `Symbol(${String(value)})`;
case 'bigint':
case 'boolean':
case 'number':
default:
return String(value);
}
}
function getTokenType(type: string) {
switch (type) {
case 'color':
return 'string';
case 'object':
case 'array':
return 'comment';
default:
return type;
}
}
const Color = styled('span')(({ theme }) => ({
backgroundColor: '#fff',
display: 'inline-block',
marginBottom: -1,
marginRight: theme.spacing(0.5),
border: '1px solid',
backgroundImage:
'url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%202%202%22%3E%3Cpath%20d%3D%22M1%202V0h1v1H0v1z%22%20fill-opacity%3D%22.2%22%2F%3E%3C%2Fsvg%3E")',
}));
function ObjectEntryLabel(props: { objectKey: string; objectValue: any }) {
const { objectKey, objectValue } = props;
const type = getType(objectValue);
const label = getLabel(objectValue, type);
const tokenType = getTokenType(type);
return (
<React.Fragment>
{`${objectKey}: `}
{type === 'color' ? (
<Color style={{ borderColor: lighten(label, 0.7) }}>
<Box
component="span"
sx={{ display: 'block', width: 11, height: 11 }}
style={{ backgroundColor: label }}
/>
</Color>
) : null}
<span className={clsx('token', tokenType)}>{label}</span>
</React.Fragment>
);
}
const TreeItem = styled(MuiTreeItem)(({ theme }) => ({
[`& .${treeItemClasses.content}`]: {
padding: 4,
borderRadius: 8,
'&:hover': {
backgroundColor: alpha(blueDark[600], 0.2),
},
'&:focus': {
[`& .${treeItemClasses.content}`]: {
backgroundColor: lighten(blue[900], 0.05),
outline: `2px dashed ${lighten(blue[900], 0.3)}`,
},
},
[`& .${treeItemClasses.label}`]: {
fontFamily: 'Menlo, Consolas, Droid Sans Mono, monospace',
fontSize: theme.typography.pxToRem(13),
},
},
}));
function ObjectEntry(props: { nodeId: string; objectKey: string; objectValue: any }) {
const { nodeId, objectKey, objectValue } = props;
const keyPrefix = nodeId;
let children = null;
if (
(objectValue !== null && typeof objectValue === 'object') ||
typeof objectValue === 'function'
) {
children =
Object.keys(objectValue).length === 0
? undefined
: Object.keys(objectValue).map((key) => {
return (
<ObjectEntry
key={key}
nodeId={`${keyPrefix}.${key}`}
objectKey={key}
objectValue={objectValue[key]}
/>
);
});
}
return (
<TreeItem
nodeId={nodeId}
label={<ObjectEntryLabel objectKey={objectKey} objectValue={objectValue} />}
>
{children}
</TreeItem>
);
}
function computeNodeIds(object: Record<string, any>, prefix: string) {
if ((object !== null && typeof object === 'object') || typeof object === 'function') {
const ids: Array<string> = [];
Object.keys(object).forEach((key) => {
ids.push(`${prefix}${key}`, ...computeNodeIds(object[key], `${prefix}${key}.`));
});
return ids;
}
return [];
}
export function useNodeIdsLazy(object: Record<string, any>) {
const [allNodeIds, setAllNodeIds] = React.useState<Array<string>>([]);
// technically we want to compute them lazily until we need them (expand all)
// yielding is good enough. technically we want to schedule the computation
// with low pri and upgrade the priority later
React.useEffect(() => {
setAllNodeIds(computeNodeIds(object, ''));
}, [object]);
return allNodeIds;
}
const keyPrefix = '$ROOT';
export default function ThemeViewer({
data,
expandPaths = [],
...other
}: {
data: Record<string, any>;
expandPaths: Array<string> | null;
}) {
const defaultExpanded = React.useMemo(
() =>
Array.isArray(expandPaths)
? expandPaths.map((expandPath) => `${keyPrefix}.${expandPath}`)
: [],
[expandPaths],
);
// for default* to take effect we need to remount
const key = React.useMemo(() => defaultExpanded.join(''), [defaultExpanded]);
return (
<TreeView
key={key}
defaultCollapseIcon={<ExpandIcon />}
defaultEndIcon={<div style={{ width: 24 }} />}
defaultExpanded={defaultExpanded}
defaultExpandIcon={<CollapseIcon />}
{...other}
sx={{
color: '#FFF',
p: 1.5,
bgcolor: '#0F1924', // one-off code container color
borderRadius: 3,
border: `1px solid ${blueDark[700]}`,
}}
>
{Object.keys(data).map((objectKey) => {
return (
<ObjectEntry
key={objectKey}
nodeId={`${keyPrefix}.${objectKey}`}
objectKey={objectKey}
objectValue={data[objectKey]}
/>
);
})}
</TreeView>
);
}
| 5,316 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/TopLayoutBlog.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { styled, alpha } from '@mui/material/styles';
import { useRouter } from 'next/router';
import { exactProp } from '@mui/utils';
import ChevronLeftRoundedIcon from '@mui/icons-material/ChevronLeftRounded';
import Divider from '@mui/material/Divider';
import Typography from '@mui/material/Typography';
import Avatar from '@mui/material/Avatar';
import Head from 'docs/src/modules/components/Head';
import BrandingCssVarsProvider from 'docs/src/BrandingCssVarsProvider';
import AppHeader from 'docs/src/layouts/AppHeader';
import AppContainer from 'docs/src/modules/components/AppContainer';
import AppFooter from 'docs/src/layouts/AppFooter';
import HeroEnd from 'docs/src/components/home/HeroEnd';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import ROUTES from 'docs/src/route';
import Link from 'docs/src/modules/components/Link';
export const authors = {
oliviertassinari: {
name: 'Olivier Tassinari',
avatar: 'https://avatars.githubusercontent.com/u/3165635',
github: 'oliviertassinari',
},
mbrookes: {
name: 'Matt Brookes',
avatar: 'https://avatars.githubusercontent.com/u/357702',
github: 'mbrookes',
},
eps1lon: {
name: 'Sebastian Silbermann',
avatar: 'https://avatars.githubusercontent.com/u/12292047',
github: 'eps1lon',
},
mnajdova: {
name: 'Marija Najdova',
avatar: 'https://avatars.githubusercontent.com/u/4512430',
github: 'mnajdova',
},
michaldudak: {
name: 'Michał Dudak',
avatar: 'https://avatars.githubusercontent.com/u/4696105',
github: 'michaldudak',
},
siriwatknp: {
name: 'Siriwat Kunaporn',
avatar: 'https://avatars.githubusercontent.com/u/18292247',
github: 'siriwatknp',
},
'danilo-leal': {
name: 'Danilo Leal',
avatar: 'https://avatars.githubusercontent.com/u/67129314',
github: 'danilo-leal',
},
m4theushw: {
name: 'Matheus Wichman',
avatar: 'https://avatars.githubusercontent.com/u/42154031',
github: 'm4theushw',
},
flaviendelangle: {
name: 'Flavien Delangle',
avatar: 'https://avatars.githubusercontent.com/u/3309670',
github: 'flaviendelangle',
},
DanailH: {
name: 'Danail Hadjiatanasov',
avatar: 'https://avatars.githubusercontent.com/u/5858539',
github: 'DanailH',
},
alexfauquette: {
name: 'Alexandre Fauquette',
avatar: 'https://avatars.githubusercontent.com/u/45398769',
github: 'alexfauquette',
},
samuelsycamore: {
name: 'Sam Sycamore',
avatar: 'https://avatars.githubusercontent.com/u/71297412',
github: 'samuelsycamore',
},
josefreitas: {
name: 'José Freitas',
avatar: 'https://avatars.githubusercontent.com/u/550141',
github: 'joserodolfofreitas',
},
cherniavskii: {
name: 'Andrew Cherniavskyi',
avatar: 'https://avatars.githubusercontent.com/u/13808724',
github: 'cherniavskii',
},
mikailaread: {
name: 'Mikaila Read',
avatar: 'https://avatars.githubusercontent.com/u/76401606',
github: 'mikailaread',
},
prakhargupta: {
name: 'Prakhar Gupta',
avatar: 'https://avatars.githubusercontent.com/u/92228082',
github: 'prakhargupta1',
},
richbustos: {
name: 'Rich Bustos',
avatar: 'https://avatars.githubusercontent.com/u/92274722',
github: 'richbustos',
},
};
const classes = {
back: 'TopLayoutBlog-back',
time: 'TopLayoutBlog-time',
container: 'TopLayoutBlog-container',
};
// Replicate the value used by https://medium.com/, a trusted reference.
const BLOG_MAX_WIDTH = 692;
const AuthorsContainer = styled('div')(({ theme }) => ({
display: 'flex',
flexWrap: 'wrap',
marginBottom: theme.spacing(2),
'& .author': {
display: 'flex',
alignItems: 'center',
paddingBottom: theme.spacing(2),
paddingRight: theme.spacing(3),
'& .MuiAvatar-root': {
marginRight: theme.spacing(1),
},
},
}));
const Root = styled('div')(
({ theme }) => ({
flexGrow: 1,
background: `linear-gradient(180deg, ${
(theme.vars || theme).palette.grey[50]
} 0%, #FFFFFF 100%)`,
backgroundSize: '100% 500px',
backgroundRepeat: 'no-repeat',
[`& .${classes.back}`]: {
display: 'flex',
alignItems: 'center',
marginBottom: theme.spacing(2),
marginLeft: theme.spacing(-1),
},
[`& .${classes.container}`]: {
paddingTop: 60 + 20,
marginBottom: theme.spacing(12),
maxWidth: `calc(${BLOG_MAX_WIDTH}px + ${theme.spacing(2 * 2)})`,
[theme.breakpoints.up('md')]: {
maxWidth: `calc(${BLOG_MAX_WIDTH}px + ${theme.spacing(3 * 2)})`,
},
[theme.breakpoints.up('lg')]: {
maxWidth: `calc(${BLOG_MAX_WIDTH}px + ${theme.spacing(8 * 2)})`,
},
'& h1': {
marginBottom: theme.spacing(3),
},
'& .markdown-body': {
lineHeight: 1.7,
},
'& img, & video': {
borderRadius: 4,
display: 'block',
margin: 'auto',
},
'& strong': {
color: (theme.vars || theme).palette.grey[900],
},
'& summary': {
padding: 8,
fontSize: theme.typography.pxToRem(14),
fontWeight: theme.typography.fontWeightMedium,
color: (theme.vars || theme).palette.grey[900],
},
'& details': {
paddingLeft: 16,
paddingRight: 16,
background: alpha(theme.palette.grey[50], 0.5),
border: '1px solid',
borderRadius: 10,
borderColor: (theme.vars || theme).palette.grey[200],
transitionProperty: 'all',
transitionTiming: 'cubic-bezier(0.4, 0, 0.2, 1)',
transitionDuration: '200ms',
'&:hover, &:focus-visible': {
background: (theme.vars || theme).palette.grey[50],
borderColor: (theme.vars || theme).palette.grey[300],
},
},
'& th': {
textAlign: 'left',
borderBottom: `3px solid rgba(62, 80, 96, 0.2) !important`,
},
'& .blog-description': {
fontSize: theme.typography.pxToRem(13),
marginTop: 8,
textAlign: 'center',
color: (theme.vars || theme).palette.grey[700],
'& a': {
color: 'inherit',
textDecoration: 'underline',
},
},
'& .MuiCode-root + .blog-description': {
marginTop: -20 + 8,
},
},
[`& .${classes.time}`]: {
color: (theme.vars || theme).palette.text.secondary,
...theme.typography.caption,
fontWeight: 500,
},
}),
({ theme }) =>
theme.applyDarkStyles({
background: `linear-gradient(180deg, ${alpha(theme.palette.primary[900], 0.2)} 0%, ${
(theme.vars || theme).palette.primaryDark[800]
} 100%)`,
backgroundSize: '100% 500px',
backgroundRepeat: 'no-repeat',
[`& .${classes.container}`]: {
'& strong': {
color: (theme.vars || theme).palette.grey[100],
},
'& summary': {
color: (theme.vars || theme).palette.grey[300],
},
'& details': {
background: alpha(theme.palette.primary[900], 0.3),
borderColor: (theme.vars || theme).palette.primaryDark[700],
'&:hover, &:focus-visible': {
background: alpha(theme.palette.primary[900], 0.4),
borderColor: (theme.vars || theme).palette.primaryDark[500],
},
},
'& .blog-description': {
color: (theme.vars || theme).palette.grey[500],
},
},
}),
);
export default function TopLayoutBlog(props) {
const { className, docs } = props;
const { description, rendered, title, headers } = docs.en;
const finalTitle = title || headers.title;
const router = useRouter();
const slug = router.pathname.replace(/(.*)\/(.*)/, '$2');
const { canonicalAsServer } = pathnameToLanguage(router.asPath);
const card =
headers.card === 'true'
? `https://mui.com/static/blog/${slug}/card.png`
: 'https://mui.com/static/logo.png';
return (
<BrandingCssVarsProvider>
<AppHeader />
<Head
title={`${finalTitle} - MUI`}
description={description}
largeCard={headers.card === 'true'}
disableAlternateLocale
card={card}
type="article"
>
<meta name="author" content={headers.authors.map((key) => authors[key].name).join(', ')} />
<meta property="article:published_time" content={headers.date} />
<script
type="application/ld+json"
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: JSON.stringify({
'@context': 'https://schema.org',
'@type': 'Article',
publisher: {
'@type': 'Organization',
name: 'MUI blog',
url: 'https://mui.com/blog/',
logo: {
'@type': 'ImageObject',
url: 'https://mui.com/static/icons/512x512.png',
},
},
author: {
'@type': 'Person',
name: authors[headers.authors[0]].name,
image: {
'@type': 'ImageObject',
url: `${authors[headers.authors[0]].avatar}?s=${250}`,
width: 250,
height: 250,
},
sameAs: [`https://github.com/${authors[headers.authors[0]].github}`],
},
headline: finalTitle,
url: `https://mui.com${canonicalAsServer}`,
datePublished: headers.date,
dateModified: headers.date,
image: {
'@type': 'ImageObject',
url: card,
width: 1280,
height: 640,
},
keywords: headers.tags.join(', '),
description,
mainEntityOfPage: {
'@type': 'WebPage',
'@id': 'https://mui.com/blog/',
},
}),
}}
/>
</Head>
<Root className={className}>
<AppContainer component="main" className={classes.container}>
<Link
href={ROUTES.blog}
{...(ROUTES.blog.startsWith('http') && {
rel: 'nofollow',
})}
color="primary"
variant="body2"
className={classes.back}
>
<ChevronLeftRoundedIcon fontSize="small" sx={{ mr: 0.5 }} />
{/* eslint-disable-next-line material-ui/no-hardcoded-labels */}
{'Back to blog'}
</Link>
{headers.title ? (
<React.Fragment>
{/*
Depending on the timezone, the display date can change from one day to another.
e.g. Sunday vs. Monday
TODO: Move the date formating to the server.
*/}
<time dateTime={headers.date} className={classes.time}>
{new Intl.DateTimeFormat('en', {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric',
}).format(new Date(headers.date))}
</time>
<MarkdownElement>
<h1>{headers.title}</h1>
</MarkdownElement>
<AuthorsContainer>
{headers.authors.map((author) => (
<div key={author} className="author">
<Avatar
sx={{ width: 36, height: 36 }}
alt=""
src={`${authors[author].avatar}?s=${36}`}
srcSet={`${authors[author].avatar}?s=${36 * 2} 2x`}
/>
<div>
<Typography variant="body2" fontWeight="500">
{authors[author].name}
</Typography>
<Link
href={`https://github.com/${authors[author].github}`}
target="_blank"
rel="noreferrer noopener"
color="primary"
variant="body2"
sx={{ fontWeight: 500 }}
>
@{authors[author].github}
</Link>
</div>
</div>
))}
</AuthorsContainer>
</React.Fragment>
) : null}
{rendered.map((chunk, index) => {
return <MarkdownElement key={index} renderedMarkdown={chunk} />;
})}
</AppContainer>
<Divider />
<HeroEnd />
<Divider />
<AppFooter />
</Root>
</BrandingCssVarsProvider>
);
}
TopLayoutBlog.propTypes = {
className: PropTypes.string,
docs: PropTypes.object.isRequired,
};
if (process.env.NODE_ENV !== 'production') {
TopLayoutBlog.propTypes = exactProp(TopLayoutBlog.propTypes);
}
| 5,317 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/TopLayoutCareers.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import Divider from '@mui/material/Divider';
import Head from 'docs/src/modules/components/Head';
import AppContainer from 'docs/src/modules/components/AppContainer';
import AppFooter from 'docs/src/layouts/AppFooter';
import AppHeader from 'docs/src/layouts/AppHeader';
import BrandingCssVarsProvider from 'docs/src/BrandingCssVarsProvider';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
import Link from 'docs/src/modules/components/Link';
const StyledDiv = styled('div')({
flex: '1 0 100%',
});
const StyledAppContainer = styled(AppContainer)(({ theme }) => ({
'& .markdownElement': {
[theme.breakpoints.up('md')]: {
paddingRight: theme.spacing(4),
},
},
}));
export default function TopLayoutCareers(props) {
const { docs } = props;
const { description, rendered, title } = docs.en;
return (
<BrandingCssVarsProvider>
<AppHeader />
<Head title={`${title} - MUI`} description={description}>
<meta name="robots" content="noindex,nofollow" />
</Head>
<StyledDiv>
<StyledAppContainer component="main" sx={{ py: { xs: 3, sm: 4, md: 8 } }}>
<Link
href="/careers/#open-roles"
rel="nofollow"
variant="body2"
sx={{ display: 'block', mb: 2 }}
>
{/* eslint-disable-next-line material-ui/no-hardcoded-labels */}
{'< Back to open roles'}
</Link>
{rendered.map((chunk, index) => {
return <MarkdownElement key={index} renderedMarkdown={chunk} />;
})}
</StyledAppContainer>
<Divider />
<AppFooter />
</StyledDiv>
</BrandingCssVarsProvider>
);
}
TopLayoutCareers.propTypes = {
docs: PropTypes.object.isRequired,
};
| 5,318 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/W3CIcon.js | import * as React from 'react';
import { createSvgIcon } from '@mui/material/utils';
export default createSvgIcon(
<g fillRule="nonzero" fill="none">
<path
d="M6.92 6.1l2.33 7.99 2.32-8h6.3v.8l-2.37 4.14c.83.27 1.46.76 1.89 1.47.43.71.64 1.55.64 2.51 0 1.2-.31 2.2-.94 3a2.93 2.93 0 01-2.42 1.22 2.9 2.9 0 01-1.96-.72 4.25 4.25 0 01-1.23-1.96l1.31-.55c.2.5.45.9.76 1.18.32.28.69.43 1.12.43.44 0 .82-.26 1.13-.76.31-.51.47-1.12.47-1.84 0-.79-.17-1.4-.5-1.83-.38-.5-.99-.76-1.81-.76h-.64v-.78l2.24-3.92h-2.7l-.16.26-3.3 11.25h-.15l-2.4-8.14-2.41 8.14h-.16L.43 6.1H2.1l2.33 7.99L6 8.71 5.24 6.1h1.68z"
fill="#005A9C"
/>
<g fill="currentColor">
<path d="M23.52 6.25l.28 1.62-.98 1.8s-.38-.76-1.01-1.19c-.53-.35-.87-.43-1.41-.33-.7.14-1.48.93-1.82 1.9-.41 1.18-.42 1.74-.43 2.26a4.9 4.9 0 00.11 1.33s-.6-1.06-.59-2.61c0-1.1.19-2.11.72-3.1.47-.87 1.17-1.4 1.8-1.45.63-.07 1.14.23 1.53.55.42.33.83 1.07.83 1.07l.97-1.85zM23.64 15.4s-.43.75-.7 1.04c-.27.28-.76.79-1.36 1.04-.6.25-.91.3-1.5.25a3.03 3.03 0 01-1.34-.52 5.08 5.08 0 01-1.67-2.04s.24.75.39 1.07c.09.18.36.74.74 1.23a3.5 3.5 0 002.1 1.42c1.04.18 1.76-.27 1.94-.38a5.32 5.32 0 001.4-1.43c.1-.14.25-.43.25-.43l-.25-1.25z" />
</g>
</g>,
'W3C',
);
| 5,319 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ad.styles.js | import { alpha } from '@mui/material/styles';
import { adShape } from 'docs/src/modules/components/AdManager';
const adBodyImageStyles = (theme) => ({
root: {
display: 'block',
overflow: 'hidden',
border: '1px dashed',
borderColor: theme.palette.divider,
padding: '12px 12px 12px calc(12px + 130px)',
borderRadius: theme.shape.borderRadius,
},
imgWrapper: {
float: 'left',
marginLeft: -130,
width: 130,
height: 100,
},
img: {
verticalAlign: 'middle',
},
a: {
color: theme.palette.text.primary,
textDecoration: 'none',
},
description: {
...theme.typography.body1,
display: 'block',
marginLeft: theme.spacing(1.5),
},
poweredby: {
...theme.typography.caption,
marginLeft: theme.spacing(1.5),
color: theme.palette.text.secondary,
display: 'block',
marginTop: theme.spacing(0.5),
fontWeight: theme.typography.fontWeightRegular,
},
});
const adBodyInlineStyles = (theme) => {
const baseline = adBodyImageStyles(theme);
return {
...baseline,
root: {
display: 'block',
paddingTop: 8,
},
imgWrapper: {
display: 'none',
},
description: {
...baseline.description,
marginLeft: 0,
'&:before': {
border: '1px solid #3e8e41',
color: '#3e8e41',
marginRight: 6,
padding: '1px 5px',
borderRadius: 3,
content: '"Ad"',
fontSize: theme.typography.pxToRem(14),
},
'&:after': {
// Link
marginLeft: 4,
content: '"Get started"',
// Style taken from the Link component & MarkdownElement.
color:
theme.palette.mode === 'light' ? theme.palette.primary[600] : theme.palette.primary[300],
textDecoration: 'underline',
textDecorationColor: alpha(theme.palette.primary.main, 0.4),
},
},
poweredby: {
...baseline.poweredby,
marginTop: 2,
marginLeft: 0,
},
link: {
display: 'none',
},
};
};
export const adStylesObject = {
'body-image': adBodyImageStyles,
'body-inline': adBodyInlineStyles,
};
export default adStylesObject[`body-${adShape}`];
| 5,320 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/bootstrap.js | // Disable auto highlighting
// https://github.com/PrismJS/prism/issues/765
if (typeof window !== 'undefined') {
window.Prism = window.Prism || {};
window.Prism.manual = true;
}
| 5,321 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/list/CSSList.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import { styled } from '@mui/material/styles';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import ExpendableApiItem, {
ApiItemContaier,
} from 'docs/src/modules/components/ApiPage/list/ExpendableApiItem';
import { brandingDarkTheme as darkTheme } from 'docs/src/modules/brandingTheme';
const StyledApiItem = styled(ExpendableApiItem)(
({ theme }) => ({
'& p': {
margin: 0,
},
'& .prop-list-title': {
...theme.typography.body2,
fontWeight: theme.typography.fontWeightSemiBold,
color: theme.palette.text.primary,
paddingRight: 5,
whiteSpace: 'nowrap',
margin: 0,
},
'& .prop-list-class': {
margin: 0,
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& .prop-list-title': {
color: `var(--muidocs-palette-grey-50, ${darkTheme.palette.grey[50]})`,
},
},
}),
);
type HashParams = { componentName?: string; className: string };
export type CSSFormatedParams = {
componentName?: string;
className: string;
isGlobalStateClass: boolean;
selector: string;
description?: string;
};
export const getHash = ({ componentName, className }: HashParams) =>
`${componentName ? `${componentName}-` : ''}css-${className}`;
interface CSSListProps {
classes: CSSFormatedParams[];
displayOption: 'collapsed' | 'expended';
}
export default function CSSList(props: CSSListProps) {
const { classes, displayOption } = props;
const t = useTranslate();
return (
<ApiItemContaier>
{classes.map((params) => {
const { componentName, className, isGlobalStateClass, selector, description } = params;
return (
<StyledApiItem
key={className}
id={getHash({ componentName, className })}
title={selector}
note={isGlobalStateClass ? t('api-docs.state') : ''}
type="CSS"
displayOption={displayOption}
>
{description && (
<p
dangerouslySetInnerHTML={{
__html: description,
}}
/>
)}
{className && (
<p className="prop-list-class">
<span className="prop-list-title">{'Rule name'}:</span>
<code className="Api-code">{className}</code>
</p>
)}
</StyledApiItem>
);
})}
</ApiItemContaier>
);
}
| 5,322 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/list/ClassesList.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import ExpendableApiItem, {
ApiItemContaier,
} from 'docs/src/modules/components/ApiPage/list/ExpendableApiItem';
export type ClassesFormatedParams = {
className: string;
isGlobalStateClass: boolean;
cssClassName: string;
description?: string;
componentName: string;
};
type ClassesListProps = {
classes: ClassesFormatedParams[];
displayOption: 'collapsed' | 'expended';
};
type HashParams = { componentName?: string; className: string };
export const getHash = ({ componentName, className }: HashParams) =>
`${componentName ? `${componentName}-` : ''}classes-${className}`;
export default function ClassesList(props: ClassesListProps) {
const { classes, displayOption } = props;
const t = useTranslate();
return (
<ApiItemContaier>
{classes.map((params) => {
const { className, isGlobalStateClass, cssClassName, description, componentName } = params;
return (
<ExpendableApiItem
id={getHash({ componentName, className })}
key={className}
note={isGlobalStateClass ? t('api-docs.state') : ''}
title={cssClassName}
type="classes"
displayOption={displayOption}
isExtendable={!!description}
>
{description && <p dangerouslySetInnerHTML={{ __html: description }} />}
</ExpendableApiItem>
);
})}
</ApiItemContaier>
);
}
| 5,323 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/list/ExpendableApiItem.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { alpha, styled } from '@mui/material/styles';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import { Divider, IconButton, SxProps } from '@mui/material';
import {
brandingDarkTheme as darkTheme,
brandingLightTheme as lightTheme,
} from 'docs/src/modules/brandingTheme';
type DescriptionType = 'props' | 'classes' | 'CSS' | 'slots';
const Root = styled('div')<{ ownerState: { type?: DescriptionType } }>(
({ theme }) => ({
position: 'relative',
marginBottom: 12,
scrollMarginTop: 'calc(var(--MuiDocs-header-height) + 32px)',
'& .MuiApi-item-header': {
minHeight: 26,
display: 'flex',
alignItems: 'center',
marginLeft: -38,
marginBottom: 8,
lineHeight: 1.5,
},
'& .MuiApi-item-link-visual': {
display: 'none',
flexShrink: 0,
border: '1px solid',
borderColor: `var(--muidocs-palette-divider, ${lightTheme.palette.divider})`,
borderRadius: 8,
backgroundColor: `var(--muidocs-palette-primary-50, ${lightTheme.palette.primary[50]})`,
height: 26,
width: 26,
textAlign: 'center',
lineHeight: '26px',
'& svg': {
fill: `var(--muidocs-palette-text-secondary, ${lightTheme.palette.text.secondary})`,
height: '14px',
width: '14px',
},
},
'& .MuiApi-item-title': {
marginLeft: 32,
padding: '2px 6px',
flexShrink: 0,
fontWeight: theme.typography.fontWeightSemiBold,
fontFamily: theme.typography.fontFamilyCode,
fontSize: theme.typography.pxToRem(13),
color: `var(--muidocs-palette-primary-600, ${lightTheme.palette.primary[600]})`,
},
'& .MuiApi-item-content': {
verticalAlign: 'top',
paddingBottom: theme.spacing(2),
p: { marginBottom: theme.spacing(1.5) },
},
'& .MuiApi-item-note': {
fontSize: 11,
marginLeft: 6,
letterSpacing: '1px',
textTransform: 'uppercase',
color: `var(--muidocs-palette-success-800, ${lightTheme.palette.success[800]})`,
fontWeight: theme.typography.fontWeightBold,
lineHeight: '24px',
},
'& .MuiApi-expend-button': {},
'& hr': {
margin: 0,
},
[theme.breakpoints.up('lg')]: {
'&:hover, &:target': {
'.MuiApi-item-link-visual': {
display: 'inline-block',
},
'.MuiApi-item-title': {
marginLeft: 6,
},
'.MuiApi-item-link-visual:hover': {
cursor: 'pointer',
backgroundColor: alpha(lightTheme.palette.primary[100], 0.4),
borderColor: `var(--muidocs-palette-primary-100, ${lightTheme.palette.primary[100]})`,
'& svg': {
fill: `var(--muidocs-palette-primary-main, ${lightTheme.palette.primary.main})`,
},
},
},
'&:target': {
'.MuiApi-item-link-visual': {
'&>svg': {
transform: 'rotate(90deg) translateX(-0.5px) translateY(0.1px)',
},
},
},
},
'& .MuiAlert-standardWarning': {
padding: '6px 12px',
fontWeight: theme.typography.fontWeightMedium,
border: '1px solid',
borderColor: `var(--muidocs-palette-warning-300, ${lightTheme.palette.warning[300]})`,
borderRadius: 12,
backgroundColor: `var(--muidocs-palette-warning-50, ${lightTheme.palette.warning[50]})`,
color: `var(--muidocs-palette-warning-800, ${lightTheme.palette.warning[800]})`,
marginBottom: 16,
'.MuiAlert-icon': {
display: 'flex',
alignItems: 'center',
fill: `var(--muidocs-palette-warning-800, ${lightTheme.palette.warning[800]})`,
},
},
'& code.Api-code': {
...theme.typography.caption,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightRegular,
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
padding: '1px 4px',
borderRadius: 6,
border: '1px solid',
borderColor: alpha(darkTheme.palette.primary[100], 0.8),
backgroundColor: `var(--muidocs-palette-primary-50, ${lightTheme.palette.primary[50]})`,
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& .MuiApi-item-header': {
'&>span, &>div': {
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
},
'& .MuiApi-item-title': {
color: `var(--muidocs-palette-primary-200, ${darkTheme.palette.primary[200]})`,
},
'& .MuiApi-item-link-visual': {
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
backgroundColor: alpha(darkTheme.palette.primary[900], 0.5),
'& svg': {
fill: `var(--muidocs-palette-primary-200, ${darkTheme.palette.primary[200]})`,
},
},
'&:hover, &:target': {
'.MuiApi-item-link-visual:hover': {
borderColor: `var(--muidocs-palette-primary-900, ${darkTheme.palette.primary[900]})`,
backgroundColor: alpha(darkTheme.palette.primary[900], 0.6),
'& svg': {
fill: `var(--muidocs-palette-primary-100, ${darkTheme.palette.primary[100]})`,
},
},
},
'& .MuiApi-item-description': {
color: `var(--muidocs-palette-grey-500, ${darkTheme.palette.grey[500]})`,
},
'& .MuiApi-item-note': {
color: `var(--muidocs-palette-success-400, ${darkTheme.palette.success[400]})`,
},
},
'& .MuiAlert-standardWarning': {
borderColor: alpha(darkTheme.palette.warning[800], 0.3),
backgroundColor: alpha(darkTheme.palette.warning[800], 0.2),
color: `var(--muidocs-palette-warning-100, ${darkTheme.palette.warning[100]})`,
'.MuiAlert-icon svg': {
fill: `var(--muidocs-palette-warning-400, ${darkTheme.palette.warning[400]})`,
},
},
'& code.Api-code': {
borderColor: alpha(darkTheme.palette.primary[400], 0.1),
backgroundColor: alpha(darkTheme.palette.primary[900], 0.4),
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
},
},
}),
);
export type ApiItemProps = {
id: string;
title: string;
description?: string;
note?: string;
type?: DescriptionType;
isExtendable?: boolean;
className?: string;
children?: React.ReactNode;
sx?: SxProps;
displayOption?: 'collapsed' | 'expended';
};
function ApiItem(props: ApiItemProps) {
const {
title,
description,
note,
children,
type,
id,
isExtendable = true,
className,
displayOption,
...other
} = props;
const [isExtended, setIsExtended] = React.useState(() => displayOption === 'expended');
React.useEffect(() => {
setIsExtended(displayOption === 'expended');
}, [displayOption]);
return (
<Root
ownerState={{ type }}
{...other}
id={id}
className={clsx(
`MuiApi-item-root ${isExtendable ? 'MuiApi-item-header-extendable' : ''}`,
className,
)}
>
<div className="MuiApi-item-header">
<a className="MuiApi-item-link-visual" href={`#${id}`}>
<svg>
<use xlinkHref="#anchor-link-icon" />
</svg>
</a>
<span
className="MuiApi-item-title algolia-lvl3" // This className is used by Algolia
>
{title}
</span>
{note && <span className="MuiApi-item-note">{note}</span>}
{isExtendable && (
<IconButton
onClick={() => setIsExtended((prev) => !prev)}
className="MuiApi-expend-button"
size="small"
sx={{ p: 0, ml: 'auto', borderRadius: '6px' }}
>
{isExtended ? (
<KeyboardArrowUpIcon sx={{ color: 'grey.500' }} />
) : (
<KeyboardArrowDownIcon sx={{ color: 'grey.500' }} />
)}
</IconButton>
)}
</div>
{isExtended && <div className={`MuiApi-item-content`}>{isExtended && children}</div>}
<Divider />
</Root>
);
}
ApiItem.propTypes = {
description: PropTypes.string,
note: PropTypes.string,
title: PropTypes.string.isRequired,
};
export const ApiItemContaier = styled('div')({
width: '100%',
display: 'flex',
flexDirection: 'column',
});
export default ApiItem;
| 5,324 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/list/PropertiesList.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import Alert from '@mui/material/Alert';
import WarningRoundedIcon from '@mui/icons-material/WarningRounded';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import {
brandingDarkTheme as darkTheme,
brandingLightTheme as lightTheme,
} from 'docs/src/modules/brandingTheme';
import ExpendableApiItem, {
ApiItemContaier,
} from 'docs/src/modules/components/ApiPage/list/ExpendableApiItem';
const StyledApiItem = styled(ExpendableApiItem)(
({ theme }) => ({
'& .prop-list-description': {
marginBottom: 10,
},
'& .prop-list-additional-info': {
display: 'flex',
flexDirection: 'column',
gap: 8,
'&>p': {
margin: 0,
},
'& .prop-list-title': {
...theme.typography.body2,
fontWeight: theme.typography.fontWeightSemiBold,
color: theme.palette.text.primary,
paddingRight: 5,
whiteSpace: 'nowrap',
margin: 0,
},
'& .default-value': {
fontSize: theme.typography.pxToRem(12),
},
},
'& .prop-list-deprecated': {
'& code ': { all: 'unset' },
},
'& .prop-list-default-props': {
...theme.typography.body2,
fontWeight: theme.typography.fontWeightSemiBold,
},
'& .prop-list-signature': {
p: {
...theme.typography.body2,
fontWeight: theme.typography.fontWeightSemiBold,
marginBottom: 8,
},
ul: {
paddingLeft: 24,
marginTop: 2,
marginBottom: 0,
},
'&>code': {
borderRadius: 8,
padding: 12,
width: '100%',
marginBottom: 8,
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[50]})`,
border: '1px solid',
borderColor: `var(--muidocs-palette-primaryDark-700, ${lightTheme.palette.primaryDark[700]})`,
backgroundColor: `var(--muidocs-palette-primaryDark-800, ${lightTheme.palette.primaryDark[800]})`,
},
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& .prop-list-additional-info': {
'& .prop-list-title': {
p: {
color: `var(--muidocs-palette-grey-50, ${darkTheme.palette.grey[50]})`,
},
},
},
'& .prop-list-default-props': {
color: `var(--muidocs-palette-grey-300, ${darkTheme.palette.grey[300]})`,
},
},
}),
);
function PropDescription({ description }: { description: string }) {
const isUlPresent = description.includes('<ul>');
const ComponentToRender = isUlPresent ? 'div' : 'p';
return (
<ComponentToRender
className="prop-list-description algolia-content" // This className is used by Algolia
dangerouslySetInnerHTML={{
__html: description,
}}
/>
);
}
PropDescription.propTypes = {
description: PropTypes.string.isRequired,
};
export const getHash = ({
targetName,
propName,
hooksParameters,
hooksReturnValue,
}: {
targetName: string;
propName: string;
hooksParameters?: boolean;
hooksReturnValue?: boolean;
}) => {
let sectionName = 'prop';
if (hooksParameters) {
sectionName = 'parameters';
} else if (hooksReturnValue) {
sectionName = 'return-value';
}
return `${targetName ? `${targetName}-` : ''}${sectionName}-${propName}`;
};
export interface PropDescriptionParams {
targetName: string;
propName: string;
description?: string;
requiresRef?: string;
isOptional?: boolean;
isRequired?: boolean;
isDeprecated?: boolean;
hooksParameters?: boolean;
hooksReturnValue?: boolean;
deprecationInfo?: string;
typeName: string;
propDefault?: string;
additionalInfo: string[];
signature?: string;
signatureArgs?: { argName: string; argDescription?: string }[];
signatureReturnDescription?: string;
}
interface PropertiesListProps {
properties: PropDescriptionParams[];
displayOption: 'collapsed' | 'expended';
}
export default function PropertiesList(props: PropertiesListProps) {
const { properties, displayOption } = props;
const t = useTranslate();
return (
<ApiItemContaier>
{properties.map((params) => {
const {
targetName,
propName,
description,
requiresRef,
isOptional,
isRequired,
isDeprecated,
hooksParameters,
hooksReturnValue,
deprecationInfo,
typeName,
propDefault,
additionalInfo,
signature,
signatureArgs,
signatureReturnDescription,
} = params;
return (
<StyledApiItem
key={propName}
id={getHash({ targetName, propName, hooksParameters, hooksReturnValue })}
title={propName}
note={(isOptional && 'Optional') || (isRequired && 'Required') || ''}
type="props"
displayOption={displayOption}
>
{description && <PropDescription description={description} />}
{requiresRef && (
<Alert
severity="warning"
icon={<WarningRoundedIcon fontSize="small" />}
sx={{
'& .MuiAlert-icon': {
height: 'fit-content',
py: '8px',
},
}}
>
<span
dangerouslySetInnerHTML={{
__html: t('api-docs.requires-ref'),
}}
/>
</Alert>
)}
{additionalInfo.map((key) => (
<p
className="prop-list-additional-description MuiApi-collapsible"
key={key}
dangerouslySetInnerHTML={{
__html: t(`api-docs.additional-info.${key}`),
}}
/>
))}
{isDeprecated && (
<Alert
className="MuiApi-collapsible prop-list-deprecated"
severity="warning"
icon={<WarningRoundedIcon fontSize="small" />}
sx={{
'& .MuiAlert-icon': {
height: 'fit-content',
py: '8px',
},
}}
>
{t('api-docs.deprecated')}
{deprecationInfo && (
<React.Fragment>
{' - '}
<span
dangerouslySetInnerHTML={{
__html: deprecationInfo,
}}
/>
</React.Fragment>
)}
</Alert>
)}
<div className="prop-list-additional-info">
{typeName && (
<p className="prop-list-type MuiApi-collapsible">
<span className="prop-list-title">{t('api-docs.type')}:</span>
<code
className="Api-code"
dangerouslySetInnerHTML={{
__html: typeName,
}}
/>
</p>
)}
{propDefault && (
<p className="prop-list-default-props MuiApi-collapsible">
<span className="prop-list-title">{t('api-docs.default')}:</span>
<code className="default-value">{propDefault}</code>
</p>
)}
{signature && (
<div className="prop-list-signature MuiApi-collapsible">
<span className="prop-list-title">{t('api-docs.signature')}:</span>
<div className="prop-list-content">
<code
dangerouslySetInnerHTML={{
__html: signature,
}}
/>
{signatureArgs && (
<div>
<ul>
{signatureArgs.map(({ argName, argDescription }) => (
<li
key={argName}
dangerouslySetInnerHTML={{
__html: `<code>${argName}</code> ${argDescription}`,
}}
/>
))}
</ul>
</div>
)}
{signatureReturnDescription && (
<p>
{t('api-docs.returns')}
<span
dangerouslySetInnerHTML={{
__html: signatureReturnDescription,
}}
/>
</p>
)}
</div>
</div>
)}
</div>
</StyledApiItem>
);
})}
</ApiItemContaier>
);
}
| 5,325 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/list/SlotsList.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import { styled, alpha } from '@mui/material/styles';
import {
brandingLightTheme as lightTheme,
brandingDarkTheme as darkTheme,
} from 'docs/src/modules/brandingTheme';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import ExpendableApiItem, {
ApiItemContaier,
} from 'docs/src/modules/components/ApiPage/list/ExpendableApiItem';
const StyledApiItem = styled(ExpendableApiItem)(
({ theme }) => ({
'.slot-classname, .slot-default-element': {
marginBottom: 8,
'& .prop-list-title': {
...theme.typography.body2,
fontWeight: theme.typography.fontWeightSemiBold,
color: theme.palette.text.primary,
},
},
'& .default-slot-value': {
...theme.typography.caption,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightRegular,
},
'& .global-class-value': {
...theme.typography.caption,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightRegular,
borderColor: alpha(darkTheme.palette.primary[100], 0.5),
backgroundColor: `var(--muidocs-palette-primary-50, ${lightTheme.palette.primary[50]})`,
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& .global-class-value': {
borderColor: alpha(darkTheme.palette.primary[400], 0.1),
backgroundColor: alpha(darkTheme.palette.primary[900], 0.4),
},
},
}),
);
export type SlotsFormatedParams = {
className: string;
componentName?: string;
description?: string;
name: string;
defaultValue?: string;
};
type HashParams = { componentName?: string; className: string };
export const getHash = ({ componentName, className }: HashParams) =>
`${componentName ? `${componentName}-` : ''}css-${className}`;
interface SlotsListProps {
slots: SlotsFormatedParams[];
displayOption: 'collapsed' | 'expended';
}
export default function SlotsList(props: SlotsListProps) {
const { slots, displayOption } = props;
const t = useTranslate();
return (
<ApiItemContaier className="MuiApi-slot-list">
{slots.map((params) => {
const { description, className, name, defaultValue, componentName } = params;
const isExtendable = description || defaultValue || className;
return (
<StyledApiItem
id={getHash({ componentName, className })}
key={className}
title={name}
note=""
type="slots"
isExtendable={!!isExtendable}
displayOption={displayOption}
>
{description && (
<p
dangerouslySetInnerHTML={{
__html: description,
}}
/>
)}
{className && (
<p className="slot-classname">
<span className="prop-list-title">{t('api-docs.globalClass')}:</span>{' '}
<code
dangerouslySetInnerHTML={{ __html: className }}
className="global-class-value"
/>
</p>
)}
{defaultValue && (
<p className="slot-default-element">
<span className="prop-list-title">{t('api-docs.default')}:</span>{' '}
<code className="default-slot-value">{defaultValue}</code>
</p>
)}
</StyledApiItem>
);
})}
</ApiItemContaier>
);
}
| 5,326 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/sections/ClassesSection.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import Box from '@mui/material/Box';
import ToggleDisplayOption, {
API_LAYOUT_STORAGE_KEYS,
useApiPageOption,
} from 'docs/src/modules/components/ApiPage/sections/ToggleDisplayOption';
import ClassesList from 'docs/src/modules/components/ApiPage/list/ClassesList';
import ClassesTable from 'docs/src/modules/components/ApiPage/table/ClassesTable';
type ComponentClasses = {
classes: string[];
globalClasses: { [classeKey: string]: string };
};
type ClassDescription = {
[classeKey: string]: {
description: string;
nodeName?: string;
conditions?: string;
};
};
export type ClassesSectionProps = {
componentClasses: ComponentClasses;
classDescriptions: ClassDescription;
componentName: string;
spreadHint?: string;
title: string;
titleHash: string;
level?: 'h2' | 'h3' | 'h4';
};
export default function ClassesSection(props: ClassesSectionProps) {
const {
componentClasses,
classDescriptions,
componentName,
spreadHint,
title = 'api-docs.classes',
titleHash = 'classes',
level: Level = 'h2',
} = props;
const t = useTranslate();
const [displayOption, setDisplayOption] = useApiPageOption(API_LAYOUT_STORAGE_KEYS.classes);
if (!componentClasses?.classes || componentClasses.classes.length === 0) {
return null;
}
const formatedClasses = componentClasses.classes
.map((classKey) => {
const className =
componentClasses.globalClasses[classKey] ||
`Mui${componentName.replace('Unstyled', '')}-${classKey}`;
const isGlobalStateClass = !!componentClasses.globalClasses[classKey];
const cssClassName = `.${className}`;
const description =
classDescriptions[classKey] &&
classDescriptions[classKey].description
.replace(/{{conditions}}/, classDescriptions[classKey].conditions!)
.replace(/{{nodeName}}/, classDescriptions[classKey].nodeName!);
return { className, isGlobalStateClass, cssClassName, description, componentName };
})
.sort((a, b) => a.className.localeCompare(b.className));
return (
<React.Fragment>
<Box sx={{ display: 'flex', alignItems: 'baseline', mb: 1 }}>
<Level id={titleHash} style={{ flexGrow: 1 }}>
{t(title)}
<a
aria-labelledby={titleHash}
className="anchor-link"
href={`#${titleHash}`}
tabIndex={-1}
>
<svg>
<use xlinkHref="#anchor-link-icon" />
</svg>
</a>
</Level>
<ToggleDisplayOption displayOption={displayOption} setDisplayOption={setDisplayOption} />
</Box>
{spreadHint && <p dangerouslySetInnerHTML={{ __html: spreadHint }} />}
{displayOption === 'table' ? (
<ClassesTable classes={formatedClasses} />
) : (
<ClassesList classes={formatedClasses} displayOption={displayOption} />
)}
</React.Fragment>
);
}
| 5,327 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/sections/CssSection.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import Box from '@mui/material/Box';
import ToggleDisplayOption, {
API_LAYOUT_STORAGE_KEYS,
useApiPageOption,
} from 'docs/src/modules/components/ApiPage/sections/ToggleDisplayOption';
import CSSList, { getHash } from 'docs/src/modules/components/ApiPage/list/CSSList';
import CSSTable from 'docs/src/modules/components/ApiPage/table/CSSTable';
type ComponentStyles = {
classes: string[];
globalClasses: { [classeKey: string]: string };
name: null | string;
};
type ClassDescription = {
[classeKey: string]: {
description: string;
nodeName?: string;
conditions?: string;
};
};
export type GetCssToCParams = {
componentName: string;
componentStyles: ComponentStyles;
t: (key: any, options?: {}) => any;
hash?: string;
};
export const getCssToC = ({ componentName, componentStyles, t, hash }: GetCssToCParams) =>
componentStyles.classes.length === 0
? []
: [
{
text: t('api-docs.css'),
hash: hash ?? 'css',
children: [
...componentStyles.classes.map((className) => ({
text: className,
hash: getHash({ componentName, className }),
children: [],
})),
],
},
];
export type CSSSectionProps = {
componentStyles: ComponentStyles;
classDescriptions: ClassDescription;
componentName?: string;
spreadHint?: string;
title: string;
titleHash: string;
level?: 'h2' | 'h3' | 'h4';
styleOverridesLink: string;
};
export default function CSSSection(props: CSSSectionProps) {
const {
componentStyles,
classDescriptions,
componentName,
spreadHint,
styleOverridesLink,
title = 'api-docs.css',
titleHash = 'css',
level: Level = 'h2',
} = props;
const t = useTranslate();
const [displayOption, setDisplayOption] = useApiPageOption(API_LAYOUT_STORAGE_KEYS.css);
if (!componentStyles?.classes || componentStyles.classes.length === 0) {
return null;
}
const formatedClasses = componentStyles.classes.map((className) => {
const isGlobalStateClass = !!componentStyles.globalClasses[className];
const selector = `.${
componentStyles.globalClasses[className] || `${componentStyles.name}-${className}`
}`;
const description =
classDescriptions[className] &&
classDescriptions[className].description
.replace(/{{conditions}}/, classDescriptions[className].conditions ?? '{{conditions}}')
.replace(/{{nodeName}}/, classDescriptions[className].nodeName ?? '{{nodeName}}');
return {
componentName,
className,
isGlobalStateClass,
selector,
description,
};
});
return (
<React.Fragment>
<Box sx={{ display: 'flex', alignItems: 'baseline', mb: 1 }}>
<Level id={titleHash} style={{ flexGrow: 1 }}>
{t(title)}
<a
aria-labelledby={titleHash}
className="anchor-link"
href={`#${titleHash}`}
tabIndex={-1}
>
<svg>
<use xlinkHref="#anchor-link-icon" />
</svg>
</a>
</Level>
<ToggleDisplayOption displayOption={displayOption} setDisplayOption={setDisplayOption} />
</Box>
{spreadHint && <p dangerouslySetInnerHTML={{ __html: spreadHint }} />}
{displayOption === 'table' ? (
<CSSTable classes={formatedClasses} />
) : (
<CSSList classes={formatedClasses} displayOption={displayOption} />
)}
<br />
<p dangerouslySetInnerHTML={{ __html: t('api-docs.overrideStyles') }} />
<span
dangerouslySetInnerHTML={{
__html: t('api-docs.overrideStylesStyledComponent').replace(
/{{styleOverridesLink}}/,
styleOverridesLink,
),
}}
/>
</React.Fragment>
);
}
| 5,328 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/sections/PropertiesSection.js | /* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import Box from '@mui/material/Box';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import ToggleDisplayOption, {
API_LAYOUT_STORAGE_KEYS,
useApiPageOption,
} from 'docs/src/modules/components/ApiPage/sections/ToggleDisplayOption';
import PropertiesList, { getHash } from 'docs/src/modules/components/ApiPage/list/PropertiesList';
import PropertiesTable from 'docs/src/modules/components/ApiPage/table/PropertiesTable';
export const getPropsToC = ({
componentName,
componentProps,
inheritance,
themeDefaultProps,
t,
hash,
}) => ({
text: t('api-docs.props'),
hash: hash ?? 'props',
children: [
...Object.entries(componentProps)
.filter(([, propData]) => propData.description !== '@ignore')
.map(([propName]) => ({
text: propName,
hash: getHash({ propName, targetName: componentName }),
children: [],
})),
...(inheritance
? [{ text: t('api-docs.inheritance'), hash: 'inheritance', children: [] }]
: []),
...(themeDefaultProps
? [{ text: t('api-docs.themeDefaultProps'), hash: 'theme-default-props', children: [] }]
: []),
],
});
export default function PropertiesSection(props) {
const {
properties,
propertiesDescriptions,
targetName = '',
showOptionalAbbr = false,
title = 'api-docs.props',
titleHash = 'props',
level: Level = 'h2',
spreadHint,
hooksParameters = false,
hooksReturnValue = false,
} = props;
const t = useTranslate();
const [displayOption, setDisplayOption] = useApiPageOption(API_LAYOUT_STORAGE_KEYS.props);
const formatedProperties = Object.entries(properties)
.filter(([, propData]) => propData.description !== '@ignore')
.map(([propName, propData]) => {
const isRequired = propData.required && !showOptionalAbbr;
const isOptional = !propData.required && showOptionalAbbr;
const isDeprecated = propData.deprecated;
const deprecationInfo = propData.deprecationInfo;
const typeName = propData.type?.description || propData.type.name;
const propDefault = propData.default;
const propDescription = propertiesDescriptions[propName];
const additionalInfo = [
'cssApi',
'sx',
'slotsApi',
'joy-size',
'joy-color',
'joy-variant',
].filter((key) => propData.additionalInfo?.[key]);
const signature = propData.signature?.type;
const signatureArgs = propData.signature?.describedArgs?.map((argName) => ({
argName,
argDescription: propertiesDescriptions[propName].typeDescriptions[argName],
}));
const signatureReturnDescription =
propData.signature?.returned &&
propertiesDescriptions[propName].typeDescriptions[propData.signature.returned];
return {
targetName,
propName,
description: propDescription?.description,
requiresRef: propDescription?.requiresRef,
isOptional,
isRequired,
isDeprecated,
hooksParameters,
hooksReturnValue,
deprecationInfo,
typeName,
propDefault,
additionalInfo,
signature,
signatureArgs,
signatureReturnDescription,
};
});
return (
<React.Fragment>
<Box sx={{ display: 'flex', alignItems: 'baseline', mb: 1 }}>
<Level id={titleHash} style={{ flexGrow: 1 }}>
{t(title)}
<a
aria-labelledby={titleHash}
className="anchor-link"
href={`#${titleHash}`}
tabIndex={-1}
>
<svg>
<use xlinkHref="#anchor-link-icon" />
</svg>
</a>
</Level>
<ToggleDisplayOption displayOption={displayOption} setDisplayOption={setDisplayOption} />
</Box>
{spreadHint && <p dangerouslySetInnerHTML={{ __html: spreadHint }} />}
{displayOption === 'table' ? (
<PropertiesTable properties={formatedProperties} />
) : (
<PropertiesList properties={formatedProperties} displayOption={displayOption} />
)}
</React.Fragment>
);
}
PropertiesSection.propTypes = {
hooksParameters: PropTypes.bool,
hooksReturnValue: PropTypes.bool,
level: PropTypes.string,
properties: PropTypes.object.isRequired,
propertiesDescriptions: PropTypes.object.isRequired,
showOptionalAbbr: PropTypes.bool,
spreadHint: PropTypes.string,
targetName: PropTypes.string,
title: PropTypes.string,
titleHash: PropTypes.string,
};
| 5,329 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/sections/SlotsSection.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import Box from '@mui/material/Box';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import ToggleDisplayOption, {
API_LAYOUT_STORAGE_KEYS,
useApiPageOption,
} from 'docs/src/modules/components/ApiPage/sections/ToggleDisplayOption';
import SlotsList from 'docs/src/modules/components/ApiPage/list/SlotsList';
import SlotsTable from 'docs/src/modules/components/ApiPage/table/SlotsTable';
export type SlotsSectionProps = {
componentSlots: { class: string; name: string; default: string }[];
slotDescriptions: { [key: string]: string };
componentName?: string;
title?: string;
titleHash?: string;
level?: 'h2' | 'h3' | 'h4';
spreadHint?: string;
};
export default function SlotsSection(props: SlotsSectionProps) {
const {
componentSlots,
slotDescriptions,
componentName,
title = 'api-docs.slots',
titleHash = 'slots',
level: Level = 'h2',
spreadHint,
} = props;
const t = useTranslate();
const [displayOption, setDisplayOption] = useApiPageOption(API_LAYOUT_STORAGE_KEYS.slots);
if (!componentSlots || componentSlots.length === 0) {
return null;
}
const formatedSlots = componentSlots?.map(({ class: className, name, default: defaultValue }) => {
const description = slotDescriptions[name];
return {
description,
className,
name,
defaultValue,
componentName,
};
});
return (
<React.Fragment>
<Box sx={{ display: 'flex', alignItems: 'baseline', mb: 1 }}>
<Level id={titleHash} style={{ flexGrow: 1 }}>
{t(title)}
<a
aria-labelledby={titleHash}
className="anchor-link"
href={`#${titleHash}`}
tabIndex={-1}
>
<svg>
<use xlinkHref="#anchor-link-icon" />
</svg>
</a>
</Level>
<ToggleDisplayOption displayOption={displayOption} setDisplayOption={setDisplayOption} />
</Box>
{spreadHint && <p dangerouslySetInnerHTML={{ __html: spreadHint }} />}
{displayOption === 'table' ? (
<SlotsTable slots={formatedSlots} />
) : (
<SlotsList slots={formatedSlots} displayOption={displayOption} />
)}
</React.Fragment>
);
}
| 5,330 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/sections/ToggleDisplayOption.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import Tooltip, { TooltipProps } from '@mui/material/Tooltip';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton, { ToggleButtonProps } from '@mui/material/ToggleButton';
import CalendarViewDayRoundedIcon from '@mui/icons-material/CalendarViewDayRounded';
import TableChartRoundedIcon from '@mui/icons-material/TableChartRounded';
import ReorderRoundedIcon from '@mui/icons-material/ReorderRounded';
import useEnhancedEffect from '@mui/utils/useEnhancedEffect';
type ApiDisplayOptions = 'collapsed' | 'expended' | 'table';
const options: ApiDisplayOptions[] = ['collapsed', 'expended', 'table'];
const DEFAULT_LAYOUT: ApiDisplayOptions = 'expended';
export const API_LAYOUT_STORAGE_KEYS = {
default: 'apiPage_default',
slots: 'apiPage_slots',
props: 'apiPage_props',
css: 'apiPage_css',
classes: 'apiPage_classes',
} as const;
// https://stackoverflow.com/a/20084661
function isBot() {
return /bot|googlebot|crawler|spider|robot|crawling/i.test(navigator.userAgent);
}
function getRandomOption() {
if (isBot()) {
// When crawlers visit the page, they should not have to expand items
return DEFAULT_LAYOUT;
}
// A default layout is saved in localstorage at first render to make sure all section start with the same layout.
const savedDefaultOption = localStorage.getItem(
API_LAYOUT_STORAGE_KEYS.default,
) as null | ApiDisplayOptions;
if (savedDefaultOption !== null && options.includes(savedDefaultOption)) {
return savedDefaultOption;
}
const randomOption = options[Math.floor(options.length * Math.random())];
try {
localStorage.setItem(API_LAYOUT_STORAGE_KEYS.default, randomOption);
} catch (error) {
// Do nothing
}
return randomOption;
}
let neverHydrated = true;
function getOption(storageKey: string) {
if (neverHydrated) {
return DEFAULT_LAYOUT;
}
try {
const savedOption = localStorage.getItem(storageKey);
if (savedOption !== null) {
return savedOption as ApiDisplayOptions;
}
const randomOption = getRandomOption();
return randomOption;
} catch (error) {
return DEFAULT_LAYOUT;
}
}
export function useApiPageOption(
storageKey: string,
): [ApiDisplayOptions, (newOption: ApiDisplayOptions) => void] {
const [option, setOption] = React.useState(getOption(storageKey));
useEnhancedEffect(() => {
neverHydrated = false;
const newOption = getOption(storageKey);
setOption(newOption);
}, [storageKey]);
React.useEffect(() => {
if (option !== DEFAULT_LAYOUT) {
const id = document.location.hash.slice(1);
const element = document.getElementById(id);
element?.scrollIntoView();
}
return undefined;
}, [option]);
const updateOption = React.useCallback(
(newOption: ApiDisplayOptions) => {
try {
localStorage.setItem(storageKey, newOption);
} catch (error) {
// Do nothing
}
setOption(newOption);
},
[storageKey],
);
return [option, updateOption];
}
export function getApiPageLayout() {
const rep: { [key: string]: string } = {};
Object.values(API_LAYOUT_STORAGE_KEYS).forEach((localStorageKey) => {
try {
const savedOption = localStorage.getItem(localStorageKey);
rep[localStorageKey] = savedOption || 'none';
} catch {
rep[localStorageKey] = 'none';
}
});
return rep;
}
// Fix Toggle buton highlight (taken from https://github.com/mui/material-ui/issues/18091)
type TooltipToggleButtonProps = ToggleButtonProps & {
/**
* The title passed to the Tooltip
*/
title: string;
TooltipProps?: Omit<TooltipProps, 'children' | 'title'>;
};
// Catch props and forward to ToggleButton
const TooltipToggleButton = React.forwardRef<HTMLButtonElement, TooltipToggleButtonProps>(
({ title, TooltipProps: tooltipProps, ...props }, ref) => {
return (
<Tooltip {...tooltipProps} title={title}>
<ToggleButton ref={ref} {...props} />
</Tooltip>
);
},
);
TooltipToggleButton.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
title: PropTypes.string.isRequired,
TooltipProps: PropTypes.object,
};
interface ToggleDisplayOptionProps {
displayOption: ApiDisplayOptions;
setDisplayOption: (newValue: ApiDisplayOptions) => void;
}
export default function ToggleDisplayOption(props: ToggleDisplayOptionProps) {
const { displayOption, setDisplayOption } = props;
const handleAlignment = (
event: React.MouseEvent<HTMLElement>,
newDisplayOption: ApiDisplayOptions | null,
) => {
if (newDisplayOption === null) {
return;
}
setDisplayOption(newDisplayOption);
};
return (
<ToggleButtonGroup
size="small"
value={displayOption}
exclusive
onChange={handleAlignment}
aria-label="API display option"
sx={{
'& .MuiSvgIcon-root': {
height: '18px',
width: '18px',
},
'&.MuiToggleButtonGroup-root .MuiToggleButton-root': {
padding: '4px 6px',
borderRadius: '6px',
'&.MuiToggleButtonGroup-grouped:not(:last-of-type)': {
borderTopRightRadius: 0,
borderBottomRightRadius: 0,
},
'&.MuiToggleButtonGroup-grouped:not(:first-of-type)': {
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0,
},
},
}}
>
<TooltipToggleButton value="collapsed" aria-label="colapsed list" title="Collapse list view">
<ReorderRoundedIcon size="small" />
</TooltipToggleButton>
<TooltipToggleButton value="expended" aria-label="expended list" title="Expand list view">
<CalendarViewDayRoundedIcon />
</TooltipToggleButton>
<TooltipToggleButton value="table" aria-label="table" title="Table view">
<TableChartRoundedIcon />
</TooltipToggleButton>
</ToggleButtonGroup>
);
}
| 5,331 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/table/CSSTable.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import { styled, alpha } from '@mui/material/styles';
import {
brandingDarkTheme as darkTheme,
brandingLightTheme as lightTheme,
} from 'docs/src/modules/brandingTheme';
import { CSSFormatedParams, getHash } from 'docs/src/modules/components/ApiPage/list/CSSList';
import StyledTableContainer from './StyledTableContainer';
const StyledTable = styled('table')(
({ theme }) => ({
'& .MuiApi-table-rule-name': {
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightSemiBold,
fontSize: theme.typography.pxToRem(13),
color: `var(--muidocs-palette-primary-600, ${lightTheme.palette.primary[600]})`,
},
'& .MuiApi-table-ruleName': {
...theme.typography.caption,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightRegular,
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
padding: '1px 4px',
borderRadius: 6,
border: '1px solid',
borderColor: alpha(darkTheme.palette.primary[100], 0.8),
backgroundColor: `var(--muidocs-palette-primary-50, ${lightTheme.palette.primary[50]})`,
},
'& .MuiApi-table-global-class': {
fontWeight: theme.typography.fontWeightSemiBold,
fontFamily: theme.typography.fontFamilyCode,
fontSize: theme.typography.pxToRem(13),
color: `var(--muidocs-palette-primary-600, ${lightTheme.palette.primary[600]})`,
},
'& .MuiCssTable-description-column': {
width: '50%',
paddingRight: 8,
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& .MuiApi-table-ruleName': {
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
borderColor: alpha(darkTheme.palette.primary[400], 0.1),
backgroundColor: alpha(darkTheme.palette.primary[900], 0.4),
},
'& .MuiApi-table-global-class': {
color: `var(--muidocs-palette-primary-200, ${darkTheme.palette.primary[200]})`,
},
},
}),
);
interface CSSTableProps {
classes: CSSFormatedParams[];
}
export default function CSSTable(props: CSSTableProps) {
const { classes } = props;
return (
<StyledTableContainer>
<StyledTable>
<thead>
<tr>
<th>Global class</th>
<th>Rule name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{classes.map((params) => {
const { componentName, className, selector, description } = params;
return (
<tr key={className} id={getHash({ componentName, className })}>
<td>
{
<span
className="MuiApi-table-global-class"
dangerouslySetInnerHTML={{
__html: selector || '',
}}
/>
}
</td>
<td>
<span className="MuiApi-table-ruleName">{className}</span>
</td>
<td className="MuiCssTable-description-column">
<span
className="MuiApi-table-description"
dangerouslySetInnerHTML={{
__html: description || '',
}}
/>
</td>
</tr>
);
})}
</tbody>
</StyledTable>
</StyledTableContainer>
);
}
| 5,332 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/table/ClassesTable.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import { styled } from '@mui/material/styles';
import {
brandingDarkTheme as darkTheme,
brandingLightTheme as lightTheme,
} from 'docs/src/modules/brandingTheme';
import {
ClassesFormatedParams,
getHash,
} from 'docs/src/modules/components/ApiPage/list/ClassesList';
const StyledTable = styled('table')(
({ theme }) => ({
'& .rule-name': {
flexShrink: 0,
fontWeight: theme.typography.fontWeightSemiBold,
fontFamily: theme.typography.fontFamilyCode,
fontSize: theme.typography.pxToRem(13),
color: `var(--muidocs-palette-primary-600, ${lightTheme.palette.primary[600]})`,
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& .rule-name': {
color: `var(--muidocs-palette-primary-200, ${darkTheme.palette.primary[200]})`,
},
},
}),
);
interface ClassesTableProps {
classes: ClassesFormatedParams[];
}
export default function ClassesTable(props: ClassesTableProps) {
const { classes } = props;
return (
<StyledTable>
<thead>
<tr>
<th>Rule name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{classes.map((params) => {
const { className, cssClassName, description, componentName } = params;
return (
<tr key={className} id={getHash({ componentName, className })}>
<td className="MuiApi-table-global-class">
<span className="rule-name">{cssClassName}</span>
</td>
<td>
<span
className="MuiApi-table-description"
dangerouslySetInnerHTML={{
__html: description || '',
}}
/>
</td>
</tr>
);
})}
</tbody>
</StyledTable>
);
}
| 5,333 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/table/PropertiesTable.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled, alpha } from '@mui/material/styles';
import Alert from '@mui/material/Alert';
import WarningRoundedIcon from '@mui/icons-material/WarningRounded';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import {
brandingDarkTheme as darkTheme,
brandingLightTheme as lightTheme,
} from 'docs/src/modules/brandingTheme';
import {
PropDescriptionParams,
getHash,
} from 'docs/src/modules/components/ApiPage/list/PropertiesList';
import StyledTableContainer from 'docs/src/modules/components/ApiPage/table/StyledTableContainer';
const StyledTable = styled('table')(
({ theme }) => ({
'& .type-column': {
minWidth: '20%',
},
'& .default-column': {
minWidth: '20%',
},
'& .MuiApi-table-item-title': {
minWidth: '20%',
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightSemiBold,
fontSize: theme.typography.pxToRem(13),
color: `var(--muidocs-palette-primary-600, ${lightTheme.palette.primary[600]})`,
},
'& .MuiApi-table-item-type': {
...theme.typography.caption,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightRegular,
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
padding: '1px 4px',
borderRadius: 6,
border: '1px solid',
borderColor: alpha(darkTheme.palette.primary[100], 0.8),
backgroundColor: `var(--muidocs-palette-primary-50, ${lightTheme.palette.primary[50]})`,
},
'& .MuiApi-table-item-default': {
...theme.typography.caption,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightRegular,
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
padding: '1px 4px',
borderRadius: 6,
border: '1px solid',
borderColor: `var(--muidocs-palette-grey-200, ${lightTheme.palette.grey[200]})`,
backgroundColor: `var(--muidocs-palette-grey-50, ${lightTheme.palette.grey[50]})`,
},
'& .MuiPropTable-description-column': {
width: '40%',
paddingRight: 8,
'& .prop-table-description': {
marginBottom: 0,
},
'& .prop-table-additional-description': {
marginTop: 12,
marginBottom: 0,
},
'& .prop-table-deprecated': {
'& code ': { all: 'unset' },
},
'& .prop-table-alert': {
padding: '2px 12px',
marginTop: 12,
color: `var(--muidocs-palette-grey-900, ${lightTheme.palette.grey[900]})`,
backgroundColor: alpha(lightTheme.palette.warning[50], 0.5),
borderColor: `var(--muidocs-palette-warning-200, ${lightTheme.palette.warning[200]})`,
'& .MuiAlert-icon': {
padding: 0,
},
'& strong': {
color: `var(--muidocs-palette-warning-800, ${lightTheme.palette.warning[800]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-warning-600, ${lightTheme.palette.warning[600]})`,
},
'& a': {
color: `var(--muidocs-palette-warning-800, ${lightTheme.palette.warning[800]})`,
textDecorationColor: alpha(lightTheme.palette.warning.main, 0.4),
'&:hover': {
textDecorationColor: 'inherit',
},
},
},
},
'& .prop-table-signature': {
marginTop: 12,
marginBottom: 0,
display: 'flex',
flexDirection: 'column',
gap: 16,
'& .prop-table-title': {
fontWeight: theme.typography.fontWeightMedium,
},
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& .MuiApi-table-item-title': {
color: `var(--muidocs-palette-primary-200, ${darkTheme.palette.primary[200]})`,
},
'& .MuiApi-table-item-type': {
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
backgroundColor: alpha(darkTheme.palette.primary[900], 0.5),
},
'& .MuiApi-table-item-default': {
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
backgroundColor: `var(--muidocs-palette-grey-900, ${darkTheme.palette.grey[900]})`,
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
},
'& .prop-table-signature': {
'& .prop-table-title': {
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
},
},
'& .MuiPropTable-description-column': {
'& .prop-table-alert': {
color: `var(--muidocs-palette-warning-50, ${darkTheme.palette.warning[50]})`,
backgroundColor: alpha(darkTheme.palette.warning[700], 0.15),
borderColor: alpha(darkTheme.palette.warning[600], 0.3),
'& strong': {
color: `var(--muidocs-palette-warning-200, ${darkTheme.palette.warning[200]})`,
},
'&>svg': {
fill: `var(--muidocs-palette-warning-400, ${darkTheme.palette.warning[400]})`,
},
'& a': {
color: `var(--muidocs-palette-warning-100, ${darkTheme.palette.warning[100]})`,
},
},
},
},
}),
);
function PropDescription({ description }: { description: string }) {
const isUlPresent = description.includes('<ul>');
const ComponentToRender = isUlPresent ? 'div' : 'p';
return (
<ComponentToRender
className="prop-table-description" // This className is used by Algolia
dangerouslySetInnerHTML={{
__html: description,
}}
/>
);
}
PropDescription.propTypes = {
description: PropTypes.string.isRequired,
};
interface PropertiesTableProps {
properties: PropDescriptionParams[];
}
export default function PropertiesTable(props: PropertiesTableProps) {
const { properties } = props;
const t = useTranslate();
return (
<StyledTableContainer>
<StyledTable>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{properties.map((params) => {
const {
targetName,
propName,
description,
requiresRef,
isOptional,
isRequired,
isDeprecated,
hooksParameters,
hooksReturnValue,
deprecationInfo,
typeName,
propDefault,
additionalInfo,
signature,
signatureArgs,
signatureReturnDescription,
} = params;
return (
<tr
key={propName}
id={getHash({ targetName, propName, hooksParameters, hooksReturnValue })}
>
<td className="MuiApi-table-item-title">
{propName}
{isRequired ? '*' : ''}
{isOptional ? '?' : ''}
</td>
<td className="type-column">
{
<span
className="MuiApi-table-item-type"
dangerouslySetInnerHTML={{
__html: typeName,
}}
/>
}
</td>
<td className="default-column">
<span className="MuiApi-table-item-default">{propDefault}</span>
</td>
<td className="MuiPropTable-description-column">
{description && <PropDescription description={description} />}
{requiresRef && (
<Alert
className="prop-table-alert"
severity="warning"
icon={<WarningRoundedIcon fontSize="small" />}
sx={{
alignItems: 'center',
'& .MuiAlert-icon': {
height: 'fit-content',
p: 0,
mr: 1,
mb: 0.3,
},
}}
>
<span
dangerouslySetInnerHTML={{
__html: t('api-docs.requires-ref'),
}}
/>
</Alert>
)}
{additionalInfo.map((key) => (
<p
className="prop-table-additional-description"
key={key}
dangerouslySetInnerHTML={{
__html: t(`api-docs.additional-info.${key}`),
}}
/>
))}
{isDeprecated && (
<Alert
severity="warning"
className="prop-table-alert prop-table-deprecated"
icon={<WarningRoundedIcon fontSize="small" />}
sx={{ mb: 1, py: 0, alignItems: 'center' }}
>
{t('api-docs.deprecated')}
{deprecationInfo && (
<React.Fragment>
{' - '}
<span
dangerouslySetInnerHTML={{
__html: deprecationInfo,
}}
/>
</React.Fragment>
)}
</Alert>
)}
{signature && (
<div className="prop-table-signature">
<span className="prop-table-title">{t('api-docs.signature')}:</span>
<code
dangerouslySetInnerHTML={{
__html: signature,
}}
/>
{signatureArgs && (
<div>
<ul>
{signatureArgs.map(({ argName, argDescription }) => (
<li
className="prop-signature-list"
key={argName}
dangerouslySetInnerHTML={{
__html: `<code>${argName}</code> ${argDescription}`,
}}
/>
))}
</ul>
</div>
)}
{signatureReturnDescription && (
<p>
{t('api-docs.returns')}
<span
dangerouslySetInnerHTML={{
__html: signatureReturnDescription,
}}
/>
</p>
)}
</div>
)}
</td>
</tr>
);
})}
</tbody>
</StyledTable>
</StyledTableContainer>
);
}
| 5,334 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/table/SlotsTable.tsx | /* eslint-disable react/no-danger */
import * as React from 'react';
import { styled, alpha } from '@mui/material/styles';
import {
brandingDarkTheme as darkTheme,
brandingLightTheme as lightTheme,
} from 'docs/src/modules/brandingTheme';
import { SlotsFormatedParams, getHash } from 'docs/src/modules/components/ApiPage/list/SlotsList';
import StyledTableContainer from 'docs/src/modules/components/ApiPage/table/StyledTableContainer';
const StyledTable = styled('table')(
({ theme }) => ({
'& .slot-name': {
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightSemiBold,
fontSize: theme.typography.pxToRem(13),
color: `var(--muidocs-palette-primary-600, ${lightTheme.palette.primary[600]})`,
},
'& .class-name': {
...theme.typography.caption,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightRegular,
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
padding: '1px 4px',
borderRadius: 6,
border: '1px solid',
borderColor: alpha(darkTheme.palette.primary[100], 0.8),
backgroundColor: `var(--muidocs-palette-primary-50, ${lightTheme.palette.primary[50]})`,
},
'& .item-default': {
...theme.typography.caption,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: theme.typography.fontWeightRegular,
color: `var(--muidocs-palette-text-primary, ${lightTheme.palette.text.primary})`,
padding: '1px 4px',
borderRadius: 6,
border: '1px solid',
borderColor: `var(--muidocs-palette-grey-200, ${lightTheme.palette.grey[200]})`,
backgroundColor: `var(--muidocs-palette-grey-50, ${lightTheme.palette.grey[50]})`,
},
'& .description-column': {
width: '40%',
paddingRight: 8,
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& .slot-name': {
color: `var(--muidocs-palette-primary-200, ${darkTheme.palette.primary[200]})`,
},
'& .class-name': {
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
backgroundColor: alpha(darkTheme.palette.primary[900], 0.5),
},
'& .item-default': {
color: `var(--muidocs-palette-text-primary, ${darkTheme.palette.text.primary})`,
backgroundColor: `var(--muidocs-palette-grey-900, ${darkTheme.palette.grey[900]})`,
borderColor: `var(--muidocs-palette-divider, ${darkTheme.palette.divider})`,
},
},
}),
);
interface SlotsTableProps {
slots: SlotsFormatedParams[];
}
export default function SlotsTable(props: SlotsTableProps) {
const { slots } = props;
return (
<StyledTableContainer>
<StyledTable>
<thead>
<tr>
<th>Slot name</th>
<th>Class name</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{slots.map((params) => {
const { description, className, name, defaultValue, componentName } = params;
return (
<tr key={className} id={getHash({ componentName, className })}>
<td className="slot-name" style={{ fontWeight: '600' }}>
{name}
</td>
<td className="MuiApi-table-class-name">
<span className="class-name">{className}</span>
</td>
<td>{defaultValue && <code className="item-default">{defaultValue}</code>}</td>
<td className="description-column">
<span
dangerouslySetInnerHTML={{
__html: description || '',
}}
/>
</td>
</tr>
);
})}
</tbody>
</StyledTable>
</StyledTableContainer>
);
}
| 5,335 |
0 | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage/table/StyledTableContainer.tsx | import { styled, alpha } from '@mui/material/styles';
import { brandingDarkTheme as darkTheme } from 'docs/src/modules/brandingTheme';
const StyledTableContainer = styled('div')(
({ theme }) => ({
overflow: 'hidden',
'& table': {
borderRadius: '10px',
marginLeft: -1,
marginRight: -1,
background: [
'linear-gradient(to right, rgb(255, 255, 255) 5%, rgba(255, 255, 255, 0) 90%) local',
'linear-gradient(to right, rgba(255, 255, 255, 0), rgb(255, 255, 255) 100%) 100% center local',
`linear-gradient(to right, ${alpha(
theme.palette.grey[500],
0.5,
)}, rgba(0, 0, 0, 0) 5%) scroll`,
`linear-gradient(to left, ${alpha(
theme.palette.grey[500],
0.2,
)}, rgba(0, 0, 0, 0) 5%) scroll`,
].join(', '),
},
'&& th': {
paddingTop: 8,
paddingBottom: 8,
textAlign: 'left',
fontWeight: theme.typography.fontWeightSemiBold,
fontSize: theme.typography.pxToRem(14),
},
'& tr': {
scrollMarginTop: 'calc(var(--MuiDocs-header-height) + 32px)',
'&:hover': {
backgroundColor: alpha(darkTheme.palette.grey[50], 0.5),
},
'& .MuiPropTable-description-column': {
minWidth: 400,
},
},
}),
({ theme }) => ({
[`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: {
'& table': {
background: [
`linear-gradient(to right, ${theme.palette.primaryDark[900]} 5%, ${alpha(
theme.palette.primaryDark[900],
0,
)} 80%) local`,
`linear-gradient(to right, ${alpha(theme.palette.primaryDark[900], 0)}, ${
theme.palette.primaryDark[900]
} 100%) 100% center local`,
`linear-gradient(to right, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0) 10%) scroll`,
'linear-gradient(to left, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0) 10%) scroll',
].join(', '),
},
'& tr': {
'&:hover': {
backgroundColor: alpha(darkTheme.palette.primaryDark[800], 0.5),
},
},
},
}),
);
export default StyledTableContainer;
| 5,336 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/joy/generateThemeAugmentation.test.ts | import { expect } from 'chai';
import generateThemeAugmentation from './generateThemeAugmentation';
describe('generateThemeAugmentation', () => {
it('should not augment default tokens', () => {
expect(
generateThemeAugmentation({
colorSchemes: {
light: {
palette: {
primary: {
50: '#fff',
},
},
},
},
}),
).to.equal(`
declare module '@mui/joy/styles' {
// No custom tokens found, you can skip the theme augmentation.
}
`);
});
[
'PalettePrimaryOverrides',
'PaletteNeutralOverrides',
'PaletteDangerOverrides',
'PaletteSuccessOverrides',
'PaletteWarningOverrides',
'PaletteBackgroundOverrides',
'PaletteCommonOverrides',
'PaletteTextOverrides',
].forEach((type) => {
it(`augment ${type}`, () => {
const paletteName = type.replace(/^Palette([a-zA-Z]+)Overrides$/, '$1').toLowerCase();
expect(
generateThemeAugmentation({
colorSchemes: {
light: {
palette: {
[paletteName]: {
custom: '#000',
},
},
},
},
}),
).to.equal(`
declare module '@mui/joy/styles' {
interface ${type} {
custom: true;
}
}
`);
});
});
it('should augment new tokens', () => {
expect(
generateThemeAugmentation({
colorSchemes: {
light: {
palette: {
primary: {
gradient: 'any',
},
neutral: {
gradient2: 'any',
},
danger: {
gradient3: 'any',
},
success: {
gradient5: 'any',
},
warning: {
gradient6: 'any',
},
background: {
gradient7: 'any',
},
common: {
gradient8: 'any',
},
text: {
gradient9: 'any',
},
},
},
},
}),
).to.equal(`
declare module '@mui/joy/styles' {
interface PalettePrimaryOverrides {
gradient: true;
}
interface PaletteNeutralOverrides {
gradient2: true;
}
interface PaletteDangerOverrides {
gradient3: true;
}
interface PaletteSuccessOverrides {
gradient5: true;
}
interface PaletteWarningOverrides {
gradient6: true;
}
interface PaletteBackgroundOverrides {
gradient7: true;
}
interface PaletteCommonOverrides {
gradient8: true;
}
interface PaletteTextOverrides {
gradient9: true;
}
}
`);
});
});
| 5,337 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/joy/generateThemeAugmentation.ts | import { extendTheme, Palette } from '@mui/joy/styles';
const defaultTheme = extendTheme();
const augmentPalette = (colorSchemes: any, prop: keyof Palette) => {
if (!colorSchemes) {
return '';
}
const result: Array<string> = [];
const palette = { ...colorSchemes.light?.palette?.[prop], ...colorSchemes.dark?.palette?.[prop] };
Object.keys(palette).forEach((k) => {
if (
!Object.keys(defaultTheme.colorSchemes.light.palette[prop]).includes(k) &&
!k.match(/^(plain|outlined|soft|solid)/)
) {
result.push(`${k}: true;`);
}
if (
Object.keys(defaultTheme.colorSchemes.light.palette[prop]).includes(k) &&
palette[k] === undefined
) {
result.push(`${k}: false;`);
}
});
return result.join('\n');
};
const prependSpace = (text: string, space = 0) => {
const lines = text.split('\n').map((line) => `${[...Array(space).fill(' ')].join('')}${line}`);
return lines.join('\n');
};
const renderInterface = (name: string, text: string) => {
if (!text || !text.trim()) {
return '';
}
return `interface ${name} {
${text}
}`;
};
export default function generateThemeAugmentation(data: any) {
const result = [
renderInterface(
'PalettePrimaryOverrides',
prependSpace(augmentPalette(data?.colorSchemes, 'primary'), 4),
),
renderInterface(
`PaletteNeutralOverrides`,
prependSpace(augmentPalette(data?.colorSchemes, 'neutral'), 4),
),
renderInterface(
'PaletteDangerOverrides',
prependSpace(augmentPalette(data?.colorSchemes, 'danger'), 4),
),
renderInterface(
'PaletteSuccessOverrides',
prependSpace(augmentPalette(data?.colorSchemes, 'success'), 4),
),
renderInterface(
'PaletteWarningOverrides',
prependSpace(augmentPalette(data?.colorSchemes, 'warning'), 4),
),
renderInterface(
'PaletteBackgroundOverrides',
prependSpace(augmentPalette(data?.colorSchemes, 'background'), 4),
),
renderInterface(
'PaletteCommonOverrides',
prependSpace(augmentPalette(data?.colorSchemes, 'common'), 4),
),
renderInterface(
'PaletteTextOverrides',
prependSpace(augmentPalette(data?.colorSchemes, 'text'), 4),
),
]
.filter((text) => !!text)
.join('\n ');
return `
declare module '@mui/joy/styles' {
${result === '' ? '// No custom tokens found, you can skip the theme augmentation.' : result}
}
`;
}
| 5,338 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/joy/getMinimalJoyTemplate.ts | export default function getMinimalJoyTemplate() {
return `import * as React from "react";
import { CssVarsProvider, useColorScheme } from "@mui/joy/styles";
import Box from "@mui/joy/Box";
import Button from "@mui/joy/Button";
import CssBaseline from "@mui/joy/CssBaseline";
import Card from "@mui/joy/Card";
import Divider from "@mui/joy/Divider";
import Link from "@mui/joy/Link";
import List from "@mui/joy/List";
import ListSubheader from "@mui/joy/ListSubheader";
import ListItem from "@mui/joy/ListItem";
import ListItemButton from "@mui/joy/ListItemButton";
import Typography from "@mui/joy/Typography";
import theme from "./theme";
const ColorSchemeToggle = () => {
const { mode, setMode } = useColorScheme();
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return <Button variant="outlined" color="primary" />;
}
return (
<Button
variant="outlined"
onClick={() => {
if (mode === "light") {
setMode("dark");
} else {
setMode("light");
}
}}
>
{mode === "light" ? "Turn dark" : "Turn light"}
</Button>
);
};
export default function App() {
return (
<CssVarsProvider theme={theme}>
<CssBaseline />
<Card
size="lg"
variant="solid"
color="primary"
invertedColors
sx={{
borderRadius: "sm",
m: 1,
fontSize: "lg",
background: (theme) =>
\`linear-gradient(-10deg, \${theme.vars.palette.primary[900]} -10%, \${theme.vars.palette.primary[700]}, \${theme.vars.palette.primary[500]} 70%, \${theme.vars.palette.primary[400]})\`
}}
>
<Box sx={{ position: "absolute", top: "1.5rem", right: "1.5rem" }}>
<ColorSchemeToggle />
</Box>
<Typography level="h1" fontWeight="xl" sx={{ mt: -1 }}>
Joy UI
</Typography>
<Typography sx={{ mt: 0.5 }}>
Hand-crafted React components with fresh design. Focus on developer
experience and customizability.
</Typography>
<Divider sx={{ mt: 2 }} />
<List sx={{ mx: -1 }}>
<ListSubheader>documentation</ListSubheader>
<ListItem>
<ListItemButton
component="a"
href="https://mui.com/joy-ui/main-features/global-variants/"
target="_blank"
rel="noopener noreferrer"
>
Main features <span role="img">↗</span>️
</ListItemButton>
</ListItem>
<ListItem>
<ListItemButton
component="a"
href="https://mui.com/joy-ui/react-autocomplete/"
target="_blank"
rel="noopener noreferrer"
>
Browse components <span role="img">↗</span>️
</ListItemButton>
</ListItem>
<ListItem>
<ListItemButton
component="a"
href="https://mui.com/joy-ui/customization/approaches/"
target="_blank"
rel="noopener noreferrer"
>
Check out theming and customization {" "}
<span role="img">↗</span>️
</ListItemButton>
</ListItem>
</List>
</Card>
<Typography textAlign="center" level="body-sm">
Developed by{" "}
<Link
underline="always"
href="https://mui.com/about"
target="_blank"
rel="noopener noreferrer"
>
MUI
</Link>{" "}
team.
</Typography>
</CssVarsProvider>
);
}
`;
}
| 5,339 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/joy/literalToObject.test.ts | import { expect } from 'chai';
import literalToObject from './literalToObject';
describe('literalToObject', () => {
it('should work with theme file', () => {
expect(
literalToObject(`
const theme = extendTheme({
colorSchemes: {
light: {
palette: {
primary: {
900: '#000',
}
}
}
},
fontFamily: {
display: '"Inter"',
body: '"Inter"',
}
})`),
).to.deep.equal({
colorSchemes: {
light: {
palette: {
primary: {
900: '#000',
},
},
},
},
fontFamily: {
display: '"Inter"',
body: '"Inter"',
},
});
});
});
| 5,340 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/joy/literalToObject.ts | export default function literalToObject(literal: string | null | undefined) {
if (!literal) {
return {};
}
const lines = literal.split('\n');
const result: Record<string, any> = {};
const parent: Array<Record<string, any>> = [];
let nested: Record<string, any> | null | undefined = null;
lines.forEach((line) => {
const trimmedLine = line.trim();
if (!trimmedLine.match(/}/)) {
const [key, value] = trimmedLine.split(':');
if (value && value.match(/{/)) {
if (!nested) {
result[key] = {};
nested = result[key];
} else {
parent.push(nested);
nested[key] = {};
nested = nested[key];
}
} else if (key && !key.trim().match(/^(\/\/|\/\*)/) && value && nested) {
try {
const trimmedValue = value.trim().replace(/,$/, '');
if (trimmedValue === 'undefined') {
nested[key] = undefined;
}
if (trimmedValue === 'null') {
nested[key] = null;
}
if (trimmedValue.match(/^('|")/)) {
nested[key] = trimmedValue.slice(1, -1);
}
} catch (error) {
// igore error
}
}
} else {
nested = parent.pop();
}
});
return result;
}
| 5,341 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/joy/sourceJoyTemplates.ts | const templateMap = new Map<string, { files: Record<string, string>; codeVariant: 'TS' | 'JS' }>();
// @ts-ignore
const req = require.context(
'../../../data/joy/getting-started/templates/?raw',
true,
/^\.\/[^/]+\/.*\.(js|tsx|ts)$/,
);
req.keys().forEach((key: string) => {
const match = /\/(?<name>[^/]+)\/(?<filePath>.*)/.exec(key);
if (match) {
const name = match.groups?.name;
const filePath = match.groups?.filePath;
if (name && filePath) {
const { files, codeVariant } = templateMap.get(name) || {};
templateMap.set(name, {
files: { ...files, [filePath]: req(key) },
codeVariant: filePath.match(/\.(ts|tsx)$/) ? 'TS' : codeVariant || 'JS',
});
}
}
});
export interface TemplateData {
files: Record<string, string>;
codeVariant: 'TS' | 'JS';
}
export default function sourceJoyTemplates() {
return {
names: Array.from(templateMap.keys()),
templates: Array.from(templateMap.values()),
map: new Map(templateMap),
};
}
| 5,342 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/CodeSandbox.test.js | import { expect } from 'chai';
import CodeSandbox from './CodeSandbox';
const testCase = `import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
export default function BasicButtons() {
return (
<Stack spacing={2} direction="row">
<Button variant="text">Text</Button>
<Button variant="contained">Contained</Button>
<Button variant="outlined">Outlined</Button>
</Stack>
);
}
`;
describe('CodeSandbox', () => {
it('generate the correct JavaScript result', () => {
const result = CodeSandbox.createReactApp({
title: 'BasicButtons Material Demo',
githubLocation:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.js',
codeVariant: 'JS',
language: 'en',
raw: testCase,
});
expect(result.files).to.deep.equal({
'package.json': {
content: {
description:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.js',
dependencies: {
react: 'latest',
'@mui/material': 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
},
devDependencies: {
'react-scripts': 'latest',
},
},
},
'public/index.html': {
content: `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>BasicButtons Material Demo</title>
<meta name="viewport" content="initial-scale=1, width=device-width" />
<!-- Fonts to support Material Design -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;600;700&display=swap"
/>
<!-- Icons to support Material Design -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
</head>
<body>
<div id="root"></div>
</body>
</html>`,
},
'src/Demo.js': {
content: `import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
export default function BasicButtons() {
return (
<Stack spacing={2} direction="row">
<Button variant="text">Text</Button>
<Button variant="contained">Contained</Button>
<Button variant="outlined">Outlined</Button>
</Stack>
);
}
`,
},
'src/index.js': {
content: `import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './Demo';
ReactDOM.createRoot(document.querySelector("#root")).render(
<React.StrictMode>
<StyledEngineProvider injectFirst>
<Demo />
</StyledEngineProvider>
</React.StrictMode>
);`,
},
});
});
it('generate the correct TypeScript result', () => {
const result = CodeSandbox.createReactApp({
title: 'BasicButtons Material Demo',
githubLocation:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.tsx',
codeVariant: 'TS',
language: 'en',
raw: testCase,
});
expect(result.files).to.deep.equal({
'package.json': {
content: {
description:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.tsx',
dependencies: {
react: 'latest',
'@mui/material': 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@types/react': 'latest',
'@types/react-dom': 'latest',
typescript: 'latest',
},
devDependencies: {
'react-scripts': 'latest',
},
main: 'index.tsx',
scripts: {
start: 'react-scripts start',
},
},
},
'public/index.html': {
content: `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>BasicButtons Material Demo</title>
<meta name="viewport" content="initial-scale=1, width=device-width" />
<!-- Fonts to support Material Design -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;600;700&display=swap"
/>
<!-- Icons to support Material Design -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
</head>
<body>
<div id="root"></div>
</body>
</html>`,
},
'src/Demo.tsx': {
content: `import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
export default function BasicButtons() {
return (
<Stack spacing={2} direction="row">
<Button variant="text">Text</Button>
<Button variant="contained">Contained</Button>
<Button variant="outlined">Outlined</Button>
</Stack>
);
}
`,
},
'src/index.tsx': {
content: `import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './Demo';
ReactDOM.createRoot(document.querySelector("#root")!).render(
<React.StrictMode>
<StyledEngineProvider injectFirst>
<Demo />
</StyledEngineProvider>
</React.StrictMode>
);`,
},
'tsconfig.json': {
content: `{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
`,
},
});
expect(result.dependencies).to.deep.equal({
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@types/react': 'latest',
'@types/react-dom': 'latest',
react: 'latest',
'react-dom': 'latest',
typescript: 'latest',
});
expect(result.devDependencies).to.deep.equal({
'react-scripts': 'latest',
});
});
it('generate the correct index.html result when Tailwind is used', () => {
const result = CodeSandbox.createReactApp({
title: 'BasicButtons Material Demo',
githubLocation:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.js',
codeVariant: 'JS',
language: 'en',
raw: testCase,
codeStyling: 'Tailwind',
});
expect(result.files['public/index.html'].content).to.contain(
'<script src="https://cdn.tailwindcss.com"></script>',
);
});
it('should generate the correct stylesheet font link in index.html for Material Two Tones icons', () => {
const raw = `import * as React from 'react';
import Icon from '@mui/material/Icon';
export default function TwoToneIcons() {
return <Icon baseClassName="material-icons-two-tone">add_circle</Icon>;
}
`;
const result = CodeSandbox.createReactApp({
raw,
codeVariant: 'JS',
});
expect(result.files['public/index.html'].content).to.contain(
'https://fonts.googleapis.com/icon?family=Material+Icons+Two+Tone',
);
});
});
| 5,343 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/CodeSandbox.ts | // @ts-ignore
import LZString from 'lz-string';
import addHiddenInput from 'docs/src/modules/utils/addHiddenInput';
import SandboxDependencies from 'docs/src/modules/sandbox/Dependencies';
import * as CRA from 'docs/src/modules/sandbox/CreateReactApp';
import getFileExtension from 'docs/src/modules/sandbox/FileExtension';
import { DemoData, CodeVariant, CodeStyling } from 'docs/src/modules/sandbox/types';
function compress(object: any) {
return LZString.compressToBase64(JSON.stringify(object))
.replace(/\+/g, '-') // Convert '+' to '-'
.replace(/\//g, '_') // Convert '/' to '_'
.replace(/=+$/, ''); // Remove ending '='
}
function openSandbox({ files, codeVariant, initialFile }: any) {
const extension = codeVariant === 'TS' ? '.tsx' : '.js';
const parameters = compress({ files });
// ref: https://codesandbox.io/docs/api/#define-api
const form = document.createElement('form');
form.method = 'POST';
form.target = '_blank';
form.action = 'https://codesandbox.io/api/v1/sandboxes/define';
addHiddenInput(form, 'parameters', parameters);
addHiddenInput(
form,
'query',
`file=${initialFile}${initialFile.match(/(\.tsx|\.ts|\.js)$/) ? '' : extension}`,
);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
const createReactApp = (demoData: DemoData) => {
const ext = getFileExtension(demoData.codeVariant);
const { title, githubLocation: description } = demoData;
const files: Record<string, object> = {
'public/index.html': {
content: CRA.getHtml(demoData),
},
[`src/index.${ext}`]: {
content: CRA.getRootIndex(demoData),
},
[`src/Demo.${ext}`]: {
content: demoData.raw,
},
...(demoData.codeVariant === 'TS' && {
'tsconfig.json': {
content: CRA.getTsconfig(),
},
}),
};
const { dependencies, devDependencies } = SandboxDependencies(demoData, {
commitRef: process.env.PULL_REQUEST_ID ? process.env.COMMIT_REF : undefined,
});
files['package.json'] = {
content: {
description,
dependencies,
devDependencies,
...(demoData.codeVariant === 'TS' && {
main: 'index.tsx',
scripts: {
start: 'react-scripts start',
},
}),
},
};
return {
title,
description,
files,
dependencies,
devDependencies,
/**
* @param {string} initialFile
* @description should start with `/`, e.g. `/Demo.tsx`. If the extension is not provided,
* it will be appended based on the code variant.
*/
openSandbox: (initialFile: string = `/src/Demo.${ext}`) =>
openSandbox({ files, codeVariant: demoData.codeVariant, initialFile }),
};
};
const createJoyTemplate = (templateData: {
title: string;
files: Record<string, string>;
githubLocation: string;
codeVariant: CodeVariant;
codeStyling?: CodeStyling;
}) => {
const ext = getFileExtension(templateData.codeVariant);
const { title, githubLocation: description } = templateData;
// document.querySelector returns 'Element | null' but createRoot expects 'Element | DocumentFragment'.
const type = templateData.codeVariant === 'TS' ? '!' : '';
const files: Record<string, object> = {
'public/index.html': {
content: CRA.getHtml({
title: templateData.title,
language: 'en',
codeStyling: templateData.codeStyling ?? 'MUI System',
}),
},
[`index.${ext}`]: {
content: `import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/joy/styles';
import App from './App';
ReactDOM.createRoot(document.querySelector("#root")${type}).render(
<React.StrictMode>
<StyledEngineProvider injectFirst>
<App />
</StyledEngineProvider>
</React.StrictMode>
);`,
},
...Object.entries(templateData.files).reduce(
(prev, curr) => ({
...prev,
[curr[0]]: {
content: curr[1],
},
}),
{},
),
...(templateData.codeVariant === 'TS' && {
'tsconfig.json': {
content: CRA.getTsconfig(),
},
}),
};
const { dependencies, devDependencies } = SandboxDependencies(
{
codeVariant: templateData.codeVariant,
raw: Object.entries(templateData.files).reduce((prev, curr) => `${prev}\n${curr}`, ''),
productId: 'joy-ui',
},
{
commitRef: process.env.PULL_REQUEST_ID ? process.env.COMMIT_REF : undefined,
},
);
files['package.json'] = {
content: {
description,
dependencies,
devDependencies,
...(templateData.codeVariant === 'TS' && {
main: 'index.tsx',
scripts: {
start: 'react-scripts start',
},
}),
},
};
return {
title,
files,
dependencies,
devDependencies,
openSandbox: (initialFile: string = '/App') =>
openSandbox({ files, codeVariant: templateData.codeVariant, initialFile }),
};
};
export default {
createReactApp,
createJoyTemplate,
};
| 5,344 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/CreateReactApp.ts | import { DemoData } from 'docs/src/modules/sandbox/types';
export const getHtml = ({
title,
language,
codeStyling,
raw,
}: {
title: string;
language: string;
codeStyling?: 'Tailwind' | 'MUI System';
raw?: string;
}) => {
return `<!DOCTYPE html>
<html lang="${language}">
<head>
<meta charset="utf-8" />
<title>${title}</title>
<meta name="viewport" content="initial-scale=1, width=device-width" />
<!-- Fonts to support Material Design -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;600;700&display=swap"
/>
<!-- Icons to support Material Design -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons${
raw?.includes('material-icons-two-tone') ? '+Two+Tone' : ''
}"
/>${
codeStyling === 'Tailwind'
? `
<!-- Check the Tailwind CSS's installation guide for setting up tailwind: https://tailwindcss.com/docs/installation -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
animation: {
appear: 'in-right 200ms',
},
border: {
3: '3px',
},
boxShadow: {
'outline-purple': '0 0 0 4px rgba(192, 132, 252, 0.25)',
'outline-purple-light': '0 0 0 4px rgba(245, 208, 254, 0.25)',
'outline-purple-xs': '0 0 0 1px rgba(192, 132, 252, 0.25)',
'outline-switch': '0 0 1px 3px rgba(168, 85, 247, 0.35)',
},
cursor: {
inherit: 'inherit',
},
keyframes: {
'in-right': {
from: { transform: 'translateX(100%)' },
to: { transform: 'translateX(0)' },
},
},
lineHeight: {
'5.5': '1.375rem',
},
maxWidth: {
snackbar: '560px',
},
minHeight: {
badge: '22px',
},
minWidth: {
badge: '22px',
listbox: '200px',
snackbar: '300px',
'tabs-list': '400px',
},
},
},
}
</script>`
: ''
}
</head>
<body>
<div id="root"></div>
</body>
</html>`;
};
export function getRootIndex(demoData: DemoData) {
// document.querySelector returns 'Element | null' but createRoot expects 'Element | DocumentFragment'.
const type = demoData.codeVariant === 'TS' ? '!' : '';
if (demoData.productId === 'joy-ui') {
return `import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { StyledEngineProvider, CssVarsProvider } from '@mui/joy/styles';
import Demo from './Demo';
ReactDOM.createRoot(document.querySelector("#root")${type}).render(
<React.StrictMode>
<StyledEngineProvider injectFirst>
<CssVarsProvider>
<Demo />
</CssVarsProvider>
</StyledEngineProvider>
</React.StrictMode>
);`;
}
if (demoData.productId === 'base-ui') {
return `import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import Demo from './Demo';
ReactDOM.createRoot(document.querySelector("#root")${type}).render(
<React.StrictMode>
<Demo />
</React.StrictMode>
);`;
}
return `import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './Demo';
ReactDOM.createRoot(document.querySelector("#root")${type}).render(
<React.StrictMode>
<StyledEngineProvider injectFirst>
<Demo />
</StyledEngineProvider>
</React.StrictMode>
);`;
}
export const getTsconfig = () => `{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
`;
| 5,345 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/Dependencies.test.js | import { expect } from 'chai';
import SandboxDependencies from './Dependencies';
describe('Dependencies', () => {
before(() => {
process.env.SOURCE_CODE_REPO = 'https://github.com/mui/material-ui';
});
after(() => {
delete process.env.SOURCE_CODE_REPO;
});
const s1 = `
import * as React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@mui/material/styles';
import Input from '@mui/material/Input';
import InputLabel from '@mui/material/InputLabel';
import FormControl from '@mui/material/FormControl';
import FormHelperText from '@mui/material/FormHelperText';
import Select from '@mui/material/Select';
import { SliderUnstyled } from '@mui/base/SliderUnstyled';
import FooBar, { Qux } from '@foo-bar/bip';
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
formControl
`;
it('should handle @ dependencies', () => {
const { dependencies } = SandboxDependencies({
raw: s1,
codeVariant: 'JS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@foo-bar/bip': 'latest',
'@mui/material': 'latest',
'@mui/base': 'latest',
'prop-types': 'latest',
});
});
it('should handle * dependencies', () => {
const source = `
import * as React from 'react';
import PropTypes from 'prop-types';
import * as _ from '@unexisting/thing';
import Draggable from 'react-draggable';
import match from 'autosuggest-highlight/match';
import parse from 'autosuggest-highlight/parse';
import TextField from '@mui/material/TextField';
import Paper from '@mui/material/Paper';
import MenuItem from '@mui/material/MenuItem';
import { withStyles } from '@mui/material/styles';
const suggestions = [
`;
const { dependencies } = SandboxDependencies({
raw: source,
codeVariant: 'JS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@unexisting/thing': 'latest',
'autosuggest-highlight': 'latest',
'prop-types': 'latest',
'react-draggable': 'latest',
});
});
it('should support direct import', () => {
const source = `
import * as React from 'react';
import PropTypes from 'prop-types';
import Grid from '@mui/material/Grid';
import { withStyles } from '@mui/material/styles';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import { LocalizationProvider as MuiPickersLocalizationProvider, KeyboardTimePicker, KeyboardDatePicker } from '@mui/lab';
`;
const { dependencies } = SandboxDependencies({
raw: source,
codeVariant: 'JS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'prop-types': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@mui/lab': 'latest',
'date-fns': 'latest',
});
});
it('should support import for side effect', () => {
const source = `
import * as React from 'react';
import PropTypes from 'prop-types';
import '@mui/material/Grid';
import '@mui/material/styles';
import '@mui/lab/AdapterDateFns';
import '@mui/lab';
import 'exceljs';
`;
const { dependencies } = SandboxDependencies({
raw: source,
codeVariant: 'JS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'prop-types': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@mui/lab': 'latest',
'date-fns': 'latest',
exceljs: 'latest',
});
});
it('can collect required @types packages', () => {
const { dependencies } = SandboxDependencies({
raw: s1,
codeVariant: 'TS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'prop-types': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@foo-bar/bip': 'latest',
'@mui/material': 'latest',
'@mui/base': 'latest',
'@types/foo-bar__bip': 'latest',
'@types/prop-types': 'latest',
'@types/react-dom': 'latest',
'@types/react': 'latest',
typescript: 'latest',
});
});
it('should handle @types correctly', () => {
const { dependencies } = SandboxDependencies({
raw: `import utils from '../utils';`,
codeVariant: 'TS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@types/react-dom': 'latest',
'@types/react': 'latest',
typescript: 'latest',
});
});
it('should handle multilines', () => {
const source = `
import * as React from 'react';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import {
LocalizationProvider as MuiPickersLocalizationProvider,
KeyboardTimePicker,
KeyboardDatePicker,
} from '@mui/lab';
`;
const { dependencies } = SandboxDependencies({
raw: source,
codeVariant: 'JS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@mui/lab': 'latest',
'date-fns': 'latest',
});
});
it('should include core if lab present', () => {
const source = `
import lab from '@mui/lab';
`;
const { dependencies } = SandboxDependencies({
raw: source,
codeVariant: 'JS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@mui/lab': 'latest',
});
});
it('can use codesandbox deploys if a commit is given', () => {
const source = `
import * as Material from '@mui/material';
import * as Base from '@mui/base';
import * as IconsMaterial from '@mui/icons-material';
import * as Lab from '@mui/lab';
import * as Styles from '@mui/styles';
import * as System from '@mui/system';
import * as Utils from '@mui/utils';
`;
const { dependencies } = SandboxDependencies(
{
raw: source,
codeVariant: 'JS',
},
{ commitRef: '2d0e8b4daf20b7494c818b6f8c4cc8423bc99d6f' },
);
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'https://pkg.csb.dev/mui/material-ui/commit/2d0e8b4d/@mui/material',
'@mui/icons-material':
'https://pkg.csb.dev/mui/material-ui/commit/2d0e8b4d/@mui/icons-material',
'@mui/lab': 'https://pkg.csb.dev/mui/material-ui/commit/2d0e8b4d/@mui/lab',
'@mui/styles': 'https://pkg.csb.dev/mui/material-ui/commit/2d0e8b4d/@mui/styles',
'@mui/system': 'https://pkg.csb.dev/mui/material-ui/commit/2d0e8b4d/@mui/system',
'@mui/utils': 'https://pkg.csb.dev/mui/material-ui/commit/2d0e8b4d/@mui/utils',
'@mui/base': 'https://pkg.csb.dev/mui/material-ui/commit/2d0e8b4d/@mui/base',
});
});
it('should handle date adapters', () => {
const source = `
import * as React from 'react';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import AdapterDayjs from '@mui/lab/AdapterDayjs';
import AdapterLuxon from '@mui/lab/AdapterLuxon';
import AdapterMoment from '@mui/lab/AdapterMoment';
`;
const { dependencies } = SandboxDependencies({
raw: source,
codeVariant: 'JS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@mui/lab': 'latest',
'date-fns': 'latest',
dayjs: 'latest',
luxon: 'latest',
moment: 'latest',
});
});
it('should handle dependencies for @mui/x-date-pickers', () => {
const source = `
import * as React from 'react';
import TextField from '@mui/material/TextField';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { AdapterDateFnsJalali } from '@mui/x-date-pickers/AdapterDateFnsJalali';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { AdapterLuxon } from '@mui/x-date-pickers/AdapterLuxon';
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';
import { AdapterMomentHijri } from '@mui/x-date-pickers/AdapterMomentHijri';
import { AdapterMomentJalaali } from '@mui/x-date-pickers/AdapterMomentJalaali';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';`;
const { dependencies } = SandboxDependencies({
raw: source,
codeVariant: 'JS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': 'latest',
'@mui/x-date-pickers': 'latest',
'date-fns': 'latest',
'date-fns-jalali': 'latest',
dayjs: 'latest',
luxon: 'latest',
moment: 'latest',
'moment-hijri': 'latest',
'moment-jalaali': 'latest',
});
});
it('should not have . as a dependency', () => {
const source = `import * as React from 'react';
import Box, { BoxProps } from '@mui/joy/Box';
import Sheet from '@mui/joy/Sheet';
const Root = (props: BoxProps) => (
<Box
{...props}
sx={[
{
bgcolor: 'background.bodyEmail',
display: 'grid',
gridTemplateColumns: {
xs: '1fr',
sm: 'minmax(64px, 200px) minmax(450px, 1fr)',
md: 'minmax(160px, 300px) minmax(300px, 500px) minmax(500px, 1fr)',
},
gridTemplateRows: '64px 1fr',
minHeight: '100vh',
},
...(Array.isArray(props.sx) ? props.sx : [props.sx]),
]}
/>
);
export default {
Root,
Header,
SideNav,
SidePane,
SideDrawer,
Main,
};
import * as React from 'react';
import { GlobalStyles } from '@mui/system';
import { CssVarsProvider, useColorScheme } from '@mui/joy/styles';
import type { Theme } from '@mui/joy/styles';
import Box from '@mui/joy/Box';
import Typography from '@mui/joy/Typography';
import Input from '@mui/joy/Input';
import IconButton from '@mui/joy/IconButton';
// Icons import
import SearchRoundedIcon from '@mui/icons-material/SearchRounded';
import DarkModeRoundedIcon from '@mui/icons-material/DarkModeRounded';
import LightModeRoundedIcon from '@mui/icons-material/LightModeRounded';
import GridViewRoundedIcon from '@mui/icons-material/GridViewRounded';
import MailRoundedIcon from '@mui/icons-material/MailRounded';
import KeyboardArrowDownRoundedIcon from '@mui/icons-material/KeyboardArrowDownRounded';
import MenuIcon from '@mui/icons-material/Menu';
// custom
import emailTheme from './theme';
import Layout from './components/Layout';
import Navigation from './components/Navigation';
import Mails from './components/Mails';
import MailContent from './components/MailContent';
const ColorSchemeToggle = () => {
const { mode, setMode } = useColorScheme();
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return <IconButton size="sm" variant="outlined" color="primary" />;
}
return (
<IconButton
size="sm"
variant="outlined"
color="primary"
onClick={() => {
if (mode === 'light') {
setMode('dark');
} else {
setMode('light');
}
}}
>
{mode === 'light' ? <DarkModeRoundedIcon /> : <LightModeRoundedIcon />}
</IconButton>
);
};
export default function EmailExample() {
const [drawerOpen, setDrawerOpen] = React.useState(false);
return (
<CssVarsProvider disableTransitionOnChange theme={emailTheme}>
<GlobalStyles<Theme>
styles={(theme) => ({
body: {
margin: 0,
fontFamily: theme.vars.fontFamily.body,
},
})}
/>
{drawerOpen && (
<Layout.SideDrawer onClose={() => setDrawerOpen(false)}>
<Navigation />
</Layout.SideDrawer>
)}
<Layout.Root
sx={{
...(drawerOpen && {
height: '100vh',
overflow: 'hidden',
}),
}}
>
<Layout.Header>
<Box
sx={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
gap: 1.5,
}}
>
<IconButton
variant="outlined"
size="sm"
onClick={() => setDrawerOpen(true)}
sx={{ display: { sm: 'none' } }}
>
<MenuIcon />
</IconButton>
<IconButton
size="sm"
variant="solid"
sx={{ display: { xs: 'none', sm: 'inherit' } }}
>
<MailRoundedIcon />
</IconButton>
<Typography fontWeight={700}>Email</Typography>
</Box>
<Input
size="sm"
placeholder="Search anything…"
startDecorator={<SearchRoundedIcon color="primary" />}
endDecorator={
<IconButton variant="outlined" size="sm" color="neutral">
<Typography fontWeight="lg" fontSize="sm" textColor="text.tertiary">
/
</Typography>
</IconButton>
}
sx={{
flexBasis: '500px',
display: {
xs: 'none',
sm: 'flex',
},
}}
/>
<Box sx={{ display: 'flex', flexDirection: 'row', gap: 1.5 }}>
<IconButton
size="sm"
variant="outlined"
color="primary"
sx={{ display: { xs: 'inline-flex', sm: 'none' } }}
>
<SearchRoundedIcon />
</IconButton>
<IconButton size="sm" variant="outlined" color="primary">
<GridViewRoundedIcon />
</IconButton>
<ColorSchemeToggle />
</Box>
</Layout.Header>
<Layout.SideNav>
<Navigation />
</Layout.SideNav>
<Layout.SidePane>
<Box
sx={{
p: 2,
mb: 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Typography
textColor="neutral.500"
fontWeight={700}
sx={{
fontSize: '10px',
textTransform: 'uppercase',
letterSpacing: '.1rem',
}}
>
Unread
</Typography>
<IconButton
size="sm"
variant="plain"
color="primary"
sx={{ '--IconButton-size': '24px' }}
>
<KeyboardArrowDownRoundedIcon fontSize="small" color="primary" />
</IconButton>
</Box>
<Box sx={{ py: 10 }}>
<Typography
textColor="text.tertiary"
level="body-sm"
sx={{ textAlign: 'center' }}
>
You've read all messages in your inbox.
</Typography>
</Box>
<Box
sx={{
p: 2,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Typography
textColor="neutral.500"
fontWeight={700}
sx={{
fontSize: '10px',
textTransform: 'uppercase',
letterSpacing: '.1rem',
}}
>
Everything else
</Typography>
<IconButton
size="sm"
variant="plain"
color="primary"
sx={{ '--IconButton-size': '24px' }}
>
<KeyboardArrowDownRoundedIcon fontSize="small" color="primary" />
</IconButton>
</Box>
<Mails />
</Layout.SidePane>
<Layout.Main>
<MailContent />
</Layout.Main>
</Layout.Root>
</CssVarsProvider>
);
}
`;
const { dependencies } = SandboxDependencies({
raw: source,
codeVariant: 'TS',
});
expect(dependencies).to.deep.equal({
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/icons-material': 'latest',
'@mui/joy': 'latest',
'@mui/material': 'latest',
'@mui/system': 'latest',
'@types/react': 'latest',
'@types/react-dom': 'latest',
typescript: 'latest',
});
});
});
| 5,346 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/Dependencies.ts | import { CODE_VARIANTS } from 'docs/src/modules/constants';
import type { MuiProductId } from 'docs/src/modules/utils/getProductInfoFromUrl';
type RegExpMatchArrayWithGroupsOnly<T> = {
groups?: {
[key in keyof T]: string;
};
};
type RegExpMatchArrayWithGroups<T> = (RegExpMatchArray & RegExpMatchArrayWithGroupsOnly<T>) | null;
export default function SandboxDependencies(
demo: {
raw: string;
productId?: MuiProductId;
codeVariant: keyof typeof CODE_VARIANTS;
},
options?: { commitRef?: string },
) {
const { commitRef } = options || {};
/**
* WARNING: Always uses `latest` typings.
*
* Adds dependencies to @types packages only for packages that are not listed
* in packagesWithBundledTypes
*
* @param deps - list of dependency as `name => version`
*/
function addTypeDeps(deps: Record<string, string>): void {
const packagesWithBundledTypes = ['date-fns', '@emotion/react', '@emotion/styled', 'dayjs'];
const packagesWithDTPackage = Object.keys(deps)
.filter((name) => packagesWithBundledTypes.indexOf(name) === -1)
// All the MUI packages come with bundled types
.filter((name) => name.indexOf('@mui/') !== 0);
packagesWithDTPackage.forEach((name) => {
let resolvedName = name;
// scoped package?
if (name.startsWith('@')) {
// https://github.com/DefinitelyTyped/DefinitelyTyped#what-about-scoped-packages
resolvedName = name.slice(1).replace('/', '__');
}
deps[`@types/${resolvedName}`] = 'latest';
});
}
/**
* @param packageName - The name of a package living inside this repository.
* @return string - A valid version for a dependency entry in a package.json
*/
function getMuiPackageVersion(packageName: string): string {
if (
commitRef === undefined ||
process.env.SOURCE_CODE_REPO !== 'https://github.com/mui/material-ui'
) {
// #default-branch-switch
return 'latest';
}
const shortSha = commitRef.slice(0, 8);
return `https://pkg.csb.dev/mui/material-ui/commit/${shortSha}/@mui/${packageName}`;
}
function extractDependencies(raw: string) {
function includePeerDependencies(
deps: Record<string, string>,
versions: Record<string, string>,
): Record<string, string> {
let newDeps: Record<string, string> = {
...deps,
'react-dom': versions['react-dom'],
react: versions.react,
'@emotion/react': versions['@emotion/react'],
'@emotion/styled': versions['@emotion/styled'],
};
if (newDeps['@mui/lab'] || newDeps['@mui/icons-material']) {
newDeps['@mui/material'] = versions['@mui/material'];
}
if (newDeps['@mui/x-data-grid']) {
newDeps['@mui/material'] = versions['@mui/material'];
}
// TODO: consider if this configuration could be injected in a "cleaner" way.
if ((window as any).muiDocConfig) {
newDeps = (window as any).muiDocConfig.csbIncludePeerDependencies(newDeps, { versions });
}
return newDeps;
}
let deps: Record<string, string> = {};
let versions: Record<string, string> = {
react: 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@mui/material': getMuiPackageVersion('material'),
'@mui/icons-material': getMuiPackageVersion('icons-material'),
'@mui/lab': getMuiPackageVersion('lab'),
'@mui/styled-engine': getMuiPackageVersion('styled-engine'),
'@mui/styles': getMuiPackageVersion('styles'),
'@mui/system': getMuiPackageVersion('system'),
'@mui/private-theming': getMuiPackageVersion('theming'),
'@mui/private-classnames': getMuiPackageVersion('classnames'),
'@mui/base': getMuiPackageVersion('base'),
'@mui/utils': getMuiPackageVersion('utils'),
'@mui/material-next': getMuiPackageVersion('material-next'),
'@mui/joy': getMuiPackageVersion('joy'),
};
// TODO: consider if this configuration could be injected in a "cleaner" way.
if ((window as any).muiDocConfig) {
const muiCommitRef = process.env.PULL_REQUEST_ID ? process.env.COMMIT_REF : undefined;
versions = (window as any).muiDocConfig.csbGetVersions(versions, { muiCommitRef });
}
const re = /^import\s'([^']+)'|import\s[\s\S]*?\sfrom\s+'([^']+)/gm;
let m: RegExpExecArray | null = null;
// eslint-disable-next-line no-cond-assign
while ((m = re.exec(raw))) {
const fullName = m[2] ?? m[1];
// handle scope names
const name =
fullName.charAt(0) === '@' ? fullName.split('/', 2).join('/') : fullName.split('/', 1)[0];
if (!deps[name] && !name.startsWith('.')) {
deps[name] = versions[name] ? versions[name] : 'latest';
}
// e.g. date-fns
const dateAdapterMatch = fullName.match(
/^@mui\/(lab|x-date-pickers)\/(?<adapterName>Adapter.*)/,
) as RegExpMatchArrayWithGroups<{ adapterName: string }>;
if (dateAdapterMatch !== null) {
/**
* Mapping from the date adapter sub-packages to the npm packages they require.
* @example `@mui/x-date-pickers/AdapterDayjs` has a peer dependency on `dayjs`.
*/
const packageName = (
{
AdapterDateFns: 'date-fns',
AdapterDateFnsJalali: 'date-fns-jalali',
AdapterDayjs: 'dayjs',
AdapterLuxon: 'luxon',
AdapterMoment: 'moment',
AdapterMomentHijri: 'moment-hijri',
AdapterMomentJalaali: 'moment-jalaali',
} as Record<string, string>
)[dateAdapterMatch.groups?.adapterName || ''];
if (packageName === undefined) {
throw new TypeError(
`Can't determine required npm package for adapter '${dateAdapterMatch[1]}'`,
);
}
deps[packageName] = 'latest';
}
}
deps = includePeerDependencies(deps, versions);
return deps;
}
const dependencies = extractDependencies(demo.raw);
if (demo.codeVariant === CODE_VARIANTS.TS) {
addTypeDeps(dependencies);
dependencies.typescript = 'latest';
}
if (!demo.productId && !dependencies['@mui/material']) {
// The `index.js` imports StyledEngineProvider from '@mui/material', so we need to make sure we have it as a dependency
const name = '@mui/material';
const versions = {
[name]: getMuiPackageVersion('material'),
};
dependencies[name] = versions[name] ? versions[name] : 'latest';
}
const devDependencies = {
'react-scripts': 'latest',
};
return { dependencies, devDependencies };
}
| 5,347 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/FileExtension.ts | export default function getFileExtension(codeVariant: 'TS' | 'JS') {
if (codeVariant === 'TS') {
return 'tsx';
}
if (codeVariant === 'JS') {
return 'js';
}
throw new Error(`Unsupported codeVariant: ${codeVariant}`);
}
| 5,348 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/StackBlitz.test.js | import { expect } from 'chai';
import StackBlitz from './StackBlitz';
const testCase = `import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
export default function BasicButtons() {
return (
<Stack spacing={2} direction="row">
<Button variant="text">Text</Button>
<Button variant="contained">Contained</Button>
<Button variant="outlined">Outlined</Button>
</Stack>
);
}
`;
describe('StackBlitz', () => {
it('generate the correct JavaScript result', () => {
const { openSandbox, ...result } = StackBlitz.createReactApp({
title: 'BasicButtons Material Demo',
githubLocation:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.js',
codeVariant: 'JS',
language: 'en',
raw: testCase,
});
expect(result).to.deep.equal({
title: 'BasicButtons Material Demo',
description:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.js',
files: {
'index.html': `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>BasicButtons Material Demo</title>
<meta name="viewport" content="initial-scale=1, width=device-width" />
<!-- Fonts to support Material Design -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;600;700&display=swap"
/>
<!-- Icons to support Material Design -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
</head>
<body>
<div id="root"></div>
</body>
</html>`,
'Demo.js': `import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
export default function BasicButtons() {
return (
<Stack spacing={2} direction="row">
<Button variant="text">Text</Button>
<Button variant="contained">Contained</Button>
<Button variant="outlined">Outlined</Button>
</Stack>
);
}
`,
'index.js': `import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './Demo';
ReactDOM.createRoot(document.querySelector("#root")).render(
<React.StrictMode>
<StyledEngineProvider injectFirst>
<Demo />
</StyledEngineProvider>
</React.StrictMode>
);`,
},
dependencies: {
react: 'latest',
'@mui/material': 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
},
devDependencies: {
'react-scripts': 'latest',
},
});
});
it('generate the correct TypeScript result', () => {
const { openSandbox, ...result } = StackBlitz.createReactApp({
title: 'BasicButtons Material Demo',
githubLocation:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.tsx',
codeVariant: 'TS',
language: 'en',
raw: testCase,
});
expect(result).to.deep.equal({
title: 'BasicButtons Material Demo',
description:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.tsx',
files: {
'index.html': `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>BasicButtons Material Demo</title>
<meta name="viewport" content="initial-scale=1, width=device-width" />
<!-- Fonts to support Material Design -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;600;700&display=swap"
/>
<!-- Icons to support Material Design -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
</head>
<body>
<div id="root"></div>
</body>
</html>`,
'Demo.tsx': `import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
export default function BasicButtons() {
return (
<Stack spacing={2} direction="row">
<Button variant="text">Text</Button>
<Button variant="contained">Contained</Button>
<Button variant="outlined">Outlined</Button>
</Stack>
);
}
`,
'index.tsx': `import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './Demo';
ReactDOM.createRoot(document.querySelector("#root")!).render(
<React.StrictMode>
<StyledEngineProvider injectFirst>
<Demo />
</StyledEngineProvider>
</React.StrictMode>
);`,
'tsconfig.json': `{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
`,
},
dependencies: {
react: 'latest',
'@mui/material': 'latest',
'react-dom': 'latest',
'@emotion/react': 'latest',
'@emotion/styled': 'latest',
'@types/react': 'latest',
'@types/react-dom': 'latest',
typescript: 'latest',
},
devDependencies: {
'react-scripts': 'latest',
},
});
});
it('generate the correct index.html result when Tailwind is used', () => {
const { openSandbox, ...result } = StackBlitz.createReactApp({
title: 'BasicButtons Material Demo',
githubLocation:
'https://github.com/mui/material-ui/blob/v5.7.0/docs/data/material/components/buttons/BasicButtons.js',
codeVariant: 'JS',
language: 'en',
raw: testCase,
codeStyling: 'Tailwind',
});
expect(result.files['index.html']).to.contain(
'<script src="https://cdn.tailwindcss.com"></script>',
);
});
it('should generate the correct stylesheet font link in index.html for Material Two Tones icons', () => {
const raw = `import * as React from 'react';
import Icon from '@mui/material/Icon';
export default function TwoToneIcons() {
return <Icon baseClassName="material-icons-two-tone">add_circle</Icon>;
}
`;
const result = StackBlitz.createReactApp({
raw,
codeVariant: 'JS',
});
expect(result.files['index.html']).to.contain(
'https://fonts.googleapis.com/icon?family=Material+Icons+Two+Tone',
);
});
});
| 5,349 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/StackBlitz.ts | import addHiddenInput from 'docs/src/modules/utils/addHiddenInput';
import { CODE_VARIANTS } from 'docs/src/modules/constants';
import SandboxDependencies from 'docs/src/modules/sandbox/Dependencies';
import * as CRA from 'docs/src/modules/sandbox/CreateReactApp';
import getFileExtension from 'docs/src/modules/sandbox/FileExtension';
import { DemoData } from 'docs/src/modules/sandbox/types';
const createReactApp = (demoData: DemoData) => {
const ext = getFileExtension(demoData.codeVariant);
const { title, githubLocation: description } = demoData;
const files: Record<string, string> = {
'index.html': CRA.getHtml(demoData),
[`index.${ext}`]: CRA.getRootIndex(demoData),
[`Demo.${ext}`]: demoData.raw,
...(demoData.codeVariant === 'TS' && {
'tsconfig.json': CRA.getTsconfig(),
}),
};
const { dependencies, devDependencies } = SandboxDependencies(demoData, {
// Waiting for https://github.com/stackblitz/core/issues/437
// commitRef: process.env.PULL_REQUEST_ID ? process.env.COMMIT_REF : undefined,
});
return {
title,
description,
files,
dependencies,
devDependencies,
openSandbox: (initialFile = `Demo.${ext}`) => {
const extension = demoData.codeVariant === CODE_VARIANTS.TS ? '.tsx' : '.js';
// ref: https://developer.stackblitz.com/docs/platform/post-api/
const form = document.createElement('form');
form.method = 'POST';
form.target = '_blank';
form.action = `https://stackblitz.com/run?file=${initialFile}${
initialFile.match(/(\.tsx|\.ts|\.js)$/) ? '' : extension
}`;
addHiddenInput(form, 'project[template]', 'create-react-app');
addHiddenInput(form, 'project[title]', title);
addHiddenInput(form, 'project[description]', `# ${title}\n${description}`);
addHiddenInput(form, 'project[dependencies]', JSON.stringify(dependencies));
addHiddenInput(form, 'project[devDependencies]', JSON.stringify(devDependencies));
Object.keys(files).forEach((key) => {
const value = files[key];
addHiddenInput(form, `project[files][${key}]`, value);
});
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
},
};
};
export default {
createReactApp,
};
| 5,350 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/sandbox/types.ts | import type { MuiProductId } from 'docs/src/modules/utils/getProductInfoFromUrl';
export type CodeStyling = 'Tailwind' | 'MUI System';
export type CodeVariant = 'TS' | 'JS';
export interface DemoData {
title: string;
language: string;
raw: string;
codeVariant: CodeVariant;
githubLocation: string;
productId?: Exclude<MuiProductId, 'null'>;
codeStyling: CodeStyling;
}
| 5,351 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/CodeCopy.tsx | import * as React from 'react';
import copy from 'clipboard-copy';
import { useRouter } from 'next/router';
const CodeBlockContext = React.createContext<React.MutableRefObject<HTMLDivElement | null>>({
current: null,
});
/**
* How to use: spread the handlers to the .MuiCode-root
*
* The html structure should be:
* <div className="MuiCode-root">
* <pre>...</pre>
* <button className="MuiCode-copy">...</button>
* </div>
*/
export function useCodeCopy(): any {
const rootNode = React.useContext(CodeBlockContext);
return {
onMouseEnter: (event: React.MouseEvent) => {
rootNode.current = event.currentTarget as HTMLDivElement;
},
onMouseLeave: (event: React.MouseEvent) => {
if (rootNode.current === event.currentTarget) {
(rootNode.current.querySelector('.MuiCode-copy') as null | HTMLButtonElement)?.blur();
rootNode.current = null;
}
},
onFocus: (event: React.MouseEvent) => {
rootNode.current = event.currentTarget as HTMLDivElement;
},
onBlur: (event: React.FocusEvent) => {
if (rootNode.current === event.currentTarget) {
rootNode.current = null;
}
},
};
}
function InitCodeCopy() {
const rootNode = React.useContext(CodeBlockContext);
const router = useRouter();
React.useEffect(() => {
let key = 'Ctrl + ';
if (typeof window !== 'undefined') {
const macOS = window.navigator.platform.toUpperCase().indexOf('MAC') >= 0;
if (macOS) {
key = '⌘';
}
}
const codeRoots = document.getElementsByClassName(
'MuiCode-root',
) as HTMLCollectionOf<HTMLDivElement>;
if (codeRoots !== null) {
const listeners: Array<() => void> = [];
Array.from(codeRoots).forEach((elm) => {
const handleMouseEnter = () => {
rootNode.current = elm;
};
elm.addEventListener('mouseenter', handleMouseEnter);
listeners.push(() => elm.removeEventListener('mouseenter', handleMouseEnter));
const handleMouseLeave = () => {
if (rootNode.current === elm) {
(rootNode.current.querySelector('.MuiCode-copy') as null | HTMLButtonElement)?.blur();
rootNode.current = null;
}
};
elm.addEventListener('mouseleave', handleMouseLeave);
listeners.push(() => elm.removeEventListener('mouseleave', handleMouseLeave));
const handleFocusin = () => {
// use `focusin` because it bubbles from the copy button
rootNode.current = elm;
};
elm.addEventListener('focusin', handleFocusin);
listeners.push(() => elm.removeEventListener('focusin', handleFocusin));
const handleFocusout = () => {
// use `focusout` because it bubbles from the copy button
if (rootNode.current === elm) {
rootNode.current = null;
}
};
elm.addEventListener('focusout', handleFocusout);
listeners.push(() => elm.removeEventListener('focusout', handleFocusout));
async function handleClick(event: MouseEvent) {
const trigger = event.currentTarget as HTMLButtonElement;
const pre = (event.currentTarget as Element)?.previousElementSibling as Element;
const textNode = trigger.childNodes[0];
textNode.nodeValue = textNode.textContent?.replace('Copy', 'Copied') || null;
trigger.dataset.copied = 'true';
setTimeout(() => {
if (trigger) {
textNode.nodeValue = textNode.textContent?.replace('Copied', 'Copy') || null;
delete trigger.dataset.copied;
}
}, 2000);
try {
if (pre.textContent) {
await copy(pre.textContent);
}
// eslint-disable-next-line no-empty
} catch (error) {}
}
const btn = elm.querySelector('.MuiCode-copy') as HTMLButtonElement | null;
if (btn) {
const keyNode = btn.querySelector('.MuiCode-copyKeypress')?.childNodes[1];
if (!keyNode) {
// skip the logic if the btn is not generated from the markdown.
return;
}
keyNode.textContent = keyNode?.textContent?.replace('$key', key) || null;
btn.addEventListener('click', handleClick);
listeners.push(() => btn.removeEventListener('click', handleClick));
}
});
return () => {
listeners.forEach((removeEventListener) => {
removeEventListener();
});
};
}
return undefined;
}, [rootNode, router.pathname]);
return null;
}
function hasNativeSelection(element: HTMLTextAreaElement) {
if (window.getSelection()?.toString()) {
return true;
}
// window.getSelection() returns an empty string in Firefox for selections inside a form element.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=85686.
// Instead, we can use element.selectionStart that is only defined on form elements.
if (element && (element.selectionEnd || 0) - (element.selectionStart || 0) > 0) {
return true;
}
return false;
}
interface CodeCopyProviderProps {
children: React.ReactNode;
}
/**
* Place <CodeCopyProvider> at the page level. It will check the keydown event and try to initiate copy click if rootNode exist.
* Any code block inside the tree can set the rootNode when mouse enter to leverage keyboard copy.
*/
export function CodeCopyProvider({ children }: CodeCopyProviderProps) {
const rootNode = React.useRef<HTMLDivElement | null>(null);
React.useEffect(() => {
document.addEventListener('keydown', (event) => {
if (hasNativeSelection(event.target as HTMLTextAreaElement)) {
// Skip if user is highlighting a text.
return;
}
// event.key === 'c' is not enough as alt+c can lead to ©, ç, or other characters on macOS.
// event.code === 'KeyC' is not enough as event.code assume a QWERTY keyboard layout which would
// be wrong with a Dvorak keyboard (as if pressing J).
const isModifierKeyPressed = event.ctrlKey || event.metaKey || event.altKey;
if (String.fromCharCode(event.keyCode) !== 'C' || !isModifierKeyPressed) {
return;
}
if (!rootNode.current) {
return;
}
const copyBtn = rootNode.current.querySelector('.MuiCode-copy') as HTMLButtonElement | null;
if (!copyBtn) {
return;
}
const initialEventAction = copyBtn.getAttribute('data-ga-event-action');
// update the 'data-ga-event-action' on the button to track keyboard interaction
copyBtn.dataset.gaEventAction =
initialEventAction?.replace('click', 'keyboard') || 'copy-keyboard';
copyBtn.click(); // let the GA setup in GoogleAnalytics.js do the job
copyBtn.dataset.gaEventAction = initialEventAction!; // reset the 'data-ga-event-action' back to initial
});
}, []);
return (
<CodeBlockContext.Provider value={rootNode}>
<InitCodeCopy />
{children}
</CodeBlockContext.Provider>
);
}
| 5,352 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/StyledEngineProvider.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { StyleSheetManager } from 'styled-components';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { prefixer } from 'stylis';
import rtlPlugin from 'stylis-plugin-rtl';
import { useTheme } from '@mui/material/styles';
// Cache for the rtl version of the styles
const cacheRtl = createCache({
key: 'rtl',
prepend: true,
stylisPlugins: [prefixer, rtlPlugin],
});
export default function StyledEngineProvider(props) {
const { children, cacheLtr } = props;
const theme = useTheme();
const rtl = theme.direction === 'rtl';
const emotionCache = theme.direction === 'rtl' ? cacheRtl : cacheLtr;
return (
<StyleSheetManager stylisPlugins={rtl ? [rtlPlugin] : []}>
<CacheProvider value={emotionCache}>{children}</CacheProvider>
</StyleSheetManager>
);
}
StyledEngineProvider.propTypes = {
cacheLtr: PropTypes.object.isRequired,
children: PropTypes.node,
};
| 5,353 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/addHiddenInput.ts | export default function addHiddenInput(form: HTMLFormElement, name: string, value: string) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
form.appendChild(input);
}
| 5,354 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/babel-plugin-jsx-preview.js | const fs = require('fs');
const pluginName = 'babel-plugin-jsx-preview';
/**
* @returns {import('@babel/core').PluginObj}
*/
export default function babelPluginJsxPreview() {
const wrapperTypes = ['div', 'Box', 'Stack'];
/**
* @type {import('@babel/core').types.JSXElement | import('@babel/core').types.JSXElement['children']}
*/
let previewNode = null;
return {
name: pluginName,
visitor: {
ExportDefaultDeclaration(path) {
const { declaration } = path.node;
if (declaration.type !== 'FunctionDeclaration') {
return;
}
const { body } = declaration.body;
/**
* @type {import('@babel/core').types.ReturnStatement[]}
*/
const [lastReturn] = body
.filter((statement) => {
return statement.type === 'ReturnStatement';
})
.reverse();
const returnedJSX = lastReturn.argument;
if (returnedJSX.type === 'JSXElement') {
previewNode = returnedJSX;
if (
wrapperTypes.includes(previewNode.openingElement.name.name) &&
previewNode.children.length > 0
) {
// Trim blank JSXText to normalize
// return (
// <div />
// )
// and
// return (
// <Stack>
// <div />
// ^^^^ Blank JSXText including newline
// </Stack>
// )
previewNode = previewNode.children.filter((child, index, children) => {
const isSurroundingBlankJSXText =
(index === 0 || index === children.length - 1) &&
child.type === 'JSXText' &&
!/[^\s]+/.test(child.value);
return !isSurroundingBlankJSXText;
});
}
}
},
},
post(state) {
const { maxLines, outputFilename } = state.opts.plugins.find((plugin) => {
return plugin.key === pluginName;
}).options;
let hasPreview = false;
if (previewNode !== null) {
const [startNode, endNode] = Array.isArray(previewNode)
? [previewNode[0], previewNode.slice(-1)[0]]
: [previewNode, previewNode];
const preview = state.code.slice(startNode.start, endNode.end);
const previewLines = preview.split(/\n/);
// The first line is already trimmed either due to trimmed blank JSXText or because it's a single node which babel already trims.
// The last line is therefore the measure for indentation
const indentation = previewLines.slice(-1)[0].match(/^\s*/)[0].length;
const deindentedPreviewLines = preview.split(/\n/).map((line, index) => {
if (index === 0) {
return line;
}
return line.slice(indentation);
});
if (deindentedPreviewLines.length <= maxLines) {
fs.writeFileSync(outputFilename, deindentedPreviewLines.join('\n'));
hasPreview = true;
}
}
if (!hasPreview) {
try {
fs.unlinkSync(outputFilename);
} catch (error) {
// Would throw if the file doesn't exist.
// But we do want to ensure that the file doesn't exist so the error is fine.
}
}
},
};
}
| 5,355 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/codeStylingSolution.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { getCookie } from 'docs/src/modules/utils/helpers';
import { CODE_STYLING } from 'docs/src/modules/constants';
const CodeStylingContext = React.createContext({
codeStyling: CODE_STYLING.SYSTEM,
setCodeStyling: () => {},
});
if (process.env.NODE_ENV !== 'production') {
CodeStylingContext.displayName = 'CodeStyling';
}
function useFirstRender() {
const firstRenderRef = React.useRef(true);
React.useEffect(() => {
firstRenderRef.current = false;
}, []);
return firstRenderRef.current;
}
export function CodeStylingProvider(props) {
const { children } = props;
const [codeStyling, setCodeStyling] = React.useState(CODE_STYLING.SYSTEM);
const navigatedCodeStyling = React.useMemo(() => {
const navigatedCodeMatch =
typeof window !== 'undefined' ? window.location.hash.match(/\.(js|tsx)$/) : null;
if (navigatedCodeMatch === null) {
return undefined;
}
if (typeof window !== 'undefined') {
if (window.location.hash.indexOf('tailwind-') >= 0) {
return CODE_STYLING.TAILWIND;
}
if (window.location.hash.indexOf('css-') >= 0) {
return CODE_STYLING.CSS;
}
if (window.location.hash.indexOf('system-') >= 0) {
return CODE_STYLING.SYSTEM;
}
}
return undefined;
}, []);
const persistedCodeStyling = React.useMemo(() => {
if (typeof window === 'undefined') {
return undefined;
}
return getCookie('codeStyling');
}, []);
const isFirstRender = useFirstRender();
// We initialize from navigation or cookies. on subsequent renders the store is the truth
const noSsrCodeStyling =
isFirstRender === true
? navigatedCodeStyling || persistedCodeStyling || codeStyling
: codeStyling;
React.useEffect(() => {
if (codeStyling !== noSsrCodeStyling) {
setCodeStyling(noSsrCodeStyling);
}
}, [codeStyling, noSsrCodeStyling]);
React.useEffect(() => {
document.cookie = `codeStyling=${codeStyling};path=/;max-age=31536000`;
}, [codeStyling]);
const contextValue = React.useMemo(() => {
return { codeStyling, noSsrCodeStyling, setCodeStyling };
}, [codeStyling, noSsrCodeStyling]);
return <CodeStylingContext.Provider value={contextValue}>{children}</CodeStylingContext.Provider>;
}
CodeStylingProvider.propTypes = {
children: PropTypes.node.isRequired,
};
export function useCodeStyling() {
return React.useContext(CodeStylingContext).codeStyling;
}
export function useNoSsrCodeStyling() {
return React.useContext(CodeStylingContext).noSsrCodeStyling;
}
export function useSetCodeStyling() {
return React.useContext(CodeStylingContext).setCodeStyling;
}
| 5,356 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/codeVariant.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { getCookie } from 'docs/src/modules/utils/helpers';
import { CODE_VARIANTS } from 'docs/src/modules/constants';
const CodeVariantContext = React.createContext({
codeVariant: CODE_VARIANTS.TS,
setCodeVariant: () => {},
});
if (process.env.NODE_ENV !== 'production') {
CodeVariantContext.displayName = 'CodeVariant';
}
function useFirstRender() {
const firstRenderRef = React.useRef(true);
React.useEffect(() => {
firstRenderRef.current = false;
}, []);
return firstRenderRef.current;
}
export function CodeVariantProvider(props) {
const { children } = props;
const [codeVariant, setCodeVariant] = React.useState(CODE_VARIANTS.TS);
const navigatedCodeVariant = React.useMemo(() => {
const navigatedCodeVariantMatch =
typeof window !== 'undefined' ? window.location.hash.match(/\.(js|tsx)$/) : null;
if (navigatedCodeVariantMatch === null) {
return undefined;
}
return navigatedCodeVariantMatch[1] === 'tsx' ? CODE_VARIANTS.TS : CODE_VARIANTS.JS;
}, []);
const persistedCodeVariant = React.useMemo(() => {
if (typeof window === 'undefined') {
return undefined;
}
return getCookie('codeVariant');
}, []);
const isFirstRender = useFirstRender();
// We initialize from navigation or cookies. on subsequent renders the store is the truth
const noSsrCodeVariant =
isFirstRender === true
? navigatedCodeVariant || persistedCodeVariant || codeVariant
: codeVariant;
React.useEffect(() => {
if (codeVariant !== noSsrCodeVariant) {
setCodeVariant(noSsrCodeVariant);
}
}, [codeVariant, noSsrCodeVariant]);
React.useEffect(() => {
document.cookie = `codeVariant=${codeVariant};path=/;max-age=31536000`;
}, [codeVariant]);
const contextValue = React.useMemo(() => {
return { codeVariant, noSsrCodeVariant, setCodeVariant };
}, [codeVariant, noSsrCodeVariant]);
return <CodeVariantContext.Provider value={contextValue}>{children}</CodeVariantContext.Provider>;
}
CodeVariantProvider.propTypes = {
children: PropTypes.node.isRequired,
};
export function useCodeVariant() {
return React.useContext(CodeVariantContext).codeVariant;
}
export function useNoSsrCodeVariant() {
return React.useContext(CodeVariantContext).noSsrCodeVariant;
}
export function useSetCodeVariant() {
return React.useContext(CodeVariantContext).setCodeVariant;
}
| 5,357 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/extractTemplates.test.js | import { expect } from 'chai';
import extractTemplates from './extractTemplates';
describe('extractTemplates', () => {
it('get correct templates', () => {
const result = extractTemplates({
'./email/App.tsx': '',
'./team/App.tsx': '',
'./files/App.tsx': '',
});
expect(Object.keys(result)).to.deep.equal(['email', 'team', 'files']);
});
it('extract correct template files', () => {
const result = extractTemplates({
'./email/App.tsx': '',
'./email/components/Layout.tsx': '',
'./email/components/MailContent.tsx': '',
'./email/components/Mails.tsx': '',
'./email/components/Navigation.tsx': '',
'./email/theme.tsx': '',
});
expect(result.email.files).to.deep.equal({
'App.tsx': '',
'components/Layout.tsx': '',
'components/MailContent.tsx': '',
'components/Mails.tsx': '',
'components/Navigation.tsx': '',
'theme.tsx': '',
});
});
it('extract code variant', () => {
const result = extractTemplates({
'./email/App.js': '',
'./email/components/Layout.js': '',
'./email/components/MailContent.js': '',
'./email/components/Mails.js': '',
'./email/components/Navigation.js': '',
'./email/theme.tsx': '',
});
expect(result.email.codeVariant).to.equal('TS');
});
});
| 5,358 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/extractTemplates.ts | export default function extractTemplates(record: Record<string, string>) {
const result: Record<string, { files: Record<string, string>; codeVariant: 'JS' | 'TS' }> = {};
Object.entries(record).forEach((data) => {
const match = /\/(?<name>[^/]+)\/(?<filePath>.*)/.exec(data[0]);
if (match) {
const name = match.groups?.name;
const filePath = match.groups?.filePath;
if (name && filePath) {
if (!result[name]) {
result[name] = { files: {}, codeVariant: 'JS' };
}
if (filePath.match(/\.(ts|tsx)$/)) {
result[name].codeVariant = 'TS';
}
result[name].files[filePath] = data[1];
}
}
});
return result;
}
| 5,359 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/find.js | const fs = require('fs');
const path = require('path');
const pageRegex = /(\.js|\.tsx)$/;
const blackList = ['/.eslintrc', '/_document', '/_app'];
/**
* @typedef {object} NextJSPage
* @property {string} pathname
* @property {NextJSPage[]} [children]
*/
/**
* Returns the Next.js pages available in a nested format.
* The output is in the next.js format.
* Each pathname is a route you can navigate to.
* @param {{ front: true }} [options]
* @param {string} [directory]
* @param {NextJSPage[]} pages
* @returns {NextJSPage[]}
*/
function findPages(
options = {},
directory = path.resolve(__dirname, '../../../pages'),
pages = [],
) {
fs.readdirSync(directory).forEach((item) => {
const itemPath = path.resolve(directory, item);
const pathname = itemPath
.replace(new RegExp(`\\${path.sep}`, 'g'), '/')
.replace(/^.*\/pages/, '')
.replace('.js', '')
.replace('.tsx', '')
.replace(/^\/index$/, '/') // Replace `index` by `/`.
.replace(/\/index$/, '');
if (pathname.indexOf('.eslintrc') !== -1) {
return;
}
if (
options.front &&
pathname.indexOf('/components') === -1 &&
pathname.indexOf('/api-docs') === -1
) {
return;
}
if (fs.statSync(itemPath).isDirectory()) {
const children = [];
pages.push({
pathname,
children,
});
findPages(options, itemPath, children);
return;
}
if (!pageRegex.test(item) || blackList.includes(pathname)) {
return;
}
pages.push({
pathname,
});
});
// sort by pathnames without '-' so that e.g. card comes before card-action
pages.sort((a, b) => {
const pathnameA = a.pathname.replace(/-/g, '');
const pathnameB = b.pathname.replace(/-/g, '');
if (pathnameA < pathnameB) {
return -1;
}
if (pathnameA > pathnameB) {
return 1;
}
return 0;
});
return pages;
}
module.exports = {
findPages,
};
| 5,360 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/findActivePage.test.js | import { expect } from 'chai';
import findActivePage from './findActivePage';
describe('findActivePage', () => {
describe('old structure', () => {
const pages = [
{
pathname: '/getting-started',
icon: 'DescriptionIcon',
children: [{ pathname: '/getting-started/installation' }],
},
{
pathname: '/react-',
icon: 'ToggleOnIcon',
children: [
{
pathname: '/components',
subheader: '/components/inputs',
children: [
{ pathname: '/components/autocomplete' },
{ pathname: '/components/buttons', title: 'Button' },
{ pathname: '/components/button-group' },
{ pathname: '/components/checkboxes', title: 'Checkbox' },
{ pathname: '/components/floating-action-button' },
{ pathname: '/components/radio-buttons', title: 'Radio button' },
{ pathname: '/components/rating' },
{ pathname: '/components/selects', title: 'Select' },
{ pathname: '/components/slider' },
{ pathname: '/components/switches', title: 'Switch' },
{ pathname: '/components/text-fields', title: 'Text field' },
{ pathname: '/components/transfer-list' },
{ pathname: '/components/toggle-button' },
],
},
],
},
];
it('return first level page', () => {
expect(findActivePage(pages, '/getting-started').activePage).to.deep.equal({
pathname: '/getting-started',
icon: 'DescriptionIcon',
children: [{ pathname: '/getting-started/installation' }],
});
});
it('return nested page', () => {
expect(findActivePage(pages, '/getting-started/installation').activePage).to.deep.equal({
pathname: '/getting-started/installation',
});
});
it('return deep nested page', () => {
expect(findActivePage(pages, '/components/radio-buttons').activePage).to.deep.equal({
pathname: '/components/radio-buttons',
title: 'Radio button',
});
});
});
describe('new structure', () => {
const pages = [
{
pathname: '/material-ui/react-',
icon: 'ToggleOnIcon',
children: [
{
pathname: '/material-ui/components',
subheader: '/components/inputs',
children: [
{ pathname: '/material-ui/react-autocomplete' },
{ pathname: '/material-ui/react-buttons', title: 'Button' },
{ pathname: '/material-ui/react-button-group' },
{ pathname: '/material-ui/react-checkboxes', title: 'Checkbox' },
{ pathname: '/material-ui/react-floating-action-button' },
{ pathname: '/material-ui/react-radio-buttons', title: 'Radio button' },
{ pathname: '/material-ui/react-rating' },
{ pathname: '/material-ui/react-selects', title: 'Select' },
{ pathname: '/material-ui/react-slider' },
{ pathname: '/material-ui/react-switches', title: 'Switch' },
{ pathname: '/material-ui/react-text-fields', title: 'Text field' },
{ pathname: '/material-ui/react-transfer-list' },
{ pathname: '/material-ui/react-toggle-button' },
],
},
],
},
];
it('return deep nested page', () => {
expect(findActivePage(pages, '/material-ui/react-radio-buttons').activePage).to.deep.equal({
pathname: '/material-ui/react-radio-buttons',
title: 'Radio button',
});
});
});
});
| 5,361 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/findActivePage.ts | import type { MuiPage } from 'docs/src/MuiPage';
export default function findActivePage(
currentPages: MuiPage[],
currentPathname: string,
): { activePage: MuiPage | null; activePageParents: MuiPage[] } {
const map: Record<string, MuiPage> = {};
const mapParent: Record<string, MuiPage> = {};
const pathname = currentPathname
.replace('/[docsTab]', '')
.replace('components-api', '')
.replace('hooks-api', '');
const traverse = (parent: MuiPage) => {
(parent.children || []).forEach((child) => {
const childPathname = child.pathname
.replace('/[docsTab]', '')
.replace('components-api', '')
.replace('hooks-api', '');
map[childPathname] = child;
const isChildApiPathname =
child.pathname.indexOf('components-api') >= 0 || child.pathname.indexOf('hooks-api') >= 0;
if (!isChildApiPathname && mapParent[childPathname]) {
throw new Error(`Duplicated pathname ${child.pathname} in pages`);
}
if (!isChildApiPathname) {
mapParent[childPathname] = parent;
}
traverse(child);
});
};
traverse({ pathname: '/', children: currentPages });
const activePage = map[pathname] || null;
const activePageParents = [];
let traversePage = activePage;
while (traversePage && traversePage.pathname !== '/') {
const parent = mapParent[traversePage.pathname];
activePageParents.push(parent);
traversePage = parent;
}
return {
activePage,
activePageParents,
};
}
| 5,362 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/getProductInfoFromUrl.test.js | import { expect } from 'chai';
import getProductInfoFromUrl from './getProductInfoFromUrl';
describe('getProductInfoFromUrl', () => {
it('should handle Material UI', () => {
expect(getProductInfoFromUrl('/material-ui/react-button/')).to.deep.equal({
productCategoryId: 'core',
productId: 'material-ui',
});
expect(getProductInfoFromUrl('/zh/material-ui/react-button/')).to.deep.equal({
productCategoryId: 'core',
productId: 'material-ui',
});
});
it('should ignore anchor', () => {
expect(
getProductInfoFromUrl('/material-ui/react-app-bar/#app-bar-with-responsive-menu'),
).to.deep.equal({
productCategoryId: 'core',
productId: 'material-ui',
});
});
it('should handle Base UI', () => {
expect(getProductInfoFromUrl('/base-ui/react-button/')).to.deep.equal({
productCategoryId: 'core',
productId: 'base-ui',
});
});
it('should handle Joy UI', () => {
expect(getProductInfoFromUrl('/joy-ui/react-button/')).to.deep.equal({
productCategoryId: 'core',
productId: 'joy-ui',
});
});
it('should handle MUI System', () => {
expect(getProductInfoFromUrl('/system/')).to.deep.equal({
productCategoryId: 'core',
productId: 'system',
});
});
it('should handle MUI X Data Drid', () => {
expect(getProductInfoFromUrl('/x/react-data-grid/components')).to.deep.equal({
productCategoryId: 'x',
productId: 'x-data-grid',
});
});
it('should handle MUI X Date Pickers', () => {
expect(getProductInfoFromUrl('/x/react-date-pickers/components')).to.deep.equal({
productCategoryId: 'x',
productId: 'x-date-pickers',
});
});
it('should handle MUI X', () => {
expect(getProductInfoFromUrl('/x/migration/migration-data-grid-v5/')).to.deep.equal({
productCategoryId: 'x',
// Not smart enough to know it's about the data grid.
// Now, it's a none goal to be able to handle this. Either change the URL to be
// /x/react-data-grid/migration-v5/
// or add the productId header to the markdown of this page.
productId: 'null',
});
});
it('should return x', () => {
expect(getProductInfoFromUrl('/x/introduction/')).to.deep.equal({
productCategoryId: 'x',
productId: 'null',
});
});
it('should return uncategorized', () => {
expect(getProductInfoFromUrl('/')).to.deep.equal({
productCategoryId: 'null',
productId: 'null',
});
expect(getProductInfoFromUrl('/#foo')).to.deep.equal({
productCategoryId: 'null',
productId: 'null',
});
expect(getProductInfoFromUrl('/versions')).to.deep.equal({
productCategoryId: 'null',
productId: 'null',
});
});
it('should handle MUI Toolpad', () => {
expect(getProductInfoFromUrl('/toolpad/getting-started/first-app/')).to.deep.equal({
productCategoryId: 'null',
productId: 'toolpad',
});
});
});
| 5,363 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/getProductInfoFromUrl.ts | import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
export type MuiProductId =
| 'null'
| 'base-ui'
| 'material-ui'
| 'joy-ui'
| 'system'
| 'docs-infra'
| 'docs'
| 'x-data-grid'
| 'x-date-pickers'
| 'x-charts';
type MuiProductCategoryId = 'null' | 'core' | 'x';
interface MuiProductInfo {
productId: MuiProductId;
productCategoryId: MuiProductCategoryId;
}
// This is a fallback logic to define the productId and productCategoryId of the page.
// Markdown pages can override this value when the URL patterns they follow are a bit strange,
// which should stay the rare exception.
export default function getProductInfoFromUrl(asPath: string): MuiProductInfo {
const asPathWithoutLang = pathnameToLanguage(asPath).canonicalAsServer;
const firstFolder = asPathWithoutLang.replace(/^\/+([^/]+)\/.*/, '$1');
// When serialized undefined/null are the same, so we encode null as 'null' to be
// able to differentiate when the value isn't set vs. set to the right null value.
let productCategoryId = 'null';
let productId = 'null';
if (
firstFolder === 'material-ui' ||
firstFolder === 'joy-ui' ||
firstFolder === 'base-ui' ||
firstFolder === 'system'
) {
productCategoryId = 'core';
productId = firstFolder;
}
if (firstFolder === 'x') {
productCategoryId = 'x';
productId = `x-${asPathWithoutLang.replace('/x/react-', '').replace(/\/.*/, '')}`;
// No match, give up on it.
if (productId === 'x-') {
productId = 'null';
}
}
if (firstFolder === 'toolpad' || firstFolder === 'docs') {
productId = firstFolder;
}
// TODO remove, legacy
if (firstFolder === 'versions' || firstFolder === 'production-error') {
productId = 'docs';
}
if (asPathWithoutLang.startsWith('/experiments/docs/')) {
productId = 'docs-infra';
}
return {
productCategoryId,
productId,
} as MuiProductInfo;
}
| 5,364 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/helpers.test.js | import { expect } from 'chai';
import { pageToTitle } from './helpers';
describe('docs getDependencies helpers', () => {
before(() => {
process.env.SOURCE_CODE_REPO = 'https://github.com/mui/material-ui';
});
after(() => {
delete process.env.SOURCE_CODE_REPO;
});
it('should return correct title', () => {
expect(pageToTitle({ pathname: '/docs/src/pages/components/button/button.md' })).to.equal(
'Button',
);
expect(pageToTitle({ pathname: '/components' })).to.equal('Components');
expect(pageToTitle({ pathname: '/customization/how-to-customize' })).to.equal(
'How to customize',
);
});
it('should remove `react-` prefix', () => {
expect(pageToTitle({ pathname: '/docs/pages/material/react-buttons.js' })).to.equal('Buttons');
});
});
| 5,365 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/helpers.ts | import upperFirst from 'lodash/upperFirst';
import camelCase from 'lodash/camelCase';
import { LANGUAGES } from 'docs/config';
function pascalCase(str: string) {
return upperFirst(camelCase(str));
}
function titleize(hyphenedString: string): string {
return upperFirst(hyphenedString.split('-').join(' '));
}
export interface Page {
pathname: string;
query?: object;
subheader?: string;
title?: string | false;
}
export function pageToTitle(page: Page): string | null {
if (page.title === false) {
return null;
}
if (page.title) {
return page.title;
}
const path = page.subheader || page.pathname;
const name = path.replace(/.*\//, '').replace('react-', '').replace(/\..*/, '');
// TODO remove post migration
if (path.indexOf('/api-docs/') !== -1) {
return pascalCase(name);
}
// TODO support more than React component API (PascalCase)
if (path.indexOf('/api/') !== -1) {
return name.startsWith('use') ? camelCase(name) : pascalCase(name);
}
return titleize(name);
}
export type Translate = (id: string, options?: Partial<{ ignoreWarning: boolean }>) => string;
export function pageToTitleI18n(page: Page, t: Translate): string | null {
const path = page.subheader || page.pathname;
return page.query
? pageToTitle(page)
: t(`pages.${path}`, { ignoreWarning: true }) || pageToTitle(page);
}
/**
* Get the value of a cookie
* Source: https://vanillajstoolkit.com/helpers/getcookie/
* @param name - The name of the cookie
* @return The cookie value
*/
export function getCookie(name: string): string | undefined {
if (typeof document === 'undefined') {
throw new Error(
'getCookie() is not supported on the server. Fallback to a different value when rendering on the server.',
);
}
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) {
return parts[1].split(';').shift();
}
return undefined;
}
/**
* as is a reference to Next.js's as, the path in the URL
* pathname is a reference to Next.js's pathname, the name of page in the filesystem
* https://nextjs.org/docs/api-reference/next/router
*/
export function pathnameToLanguage(pathname: string): {
userLanguage: string;
canonicalAs: string;
canonicalAsServer: string;
canonicalPathname: string;
} {
let userLanguage;
const userLanguageCandidate = pathname.substring(1, 3);
if (
[...LANGUAGES, 'zh'].indexOf(userLanguageCandidate) !== -1 &&
pathname.indexOf(`/${userLanguageCandidate}/`) === 0
) {
userLanguage = userLanguageCandidate;
} else {
userLanguage = 'en';
}
const canonicalAs = userLanguage === 'en' ? pathname : pathname.substring(3);
// Remove hash as it's never sent to the server
// https://github.com/vercel/next.js/issues/25202
const canonicalAsServer = canonicalAs.replace(/#(.*)$/, '');
let canonicalPathname = canonicalAsServer.replace(/^\/api/, '/api-docs');
// Remove trailing slash as Next.js doesn't expect it here
// https://nextjs.org/docs/pages/api-reference/functions/use-router#router-object
if (canonicalPathname !== '/') {
canonicalPathname = canonicalPathname.replace(/\/$/, '');
}
return {
userLanguage,
canonicalAs,
canonicalAsServer,
canonicalPathname,
};
}
| 5,366 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/i18n.js | import * as React from 'react';
import PropTypes from 'prop-types';
function mapTranslations(req) {
const translations = {};
req.keys().forEach((filename) => {
const match = filename.match(/-([a-z]{2}).json$/);
if (match) {
translations[match[1]] = req(filename);
} else {
translations.en = req(filename);
}
});
return translations;
}
const req = require.context('docs/translations', false, /translations.*\.json$/);
const translations = mapTranslations(req);
function getPath(obj, path) {
if (!path || typeof path !== 'string') {
return null;
}
return path.split('.').reduce((acc, item) => (acc && acc[item] ? acc[item] : null), obj);
}
const UserLanguageContext = React.createContext({ userLanguage: '', setUserLanguage: () => {} });
if (process.env.NODE_ENV !== 'production') {
UserLanguageContext.displayName = 'UserLanguage';
}
export function UserLanguageProvider(props) {
const { children, defaultUserLanguage } = props;
const [userLanguage, setUserLanguage] = React.useState(defaultUserLanguage);
const contextValue = React.useMemo(() => {
return { userLanguage, setUserLanguage };
}, [userLanguage]);
return (
<UserLanguageContext.Provider value={contextValue}>{children}</UserLanguageContext.Provider>
);
}
UserLanguageProvider.propTypes = {
children: PropTypes.node.isRequired,
defaultUserLanguage: PropTypes.string,
};
export function useUserLanguage() {
return React.useContext(UserLanguageContext).userLanguage;
}
export function useSetUserLanguage() {
return React.useContext(UserLanguageContext).setUserLanguage;
}
const warnedOnce = {};
export function useTranslate() {
const userLanguage = useUserLanguage();
return React.useMemo(
() =>
function translate(key, options = {}) {
const { ignoreWarning = false } = options;
const wordings = translations[userLanguage];
if (!wordings) {
console.error(`Missing language: ${userLanguage}.`);
return '…';
}
const translation = getPath(wordings, key);
if (!translation) {
const fullKey = `${userLanguage}:${key}`;
// No warnings in CI env
if (!ignoreWarning && !warnedOnce[fullKey] && typeof window !== 'undefined') {
console.error(`Missing translation for ${fullKey}`);
warnedOnce[fullKey] = true;
}
return getPath(translations.en, key);
}
return translation;
},
[userLanguage],
);
}
| 5,367 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/loadScript.js | export default function loadScript(src, position) {
const script = document.createElement('script');
script.setAttribute('async', '');
script.src = src;
position.appendChild(script);
return script;
}
| 5,368 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/mapApiPageTranslations.js | import { createRender } from '@mui/markdown';
import { LANGUAGES_IGNORE_PAGES } from '../../../config';
const notEnglishJsonRegExp = /-([a-z]{2})\.json$/;
export default function mapApiPageTranslations(req) {
const headingHashes = {};
const translations = {};
// Process the English markdown before the other locales.
// English ToC anchor links are used in all languages
let filenames = [];
req.keys().forEach((filename) => {
if (filename.match(notEnglishJsonRegExp)) {
filenames.push(filename);
} else {
filenames = [filename].concat(filenames);
}
});
filenames.forEach((filename) => {
const matchNotEnglishMarkdown = filename.match(notEnglishJsonRegExp);
const userLanguage = matchNotEnglishMarkdown !== null ? matchNotEnglishMarkdown[1] : 'en';
const translation = req(filename) || null;
if (translation !== null && translation.componentDescription) {
const componentDescriptionToc = [];
const render = createRender({
headingHashes,
toc: componentDescriptionToc,
userLanguage,
location: filenames,
options: {
ignoreLanguagePages: LANGUAGES_IGNORE_PAGES,
env: {
SOURCE_CODE_REPO: '',
},
},
});
translation.componentDescription = render(translation.componentDescription);
translation.componentDescriptionToc = componentDescriptionToc;
}
translations[userLanguage] = translation;
});
return translations;
}
| 5,369 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/replaceMarkdownLinks.test.js | import { expect } from 'chai';
import {
replaceMaterialLinks,
replaceAPILinks,
replaceComponentLinks,
} from './replaceMarkdownLinks';
describe('replaceMarkdownLinks', () => {
it('replace material related links', () => {
expect(
replaceMaterialLinks(`
[reading this guide on minimizing bundle size](/guides/minimizing-bundle-size/)
[default props](/customization/theme-components/#default-props)
[Get started](/getting-started/usage/)
[Tree view](/discover-more/related-projects/)
`),
).to.equal(`
[reading this guide on minimizing bundle size](/material-ui/guides/minimizing-bundle-size/)
[default props](/material-ui/customization/theme-components/#default-props)
[Get started](/material-ui/getting-started/usage/)
[Tree view](/material-ui/discover-more/related-projects/)
`);
});
it('should not change if links have been updated', () => {
expect(
replaceMaterialLinks(`
[reading this guide on minimizing bundle size](/material-ui/guides/minimizing-bundle-size/)
[default props](/material-ui/customization/theme-components/#default-props)
[Get started](/material-ui/getting-started/usage/)
[Tree view](/material-ui/discover-more/related-projects/)
`),
).to.equal(`
[reading this guide on minimizing bundle size](/material-ui/guides/minimizing-bundle-size/)
[default props](/material-ui/customization/theme-components/#default-props)
[Get started](/material-ui/getting-started/usage/)
[Tree view](/material-ui/discover-more/related-projects/)
`);
});
it('replace correct component links', () => {
expect(
replaceComponentLinks(`
[ButtonGroup](/components/button-group/)
[Buttons](/components/buttons/)
[text](/components/checkboxes/#main-content)
[text](/components/radio-buttons#main-content)
[text](/components/selects/#main-content)
[text](/components/switches/#main-content)
[text](/components/text-fields/#main-content)
[text](/components/avatars/#main-content)
[text](/components/badges/#main-content)
[text](/components/chips/#main-content)
[text](/components/dividers/#main-content)
[text](/components/icons/#main-content)
[text](/components/material-icons/#main-content)
[text](/components/lists/#main-content)
[text](/components/tables/#main-content)
[text](/components/tooltips/#main-content)
[text](/components/dialogs/#main-content)
[text](/components/snackbars/#main-content)
[text](/components/cards/#main-content)
[text](/components/breadcrumbs/#main-content)
[text](/components/drawers/#main-content)
[text](/components/links/#main-content)
[text](/components/menus/#main-content)
[text](/components/steppers/#main-content)
[text](/components/tabs/#main-content)
[text](/components/transitions/#main-content)
[text](/components/pickers/#main-content)
[text](/components/trap-focus/#main-content)
[text](/components/css-baseline/#main-content)
[text](/components/no-ssr/#main-content)
[text](/components/image-list/#main-content)
[text](/components/progress/#main-content)
-
[Tree view](/components/tree-view/)
[Demo](/components/data-grid/demo/)
`),
).to.equal(`
[ButtonGroup](/material-ui/react-button-group/)
[Buttons](/material-ui/react-button/)
[text](/material-ui/react-checkbox/#main-content)
[text](/material-ui/react-radio-button#main-content)
[text](/material-ui/react-select/#main-content)
[text](/material-ui/react-switch/#main-content)
[text](/material-ui/react-text-field/#main-content)
[text](/material-ui/react-avatar/#main-content)
[text](/material-ui/react-badge/#main-content)
[text](/material-ui/react-chip/#main-content)
[text](/material-ui/react-divider/#main-content)
[text](/material-ui/icons/#main-content)
[text](/material-ui/material-icons/#main-content)
[text](/material-ui/react-list/#main-content)
[text](/material-ui/react-table/#main-content)
[text](/material-ui/react-tooltip/#main-content)
[text](/material-ui/react-dialog/#main-content)
[text](/material-ui/react-snackbar/#main-content)
[text](/material-ui/react-card/#main-content)
[text](/material-ui/react-breadcrumbs/#main-content)
[text](/material-ui/react-drawer/#main-content)
[text](/material-ui/react-link/#main-content)
[text](/material-ui/react-menu/#main-content)
[text](/material-ui/react-stepper/#main-content)
[text](/material-ui/react-tabs/#main-content)
[text](/material-ui/transitions/#main-content)
[text](/material-ui/pickers/#main-content)
[text](/material-ui/react-trap-focus/#main-content)
[text](/material-ui/react-css-baseline/#main-content)
[text](/material-ui/react-no-ssr/#main-content)
[text](/material-ui/react-image-list/#main-content)
[text](/material-ui/react-progress/#main-content)
-
[Tree view](/material-ui/react-tree-view/)
[Demo](/x/react-data-grid/demo/)
`);
});
it('should do nothing if the components have updated', () => {
expect(
replaceComponentLinks(`
[ButtonGroup](/material-ui/react-button-group/)
[Buttons](/material-ui/react-button/)
[text](/material-ui/react-checkbox/#main-content)
[text](/material-ui/react-radio-button#main-content)
[text](/material-ui/react-select/#main-content)
[text](/material-ui/react-switch/#main-content)
[text](/material-ui/react-text-field/#main-content)
[text](/material-ui/react-avatar/#main-content)
[text](/material-ui/react-badge/#main-content)
[text](/material-ui/react-chip/#main-content)
[text](/material-ui/react-divider/#main-content)
[text](/material-ui/icons/#main-content)
[text](/material-ui/material-icons/#main-content)
[text](/material-ui/react-list/#main-content)
[text](/material-ui/react-table/#main-content)
[text](/material-ui/react-tooltip/#main-content)
[text](/material-ui/react-dialog/#main-content)
[text](/material-ui/react-snackbar/#main-content)
[text](/material-ui/react-card/#main-content)
[text](/material-ui/react-breadcrumbs/#main-content)
[text](/material-ui/react-drawer/#main-content)
[text](/material-ui/react-link/#main-content)
[text](/material-ui/react-menu/#main-content)
[text](/material-ui/react-stepper/#main-content)
[text](/material-ui/react-tabs/#main-content)
[text](/material-ui/transitions/#main-content)
[text](/material-ui/pickers/#main-content)
-
[Tree view](/material-ui/react-tree-view/)
[Demo](/x/react-data-grid/demo/)
`),
).to.equal(`
[ButtonGroup](/material-ui/react-button-group/)
[Buttons](/material-ui/react-button/)
[text](/material-ui/react-checkbox/#main-content)
[text](/material-ui/react-radio-button#main-content)
[text](/material-ui/react-select/#main-content)
[text](/material-ui/react-switch/#main-content)
[text](/material-ui/react-text-field/#main-content)
[text](/material-ui/react-avatar/#main-content)
[text](/material-ui/react-badge/#main-content)
[text](/material-ui/react-chip/#main-content)
[text](/material-ui/react-divider/#main-content)
[text](/material-ui/icons/#main-content)
[text](/material-ui/material-icons/#main-content)
[text](/material-ui/react-list/#main-content)
[text](/material-ui/react-table/#main-content)
[text](/material-ui/react-tooltip/#main-content)
[text](/material-ui/react-dialog/#main-content)
[text](/material-ui/react-snackbar/#main-content)
[text](/material-ui/react-card/#main-content)
[text](/material-ui/react-breadcrumbs/#main-content)
[text](/material-ui/react-drawer/#main-content)
[text](/material-ui/react-link/#main-content)
[text](/material-ui/react-menu/#main-content)
[text](/material-ui/react-stepper/#main-content)
[text](/material-ui/react-tabs/#main-content)
[text](/material-ui/transitions/#main-content)
[text](/material-ui/pickers/#main-content)
-
[Tree view](/material-ui/react-tree-view/)
[Demo](/x/react-data-grid/demo/)
`);
});
it('replace correct API links', () => {
expect(
replaceAPILinks(`
[Button](/api/button)
[No Ssr](/api/no-ssr)
[Portal](/api/portal)
[Textarea Autosize](/api/textarea-autosize)
[ButtonBase](/api/button-base)
[TabPanel](/api/tab-panel)
[TabsList](/api/tab-panel)
[ButtonUnstyled](/api/button-unstyled)
[TabPanelUnstyled](/api/tab-panel-unstyled)
[TabsListUnstyled](/api/tabs-list-unstyled)
[FocusTrap](/api/focus-trap)
[ClickAwayListener](/api/click-away-listener)
[IconButton](/api/icon-button)
[LoadingButton](/api/loading-button)
[DataGrid](/api/data-grid/data-grid)
[DataGridPro](/api/data-grid/data-grid-pro)
[System](/system/basics)
`),
).to.equal(`
[Button](/material-ui/api/button)
[No Ssr](/base-ui/api/no-ssr)
[Portal](/base-ui/api/portal)
[Textarea Autosize](/base-ui/api/textarea-autosize)
[ButtonBase](/material-ui/api/button-base)
[TabPanel](/material-ui/api/tab-panel)
[TabsList](/material-ui/api/tab-panel)
[ButtonUnstyled](/base-ui/api/button)
[TabPanelUnstyled](/base-ui/api/tab-panel)
[TabsListUnstyled](/base-ui/api/tabs-list)
[FocusTrap](/base-ui/api/focus-trap)
[ClickAwayListener](/base-ui/api/click-away-listener)
[IconButton](/material-ui/api/icon-button)
[LoadingButton](/material-ui/api/loading-button)
[DataGrid](/x/api/data-grid/data-grid)
[DataGridPro](/x/api/data-grid/data-grid-pro)
[System](/system/basics)
`);
});
it('should do nothing if the APIs have updated', () => {
expect(
replaceAPILinks(`
[Button](/material-ui/api/button)
[ButtonBase](/material-ui/api/button-base)
[ButtonUnstyled](/base-ui/api/button)
[IconButton](/material-ui/api/icon-button)
[LoadingButton](/material-ui/api/loading-button)
[DataGrid](/x/api/data-grid/data-grid)
[DataGridPro](/x/api/data-grid/data-grid-pro)
[System](/system/basics)
`),
).to.equal(`
[Button](/material-ui/api/button)
[ButtonBase](/material-ui/api/button-base)
[ButtonUnstyled](/base-ui/api/button)
[IconButton](/material-ui/api/icon-button)
[LoadingButton](/material-ui/api/loading-button)
[DataGrid](/x/api/data-grid/data-grid)
[DataGridPro](/x/api/data-grid/data-grid-pro)
[System](/system/basics)
`);
});
});
| 5,370 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/replaceMarkdownLinks.ts | export const replaceMaterialLinks = (markdown: string) => {
return markdown.replace(
/\(\/(guides|customization|getting-started|discover-more)\/([^)]*)\)/gm,
'(/material-ui/$1/$2)',
);
};
export const replaceComponentLinks = (markdown: string) => {
return markdown
.replace(/\(\/components\/data-grid([^)]*)\)/gm, '(/x/react-data-grid$1)')
.replace(
/\(\/components\/((icons|material-icons|transitions|pickers|about-the-lab)\/?[^)]*)\)/gm,
'(/material-ui/$1)',
)
.replace(/\(\/components\/(?!tabs|breadcrumbs)([^)]*)\)/gm, '(/material-ui/react-$1)')
.replace(/\(\/material-ui\/(react-[-a-z]+)(x|ch)es(\/|#)([^)]*)\)/gm, '(/material-ui/$1$2$3$4)')
.replace(/\(\/material-ui\/(react-[-a-z]+)(x|ch)es"/gm, '(/material-ui/$1$2)')
.replace(
/\(\/material-ui\/(?!react-tabs|react-breadcrumbs)(react-[-a-z]+)s(\/|#)([^)]*)\)/gm,
'(/material-ui/$1$2$3)',
)
.replace(
/\(\/material-ui\/(?!react-tabs|react-breadcrumbs)(react-[-a-z]+)s"/gm,
'(/material-ui/$1)',
)
.replace(/react-trap-focu/gm, 'react-trap-focus')
.replace(/react-trap-focuss/gm, 'react-trap-focus')
.replace(/react-progres/gm, 'react-progress')
.replace(/react-progresss/gm, 'react-progress')
.replace(/\(\/components\/(tabs|breadcrumbs)([^)]*)\)/gm, '(/material-ui/react-$1$2)');
};
export const replaceAPILinks = (markdown: string) => {
return markdown
.replace(/\(\/api\/data-grid([^)]*)\)/gm, '(/x/api/data-grid$1)')
.replace(/\(\/api\/([^"/]+)(-unstyled)([^)]*)\)/gm, '(/base-ui/api/$1$3)')
.replace(
/\(\/api\/(focus-trap|click-away-listener|no-ssr|portal|textarea-autosize)([^)]*)\)/gm,
'(/base-ui/api/$1$2)',
)
.replace(
/\(\/api\/(loading-button|tab-list|tab-panel|date-picker|date-time-picker|time-picker|calendar-picker|calendar-picker-skeleton|desktop-picker|mobile-date-picker|month-picker|pickers-day|static-date-picker|year-picker|masonry|timeline|timeline-connector|timeline-content|timeline-dot|timeline-item|timeline-opposite-content|timeline-separator|unstable-trap-focus|tree-item|tree-view)([^)]*)\)/gm,
'(/material-ui/api/$1$2)',
)
.replace(/\(\/api\/([^)]*)\)/gm, '(/material-ui/api/$1)');
};
| 5,371 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/stylingSolutionMapping.js | import { CODE_STYLING } from 'docs/src/modules/constants';
const stylingSolutionMapping = {
[CODE_STYLING.TAILWIND]: 'tailwind',
[CODE_STYLING.CSS]: 'css',
[CODE_STYLING.SYSTEM]: 'system',
};
export default stylingSolutionMapping;
| 5,372 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/useClipboardCopy.ts | import * as React from 'react';
import clipboardCopy from 'clipboard-copy';
export default function useClipboardCopy() {
const [isCopied, setIsCopied] = React.useState(false);
const timeout = React.useRef<ReturnType<typeof setTimeout> | undefined>();
const mounted = React.useRef(false);
React.useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const copy = async (text: string) => {
try {
setIsCopied(true);
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
if (mounted) {
setIsCopied(false);
}
}, 1200);
await clipboardCopy(text);
} catch (error) {
// ignore error
}
};
return { copy, isCopied };
}
| 5,373 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/useLazyCSS.js | import * as React from 'react';
import { loadCSS } from 'fg-loadcss/src/loadCSS';
/**
* Convenience wrapper around fgLoadCSS for hooks usage
* @param {string} href
* @param {string} before - CSS selector
* @returns {() => void} cleanup function
*/
export default function useLazyCSS(href, before) {
React.useEffect(() => {
const link = loadCSS(href, document.querySelector(before));
return () => {
link.parentElement.removeChild(link);
};
}, [href, before]);
}
| 5,374 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/utils/useQueryParameterState.ts | import * as React from 'react';
import { useRouter } from 'next/router';
import { debounce } from '@mui/material/utils';
const QUERY_UPDATE_WAIT_MS = 220;
/**
* Similar to `React.useState`, but it syncs back the current state to a query
* parameter in the url, therefore it only supports strings. Wrap the result with
* parse/stringify logic if more complex values are needed.
*
* REMARK: this doesn't listen for router changes (yet) to update back the state.
*/
export default function useQueryParameterState(
name: string,
initialValue = '',
): [string, (newValue: string) => void] {
const initialValueRef = React.useRef(initialValue);
const router = useRouter();
const queryParamValue = router.query[name];
const urlValue = Array.isArray(queryParamValue) ? queryParamValue[0] : queryParamValue;
const [state, setState] = React.useState(urlValue || initialValue);
const setUrlValue = React.useMemo(
() =>
debounce((newValue = '') => {
const query = new URLSearchParams(window.location.search);
if (newValue && newValue !== initialValueRef.current) {
query.set(name, newValue);
} else {
query.delete(name);
}
const newSearch = query.toString();
if (window.location.search !== newSearch) {
router.replace(
{
pathname: router.pathname,
// TODO: this resets the scroll position, even though we have scroll: false
// hash: window.location.hash,
search: newSearch,
},
undefined,
{
scroll: false,
shallow: true,
},
);
}
}, QUERY_UPDATE_WAIT_MS),
[name, router],
);
React.useEffect(
() => () => {
setUrlValue.clear();
},
[setUrlValue],
);
const setUserState = React.useCallback(
(newValue: string) => {
setUrlValue(newValue);
setState(newValue);
},
[setUrlValue],
);
// Make sure to initialize the state when route params are only available client-side
const isInitialized = React.useRef(false);
React.useEffect(() => {
if (isInitialized.current) {
return;
}
isInitialized.current = true;
const query = new URLSearchParams(window.location.search);
const value = query.get(name);
setState(value || initialValue);
}, [name, initialValue]);
return [state, setUserState];
}
| 5,375 |
0 | petrpan-code/mui/material-ui/docs/src/pages/company | petrpan-code/mui/material-ui/docs/src/pages/company/contact/contact.md | # Contact us
<p class="description">We're all ears.</p>
Please choose a topic below related to your inquiry:
- [Help & Support](/material-ui/getting-started/support/)
- Email enquiries: [[email protected]](mailto:[email protected])
- Our address:<br /><br />
**Material-UI SAS**<br />
128 Rue La Boétie<br />
75008 Paris<br />
France
| 5,376 |
0 | petrpan-code/mui/material-ui/docs/src/pages/components | petrpan-code/mui/material-ui/docs/src/pages/components/tabs/UnstyledTabsCustomized.preview | <TabsUnstyled defaultValue={0}>
<TabsList>
<Tab>One</Tab>
<Tab>Two</Tab>
<Tab>Three</Tab>
</TabsList>
<TabPanel value={0}>First content</TabPanel>
<TabPanel value={1}>Second content</TabPanel>
<TabPanel value={2}>Third content</TabPanel>
</TabsUnstyled> | 5,377 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/ForgotPassword.js | import * as React from 'react';
import { Field, Form, FormSpy } from 'react-final-form';
import Box from '@mui/material/Box';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import AppForm from './modules/views/AppForm';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import withRoot from './modules/withRoot';
function ForgotPassword() {
const [sent, setSent] = React.useState(false);
const validate = (values) => {
const errors = required(['email'], values);
if (!errors.email) {
const emailError = email(values.email);
if (emailError) {
errors.email = emailError;
}
}
return errors;
};
const handleSubmit = () => {
setSent(true);
};
return (
<React.Fragment>
<AppAppBar />
<AppForm>
<React.Fragment>
<Typography variant="h3" gutterBottom marked="center" align="center">
Forgot your password?
</Typography>
<Typography variant="body2" align="center">
{"Enter your email address below and we'll " +
'send you a link to reset your password.'}
</Typography>
</React.Fragment>
<Form
onSubmit={handleSubmit}
subscription={{ submitting: true }}
validate={validate}
>
{({ handleSubmit: handleSubmit2, submitting }) => (
<Box component="form" onSubmit={handleSubmit2} noValidate sx={{ mt: 6 }}>
<Field
autoFocus
autoComplete="email"
component={RFTextField}
disabled={submitting || sent}
fullWidth
label="Email"
margin="normal"
name="email"
required
size="large"
/>
<FormSpy subscription={{ submitError: true }}>
{({ submitError }) =>
submitError ? (
<FormFeedback error sx={{ mt: 2 }}>
{submitError}
</FormFeedback>
) : null
}
</FormSpy>
<FormButton
sx={{ mt: 3, mb: 2 }}
disabled={submitting || sent}
size="large"
color="secondary"
fullWidth
>
{submitting || sent ? 'In progress…' : 'Send reset link'}
</FormButton>
</Box>
)}
</Form>
</AppForm>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(ForgotPassword);
| 5,378 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/ForgotPassword.tsx | import * as React from 'react';
import { Field, Form, FormSpy } from 'react-final-form';
import Box from '@mui/material/Box';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import AppForm from './modules/views/AppForm';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import withRoot from './modules/withRoot';
function ForgotPassword() {
const [sent, setSent] = React.useState(false);
const validate = (values: { [index: string]: string }) => {
const errors = required(['email'], values);
if (!errors.email) {
const emailError = email(values.email);
if (emailError) {
errors.email = emailError;
}
}
return errors;
};
const handleSubmit = () => {
setSent(true);
};
return (
<React.Fragment>
<AppAppBar />
<AppForm>
<React.Fragment>
<Typography variant="h3" gutterBottom marked="center" align="center">
Forgot your password?
</Typography>
<Typography variant="body2" align="center">
{"Enter your email address below and we'll " +
'send you a link to reset your password.'}
</Typography>
</React.Fragment>
<Form
onSubmit={handleSubmit}
subscription={{ submitting: true }}
validate={validate}
>
{({ handleSubmit: handleSubmit2, submitting }) => (
<Box component="form" onSubmit={handleSubmit2} noValidate sx={{ mt: 6 }}>
<Field
autoFocus
autoComplete="email"
component={RFTextField}
disabled={submitting || sent}
fullWidth
label="Email"
margin="normal"
name="email"
required
size="large"
/>
<FormSpy subscription={{ submitError: true }}>
{({ submitError }) =>
submitError ? (
<FormFeedback error sx={{ mt: 2 }}>
{submitError}
</FormFeedback>
) : null
}
</FormSpy>
<FormButton
sx={{ mt: 3, mb: 2 }}
disabled={submitting || sent}
size="large"
color="secondary"
fullWidth
>
{submitting || sent ? 'In progress…' : 'Send reset link'}
</FormButton>
</Box>
)}
</Form>
</AppForm>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(ForgotPassword);
| 5,379 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/Home.js | import * as React from 'react';
import ProductCategories from './modules/views/ProductCategories';
import ProductSmokingHero from './modules/views/ProductSmokingHero';
import AppFooter from './modules/views/AppFooter';
import ProductHero from './modules/views/ProductHero';
import ProductValues from './modules/views/ProductValues';
import ProductHowItWorks from './modules/views/ProductHowItWorks';
import ProductCTA from './modules/views/ProductCTA';
import AppAppBar from './modules/views/AppAppBar';
import withRoot from './modules/withRoot';
function Index() {
return (
<React.Fragment>
<AppAppBar />
<ProductHero />
<ProductValues />
<ProductCategories />
<ProductHowItWorks />
<ProductCTA />
<ProductSmokingHero />
<AppFooter />
</React.Fragment>
);
}
export default withRoot(Index);
| 5,380 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/Home.tsx | import * as React from 'react';
import ProductCategories from './modules/views/ProductCategories';
import ProductSmokingHero from './modules/views/ProductSmokingHero';
import AppFooter from './modules/views/AppFooter';
import ProductHero from './modules/views/ProductHero';
import ProductValues from './modules/views/ProductValues';
import ProductHowItWorks from './modules/views/ProductHowItWorks';
import ProductCTA from './modules/views/ProductCTA';
import AppAppBar from './modules/views/AppAppBar';
import withRoot from './modules/withRoot';
function Index() {
return (
<React.Fragment>
<AppAppBar />
<ProductHero />
<ProductValues />
<ProductCategories />
<ProductHowItWorks />
<ProductCTA />
<ProductSmokingHero />
<AppFooter />
</React.Fragment>
);
}
export default withRoot(Index);
| 5,381 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/Privacy.js | import * as React from 'react';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';
import Markdown from './modules/components/Markdown';
import Typography from './modules/components/Typography';
import AppAppBar from './modules/views/AppAppBar';
import AppFooter from './modules/views/AppFooter';
import withRoot from './modules/withRoot';
import privacy from './modules/views/privacy.md';
function Privacy() {
return (
<React.Fragment>
<AppAppBar />
<Container>
<Box sx={{ mt: 7, mb: 12 }}>
<Typography variant="h3" gutterBottom marked="center" align="center">
Privacy
</Typography>
<Markdown>{privacy}</Markdown>
</Box>
</Container>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(Privacy);
| 5,382 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/Privacy.tsx | import * as React from 'react';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';
import Markdown from './modules/components/Markdown';
import Typography from './modules/components/Typography';
import AppAppBar from './modules/views/AppAppBar';
import AppFooter from './modules/views/AppFooter';
import withRoot from './modules/withRoot';
import privacy from './modules/views/privacy.md';
function Privacy() {
return (
<React.Fragment>
<AppAppBar />
<Container>
<Box sx={{ mt: 7, mb: 12 }}>
<Typography variant="h3" gutterBottom marked="center" align="center">
Privacy
</Typography>
<Markdown>{privacy}</Markdown>
</Box>
</Container>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(Privacy);
| 5,383 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/SignIn.js | import * as React from 'react';
import { Field, Form, FormSpy } from 'react-final-form';
import Box from '@mui/material/Box';
import Link from '@mui/material/Link';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import AppForm from './modules/views/AppForm';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import withRoot from './modules/withRoot';
function SignIn() {
const [sent, setSent] = React.useState(false);
const validate = (values) => {
const errors = required(['email', 'password'], values);
if (!errors.email) {
const emailError = email(values.email);
if (emailError) {
errors.email = emailError;
}
}
return errors;
};
const handleSubmit = () => {
setSent(true);
};
return (
<React.Fragment>
<AppAppBar />
<AppForm>
<React.Fragment>
<Typography variant="h3" gutterBottom marked="center" align="center">
Sign In
</Typography>
<Typography variant="body2" align="center">
{'Not a member yet? '}
<Link
href="/premium-themes/onepirate/sign-up/"
align="center"
underline="always"
>
Sign Up here
</Link>
</Typography>
</React.Fragment>
<Form
onSubmit={handleSubmit}
subscription={{ submitting: true }}
validate={validate}
>
{({ handleSubmit: handleSubmit2, submitting }) => (
<Box component="form" onSubmit={handleSubmit2} noValidate sx={{ mt: 6 }}>
<Field
autoComplete="email"
autoFocus
component={RFTextField}
disabled={submitting || sent}
fullWidth
label="Email"
margin="normal"
name="email"
required
size="large"
/>
<Field
fullWidth
size="large"
component={RFTextField}
disabled={submitting || sent}
required
name="password"
autoComplete="current-password"
label="Password"
type="password"
margin="normal"
/>
<FormSpy subscription={{ submitError: true }}>
{({ submitError }) =>
submitError ? (
<FormFeedback error sx={{ mt: 2 }}>
{submitError}
</FormFeedback>
) : null
}
</FormSpy>
<FormButton
sx={{ mt: 3, mb: 2 }}
disabled={submitting || sent}
size="large"
color="secondary"
fullWidth
>
{submitting || sent ? 'In progress…' : 'Sign In'}
</FormButton>
</Box>
)}
</Form>
<Typography align="center">
<Link underline="always" href="/premium-themes/onepirate/forgot-password/">
Forgot password?
</Link>
</Typography>
</AppForm>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(SignIn);
| 5,384 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/SignIn.tsx | import * as React from 'react';
import { Field, Form, FormSpy } from 'react-final-form';
import Box from '@mui/material/Box';
import Link from '@mui/material/Link';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import AppForm from './modules/views/AppForm';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import withRoot from './modules/withRoot';
function SignIn() {
const [sent, setSent] = React.useState(false);
const validate = (values: { [index: string]: string }) => {
const errors = required(['email', 'password'], values);
if (!errors.email) {
const emailError = email(values.email);
if (emailError) {
errors.email = emailError;
}
}
return errors;
};
const handleSubmit = () => {
setSent(true);
};
return (
<React.Fragment>
<AppAppBar />
<AppForm>
<React.Fragment>
<Typography variant="h3" gutterBottom marked="center" align="center">
Sign In
</Typography>
<Typography variant="body2" align="center">
{'Not a member yet? '}
<Link
href="/premium-themes/onepirate/sign-up/"
align="center"
underline="always"
>
Sign Up here
</Link>
</Typography>
</React.Fragment>
<Form
onSubmit={handleSubmit}
subscription={{ submitting: true }}
validate={validate}
>
{({ handleSubmit: handleSubmit2, submitting }) => (
<Box component="form" onSubmit={handleSubmit2} noValidate sx={{ mt: 6 }}>
<Field
autoComplete="email"
autoFocus
component={RFTextField}
disabled={submitting || sent}
fullWidth
label="Email"
margin="normal"
name="email"
required
size="large"
/>
<Field
fullWidth
size="large"
component={RFTextField}
disabled={submitting || sent}
required
name="password"
autoComplete="current-password"
label="Password"
type="password"
margin="normal"
/>
<FormSpy subscription={{ submitError: true }}>
{({ submitError }) =>
submitError ? (
<FormFeedback error sx={{ mt: 2 }}>
{submitError}
</FormFeedback>
) : null
}
</FormSpy>
<FormButton
sx={{ mt: 3, mb: 2 }}
disabled={submitting || sent}
size="large"
color="secondary"
fullWidth
>
{submitting || sent ? 'In progress…' : 'Sign In'}
</FormButton>
</Box>
)}
</Form>
<Typography align="center">
<Link underline="always" href="/premium-themes/onepirate/forgot-password/">
Forgot password?
</Link>
</Typography>
</AppForm>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(SignIn);
| 5,385 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/SignUp.js | import * as React from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Link from '@mui/material/Link';
import { Field, Form, FormSpy } from 'react-final-form';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import AppForm from './modules/views/AppForm';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import withRoot from './modules/withRoot';
function SignUp() {
const [sent, setSent] = React.useState(false);
const validate = (values) => {
const errors = required(['firstName', 'lastName', 'email', 'password'], values);
if (!errors.email) {
const emailError = email(values.email);
if (emailError) {
errors.email = emailError;
}
}
return errors;
};
const handleSubmit = () => {
setSent(true);
};
return (
<React.Fragment>
<AppAppBar />
<AppForm>
<React.Fragment>
<Typography variant="h3" gutterBottom marked="center" align="center">
Sign Up
</Typography>
<Typography variant="body2" align="center">
<Link href="/premium-themes/onepirate/sign-in/" underline="always">
Already have an account?
</Link>
</Typography>
</React.Fragment>
<Form
onSubmit={handleSubmit}
subscription={{ submitting: true }}
validate={validate}
>
{({ handleSubmit: handleSubmit2, submitting }) => (
<Box component="form" onSubmit={handleSubmit2} noValidate sx={{ mt: 6 }}>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Field
autoFocus
component={RFTextField}
disabled={submitting || sent}
autoComplete="given-name"
fullWidth
label="First name"
name="firstName"
required
/>
</Grid>
<Grid item xs={12} sm={6}>
<Field
component={RFTextField}
disabled={submitting || sent}
autoComplete="family-name"
fullWidth
label="Last name"
name="lastName"
required
/>
</Grid>
</Grid>
<Field
autoComplete="email"
component={RFTextField}
disabled={submitting || sent}
fullWidth
label="Email"
margin="normal"
name="email"
required
/>
<Field
fullWidth
component={RFTextField}
disabled={submitting || sent}
required
name="password"
autoComplete="new-password"
label="Password"
type="password"
margin="normal"
/>
<FormSpy subscription={{ submitError: true }}>
{({ submitError }) =>
submitError ? (
<FormFeedback error sx={{ mt: 2 }}>
{submitError}
</FormFeedback>
) : null
}
</FormSpy>
<FormButton
sx={{ mt: 3, mb: 2 }}
disabled={submitting || sent}
color="secondary"
fullWidth
>
{submitting || sent ? 'In progress…' : 'Sign Up'}
</FormButton>
</Box>
)}
</Form>
</AppForm>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(SignUp);
| 5,386 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/SignUp.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Link from '@mui/material/Link';
import { Field, Form, FormSpy } from 'react-final-form';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import AppForm from './modules/views/AppForm';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import withRoot from './modules/withRoot';
function SignUp() {
const [sent, setSent] = React.useState(false);
const validate = (values: { [index: string]: string }) => {
const errors = required(['firstName', 'lastName', 'email', 'password'], values);
if (!errors.email) {
const emailError = email(values.email);
if (emailError) {
errors.email = emailError;
}
}
return errors;
};
const handleSubmit = () => {
setSent(true);
};
return (
<React.Fragment>
<AppAppBar />
<AppForm>
<React.Fragment>
<Typography variant="h3" gutterBottom marked="center" align="center">
Sign Up
</Typography>
<Typography variant="body2" align="center">
<Link href="/premium-themes/onepirate/sign-in/" underline="always">
Already have an account?
</Link>
</Typography>
</React.Fragment>
<Form
onSubmit={handleSubmit}
subscription={{ submitting: true }}
validate={validate}
>
{({ handleSubmit: handleSubmit2, submitting }) => (
<Box component="form" onSubmit={handleSubmit2} noValidate sx={{ mt: 6 }}>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Field
autoFocus
component={RFTextField}
disabled={submitting || sent}
autoComplete="given-name"
fullWidth
label="First name"
name="firstName"
required
/>
</Grid>
<Grid item xs={12} sm={6}>
<Field
component={RFTextField}
disabled={submitting || sent}
autoComplete="family-name"
fullWidth
label="Last name"
name="lastName"
required
/>
</Grid>
</Grid>
<Field
autoComplete="email"
component={RFTextField}
disabled={submitting || sent}
fullWidth
label="Email"
margin="normal"
name="email"
required
/>
<Field
fullWidth
component={RFTextField}
disabled={submitting || sent}
required
name="password"
autoComplete="new-password"
label="Password"
type="password"
margin="normal"
/>
<FormSpy subscription={{ submitError: true }}>
{({ submitError }) =>
submitError ? (
<FormFeedback error sx={{ mt: 2 }}>
{submitError}
</FormFeedback>
) : null
}
</FormSpy>
<FormButton
sx={{ mt: 3, mb: 2 }}
disabled={submitting || sent}
color="secondary"
fullWidth
>
{submitting || sent ? 'In progress…' : 'Sign Up'}
</FormButton>
</Box>
)}
</Form>
</AppForm>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(SignUp);
| 5,387 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/Terms.js | import * as React from 'react';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';
import Markdown from './modules/components/Markdown';
import Typography from './modules/components/Typography';
import AppAppBar from './modules/views/AppAppBar';
import AppFooter from './modules/views/AppFooter';
import withRoot from './modules/withRoot';
import terms from './modules/views/terms.md';
function Terms() {
return (
<React.Fragment>
<AppAppBar />
<Container>
<Box sx={{ mt: 7, mb: 12 }}>
<Typography variant="h3" gutterBottom marked="center" align="center">
Terms
</Typography>
<Markdown>{terms}</Markdown>
</Box>
</Container>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(Terms);
| 5,388 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/Terms.tsx | import * as React from 'react';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';
import Markdown from './modules/components/Markdown';
import Typography from './modules/components/Typography';
import AppAppBar from './modules/views/AppAppBar';
import AppFooter from './modules/views/AppFooter';
import withRoot from './modules/withRoot';
import terms from './modules/views/terms.md';
function Terms() {
return (
<React.Fragment>
<AppAppBar />
<Container>
<Box sx={{ mt: 7, mb: 12 }}>
<Typography variant="h3" gutterBottom marked="center" align="center">
Terms
</Typography>
<Markdown>{terms}</Markdown>
</Box>
</Container>
<AppFooter />
</React.Fragment>
);
}
export default withRoot(Terms);
| 5,389 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules.d.ts | declare module '*.md';
| 5,390 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/theme.js | import { createTheme } from '@mui/material/styles';
import { green, grey, red } from '@mui/material/colors';
const rawTheme = createTheme({
palette: {
primary: {
light: '#69696a',
main: '#28282a',
dark: '#1e1e1f',
},
secondary: {
light: '#fff5f8',
main: '#ff3366',
dark: '#e62958',
},
warning: {
main: '#ffc071',
dark: '#ffb25e',
},
error: {
light: red[50],
main: red[500],
dark: red[700],
},
success: {
light: green[50],
main: green[500],
dark: green[700],
},
},
typography: {
fontFamily: "'Work Sans', sans-serif",
fontSize: 14,
fontWeightLight: 300, // Work Sans
fontWeightRegular: 400, // Work Sans
fontWeightMedium: 700, // Roboto Condensed
},
});
const fontHeader = {
color: rawTheme.palette.text.primary,
fontWeight: rawTheme.typography.fontWeightMedium,
fontFamily: "'Roboto Condensed', sans-serif",
textTransform: 'uppercase',
};
const theme = {
...rawTheme,
palette: {
...rawTheme.palette,
background: {
...rawTheme.palette.background,
default: rawTheme.palette.common.white,
placeholder: grey[200],
},
},
typography: {
...rawTheme.typography,
fontHeader,
h1: {
...rawTheme.typography.h1,
...fontHeader,
letterSpacing: 0,
fontSize: 60,
},
h2: {
...rawTheme.typography.h2,
...fontHeader,
fontSize: 48,
},
h3: {
...rawTheme.typography.h3,
...fontHeader,
fontSize: 42,
},
h4: {
...rawTheme.typography.h4,
...fontHeader,
fontSize: 36,
},
h5: {
...rawTheme.typography.h5,
fontSize: 20,
fontWeight: rawTheme.typography.fontWeightLight,
},
h6: {
...rawTheme.typography.h6,
...fontHeader,
fontSize: 18,
},
subtitle1: {
...rawTheme.typography.subtitle1,
fontSize: 18,
},
body1: {
...rawTheme.typography.body2,
fontWeight: rawTheme.typography.fontWeightRegular,
fontSize: 16,
},
body2: {
...rawTheme.typography.body1,
fontSize: 14,
},
},
};
export default theme;
| 5,391 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/theme.ts | import { createTheme } from '@mui/material/styles';
import { green, grey, red } from '@mui/material/colors';
const rawTheme = createTheme({
palette: {
primary: {
light: '#69696a',
main: '#28282a',
dark: '#1e1e1f',
},
secondary: {
light: '#fff5f8',
main: '#ff3366',
dark: '#e62958',
},
warning: {
main: '#ffc071',
dark: '#ffb25e',
},
error: {
light: red[50],
main: red[500],
dark: red[700],
},
success: {
light: green[50],
main: green[500],
dark: green[700],
},
},
typography: {
fontFamily: "'Work Sans', sans-serif",
fontSize: 14,
fontWeightLight: 300, // Work Sans
fontWeightRegular: 400, // Work Sans
fontWeightMedium: 700, // Roboto Condensed
},
});
const fontHeader = {
color: rawTheme.palette.text.primary,
fontWeight: rawTheme.typography.fontWeightMedium,
fontFamily: "'Roboto Condensed', sans-serif",
textTransform: 'uppercase',
};
const theme = {
...rawTheme,
palette: {
...rawTheme.palette,
background: {
...rawTheme.palette.background,
default: rawTheme.palette.common.white,
placeholder: grey[200],
},
},
typography: {
...rawTheme.typography,
fontHeader,
h1: {
...rawTheme.typography.h1,
...fontHeader,
letterSpacing: 0,
fontSize: 60,
},
h2: {
...rawTheme.typography.h2,
...fontHeader,
fontSize: 48,
},
h3: {
...rawTheme.typography.h3,
...fontHeader,
fontSize: 42,
},
h4: {
...rawTheme.typography.h4,
...fontHeader,
fontSize: 36,
},
h5: {
...rawTheme.typography.h5,
fontSize: 20,
fontWeight: rawTheme.typography.fontWeightLight,
},
h6: {
...rawTheme.typography.h6,
...fontHeader,
fontSize: 18,
},
subtitle1: {
...rawTheme.typography.subtitle1,
fontSize: 18,
},
body1: {
...rawTheme.typography.body2,
fontWeight: rawTheme.typography.fontWeightRegular,
fontSize: 16,
},
body2: {
...rawTheme.typography.body1,
fontSize: 14,
},
},
};
export default theme;
| 5,392 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/withRoot.js | import * as React from 'react';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import theme from './theme';
export default function withRoot(Component) {
function WithRoot(props) {
return (
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...props} />
</ThemeProvider>
);
}
return WithRoot;
}
| 5,393 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/withRoot.tsx | import * as React from 'react';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import theme from './theme';
export default function withRoot<P extends JSX.IntrinsicAttributes>(
Component: React.ComponentType<P>,
) {
function WithRoot(props: P) {
return (
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...props} />
</ThemeProvider>
);
}
return WithRoot;
}
| 5,394 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/components/AppBar.js | import * as React from 'react';
import MuiAppBar from '@mui/material/AppBar';
function AppBar(props) {
return <MuiAppBar elevation={0} position="fixed" {...props} />;
}
export default AppBar;
| 5,395 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/components/AppBar.tsx | import * as React from 'react';
import MuiAppBar, { AppBarProps } from '@mui/material/AppBar';
function AppBar(props: AppBarProps) {
return <MuiAppBar elevation={0} position="fixed" {...props} />;
}
export default AppBar;
| 5,396 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/components/Button.js | import * as React from 'react';
import { experimentalStyled as styled } from '@mui/material/styles';
import MuiButton from '@mui/material/Button';
const ButtonRoot = styled(MuiButton)(({ theme, size }) => ({
borderRadius: 0,
fontWeight: theme.typography.fontWeightMedium,
fontFamily: theme.typography.h1.fontFamily,
padding: theme.spacing(2, 4),
fontSize: theme.typography.pxToRem(14),
boxShadow: 'none',
'&:active, &:focus': {
boxShadow: 'none',
},
...(size === 'small' && {
padding: theme.spacing(1, 3),
fontSize: theme.typography.pxToRem(13),
}),
...(size === 'large' && {
padding: theme.spacing(2, 5),
fontSize: theme.typography.pxToRem(16),
}),
}));
// See https://mui.com/guides/typescript/#usage-of-component-prop for why the types uses `C`.
function Button(props) {
return <ButtonRoot {...props} />;
}
export default Button;
| 5,397 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/components/Button.tsx | import * as React from 'react';
import { experimentalStyled as styled } from '@mui/material/styles';
import MuiButton, { ButtonProps } from '@mui/material/Button';
const ButtonRoot = styled(MuiButton)(({ theme, size }) => ({
borderRadius: 0,
fontWeight: theme.typography.fontWeightMedium,
fontFamily: theme.typography.h1.fontFamily,
padding: theme.spacing(2, 4),
fontSize: theme.typography.pxToRem(14),
boxShadow: 'none',
'&:active, &:focus': {
boxShadow: 'none',
},
...(size === 'small' && {
padding: theme.spacing(1, 3),
fontSize: theme.typography.pxToRem(13),
}),
...(size === 'large' && {
padding: theme.spacing(2, 5),
fontSize: theme.typography.pxToRem(16),
}),
}));
// See https://mui.com/guides/typescript/#usage-of-component-prop for why the types uses `C`.
function Button<C extends React.ElementType>(
props: ButtonProps<C, { component?: C }>,
) {
return <ButtonRoot {...props} />;
}
export default Button;
| 5,398 |
0 | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules | petrpan-code/mui/material-ui/docs/src/pages/premium-themes/onepirate/modules/components/Markdown.js | import * as React from 'react';
import ReactMarkdown from 'markdown-to-jsx';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Link from '@mui/material/Link';
const options = {
overrides: {
h1: {
component: Typography,
props: {
gutterBottom: true,
variant: 'h4',
},
},
h2: {
component: Typography,
props: { gutterBottom: true, variant: 'h6' },
},
h3: {
component: Typography,
props: { gutterBottom: true, variant: 'subtitle1' },
},
h4: {
component: Typography,
props: {
gutterBottom: true,
variant: 'caption',
paragraph: true,
},
},
p: {
component: Typography,
props: { paragraph: true },
},
a: { component: Link },
li: {
component: (props) => (
<Box component="li" sx={{ mt: 1 }}>
<Typography component="span" {...props} />
</Box>
),
},
},
};
export default function Markdown(props) {
return <ReactMarkdown options={options} {...props} />;
}
| 5,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.