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

feat: add sanitizeEmptyValues prop #460

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 3.3.0

* Add `sanitizeEmptyValues` prop (default `true`) to `CreateGuesser` and `EditGuesser`
* Add `sanitizeEmptyValue` prop (default `true`) to `InputGuesser`
* Fix `transform` prop in `CreateGuesser` and `EditGuesser`

## 3.2.0

* Take the operations into account (list, create, edit, delete)
Expand Down
15 changes: 13 additions & 2 deletions src/CreateGuesser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,11 @@ export const IntrospectedCreateGuesser = ({
redirect: redirectTo = 'list',
mode,
defaultValues,
transform,
validate,
toolbar,
warnWhenUnsavedChanges,
sanitizeEmptyValues,
simpleFormComponent,
children,
...props
Expand All @@ -66,7 +68,11 @@ export const IntrospectedCreateGuesser = ({
let inputChildren = React.Children.toArray(children);
if (inputChildren.length === 0) {
inputChildren = writableFields.map((field) => (
<InputGuesser key={field.name} source={field.name} />
<InputGuesser
key={field.name}
source={field.name}
sanitizeEmptyValue={sanitizeEmptyValues}
/>
));
displayOverrideCode(getOverrideCode(schema, writableFields));
}
Expand All @@ -78,11 +84,15 @@ export const IntrospectedCreateGuesser = ({

const save = useCallback(
async (values: Partial<RaRecord>) => {
let data = values;
if (transform) {
data = transform(values);
}
try {
const response = await create(
resource,
{
data: { ...values, extraInformation: { hasFileField } },
data: { ...data, extraInformation: { hasFileField } },
},
{ returnPromise: true },
);
Expand Down Expand Up @@ -136,6 +146,7 @@ export const IntrospectedCreateGuesser = ({
redirect,
redirectTo,
schemaAnalyzer,
transform,
],
);

Expand Down
19 changes: 15 additions & 4 deletions src/EditGuesser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,11 @@ export const IntrospectedEditGuesser = ({
mode,
defaultValues,
validate,
transform,
toolbar,
warnWhenUnsavedChanges,
simpleFormComponent,
sanitizeEmptyValues,
children,
...props
}: IntrospectedEditGuesserProps) => {
Expand All @@ -70,7 +72,11 @@ export const IntrospectedEditGuesser = ({
let inputChildren = React.Children.toArray(children);
if (inputChildren.length === 0) {
inputChildren = writableFields.map((field) => (
<InputGuesser key={field.name} source={field.name} />
<InputGuesser
key={field.name}
source={field.name}
sanitizeEmptyValue={sanitizeEmptyValues}
/>
));
displayOverrideCode(getOverrideCode(schema, writableFields));
}
Expand All @@ -85,23 +91,27 @@ export const IntrospectedEditGuesser = ({
if (id === undefined) {
return undefined;
}
let data = values;
if (transform) {
data = transform(values);
}
try {
const response = await update(
resource,
{
id,
data: { ...values, extraInformation: { hasFileField } },
data: { ...data, extraInformation: { hasFileField } },
},
{ returnPromise: true },
);
const success =
mutationOptions?.onSuccess ??
((data: RaRecord) => {
((updatedRecord: RaRecord) => {
notify('ra.notification.updated', {
type: 'info',
messageArgs: { smart_count: 1 },
});
redirect(redirectTo, resource, data.id, data);
redirect(redirectTo, resource, updatedRecord.id, updatedRecord);
});
success(response, { id, data: response, previousData: values }, {});
return undefined;
Expand Down Expand Up @@ -149,6 +159,7 @@ export const IntrospectedEditGuesser = ({
redirect,
redirectTo,
schemaAnalyzer,
transform,
],
);

Expand Down
53 changes: 52 additions & 1 deletion src/InputGuesser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const dataProvider: ApiPlatformAdminDataProvider = {
fieldB: 'fieldB value',
deprecatedField: 'deprecatedField value',
title: 'Title',
body: 'Body',
description: 'Lorem ipsum dolor sit amet',
},
}),
introspect: () =>
Expand Down Expand Up @@ -92,6 +92,7 @@ describe('<InputGuesser />', () => {
expect(idField).toHaveValue(123);

await user.type(idField, '4');
await user.tab();
expect(idField).toHaveValue(1234);

const saveButton = screen.getByRole('button', { name: 'ra.action.save' });
Expand All @@ -100,4 +101,54 @@ describe('<InputGuesser />', () => {
expect(updatedData).toMatchObject({ id: 1234 });
});
});

test('renders a sanitized text input', async () => {
const user = userEvent.setup();
let updatedData = {};

render(
<AdminContext dataProvider={dataProvider}>
<SchemaAnalyzerContext.Provider value={hydraSchemaAnalyzer}>
<ResourceContextProvider value="users">
<Edit id="/users/123" mutationMode="pessimistic">
<SimpleForm
onSubmit={(data: {
title?: string | null;
description?: string | null;
}) => {
updatedData = data;
}}>
<InputGuesser source="title" />
<InputGuesser source="description" sanitizeEmptyValue={false} />
</SimpleForm>
</Edit>
</ResourceContextProvider>
</SchemaAnalyzerContext.Provider>
</AdminContext>,
);

expect(
await screen.findAllByText('resources.users.fields.title'),
).toHaveLength(1);
const titleField = screen.getByLabelText('resources.users.fields.title');
expect(titleField).toHaveValue('Title');
expect(
await screen.findAllByText('resources.users.fields.description'),
).toHaveLength(1);
const descriptionField = screen.getByLabelText(
'resources.users.fields.description',
);
expect(descriptionField).toHaveValue('Lorem ipsum dolor sit amet');

await user.clear(titleField);
expect(titleField).toHaveValue('');
await user.clear(descriptionField);
expect(descriptionField).toHaveValue('');

const saveButton = screen.getByRole('button', { name: 'ra.action.save' });
fireEvent.click(saveButton);
await waitFor(() => {
expect(updatedData).toMatchObject({ title: null, description: '' });
});
});
});
45 changes: 36 additions & 9 deletions src/InputGuesser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,19 @@ import isPlainObject from 'lodash.isplainobject';
import Introspecter from './Introspecter';
import type { InputGuesserProps, IntrospectedInputGuesserProps } from './types';

const convertEmptyStringToNull = (value: string) =>
value === '' ? null : value;

const convertNullToEmptyString = (value: string | null) => value ?? '';

export const IntrospectedInputGuesser = ({
fields,
readableFields,
writableFields,
schema,
schemaAnalyzer,
validate,
sanitizeEmptyValue = true,
...props
}: IntrospectedInputGuesserProps) => {
const field = fields.find(({ name }) => name === props.source);
Expand Down Expand Up @@ -82,6 +88,12 @@ export const IntrospectedInputGuesser = ({
);
}

const defaultValueSanitize = sanitizeEmptyValue ? null : '';
const formatSanitize = (value: string | null) =>
convertNullToEmptyString(value);
const parseSanitize = (value: string) =>
sanitizeEmptyValue ? convertEmptyStringToNull(value) : value;

let { format, parse } = props;
const fieldType = schemaAnalyzer.getFieldType(field);

Expand All @@ -100,9 +112,20 @@ export const IntrospectedInputGuesser = ({
};
}

const formatEmbedded = (value: string | object) =>
typeof value === 'string' ? value : JSON.stringify(value);
const parseEmbedded = (value: string) => {
const formatEmbedded = (value: string | object | null) => {
if (value === null) {
return '';
}
if (typeof value === 'string') {
return value;
}

return JSON.stringify(value);
};
const parseEmbedded = (value: string | null) => {
if (value === null) {
return null;
}
try {
const parsed = JSON.parse(value);
if (!isPlainObject(parsed)) {
Expand All @@ -113,20 +136,22 @@ export const IntrospectedInputGuesser = ({
return value;
}
};
const parseEmbeddedSanitize = (value: string) =>
parseEmbedded(parseSanitize(value));

if (field.embedded !== null && field.maxCardinality === 1) {
format = formatEmbedded;
parse = parseEmbedded;
parse = parseEmbeddedSanitize;
}

let textInputFormat = (value: string) => value;
let textInputParse = (value: string) => value;
let textInputFormat = formatSanitize;
let textInputParse = parseSanitize;

switch (fieldType) {
case 'array':
if (field.embedded !== null && field.maxCardinality !== 1) {
textInputFormat = formatEmbedded;
textInputParse = parseEmbedded;
textInputParse = parseEmbeddedSanitize;
}

return (
Expand All @@ -138,6 +163,7 @@ export const IntrospectedInputGuesser = ({
<SimpleFormIterator>
<TextInput
source=""
defaultValue={defaultValueSanitize}
format={textInputFormat}
parse={textInputParse}
/>
Expand Down Expand Up @@ -212,9 +238,10 @@ export const IntrospectedInputGuesser = ({
<TextInput
key={field.name}
validate={guessedValidate}
defaultValue={defaultValueSanitize}
{...(props as TextInputProps)}
format={format}
parse={parse}
format={format ?? formatSanitize}
parse={parse ?? parseSanitize}
source={field.name}
/>
);
Expand Down
14 changes: 14 additions & 0 deletions src/__fixtures__/parsedData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,18 @@ export const API_FIELDS_DATA = [
required: true,
deprecated: true,
}),
new Field('title', {
id: 'http://schema.org/title',
range: 'http://www.w3.org/2001/XMLSchema#string',
reference: null,
embedded: null,
required: false,
}),
new Field('description', {
id: 'http://schema.org/description',
range: 'http://www.w3.org/2001/XMLSchema#string',
reference: null,
embedded: null,
required: false,
}),
];
24 changes: 18 additions & 6 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,25 +372,33 @@ type CreateSimpleFormProps = Omit<
};

export type IntrospectedCreateGuesserProps = CreateSimpleFormProps &
IntrospectedGuesserProps;
IntrospectedGuesserProps & {
sanitizeEmptyValues?: boolean;
};

export type CreateGuesserProps = Omit<
CreateSimpleFormProps & Omit<BaseIntrospecterProps, 'resource'>,
'component'
>;
> & {
sanitizeEmptyValues?: boolean;
};

type EditSimpleFormProps = Omit<EditProps & SimpleFormProps, 'children'> &
Partial<PickRename<SimpleFormProps, 'component', 'simpleFormComponent'>> & {
children?: ReactNode;
};

export type IntrospectedEditGuesserProps = EditSimpleFormProps &
IntrospectedGuesserProps;
IntrospectedGuesserProps & {
sanitizeEmptyValues?: boolean;
};

export type EditGuesserProps = Omit<
EditSimpleFormProps & Omit<BaseIntrospecterProps, 'resource'>,
'component'
>;
> & {
sanitizeEmptyValues?: boolean;
};

type ListDatagridProps = Omit<
ListProps & Omit<DatagridProps, 'sx'>,
Expand Down Expand Up @@ -461,12 +469,16 @@ type InputProps =
| ReferenceInputProps;

export type IntrospectedInputGuesserProps = Partial<InputProps> &
IntrospectedGuesserProps;
IntrospectedGuesserProps & {
sanitizeEmptyValue?: boolean;
};

export type InputGuesserProps = Omit<
InputProps & Omit<BaseIntrospecterProps, 'resource'>,
'component'
>;
> & {
sanitizeEmptyValue?: boolean;
};

export type IntrospecterProps = (
| CreateGuesserProps
Expand Down