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

Add support for react-admin v5 #572

Merged
merged 18 commits into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
fzaninotto marked this conversation as resolved.
Show resolved Hide resolved
5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@
"sideEffects": false,
"dependencies": {
"@api-platform/api-doc-parser": "^0.16.2",
"history": "^5.0.0",
"jsonld": "^8.1.0",
"lodash.isplainobject": "^4.0.6",
"prop-types": "^15.6.2",
"react-admin": "^4.4.0",
"react-error-boundary": "^4.0.13"
"react-admin": "^5.0.3"
},
"devDependencies": {
"@babel/preset-env": "^7.23.3",
Expand Down
3 changes: 2 additions & 1 deletion src/AdminGuesser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import React from 'react';
import { AdminUI, AuthContext } from 'react-admin';
import type { AdminProps, AuthProvider } from 'react-admin';
import ReactTestRenderer from 'react-test-renderer/shallow';
import AdminGuesser, { AdminResourcesGuesser } from './AdminGuesser.js';
import AdminGuesser from './AdminGuesser.js';
import { AdminResourcesGuesser } from './AdminResourcesGuesser.js';
import ResourceGuesser from './ResourceGuesser.js';
import schemaAnalyzer from './hydra/schemaAnalyzer.js';
import resources from './__fixtures__/resources.js';
Expand Down
156 changes: 14 additions & 142 deletions src/AdminGuesser.tsx
Copy link
Contributor Author

Choose a reason for hiding this comment

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

moved to core

Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import {
AdminContext,
AdminUI,
ComponentPropType,
Loading,
defaultI18nProvider,
} from 'react-admin';
import { ErrorBoundary } from 'react-error-boundary';
import type { FallbackProps } from 'react-error-boundary';
import type { ComponentType, ErrorInfo } from 'react';
import type { AdminProps, ErrorProps } from 'react-admin';
import React, { useEffect, useMemo, useState } from 'react';
import { AdminContext, defaultI18nProvider } from 'react-admin';

import type { ComponentType } from 'react';
import type { AdminProps } from 'react-admin';
import type { Resource } from '@api-platform/api-doc-parser';

import { AdminResourcesGuesser } from './AdminResourcesGuesser.js';
import IntrospectionContext from './IntrospectionContext.js';
import ResourceGuesser from './ResourceGuesser.js';
import SchemaAnalyzerContext from './SchemaAnalyzerContext.js';
import {
Error as DefaultError,
Expand All @@ -23,10 +15,6 @@ import {
darkTheme,
lightTheme,
} from './layout/index.js';
import getRoutesAndResourcesFromNodes, {
isSingleChildFunction,
} from './getRoutesAndResourcesFromNodes.js';
import useDisplayOverrideCode from './useDisplayOverrideCode.js';
import type { ApiPlatformAdminDataProvider, SchemaAnalyzer } from './types.js';

export interface AdminGuesserProps extends AdminProps {
Expand All @@ -36,88 +24,18 @@ export interface AdminGuesserProps extends AdminProps {
includeDeprecated?: boolean;
}

interface AdminGuesserWithErrorProps extends AdminGuesserProps {
error?: ComponentType<ErrorProps>;
}

interface AdminResourcesGuesserProps extends Omit<AdminProps, 'loading'> {
admin?: ComponentType<AdminProps>;
includeDeprecated: boolean;
loading: boolean;
loadingPage?: ComponentType;
resources: Resource[];
}

const getOverrideCode = (resources: Resource[]) => {
let code =
'If you want to override at least one resource, paste this content in the <AdminGuesser> component of your app:\n\n';

resources.forEach((r) => {
code += `<ResourceGuesser name={"${r.name}"} />\n`;
});

return code;
};

/**
* AdminResourcesGuesser automatically renders an `<AdminUI>` component for resources exposed by a web API documented with Hydra, OpenAPI or any other format supported by `@api-platform/api-doc-parser`.
* If child components are passed (usually `<ResourceGuesser>` or `<Resource>` components, but it can be any other React component), they are rendered in the given order.
* If no children are passed, a `<ResourceGuesser>` component is created for each resource type exposed by the API, in the order they are specified in the API documentation.
*/
export const AdminResourcesGuesser = ({
// Admin props
Copy link
Contributor Author

Choose a reason for hiding this comment

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

extracted to its own file for clarity

loadingPage: LoadingPage = Loading,
admin: AdminEl = AdminUI,
// Props
children,
includeDeprecated,
resources,
loading,
...rest
}: AdminResourcesGuesserProps) => {
const displayOverrideCode = useDisplayOverrideCode();

if (loading) {
return <LoadingPage />;
}

let adminChildren = children;
const { resources: resourceChildren, customRoutes } =
getRoutesAndResourcesFromNodes(children);
if (
!isSingleChildFunction(adminChildren) &&
resourceChildren.length === 0 &&
resources
) {
const guessResources = includeDeprecated
? resources
: resources.filter((r) => !r.deprecated);
adminChildren = [
...customRoutes,
...guessResources.map((r) => (
<ResourceGuesser name={r.name} key={r.name} />
)),
];
displayOverrideCode(getOverrideCode(guessResources));
}

return (
<AdminEl loading={LoadingPage} {...rest}>
{adminChildren}
</AdminEl>
);
};

const AdminGuesser = ({
// Props for SchemaAnalyzerContext
schemaAnalyzer,
// Props for AdminResourcesGuesser
includeDeprecated = false,
// Admin props
basename,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error = DefaultError as any,
store,
dataProvider,
i18nProvider,
i18nProvider = defaultI18nProvider,
authProvider,
queryClient,
defaultTheme,
Expand Down Expand Up @@ -152,10 +70,10 @@ const AdminGuesser = ({
setIntrospect(false);
setLoading(false);
})
.catch((error) => {
// Allow error to be caught by the error boundary
.catch((err) => {
// Allow err to be caught by the error boundary
setError(() => {
throw error;
throw err;
});
});
}, [introspect, dataProvider]);
Expand Down Expand Up @@ -193,6 +111,7 @@ const AdminGuesser = ({
loginPage={loginPage}
loadingPage={loadingPage}
theme={theme}
error={error}
{...rest}>
{children}
</AdminResourcesGuesser>
Expand All @@ -202,51 +121,4 @@ const AdminGuesser = ({
);
};

/* eslint-disable tree-shaking/no-side-effects-in-initialization */
AdminGuesser.propTypes = {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

react-admin v5 no longer has propTypes, React 18.3 warns against them, so I removed them

dataProvider: PropTypes.oneOfType([PropTypes.object, PropTypes.func])
.isRequired,
authProvider: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
i18nProvider: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
history: PropTypes.object,
customSagas: PropTypes.array,
initialState: PropTypes.object,
schemaAnalyzer: PropTypes.object.isRequired,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
theme: PropTypes.object,
includeDeprecated: PropTypes.bool,
admin: PropTypes.elementType,
};
/* eslint-enable tree-shaking/no-side-effects-in-initialization */

const AdminGuesserWithError = ({
error: ErrorComponent = DefaultError,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

We no longer need this wrapper as react-admin v5 has a global error boundary

i18nProvider = defaultI18nProvider,
theme = lightTheme,
...props
}: AdminGuesserWithErrorProps) => {
const [errorInfo, setErrorInfo] = useState<ErrorInfo>();

const handleError = (_error: Error, info: ErrorInfo) => {
setErrorInfo(info);
};

const renderError = useCallback(
(fallbackRenderProps: FallbackProps) => (
<ErrorComponent {...fallbackRenderProps} errorInfo={errorInfo} />
),
[ErrorComponent, errorInfo],
);

return (
<ErrorBoundary onError={handleError} fallbackRender={renderError}>
<AdminGuesser {...props} i18nProvider={i18nProvider} theme={theme} />
</ErrorBoundary>
);
};

AdminGuesserWithError.propTypes = {
error: ComponentPropType,
};

export default AdminGuesserWithError;
export default AdminGuesser;
95 changes: 95 additions & 0 deletions src/AdminResourcesGuesser.tsx
Copy link
Contributor Author

Choose a reason for hiding this comment

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

component extracted to its own file for clarity

Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import React from 'react';
import { AdminUI, Loading } from 'react-admin';
import type { ComponentType } from 'react';
import type { AdminProps } from 'react-admin';
import type { Resource } from '@api-platform/api-doc-parser';

import ResourceGuesser from './ResourceGuesser.js';

import getRoutesAndResourcesFromNodes, {
isSingleChildFunction,
} from './getRoutesAndResourcesFromNodes.js';
import useDisplayOverrideCode from './useDisplayOverrideCode.js';
import type { ApiPlatformAdminDataProvider, SchemaAnalyzer } from './types.js';

export interface AdminGuesserProps extends AdminProps {
admin?: ComponentType<AdminProps>;
dataProvider: ApiPlatformAdminDataProvider;
schemaAnalyzer: SchemaAnalyzer;
includeDeprecated?: boolean;
}

interface AdminResourcesGuesserProps extends Omit<AdminProps, 'loading'> {
admin?: ComponentType<AdminProps>;
includeDeprecated: boolean;
loading: boolean;
loadingPage?: ComponentType;
resources: Resource[];
}

const getOverrideCode = (resources: Resource[]) => {
let code =
'If you want to override at least one resource, paste this content in the <AdminGuesser> component of your app:\n\n';

resources.forEach((r) => {
code += `<ResourceGuesser name={"${r.name}"} />\n`;
});

return code;
};

/**
* AdminResourcesGuesser automatically renders an `<AdminUI>` component
* for resources exposed by a web API documented with Hydra, OpenAPI
* or any other format supported by `@api-platform/api-doc-parser`.
*
* If child components are passed (usually `<ResourceGuesser>` or `<Resource>`
* components, but it can be any other React component), they are rendered in
* the given order.
* If no children are passed, a `<ResourceGuesser>` component is created for
* each resource type exposed by the API, in the order they are specified in
* the API documentation.
*/
export const AdminResourcesGuesser = ({
// Admin props
loadingPage: LoadingPage = Loading,
admin: AdminEl = AdminUI,
// Props
children,
includeDeprecated,
resources,
loading,
...rest
}: AdminResourcesGuesserProps) => {
const displayOverrideCode = useDisplayOverrideCode();

if (loading) {
return <LoadingPage />;
}

let adminChildren = children;
const { resources: resourceChildren, customRoutes } =
getRoutesAndResourcesFromNodes(children);
if (
!isSingleChildFunction(adminChildren) &&
resourceChildren.length === 0 &&
resources
) {
const guessedResources = includeDeprecated
? resources
: resources.filter((r) => !r.deprecated);
adminChildren = [
...customRoutes,
...guessedResources.map((r) => (
<ResourceGuesser name={r.name} key={r.name} />
)),
];
displayOverrideCode(getOverrideCode(guessedResources));
}

return (
<AdminEl loading={LoadingPage} {...rest}>
{adminChildren}
</AdminEl>
);
};
11 changes: 3 additions & 8 deletions src/CreateGuesser.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from 'react';
import PropTypes from 'prop-types';
import {
Create,
FormTab,
Expand Down Expand Up @@ -102,6 +101,9 @@ export const IntrospectedCreateGuesser = ({

const CreateGuesser = (props: CreateGuesserProps) => {
const resource = useResourceContext(props);
if (!resource) {
throw new Error('guesser must be used with a resource');
}

return (
<Introspecter
Expand All @@ -112,11 +114,4 @@ const CreateGuesser = (props: CreateGuesserProps) => {
);
};

/* eslint-disable tree-shaking/no-side-effects-in-initialization */
CreateGuesser.propTypes = {
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
resource: PropTypes.string,
};
/* eslint-enable tree-shaking/no-side-effects-in-initialization */

export default CreateGuesser;
11 changes: 3 additions & 8 deletions src/EditGuesser.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from 'react';
import PropTypes from 'prop-types';
import {
Edit,
FormTab,
Expand Down Expand Up @@ -114,6 +113,9 @@ export const IntrospectedEditGuesser = ({

const EditGuesser = (props: EditGuesserProps) => {
const resource = useResourceContext(props);
if (!resource) {
throw new Error('guesser must be used with a resource');
}

return (
<Introspecter
Expand All @@ -124,11 +126,4 @@ const EditGuesser = (props: EditGuesserProps) => {
);
};

/* eslint-disable tree-shaking/no-side-effects-in-initialization */
EditGuesser.propTypes = {
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
resource: PropTypes.string,
};
/* eslint-enable tree-shaking/no-side-effects-in-initialization */

export default EditGuesser;
6 changes: 0 additions & 6 deletions src/EnumField.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from 'react';
import PropTypes from 'prop-types';
import {
ArrayField,
SingleFieldList,
Expand Down Expand Up @@ -34,9 +33,4 @@ const EnumField = ({ transformEnum, source, ...props }: EnumFieldProps) => {

EnumField.displayName = 'EnumField';

EnumField.propTypes = {
...TextField.propTypes,
transformEnum: PropTypes.func,
};

export default EnumField;
Loading
Loading