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

[RFR] Improve buttons props sanitation #4574

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
44 changes: 44 additions & 0 deletions packages/ra-ui-materialui/src/button/Button.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { render, cleanup } from '@testing-library/react';
import React from 'react';
import expect from 'expect';
import { TestContext } from 'ra-core';
import { createMuiTheme, ThemeProvider } from '@material-ui/core';
import Button from './Button';

const theme = createMuiTheme();

const invalidButtonDomProps = {
basePath: '',
handleSubmit: jest.fn(),
handleSubmitWithRedirect: jest.fn(),
invalid: false,
onSave: jest.fn(),
pristine: false,
record: { id: 123, foo: 'bar' },
redirect: 'list',
resource: 'posts',
saving: false,
submitOnEnter: true,
undoable: false,
};

describe('<Button />', () => {
afterEach(cleanup);

it('should render as submit type with no DOM errors', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});

const { getByLabelText } = render(
<TestContext>
<ThemeProvider theme={theme}>
<Button label="button" {...invalidButtonDomProps} />
</ThemeProvider>
</TestContext>
);

expect(spy).not.toHaveBeenCalled();
expect(getByLabelText('button').getAttribute('type')).toEqual('button');

spy.mockRestore();
});
});
46 changes: 41 additions & 5 deletions packages/ra-ui-materialui/src/button/Button.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { FC, ReactElement } from 'react';
import React, { FC, ReactElement, SyntheticEvent, ReactNode } from 'react';
import PropTypes from 'prop-types';
import {
Button as MuiButton,
Expand All @@ -11,7 +11,7 @@ import {
import { ButtonProps as MuiButtonProps } from '@material-ui/core/Button';
import { Theme } from '@material-ui/core';
import classnames from 'classnames';
import { useTranslate } from 'ra-core';
import { Record, RedirectionSideEffect, useTranslate } from 'ra-core';

/**
* A generic Button with side icon. Only the icon is displayed on small screens.
Expand Down Expand Up @@ -43,6 +43,7 @@ const Button: FC<ButtonProps> = props => {
const isXSmall = useMediaQuery((theme: Theme) =>
theme.breakpoints.down('xs')
);
const restProps = sanitizeButtonRestProps(rest);

return isXSmall ? (
label && !disabled ? (
Expand All @@ -51,7 +52,7 @@ const Button: FC<ButtonProps> = props => {
aria-label={translate(label, { _: label })}
className={className}
color={color}
{...rest}
{...restProps}
>
{children}
</IconButton>
Expand All @@ -61,7 +62,7 @@ const Button: FC<ButtonProps> = props => {
className={className}
color={color}
disabled={disabled}
{...rest}
{...restProps}
>
{children}
</IconButton>
Expand All @@ -73,7 +74,7 @@ const Button: FC<ButtonProps> = props => {
size={size}
aria-label={label ? translate(label, { _: label }) : undefined}
disabled={disabled}
{...rest}
{...restProps}
>
{alignIcon === 'left' &&
children &&
Expand Down Expand Up @@ -130,13 +131,48 @@ interface Props {
classes?: object;
className?: string;
color?: MuiPropTypes.Color;
component?: ReactNode;
to?: string | { pathname: string; search: string };
disabled?: boolean;
label?: string;
size?: 'small' | 'medium' | 'large';
icon?: ReactElement;
onClick?: (e: MouseEvent) => void;
redirect?: RedirectionSideEffect;
variant?: string;
// May be injected by Toolbar
basePath?: string;
handleSubmit?: (event?: SyntheticEvent<HTMLFormElement>) => Promise<Object>;
handleSubmitWithRedirect?: (redirect?: RedirectionSideEffect) => void;
invalid?: boolean;
onSave?: (values: object, redirect: RedirectionSideEffect) => void;
saving?: boolean;
submitOnEnter?: boolean;
pristine?: boolean;
record?: Record;
resource?: string;
undoable?: boolean;
}

export type ButtonProps = Props & MuiButtonProps;

export const sanitizeButtonRestProps = ({
// The next props are injected by Toolbar
basePath,
handleSubmit,
handleSubmitWithRedirect,
invalid,
onSave,
pristine,
record,
redirect,
resource,
saving,
submitOnEnter,
undoable,
...rest
}: any) => rest;

Button.propTypes = {
alignIcon: PropTypes.oneOf(['left', 'right']),
children: PropTypes.element,
Expand Down
39 changes: 38 additions & 1 deletion packages/ra-ui-materialui/src/button/CloneButton.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,33 @@
import expect from 'expect';
import { ThemeProvider, createMuiTheme } from '@material-ui/core';
import { render } from '@testing-library/react';
import { cleanup, render } from '@testing-library/react';
import React from 'react';
import { createMemoryHistory } from 'history';
import { Router } from 'react-router-dom';

import { CloneButton } from './CloneButton';
import { TestContext } from 'ra-core';

const theme = createMuiTheme();

const invalidButtonDomProps = {
basePath: '',
handleSubmit: jest.fn(),
handleSubmitWithRedirect: jest.fn(),
invalid: false,
onSave: jest.fn(),
pristine: false,
record: { id: 123, foo: 'bar' },
redirect: 'list',
resource: 'posts',
saving: false,
submitOnEnter: true,
undoable: false,
};

describe('<CloneButton />', () => {
afterEach(cleanup);

it('should pass a clone of the record in the location state', () => {
const history = createMemoryHistory();
const { getByRole } = render(
Expand All @@ -25,4 +43,23 @@ describe('<CloneButton />', () => {
'/create?source=%7B%22foo%22%3A%22bar%22%7D'
);
});

it('should render as button type with no DOM errors', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});

const { getByRole } = render(
<TestContext>
<ThemeProvider theme={theme}>
<CloneButton {...invalidButtonDomProps} />
</ThemeProvider>
</TestContext>
);

expect(spy).not.toHaveBeenCalled();
expect(getByRole('button').getAttribute('href')).toEqual(
'/create?source=%7B%22foo%22%3A%22bar%22%7D'
);

spy.mockRestore();
});
});
13 changes: 1 addition & 12 deletions packages/ra-ui-materialui/src/button/CloneButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const CloneButton: FC<CloneButtonProps> = ({
}
label={label}
onClick={stopPropagation}
{...sanitizeRestProps(rest)}
{...rest}
>
{icon}
</Button>
Expand All @@ -42,17 +42,6 @@ const stopPropagation = e => e.stopPropagation();

const omitId = ({ id, ...rest }: Record) => rest;

const sanitizeRestProps = ({
// the next 6 props are injected by Toolbar
handleSubmit,
handleSubmitWithRedirect,
invalid,
pristine,
saving,
submitOnEnter,
...rest
}: any) => rest;

interface Props {
basePath?: string;
record?: Record;
Expand Down
50 changes: 50 additions & 0 deletions packages/ra-ui-materialui/src/button/CreateButton.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { render, cleanup } from '@testing-library/react';
import React from 'react';
import expect from 'expect';
import { TestContext } from 'ra-core';
import { createMuiTheme, ThemeProvider } from '@material-ui/core';
import CreateButton from './CreateButton';

const invalidButtonDomProps = {
basePath: '',
handleSubmit: jest.fn(),
handleSubmitWithRedirect: jest.fn(),
invalid: false,
onSave: jest.fn(),
pristine: false,
record: { id: 123, foo: 'bar' },
redirect: 'list',
resource: 'posts',
saving: false,
submitOnEnter: true,
undoable: false,
};

describe('<CreateButton />', () => {
afterEach(cleanup);

it('should render a button with no DOM errors', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});

const theme = createMuiTheme({
props: {
MuiWithWidth: {
initialWidth: 'sm',
},
},
});

const { getByLabelText } = render(
<TestContext>
<ThemeProvider theme={theme}>
<CreateButton {...invalidButtonDomProps} />
</ThemeProvider>
</TestContext>
);

expect(spy).not.toHaveBeenCalled();
expect(getByLabelText('ra.action.create').tagName).toEqual('A');

spy.mockRestore();
});
});
4 changes: 2 additions & 2 deletions packages/ra-ui-materialui/src/button/CreateButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import classnames from 'classnames';
import { Link } from 'react-router-dom';
import { useTranslate } from 'ra-core';

import Button, { ButtonProps } from './Button';
import Button, { ButtonProps, sanitizeButtonRestProps } from './Button';

const CreateButton: FC<CreateButtonProps> = props => {
const {
Expand All @@ -30,7 +30,7 @@ const CreateButton: FC<CreateButtonProps> = props => {
className={classnames(classes.floating, className)}
to={`${basePath}/create`}
aria-label={label && translate(label)}
{...rest as any}
{...sanitizeButtonRestProps(rest)}
>
{icon}
</Fab>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { render, cleanup } from '@testing-library/react';
import React from 'react';
import expect from 'expect';
import { TestContext } from 'ra-core';
import { createMuiTheme, ThemeProvider } from '@material-ui/core';
import DeleteWithConfirmButton from './DeleteWithConfirmButton';

const theme = createMuiTheme();

const invalidButtonDomProps = {
basePath: '',
handleSubmit: jest.fn(),
handleSubmitWithRedirect: jest.fn(),
invalid: false,
onSave: jest.fn(),
pristine: false,
record: { id: 123, foo: 'bar' },
redirect: 'list',
resource: 'posts',
saving: false,
submitOnEnter: true,
undoable: false,
};

describe('<DeleteWithConfirmButton />', () => {
afterEach(cleanup);

it('should render a button with no DOM errors', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});

const { getByLabelText } = render(
<TestContext
initialState={{
admin: {
resources: {
posts: {
data: {
1: {
id: 1,
foo: 'bar',
},
},
},
},
},
}}
>
<ThemeProvider theme={theme}>
<DeleteWithConfirmButton {...invalidButtonDomProps} />
</ThemeProvider>
</TestContext>
);

expect(spy).not.toHaveBeenCalled();
expect(getByLabelText('ra.action.delete').getAttribute('type')).toEqual(
'button'
);

spy.mockRestore();
});
});
Loading