Skip to content
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
23 changes: 21 additions & 2 deletions packages/ra-input-rich-text/src/RichTextInput.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as React from 'react';
import expect from 'expect';
import { render, waitFor } from '@testing-library/react';
import { Basic } from './RichTextInput.stories';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Basic, EditorRecreation } from './RichTextInput.stories';

describe('<RichTextInput />', () => {
it('should update its content when fields value changes and add a trailing break to it', async () => {
Expand All @@ -23,4 +24,22 @@ describe('<RichTextInput />', () => {
);
});
});

it('should update its content when the editor is recreated while the field value changes', async () => {
const { container } = render(<EditorRecreation />);

await waitFor(() => {
expect(container.querySelector('.ProseMirror')?.innerHTML).toEqual(
'<p>This post is a draft, you can edit it.</p>'
);
});

await userEvent.click(screen.getByText('Switch post'));

await waitFor(() => {
expect(container.querySelector('.ProseMirror')?.innerHTML).toEqual(
'<p>This post is published, it is read-only.</p>'
);
});
});
});
61 changes: 60 additions & 1 deletion packages/ra-input-rich-text/src/RichTextInput.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
Toolbar as RAToolbar,
SaveButton,
} from 'ra-ui-materialui';
import { useWatch } from 'react-hook-form';
import { useFormContext, useWatch } from 'react-hook-form';
import fakeRestDataProvider from 'ra-data-fakerest';
import { Routes, Route } from 'react-router-dom';
import Mention from '@tiptap/extension-mention';
Expand Down Expand Up @@ -112,6 +112,65 @@ export const ReadOnly = (props: Partial<SimpleFormProps>) => (
</AdminContext>
);

const postsToSwitch = [
{ body: '<p>This post is a draft, you can edit it.</p>', readOnly: false },
{ body: '<p>This post is published, it is read-only.</p>', readOnly: true },
];

const SwitchPostButton = ({
postIndex,
onSwitch,
}: {
postIndex: number;
onSwitch: (index: number) => void;
}) => {
const { setValue } = useFormContext();
return (
<Button
onClick={() => {
const nextIndex = (postIndex + 1) % postsToSwitch.length;
setValue('body', postsToSwitch[nextIndex].body);
onSwitch(nextIndex);
}}
>
Switch post
</Button>
);
};

/**
* Changing the value and the readOnly prop at the same time recreates the editor
* while the content sync effect still references the previous (destroyed) one.
* Clicking on "Switch post" used to throw
* "Cannot read properties of null (reading 'commands')".
*/
export const EditorRecreation = (props: Partial<SimpleFormProps>) => {
const [postIndex, setPostIndex] = React.useState(0);
return (
<AdminContext i18nProvider={i18nProvider}>
<ResourceContextProvider value="posts">
<Card>
<SimpleForm
defaultValues={{ body: postsToSwitch[0].body }}
onSubmit={() => {}}
{...props}
>
<SwitchPostButton
postIndex={postIndex}
onSwitch={setPostIndex}
/>
<RichTextInput
source="body"
readOnly={postsToSwitch[postIndex].readOnly}
/>
<FormInspector />
</SimpleForm>
</Card>
</ResourceContextProvider>
</AdminContext>
);
};

export const Small = (props: Partial<SimpleFormProps>) => (
<AdminContext i18nProvider={i18nProvider}>
<ResourceContextProvider value="posts">
Expand Down
7 changes: 6 additions & 1 deletion packages/ra-input-rich-text/src/RichTextInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,12 @@ export const RichTextInput = (props: RichTextInputProps) => {
const { error, invalid, isTouched } = fieldState;

useEffect(() => {
if (!editor) return;
// Tiptap v3's Editor.destroy() sets commandManager to null, and the
// `commands` getter dereferences it. When the editor is recreated (e.g.
// readOnly/disabled/editorOptions/id change), this passive effect can run
// against the just-destroyed instance, throwing "Cannot read properties of
// null (reading 'commands')". Bail out on destroyed editors as well.
if (!editor || editor.isDestroyed) return;

const { from, to } = editor.state.selection;

Expand Down
24 changes: 24 additions & 0 deletions packages/ra-ui-materialui/src/layout/Notification.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { major as muiMajor } from '@mui/material';

import {
ConsecutiveNotifications,
Expand All @@ -8,6 +9,29 @@ import {
} from './Notification.stories';

describe('<Notification />', () => {
(muiMajor >= 6 ? it : it.skip)(
'should confirm an undoable mutation only once when its notification exits with MUI 6+',
async () => {
const deleteOne = jest
.fn()
.mockImplementation((_resource, { id }) =>
Promise.resolve({ data: { id } })
);
const dataProvider = { delete: deleteOne } as any;
const { container } = render(
<ConsecutiveUndoable dataProvider={dataProvider} />
);

(await screen.findByText('Delete post 1')).click();
await screen.findByText('Post 1 deleted');
fireEvent.click(container);

await waitFor(() => expect(deleteOne).toHaveBeenCalled());
expect(deleteOne).toHaveBeenCalledTimes(1);
expect(deleteOne).toHaveBeenCalledWith('posts', { id: 1 });
}
);

it('should confirm the first undoable notification when a second one starts', async () => {
const deleteOne = jest
.fn()
Expand Down
8 changes: 6 additions & 2 deletions packages/ra-ui-materialui/src/layout/Notification.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,12 @@ export const Notification = (inProps: NotificationProps) => {
: autoHideDurationFromMessage ?? undefined
}
disableWindowBlurListener={undoable}
TransitionProps={transitionProps}
ContentProps={contentProps}
{...(muiMajor < 6
? {
TransitionProps: transitionProps,
ContentProps: contentProps,
}
: {})}
onClose={handleRequestClose}
action={
undoable ? (
Expand Down
73 changes: 73 additions & 0 deletions packages/ra-ui-materialui/src/list/datatable/DataTable.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { QueryClient } from '@tanstack/react-query';
import * as React from 'react';
import {
ResourceContextProvider,
TestMemoryRouter,
type AuthProvider,
} from 'ra-core';
import {
Basic,
Columns,
Expand All @@ -12,6 +18,8 @@ import {
StandaloneDynamic,
StandaloneStatic,
} from './DataTable.stories';
import { DataTable } from './DataTable';
import { AdminContext } from '../../AdminContext';

describe('DataTable', () => {
it('should render one row per record in the list', async () => {
Expand Down Expand Up @@ -218,6 +226,71 @@ describe('DataTable', () => {
});
});
describe('bulkActionButtons', () => {
it('should not enable delete permission queries without an auth provider', async () => {
const queryClient = new QueryClient();

render(
<TestMemoryRouter>
<AdminContext queryClient={queryClient}>
<ResourceContextProvider value="books">
<DataTable
bulkActionsToolbar={<></>}
data={[{ id: 1 }]}
isPending={false}
onSelect={jest.fn()}
onToggleItem={jest.fn()}
selectedIds={[]}
total={1}
>
<DataTable.Col source="id" />
</DataTable>
</ResourceContextProvider>
</AdminContext>
</TestMemoryRouter>
);

await waitFor(() => {
const [query] = queryClient.getQueryCache().findAll({
queryKey: ['auth', 'canAccess'],
});
expect(query.state.fetchStatus).toBe('idle');
expect(query.state.data).toBeUndefined();
});
});

it('should not check delete permissions when bulk actions are disabled', () => {
const authProvider: AuthProvider = {
canAccess: jest.fn().mockResolvedValue(true),
checkAuth: jest.fn().mockResolvedValue(undefined),
checkError: jest.fn().mockResolvedValue(undefined),
getPermissions: jest.fn().mockResolvedValue(undefined),
login: jest.fn().mockResolvedValue(undefined),
logout: jest.fn().mockResolvedValue(undefined),
};

render(
<TestMemoryRouter>
<AdminContext authProvider={authProvider}>
<ResourceContextProvider value="books">
<DataTable
bulkActionButtons={false}
data={[{ id: 1 }]}
isPending={false}
onSelect={jest.fn()}
onToggleItem={jest.fn()}
selectedIds={[]}
total={1}
>
<DataTable.Col source="id" />
</DataTable>
</ResourceContextProvider>
</AdminContext>
</TestMemoryRouter>
);

expect(authProvider.canAccess).not.toHaveBeenCalled();
});

it('should reveal bulk delete button by default on row selection', async () => {
render(<Basic />);
const checkboxes = await screen.findAllByRole('checkbox');
Expand Down
1 change: 1 addition & 0 deletions packages/ra-ui-materialui/src/list/datatable/DataTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ export const DataTable = React.forwardRef(function DataTable<
const { canAccess: canDelete } = useCanAccess({
resource: resourceFromContext,
action: 'delete',
...(props.bulkActionButtons === false ? { enabled: false } : {}),
});

const {
Expand Down
6 changes: 3 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -14533,9 +14533,9 @@ __metadata:
linkType: hard

"ip-address@npm:^10.0.1":
version: 10.2.0
resolution: "ip-address@npm:10.2.0"
checksum: 5a00aada6e922c9c69dfc800ed5d0fa3348675ebdeed0e1575f503f27ca385b5f534363c9af7ad1daf64c1f1409388cdd3cc2e9b9b0fe1c924a431378d55075a
version: 10.4.0
resolution: "ip-address@npm:10.4.0"
checksum: d7b0bd2624fd861afbae6e49036a9b56f9506eaff7ff38592b7b4492dd5c272b53f5356dc8cc019e318acf29a96c90a3d1af1df761960267d23efa96858270fa
languageName: node
linkType: hard

Expand Down
Loading