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/components | petrpan-code/mui/material-ui/docs/src/components/productTemplate/TemplateHero.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import KeyboardArrowRightRounded from '@mui/icons-material/KeyboardArrowRightRounded';
import GradientText from 'docs/src/components/typography/GradientText';
import HeroContainer from 'docs/src/layouts/HeroContainer';
import IconImage from 'docs/src/components/icon/IconImage';
import Link from 'docs/src/modules/components/Link';
import {
StoreTemplatesSet1,
StoreTemplatesSet2,
} from 'docs/src/components/home/StoreTemplatesBanner';
export default function TemplateHero() {
return (
<HeroContainer
linearGradient
left={
<Box sx={{ textAlign: { xs: 'center', md: 'left' } }}>
<Typography
fontWeight="bold"
variant="body2"
sx={(theme) => ({
display: 'flex',
alignItems: 'center',
justifyContent: { xs: 'center', md: 'start' },
'& > *': { mr: 1 },
color: 'primary.600',
...theme.applyDarkStyles({
color: 'primary.400',
}),
})}
>
<IconImage width={28} height={28} loading="eager" name="product-templates" /> Templates
</Typography>
<Typography variant="h1" sx={{ my: 2, maxWidth: 500 }}>
<GradientText>Fully built</GradientText> Material UI templates
</Typography>
<Typography color="text.secondary" sx={{ mb: 3, maxWidth: 500 }}>
A collection of 4.5 average rating templates, selected and curated by MUI's team of
maintainers to get your projects up and running today.
</Typography>
<Button
component={Link}
noLinkStyle
href="https://mui.com/store/?utm_source=marketing&utm_medium=referral&utm_campaign=templates-cta#populars"
size="large"
variant="contained"
endIcon={<KeyboardArrowRightRounded />}
sx={{ width: { xs: '100%', sm: 'auto' } }}
>
Browse templates
</Button>
</Box>
}
right={
<Box sx={{ position: 'relative', height: '100%', perspective: '1000px' }}>
<Box
sx={{
left: '40%',
position: 'absolute',
display: 'flex',
transform: 'translateX(-40%) rotateZ(-30deg) rotateX(8deg) rotateY(8deg)',
transformOrigin: 'center center',
}}
>
<StoreTemplatesSet1
disableLink
keyframes={{
'0%': {
transform: 'translateY(-200px)',
},
'100%': {
transform: 'translateY(-40px)',
},
}}
/>
<StoreTemplatesSet2
disableLink
keyframes={{
'0%': {
transform: 'translateY(150px)',
},
'100%': {
transform: 'translateY(40px)',
},
}}
sx={{ ml: { xs: 2, sm: 4, md: 8 } }}
/>
</Box>
</Box>
}
/>
);
}
| 5,200 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XChartsDemo.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import { alpha } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import { LineChart } from '@mui/x-charts/LineChart';
import { BarChart } from '@mui/x-charts/BarChart';
import { mangoFusionPalette } from '@mui/x-charts';
import Frame from 'docs/src/components/action/Frame';
export default function XChartsDemo() {
return (
<Frame sx={{ height: '100%' }}>
<Frame.Demo sx={{ p: 2, flexGrow: 1 }}>
<Paper
variant="outlined"
sx={[
{
'& > div': {
borderRadius: 1,
bgcolor: '#fff',
},
},
(theme) =>
theme.applyDarkStyles({
'& > div': {
bgcolor: 'primaryDark.900',
},
}),
]}
>
<Box sx={{ py: 1 }}>
<LineChart
sx={{
'& .MuiMarkElement-root': { display: 'none' },
'& .MuiMarkElement-root.MuiMarkElement-highlighted': { display: 'block' },
}}
margin={{ top: 10, bottom: 50, left: 40, right: 20 }}
series={[
{ data: [35, 44, 24, 34], stack: 'total', area: true },
{ data: [51, 6, 49, 30], stack: 'total', area: true },
{ data: [5, 15, 30, 50], stack: 'total', area: true },
{ data: [60, 50, 15, 10], stack: 'total', area: true },
]}
xAxis={[{ data: ['Q1', 'Q2', 'Q3', 'Q4'], scaleType: 'point' }]}
colors={mangoFusionPalette}
height={250}
/>
<BarChart
sx={{
'& .MuiMarkElement-root': { display: 'none' },
'& .MuiMarkElement-root.MuiMarkElement-highlighted': { display: 'block' },
}}
margin={{ top: 10, bottom: 30, left: 40, right: 10 }}
series={[
{ data: [35, 44, 24, 34] },
{ data: [51, 6, 49, 30] },
{ data: [15, 25, 30, 50] },
{ data: [60, 50, 15, 25] },
]}
xAxis={[{ data: ['Q1', 'Q2', 'Q3', 'Q4'], scaleType: 'band' }]}
height={200}
colors={mangoFusionPalette}
/>
</Box>
</Paper>
</Frame.Demo>
<Frame.Info data-mui-color-scheme="dark">
<Box
sx={{
display: 'flex',
alignItems: 'center',
lineHeight: 1,
mb: 0.5,
}}
>
<Typography variant="body2" fontWeight="bold" sx={{ mr: 1 }}>
Experiment with Charts now!
</Typography>
<Chip
variant="outlined"
label="Alpha"
color="warning"
size="small"
sx={(theme) => ({
pb: 0.2,
fontWeight: theme.typography.fontWeightSemiBold,
color: (theme.vars || theme).palette.warning[300],
borderColor: alpha(theme.palette.warning[300], 0.3),
background: alpha(theme.palette.warning[800], 0.3),
})}
/>
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Using D3.js for data manipulation and SVG for rendering, Charts are coming to MUI X!
</Typography>
<Button
variant="outlined"
href="/x/react-charts/"
component="a"
sx={{ mt: { xs: 2, sm: 0 }, color: 'primary.300' }}
>
View the documentation
</Button>
</Frame.Info>
</Frame>
);
}
| 5,201 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XComponents.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Fade from '@mui/material/Fade';
import Grid from '@mui/material/Grid';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import TableChartRounded from '@mui/icons-material/TableChartRounded';
import DateRangeRounded from '@mui/icons-material/DateRangeRounded';
import AccountTreeRounded from '@mui/icons-material/AccountTreeRounded';
import ShowChartRounded from '@mui/icons-material/ShowChartRounded';
import BarChartRounded from '@mui/icons-material/BarChartRounded';
import Section from 'docs/src/layouts/Section';
import SectionHeadline from 'docs/src/components/typography/SectionHeadline';
import GradientText from 'docs/src/components/typography/GradientText';
import Item, { Group } from 'docs/src/components/action/Item';
import Highlighter from 'docs/src/components/action/Highlighter';
import XGridFullDemo from 'docs/src/components/productX/XGridFullDemo';
import XDateRangeDemo from 'docs/src/components/productX/XDateRangeDemo';
import XTreeViewDemo from 'docs/src/components/productX/XTreeViewDemo';
import XChartsDemo from 'docs/src/components/productX/XChartsDemo';
import XSparklineDemo from 'docs/src/components/productX/XSparklineDemo';
import More from 'docs/src/components/action/More';
import ROUTES from 'docs/src/route';
import IconImage from 'docs/src/components/icon/IconImage';
const DEMOS = ['Data Grid', 'Date and Time Pickers', 'Charts', 'Tree View', 'Sparkline'];
const WIP = DEMOS.slice(4);
function PrefetchImages() {
function makeImg(component: 'sparkline' | 'chart', mode: string, num: number) {
return {
loading: 'lazy' as const,
width: 100,
src: `/static/branding/mui-x/${component}-${mode}${num}.png`,
};
}
return (
<Box
sx={{
width: 0,
height: 0,
visibility: 'hidden',
'& > img': {
position: 'absolute',
},
}}
>
{[...Array(2)].map((_, index) => (
<React.Fragment key={index}>
<img alt="" {...makeImg('sparkline', 'light', index + 1)} />
<img alt="" {...makeImg('sparkline', 'dark', index + 1)} />
</React.Fragment>
))}
{[...Array(4)].map((_, index) => (
<React.Fragment key={index}>
<img alt="" {...makeImg('chart', 'light', index + 1)} />
<img alt="" {...makeImg('chart', 'dark', index + 1)} />
</React.Fragment>
))}
</Box>
);
}
export default function XComponents() {
const [demo, setDemo] = React.useState(DEMOS[1]);
const icons = {
[DEMOS[0]]: <TableChartRounded fontSize="small" />,
[DEMOS[1]]: <DateRangeRounded fontSize="small" />,
[DEMOS[2]]: <BarChartRounded fontSize="small" />,
[DEMOS[3]]: <AccountTreeRounded fontSize="small" />,
[DEMOS[4]]: <ShowChartRounded fontSize="small" />,
};
return (
<Section bg="gradient">
<Grid container spacing={2}>
<Grid item md={6} sx={{ minWidth: 0 }}>
<SectionHeadline
overline="React component library"
title={
<Typography variant="h2">
Powerful components for <GradientText>advanced</GradientText> use-cases
</Typography>
}
description="The MUI X package enables applications to have complex use-cases, supported by several advanced components."
/>
<Group desktopColumns={2} sx={{ m: -2, p: 2 }}>
{DEMOS.map((name) => (
<Highlighter key={name} selected={name === demo} onClick={() => setDemo(name)}>
<Item icon={React.cloneElement(icons[name])} title={name} />
{WIP.includes(name) && (
<Tooltip title="Work in progress">
<IconImage name="pricing/time" sx={{ ml: 'auto', mr: 2 }} />
</Tooltip>
)}
</Highlighter>
))}
<More href={ROUTES.xDocs} />
</Group>
</Grid>
<Grid item xs={12} md={6} sx={{ position: 'relative' }}>
<PrefetchImages />
{demo === DEMOS[0] && (
<Fade in timeout={500}>
<Box sx={{ height: '100%' }}>
<XGridFullDemo />
</Box>
</Fade>
)}
{demo === DEMOS[1] && (
<Fade in timeout={500}>
<div>
<XDateRangeDemo />
</div>
</Fade>
)}
{demo === DEMOS[2] && (
<Fade in timeout={500}>
<div>
<XChartsDemo />
</div>
</Fade>
)}
{demo === DEMOS[3] && (
<Fade in timeout={500}>
<div>
<XTreeViewDemo />
</div>
</Fade>
)}
{demo === DEMOS[4] && (
<Fade in timeout={500}>
<div>
<XSparklineDemo />
</div>
</Fade>
)}
</Grid>
</Grid>
</Section>
);
}
| 5,202 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XDataGrid.tsx | import * as React from 'react';
import { DataGridPro, useGridApiRef } from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import EditRoundedIcon from '@mui/icons-material/EditRounded';
import LibraryAddCheckRounded from '@mui/icons-material/LibraryAddCheckRounded';
import SortByAlphaRounded from '@mui/icons-material/SortByAlphaRounded';
import AutoStoriesOutlined from '@mui/icons-material/AutoStoriesOutlined';
import FilterAltRounded from '@mui/icons-material/FilterAltRounded';
import Section from 'docs/src/layouts/Section';
import SectionHeadline from 'docs/src/components/typography/SectionHeadline';
import GradientText from 'docs/src/components/typography/GradientText';
import Item, { Group } from 'docs/src/components/action/Item';
import Highlighter from 'docs/src/components/action/Highlighter';
import More from 'docs/src/components/action/More';
import Frame from 'docs/src/components/action/Frame';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
import MarkdownElement from 'docs/src/components/markdown/MarkdownElement';
import FlashCode from 'docs/src/components/animation/FlashCode';
import XGridGlobalStyles from 'docs/src/components/home/XGridGlobalStyles';
import StylingInfo from 'docs/src/components/action/StylingInfo';
import Link from 'docs/src/modules/components/Link';
import ROUTES from 'docs/src/route';
const DEMOS = ['Editing', 'Selection', 'Sorting', 'Pagination', 'Filtering'] as const;
const code = `<DataGrid
columns={[ // column definition example
{
field: 'name',
headerName: 'Name',
editable: true,
sortable: true,
filterable: true,
},
]}
checkboxSelection
disableRowSelectionOnClick
pagination
/>`;
const startLine = {
[DEMOS[0]]: 5,
[DEMOS[1]]: 10,
[DEMOS[2]]: 6,
[DEMOS[3]]: 12,
[DEMOS[4]]: 7,
};
const dataGridStyleOverrides = <XGridGlobalStyles selector="#data-grid-demo" pro />;
export default function XDataGrid() {
const [demo, setDemo] = React.useState<(typeof DEMOS)[number] | null>(null);
const gridApiRef = useGridApiRef();
const icons = {
[DEMOS[0]]: <EditRoundedIcon fontSize="small" />,
[DEMOS[1]]: <LibraryAddCheckRounded fontSize="small" />,
[DEMOS[2]]: <SortByAlphaRounded fontSize="small" />,
[DEMOS[3]]: <AutoStoriesOutlined fontSize="small" />,
[DEMOS[4]]: <FilterAltRounded fontSize="small" />,
};
const { loading, data } = useDemoData({
dataSet: 'Employee',
rowLength: 1000,
maxColumns: 5,
editable: true,
});
const firstRowId = data.rows[0]?.id;
React.useEffect(() => {
if (gridApiRef && gridApiRef.current && !loading) {
if (demo) {
gridApiRef.current.scroll({ top: 0, left: 0 });
}
if (demo === DEMOS[0]) {
document.body.focus();
setTimeout(() => {
const cell = document.querySelector(
'#data-grid-demo div[role="cell"][data-field="name"]',
);
if (cell) {
const clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent('dblclick', true, true);
cell.dispatchEvent(clickEvent);
}
}, 120);
}
if (demo === DEMOS[1]) {
const checkbox = document.querySelector(
'#data-grid-demo div[data-field="__check__"] input',
) as HTMLInputElement | null;
if (checkbox && !checkbox.checked) {
checkbox.click();
}
}
if (demo === DEMOS[2]) {
const sorter = document.querySelector(
'#data-grid-demo button[aria-label="Sort"]',
) as HTMLButtonElement | null;
if (sorter) {
sorter.click();
}
}
if (demo === DEMOS[3]) {
const nextPage = document.querySelector(
'#data-grid-demo button[aria-label="Go to next page"]',
) as HTMLButtonElement | null;
if (nextPage) {
nextPage.click();
}
}
if (demo === DEMOS[4]) {
document.body.focus();
gridApiRef.current.showFilterPanel('name');
}
}
}, [demo, loading, firstRowId, gridApiRef]);
return (
<Section>
<Grid container spacing={2}>
<Grid item md={6} sx={{ minWidth: 0 }}>
<SectionHeadline
overline="Data Grid"
title={
<Typography variant="h2">
A level of <GradientText>performance and quality</GradientText> that hasn't
been seen before
</Typography>
}
description="The MUI X Data Grid is a data table powerhouse. It is packed with exclusive features that will enrich the experience of dealing with and maintaining lots of data."
/>
<Group desktopColumns={2} sx={{ m: -2, p: 2 }}>
{DEMOS.map((name) => (
<Highlighter
selectedBg="comfort"
key={name}
selected={name === demo}
onClick={() => setDemo(name)}
>
<Item icon={icons[name]} title={name} />
</Highlighter>
))}
<More href={ROUTES.dataGridFeatures} />
</Group>
</Grid>
<Grid item xs={12} md={6}>
<Paper
id="data-grid-demo"
variant="outlined"
sx={[
{
position: 'relative',
zIndex: 1,
height: 240,
borderRadius: '10px 10px 0 0',
borderColor: 'grey.200',
'& .MuiDataGrid-root': {
'& .MuiAvatar-root': { width: 24, height: 24, fontSize: 14, fontWeight: 'bold' },
'& .MuiDataGrid-footerContainer': {
minHeight: 48,
borderTop: '1px solid',
borderColor: 'grey.200',
},
'& .MuiTablePagination-root': {
fontSize: '0.75rem',
'& p': {
fontSize: '0.75rem',
},
'& .MuiToolbar-root': {
minHeight: 48,
},
},
},
},
(theme) =>
theme.applyDarkStyles({
borderColor: 'primaryDark.600',
'& .MuiDataGrid-root': {
'& .MuiDataGrid-footerContainer': {
borderColor: 'primaryDark.600',
},
},
}),
]}
>
{dataGridStyleOverrides}
<DataGridPro
{...data}
apiRef={gridApiRef}
loading={loading}
density="compact"
checkboxSelection
disableRowSelectionOnClick
pagination
/>
</Paper>
<Frame.Info
sx={{
borderBottomLeftRadius: 10,
borderBottomRightRadius: 10,
mt: -1,
pb: 1,
'&::-webkit-scrollbar': {
display: 'none',
},
'&& pre': {
bgcolor: 'transparent',
'&::-webkit-scrollbar': {
display: 'none',
},
},
overflow: 'hidden',
}}
>
<Box sx={{ position: 'relative' }}>
<Box sx={{ position: 'relative', zIndex: 1 }}>
<HighlightedCode
copyButtonHidden
component={MarkdownElement}
code={code}
language="jsx"
/>
</Box>
{demo && <FlashCode startLine={startLine[demo]} sx={{ mx: -2 }} />}
<StylingInfo
appeared={demo === DEMOS[3] || demo === DEMOS[4]}
stylingContent={
<React.Fragment>
<Typography fontWeight="bold" color="#fff" variant="body2">
{demo === DEMOS[3] && 'Pagination > 100 rows per page is a paid feature!'}
{demo === DEMOS[4] && 'Multi-column filtering is a paid feature!'}
</Typography>
<Typography color="grey.400" variant="body2">
The Data Grid and all other MUI X components are available on free and paid
versions. More details about each plan and its features are on{' '}
<Link href={ROUTES.pricing} sx={{ color: 'primary.300' }}>
the pricing page
</Link>
.
</Typography>
</React.Fragment>
}
sx={{ mx: -2, mb: -1 }}
/>
</Box>
</Frame.Info>
</Grid>
</Grid>
</Section>
);
}
| 5,203 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XDateRangeDemo.tsx | import * as React from 'react';
import { alpha } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import { StaticDateRangePicker } from '@mui/x-date-pickers-pro/StaticDateRangePicker';
import { PickersShortcutsItem, PickersShortcutsProps, DateRange } from '@mui/x-date-pickers-pro';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { startOfWeek, endOfWeek, subDays } from 'date-fns';
import Frame from 'docs/src/components/action/Frame';
const startDate = new Date();
startDate.setDate(10);
const endDate = new Date();
endDate.setDate(endDate.getDate() + 28);
function CustomRangeShortcuts(props: PickersShortcutsProps<DateRange<Date>>) {
const { items, onChange, isValid } = props;
if (items == null || items.length === 0) {
return null;
}
const resolvedItems = items.map((item: PickersShortcutsItem<DateRange<Date>>) => {
const newValue = item.getValue({ isValid });
return {
label: item.label,
onClick: () => {
onChange(newValue);
},
disabled: !isValid(newValue),
};
});
return (
<Box
sx={{
gridRow: 1,
gridColumn: 2,
}}
>
<List
sx={{
display: 'flex',
p: 1.5,
gap: 1,
'& .MuiListItem-root': {
p: 0,
width: 'fit-content',
},
}}
>
{resolvedItems.map((item) => {
return (
<ListItem key={item.label}>
<Chip size="small" {...item} />
</ListItem>
);
})}
</List>
<Divider />
</Box>
);
}
export default function XDateRangeDemo() {
const today = new Date();
const shortcutsItems: PickersShortcutsItem<DateRange<Date>>[] = [
{
label: 'This Week',
getValue: () => {
return [startOfWeek(today), endOfWeek(today)];
},
},
{
label: 'Last Week',
getValue: () => {
const prevWeek = subDays(today, 7);
return [startOfWeek(prevWeek), endOfWeek(prevWeek)];
},
},
{
label: 'Last 7 Days',
getValue: () => {
return [subDays(today, 7), today];
},
},
{ label: 'Reset', getValue: () => [null, null] },
];
return (
<Frame>
<Frame.Demo sx={{ p: 2 }}>
<Paper
variant="outlined"
sx={[
{
'& > div': {
borderRadius: 1,
overflow: 'auto',
bgcolor: '#fff',
},
'& > div > div > div > div': {
flexGrow: 1,
},
'& .MuiTypography-subtitle1': {
fontSize: '0.875rem',
},
'& .MuiTypography-caption': {
width: 28,
height: 32,
},
'& .MuiPickersSlideTransition-root': {
minWidth: 258,
minHeight: 238,
},
'& [role="row"]': {
margin: '4px 0',
},
'& .MuiDateRangePickerDay-root': {
lineHeight: 0,
margin: 0,
},
'& .MuiPickersArrowSwitcher-root': {
padding: 0,
paddingTop: 0.5,
},
'& .MuiPickersDay-root': {
width: 28,
height: 28,
fontWeight: 400,
},
'& .MuiDateRangePickerDay-day.Mui-selected': {
fontWeight: 600,
},
'& .MuiDateRangePickerDay-day:not(.Mui-selected)': {
borderColor: 'primary.300',
},
},
(theme) =>
theme.applyDarkStyles({
'& > div': {
bgcolor: 'primaryDark.900',
},
'& .MuiDateRangePickerDay-day.Mui-selected': {
color: '#FFF',
},
}),
]}
>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<StaticDateRangePicker
displayStaticWrapperAs="desktop"
value={[startDate, endDate]}
slots={{
shortcuts: CustomRangeShortcuts,
}}
slotProps={{
shortcuts: {
items: shortcutsItems,
},
}}
/>
</LocalizationProvider>
</Paper>
</Frame.Demo>
<Frame.Info data-mui-color-scheme="dark">
<Box
sx={{
display: 'flex',
alignItems: 'center',
lineHeight: 1,
mb: 0.5,
}}
>
<Typography variant="body2" fontWeight="bold" sx={{ mr: 1 }}>
Date Range Picker now available for your project!
</Typography>
<Chip
variant="outlined"
label="Available now"
color="success"
size="small"
sx={(theme) => ({
pb: 0.2,
fontWeight: theme.typography.fontWeightSemiBold,
color: (theme.vars || theme).palette.success[300],
borderColor: alpha(theme.palette.success[300], 0.3),
background: alpha(theme.palette.success[800], 0.3),
})}
/>
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
A thorough and advanced stable implementation of a long-requested component!
</Typography>
<Button
variant="outlined"
href="/x/react-date-pickers/date-range-picker/"
component="a"
sx={{ mt: { xs: 2, sm: 0 }, color: 'primary.300' }}
>
View the documentation
</Button>
</Frame.Info>
</Frame>
);
}
| 5,204 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XGridFullDemo.tsx | import * as React from 'react';
import { red, green, yellow, blue } from '@mui/material/colors';
import { alpha } from '@mui/material/styles';
import { DataGridPro, GridToolbar, GridPaginationModel } from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';
import FormControl from '@mui/material/FormControl';
import FormGroup from '@mui/material/FormGroup';
import Button from '@mui/material/Button';
import Paper from '@mui/material/Paper';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import Frame from 'docs/src/components/action/Frame';
import XGridGlobalStyles from 'docs/src/components/home/XGridGlobalStyles';
type GridDataType = 'Employee' | 'Commodity';
interface GridPaginationSettings {
pagination: boolean;
autoPageSize: boolean;
paginationModel: GridPaginationModel | undefined;
}
interface GridConfigOptions {
size: number;
type: GridDataType;
pagesize: number;
}
interface GridToolbarContainerProps {
onApply: (options: GridConfigOptions) => void;
size: number;
type: GridDataType;
}
const pageSizeOptions = [25, 100, 1000];
function SettingsPanel(props: GridToolbarContainerProps) {
const { onApply, type, size } = props;
const [sizeState, setSize] = React.useState<number>(size);
const [typeState, setType] = React.useState<GridDataType>(type);
const [selectedPaginationValue, setSelectedPaginationValue] = React.useState<number>(-1);
const handleSizeChange = React.useCallback((event: SelectChangeEvent<string>) => {
setSize(Number(event.target.value));
}, []);
const handleDatasetChange = React.useCallback((event: SelectChangeEvent<GridDataType>) => {
setType(event.target.value as GridDataType);
}, []);
const handlePaginationChange = React.useCallback((event: SelectChangeEvent<number>) => {
setSelectedPaginationValue(Number(event.target.value));
}, []);
const handleApplyChanges = React.useCallback(() => {
onApply({
size: sizeState,
type: typeState,
pagesize: selectedPaginationValue,
});
}, [sizeState, typeState, selectedPaginationValue, onApply]);
return (
<FormGroup
className="MuiFormGroup-options"
sx={{
flexDirection: { xs: 'column', sm: 'row' },
alignContent: { xs: 'start', sm: 'center' },
alignItems: { xs: 'start', sm: 'center' },
'& > *': {
'&:not(:first-child)': { ml: { xs: 0, sm: 1 } },
'&:last-child': { ml: 'auto' },
},
'& .MuiFilledInput-root': {
borderRadius: 1,
backgroundColor: 'transparent',
},
'& .MuiInputBase-sizeSmall': {
fontSize: '0.875rem',
},
}}
>
<FormControl variant="filled" size="small">
<InputLabel>Dataset</InputLabel>
<Select value={typeState} onChange={handleDatasetChange} disableUnderline>
<MenuItem value="Employee">Employee</MenuItem>
<MenuItem value="Commodity">Commodity</MenuItem>
</Select>
</FormControl>
<FormControl variant="filled" size="small">
<InputLabel>Rows</InputLabel>
<Select value={String(sizeState)} onChange={handleSizeChange} disableUnderline>
<MenuItem value={100}>100</MenuItem>
<MenuItem value={1000}>{Number(1000).toLocaleString()}</MenuItem>
<MenuItem value={10000}>{Number(10000).toLocaleString()}</MenuItem>
<MenuItem value={100000}>{Number(100000).toLocaleString()}</MenuItem>
</Select>
</FormControl>
<FormControl variant="filled" size="small" sx={{ minWidth: 80 }}>
<InputLabel>Page Size</InputLabel>
<Select value={selectedPaginationValue} onChange={handlePaginationChange} disableUnderline>
<MenuItem value={-1}>off</MenuItem>
<MenuItem value={0}>auto</MenuItem>
{pageSizeOptions.map((pageSize) => (
<MenuItem key={pageSize} value={pageSize}>
{Number(pageSize).toLocaleString()}
</MenuItem>
))}
</Select>
</FormControl>
<Button
variant="outlined"
onClick={handleApplyChanges}
sx={{ mt: { xs: 2, sm: 0 }, color: 'primary.300', height: 'fit-content' }}
>
Apply changes
</Button>
</FormGroup>
);
}
export default function XGridFullDemo() {
const [type, setType] = React.useState<GridDataType>('Commodity');
const [size, setSize] = React.useState(100);
const { loading, data, setRowLength, loadNewData } = useDemoData({
dataSet: type,
rowLength: size,
maxColumns: 40,
editable: true,
});
const [pagination, setPagination] = React.useState<GridPaginationSettings>({
pagination: false,
autoPageSize: false,
paginationModel: undefined,
});
const handleApplyClick = (settings: GridConfigOptions) => {
if (size !== settings.size) {
setSize(settings.size);
}
if (type !== settings.type) {
setType(settings.type);
}
if (size !== settings.size || type !== settings.type) {
setRowLength(settings.size);
loadNewData();
}
const newPaginationSettings: GridPaginationSettings = {
pagination: settings.pagesize !== -1,
autoPageSize: settings.pagesize === 0,
paginationModel: settings.pagesize > 0 ? { pageSize: settings.pagesize, page: 0 } : undefined,
};
setPagination(newPaginationSettings);
};
const handlePaginationModelChange = React.useCallback((newModel: GridPaginationModel) => {
setPagination((prev) => ({
...prev,
paginationModel: newModel,
}));
}, []);
return (
<Frame>
<Frame.Demo sx={{ p: 2 }}>
<XGridGlobalStyles selector="#data-grid-full" pro />
<Paper
id="data-grid-full"
variant="outlined"
sx={[
{
overflow: 'auto',
borderRadius: '8px',
height: 328,
'& .MuiDataGrid-root': {
bgcolor: '#fff',
'& .MuiAvatar-root': { width: 24, height: 24, fontSize: 14, fontWeight: 'bold' },
'& .MuiButton-root': { marginLeft: 0, marginRight: 1 },
'& .MuiDataGrid-cell': {
bgcolor: 'grey.50',
},
'& .MuiChip-root.Rejected': {
color: red[800],
backgroundColor: red[50],
borderColor: red[100],
},
'& .MuiChip-root.Filled': {
color: green[800],
backgroundColor: green[50],
borderColor: green[100],
},
'& .MuiChip-root.Open': {
color: blue[800],
backgroundColor: blue[50],
borderColor: blue[100],
},
'& .MuiChip-root.PartiallyFilled': {
color: 'text.secondary',
backgroundColor: yellow[50],
borderColor: yellow[600],
},
'& .MuiDataGrid-footerContainer': {
minHeight: 48,
borderTop: '1px solid',
borderColor: 'grey.200',
},
'& .MuiTablePagination-root': {
fontSize: '0.75rem',
'& p': {
fontSize: '0.75rem',
},
'& .MuiToolbar-root': {
minHeight: 48,
},
},
},
},
(theme) =>
theme.applyDarkStyles({
'& .MuiDataGrid-root': {
bgcolor: 'primaryDark.900',
'& .MuiDataGrid-cell': {
bgcolor: 'primaryDark.800',
},
'& .MuiDataGrid-footerContainer': {
borderColor: 'primaryDark.600',
},
'& .MuiChip-root.Rejected': {
color: red[200],
backgroundColor: alpha(red[900], 0.2),
borderColor: alpha(red[700], 0.5),
},
'& .MuiChip-root.Filled': {
color: green[200],
backgroundColor: alpha(green[900], 0.2),
borderColor: alpha(green[700], 0.5),
},
'& .MuiChip-root.Open': {
color: blue[200],
backgroundColor: alpha(blue[900], 0.2),
borderColor: alpha(blue[700], 0.5),
},
'& .MuiChip-root.PartiallyFilled': {
color: yellow[200],
backgroundColor: alpha(yellow[900], 0.2),
borderColor: alpha(yellow[700], 0.2),
},
},
}),
]}
>
<DataGridPro
density="compact"
{...data}
components={{
Toolbar: GridToolbar,
}}
loading={loading}
checkboxSelection
disableRowSelectionOnClick
pageSizeOptions={pageSizeOptions}
{...pagination}
onPaginationModelChange={handlePaginationModelChange}
/>
</Paper>
</Frame.Demo>
<Frame.Info data-mui-color-scheme="dark" sx={{ pl: 1, pr: 2, py: 1.5 }}>
<SettingsPanel onApply={handleApplyClick} size={size} type={type} />
</Frame.Info>
</Frame>
);
}
| 5,205 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XHero.tsx | import * as React from 'react';
import { red, green, yellow, blue } from '@mui/material/colors';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import { StaticDateRangePicker } from '@mui/x-date-pickers-pro/StaticDateRangePicker';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { alpha } from '@mui/material/styles';
import {
DataGridPremium,
useGridApiRef,
useKeepGroupedColumnsHidden,
} from '@mui/x-data-grid-premium';
import { useDemoData } from '@mui/x-data-grid-generator';
import GradientText from 'docs/src/components/typography/GradientText';
import GetStartedButtons from 'docs/src/components/home/GetStartedButtons';
import HeroContainer from 'docs/src/layouts/HeroContainer';
import IconImage from 'docs/src/components/icon/IconImage';
import FolderTreeView from 'docs/src/components/showcase/FolderTreeView';
import ROUTES from 'docs/src/route';
const startDate = new Date();
startDate.setDate(10);
const endDate = new Date();
endDate.setDate(endDate.getDate() + 28);
const visibleFields = [
'commodity',
'unitPrice',
'feeRate',
'quantity',
'filledQuantity',
'isFilled',
'traderName',
'status',
'totalPrice',
];
export default function XHero() {
const { loading, data } = useDemoData({
dataSet: 'Commodity',
rowLength: 10000,
editable: true,
visibleFields,
});
const apiRef = useGridApiRef();
const sortedColumns = React.useMemo(() => {
return [...data.columns].sort((a, b) => {
return visibleFields.indexOf(a.field) - visibleFields.indexOf(b.field);
});
}, [data.columns]);
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
...data.initialState,
rowGrouping: {
model: ['commodity'],
},
aggregation: {
model: {
quantity: 'sum',
unitPrice: 'avg',
feeRate: 'min',
totalPrice: 'max',
},
},
},
});
const groupingColDef = React.useMemo(
() => ({
headerClassName: 'grouping-column-header',
}),
[],
);
let rowGroupingCounter = 0;
const isGroupExpandedByDefault = React.useCallback(() => {
// eslint-disable-next-line react-hooks/exhaustive-deps
rowGroupingCounter += 1;
return rowGroupingCounter === 3;
}, []);
return (
<HeroContainer
linearGradient
left={
<Box sx={{ textAlign: { xs: 'center', md: 'left' } }}>
<Typography
fontWeight="bold"
variant="body2"
sx={(theme) => ({
color: 'primary.600',
display: 'flex',
alignItems: 'center',
justifyContent: { xs: 'center', md: 'flex-start' },
'& > *': { mr: 1 },
...theme.applyDarkStyles({
color: 'primary.400',
}),
})}
>
<IconImage width={28} height={28} loading="eager" name="product-advanced" /> MUI X
</Typography>
<Typography variant="h1" sx={{ my: 2, maxWidth: 500 }}>
Performant
<br />
<GradientText>advanced</GradientText>
<br /> components
</Typography>
<Typography color="text.secondary" sx={{ mb: 3, maxWidth: 500 }}>
Build complex and data-rich applications using a growing list of advanced React
components. We're kicking it off with the most powerful Data Grid on the market.
</Typography>
<GetStartedButtons
primaryUrl={ROUTES.advancedComponents}
sx={{ justifyContent: { xs: 'center', md: 'flex-start' } }}
/>
</Box>
}
rightSx={{
p: { md: 2, lg: 3, xl: 4 },
overflow: 'hidden', // the components on the Hero section are mostly illustrative, even though they're interactive. That's why scrolling is disabled.
}}
right={
<React.Fragment>
<Paper
sx={(theme) => ({
backgroundColor: '#fff',
border: '1px solid',
borderColor: 'grey.200',
boxShadow: '0px 4px 20px rgba(170, 180, 190, 0.3)',
mb: { md: 2, lg: 3, xl: 4 },
overflow: 'hidden',
...theme.applyDarkStyles({
backgroundColor: 'primaryDark.800',
borderColor: 'primaryDark.600',
boxShadow: '0px 4px 20px rgba(0, 0, 0, 0.3)',
}),
})}
>
<Box
sx={(theme) => ({
textAlign: 'center',
py: 1.5,
position: 'relative',
borderRadius: 0,
borderBottom: '1px solid',
borderColor: 'grey.200',
...theme.applyDarkStyles({
borderColor: 'primaryDark.600',
}),
})}
>
<Typography fontWeight={500}>Trades, March 2023</Typography>
</Box>
<Box
sx={[
{
height: { md: 300, xl: 370 },
'& .MuiDataGrid-root': {
borderRadius: 1,
border: 0,
color: 'text.secondary',
'& .MuiCheckbox-root': {
p: 0.5,
'& > svg': {
fontSize: '1.25rem',
},
},
'& .MuiDataGrid-columnHeaders': {
borderBottom: '1px solid',
borderColor: 'grey.200',
},
[`& .MuiDataGrid-columnHeader:focus, & .MuiDataGrid-columnHeader:focus-within`]:
{
outline: 'none',
},
'& .MuiDataGrid-columnHeaderTitleContainer': {
padding: 0,
color: 'text.primary',
},
'& .MuiDataGrid-columnHeaderTitle': {
flexGrow: 1,
fontSize: '0.875rem',
},
'& button, & button > svg': {
fontSize: 16,
},
'& .MuiDataGrid-cell': {
fontSize: '0.875rem',
color: 'text.secondary',
borderBottom: '1px solid',
borderColor: 'grey.200',
},
'& .MuiDataGrid-viewport': {
'& .MuiDataGrid-cell': {
fontSize: '0.875rem',
color: 'text.secondary',
},
'& .MuiInputBase-input': {
fontSize: '0.875rem',
px: 0.5,
},
},
'& .MuiChip-root.Rejected': {
color: red[800],
backgroundColor: red[50],
borderColor: red[100],
},
'& .MuiChip-root.Filled': {
color: green[800],
backgroundColor: green[50],
borderColor: green[100],
},
'& .MuiChip-root.Open': {
color: blue[800],
backgroundColor: blue[50],
borderColor: blue[100],
},
'& .MuiChip-root.PartiallyFilled': {
color: 'text.secondary',
backgroundColor: yellow[50],
borderColor: yellow[600],
},
'& .grouping-column-header': {
pl: 6,
},
},
},
(theme) =>
theme.applyDarkStyles({
'& .MuiDataGrid-root': {
'& .MuiDataGrid-columnHeaders': {
borderColor: 'primaryDark.600',
},
'& .MuiDataGrid-cell': {
borderColor: alpha(theme.palette.primaryDark[600], 0.5),
},
'& .MuiChip-root.Rejected': {
color: red[200],
backgroundColor: alpha(red[900], 0.2),
borderColor: alpha(red[700], 0.5),
},
'& .MuiChip-root.Filled': {
color: green[200],
backgroundColor: alpha(green[900], 0.2),
borderColor: alpha(green[700], 0.5),
},
'& .MuiChip-root.Open': {
color: blue[200],
backgroundColor: alpha(blue[900], 0.2),
borderColor: alpha(blue[700], 0.5),
},
'& .MuiChip-root.PartiallyFilled': {
color: yellow[200],
backgroundColor: alpha(yellow[900], 0.2),
borderColor: alpha(yellow[700], 0.2),
},
},
}),
]}
>
<DataGridPremium
{...data}
columns={sortedColumns}
apiRef={apiRef}
initialState={initialState}
disableRowSelectionOnClick
groupingColDef={groupingColDef}
rowHeight={36}
columnHeaderHeight={48}
hideFooter
loading={loading}
isGroupExpandedByDefault={isGroupExpandedByDefault}
/>
</Box>
</Paper>
<Box
sx={{
display: 'flex',
overflow: { md: 'auto', xl: 'unset' },
m: { md: -2, lg: -3, xl: 0 },
p: { md: 2, lg: 3, xl: 0 },
}}
>
<Paper
sx={(theme) => ({
backgroundColor: '#fff',
border: '1px solid',
borderColor: 'grey.200',
boxShadow: '0px 4px 20px rgba(170, 180, 190, 0.3)',
...theme.applyDarkStyles({
backgroundColor: 'primaryDark.800',
borderColor: 'primaryDark.600',
boxShadow: '0px 4px 20px rgba(0, 0, 0, 0.3)',
}),
minWidth: 300,
mr: { md: 2, lg: 3, xl: 4 },
flexGrow: 1,
})}
>
<Typography fontWeight={500} p={2}>
Cool UI project
</Typography>
<Divider />
<FolderTreeView />
</Paper>
<Paper
sx={[
{
border: '1px solid',
borderColor: 'grey.200',
boxShadow: '0px 4px 20px rgba(170, 180, 190, 0.3)',
'& > div': {
borderRadius: 1,
overflow: 'auto',
backgroundColor: 'initial',
},
'& .MuiTypography-subtitle1': {
fontSize: '0.875rem',
},
'& .MuiTypography-caption': {
width: { xs: 28, xl: 32 },
height: 32,
},
'& .MuiPickersSlideTransition-root': {
minWidth: { xs: 268, xl: 300 },
minHeight: { xs: 238, xl: 288 },
},
'& [role="row"]': {
margin: { xs: '4px 0', xl: '6px 0' },
},
'& .MuiPickersArrowSwitcher-root': {
padding: 1,
},
'& .MuiDateRangePickerDay-root': {
lineHeight: 0,
margin: 0,
},
'& .MuiPickersDay-root': {
width: { xs: 28, xl: 32 },
height: { xs: 28, xl: 32 },
fontWeight: 400,
},
'& .MuiDateRangePickerDay-day.Mui-selected': {
fontWeight: 600,
},
'& .MuiDateRangePickerDay-day:not(.Mui-selected)': {
borderColor: 'primary.300',
},
},
(theme) =>
theme.applyDarkStyles({
borderColor: 'primaryDark.600',
boxShadow: '0px 4px 20px rgba(0, 0, 0, 0.3)',
'& > div': {
backgroundColor: 'primaryDark.800',
},
'& .MuiDateRangePickerDay-day.Mui-selected': {
color: '#FFF',
},
}),
]}
>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<StaticDateRangePicker
displayStaticWrapperAs="desktop"
value={[startDate, endDate]}
/>
</LocalizationProvider>
</Paper>
</Box>
</React.Fragment>
}
/>
);
}
| 5,206 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XPlans.tsx | import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import KeyboardArrowRightRounded from '@mui/icons-material/KeyboardArrowRightRounded';
import Section from 'docs/src/layouts/Section';
import SectionHeadline from 'docs/src/components/typography/SectionHeadline';
import GradientText from 'docs/src/components/typography/GradientText';
import Link from 'docs/src/modules/components/Link';
import ROUTES from 'docs/src/route';
import Frame from 'docs/src/components/action/Frame';
const Image = styled('img')(({ theme }) => ({
filter: 'drop-shadow(-8px 4px 20px rgba(61, 71, 82, 0.1))',
transition: '0.3s',
display: 'block',
height: 'auto',
borderRadius: '8px',
...theme.applyDarkStyles({
filter: 'drop-shadow(-8px 4px 20px rgba(0, 0, 0, 0.4))',
}),
}));
export default function XPlans() {
return (
<Section cozy>
<Grid container spacing={2} alignItems="center">
<Grid item md={6} sx={{ minWidth: 0 }}>
<Box maxWidth={500} sx={{ mb: { xs: 2, sm: 0 } }}>
<SectionHeadline
overline="Plans"
title={
<Typography variant="h2">
Available with <GradientText>MIT and commercial licenses</GradientText>
</Typography>
}
description="MUI X components are available under two licenses: MIT for the free community version, and commercial for Pro and Premium plans."
/>
<Button
component={Link}
href={ROUTES.pricing}
noLinkStyle
size="large"
variant="contained"
endIcon={<KeyboardArrowRightRounded />}
sx={{ width: { xs: '100%', sm: 'auto' } }}
>
Compare plans
</Button>
</Box>
</Grid>
<Grid item xs={12} md={6}>
<Frame>
<Frame.Demo
sx={{
overflow: 'hidden',
height: { xs: 240, sm: 390 },
perspective: '1000px',
}}
>
<Image
src={`/static/branding/mui-x/Mocktable-light.png`}
alt="Illustration of MUI's pricing page."
loading="lazy"
width="300"
sx={(theme) => ({
width: { sm: 480 },
position: 'absolute',
left: '50%',
top: '50%',
transform: 'translate(-50%, -50%)',
...theme.applyDarkStyles({
content: 'url(/static/branding/mui-x/Mocktable-dark.png)',
}),
})}
/>
</Frame.Demo>
</Frame>
</Grid>
</Grid>
</Section>
);
}
| 5,207 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XRoadmap.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import KeyboardArrowRightRounded from '@mui/icons-material/KeyboardArrowRightRounded';
import TableChartRounded from '@mui/icons-material/TableChartRounded';
import DateRangeRounded from '@mui/icons-material/DateRangeRounded';
import AccountTreeRounded from '@mui/icons-material/AccountTreeRounded';
import ShowChartRounded from '@mui/icons-material/ShowChartRounded';
import BarChartRounded from '@mui/icons-material/BarChartRounded';
import FileUploadRounded from '@mui/icons-material/FileUploadRounded';
import PendingActionsRounded from '@mui/icons-material/PendingActions';
import InsertDriveFileOutlined from '@mui/icons-material/InsertDriveFileOutlined';
import SpeedRounded from '@mui/icons-material/SpeedRounded';
import { alpha } from '@mui/material/styles';
import ROUTES from 'docs/src/route';
import Link from 'docs/src/modules/components/Link';
import SectionHeadline from 'docs/src/components/typography/SectionHeadline';
import Section from 'docs/src/layouts/Section';
export default function XRoadmap() {
function renderList(content: React.ReactElement, nested?: boolean) {
return (
<Box
sx={{
mt: 2,
display: 'grid',
alignItems: 'center',
gap: 1.5,
gridTemplateColumns: 'max-content 1fr',
position: 'relative',
fontWeight: 'semiBold',
...(nested && {
'&:before': {
content: '""',
display: 'block',
position: 'absolute',
width: 1.5,
bgcolor: 'primaryDark.600',
top: 24,
bottom: 10,
left: 8,
},
}),
}}
>
{content}
</Box>
);
}
const bullet = (
<Box
sx={{
ml: 1,
mr: -2,
display: 'flex',
alignItems: 'center',
'&:before': {
content: '""',
display: 'block',
height: 1.5,
width: 15,
bgcolor: 'primaryDark.600',
},
}}
/>
);
return (
<Section
cozy
data-mui-color-scheme="dark"
sx={{
color: 'text.secondary',
background: (theme) =>
`linear-gradient(180deg, ${(theme.vars || theme).palette.primaryDark[800]} 50%,
${alpha(theme.palette.primary[800], 0.2)} 100%), ${
(theme.vars || theme).palette.primaryDark[800]
}`,
}}
>
<Grid container spacing={2} alignItems="center" justifyContent="space-between">
<Grid item xs={12} md={5}>
<SectionHeadline
overline="Roadmap"
title="Follow the MUI X roadmap for future updates"
description="It's just the beginning of the MUI X components. Stay tuned for the exciting news and updates coming soon!"
/>
<Button
component={Link}
href={ROUTES.xRoadmap}
noLinkStyle
size="large"
variant="contained"
endIcon={<KeyboardArrowRightRounded />}
sx={{ width: { xs: '100%', sm: 'auto' } }}
>
See the roadmap
</Button>
</Grid>
<Grid
item
xs={12}
md={7}
lg="auto"
container
spacing={2}
sx={{
typography: 'body2',
'& .MuiPaper-root': {
p: 2,
minWidth: { lg: 180 },
},
'& svg': {
color: 'primary.300',
},
}}
>
<Grid item xs={12} sm={4} lg="auto">
<Paper variant="outlined">
<Typography fontWeight="bold" variant="body2" color="text.primary">
Released
<Box
sx={{
ml: 1,
display: 'inline-block',
width: 8,
height: 8,
borderRadius: 10,
bgcolor: 'success.main',
}}
/>
</Typography>
{renderList(
<React.Fragment>
<TableChartRounded sx={{ fontSize: 16 }} />
Data Grid
<DateRangeRounded sx={{ fontSize: 16 }} />
Date and Time Pickers
<BarChartRounded sx={{ fontSize: 16 }} />
Charts
<AccountTreeRounded sx={{ fontSize: 16 }} />
Tree View
</React.Fragment>,
)}
</Paper>
</Grid>
<Grid item xs={12} sm={4} lg="auto">
<Paper variant="outlined">
<Typography fontWeight="bold" variant="body2" color="text.primary">
Work in progress
<Box
sx={{
ml: 1,
display: 'inline-block',
width: 8,
height: 8,
borderRadius: 10,
bgcolor: 'warning.main',
}}
/>
</Typography>
{renderList(
<React.Fragment>
<Box
sx={{
lineHeight: 0,
}}
>
<TableChartRounded sx={{ fontSize: 16 }} />
</Box>
Data Grid
{bullet}
Pivoting
{bullet}
Charts integration
{bullet}
<Link href={ROUTES.dataGridFeaturesComparison} sx={{ color: 'primary.300' }}>
And more!
</Link>
</React.Fragment>,
true,
)}
{renderList(
<React.Fragment>
<Box
sx={{
lineHeight: 0,
}}
>
<AccountTreeRounded sx={{ fontSize: 16 }} />
</Box>
Tree View
{bullet}
Virtualization
{bullet}
Drag and Drop
</React.Fragment>,
true,
)}
</Paper>
</Grid>
<Grid item xs={12} sm={4} lg="auto">
<Paper variant="outlined">
<Typography fontWeight="bold" variant="body2" color="text.primary">
Sometime soon
<Box
sx={{
ml: 1,
display: 'inline-block',
width: 8,
height: 8,
borderRadius: 10,
bgcolor: 'primaryDark.400',
}}
/>
</Typography>
{renderList(
<React.Fragment>
<ShowChartRounded sx={{ fontSize: 16 }} />
Sparkline
<InsertDriveFileOutlined sx={{ fontSize: 16 }} />
Rich Text Editor
<FileUploadRounded sx={{ fontSize: 16 }} />
Upload
<PendingActionsRounded sx={{ fontSize: 16 }} />
Scheduler
<SpeedRounded sx={{ fontSize: 16 }} />
Gauge
</React.Fragment>,
)}
</Paper>
</Grid>
</Grid>
</Grid>
</Section>
);
}
| 5,208 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XSparklineDemo.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Chip from '@mui/material/Chip';
import { styled } from '@mui/material/styles';
import { shouldForwardProp } from '@mui/system';
import EmailSubscribe from 'docs/src/components/footer/EmailSubscribe';
import Frame from 'docs/src/components/action/Frame';
const AspectRatioImage = styled('div', {
shouldForwardProp: (prop) => shouldForwardProp(prop) && prop !== 'src' && prop !== 'ratio',
})<{ ratio: number; src: string }>(({ src, ratio, theme }) => ({
height: 0,
backgroundImage: `url(${src})`,
backgroundRepeat: 'no-repeat',
backgroundSize: 'contain',
paddingBottom: `${(1 / ratio) * 100}%`,
margin: 'auto',
...theme.applyDarkStyles({
backgroundImage: `url(${src.replace('-light', '-dark')})`,
}),
}));
export default function XSparklineDemo() {
return (
<Box sx={{ height: '100%' }}>
<Frame sx={{ height: '100%' }}>
<Frame.Demo sx={{ p: 2, flexGrow: 1 }}>
<Grid container justifyContent="space-around" spacing={1}>
<Grid item xs={6}>
<Box sx={{ maxWidth: 200, ml: 'auto' }}>
<AspectRatioImage
src="/static/branding/mui-x/sparkline-light1.png"
ratio={211 / 220}
/>
</Box>
</Grid>
<Grid item xs={6}>
<Box sx={{ maxWidth: 200, mr: 'auto' }}>
<AspectRatioImage
src="/static/branding/mui-x/sparkline-light2.png"
ratio={211 / 220}
/>
</Box>
</Grid>
</Grid>
</Frame.Demo>
<Frame.Info data-mui-color-scheme="dark">
<Box
sx={{
display: 'flex',
alignItems: 'center',
lineHeight: 1,
mb: 0.5,
}}
>
<Typography variant="body2" fontWeight="bold" sx={{ mr: 1 }}>
Coming soon!
</Typography>
<Chip variant="outlined" label="PNG Preview" size="small" sx={{ fontWeight: 500 }} />
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Subscribe to our newsletter to get first-hand info about the development and release of
new components.
</Typography>
<EmailSubscribe />
</Frame.Info>
</Frame>
</Box>
);
}
| 5,209 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XTheming.tsx | import * as React from 'react';
import {
DataGridPro,
GridColDef,
GridCellParams,
GridRenderEditCellParams,
} from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';
import { Experimental_CssVarsProvider as CssVarsProvider } from '@mui/material/styles';
import { red } from '@mui/material/colors';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Section from 'docs/src/layouts/Section';
import SectionHeadline from 'docs/src/components/typography/SectionHeadline';
import GradientText from 'docs/src/components/typography/GradientText';
import Item, { Group } from 'docs/src/components/action/Item';
import Highlighter from 'docs/src/components/action/Highlighter';
import SvgTwinkle from 'docs/src/icons/SvgTwinkle';
import SvgMaterialDesign from 'docs/src/icons/SvgMaterialDesign';
import XGridGlobalStyles from 'docs/src/components/home/XGridGlobalStyles';
import ProgressBar from 'docs/src/components/x-grid/ProgressBar';
import EditProgress from 'docs/src/components/x-grid/EditProgress';
import Status from 'docs/src/components/x-grid/Status';
import EditStatus from 'docs/src/components/x-grid/EditStatus';
const dataGridStyleOverrides = <XGridGlobalStyles selector="#data-grid-theming" pro />;
export default function XTheming() {
const [customized, setCustomized] = React.useState(true);
const { loading, data } = useDemoData({
dataSet: 'Commodity',
rowLength: 1000,
maxColumns: 40,
editable: true,
});
const baseFilledQuantityCol = data.columns.find(({ field }) => field === 'filledQuantity');
const baseStatusCol = data.columns.find(({ field }) => field === 'status');
function getColumns() {
const columns: Array<GridColDef> = [
{
field: 'desk',
headerName: 'desk',
width: customized ? 72 : 100,
sortable: false,
editable: true,
},
{
field: 'commodity',
headerName: 'Commodity',
width: customized ? 132 : 160,
editable: true,
},
{
field: 'traderName',
headerName: 'Trader Name',
width: customized ? 148 : 172,
editable: true,
},
{
field: 'filledQuantity',
headerName: 'Filled',
...baseFilledQuantityCol,
width: customized ? 130 : 150,
sortable: false,
editable: true,
...(customized && {
renderCell: (params: GridCellParams) => {
return <ProgressBar value={Number(params.value)!} />;
},
renderEditCell: (params: GridRenderEditCellParams) => {
return <EditProgress {...params} />;
},
}),
},
{
field: 'status',
headerName: 'Status',
...baseStatusCol,
width: 150,
sortable: false,
editable: true,
...(customized && {
renderCell: (params: GridCellParams) => {
return <Status status={(params.value || '').toString()} />;
},
renderEditCell: (params: GridRenderEditCellParams) => {
return <EditStatus {...params} />;
},
}),
},
];
return columns;
}
return (
<Section bg="gradient">
<Grid container spacing={2}>
<Grid item md={6} sx={{ minWidth: 0 }}>
<SectionHeadline
overline="Theming"
title={
<Typography variant="h2">
Advanced and <GradientText>beautiful</GradientText>
</Typography>
}
description="Use the sophisticated theming features to make the MUI X components look exactly as you want."
/>
<Group sx={{ m: -2, p: 2 }}>
<Highlighter disableBorder selected={customized} onClick={() => setCustomized(true)}>
<Item
icon={<SvgTwinkle />}
title="Custom theme"
description="Theming allows you to use your brand's design tokens, easily making the components reflect its look and feel."
/>
</Highlighter>
<Highlighter disableBorder selected={!customized} onClick={() => setCustomized(false)}>
<Item
icon={<SvgMaterialDesign />}
title="Material Design"
description="Every component comes with Google's tried and tested design system ready for use."
/>
</Highlighter>
</Group>
</Grid>
<Grid item xs={12} md={6}>
{customized ? (
<Paper
id="data-grid-theming"
variant="outlined"
sx={(theme) => ({
height: 418,
borderColor: 'grey.200',
...theme.applyDarkStyles({
borderColor: 'primaryDark.600',
}),
})}
>
{dataGridStyleOverrides}
<DataGridPro
{...data}
columns={getColumns()}
disableRowSelectionOnClick
checkboxSelection
loading={loading}
pagination
density="compact"
/>
</Paper>
) : (
<CssVarsProvider>
<Paper
elevation={0}
sx={[
{
height: 418,
'& .MuiDataGrid-cell[data-field="status"][data-value="Rejected"]': {
'& .MuiChip-root': {
color: red[500],
},
},
},
(theme) =>
theme.applyDarkStyles({
'& .MuiDataGrid-cell[data-field="status"][data-value="Rejected"]': {
'& .MuiChip-root': {
color: red[300],
},
},
}),
]}
>
<DataGridPro
{...data}
columns={getColumns()}
disableRowSelectionOnClick
checkboxSelection
loading={loading}
pagination
density="compact"
/>
</Paper>
</CssVarsProvider>
)}
</Grid>
</Grid>
</Section>
);
}
| 5,210 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/productX/XTreeViewDemo.tsx | import * as React from 'react';
import clsx from 'clsx';
import { styled, alpha } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Chip from '@mui/material/Chip';
import { TreeView } from '@mui/x-tree-view/TreeView';
import {
TreeItem as MuiTreeItem,
useTreeItem,
TreeItemProps,
TreeItemContentProps,
} from '@mui/x-tree-view/TreeItem';
import Typography from '@mui/material/Typography';
import FolderRounded from '@mui/icons-material/FolderRounded';
import FolderOpenRounded from '@mui/icons-material/FolderOpenRounded';
import PhotoOutlined from '@mui/icons-material/PhotoOutlined';
import PictureAsPdfOutlined from '@mui/icons-material/PictureAsPdfOutlined';
import VideocamOutlined from '@mui/icons-material/VideocamOutlined';
import FourKOutlined from '@mui/icons-material/FourKOutlined';
import Button from '@mui/material/Button';
import Frame from 'docs/src/components/action/Frame';
const CustomContent = React.forwardRef(function CustomContent(
props: TreeItemContentProps & { lastNestedChild?: boolean },
ref,
) {
const {
lastNestedChild,
classes,
className,
label,
nodeId,
icon: iconProp,
expansionIcon,
displayIcon,
} = props;
const {
disabled,
expanded,
selected,
focused,
handleExpansion,
handleSelection,
preventSelection,
} = useTreeItem(nodeId);
const icon = iconProp || expansionIcon || displayIcon;
const handleMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
preventSelection(event);
};
const handleExpansionClick = (event: React.MouseEvent<HTMLDivElement>) => {
handleExpansion(event);
handleSelection(event);
};
const handleSelectionClick = (event: React.MouseEvent<HTMLDivElement>) => {
handleSelection(event);
};
const renderExtension = () => {
if (typeof label !== 'string') {
return label;
}
const extension = (label || '').split('.').slice(-1)[0];
if (extension.match(/(jpg|jpeg|png)/)) {
return <PhotoOutlined />;
}
if (extension === 'pdf') {
return <PictureAsPdfOutlined />;
}
if (extension === 'mp4') {
return <VideocamOutlined />;
}
if (extension === 'mkv') {
return <FourKOutlined />;
}
return (
<Box
sx={{
width: 6,
height: 6,
borderRadius: '50%',
bgcolor: 'warning.main',
display: 'inline-block',
verticalAlign: 'middle',
zIndex: 1,
}}
/>
);
};
return (
/* @ts-ignore -- Key event is handled by the TreeView */
<Box
className={clsx(className, classes.root, {
[classes.expanded]: expanded,
[classes.selected]: selected,
[classes.focused]: focused,
[classes.disabled]: disabled,
'CustomContent-last': lastNestedChild,
})}
onClick={handleExpansionClick}
onMouseDown={handleMouseDown}
ref={ref as React.Ref<HTMLButtonElement>}
sx={{
border: 'none',
borderRadius: '5px',
textAlign: 'left',
position: 'relative',
zIndex: 1,
'& svg': {
fontSize: 18,
color: nodeId.startsWith('root') ? 'primary.main' : 'grey.600',
},
'&:not(.CustomContent-last)': {
'& svg': {
'&:first-of-type': {
fontSize: 14,
color: 'primary.main',
},
},
},
}}
>
{icon}
{lastNestedChild && renderExtension()}
{!lastNestedChild && (expanded ? <FolderOpenRounded /> : <FolderRounded />)}
<Typography
onClick={handleSelectionClick}
component="div"
className={classes.label}
noWrap
sx={{
'&&': {
color: lastNestedChild ? 'text.secondary' : 'text.primary',
fontWeight: lastNestedChild ? 400 : 500,
},
}}
>
{label}
</Typography>
</Box>
);
});
const StyledTreeItem = styled(MuiTreeItem)(({ theme }) => [
{
paddingTop: 5,
'& .MuiTreeItem-content .MuiTreeItem-label': {
paddingLeft: theme.spacing(0.75),
},
'& .MuiTreeItem-root': {
position: 'relative',
'&:before': {
content: '""',
display: 'block',
position: 'absolute',
left: -14,
height: '100%',
width: 1.5,
backgroundColor: (theme.vars || theme).palette.grey[100],
},
},
'& .MuiTreeItem-content': {
padding: theme.spacing('2px', 0.5),
},
'& .MuiTreeItem-group': {
marginLeft: 0,
paddingLeft: theme.spacing(3),
},
},
theme.applyDarkStyles({
'& .MuiTreeItem-root': {
'&:before': {
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
},
},
'& .MuiTreeItem-group': {
'& .MuiTreeItem-content': {
'&:before': {
backgroundColor: (theme.vars || theme).palette.primaryDark[500],
},
},
},
}),
]);
const TreeItem = React.forwardRef(function TreeItem(
props: TreeItemProps & {
ContentProps?: { lastNestedChild?: boolean };
},
ref: React.Ref<HTMLLIElement>,
) {
return <StyledTreeItem ContentComponent={CustomContent} {...props} ref={ref} />;
});
export default function XDateRangeDemo() {
return (
<Frame>
<Frame.Demo sx={{ p: 2, flexGrow: 1 }}>
<Paper
variant="outlined"
sx={(theme) => ({
maxWidth: '100%',
mx: 'auto',
bgcolor: '#fff',
...theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
}),
})}
>
<TreeView
aria-label="file system navigator"
defaultExpanded={['2', '2.3', '3']}
sx={{ height: { xs: 260, sm: 300 }, overflowY: 'auto', p: 1 }}
>
<TreeItem nodeId="1" label="Drive">
<TreeItem nodeId="1.1" label="Backup">
<TreeItem
nodeId="1.1.1"
label="Jan 2021.pdf"
ContentProps={{ lastNestedChild: true }}
/>
<TreeItem
nodeId="1.1.2"
label="Feb 2021.pdf"
ContentProps={{ lastNestedChild: true }}
/>
<TreeItem
nodeId="1.1.3"
label="Mar 2021.pdf"
ContentProps={{ lastNestedChild: true }}
/>
</TreeItem>
<TreeItem nodeId="1.2" label="Photos">
<TreeItem
nodeId="1.2.1"
label="family.jpeg"
ContentProps={{ lastNestedChild: true }}
/>
<TreeItem
nodeId="1.2.2"
label="my_dogpng"
ContentProps={{ lastNestedChild: true }}
/>
</TreeItem>
</TreeItem>
<TreeItem nodeId="2" label="Favorite">
<TreeItem
nodeId="2.1"
label="MUI_retreat_photo.jpg"
ContentProps={{ lastNestedChild: true }}
/>
<TreeItem
nodeId="2.2"
label="v6_secrets.mkv"
ContentProps={{ lastNestedChild: true }}
/>
<TreeItem nodeId="2.3" label="Other pictures">
<TreeItem
nodeId="2.3.1"
label="my_avatar.jpg"
ContentProps={{ lastNestedChild: true }}
/>
</TreeItem>
</TreeItem>
</TreeView>
</Paper>
</Frame.Demo>
<Frame.Info data-mui-color-scheme="dark">
<Box
sx={{
display: 'flex',
alignItems: 'center',
lineHeight: 1,
mb: 0.5,
}}
>
<Typography variant="body2" fontWeight="bold" sx={{ mr: 1 }}>
Experiment with the Tree View now!
</Typography>
<Chip
variant="outlined"
label="Alpha"
color="warning"
size="small"
sx={(theme) => ({
pb: 0.2,
fontWeight: theme.typography.fontWeightSemiBold,
color: (theme.vars || theme).palette.warning[300],
borderColor: alpha(theme.palette.warning[300], 0.3),
background: alpha(theme.palette.warning[800], 0.3),
})}
/>
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Play with the component and let us know what you think!
</Typography>
<Button
variant="outlined"
href="/x/react-tree-view"
component="a"
sx={{ mt: { xs: 2, sm: 0 }, color: 'primary.300' }}
>
View the documentation
</Button>
</Frame.Info>
</Frame>
);
}
| 5,211 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/FolderTable.tsx | import * as React from 'react';
import { Theme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableSortLabel from '@mui/material/TableSortLabel';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import { visuallyHidden } from '@mui/utils';
import Folder from '@mui/icons-material/Folder';
const data = [
{ name: 'Typography', size: 125600 },
{ name: 'Pictures & videos', size: 134000000 },
{ name: 'Source files', size: 200000000 },
{ name: 'Dependencies', size: 44000000 },
{ name: 'Assets & illustrations', size: 21000000 },
{ name: 'Components', size: 11000 },
];
type Data = typeof data extends Array<infer T> ? T : never;
type Order = 'asc' | 'desc';
function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
function getComparator<Key extends keyof any>(
order: Order,
orderBy: Key,
): (a: { [key in Key]: number | string }, b: { [key in Key]: number | string }) => number {
return order === 'desc'
? (a, b) => descendingComparator(a, b, orderBy)
: (a, b) => -descendingComparator(a, b, orderBy);
}
// Since 2020 all major browsers ensure sort stability with Array.prototype.sort().
// stableSort() brings sort stability to non-modern browsers (notably IE11). If you
// only support modern browsers you can replace stableSort(exampleArray, exampleComparator)
// with exampleArray.slice().sort(exampleComparator)
function stableSort<T>(array: readonly T[], comparator: (a: T, b: T) => number) {
const stabilizedThis = array.map((el, index) => [el, index] as [T, number]);
stabilizedThis.sort((a, b) => {
const order = comparator(a[0], b[0]);
if (order !== 0) {
return order;
}
return a[1] - b[1];
});
return stabilizedThis.map((el) => el[0]);
}
function formatSize(size: number) {
const kb = size / 1000;
if (kb < 1000) {
return `${kb.toFixed(1)} kB`;
}
return `${(kb / 1000).toFixed(0)} MB`;
}
export default function BasicTable() {
const [order, setOrder] = React.useState<Order>('asc');
const [orderBy, setOrderBy] = React.useState<keyof Data>('name');
const handleRequestSort = (event: React.MouseEvent<unknown>, property: keyof Data) => {
const isAsc = orderBy === property && order === 'asc';
setOrder(isAsc ? 'desc' : 'asc');
setOrderBy(property);
};
const createSortHandler = (property: keyof Data) => (event: React.MouseEvent<unknown>) => {
handleRequestSort(event, property);
};
const headCells = [
{ id: 'name', label: 'Name', TableCellProps: {} },
{ id: 'size', label: 'Size', TableCellProps: { align: 'right' } },
] as const;
return (
<TableContainer
component={Paper}
variant="outlined"
sx={[
{
maxWidth: 260,
[`& .${tableCellClasses.root}`]: {
borderColor: 'grey.200',
},
[`& .${tableCellClasses.sizeSmall}`]: {
padding: '0.625rem 1rem',
},
},
(theme) =>
theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
borderColor: 'primaryDark.700',
[`& .${tableCellClasses.root}`]: {
borderColor: 'primaryDark.700',
},
}),
]}
>
<Table aria-label="folder table" size="small">
<TableHead>
<TableRow>
{headCells.map((headCell) => (
<TableCell
key={headCell.id}
sortDirection={orderBy === headCell.id ? order : false}
{...headCell.TableCellProps}
>
<TableSortLabel
active={orderBy === headCell.id}
direction={orderBy === headCell.id ? order : 'asc'}
onClick={createSortHandler(headCell.id)}
sx={{ fontSize: '0.75rem', color: 'text.secondary' }}
>
{headCell.label}
{orderBy === headCell.id ? (
<Box component="span" sx={visuallyHidden}>
{order === 'desc' ? 'sorted descending' : 'sorted ascending'}
</Box>
) : null}
</TableSortLabel>
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{stableSort(data, getComparator(order, orderBy)).map((row) => (
<TableRow key={row.name} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
<TableCell component="th" scope="row">
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Folder fontSize="small" sx={{ color: 'primary.400' }} />
<Typography fontSize={13} fontWeight={500} color="text.primary">
{row.name}
</Typography>
</Box>
</TableCell>
<TableCell align="right">
<Typography
fontSize={13}
fontWeight={600}
sx={(theme: Theme) => ({
mr: 1,
color: 'success.700',
...theme.applyDarkStyles({
color: 'success.500',
}),
})}
>
{formatSize(row.size)}
</Typography>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
| 5,212 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/FolderTreeView.tsx | /* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
import * as React from 'react';
import clsx from 'clsx';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import { TreeView } from '@mui/x-tree-view/TreeView';
import {
TreeItem,
useTreeItem,
TreeItemProps,
TreeItemContentProps,
} from '@mui/x-tree-view/TreeItem';
import Typography from '@mui/material/Typography';
import KeyboardArrowDownRounded from '@mui/icons-material/KeyboardArrowDownRounded';
import KeyboardArrowUpRounded from '@mui/icons-material/KeyboardArrowUpRounded';
import FolderRounded from '@mui/icons-material/FolderRounded';
const CustomContent = React.forwardRef(function CustomContent(
props: TreeItemContentProps & { lastNestedChild?: boolean },
ref,
) {
const {
lastNestedChild,
classes,
className,
label,
nodeId,
icon: iconProp,
expansionIcon,
displayIcon,
} = props;
const {
disabled,
expanded,
selected,
focused,
handleExpansion,
handleSelection,
preventSelection,
} = useTreeItem(nodeId);
const icon = iconProp || expansionIcon || displayIcon;
const handleMouseDown = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
preventSelection(event);
};
const handleExpansionClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
handleExpansion(event);
};
const handleSelectionClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
handleSelection(event);
};
return (
<div
className={clsx(className, classes.root, {
[classes.expanded]: expanded,
[classes.selected]: selected,
[classes.focused]: focused,
[classes.disabled]: disabled,
})}
// @ts-ignore
onClick={handleExpansionClick}
// @ts-ignore
onMouseDown={handleMouseDown}
// @ts-ignore
ref={ref as React.Ref<HTMLButtonElement>}
>
{lastNestedChild ? (
<Box
sx={{
width: 6,
height: 6,
borderRadius: '50%',
bgcolor: 'warning.main',
display: 'inline-block',
verticalAlign: 'middle',
zIndex: 1,
}}
/>
) : (
<FolderRounded
sx={{
fontSize: 16,
color: nodeId === '1' ? 'primary.main' : 'grey.600',
}}
/>
)}
<Typography
onClick={handleSelectionClick}
component="div"
className={classes.label}
sx={{
'&&': {
color: lastNestedChild ? 'text.secondary' : 'text.primary',
fontWeight: lastNestedChild ? 400 : 500,
},
}}
>
{label}
</Typography>
{icon}
</div>
);
});
const StyledTreeItem = styled(TreeItem)(({ theme }) => [
{
'& .MuiTreeItem-content': {
border: 'none',
backgroundColor: 'transparent',
borderRadius: 5,
padding: theme.spacing(0.5),
textAlign: 'left',
position: 'relative',
zIndex: 1,
},
'& .MuiTreeItem-content .MuiTreeItem-label': {
paddingLeft: theme.spacing(1),
},
'& .MuiTreeItem-root': {
position: 'relative',
'&:before': {
content: '""',
display: 'block',
position: 'absolute',
left: -14,
height: '100%',
width: 1.5,
backgroundColor: (theme.vars || theme).palette.grey[200],
},
},
'& .MuiTreeItem-group': {
marginLeft: 0,
paddingLeft: theme.spacing(3),
},
},
theme.applyDarkStyles({
'& .MuiTreeItem-root': {
'&:before': {
backgroundColor: (theme.vars || theme).palette.primaryDark[600],
},
},
'& .MuiTreeItem-group': {
'& .MuiTreeItem-content': {
'&:before': {
backgroundColor: (theme.vars || theme).palette.primaryDark[600],
},
},
},
}),
]);
const CustomTreeItem = React.forwardRef(function CustomTreeItem(
props: TreeItemProps & {
ContentProps?: { lastNestedChild?: boolean };
},
ref: React.Ref<HTMLLIElement>,
) {
return <StyledTreeItem ContentComponent={CustomContent} {...props} ref={ref} />;
});
export default function FolderTreeView() {
return (
<TreeView
aria-label="folder"
defaultExpanded={['1', '2', '5']}
defaultCollapseIcon={<KeyboardArrowUpRounded sx={{ fontSize: 16, color: 'primary.main' }} />}
defaultExpandIcon={<KeyboardArrowDownRounded sx={{ fontSize: 16, color: 'grey.600' }} />}
defaultEndIcon={<div style={{ width: 24 }} />}
sx={{ p: 1, overflowY: 'auto' }}
>
<CustomTreeItem nodeId="1" label="src">
<CustomTreeItem nodeId="2" label="components">
<CustomTreeItem nodeId="3" label="Button.tsx" ContentProps={{ lastNestedChild: true }} />
<CustomTreeItem nodeId="4" label="Drawer.tsx" ContentProps={{ lastNestedChild: true }} />
<CustomTreeItem nodeId="5" label="Navbar.tsx" ContentProps={{ lastNestedChild: true }} />
<CustomTreeItem
nodeId="6"
label="TreeView.tsx"
ContentProps={{ lastNestedChild: true }}
/>
</CustomTreeItem>
<CustomTreeItem nodeId="7" label="blocks">
<CustomTreeItem
nodeId="8"
label="SignUpPage.tsx"
ContentProps={{ lastNestedChild: true }}
/>
<CustomTreeItem nodeId="9" label="PricingTable.tsx">
<CustomTreeItem
nodeId="10"
label="PaymentOptions.tsx"
ContentProps={{ lastNestedChild: true }}
/>
<CustomTreeItem
nodeId="11"
label="EarlyBirdDiscount.tsx"
ContentProps={{ lastNestedChild: true }}
/>
</CustomTreeItem>
</CustomTreeItem>
</CustomTreeItem>
</TreeView>
);
}
| 5,213 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/NotificationCard.tsx | import * as React from 'react';
import { alpha } from '@mui/material/styles';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Chip from '@mui/material/Chip';
import Fade from '@mui/material/Fade';
import Typography from '@mui/material/Typography';
export default function NotificationCard() {
return (
<Fade in timeout={700}>
<Card
variant="outlined"
sx={(theme) => ({
display: 'flex',
p: 2,
gap: 2,
maxWidth: 283,
...theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
borderColor: 'primaryDark.700',
}),
})}
>
<Box
sx={(theme) => ({
height: 'fit-content',
p: 0.5,
bgcolor: 'primary.50',
border: '1px solid',
borderColor: 'primary.200',
borderRadius: 99,
...theme.applyDarkStyles({
borderColor: 'primary.800',
bgcolor: alpha(theme.palette.primary[900], 0.5),
}),
})}
>
<Avatar
imgProps={{ 'aria-labelledby': 'demo-notification-card-messenger-name' }}
src="/static/images/avatar/3-sm.jpeg"
sx={{ width: 40, height: 40 }}
/>
</Box>
<Box sx={{ flexGrow: 1 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
<Typography
id="demo-notification-card-messenger-name"
color="primary.main"
fontWeight="semiBold"
fontSize={12}
gutterBottom
>
Angela Erickson
</Typography>
<Typography color="text.secondary" variant="caption">
09:41
</Typography>
</Box>
<Box sx={{ display: 'flex', gap: 2 }}>
<div>
<Typography fontWeight="semiBold" fontSize={14}>
Incredible discoveries
</Typography>
<Typography fontSize={14} color="text.secondary">
It's about Material UI & Base UI...
</Typography>
</div>
<Chip
label="3"
color="success"
size="small"
sx={{ ml: 'auto', color: '#fff', fontSize: '0.75rem', height: 18 }}
/>
</Box>
</Box>
</Card>
</Fade>
);
}
| 5,214 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/PlayerCard.tsx | import * as React from 'react';
import Stack from '@mui/material/Stack';
import Card from '@mui/material/Card';
import CardMedia from '@mui/material/CardMedia';
import Fade from '@mui/material/Fade';
import IconButton, { iconButtonClasses } from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import FastForwardRounded from '@mui/icons-material/FastForwardRounded';
import FastRewindRounded from '@mui/icons-material/FastRewindRounded';
import PlayArrowRounded from '@mui/icons-material/PlayArrowRounded';
import PauseRounded from '@mui/icons-material/PauseRounded';
import ShuffleRoundedIcon from '@mui/icons-material/ShuffleRounded';
import LoopRoundedIcon from '@mui/icons-material/LoopRounded';
export default function PlayerCard({
disableTheming,
extraStyles,
}: {
disableTheming?: boolean;
extraStyles?: boolean;
}) {
const [paused, setPaused] = React.useState(true);
return (
<Fade in timeout={700}>
<Card
variant="outlined"
sx={[
{
width: { xs: '100%', sm: 'auto' },
p: 2,
display: 'flex',
flexDirection: { xs: 'column', sm: 'row' },
alignItems: 'center',
borderColor: extraStyles ? 'primary.200' : 'grey.200',
gap: 2,
boxShadow: extraStyles ? '0 2px 4px rgba(0, 127, 255, 0.15)' : 'none',
...(!disableTheming && {
[`& .${iconButtonClasses.root}`]: {
border: '1px solid',
bgcolor: 'primary.50',
color: 'primary.500',
borderColor: 'primary.200',
'&:hover': {
bgcolor: 'primary.100',
},
},
[`& .${iconButtonClasses.disabled}`]: {
height: 'fit-content',
bgcolor: 'transparent',
border: '1px solid',
borderColor: 'grey.100',
color: 'grey.300',
},
}),
},
!disableTheming &&
((theme) =>
theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
borderColor: extraStyles ? 'primary.800' : 'primaryDark.700',
[`& .${iconButtonClasses.root}`]: {
bgcolor: 'primary.900',
color: 'primary.200',
borderColor: 'primary.600',
'&:hover': {
bgcolor: 'primary.800',
},
},
[`& .${iconButtonClasses.disabled}`]: {
bgcolor: 'transparent',
border: '1px solid',
borderColor: 'primaryDark.600',
color: 'primaryDark.400',
},
})),
]}
>
<CardMedia
component="img"
width="100"
height="100"
alt="Contemplative Reptile album cover"
src="/static/images/cards/contemplative-reptile.jpg"
sx={{
width: { xs: '100%', sm: 100 },
borderRadius: 0.6,
}}
/>
<Stack direction="column" spacing={2} alignItems="center">
<Stack direction="column" spacing={0.2} alignItems="center">
<Typography color="text.primary" fontWeight="medium" fontSize={15}>
Contemplative Reptile
</Typography>
<Typography
component="div"
variant="caption"
color="text.secondary"
fontWeight="regular"
>
Sounds of Nature
</Typography>
</Stack>
<Stack direction="row" alignItems="center" spacing={1.5}>
<IconButton aria-label="shuffle" disabled size="small" sx={{ flexGrow: 0 }}>
<ShuffleRoundedIcon fontSize="small" />
</IconButton>
<IconButton aria-label="fast rewind" disabled size="small">
<FastRewindRounded fontSize="small" />
</IconButton>
<IconButton
aria-label={paused ? 'play' : 'pause'}
sx={{ mx: 1 }}
onClick={() => setPaused((val) => !val)}
>
{paused ? <PlayArrowRounded /> : <PauseRounded />}
</IconButton>
<IconButton aria-label="fast forward" disabled size="small">
<FastForwardRounded fontSize="small" />
</IconButton>
<IconButton aria-label="loop" disabled size="small">
<LoopRoundedIcon fontSize="small" />
</IconButton>
</Stack>
</Stack>
</Card>
</Fade>
);
}
| 5,215 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/RealEstateCard.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Card, { CardProps } from '@mui/material/Card';
import CardMedia from '@mui/material/CardMedia';
import Typography from '@mui/material/Typography';
import InfoRounded from '@mui/icons-material/InfoRounded';
export default function RealEstateCard({ sx, ...props }: CardProps) {
return (
<Card
variant="outlined"
{...props}
sx={[
(theme) => ({
display: 'flex',
flexWrap: 'wrap',
p: 2,
zIndex: 1,
boxShadow: '0 2px 4px rgba(0, 127, 255, 0.1)',
...theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
boxShadow: '0 2px 4px rgba(0, 0, 0, 0.8)',
}),
}),
...(Array.isArray(sx) ? sx : [sx]),
]}
>
<CardMedia
component="img"
width="100"
height="100"
alt="123 Main St, Phoenix, AZ cover"
src="/static/images/cards/real-estate.png"
sx={{
borderRadius: 0.5,
width: 'clamp(100px, (304px - 100%) * 999 , 100%)',
}}
/>
<Box sx={{ width: 'clamp(15px, (304px - 100%) * 999 , 100%)', height: 15 }} />
<Box sx={{ alignSelf: 'center' }}>
<Typography variant="caption" color="text.secondary" fontWeight="medium">
123 Main St, Phoenix, AZ
</Typography>
<Typography fontWeight="bold" noWrap>
$280k - $310k
</Typography>
<Box
sx={(theme) => ({
mt: 1,
py: 0.4,
pl: 0.5,
pr: 1,
typography: 'caption',
borderRadius: 10,
display: 'flex',
bgcolor: 'primary.50',
border: '1px solid',
borderColor: 'primary.100',
color: 'primary.700',
...theme.applyDarkStyles({
bgcolor: 'primaryDark.700',
color: 'primary.200',
borderColor: 'primary.900',
}),
})}
>
<InfoRounded sx={{ fontSize: 16, mr: 0.5, mt: '1px' }} /> Confidence score: 85%
</Box>
</Box>
</Card>
);
}
| 5,216 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/TaskCard.tsx | import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Fade from '@mui/material/Fade';
import LinearProgress, { linearProgressClasses } from '@mui/material/LinearProgress';
import Typography from '@mui/material/Typography';
import CodeRounded from '@mui/icons-material/CodeRounded';
import ScheduleRounded from '@mui/icons-material/ScheduleRounded';
export default function TaskCard() {
return (
<Fade in timeout={700}>
<Card
data-mui-color-scheme="dark"
sx={(theme) => ({
minWidth: 280,
maxWidth: 360,
minHeight: 280,
display: 'flex',
flexDirection: 'column',
p: 3,
background: `linear-gradient(to right bottom, ${
(theme.vars || theme).palette.primary[500]
}, ${(theme.vars || theme).palette.primary[600]} 120%)`,
boxShadow: '0px 20px 25px rgba(0, 0, 0, 0.1), 0px 10px 10px rgba(0, 0, 0, 0.04)',
})}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.8 }}>
<ScheduleRounded fontSize="inherit" />
<Typography variant="caption" fontWeight="semiBold">
March 25th
</Typography>
</Box>
<Box sx={{ my: 'auto' }}>
<CodeRounded color="white" />
<Typography fontSize={18} component="div" fontWeight="semiBold" sx={{ lineHeight: 1.4 }}>
Customize every button and chip instance primary color
</Typography>
</Box>
<Box sx={{ display: 'flex', gap: 1, py: 1, alignItems: 'center' }}>
<Box
sx={{
p: 0.5,
bgcolor: 'primary.400',
border: '1px solid',
borderColor: 'primary.100',
borderRadius: 99,
}}
>
<Avatar
imgProps={{ 'aria-labelledby': 'demo-task-card-assignee-name' }}
src="/static/images/avatar/2.jpg"
/>
</Box>
<div>
<Typography color="primary.100" fontWeight="semiBold" fontSize={12}>
Assigned to
</Typography>
<Typography id="demo-task-card-assignee-name" variant="body2" fontWeight="semiBold">
Lucas Smith
</Typography>
</div>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<LinearProgress
aria-label="Progress"
variant="determinate"
value={60}
sx={{
flexGrow: 1,
borderRadius: 10,
backgroundColor: 'primary.400',
[`& .${linearProgressClasses.bar}`]: {
borderRadius: 10,
backgroundColor: '#fff',
},
}}
/>
<Typography color="primary.50" variant="body2" fontWeight={700} sx={{ ml: 2 }}>
60%
</Typography>
</Box>
</Card>
</Fade>
);
}
| 5,217 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeAccordion.tsx | import * as React from 'react';
import Accordion, { accordionClasses } from '@mui/material/Accordion';
import AccordionSummary, { accordionSummaryClasses } from '@mui/material/AccordionSummary';
import AccordionDetails, { accordionDetailsClasses } from '@mui/material/AccordionDetails';
import Box from '@mui/material/Box';
import Fade from '@mui/material/Fade';
import Typography from '@mui/material/Typography';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import FontDownloadRoundedIcon from '@mui/icons-material/FontDownloadRounded';
import Folder from '@mui/icons-material/Folder';
export default function ThemeAccordion() {
const [expanded, setExpanded] = React.useState<string | false>('panel1');
const handleChange = (panel: string) => (event: React.SyntheticEvent, newExpanded: boolean) => {
setExpanded(newExpanded ? panel : false);
};
return (
<Fade in timeout={700}>
<Box
sx={[
{
[`& .${accordionClasses.root}`]: {
bgcolor: '#fff',
[`&.${accordionClasses.expanded}`]: {
margin: 0,
},
'&:not(:first-of-type)': {
marginTop: '-1px',
},
},
[`& .${accordionSummaryClasses.root}`]: {
[`&.${accordionSummaryClasses.expanded}`]: {
minHeight: 'auto',
},
[`& .${accordionSummaryClasses.content}`]: {
flexDirection: 'column',
margin: '20px 0 !important',
'& svg': {
marginTop: '3px',
marginRight: '20px',
color: 'grey.500',
},
},
[`& .${accordionSummaryClasses.expandIconWrapper}`]: {
color: 'primary.500',
},
},
[`& .${accordionDetailsClasses.root}`]: {
paddingTop: 0,
},
},
(theme) =>
theme.applyDarkStyles({
[`& .${accordionClasses.root}`]: {
bgcolor: 'primaryDark.900',
borderColor: 'primaryDark.700',
},
[`& .${accordionSummaryClasses.root}`]: {
[`& .${accordionSummaryClasses.content}`]: {
'& svg': {
color: 'grey.300',
},
},
},
}),
]}
>
<Accordion
variant="outlined"
expanded={expanded === 'panel1'}
onChange={handleChange('panel1')}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon sx={{ color: 'primary.400' }} />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Box sx={{ display: 'flex' }}>
<FontDownloadRoundedIcon fontSize="small" />
<div>
<Typography fontWeight={500}>Typography</Typography>
<Typography variant="body2" color="text.secondary">
Fonts used in this website revamp project.
</Typography>
</div>
</Box>
</AccordionSummary>
<AccordionDetails>
<Typography variant="body2" color="text.secondary">
Tag line headings (h1, h2) use General Sans, whereas the rest of the website use IBM
Plex Sans.
</Typography>
</AccordionDetails>
</Accordion>
<Accordion
variant="outlined"
expanded={expanded === 'panel2'}
onChange={handleChange('panel2')}
>
<AccordionSummary
disabled
expandIcon={<ExpandMoreIcon />}
aria-controls="panel2a-content"
id="panel2a-header"
>
<Box sx={{ display: 'flex' }}>
<Folder fontSize="small" />
<div>
<Typography>Hacks</Typography>
<Typography variant="body2" color="text.secondary">
Some of our secrets to make this website.
</Typography>
</div>
</Box>
</AccordionSummary>
</Accordion>
</Box>
</Fade>
);
}
| 5,218 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeButton.tsx | import * as React from 'react';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
export default function ThemeButton() {
return (
<Stack direction="row" spacing={2}>
<Button variant="contained" sx={{ flexGrow: 1 }}>
Install everything
</Button>
<Button variant="outlined" sx={{ flexGrow: 1 }}>
Learn about it
</Button>
</Stack>
);
}
| 5,219 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeChip.tsx | import * as React from 'react';
import Chip, { chipClasses } from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
export default function ThemeChip() {
return (
<Stack
direction="row"
spacing={1}
sx={[
{
[`& .${chipClasses.root}`]: {
border: '1px solid',
[`&.${chipClasses.filled}`]: {
borderColor: 'grey.200',
color: 'grey.800',
bgcolor: 'grey.50',
[`&.${chipClasses.colorPrimary}`]: {
borderColor: 'primary.200',
bgcolor: 'primary.50',
color: 'primary.600',
},
[`&.${chipClasses.colorSuccess}`]: {
borderColor: 'success.200',
bgcolor: 'success.50',
color: 'success.800',
},
[`&.${chipClasses.colorWarning}`]: {
borderColor: 'warning.300',
bgcolor: 'warning.50',
color: 'warning.700',
},
[`&.${chipClasses.colorError}`]: {
borderColor: 'error.200',
bgcolor: 'error.50',
color: 'error.800',
},
},
[`& .${chipClasses.label}`]: {
marginBottom: '1px',
fontSize: '0.875rem',
lineHeight: 1.5,
fontWeight: 600,
},
},
},
(theme) =>
theme.applyDarkStyles({
[`& .${chipClasses.root}`]: {
[`&.${chipClasses.filled}`]: {
color: '#FFF',
bgcolor: 'primaryDark.700',
borderColor: 'primaryDark.500',
[`&.${chipClasses.colorPrimary}`]: {
borderColor: 'primary.700',
bgcolor: 'primary.900',
color: 'primary.100',
},
[`&.${chipClasses.colorSuccess}`]: {
borderColor: 'success.700',
bgcolor: 'success.900',
color: 'success.200',
},
[`&.${chipClasses.colorWarning}`]: {
borderColor: 'warning.700',
bgcolor: 'warning.900',
color: 'warning.200',
},
[`&.${chipClasses.colorError}`]: {
borderColor: 'error.800',
bgcolor: 'error.900',
color: 'error.100',
},
},
},
}),
]}
>
<Chip label="MUI" color="primary" size="small" />
<Chip label="React" color="warning" size="small" />
<Chip label="CSS" color="success" size="small" />
<Chip label="TypeScript" color="error" size="small" />
<Chip label="JavaScript" size="small" />
</Stack>
);
}
| 5,220 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeDatePicker.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Fade from '@mui/material/Fade';
import { iconButtonClasses } from '@mui/material/IconButton';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { StaticDatePicker } from '@mui/x-date-pickers/StaticDatePicker';
export default function ThemeDatePicker() {
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Fade in timeout={700}>
<Box
sx={[
{
'& > div': {
border: '1px solid',
borderColor: 'grey.200',
borderRadius: 1,
},
'& > div > div > div': {
width: '100%',
},
[`& .${iconButtonClasses.root}`]: {
color: 'primary.500',
},
'& .MuiPickerStaticWrapper-root': {
bgcolor: '#fff',
},
'& .MuiPickerStaticWrapper-content': {
bgcolor: 'initial',
},
'& .MuiYearCalendar-root': {
width: '100%',
},
'& .MuiDateCalendar-root': {
width: '100%',
height: 'fit-content',
'& .MuiPickersCalendarHeader-root': {
margin: '12px 0',
paddingLeft: '18px',
},
'& .MuiTypography-caption': {
color: 'grey.500',
height: 24,
},
'[role="presentation"]': {
'& .MuiIconButton-root': {
padding: 0,
},
},
'& .MuiPickersSlideTransition-root': {
minHeight: 165,
},
'& .MuiPickersYear-yearButton': {
flexBasis: '20%',
fontSize: '0.875rem',
height: 'auto',
width: 'auto',
padding: '8px 12px',
'&.Mui-selected': {
color: '#fff',
bgcolor: 'primary.main',
},
},
'& [role="row"]': {
justifyContent: 'space-around',
},
'& .MuiDateCalendar-viewTransitionContainer > div > div': {
justifyContent: 'space-around',
},
'& .MuiPickersDay-root': {
width: 24,
height: 24,
fontWeight: 500,
'&:not(:hover)': {
bgcolor: 'transparent',
},
'&.Mui-selected': {
color: '#fff',
bgcolor: 'primary.main',
},
'&.MuiPickersDay-today': {
'&:not(.Mui-selected)': {
borderColor: 'primary.main',
},
},
},
},
},
(theme) =>
theme.applyDarkStyles({
'& > div': {
borderColor: 'primaryDark.700',
},
[`& .${iconButtonClasses.root}`]: {
color: 'primary.300',
},
'& .MuiPickerStaticWrapper-root': {
bgcolor: 'primaryDark.800',
},
'& .MuiDateCalendar-root': {
'& .MuiPickersDay-root': {
color: 'primary.100',
},
},
}),
]}
>
<StaticDatePicker displayStaticWrapperAs="desktop" />
</Box>
</Fade>
</LocalizationProvider>
);
}
| 5,221 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeSlider.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Fade from '@mui/material/Fade';
import Slider, { sliderClasses } from '@mui/material/Slider';
function valuetext(value: number) {
return `${value}°C`;
}
export default function ThemeSlider() {
return (
<Fade in timeout={700}>
<Box
sx={(theme) => ({
display: 'flex',
justifyContent: 'center',
bgcolor: '#fff',
border: '1px solid',
borderColor: 'grey.200',
borderRadius: 1,
px: 3,
py: 4,
...theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
borderColor: 'primaryDark.700',
}),
})}
>
<Slider
getAriaLabel={() => 'Temperature'}
getAriaValueText={valuetext}
defaultValue={[25, 50]}
valueLabelFormat={valuetext}
valueLabelDisplay="on"
marks={[
{ value: 0, label: '0ºC' },
{ value: 10 },
{ value: 20, label: '20ºC' },
{ value: 30 },
{ value: 40 },
{ value: 50, label: '50ºC' },
{ value: 60 },
{ value: 70 },
{ value: 80, label: '80ºC' },
{ value: 90 },
{ value: 100, label: '100ºC' },
]}
sx={[
{
display: 'inline-block',
width: '100%',
color: 'primary.500',
height: 6,
margin: 0,
pt: 2,
pb: 2,
[`& .${sliderClasses.rail}`]: {
opacity: 1,
bgcolor: 'grey.200',
},
[`& .${sliderClasses.track}`]: {
border: 'none',
},
[`& .${sliderClasses.mark}`]: {
color: 'transparent',
},
[`& .${sliderClasses.markLabel}`]: {
color: 'grey.900',
fontSize: '0.75rem',
fontWeight: 600,
},
[`& .${sliderClasses.thumb}`]: {
width: 12,
height: 12,
'&:before': {
boxShadow: 'none',
},
},
[`& .${sliderClasses.valueLabel}`]: {
backgroundColor: 'transparent',
color: 'primary.600',
fontWeight: 700,
padding: 0,
[`& .${sliderClasses.valueLabelOpen}`]: {
transform: 'none',
top: 'initial',
},
},
},
(theme) =>
theme.applyDarkStyles({
color: 'primary.400',
[`& .${sliderClasses.rail}`]: {
bgcolor: 'primaryDark.600',
},
[`& .${sliderClasses.markLabel}`]: {
color: 'grey.600',
},
[`& .${sliderClasses.valueLabel}`]: {
color: 'primary.200',
},
}),
]}
/>
</Box>
</Fade>
);
}
| 5,222 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeSwitch.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Switch, { switchClasses } from '@mui/material/Switch';
export default function ThemeSwitch() {
const label = { inputProps: { 'aria-label': 'Themed Switch' } };
return (
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
flexGrow: 1,
[`& .${switchClasses.root}`]: {
width: 32,
height: 20,
padding: 0,
[`& .${switchClasses.switchBase}`]: {
padding: '3px',
color: '#fff',
[`&.${switchClasses.checked}`]: {
transform: 'translateX(12px)',
},
},
[`& .${switchClasses.thumb}`]: {
padding: 0,
height: 14,
width: 14,
boxShadow: 'none',
},
},
}}
>
<Switch defaultChecked {...label} />
<Switch {...label} />
</Box>
);
}
| 5,223 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeTabs.tsx | import * as React from 'react';
import Fade from '@mui/material/Fade';
import Tabs, { tabsClasses } from '@mui/material/Tabs';
import Tab, { tabClasses } from '@mui/material/Tab';
export default function ThemeTabs() {
const [value, setValue] = React.useState(0);
const handleChange = (event: React.SyntheticEvent, newValue: number) => {
setValue(newValue);
};
return (
<Fade in timeout={700}>
<Tabs
value={value}
onChange={handleChange}
aria-label="theme example"
variant="fullWidth"
sx={[
{
background:
'linear-gradient(180deg, var(--muidocs-palette-primary-500) 0%, var(--muidocs-palette-primary-600) 100%)',
borderRadius: 1,
boxShadow: '0px 20px 25px rgba(0, 0, 0, 0.1), 0px 10px 10px rgba(0, 0, 0, 0.04)',
[`& .${tabsClasses.indicator}`]: {
backgroundColor: 'transparent',
'&:before': {
content: '""',
display: 'block',
position: 'absolute',
left: 30,
right: 30,
height: '100%',
backgroundColor: '#fff',
},
},
[`& .${tabClasses.root}`]: {
minHeight: 48,
margin: 0,
color: 'primary.100',
'&:hover': {
backgroundColor: 'transparent',
},
'&.Mui-selected': {
color: '#fff',
},
},
},
(theme) =>
theme.applyDarkStyles({
[`& .${tabClasses.root}`]: {
color: 'primary.200',
},
}),
]}
>
<Tab label="Material UI" />
<Tab label="Base UI" />
<Tab label="Joy UI" />
</Tabs>
</Fade>
);
}
| 5,224 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeTimeline.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Fade from '@mui/material/Fade';
import Typography from '@mui/material/Typography';
import Timeline from '@mui/lab/Timeline';
import TimelineItem, { timelineItemClasses } from '@mui/lab/TimelineItem';
import TimelineSeparator from '@mui/lab/TimelineSeparator';
import TimelineConnector, { timelineConnectorClasses } from '@mui/lab/TimelineConnector';
import TimelineContent, { timelineContentClasses } from '@mui/lab/TimelineContent';
import TimelineDot, { timelineDotClasses } from '@mui/lab/TimelineDot';
export default function BasicTimeline() {
return (
<Fade in timeout={700}>
<Card
variant="outlined"
sx={(theme) => ({
p: 2,
pb: 1,
display: 'flex',
alignItems: 'flex-start',
...theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
borderColor: 'primaryDark.700',
}),
})}
>
<Box
sx={(theme) => ({
height: 24,
width: 24,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
fontSize: '0.75rem',
fontWeight: 700,
borderRadius: 0.3,
bgcolor: 'primary.50',
color: 'primary.600',
...theme.applyDarkStyles({
bgcolor: 'primary.900',
color: 'primary.50',
}),
})}
>
1
</Box>
<Box sx={{ ml: 2, flex: 1 }}>
<Typography variant="body2" color="text.primary" gutterBottom>
Install one of our production-ready libraries to get your next app started inevitably
successful:
</Typography>
<Timeline
sx={[
{
pl: 0,
py: 0,
my: 0,
[`& .${timelineItemClasses.root}`]: {
minHeight: 24,
'&:before': {
display: 'none',
},
},
[`& .${timelineDotClasses.root}`]: {
zIndex: 1,
padding: '3px',
boxShadow: 'none',
margin: '15px 0',
border: 'none',
bgcolor: 'primary.500',
},
[`& .${timelineConnectorClasses.root}`]: {
margin: '-8px 0',
bgcolor: 'primary.100',
},
[`& .${timelineContentClasses.root}`]: {
fontSize: '0.875rem',
color: 'grey.800',
},
},
(theme) =>
theme.applyDarkStyles({
[`& .${timelineConnectorClasses.root}`]: {
bgcolor: 'primary.900',
},
[`& .${timelineContentClasses.root}`]: {
color: 'grey.100',
},
}),
]}
>
<TimelineItem>
<TimelineSeparator>
<TimelineDot />
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>Material UI</TimelineContent>
</TimelineItem>
<TimelineItem>
<TimelineSeparator>
<TimelineDot />
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>Base UI</TimelineContent>
</TimelineItem>
<TimelineItem>
<TimelineSeparator>
<TimelineDot />
</TimelineSeparator>
<TimelineContent>Joy UI</TimelineContent>
</TimelineItem>
</Timeline>
</Box>
</Card>
</Fade>
);
}
| 5,225 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ThemeToggleButton.tsx | import * as React from 'react';
import Fade from '@mui/material/Fade';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
export default function ThemeToggleButton() {
const [lang, setLang] = React.useState('joy');
return (
<Fade in timeout={700}>
<ToggleButtonGroup
fullWidth
// size="small"
color="primary"
value={lang}
exclusive
onChange={(event, value) => setLang(value)}
aria-label="language"
sx={[
{
bgcolor: '#fff',
'& .MuiToggleButton-root': {
textTransform: 'none',
fontWeight: 600,
color: 'grey.700',
borderColor: 'grey.200',
'&.Mui-selected': {
color: 'primary.600',
bgcolor: 'primary.100',
},
},
},
(theme) =>
theme.applyDarkStyles({
bgcolor: 'primaryDark.900',
'& .MuiToggleButton-root': {
color: 'grey.400',
borderColor: 'primaryDark.700',
'&.Mui-selected': {
color: 'primary.100',
bgcolor: 'primary.900',
},
},
}),
]}
>
<ToggleButton value="joy">Joy UI</ToggleButton>
<ToggleButton value="material">Material UI</ToggleButton>
<ToggleButton value="base">Base UI</ToggleButton>
</ToggleButtonGroup>
</Fade>
);
}
| 5,226 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/showcase/ViewToggleButton.tsx | import * as React from 'react';
import ToggleButton, { toggleButtonClasses } from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ViewQuiltRounded from '@mui/icons-material/ViewQuiltRounded';
import ViewModuleRounded from '@mui/icons-material/ViewModuleRounded';
import ViewAgendaRounded from '@mui/icons-material/ViewAgendaRounded';
import ViewWeekRounded from '@mui/icons-material/ViewWeekRounded';
import ViewSidebarRounded from '@mui/icons-material/ViewSidebarRounded';
const views = ['quilt', 'module', 'agenda', 'week', 'sidebar'] as const;
type View = (typeof views)[number];
const viewIcons: Record<View, React.ReactElement> = {
quilt: <ViewQuiltRounded />,
module: <ViewModuleRounded />,
agenda: <ViewAgendaRounded />,
week: <ViewWeekRounded />,
sidebar: <ViewSidebarRounded />,
};
export default function ViewToggleButton() {
const [view, setView] = React.useState<View>('quilt');
return (
<ToggleButtonGroup
size="small"
color="primary"
value={view}
exclusive
onChange={(event, value) => setView(value)}
aria-label="view"
sx={(theme) => ({
bgcolor: '#fff',
...theme.applyDarkStyles({
bgcolor: 'primaryDark.800',
}),
})}
>
{views.map((item) => (
<ToggleButton
key={item}
value={item}
aria-label={item}
sx={[
{
color: 'grey.400',
[`&.${toggleButtonClasses.selected}`]: {
color: 'primary.500',
},
},
(theme) =>
theme.applyDarkStyles({
color: '#fff',
[`&.${toggleButtonClasses.selected}`]: {
color: 'primary.300',
},
}),
]}
>
{viewIcons[item]}
</ToggleButton>
))}
</ToggleButtonGroup>
);
}
| 5,227 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/typography/GradientText.tsx | import { styled } from '@mui/material/styles';
const GradientText = styled('span')<{
color?: 'primary' | 'error' | 'success' | 'warning';
}>(({ theme, color = 'primary' }) => ({
background: `linear-gradient(90deg, ${(theme.vars || theme).palette[color][400]} 5%, ${
(theme.vars || theme).palette[color].main
} 90%)`,
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
}));
export default GradientText;
| 5,228 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/typography/SectionHeadline.tsx | import * as React from 'react';
import Typography from '@mui/material/Typography';
interface SectionHeadlineProps {
description?: React.ReactNode;
id?: string;
overline?: React.ReactNode;
title: string | React.ReactElement;
alwaysCenter?: boolean;
/**
* For using with dark background.
*/
inverted?: boolean;
}
export default function SectionHeadline(props: SectionHeadlineProps) {
const { description, id, overline, title, alwaysCenter = false, inverted = false } = props;
return (
<React.Fragment>
{overline && (
<Typography
id={id}
component="h2"
variant="body2"
fontWeight="bold"
color="primary.main"
sx={{
mb: 1,
...(alwaysCenter && {
textAlign: 'center',
}),
}}
>
{overline}
</Typography>
)}
{typeof title === 'string' ? (
<Typography
variant="h2"
sx={(theme) => ({
...(inverted
? {
color: '#fff',
}
: {
color: 'primaryDark.900',
...theme.applyDarkStyles({
color: 'grey.100',
}),
}),
...(alwaysCenter && {
textAlign: 'center',
}),
})}
>
{title}
</Typography>
) : (
React.cloneElement(title, {
style: {
...(alwaysCenter && {
textAlign: 'center',
}),
...(inverted && {
color: '#fff',
}),
},
})
)}
{description && (
<Typography
sx={(theme) => ({
mt: 1,
mb: 3,
maxWidth: 450,
...(inverted
? {
color: 'grey.400',
}
: {
color: 'grey.800',
...theme.applyDarkStyles({
color: 'grey.500',
}),
}),
...(alwaysCenter && {
textAlign: 'center',
mx: 'auto',
maxWidth: 600,
}),
})}
>
{description}
</Typography>
)}
</React.Fragment>
);
}
| 5,229 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/x-grid/EditProgress.tsx | import * as React from 'react';
import { GridRenderEditCellParams, useGridApiContext } from '@mui/x-data-grid';
import { debounce } from '@mui/material/utils';
import { alpha } from '@mui/material/styles';
import Slider, { SliderValueLabelProps } from '@mui/material/Slider';
import Tooltip from '@mui/material/Tooltip';
function ValueLabelComponent(props: SliderValueLabelProps) {
const { children, open, value } = props;
return (
<Tooltip open={open} enterTouchDelay={0} placement="top" title={value} arrow>
{children}
</Tooltip>
);
}
export default function EditProgress(props: GridRenderEditCellParams) {
const { id, value, field } = props;
const apiRef = useGridApiContext();
const [valueState, setValueState] = React.useState(Number(value));
const updateCellEditProps = React.useCallback(
(newValue: number | number[]) => {
apiRef.current.setEditCellValue({ id, field, value: newValue });
},
[field, id, apiRef],
);
const debouncedUpdateCellEditProps = React.useMemo(
() => debounce(updateCellEditProps, 60),
[updateCellEditProps],
);
const handleChange = (event: Event, newValue: number | number[]) => {
setValueState(newValue as number);
debouncedUpdateCellEditProps(newValue);
};
React.useEffect(() => {
setValueState(Number(value));
}, [value]);
const handleRef = (element: any) => {
if (element) {
const input = element.querySelector('input') as null | HTMLInputElement;
if (input) {
input.focus();
}
}
};
return (
<Slider
ref={handleRef}
sx={[
{
p: 0,
height: '100%',
borderRadius: '0px',
'& .MuiSlider-rail': {
bgcolor: 'grey.100',
},
'& .MuiSlider-track': {
border: 0,
...(valueState < 0.3 && {
bgcolor: 'error.500',
}),
...(valueState >= 0.3 &&
valueState <= 0.7 && {
bgcolor: 'warning.500',
}),
...(valueState > 0.7 && {
bgcolor: 'success.500',
}),
},
'& .MuiSlider-thumb': {
cursor: 'col-resize',
height: '100%',
width: 5,
borderRadius: '0px',
marginTop: 0,
backgroundColor: alpha('#000000', 0.2),
},
},
(theme) =>
theme.applyDarkStyles({
'& .MuiSlider-rail': {
bgcolor: 'primaryDark.700',
},
'& .MuiSlider-track': {
...(valueState < 0.3 && {
bgcolor: 'error.800',
}),
...(valueState >= 0.3 &&
valueState <= 0.7 && {
bgcolor: 'warning.800',
}),
...(valueState > 0.7 && {
bgcolor: 'success.800',
}),
},
}),
]}
value={valueState}
max={1}
step={0.00001}
onChange={handleChange}
slots={{
valueLabel: ValueLabelComponent,
}}
valueLabelDisplay="auto"
valueLabelFormat={(newValue) => `${(newValue * 100).toLocaleString()} %`}
/>
);
}
| 5,230 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/x-grid/EditStatus.tsx | import * as React from 'react';
import {
GridRenderEditCellParams,
useGridRootProps,
useGridApiContext,
GridEditModes,
} from '@mui/x-data-grid';
import Select, { SelectProps } from '@mui/material/Select';
import { MenuProps } from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import ReportProblemIcon from '@mui/icons-material/ReportProblem';
import InfoIcon from '@mui/icons-material/Info';
import AutorenewIcon from '@mui/icons-material/Autorenew';
import DoneIcon from '@mui/icons-material/Done';
const STATUS_OPTIONS = ['Open', 'PartiallyFilled', 'Filled', 'Rejected'];
export default function EditStatus(props: GridRenderEditCellParams) {
const { id, value, field } = props;
const rootProps = useGridRootProps();
const apiRef = useGridApiContext();
const handleChange: SelectProps['onChange'] = async (event) => {
const isValid = await apiRef.current.setEditCellValue({ id, field, value: event.target.value });
if (isValid && rootProps.editMode === GridEditModes.Cell) {
apiRef.current.stopCellEditMode({ id, field, cellToFocusAfter: 'below' });
}
};
const handleClose: MenuProps['onClose'] = (event, reason) => {
if (reason === 'backdropClick') {
apiRef.current.stopCellEditMode({ id, field, ignoreModifications: true });
}
};
return (
<Select
value={value}
onChange={handleChange}
MenuProps={{
onClose: handleClose,
}}
autoFocus
fullWidth
open
>
{STATUS_OPTIONS.map((option) => {
let IconComponent: any = null;
if (option === 'Rejected') {
IconComponent = ReportProblemIcon;
} else if (option === 'Open') {
IconComponent = InfoIcon;
} else if (option === 'PartiallyFilled') {
IconComponent = AutorenewIcon;
} else if (option === 'Filled') {
IconComponent = DoneIcon;
}
let label = option;
if (option === 'PartiallyFilled') {
label = 'Partially Filled';
}
return (
<MenuItem
key={option}
value={option}
dense
sx={{ '& .MuiListItemIcon-root': { minWidth: 24, '& > svg': { fontSize: '1rem' } } }}
>
<ListItemIcon>
<IconComponent />
</ListItemIcon>
<ListItemText primary={label} sx={{ overflow: 'hidden' }} />
</MenuItem>
);
})}
</Select>
);
}
| 5,231 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/x-grid/ProgressBar.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
interface ProgressBarProps {
value: number;
}
const ProgressBar = React.memo(function ProgressBar(props: ProgressBarProps) {
const { value } = props;
const valueInPercent = value * 100;
return (
<Box
sx={(theme) => ({
lineHeight: 1,
position: 'relative',
p: 0.5,
borderRadius: '3px',
width: '100%',
bgcolor: 'grey.100',
...theme.applyDarkStyles({
bgcolor: 'primaryDark.700',
}),
})}
>
<Box
sx={{ fontWeight: 'bold', color: 'text.primary', position: 'relative', zIndex: 1 }}
>{`${valueInPercent.toLocaleString()} %`}</Box>
<Box
sx={(theme) => ({
borderRadius: '3px',
position: 'absolute',
height: '100%',
left: 0,
top: 0,
...(valueInPercent < 30 && {
bgcolor: 'error.200',
}),
...(valueInPercent >= 30 &&
valueInPercent <= 70 && {
bgcolor: 'warning.400',
}),
...(valueInPercent > 70 && {
bgcolor: 'success.300',
}),
width: `${valueInPercent}%`,
...theme.applyDarkStyles({
...(valueInPercent < 30 && {
bgcolor: 'error.700',
}),
...(valueInPercent >= 30 &&
valueInPercent <= 70 && {
bgcolor: 'warning.900',
}),
...(valueInPercent > 70 && {
bgcolor: 'success.800',
}),
}),
})}
/>
</Box>
);
});
export default ProgressBar;
| 5,232 |
0 | petrpan-code/mui/material-ui/docs/src/components | petrpan-code/mui/material-ui/docs/src/components/x-grid/Status.tsx | import * as React from 'react';
import { alpha } from '@mui/material/styles';
import Chip from '@mui/material/Chip';
interface StatusProps {
status: string;
}
const Status = React.memo((props: StatusProps) => {
const { status } = props;
let label = status;
if (status === 'PartiallyFilled') {
label = 'Partial';
}
return (
<Chip
size="small"
label={label}
variant="outlined"
sx={(theme) => ({
lineHeight: 1,
fontSize: '10px',
fontWeight: 'bold',
...(status === 'Open' && {
borderColor: 'primary.500',
bgcolor: alpha(theme.palette.primary[500], 0.1),
color: 'primary.600',
}),
...(status === 'Filled' && {
borderColor: 'success.500',
bgcolor: alpha(theme.palette.success[500], 0.1),
color: 'success.800',
}),
...(status === 'PartiallyFilled' && {
borderColor: 'warning.600',
bgcolor: alpha(theme.palette.warning[500], 0.1),
color: 'warning.900',
}),
...(status === 'Rejected' && {
borderColor: 'error.500',
bgcolor: alpha(theme.palette.error[500], 0.1),
color: 'error.600',
}),
...theme.applyDarkStyles({
...(status === 'Open' && {
color: 'primary.300',
}),
...(status === 'Filled' && {
color: 'success.500',
}),
...(status === 'PartiallyFilled' && {
color: 'warning.300',
}),
...(status === 'Rejected' && {
color: 'error.400',
}),
}),
})}
/>
);
});
export default Status;
| 5,233 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/DiscordIcon.tsx | import * as React from 'react';
import SvgIcon, { SvgIconProps } from '@mui/material/SvgIcon';
export default function SvgDiscord(props: SvgIconProps) {
return (
<SvgIcon {...props}>
<path d="M20.32 4.37a19.8 19.8 0 0 0-4.89-1.52.07.07 0 0 0-.08.04c-.2.38-.44.87-.6 1.25a18.27 18.27 0 0 0-5.5 0c-.16-.4-.4-.87-.6-1.25a.08.08 0 0 0-.09-.04 19.74 19.74 0 0 0-4.88 1.52.07.07 0 0 0-.04.03A20.26 20.26 0 0 0 .1 18.06a.08.08 0 0 0 .03.05 19.9 19.9 0 0 0 6 3.03.08.08 0 0 0 .08-.02c.46-.63.87-1.3 1.22-2a.08.08 0 0 0-.04-.1 13.1 13.1 0 0 1-1.87-.9.08.08 0 0 1 0-.12l.36-.3a.07.07 0 0 1 .08 0 14.2 14.2 0 0 0 12.06 0 .07.07 0 0 1 .08 0l.37.3a.08.08 0 0 1 0 .12 12.3 12.3 0 0 1-1.88.9.08.08 0 0 0-.04.1c.36.7.78 1.36 1.23 2a.08.08 0 0 0 .08.02c1.96-.6 3.95-1.52 6-3.03a.08.08 0 0 0 .04-.05c.5-5.18-.84-9.68-3.55-13.66a.06.06 0 0 0-.03-.03zM8.02 15.33c-1.18 0-2.16-1.08-2.16-2.42 0-1.33.96-2.42 2.16-2.42 1.21 0 2.18 1.1 2.16 2.42 0 1.34-.96 2.42-2.16 2.42zm7.97 0c-1.18 0-2.15-1.08-2.15-2.42 0-1.33.95-2.42 2.15-2.42 1.22 0 2.18 1.1 2.16 2.42 0 1.34-.94 2.42-2.16 2.42Z" />
</SvgIcon>
);
}
| 5,234 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/RootSvg.tsx | import { styled, Theme } from '@mui/material/styles';
import { SxProps } from '@mui/system';
export type RootSvgProps<P = unknown> = Omit<React.SVGProps<SVGSVGElement>, 'ref'> & {
sx?: SxProps<Theme>;
ref?: React.Ref<SVGSVGElement>;
} & P;
const Svg = styled('svg')({
verticalAlign: 'bottom',
});
export default Svg;
| 5,235 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/SvgHamburgerMenu.tsx | import * as React from 'react';
import RootSvg, { RootSvgProps } from 'docs/src/icons/RootSvg';
export default function SvgHamburgerMenu(props: RootSvgProps) {
return (
<RootSvg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
viewBox="0 0 16 16"
fill="none"
{...props}
>
<rect x={1} y={5} width={14} height={1.5} rx={1} fill="#007FFF" />
<rect x={1} y={9} width={14} height={1.5} rx={1} fill="#007FFF" />
</RootSvg>
);
}
| 5,236 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/SvgMaterialDesign.tsx | import * as React from 'react';
import RootSvg, { RootSvgProps } from 'docs/src/icons/RootSvg';
function SvgMaterialDesign(props: RootSvgProps) {
return (
<RootSvg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
viewBox="0 0 24 24"
fill="none"
{...props}
>
<circle cx={12} cy={12} r={12} fill="#737373" />
<path fill="#BDBDBD" d="M4 4h16v16H4z" />
<path fillRule="evenodd" clipRule="evenodd" d="M12 20l8-16H4l8 16z" fill="#fff" />
</RootSvg>
);
}
export default SvgMaterialDesign;
| 5,237 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/SvgMuiLogomark.tsx | import * as React from 'react';
import RootSvg, { RootSvgProps } from 'docs/src/icons/RootSvg';
export default function SvgMuiLogomark(props: RootSvgProps) {
return (
<RootSvg
xmlns="http://www.w3.org/2000/svg"
width={36}
height={32}
viewBox="0 0 36 32"
fill="none"
{...props}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M30.343 21.976a1 1 0 00.502-.864l.018-5.787a1 1 0 01.502-.864l3.137-1.802a1 1 0 011.498.867v10.521a1 1 0 01-.502.867l-11.839 6.8a1 1 0 01-.994.001l-9.291-5.314a1 1 0 01-.504-.868v-5.305c0-.006.007-.01.013-.007.005.003.012 0 .012-.007v-.006c0-.004.002-.008.006-.01l7.652-4.396c.007-.004.004-.015-.004-.015a.008.008 0 01-.008-.008l.015-5.201a1 1 0 00-1.5-.87l-5.687 3.277a1 1 0 01-.998 0L6.666 9.7a1 1 0 00-1.499.866v9.4a1 1 0 01-1.496.869l-3.166-1.81a1 1 0 01-.504-.87l.028-16.43A1 1 0 011.527.86l10.845 6.229a1 1 0 00.996 0L24.21.86a1 1 0 011.498.868v16.434a1 1 0 01-.501.867l-5.678 3.27a1 1 0 00.004 1.735l3.132 1.783a1 1 0 00.993-.002l6.685-3.839zM31 7.234a1 1 0 001.514.857l3-1.8A1 1 0 0036 5.434V1.766A1 1 0 0034.486.91l-3 1.8a1 1 0 00-.486.857v3.668z"
fill="#007FFF"
/>
</RootSvg>
);
}
| 5,238 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/SvgMuiLogotype.tsx | import * as React from 'react';
import RootSvg, { RootSvgProps } from 'docs/src/icons/RootSvg';
export default function SvgMuiLogomark(props: RootSvgProps) {
return (
<RootSvg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 117 36"
fill="none"
sx={[
(theme) => ({
flexShrink: 0,
color: 'common.black',
...theme.applyDarkStyles({
color: '#FFF',
}),
}),
...(Array.isArray(props.sx) ? props.sx : [props.sx]),
]}
{...props}
>
<path
d="M11.59 10.73.75 4.43a.5.5 0 0 0-.75.44V22.4c0 .18.1.34.25.43l4.05 2.38a.5.5 0 0 0 .75-.43V13.34a.2.2 0 0 1 .3-.17l6.25 3.58a2 2 0 0 0 2-.01l6.1-3.57a.2.2 0 0 1 .3.17v5.6a1 1 0 0 1-.48.85l-6.28 3.86a.5.5 0 0 0-.24.43v5.64c0 .18.09.34.23.43l8.23 5.2a2 2 0 0 0 2.1.02l10.46-6.2a2 2 0 0 0 .98-1.73V16.63a.5.5 0 0 0-.76-.43l-3.31 2a2 2 0 0 0-.97 1.7v5.43a.5.5 0 0 1-.25.43l-6.19 3.65a2 2 0 0 1-2.04-.01l-3.33-2a.5.5 0 0 1-.02-.84l6.02-3.97a2 2 0 0 0 .9-1.67V4.87a.5.5 0 0 0-.75-.43l-10.7 6.29a2 2 0 0 1-2.01 0Z"
fill="#007FFF"
/>
<path
d="M35 5.36v3.42a2 2 0 0 1-.94 1.7l-3.3 2.05a.5.5 0 0 1-.76-.43V8.52a2 2 0 0 1 1-1.73l3.25-1.86a.5.5 0 0 1 .75.43Z"
fill="#007FFF"
/>
<path
d="M50.38 26.5V8.3h4.5l7.56 10.5-3.32-.02L66.7 8.3h4.44v18.2H66.2v-5.02c0-1.49.03-2.86.1-4.1.07-1.27.21-2.55.42-3.83l.52 1.61-5.64 7.28h-1.72l-5.62-7.35.58-1.54c.2 1.25.34 2.5.41 3.75.07 1.24.1 2.64.1 4.18v5.02h-4.96Zm34.88.16c-1.77 0-3.34-.35-4.7-1.04a7.87 7.87 0 0 1-3.18-2.89 7.92 7.92 0 0 1-1.11-4.19V8.3h5.2v10.09c0 .76.16 1.43.49 2 .33.57.78 1.01 1.35 1.33a4 4 0 0 0 1.95.46c.76 0 1.44-.15 2.03-.46.6-.32 1.07-.76 1.4-1.33.35-.57.52-1.24.52-2V8.3h5.05v10.24a7.78 7.78 0 0 1-4.3 7.08c-1.33.69-2.9 1.04-4.7 1.04Zm14.41-.16v-4.32h4.19v-9.56h-4.19V8.3h13.5v4.32H109v9.56h4.16v4.32h-13.5Z"
fill="currentColor"
/>
</RootSvg>
);
}
| 5,239 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/SvgMuiX.tsx | import * as React from 'react';
import RootSvg, { RootSvgProps } from 'docs/src/icons/RootSvg';
export default function SvgMuiX(props: RootSvgProps) {
return (
<RootSvg
xmlns="http://www.w3.org/2000/svg"
width={16}
height={16}
viewBox="0 0 16 16"
fill="none"
{...props}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M8 7.748L4.15 14.415H1.585l3.849-6.667-2.566-4.444h2.566L8 7.748zm0 0l2.566 4.445h2.566l-2.566-4.445 3.849-6.666h-2.566L8 7.748z"
fill="#265D97"
/>
</RootSvg>
);
}
| 5,240 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/SvgStackOverflow.tsx | import * as React from 'react';
import SvgIcon, { SvgIconProps } from '@mui/material/SvgIcon';
export default function SvgStackOverflow(props: SvgIconProps) {
return (
<SvgIcon {...props}>
<path d="M19.04 20.04v-5.87h1.99V22H3v-7.83h2v5.87h14.05-.01ZM6.98 18.09h10.05v-1.96H6.99v1.96Zm.25-4.45 9.8 2 .42-1.89-9.8-2.02-.41 1.9-.01.01ZM8.5 9l9.07 4.15.84-1.78L9.34 7.2 8.5 9V9Zm2.53-4.38 7.69 6.28 1.27-1.49-7.69-6.28-1.26 1.49ZM16.01 0l-1.64 1.2 6 7.87L22 7.88 16 0Z" />
</SvgIcon>
);
}
| 5,241 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/icons/SvgTwinkle.tsx | import * as React from 'react';
import RootSvg, { RootSvgProps } from 'docs/src/icons/RootSvg';
function SvgTwinkle(props: RootSvgProps) {
return (
<RootSvg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
viewBox="0 0 24 24"
fill="none"
{...props}
>
<path
d="M19.46 8l.79-1.75L22 5.46a.5.5 0 000-.91l-1.75-.79L19.46 2a.5.5 0 00-.91 0l-.79 1.75-1.76.79a.5.5 0 000 .91l1.75.79.79 1.76c.18.39.74.39.92 0zM11.5 9.5L9.91 6c-.35-.78-1.47-.78-1.82 0L6.5 9.5 3 11.09c-.78.36-.78 1.47 0 1.82l3.5 1.59L8.09 18c.36.78 1.47.78 1.82 0l1.59-3.5 3.5-1.59c.78-.36.78-1.47 0-1.82L11.5 9.5zm7.04 6.5l-.79 1.75-1.75.79a.5.5 0 000 .91l1.75.79.79 1.76a.5.5 0 00.91 0l.79-1.75 1.76-.79a.5.5 0 000-.91l-1.75-.79-.79-1.76a.508.508 0 00-.92 0z"
fill="#FFBC1F"
/>
</RootSvg>
);
}
export default SvgTwinkle;
| 5,242 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/layouts/AppFooter.tsx | import * as React from 'react';
import Box from '@mui/material/Box';
import Container from '@mui/material/Container';
import Divider from '@mui/material/Divider';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import Stack from '@mui/material/Stack';
import TwitterIcon from '@mui/icons-material/Twitter';
import GitHubIcon from '@mui/icons-material/GitHub';
import LinkedInIcon from '@mui/icons-material/LinkedIn';
import YouTubeIcon from '@mui/icons-material/YouTube';
import RssFeedIcon from '@mui/icons-material/RssFeed';
import { alpha } from '@mui/material/styles';
import SvgMuiLogotype from 'docs/src/icons/SvgMuiLogotype';
import EmailSubscribe from 'docs/src/components/footer/EmailSubscribe';
import ROUTES from 'docs/src/route';
import DiscordIcon from 'docs/src/icons/DiscordIcon';
import Link from 'docs/src/modules/components/Link';
import SvgStackOverflow from 'docs/src/icons/SvgStackOverflow';
interface AppFooterProps {
stackOverflowUrl?: string;
}
export default function AppFooter(props: AppFooterProps) {
const { stackOverflowUrl } = props;
return (
<Container component="footer">
<Box
sx={{
py: { xs: 4, sm: 8 },
display: 'grid',
gridAutoColumns: '1fr',
alignItems: 'flex-start',
justifyContent: 'space-between',
gap: 4,
gridTemplateColumns: { xs: '1fr', sm: '1fr', md: '1fr 1.75fr', lg: '1fr 1fr' },
gridTemplateRows: 'auto',
'& a:not(.MuiIconButton-root)': {
pt: 0.5,
pb: 0.5,
color: 'text.secondary',
typography: 'body2',
'&:hover': {
color: 'primary.main',
textDecoration: 'underline',
},
},
}}
>
<div>
<Link href="/" aria-label="Go to homepage" sx={{ mb: 2 }}>
<SvgMuiLogotype height={28} width={91} />
</Link>
<Typography variant="body2" fontWeight="bold" gutterBottom>
Keep up to date
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
Join our newsletter for regular updates. No spam ever.
</Typography>
<EmailSubscribe sx={{ mb: 4 }} />
</div>
<Box
sx={{
display: 'grid',
gridTemplateColumns: { xs: '1fr 1fr', md: '1fr 1fr 1fr 1fr' },
gridAutoColumns: '1fr',
gap: 2,
}}
>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<Typography fontWeight="bold" variant="body2" sx={{ mb: 0.5 }}>
Products
</Typography>
<Link href={ROUTES.productMaterial}>Material UI</Link>
<Link href={ROUTES.productBase}>Base UI</Link>
<Link href={ROUTES.productAdvanced}>MUI X</Link>
<Link href={ROUTES.productToolpad}>MUI Toolpad</Link>
<Link href={ROUTES.productTemplates}>Templates</Link>
<Link href={ROUTES.productDesignKits}>Design kits</Link>
</Box>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<Typography fontWeight="bold" variant="body2" sx={{ mb: 0.5 }}>
Resources
</Typography>
<Link href={ROUTES.materialIcons}>Material Icons</Link>
<Link href={ROUTES.freeTemplates}>Free templates</Link>
<Link href={ROUTES.components}>Components</Link>
<Link href={ROUTES.customization}>Customization</Link>
<Link href={ROUTES.theming}>Theming</Link>
</Box>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<Typography fontWeight="bold" variant="body2" sx={{ mb: 0.5 }}>
Explore
</Typography>
<Link href={ROUTES.documentation}>Documentation</Link>
<Link href={ROUTES.store}>Store</Link>
<Link href={ROUTES.blog}>Blog</Link>
<Link href={ROUTES.showcase}>Showcase</Link>
<Link href={ROUTES.coreRoadmap}>Roadmap</Link>
</Box>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<Typography fontWeight="bold" variant="body2" sx={{ mb: 0.5 }}>
Company
</Typography>
<Link href={ROUTES.about}>About</Link>
<Link href={ROUTES.vision}>Vision</Link>
<Box sx={{ display: 'flex', alignItems: 'end' }}>
<Link href={ROUTES.careers}>Careers </Link>
<Box
sx={(theme) => ({
px: 0.5,
py: 0.1,
ml: 1,
mb: '1px',
position: 'relative',
top: theme.spacing(-0.5),
fontSize: theme.typography.pxToRem(10),
fontWeight: 'Bold',
textTransform: 'uppercase',
letterSpacing: '.04rem',
borderRadius: 8,
border: 1,
borderColor: 'success.300',
bgcolor: alpha(theme.palette.success[100], 0.4),
color: 'success.700',
...theme.applyDarkStyles({
borderColor: alpha(theme.palette.success[800], 0.5),
bgcolor: alpha(theme.palette.success[800], 0.2),
color: 'success.200',
}),
})}
>
Hiring
</Box>
</Box>
<Link href={ROUTES.support}>Support</Link>
<Link href={ROUTES.privacyPolicy}>Privacy policy</Link>
<Link target="_blank" rel="noopener noreferrer" href="mailto:[email protected]">
Contact us
</Link>
</Box>
</Box>
</Box>
<Divider />
<Stack
direction={{ xs: 'column', sm: 'row' }}
alignItems="center"
justifyContent={{ sm: 'space-between' }}
gap={{ xs: 2, sm: 1 }}
sx={{ my: 4 }}
>
<Typography color="text.tertiary" variant="caption" fontWeight={400}>
Copyright © {new Date().getFullYear()} Material UI SAS, trading as MUI.
</Typography>
<Stack spacing={1} direction="row" flexWrap="wrap" useFlexGap>
<IconButton
target="_blank"
rel="noopener noreferrer"
href="https://github.com/mui"
aria-label="github"
title="GitHub"
size="small"
>
<GitHubIcon fontSize="small" />
</IconButton>
<IconButton
target="_blank"
rel="noopener noreferrer"
href={ROUTES.rssFeed}
aria-label="RSS Feed"
title="RSS Feed"
size="small"
>
<RssFeedIcon fontSize="small" />
</IconButton>
<IconButton
target="_blank"
rel="noopener noreferrer"
href="https://twitter.com/MUI_hq"
aria-label="twitter"
title="Twitter"
size="small"
>
<TwitterIcon fontSize="small" />
</IconButton>
<IconButton
target="_blank"
rel="noopener noreferrer"
href="https://www.linkedin.com/company/mui/"
aria-label="linkedin"
title="LinkedIn"
size="small"
>
<LinkedInIcon fontSize="small" />
</IconButton>
<IconButton
target="_blank"
rel="noopener noreferrer"
href="https://www.youtube.com/@MUI_hq"
aria-label="YouTube"
title="YouTube"
size="small"
>
<YouTubeIcon fontSize="small" />
</IconButton>
<IconButton
target="_blank"
rel="noopener noreferrer"
href="https://mui.com/r/discord/"
aria-label="Discord"
title="Discord"
size="small"
>
<DiscordIcon fontSize="small" />
</IconButton>
{stackOverflowUrl ? (
<IconButton
target="_blank"
rel="noopener noreferrer"
href={stackOverflowUrl}
aria-label="Stack Overflow"
title="Stack Overflow"
size="small"
>
<SvgStackOverflow fontSize="small" />
</IconButton>
) : null}
</Stack>
</Stack>
</Container>
);
}
| 5,243 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/layouts/AppHeader.tsx | import * as React from 'react';
import { styled, alpha } from '@mui/material/styles';
import GlobalStyles from '@mui/material/GlobalStyles';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Container from '@mui/material/Container';
import Tooltip from '@mui/material/Tooltip';
import IconButton from '@mui/material/IconButton';
import GitHubIcon from '@mui/icons-material/GitHub';
import SvgMuiLogomark from 'docs/src/icons/SvgMuiLogomark';
import HeaderNavBar from 'docs/src/components/header/HeaderNavBar';
import HeaderNavDropdown from 'docs/src/components/header/HeaderNavDropdown';
import ThemeModeToggle from 'docs/src/components/header/ThemeModeToggle';
import Link from 'docs/src/modules/components/Link';
import { DeferredAppSearch } from 'docs/src/modules/components/AppFrame';
import { useTranslate } from 'docs/src/modules/utils/i18n';
const Header = styled('header')(({ theme }) => [
{
position: 'sticky',
top: 0,
transition: theme.transitions.create('top'),
zIndex: theme.zIndex.appBar,
backdropFilter: 'blur(8px)',
boxShadow: `inset 0px -1px 1px ${(theme.vars || theme).palette.grey[100]}`,
backgroundColor: 'rgba(255,255,255,0.8)',
} as const,
theme.applyDarkStyles({
boxShadow: `inset 0px -1px 1px ${(theme.vars || theme).palette.primaryDark[700]}`,
backgroundColor: alpha(theme.palette.primaryDark[900], 0.7),
}),
]);
const HEIGHT = 60;
interface AppHeaderProps {
gitHubRepository?: string;
}
export default function AppHeader(props: AppHeaderProps) {
const { gitHubRepository = 'https://github.com/mui' } = props;
const t = useTranslate();
return (
<Header>
<GlobalStyles
styles={{
':root': {
'--MuiDocs-header-height': `${HEIGHT}px`,
},
}}
/>
<Container sx={{ display: 'flex', alignItems: 'center', minHeight: HEIGHT }}>
<Box component={Link} href="/" aria-label="Go to homepage" sx={{ lineHeight: 0, mr: 2 }}>
<SvgMuiLogomark width={30} />
</Box>
<Box sx={{ display: { xs: 'none', md: 'initial' } }}>
<HeaderNavBar />
</Box>
<Box sx={{ ml: 'auto' }} />
<Stack direction="row" spacing={1}>
<DeferredAppSearch />
<Tooltip title={t('appFrame.github')} enterDelay={300}>
<IconButton
component="a"
color="primary"
href={gitHubRepository}
target="_blank"
rel="noopener"
data-ga-event-category="header"
data-ga-event-action="github"
>
<GitHubIcon fontSize="small" />
</IconButton>
</Tooltip>
<ThemeModeToggle />
</Stack>
<Box sx={{ display: { md: 'none' }, ml: 1 }}>
<HeaderNavDropdown />
</Box>
</Container>
</Header>
);
}
| 5,244 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/layouts/HeroContainer.tsx | import * as React from 'react';
import Box, { BoxProps } from '@mui/material/Box';
import Container from '@mui/material/Container';
import Grid from '@mui/material/Grid';
import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils';
import { alpha } from '@mui/material/styles';
interface HeroContainerProps {
disableMobileHidden?: boolean;
disableTabExclusion?: boolean;
left: React.ReactElement;
linearGradient?: boolean;
right: React.ReactElement;
rightSx?: BoxProps['sx'];
}
export default function HeroContainer(props: HeroContainerProps) {
const {
disableMobileHidden,
disableTabExclusion = false,
left,
linearGradient,
right,
rightSx,
} = props;
const frame = React.useRef<HTMLDivElement>(null);
useEnhancedEffect(() => {
let obs: undefined | MutationObserver;
function suppressTabIndex() {
if (!disableTabExclusion) {
const elements = frame.current!.querySelectorAll(
'a, button, input, textarea, select, details, [tabindex]:not([tabindex="-1"])',
);
elements.forEach((elm) => {
elm.setAttribute('tabindex', '-1');
});
}
}
if (typeof MutationObserver !== 'undefined' && frame.current) {
obs = new MutationObserver(suppressTabIndex);
obs.observe(frame.current, { childList: true, subtree: true });
}
return () => {
if (obs) {
obs.disconnect();
}
};
}, [disableTabExclusion]);
const renderRightWrapper = (sx?: BoxProps['sx']) => (
<Box
ref={frame}
aria-hidden={disableTabExclusion ? undefined : 'true'}
sx={[
(theme) => ({
minWidth: '50vw',
minHeight: 500,
height: 'calc(100vh - 120px)',
maxHeight: { md: 700, xl: 1000 },
borderBottomLeftRadius: 12,
transition: 'max-height 0.3s',
position: 'relative',
overflow: 'hidden',
borderLeft: '1px solid',
borderBottom: '1px solid',
borderColor: 'divider',
...(linearGradient && {
background: `radial-gradient(farthest-corner circle at 0% 0%, ${
(theme.vars || theme).palette.grey[50]
} 0%, ${(theme.vars || theme).palette.primary[50]} 100%)`,
}),
}),
(theme) =>
theme.applyDarkStyles({
background: 'primaryDark.900',
borderColor: 'primaryDark.700',
...(linearGradient && {
background: `radial-gradient(farthest-corner circle at 0% 0%, ${alpha(
theme.palette.primary[900],
0.3,
)} 0%, ${(theme.vars || theme).palette.primaryDark[900]} 100%)`,
}),
}),
...(Array.isArray(sx) ? sx : [sx]),
...(Array.isArray(rightSx) ? rightSx : [rightSx]),
]}
>
{right}
</Box>
);
if (disableMobileHidden) {
return (
<Box sx={{ overflow: 'hidden' }}>
<Container
sx={{
minHeight: 500,
height: { md: 'calc(100vh - 120px)' },
maxHeight: { md: 700, xl: 1000 },
transition: '0.3s',
}}
>
<Grid container alignItems="center" sx={{ height: '100%', mx: 'auto' }}>
<Grid
item
xs={12}
md={7}
lg={6}
sx={{
display: { xs: 'flex', md: 'block' },
minHeight: { xs: 500, sm: 700, md: 'initial' },
m: 'auto',
'& > *': {
m: { xs: 'auto', md: 'initial' },
},
}}
>
{left}
</Grid>
<Grid item xs={12} md={5} lg={6} sx={{ maxHeight: '100%' }}>
{renderRightWrapper({
height: {
xs: 'initial',
md: 'calc(100vh - 120px)',
},
borderLeftWidth: { xs: 0, md: 1 },
borderBottomLeftRadius: { xs: 0, md: 12 },
mx: { xs: -2, sm: -3, md: 'initial' },
})}
</Grid>
</Grid>
</Container>
</Box>
);
}
return (
<Box sx={{ overflow: 'hidden' }}>
<Container
sx={{
minHeight: 500,
height: 'calc(100vh - 120px)',
maxHeight: { xs: 500, sm: 700, xl: 1000 },
transition: '0.3s',
}}
>
<Grid container alignItems="center" wrap="nowrap" sx={{ height: '100%', mx: 'auto' }}>
<Grid item md={7} lg={6} sx={{ m: 'auto' }}>
{left}
</Grid>
<Grid
item
md={5}
lg={6}
sx={{ maxHeight: '100%', display: { xs: 'none', md: 'initial' } }}
>
{renderRightWrapper()}
</Grid>
</Grid>
</Container>
</Box>
);
}
| 5,245 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/layouts/Section.tsx | import * as React from 'react';
import Container from '@mui/material/Container';
import Box, { BoxProps } from '@mui/material/Box';
import { alpha } from '@mui/material/styles';
interface SelectionProps extends BoxProps {
bg?: 'white' | 'comfort' | 'dim' | 'gradient' | 'transparent';
/**
* More spacing
*/
cozy?: boolean;
}
const map = {
white: {
light: 'common.white',
dark: 'primaryDark.800',
},
comfort: {
light: 'grey.50',
dark: 'primaryDark.900',
},
dim: {
light: 'primaryDark.700',
dark: 'primaryDark.700',
},
transparent: {
light: 'transparent',
dark: 'transparent',
},
};
const Section = React.forwardRef<HTMLDivElement, SelectionProps>(function Section(props, ref) {
const { bg = 'white', children, sx, cozy = false, ...other } = props;
return (
<Box
ref={ref}
{...other}
sx={[
(theme) => ({
...(bg === 'gradient'
? {
background: `linear-gradient(180deg, #FFF 0%, ${
(theme.vars || theme).palette.primary[50]
} 100%)`,
...theme.applyDarkStyles({
background: `linear-gradient(180deg, ${
(theme.vars || theme).palette.primaryDark[800]
} 0%, ${alpha(theme.palette.primary[900], 0.2)} 100%)`,
}),
}
: {
bgcolor: map[bg].light,
...theme.applyDarkStyles({
bgcolor: map[bg].dark,
}),
}),
py: cozy ? { xs: 6, sm: 10, md: 12 } : { xs: 4, sm: 12, md: 14 },
overflow: 'hidden',
}),
...(Array.isArray(sx) ? sx : [sx]),
]}
>
<Container>{children}</Container>
</Box>
);
});
export default Section;
| 5,246 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/modules/brandingTheme.ts | import { CSSObject } from '@mui/system';
import type {} from '@mui/material/themeCssVarsAugmentation';
import ArrowDropDownRounded from '@mui/icons-material/ArrowDropDownRounded';
import { createTheme, ThemeOptions, Theme, alpha } from '@mui/material/styles';
interface ApplyDarkStyles {
(scheme: CSSObject): CSSObject;
}
declare module '@mui/material/styles' {
interface Theme {
applyDarkStyles: ApplyDarkStyles;
}
}
declare module '@mui/material/styles/createPalette' {
interface ColorRange {
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
}
interface PaletteColor extends ColorRange {}
interface Palette {
primaryDark: PaletteColor;
gradients: {
lightGrayRadio: string;
stylizedRadio: string;
linearSubtle: string;
};
}
interface TypeText {
tertiary: string;
}
}
declare module '@mui/material/styles/createTypography' {
interface TypographyOptions {
fontWeightSemiBold?: number;
fontWeightExtraBold?: number;
fontFamilyCode?: string;
fontFamilySystem?: string;
}
interface Typography {
fontWeightSemiBold: number;
fontWeightExtraBold: number;
fontFamilyCode: string;
fontFamilySystem: string;
}
}
declare module '@mui/material/Chip' {
interface ChipPropsColorOverrides {
grey: true;
}
}
// TODO: enable this once types conflict is fixed
// declare module '@mui/material/Button' {
// interface ButtonPropsVariantOverrides {
// code: true;
// }
// }
const defaultTheme = createTheme();
export const blue = {
50: '#F0F7FF',
100: '#C2E0FF',
200: '#99CCF3',
300: '#66B2FF',
400: '#3399FF',
main: '#007FFF',
500: '#007FFF',
600: '#0072E5', // vs blueDark 900: WCAG 4.6 AAA (large), APCA 36 Not for reading text
700: '#0059B2',
800: '#004C99',
900: '#003A75',
};
export const blueDark = {
50: '#EAEDF1',
100: '#DAE0E7',
200: '#ACBAC8',
300: '#7B91A7',
main: '#7B91A7',
400: '#4B5E71',
500: '#3B4A59',
600: '#2F3A46',
700: '#1F262E', // contrast 13.64:1
800: '#141A1F',
900: '#101418',
};
export const grey = {
50: '#F3F6F9',
100: '#E5EAF2',
200: '#DAE2ED',
300: '#C7D0DD', // vs blueDark 900: WCAG 11.6 AAA, APCA 78 Best for text
400: '#B0B8C4', // vs blueDark 900: WCAG 9 AAA, APCA 63.3 Ok for text
500: '#9DA8B7', // vs blueDark 900: WCAG 7.5 AAA, APCA 54.3 Only for large text
600: '#6B7A90', // vs white bg: WCAG 4.1 AA, APCA 68.7 Ok for text
700: '#434D5B', // vs white bg: WCAG 8.3 AAA, APCA 88.7 Best for text
800: '#303740', // vs white bg: WCAG 11.9 AAA, APCA 97.3 Best for text
900: '#1C2025',
};
export const error = {
50: '#FFF0F1',
100: '#FFDBDE',
200: '#FFBDC2',
300: '#FF99A2',
400: '#FF7A86',
500: '#FF505F',
main: '#EB0014', // contrast 4.63:1
600: '#EB0014',
700: '#C70011',
800: '#94000D',
900: '#570007',
};
export const success = {
50: '#E9FBF0',
100: '#C6F6D9',
200: '#9AEFBC',
300: '#6AE79C',
400: '#3EE07F',
500: '#21CC66',
600: '#1DB45A',
700: '#1AA251',
800: '#178D46',
900: '#0F5C2E',
};
export const warning = {
50: '#FFF9EB',
100: '#FFF3C1',
200: '#FFECA1',
300: '#FFDC48', // vs blueDark900: WCAG 10.4 AAA, APCA 72 Ok for text
400: '#F4C000', // vs blueDark900: WCAG 6.4 AA normal, APCA 48 Only large text
500: '#DEA500', // vs blueDark900: WCAG 8 AAA normal, APCA 58 Only large text
main: '#DEA500',
600: '#D18E00', // vs blueDark900: WCAG 6.4 AA normal, APCA 48 Only large text
700: '#AB6800', // vs white bg: WCAG 4.4 AA large, APCA 71 Ok for text
800: '#8C5800', // vs white bg: WCAG 5.9 AAA large, APCA 80 Best for text
900: '#5A3600', // vs white bg: WCAG 10.7 AAA, APCA 95 Best for text
};
// context on the Advanced Perceptual Contrast Algorithm (APCA) used above here: https://github.com/w3c/wcag/issues/695
const systemFont = [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
];
export const getMetaThemeColor = (mode: 'light' | 'dark') => {
const themeColor = {
light: blue[600],
dark: blueDark[900],
};
return themeColor[mode];
};
export const getDesignTokens = (mode: 'light' | 'dark') =>
({
palette: {
primary: {
...blue,
...(mode === 'dark' && {
main: blue[400],
}),
},
secondary: {
...grey,
...(mode === 'light' && {
main: blueDark[100],
contrastText: blueDark[600],
}),
...(mode === 'dark' && {
main: blueDark[700],
contrastText: blueDark[600],
}),
},
divider: mode === 'dark' ? alpha(blueDark[100], 0.08) : grey[100],
primaryDark: blueDark,
mode,
...(mode === 'dark' && {
background: {
default: blueDark[800],
paper: blueDark[900],
},
}),
common: {
black: '#0B0D0E',
},
text: {
...(mode === 'light' && {
primary: grey[900],
secondary: grey[700],
tertiary: grey[600],
}),
...(mode === 'dark' && {
primary: '#fff',
secondary: grey[400],
tertiary: grey[400],
}),
},
grey: {
...grey,
...(mode === 'light' && {
main: grey[100],
contrastText: grey[600],
}),
...(mode === 'dark' && {
main: grey[700],
contrastText: grey[600],
}),
},
error,
success: {
...success,
...(mode === 'dark' && {
main: '#1DB45A', // contrast 6.17:1 (blueDark.800)
}),
...(mode === 'light' && {
main: '#1AA251', // contrast 3.31:1
}),
},
warning,
gradients: {
lightGrayRadio:
'radial-gradient(50% 50% at 50% 50%, #F0F7FF 0%, rgba(240, 247, 255, 0.05) 100%)',
stylizedRadio:
mode === 'dark'
? 'linear-gradient(rgba(0 0 0 / 0.1), rgba(0 0 0 / 0.1)), linear-gradient(254.86deg, rgba(0, 58, 117, 0.18) 0%, rgba(11, 13, 14, 0.3) 49.98%, rgba(0, 76, 153, 0.21) 100.95%)'
: 'linear-gradient(rgba(255 255 255 / 0.3), rgba(255 255 255 / 0.3)), linear-gradient(254.86deg, rgba(194, 224, 255, 0.12) 0%, rgba(194, 224, 255, 0.12) 0%, rgba(255, 255, 255, 0.3) 49.98%, rgba(240, 247, 255, 0.3) 100.95%)',
linearSubtle:
mode === 'light'
? `linear-gradient(to top right, ${alpha(blue[50], 0.3)} 40%, ${alpha(
grey[50],
0.2,
)} 100%)`
: `linear-gradient(to top right, ${alpha(blue[900], 0.1)} 40%, ${alpha(
blueDark[800],
0.2,
)} 100%)`,
},
},
shape: {
borderRadius: 12,
},
spacing: 8,
typography: {
fontFamily: ['"IBM Plex Sans"', ...systemFont].join(','),
// Match VS Code
// https://github.com/microsoft/vscode/blob/b38691f611d1ce3ef437c67a1b047c757b7b4e53/src/vs/editor/common/config/editorOptions.ts#L4578-L4580
// https://github.com/microsoft/vscode/blob/d950552131d7350a45dac8b59bf179469c36c2ac/src/vs/editor/standalone/browser/standalone-tokens.css#L10
fontFamilyCode: [
'Menlo', // macOS
'Consolas', // Windows
'"Droid Sans Mono"', // Linux
'monospace', // fallback
].join(','),
fontFamilyTagline: ['"General Sans"', ...systemFont].join(','),
fontFamilySystem: systemFont.join(','),
fontWeightSemiBold: 600,
fontWeightExtraBold: 800,
h1: {
fontFamily: ['"General Sans"', ...systemFont].join(','),
fontSize: 'clamp(2.5rem, 1.125rem + 3.5vw, 3.5em)',
fontWeight: 600,
lineHeight: 78 / 70,
letterSpacing: -0.2,
...(mode === 'light' && {
color: blueDark[900],
}),
},
h2: {
fontFamily: ['"General Sans"', ...systemFont].join(','),
fontSize: 'clamp(1.5rem, 0.9643rem + 1.4286vw, 2.25rem)',
fontWeight: 600,
lineHeight: 44 / 36,
letterSpacing: -0.2,
color: mode === 'dark' ? grey[100] : blueDark[700],
},
h3: {
fontFamily: ['"General Sans"', ...systemFont].join(','),
fontSize: defaultTheme.typography.pxToRem(36),
lineHeight: 44 / 36,
letterSpacing: 0.2,
},
h4: {
fontFamily: ['"General Sans"', ...systemFont].join(','),
fontSize: defaultTheme.typography.pxToRem(30),
lineHeight: 42 / 28,
letterSpacing: 0.2,
},
h5: {
fontSize: defaultTheme.typography.pxToRem(24),
lineHeight: 36 / 24,
letterSpacing: 0.1,
color: mode === 'dark' ? blue[300] : blue.main,
},
h6: {
fontSize: defaultTheme.typography.pxToRem(20),
lineHeight: 30 / 20,
},
button: {
textTransform: 'initial',
fontWeight: 700,
letterSpacing: 0,
},
subtitle1: {
fontSize: defaultTheme.typography.pxToRem(18),
lineHeight: 24 / 18,
letterSpacing: 0,
fontWeight: 500,
},
body1: {
fontSize: defaultTheme.typography.pxToRem(16), // 16px
lineHeight: 24 / 16,
letterSpacing: 0,
},
body2: {
fontSize: defaultTheme.typography.pxToRem(14), // 14px
lineHeight: 21 / 14,
letterSpacing: 0,
},
caption: {
display: 'inline-block',
fontSize: defaultTheme.typography.pxToRem(12), // 12px
lineHeight: 18 / 12,
letterSpacing: 0,
fontWeight: 700,
},
allVariants: {
scrollMarginTop: 'calc(var(--MuiDocs-header-height) + 32px)',
},
},
/**
* This utility exists to help transitioning to CSS variables page by page (prevent dark mode flicker).
* It will use the proper styling method based on the theme because the component might be on the page that does not support CSS variables yet.
*
* 😓 Without this utility:
* {
* ...theme.vars ? {
* color: theme.vars.palette.primary.main,
* [theme.getColorScheme('dark')]: {
* color: '#fff',
* }
* } : {
* color: theme.palette.mode === 'dark' ? '#fff' : theme.palette.primary.main,
* }
* }
*
* 🤩 Using the utility:
* {
* color: (theme.vars || theme).palette.primary.main,
* ...theme.applyDarkStyles({
* color: '#fff',
* }),
* }
*
* -------------------------------------------------------------------------------------------------
* 💡 This util should be used in an array if the styles contain pseudo classes or nested selectors:
*
* ❌ There is a chance that the upper selectors could be overridden
* {
* // the whole selector could be overridden
* '&::before': {
* color: ...
* },
* ...theme.applyDarkStyles({
* '&::before': {
* color: ...
* }
* })
* }
*
* ✅ use an array (supports in both emotion and styled-components)
* Only the `color` will be overridden in dark mode.
* [
* '&::before': {
* color: ...
* },
* theme.applyDarkStyles({
* '&::before': {
* color: ...
* }
* })
* ]
*/
applyDarkStyles(css: Parameters<ApplyDarkStyles>[0]) {
if ((this as Theme).vars) {
// If CssVarsProvider is used as a provider,
// returns ':where([data-mui-color-scheme="light|dark"]) &'
const selector = (this as Theme)
.getColorSchemeSelector('dark')
.replace(/(\[[^\]]+\])/, ':where($1)');
return {
[selector]: css,
};
}
if ((this as Theme).palette.mode === 'dark') {
return css;
}
return undefined;
},
} as ThemeOptions);
export function getThemedComponents(): ThemeOptions {
return {
components: {
MuiAlert: {
styleOverrides: {
root: {
padding: '12px 16px',
},
standardWarning: ({ theme }) => [
{
backgroundColor: alpha(theme.palette.warning[50], 0.5),
color: (theme.vars || theme).palette.grey[900],
border: '1px solid',
borderColor: alpha(theme.palette.warning[600], 0.3),
'& .MuiAlert-icon': {
color: (theme.vars || theme).palette.warning[700],
},
},
theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.warning[700], 0.2),
color: (theme.vars || theme).palette.warning[50],
'& .MuiAlert-icon': {
color: (theme.vars || theme).palette.warning[200],
},
}),
],
icon: {
paddingTop: 12,
paddingBottom: 0,
},
},
},
MuiButtonBase: {
defaultProps: {
disableTouchRipple: true,
},
},
MuiButton: {
defaultProps: {
disableElevation: true,
},
styleOverrides: {
root: ({ theme, ownerState }) => ({
...(ownerState.size === 'large' && {
...theme.typography.body1,
lineHeight: 21 / 16,
fontWeight: theme.typography.fontWeightBold,
padding: theme.spacing('12px', '12px', '12px', '14px'),
minHeight: 0,
'& > span': { transition: '0.2s', marginLeft: 4 },
'&:hover > span': { transform: 'translateX(2px)' },
}),
...(ownerState.size === 'medium' && {
padding: theme.spacing('8px', '12px'),
'& > span': { transition: '0.2s', marginLeft: 4 },
'&:hover > span': { transform: 'translateX(2px)' },
}),
...(ownerState.size === 'small' && {
padding: theme.spacing('6px', 1),
fontFamily: theme.typography.fontFamily,
fontSize: defaultTheme.typography.pxToRem(13),
fontWeight: theme.typography.fontWeightSemiBold,
borderRadius: 8,
'& .MuiButton-startIcon': {
transition: '0.15s',
marginRight: 4,
marginLeft: -1,
},
'& .MuiButton-endIcon': {
transition: '0.15s',
marginLeft: 4,
},
'&:hover': {
'& .MuiButton-startIcon': { transform: 'translateX(-2px)' },
'& .MuiButton-endIcon': { transform: 'translateX(2px)' },
},
}),
...(ownerState.variant === 'outlined' &&
ownerState.color === 'secondary' && {
color: (theme.vars || theme).palette.text.secondary,
backgroundColor: alpha(theme.palette.primaryDark[50], 0.3),
borderColor: (theme.vars || theme).palette.primaryDark[100],
boxShadow: `0px 2px 1px ${alpha(
theme.palette.grey[200],
0.3,
)}, inset 0px 2px 3px ${alpha(theme.palette.primaryDark[100], 0.2)}`,
'&:hover': {
background: (theme.vars || theme).palette.primaryDark[50],
},
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primaryDark[100],
borderColor: (theme.vars || theme).palette.primaryDark[600],
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
boxShadow: `0px 2px 1px ${theme.palette.common.black}, inset 0px 2px 3px ${alpha(
theme.palette.primaryDark[500],
0.3,
)}`,
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primaryDark[600],
},
}),
}),
...(ownerState.variant === 'outlined' &&
ownerState.color === 'primary' && {
color: (theme.vars || theme).palette.primary[500],
backgroundColor: alpha(theme.palette.primary[50], 0.3),
borderColor: (theme.vars || theme).palette.primary[100],
boxShadow: `0px 1px 1px ${alpha(
theme.palette.primary[100],
0.5,
)}, inset 0px 4px 2px ${alpha(theme.palette.primary[100], 0.1)}`,
'&:hover': {
background: (theme.vars || theme).palette.primary[50],
borderColor: (theme.vars || theme).palette.primary[300],
},
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[200],
borderColor: (theme.vars || theme).palette.primary[900],
backgroundColor: alpha(theme.palette.primary[900], 0.2),
boxShadow: '0px 2px 2px #0B0D0E, inset 0px 4px 4px rgba(20, 25, 31, 0.3)',
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[900],
borderColor: (theme.vars || theme).palette.primary[700],
},
}),
}),
...(ownerState.variant === 'contained' &&
ownerState.color === 'primary' && {
color: '#FFF',
backgroundImage: `linear-gradient(180deg, ${alpha(
theme.palette.primary[300],
0.5,
)} 0%, ${alpha(theme.palette.primary[600], 0.5)} 100%)`,
boxShadow: `0px 1px 2px ${alpha(
theme.palette.primary[900],
0.1,
)}, inset 0px 0px 0px 1px ${
theme.palette.primary[600]
}, inset 0px 0px 0px 2px rgba(255, 255, 255, 0.2), 0px 2px 1px ${alpha(
theme.palette.primary[200],
0.3,
)} `,
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[600],
},
textShadow: `0px 1px 1px ${alpha(theme.palette.grey[900], 0.3)}`,
...theme.applyDarkStyles({
backgroundImage: `linear-gradient(180deg, ${alpha(
theme.palette.primary[400],
0.2,
)} 0%, ${alpha(theme.palette.primary[700], 0.8)} 100%)`,
boxShadow: `0px 1px 2px ${alpha(
theme.palette.primary[900],
0.1,
)}, inset 0px 0px 0px 1px ${
theme.palette.primary[600]
}, inset 0px 0px 0px 2px rgba(255, 255, 255, 0.1), 0px 2px 1px ${
theme.palette.common.black
} `,
}),
}),
}),
},
variants: [
{
// @ts-ignore internal repo module augmentation issue
props: { variant: 'code' },
style: ({ theme }) => [
{
cursor: 'copy',
padding: 0,
width: 'max-content',
backgroundColor: 'transparent',
color: (theme.vars || theme).palette.grey[600],
fontFamily: theme.typography.fontFamilyCode,
fontWeight: 400,
fontSize: defaultTheme.typography.pxToRem(12),
lineHeight: 21 / 14,
letterSpacing: 0,
WebkitFontSmoothing: 'subpixel-antialiased',
'& .MuiButton-startIcon': {
color: (theme.vars || theme).palette.grey[400],
},
'& .MuiButton-endIcon': {
display: 'inline-block',
position: 'absolute',
color: (theme.vars || theme).palette.primary.main,
right: -22,
top: -1,
opacity: 0,
transitionProperty: 'opacity',
transitionDuration: '100ms',
transitionTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
},
'&:hover, &.Mui-focusVisible': {
backgroundColor: 'transparent',
color: (theme.vars || theme).palette.primary.main,
'& .MuiButton-endIcon': {
color: (theme.vars || theme).palette.primary.main,
opacity: 1,
},
},
},
theme.applyDarkStyles({
'& .MuiButton-endIcon': {
color: (theme.vars || theme).palette.primary[300],
},
'&:hover, &.Mui-focusVisible': {
color: (theme.vars || theme).palette.primary[300],
'& .MuiButton-endIcon': {
opacity: 1,
},
},
}),
],
},
{
// @ts-ignore internal repo module augmentation issue
props: { variant: 'codeOutlined' },
style: ({ theme }) => [
{
display: 'inline-block',
justifyContent: 'start',
overflowX: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
position: 'relative',
border: '1px solid',
color: (theme.vars || theme).palette.grey[900],
backgroundColor: alpha(theme.palette.primary[50], 0.3),
borderColor: (theme.vars || theme).palette.grey[200],
boxShadow: `0px 2px 2px ${alpha(
theme.palette.primary[100],
0.2,
)}, inset 0px 4px 4px ${alpha(theme.palette.primary[100], 0.2)}`,
fontFamily: theme.typography.fontFamilyCode,
fontWeight: 400,
fontSize: defaultTheme.typography.pxToRem(12),
lineHeight: 21 / 14,
letterSpacing: 0,
WebkitFontSmoothing: 'subpixel-antialiased',
'& .MuiButton-endIcon': {
display: 'inline-block',
position: 'absolute',
top: 12,
right: 0,
marginRight: 10,
color: (theme.vars || theme).palette.grey[600],
},
'&:hover, &.Mui-focusVisible': {
borderColor: (theme.vars || theme).palette.primary.main,
backgroundColor: (theme.vars || theme).palette.primary[50],
color: (theme.vars || theme).palette.primary[600],
'& .MuiButton-endIcon': {
color: (theme.vars || theme).palette.primary.main,
},
},
} as const,
theme.applyDarkStyles({
color: (theme.vars || theme).palette.grey[500],
borderColor: (theme.vars || theme).palette.primaryDark[600],
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
boxShadow: '0px 2px 2px #0B0D0E, inset 0px 4px 4px rgba(20, 25, 31, 0.3)',
'& .MuiButton-endIcon': {
color: (theme.vars || theme).palette.grey[400],
},
'&:hover, &.Mui-focusVisible': {
backgroundColor: (theme.vars || theme).palette.primary[900],
color: (theme.vars || theme).palette.primary[100],
'& .MuiButton-endIcon': {
color: (theme.vars || theme).palette.primary[300],
},
},
}),
],
},
{
// @ts-ignore internal repo module augmentation issue
props: { variant: 'link' },
style: ({ theme }) => ({
marginBottom: 1,
fontSize: theme.typography.pxToRem(14),
fontWeight: theme.typography.fontWeightBold,
color: (theme.vars || theme).palette.primary[600],
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[50],
},
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[300],
'&:hover': {
backgroundColor: alpha(theme.palette.primary[800], 0.3),
},
}),
}),
},
],
},
MuiIconButton: {
variants: [
{
props: { color: 'primary' },
style: ({ theme }) => [
{
height: 34,
width: 34,
border: `1px solid`,
borderColor: (theme.vars || theme).palette.grey[200],
color: (theme.vars || theme).palette.primary[500],
borderRadius: theme.shape.borderRadius,
boxShadow: `inset 0 1px 2px ${
(theme.vars || theme).palette.grey[50]
}, 0 1px 0.5px ${alpha(theme.palette.grey[100], 0.6)}`,
'&:hover': {
borderColor: (theme.vars || theme).palette.grey[300],
background: (theme.vars || theme).palette.grey[50],
},
},
theme.applyDarkStyles({
borderColor: (theme.vars || theme).palette.primaryDark[700],
color: (theme.vars || theme).palette.primary[300],
boxShadow: `inset 0 1px 1px ${
(theme.vars || theme).palette.primaryDark[900]
}, 0 1px 0.5px ${(theme.vars || theme).palette.common.black}`,
'&:hover': {
borderColor: (theme.vars || theme).palette.primaryDark[600],
background: alpha(theme.palette.primaryDark[700], 0.4),
},
}),
],
},
{
props: { color: 'info' },
style: ({ theme }) => [
{
height: 34,
width: 34,
border: `1px solid`,
borderColor: (theme.vars || theme).palette.grey[200],
color: (theme.vars || theme).palette.grey[600],
borderRadius: theme.shape.borderRadius,
boxShadow: `inset 0 1px 2px ${
(theme.vars || theme).palette.grey[50]
}, 0 1px 0.5px ${alpha(theme.palette.grey[100], 0.6)}`,
'&:hover': {
color: (theme.vars || theme).palette.primary.main,
borderColor: (theme.vars || theme).palette.grey[300],
background: (theme.vars || theme).palette.grey[50],
},
},
theme.applyDarkStyles({
borderColor: (theme.vars || theme).palette.primaryDark[700],
color: (theme.vars || theme).palette.grey[400],
boxShadow: `inset 0 1px 1px ${
(theme.vars || theme).palette.primaryDark[900]
}, 0 1px 0.5px ${(theme.vars || theme).palette.common.black}`,
'&:hover': {
color: (theme.vars || theme).palette.primary[400],
borderColor: (theme.vars || theme).palette.primaryDark[600],
background: alpha(theme.palette.primaryDark[700], 0.4),
},
}),
],
},
],
},
MuiMenu: {
styleOverrides: {
paper: ({ theme }) => [
{
minWidth: 160,
color: (theme.vars || theme).palette.text.secondary,
backgroundImage: 'none',
border: '1px solid',
backgroundColor: (theme.vars || theme).palette.background.paper,
borderColor: (theme.vars || theme).palette.grey[200],
'& .MuiMenuItem-root': {
fontSize: theme.typography.pxToRem(14),
fontWeight: 500,
'&:hover, &:focus': {
backgroundColor: (theme.vars || theme).palette.grey[50],
},
'&.Mui-selected': {
fontWeight: 500,
color: (theme.vars || theme).palette.primary[600],
backgroundColor: alpha(theme.palette.primary[100], 0.6),
},
},
},
theme.applyDarkStyles({
backgroundColor: (theme.vars || theme).palette.primaryDark[900],
borderColor: (theme.vars || theme).palette.primaryDark[700],
'& .MuiMenuItem-root': {
'&:hover, &:focus': {
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
},
'&.Mui-selected': {
color: (theme.vars || theme).palette.primary[300],
backgroundColor: alpha(theme.palette.primary[900], 0.4),
},
},
}),
],
},
},
MuiPopover: {
styleOverrides: {
paper: ({ theme }) => ({
boxShadow: '0px 4px 20px rgba(170, 180, 190, 0.3)',
...theme.applyDarkStyles({
boxShadow: '0px 4px 20px rgba(0, 0, 0, 0.5)',
}),
}),
},
},
MuiDivider: {
styleOverrides: {
root: ({ theme }) => ({
borderColor: (theme.vars || theme).palette.grey[100],
...theme.applyDarkStyles({
borderColor: alpha(theme.palette.primary[100], 0.08),
}),
}),
},
},
MuiLink: {
defaultProps: {
underline: 'none',
},
styleOverrides: {
root: {
fontWeight: 700,
display: 'inline-flex',
alignItems: 'center',
'&.MuiTypography-body1 > svg': {
marginTop: 2,
},
'& svg:last-child': {
marginLeft: 2,
},
},
},
variants: [
{
props: { color: 'primary' },
style: ({ theme }) => [
{
color: (theme.vars || theme).palette.primary[600],
'&:hover': {
color: (theme.vars || theme).palette.primary[700],
},
},
theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[300],
'&:hover': {
color: (theme.vars || theme).palette.primary[200],
},
}),
],
},
],
},
MuiChip: {
styleOverrides: {
root: ({ ownerState: { color, variant }, theme }) => ({
fontWeight: theme.typography.fontWeightSemiBold,
...(variant === 'outlined' &&
color === 'default' && {
backgroundColor: alpha(theme.palette.grey[50], 0.5),
color: (theme.vars || theme).palette.grey[900],
borderColor: (theme.vars || theme).palette.grey[200],
'&:hover': {
backgroundColor: (theme.vars || theme).palette.grey[100],
color: (theme.vars || theme).palette.grey[900],
},
...theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primaryDark[700], 0.4),
color: (theme.vars || theme).palette.grey[300],
borderColor: alpha(theme.palette.primaryDark[500], 0.5),
'&:hover': {
color: (theme.vars || theme).palette.grey[300],
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
},
}),
}),
...(variant === 'outlined' &&
color === 'primary' && {
borderColor: (theme.vars || theme).palette.primary[200],
...theme.applyDarkStyles({
borderColor: alpha(theme.palette.primary[500], 0.3),
}),
}),
...(variant === 'filled' && {
...(color === 'default' && {
border: '1px solid transparent',
color: (theme.vars || theme).palette.primary[700],
backgroundColor: alpha(theme.palette.primary[100], 0.5),
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[100],
},
...theme.applyDarkStyles({
color: '#fff',
backgroundColor: alpha(theme.palette.primaryDark[500], 0.8),
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primaryDark[600],
},
}),
}),
...(color === 'primary' && {
color: (theme.vars || theme).palette.primary[600],
backgroundColor: alpha(theme.palette.primary[100], 0.4),
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[100],
},
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[100],
backgroundColor: alpha(theme.palette.primary[800], 0.5),
'&:hover': {
backgroundColor: alpha(theme.palette.primary[900], 0.5),
},
}),
}),
}),
// for labelling product in the search
// @ts-ignore internal repo module augmentation issue
...(variant === 'light' && {
...(color === 'default' && {
color: (theme.vars || theme).palette.primary[700],
backgroundColor: alpha(theme.palette.primary[100], 0.3),
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[200],
backgroundColor: alpha(theme.palette.primaryDark[700], 0.5),
}),
}),
...(color === 'warning' && {
color: (theme.vars || theme).palette.warning[900],
backgroundColor: (theme.vars || theme).palette.warning[100],
...theme.applyDarkStyles({
color: '#fff',
backgroundColor: (theme.vars || theme).palette.warning[900],
}),
}),
...(color === 'success' && {
color: (theme.vars || theme).palette.success[900],
backgroundColor: (theme.vars || theme).palette.success[100],
...theme.applyDarkStyles({
color: '#fff',
backgroundColor: (theme.vars || theme).palette.success[900],
}),
}),
}),
}),
},
},
MuiList: {
styleOverrides: {
root: {
padding: 0,
},
},
},
MuiListItemButton: {
styleOverrides: {
root: ({ theme }) => [
{
padding: '8px',
textTransform: 'none',
fontWeight: 500,
fontSize: theme.typography.pxToRem(14),
color: theme.palette.grey[700],
borderRadius: 0,
'&:hover': {
backgroundColor: theme.palette.grey[50],
},
'&.Mui-selected': {
borderRadius: 10,
border: '1px solid',
color: (theme.vars || theme).palette.primary[500],
borderColor: `${(theme.vars || theme).palette.primary[500]} !important`,
backgroundColor: (theme.vars || theme).palette.primary[50],
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[100],
},
},
} as const,
theme.applyDarkStyles({
color: theme.palette.grey[300],
'&:hover': {
backgroundColor: alpha(theme.palette.primaryDark[700], 0.4),
},
'&.Mui-selected': {
color: '#fff',
borderColor: `${(theme.vars || theme).palette.primary[700]} !important`,
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primaryDark[600],
},
},
}),
],
},
},
MuiSelect: {
defaultProps: {
IconComponent: ArrowDropDownRounded,
},
styleOverrides: {
iconFilled: {
top: 'calc(50% - .25em)',
},
},
},
MuiTab: {
defaultProps: {
disableTouchRipple: true,
},
},
MuiPaper: {
styleOverrides: {
root: ({ theme, ownerState }) => [
{
backgroundImage: 'none',
backgroundColor: '#fff',
'&[href]': {
textDecorationLine: 'none',
},
transition: theme.transitions.create(['border', 'box-shadow'], {
duration: theme.transitions.duration.shortest,
}),
...(ownerState.variant === 'outlined' && {
display: 'block',
borderColor: (theme.vars || theme).palette.grey[100],
'&[href]': {
textDecorationLine: 'none',
boxShadow: `inset 0 1px 2px ${
(theme.vars || theme).palette.grey[50]
}, 0 1px 0.5px ${alpha(theme.palette.grey[100], 0.6)}`,
'&:hover': {
borderColor: (theme.vars || theme).palette.primary[200],
boxShadow: `0px 4px 16px ${(theme.vars || theme).palette.grey[200]}`,
},
},
':is(a&), :is(button&)': {
'&:hover': {
borderColor: (theme.vars || theme).palette.primary[200],
boxShadow: `0px 4px 16px ${(theme.vars || theme).palette.grey[200]}`,
},
},
}),
},
theme.applyDarkStyles({
backgroundColor: (theme.vars || theme).palette.primaryDark[900],
...(ownerState.variant === 'outlined' && {
borderColor: (theme.vars || theme).palette.primaryDark[600],
backgroundColor: alpha(theme.palette.primaryDark[700], 0.5),
'&[href]': {
textDecorationLine: 'none',
boxShadow: `inset 0 1px 1px ${
(theme.vars || theme).palette.primaryDark[900]
}, 0 1px 0.5px ${(theme.vars || theme).palette.common.black}`,
'&:hover': {
borderColor: (theme.vars || theme).palette.primary[700],
boxShadow: `0px 4px 24px ${(theme.vars || theme).palette.common.black}`,
},
},
':is(a&), :is(button&)': {
'&:hover': {
boxShadow: `0px 4px 24px ${(theme.vars || theme).palette.common.black}`,
},
},
}),
}),
],
},
},
MuiTableCell: {
styleOverrides: {
root: ({ theme, ownerState }) => ({
padding: theme.spacing(1, 2),
borderColor: (theme.vars || theme).palette.divider,
...(ownerState.variant === 'head' && {
color: (theme.vars || theme).palette.text.primary,
fontWeight: 700,
}),
...(ownerState.variant === 'body' && {
color: (theme.vars || theme).palette.text.secondary,
}),
}),
},
},
MuiToggleButtonGroup: {
styleOverrides: {
root: ({ theme }) => ({
backgroundColor: '#fff',
...theme.applyDarkStyles({
backgroundColor: (theme.vars || theme).palette.primaryDark[900],
}),
}),
},
},
MuiToggleButton: {
styleOverrides: {
root: ({ theme, ownerState }) => [
{
textTransform: 'none',
fontWeight: 500,
color: theme.palette.grey[700],
borderColor: theme.palette.grey[200],
...(ownerState.size === 'small' && {
padding: '0.375rem 0.75rem',
}),
'&.Mui-selected': {
color: (theme.vars || theme).palette.primary[500],
borderColor: `${(theme.vars || theme).palette.primary[500]} !important`,
backgroundColor: (theme.vars || theme).palette.primary[50],
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[100],
},
},
} as const,
theme.applyDarkStyles({
color: theme.palette.grey[300],
borderColor: theme.palette.primaryDark[500],
'&.Mui-selected': {
color: (theme.vars || theme).palette.primary[200],
borderColor: `${(theme.vars || theme).palette.primary[700]} !important`,
backgroundColor: alpha(theme.palette.primary[900], 0.4),
'&:hover': {
backgroundColor: alpha(theme.palette.primary[900], 0.8),
borderColor: `${(theme.vars || theme).palette.primary[400]} !important`,
},
},
}),
],
},
},
MuiTooltip: {
styleOverrides: {
tooltip: {
borderRadius: 6,
padding: '6px 12px',
},
},
},
MuiSwitch: {
styleOverrides: {
root: {
width: 32,
height: 20,
padding: 0,
'& .MuiSwitch-switchBase': {
'&.Mui-checked': {
transform: 'translateX(11px)',
color: '#fff',
},
},
},
switchBase: {
height: 20,
width: 20,
padding: 0,
color: '#fff',
'&.Mui-checked + .MuiSwitch-track': {
opacity: 1,
},
},
track: ({ theme }) => ({
opacity: 1,
borderRadius: 32,
backgroundColor: theme.palette.grey[400],
...theme.applyDarkStyles({
backgroundColor: theme.palette.grey[800],
}),
}),
thumb: {
flexShrink: 0,
width: '14px',
height: '14px',
},
},
},
MuiPaginationItem: {
styleOverrides: {
root: ({ theme }) => [
{
textTransform: 'none',
fontWeight: 700,
color: theme.palette.grey[700],
borderColor: theme.palette.grey[200],
'&.Mui-selected': {
color: (theme.vars || theme).palette.primary[500],
borderColor: `${(theme.vars || theme).palette.primary[500]} !important`,
backgroundColor: (theme.vars || theme).palette.primary[50],
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[100],
},
},
} as const,
theme.applyDarkStyles({
color: theme.palette.grey[300],
borderColor: theme.palette.primaryDark[500],
'&.Mui-selected': {
color: '#fff',
borderColor: `${(theme.vars || theme).palette.primary[700]} !important`,
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primaryDark[600],
},
},
}),
],
},
},
MuiCssBaseline: {
defaultProps: {
enableColorScheme: true,
},
},
},
};
}
export const brandingDarkTheme = createTheme({
...getDesignTokens('dark'),
...getThemedComponents(),
});
export const brandingLightTheme = createTheme({
...getDesignTokens('light'),
...getThemedComponents(),
});
| 5,247 |
0 | petrpan-code/mui/material-ui/docs/src | petrpan-code/mui/material-ui/docs/src/modules/constants.js | const CODE_VARIANTS = {
JS: 'JS',
TS: 'TS',
};
const CODE_STYLING = {
SYSTEM: 'MUI System',
TAILWIND: 'Tailwind',
CSS: 'CSS',
};
// Valid languages to use in production
const LANGUAGES_LABEL = [
{
code: 'en',
text: 'English',
},
];
module.exports = {
CODE_VARIANTS,
LANGUAGES_LABEL,
CODE_STYLING,
};
| 5,248 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/Ad.js | import * as React from 'react';
import PropTypes from 'prop-types';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import AdCarbon from 'docs/src/modules/components/AdCarbon';
import AdInHouse from 'docs/src/modules/components/AdInHouse';
import { AdContext, adShape } from 'docs/src/modules/components/AdManager';
import { useTranslate } from 'docs/src/modules/utils/i18n';
function PleaseDisableAdblock(props) {
const t = useTranslate();
return (
<Paper
component="span"
elevation={0}
sx={{ display: 'block', p: 1.5, border: '2px solid', borderColor: 'primary.main' }}
{...props}
>
<Typography variant="body2" display="block" component="span" gutterBottom>
{t('likeMui')}
</Typography>
<Typography variant="body2" display="block" component="span" gutterBottom>
{t('adblock')}
</Typography>
<Typography variant="body2" display="block" component="span" gutterBottom>
{t('thanks')}{' '}
<span role="img" aria-label={t('emojiLove')}>
❤️
</span>
</Typography>
</Paper>
);
}
const disableAd =
process.env.NODE_ENV !== 'production' && process.env.ENABLE_AD_IN_DEV_MODE !== 'true';
const inHouseAds = [
{
name: 'scaffoldhub',
link: 'https://v2.scaffoldhub.io/scaffolds/react-material-ui?partner=1',
img: '/static/ads-in-house/scaffoldhub.png',
description: '<b>ScaffoldHub</b>. Automate building your full-stack Material UI web-app.',
},
{
name: 'templates',
link: 'https://mui.com/store/?utm_source=docs&utm_medium=referral&utm_campaign=in-house-templates',
img: '/static/ads-in-house/themes-2.jpg',
description:
'<b>Premium Templates</b>. Start your project with the best templates for admins, dashboards, and more.',
},
{
name: 'themes',
link: 'https://mui.com/store/?utm_source=docs&utm_medium=referral&utm_campaign=in-house-themes',
img: '/static/ads-in-house/themes.png',
description:
'<b>Premium Themes</b>. Kickstart your application development with a ready-made theme.',
},
{
name: 'tidelift',
link: 'https://tidelift.com/subscription/pkg/npm-material-ui?utm_source=npm-material-ui&utm_medium=referral&utm_campaign=enterprise&utm_content=ad',
img: '/static/ads-in-house/tidelift.png',
description:
'<b>MUI for enterprise</b>. Save time and reduce risk. Managed open source — backed by maintainers.',
},
{
name: 'figma',
link: 'https://mui.com/store/items/figma-react/?utm_source=docs&utm_medium=referral&utm_campaign=in-house-figma',
img: '/static/ads-in-house/figma.png',
description:
'<b>For Figma</b>. A large UI kit with over 600 handcrafted Material UI, MUI X, Joy UI components 🎨.',
},
];
class AdErrorBoundary extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
eventLabel: PropTypes.string,
};
state = { didError: false };
static getDerivedStateFromError() {
return { didError: true };
}
componentDidCatch() {
// send explicit `'null'`
const eventLabel = String(this.props.eventLabel);
// TODO: Use proper error monitoring service (e.g. Sentry) instead
window.gtag('event', 'ad', {
eventAction: 'crash',
eventLabel,
});
}
render() {
const { didError } = this.state;
const { children } = this.props;
if (didError) {
return null;
}
return children;
}
}
export const AD_MARGIN_TOP = 3;
export const AD_MARGIN_BOTTOM = 3;
export const AD_HEIGHT = 126;
// https://stackoverflow.com/a/20084661
function isBot() {
return /bot|googlebot|crawler|spider|robot|crawling/i.test(navigator.userAgent);
}
export default function Ad() {
const [adblock, setAdblock] = React.useState(null);
const [carbonOut, setCarbonOut] = React.useState(null);
const { current: randomAdblock } = React.useRef(Math.random());
const { current: randomInHouse } = React.useRef(Math.random());
let children;
let label;
// Hide the content to google bot to avoid its indexation.
if ((typeof window !== 'undefined' && isBot()) || disableAd) {
children = <span />;
} else if (adblock) {
if (randomAdblock < 0.2) {
children = <PleaseDisableAdblock />;
label = 'in-house-adblock';
} else {
children = <AdInHouse ad={inHouseAds[Math.floor(inHouseAds.length * randomInHouse)]} />;
label = 'in-house';
}
} else if (carbonOut) {
children = <AdInHouse ad={inHouseAds[Math.floor(inHouseAds.length * randomInHouse)]} />;
label = 'in-house-carbon';
} else {
children = <AdCarbon />;
label = 'carbon';
}
const ad = React.useContext(AdContext);
const eventLabel = label ? `${label}-${ad.placement}-${adShape}` : null;
const timerAdblock = React.useRef();
const checkAdblock = React.useCallback(
(attempt = 1) => {
if (
document.querySelector('.ea-placement') ||
document.querySelector('#carbonads') ||
document.querySelector('.carbonads') ||
carbonOut
) {
if (
document.querySelector('#carbonads a') &&
document.querySelector('#carbonads a').getAttribute('href') ===
'https://material-ui-next.com/discover-more/backers'
) {
setCarbonOut(true);
}
setAdblock(false);
return;
}
if (attempt < 30) {
timerAdblock.current = setTimeout(() => {
checkAdblock(attempt + 1);
}, 500);
}
if (attempt > 6) {
setAdblock(true);
}
},
[carbonOut],
);
React.useEffect(() => {
if (disableAd) {
return undefined;
}
checkAdblock();
return () => {
clearTimeout(timerAdblock.current);
};
}, [checkAdblock]);
React.useEffect(() => {
// Avoid an exceed on the Google Analytics quotas.
if (Math.random() < 0.9 || !eventLabel) {
return undefined;
}
const delay = setTimeout(() => {
window.gtag('event', 'ad', {
eventAction: 'display',
eventLabel,
});
}, 2500);
return () => {
clearTimeout(delay);
};
}, [eventLabel]);
return (
<Box
component="span"
sx={{
position: 'relative',
display: 'block',
mt: AD_MARGIN_TOP,
mb: AD_MARGIN_BOTTOM,
...(adShape === 'image' && {
minHeight: AD_HEIGHT,
}),
...(adShape === 'inline' && {
minHeight: AD_HEIGHT,
display: 'flex',
alignItems: 'flex-end',
}),
...(adShape === 'inline2' && {
minHeight: AD_HEIGHT,
display: 'flex',
alignItems: 'flex-end',
}),
}}
data-ga-event-category="ad"
data-ga-event-action="click"
data-ga-event-label={eventLabel}
>
<AdErrorBoundary eventLabel={eventLabel}>{children}</AdErrorBoundary>
</Box>
);
}
| 5,249 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AdCarbon.js | import * as React from 'react';
import { styled } from '@mui/material/styles';
import loadScript from 'docs/src/modules/utils/loadScript';
import AdDisplay from 'docs/src/modules/components/AdDisplay';
import { adStylesObject } from 'docs/src/modules/components/ad.styles';
const CarbonRoot = styled('span')(({ theme }) => {
const styles = adStylesObject['body-image'](theme);
return {
'& > div': {
// The isolation logic of carbonads is broken.
// Once the script starts loading, it will asynchronous resolve, with no way to stop it.
// This leads to duplication of the ad.
//
// To solve the issue, we only display the #carbonads div
display: 'none',
},
'& #carbonads': {
display: 'block',
...styles.root,
'& .carbon-img': styles.imgWrapper,
'& img': styles.img,
'& a, & a:hover': styles.a,
'& .carbon-text': styles.description,
'& .carbon-poweredby': styles.poweredby,
},
};
});
function AdCarbonImage() {
const ref = React.useRef(null);
React.useEffect(() => {
// The isolation logic of carbonads is broken.
// Once the script starts loading, it will asynchronous resolve, with no way to stop it.
// This leads to duplication of the ad.
//
// To solve the issue, e.g. StrictModel double effect execution, we debounce the load action.
const load = setTimeout(() => {
const script = loadScript(
'https://cdn.carbonads.com/carbon.js?serve=CKYIL27L&placement=material-uicom',
ref.current,
);
script.id = '_carbonads_js';
});
return () => {
clearTimeout(load);
};
}, []);
return <CarbonRoot ref={ref} />;
}
export function AdCarbonInline(props) {
const [ad, setAd] = React.useState(null);
React.useEffect(() => {
let active = true;
let attempt = 0;
(async () => {
async function tryFetch() {
if (attempt >= 10 || !active) {
return null;
}
attempt += 1;
let response;
try {
response = await fetch('https://srv.buysellads.com/ads/CE7DC23W.json');
} catch (err) {
// Ad blocker crashes this request
return null;
}
const data = await response.json();
// Inspired by https://github.com/Semantic-Org/Semantic-UI-React/blob/2c7134128925dd831de85011e3eb0ec382ba7f73/docs/src/components/CarbonAd/CarbonAdNative.js#L9
const sanitizedAd = data.ads
.filter((item) => Object.keys(item).length > 0)
.filter((item) => item.statlink)
.filter(Boolean)[0];
if (!sanitizedAd) {
return tryFetch();
}
return sanitizedAd;
}
const sanitizedAd = await tryFetch();
if (active) {
setAd(sanitizedAd);
}
})();
return () => {
active = false;
};
}, []);
return ad ? (
<React.Fragment>
{/* Impression */}
<img src={ad.statimp} alt="" style={{ display: 'none' }} />
{/* Pixel */}
{ad.pixel &&
ad.pixel
.split('||')
.map((pixel, i) => (
<img
key={i}
src={`${pixel.replace('[timestamp]', ad.timestamp)}`}
style={{ display: 'none' }}
alt=""
/>
))}
<AdDisplay
{...props}
className="carbonads"
shape="inline"
ad={{
link: ad.statlink,
img: ad.image,
name: ad.company,
description: `<strong>${ad.company}</strong> - ${ad.description}`,
poweredby: 'Carbon',
}}
/>
</React.Fragment>
) : (
<div {...props} style={{ minHeight: 52 }} />
);
}
export default function AdCarbon() {
return <AdCarbonImage />;
}
| 5,250 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AdDisplay.js | /* eslint react/jsx-no-target-blank: ["error", { allowReferrer: true }] */
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import { adShape } from 'docs/src/modules/components/AdManager';
import { adStylesObject } from 'docs/src/modules/components/ad.styles';
const Root = styled('span', { shouldForwardProp: (prop) => prop !== 'shape' })(
({ theme, shape }) => {
const styles = adStylesObject[`body-${shape}`](theme);
return {
...styles.root,
'& img': styles.img,
'& a, & a:hover': styles.a,
'& .AdDisplay-imageWrapper': styles.imgWrapper,
'& .AdDisplay-description': styles.description,
'& .AdDisplay-poweredby': styles.poweredby,
};
},
);
export default function AdDisplay(props) {
const { ad, className, shape = 'auto' } = props;
/* eslint-disable material-ui/no-hardcoded-labels, react/no-danger */
return (
<Root shape={shape === 'inline' ? 'inline' : adShape} className={className}>
<a
href={ad.link}
target="_blank"
rel="noopener sponsored"
{...(ad.label
? {
'data-ga-event-category': 'ad',
'data-ga-event-action': 'click',
'data-ga-event-label': ad.label,
}
: {})}
>
<span className="AdDisplay-imageWrapper">
<img height="100" width="130" src={ad.img} alt={ad.name} />
</span>
<span
className="AdDisplay-description"
dangerouslySetInnerHTML={{ __html: ad.description }}
/>
</a>
<span className="AdDisplay-poweredby">ad by {ad.poweredby}</span>
</Root>
);
/* eslint-enable material-ui/no-hardcoded-labels, react/no-danger */
}
AdDisplay.propTypes = {
ad: PropTypes.object.isRequired,
className: PropTypes.string,
shape: PropTypes.oneOf(['inline', 'auto']),
};
| 5,251 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AdGuest.js | import * as React from 'react';
import PropTypes from 'prop-types';
import Portal from '@mui/material/Portal';
import { AdContext } from 'docs/src/modules/components/AdManager';
export default function AdGuest(props) {
const { classSelector = '.description', children } = props;
const ad = React.useContext(AdContext);
if (!ad.element) {
return null;
}
return (
<Portal
container={() => {
const element = document.querySelector(classSelector);
if (ad.element === element) {
element.classList.add('ad');
} else {
element.classList.remove('ad');
}
return ad.element;
}}
>
{children}
</Portal>
);
}
AdGuest.propTypes = {
children: PropTypes.node,
classSelector: PropTypes.string,
};
| 5,252 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AdInHouse.js | /* eslint react/jsx-no-target-blank: ["error", { allowReferrer: true }] */
import * as React from 'react';
import PropTypes from 'prop-types';
import AdDisplay from 'docs/src/modules/components/AdDisplay';
export default function AdInHouse(props) {
const { ad } = props;
return <AdDisplay ad={{ poweredby: 'MUI', label: `in-house-${ad.name}`, ...ad }} />;
}
AdInHouse.propTypes = {
ad: PropTypes.object.isRequired,
};
| 5,253 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AdManager.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/material/utils';
export const AdContext = React.createContext();
// Persisted for the whole session.
// The state is used to use different ad placements.
const randomSession = Math.random();
// Distribution profile:
// 20% body-inline
// 80% body-image
export const adShape = randomSession < 0.2 ? 'inline' : 'image';
export default function AdManager({ classSelector = '.description', ...props }) {
const [portal, setPortal] = React.useState({});
useEnhancedEffect(() => {
const description = document.querySelector(classSelector);
setPortal({ placement: 'body-top', element: description });
}, [classSelector]);
return <AdContext.Provider value={portal}>{props.children}</AdContext.Provider>;
}
AdManager.propTypes = {
children: PropTypes.node,
classSelector: PropTypes.string,
};
| 5,254 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AdobeXDIcon.js | import * as React from 'react';
import { createSvgIcon } from '@mui/material/utils';
export default createSvgIcon(
<g fillRule="nonzero" fill="none">
<path
d="M5.54 2h12.92C20.42 2 22 3.6 22 5.58v12.55a3.56 3.56 0 01-3.54 3.58H5.54A3.56 3.56 0 012 18.13V5.58A3.56 3.56 0 015.54 2z"
fill="#470137"
/>
<path
d="M12.52 7.28L10 11.45l2.68 4.41c.01.04.02.07.01.1 0 .04-.04.01-.09.02H10.7c-.13 0-.22 0-.28-.1l-.54-1.04c-.17-.35-.36-.7-.57-1.06l-.6-1.1h-.02c-.17.36-.36.73-.56 1.09l-.57 1.07-.57 1.06c-.04.09-.1.1-.2.1H4.94c-.03 0-.06.01-.06-.03 0-.03 0-.07.02-.1l2.6-4.28-2.53-4.31c-.03-.04-.04-.07-.02-.09.02-.02.05-.03.09-.03h1.9a.5.5 0 01.11.01c.04.02.06.05.09.08.16.36.34.72.53 1.09l.6 1.06c.2.36.39.71.57 1.07h.01c.18-.37.36-.73.55-1.08.18-.36.37-.71.57-1.06l.56-1.06c0-.04.02-.07.05-.09.03-.01.06-.02.1-.01h1.77c.04-.01.09.01.1.06 0 0-.01.04-.03.05zM16.39 16.16c-.62 0-1.24-.12-1.8-.38a2.92 2.92 0 01-1.27-1.15 3.65 3.65 0 01-.46-1.91 3.46 3.46 0 011.8-3.08 4.27 4.27 0 012.29-.48c.07 0 .16 0 .26.02V6.52c0-.06.02-.1.08-.1H19c.04 0 .08.03.08.07v8.01l.02.51.03.49c0 .06-.02.11-.08.13a6.37 6.37 0 01-2.65.53zm.82-1.69v-3.7a2.11 2.11 0 00-1.45.16c-.29.15-.53.36-.71.63-.19.27-.28.63-.28 1.06 0 .3.04.6.14.87a1.44 1.44 0 00.95.93c.23.08.46.11.7.11a4.49 4.49 0 00.65-.06z"
fill="#FF61F6"
/>
</g>,
'AdobeXD',
);
| 5,255 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ApiDivider.js | import * as React from 'react';
import MuiDivider from '@mui/material/Divider';
export default function Divider() {
return (
<MuiDivider
sx={{
borderBottomWidth: 2,
borderBottomStyle: 'dashed',
borderBottomColor: 'divider',
}}
/>
);
}
| 5,256 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ApiPage.js | /* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import { exactProp } from '@mui/utils';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import AdGuest from 'docs/src/modules/components/AdGuest';
import Alert from '@mui/material/Alert';
import VerifiedRoundedIcon from '@mui/icons-material/VerifiedRounded';
import { alpha } from '@mui/material/styles';
import { useTranslate, useUserLanguage } from 'docs/src/modules/utils/i18n';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
import AppLayoutDocs from 'docs/src/modules/components/AppLayoutDocs';
import Ad from 'docs/src/modules/components/Ad';
import BrandingProvider from 'docs/src/BrandingProvider';
import PropertiesSection, {
getPropsToC,
} from 'docs/src/modules/components/ApiPage/sections/PropertiesSection';
import CSSSection, { getCssToC } from 'docs/src/modules/components/ApiPage/sections/CssSection';
import ClassesSection from 'docs/src/modules/components/ApiPage/sections/ClassesSection';
import SlotsSection from 'docs/src/modules/components/ApiPage/sections/SlotsSection';
export function getTranslatedHeader(t, header) {
const translations = {
demos: t('api-docs.demos'),
import: t('api-docs.import'),
props: t('api-docs.props'),
'theme-default-props': t('api-docs.themeDefaultProps'),
inheritance: t('api-docs.inheritance'),
slots: t('api-docs.slots'),
classes: t('api-docs.classes'),
css: t('api-docs.css'),
};
// TODO Drop runtime type-checking once we type-check this file
if (!translations.hasOwnProperty(header)) {
throw new TypeError(
`Unable to translate header '${header}'. Did you mean one of '${Object.keys(
translations,
).join("', '")}'`,
);
}
return translations[header] || header;
}
function Heading(props) {
const { hash, level: Level = 'h2' } = props;
const t = useTranslate();
return (
<Level id={hash}>
{getTranslatedHeader(t, hash)}
<a aria-labelledby={hash} className="anchor-link" href={`#${hash}`} tabIndex={-1}>
<svg>
<use xlinkHref="#anchor-link-icon" />
</svg>
</a>
</Level>
);
}
Heading.propTypes = {
hash: PropTypes.string.isRequired,
level: PropTypes.string,
};
export default function ApiPage(props) {
const { descriptions, disableAd = false, pageContent } = props;
const t = useTranslate();
const userLanguage = useUserLanguage();
const {
cssComponent,
demos,
filename,
forwardsRefTo,
inheritance,
props: componentProps,
spread,
styles: componentStyles,
slots: componentSlots,
classes: componentClasses,
} = pageContent;
const isJoyComponent = filename.includes('mui-joy');
const isBaseComponent = filename.includes('mui-base');
const defaultPropsLink = isJoyComponent
? '/joy-ui/customization/themed-components/#theme-default-props'
: '/material-ui/customization/theme-components/#theme-default-props';
const styleOverridesLink = isJoyComponent
? '/joy-ui/customization/themed-components/#theme-style-overrides'
: '/material-ui/customization/theme-components/#theme-style-overrides';
let slotGuideLink = '';
if (isJoyComponent) {
slotGuideLink = '/joy-ui/customization/overriding-component-structure/';
} else if (isBaseComponent) {
slotGuideLink = '/base-ui/guides/overriding-component-structure/';
}
const {
componentDescription,
componentDescriptionToc = [],
classDescriptions,
propDescriptions,
slotDescriptions,
} = descriptions[userLanguage];
const description = t('api-docs.pageDescription').replace(/{{name}}/, pageContent.name);
// Prefer linking the .tsx or .d.ts for the "Edit this page" link.
const apiSourceLocation = filename.replace('.js', '.d.ts');
const hasClasses =
componentClasses?.classes?.length ||
Object.keys(componentClasses?.classes?.globalClasses || {}).length;
function createTocEntry(sectionName) {
return {
text: getTranslatedHeader(t, sectionName),
hash: sectionName,
children: [
...(sectionName === 'props' && inheritance
? [{ text: t('api-docs.inheritance'), hash: 'inheritance', children: [] }]
: []),
...(sectionName === 'props' && pageContent.themeDefaultProps
? [{ text: t('api-docs.themeDefaultProps'), hash: 'theme-default-props', children: [] }]
: []),
],
};
}
const toc = [
createTocEntry('demos'),
createTocEntry('import'),
...componentDescriptionToc,
getPropsToC({
t,
componentName: pageContent.name,
componentProps,
inheritance,
themeDefaultProps: pageContent.themeDefaultProps,
}),
...getCssToC({
t,
componentName: pageContent.name,
componentStyles,
}),
componentSlots?.length > 0 && createTocEntry('slots'),
hasClasses && createTocEntry('classes'),
].filter(Boolean);
// The `ref` is forwarded to the root element.
let refHint = t('api-docs.refRootElement');
if (forwardsRefTo == null) {
// The component cannot hold a ref.
refHint = t('api-docs.refNotHeld');
}
let spreadHint = '';
if (spread) {
// Any other props supplied will be provided to the root element ({{spreadHintElement}}).
spreadHint = t('api-docs.spreadHint').replace(
/{{spreadHintElement}}/,
inheritance
? `<a href="${inheritance.pathname}">${inheritance.component}</a>`
: t('api-docs.nativeElement'),
);
}
let inheritanceSuffix = '';
if (inheritance && inheritance.component === 'Transition') {
inheritanceSuffix = t('api-docs.inheritanceSuffixTransition');
}
return (
<AppLayoutDocs
description={description}
disableAd={disableAd}
disableToc={false}
location={apiSourceLocation}
title={`${pageContent.name} API`}
toc={toc}
>
<MarkdownElement>
<h1>{pageContent.name} API</h1>
<Typography variant="h5" component="p" className="description" gutterBottom>
{description}
{disableAd ? null : (
<BrandingProvider>
<AdGuest>
<Ad />
</AdGuest>
</BrandingProvider>
)}
</Typography>
<Heading hash="demos" />
<Alert
severity="success"
variant="outlined"
icon={<VerifiedRoundedIcon sx={{ fontSize: 20 }} />}
sx={[
(theme) => ({
mt: 1.5,
pt: 1,
px: 2,
pb: 0,
fontSize: theme.typography.pxToRem(16),
backgroundColor: (theme.vars || theme).palette.success[50],
borderColor: (theme.vars || theme).palette.success[100],
'& * p': {
mb: 1,
},
'& * a': {
fontWeight: theme.typography.fontWeightMedium,
color: (theme.vars || theme).palette.success[900],
textDecorationColor: alpha(theme.palette.success[600], 0.3),
},
...theme.applyDarkStyles({
'& * a': {
color: (theme.vars || theme).palette.success[100],
textDecorationColor: alpha(theme.palette.success[100], 0.3),
},
backgroundColor: alpha(theme.palette.success[700], 0.15),
borderColor: alpha(theme.palette.success[600], 0.3),
}),
}),
]}
>
<span
dangerouslySetInnerHTML={{
__html: `<p>For examples and details on the usage of this React component, visit the component demo pages:</p>
${demos}`,
}}
/>
</Alert>
<Heading hash="import" />
<HighlightedCode
code={pageContent.imports.join(`
// ${t('or')}
`)}
language="jsx"
/>
<span dangerouslySetInnerHTML={{ __html: t('api-docs.importDifference') }} />
{componentDescription ? (
<React.Fragment>
<br />
<br />
<span
dangerouslySetInnerHTML={{
__html: componentDescription,
}}
/>
</React.Fragment>
) : null}
<PropertiesSection
properties={componentProps}
propertiesDescriptions={propDescriptions}
targetName={pageContent.name}
spreadHint={spreadHint}
/>
{cssComponent && (
<React.Fragment>
<span
dangerouslySetInnerHTML={{
__html: t('api-docs.cssComponent').replace(/{{name}}/, pageContent.name),
}}
/>
<br />
<br />
</React.Fragment>
)}
<div
className="MuiCallout-root MuiCallout-info"
dangerouslySetInnerHTML={{ __html: refHint }}
style={{
alignItems: 'baseline',
gap: '4px',
marginTop: 0,
}}
/>
{inheritance && (
<React.Fragment>
<Heading hash="inheritance" level="h3" />
<p
dangerouslySetInnerHTML={{
__html: t('api-docs.inheritanceDescription')
.replace(/{{component}}/, inheritance.component)
.replace(/{{pathname}}/, inheritance.pathname)
.replace(/{{suffix}}/, inheritanceSuffix)
.replace(/{{name}}/, pageContent.name),
}}
/>
<Divider />
</React.Fragment>
)}
{pageContent.themeDefaultProps && (
<React.Fragment>
<Heading hash="theme-default-props" level="h3" />
<p
dangerouslySetInnerHTML={{
__html: t('api-docs.themeDefaultPropsDescription')
.replace(/{{muiName}}/, pageContent.muiName)
.replace(/{{defaultPropsLink}}/, defaultPropsLink),
}}
/>
<Divider sx={{ 'hr&&': { mb: 0 } }} />
</React.Fragment>
)}
<CSSSection
componentStyles={componentStyles}
classDescriptions={classDescriptions}
componentName={pageContent.name}
spreadHint={t('api-docs.cssDescription')}
styleOverridesLink={styleOverridesLink}
/>
<SlotsSection
componentSlots={componentSlots}
slotDescriptions={slotDescriptions}
componentName={pageContent.name}
spreadHint={
slotGuideLink &&
t('api-docs.slotDescription').replace(/{{slotGuideLink}}/, slotGuideLink)
}
/>
<ClassesSection
componentClasses={componentClasses}
componentName={pageContent.name}
classDescriptions={classDescriptions}
spreadHint={t('api-docs.classesDescription')}
/>
</MarkdownElement>
<svg style={{ display: 'none' }} xmlns="http://www.w3.org/2000/svg">
<symbol id="anchor-link-icon" viewBox="0 0 12 6">
<path d="M8.9176 0.083252H7.1676C6.84677 0.083252 6.58427 0.345752 6.58427 0.666585C6.58427 0.987419 6.84677 1.24992 7.1676 1.24992H8.9176C9.8801 1.24992 10.6676 2.03742 10.6676 2.99992C10.6676 3.96242 9.8801 4.74992 8.9176 4.74992H7.1676C6.84677 4.74992 6.58427 5.01242 6.58427 5.33325C6.58427 5.65409 6.84677 5.91659 7.1676 5.91659H8.9176C10.5276 5.91659 11.8343 4.60992 11.8343 2.99992C11.8343 1.38992 10.5276 0.083252 8.9176 0.083252ZM3.6676 2.99992C3.6676 3.32075 3.9301 3.58325 4.25094 3.58325H7.75094C8.07177 3.58325 8.33427 3.32075 8.33427 2.99992C8.33427 2.67909 8.07177 2.41659 7.75094 2.41659H4.25094C3.9301 2.41659 3.6676 2.67909 3.6676 2.99992ZM4.83427 4.74992H3.08427C2.12177 4.74992 1.33427 3.96242 1.33427 2.99992C1.33427 2.03742 2.12177 1.24992 3.08427 1.24992H4.83427C5.1551 1.24992 5.4176 0.987419 5.4176 0.666585C5.4176 0.345752 5.1551 0.083252 4.83427 0.083252H3.08427C1.47427 0.083252 0.167603 1.38992 0.167603 2.99992C0.167603 4.60992 1.47427 5.91659 3.08427 5.91659H4.83427C5.1551 5.91659 5.4176 5.65409 5.4176 5.33325C5.4176 5.01242 5.1551 4.74992 4.83427 4.74992Z" />
</symbol>
</svg>
</AppLayoutDocs>
);
}
ApiPage.propTypes = {
descriptions: PropTypes.object.isRequired,
disableAd: PropTypes.bool,
pageContent: PropTypes.object.isRequired,
};
if (process.env.NODE_ENV !== 'production') {
ApiPage.propTypes = exactProp(ApiPage.propTypes);
}
| 5,257 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppContainer.js | import * as React from 'react';
import { styled } from '@mui/material/styles';
import Container from '@mui/material/Container';
const StyledAppContainer = styled(Container)(({ theme }) => {
return {
paddingTop: `calc(var(--MuiDocs-header-height) + ${theme.spacing(4)})`,
// We're mostly hosting text content so max-width by px does not make sense considering font-size is system-adjustable.
// 105ch ≈ 930px
fontFamily: 'Arial',
maxWidth: '105ch',
[theme.breakpoints.up('lg')]: {
paddingLeft: theme.spacing(8),
paddingRight: theme.spacing(8),
},
};
});
export default function AppContainer(props) {
return <StyledAppContainer id="main-content" maxWidth={false} {...props} />;
}
| 5,258 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppFrame.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { useRouter } from 'next/router';
import GlobalStyles from '@mui/material/GlobalStyles';
import { styled, alpha } from '@mui/material/styles';
import NProgress from 'nprogress';
import CssBaseline from '@mui/material/CssBaseline';
import AppBar from '@mui/material/AppBar';
import Stack from '@mui/material/Stack';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import Tooltip from '@mui/material/Tooltip';
import Box from '@mui/material/Box';
import SettingsIcon from '@mui/icons-material/SettingsOutlined';
import GitHubIcon from '@mui/icons-material/GitHub';
import NProgressBar from '@mui/docs/NProgressBar';
import { debounce } from '@mui/material/utils';
import NextLink from 'next/link';
import SvgHamburgerMenu from 'docs/src/icons/SvgHamburgerMenu';
import AppNavDrawer from 'docs/src/modules/components/AppNavDrawer';
import AppSettingsDrawer from 'docs/src/modules/components/AppSettingsDrawer';
import Notifications from 'docs/src/modules/components/Notifications';
import MarkdownLinks from 'docs/src/modules/components/MarkdownLinks';
import SkipLink from 'docs/src/modules/components/SkipLink';
import PageContext from 'docs/src/modules/components/PageContext';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import SvgMuiLogomark from 'docs/src/icons/SvgMuiLogomark';
import AppFrameBanner from 'docs/src/components/banner/AppFrameBanner';
const nProgressStart = debounce(() => {
NProgress.start();
}, 200);
const nProgressDone = () => {
nProgressStart.clear();
NProgress.done();
};
export function NextNProgressBar() {
const router = useRouter();
React.useEffect(() => {
const handleRouteChangeStart = (url, { shallow }) => {
if (!shallow) {
nProgressStart();
}
};
const handleRouteChangeDone = (url, { shallow }) => {
if (!shallow) {
nProgressDone();
}
};
router.events.on('routeChangeStart', handleRouteChangeStart);
router.events.on('routeChangeComplete', handleRouteChangeDone);
router.events.on('routeChangeError', handleRouteChangeDone);
return () => {
router.events.off('routeChangeStart', handleRouteChangeStart);
router.events.off('routeChangeComplete', handleRouteChangeDone);
router.events.off('routeChangeError', handleRouteChangeDone);
};
}, [router]);
return <NProgressBar />;
}
const sx = { minWidth: { sm: 160 } };
const AppSearch = React.lazy(() => import('docs/src/modules/components/AppSearch'));
export function DeferredAppSearch() {
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
return (
<React.Fragment>
{/* Suspense isn't supported for SSR yet */}
{mounted ? (
<React.Suspense fallback={<Box sx={sx} />}>
<AppSearch sx={sx} />
</React.Suspense>
) : (
<Box sx={sx} />
)}
</React.Fragment>
);
}
const RootDiv = styled('div')(({ theme }) => {
return {
display: 'flex',
...theme.applyDarkStyles({
background: (theme.vars || theme).palette.primaryDark[900],
}),
// TODO: Should be handled by the main component
};
});
const StyledAppBar = styled(AppBar, {
shouldForwardProp: (prop) => prop !== 'disablePermanent',
})(({ disablePermanent, theme }) => {
return {
padding: theme.spacing(1, 2),
transition: theme.transitions.create('width'),
...(disablePermanent && {
boxShadow: 'none',
}),
...(!disablePermanent && {
[theme.breakpoints.up('lg')]: {
width: 'calc(100% - var(--MuiDocs-navDrawer-width))',
},
}),
boxShadow: 'none',
backdropFilter: 'blur(8px)',
borderStyle: 'solid',
borderColor: (theme.vars || theme).palette.grey[100],
borderWidth: 0,
borderBottomWidth: 'thin',
backgroundColor: 'rgba(255,255,255,0.9)',
color: (theme.vars || theme).palette.grey[800],
...theme.applyDarkStyles({
borderColor: alpha(theme.palette.primary[100], 0.08),
backgroundColor: alpha(theme.palette.primaryDark[900], 0.8),
color: (theme.vars || theme).palette.grey[500],
}),
};
});
const GrowingDiv = styled('div')({
flex: '1 1 auto',
});
const NavIconButton = styled(IconButton, {
shouldForwardProp: (prop) => prop !== 'disablePermanent',
})(({ disablePermanent, theme }) => {
if (disablePermanent) {
return {};
}
return {
[theme.breakpoints.up('lg')]: {
display: 'none',
},
};
});
const StyledAppNavDrawer = styled(AppNavDrawer)(({ disablePermanent, theme }) => {
if (disablePermanent) {
return {};
}
return {
[theme.breakpoints.up('lg')]: {
flexShrink: 0,
width: 'var(--MuiDocs-navDrawer-width)',
},
};
});
export const HEIGHT = 64;
export default function AppFrame(props) {
const { children, disableDrawer = false, className, BannerComponent = AppFrameBanner } = props;
const t = useTranslate();
const [mobileOpen, setMobileOpen] = React.useState(false);
const [settingsOpen, setSettingsOpen] = React.useState(false);
const { activePage } = React.useContext(PageContext);
const disablePermanent = activePage?.disableDrawer === true || disableDrawer === true;
return (
<RootDiv className={className}>
<NextNProgressBar />
<CssBaseline />
<SkipLink />
<MarkdownLinks />
<StyledAppBar disablePermanent={disablePermanent}>
<GlobalStyles
styles={{
':root': {
'--MuiDocs-header-height': `${HEIGHT}px`,
},
}}
/>
<Toolbar variant="dense" disableGutters>
<NavIconButton
edge="start"
color="primary"
aria-label={t('appFrame.openDrawer')}
disablePermanent={disablePermanent}
onClick={() => setMobileOpen(true)}
sx={{ ml: '1px' }}
>
<SvgHamburgerMenu />
</NavIconButton>
<NextLink href="/" passHref /* onClick={onClose} */ legacyBehavior>
<Box
component="a"
aria-label={t('goToHome')}
sx={{ display: { md: 'flex', lg: 'none' }, ml: 2 }}
>
<SvgMuiLogomark width={30} />
</Box>
</NextLink>
<GrowingDiv />
<Stack direction="row" spacing="10px">
<BannerComponent />
<DeferredAppSearch />
<Tooltip title={t('appFrame.github')} enterDelay={300}>
<IconButton
component="a"
color="primary"
href={process.env.SOURCE_CODE_REPO}
data-ga-event-category="header"
data-ga-event-action="github"
>
<GitHubIcon fontSize="small" />
</IconButton>
</Tooltip>
<Notifications />
<Tooltip title={t('appFrame.toggleSettings')} enterDelay={300}>
<IconButton color="primary" onClick={() => setSettingsOpen(true)} sx={{ px: '8px' }}>
<SettingsIcon fontSize="small" />
</IconButton>
</Tooltip>
</Stack>
</Toolbar>
</StyledAppBar>
<StyledAppNavDrawer
disablePermanent={disablePermanent}
onClose={() => setMobileOpen(false)}
onOpen={() => setMobileOpen(true)}
mobileOpen={mobileOpen}
/>
{children}
<AppSettingsDrawer onClose={() => setSettingsOpen(false)} open={settingsOpen} />
</RootDiv>
);
}
AppFrame.propTypes = {
BannerComponent: PropTypes.elementType,
children: PropTypes.node.isRequired,
className: PropTypes.string,
disableDrawer: PropTypes.bool,
};
| 5,259 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppLayoutDocs.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { useRouter } from 'next/router';
import { styled } from '@mui/material/styles';
import { exactProp } from '@mui/utils';
import GlobalStyles from '@mui/material/GlobalStyles';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import Head from 'docs/src/modules/components/Head';
import AppFrame from 'docs/src/modules/components/AppFrame';
import AppContainer from 'docs/src/modules/components/AppContainer';
import AppTableOfContents from 'docs/src/modules/components/AppTableOfContents';
import AdManager from 'docs/src/modules/components/AdManager';
import AppLayoutDocsFooter from 'docs/src/modules/components/AppLayoutDocsFooter';
import BackToTop from 'docs/src/modules/components/BackToTop';
import { AD_MARGIN_TOP, AD_HEIGHT, AD_MARGIN_BOTTOM } from 'docs/src/modules/components/Ad';
const TOC_WIDTH = 242;
const Main = styled('main', {
shouldForwardProp: (prop) => prop !== 'disableToc',
})(({ disableToc, theme }) => ({
minHeight: '100vh',
display: 'grid',
width: '100%',
...(disableToc
? {
[theme.breakpoints.up('md')]: {
marginRight: TOC_WIDTH / 2,
},
}
: {
[theme.breakpoints.up('md')]: {
gridTemplateColumns: `1fr ${TOC_WIDTH}px`,
},
}),
'& .markdown-body .comment-link': {
display: 'inline-block',
},
}));
const StyledAppContainer = styled(AppContainer, {
shouldForwardProp: (prop) => prop !== 'disableAd' && prop !== 'hasTabs' && prop !== 'disableToc',
})(({ disableAd, hasTabs, disableToc, theme }) => {
return {
position: 'relative',
// By default, a grid item cannot be smaller than the size of its content.
// https://stackoverflow.com/questions/43311943/prevent-content-from-expanding-grid-items
minWidth: 0,
...(disableToc
? {
// 105ch ≈ 930px
maxWidth: `calc(105ch + ${TOC_WIDTH / 2}px)`,
}
: {
// We're mostly hosting text content so max-width by px does not make sense considering font-size is system-adjustable.
fontFamily: 'Arial',
// 105ch ≈ 930px
maxWidth: '105ch',
}),
...(!disableAd && {
...(hasTabs
? {
'&& .component-tabs .MuiTabs-root': {
// 40px matches MarkdownElement h2 margin-top.
marginBottom: `calc(${theme.spacing(AD_MARGIN_TOP)} + ${AD_HEIGHT}px + 40px)`,
},
'&& .component-tabs.ad .MuiTabs-root': {
marginBottom: 0,
},
}
: {
'&& .description': {
paddingBottom: `calc(${theme.spacing(AD_MARGIN_TOP)} + ${AD_HEIGHT}px)`,
marginBottom: theme.spacing(AD_MARGIN_BOTTOM),
},
'&& .description.ad': {
paddingBottom: 0,
marginBottom: 0,
},
}),
}),
[theme.breakpoints.up('lg')]: {
paddingLeft: '60px',
paddingRight: '60px',
},
};
});
export default function AppLayoutDocs(props) {
const router = useRouter();
const {
BannerComponent,
children,
description,
disableAd = false,
// TODO, disableLayout should be the default, retaining the layout between pages
// improves the UX. It's faster to transition, and you don't lose UI states, like scroll.
disableLayout = false,
disableToc = false,
hasTabs = false,
location,
title,
toc,
} = props;
if (description === undefined) {
throw new Error('Missing description in the page');
}
const { canonicalAs } = pathnameToLanguage(router.asPath);
let productName = 'MUI';
if (canonicalAs.startsWith('/material-ui/')) {
productName = 'Material UI';
} else if (canonicalAs.startsWith('/base-ui/')) {
productName = 'Base UI';
} else if (canonicalAs.startsWith('/x/')) {
productName = 'MUI X';
} else if (canonicalAs.startsWith('/system/')) {
productName = 'MUI System';
} else if (canonicalAs.startsWith('/toolpad/')) {
productName = 'MUI Toolpad';
} else if (canonicalAs.startsWith('/joy-ui/')) {
productName = 'Joy UI';
}
const Layout = disableLayout ? React.Fragment : AppFrame;
const layoutProps = disableLayout ? {} : { BannerComponent };
return (
<Layout {...layoutProps}>
<GlobalStyles
styles={{
':root': {
'--MuiDocs-navDrawer-width': '300px',
},
}}
/>
<AdManager {...(hasTabs && { classSelector: '.component-tabs' })}>
<Head
title={`${title} - ${productName}`}
description={description}
largeCard={false}
card="https://mui.com/static/logo.png"
/>
<Main disableToc={disableToc}>
{/*
Render the TOCs first to avoid layout shift when the HTML is streamed.
See https://jakearchibald.com/2014/dont-use-flexbox-for-page-layout/ for more details.
*/}
<StyledAppContainer disableAd={disableAd} hasTabs={hasTabs} disableToc={disableToc}>
{children}
<AppLayoutDocsFooter tableOfContents={toc} location={location} />
</StyledAppContainer>
{disableToc ? null : <AppTableOfContents toc={toc} />}
</Main>
</AdManager>
<BackToTop />
</Layout>
);
}
AppLayoutDocs.propTypes = {
BannerComponent: PropTypes.elementType,
children: PropTypes.node.isRequired,
description: PropTypes.string.isRequired,
disableAd: PropTypes.bool.isRequired,
disableLayout: PropTypes.bool,
disableToc: PropTypes.bool.isRequired,
hasTabs: PropTypes.bool,
location: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
toc: PropTypes.array.isRequired,
};
if (process.env.NODE_ENV !== 'production') {
AppLayoutDocs.propTypes = exactProp(AppLayoutDocs.propTypes);
}
| 5,260 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppLayoutDocsFooter.js | /* eslint-disable no-restricted-globals */
/* eslint-disable material-ui/no-hardcoded-labels */
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled, useTheme } from '@mui/material/styles';
// Components
import DialogActions from '@mui/material/DialogActions';
import TextField from '@mui/material/TextField';
import Collapse from '@mui/material/Collapse';
import Button from '@mui/material/Button';
import Alert from '@mui/material/Alert';
import Divider from '@mui/material/Divider';
import Typography from '@mui/material/Typography';
import Tooltip from '@mui/material/Tooltip';
import Stack from '@mui/material/Stack';
import Snackbar from '@mui/material/Snackbar';
import IconButton from '@mui/material/IconButton';
// Icons
import ThumbUpAltRoundedIcon from '@mui/icons-material/ThumbUpAltRounded';
import ThumbDownAltRoundedIcon from '@mui/icons-material/ThumbDownAltRounded';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import PanToolRoundedIcon from '@mui/icons-material/PanToolRounded';
import TwitterIcon from '@mui/icons-material/Twitter';
import YouTubeIcon from '@mui/icons-material/YouTube';
import RssFeedIcon from '@mui/icons-material/RssFeed';
import ArrowOutwardRoundedIcon from '@mui/icons-material/ArrowOutwardRounded';
import DiscordIcon from 'docs/src/icons/DiscordIcon';
// Other imports
import ROUTES from 'docs/src/route';
import Link from 'docs/src/modules/components/Link';
import PageContext from 'docs/src/modules/components/PageContext';
import EditPage from 'docs/src/modules/components/EditPage';
import SvgMuiLogotype from 'docs/src/icons/SvgMuiLogotype';
import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n';
import { getCookie, pageToTitleI18n } from 'docs/src/modules/utils/helpers';
const FooterLink = styled(Typography)(({ theme }) => {
return {
...theme.typography.body2,
display: 'flex',
alignItems: 'center',
gap: 4,
fontWeight: (theme.vars || theme).typography.fontWeightSemiBold,
color: (theme.vars || theme).palette.primary.main,
'& > svg': { transition: '0.2s' },
'&:hover > svg': { transform: 'translateX(2px)' },
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[300],
}),
};
});
/**
* @typedef {import('docs/src/pages').MuiPage} MuiPage
* @typedef {import('docs/src/pages').OrderedMuiPage} OrderedMuiPage
*/
/**
* @param {MuiPage[]} pages
* @param {MuiPage[]} [current]
* @returns {OrderedMuiPage[]}
*/
function orderedPages(pages, current = []) {
return pages
.reduce((items, item) => {
if (item.children && item.children.length > 1) {
items = orderedPages(item.children, items);
} else {
items.push(item.children && item.children.length === 1 ? item.children[0] : item);
}
return items;
}, current)
.filter((page) => {
return (
page.inSideNav !== false &&
// ignore external pages
page.pathname.startsWith('/')
);
});
}
async function postFeedback(data) {
const env = window.location.host.indexOf('mui.com') !== -1 ? 'prod' : 'dev';
try {
const response = await fetch(`${process.env.FEEDBACK_URL}/${env}/feedback`, {
method: 'POST',
referrerPolicy: 'origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return response.json();
} catch (error) {
console.error(error);
return null;
}
}
async function postFeedbackOnSlack(data) {
const { rating, comment, commentedSection } = data;
const sentData = {
callback_id: 'send_feedback',
rating,
comment,
currentLocationURL: window.location.href,
commmentSectionURL: `${window.location.origin}${window.location.pathname}#${commentedSection.hash}`,
commmentSectionTitle: commentedSection.text,
githubRepo: process.env.SOURCE_CODE_REPO,
};
if (!comment || comment.length < 10) {
return 'ignored';
}
try {
const res = await fetch(`${window.location.origin}/.netlify/functions/feedback-management/`, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
// Seems tricky but it's to match how slack send data
body: `payload=${encodeURIComponent(JSON.stringify(sentData))}`,
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
return 'sent';
} catch (error) {
console.error(error);
return null;
}
/**
Not used because I ignore how to encode that with:
'content-type': 'application/x-www-form-urlencoded'
const complexSlackMessage = {
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: `New comment ${rating > 0 ? '👍' : '👎'}`,
emoji: true,
},
},
{
type: 'section',
text: {
type: 'plain_text',
text: comment,
emoji: true,
},
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `v: ${version}, lang: ${language}`,
},
accessory: {
type: 'button',
text: {
type: 'plain_text',
text: 'Go to the page',
emoji: true,
},
url: window.location.host,
},
},
],
};
*/
}
async function getUserFeedback(id) {
const env = location.hostname === 'mui.com' ? 'prod' : 'dev';
const URL = `${process.env.FEEDBACK_URL}/${env}/feedback/${id}`;
try {
const response = await fetch(URL, {
method: 'GET',
cache: 'no-store',
referrerPolicy: 'origin',
});
return response.json();
} catch (error) {
console.error(error);
return null;
}
}
async function submitFeedback(page, rating, comment, language, commentedSection) {
const data = {
id: getCookie('feedbackId'),
page,
rating,
comment,
version: process.env.LIB_VERSION,
language,
};
const resultSlack = await postFeedbackOnSlack({ ...data, commentedSection });
if (rating !== undefined) {
const resultVote = await postFeedback(data);
if (resultVote) {
document.cookie = `feedbackId=${resultVote.id};path=/;max-age=31536000`;
setTimeout(async () => {
const userFeedback = await getUserFeedback(resultVote.id);
if (userFeedback) {
document.cookie = `feedback=${JSON.stringify(userFeedback)};path=/;max-age=31536000`;
}
});
}
return resultSlack && resultVote;
}
return resultSlack;
}
function getCurrentRating(pathname) {
let userFeedback;
if (typeof window !== 'undefined') {
try {
userFeedback = getCookie('feedback');
userFeedback = userFeedback && JSON.parse(userFeedback);
} catch {
// For unknown reason the `userFeedback` can be uncomplet, leading the JSON.parse to crash the entire docs
return undefined;
}
}
return userFeedback && userFeedback[pathname] && userFeedback[pathname].rating;
}
/**
* @returns { { prevPage: OrderedMuiPage | null; nextPage: OrderedMuiPage | null } }
*/
function usePageNeighbours() {
const { activePage, pages } = React.useContext(PageContext);
const pageList = orderedPages(pages);
const currentPageNum = pageList.indexOf(activePage);
if (currentPageNum === -1) {
return { prevPage: null, nextPage: null };
}
const prevPage = pageList[currentPageNum - 1] ?? null;
const nextPage = pageList[currentPageNum + 1] ?? null;
return { prevPage, nextPage };
}
const EMPTY_SECTION = { hash: '', text: '' };
// The design feedback alert was removed in https://github.com/mui/material-ui/pull/39691
// This dead code is here to simplify the creation of special feedback channel
const SPEACIAL_FEEDBACK_HASH = [{ hash: 'new-docs-api-feedback', text: 'New API content design' }];
export default function AppLayoutDocsFooter(props) {
const { tableOfContents = [], location } = props;
const theme = useTheme();
const t = useTranslate();
const userLanguage = useUserLanguage();
const { activePage } = React.useContext(PageContext);
const [rating, setRating] = React.useState();
const [comment, setComment] = React.useState('');
const [snackbarOpen, setSnackbarOpen] = React.useState(false);
const [snackbarMessage, setSnackbarMessage] = React.useState(false);
const inputRef = React.useRef();
const [commentOpen, setCommentOpen] = React.useState(false);
const [commentedSection, setCommentedSection] = React.useState(EMPTY_SECTION);
const { nextPage, prevPage } = usePageNeighbours();
const sectionOptions = React.useMemo(
() =>
tableOfContents.flatMap((section) => [
{
hash: section.hash,
text: section.text,
},
...section.children.map(({ hash, text }) => ({ hash, text })),
]),
[tableOfContents],
);
const setCurrentRatingFromCookie = React.useCallback(() => {
if (activePage !== null) {
setRating(getCurrentRating(activePage.pathname));
}
}, [activePage]);
React.useEffect(() => {
setCurrentRatingFromCookie();
}, [setCurrentRatingFromCookie]);
async function processFeedback() {
if (activePage === null) {
setSnackbarMessage(t('feedbackFailed'));
}
const result = await submitFeedback(
activePage.pathname,
rating,
comment,
userLanguage,
commentedSection,
);
if (result) {
setSnackbarMessage(t('feedbackSubmitted'));
} else {
setCurrentRatingFromCookie();
setSnackbarMessage(t('feedbackFailed'));
}
setSnackbarOpen(true);
}
const handleClickThumb = (vote) => async () => {
if (vote !== rating) {
setRating(vote);
setCommentOpen(true);
}
// Manually move focus if comment is already open.
// If the comment is closed, onEntered will call focus itself;
if (inputRef.current) {
inputRef.current.focus();
}
};
const handleChangeTextfield = (event) => {
setComment(event.target.value);
};
const handleSubmitComment = (event) => {
event.preventDefault();
setCommentOpen(false);
processFeedback();
};
// See https://github.com/mui/mui-toolpad/issues/1164 for context.
const handleKeyDownForm = (event) => {
const modifierKey = (event.metaKey || event.ctrlKey) && !event.shiftKey;
if (event.key === 'Enter' && modifierKey) {
const submitButton = event.currentTarget.querySelector('[type="submit"]');
submitButton.click();
}
};
const handleCancelComment = () => {
setCommentOpen(false);
setCurrentRatingFromCookie();
setCommentedSection(EMPTY_SECTION);
};
const handleEntered = () => {
inputRef.current.focus();
};
const handleCloseSnackbar = () => {
setSnackbarOpen(false);
};
React.useEffect(() => {
const eventListener = (event) => {
const feedbackHash = event.target.getAttribute('data-feedback-hash');
if (feedbackHash) {
const section =
[...sectionOptions, ...SPEACIAL_FEEDBACK_HASH].find(
(item) => item.hash === feedbackHash,
) || EMPTY_SECTION;
setCommentOpen(true);
setCommentedSection(section);
// Manually move focus if comment is already open.
// If the comment is closed, onEntered will call focus itself;
if (inputRef.current) {
inputRef.current.focus();
}
}
};
document.addEventListener('click', eventListener);
return () => {
document.removeEventListener('click', eventListener);
};
}, [sectionOptions]);
const hidePagePagination = activePage === null || activePage.ordered === false;
return (
<React.Fragment>
<Stack component="footer" direction="column" spacing={2.5} sx={{ my: 6 }}>
<Stack
direction={{ xs: 'column', sm: 'row' }}
alignItems="center"
justifyContent="space-between"
spacing={{ xs: 3, sm: 1 }}
>
<EditPage sourceLocation={location} />
<Stack direction="row" alignItems="center" spacing={1}>
<Typography
id="feedback-message"
variant="body2"
fontWeight="medium"
color="text.secondary"
>
{t('feedbackMessage')}
</Typography>
<Tooltip title={t('feedbackYes')}>
<IconButton color="info" onClick={handleClickThumb(1)} aria-pressed={rating === 1}>
<ThumbUpAltRoundedIcon
color={rating === 1 ? 'primary' : undefined}
sx={{ fontSize: 15 }}
/>
</IconButton>
</Tooltip>
<Tooltip title={t('feedbackNo')}>
<IconButton color="info" onClick={handleClickThumb(0)} aria-pressed={rating === 0}>
<ThumbDownAltRoundedIcon
color={rating === 0 ? 'error' : undefined}
sx={{ fontSize: 15 }}
/>
</IconButton>
</Tooltip>
</Stack>
</Stack>
{/* Wrapper div to fix Collapse close animation */}
<div>
<Collapse
in={commentOpen}
unmountOnExit
onEntered={handleEntered}
timeout={{ enter: 0, exit: theme.transitions.duration.standard }}
>
{/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */}
<form
aria-labelledby="feedback-message"
onReset={handleCancelComment}
onSubmit={handleSubmitComment}
onKeyDown={handleKeyDownForm}
>
<div>
{commentedSection.text ? (
<Typography
variant="body2"
id="feedback-description"
color="text.secondary"
dangerouslySetInnerHTML={{
__html: t('feedbackSectionSpecific').replace(
'{{sectionName}}',
`"${commentedSection.text}"`,
),
}}
/>
) : (
<Typography variant="body2" id="feedback-description" color="text.secondary">
{rating === 1 ? t('feedbackMessageUp') : t('feedbackMessageDown')}
</Typography>
)}
<TextField
multiline
margin="dense"
name="comment"
fullWidth
rows={4}
value={comment}
onChange={handleChangeTextfield}
inputProps={{
'aria-label': t('feedbackCommentLabel'),
'aria-describedby': 'feedback-description',
ref: inputRef,
}}
/>
{rating !== 1 && typeof window !== 'undefined' && (
<Alert
severity="warning"
color="warning"
icon={<PanToolRoundedIcon fontSize="small" />}
sx={{ my: 1.5 }}
>
<Typography id="feedback-description" color="text.secondary">
{t('feedbackMessageToGitHub.usecases')}{' '}
<Link
href={`${process.env.SOURCE_CODE_REPO}/issues/new?template=${process.env.GITHUB_TEMPLATE_DOCS_FEEDBACK}&page-url=${window.location.href}`}
target="_blank"
>
{t('feedbackMessageToGitHub.callToAction.link')}
</Link>{' '}
{t('feedbackMessageToGitHub.reasonWhy')}
</Typography>
</Alert>
)}
<DialogActions>
<Button type="reset" size="small">
{t('cancel')}
</Button>
<Button type="submit" variant="contained" size="small">
{t('submit')}
</Button>
</DialogActions>
</div>
</form>
</Collapse>
</div>
<Divider />
{hidePagePagination ? null : (
<Stack direction="row" justifyContent="space-between" sx={{ my: 2 }}>
{prevPage !== null ? (
<Button
size="small"
component={Link}
noLinkStyle
prefetch={false}
href={prevPage.pathname}
{...prevPage.linkProps}
startIcon={<ChevronLeftIcon />}
>
{pageToTitleI18n(prevPage, t)}
</Button>
) : (
<div />
)}
{nextPage !== null ? (
<Button
size="small"
component={Link}
noLinkStyle
prefetch={false}
href={nextPage.pathname}
{...nextPage.linkProps}
endIcon={<ChevronRightIcon />}
>
{pageToTitleI18n(nextPage, t)}
</Button>
) : null}
</Stack>
)}
<Divider />
<Stack
direction={{ xs: 'column', sm: 'row' }}
alignItems="center"
spacing={{ xs: 3, sm: 1 }}
>
<Stack direction="row" alignItems="center" spacing={1.2} sx={{ flexGrow: 1 }}>
<Link href="/" aria-label="Go to homepage" sx={{ mb: 2 }}>
<SvgMuiLogotype height={24} width={72} />
</Link>
<Typography color="grey.500" fontSize={13} sx={{ opacity: '70%' }}>
•
</Typography>
<Link href={ROUTES.blog} target="_blank" rel="noopener noreferrer">
<FooterLink>
Blog <ArrowOutwardRoundedIcon sx={{ fontSize: 14 }} />
</FooterLink>
</Link>
<Typography color="grey.500" fontSize={13} sx={{ opacity: '70%' }}>
•
</Typography>
<Link href={ROUTES.store} target="_blank" rel="noopener noreferrer">
<FooterLink>
Store <ArrowOutwardRoundedIcon sx={{ fontSize: 14 }} />
</FooterLink>
</Link>
</Stack>
<Stack spacing={1} direction="row">
<IconButton
target="_blank"
rel="noopener noreferrer"
href={ROUTES.rssFeed}
aria-label="RSS Feed"
title="RSS Feed"
size="small"
>
<RssFeedIcon fontSize="small" sx={{ color: 'grey.500' }} />
</IconButton>
<IconButton
target="_blank"
rel="noopener noreferrer"
href="https://twitter.com/MUI_hq"
aria-label="twitter"
title="Twitter"
size="small"
>
<TwitterIcon fontSize="small" sx={{ color: 'grey.500' }} />
</IconButton>
<IconButton
target="_blank"
rel="noopener noreferrer"
href="https://www.youtube.com/@MUI_hq"
aria-label="YouTube"
title="YouTube"
size="small"
>
<YouTubeIcon fontSize="small" sx={{ color: 'grey.500' }} />
</IconButton>
<IconButton
target="_blank"
rel="noopener noreferrer"
href="https://mui.com/r/discord/"
aria-label="Discord"
title="Discord"
size="small"
>
<DiscordIcon fontSize="small" sx={{ color: 'grey.500' }} />
</IconButton>
</Stack>
</Stack>
</Stack>
<Snackbar
open={snackbarOpen}
autoHideDuration={3000}
onClose={handleCloseSnackbar}
message={snackbarMessage}
/>
</React.Fragment>
);
}
AppLayoutDocsFooter.propTypes = {
location: PropTypes.string.isRequired,
tableOfContents: PropTypes.array,
};
| 5,261 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppNavDrawer.js | import * as React from 'react';
import PropTypes from 'prop-types';
import NextLink from 'next/link';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import { styled, ThemeProvider } from '@mui/material/styles';
import List from '@mui/material/List';
import Drawer from '@mui/material/Drawer';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
import SwipeableDrawer from '@mui/material/SwipeableDrawer';
import useMediaQuery from '@mui/material/useMediaQuery';
import Box from '@mui/material/Box';
import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils';
import ArrowDropDownRoundedIcon from '@mui/icons-material/ArrowDropDownRounded';
import DoneRounded from '@mui/icons-material/DoneRounded';
import SvgMuiLogomark from 'docs/src/icons/SvgMuiLogomark';
import AppNavDrawerItem from 'docs/src/modules/components/AppNavDrawerItem';
import { pageToTitleI18n } from 'docs/src/modules/utils/helpers';
import PageContext from 'docs/src/modules/components/PageContext';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import MuiProductSelector from 'docs/src/modules/components/MuiProductSelector';
// TODO: Collapse should expose an API to customize the duration based on the height.
function transitionTheme(theme) {
return {
...theme,
transitions: {
...theme.transitions,
getAutoHeightDuration: (height) => {
if (!height) {
return 0;
}
const constant = height / 80;
// https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10
return Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10);
},
},
};
}
const savedScrollTop = {};
function ProductDrawerButton(props) {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<React.Fragment>
<Button
id="mui-product-selector"
aria-haspopup="true"
aria-controls={open ? 'drawer-open-button' : undefined}
aria-expanded={open ? 'true' : undefined}
onClick={handleClick}
endIcon={<ArrowDropDownRoundedIcon fontSize="small" sx={{ ml: -0.5 }} />}
sx={(theme) => ({
py: 0.1,
minWidth: 0,
fontSize: theme.typography.pxToRem(13),
fontWeight: theme.typography.fontWeightMedium,
color: (theme.vars || theme).palette.primary[600],
'& svg': {
ml: -0.6,
width: 18,
height: 18,
},
'& > span': {
ml: '4px',
},
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[300],
}),
})}
>
{props.productName}
</Button>
<Menu
id="mui-product-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
MenuListProps={{
'aria-labelledby': 'mui-product-selector',
}}
PaperProps={{
sx: {
width: { xs: 340, sm: 'auto' },
},
}}
>
<MuiProductSelector />
</Menu>
</React.Fragment>
);
}
ProductDrawerButton.propTypes = {
productName: PropTypes.string,
};
function ProductIdentifier(props) {
const { name, metadata, versionSelector } = props;
return (
<Box sx={{ flexGrow: 1 }}>
<Typography
sx={(theme) => ({
ml: 1,
color: (theme.vars || theme).palette.grey[600],
fontSize: theme.typography.pxToRem(11),
fontWeight: 700,
textTransform: 'uppercase',
letterSpacing: '.08rem',
})}
>
{metadata}
</Typography>
<Box sx={{ display: 'flex' }}>
<ProductDrawerButton productName={name} />
{versionSelector}
</Box>
</Box>
);
}
ProductIdentifier.propTypes = {
metadata: PropTypes.string,
name: PropTypes.string.isRequired,
versionSelector: PropTypes.element.isRequired,
};
// To match scrollMarginBottom
const browserUrlPreviewMarge = 120;
function PersistScroll(props) {
const { slot, children, enabled } = props;
const rootRef = React.useRef();
useEnhancedEffect(() => {
const scrollContainer = rootRef.current ? rootRef.current.parentElement : null;
const activeDrawerLink = scrollContainer.querySelector('.app-drawer-active');
if (!enabled || !scrollContainer || !activeDrawerLink || !activeDrawerLink.scrollIntoView) {
return undefined;
}
scrollContainer.scrollTop = savedScrollTop[slot];
const activeBox = activeDrawerLink.getBoundingClientRect();
if (activeBox.top < 0 || activeBox.bottom + browserUrlPreviewMarge > window.innerHeight) {
// Scroll the least possible from the initial render, e.g. server-side, scrollTop = 0.
activeDrawerLink.scrollIntoView({ block: 'nearest' });
}
return () => {
savedScrollTop[slot] = scrollContainer.scrollTop;
};
}, [enabled, slot]);
return <div ref={rootRef}>{children}</div>;
}
PersistScroll.propTypes = {
children: PropTypes.node.isRequired,
enabled: PropTypes.bool.isRequired,
slot: PropTypes.string.isRequired,
};
const ToolbarDiv = styled('div')(({ theme }) => ({
padding: theme.spacing(1.6, 2),
paddingRight: 0,
flexShrink: 0,
height: 'var(--MuiDocs-header-height)',
boxSizing: 'border-box', // TODO have CssBaseline in the Next.js layout
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
}));
const StyledDrawer = styled(Drawer)(({ theme }) => ({
[theme.breakpoints.up('xs')]: {
display: 'none',
},
[theme.breakpoints.up('lg')]: {
display: 'block',
},
}));
const AppNavPaperComponent = styled('div')(() => {
return {
width: 'var(--MuiDocs-navDrawer-width)',
boxShadow: 'none',
border: '0 !important', // TODO add a Paper slot
overflowY: 'unset !important', // TODO add a Paper slot
boxSizing: 'border-box', // TODO have CssBaseline in the Next.js layout
};
});
function renderNavItems(options) {
const { pages, ...params } = options;
return (
<List>{pages.reduce((items, page) => reduceChildRoutes({ items, page, ...params }), [])}</List>
);
}
/**
* @param {object} context
* @param {import('docs/src/pages').MuiPage} context.page
*/
function reduceChildRoutes(context) {
const { onClose, activePageParents, items, depth, t } = context;
const { page } = context;
if (page.inSideNav === false) {
return items;
}
const title = pageToTitleI18n(page, t);
if (page.children && page.children.length >= 1) {
const topLevel =
activePageParents.map((parentPage) => parentPage.pathname).indexOf(page.pathname) !== -1;
let firstChild = page.children[0];
if (firstChild.subheader && firstChild.children) {
firstChild = firstChild.children[0];
}
const subheader = Boolean(page.subheader);
const [path, hash] = firstChild.pathname.split('#');
items.push(
<AppNavDrawerItem
linkProps={page.linkProps}
depth={depth}
key={title}
title={title}
href={{
pathname: path,
...(firstChild.query && { query: firstChild.query }),
...(hash && { hash }),
}}
legacy={page.legacy}
newFeature={page.newFeature}
planned={page.planned}
unstable={page.unstable}
plan={page.plan}
icon={page.icon}
subheader={subheader}
topLevel={topLevel && !page.subheader}
initiallyExpanded={topLevel || subheader}
expandable={!subheader}
>
{renderNavItems({
onClose,
pages: page.children,
activePageParents,
depth: subheader ? depth : depth + 1,
t,
})}
</AppNavDrawerItem>,
);
} else {
const [path, hash] = page.pathname.split('#');
items.push(
<AppNavDrawerItem
linkProps={page.linkProps}
depth={depth}
key={title}
title={title}
href={{
pathname: path,
...(page.query && { query: page.query }),
...(hash && { hash }),
}}
legacy={page.legacy}
newFeature={page.newFeature}
planned={page.planned}
unstable={page.unstable}
plan={page.plan}
icon={page.icon}
subheader={Boolean(page.subheader)}
onClick={onClose}
/>,
);
}
return items;
}
// iOS is hosted on high-end devices. We can enable the backdrop transition without
// dropping frames. The performance will be good enough.
// So: <SwipeableDrawer disableBackdropTransition={false} />
const iOS = typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent);
export default function AppNavDrawer(props) {
const { className, disablePermanent, mobileOpen, onClose, onOpen } = props;
const { activePageParents, pages, productIdentifier } = React.useContext(PageContext);
const [anchorEl, setAnchorEl] = React.useState(null);
const t = useTranslate();
const mobile = useMediaQuery((theme) => theme.breakpoints.down('lg'));
const swipeableDrawer = disablePermanent || mobile;
const drawer = React.useMemo(() => {
const navItems = renderNavItems({ onClose, pages, activePageParents, depth: 0, t });
const renderVersionSelector = (versions, sx) => {
if (!versions?.length) {
return null;
}
const currentVersion = versions.find((version) => version.current) || versions[0];
return (
<React.Fragment>
<Button
id="mui-version-selector"
onClick={(event) => {
setAnchorEl(event.currentTarget);
}}
endIcon={
versions.length > 1 ? (
<ArrowDropDownRoundedIcon fontSize="small" sx={{ ml: -0.5 }} />
) : null
}
sx={[
(theme) => ({
py: 0.1,
minWidth: 0,
fontSize: theme.typography.pxToRem(13),
fontWeight: 500,
color: (theme.vars || theme).palette.primary[600],
'& svg': {
ml: -0.6,
width: 18,
height: 18,
},
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[300],
}),
}),
...(Array.isArray(sx) ? sx : [sx]),
]}
>
{currentVersion.text}
</Button>
<Menu
id="mui-version-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
>
{versions.map((item) => {
if (item.text === 'View all versions') {
return [
<Divider key="divider" />,
<MenuItem key="all-versions" component="a" href={item.href} onClick={onClose}>
{/* eslint-disable-next-line material-ui/no-hardcoded-labels -- version string is untranslatable */}
{`View all versions`}
</MenuItem>,
];
}
return (
<MenuItem
key={item.text}
{...(item.current
? {
selected: true,
onClick: () => setAnchorEl(null),
}
: {
component: 'a',
href: item.href,
onClick: onClose,
})}
>
{item.text} {item.current && <DoneRounded sx={{ fontSize: 16, ml: 0.25 }} />}
</MenuItem>
);
})}
</Menu>
</React.Fragment>
);
};
return (
<React.Fragment>
<ToolbarDiv>
<NextLink href="/" passHref legacyBehavior>
<Box
component="a"
onClick={onClose}
aria-label={t('goToHome')}
sx={{
pr: '12px',
mr: '4px',
borderRight: '1px solid',
borderColor: 'divider',
}}
>
<SvgMuiLogomark width={30} />
</Box>
</NextLink>
<ProductIdentifier
name={productIdentifier.name}
metadata={productIdentifier.metadata}
versionSelector={renderVersionSelector(productIdentifier.versions)}
/>
</ToolbarDiv>
<Divider />
<Box
sx={{
pt: 0.5,
pb: 5,
overflowY: 'auto',
flexGrow: 1,
...(swipeableDrawer
? {}
: {
borderRight: '1px solid',
borderColor: 'divider',
}),
}}
>
<PersistScroll slot="side" enabled>
{navItems}
</PersistScroll>
</Box>
</React.Fragment>
);
}, [onClose, pages, activePageParents, t, productIdentifier, anchorEl, swipeableDrawer]);
if (process.env.NODE_ENV !== 'production') {
if (!productIdentifier) {
throw new Error('docs-infra: missing productIdentifier in PageContext');
}
if (!productIdentifier.versions) {
throw new Error('docs-infra: missing productIdentifier.versions in PageContext');
}
}
return (
<ThemeProvider theme={transitionTheme}>
<nav className={className} aria-label={t('mainNavigation')}>
{swipeableDrawer ? (
<SwipeableDrawer
disableBackdropTransition={!iOS}
variant="temporary"
open={mobileOpen}
onOpen={onOpen}
onClose={onClose}
ModalProps={{
keepMounted: true,
}}
PaperProps={{
component: AppNavPaperComponent,
}}
>
{drawer}
</SwipeableDrawer>
) : (
<StyledDrawer
variant="permanent"
PaperProps={{
component: AppNavPaperComponent,
}}
open
>
{drawer}
</StyledDrawer>
)}
</nav>
</ThemeProvider>
);
}
AppNavDrawer.propTypes = {
className: PropTypes.string,
disablePermanent: PropTypes.bool.isRequired,
mobileOpen: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
onOpen: PropTypes.func.isRequired,
};
| 5,262 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppNavDrawerItem.js | import * as React from 'react';
import PropTypes from 'prop-types';
import KeyboardArrowRightRoundedIcon from '@mui/icons-material/KeyboardArrowRightRounded';
import { alpha, styled } from '@mui/material/styles';
import Collapse from '@mui/material/Collapse';
import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import { samePageLinkNavigation } from 'docs/src/modules/components/MarkdownLinks';
import Link from 'docs/src/modules/components/Link';
import standardNavIcons from './AppNavIcons';
const Item = styled(
function Item({ component: Component = 'div', ...props }) {
return <Component {...props} />;
},
{
shouldForwardProp: (prop) =>
prop !== 'depth' && prop !== 'hasIcon' && prop !== 'subheader' && prop !== 'expandable',
},
)(({ theme, hasIcon, depth, subheader, expandable }) => {
const color = {
color: (theme.vars || theme).palette.text.secondary,
...(depth === 0 && {
color: (theme.vars || theme).palette.text.primary,
}),
...(subheader && {
color: (theme.vars || theme).palette.grey[600],
}),
};
return [
{
...theme.typography.body2,
position: 'relative',
display: 'flex',
alignItems: 'center',
borderRadius: 6,
outline: 0,
width: '100%',
padding: 6,
justifyContent: 'flex-start',
fontWeight:
depth === 0 ? theme.typography.fontWeightSemiBold : theme.typography.fontWeightMedium,
transition: theme.transitions.create(['color', 'background-color'], {
duration: theme.transitions.duration.shortest,
}),
fontSize: theme.typography.pxToRem(14),
textDecoration: 'none',
paddingLeft: 10 + (depth + 1) * 13 - (expandable ? 21 : 0),
'&:before': {
content: '""',
display: 'block',
position: 'absolute',
zIndex: 1,
left: 9.5,
height: '100%',
width: 1,
opacity: depth === 0 ? 0 : 1,
background: (theme.vars || theme).palette.grey[100],
},
...color,
...(subheader && {
marginTop: theme.spacing(1),
textTransform: 'uppercase',
letterSpacing: '.08rem',
fontWeight: theme.typography.fontWeightBold,
fontSize: theme.typography.pxToRem(11),
'&:before': {
content: '""',
display: 'block',
position: 'absolute',
zIndex: 1,
left: 9.5,
height: '55%',
top: 16,
width: 1,
opacity: depth === 0 ? 0 : 1,
background: (theme.vars || theme).palette.grey[100],
},
'&:after': {
content: '""',
display: 'block',
position: 'absolute',
zIndex: 5,
left: 6,
height: 8,
width: 8,
borderRadius: 2,
opacity: depth === 0 ? 0 : 1,
background: alpha(theme.palette.grey[50], 0.5),
border: '1px solid',
borderColor: (theme.vars || theme).palette.grey[200],
},
}),
...(hasIcon && {
paddingLeft: 0,
}),
'&.app-drawer-active': {
// To match browserUrlPreviewMarge
scrollMarginBottom: 120,
color: (theme.vars || theme).palette.primary[600],
backgroundColor: (theme.vars || theme).palette.primary[50],
'&:hover': {
backgroundColor: theme.vars
? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))`
: alpha(
theme.palette.primary.main,
theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity,
),
'@media (hover: none)': {
backgroundColor: theme.vars
? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})`
: alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
},
},
'&.Mui-focusVisible': {
backgroundColor: theme.vars
? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))`
: alpha(
theme.palette.primary.main,
theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity,
),
},
'&:before': {
background: (theme.vars || theme).palette.primary[400],
},
},
'& .MuiChip-root': {
marginTop: '2px',
},
...(!subheader && {
'&:hover': {
color: (theme.vars || theme).palette.common.black,
backgroundColor: (theme.vars || theme).palette.grey[50],
'@media (hover: none)': {
color: color.color,
backgroundColor: 'transparent',
},
},
}),
'&.Mui-focusVisible': {
backgroundColor: (theme.vars || theme).palette.action.focus,
},
[theme.breakpoints.up('md')]: {
paddingTop: 4,
paddingBottom: 4,
},
'& .ItemButtonIcon': {
marginRight: '5px',
color: (theme.vars || theme).palette.primary.main,
},
'&:hover .ItemButtonIcon': {
color: (theme.vars || theme).palette.text.primary,
'@media (hover: none)': {
color: (theme.vars || theme).palette.primary.main,
},
},
},
theme.applyDarkStyles({
...color,
'&:before': {
background: alpha(theme.palette.primaryDark[700], 0.6),
},
'&.app-drawer-active': {
color: (theme.vars || theme).palette.primary[300],
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
'&:before': {
background: (theme.vars || theme).palette.primary[400],
},
},
...(subheader && {
'&:before': {
background: alpha(theme.palette.primaryDark[700], 0.6),
},
'&:after': {
background: alpha(theme.palette.primaryDark[700], 0.8),
borderColor: alpha(theme.palette.primaryDark[600], 0.6),
},
}),
...(!subheader && {
'&:hover': {
color: '#fff',
backgroundColor: alpha(theme.palette.primaryDark[700], 0.4),
'@media (hover: none)': {
color: color.color,
backgroundColor: 'transparent',
},
},
}),
}),
];
});
const ItemButtonIcon = styled(KeyboardArrowRightRoundedIcon, {
shouldForwardProp: (prop) => prop !== 'open',
})(({ open }) => ({
fontSize: '1rem',
transform: open && 'rotate(90deg)',
'&&:last-child': {
// overrrides https://github.com/mui/material-ui/blob/ca7c5c63e64b6a7f55255981f1836a565927b56c/docs/src/modules/brandingTheme.ts#L757-L759
marginLeft: 0,
},
}));
const StyledLi = styled('li', { shouldForwardProp: (prop) => prop !== 'depth' })(
({ theme, depth }) => ({
display: 'block',
padding: depth === 0 ? theme.spacing(1, '10px', 0, '10px') : 0,
}),
);
export const sxChip = (color) => [
(theme) => ({
ml: 1.5,
fontSize: theme.typography.pxToRem(10),
fontWeight: 'semiBold',
textTransform: 'uppercase',
letterSpacing: '.04rem',
height: '16px',
border: 1,
borderColor: (theme.vars || theme).palette[color][300],
bgcolor: alpha(theme.palette[color][100], 0.5),
color: (theme.vars || theme).palette[color][700],
'&:hover': {
bgcolor: alpha(theme.palette[color][100], 0.5),
},
'& .MuiChip-label': {
px: 0.6,
},
}),
(theme) =>
theme.applyDarkStyles({
borderColor: alpha(theme.palette[color][800], 0.5),
bgcolor: alpha(theme.palette[color][800], 0.5),
color: (theme.vars || theme).palette[color][300],
'&:hover': {
bgcolor: alpha(theme.palette[color][900], 0.5),
},
}),
];
function DeadLink(props) {
const { activeClassName, href, noLinkStyle, prefetch, ...other } = props;
return <div {...other} />;
}
DeadLink.propTypes = {
activeClassName: PropTypes.any,
href: PropTypes.any,
noLinkStyle: PropTypes.any,
prefetch: PropTypes.any,
};
export default function AppNavDrawerItem(props) {
const {
children,
depth,
href,
icon,
legacy,
newFeature,
planned,
unstable,
linkProps,
onClick,
initiallyExpanded = false,
expandable = false,
plan = 'community',
subheader,
title,
topLevel = false,
...other
} = props;
const [open, setOpen] = React.useState(initiallyExpanded);
const handleClick = (event) => {
// Ignore the action if opening the link in a new tab
if (samePageLinkNavigation(event)) {
return;
}
if (onClick) {
onClick(event);
}
if (expandable) {
event.preventDefault();
setOpen((oldOpen) => !oldOpen);
}
};
const hasIcon = icon && (typeof icon !== 'string' || !!standardNavIcons[icon]);
const IconComponent = typeof icon === 'string' ? standardNavIcons[icon] : icon;
const iconElement = hasIcon ? (
<Box
component="span"
sx={{
'& svg': { fontSize: (theme) => theme.typography.pxToRem(16.5) },
display: 'flex',
alignItems: 'center',
height: '100%',
marginRight: '6px',
}}
>
<IconComponent fontSize="small" color="primary" />
</Box>
) : null;
return (
<StyledLi {...other} depth={depth}>
{/* Fix overloading with prefetch={false}, only prefetch on hover */}
<Item
component={subheader ? DeadLink : Link}
depth={depth}
hasIcon={hasIcon}
href={href}
prefetch={false}
subheader={subheader}
expandable={expandable}
activeClassName={initiallyExpanded ? null : 'app-drawer-active'}
className={topLevel ? 'algolia-lvl0' : null}
onClick={handleClick}
{...linkProps}
>
{iconElement}
{expandable && <ItemButtonIcon className="ItemButtonIcon" open={open} />}
{title}
{plan === 'pro' && <span className="plan-pro" title="Pro plan" />}
{plan === 'premium' && <span className="plan-premium" title="Premium plan" />}
{legacy && <Chip label="Legacy" sx={sxChip('warning')} />}
{newFeature && <Chip label="New" sx={sxChip('success')} />}
{planned && <Chip label="Planned" sx={sxChip('grey')} />}
{unstable && <Chip label="Preview" sx={sxChip('primary')} />}
</Item>
{expandable ? (
<Collapse in={open} timeout="auto" unmountOnExit>
{children}
</Collapse>
) : (
children
)}
</StyledLi>
);
}
AppNavDrawerItem.propTypes = {
children: PropTypes.node,
depth: PropTypes.number.isRequired,
expandable: PropTypes.bool,
href: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
icon: PropTypes.elementType,
initiallyExpanded: PropTypes.bool,
legacy: PropTypes.bool,
linkProps: PropTypes.object,
newFeature: PropTypes.bool,
onClick: PropTypes.func,
plan: PropTypes.oneOf(['community', 'pro', 'premium']),
planned: PropTypes.bool,
subheader: PropTypes.bool.isRequired,
title: PropTypes.string.isRequired,
topLevel: PropTypes.bool,
unstable: PropTypes.bool,
};
| 5,263 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppNavIcons.ts | /// <reference path="../../../types/icons.d.ts"/>
import ArticleRoundedIcon from '@mui/icons-material/ArticleRounded';
import VisibilityRoundedIcon from '@mui/icons-material/VisibilityRounded';
import BookRoundedIcon from '@mui/icons-material/BookRounded';
import ChromeReaderModeRoundedIcon from '@mui/icons-material/ChromeReaderModeRounded';
const standardNavIcons = {
ReaderIcon: ChromeReaderModeRoundedIcon,
BookIcon: BookRoundedIcon,
DescriptionIcon: ArticleRoundedIcon,
VisibilityIcon: VisibilityRoundedIcon,
};
export default standardNavIcons;
| 5,264 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppSearch.js | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as ReactDOMServer from 'react-dom/server';
import PropTypes from 'prop-types';
import NextLink from 'next/link';
import { useRouter } from 'next/router';
import { DocSearchModal, useDocSearchKeyboardEvents } from '@docsearch/react';
import Chip from '@mui/material/Chip';
import ArticleRoundedIcon from '@mui/icons-material/ArticleRounded';
import ToggleOffRoundedIcon from '@mui/icons-material/ToggleOffRounded';
import EditRoundedIcon from '@mui/icons-material/EditRounded';
import HandymanRoundedIcon from '@mui/icons-material/HandymanRounded';
import KeyboardArrowRightRounded from '@mui/icons-material/KeyboardArrowRightRounded';
import SearchIcon from '@mui/icons-material/Search';
import GlobalStyles from '@mui/material/GlobalStyles';
import { alpha, styled } from '@mui/material/styles';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import { LANGUAGES_SSR } from 'docs/config';
import Link from 'docs/src/modules/components/Link';
import { useTranslate, useUserLanguage } from 'docs/src/modules/utils/i18n';
import useLazyCSS from 'docs/src/modules/utils/useLazyCSS';
import PageContext from 'docs/src/modules/components/PageContext';
const SearchButton = styled('button')(({ theme }) => [
{
minHeight: 34,
display: 'flex',
alignItems: 'center',
margin: 0,
paddingLeft: theme.spacing(0.6),
[theme.breakpoints.only('xs')]: {
backgroundColor: 'transparent',
padding: 0,
minWidth: 34,
justifyContent: 'center',
'& > *:not(.MuiSvgIcon-root)': {
display: 'none',
},
},
fontFamily: theme.typography.fontFamily,
position: 'relative',
backgroundColor: (theme.vars || theme).palette.grey[50],
color: (theme.vars || theme).palette.text.secondary,
fontSize: theme.typography.pxToRem(14),
border: `1px solid ${(theme.vars || theme).palette.grey[200]}`,
borderRadius: 10,
cursor: 'pointer',
transitionProperty: 'all',
transitionDuration: '150ms',
boxShadow: `inset 0 1px 1px ${(theme.vars || theme).palette.grey[100]}, 0 1px 0.5px ${alpha(
theme.palette.grey[100],
0.6,
)}`,
'&:hover': {
background: (theme.vars || theme).palette.grey[100],
borderColor: (theme.vars || theme).palette.grey[300],
},
},
theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primaryDark[700], 0.4),
borderColor: (theme.vars || theme).palette.primaryDark[700],
boxShadow: `inset 0 1px 1px ${(theme.vars || theme).palette.primaryDark[900]}, 0 1px 0.5px ${
(theme.vars || theme).palette.common.black
}`,
'&:hover': {
background: (theme.vars || theme).palette.primaryDark[700],
borderColor: (theme.vars || theme).palette.primaryDark[600],
},
}),
]);
const SearchLabel = styled('span')(({ theme }) => {
return {
marginLeft: theme.spacing(1),
marginRight: 'auto',
};
});
const Shortcut = styled('div')(({ theme }) => {
return {
fontSize: theme.typography.pxToRem(12),
fontWeight: 700,
lineHeight: '20px',
marginLeft: theme.spacing(0.5),
border: `1px solid ${(theme.vars || theme).palette.grey[200]}`,
backgroundColor: '#FFF',
padding: theme.spacing(0, 0.5),
borderRadius: 7,
...theme.applyDarkStyles({
borderColor: (theme.vars || theme).palette.primaryDark[600],
backgroundColor: (theme.vars || theme).palette.primaryDark[800],
}),
};
});
function NewStartScreen() {
const startScreenOptions = [
{
category: {
name: 'Getting started',
icon: <ArticleRoundedIcon className="DocSearch-NewStartScreenTitleIcon" />,
},
items: [
{ name: 'Installation', href: '/material-ui/getting-started/installation/' },
{ name: 'Usage', href: '/material-ui/getting-started/usage/' },
{ name: 'Learn', href: '/material-ui/getting-started/learn/' },
],
},
{
category: {
name: 'Popular searches',
icon: <ToggleOffRoundedIcon className="DocSearch-NewStartScreenTitleIcon" />,
},
items: [
{ name: 'Material Icons', href: '/material-ui/material-icons/' },
{ name: 'Text Field', href: '/material-ui/react-text-field/' },
{ name: 'Button', href: '/material-ui/react-button/' },
],
},
{
category: {
name: 'Customization',
icon: <EditRoundedIcon className="DocSearch-NewStartScreenTitleIcon" />,
},
items: [
{ name: 'How to customize', href: '/material-ui/customization/how-to-customize/' },
{ name: 'Theming', href: '/material-ui/customization/theming/' },
{ name: 'Default theme', href: '/material-ui/customization/default-theme/' },
],
},
{
category: {
name: 'System',
icon: <HandymanRoundedIcon className="DocSearch-NewStartScreenTitleIcon" />,
},
items: [
{ name: 'Overview', href: '/system/getting-started/' },
{ name: 'Properties', href: '/system/properties/' },
{ name: 'The sx prop', href: '/system/getting-started/the-sx-prop/' },
],
},
];
return (
<div className="DocSearch-NewStartScreen">
{startScreenOptions.map(({ category, items }) => (
<div key={category.name} className="DocSearch-NewStartScreenCategory">
<div className="DocSearch-NewStartScreenTitle">
{category.icon}
{category.name}
</div>
{items.map(({ name, href }) => (
<NextLink key={name} href={href} className="DocSearch-NewStartScreenItem">
{name}
<KeyboardArrowRightRounded className="DocSearch-NewStartScreenItemIcon" />
</NextLink>
))}
</div>
))}
</div>
);
}
const displayTagProductId = {
'material-ui': 'Material UI',
'joy-ui': 'Joy UI',
'base-ui': 'Base UI',
x: 'MUI X',
system: 'MUI System',
toolpad: 'Toolpad',
};
function getDisplayTag(hit) {
if (hit.productId === undefined || hit.productCategoryId === undefined) {
return null;
}
const productInfo = {
productId: hit.productId,
productCategoryId: hit.productCategoryId,
};
const displayTag =
displayTagProductId[productInfo.productId] ||
displayTagProductId[productInfo.productCategoryId];
if (!displayTag) {
console.error(
`getDisplayTag missing mapping for productId: ${productInfo.productId}, pathname: ${hit.pathname}.`,
);
}
return <Chip label={displayTag} size="small" variant="outlined" sx={{ mr: 1 }} />;
}
function DocSearchHit(props) {
const { children, hit } = props;
if (hit.pathname) {
return (
<Link
href={hit.pathname}
as={hit.as}
sx={{ display: 'flex !important', '& .DocSearch-Hit-Container': { flex: 1, minWidth: 0 } }}
>
{children}
{getDisplayTag(hit)}
</Link>
);
}
// DocSearch stores the old results in its cache
// hit.pathname won't be defined for them.
return <Link href={hit.url}>{children}</Link>;
}
DocSearchHit.propTypes = {
children: PropTypes.node,
hit: PropTypes.object.isRequired,
};
export default function AppSearch(props) {
useLazyCSS(
'https://cdn.jsdelivr.net/npm/@docsearch/[email protected]/dist/style.min.css',
'#app-search',
);
const FADE_DURATION = 100; // ms
const t = useTranslate();
const userLanguage = useUserLanguage();
const searchButtonRef = React.useRef(null);
const [isOpen, setIsOpen] = React.useState(false);
const [initialQuery, setInitialQuery] = React.useState(undefined);
const facetFilterLanguage =
LANGUAGES_SSR.indexOf(userLanguage) !== -1 ? `language:${userLanguage}` : `language:en`;
const macOS = window.navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const onOpen = React.useCallback(() => {
setIsOpen(true);
}, [setIsOpen]);
const router = useRouter();
const pageContext = React.useContext(PageContext);
const keyboardNavigator = {
navigate({ item }) {
const as = item.userLanguage !== 'en' ? `/${item.userLanguage}${item.as}` : item.as;
router.push(item.pathname, as);
},
};
const onClose = React.useCallback(() => {
const modal = document.querySelector('.DocSearch-Container');
if (modal) {
// fade out transition
modal.style.opacity = 0;
}
setIsOpen(false); // DO NOT call setIsOpen inside a timeout (it causes scroll issue).
}, [setIsOpen]);
const onInput = React.useCallback(
(event) => {
setIsOpen(true);
setInitialQuery(event.key);
},
[setIsOpen, setInitialQuery],
);
useDocSearchKeyboardEvents({
isOpen,
onOpen,
onClose,
onInput,
searchButtonRef,
});
React.useEffect(() => {
const addStartScreen = () => {
const dropDown = document.querySelector('.DocSearch-Dropdown');
const isExisting = document.querySelector('.DocSearch-NewStartScreen');
if (dropDown && !isExisting) {
dropDown.insertAdjacentHTML(
'beforeend',
ReactDOMServer.renderToStaticMarkup(<NewStartScreen />),
);
}
};
// add transition to Modal
if (isOpen) {
const modal = document.querySelector('.DocSearch-Container');
const searchInput = document.querySelector('.DocSearch-Input');
if (modal) {
modal.style.opacity = 1;
addStartScreen();
}
if (searchInput) {
const handleInput = (event) => {
const newStartScreen = document.querySelector('.DocSearch-NewStartScreen');
if (newStartScreen) {
newStartScreen.style.display = event.target.value !== '' ? 'none' : 'grid';
}
};
searchInput.addEventListener('input', handleInput);
return () => {
searchInput.removeEventListener('input', handleInput);
};
}
}
return () => {};
}, [isOpen]);
const search = `${t('algoliaSearch')}…`;
const optionalFilters = [];
if (pageContext.productId !== 'null') {
optionalFilters.push(`productId:${pageContext.productId}`);
} else if (pageContext.productCategoryId !== 'null') {
optionalFilters.push(`productCategoryId:${pageContext.productCategoryId}`);
}
return (
<React.Fragment>
<SearchButton
ref={searchButtonRef}
onClick={onOpen}
aria-labelledby="app-search-label"
{...props}
>
<SearchIcon
fontSize="small"
sx={(theme) => ({
color: 'primary.500',
...theme.applyDarkStyles({
color: 'primary.300',
}),
})}
/>
<SearchLabel id="app-search-label">{search}</SearchLabel>
<Shortcut aria-hidden="true">
{/* eslint-disable-next-line material-ui/no-hardcoded-labels */}
{macOS ? '⌘' : 'Ctrl+'}K
</Shortcut>
</SearchButton>
{isOpen &&
ReactDOM.createPortal(
<DocSearchModal
initialQuery={initialQuery}
appId="TZGZ85B9TB"
apiKey="8177dfb3e2be72b241ffb8c5abafa899"
indexName="material-ui"
searchParameters={{
facetFilters: ['version:master', facetFilterLanguage],
optionalFilters,
attributesToRetrieve: [
// Copied from https://github.com/algolia/docsearch/blob/ce0c865cd8767e961ce3088b3155fc982d4c2e2e/packages/docsearch-react/src/DocSearchModal.tsx#L231
'hierarchy.lvl0',
'hierarchy.lvl1',
'hierarchy.lvl2',
'hierarchy.lvl3',
'hierarchy.lvl4',
'hierarchy.lvl5',
'hierarchy.lvl6',
'content',
'type',
'url',
// Extra
'productId',
'productCategoryId',
],
analyticsTags: [facetFilterLanguage, `product:${pageContext.productId}`],
hitsPerPage: 40,
}}
placeholder={search}
transformItems={(items) => {
return items.map((item) => {
// `url` contains the domain
// but we want to link to the current domain e.g. deploy-preview-1--material-ui.netlify.app
const parseUrl = document.createElement('a');
parseUrl.href = item.url;
const { canonicalAs, canonicalPathname } = pathnameToLanguage(
`${parseUrl.pathname}${parseUrl.hash}`,
);
return {
...item,
pathname: canonicalPathname,
as: canonicalAs,
userLanguage,
};
});
}}
hitComponent={DocSearchHit}
initialScrollY={typeof window !== 'undefined' ? window.scrollY : undefined}
onClose={onClose}
navigator={keyboardNavigator}
/>,
document.body,
)}
<GlobalStyles
styles={(theme) => ({
html: {
':root': {
'--docsearch-primary-color': (theme.vars || theme).palette.primary[500],
'--docsearch-text-color': (theme.vars || theme).palette.text.primary,
'--docsearch-muted-color': (theme.vars || theme).palette.grey[600],
'--docsearch-searchbox-shadow': 0,
'--docsearch-hit-shadow': 0,
'--docsearch-footer-shadow': 0,
'--docsearch-spacing': theme.spacing(1.5),
'--docsearch-hit-active-color': (theme.vars || theme).palette.primary[600],
'--docsearch-logo-color': (theme.vars || theme).palette.grey[600],
'--docsearch-searchbox-focus-background': 'unset',
'--docsearch-footer-background': 'unset',
'--docsearch-modal-background': (theme.vars || theme).palette.background.paper,
},
},
body: {
'.DocSearch-Container': {
transition: `opacity ${FADE_DURATION}ms`,
opacity: 0,
zIndex: theme.zIndex.tooltip + 100,
backgroundColor: alpha(theme.palette.grey[600], 0.2),
backdropFilter: 'blur(4px)',
},
'& .DocSearch-StartScreen': {
display: 'none',
},
'& .DocSearch-NewStartScreen': {
display: 'grid',
gridTemplateColumns: 'repeat(2, 1fr)',
gap: theme.spacing(2),
padding: theme.spacing(2, 1),
},
'& .DocSearch-NewStartScreenCategory': {
display: 'flex',
flexDirection: 'column',
},
'& .DocSearch-NewStartScreenTitle': {
display: 'flex',
alignItems: 'center',
padding: theme.spacing(1, 1),
fontSize: theme.typography.pxToRem(14),
color: (theme.vars || theme).palette.text.secondary,
},
'& .DocSearch-NewStartScreenTitleIcon': {
color: (theme.vars || theme).palette.primary[500],
marginRight: theme.spacing(1.5),
fontSize: theme.typography.pxToRem(16),
},
'& .DocSearch-NewStartScreenItem': {
display: 'flex',
alignItems: 'center',
cursor: 'pointer',
width: '100%',
padding: theme.spacing(0.5, 4.6),
color: (theme.vars || theme).palette.primary[500],
fontWeight: 500,
fontSize: theme.typography.pxToRem(14),
'&:hover, &:focus': {
'.DocSearch-NewStartScreenItemIcon': {
marginLeft: theme.spacing(1),
},
},
},
'& .DocSearch-NewStartScreenItemIcon': {
marginLeft: theme.spacing(0.5),
transition: 'margin 0.2s',
fontSize: theme.typography.pxToRem(16),
},
'& .DocSearch-Modal': {
maxWidth: '700px',
boxShadow: `0px 4px 20px ${alpha(theme.palette.grey[700], 0.2)}`,
// docsearch.css: <= 750px will be full screen modal
borderRadius: `clamp(0px, (100vw - 750px) * 9999, ${theme.shape.borderRadius}px)`,
},
'& .DocSearch-SearchBar': {
borderBottom: '1px solid',
borderColor: (theme.vars || theme).palette.grey[200],
padding: theme.spacing(1),
},
'& .DocSearch-Form': {
'& .DocSearch-Reset': {
display: 'none',
},
'& .DocSearch-Input': {
paddingLeft: theme.spacing(2.5),
},
'& .DocSearch-Search-Icon': {
width: '20px',
height: '20px',
},
},
'& .DocSearch-Cancel': {
display: 'block',
alignSelf: 'center',
cursor: 'pointer',
height: '1.5rem',
marginRight: theme.spacing(1),
padding: theme.spacing(0.3, 0.8, 0.6, 0.8),
fontSize: 0,
borderRadius: 5,
backgroundColor: (theme.vars || theme).palette.grey[50],
border: '1px solid',
borderColor: (theme.vars || theme).palette.grey[300],
'&::before': {
content: '"esc"',
fontSize: theme.typography.pxToRem(12),
letterSpacing: '.08rem',
fontWeight: 700,
color: (theme.vars || theme).palette.text.secondary,
},
},
'& .DocSearch-Dropdown': {
minHeight: 384, // = StartScreen height, to prevent layout shift when first char
'&::-webkit-scrollbar-thumb': {
borderColor: (theme.vars || theme).palette.background.paper,
backgroundColor: (theme.vars || theme).palette.grey[500],
},
'&::-webkit-scrollbar-track': {
backgroundColor: (theme.vars || theme).palette.background.paper,
},
},
'& .DocSearch-Dropdown-Container': {
'& .DocSearch-Hits:first-of-type': {
'& .DocSearch-Hit-source': {
paddingTop: theme.spacing(1),
},
},
},
'& .DocSearch-Hit-source': {
top: 'initial',
paddingTop: theme.spacing(2),
background: (theme.vars || theme).palette.background.paper,
fontSize: theme.typography.pxToRem(13),
fontWeight: 500,
color: (theme.vars || theme).palette.text.secondary,
},
'& .DocSearch-Hit': {
paddingBottom: 0,
'&:not(:first-of-type)': {
marginTop: -1,
},
},
'& .DocSearch-Hit a': {
backgroundColor: 'transparent',
padding: theme.spacing(0.25, 0),
paddingLeft: theme.spacing(2),
border: '1px solid transparent',
borderBottomColor: (theme.vars || theme).palette.grey[100],
},
'& .DocSearch-Hit-content-wrapper': {
paddingLeft: theme.spacing(2),
},
'& .DocSearch-Hit-title': {
fontSize: theme.typography.pxToRem(14),
color: `${theme.palette.text.primary}`,
},
'& .DocSearch-Hit-path': {
fontSize: theme.typography.pxToRem(12),
color: `${theme.palette.text.secondary}`,
},
'& .DocSearch-Hit-Select-Icon': {
height: '15px',
width: '15px',
},
'& .DocSearch-Hit[aria-selected="true"] a': {
backgroundColor: (theme.vars || theme).palette.primary[50],
borderColor: (theme.vars || theme).palette.primary[500],
borderRadius: theme.shape.borderRadius,
},
'& .DocSearch-Hit-action, & .DocSearch-Hits mark': {
color: (theme.vars || theme).palette.primary[500],
},
'& .DocSearch-Footer': {
borderTop: '1px solid',
borderColor: (theme.vars || theme).palette.grey[200],
'& .DocSearch-Commands': {
display: 'none',
},
},
},
})}
/>
<GlobalStyles
styles={(theme) => [
{
[theme.vars ? '[data-mui-color-scheme="dark"]:root' : '.mode-dark']: {
'--docsearch-primary-color': (theme.vars || theme).palette.primaryDark[300],
'--docsearch-hit-active-color': (theme.vars || theme).palette.primary[300],
},
},
{
[theme.vars ? '[data-mui-color-scheme="dark"] body' : '.mode-dark']: {
'.DocSearch-Container': {
backgroundColor: alpha(theme.palette.grey[900], 0.7),
},
'& .DocSearch-NewStartScreenTitleIcon': {
color: (theme.vars || theme).palette.primaryDark[300],
},
'& .DocSearch-NewStartScreenItem': {
color: (theme.vars || theme).palette.primaryDark[300],
},
'& .DocSearch-Modal': {
boxShadow: `0px 4px 20px ${alpha(theme.palette.background.paper, 0.7)}`,
border: '1px solid',
borderColor: (theme.vars || theme).palette.primaryDark[700],
},
'& .DocSearch-SearchBar': {
borderColor: (theme.vars || theme).palette.primaryDark[700],
},
'& .DocSearch-Cancel': {
backgroundColor: (theme.vars || theme).palette.primaryDark[800],
borderColor: (theme.vars || theme).palette.primaryDark[600],
},
'& .DocSearch-Dropdown': {
'&::-webkit-scrollbar-thumb': {
borderColor: (theme.vars || theme).palette.primaryDark[900],
backgroundColor: (theme.vars || theme).palette.primaryDark[700],
},
},
'& .DocSearch-Hit a': {
borderBottomColor: (theme.vars || theme).palette.primaryDark[700],
},
'& .DocSearch-Hit[aria-selected="true"] a': {
backgroundColor: (theme.vars || theme).palette.primaryDark[800],
borderColor: (theme.vars || theme).palette.primaryDark[400],
},
'& .DocSearch-Hit-action, & .DocSearch-Hits mark': {
color: (theme.vars || theme).palette.primary[400],
},
'& .DocSearch-Footer': {
borderColor: (theme.vars || theme).palette.primaryDark[700],
},
},
},
]}
/>
</React.Fragment>
);
}
| 5,265 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppSettingsDrawer.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { styled, useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import Drawer from '@mui/material/Drawer';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import LightModeIcon from '@mui/icons-material/LightMode';
import DarkModeOutlinedIcon from '@mui/icons-material/DarkModeOutlined';
import SettingsBrightnessIcon from '@mui/icons-material/SettingsBrightness';
import FormatTextdirectionLToRIcon from '@mui/icons-material/FormatTextdirectionLToR';
import FormatTextdirectionRToLIcon from '@mui/icons-material/FormatTextdirectionRToL';
import { useChangeTheme } from 'docs/src/modules/components/ThemeContext';
import { useTranslate } from 'docs/src/modules/utils/i18n';
const Heading = styled(Typography)(({ theme }) => ({
margin: '20px 0 10px',
color: theme.palette.grey[600],
fontWeight: 700,
fontSize: theme.typography.pxToRem(11),
textTransform: 'uppercase',
letterSpacing: '.08rem',
}));
const IconToggleButton = styled(ToggleButton)({
display: 'flex',
justifyContent: 'center',
width: '100%',
'& > *': {
marginRight: '8px',
},
});
function AppSettingsDrawer(props) {
const { onClose, open = false, ...other } = props;
const t = useTranslate();
const upperTheme = useTheme();
const changeTheme = useChangeTheme();
const [mode, setMode] = React.useState(null);
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const preferredMode = prefersDarkMode ? 'dark' : 'light';
React.useEffect(() => {
// syncing with homepage, can be removed once all pages are migrated to CSS variables
let initialMode = 'system';
try {
initialMode = localStorage.getItem('mui-mode') || initialMode;
} catch (error) {
// do nothing
}
setMode(initialMode);
}, [preferredMode]);
const handleChangeThemeMode = (event, paletteMode) => {
if (paletteMode === null) {
return;
}
setMode(paletteMode);
if (paletteMode === 'system') {
try {
localStorage.setItem('mui-mode', 'system'); // syncing with homepage, can be removed once all pages are migrated to CSS variables
} catch (error) {
// thrown when cookies are disabled.
}
changeTheme({ paletteMode: preferredMode });
} else {
try {
localStorage.setItem('mui-mode', paletteMode); // syncing with homepage, can be removed once all pages are migrated to CSS variables
} catch (error) {
// thrown when cookies are disabled.
}
changeTheme({ paletteMode });
}
};
const handleChangeDirection = (event, direction) => {
if (direction === null) {
direction = upperTheme.direction;
}
changeTheme({ direction });
};
return (
<Drawer
anchor="right"
onClose={onClose}
open={open}
PaperProps={{
elevation: 0,
sx: { width: { xs: 310, sm: 360 }, borderRadius: '10px 0px 0px 10px' },
}}
{...other}
>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', p: 2 }}>
<Typography variant="body1" fontWeight="500">
{t('settings.settings')}
</Typography>
<IconButton color="inherit" onClick={onClose} edge="end" aria-label={t('close')}>
<CloseIcon color="primary" fontSize="small" />
</IconButton>
</Box>
<Divider />
<Box sx={{ pl: 2, pr: 2 }}>
<Heading gutterBottom id="settings-mode">
{t('settings.mode')}
</Heading>
<ToggleButtonGroup
exclusive
value={mode}
color="primary"
onChange={handleChangeThemeMode}
aria-labelledby="settings-mode"
fullWidth
>
<IconToggleButton
value="light"
aria-label={t('settings.light')}
data-ga-event-category="settings"
data-ga-event-action="light"
>
<LightModeIcon fontSize="small" />
{t('settings.light')}
</IconToggleButton>
<IconToggleButton
value="system"
aria-label={t('settings.system')}
data-ga-event-category="settings"
data-ga-event-action="system"
>
<SettingsBrightnessIcon fontSize="small" />
{t('settings.system')}
</IconToggleButton>
<IconToggleButton
value="dark"
aria-label={t('settings.dark')}
data-ga-event-category="settings"
data-ga-event-action="dark"
>
<DarkModeOutlinedIcon fontSize="small" />
{t('settings.dark')}
</IconToggleButton>
</ToggleButtonGroup>
<Heading gutterBottom id="settings-direction">
{t('settings.direction')}
</Heading>
<ToggleButtonGroup
exclusive
value={upperTheme.direction}
onChange={handleChangeDirection}
aria-labelledby="settings-direction"
color="primary"
fullWidth
>
<IconToggleButton
value="ltr"
aria-label={t('settings.ltr')}
data-ga-event-category="settings"
data-ga-event-action="ltr"
>
<FormatTextdirectionLToRIcon fontSize="small" />
{t('settings.ltr')}
</IconToggleButton>
<IconToggleButton
value="rtl"
aria-label={t('settings.rtl')}
data-ga-event-category="settings"
data-ga-event-action="rtl"
>
<FormatTextdirectionRToLIcon fontSize="small" />
{t('settings.rtl')}
</IconToggleButton>
</ToggleButtonGroup>
<Heading gutterBottom>{t('settings.color')}</Heading>
<Button
component="a"
href="/material-ui/customization/color/#playground"
data-ga-event-category="settings"
data-ga-event-action="colors"
size="medium"
variant="outlined"
fullWidth
>
{t('settings.editWebsiteColors')}
</Button>
</Box>
</Drawer>
);
}
AppSettingsDrawer.propTypes = {
onClose: PropTypes.func.isRequired,
open: PropTypes.bool,
};
export default AppSettingsDrawer;
| 5,266 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppTableOfContents.js | /* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import throttle from 'lodash/throttle';
import { styled, alpha } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import NoSsr from '@mui/material/NoSsr';
import Link from 'docs/src/modules/components/Link';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import { samePageLinkNavigation } from 'docs/src/modules/components/MarkdownLinks';
import TableOfContentsBanner from 'docs/src/components/banner/TableOfContentsBanner';
import featureToggle from 'docs/src/featureToggle';
import DiamondSponsors from 'docs/src/modules/components/DiamondSponsors';
const Nav = styled('nav')(({ theme }) => ({
top: 'var(--MuiDocs-header-height)',
marginTop: 'var(--MuiDocs-header-height)',
paddingLeft: 2, // Fix truncated focus outline style
position: 'sticky',
height: 'calc(100vh - var(--MuiDocs-header-height))',
overflowY: 'auto',
paddingTop: theme.spacing(4),
paddingBottom: theme.spacing(7),
paddingRight: theme.spacing(4), // We can't use `padding` as stylis-plugin-rtl doesn't swap it
display: 'none',
[theme.breakpoints.up('md')]: {
display: 'block',
},
}));
const NavLabel = styled(Typography)(({ theme }) => ({
padding: theme.spacing(1, 0, 1, 1.4),
fontSize: theme.typography.pxToRem(11),
fontWeight: theme.typography.fontWeightBold,
textTransform: 'uppercase',
letterSpacing: '.08rem',
color: theme.palette.grey[600],
}));
const NavList = styled(Typography)({
padding: 0,
margin: 0,
listStyle: 'none',
});
const NavItem = styled(Link, {
shouldForwardProp: (prop) =>
prop !== 'active' && prop !== 'secondary' && prop !== 'secondarySubItem',
})(({ active, secondary, secondarySubItem, theme }) => {
const activeStyles = {
borderLeftColor: (theme.vars || theme).palette.primary[200],
color: (theme.vars || theme).palette.primary[600],
'&:hover': {
borderLeftColor: (theme.vars || theme).palette.primary[600],
color: (theme.vars || theme).palette.primary[600],
},
};
const activeDarkStyles = {
borderLeftColor: (theme.vars || theme).palette.primary[600],
color: (theme.vars || theme).palette.primary[300],
'&:hover': {
borderLeftColor: (theme.vars || theme).palette.primary[400],
color: (theme.vars || theme).palette.primary[400],
},
};
let paddingLeft = '12px';
if (secondary) {
paddingLeft = 3;
}
if (secondarySubItem) {
paddingLeft = 4.5;
}
return [
{
boxSizing: 'border-box',
padding: theme.spacing('6px', 0, '6px', paddingLeft),
borderLeft: `1px solid transparent`,
display: 'block',
fontSize: theme.typography.pxToRem(13),
fontWeight: theme.typography.fontWeightMedium,
textOverflow: 'ellipsis',
overflow: 'hidden',
'&:hover': {
borderLeftColor: (theme.vars || theme).palette.grey[400],
color: (theme.vars || theme).palette.grey[600],
},
...(!active && {
color: (theme.vars || theme).palette.text.primary,
}),
// TODO: We probably want `aria-current="location"` instead.
...(active && activeStyles),
'&:active': activeStyles,
},
theme.applyDarkStyles({
'&:hover': {
borderLeftColor: (theme.vars || theme).palette.grey[500],
color: (theme.vars || theme).palette.grey[200],
},
...(!active && {
color: (theme.vars || theme).palette.grey[500],
}),
...(active && activeDarkStyles),
'&:active': activeDarkStyles,
}),
];
});
const noop = () => {};
function useThrottledOnScroll(callback, delay) {
const throttledCallback = React.useMemo(
() => (callback ? throttle(callback, delay) : noop),
[callback, delay],
);
React.useEffect(() => {
if (throttledCallback === noop) {
return undefined;
}
window.addEventListener('scroll', throttledCallback);
return () => {
window.removeEventListener('scroll', throttledCallback);
throttledCallback.cancel();
};
}, [throttledCallback]);
}
function flatten(headings) {
const itemsWithNode = [];
headings.forEach((item) => {
itemsWithNode.push(item);
if (item.children.length > 0) {
item.children.forEach((subitem) => {
itemsWithNode.push(subitem);
});
}
});
return itemsWithNode;
}
function shouldShowJobAd() {
const date = new Date();
const timeZoneOffset = date.getTimezoneOffset();
// Hide for time zones UT+5.5 - UTC+14 & UTC-8 - UTC-12
if (timeZoneOffset <= -5.5 * 60 || timeZoneOffset >= 8 * 60) {
return false;
}
return true;
}
const showSurveyBanner = false;
const showJobAd = featureToggle.enable_job_banner && shouldShowJobAd();
export default function AppTableOfContents(props) {
const { toc } = props;
const t = useTranslate();
const items = React.useMemo(() => flatten(toc), [toc]);
const [activeState, setActiveState] = React.useState(null);
const clickedRef = React.useRef(false);
const unsetClickedRef = React.useRef(null);
const findActiveIndex = React.useCallback(() => {
// Don't set the active index based on scroll if a link was just clicked
if (clickedRef.current) {
return;
}
let active;
for (let i = items.length - 1; i >= 0; i -= 1) {
// No hash if we're near the top of the page
if (document.documentElement.scrollTop < 200) {
active = { hash: null };
break;
}
const item = items[i];
const node = document.getElementById(item.hash);
if (process.env.NODE_ENV !== 'production') {
if (!node) {
console.error(`Missing node on the item ${JSON.stringify(item, null, 2)}`);
}
}
if (
node &&
node.offsetTop <
document.documentElement.scrollTop + document.documentElement.clientHeight / 8
) {
active = item;
break;
}
}
if (active && activeState !== active.hash) {
setActiveState(active.hash);
}
}, [activeState, items]);
// Corresponds to 10 frames at 60 Hz
useThrottledOnScroll(items.length > 0 ? findActiveIndex : null, 166);
const handleClick = (hash) => (event) => {
// Ignore click for new tab/new window behavior
if (samePageLinkNavigation(event)) {
return;
}
// Used to disable findActiveIndex if the page scrolls due to a click
clickedRef.current = true;
unsetClickedRef.current = setTimeout(() => {
clickedRef.current = false;
}, 1000);
if (activeState !== hash) {
setActiveState(hash);
}
};
React.useEffect(
() => () => {
clearTimeout(unsetClickedRef.current);
},
[],
);
const itemLink = (item, secondary, secondarySubItem) => (
<NavItem
display="block"
href={`#${item.hash}`}
underline="none"
onClick={handleClick(item.hash)}
active={activeState === item.hash}
secondary={secondary}
secondarySubItem={secondarySubItem}
>
<span dangerouslySetInnerHTML={{ __html: item.text }} />
</NavItem>
);
return (
<Nav aria-label={t('pageTOC')}>
<TableOfContentsBanner />
<NoSsr>
{showSurveyBanner && (
<Link
href="https://www.surveymonkey.com/r/mui-developer-survey-2022?source=docs"
target="_blank"
sx={[
(theme) => ({
mb: 2,
p: 1,
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
backgroundColor: alpha(theme.palette.grey[50], 0.4),
border: '1px solid',
borderColor: (theme.vars || theme).palette.grey[200],
borderRadius: 1,
transitionProperty: 'all',
transitionTiming: 'cubic-bezier(0.4, 0, 0.2, 1)',
transitionDuration: '150ms',
'&:hover, &:focus-visible': {
borderColor: (theme.vars || theme).palette.primary[200],
},
}),
(theme) =>
theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primary[900], 0.2),
borderColor: (theme.vars || theme).palette.primaryDark[700],
'&:hover, &:focus-visible': {
borderColor: (theme.vars || theme).palette.primaryDark[500],
},
}),
]}
>
<Typography component="span" variant="button" fontWeight="500" color="text.primary">
{'📫 MUI Developer survey 2022 is live!'}
</Typography>
<Typography
component="span"
variant="caption"
fontWeight="normal"
color="text.secondary"
sx={{ mt: 0.5 }}
>
{/* eslint-disable-next-line material-ui/no-hardcoded-labels */}
{'Influence the future of MUI. Help define the roadmap for 2023!'}
</Typography>
</Link>
)}
{!showSurveyBanner && showJobAd && (
<Link
href="https://jobs.ashbyhq.com/MUI?utm_source=2vOWXNv1PE"
target="_blank"
sx={[
(theme) => ({
mb: 2,
p: 1,
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
backgroundColor: alpha(theme.palette.grey[50], 0.4),
border: '1px solid',
borderColor: (theme.vars || theme).palette.grey[200],
borderRadius: 1,
transitionProperty: 'all',
transitionTiming: 'cubic-bezier(0.4, 0, 0.2, 1)',
transitionDuration: '150ms',
'&:hover, &:focus-visible': {
borderColor: (theme.vars || theme).palette.primary[200],
},
}),
(theme) =>
theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primary[900], 0.2),
borderColor: (theme.vars || theme).palette.primaryDark[700],
'&:hover, &:focus-visible': {
borderColor: (theme.vars || theme).palette.primaryDark[500],
},
}),
]}
>
<Typography component="span" variant="button" fontWeight="500" color="text.primary">
{'🚀 Join the MUI team!'}
</Typography>
<Typography
component="span"
variant="caption"
fontWeight="normal"
color="text.secondary"
sx={{ mt: 0.5 }}
>
{/* eslint-disable-next-line material-ui/no-hardcoded-labels */}
{"We're looking for React Engineers and other amazing roles-come find out more!"}
</Typography>
</Link>
)}
</NoSsr>
{toc.length > 0 ? (
<React.Fragment>
<NavLabel>{t('tableOfContents')}</NavLabel>
<NavList component="ul">
{toc.map((item) => (
<li key={item.text}>
{itemLink(item)}
{item.children.length > 0 ? (
<NavList as="ul">
{item.children.map((subitem) => (
<li key={subitem.text}>
{itemLink(subitem, true)}
{subitem.children?.length > 0 ? (
<NavList as="ul">
{subitem.children.map((nestedSubItem) => (
<li key={nestedSubItem.text}>
{itemLink(nestedSubItem, false, true)}
</li>
))}
</NavList>
) : null}
</li>
))}
</NavList>
) : null}
</li>
))}
</NavList>
</React.Fragment>
) : null}
<DiamondSponsors />
</Nav>
);
}
AppTableOfContents.propTypes = {
toc: PropTypes.array.isRequired,
};
| 5,267 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/AppTheme.js | import * as React from 'react';
import PropTypes from 'prop-types';
import Head from 'docs/src/modules/components/Head';
export default function AppTheme(props) {
const { children } = props;
return (
<React.Fragment>
<Head>
<meta name="robots" content="noindex,nofollow" />
</Head>
{children}
</React.Fragment>
);
}
AppTheme.propTypes = {
children: PropTypes.node.isRequired,
};
| 5,268 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/BackToTop.tsx | import * as React from 'react';
import useScrollTrigger from '@mui/material/useScrollTrigger';
import Fab from '@mui/material/Fab';
import Box from '@mui/material/Box';
import Tooltip from '@mui/material/Tooltip';
import KeyboardArrowUpRoundedIcon from '@mui/icons-material/KeyboardArrowUpRounded';
import Fade from '@mui/material/Fade';
import { Theme } from '@mui/material/styles';
import { useTranslate } from 'docs/src/modules/utils/i18n';
export default function BackToTop() {
const t = useTranslate();
const [open, setOpen] = React.useState(false);
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
const trigger = useScrollTrigger({
disableHysteresis: true,
threshold: 200,
});
const handleClick = () => {
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
const behavior = prefersReducedMotion.matches ? 'auto' : 'smooth';
window.scrollTo({ top: 0, behavior });
setOpen(false);
};
return (
<Fade in={trigger}>
<Tooltip title="Scroll to top" open={open} onClose={handleClose} onOpen={handleOpen}>
<Box
className="mui-fixed"
sx={{
position: 'fixed',
bottom: 24,
right: 24,
zIndex: 10,
}}
>
<Fab
sx={[
(theme) => ({
backgroundColor: (theme.vars || theme).palette.primary[100],
boxShadow: `0px 4px 20px rgba(170, 180, 190, 0.3)`,
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primary[200],
},
'&:active': {
boxShadow: `0px 4px 20px rgba(170, 180, 190, 0.6)`,
},
}),
(theme) =>
theme.applyDarkStyles({
backgroundColor: (theme.vars || theme).palette.primaryDark[400],
boxShadow: `0px 4px 20px rgba(0, 0, 0, 0.5)`,
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primaryDark[500],
},
'&:active': {
boxShadow: `0px 4px 20px rgba(0, 0, 0, 0.7)`,
},
}),
]}
size="small"
aria-label={t('backToTop')}
onClick={handleClick}
data-ga-event-category="docs"
data-ga-event-action="click-back-to-top"
>
<KeyboardArrowUpRoundedIcon
sx={(theme: Theme) => ({
color: (theme.vars || theme).palette.primary[800],
...theme.applyDarkStyles({
color: (theme.vars || theme).palette.primary[200],
}),
})}
/>
</Fab>
</Box>
</Tooltip>
</Fade>
);
}
| 5,269 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/BaseUIComponents.js | import * as React from 'react';
import Card from '@mui/material/Card';
import CardMedia from '@mui/material/CardMedia';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import { alpha } from '@mui/material/styles';
import Link from 'docs/src/modules/components/Link';
function components() {
return [
{
title: 'Autocomplete',
srcLight: '/static/base-ui/react-components/autocomplete-light.png',
srcDark: '/static/base-ui/react-components/autocomplete-dark.png',
href: '/base-ui/react-autocomplete/',
},
{
title: 'Badge',
srcLight: '/static/base-ui/react-components/badge-light.png',
srcDark: '/static/base-ui/react-components/badge-dark.png',
href: '/base-ui/react-badge/',
},
{
title: 'Button',
srcLight: '/static/base-ui/react-components/button-light.png',
srcDark: '/static/base-ui/react-components/button-dark.png',
href: '/base-ui/react-button/',
},
{
title: 'Click-Away Listener',
srcLight: '/static/base-ui/react-components/click-away-light.png',
srcDark: '/static/base-ui/react-components/click-away-dark.png',
href: '/base-ui/react-click-away-listener/',
},
{
title: 'Focus Trap',
srcLight: '/static/base-ui/react-components/focus-trap-light.png',
srcDark: '/static/base-ui/react-components/focus-trap-dark.png',
href: '/base-ui/react-focus-trap/',
},
{
title: 'Form Control',
srcLight: '/static/base-ui/react-components/form-control-light.png',
srcDark: '/static/base-ui/react-components/form-control-dark.png',
href: '/base-ui/react-form-control/',
},
{
title: 'Input',
srcLight: '/static/base-ui/react-components/input-light.png',
srcDark: '/static/base-ui/react-components/input-dark.png',
href: '/base-ui/react-input/',
},
{
title: 'Menu',
srcLight: '/static/base-ui/react-components/menu-light.png',
srcDark: '/static/base-ui/react-components/menu-dark.png',
href: '/base-ui/react-menu/',
},
{
title: 'Modal',
srcLight: '/static/base-ui/react-components/modal-light.png',
srcDark: '/static/base-ui/react-components/modal-dark.png',
href: '/base-ui/react-modal/',
},
{
title: 'No-SSR',
srcLight: '/static/base-ui/react-components/no-ssr-light.png',
srcDark: '/static/base-ui/react-components/no-ssr-dark.png',
href: '/base-ui/react-no-ssr/',
},
{
title: 'Number Input',
srcLight: '/static/base-ui/react-components/number-input-light.png',
srcDark: '/static/base-ui/react-components/number-input-dark.png',
href: '/base-ui/react-number-input/',
},
{
title: 'Popper',
srcLight: '/static/base-ui/react-components/popper-light.png',
srcDark: '/static/base-ui/react-components/popper-dark.png',
href: '/base-ui/react-popper/',
},
{
title: 'Portal',
srcLight: '/static/base-ui/react-components/portal-light.png',
srcDark: '/static/base-ui/react-components/portal-dark.png',
href: '/base-ui/react-portal/',
},
{
title: 'Select',
srcLight: '/static/base-ui/react-components/select-light.png',
srcDark: '/static/base-ui/react-components/select-dark.png',
href: '/base-ui/react-select/',
},
{
title: 'Slider',
srcLight: '/static/base-ui/react-components/slider-light.png',
srcDark: '/static/base-ui/react-components/slider-dark.png',
href: '/base-ui/react-slider/',
},
{
title: 'Snackbar',
srcLight: '/static/base-ui/react-components/snackbar-light.png',
srcDark: '/static/base-ui/react-components/snackbar-dark.png',
href: '/base-ui/react-snackbar/',
},
{
title: 'Switch',
srcLight: '/static/base-ui/react-components/switch-light.png',
srcDark: '/static/base-ui/react-components/switch-dark.png',
href: '/base-ui/react-switch/',
},
{
title: 'Table Pagination',
srcLight: '/static/base-ui/react-components/pagination-light.png',
srcDark: '/static/base-ui/react-components/pagination-dark.png',
href: '/base-ui/react-table-pagination/',
},
{
title: 'Tabs',
srcLight: '/static/base-ui/react-components/tabs-light.png',
srcDark: '/static/base-ui/react-components/tabs-dark.png',
href: '/base-ui/react-tabs/',
},
{
title: 'Textarea Autosize',
srcLight: '/static/base-ui/react-components/textarea-light.png',
srcDark: '/static/base-ui/react-components/textarea-dark.png',
href: '/base-ui/react-textarea-autosize/',
},
];
}
export default function BaseUIComponents() {
return (
<Grid container spacing={2} sx={{ pt: 2, pb: 4 }}>
{components().map((component) => (
<Grid item xs={12} sm={4} sx={{ flexGrow: 1 }} key={component.title}>
<Card
component={Link}
noLinkStyle
variant="outlined"
href={component.href}
sx={(theme) => ({
height: '100%',
display: 'flex',
flexDirection: 'column',
borderRadius: 1,
borderColor: 'divider',
...theme.applyDarkStyles({
backgroundColor: `${alpha(theme.palette.primaryDark[700], 0.3)}`,
borderColor: 'divider',
}),
})}
>
<CardMedia
component="img"
alt=""
image={component.srcLight}
sx={(theme) => ({
aspectRatio: '16 / 9',
background: `linear-gradient(180deg, ${alpha(
theme.palette.grey[50],
0.5,
)} 20%, #FFF 100%)`,
borderBottom: '1px solid',
borderColor: 'divider',
...theme.applyDarkStyles({
content: `url(${component.srcDark})`,
background: `linear-gradient(180deg, ${alpha(
theme.palette.primaryDark[800],
0.5,
)} 20%, ${theme.palette.primaryDark[900]} 100%)`,
borderColor: 'divider',
}),
})}
/>
<Typography
component="h2"
variant="body2"
fontWeight="semiBold"
sx={{ px: 2, py: 1.5 }}
>
{component.title}
</Typography>
</Card>
</Grid>
))}
</Grid>
);
}
| 5,270 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/BundleSizeIcon.js | import * as React from 'react';
import { createSvgIcon } from '@mui/material/utils';
export default createSvgIcon(
<g fill="currentColor" fillRule="nonzero">
<path
d="M5.84 3c-.52 0-1 .25-1.3.67l-1.4 2.05c-.06.09-.1.19-.14.28h8V3H5.84zM20.86 5.72l-1.4-2.05c-.3-.42-.81-.67-1.33-.67H13v3h8c-.05-.1-.08-.2-.14-.28z"
fillOpacity=".79"
/>
<path
d="M20.98 7H3.02L3 7.11V19.4c0 .89.71 1.61 1.58 1.61h14.84A1.6 1.6 0 0021 19.4V7.1L20.98 7zm-6.87 5.36H9.89a1.6 1.6 0 01-1.58-1.61c0-.89.7-1.6 1.58-1.6h4.22c.87 0 1.58.71 1.58 1.6 0 .89-.7 1.6-1.58 1.6z"
fillOpacity=".87"
/>
</g>,
'BundleSize',
);
| 5,271 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/CodeCopyButton.tsx | import * as React from 'react';
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
import LibraryAddCheckRoundedIcon from '@mui/icons-material/LibraryAddCheckRounded';
import useClipboardCopy from 'docs/src/modules/utils/useClipboardCopy';
interface CodeCopyButtonProps {
code: string;
}
export default function CodeCopyButton(props: CodeCopyButtonProps) {
const { code, ...other } = props;
const { copy, isCopied } = useClipboardCopy();
// This component is designed to be wrapped in NoSsr
const macOS = window.navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const key = macOS ? '⌘' : 'Ctrl + ';
return (
<button
{...other}
aria-label="Copy the code"
type="button"
className="MuiCode-copy"
onClick={async () => {
// event.stopPropagation();
await copy(code);
}}
>
{/* material-ui/no-hardcoded-labels */}
{isCopied ? (
<LibraryAddCheckRoundedIcon sx={{ fontSize: 18 }} />
) : (
<ContentCopyRoundedIcon sx={{ fontSize: 18 }} />
)}
<span className="MuiCode-copyKeypress">
<span>(or</span> {key}C<span>)</span>
</span>
</button>
);
}
| 5,272 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ComponentLinkHeader.js | import * as React from 'react';
import PropTypes from 'prop-types';
import Chip from '@mui/material/Chip';
import Tooltip from '@mui/material/Tooltip';
import ChatRounded from '@mui/icons-material/ChatRounded';
import { styled } from '@mui/material/styles';
import SketchIcon from 'docs/src/modules/components/SketchIcon';
import FigmaIcon from 'docs/src/modules/components/FigmaIcon';
import AdobeXDIcon from 'docs/src/modules/components/AdobeXDIcon';
import BundleSizeIcon from 'docs/src/modules/components/BundleSizeIcon';
import W3CIcon from 'docs/src/modules/components/W3CIcon';
import MaterialDesignIcon from 'docs/src/modules/components/MaterialDesignIcon';
import { useTranslate } from 'docs/src/modules/utils/i18n';
const Root = styled('ul')({
margin: 0,
padding: 0,
listStyle: 'none',
display: 'flex',
flexWrap: 'wrap',
gap: 8,
'& .MuiChip-root .MuiChip-iconSmall': {
marginLeft: 4,
},
});
const defaultPackageNames = {
'material-ui': '@mui/material',
'joy-ui': '@mui/joy',
'base-ui': '@mui/base',
system: '@mui/system',
};
export default function ComponentLinkHeader(props) {
const {
markdown: { headers },
design,
} = props;
const t = useTranslate();
const packageName =
headers.packageName ?? defaultPackageNames[headers.productId] ?? '@mui/material';
return (
<Root>
{headers.githubLabel ? (
<li>
<Chip
clickable
role={undefined}
component="a"
size="small"
variant="outlined"
rel="nofollow"
href={`${process.env.SOURCE_CODE_REPO}/labels/${encodeURIComponent(
headers.githubLabel,
)}`}
icon={<ChatRounded color="primary" />}
data-ga-event-category="ComponentLinkHeader"
data-ga-event-action="click"
data-ga-event-label={t('githubLabel')}
data-ga-event-split="0.1"
label={t('githubLabel')}
/>
</li>
) : null}
<li>
<Tooltip title={t('bundleSizeTooltip')}>
<Chip
clickable
role={undefined}
component="a"
size="small"
variant="outlined"
rel="nofollow"
href={`https://bundlephobia.com/package/${packageName}@latest`}
icon={<BundleSizeIcon color="primary" />}
data-ga-event-category="ComponentLinkHeader"
data-ga-event-action="click"
data-ga-event-label={t('bundleSize')}
data-ga-event-split="0.1"
label={t('bundleSize')}
/>
</Tooltip>
</li>
{headers.waiAria ? (
<li>
<Chip
clickable
role={undefined}
component="a"
size="small"
variant="outlined"
rel="nofollow"
href={headers.waiAria}
icon={<W3CIcon color="primary" />}
data-ga-event-category="ComponentLinkHeader"
data-ga-event-action="click"
data-ga-event-label="WAI-ARIA"
data-ga-event-split="0.1"
label="WAI-ARIA"
/>
</li>
) : null}
{headers.materialDesign ? (
<li>
<Chip
clickable
role={undefined}
component="a"
size="small"
variant="outlined"
rel="nofollow"
href={headers.materialDesign}
icon={<MaterialDesignIcon />}
data-ga-event-category="ComponentLinkHeader"
data-ga-event-action="click"
data-ga-event-label="Material Design"
data-ga-event-split="0.1"
label="Material Design"
/>
</li>
) : null}
{design !== false ? (
<React.Fragment>
<li>
<Chip
clickable
role={undefined}
component="a"
size="small"
variant="outlined"
rel="nofollow"
href="https://mui.com/store/items/figma-react/?utm_source=docs&utm_medium=referral&utm_campaign=component-link-header"
icon={<FigmaIcon />}
data-ga-event-category="ComponentLinkHeader"
data-ga-event-action="click"
data-ga-event-label="Figma"
data-ga-event-split="0.1"
label="Figma"
/>
</li>
{packageName !== '@mui/joy' ? (
<li>
<Chip
clickable
role={undefined}
component="a"
size="small"
variant="outlined"
rel="nofollow"
href="https://mui.com/store/items/adobe-xd-react/?utm_source=docs&utm_medium=referral&utm_campaign=component-link-header"
icon={<AdobeXDIcon />}
data-ga-event-category="ComponentLinkHeader"
data-ga-event-action="click"
data-ga-event-label="Adobe XD"
data-ga-event-split="0.1"
label="Adobe"
/>
</li>
) : null}
{packageName !== '@mui/joy' ? (
<li>
<Chip
clickable
role={undefined}
component="a"
size="small"
variant="outlined"
rel="nofollow"
href="https://mui.com/store/items/sketch-react/?utm_source=docs&utm_medium=referral&utm_campaign=component-link-header"
icon={<SketchIcon />}
data-ga-event-category="ComponentLinkHeader"
data-ga-event-action="click"
data-ga-event-label="Sketch"
data-ga-event-split="0.1"
label="Sketch"
/>
</li>
) : null}
</React.Fragment>
) : null}
</Root>
);
}
ComponentLinkHeader.propTypes = {
design: PropTypes.bool,
markdown: PropTypes.shape({
headers: PropTypes.object.isRequired,
}).isRequired,
};
| 5,273 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ComponentPageTabs.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { useRouter } from 'next/router';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Tabs, { tabsClasses } from '@mui/material/Tabs';
import Tab, { tabClasses } from '@mui/material/Tab';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import Link from 'docs/src/modules/components/Link';
export const HEIGHT = 50;
const StyledTab = styled(Tab)(({ theme }) => ({
padding: theme.spacing(1),
marginBottom: theme.spacing(1),
marginRight: theme.spacing(1),
fontWeight: 600,
minHeight: 32,
minWidth: 0,
borderRadius: '12px',
'&:hover': {
background: (theme.vars || theme).palette.grey[50],
},
...theme.applyDarkStyles({
'&:hover': {
background: (theme.vars || theme).palette.primaryDark[700],
},
'&.Mui-selected': {
color: (theme.vars || theme).palette.primary[300],
},
}),
}));
export default function ComponentPageTabs(props) {
const {
activeTab,
children,
markdown: { headers },
} = props;
const router = useRouter();
const t = useTranslate();
const demosHref = router.pathname.endsWith('[docsTab]')
? router.pathname.replace('[docsTab]', '')
: router.pathname;
const apiPathname = `${demosHref.endsWith('/') ? demosHref : `${demosHref}/`}`;
const componentsHref = `${apiPathname}components-api`;
const hooksHref = `${apiPathname}hooks-api`;
return (
<Box className="component-tabs" sx={{ display: 'inline' }}>
<Tabs
value={activeTab}
sx={{
position: 'sticky',
top: 65, // to be positioned below the app bar
mt: 1,
pt: 1,
mx: {
xs: -2,
sm: 0,
},
px: {
xs: 2,
sm: 0,
},
backgroundColor: (theme) =>
theme.palette.mode === 'dark' ? theme.palette.primaryDark[900] : 'rgba(255,255,255)',
borderBottom: 1,
borderColor: 'divider',
zIndex: 1000,
[`& .${tabsClasses.indicator}`]: {
transition: 'none',
},
// Make server side styles closer to hydrated
[`& .${tabClasses.root}`]: {
overflow: 'visible',
[`& .${tabsClasses.indicator}`]: {
top: '39px',
borderRadius: 0,
},
},
}}
>
<StyledTab
component={Link}
shallow
scroll
href={demosHref}
label={t('api-docs.demos')}
value=""
/>
{headers.components?.length > 0 && (
<StyledTab
className="skip-algolia-crawler" // For more details, see https://github.com/mui/material-ui/pull/37539.
component={Link}
shallow
scroll
href={componentsHref}
label={t('api-docs.componentsApi')}
value="components-api"
/>
)}
{headers.hooks && headers.hooks.length > 0 && (
<StyledTab
className="skip-algolia-crawler" // For more details, see https://github.com/mui/material-ui/pull/37539.
component={Link}
shallow
scroll
href={hooksHref}
label={t('api-docs.hooksApi')}
value="hooks-api"
/>
)}
</Tabs>
{children}
</Box>
);
}
ComponentPageTabs.propTypes = {
activeTab: PropTypes.string,
children: PropTypes.node,
markdown: PropTypes.shape({
headers: PropTypes.shape({
components: PropTypes.array,
hooks: PropTypes.array,
}),
}),
};
| 5,274 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/ComponentsApiContent.js | /* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import kebabCase from 'lodash/kebabCase';
import { useRouter } from 'next/router';
import { exactProp } from '@mui/utils';
import { useTranslate, useUserLanguage } from 'docs/src/modules/utils/i18n';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
import PropertiesSection from 'docs/src/modules/components/ApiPage/sections/PropertiesSection';
import CSSSection from 'docs/src/modules/components/ApiPage/sections/CssSection';
import ClassesSection from 'docs/src/modules/components/ApiPage/sections/ClassesSection';
import SlotsSection from 'docs/src/modules/components/ApiPage/sections/SlotsSection';
function getTranslatedHeader(t, header, text) {
const translations = {
demos: t('api-docs.demos'),
import: t('api-docs.import'),
props: t('api-docs.props'),
'theme-default-props': t('api-docs.themeDefaultProps'),
inheritance: t('api-docs.inheritance'),
slots: t('api-docs.slots'),
classes: t('api-docs.classes'),
css: t('api-docs.css'),
};
return translations[header] || translations[text] || text || header;
}
function Heading(props) {
const { hash, text, level: Level = 'h2' } = props;
const t = useTranslate();
return (
<Level id={hash}>
{getTranslatedHeader(t, hash, text)}
<a aria-labelledby={hash} className="anchor-link" href={`#${hash}`} tabIndex={-1}>
<svg>
<use xlinkHref="#anchor-link-icon" />
</svg>
</a>
</Level>
);
}
Heading.propTypes = {
hash: PropTypes.string.isRequired,
level: PropTypes.string,
text: PropTypes.string,
};
export default function ComponentsApiContent(props) {
const { descriptions, pageContents } = props;
const t = useTranslate();
const userLanguage = useUserLanguage();
const router = useRouter();
// There are legacy links where the the components had the Unstyled suffix
// This effects makes sure that the anchors will be correct wtih the renames
React.useEffect(() => {
const anchor = router.asPath.indexOf('#') >= 0 ? router.asPath.split('#')[1] : null;
if (router.isReady && anchor && anchor.indexOf('-unstyled') >= 0) {
router.replace(
{
hash: `${anchor.replace('-unstyled', '')}`,
},
null,
{
shallow: true,
},
);
}
}, [router]);
const components = Object.keys(pageContents);
return components.map((key) => {
const pageContent = pageContents[key];
const {
cssComponent,
filename,
forwardsRefTo,
inheritance,
name: componentName,
props: componentProps,
spread,
styles: componentStyles,
slots: componentSlots,
classes: componentClasses,
imports,
} = pageContent;
const { classDescriptions, propDescriptions, slotDescriptions } =
descriptions[key][userLanguage];
const isJoyComponent = filename.includes('mui-joy');
const isBaseComponent = filename.includes('mui-base');
const defaultPropsLink = isJoyComponent
? '/joy-ui/customization/themed-components/#theme-default-props'
: '/material-ui/customization/theme-components/#theme-default-props';
const styleOverridesLink = isJoyComponent
? '/joy-ui/customization/themed-components/#theme-style-overrides'
: '/material-ui/customization/theme-components/#theme-style-overrides';
let slotGuideLink = '';
if (isJoyComponent) {
slotGuideLink = '/joy-ui/customization/overriding-component-structure/';
} else if (isBaseComponent) {
slotGuideLink = '/base-ui/guides/overriding-component-structure/';
}
// The `ref` is forwarded to the root element.
let refHint = t('api-docs.refRootElement');
if (forwardsRefTo == null) {
// The component cannot hold a ref.
refHint = t('api-docs.refNotHeld');
}
let spreadHint = '';
if (spread) {
// Any other props supplied will be provided to the root element ({{spreadHintElement}}).
spreadHint = t('api-docs.spreadHint').replace(
/{{spreadHintElement}}/,
inheritance
? `<a href="${inheritance.pathname}">${inheritance.component}</a>`
: t('api-docs.nativeElement'),
);
}
let inheritanceSuffix = '';
if (inheritance && inheritance.component === 'Transition') {
inheritanceSuffix = t('api-docs.inheritanceSuffixTransition');
}
const componentNameKebabCase = kebabCase(componentName);
const importInstructions = imports.join(`
// ${t('or')}
`);
return (
<React.Fragment key={`component-api-${key}`}>
<MarkdownElement>
<Heading hash={componentNameKebabCase} text={`${componentName} API`} />
<Heading text="import" hash={`${componentNameKebabCase}-import`} level="h3" />
<HighlightedCode code={importInstructions} language="jsx" />
<span dangerouslySetInnerHTML={{ __html: t('api-docs.importDifference') }} />
<PropertiesSection
properties={componentProps}
propertiesDescriptions={propDescriptions}
targetName={componentNameKebabCase}
spreadHint={spreadHint}
level="h3"
titleHash={`${componentNameKebabCase}-props`}
/>
<br />
{cssComponent && (
<React.Fragment>
<span
dangerouslySetInnerHTML={{
__html: t('api-docs.cssComponent').replace(/{{name}}/, pageContent.name),
}}
/>
<br />
<br />
</React.Fragment>
)}
<div
className="MuiCallout-root MuiCallout-info"
dangerouslySetInnerHTML={{ __html: refHint }}
style={{
alignItems: 'baseline',
gap: '4px',
marginTop: 0,
}}
/>
{inheritance && (
<React.Fragment>
<Heading
text="inheritance"
hash={`${componentNameKebabCase}-inheritance`}
level="h3"
/>
<span
dangerouslySetInnerHTML={{
__html: t('api-docs.inheritanceDescription')
.replace(/{{component}}/, inheritance.component)
.replace(/{{pathname}}/, inheritance.pathname)
.replace(/{{suffix}}/, inheritanceSuffix)
.replace(/{{name}}/, pageContent.name),
}}
/>
</React.Fragment>
)}
{pageContent.themeDefaultProps && (
<React.Fragment>
<Heading
text="theme-default-props"
hash={`${componentName}-theme-default-props`}
level="h4"
/>
<span
dangerouslySetInnerHTML={{
__html: t('api-docs.themeDefaultPropsDescription')
.replace(/{{muiName}}/, pageContent.muiName)
.replace(/{{defaultPropsLink}}/, defaultPropsLink),
}}
/>
</React.Fragment>
)}
<CSSSection
componentStyles={componentStyles}
classDescriptions={classDescriptions}
componentName={componentName}
styleOverridesLink={styleOverridesLink}
titleHash={`${componentName}-css`}
level="h3"
/>
<SlotsSection
componentSlots={componentSlots}
slotDescriptions={slotDescriptions}
componentName={componentName}
titleHash={`${componentNameKebabCase}-slots`}
level="h3"
spreadHint={
slotGuideLink &&
t('api-docs.slotDescription').replace(/{{slotGuideLink}}/, slotGuideLink)
}
/>
<ClassesSection
componentClasses={componentClasses}
componentName={pageContent.name}
classDescriptions={classDescriptions}
spreadHint={t('api-docs.classesDescription')}
titleHash={`${componentNameKebabCase}-classes`}
level="h3"
/>
</MarkdownElement>
<svg style={{ display: 'none' }} xmlns="http://www.w3.org/2000/svg">
<symbol id="anchor-link-icon" viewBox="0 0 16 16">
<path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z" />
</symbol>
</svg>
</React.Fragment>
);
});
}
ComponentsApiContent.propTypes = {
descriptions: PropTypes.object.isRequired,
pageContents: PropTypes.object.isRequired,
};
if (process.env.NODE_ENV !== 'production') {
ComponentsApiContent.propTypes = exactProp(ComponentsApiContent.propTypes);
}
| 5,275 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/Demo.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { useRouter } from 'next/router';
import { debounce } from '@mui/material/utils';
import { alpha, styled } from '@mui/material/styles';
import { styled as joyStyled } from '@mui/joy/styles';
import { unstable_useId as useId } from '@mui/utils';
import IconButton from '@mui/material/IconButton';
import Box from '@mui/material/Box';
import Collapse from '@mui/material/Collapse';
import NoSsr from '@mui/material/NoSsr';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
import DemoSandbox from 'docs/src/modules/components/DemoSandbox';
import ReactRunner from 'docs/src/modules/components/ReactRunner';
import DemoEditor from 'docs/src/modules/components/DemoEditor';
import DemoEditorError from 'docs/src/modules/components/DemoEditorError';
import { AdCarbonInline } from 'docs/src/modules/components/AdCarbon';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import { useCodeVariant } from 'docs/src/modules/utils/codeVariant';
import { useCodeStyling } from 'docs/src/modules/utils/codeStylingSolution';
import { CODE_VARIANTS, CODE_STYLING } from 'docs/src/modules/constants';
import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n';
import stylingSolutionMapping from 'docs/src/modules/utils/stylingSolutionMapping';
import BrandingProvider from 'docs/src/BrandingProvider';
import DemoToolbarRoot from 'docs/src/modules/components/DemoToolbarRoot';
import { blue, blueDark, grey } from 'docs/src/modules/brandingTheme';
/**
* Removes leading spaces (indentation) present in the `.tsx` previews
* to be able to replace the existing code with the incoming dynamic code
* @param {string} input
*/
function trimLeadingSpaces(input = '') {
return input.replace(/^\s+/gm, '');
}
const DemoToolbar = React.lazy(() => import('./DemoToolbar'));
function DemoToolbarFallback() {
const t = useTranslate();
// Sync with styles from DemoToolbar, we can't import the styles
return <Box sx={{ height: 40 }} aria-busy aria-label={t('demoToolbarLabel')} role="toolbar" />;
}
function getDemoName(location) {
return location.endsWith('.js') || location.endsWith('.tsx')
? location.replace(/(.+?)(\w+)\.\w+$$/, '$2')
: // the demos with multiple styling solution point to directory
location.split('/').pop();
}
function useDemoData(codeVariant, demo, githubLocation, codeStyling) {
const userLanguage = useUserLanguage();
const router = useRouter();
const { canonicalAs } = pathnameToLanguage(router.asPath);
return React.useMemo(() => {
let productId;
let name = 'Material UI';
if (canonicalAs.startsWith('/joy-ui/')) {
productId = 'joy-ui';
name = 'Joy UI';
} else if (canonicalAs.startsWith('/base-ui/')) {
productId = 'base-ui';
name = 'Base UI';
} else if (canonicalAs.startsWith('/x/')) {
name = 'MUI X';
}
let codeOptions = {};
if (codeStyling === CODE_STYLING.SYSTEM) {
if (codeVariant === CODE_VARIANTS.TS && demo.rawTS) {
codeOptions = {
codeVariant: CODE_VARIANTS.TS,
githubLocation: githubLocation.replace(/\.js$/, '.tsx'),
raw: demo.rawTS,
Component: demo.tsx,
sourceLanguage: 'tsx',
};
} else {
codeOptions = {
codeVariant: CODE_VARIANTS.JS,
githubLocation,
raw: demo.raw,
Component: demo.js,
sourceLanguage: 'jsx',
};
}
} else if (codeStyling === CODE_STYLING.TAILWIND) {
if (codeVariant === CODE_VARIANTS.TS && demo.rawTailwindTS) {
codeOptions = {
codeVariant: CODE_VARIANTS.TS,
githubLocation: githubLocation.replace(/\/system\/index\.js$/, '/tailwind/index.tsx'),
raw: demo.rawTailwindTS,
Component: demo.tsxTailwind,
sourceLanguage: 'tsx',
};
} else {
codeOptions = {
codeVariant: CODE_VARIANTS.JS,
githubLocation: githubLocation.replace(/\/system\/index\.js$/, '/tailwind/index.js'),
raw: demo.rawTailwind ?? demo.raw,
Component: demo.jsTailwind ?? demo.js,
sourceLanguage: 'jsx',
};
}
} else if (codeStyling === CODE_STYLING.CSS) {
if (codeVariant === CODE_VARIANTS.TS && demo.rawCSSTS) {
codeOptions = {
codeVariant: CODE_VARIANTS.TS,
githubLocation: githubLocation.replace(/\/system\/index\.js$/, '/css/index.tsx'),
raw: demo.rawCSSTS,
Component: demo.tsxCSS,
sourceLanguage: 'tsx',
};
} else {
codeOptions = {
codeVariant: CODE_VARIANTS.JS,
githubLocation: githubLocation.replace(/\/system\/index\.js$/, '/css/index.js'),
raw: demo.rawCSS ?? demo.raw,
Component: demo.jsCSS ?? demo.js,
sourceLanguage: 'jsx',
};
}
}
let jsxPreview = demo.jsxPreview;
if (codeStyling === CODE_STYLING.TAILWIND && demo.tailwindJsxPreview) {
jsxPreview = demo.tailwindJsxPreview;
} else if (codeStyling === CODE_STYLING.CSS && demo.cssJsxPreview) {
jsxPreview = demo.cssJsxPreview;
}
return {
scope: demo.scope,
jsxPreview,
...codeOptions,
title: `${getDemoName(githubLocation)} demo — ${name}`,
productId,
language: userLanguage,
codeStyling,
};
}, [canonicalAs, codeVariant, demo, githubLocation, userLanguage, codeStyling]);
}
function useDemoElement({ demoData, editorCode, setDebouncedError, liveDemoActive }) {
const debouncedSetError = React.useMemo(
() => debounce(setDebouncedError, 300),
[setDebouncedError],
);
React.useEffect(() => {
return () => {
debouncedSetError.clear();
};
}, [debouncedSetError]);
// Memoize to avoid rendering the demo more than it needs to be.
// For example, avoid a render when the demo is hovered.
const BundledComponent = React.useMemo(() => <demoData.Component />, [demoData]);
const LiveComponent = React.useMemo(
() => (
<ReactRunner
scope={demoData.scope}
onError={debouncedSetError}
code={
editorCode.isPreview
? trimLeadingSpaces(demoData.raw).replace(
trimLeadingSpaces(demoData.jsxPreview),
editorCode.value,
)
: editorCode.value
}
/>
),
[demoData, debouncedSetError, editorCode.isPreview, editorCode.value],
);
// No need for a live environment if the code matches with the component rendered server-side.
return editorCode.value === editorCode.initialEditorCode && liveDemoActive === false
? BundledComponent
: LiveComponent;
}
const Root = styled('div')(({ theme }) => ({
marginBottom: 24,
marginLeft: theme.spacing(-2),
marginRight: theme.spacing(-2),
[theme.breakpoints.up('sm')]: {
marginLeft: 0,
marginRight: 0,
},
}));
const DemoRootMaterial = styled('div', {
shouldForwardProp: (prop) => prop !== 'hideToolbar' && prop !== 'bg',
})(({ theme, hideToolbar, bg }) => ({
position: 'relative',
margin: 'auto',
display: 'flex',
justifyContent: 'center',
[theme.breakpoints.up('sm')]: {
borderRadius: hideToolbar ? 12 : '12px 12px 0 0',
...(bg === 'outlined' && {
borderLeftWidth: 1,
borderRightWidth: 1,
}),
/* Make no difference between the demo and the markdown. */
...(bg === 'inline' && {
padding: theme.spacing(0),
}),
},
/* Isolate the demo with an outline. */
...(bg === 'outlined' && {
padding: theme.spacing(3),
backgroundColor: (theme.vars || theme).palette.background.paper,
border: `1px solid ${(theme.vars || theme).palette.divider}`,
borderLeftWidth: 0,
borderRightWidth: 0,
}),
/* Similar to the outlined one but without padding. Ideal for playground demos. */
...(bg === 'playground' && {
backgroundColor: (theme.vars || theme).palette.background.paper,
border: `1px solid ${(theme.vars || theme).palette.divider}`,
overflow: 'auto',
}),
/* Prepare the background to display an inner elevation. */
...(bg === true && {
padding: theme.spacing(3),
backgroundColor: (theme.vars || theme).palette.grey[50],
border: `1px solid ${(theme.vars || theme).palette.divider}`,
...theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primaryDark[700], 0.3),
}),
}),
/* Mostly meant for introduction demos. */
...(bg === 'gradient' && {
padding: theme.spacing(20, 8),
border: `1px solid`,
borderColor: (theme.vars || theme).palette.divider,
overflow: 'auto',
backgroundColor: alpha(theme.palette.primary[50], 0.5),
backgroundClip: 'padding-box',
backgroundImage: `radial-gradient(at 51% 52%, ${alpha(
theme.palette.primary[50],
0.5,
)} 0px, transparent 50%),
radial-gradient(at 80% 0%, #FFFFFF 0px, transparent 20%),
radial-gradient(at 0% 95%, ${alpha(theme.palette.primary[100], 0.3)}, transparent 40%),
radial-gradient(at 0% 20%, ${
(theme.vars || theme).palette.primary[50]
} 0px, transparent 50%),
radial-gradient(at 93% 85%, ${alpha(
theme.palette.primary[100],
0.2,
)} 0px, transparent 50%);`,
...theme.applyDarkStyles({
borderColor: alpha(theme.palette.primaryDark[500], 0.7),
backgroundColor: alpha(theme.palette.primary[900], 0.1),
backgroundImage: `radial-gradient(at 51% 52%, ${alpha(
theme.palette.primaryDark[700],
0.5,
)} 0px, transparent 50%),
radial-gradient(at 80% 0%, ${alpha(theme.palette.primary[900], 0.3)} 0px, transparent 50%),
radial-gradient(at 0% 95%, ${alpha(theme.palette.primary[900], 0.5)} 0px, transparent 50%),
radial-gradient(at 0% 5%, ${alpha(theme.palette.primary[900], 0.5)} 0px, transparent 35%),
radial-gradient(at 93% 85%, ${alpha(theme.palette.primary[900], 0.3)} 0px, transparent 50%);`,
}),
}),
}));
const DemoRootJoy = joyStyled('div', {
shouldForwardProp: (prop) => prop !== 'hideToolbar' && prop !== 'bg',
})(({ theme, hideToolbar, bg }) => ({
position: 'relative',
margin: 'auto',
display: 'flex',
justifyContent: 'center',
[theme.breakpoints.up('sm')]: {
borderRadius: hideToolbar ? 12 : '12px 12px 0 0',
...(bg === 'outlined' && {
borderLeftWidth: 1,
borderRightWidth: 1,
}),
/* Make no difference between the demo and the markdown. */
...(bg === 'inline' && {
padding: theme.spacing(0),
}),
},
/* Isolate the demo with an outline. */
...(bg === 'outlined' && {
padding: theme.spacing(3),
border: `1px solid`,
borderColor: grey[100],
borderLeftWidth: 0,
borderRightWidth: 0,
backgroundColor: '#fff',
...theme.applyDarkStyles({
borderColor: alpha(grey[700], 0.3),
backgroundColor: alpha(blueDark[800], 0.2),
}),
}),
/* Prepare the background to display an inner elevation. */
...(bg === true && {
padding: theme.spacing(3),
backgroundColor: theme.vars.palette.background.level2,
}),
/* Mostly meant for introduction demos. */
...(bg === 'gradient' && {
[theme.breakpoints.up('sm')]: {
borderRadius: 12,
},
borderRadius: 0,
padding: theme.spacing(0),
overflow: 'auto',
backgroundColor: alpha(blue[50], 0.5),
border: `1px solid`,
borderColor: grey[100],
backgroundImage: `radial-gradient(at 51% 52%, ${alpha(blue[50], 0.5)} 0px, transparent 50%),
radial-gradient(at 80% 0%, #FFFFFF 0px, transparent 20%),
radial-gradient(at 0% 95%, ${alpha(blue[100], 0.3)}, transparent 40%),
radial-gradient(at 0% 20%, ${blue[50]} 0px, transparent 50%),
radial-gradient(at 93% 85%, ${alpha(blue[100], 0.2)} 0px, transparent 50%);`,
...theme.applyDarkStyles({
backgroundColor: alpha(blue[900], 0.1),
borderColor: alpha(grey[700], 0.3),
backgroundImage: `radial-gradient(at 51% 52%, ${alpha(
blueDark[700],
0.5,
)} 0px, transparent 50%),
radial-gradient(at 80% 0%, ${alpha(blue[900], 0.3)} 0px, transparent 50%),
radial-gradient(at 0% 95%, ${alpha(blue[900], 0.5)} 0px, transparent 50%),
radial-gradient(at 0% 5%, ${alpha(blue[900], 0.5)} 0px, transparent 35%),
radial-gradient(at 93% 85%, ${alpha(blue[900], 0.3)} 0px, transparent 50%);`,
}),
}),
}));
const DemoCodeViewer = styled(HighlightedCode)(() => ({
'& pre': {
margin: 0,
maxHeight: 'min(68vh, 1000px)',
maxWidth: 'initial',
borderRadius: 0,
},
}));
const AnchorLink = styled('div')({
marginTop: -64, // height of toolbar
position: 'absolute',
});
const InitialFocus = styled(IconButton)(({ theme }) => ({
position: 'absolute',
top: 0,
left: 0,
width: theme.spacing(4),
height: theme.spacing(4),
pointerEvents: 'none',
}));
export default function Demo(props) {
const { demo, demoOptions, disableAd, githubLocation, mode } = props;
if (process.env.NODE_ENV !== 'production') {
if (demoOptions.hideToolbar === false) {
throw new Error(
[
'"hideToolbar": false is already the default.',
`Please remove the property in {{"demo": "${demoOptions.demo}", …}}.`,
].join('\n'),
);
}
if (demoOptions.hideToolbar === true && demoOptions.defaultCodeOpen === true) {
throw new Error(
[
'"hideToolbar": true, "defaultCodeOpen": true combination is invalid.',
`Please remove one of the properties in {{"demo": "${demoOptions.demo}", …}}.`,
].join('\n'),
);
}
if (demoOptions.hideToolbar === true && demoOptions.disableAd === true) {
throw new Error(
[
'"hideToolbar": true, "disableAd": true combination is invalid.',
`Please remove one of the properties in {{"demo": "${demoOptions.demo}", …}}.`,
].join('\n'),
);
}
}
if (
(demoOptions.demo.endsWith('.ts') || demoOptions.demo.endsWith('.tsx')) &&
demoOptions.hideToolbar !== true
) {
throw new Error(
[
`The following demos use TS directly: ${demoOptions.demo}.`,
'',
'Please run "yarn docs:typescript:formatted" to generate a JS version and reference it:',
`{{"demo": "${demoOptions.demo.replace(/\.(.*)$/, '.js')}", …}}.`,
'',
"Otherwise, if it's not a code demo hide the toolbar:",
`{{"demo": "${demoOptions.demo}", "hideToolbar": true, …}}.`,
].join('\n'),
);
}
const t = useTranslate();
const codeVariant = useCodeVariant();
const styleSolution = useCodeStyling();
const demoData = useDemoData(codeVariant, demo, githubLocation, styleSolution);
const hasNonSystemDemos = demo.rawTailwind || demo.rawTailwindTS || demo.rawCSS || demo.rawCSSTs;
const demoName = getDemoName(demoData.githubLocation);
const demoSandboxedStyle = React.useMemo(
() => ({
maxWidth: demoOptions.maxWidth,
height: demoOptions.height,
}),
[demoOptions.height, demoOptions.maxWidth],
);
if (demoOptions.bg == null) {
demoOptions.bg = 'outlined';
}
if (demoOptions.iframe) {
demoOptions.bg = true;
}
const [codeOpen, setCodeOpen] = React.useState(demoOptions.defaultCodeOpen || false);
const shownOnce = React.useRef(false);
if (codeOpen) {
shownOnce.current = true;
}
React.useEffect(() => {
const navigatedDemoName = getDemoName(window.location.hash);
if (navigatedDemoName && demoName === navigatedDemoName) {
setCodeOpen(true);
}
}, [demoName]);
const showPreview =
!demoOptions.hideToolbar &&
demoOptions.defaultCodeOpen !== false &&
Boolean(demoData.jsxPreview);
const [demoKey, setDemoKey] = React.useReducer((key) => key + 1, 0);
const demoId = `demo-${useId()}`;
const demoSourceId = `demoSource-${useId()}`;
const openDemoSource = codeOpen || showPreview;
const initialFocusRef = React.useRef(null);
const [showAd, setShowAd] = React.useState(false);
const adVisibility = showAd && !disableAd && !demoOptions.disableAd;
const DemoRoot = demoData.productId === 'joy-ui' ? DemoRootJoy : DemoRootMaterial;
const Wrapper = demoData.productId === 'joy-ui' ? BrandingProvider : React.Fragment;
const isPreview = !codeOpen && showPreview;
const initialEditorCode = isPreview
? demoData.jsxPreview
: // Prettier remove all the leading lines except for the last one, remove it as we don't
// need it in the live edit view.
demoData.raw.replace(/\n$/, '');
const [editorCode, setEditorCode] = React.useState({
value: initialEditorCode,
isPreview,
initialEditorCode,
});
const resetDemo = React.useMemo(
() => () => {
setEditorCode({
value: initialEditorCode,
isPreview,
initialEditorCode,
});
setDemoKey();
},
[setEditorCode, setDemoKey, initialEditorCode, isPreview],
);
React.useEffect(() => {
setEditorCode({
value: initialEditorCode,
isPreview,
initialEditorCode,
});
}, [initialEditorCode, isPreview]);
const [debouncedError, setDebouncedError] = React.useState(null);
const [liveDemoActive, setLiveDemoActive] = React.useState(false);
const demoElement = useDemoElement({
demoData,
editorCode,
setDebouncedError,
liveDemoActive,
});
return (
<Root>
<AnchorLink id={demoName} />
<DemoRoot hideToolbar={demoOptions.hideToolbar} bg={demoOptions.bg} id={demoId}>
<Wrapper {...(demoData.productId === 'joy-ui' && { mode })}>
<InitialFocus
aria-label={t('initialFocusLabel')}
action={initialFocusRef}
tabIndex={-1}
/>
</Wrapper>
<DemoSandbox
key={demoKey}
style={demoSandboxedStyle}
iframe={demoOptions.iframe}
productId={demoData.productId}
name={demoName}
onResetDemoClick={resetDemo}
>
{demoElement}
</DemoSandbox>
</DemoRoot>
{/* TODO: Wrapper shouldn't be needed, it should already be at the top of the docs page */}
{demoOptions.hideToolbar ? null : (
<Wrapper {...(demoData.productId === 'joy-ui' ? { mode } : {})}>
{Object.keys(stylingSolutionMapping).map((key) => (
<React.Fragment key={key}>
<AnchorLink id={`${stylingSolutionMapping[key]}-${demoName}.js`} />
<AnchorLink id={`${stylingSolutionMapping[key]}-${demoName}.tsx`} />
</React.Fragment>
))}
<AnchorLink id={`${demoName}.js`} />
<AnchorLink id={`${demoName}.tsx`} />
<DemoToolbarRoot demoOptions={demoOptions} openDemoSource={openDemoSource}>
<NoSsr fallback={<DemoToolbarFallback />}>
<React.Suspense fallback={<DemoToolbarFallback />}>
<DemoToolbar
codeOpen={codeOpen}
codeVariant={codeVariant}
hasNonSystemDemos={hasNonSystemDemos}
demo={demo}
demoData={demoData}
demoId={demoId}
demoName={demoName}
demoOptions={demoOptions}
demoSourceId={demoSourceId}
initialFocusRef={initialFocusRef}
onCodeOpenChange={() => {
setCodeOpen((open) => !open);
setShowAd(true);
}}
onResetDemoClick={resetDemo}
openDemoSource={openDemoSource}
showPreview={showPreview}
/>
</React.Suspense>
</NoSsr>
</DemoToolbarRoot>
<Collapse in={openDemoSource} unmountOnExit timeout={150}>
{/* A limitation from https://github.com/nihgwu/react-runner,
we can't inject the `window` of the iframe so we need a disableLiveEdit option. */}
{demoOptions.disableLiveEdit ? (
<DemoCodeViewer
code={editorCode.value}
id={demoSourceId}
language={demoData.sourceLanguage}
copyButtonProps={{
'data-ga-event-category': codeOpen ? 'demo-expand' : 'demo',
'data-ga-event-label': demo.gaLabel,
'data-ga-event-action': 'copy-click',
}}
/>
) : (
<DemoEditor
// Mount a new text editor when the preview mode change to reset the undo/redo history.
key={editorCode.isPreview}
value={editorCode.value}
onChange={(value) => {
setEditorCode({
...editorCode,
value,
});
}}
onFocus={() => {
setLiveDemoActive(true);
}}
id={demoSourceId}
language={demoData.sourceLanguage}
copyButtonProps={{
'data-ga-event-category': codeOpen ? 'demo-expand' : 'demo',
'data-ga-event-label': demo.gaLabel,
'data-ga-event-action': 'copy-click',
}}
>
<DemoEditorError>{debouncedError}</DemoEditorError>
</DemoEditor>
)}
</Collapse>
{adVisibility ? <AdCarbonInline /> : null}
</Wrapper>
)}
</Root>
);
}
Demo.propTypes = {
demo: PropTypes.object.isRequired,
/**
* The options provided with: {{"demo": "Name.js", …demoOptions}}
*/
demoOptions: PropTypes.object.isRequired,
disableAd: PropTypes.bool.isRequired,
githubLocation: PropTypes.string.isRequired,
mode: PropTypes.string, // temporary, just to make Joy docs work.
};
| 5,276 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/DemoEditor.tsx | import * as React from 'react';
import SimpleCodeEditor from 'react-simple-code-editor';
import Box from '@mui/material/Box';
import { NoSsr } from '@mui/base/NoSsr';
import { styled, useTheme } from '@mui/material/styles';
import prism from '@mui/markdown/prism';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
import CodeCopyButton from 'docs/src/modules/components/CodeCopyButton';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import { useCodeCopy } from 'docs/src/modules/utils/CodeCopy';
import { blueDark } from 'docs/src/modules/brandingTheme';
const StyledMarkdownElement = styled(MarkdownElement)(({ theme }) => [
{
'& .scrollContainer': {
maxHeight: 'min(68vh, 1000px)',
overflow: 'auto',
marginTop: -1,
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.
border: `1px solid ${(theme.vars || theme).palette.divider}`,
colorScheme: 'dark',
'&:hover': {
boxShadow: `0 0 0 3px ${(theme.vars || theme).palette.primary.light}`,
},
'&:focus-within': {
boxShadow: `0 0 0 2px ${(theme.vars || theme).palette.primary.main}`,
},
[theme.breakpoints.up('sm')]: {
borderRadius: '0 0 12px 12px',
},
},
'& pre': {
// The scroll container needs to be the parent of the editor, overriding:
// https://github.com/mui/material-ui/blob/269c1d0c7572fcb6ae3b270a2622d16c7e40c848/docs/src/modules/components/MarkdownElement.js#L27-L26
maxWidth: 'initial',
maxHeight: 'initial',
},
},
theme.applyDarkStyles({
'& .scrollContainer': {
borderColor: (theme.vars || theme).palette.divider,
'&:hover': {
boxShadow: `0 0 0 3px ${(theme.vars || theme).palette.primaryDark[300]}`,
},
'&:focus-within': {
boxShadow: `0 0 0 2px ${(theme.vars || theme).palette.primaryDark[400]}`,
},
},
}),
]) as any;
const StyledSimpleCodeEditor = styled(SimpleCodeEditor)(({ theme }) => ({
...theme.typography.body2,
fontSize: theme.typography.pxToRem(13),
fontFamily: theme.typography.fontFamilyCode,
fontWeight: 400,
WebkitFontSmoothing: 'subpixel-antialiased',
color: '#f8f8f2',
direction: 'ltr /*! @noflip */' as any,
float: 'left',
minWidth: '100%',
'& textarea': {
outline: 0,
},
'& > textarea, & > pre': {
// Override inline-style
whiteSpace: 'pre !important',
},
}));
interface DemoEditorProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
copyButtonProps: {};
id: string;
language: string;
onChange: () => {};
value: string;
}
export default function DemoEditor(props: DemoEditorProps) {
const { language, value, onChange, copyButtonProps, children, id, ...other } = props;
const t = useTranslate();
const contextTheme = useTheme();
const wrapperRef = React.useRef<HTMLElement>(null);
const enterRef = React.useRef<HTMLElement>(null);
const handlers = useCodeCopy();
React.useEffect(() => {
wrapperRef.current!.querySelector('textarea')!.tabIndex = -1;
}, []);
return (
<StyledMarkdownElement
ref={wrapperRef}
onKeyDown={(event: React.KeyboardEvent) => {
if (event.key === 'Tab') {
return;
}
if (event.key === 'Escape') {
enterRef.current!.focus();
return;
}
if (event.key === 'Enter') {
const textarea = wrapperRef.current!.querySelector('textarea');
if (textarea !== document.activeElement) {
event.preventDefault();
event.stopPropagation();
textarea!.focus();
}
}
}}
{...other}
>
<div className="MuiCode-root" {...handlers}>
<div className="scrollContainer">
<StyledSimpleCodeEditor
padding={contextTheme.spacing(2)}
highlight={(code: any) =>
`<code class="language-${language}">${prism(code, language)}</code>`
}
id={id}
value={value}
onValueChange={onChange}
/>
</div>
<Box
ref={enterRef}
aria-live="polite"
tabIndex={0}
sx={(theme) => ({
position: 'absolute',
top: theme.spacing(1),
padding: theme.spacing(0.2, 1, 0.5, 1),
outline: 0,
left: '50%',
border: '1px solid',
borderColor: blueDark[600],
backgroundColor: blueDark[700],
color: '#FFF',
transform: 'translateX(-50%)',
borderRadius: '6px',
fontSize: theme.typography.pxToRem(13),
transition: 'all 0.3s',
boxShadow: '0 2px 4px rgba(0,0,0,0.5)',
'&:not(:focus)': {
top: 0,
opacity: 0,
pointerEvents: 'none',
},
'> kbd': {
padding: theme.spacing(0.2, 0.4),
backgroundColor: blueDark[500],
fontSize: theme.typography.pxToRem(11),
borderRadius: '6px',
border: '1px solid',
borderColor: blueDark[400],
},
})}
dangerouslySetInnerHTML={{
__html: t('editorHint'),
}}
/>
<NoSsr>
<CodeCopyButton {...copyButtonProps} code={value} />
</NoSsr>
{children}
</div>
</StyledMarkdownElement>
);
}
| 5,277 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/DemoEditorError.tsx | import * as React from 'react';
import Alert, { AlertProps } from '@mui/material/Alert';
export default function DemoEditorError(props: AlertProps) {
if (!props.children) {
return null;
}
return (
<Alert
aria-live="polite"
variant="filled"
severity="error"
sx={{
position: 'absolute',
top: 0,
left: '50%',
transform: 'translateX(-50%) translateY(-50%)',
py: '2px',
px: '6px',
'& .MuiAlert-icon': {
fontSize: 14,
mr: 0.5,
mt: 0.25,
py: 0,
},
'& .MuiAlert-message': {
fontSize: 12,
py: 0,
},
}}
{...props}
/>
);
}
| 5,278 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/DemoErrorBoundary.js | import * as React from 'react';
import PropTypes from 'prop-types';
import Typography from '@mui/material/Typography';
import Link from '@mui/material/Link';
import Button from '@mui/material/Button';
/**
* Based on https://github.com/sindresorhus/new-github-issue-url/blob/061fa0ddb7d51f3b96d3a0f6a6bebb196f105a7b/index.js
* with node 8 + IE11 support i.e. not using URL (URLSearchParams.set replaced with Map.set)
*/
function newGitHubIssueUrl(options) {
const url = `${process.env.SOURCE_CODE_REPO}/issues/new`;
const query = Object.keys(options)
.map((type) => {
const value = options[type];
return `${type}=${encodeURIComponent(String(value))}`;
})
.join('&');
return `${url}?${query}`;
}
export default class DemoErrorBoundary extends React.Component {
state = {
error: null,
};
static getDerivedStateFromError(error) {
return { error };
}
render() {
const { children, name, onResetDemoClick, t } = this.props;
const { error } = this.state;
if (error) {
const title = `[docs] Demo ${name} crashes`;
const searchQuery = encodeURIComponent(`is:issue ${title}`);
const issueLink = newGitHubIssueUrl({
title,
body: `
<!-- Please make sure you have fulfilled the following items before submitting -->
<!-- Checked checkbox should look like this: [x] -->
- [ ] I have [searched for similar issues](${
process.env.SOURCE_CODE_REPO
}/issues?q=${searchQuery}) in this repository and believe that this is not a duplicate.
## Steps to reproduce
1. Visit ${window.location.href}
2. ??
3. demo *${name}* crashes
## Your environment
| Tech | Version |
|--------------|---------|
| Version | v${process.env.LIB_VERSION} |
| Netlify deploy | ${process.env.NETLIFY_DEPLOY_URL} |
| Browser | ${
typeof window !== 'undefined' && window.navigator
? window.navigator.userAgent
: '*Unknown*'
} |
`,
});
/* eslint-disable material-ui/no-hardcoded-labels */
return (
<div>
<Typography color="error" component="p" variant="h5" gutterBottom>
This demo had a runtime error!
</Typography>
<Typography>
{'We would appreciate it if you '}
<Link href={issueLink} rel="noreferrer" target="_blank">
report this error
</Link>
{` directly in our issue tracker with the steps you took to trigger it.
The "report this error" link prefills the issue description with valuable information.`}
</Typography>
<pre style={{ whiteSpace: 'pre-wrap' }}>{error.toString()}</pre>
<Button onClick={onResetDemoClick} variant="text">
{t('resetDemo')}
</Button>
</div>
);
/* eslint-enable material-ui/no-hardcoded-labels */
}
return children;
}
}
DemoErrorBoundary.propTypes = {
children: PropTypes.node,
name: PropTypes.string.isRequired,
onResetDemoClick: PropTypes.func.isRequired,
/**
* translate function from redux store
*/
t: PropTypes.func.isRequired,
};
| 5,279 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/DemoSandbox.js | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { create } from 'jss';
import { prefixer } from 'stylis';
import rtlPlugin from 'stylis-plugin-rtl';
import createCache from '@emotion/cache';
import { CacheProvider } from '@emotion/react';
import { StyleSheetManager } from 'styled-components';
import { jssPreset, StylesProvider } from '@mui/styles';
import { CssVarsProvider, extendTheme } from '@mui/joy/styles';
import { useTheme, styled, createTheme, ThemeProvider } from '@mui/material/styles';
import rtl from 'jss-rtl';
import DemoErrorBoundary from 'docs/src/modules/components/DemoErrorBoundary';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import { getDesignTokens } from 'docs/src/modules/brandingTheme';
import { highDensity } from 'docs/src/modules/components/ThemeContext';
const iframeDefaultJoyTheme = extendTheme({
cssVarPrefix: 'demo-iframe',
});
function FramedDemo(props) {
const { children, document, productId } = props;
const theme = useTheme();
React.useEffect(() => {
document.body.dir = theme.direction;
}, [document, theme.direction]);
const { jss, sheetsManager } = React.useMemo(() => {
return {
jss: create({
plugins: [...jssPreset().plugins, rtl()],
insertionPoint: document.head,
}),
sheetsManager: new Map(),
};
}, [document]);
const cache = React.useMemo(
() =>
createCache({
key: `iframe-demo-${theme.direction}`,
prepend: true,
container: document.head,
stylisPlugins: theme.direction === 'rtl' ? [prefixer, rtlPlugin] : [prefixer],
}),
[document, theme.direction],
);
const getWindow = React.useCallback(() => document.defaultView, [document]);
const Wrapper = productId === 'joy-ui' ? CssVarsProvider : React.Fragment;
const wrapperProps =
productId === 'joy-ui'
? {
documentNode: document,
colorSchemeNode: document.documentElement,
theme: iframeDefaultJoyTheme,
}
: {};
return (
<StylesProvider jss={jss} sheetsManager={sheetsManager}>
<StyleSheetManager
target={document.head}
stylisPlugins={theme.direction === 'rtl' ? [rtlPlugin] : []}
>
<CacheProvider value={cache}>
<Wrapper {...wrapperProps}>
{React.cloneElement(children, {
window: getWindow,
})}
</Wrapper>
</CacheProvider>
</StyleSheetManager>
</StylesProvider>
);
}
FramedDemo.propTypes = {
children: PropTypes.node,
document: PropTypes.object.isRequired,
productId: PropTypes.string,
};
const Iframe = styled('iframe')(({ theme }) => ({
backgroundColor: (theme.vars || theme).palette.background.default,
flexGrow: 1,
height: 400,
border: 0,
boxShadow: (theme.vars || theme)?.shadows?.[1],
}));
function DemoIframe(props) {
const { children, name, productId, ...other } = props;
/**
* @type {import('react').Ref<HTMLIFrameElement>}
*/
const frameRef = React.useRef(null);
// If we portal content into the iframe before the load event then that content
// is dropped in firefox.
const [iframeLoaded, onLoad] = React.useReducer(() => true, false);
React.useEffect(() => {
const document = frameRef.current.contentDocument;
// When we hydrate the iframe then the load event is already dispatched
// once the iframe markup is parsed (maybe later but the important part is
// that it happens before React can attach event listeners).
// We need to check the readyState of the document once the iframe is mounted
// and "replay" the missed load event.
// See https://github.com/facebook/react/pull/13862 for ongoing effort in React
// (though not with iframes in mind).
if (document != null && document.readyState === 'complete' && !iframeLoaded) {
onLoad();
}
}, [iframeLoaded]);
const document = frameRef.current?.contentDocument;
return (
<React.Fragment>
<Iframe onLoad={onLoad} ref={frameRef} title={`${name} demo`} {...other} />
{iframeLoaded !== false
? ReactDOM.createPortal(
<FramedDemo document={document} productId={productId}>
{children}
</FramedDemo>,
document.body,
)
: null}
</React.Fragment>
);
}
DemoIframe.propTypes = {
children: PropTypes.node.isRequired,
name: PropTypes.string.isRequired,
productId: PropTypes.string,
};
// Use the default Material UI theme for the demos
function getTheme(outerTheme) {
const brandingDesignTokens = getDesignTokens(outerTheme.palette.mode);
const isCustomized =
outerTheme.palette.primary?.main &&
outerTheme.palette.primary.main !== brandingDesignTokens.palette.primary.main;
const resultTheme = createTheme(
{
palette: {
mode: outerTheme.palette.mode || 'light',
...(isCustomized && {
// Apply color from the color playground
primary: { main: outerTheme.palette.primary.main },
secondary: { main: outerTheme.palette.secondary.main },
}),
},
},
// To make DensityTool playground works
// check from MuiFormControl because brandingTheme does not customize this component
outerTheme.components?.MuiFormControl?.defaultProps?.margin === 'dense' ? highDensity : {},
);
if (outerTheme.direction) {
resultTheme.direction = outerTheme.direction;
}
if (outerTheme.spacing) {
resultTheme.spacing = outerTheme.spacing;
}
return resultTheme;
}
// TODO: Let demos decide whether they need JSS
const jss = create({
plugins: [...jssPreset().plugins, rtl()],
insertionPoint:
typeof window !== 'undefined' ? document.querySelector('#insertion-point-jss') : null,
});
/**
* Isolates the demo component as best as possible. Additional props are spread
* to an `iframe` if `iframe={true}`.
*/
function DemoSandbox(props) {
const {
children: childrenProp,
iframe = false,
name,
onResetDemoClick,
productId,
...other
} = props;
const Sandbox = iframe ? DemoIframe : React.Fragment;
const sandboxProps = iframe ? { name, productId, ...other } : {};
const t = useTranslate();
// `childrenProp` needs to be a child of `Sandbox` since the iframe implementation rely on `cloneElement`.
const children = <Sandbox {...sandboxProps}>{childrenProp}</Sandbox>;
return (
<DemoErrorBoundary name={name} onResetDemoClick={onResetDemoClick} t={t}>
{productId === 'joy-ui' ? (
children
) : (
<StylesProvider jss={jss}>
<ThemeProvider theme={(outerTheme) => getTheme(outerTheme)}>{children}</ThemeProvider>
</StylesProvider>
)}
</DemoErrorBoundary>
);
}
DemoSandbox.propTypes = {
children: PropTypes.node.isRequired,
iframe: PropTypes.bool,
name: PropTypes.string.isRequired,
onResetDemoClick: PropTypes.func.isRequired,
productId: PropTypes.string,
};
export default React.memo(DemoSandbox);
| 5,280 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/DemoToolbar.js | import * as React from 'react';
import PropTypes from 'prop-types';
import copy from 'clipboard-copy';
import { useTheme, styled, alpha } from '@mui/material/styles';
import IconButton from '@mui/material/IconButton';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import CheckIcon from '@mui/icons-material/Check';
import Fade from '@mui/material/Fade';
import MDButton from '@mui/material/Button';
import Box from '@mui/material/Box';
import MDToggleButton, { toggleButtonClasses } from '@mui/material/ToggleButton';
import MDToggleButtonGroup, { toggleButtonGroupClasses } from '@mui/material/ToggleButtonGroup';
import SvgIcon from '@mui/material/SvgIcon';
import Snackbar from '@mui/material/Snackbar';
import Menu from '@mui/material/Menu';
import MDMenuItem, { menuItemClasses } from '@mui/material/MenuItem';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import Tooltip from '@mui/material/Tooltip';
import Divider from '@mui/material/Divider';
import RefreshRoundedIcon from '@mui/icons-material/RefreshRounded';
import ResetFocusIcon from '@mui/icons-material/CenterFocusWeak';
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
import { useRouter } from 'next/router';
import { CODE_VARIANTS, CODE_STYLING } from 'docs/src/modules/constants';
import { useSetCodeVariant } from 'docs/src/modules/utils/codeVariant';
import { useSetCodeStyling, useCodeStyling } from 'docs/src/modules/utils/codeStylingSolution';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import stylingSolutionMapping from 'docs/src/modules/utils/stylingSolutionMapping';
import codeSandbox from '../sandbox/CodeSandbox';
import stackBlitz from '../sandbox/StackBlitz';
const Root = styled('div')(({ theme }) => [
{
[theme.breakpoints.up('sm')]: {
justifyContent: 'space-between',
alignItems: 'center',
display: 'flex',
},
'& .MuiSvgIcon-root': {
fontSize: 16,
color: (theme.vars || theme).palette.grey[800],
},
},
theme.applyDarkStyles({
'& .MuiSvgIcon-root': {
color: (theme.vars || theme).palette.grey[400],
},
}),
]);
function DemoTooltip(props) {
return (
<Tooltip
componentsProps={{
popper: {
sx: {
zIndex: (theme) => theme.zIndex.appBar - 1,
},
},
}}
{...props}
/>
);
}
const alwaysTrue = () => true;
const ToggleButtonGroup = styled(MDToggleButtonGroup)(({ theme }) => [
theme.unstable_sx({
[`& .${toggleButtonGroupClasses.grouped}`]: {
'&:not(:first-of-type)': {
marginLeft: 0.8,
borderLeft: '1px solid',
borderLeftColor: 'divider',
borderTopLeftRadius: 999,
borderBottomLeftRadius: 999,
},
'&:not(:last-of-type)': {
borderTopRightRadius: 999,
borderBottomRightRadius: 999,
},
},
}),
]);
const Button = styled(MDButton)(({ theme }) => ({
height: 24,
padding: '5px 8px 6px 8px', // the one-off 5px is for visually centering the text on the button's container
flexShrink: 0,
borderRadius: 999,
border: '1px solid',
borderColor: alpha(theme.palette.primary[100], 0.6),
fontSize: theme.typography.pxToRem(13),
fontWeight: theme.typography.fontWeightMedium,
color: theme.palette.primary.main,
'& .MuiSvgIcon-root': {
color: theme.palette.primary.main,
},
'&:hover': {
backgroundColor: theme.palette.primary[50],
borderColor: theme.palette.primary[200],
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent',
},
},
...theme.applyDarkStyles({
color: theme.palette.primary[300],
borderColor: alpha(theme.palette.primary[300], 0.2),
'& .MuiSvgIcon-root': {
color: theme.palette.primary[300],
},
'&:hover': {
borderColor: alpha(theme.palette.primary[300], 0.5),
backgroundColor: alpha(theme.palette.primary[500], 0.2),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent',
},
},
}),
}));
const MenuItem = styled(MDMenuItem)(({ theme }) => ({
padding: theme.spacing(1),
[`& .${menuItemClasses.selected}`]: {
backgroundColor: theme.palette.primary[50],
},
}));
const ToggleButton = styled(MDToggleButton)(({ theme }) => [
theme.unstable_sx({
padding: theme.spacing(0, 1, 0.1, 1),
fontSize: theme.typography.pxToRem(13),
borderColor: 'grey.200',
borderRadius: '999px',
'&.Mui-disabled': {
opacity: 0.5,
},
[`&.${toggleButtonClasses.selected}:hover`]: {
backgroundColor: theme.vars
? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))`
: alpha(
theme.palette.primary.main,
theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity,
),
'@media (hover: none)': {
backgroundColor: theme.vars
? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})`
: alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),
},
},
}),
theme.applyDarkStyles({
borderColor: theme.palette.primaryDark[700],
}),
]);
/**
* @param {React.Ref<HTMLElement>[]} controlRefs
* @param {object} [options]
* @param {(index: number) => boolean} [options.isFocusableControl] In case certain controls become unfocusable
* @param {number} [options.defaultActiveIndex]
*/
function useToolbar(controlRefs, options = {}) {
const { defaultActiveIndex = 0, isFocusableControl = alwaysTrue } = options;
const [activeControlIndex, setActiveControlIndex] = React.useState(defaultActiveIndex);
// TODO: do we need to do this during layout practically? It's technically
// a bit too late since we allow user interaction between layout and passive effects
React.useEffect(() => {
setActiveControlIndex((currentActiveControlIndex) => {
if (!isFocusableControl(currentActiveControlIndex)) {
return defaultActiveIndex;
}
return currentActiveControlIndex;
});
}, [defaultActiveIndex, isFocusableControl]);
// controlRefs.findIndex(controlRef => controlRef.current = element)
function findControlIndex(element) {
let controlIndex = -1;
controlRefs.forEach((controlRef, index) => {
if (controlRef.current === element) {
controlIndex = index;
}
});
return controlIndex;
}
function handleControlFocus(event) {
const nextActiveControlIndex = findControlIndex(event.target);
if (nextActiveControlIndex !== -1) {
setActiveControlIndex(nextActiveControlIndex);
} else {
// make sure DCE works
// eslint-disable-next-line no-lonely-if
if (process.env.NODE_ENV !== 'production') {
console.error(
'MUI: The toolbar contains a focusable element that is not controlled by the toolbar. ' +
'Make sure you have attached `getControlProps(index)` to every focusable element within this toolbar.',
);
}
}
}
let handleToolbarFocus;
if (process.env.NODE_ENV !== 'production') {
handleToolbarFocus = (event) => {
if (findControlIndex(event.target) === -1) {
console.error(
'MUI: The toolbar contains a focusable element that is not controlled by the toolbar. ' +
'Make sure you have attached `getControlProps(index)` to every focusable element within this toolbar.',
);
}
};
}
const { direction } = useTheme();
function handleToolbarKeyDown(event) {
// We handle toolbars where controls can be hidden temporarily.
// When a control is hidden we can't move focus to it and have to exclude
// it from the order.
let currentFocusableControlIndex = -1;
const focusableControls = [];
controlRefs.forEach((controlRef, index) => {
const { current: control } = controlRef;
if (index === activeControlIndex) {
currentFocusableControlIndex = focusableControls.length;
}
if (control !== null && isFocusableControl(index)) {
focusableControls.push(control);
}
});
const prevControlKey = direction === 'ltr' ? 'ArrowLeft' : 'ArrowRight';
const nextControlKey = direction === 'ltr' ? 'ArrowRight' : 'ArrowLeft';
let nextFocusableIndex = -1;
switch (event.key) {
case prevControlKey:
nextFocusableIndex =
(currentFocusableControlIndex - 1 + focusableControls.length) % focusableControls.length;
break;
case nextControlKey:
nextFocusableIndex = (currentFocusableControlIndex + 1) % focusableControls.length;
break;
case 'Home':
nextFocusableIndex = 0;
break;
case 'End':
nextFocusableIndex = focusableControls.length - 1;
break;
default:
break;
}
if (nextFocusableIndex !== -1) {
event.preventDefault();
focusableControls[nextFocusableIndex].focus();
}
}
function getControlProps(index) {
return {
onFocus: handleControlFocus,
ref: controlRefs[index],
tabIndex: index === activeControlIndex ? 0 : -1,
};
}
return {
getControlProps,
toolbarProps: {
// TODO: good opportunity to warn on missing `aria-label`
onFocus: handleToolbarFocus,
onKeyDown: handleToolbarKeyDown,
role: 'toolbar',
},
};
}
export default function DemoToolbar(props) {
const {
codeOpen,
codeVariant,
hasNonSystemDemos,
demo,
demoData,
demoId,
demoName,
demoOptions,
demoSourceId,
initialFocusRef,
onCodeOpenChange,
onResetDemoClick,
openDemoSource,
showPreview,
} = props;
const setCodeVariant = useSetCodeVariant();
const styleSolution = useCodeStyling();
const setCodeStyling = useSetCodeStyling();
const t = useTranslate();
const hasTSVariant = demo.rawTS;
const renderedCodeVariant = () => {
if (codeVariant === CODE_VARIANTS.TS && hasTSVariant) {
return CODE_VARIANTS.TS;
}
return CODE_VARIANTS.JS;
};
const handleCodeLanguageClick = (event, clickedCodeVariant) => {
if (clickedCodeVariant !== null && codeVariant !== clickedCodeVariant) {
setCodeVariant(clickedCodeVariant);
}
};
const [anchorEl, setAnchorEl] = React.useState(null);
const handleMoreClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleMoreClose = () => {
setAnchorEl(null);
};
const [snackbarOpen, setSnackbarOpen] = React.useState(false);
const [snackbarMessage, setSnackbarMessage] = React.useState(undefined);
const handleSnackbarClose = () => {
setSnackbarOpen(false);
};
const handleCopyClick = async () => {
try {
await copy(demoData.raw);
setSnackbarMessage(t('copiedSource'));
setSnackbarOpen(true);
} finally {
handleMoreClose();
}
};
const createHandleCodeSourceLink = (anchor, codeVariantParam, stylingSolution) => async () => {
try {
await copy(
`${window.location.href.split('#')[0]}#${
stylingSolution ? `${stylingSolutionMapping[stylingSolution]}-` : ''
}${anchor}${codeVariantParam === CODE_VARIANTS.TS ? '.tsx' : '.js'}`,
);
setSnackbarMessage(t('copiedSourceLink'));
setSnackbarOpen(true);
} finally {
handleMoreClose();
}
};
const handleResetFocusClick = () => {
initialFocusRef.current.focusVisible();
};
let showCodeLabel;
if (codeOpen) {
showCodeLabel = showPreview ? t('hideFullSource') : t('hideSource');
} else {
showCodeLabel = showPreview ? t('showFullSource') : t('showSource');
}
const controlRefs = [
React.useRef(null),
React.useRef(null),
React.useRef(null),
React.useRef(null),
React.useRef(null),
React.useRef(null),
React.useRef(null),
React.useRef(null),
React.useRef(null),
React.useRef(null),
];
// if the code is not open we hide the language controls
const isFocusableControl = React.useCallback(
(index) => (codeOpen ? true : index !== 1 && index !== 2),
[codeOpen],
);
const { getControlProps, toolbarProps } = useToolbar(controlRefs, {
defaultActiveIndex: 0,
isFocusableControl,
});
const devMenuItems = [];
if (process.env.DEPLOY_ENV === 'staging' || process.env.DEPLOY_ENV === 'pull-request') {
/* eslint-disable material-ui/no-hardcoded-labels -- staging only */
// eslint-disable-next-line react-hooks/rules-of-hooks -- process.env never changes
const router = useRouter();
if (process.env.PULL_REQUEST_ID) {
devMenuItems.push(
<MenuItem
key="link-deploy-preview"
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="link-deploy-preview"
component="a"
href={`https://deploy-preview-${process.env.PULL_REQUEST_ID}--${process.env.NETLIFY_SITE_NAME}.netlify.app${router.route}/#${demoName}`}
target="_blank"
rel="noopener nofollow"
onClick={handleMoreClose}
>
demo on PR #{process.env.PULL_REQUEST_ID}
</MenuItem>,
);
}
devMenuItems.push(
<MenuItem
key="link-next"
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="link-next"
component="a"
href={`https://next--${process.env.NETLIFY_SITE_NAME}.netlify.app${router.route}/#${demoName}`}
target="_blank"
rel="noopener nofollow"
onClick={handleMoreClose}
>
demo on <code>next</code>
</MenuItem>,
<MenuItem
key="permalink"
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="permalink"
component="a"
href={`${process.env.NETLIFY_DEPLOY_URL}${router.route}#${demoName}`}
target="_blank"
rel="noopener nofollow"
onClick={handleMoreClose}
>
demo permalink
</MenuItem>,
<MenuItem
key="link-master"
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="link-master"
component="a"
href={`https://master--${process.env.NETLIFY_SITE_NAME}.netlify.app${router.route}/#${demoName}`}
target="_blank"
rel="noopener nofollow"
onClick={handleMoreClose}
>
demo on <code>master</code>
</MenuItem>,
);
/* eslint-enable material-ui/no-hardcoded-labels */
}
const [stylingAnchorEl, setStylingAnchorEl] = React.useState(null);
const stylingMenuOpen = Boolean(stylingAnchorEl);
const handleStylingButtonClose = () => {
setStylingAnchorEl(null);
};
const handleStylingSolutionChange = (eventStylingSolution) => {
if (eventStylingSolution !== null && eventStylingSolution !== styleSolution) {
setCodeStyling(eventStylingSolution);
}
handleStylingButtonClose();
};
const codeStylingLabels = {
[CODE_STYLING.SYSTEM]: t('demoStylingSelectSystem'),
[CODE_STYLING.TAILWIND]: t('demoStylingSelectTailwind'),
[CODE_STYLING.CSS]: t('demoStylingSelectCSS'),
};
const handleStylingButtonClick = (event) => {
setStylingAnchorEl(event.currentTarget);
};
return (
<React.Fragment>
<Root aria-label={t('demoToolbarLabel')} {...toolbarProps}>
{hasNonSystemDemos && (
<Button
id="styling-solution"
aria-controls={stylingMenuOpen ? 'demo-styling-menu' : undefined}
aria-haspopup="true"
aria-expanded={stylingMenuOpen ? 'true' : undefined}
onClick={handleStylingButtonClick}
{...getControlProps(0)}
sx={{ pr: 0.5 }}
>
{codeStylingLabels[styleSolution]}
<ExpandMoreIcon />
</Button>
)}
<Fade in={codeOpen}>
<Box sx={{ display: 'flex', height: 40 }}>
{hasNonSystemDemos && (
<Divider orientation="vertical" variant="middle" sx={{ mx: 1, height: '24px' }} />
)}
<ToggleButtonGroup
sx={{ margin: '8px 0' }}
exclusive
value={renderedCodeVariant()}
onChange={handleCodeLanguageClick}
>
<ToggleButton
value={CODE_VARIANTS.JS}
aria-label={t('showJSSource')}
data-ga-event-category="demo"
data-ga-event-action="source-js"
data-ga-event-label={demo.gaLabel}
{...getControlProps(1)}
// eslint-disable-next-line material-ui/no-hardcoded-labels
>
JS
</ToggleButton>
<ToggleButton
value={CODE_VARIANTS.TS}
disabled={!hasTSVariant}
aria-label={t('showTSSource')}
data-ga-event-category="demo"
data-ga-event-action="source-ts"
data-ga-event-label={demo.gaLabel}
{...getControlProps(2)}
// eslint-disable-next-line material-ui/no-hardcoded-labels
>
TS
</ToggleButton>
</ToggleButtonGroup>
</Box>
</Fade>
<Box sx={{ ml: 'auto' }}>
<Button
aria-controls={openDemoSource ? demoSourceId : null}
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="expand"
onClick={onCodeOpenChange}
{...getControlProps(3)}
sx={{ mr: 0.5 }}
>
{showCodeLabel}
</Button>
{demoOptions.hideEditButton ? null : (
<React.Fragment>
<DemoTooltip title={t('codesandbox')} placement="bottom">
<IconButton
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="codesandbox"
onClick={() => codeSandbox.createReactApp(demoData).openSandbox()}
{...getControlProps(4)}
sx={{ borderRadius: 1 }}
>
<SvgIcon viewBox="0 0 1024 1024">
<path d="M755 140.3l0.5-0.3h0.3L512 0 268.3 140h-0.3l0.8 0.4L68.6 256v512L512 1024l443.4-256V256L755 140.3z m-30 506.4v171.2L548 920.1V534.7L883.4 341v215.7l-158.4 90z m-584.4-90.6V340.8L476 534.4v385.7L300 818.5V646.7l-159.4-90.6zM511.7 280l171.1-98.3 166.3 96-336.9 194.5-337-194.6 165.7-95.7L511.7 280z" />
</SvgIcon>
</IconButton>
</DemoTooltip>
<DemoTooltip title={t('stackblitz')} placement="bottom">
<IconButton
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="stackblitz"
onClick={() => stackBlitz.createReactApp(demoData).openSandbox()}
{...getControlProps(5)}
sx={{ borderRadius: 1 }}
>
<SvgIcon viewBox="0 0 19 28">
<path d="M8.13378 16.1087H0L14.8696 0L10.8662 11.1522L19 11.1522L4.13043 27.2609L8.13378 16.1087Z" />
</SvgIcon>
</IconButton>
</DemoTooltip>
</React.Fragment>
)}
<DemoTooltip title={t('copySource')} placement="bottom">
<IconButton
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="copy"
onClick={handleCopyClick}
{...getControlProps(6)}
sx={{ borderRadius: 1 }}
>
<ContentCopyRoundedIcon />
</IconButton>
</DemoTooltip>
<DemoTooltip title={t('resetFocus')} placement="bottom">
<IconButton
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="reset-focus"
onClick={handleResetFocusClick}
{...getControlProps(7)}
sx={{ borderRadius: 1 }}
>
<ResetFocusIcon />
</IconButton>
</DemoTooltip>
<DemoTooltip title={t('resetDemo')} placement="bottom">
<IconButton
aria-controls={demoId}
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="reset"
onClick={onResetDemoClick}
{...getControlProps(8)}
sx={{ borderRadius: 1 }}
>
<RefreshRoundedIcon />
</IconButton>
</DemoTooltip>
<IconButton
onClick={handleMoreClick}
aria-label={t('seeMore')}
aria-owns={anchorEl ? 'demo-menu-more' : undefined}
aria-haspopup="true"
{...getControlProps(9)}
sx={{ borderRadius: 1 }}
>
<MoreVertIcon />
</IconButton>
</Box>
</Root>
<Menu
id="demo-styling-menu"
anchorEl={stylingAnchorEl}
open={stylingMenuOpen}
onClose={handleStylingButtonClose}
MenuListProps={{
'aria-labelledby': 'basic-button',
}}
>
<MenuItem
value={CODE_STYLING.SYSTEM}
data-ga-event-category="demo"
data-ga-event-action="styling-system"
data-ga-event-label={demo.gaLabel}
selected={styleSolution === CODE_STYLING.SYSTEM}
onClick={() => handleStylingSolutionChange(CODE_STYLING.SYSTEM)}
>
{codeStylingLabels[CODE_STYLING.SYSTEM]}
{styleSolution === CODE_STYLING.SYSTEM && (
<CheckIcon sx={{ fontSize: '0.85rem', ml: 'auto' }} />
)}
</MenuItem>
<MenuItem
value={CODE_STYLING.TAILWIND}
data-ga-event-category="demo"
data-ga-event-action="styling-tailwind"
data-ga-event-label={demo.gaLabel}
selected={styleSolution === CODE_STYLING.TAILWIND}
onClick={() => handleStylingSolutionChange(CODE_STYLING.TAILWIND)}
>
{codeStylingLabels[CODE_STYLING.TAILWIND]}
{styleSolution === CODE_STYLING.TAILWIND && (
<CheckIcon sx={{ fontSize: '0.85rem', ml: 'auto' }} />
)}
</MenuItem>
<MenuItem
value={CODE_STYLING.CSS}
data-ga-event-category="demo"
data-ga-event-action="styling-css"
data-ga-event-label={demo.gaLabel}
selected={styleSolution === CODE_STYLING.CSS}
onClick={() => handleStylingSolutionChange(CODE_STYLING.CSS)}
>
{codeStylingLabels[CODE_STYLING.CSS]}
{styleSolution === CODE_STYLING.CSS && (
<CheckIcon sx={{ fontSize: '0.85rem', ml: 'auto' }} />
)}
</MenuItem>
</Menu>
<Menu
id="demo-menu-more"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleMoreClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
>
<MenuItem
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="github"
component="a"
href={demoData.githubLocation}
target="_blank"
rel="noopener nofollow"
onClick={handleMoreClose}
>
{t('viewGitHub')}
</MenuItem>
<MenuItem
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="copy-js-source-link"
onClick={createHandleCodeSourceLink(demoName, CODE_VARIANTS.JS, styleSolution)}
>
{t('copySourceLinkJS')}
</MenuItem>
<MenuItem
data-ga-event-category="demo"
data-ga-event-label={demo.gaLabel}
data-ga-event-action="copy-ts-source-link"
onClick={createHandleCodeSourceLink(demoName, CODE_VARIANTS.TS, styleSolution)}
>
{t('copySourceLinkTS')}
</MenuItem>
{devMenuItems}
</Menu>
<Snackbar
open={snackbarOpen}
autoHideDuration={3000}
onClose={handleSnackbarClose}
message={snackbarMessage}
/>
</React.Fragment>
);
}
DemoToolbar.propTypes = {
codeOpen: PropTypes.bool.isRequired,
codeVariant: PropTypes.string.isRequired,
demo: PropTypes.object.isRequired,
demoData: PropTypes.object.isRequired,
demoId: PropTypes.string,
demoName: PropTypes.string.isRequired,
demoOptions: PropTypes.object.isRequired,
demoSourceId: PropTypes.string,
hasNonSystemDemos: PropTypes.string,
initialFocusRef: PropTypes.shape({ current: PropTypes.object }).isRequired,
onCodeOpenChange: PropTypes.func.isRequired,
onResetDemoClick: PropTypes.func.isRequired,
openDemoSource: PropTypes.bool.isRequired,
showPreview: PropTypes.bool.isRequired,
};
| 5,281 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/DemoToolbarRoot.ts | import { styled, alpha } from '@mui/material/styles';
interface DemoToolbarRootProps {
demoOptions: any;
openDemoSource: any;
}
const DemoToolbarRoot = styled('div', {
shouldForwardProp: (prop) => prop !== 'demoOptions' && prop !== 'openDemoSource',
})<DemoToolbarRootProps>(({ theme, demoOptions, openDemoSource }) => [
{
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
border: `1px solid ${(theme.vars || theme).palette.divider}`,
marginTop: demoOptions.bg === 'inline' ? theme.spacing(1) : -1,
top: 0,
padding: theme.spacing(0.5, 1),
backgroundColor: alpha(theme.palette.grey[50], 0.2),
borderRadius: openDemoSource ? 0 : '0 0 12px 12px',
transition: theme.transitions.create('border-radius'),
...(theme.direction === 'rtl' && {
left: theme.spacing(1),
}),
...(theme.direction !== 'rtl' && {
right: theme.spacing(1),
}),
},
},
theme.applyDarkStyles({
[theme.breakpoints.up('sm')]: {
backgroundColor: alpha(theme.palette.primaryDark[800], 0.2),
},
}),
]);
export default DemoToolbarRoot;
| 5,282 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/DiamondSponsors.js | import * as React from 'react';
import { styled, alpha } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import DiamondOutlinedIcon from '@mui/icons-material/DiamondOutlined';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import Link from 'docs/src/modules/components/Link';
const StyledAnchor = styled('a')(({ theme }) => ({
boxSizing: 'border-box', // TODO have CssBaseline in the Next.js layout
width: '100%',
height: 45,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 12,
border: '1px solid',
borderColor: (theme.vars || theme).palette.divider,
transition: theme.transitions.create(['color', 'border-color']),
boxShadow: `inset 0 1px 1px ${(theme.vars || theme).palette.grey[50]}, 0 1px 2px ${alpha(
theme.palette.grey[100],
0.6,
)}`,
'&:hover': {
backgroundColor: (theme.vars || theme).palette.grey[50],
},
'& img': {
display: 'inline-block',
},
...theme.applyDarkStyles({
boxShadow: `inset 0 1px 1px ${(theme.vars || theme).palette.primaryDark[900]}, 0 1px 0.5px ${
(theme.vars || theme).palette.common.black
}`,
'&:hover': {
backgroundColor: (theme.vars || theme).palette.primaryDark[800],
borderColor: (theme.vars || theme).palette.primaryDark[600],
},
}),
}));
export default function DiamondSponsors() {
const t = useTranslate();
return (
<Stack
spacing={0.5}
direction="column"
sx={{
mt: 1.5,
pt: 1.5,
borderTop: '1px solid',
borderColor: 'divider',
}}
>
<Button
component="a"
href="/material-ui/discover-more/backers/"
target="_blank"
rel="noopener nofollow"
size="small"
startIcon={<DiamondOutlinedIcon />}
sx={{
width: 'fit-content',
fontSize: (theme) => theme.typography.pxToRem(12.5),
'& svg': {
marginRight: 0.5,
width: 16,
height: 16,
},
}}
>
{t('diamondSponsors')}
</Button>
<Stack spacing={1}>
<StyledAnchor
data-ga-event-category="sponsor"
data-ga-event-action="docs-premium"
data-ga-event-label="octopus.com"
href="https://octopus.com/?utm_source=materialui&utm_medium=referral"
rel="noopener noreferrer sponsored"
target="_blank"
>
<Box
component="img"
height="25px"
width="116px"
src="/static/sponsors/octopus-light.svg"
alt="octopus"
title="Repeatable, reliable deployments"
loading="lazy"
sx={(theme) =>
theme.applyDarkStyles({
content: `url(/static/sponsors/octopus-dark.svg)`,
})
}
/>
</StyledAnchor>
<StyledAnchor
data-ga-event-category="sponsor"
data-ga-event-action="docs-premium"
data-ga-event-label="doit.com"
href="https://www.doit.com/flexsave/?utm_source=materialui&utm_medium=referral"
rel="noopener noreferrer sponsored"
target="_blank"
>
<Box
component="img"
height="28px"
width="68px"
src="/static/sponsors/doit-light.svg"
alt="doit"
title="Management Platform for Google Cloud and AWS"
loading="lazy"
sx={(theme) =>
theme.applyDarkStyles({
content: `url(/static/sponsors/doit-dark.svg)`,
})
}
/>
</StyledAnchor>
<Link
aria-label={`${t('becomeADiamondSponsor')}${t('diamondSponsorVacancies')}`}
href="/material-ui/discover-more/backers/#diamond-sponsors"
sx={(theme) => ({
width: '100%',
p: 1,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 1,
border: '1px dashed',
transition: theme.transitions.create(['color', 'border-color', 'background-color']),
backgroundColor: alpha(theme.palette.primary[50], 0.5),
borderColor: (theme.vars || theme).palette.primary[200],
boxShadow: `inset 0 1px 1px ${
(theme.vars || theme).palette.grey[50]
}, 0 1px 2px ${alpha(theme.palette.primary[100], 0.8)}`,
'&:hover': {
backgroundColor: alpha(theme.palette.primary[100], 0.5),
borderColor: (theme.vars || theme).palette.primary[300],
},
...theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primary[400], 0.05),
borderColor: alpha(theme.palette.primary[300], 0.3),
boxShadow: `inset 0 1px 1px ${
(theme.vars || theme).palette.primaryDark[800]
}, 0 1px 0.5px ${(theme.vars || theme).palette.common.black}`,
'&:hover': {
backgroundColor: alpha(theme.palette.primary[400], 0.1),
borderColor: (theme.vars || theme).palette.primary[400],
},
}),
})}
>
<Typography variant="caption" fontWeight="semiBold" textAlign="center">
{t('becomeADiamondSponsor')}
</Typography>
<Typography variant="caption" fontWeight="regular" color="text.secondary">
{t('diamondSponsorVacancies')}
</Typography>
</Link>
</Stack>
</Stack>
);
}
| 5,283 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/EditPage.js | import * as React from 'react';
import PropTypes from 'prop-types';
import Button from '@mui/material/Button';
import GitHubIcon from '@mui/icons-material/GitHub';
import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n';
const LOCALES = { zh: 'zh-CN', pt: 'pt-BR', es: 'es-ES' };
export default function EditPage(props) {
const { sourceLocation } = props;
const t = useTranslate();
const userLanguage = useUserLanguage();
const CROWDIN_ROOT_URL = 'https://crowdin.com/project/material-ui-docs/';
const crowdInLocale = LOCALES[userLanguage] || userLanguage;
const crowdInPath = sourceLocation.substring(0, sourceLocation.lastIndexOf('/'));
return (
<Button
component="a"
size="small"
variant="outlined"
startIcon={<GitHubIcon sx={{ mr: 0.5 }} />}
href={
userLanguage === 'en'
? `${process.env.SOURCE_CODE_REPO}/edit/${process.env.SOURCE_GITHUB_BRANCH}${sourceLocation}`
: `${CROWDIN_ROOT_URL}${crowdInLocale}#/${process.env.SOURCE_CODE_ROOT_URL.replace(
'https://github.com/mui/',
'',
).replace('/blob/', '%20%2F%20')}${crowdInPath}`
}
target="_blank"
rel="noopener nofollow"
data-ga-event-category={userLanguage === 'en' ? undefined : 'l10n'}
data-ga-event-action={userLanguage === 'en' ? undefined : 'edit-button'}
data-ga-event-label={userLanguage === 'en' ? undefined : userLanguage}
sx={{ '&:hover > span': { transform: 'translateX(-2px)' } }}
>
{t('editPage')}
</Button>
);
}
EditPage.propTypes = {
sourceLocation: PropTypes.string.isRequired,
};
| 5,284 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/FigmaIcon.js | import * as React from 'react';
import { createSvgIcon } from '@mui/material/utils';
export default createSvgIcon(
<g fillRule="nonzero" fill="none">
<path d="M8 24a4 4 0 004-4v-4H8a4 4 0 000 8z" fill="#0ACF83" />
<path d="M4 12a4 4 0 014-4h4v8H8a4 4 0 01-4-4z" fill="#A259FF" />
<path d="M4 4a4 4 0 014-4h4v8H8a4 4 0 01-4-4z" fill="#F24E1E" />
<path d="M12 0h4a4 4 0 010 8h-4V0z" fill="#FF7262" />
<path d="M20 12a4 4 0 11-8 0 4 4 0 018 0z" fill="#1ABCFE" />
</g>,
'Figma',
);
| 5,285 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/GoogleAnalytics.js | import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useRouter } from 'next/router';
import { useNoSsrCodeVariant } from 'docs/src/modules/utils/codeVariant';
import { useNoSsrCodeStyling } from 'docs/src/modules/utils/codeStylingSolution';
import { useUserLanguage } from 'docs/src/modules/utils/i18n';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import { getApiPageLayout } from 'docs/src/modules/components/ApiPage/sections/ToggleDisplayOption';
// So we can write code like:
//
// <Button
// data-ga-event-category="demo"
// data-ga-event-action="expand"
// >
// Foo
// </Button>
function handleClick(event) {
let element = event.target;
while (element && element !== document) {
const category = element.getAttribute('data-ga-event-category');
// We reach a tracking element, no need to look higher in the dom tree.
if (category) {
const split = parseFloat(element.getAttribute('data-ga-event-split'));
if (split && split < Math.random()) {
return;
}
window.gtag('event', category, {
eventAction: element.getAttribute('data-ga-event-action'),
eventLabel: element.getAttribute('data-ga-event-label'),
});
break;
}
element = element.parentElement;
}
}
let boundDataGaListener = false;
/**
* basically just a `useAnalytics` hook.
* However, it needs the redux store which is created
* in the same component this "hook" is used.
*/
function GoogleAnalytics() {
React.useEffect(() => {
if (!boundDataGaListener) {
boundDataGaListener = true;
document.addEventListener('click', handleClick);
}
}, []);
const router = useRouter();
const timeout = React.useRef();
React.useEffect(() => {
// Wait for the title to be updated.
// React fires useEffect twice in dev mode
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
const { canonicalAsServer } = pathnameToLanguage(window.location.pathname);
// https://developers.google.com/analytics/devguides/collection/ga4/views?client_type=gtag
window.gtag('event', 'page_view', {
page_title: document.title,
page_location: canonicalAsServer,
productId: document.querySelector('meta[name="mui:productId"]').content,
productCategoryId: document.querySelector('meta[name="mui:productCategoryId"]').content,
});
});
}, [router.route]);
const codeVariant = useNoSsrCodeVariant();
React.useEffect(() => {
window.gtag('set', 'user_properties', {
codeVariant,
});
}, [codeVariant]);
const userLanguage = useUserLanguage();
React.useEffect(() => {
window.gtag('set', 'user_properties', {
userLanguage,
});
}, [userLanguage]);
React.useEffect(() => {
/**
* Based on https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#Monitoring_screen_resolution_or_zoom_level_changes
* Adjusted to track 3 or more different ratios
*/
function trackDevicePixelRation() {
const devicePixelRatio = Math.round(window.devicePixelRatio * 10) / 10;
window.gtag('set', 'user_properties', {
devicePixelRatio,
});
}
trackDevicePixelRation();
/**
* @type {MediaQueryList}
*/
const matchMedia = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
// Intentionally use deprecated listener methods to support iOS & old browsers
matchMedia.addListener(trackDevicePixelRation);
return () => {
matchMedia.removeListener(trackDevicePixelRation);
};
}, []);
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)', { noSsr: true });
const colorSchemeOS = prefersDarkMode ? 'dark' : 'light';
const theme = useTheme();
const colorScheme = theme.palette.mode;
React.useEffect(() => {
window.gtag('set', 'user_properties', {
colorSchemeOS,
});
}, [colorSchemeOS]);
React.useEffect(() => {
window.gtag('set', 'user_properties', {
colorScheme,
});
}, [colorScheme]);
const codeStylingVariant = useNoSsrCodeStyling();
React.useEffect(() => {
window.gtag('set', 'user_properties', {
codeStylingVariant,
});
}, [codeStylingVariant]);
React.useEffect(() => {
window.gtag('set', 'user_properties', {
...getApiPageLayout(),
});
}, []);
return null;
}
export default React.memo(GoogleAnalytics);
| 5,286 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/Head.tsx | import * as React from 'react';
import NextHead from 'next/head';
import { useRouter } from 'next/router';
import { LANGUAGES_SSR } from 'docs/config';
import { useUserLanguage, useTranslate } from 'docs/src/modules/utils/i18n';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
// #major-version-switch
const HOST = 'https://mui.com';
interface HeadProps {
card?: string;
children?: React.ReactNode;
description: string;
disableAlternateLocale?: boolean;
largeCard?: boolean;
title: string;
type?: string;
}
export default function Head(props: HeadProps) {
const t = useTranslate();
const {
card = '/static/social-previews/default-preview.jpg',
children,
description = t('strapline'),
disableAlternateLocale = false,
largeCard = true,
title = t('headTitle'),
type = 'website',
} = props;
const userLanguage = useUserLanguage();
const router = useRouter();
const { canonicalAs } = pathnameToLanguage(router.asPath);
const preview = card.startsWith('http') ? card : `${HOST}${card}`;
return (
<NextHead>
<title>{title}</title>
<meta name="description" content={description} />
{/* Twitter */}
<meta name="twitter:card" content={largeCard ? 'summary_large_image' : 'summary'} />
{/* https://twitter.com/MUI_hq */}
<meta name="twitter:site" content="@MUI_hq" />
{/* #major-version-switch */}
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={preview} />
{/* Facebook */}
<meta property="og:type" content={type} />
<meta property="og:title" content={title} />
{/* #major-version-switch */}
<meta property="og:url" content={`${HOST}${router.asPath}`} />
<meta property="og:description" content={description} />
<meta property="og:image" content={preview} />
<meta property="og:ttl" content="604800" />
{/* Algolia */}
<meta name="docsearch:language" content={userLanguage} />
{/* #major-version-switch */}
<meta name="docsearch:version" content="master" />
{disableAlternateLocale
? null
: LANGUAGES_SSR.map((userLanguage2) => (
<link
key={userLanguage2}
rel="alternate"
href={`https://mui.com${
userLanguage2 === 'en' ? '' : `/${userLanguage2}`
}${canonicalAs}`}
hrefLang={userLanguage2}
/>
))}
{children}
</NextHead>
);
}
| 5,287 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/HighlightedCode.js | import * as React from 'react';
import PropTypes from 'prop-types';
import prism from '@mui/markdown/prism';
import { NoSsr } from '@mui/base/NoSsr';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
import CodeCopyButton from 'docs/src/modules/components/CodeCopyButton';
import { useCodeCopy } from 'docs/src/modules/utils/CodeCopy';
const HighlightedCode = React.forwardRef(function HighlightedCode(props, ref) {
const {
copyButtonHidden = false,
copyButtonProps,
code,
language,
component: Component = MarkdownElement,
...other
} = props;
const renderedCode = React.useMemo(() => {
return prism(code.trim(), language);
}, [code, language]);
const handlers = useCodeCopy();
return (
<Component ref={ref} {...other}>
<div className="MuiCode-root" {...handlers}>
<pre>
<code
className={`language-${language}`}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: renderedCode }}
/>
</pre>
{copyButtonHidden ? null : (
<NoSsr>
<CodeCopyButton code={code} {...copyButtonProps} />
</NoSsr>
)}
</div>
</Component>
);
});
HighlightedCode.propTypes = {
code: PropTypes.string.isRequired,
component: PropTypes.elementType,
copyButtonHidden: PropTypes.bool,
copyButtonProps: PropTypes.object,
language: PropTypes.string.isRequired,
sx: PropTypes.object,
};
export default HighlightedCode;
| 5,288 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/HighlightedCode.test.js | import * as React from 'react';
import { expect } from 'chai';
import { createRenderer } from '@mui-internal/test-utils';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { getDesignTokens } from 'docs/src/modules/brandingTheme';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
describe('HighlightedCode', () => {
const { render } = createRenderer();
it('does not crash with default theme', () => {
expect(() =>
render(
<ThemeProvider theme={createTheme()}>
<HighlightedCode code="" language="javascript" />
</ThemeProvider>,
),
).not.to.throw();
});
it('does not crash with default theme in dark mode', () => {
expect(() =>
render(
<ThemeProvider theme={createTheme({ palette: { mode: 'dark' } })}>
<HighlightedCode code="" language="javascript" />
</ThemeProvider>,
),
).not.to.throw();
});
it('does not crash with branding theme', () => {
expect(() =>
render(
<ThemeProvider theme={createTheme(getDesignTokens('light'))}>
<HighlightedCode code="" language="javascript" />
</ThemeProvider>,
),
).not.to.throw();
});
it('does not crash with branding theme in dark mode', () => {
expect(() =>
render(
<ThemeProvider theme={createTheme(getDesignTokens('dark'))}>
<HighlightedCode code="" language="javascript" />
</ThemeProvider>,
),
).not.to.throw();
});
});
| 5,289 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/HighlightedCodeWithTabs.tsx | import * as React from 'react';
import { styled, alpha } from '@mui/material/styles';
import { Tabs, TabsOwnProps } from '@mui/base/Tabs';
import { TabsList } from '@mui/base/TabsList';
import { TabPanel } from '@mui/base/TabPanel';
import { Tab } from '@mui/base/Tab';
import HighlightedCode from './HighlightedCode';
const StyledTabList = styled(TabsList)(({ theme }) => ({
padding: 6,
display: 'flex',
border: '1px solid',
borderColor: (theme.vars || theme).palette.primaryDark[700],
backgroundColor: (theme.vars || theme).palette.primaryDark[900],
borderTopLeftRadius: (theme.vars || theme).shape.borderRadius,
borderTopRightRadius: (theme.vars || theme).shape.borderRadius,
...theme.applyDarkStyles({
backgroundColor: alpha(theme.palette.primaryDark[800], 0.5),
}),
}));
const StyledTabPanel = styled(TabPanel)<{ ownerState: { mounted: boolean } }>(({ ownerState }) => ({
'& pre': {
marginTop: -1,
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
'& code': {
opacity: ownerState.mounted ? 1 : 0,
},
},
}));
const StyledTab = styled(Tab)<{ ownerState: { mounted: boolean } }>(({ theme, ownerState }) =>
theme.unstable_sx({
p: 0.8,
border: 'none',
bgcolor: 'transparent',
color: (theme.vars || theme).palette.grey[500],
fontSize: theme.typography.pxToRem(12),
fontWeight: theme.typography.fontWeightSemiBold,
fontFamily: theme.typography.fontFamilyCode,
outline: 'none',
minWidth: 52,
cursor: 'pointer',
borderRadius: '8px',
position: 'relative',
'&:not(:first-of-type)': {
marginLeft: 0.5,
},
...(ownerState.mounted && {
'&.Mui-selected': {
color: '#FFF',
'&:after': {
content: "''",
position: 'absolute',
left: 0,
bottom: '-6px',
height: 2,
width: '100%',
bgcolor: (theme.vars || theme).palette.primary.light,
},
},
}),
'&:hover': {
backgroundColor: alpha(theme.palette.primaryDark[500], 0.5),
},
'&:focus-visible': {
outline: '2px solid',
outlineOffset: '-2px',
outlineColor: (theme.vars || theme).palette.primary.light,
},
}),
);
type TabsConfig = {
code: string | ((tab: string) => string);
language: string;
tab: string;
};
export default function HighlightedCodeWithTabs({
tabs,
storageKey,
}: {
tabs: Array<TabsConfig>;
storageKey?: string;
} & Record<string, any>) {
const availableTabs = React.useMemo(() => tabs.map(({ tab }) => tab), [tabs]);
const [activeTab, setActiveTab] = React.useState(availableTabs[0]);
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
try {
setActiveTab((prev) => {
if (storageKey === undefined) {
return prev;
}
const storedValues = localStorage.getItem(storageKey);
return storedValues && availableTabs.includes(storedValues) ? storedValues : prev;
});
} catch (error) {
// ignore error
}
setMounted(true);
}, [availableTabs, storageKey]);
const handleChange: TabsOwnProps['onChange'] = (event, newValue) => {
setActiveTab(newValue as string);
if (storageKey === undefined) {
return;
}
try {
localStorage.setItem(storageKey, newValue as string);
} catch (error) {
// ignore error
}
};
const ownerState = { mounted };
return (
<Tabs selectionFollowsFocus value={activeTab} onChange={handleChange}>
<StyledTabList>
{tabs.map(({ tab }) => (
<StyledTab ownerState={ownerState} key={tab} value={tab}>
{tab}
</StyledTab>
))}
</StyledTabList>
{tabs.map(({ tab, language, code }) => (
<StyledTabPanel ownerState={ownerState} key={tab} value={tab}>
<HighlightedCode
// @ts-ignore
language={language || 'bash'}
code={typeof code === 'function' ? code(tab) : code}
/>
</StyledTabPanel>
))}
</Tabs>
);
}
| 5,290 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/HooksApiContent.js | /* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import kebabCase from 'lodash/kebabCase';
import { exactProp } from '@mui/utils';
import { useTranslate, useUserLanguage } from 'docs/src/modules/utils/i18n';
import PropertiesSection from 'docs/src/modules/components/ApiPage/sections/PropertiesSection';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
function getTranslatedHeader(t, header, text) {
const translations = {
demos: t('api-docs.demos'),
import: t('api-docs.import'),
'hook-name': t('api-docs.hookName'),
parameters: t('api-docs.parameters'),
'return-value': t('api-docs.returnValue'),
};
return translations[header] || translations[text] || text || header;
}
function Heading(props) {
const { hash, text, level: Level = 'h2' } = props;
const t = useTranslate();
return (
<Level id={hash}>
{getTranslatedHeader(t, hash, text)}
<a aria-labelledby={hash} className="anchor-link" href={`#${hash}`} tabIndex={-1}>
<svg>
<use xlinkHref="#anchor-link-icon" />
</svg>
</a>
</Level>
);
}
Heading.propTypes = {
hash: PropTypes.string.isRequired,
level: PropTypes.string,
text: PropTypes.string,
};
export default function HooksApiContent(props) {
const { descriptions, pagesContents } = props;
const userLanguage = useUserLanguage();
const t = useTranslate();
const hooks = Object.keys(pagesContents);
return hooks.map((key) => {
const { name: hookName, parameters, returnValue, imports } = pagesContents[key];
const { parametersDescriptions, returnValueDescriptions } = descriptions[key][userLanguage];
const hookNameKebabCase = kebabCase(hookName);
const importInstructions = imports.join(`
// ${t('or')}
`);
return (
<React.Fragment key={`hook-api-${key}`}>
<MarkdownElement>
<Heading hash={hookNameKebabCase} text={`${hookName} API`} />
<Heading text="import" hash={`${hookNameKebabCase}-import`} level="h3" />
<HighlightedCode code={importInstructions} language="jsx" />
<span dangerouslySetInnerHTML={{ __html: t('api-docs.importDifference') }} />
{Object.keys(parameters).length > 0 ? (
<PropertiesSection
properties={parameters}
targetName={hookNameKebabCase}
hooksParameters
propertiesDescriptions={parametersDescriptions}
level="h3"
title="api-docs.parameters"
titleHash={`${hookNameKebabCase}-parameters`}
/>
) : (
<span>{t('api-docs.hooksNoParameters')}</span>
)}
<PropertiesSection
showOptionalAbbr
properties={returnValue}
targetName={hookNameKebabCase}
hooksReturnValue
propertiesDescriptions={returnValueDescriptions}
level="h3"
title="api-docs.returnValue"
titleHash={`${hookNameKebabCase}-return-value`}
/>
<br />
</MarkdownElement>
<svg style={{ display: 'none' }} xmlns="http://www.w3.org/2000/svg">
<symbol id="anchor-link-icon" viewBox="0 0 16 16">
<path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z" />
</symbol>
</svg>
</React.Fragment>
);
});
}
HooksApiContent.propTypes = {
descriptions: PropTypes.object.isRequired,
pagesContents: PropTypes.object.isRequired,
};
if (process.env.NODE_ENV !== 'production') {
HooksApiContent.propTypes = exactProp(HooksApiContent.propTypes);
}
| 5,291 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/JoyStartingLinksCollection.js | import * as React from 'react';
import Grid from '@mui/material/Unstable_Grid2';
import InstallDesktopRoundedIcon from '@mui/icons-material/InstallDesktopRounded';
import WebRoundedIcon from '@mui/icons-material/WebRounded';
import DrawRoundedIcon from '@mui/icons-material/DrawRounded';
import InfoCard from 'docs/src/components/action/InfoCard';
const content = [
{
title: 'Installation',
description: 'Add Joy UI to your project with a few commands.',
link: '/joy-ui/getting-started/installation/',
icon: <InstallDesktopRoundedIcon color="primary" />,
},
{
title: 'Usage',
description: 'Learn the basics of working with Joy UI components.',
link: '/joy-ui/getting-started/usage/',
icon: <DrawRoundedIcon color="primary" />,
},
{
title: 'Templates',
description: 'Get started with our selection of free application templates.',
link: '/joy-ui/getting-started/templates/',
icon: <WebRoundedIcon color="primary" />,
},
{
title: 'Joy UI for Figma',
description:
'The Joy UI components, with variables, variants, and states, in your favorite design tool.',
link: 'https://www.figma.com/community/file/1293288155415213351/joy-ui-for-figma',
icon: (
<img
src={`/static/branding/design-kits/figma-logo.svg`}
alt="Figma logo"
loading="lazy"
width="24"
height="24"
/>
),
},
];
export default function JoyStartingLinksCollection() {
return (
<Grid container spacing={2}>
{content.map(({ icon, title, description, link }) => (
<Grid key={title} xs={12} sm={6}>
<InfoCard
classNameTitle="algolia-lvl3"
classNameDescription="algolia-content"
link={link}
title={title}
icon={icon}
description={description}
/>
</Grid>
))}
</Grid>
);
}
| 5,292 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/JoyThemeBuilder.tsx | import * as React from 'react';
// @ts-ignore
import { TypeScript as TypeScriptIcon } from '@mui/docs';
import startCase from 'lodash/startCase';
import { deepmerge } from '@mui/utils';
import { decomposeColor } from '@mui/system';
import * as mdColors from '@mui/material/colors';
import { useTheme as useMuiTheme } from '@mui/material/styles';
import {
CssVarsProvider,
extendTheme,
ColorPaletteProp,
VariantProp,
PaletteVariant,
} from '@mui/joy/styles';
import Autocomplete, { AutocompleteProps } from '@mui/joy/Autocomplete';
import AutocompleteOption from '@mui/joy/AutocompleteOption';
import Alert from '@mui/joy/Alert';
import AspectRatio from '@mui/joy/AspectRatio';
import Box from '@mui/joy/Box';
import Button from '@mui/joy/Button';
import Checkbox from '@mui/joy/Checkbox';
import Card from '@mui/joy/Card';
import CardCover from '@mui/joy/CardCover';
import Divider from '@mui/joy/Divider';
import FormControl from '@mui/joy/FormControl';
import FormLabel from '@mui/joy/FormLabel';
import IconButton from '@mui/joy/IconButton';
import Input, { InputProps } from '@mui/joy/Input';
import Link from '@mui/joy/Link';
import List from '@mui/joy/List';
import ListSubheader from '@mui/joy/ListSubheader';
import ListDivider from '@mui/joy/ListDivider';
import ListItem from '@mui/joy/ListItem';
import ListItemDecorator from '@mui/joy/ListItemDecorator';
import ListItemContent from '@mui/joy/ListItemContent';
import ListItemButton from '@mui/joy/ListItemButton';
import Modal from '@mui/joy/Modal';
import ModalDialog from '@mui/joy/ModalDialog';
import ModalClose from '@mui/joy/ModalClose';
import Sheet, { SheetProps } from '@mui/joy/Sheet';
import Select from '@mui/joy/Select';
import Option from '@mui/joy/Option';
import Tabs from '@mui/joy/Tabs';
import TabList from '@mui/joy/TabList';
import TabPanel, { tabPanelClasses } from '@mui/joy/TabPanel';
import Tab, { tabClasses } from '@mui/joy/Tab';
import ToggleButtonGroup from '@mui/joy/ToggleButtonGroup';
import Typography from '@mui/joy/Typography';
import SvgIcon from '@mui/joy/SvgIcon';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';
import InfoOutlined from '@mui/icons-material/InfoOutlined';
import ArrowOutwardIcon from '@mui/icons-material/ArrowOutward';
import Add from '@mui/icons-material/Add';
import Remove from '@mui/icons-material/Remove';
import Close from '@mui/icons-material/Close';
import Check from '@mui/icons-material/Check';
import Code from '@mui/icons-material/Code';
import Search from '@mui/icons-material/Search';
import DescriptionOutlinedIcon from '@mui/icons-material/DescriptionOutlined';
import DarkMode from '@mui/icons-material/DarkMode';
import LightMode from '@mui/icons-material/LightMode';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
import BrandingProvider from 'docs/src/BrandingProvider';
import codeSandbox from 'docs/src/modules/sandbox/CodeSandbox';
import sourceJoyTemplates, { TemplateData } from 'docs/src/modules/joy/sourceJoyTemplates';
import extractTemplates from 'docs/src/modules/utils/extractTemplates';
import generateThemeAugmentation from 'docs/src/modules/joy/generateThemeAugmentation';
import literalToObject from 'docs/src/modules/joy/literalToObject';
import getMinimalJoyTemplate from 'docs/src/modules/joy/getMinimalJoyTemplate';
const tailwindColors = {
slate: {
50: '#f8fafc',
100: '#f1f5f9',
200: '#e2e8f0',
300: '#cbd5e1',
400: '#94a3b8',
500: '#64748b',
600: '#475569',
700: '#334155',
800: '#1e293b',
900: '#0f172a',
},
gray: {
50: '#f9fafb',
100: '#f3f4f6',
200: '#e5e7eb',
300: '#d1d5db',
400: '#9ca3af',
500: '#6b7280',
600: '#4b5563',
700: '#374151',
800: '#1f2937',
900: '#111827',
},
zinc: {
50: '#fafafa',
100: '#f4f4f5',
200: '#e4e4e7',
300: '#d4d4d8',
400: '#a1a1aa',
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
900: '#18181b',
},
neutral: {
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
900: '#171717',
},
stone: {
50: '#fafaf9',
100: '#f5f5f4',
200: '#e7e5e4',
300: '#d6d3d1',
400: '#a8a29e',
500: '#78716c',
600: '#57534e',
700: '#44403c',
800: '#292524',
900: '#1c1917',
},
red: {
50: '#fef2f2',
100: '#fee2e2',
200: '#fecaca',
300: '#fca5a5',
400: '#f87171',
500: '#ef4444',
600: '#dc2626',
700: '#b91c1c',
800: '#991b1b',
900: '#7f1d1d',
},
orange: {
50: '#fff7ed',
100: '#ffedd5',
200: '#fed7aa',
300: '#fdba74',
400: '#fb923c',
500: '#f97316',
600: '#ea580c',
700: '#c2410c',
800: '#9a3412',
900: '#7c2d12',
},
amber: {
50: '#fffbeb',
100: '#fef3c7',
200: '#fde68a',
300: '#fcd34d',
400: '#fbbf24',
500: '#f59e0b',
600: '#d97706',
700: '#b45309',
800: '#92400e',
900: '#78350f',
},
yellow: {
50: '#fefce8',
100: '#fef9c3',
200: '#fef08a',
300: '#fde047',
400: '#facc15',
500: '#eab308',
600: '#ca8a04',
700: '#a16207',
800: '#854d0e',
900: '#713f12',
},
lime: {
50: '#f7fee7',
100: '#ecfccb',
200: '#d9f99d',
300: '#bef264',
400: '#a3e635',
500: '#84cc16',
600: '#65a30d',
700: '#4d7c0f',
800: '#3f6212',
900: '#365314',
},
green: {
50: '#f0fdf4',
100: '#dcfce7',
200: '#bbf7d0',
300: '#86efac',
400: '#4ade80',
500: '#22c55e',
600: '#16a34a',
700: '#15803d',
800: '#166534',
900: '#14532d',
},
emerald: {
50: '#ecfdf5',
100: '#d1fae5',
200: '#a7f3d0',
300: '#6ee7b7',
400: '#34d399',
500: '#10b981',
600: '#059669',
700: '#047857',
800: '#065f46',
900: '#064e3b',
},
teal: {
50: '#f0fdfa',
100: '#ccfbf1',
200: '#99f6e4',
300: '#5eead4',
400: '#2dd4bf',
500: '#14b8a6',
600: '#0d9488',
700: '#0f766e',
800: '#115e59',
900: '#134e4a',
},
cyan: {
50: '#ecfeff',
100: '#cffafe',
200: '#a5f3fc',
300: '#67e8f9',
400: '#22d3ee',
500: '#06b6d4',
600: '#0891b2',
700: '#0e7490',
800: '#155e75',
900: '#164e63',
},
sky: {
50: '#f0f9ff',
100: '#e0f2fe',
200: '#bae6fd',
300: '#7dd3fc',
400: '#38bdf8',
500: '#0ea5e9',
600: '#0284c7',
700: '#0369a1',
800: '#075985',
900: '#0c4a6e',
},
blue: {
50: '#eff6ff',
100: '#dbeafe',
200: '#bfdbfe',
300: '#93c5fd',
400: '#60a5fa',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
800: '#1e40af',
900: '#1e3a8a',
},
indigo: {
50: '#eef2ff',
100: '#e0e7ff',
200: '#c7d2fe',
300: '#a5b4fc',
400: '#818cf8',
500: '#6366f1',
600: '#4f46e5',
700: '#4338ca',
800: '#3730a3',
900: '#312e81',
},
violet: {
50: '#f5f3ff',
100: '#ede9fe',
200: '#ddd6fe',
300: '#c4b5fd',
400: '#a78bfa',
500: '#8b5cf6',
600: '#7c3aed',
700: '#6d28d9',
800: '#5b21b6',
900: '#4c1d95',
},
purple: {
50: '#faf5ff',
100: '#f3e8ff',
200: '#e9d5ff',
300: '#d8b4fe',
400: '#c084fc',
500: '#a855f7',
600: '#9333ea',
700: '#7e22ce',
800: '#6b21a8',
900: '#581c87',
},
fuchsia: {
50: '#fdf4ff',
100: '#fae8ff',
200: '#f5d0fe',
300: '#f0abfc',
400: '#e879f9',
500: '#d946ef',
600: '#c026d3',
700: '#a21caf',
800: '#86198f',
900: '#701a75',
},
pink: {
50: '#fdf2f8',
100: '#fce7f3',
200: '#fbcfe8',
300: '#f9a8d4',
400: '#f472b6',
500: '#ec4899',
600: '#db2777',
700: '#be185d',
800: '#9d174d',
900: '#831843',
},
rose: {
50: '#fff1f2',
100: '#ffe4e6',
200: '#fecdd3',
300: '#fda4af',
400: '#fb7185',
500: '#f43f5e',
600: '#e11d48',
700: '#be123c',
800: '#9f1239',
900: '#881337',
},
};
const defaultTheme = extendTheme();
const generateThemeCode = (data: any) =>
`
import { extendTheme } from '@mui/joy/styles';
${generateThemeAugmentation(data)}
const theme = extendTheme(${JSON.stringify(
data,
(k, v) => (v === undefined ? '__undefined' : v),
2,
).replace(/"__undefined"/g, 'undefined')})
export default theme;`;
function getPaletteFormProps(colorSchemes: any, colorMode: string, node: string) {
// @ts-ignore
const themeDefaultValue = defaultTheme.colorSchemes[colorMode].palette[node];
const value = colorSchemes[colorMode][node] || {};
const mergedValue = { ...themeDefaultValue, ...value };
return {
themeDefaultValue,
value,
mergedValue,
tokens: Object.keys(mergedValue).filter((k) => mergedValue[k] !== undefined),
};
}
function ColorBubblePreview({ sx, value, ...props }: SheetProps & { value: string | undefined }) {
return (
<Sheet
variant="outlined"
{...props}
sx={[
{
width: 20,
height: 20,
borderRadius: '50%',
...(value?.includes('-gradient')
? {
background: value,
}
: {
bgcolor: value,
}),
},
...(Array.isArray(sx) ? sx : [sx]),
]}
/>
);
}
function CodeBlockResult({
data,
onClose,
...props
}: { data: any; onClose: () => void } & SheetProps) {
const [lang, setLang] = React.useState('js');
return (
<Sheet
variant="outlined"
{...props}
sx={{
borderRadius: 'sm',
overflow: 'auto',
'&& pre': { maxHeight: 'initial', minHeight: 450, borderRadius: 0, margin: 0 },
}}
>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<Tabs
value={lang}
onChange={(event, newValue) => setLang(newValue as string)}
sx={{ bgcolor: 'transparent' }}
>
<TabList
variant="plain"
size="sm"
sx={{
flexGrow: 0,
'--List-radius': '0px',
'--List-padding': '0px',
'--List-gap': '0px',
'--ListItem-minHeight': '48px',
'--ListItem-paddingX': '16px',
[`& .${tabClasses.root}`]: {
bgcolor: 'transparent',
color: 'text.tertiary',
flexGrow: 0,
'&:hover, &:active': {
bgcolor: 'transparent',
},
},
[`& .${tabClasses.selected}`]: {
boxShadow: 'none',
fontWeight: 'lg',
color: 'text.primary',
'&::after': {
content: '""',
display: 'block',
height: 3,
bgcolor: 'primary.500',
position: 'absolute',
insetInline: 0,
bottom: 0,
},
},
}}
>
<Tab value="js">
<ListItemDecorator>
<DescriptionOutlinedIcon />
</ListItemDecorator>
theme.js
</Tab>
<Tab value="ts">
<ListItemDecorator>
<TypeScriptIcon />
</ListItemDecorator>
theme.d.ts
</Tab>
</TabList>
</Tabs>
<IconButton
size="sm"
variant="outlined"
color="neutral"
onClick={onClose}
sx={{ ml: 'auto', mr: 1 }}
>
<Close />
</IconButton>
</Box>
<BrandingProvider mode="dark">
<HighlightedCode
language={lang}
code={lang === 'ts' ? generateThemeAugmentation(data) : generateThemeCode(data)}
/>
</BrandingProvider>
</Sheet>
);
}
function ColorInput({
value = '',
onValidColor,
onEmptyColor,
...props
}: InputProps & {
onValidColor: (color: string) => void;
onEmptyColor: () => void;
value: string;
}) {
const [internalValue, setInternalValue] = React.useState(value);
const [isError, setIsError] = React.useState(false);
const focused = React.useRef(false);
React.useEffect(() => {
if (value !== internalValue && !focused.current) {
setInternalValue(value || '');
}
}, [value, internalValue]);
return (
<Input
{...props}
size="sm"
error={isError}
startDecorator={
<ColorBubblePreview
value={internalValue || props.placeholder}
sx={{
mr: -0.5,
}}
/>
}
value={internalValue}
onFocus={(event) => {
(event.target as HTMLInputElement).select();
focused.current = true;
}}
onBlur={() => {
focused.current = false;
}}
onChange={(event) => {
const { value: inputValue } = event.target;
setInternalValue(inputValue);
if (inputValue === '') {
onEmptyColor();
setIsError(false);
} else if (inputValue.match(/^var\(--.*\)$/)) {
onValidColor(inputValue);
setIsError(false);
} else {
try {
decomposeColor(inputValue); // if inputValue is not a valid color, it throws an error
onValidColor(inputValue);
setIsError(false);
} catch (error) {
setIsError(true);
}
}
}}
/>
);
}
function PaletteImport({
onSelect,
colorMode = 'light',
}: {
onSelect: (palette: Record<string, string>) => void;
colorMode: 'light' | 'dark';
}) {
const [anchorEl, setAnchorEl] = React.useState<HTMLElement | null>(null);
return (
<React.Fragment>
<Button
onClick={(event: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
}}
color="neutral"
variant="outlined"
size="sm"
startDecorator={<Search />}
fullWidth
sx={{ mb: 1 }}
>
Browse palette
</Button>
<Modal
data-joy-color-scheme={colorMode}
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
>
<ModalDialog
aria-labelledby="color-palettes-modal"
sx={{ '--ModalDialog-minWidth': '700px' }}
>
<ModalClose />
<Typography id="color-palettes-modal" component="h2">
Palettes
</Typography>
<Alert
size="sm"
variant="outlined"
color="neutral"
startDecorator={<InfoOutlined />}
sx={{ bgcolor: 'neutral.softBg', my: 1 }}
>
The selected palette will replace the default Joy UI color tokens or the ones you
inserted.
</Alert>
<Tabs
size="sm"
defaultValue={0}
sx={{
minHeight: 0,
flexBasis: 480,
[`& .${tabPanelClasses.root}`]: { overflow: 'auto', mr: -2, pr: 2 },
}}
>
<TabList
variant="plain"
sx={{
'--List-padding': '0px',
'--List-gap': '1rem',
'--ListItem-minHeight': '48px',
'--ListItemDecorator-size': '2rem',
'& > button': {
bgcolor: 'transparent',
boxShadow: 'none',
flex: 'none',
color: 'text.tertiary',
fontWeight: 'md',
'&:hover': { bgcolor: 'transparent' },
'&[aria-selected="true"]': {
color: 'text.primary',
'&::before': {
content: '""',
display: 'block',
position: 'absolute',
height: 2,
left: 0,
right: 0,
bottom: -1,
bgcolor: `neutral.solidBg`,
},
},
},
}}
>
<Tab>
<ListItemDecorator>
<SvgIcon viewBox="0 0 53 31" fontSize="xl2">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M25.517 0C18.712 0 14.46 3.382 12.758 10.146c2.552-3.382 5.529-4.65 8.931-3.805 1.941.482 3.329 1.882 4.864 3.432 2.502 2.524 5.398 5.445 11.722 5.445 6.804 0 11.057-3.382 12.758-10.145-2.551 3.382-5.528 4.65-8.93 3.804-1.942-.482-3.33-1.882-4.865-3.431C34.736 2.92 31.841 0 25.517 0zM12.758 15.218C5.954 15.218 1.701 18.6 0 25.364c2.552-3.382 5.529-4.65 8.93-3.805 1.942.482 3.33 1.882 4.865 3.432 2.502 2.524 5.397 5.445 11.722 5.445 6.804 0 11.057-3.381 12.758-10.145-2.552 3.382-5.529 4.65-8.931 3.805-1.941-.483-3.329-1.883-4.864-3.432-2.502-2.524-5.398-5.446-11.722-5.446z"
fill="#38bdf8"
/>
</SvgIcon>
</ListItemDecorator>{' '}
Tailwind CSS
</Tab>
<Tab>
<ListItemDecorator>
<SvgIcon viewBox="0 0 24 24" fontSize="xl">
<circle cx="12" cy="12" fill="#757575" r="12" />
<path d="m3.6 3.6h16.8v16.8h-16.8z" fill="#bdbdbd" />
<path d="m20.4 3.6-8.4 16.8-8.4-16.8z" fill="#fff" />
<path d="m0 0h24v24h-24z" fill="none" />
</SvgIcon>
</ListItemDecorator>{' '}
Material Design
</Tab>
</TabList>
<Divider inset="context" />
<TabPanel value={0}>
<List
size="sm"
sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 1 }}
>
{Object.entries(tailwindColors).map(([name, colors]) => (
<ListItem key={name}>
<ListItemButton
aria-label={name}
onClick={() => {
setAnchorEl(null);
onSelect(colors);
}}
>
<Typography sx={{ mr: 'auto' }}>{name}</Typography>
{Object.entries(colors).map(([key, value]) => (
<Box key={key} sx={{ width: 20, height: 20, bgcolor: value }} />
))}
</ListItemButton>
</ListItem>
))}
</List>
</TabPanel>
<TabPanel value={1}>
<List
size="sm"
sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 1 }}
>
{Object.entries(mdColors).map(([name, colors]) => {
if (name === 'common') {
return <React.Fragment key={name} />;
}
const filteredColors: Record<string, string> = {};
(Object.keys(colors) as Array<keyof typeof colors>).forEach((key) => {
if (!Number.isNaN(Number(key))) {
filteredColors[key] = colors[key];
}
});
return (
<ListItem key={name}>
<ListItemButton
aria-label={name}
onClick={() => {
setAnchorEl(null);
onSelect(filteredColors);
}}
>
<Typography sx={{ mr: 'auto' }}>{name}</Typography>
{Object.entries(filteredColors).map(([key, value]) => (
<Box key={key} sx={{ width: 20, height: 20, bgcolor: value }} />
))}
</ListItemButton>
</ListItem>
);
})}
</List>
</TabPanel>
</Tabs>
</ModalDialog>
</Modal>
</React.Fragment>
);
}
function ColorTokenCreator({ onChange }: { onChange: (name: string, value: string) => void }) {
const [open, setOpen] = React.useState(false);
const nameRef = React.useRef<HTMLInputElement | null>(null);
const colorRef = React.useRef<HTMLInputElement | null>(null);
const [name, setName] = React.useState('');
const [color, setColor] = React.useState('');
if (!open) {
return (
<Button
size="sm"
variant="soft"
color="neutral"
startDecorator={<Add />}
fullWidth
sx={{ mt: 2 }}
onClick={() => {
setOpen(true);
nameRef.current?.focus();
}}
>
Add token
</Button>
);
}
const isValidToken = name.trim() && color.trim();
return (
<Sheet
variant="soft"
color="neutral"
sx={{
borderRadius: 'sm',
my: 1,
p: 1,
display: 'flex',
gap: 1,
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Input
autoFocus
size="sm"
placeholder="Token name/number"
slotProps={{
input: { ref: nameRef },
}}
onChange={(event) => setName(event.target.value)}
/>{' '}
<b>:</b>{' '}
<ColorInput
size="sm"
placeholder="A valid CSS color"
value={color}
onEmptyColor={() => {
setColor('');
}}
onKeyDown={(event) => {
if (event.key === 'Enter' && name && color) {
onChange(name, color);
setOpen(false);
}
}}
onValidColor={(newColor) => {
setColor(newColor);
}}
slotProps={{
input: { ref: colorRef },
}}
sx={{ flexGrow: 1 }}
/>
<IconButton
variant="solid"
color={isValidToken ? 'primary' : 'neutral'}
size="sm"
onClick={() => {
const trimmedName = name.trim();
const trimmedColor = color.trim();
if (!trimmedName) {
nameRef.current?.focus();
} else if (!trimmedColor) {
colorRef.current?.focus();
} else {
onChange(trimmedName, trimmedColor);
setColor('');
setName('');
setOpen(false);
}
}}
>
<Check />
</IconButton>
</Sheet>
);
}
function ColorAutocomplete({
value,
onValidColor,
onEmptyColor,
options,
...props
}: AutocompleteProps<string, false, false, true> & {
onValidColor: (color: string) => void;
onEmptyColor: () => void;
value: string;
options: Array<string>;
}) {
const [showEnter, setShowEnter] = React.useState(false);
return (
<Autocomplete
freeSolo
options={options}
slotProps={{
listbox: {
disablePortal: true,
placement: 'bottom-start',
sx: {
minWidth: 'max-content',
maxHeight: 160,
},
},
}}
renderOption={(optionProps, data) => (
<AutocompleteOption {...optionProps}>
<ColorBubblePreview value={data} sx={{ mr: 0.5 }} />
{data}
</AutocompleteOption>
)}
value={value ?? ''}
blurOnSelect
openOnFocus
{...props}
startDecorator={<ColorBubblePreview value={value || props.placeholder} sx={{ mr: -0.5 }} />}
endDecorator={showEnter ? '⏎' : ''}
onChange={(event, newValue) => {
setShowEnter(false);
if (!newValue) {
onEmptyColor();
} else {
onValidColor(newValue as string);
}
}}
onInputChange={(event, newValue) => {
setShowEnter(newValue !== value);
}}
/>
);
}
function GlobalVariantTokenCreator({
primitiveTokens = [],
availableTokens = [],
onChange,
}: {
primitiveTokens: Array<string>;
availableTokens: Array<string>;
onChange: (name: string, value: string) => void;
}) {
const [open, setOpen] = React.useState(false);
const [name, setName] = React.useState('');
const [color, setColor] = React.useState('');
const inputRef = React.useRef<HTMLInputElement | null>(null);
if (!open) {
return (
<Button
size="sm"
variant="soft"
color="neutral"
startDecorator={<Add />}
fullWidth
sx={{ my: 1 }}
onClick={() => {
setOpen(true);
}}
>
Add token
</Button>
);
}
return (
<Sheet
variant="soft"
color="neutral"
sx={{ borderRadius: 'sm', my: 2, p: 1, display: 'flex', gap: 1, alignItems: 'center' }}
>
<Select
defaultListboxOpen
placeholder="Select a token"
size="sm"
onChange={(event, newValue) => {
setName(newValue as string);
inputRef.current?.focus();
}}
>
{availableTokens.map((item) => (
<Option key={item} value={item}>
{item}
</Option>
))}
</Select>{' '}
<b>:</b>{' '}
<Autocomplete
options={primitiveTokens}
size="sm"
freeSolo
blurOnSelect
slotProps={{
listbox: {
disablePortal: true,
placement: 'bottom-start',
sx: {
minWidth: 'max-content',
maxHeight: 160,
},
},
input: {
ref: inputRef,
},
}}
renderOption={(optionProps, data) => (
<AutocompleteOption {...optionProps}>
<ColorBubblePreview value={data} sx={{ mr: 0.5 }} />
{data}
</AutocompleteOption>
)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
if (name) {
onChange(name, (event.target as EventTarget & HTMLInputElement).value);
setOpen(false);
}
}
}}
onChange={(event, newValue) => setColor(newValue || '')}
onInputChange={(event, newValue) => setColor(newValue)}
sx={{ flex: 1 }}
/>
<IconButton
variant="solid"
color="neutral"
size="sm"
onClick={() => {
if (name) {
onChange(name, color);
setOpen(false);
}
}}
>
<Check />
</IconButton>
</Sheet>
);
}
function filterGlobalVariantTokens(palette: Partial<PaletteVariant>, variant: VariantProp) {
const tokens: Partial<PaletteVariant> = {};
(Object.entries(palette) as Array<[keyof PaletteVariant, string]>).forEach(([key, value]) => {
if (key.match(/^(plain|outlined|soft|solid)/) && key.startsWith(variant)) {
tokens[key] = value;
}
});
return tokens;
}
type StateReducer<T> = (state: T, action: Partial<T>) => T;
function GlobalVariantForm({
color,
themeDefaultValue: themeDefaultValueProp = {},
value: valueProp = {},
availableTokens = [],
onChange,
onRemove,
}: {
availableTokens?: Array<string>;
color: ColorPaletteProp;
themeDefaultValue: any;
value: any;
onChange: (newValue: any) => void;
onRemove: (token: string) => void;
}) {
const [selectedVariant, setSelectedVariant] = React.useState<VariantProp>('solid');
const [states, setStates] = React.useReducer<
StateReducer<{ hover: boolean; active: boolean; disabled: boolean }>
>((prevState, action) => ({ ...prevState, ...action }), {
hover: false,
active: false,
disabled: false,
});
const themeDefaultValue = filterGlobalVariantTokens(themeDefaultValueProp, selectedVariant);
const value = filterGlobalVariantTokens(valueProp, selectedVariant);
const mergedValue = { ...themeDefaultValue, ...value };
const tokens = (Object.keys(mergedValue) as Array<keyof PaletteVariant>).filter(
(k) => mergedValue[k] !== undefined,
);
const allTokens = [
`${selectedVariant}Color`,
`${selectedVariant}HoverColor`,
`${selectedVariant}ActiveColor`,
`${selectedVariant}DisabledColor`,
`${selectedVariant}Bg`,
`${selectedVariant}HoverBg`,
`${selectedVariant}ActiveBg`,
`${selectedVariant}DisabledBg`,
`${selectedVariant}Border`,
`${selectedVariant}HoverBorder`,
`${selectedVariant}ActiveBorder`,
`${selectedVariant}DisabledBorder`,
].filter((item) => !(tokens as Array<string>).includes(item));
return (
<React.Fragment>
<Typography component="div" fontWeight="xl" level="title-md">
Global variant tokens
</Typography>
<Typography component="div" level="body-sm" mb={2} mt={0.5}>
Pick the specific primitive color, now in CSS variables form already, to correspond to a
semantic global variant token.
</Typography>
<Sheet
variant="outlined"
sx={{
bgcolor: 'background.level1',
px: 2,
py: 4,
mt: 1,
mb: 3,
borderRadius: 'sm',
display: 'flex',
flexDirection: 'column',
gap: 4,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Select
variant={selectedVariant}
color={color}
value={selectedVariant}
onChange={(event, newValue) => setSelectedVariant(newValue as VariantProp)}
sx={(theme) => ({
minWidth: 120,
...(states.hover && {
...theme.variants[`${selectedVariant}Hover`][color],
'&:hover, &:active': theme.variants[`${selectedVariant}Hover`][color],
}),
...(states.active && {
...theme.variants[`${selectedVariant}Active`][color],
'&:hover, &:active': theme.variants[`${selectedVariant}Active`][color],
}),
...(states.disabled && theme.variants[`${selectedVariant}Disabled`][color]),
})}
>
<Option value="solid">solid</Option>
<Option value="soft">soft</Option>
<Option value="outlined">outlined</Option>
<Option value="plain">plain</Option>
</Select>
<Box
sx={{
display: 'flex',
gap: 1,
}}
>
<Checkbox
size="sm"
label=":hover"
checked={states.hover}
onChange={(event) => setStates({ hover: event.target.checked })}
/>
<Checkbox
size="sm"
label=":active"
checked={states.active}
onChange={(event) => setStates({ active: event.target.checked })}
/>
<Checkbox
size="sm"
label=":disabled"
checked={states.disabled}
onChange={(event) => setStates({ disabled: event.target.checked })}
/>
</Box>
</Sheet>
<Box
sx={{
my: 1,
display: 'grid',
gridTemplateColumns: 'min-content min-content 1fr',
alignItems: 'center',
gap: '6px 12px',
'& > div': {
display: 'contents',
'--FormLabel-alignSelf': 'center',
'--FormLabel-margin': '0px',
},
}}
>
{tokens.map((item) => (
<FormControl key={item} size="sm">
<IconButton
tabIndex={-1}
variant="outlined"
color="danger"
size="sm"
sx={{ borderRadius: '50%', '--IconButton-size': '24px' }}
onClick={() => {
onChange({ [item]: undefined });
}}
>
<Remove />
</IconButton>
<FormLabel>{item}:</FormLabel>
<ColorAutocomplete
value={value[item] ?? ''}
placeholder={themeDefaultValue[item]?.replace(/, #[0-9a-zA-Z]+/, '')}
options={availableTokens}
onValidColor={(newValue) => {
onChange({ [item]: newValue });
}}
onEmptyColor={() => {
onRemove(item);
}}
onFocus={() => {
if (item.includes('Hover')) {
setStates({ hover: true, active: false, disabled: false });
} else if (item.includes('Active')) {
setStates({ hover: false, active: true, disabled: false });
} else if (item.includes('Disabled')) {
setStates({ hover: false, active: false, disabled: true });
} else {
setStates({ hover: false, active: false, disabled: false });
}
}}
/>
</FormControl>
))}
</Box>
<GlobalVariantTokenCreator
primitiveTokens={availableTokens}
availableTokens={allTokens}
onChange={(token, newValue) => onChange({ [token]: newValue })}
/>
</React.Fragment>
);
}
function ColorPaletteForm({
tokens = [],
availableTokens = [],
themeDefaultValue = {},
value = {},
onChange,
onRemove,
}: {
availableTokens?: Array<string>;
tokens: Array<string>;
themeDefaultValue: any;
value: any;
onChange: (newValue: any) => void;
onRemove: (token: string) => void;
}) {
return (
<React.Fragment>
<Box
sx={{
mt: 1.5,
display: 'grid',
gridTemplateColumns: 'min-content minmax(min-content, 64px) 1fr',
alignItems: 'center',
gap: '6px 12px',
'& > div': {
display: 'contents',
'--FormLabel-alignSelf': 'center',
'--FormLabel-margin': '0px',
},
}}
>
{tokens.map((item) => (
<FormControl key={item} size="sm">
<IconButton
tabIndex={-1}
variant="outlined"
color="danger"
size="sm"
sx={{ borderRadius: '50%', '--IconButton-size': '24px' }}
onClick={() => {
if (themeDefaultValue[item]) {
onChange({ [item]: undefined });
} else {
onRemove(item);
}
}}
>
<Remove />
</IconButton>
<FormLabel>{item}:</FormLabel>
{availableTokens.length > 0 ? (
<ColorAutocomplete
value={value[item] ?? ''}
placeholder={themeDefaultValue[item]?.replace(/, #[0-9a-zA-Z]+/, '')}
options={availableTokens}
onValidColor={(newValue) => {
onChange({ [item]: newValue });
}}
onEmptyColor={() => {
onRemove(item);
}}
/>
) : (
<ColorInput
value={value[item] ?? ''}
placeholder={themeDefaultValue[item]?.replace(/, #[0-9a-zA-Z]+/, '')}
onEmptyColor={() => {
onRemove(item);
}}
onValidColor={(color) => {
onChange({ [item]: color });
}}
/>
)}
</FormControl>
))}
</Box>
<ColorTokenCreator
onChange={(name, color) => {
onChange({ [name]: color });
}}
/>
</React.Fragment>
);
}
function getAvailableTokens(colorSchemes: any, colorMode: 'light' | 'dark') {
const palette = deepmerge(
defaultTheme.colorSchemes[colorMode].palette,
colorSchemes[colorMode].palette,
);
const tokens: Array<string> = [];
function iterateObject(object: any, keys: Array<string> = []) {
Object.keys(object).forEach((k) => {
if (object[k] && !k.match(/^(mode|colorScheme)$/)) {
if (typeof object[k] === 'object') {
iterateObject(object[k], [...keys, k]);
} else {
tokens.push(`var(--joy-palette-${[...keys, k].join('-')})`);
}
}
});
}
iterateObject(palette);
return tokens;
}
function TemplatesDialog({ children, data }: { children: React.ReactElement; data: any }) {
const [open, setOpen] = React.useState(false);
const { map: templateMap } = sourceJoyTemplates();
const renderItem = (name: string, item: TemplateData) => {
if (!item.files) {
return null;
}
const themeFileName =
Object.keys(item.files).find((file) => file.match(/theme\.(ts|tsx|js)/)) || 'theme.ts';
const themeFile = item.files[themeFileName];
const customTheme = literalToObject(themeFile?.match(/extendTheme\({(.*)}\)/s)?.[1]);
const mergedData = deepmerge(customTheme, data);
const newFiles = {
...item.files,
[themeFileName]: generateThemeCode(mergedData),
};
return (
<Card component="li" size="sm" variant="outlined" key={name} sx={{ '--Card-padding': '0px' }}>
<AspectRatio ratio="2">
<Box
sx={(theme) => ({
background: `center/cover no-repeat url(/static/screenshots/joy-ui/getting-started/templates/${name}.jpg)`,
transition: '0.3s',
[theme.getColorSchemeSelector('dark')]: {
background: `center/cover no-repeat url(/static/screenshots/joy-ui/getting-started/templates/${name}-dark.jpg)`,
},
})}
/>
</AspectRatio>
<CardCover
sx={{
opacity: 0,
transition: '0.2s',
'&:hover, &:focus-within': {
opacity: 1,
bgcolor: 'rgba(0 0 0 / 0.72)',
boxShadow: 'md',
},
}}
>
<div>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<Link
component="button"
fontSize="xl"
fontWeight="xl"
color="neutral"
textColor="#fff"
overlay
onClick={() => {
codeSandbox
.createJoyTemplate({
...item,
files: newFiles,
githubLocation: '',
title: `Joy UI - Custom theme`,
codeVariant: 'TS',
})
.openSandbox();
}}
endDecorator={<ArrowOutwardIcon sx={{ color: 'inherit', opacity: 0.72 }} />}
>
{startCase(name)}
</Link>
</div>
</CardCover>
</Card>
);
};
return (
<React.Fragment>
{React.cloneElement(children, {
onClick: () => {
setOpen(true);
children.props.onClick?.();
},
})}
<Modal open={open} onClose={() => setOpen(false)}>
<ModalDialog
size="lg"
aria-labelledby="templates-dialog"
aria-describedby="templates-dialog-description"
sx={{ '--ModalDialog-minWidth': '1200px' }}
>
<ModalClose />
<Typography level="h2" id="templates-dialog">
Clone a template sandbox
</Typography>
<Typography id="templates-dialog-description" textColor="text.secondary" fontSize="md">
Click on one of these template to see start a sandbox with your custom theme.
</Typography>
<List
sx={{
px: 1,
overflow: 'auto',
flexGrow: 1,
gap: 4,
height: 'max-content',
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
'--Icon-color': (theme) => theme.vars.palette.text.tertiary,
}}
>
<Card
variant="outlined"
sx={{
borderStyle: 'dashed',
'--variant-borderWidth': '2px',
justifyContent: 'center',
alignItems: 'center',
}}
>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<Link
component="button"
fontSize="lg"
fontWeight="lg"
color="neutral"
textColor="text.primary"
overlay
onClick={() => {
const { result } = extractTemplates({
'./result/App.tsx': getMinimalJoyTemplate(),
'./result/theme.ts': generateThemeCode(data),
});
codeSandbox
.createJoyTemplate({
...result,
codeVariant: 'TS',
githubLocation: '',
title: `Joy UI - Minimal template`,
})
.openSandbox();
}}
endDecorator={<ArrowOutwardIcon />}
>
Minimal template
</Link>
<Typography textColor="text.tertiary">Build your next project with Joy!</Typography>
</Card>
{Array.from(templateMap.entries()).map(([name, template]) =>
renderItem(name, template),
)}
</List>
</ModalDialog>
</Modal>
</React.Fragment>
);
}
export default function JoyThemeBuilder() {
const muiTheme = useMuiTheme();
const [showCode, setShowCode] = React.useState(false);
const [colorMode, setColorMode] = React.useState<'light' | 'dark'>('light');
const [lightPalette, setLightPalette] = React.useState<Record<string, any>>({});
const [darkPalette, setDarkPalette] = React.useState<Record<string, any>>({});
const [colorProp, setColorProp] = React.useState<ColorPaletteProp | 'etc'>('primary');
const availableTokens = React.useMemo(
() => getAvailableTokens({ light: lightPalette, dark: darkPalette }, colorMode),
[lightPalette, darkPalette, colorMode],
);
const setter = { light: setLightPalette, dark: setDarkPalette }[colorMode];
const theme = React.useMemo(
() =>
extendTheme({
colorSchemes: {
light: {
palette: lightPalette,
},
dark: {
palette: darkPalette,
},
},
}),
[lightPalette, darkPalette],
);
const data = {
colorSchemes: {
light: {
palette: lightPalette,
},
dark: {
palette: darkPalette,
},
},
};
React.useEffect(() => {
setColorMode(muiTheme.palette.mode);
}, [muiTheme.palette.mode, setColorMode]);
return (
<CssVarsProvider theme={theme}>
{showCode && (
<CodeBlockResult
data-joy-color-scheme={muiTheme.palette.mode}
data={data}
onClose={() => setShowCode(false)}
/>
)}
{!showCode && (
<Box
data-joy-color-scheme={muiTheme.palette.mode}
sx={{
p: 1,
border: '1px solid',
borderBottomWidth: 0,
borderColor: 'divider',
bgcolor: 'background.surface',
display: 'flex',
gap: 1,
borderRadius: '8px 8px 0 0',
}}
>
<ToggleButtonGroup
size="sm"
value={colorMode}
onChange={(event, newValue) => setColorMode(newValue as 'light' | 'dark')}
>
<Button value="light">
<LightMode />
Light
</Button>
<Button value="dark">
<DarkMode />
Dark
</Button>
</ToggleButtonGroup>
<IconButton
size="sm"
variant="outlined"
color="neutral"
sx={{ ml: 'auto', minWidth: '38px' }}
onClick={() => setShowCode(true)}
>
<Code />
</IconButton>
<TemplatesDialog data={data}>
<IconButton variant="solid" color="neutral" size="sm" sx={{ minWidth: '38px' }}>
<SvgIcon viewBox="0 0 1080 1080">
<path d="M755 140.3l0.5-0.3h0.3L512 0 268.3 140h-0.3l0.8 0.4L68.6 256v512L512 1024l443.4-256V256L755 140.3z m-30 506.4v171.2L548 920.1V534.7L883.4 341v215.7l-158.4 90z m-584.4-90.6V340.8L476 534.4v385.7L300 818.5V646.7l-159.4-90.6zM511.7 280l171.1-98.3 166.3 96-336.9 194.5-337-194.6 165.7-95.7L511.7 280z" />
</SvgIcon>
</IconButton>
</TemplatesDialog>
</Box>
)}
{!showCode && (
<Sheet
data-joy-color-scheme={colorMode}
variant="outlined"
sx={{ display: 'flex', borderRadius: '0 0 8px 8px', overflow: 'auto' }}
>
<List
sx={{
flexBasis: 256,
flexGrow: 0,
'--ListDivider-gap': '0px',
'--ListItem-minHeight': '56px',
'--ListItemDecorator-size': '32px',
}}
>
<ListSubheader sx={{ minHeight: 48 }}>Palette</ListSubheader>
{(['primary', 'neutral', 'danger', 'success', 'warning'] as const).map((color) => (
<React.Fragment key={color}>
<ListItem>
<ListItemButton
{...(colorProp === color && {
variant: 'soft',
selected: true,
color,
})}
onClick={() => setColorProp(color)}
>
<ListItemDecorator>
<Box
sx={{
width: 20,
height: 20,
borderRadius: '50%',
bgcolor: `${color}.500`,
}}
/>
</ListItemDecorator>
<ListItemContent sx={{ fontSize: 'sm' }}>{color}</ListItemContent>
<KeyboardArrowRight />
</ListItemButton>
</ListItem>
<ListDivider />
</React.Fragment>
))}
<ListItem>
<ListItemButton
{...(colorProp === 'etc' && {
variant: 'soft',
color: 'neutral',
selected: true,
})}
onClick={() => setColorProp('etc')}
>
<ListItemContent sx={{ fontSize: 'sm' }}>text, background, etc.</ListItemContent>
</ListItemButton>
</ListItem>
<ListDivider />
</List>
<Divider orientation="vertical" />
{(() => {
if (colorProp === 'etc') {
return (
<Box sx={{ p: 3, flex: 1 }}>
<Typography fontSize="sm" fontWeight="lg">
background
</Typography>
<ColorPaletteForm
availableTokens={availableTokens}
{...getPaletteFormProps(
{ light: lightPalette, dark: darkPalette },
colorMode,
'background',
)}
onChange={(newValue) => {
setter((prev) => ({
...prev,
background: { ...prev.background, ...newValue },
}));
}}
onRemove={(token) => {
setter((prev) => {
const newPalette = prev.background || {};
delete newPalette[token];
return { ...prev, background: newPalette };
});
}}
/>
<Typography fontSize="sm" fontWeight="lg" mt={2}>
common
</Typography>
<ColorPaletteForm
availableTokens={availableTokens}
{...getPaletteFormProps(
{ light: lightPalette, dark: darkPalette },
colorMode,
'common',
)}
onChange={(newValue) => {
setter((prev) => ({
...prev,
common: { ...prev.common, ...newValue },
}));
}}
onRemove={(token) => {
setter((prev) => {
const newPalette = prev.common || {};
delete newPalette[token];
return { ...prev, common: newPalette };
});
}}
/>
<Typography fontSize="sm" fontWeight="lg" mt={2}>
text
</Typography>
<ColorPaletteForm
availableTokens={availableTokens}
{...getPaletteFormProps(
{ light: lightPalette, dark: darkPalette },
colorMode,
'text',
)}
onChange={(newValue) => {
setter((prev) => ({
...prev,
text: { ...prev.text, ...newValue },
}));
}}
onRemove={(token) => {
setter((prev) => {
const newPalette = prev.text || {};
delete newPalette[token];
return { ...prev, text: newPalette };
});
}}
/>
</Box>
);
}
const { mergedValue, ...formProps } = getPaletteFormProps(
{ light: lightPalette, dark: darkPalette },
colorMode,
colorProp,
);
const primitives = Object.keys(mergedValue)
.filter((k) => !k.match(/Channel$/) && !k.match(/^(plain|outlined|soft|solid)/))
.filter((k) => mergedValue[k] !== undefined);
return (
<Tabs
size="md"
defaultValue={0}
sx={{ flex: 1, [`& .${tabPanelClasses.root}`]: { p: 3 } }}
>
<TabList variant="plain">
<Tab>Primitive colors</Tab>
<Tab>Global variants</Tab>
</TabList>
<TabPanel value={0}>
<Typography component="div" fontWeight="xl" level="title-md">
Customize primitive colors
</Typography>
<Typography component="div" level="body-sm" mb={2} mt={0.5}>
Add your custom-tailored palette here, inserting each HEX value to the scale, or
choose from an available set of popular color palettes.
</Typography>
<PaletteImport
colorMode={muiTheme.palette.mode}
onSelect={(newTokens) => {
setter((prev) => ({
...prev,
[colorProp]: { ...prev[colorProp], ...newTokens },
}));
}}
/>
<ColorPaletteForm
{...formProps}
tokens={primitives}
onChange={(newValue) => {
setter((prev) => ({
...prev,
[colorProp]: { ...prev[colorProp], ...newValue },
}));
}}
onRemove={(token) => {
setter((prev) => {
const newPalette = prev[colorProp] || {};
delete newPalette[token];
return { ...prev, [colorProp]: newPalette };
});
}}
/>
</TabPanel>
<TabPanel value={1}>
<GlobalVariantForm
color={colorProp}
availableTokens={availableTokens}
themeDefaultValue={defaultTheme.colorSchemes[colorMode].palette[colorProp]}
value={{ light: lightPalette, dark: darkPalette }[colorMode][colorProp]}
onChange={(newValue) => {
setter((prev) => ({
...prev,
[colorProp]: { ...prev[colorProp], ...newValue },
}));
}}
onRemove={(token) => {
setter((prev) => {
const newPalette = prev[colorProp] || {};
delete newPalette[token];
return { ...prev, [colorProp]: newPalette };
});
}}
/>
</TabPanel>
</Tabs>
);
})()}
</Sheet>
)}
<Box sx={{ height: 200 }} />
</CssVarsProvider>
);
}
| 5,293 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/JoyUsageDemo.tsx | import * as React from 'react';
import Check from '@mui/icons-material/Check';
import CheckRounded from '@mui/icons-material/CheckRounded';
import ReplayRoundedIcon from '@mui/icons-material/ReplayRounded';
import Box from '@mui/joy/Box';
import Divider from '@mui/joy/Divider';
import Chip from '@mui/joy/Chip';
import FormControl from '@mui/joy/FormControl';
import FormLabel, { formLabelClasses } from '@mui/joy/FormLabel';
import FormHelperText from '@mui/joy/FormHelperText';
import IconButton from '@mui/joy/IconButton';
import Input, { inputClasses } from '@mui/joy/Input';
import ListItemDecorator, { listItemDecoratorClasses } from '@mui/joy/ListItemDecorator';
import Option, { optionClasses } from '@mui/joy/Option';
import Radio, { radioClasses } from '@mui/joy/Radio';
import RadioGroup from '@mui/joy/RadioGroup';
import Select from '@mui/joy/Select';
import Sheet from '@mui/joy/Sheet';
import Switch from '@mui/joy/Switch';
import Typography from '@mui/joy/Typography';
import BrandingProvider from 'docs/src/BrandingProvider';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
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]}"`
}`;
}
}
if (prop[0] === 'children') {
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');
};
interface JoyUsageDemoProps<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;
/**
* The string to be displayed in the form label.
* If not provided, the `propName` is displayed as Pascal case.
*/
formLabel?: string;
/**
* The helper text to be displayed for the knob.
*/
helperText?: string;
}>;
/**
* A function to override the code block result.
*/
getCodeBlock?: (code: string, props: ComponentProps) => string;
renderDemo: (props: ComponentProps) => React.ReactElement;
}
export default function JoyUsageDemo<T extends { [k: string]: any } = {}>({
componentName,
childrenAccepted = false,
data,
renderDemo,
getCodeBlock = defaultGetCodeBlock,
}: JoyUsageDemoProps<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];
}
});
return (
<Box
sx={{
flexGrow: 1,
maxWidth: '100%',
display: 'flex',
flexDirection: { xs: 'column', md: 'row' },
'& .markdown-body pre': {
margin: 0,
borderRadius: 'md',
},
}}
>
<Box
sx={(theme) => ({
display: 'flex',
flexDirection: 'column',
flexGrow: 999,
minWidth: 0,
p: 3,
bgcolor: '#FFF',
[theme.getColorSchemeSelector('dark')]: {
backgroundColor: theme.palette.neutral[900],
},
})}
>
<Box
sx={{
flexGrow: 1,
m: 'auto',
display: 'flex',
alignItems: 'center',
}}
>
{renderDemo(demoProps)}
</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>
<Sheet
sx={(theme) => ({
flexShrink: 0,
gap: 2,
borderLeft: '1px solid',
borderColor: `rgba(${theme.vars.palette.neutral.mainChannel} / 0.1)`,
background: `rgba(${theme.vars.palette.primary.mainChannel} / 0.02)`,
backdropFilter: 'blur(8px)',
minWidth: '280px',
})}
>
<Box
sx={{
px: 3,
py: 2,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Typography
id="usage-props"
component="h3"
fontWeight="lg"
sx={{ scrollMarginTop: 160, fontFamily: 'General Sans' }}
>
Playground
</Typography>
<IconButton
aria-label="Reset all"
variant="outlined"
color="primary"
size="sm"
onClick={() => setProps(initialProps as T)}
sx={{
visibility: !shallowEqual(props, initialProps) ? 'visible' : 'hidden',
'--IconButton-size': '30px',
}}
>
<ReplayRoundedIcon />
</IconButton>
</Box>
<Divider sx={{ opacity: 0.5 }} />
<Box
sx={{
p: 3,
display: 'flex',
flexDirection: 'column',
gap: 3,
[`& .${formLabelClasses.root}`]: {
fontWeight: 'lg',
},
}}
>
{data.map(
({
propName,
formLabel = propName,
knob,
options = [],
defaultValue,
labels,
helperText,
}) => {
const resolvedValue = props[propName] ?? defaultValue;
if (!knob) {
return null;
}
if (knob === 'switch') {
return (
<FormControl
key={propName}
size="sm"
sx={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center' }}
>
<FormLabel sx={{ textTransform: 'capitalize', mb: 0 }}>{formLabel}</FormLabel>
<Switch
checked={Boolean(resolvedValue)}
onChange={(event) =>
setProps((latestProps) => ({
...latestProps,
[propName]: event.target.checked,
}))
}
sx={{
'--Switch-trackWidth': '32px',
'--Switch-trackBackground': (theme) =>
`rgba(${theme.vars.palette.neutral.mainChannel} / 0.3)`,
'&:hover': {
'--Switch-trackBackground': (theme) =>
`rgba(${theme.vars.palette.neutral.mainChannel} / 0.5)`,
},
}}
/>
{helperText && (
<FormHelperText sx={{ gridColumn: 'span 2', m: 0 }}>
{helperText}
</FormHelperText>
)}
</FormControl>
);
}
if (knob === 'radio') {
const labelId = `${componentName}-${propName}`;
return (
<FormControl key={propName} size="sm">
<FormLabel sx={{ textTransform: 'capitalize' }}>{formLabel}</FormLabel>
<RadioGroup
orientation="horizontal"
name={labelId}
value={resolvedValue}
onChange={(event) => {
let value: string | boolean | undefined = event.target.value;
if (value === 'true') {
value = true;
} else if (value === 'false') {
value = false;
} else if (value === 'undefined') {
value = undefined;
}
setProps((latestProps) => ({
...latestProps,
[propName]: value,
}));
}}
sx={{ flexWrap: 'wrap', gap: 1, '--unstable_RadioGroup-margin': 0 }}
>
{options.map((value: string, index: number) => {
const checked = String(resolvedValue) === value;
return (
<Chip
key={value}
variant="plain"
color={checked ? 'primary' : 'neutral'}
size="sm"
sx={{ bgcolor: 'background.body' }}
>
<Radio
size="sm"
variant={checked ? 'solid' : 'outlined'}
color={checked ? 'primary' : 'neutral'}
label={<Typography>{labels?.[index] || value}</Typography>}
value={value}
disableIcon
overlay
/>
</Chip>
);
})}
</RadioGroup>
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}
if (knob === 'controlled') {
const labelId = `${componentName}-${propName}`;
const finalValue =
resolvedValue === undefined ? 'uncontrolled' : String(resolvedValue);
return (
<FormControl key={propName} size="sm">
<FormLabel sx={{ textTransform: 'capitalize' }}>{formLabel}</FormLabel>
<RadioGroup
orientation="horizontal"
name={labelId}
value={finalValue}
onChange={(event) => {
let value: string | boolean | undefined = event.target.value;
if (value === 'true') {
value = true;
} else if (value === 'false') {
value = false;
} else if (value === 'uncontrolled') {
value = undefined;
}
setProps((latestProps) => ({
...latestProps,
[propName]: value,
}));
}}
sx={{ flexWrap: 'wrap', gap: 1 }}
>
{['uncontrolled', 'true', 'false'].map((value, index) => {
const checked = finalValue === value;
return (
<Chip
key={value}
variant="plain"
color={checked ? 'primary' : 'neutral'}
size="sm"
sx={{ bgcolor: 'background.body' }}
>
<Radio
size="sm"
variant={checked ? 'solid' : 'outlined'}
color={checked ? 'primary' : 'neutral'}
label={<Typography>{labels?.[index] || value}</Typography>}
value={value}
disableIcon
overlay
/>
</Chip>
);
})}
</RadioGroup>
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}
if (knob === 'color') {
return (
<FormControl key={propName} sx={{ mb: 1 }} size="sm">
<FormLabel sx={{ textTransform: 'capitalize' }}>{formLabel}</FormLabel>
<RadioGroup
orientation="horizontal"
name={`${componentName}-color`}
value={resolvedValue || ''}
onChange={(event) =>
setProps((latestProps) => ({
...latestProps,
[propName || 'color']: event.target.value,
}))
}
sx={{ flexWrap: 'wrap', gap: 1.5, '--unstable_RadioGroup-margin': 0 }}
>
{(['primary', 'neutral', 'danger', 'success', 'warning'] as const).map(
(value) => {
const checked = resolvedValue === value;
return (
<Sheet
key={value}
variant="solid"
color={value}
sx={{
width: 26,
height: 26,
borderRadius: 'xl',
textTransform: 'capitalize',
}}
>
<Radio
variant="solid"
color={value}
label={value}
value={value}
disableIcon
overlay
sx={{
// [`& .${radioClasses.action}`]: { bgcolor: `${value}.500` },
[`& .${radioClasses.label}`]: {
fontSize: '10px',
color: 'text.secondary',
position: 'absolute',
bottom: '-1rem',
left: '50%',
transform: 'translateX(-50%)',
opacity: '0.01', // prevent double for touch device.
transition: '0.2s',
},
[`&:hover, &.${radioClasses.focusVisible}, &.${radioClasses.checked}`]:
{
[`& .${radioClasses.label}`]: {
opacity: 1,
bottom: '-1.25rem',
},
},
}}
/>
{checked && (
<Check
fontSize="md"
color="inherit"
sx={{
zIndex: 1,
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
pointerEvents: 'none',
}}
/>
)}
</Sheet>
);
},
)}
</RadioGroup>
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}
if (knob === 'select') {
return (
<FormControl key={propName} size="sm">
<FormLabel sx={{ textTransform: 'capitalize' }}>{formLabel}</FormLabel>
<Select
placeholder="Select a variant..."
slotProps={{
listbox: {
sx: {
'--ListItemDecorator-size': '24px',
},
},
}}
value={(resolvedValue || 'none') as string}
onChange={(event, val) =>
setProps((latestProps) => ({
...latestProps,
[propName]: val,
}))
}
>
{options.map((value) => (
<Option
key={value}
value={value}
label={value}
sx={{
[`&.${optionClasses.selected}`]: {
[`& .${listItemDecoratorClasses.root}`]: {
opacity: 1,
},
},
}}
>
<ListItemDecorator sx={{ opacity: 0 }}>
<CheckRounded />
</ListItemDecorator>
{value}
</Option>
))}
</Select>
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}
if (knob === 'input') {
return (
<FormControl key={propName} size="sm">
<FormLabel sx={{ textTransform: 'capitalize' }}>{formLabel}</FormLabel>
<Input
size="sm"
value={props[propName] ?? ''}
onChange={(event) =>
setProps((latestProps) => ({
...latestProps,
[propName]: event.target.value,
}))
}
sx={{
textTransform: 'capitalize',
[`& .${inputClasses.root}`]: {
bgcolor: 'background.body',
},
}}
/>
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}
if (knob === 'number') {
return (
<FormControl key={propName} size="sm">
<FormLabel sx={{ textTransform: 'capitalize' }}>{formLabel}</FormLabel>
<Input
size="sm"
type="number"
value={
typeof props[propName] === 'number'
? (props[propName] as number)
: (defaultValue as string)
}
onChange={(event) =>
setProps((latestProps) => ({
...latestProps,
[propName]: Number.isNaN(event.target.valueAsNumber)
? undefined
: event.target.valueAsNumber,
}))
}
sx={{
textTransform: 'capitalize',
[`& .${inputClasses.root}`]: {
bgcolor: 'background.body',
},
}}
/>
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}
if (knob === 'placement') {
return (
<FormControl key={propName}>
<FormLabel sx={{ textTransform: 'capitalize' }}>{formLabel}</FormLabel>
<RadioGroup
name="placement"
value={resolvedValue}
onChange={(event) =>
setProps((latestProps) => ({
...latestProps,
[propName]: event.target.value,
}))
}
>
<Box
sx={{
display: 'grid',
gridTemplateColumns: '40px 1fr 1fr 1fr 40px',
gridTemplateRows: 'repeat(5, 20px)',
gridAutoFlow: 'row dense',
alignItems: 'center',
}}
>
<Box
sx={{
gridRow: '2 / -2',
gridColumn: '2 / -2',
fontSize: 'sm',
border: '1px solid',
borderColor: 'divider',
borderRadius: 'sm',
alignSelf: 'stretch',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontWeight: 'md',
color: 'text.secondary',
}}
>
{resolvedValue}
</Box>
{/* void */}
<div />
<Box sx={{ gridColumn: '-1 / -2', gridRow: '1' }} />
<Box sx={{ gridRow: '-1 / -2', gridColumn: '1' }} />
{/* void */}
{[
'top-start',
'top',
'top-end',
'left-start',
'right-start',
'left',
'right',
'left-end',
'right-end',
'bottom-start',
'bottom',
'bottom-end',
].map((placement) => (
<Sheet
key={placement}
variant="soft"
color="primary"
sx={{
position: 'relative',
height: '14px',
width: 32,
borderRadius: 'xs',
mx: 0.5,
...(placement.match(/^(top|bottom)$/) && {
justifySelf: 'center',
}),
...(placement.match(/^(top-end|bottom-end)$/) && {
justifySelf: 'flex-end',
}),
}}
>
<Radio
value={placement}
overlay
disableIcon
slotProps={{
action: ({ checked }) => ({
sx: (theme) => ({
...(checked && {
...theme.variants.solid.primary,
'&:hover': theme.variants.solid.primary,
}),
}),
}),
}}
/>
</Sheet>
))}
</Box>
</RadioGroup>
{helperText && <FormHelperText>{helperText}</FormHelperText>}
</FormControl>
);
}
return null;
},
)}
</Box>
</Sheet>
</Box>
);
}
| 5,294 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/JoyVariablesDemo.tsx | import * as React from 'react';
import Box from '@mui/joy/Box';
import Divider from '@mui/joy/Divider';
import Link from '@mui/joy/Link';
import List from '@mui/joy/List';
import IconButton from '@mui/joy/IconButton';
import Typography from '@mui/joy/Typography';
import Sheet from '@mui/joy/Sheet';
import FormControl from '@mui/joy/FormControl';
import FormLabel from '@mui/joy/FormLabel';
import FormHelperText from '@mui/joy/FormHelperText';
import Input, { inputClasses } from '@mui/joy/Input';
import ReplayRoundedIcon from '@mui/icons-material/ReplayRounded';
import KeyboardArrowDown from '@mui/icons-material/KeyboardArrowDown';
import HighlightedCode from 'docs/src/modules/components/HighlightedCode';
import BrandingProvider from 'docs/src/BrandingProvider';
interface DataItem {
var: string;
defaultValue?: string | number;
helperText?: string;
inputAttributes?: React.InputHTMLAttributes<HTMLInputElement>;
}
function formatSx(sx: { [k: string]: string | number }) {
const lines = Object.keys(sx);
if (!lines.length) {
return '';
}
return `\n sx={${JSON.stringify(sx, null, 4)}}`.replace('}}', ' }}\n');
}
interface SlotVariablesProps {
slot: string;
data: Array<DataItem>;
renderField: (item: DataItem) => React.ReactElement;
defaultOpen?: boolean;
}
function SlotVariables({ slot, data, renderField, defaultOpen = false }: SlotVariablesProps) {
const [open, setOpen] = React.useState(defaultOpen);
return (
<React.Fragment>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<Link
id={`accordion-${slot}`}
aria-expanded={open ? 'true' : 'false'}
aria-controls={`section-${slot}`}
component="button"
underline="none"
fontSize="sm"
fontWeight="lg"
endDecorator={
<KeyboardArrowDown
sx={{ transition: '0.2s', transform: open ? 'rotate(-180deg)' : undefined }}
/>
}
onClick={() => setOpen(!open)}
sx={{
pb: 1,
justifyContent: 'space-between',
color: open ? 'text.primary' : 'text.tertiary',
}}
>
{slot}
</Link>
{open && (
<Box
hidden={open}
role="region"
aria-labelledby={`accordion-${slot}`}
id={`section-${slot}`}
sx={{
display: 'flex',
flexDirection: 'column',
flexWrap: 'wrap',
gap: 1,
}}
>
{data.map((item) => renderField(item))}
</Box>
)}
</React.Fragment>
);
}
export default function JoyVariablesDemo(props: {
componentName: string;
childrenAccepted?: boolean;
data: Array<DataItem | [string, Array<DataItem>, { defaultOpen?: boolean } | undefined]>;
renderDemo: (sx: { [k: string]: string | number }) => React.ReactElement;
renderCode?: (formattedSx: string) => string;
}) {
const { componentName, data = [], childrenAccepted = false, renderCode } = props;
const [sx, setSx] = React.useState<{ [k: string]: string | number }>({});
return (
<Box
sx={{
flexGrow: 1,
maxWidth: '100%',
display: 'flex',
flexDirection: { xs: 'column', md: 'row' },
'& .markdown-body pre': {
margin: 0,
borderRadius: 'md',
},
}}
>
<Box
sx={(theme) => ({
display: 'flex',
flexDirection: 'column',
flexGrow: 999,
minWidth: 0,
p: 3,
gap: 3,
bgcolor: '#FFF',
[theme.getColorSchemeSelector('dark')]: {
backgroundColor: theme.palette.neutral[900],
},
})}
>
<Box
sx={{
flexGrow: 1,
m: 'auto',
display: 'flex',
alignItems: 'center',
}}
>
{props.renderDemo(sx)}
</Box>
<BrandingProvider mode="dark">
<HighlightedCode
code={
renderCode
? renderCode(formatSx(sx))
: `<${componentName} ${formatSx(sx)}${childrenAccepted ? '>' : '/>'}`
}
language="jsx"
sx={{ display: { xs: 'none', md: 'block' } }}
/>
</BrandingProvider>
</Box>
<Sheet
sx={(theme) => ({
flexShrink: 0,
gap: 2,
borderLeft: '1px solid',
borderColor: `rgba(${theme.vars.palette.neutral.mainChannel} / 0.1)`,
background: `rgba(${theme.vars.palette.primary.mainChannel} / 0.02)`,
backdropFilter: 'blur(8px)',
minWidth: '280px',
})}
>
<List component="div">
<Box
sx={{
px: 3,
pt: 1,
pb: 2,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Typography fontWeight="lg" sx={{ fontFamily: 'General Sans' }}>
CSS variables
</Typography>
<IconButton
aria-label="Reset all"
variant="outlined"
color="primary"
size="sm"
onClick={() => setSx({})}
sx={{
visibility: Object.keys(sx).length > 1 ? 'visible' : 'hidden',
'--IconButton-size': '30px',
}}
>
<ReplayRoundedIcon />
</IconButton>
</Box>
<Divider sx={{ opacity: 0.5 }} />
<Box
sx={{
p: 3,
display: 'flex',
flexDirection: 'column',
gap: 1,
}}
>
{data.map((dataItem) => {
function renderField(item: DataItem) {
const resolvedValue = sx[item.var] || item.defaultValue;
const resolvedInputAttributes = item.inputAttributes || {};
return (
<FormControl key={item.var}>
<FormLabel
sx={{ fontFamily: 'Menlo, Consolas', '--FormLabel-fontSize': '0.75rem' }}
>
{item.var}
</FormLabel>
<Input
size="sm"
variant="outlined"
value={Number(`${resolvedValue}`?.replace('px', '')) || ''}
slotProps={{
input: { ...resolvedInputAttributes },
}}
endDecorator={
<React.Fragment>
{typeof resolvedValue === 'string' && (
<Typography level="body-xs" mr={0.5}>
px
</Typography>
)}
<IconButton
tabIndex={-1}
variant="plain"
color="neutral"
disabled={!sx[item.var] && sx[item.var] !== item.defaultValue}
onClick={() =>
setSx((prevSx) => {
const newSx = { ...prevSx };
delete newSx[item.var];
return newSx;
})
}
>
<ReplayRoundedIcon fontSize="sm" />
</IconButton>
</React.Fragment>
}
type="number"
onKeyDown={(event) => {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z') {
setSx((prevSx) => {
const newSx = { ...prevSx };
delete newSx[item.var];
return newSx;
});
}
}}
onChange={(event) => {
const { value } = event.target;
setSx((prevSx) => {
if (!value) {
const newSx = { ...prevSx };
// @ts-ignore
delete newSx[item.var];
return newSx;
}
return {
...prevSx,
[item.var]:
typeof resolvedValue === 'number' ? Number(value) : `${value}px`,
};
});
}}
sx={{
minWidth: 0,
flexGrow: 1,
[`& .${inputClasses.root}`]: { '--Input-paddingInline': '0.5rem' },
[`& .${inputClasses.endDecorator}`]: { alignItems: 'center' },
}}
/>
<FormHelperText sx={{ mb: 1, '--FormHelperText-fontSize': '0.75rem' }}>
{item.helperText}
</FormHelperText>
</FormControl>
);
}
if (Array.isArray(dataItem)) {
const [slot, slotData, options] = dataItem;
return [
<SlotVariables
key="variables"
slot={slot}
data={slotData}
renderField={renderField}
{...options}
/>,
];
}
return renderField(dataItem);
})}
</Box>
</List>
</Sheet>
</Box>
);
}
| 5,295 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/Link.d.ts | import { LinkProps as MuiLinkProps } from '@mui/material/Link';
import { LinkProps } from 'next/link';
export default function Link(props: LinkProps & MuiLinkProps): JSX.Element;
| 5,296 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/Link.tsx | import * as React from 'react';
import clsx from 'clsx';
import { useRouter } from 'next/router';
import NextLink, { LinkProps as NextLinkProps } from 'next/link';
import MuiLink, { LinkProps as MuiLinkProps } from '@mui/material/Link';
import { styled } from '@mui/material/styles';
import { useUserLanguage } from 'docs/src/modules/utils/i18n';
import { LANGUAGES_IGNORE_PAGES } from 'docs/config';
/**
* File to keep in sync with:
*
* - /docs/src/modules/components/Link.tsx
* - /examples/material-ui-nextjs-pages-router/src/Link.js
* - /examples/material-ui-nextjs-pages-router-ts/src/Link.tsx
*/
// Add support for the sx prop for consistency with the other branches.
const Anchor = styled('a')({});
interface NextLinkComposedProps
extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>,
Omit<NextLinkProps, 'href' | 'as' | 'passHref' | 'onMouseEnter' | 'onClick' | 'onTouchStart'> {
to: NextLinkProps['href'];
linkAs?: NextLinkProps['as'];
}
const NextLinkComposed = React.forwardRef<HTMLAnchorElement, NextLinkComposedProps>(
function NextLinkComposed(props, ref) {
const {
to,
linkAs,
replace,
scroll,
shallow,
prefetch,
legacyBehavior = true,
locale,
...other
} = props;
return (
<NextLink
href={to}
prefetch={prefetch}
as={linkAs}
replace={replace}
scroll={scroll}
shallow={shallow}
passHref
locale={locale}
legacyBehavior={legacyBehavior}
>
<Anchor data-no-markdown-link="true" ref={ref} {...other} />
</NextLink>
);
},
);
export type LinkProps = {
activeClassName?: string;
as?: NextLinkProps['as'];
href: NextLinkProps['href'];
linkAs?: NextLinkProps['as']; // Useful when the as prop is shallow by styled().
noLinkStyle?: boolean;
} & Omit<NextLinkComposedProps, 'to' | 'linkAs' | 'href'> &
Omit<MuiLinkProps, 'href'>;
// A styled version of the Next.js Pages Router Link component:
// https://nextjs.org/docs/pages/api-reference/components/link
const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(function Link(props, ref) {
const {
activeClassName = 'active',
as,
className: classNameProps,
href,
legacyBehavior,
linkAs: linkAsProp,
locale,
noLinkStyle,
prefetch,
replace,
role, // Link don't have roles.
scroll,
shallow,
...other
} = props;
const router = useRouter();
const pathname = typeof href === 'string' ? href : href?.pathname;
const routerPathname = router.pathname.replace('/[docsTab]', '');
const shouldBeActive = routerPathname === pathname;
const className = clsx(classNameProps, {
[activeClassName]: shouldBeActive && activeClassName,
});
const isExternal =
typeof href === 'string' && (href.indexOf('http') === 0 || href.indexOf('mailto:') === 0);
const userLanguage = useUserLanguage();
if (isExternal) {
if (noLinkStyle) {
return <Anchor className={className} href={href} ref={ref} {...other} />;
}
return <MuiLink className={className} href={href} ref={ref} {...other} />;
}
let linkAs = linkAsProp || as || (href as string);
if (
userLanguage !== 'en' &&
pathname &&
pathname.indexOf('/') === 0 &&
!LANGUAGES_IGNORE_PAGES(pathname) &&
!pathname.startsWith(`/${userLanguage}/`)
) {
linkAs = `/${userLanguage}${linkAs}`;
}
const nextjsProps = {
to: href,
linkAs,
replace,
scroll,
shallow,
legacyBehavior,
prefetch,
locale,
};
if (noLinkStyle) {
return <NextLinkComposed className={className} ref={ref} {...nextjsProps} {...other} />;
}
return (
<MuiLink
component={NextLinkComposed}
className={className}
ref={ref}
{...nextjsProps}
{...other}
/>
);
});
export default Link;
| 5,297 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MarkdownDocs.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { useRouter } from 'next/router';
import { useTheme } from '@mui/system';
import { exactProp } from '@mui/utils';
import { CssVarsProvider as JoyCssVarsProvider, useColorScheme } from '@mui/joy/styles';
import RichMarkdownElement from 'docs/src/modules/components/RichMarkdownElement';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import AppLayoutDocs from 'docs/src/modules/components/AppLayoutDocs';
import { useUserLanguage } from 'docs/src/modules/utils/i18n';
import BrandingProvider from 'docs/src/BrandingProvider';
import Ad from 'docs/src/modules/components/Ad';
import AdGuest from 'docs/src/modules/components/AdGuest';
function JoyModeObserver({ mode }) {
const { setMode } = useColorScheme();
React.useEffect(() => {
setMode(mode);
}, [mode, setMode]);
return null;
}
JoyModeObserver.propTypes = {
mode: PropTypes.oneOf(['light', 'dark']),
};
export default function MarkdownDocs(props) {
const theme = useTheme();
const router = useRouter();
const { canonicalAs } = pathnameToLanguage(router.asPath);
const {
disableAd = false,
disableToc = false,
/**
* Some pages, e.g. Joy theme builder, should not be a nested CssVarsProvider to control its own state.
* This config will skip the CssVarsProvider at the root of the page.
*/
disableCssVarsProvider = false,
demos = {},
docs,
demoComponents,
srcComponents,
} = props;
const userLanguage = useUserLanguage();
const localizedDoc = docs[userLanguage] || docs.en;
const isJoy = canonicalAs.startsWith('/joy-ui/') && !disableCssVarsProvider;
const CssVarsProvider = isJoy ? JoyCssVarsProvider : React.Fragment;
const Wrapper = isJoy ? BrandingProvider : React.Fragment;
const wrapperProps = {
...(isJoy && { mode: theme.palette.mode }),
};
return (
<AppLayoutDocs
description={localizedDoc.description}
disableAd={disableAd}
disableToc={disableToc}
location={localizedDoc.location}
title={localizedDoc.title}
toc={localizedDoc.toc}
>
{disableAd ? null : (
<BrandingProvider>
<AdGuest>
<Ad />
</AdGuest>
</BrandingProvider>
)}
<CssVarsProvider>
{isJoy && <JoyModeObserver mode={theme.palette.mode} />}
{localizedDoc.rendered.map((renderedMarkdownOrDemo, index) => (
<RichMarkdownElement
key={`demos-section-${index}`}
demoComponents={demoComponents}
demos={demos}
disableAd={disableAd}
localizedDoc={localizedDoc}
renderedMarkdownOrDemo={renderedMarkdownOrDemo}
srcComponents={srcComponents}
theme={theme}
WrapperComponent={Wrapper}
wrapperProps={wrapperProps}
/>
))}
</CssVarsProvider>
</AppLayoutDocs>
);
}
MarkdownDocs.propTypes = {
demoComponents: PropTypes.object,
demos: PropTypes.object,
disableAd: PropTypes.bool,
disableCssVarsProvider: PropTypes.bool,
disableToc: PropTypes.bool,
docs: PropTypes.object.isRequired,
srcComponents: PropTypes.object,
};
if (process.env.NODE_ENV !== 'production') {
MarkdownDocs.propTypes = exactProp(MarkdownDocs.propTypes);
}
| 5,298 |
0 | petrpan-code/mui/material-ui/docs/src/modules | petrpan-code/mui/material-ui/docs/src/modules/components/MarkdownDocsV2.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { useRouter } from 'next/router';
import kebabCase from 'lodash/kebabCase';
import { useTheme } from '@mui/system';
import { exactProp } from '@mui/utils';
import { CssVarsProvider as JoyCssVarsProvider, useColorScheme } from '@mui/joy/styles';
import ComponentsApiContent from 'docs/src/modules/components/ComponentsApiContent';
import HooksApiContent from 'docs/src/modules/components/HooksApiContent';
import { getTranslatedHeader as getComponentTranslatedHeader } from 'docs/src/modules/components/ApiPage';
import RichMarkdownElement from 'docs/src/modules/components/RichMarkdownElement';
import { pathnameToLanguage } from 'docs/src/modules/utils/helpers';
import AppLayoutDocs from 'docs/src/modules/components/AppLayoutDocs';
import { useTranslate, useUserLanguage } from 'docs/src/modules/utils/i18n';
import BrandingProvider from 'docs/src/BrandingProvider';
import Ad from 'docs/src/modules/components/Ad';
import { HEIGHT as AppFrameHeight } from 'docs/src/modules/components/AppFrame';
import { HEIGHT as TabsHeight } from 'docs/src/modules/components/ComponentPageTabs';
import AdGuest from 'docs/src/modules/components/AdGuest';
import { getPropsToC } from 'docs/src/modules/components/ApiPage/sections/PropertiesSection';
import { getCssToC } from 'docs/src/modules/components/ApiPage/sections/CssSection';
function JoyModeObserver({ mode }) {
const { setMode } = useColorScheme();
React.useEffect(() => {
setMode(mode);
}, [mode, setMode]);
return null;
}
JoyModeObserver.propTypes = {
mode: PropTypes.oneOf(['light', 'dark']),
};
function getHookTranslatedHeader(t, header) {
const translations = {
demos: t('api-docs.demos'),
import: t('api-docs.import'),
'hook-name': t('api-docs.hookName'),
parameters: t('api-docs.parameters'),
'return-value': t('api-docs.returnValue'),
};
// TODO Drop runtime type-checking once we type-check this file
if (!translations.hasOwnProperty(header)) {
throw new TypeError(
`Unable to translate header '${header}'. Did you mean one of '${Object.keys(
translations,
).join("', '")}'`,
);
}
return translations[header] || header;
}
export default function MarkdownDocsV2(props) {
const theme = useTheme();
const router = useRouter();
const [activeTab, setActiveTab] = React.useState(router.query.docsTab ?? '');
const { canonicalAs } = pathnameToLanguage(router.asPath);
const {
disableAd = false,
disableToc = false,
demos = {},
docs,
demoComponents,
srcComponents,
componentsApiDescriptions,
componentsApiPageContents,
hooksApiDescriptions,
hooksApiPageContents,
} = props;
const userLanguage = useUserLanguage();
const t = useTranslate();
React.useEffect(() => {
setActiveTab(router.query.docsTab ?? '');
}, [router.query.docsTab]);
const localizedDoc = docs[userLanguage] || docs.en;
// Generate the TOC based on the tab
const demosToc = localizedDoc.toc.filter((item) => item.text !== 'API');
function createHookTocEntry(hookName, sectionName, hookProps = {}) {
const hookPropToc = [];
Object.keys(hookProps).forEach((propName) => {
hookPropToc.push({
text: propName,
hash: `${hookName}-${sectionName}-${propName}`,
children: [],
});
});
return {
text: getHookTranslatedHeader(t, sectionName),
hash: `${hookName}-${sectionName}`,
children: hookPropToc,
};
}
const hooksToc = [];
if (hooksApiPageContents) {
Object.keys(hooksApiPageContents).forEach((key) => {
const { name: hookName, parameters = {}, returnValue = {} } = hooksApiPageContents[key];
const hookNameKebabCase = kebabCase(hookName);
const hookToc = [
createHookTocEntry(hookNameKebabCase, 'import'),
createHookTocEntry(hookNameKebabCase, 'parameters', parameters),
createHookTocEntry(hookNameKebabCase, 'return-value', returnValue),
].filter(Boolean);
hooksToc.push({
text: hookName,
hash: hookNameKebabCase,
children: hookToc,
});
});
}
function createComponentTocEntry(
componentName,
sectionName,
options = { inheritance: false, themeDefaultProps: false },
) {
return {
text: getComponentTranslatedHeader(t, sectionName),
hash: `${componentName}-${sectionName}`,
children: [
...(options.inheritance
? [{ text: t('api-docs.inheritance'), hash: 'inheritance', children: [] }]
: []),
...(options.themeDefaultProps
? [{ text: t('api-docs.themeDefaultProps'), hash: 'theme-default-props', children: [] }]
: []),
],
};
}
const componentsApiToc = [];
if (componentsApiPageContents) {
Object.keys(componentsApiPageContents).forEach((key) => {
const { componentDescriptionToc = [] } = componentsApiDescriptions[key][userLanguage];
const {
name: componentName,
styles,
inheritance,
slots,
themeDefaultProps,
classes,
props: componentProps,
} = componentsApiPageContents[key];
const componentNameKebabCase = kebabCase(componentName);
const componentApiToc = [
createComponentTocEntry(componentNameKebabCase, 'import'),
...componentDescriptionToc,
styles.name && createComponentTocEntry(componentNameKebabCase, 'component-name'),
getPropsToC({
t,
componentName: componentNameKebabCase,
componentProps,
inheritance,
themeDefaultProps,
hash: `${componentNameKebabCase}-props`,
}),
...getCssToC({
t,
componentName: componentNameKebabCase,
componentStyles: styles,
hash: `${componentNameKebabCase}-css`,
}),
slots?.length > 0 && createComponentTocEntry(componentNameKebabCase, 'slots'),
(classes?.classes?.length || Object.keys(classes?.classes?.globalClasses || {}).length) &&
createComponentTocEntry(componentNameKebabCase, 'classes'),
].filter(Boolean);
componentsApiToc.push({
text: componentName,
hash: componentNameKebabCase,
children: componentApiToc,
});
});
}
const isJoy = canonicalAs.startsWith('/joy-ui/');
const CssVarsProvider = isJoy ? JoyCssVarsProvider : React.Fragment;
const Wrapper = isJoy ? BrandingProvider : React.Fragment;
const wrapperProps = {
...(isJoy && { mode: theme.palette.mode }),
};
const commonElements = [];
let i = 0;
let done = false;
// process the elements before the tabs component
while (i < localizedDoc.rendered.length && !done) {
const renderedMarkdownOrDemo = localizedDoc.rendered[i];
if (renderedMarkdownOrDemo.component && renderedMarkdownOrDemo.component.indexOf('Tabs') >= 0) {
done = true;
}
commonElements.push(
<RichMarkdownElement
key={`common-elements-${i}`}
activeTab={activeTab}
demoComponents={demoComponents}
demos={demos}
disableAd={disableAd}
localizedDoc={localizedDoc}
renderedMarkdownOrDemo={renderedMarkdownOrDemo}
srcComponents={srcComponents}
theme={theme}
WrapperComponent={Wrapper}
wrapperProps={wrapperProps}
/>,
);
i += 1;
}
let activeToc = demosToc;
if (activeTab === 'hooks-api') {
activeToc = hooksToc;
}
if (activeTab === 'components-api') {
activeToc = componentsApiToc;
}
const hasTabs = localizedDoc.rendered.some((renderedMarkdownOrDemo) => {
if (
typeof renderedMarkdownOrDemo === 'object' &&
renderedMarkdownOrDemo.component &&
renderedMarkdownOrDemo.component === 'modules/components/ComponentPageTabs.js'
) {
return true;
}
return false;
});
return (
<AppLayoutDocs
description={localizedDoc.description}
disableAd={disableAd}
disableToc={disableToc}
location={localizedDoc.location}
title={localizedDoc.title}
toc={activeToc}
disableLayout
hasTabs={hasTabs}
>
<div
style={{
'--MuiDocs-header-height': hasTabs
? `${AppFrameHeight + TabsHeight}px`
: `${AppFrameHeight}px`,
}}
>
{disableAd ? null : (
<BrandingProvider>
<AdGuest classSelector={hasTabs ? '.component-tabs' : undefined}>
<Ad />
</AdGuest>
</BrandingProvider>
)}
<CssVarsProvider>
{isJoy && <JoyModeObserver mode={theme.palette.mode} />}
{commonElements}
{activeTab === '' &&
localizedDoc.rendered
// for the "hook only" edge case, e.g. Base UI autocomplete
.slice(
i,
localizedDoc.rendered.length - (localizedDoc.headers.components.length > 0 ? 1 : 0),
)
.map((renderedMarkdownOrDemo, index) => (
<RichMarkdownElement
key={`demos-section-${index}`}
activeTab={activeTab}
demoComponents={demoComponents}
demos={demos}
disableAd={disableAd}
localizedDoc={localizedDoc}
renderedMarkdownOrDemo={renderedMarkdownOrDemo}
srcComponents={srcComponents}
theme={theme}
WrapperComponent={Wrapper}
wrapperProps={wrapperProps}
/>
))}
{activeTab === 'components-api' && (
<ComponentsApiContent
descriptions={componentsApiDescriptions}
pageContents={componentsApiPageContents}
/>
)}
{activeTab === 'hooks-api' && (
<HooksApiContent
descriptions={hooksApiDescriptions}
pagesContents={hooksApiPageContents}
/>
)}
</CssVarsProvider>
</div>
</AppLayoutDocs>
);
}
MarkdownDocsV2.propTypes = {
componentsApiDescriptions: PropTypes.object,
componentsApiPageContents: PropTypes.object,
demoComponents: PropTypes.object,
demos: PropTypes.object,
disableAd: PropTypes.bool,
disableToc: PropTypes.bool,
docs: PropTypes.object.isRequired,
hooksApiDescriptions: PropTypes.object,
hooksApiPageContents: PropTypes.object,
srcComponents: PropTypes.object,
};
if (process.env.NODE_ENV !== 'production') {
MarkdownDocsV2.propTypes = exactProp(MarkdownDocsV2.propTypes);
}
| 5,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.