Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

format IDE code #2674

Merged
merged 13 commits into from
Oct 2, 2023
8 changes: 7 additions & 1 deletion packages/toolpad-app/src/server/localMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
themeSchema,
API_VERSION,
} from './schema';
import { format } from '../utils/prettier';
import { format, resolvePrettierConfig } from '../utils/prettier';
import {
Body as AppDomFetchBody,
FetchQuery,
Expand Down Expand Up @@ -1199,6 +1199,12 @@ class ToolpadProject {
await fs.rm(pageFolder, { force: true, recursive: true });
}

async getPrettierConfig() {
const root = this.getRoot();
const config = await resolvePrettierConfig(root);
return config;
}

getRuntimeConfig(): RuntimeConfig {
return {
externalUrl: this.options.externalUrl,
Expand Down
3 changes: 3 additions & 0 deletions packages/toolpad-app/src/server/rpcServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ export function createRpcServer(project: ToolpadProject) {
getVersionInfo: createMethod<typeof project.getVersionInfo>(({ params }) => {
return project.getVersionInfo(...params);
}),
getPrettierConfig: createMethod<typeof project.getPrettierConfig>(({ params }) => {
return project.getPrettierConfig(...params);
}),
},
mutation: {
saveDom: createMethod<typeof project.saveDom>(({ params }) => {
Expand Down
37 changes: 28 additions & 9 deletions packages/toolpad-app/src/toolpad/AppEditor/BindingEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ import { useAppState } from '../AppState';
import * as appDom from '../../appDom';
import { getBindingType, getBindingValue } from '../../bindings';

import client from '../../api';

// eslint-disable-next-line import/no-cycle
import BindableEditor from './PageEditor/BindableEditor';

Expand Down Expand Up @@ -181,9 +183,11 @@ function getValueBindingTab(value: Maybe<BindableAttrValue<any>>) {
}

export interface ValueBindingEditorProps
extends WithControlledProp<JsExpressionAttrValue | EnvAttrValue | null> {}
extends WithControlledProp<JsExpressionAttrValue | EnvAttrValue | null> {
error: unknown;
}

export function ValueBindingEditor({ value, onChange }: ValueBindingEditorProps) {
export function ValueBindingEditor({ value, onChange, error }: ValueBindingEditorProps) {
const {
label,
globalScope,
Expand All @@ -203,7 +207,6 @@ export function ValueBindingEditor({ value, onChange }: ValueBindingEditorProps)
const handleTabChange = (event: React.SyntheticEvent, newValue: BindableType) => {
setActiveTab(newValue);
};

const jsExpressionBindingEditor = (
<Stack direction="row" sx={{ height: 400, gap: 2, my: hasEnv ? 3 : 0 }}>
<GlobalScopeExplorer sx={{ width: 250 }} value={globalScope} meta={globalScopeMeta} />
Expand All @@ -221,7 +224,6 @@ export function ValueBindingEditor({ value, onChange }: ValueBindingEditorProps)
Make the &quot;{label}&quot; property dynamic with a JavaScript expression. This property
expects a type: <code>{propType?.type || 'any'}</code>.
</Typography>

<JsExpressionBindingEditor
globalScope={globalScope}
globalScopeMeta={globalScopeMeta}
Expand All @@ -232,7 +234,19 @@ export function ValueBindingEditor({ value, onChange }: ValueBindingEditorProps)
}
onChange={onChange}
/>

{error ? (
<Box
sx={{
marginTop: '20px',
}}
>
<Typography sx={{ mb: 2, color: 'red' }}>
Error while reading the prettier configuration:
{(error as string) ??
JerryWu1234 marked this conversation as resolved.
Show resolved Hide resolved
'The prettier config could not be loaded and therefore the code would not be formatted'}
</Typography>
</Box>
) : null}
<JsExpressionPreview jsRuntime={jsRuntime} input={value} globalScope={globalScope} />
</Box>
</Stack>
Expand Down Expand Up @@ -492,6 +506,7 @@ export function BindingEditorDialog<V>({
open,
onClose,
}: BindingEditorDialogProps<V>) {
const { error, data } = client.useQuery('getPrettierConfig', []);
const { propType, label } = useBindingEditorContext();

const [input, setInput] = React.useState(value);
Expand All @@ -501,18 +516,22 @@ export function BindingEditorDialog<V>({

const committedInput = React.useRef<BindableAttrValue<V> | null>(input);

const handleSave = React.useCallback(() => {
const handleSave = React.useCallback(async () => {
let newValue = input;

if ((input as JsExpressionAttrValue)?.$$jsExpression) {
const jsExpression = await tryFormatExpression(
(input as JsExpressionAttrValue).$$jsExpression,
data!,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the backend call to getPrettierConfig fails, or is still loading, data will be undefined. So using ! is not the right solution as that is only reserved for when data is guaranteed to be defined by the programmer.

Instead, show a warning to the user that explains that the prettier config couldn't be loaded and therefore the code won't be formatted when saving.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the backend call to getPrettierConfig fails, or is still loading, data will be undefined. So using ! is not the right solution as that is only reserved for when data is guaranteed to be defined by the programmer.

Instead, show a warning to the user that explains that the prettier config couldn't be loaded and therefore the code won't be formatted when saving.

what's type of warning for user?
such as https://mui.com/material-ui/react-alert/?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there component that i can directly invoke ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An Alert could work. I'd have to see what it looks like. For me I think it's important it's inline, close enough to the save button (i.e. no popup)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image
how about this ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this error only happens without a network I think

There could be a problem while prettier tries to access the file system, or a bug in our code, or in prettier, or our bundler could have transformed the code wrong, or it could be running on an incompatible node.js runtime that we're unaware about, a solar storm flipping a bit,... anything really 🙂

Copy link
Contributor Author

@JerryWu1234 JerryWu1234 Sep 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There could be a problem while prettier tries to access the file system, or a bug in our code, or in prettier, or our bundler could have transformed the code wrong, or it could be running on an incompatible node.js runtime that we're unaware about, a solar storm flipping a bit,... anything really

I see.

do these errors need to be passed to front-end, if back-end occurs error ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Janpot
please make a final check.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JerryWu1234 useQuery is a wrapper around react-query. Next to the data property it will return an error property.

Copy link
Contributor Author

@JerryWu1234 JerryWu1234 Sep 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice point out.
before I thought we need to add a try catch and then pass to front end. lol
I will do it late

);
newValue = {
$$jsExpression: tryFormatExpression((input as JsExpressionAttrValue).$$jsExpression),
$$jsExpression: jsExpression,
};
}

committedInput.current = newValue;
onChange(newValue);
}, [onChange, input]);
}, [onChange, input, data]);

const hasUnsavedChanges = input
? getBindingType(input) !==
Expand Down Expand Up @@ -558,6 +577,7 @@ export function BindingEditorDialog<V>({
<ActionEditor value={input} onChange={(newValue) => setInput(newValue)} />
) : (
<ValueBindingEditor
error={error}
value={
(input as JsExpressionAttrValue)?.$$jsExpression || (input as EnvAttrValue)?.$$env
? (input as JsExpressionAttrValue | EnvAttrValue)
Expand Down Expand Up @@ -611,7 +631,6 @@ export function BindingEditor<V>({
envVarNames,
}: BindingEditorProps<V>) {
const [open, setOpen] = React.useState(false);

const handleOpen = React.useCallback(() => setOpen(true), []);
const handleClose = React.useCallback(() => setOpen(false), []);

Expand Down
23 changes: 19 additions & 4 deletions packages/toolpad-app/src/utils/prettier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,19 @@ const DEFAULT_OPTIONS = {
plugins: [parserBabel],
};

/**
* get prettier config file
*/
export async function resolvePrettierConfig(filePath: string) {
const config = await prettier.resolveConfig(filePath);
return config;
}

/**
* Formats a javascript source with `prettier`.
*/
export async function format(code: string, filePath: string): Promise<string> {
const readConfig = await prettier.resolveConfig(filePath);
const readConfig = await resolvePrettierConfig(filePath);
return prettier.format(code, {
...readConfig,
...DEFAULT_OPTIONS,
Expand All @@ -20,8 +28,12 @@ export async function format(code: string, filePath: string): Promise<string> {
/**
* Formats a javascript expression with `prettier`.
*/
export function formatExpression(code: string): string {
export async function formatExpression(
code: string,
config?: prettier.Options | null,
): Promise<string> {
const formatted = prettier.format(code, {
...config,
...DEFAULT_OPTIONS,
semi: false,
});
Expand All @@ -34,9 +46,12 @@ export function formatExpression(code: string): string {
/**
* Formats a javascript expression with `prettier`, if it's valid.
*/
export function tryFormatExpression(code: string): string {
export async function tryFormatExpression(
code: string,
config?: prettier.Options,
): Promise<string> {
try {
return formatExpression(code);
return formatExpression(code, config);
} catch (err) {
return code;
}
Expand Down