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

[TypeScript] Fix minor type errors in ra-ui-material-ui and validate #6147

Merged
merged 1 commit into from
Apr 10, 2021
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
9 changes: 5 additions & 4 deletions examples/simple/src/comments/CommentEdit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ import {
TextInput,
Title,
minLength,
Record,
} from 'react-admin'; // eslint-disable-line import/no-unresolved

const LinkToRelatedPost = ({ record }) => (
<Link to={`/posts/${record.post_id}`}>
const LinkToRelatedPost = ({ record }: { record?: Record }) => (
<Link to={`/posts/${record?.post_id}`}>
<Typography variant="caption" color="inherit" align="right">
See related post
</Typography>
Expand All @@ -33,9 +34,9 @@ const useEditStyles = makeStyles({
},
});

const OptionRenderer = ({ record }) => (
const OptionRenderer = ({ record }: { record?: Record }) => (
<span>
{record.title} - {record.id}
{record?.title} - {record?.id}
</span>
);

Expand Down
6 changes: 3 additions & 3 deletions examples/simple/src/comments/CommentList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
Typography,
useMediaQuery,
} from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { makeStyles, Theme } from '@material-ui/core/styles';
import jsonExport from 'jsonexport/dist';
import {
ListBase,
Expand Down Expand Up @@ -76,7 +76,7 @@ const CommentPagination = () => {
const translate = useTranslate();
const nbPages = Math.ceil(total / perPage) || 1;
if (!loading && (total === 0 || (ids && !ids.length))) {
return <PaginationLimit total={total} page={page} ids={ids} />;
return <PaginationLimit />;
}

return (
Expand Down Expand Up @@ -209,7 +209,7 @@ const CommentList = props => (
);

const ListView = () => {
const isSmall = useMediaQuery(theme => theme.breakpoints.down('sm'));
const isSmall = useMediaQuery<Theme>(theme => theme.breakpoints.down('sm'));
const { defaultTitle } = useListContext();
return (
<>
Expand Down
41 changes: 30 additions & 11 deletions examples/simple/src/comments/PostPreview.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,39 @@
import * as React from 'react';
import { useSelector } from 'react-redux';
import { SimpleShowLayout, TextField } from 'react-admin';
import {
SimpleShowLayout,
TextField,
ReduxState,
Identifier,
Record,
} from 'react-admin';

const PostPreview = props => {
const record = useSelector(
state =>
state.admin.resources[props.resource]
? state.admin.resources[props.resource].data[props.id]
: null,
[props.resource, props.id]
const PostPreview = ({
id,
basePath,
resource,
}: {
id: Identifier;
basePath: string;
resource: string;
}) => {
const record = useSelector<ReduxState, Record>(state =>
state.admin.resources[resource]
? state.admin.resources[resource].data[id]
: null
);
const version = useSelector(state => state.admin.ui.viewVersion);
useSelector(state => state.admin.loading > 0);
const version = useSelector<ReduxState, number>(
state => state.admin.ui.viewVersion
);
useSelector<ReduxState>(state => state.admin.loading > 0);

return (
<SimpleShowLayout version={version} record={record} {...props}>
<SimpleShowLayout
version={version}
record={record}
basePath={basePath}
resource={resource}
>
<TextField source="id" />
<TextField source="title" />
<TextField source="teaser" />
Expand Down
5 changes: 4 additions & 1 deletion examples/simple/src/comments/PostQuickCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
Toolbar,
required,
showNotification,
ReduxState,
} from 'react-admin'; // eslint-disable-line import/no-unresolved

import CancelButton from './PostQuickCreateCancelButton';
Expand All @@ -36,7 +37,9 @@ const useStyles = makeStyles({
const PostQuickCreate = ({ onCancel, onSave, ...props }) => {
const classes = useStyles();
const dispatch = useDispatch();
const submitting = useSelector(state => state.admin.loading > 0);
const submitting = useSelector<ReduxState, boolean>(
state => state.admin.loading > 0
);

const handleSave = useCallback(
values => {
Expand Down
2 changes: 1 addition & 1 deletion examples/simple/src/posts/PostCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const PostCreate = ({ permissions, ...props }) => {
toolbar={<PostCreateToolbar />}
initialValues={initialValues}
validate={values => {
const errors = {};
const errors = {} as any;
['title', 'teaser'].forEach(field => {
if (!values[field]) {
errors[field] = 'Required field';
Expand Down
12 changes: 8 additions & 4 deletions examples/simple/src/posts/PostEdit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ import {
required,
FormDataConsumer,
} from 'react-admin'; // eslint-disable-line import/no-unresolved
import { Box } from '@material-ui/core';
import { Box, BoxProps } from '@material-ui/core';

import PostTitle from './PostTitle';
import TagReferenceInput from './TagReferenceInput';

const EditActions = ({ basePath, data, hasShow }) => (
const EditActions = ({ basePath, data, hasShow }: any) => (
<TopToolbar>
<CloneButton
className="button-clone"
Expand All @@ -45,7 +45,11 @@ const EditActions = ({ basePath, data, hasShow }) => (
</TopToolbar>
);

const SanitizedBox = ({ fullWidth, basePath, ...props }) => <Box {...props} />;
const SanitizedBox = ({
fullWidth,
basePath,
...props
}: BoxProps & { fullWidth?: boolean; basePath?: string }) => <Box {...props} />;

const PostEdit = ({ permissions, ...props }) => (
<Edit title={<PostTitle />} actions={<EditActions />} {...props}>
Expand Down Expand Up @@ -147,7 +151,7 @@ const PostEdit = ({ permissions, ...props }) => (
<TextInput source="url" validate={required()} />
</SimpleFormIterator>
</ArrayInput>
<DateInput source="published_at" options={{ locale: 'pt' }} />
<DateInput source="published_at" />
<SelectInput
allowEmpty
resettable
Expand Down
8 changes: 4 additions & 4 deletions examples/simple/src/posts/PostList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react';
import { Children, Fragment, cloneElement, memo } from 'react';
import BookIcon from '@material-ui/icons/Book';
import { Chip, useMediaQuery } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { makeStyles, Theme } from '@material-ui/core/styles';
import lodashGet from 'lodash/get';
import jsonExport from 'jsonexport/dist';
import {
Expand Down Expand Up @@ -35,7 +35,7 @@ const useQuickFilterStyles = makeStyles(theme => ({
marginBottom: theme.spacing(1),
},
}));
const QuickFilter = ({ label }) => {
const QuickFilter = ({ label, source, defaultValue }) => {
const translate = useTranslate();
const classes = useQuickFilterStyles();
return <Chip className={classes.chip} label={translate(label)} />;
Expand Down Expand Up @@ -81,7 +81,7 @@ const useStyles = makeStyles(theme => ({
publishedAt: { fontStyle: 'italic' },
}));

const PostListBulkActions = memo(props => (
const PostListBulkActions = memo(({ children, ...props }) => (
<Fragment>
<ResetViewsButton {...props} />
<BulkDeleteButton {...props} />
Expand Down Expand Up @@ -121,7 +121,7 @@ const PostPanel = ({ id, record, resource }) => (

const PostList = props => {
const classes = useStyles();
const isSmall = useMediaQuery(theme => theme.breakpoints.down('sm'));
const isSmall = useMediaQuery<Theme>(theme => theme.breakpoints.down('sm'));
return (
<List
{...props}
Expand Down
5 changes: 3 additions & 2 deletions examples/simple/src/posts/PostShow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,18 @@ import {
UrlField,
useShowController,
useLocale,
Record,
} from 'react-admin';
import { Link } from 'react-router-dom';
import { Button } from '@material-ui/core';
import PostTitle from './PostTitle';

const CreateRelatedComment = ({ record }) => (
const CreateRelatedComment = ({ record }: { record?: Record }) => (
<Button
component={Link}
to={{
pathname: '/comments/create',
state: { record: { post_id: record.id } },
state: { record: { post_id: record?.id } },
}}
>
Add comment
Expand Down
4 changes: 2 additions & 2 deletions examples/simple/src/posts/PostTitle.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from 'react';
import { useTranslate } from 'react-admin';
import { useTranslate, Record } from 'react-admin';

export default ({ record }) => {
export default ({ record }: { record?: Record }) => {
const translate = useTranslate();
return (
<span>
Expand Down
8 changes: 7 additions & 1 deletion examples/simple/src/posts/TagReferenceInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ const useStyles = makeStyles({
},
});

const TagReferenceInput = ({ ...props }) => {
const TagReferenceInput = ({
...props
}: {
reference: string;
source: string;
label?: string;
}) => {
const classes = useStyles();
const { change } = useForm();
const [filter, setFilter] = useState(true);
Expand Down
15 changes: 5 additions & 10 deletions examples/simple/src/users/UserCreate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,7 @@ import {

import Aside from './Aside';

const UserEditToolbar = ({
permissions,
hasList,
hasEdit,
hasShow,
hasCreate,
...props
}) => (
const UserEditToolbar = ({ permissions, ...props }) => (
<Toolbar {...props}>
<SaveButton
label="user.action.save_and_show"
Expand All @@ -39,8 +32,10 @@ const UserEditToolbar = ({
);

const isValidName = async value =>
new Promise(resolve =>
setTimeout(resolve(value === 'Admin' ? "Can't be Admin" : undefined))
new Promise<string>(resolve =>
setTimeout(() =>
resolve(value === 'Admin' ? "Can't be Admin" : undefined)
)
);

const UserCreate = ({ permissions, ...props }) => (
Expand Down
28 changes: 21 additions & 7 deletions packages/ra-core/src/form/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,18 @@ export type Validator = (
value: any,
values: any,
props: any
) => ValidationErrorMessage | null | undefined;
) =>
| ValidationErrorMessage
| null
| undefined
| Promise<ValidationErrorMessage | null | undefined>;

// type predicate, see https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
function isValidationErrorMessageWithArgs(
error: ReturnType<Validator>
): error is ValidationErrorMessageWithArgs {
return error.hasOwnProperty('message');
}

interface MessageFuncParams {
args: any;
Expand Down Expand Up @@ -74,18 +85,21 @@ export const composeValidators = (...validators) => async (
const allValidators = (Array.isArray(validators[0])
? validators[0]
: validators
).filter(isFunction);
).filter(isFunction) as Validator[];

for (const validator of allValidators) {
const errorPromise = validator(value, values, meta);

if (errorPromise) {
let error = errorPromise;

if (errorPromise.then) {
error = await errorPromise;
if (typeof errorPromise == 'string') {
return errorPromise;
}
if (isValidationErrorMessageWithArgs(errorPromise)) {
return errorPromise;
}

const error = await errorPromise;

if (error) {
return error;
}
Expand All @@ -102,7 +116,7 @@ export const composeSyncValidators = (...validators) => (
const allValidators = (Array.isArray(validators[0])
? validators[0]
: validators
).filter(isFunction);
).filter(isFunction) as Validator[];

for (const validator of allValidators) {
const error = validator(value, values, meta);
Expand Down
2 changes: 1 addition & 1 deletion packages/ra-ui-materialui/src/button/BulkExportButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ interface Props {
icon?: JSX.Element;
label?: string;
onClick?: (e: Event) => void;
selectedIds: Identifier[];
selectedIds?: Identifier[];
resource?: string;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/ra-ui-materialui/src/detail/ShowView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const ShowView = (props: ShowViewProps) => {

interface ShowViewProps
extends ShowProps,
Omit<ShowControllerProps, 'resource'> {
Partial<Omit<ShowControllerProps, 'resource'>> {
children: ReactElement;
}

Expand Down
6 changes: 3 additions & 3 deletions packages/ra-ui-materialui/src/field/TranslatableFields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,11 @@ export const TranslatableFields = (
};

export interface TranslatableFieldsProps extends UseTranslatableOptions {
basePath: string;
basePath?: string;
children: ReactNode;
classes?: ClassesOverride<typeof useStyles>;
record: Record;
resource: string;
record?: Record;
resource?: string;
selector?: ReactElement;
groupKey?: string;
}
Expand Down
7 changes: 5 additions & 2 deletions packages/ra-ui-materialui/src/form/Toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import {
ReactNode,
} from 'react';
import PropTypes from 'prop-types';
import MuiToolbar from '@material-ui/core/Toolbar';
import MuiToolbar, {
ToolbarProps as MuiToolbarProps,
} from '@material-ui/core/Toolbar';
import withWidth from '@material-ui/core/withWidth';
import { makeStyles } from '@material-ui/core/styles';
import classnames from 'classnames';
Expand Down Expand Up @@ -203,7 +205,8 @@ const Toolbar: FC<ToolbarProps> = props => {
);
};

export interface ToolbarProps<RecordType extends Record = Record> {
export interface ToolbarProps<RecordType extends Record = Record>
extends Omit<MuiToolbarProps, 'classes'> {
children?: ReactNode;
alwaysEnableSaveButton?: boolean;
className?: string;
Expand Down