Skip to content

Commit

Permalink
Fix inline previews
Browse files Browse the repository at this point in the history
  • Loading branch information
DanailH committed Nov 3, 2021
1 parent 9b012ef commit 1d8ba55
Show file tree
Hide file tree
Showing 49 changed files with 432 additions and 3 deletions.
4 changes: 2 additions & 2 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
"export": "rimraf docs/export && next export --threads=3 -o export && yarn build-sw",
"icons": "rimraf public/static/icons/* && node ./scripts/buildIcons.js",
"typescript": "tsc -p tsconfig.json",
"typescript:transpile": "node scripts/formattedTSDemos",
"typescript:transpile:dev": "node scripts/formattedTSDemos --watch"
"typescript:transpile": "cross-env BABEL_ENV=development babel-node --extensions \".tsx,.ts,.js\" scripts/formattedTSDemos",
"typescript:transpile:dev": "cross-env BABEL_ENV=development babel-node --extensions \".tsx,.ts,.js\" scripts/formattedTSDemos --watch"
},
"dependencies": {
"@babel/core": "^7.16.0",
Expand Down
12 changes: 11 additions & 1 deletion docs/scripts/formattedTSDemos.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,17 @@ async function transpileFile(tsxPath, program, ignoreCache = false) {

const source = await fse.readFile(tsxPath, 'utf8');

const { code } = await babel.transformAsync(source, { ...babelConfig, filename: tsxPath });
const transformOptions = { ...babelConfig, filename: tsxPath };
const enableJSXPreview = !tsxPath.includes(path.join('pages', 'premium-themes'));
if (enableJSXPreview) {
transformOptions.plugins = transformOptions.plugins.concat([
[
require.resolve('docsx/src/modules/utils/babel-plugin-jsx-preview'),
{ maxLines: 16, outputFilename: `${tsxPath}.preview` },
],
]);
}
const { code } = await babel.transformAsync(source, transformOptions);

if (/import \w* from 'prop-types'/.test(code)) {
throw new Error('TypeScript demo contains prop-types, please remove them');
Expand Down
102 changes: 102 additions & 0 deletions docs/src/modules/utils/babel-plugin-jsx-preview.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
const fs = require('fs');

const pluginName = 'babel-plugin-jsx-preview';

/**
* @returns {import('@babel/core').PluginObj}
*/
export default function babelPluginJsxPreview() {
const wrapperTypes = ['div', 'Box', 'Stack'];

/**
* @type {import('@babel/core').types.JSXElement | import('@babel/core').types.JSXElement['children']}
*/
let previewNode = null;

return {
name: pluginName,
visitor: {
ExportDefaultDeclaration(path) {
const { declaration } = path.node;
if (declaration.type !== 'FunctionDeclaration') {
return;
}
const { body } = declaration.body;
/**
* @type {import('@babel/core').types.ReturnStatement[]}
*/
const [lastReturn] = body
.filter((statement) => {
return statement.type === 'ReturnStatement';
})
.reverse();

const returnedJSX = lastReturn.argument;
if (returnedJSX.type === 'JSXElement') {
previewNode = returnedJSX;
if (
wrapperTypes.includes(previewNode.openingElement.name.name) &&
previewNode.children.length > 0
) {
// Trim blank JSXText to normalize
// return (
// <div />
// )
// and
// return (
// <Stack>
// <div />
// ^^^^ Blank JSXText including newline
// </Stacke>
// )
previewNode = previewNode.children.filter((child, index, children) => {
const isSurroundingBlankJSXText =
(index === 0 || index === children.length - 1) &&
child.type === 'JSXText' &&
!/[^\s]+/.test(child.value);
return !isSurroundingBlankJSXText;
});
}
}
},
},
post(state) {
const { maxLines, outputFilename } = state.opts.plugins.find((plugin) => {
return plugin.key === pluginName;
}).options;

let hasPreview = false;
if (previewNode !== null) {
const [startNode, endNode] = Array.isArray(previewNode)
? [previewNode[0], previewNode.slice(-1)[0]]
: [previewNode, previewNode];
const preview = state.code.slice(startNode.start, endNode.end);

const previewLines = preview.split(/\n/);
// The first line is already trimmed either due to trimmed blank JSXText or because it's a single node which babel already trims.
// The last line is therefore the meassure for indendation
const indendation = previewLines.slice(-1)[0].match(/^\s*/)[0].length;
const deindentedPreviewLines = preview.split(/\n/).map((line, index) => {
if (index === 0) {
return line;
}
return line.slice(indendation);
});

if (deindentedPreviewLines.length <= maxLines) {
fs.writeFileSync(outputFilename, deindentedPreviewLines.join('\n'));
hasPreview = true;
}
}

if (!hasPreview) {
try {
fs.unlinkSync(outputFilename);
} catch (error) {
// Would throw if the file doesn't exist.
// But we do want to ensure that the file doesn't exist so the error is fine.
}
}
},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<DataGrid
columns={[{ field: 'username' }, { field: 'age' }]}
rows={[
{
id: 1,
username: '@MUI',
age: 20,
},
]}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<DataGrid
columns={[{ field: 'username', minWidth: 150 }, { field: 'age' }]}
rows={rows}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<DataGridPro
columns={[
{ field: 'id' },
{ field: 'username' },
{ field: 'age', disableReorder: true },
]}
rows={rows}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<DataGridPro
columns={[
{ field: 'id' },
{ field: 'username', minWidth: 150 },
{ field: 'age', resizable: false },
]}
rows={rows}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid columns={columns} rows={rows} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<DataGrid
columns={[{ field: 'username', width: 200 }, { field: 'age' }]}
rows={rows}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<DataGrid
columns={[
{ field: 'status', width: 130 },
{ field: 'subTotal', ...usdPrice },
{ field: 'total', ...usdPrice },
]}
rows={rows}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<DataGrid
columns={[
{
field: 'username',
headerName: 'Username',
description:
'The identification used by the person with access to the online service.',
},
{ field: 'age', headerName: 'Age' },
]}
rows={rows}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid rows={rows} columns={columns} />
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid rows={rows} columns={columns} />
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid rows={rows} columns={columns} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<DataGrid
components={{
NoRowsOverlay: CustomNoRowsOverlay,
}}
rows={[]}
columns={data.columns}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<DataGrid
components={{
LoadingOverlay: CustomLoadingOverlay,
}}
loading
{...data}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<DataGrid
pagination
pageSize={5}
rowsPerPageOptions={[5]}
components={{
Pagination: CustomPagination,
}}
{...data}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<DataGrid
columns={columns}
rows={rows}
sortModel={[
{ field: 'name', sort: 'asc' },
{ field: 'stars', sort: 'desc' },
]}
components={{
ColumnSortedDescendingIcon: SortedDescendingIcon,
ColumnSortedAscendingIcon: SortedAscendingIcon,
}}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid rows={rows} columns={columns} />
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid editMode="row" rows={rows} columns={columns} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<div style={{ height: 180, width: '100%' }}>
<DataGridPro rows={rows} columns={columns} apiRef={apiRef} />
</div>
{message && (
<Alert severity="info" style={{ marginTop: 8 }}>
{message}
</Alert>
)}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Alert severity="info" style={{ marginBottom: 8 }}>
<code>editRowsModel: {JSON.stringify(editRowsModel)}</code>
</Alert>
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
editRowsModel={editRowsModel}
onEditRowsModelChange={handleEditRowsModelChange}
/>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<DataGrid
className={classes.root}
rows={rows}
columns={columns}
editMode="row"
editRowsModel={editRowsModel}
onEditRowsModelChange={handleEditRowsModelChange}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<DataGridPro
rows={rows}
columns={columns}
apiRef={apiRef}
editMode="row"
onRowEditStart={handleRowEditStart}
onRowEditStop={handleRowEditStop}
onCellFocusOut={handleCellFocusOut}
components={{
Toolbar: EditToolbar,
}}
componentsProps={{
toolbar: { apiRef },
}}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<DataGrid
className={classes.root}
rows={rows}
columns={columns}
isCellEditable={(params) => params.row.age % 2 === 0}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid rows={rows} columns={columns} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
editRowsModel={editRowsModel}
editMode="row"
onEditRowsModelChange={handleEditRowsModelChange}
/>
</div>
<Alert severity="info" style={{ marginTop: 8 }}>
<code>editRowsModel: {JSON.stringify(editRowsModel)}</code>
</Alert>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<DataGrid
className={classes.root}
rows={rows}
columns={columns}
editRowsModel={editRowsModel}
onEditRowsModelChange={handleEditRowsModelChange}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<DataGridPro
className={classes.root}
apiRef={apiRef}
rows={rows}
columns={columns}
onEditCellPropsChange={handleCellEditPropsChange}
isCellEditable={(params) => params.row.id === 5}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid rows={defaultRows} columns={columns} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<div style={{ height: 180, width: '100%' }}>
<DataGridPro apiRef={apiRef} {...data} />
</div>
{message && (
<Alert severity="info" style={{ marginTop: 8 }}>
{message}
</Alert>
)}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<DataGrid
rows={data.rows}
columns={columns}
columnTypes={{ price: priceColumnType }}
initialState={{
filter: {
filterModel: {
items: [
{ columnField: 'totalPrice', value: '3000000', operatorValue: '>' },
],
},
},
}}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<DataGrid
rows={data.rows}
columns={columns}
filterModel={filterModel}
onFilterModelChange={(model) => setFilterModel(model)}
/>
Loading

0 comments on commit 1d8ba55

Please sign in to comment.