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

Fix RichTextInput does not update when its editorOptions prop changes #9289

Merged
merged 6 commits into from
Oct 2, 2023
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
3 changes: 3 additions & 0 deletions packages/ra-input-rich-text/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
"@mui/icons-material": "^5.0.1",
"@mui/material": "^5.0.2",
"@testing-library/react": "^11.2.3",
"@tiptap/extension-mention": "^2.0.3",
"@tiptap/suggestion": "^2.0.3",
"data-generator-retail": "^4.14.4",
"ra-core": "^4.14.4",
"ra-data-fakerest": "^4.14.4",
Expand All @@ -57,6 +59,7 @@
"react-dom": "^17.0.0",
"react-hook-form": "^7.43.9",
"rimraf": "^3.0.2",
"tippy.js": "^6.3.7",
"typescript": "^5.1.3"
},
"gitHead": "b227592132da6ae5f01438fa8269e04596cdfdd8"
Expand Down
272 changes: 268 additions & 4 deletions packages/ra-input-rich-text/src/RichTextInput.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,37 @@
import * as React from 'react';
import { I18nProvider, required } from 'ra-core';
import { AdminContext, SimpleForm, SimpleFormProps } from 'ra-ui-materialui';
import { RichTextInput } from './RichTextInput';
import { RichTextInputToolbar } from './RichTextInputToolbar';
import {
I18nProvider,
required,
useGetManyReference,
useRecordContext,
} from 'ra-core';
import {
AdminContext,
Edit,
PrevNextButtons,
SimpleForm,
SimpleFormProps,
TopToolbar,
} from 'ra-ui-materialui';
import { useWatch } from 'react-hook-form';
import fakeRestDataProvider from 'ra-data-fakerest';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import Mention from '@tiptap/extension-mention';
import { ReactRenderer } from '@tiptap/react';
import tippy, { Instance as TippyInstance } from 'tippy.js';
import {
DefaultEditorOptions,
RichTextInput,
RichTextInputProps,
} from './RichTextInput';
import { RichTextInputToolbar } from './RichTextInputToolbar';
import {
List,
ListItem,
ListItemButton,
ListItemText,
Paper,
} from '@mui/material';

export default { title: 'ra-input-rich-text/RichTextInput' };

Expand Down Expand Up @@ -145,3 +173,239 @@ export const Validation = (props: Partial<SimpleFormProps>) => (
</SimpleForm>
</AdminContext>
);

const dataProvider = fakeRestDataProvider({
posts: [
{ id: 1, body: 'Post 1' },
{ id: 2, body: 'Post 2' },
{ id: 3, body: 'Post 3' },
],
tags: [
{ id: 1, name: 'tag1', post_id: 1 },
{ id: 2, name: 'tag2', post_id: 1 },
{ id: 3, name: 'tag3', post_id: 2 },
{ id: 4, name: 'tag4', post_id: 2 },
{ id: 5, name: 'tag5', post_id: 3 },
{ id: 6, name: 'tag6', post_id: 3 },
],
});

const MyRichTextInput = (props: RichTextInputProps) => {
const record = useRecordContext();
const tags = useGetManyReference('tags', {
target: 'post_id',
id: record.id,
});

const editorOptions = React.useMemo(() => {
return {
...DefaultEditorOptions,
extensions: [
...DefaultEditorOptions.extensions,
Mention.configure({
HTMLAttributes: {
class: 'mention',
},
suggestion: suggestions(tags.data?.map(t => t.name) ?? []),
}),
],
};
}, [tags.data]);

return <RichTextInput editorOptions={editorOptions} {...props} />;
};

export const CustomOptions = () => (
<MemoryRouter initialEntries={['/posts/1']}>
<AdminContext dataProvider={dataProvider}>
<Routes>
<Route
path="/posts/:id"
element={
<Edit
resource="posts"
actions={
<TopToolbar>
<PrevNextButtons />
</TopToolbar>
}
>
<SimpleForm>
<MyRichTextInput source="body" />
</SimpleForm>
</Edit>
}
/>
</Routes>
</AdminContext>
</MemoryRouter>
);

const MentionList = React.forwardRef<
MentionListRef,
{
items: string[];
command: (props: { id: string }) => void;
}
>((props, ref) => {
const [selectedIndex, setSelectedIndex] = React.useState(0);

const selectItem = index => {
const item = props.items[index];

if (item) {
props.command({ id: item });
}
};

const upHandler = () => {
setSelectedIndex(
(selectedIndex + props.items.length - 1) % props.items.length
);
};

const downHandler = () => {
setSelectedIndex((selectedIndex + 1) % props.items.length);
};

const enterHandler = () => {
selectItem(selectedIndex);
};

React.useEffect(() => setSelectedIndex(0), [props.items]);

React.useImperativeHandle(ref, () => ({
onKeyDown: ({ event }) => {
if (event.key === 'ArrowUp') {
upHandler();
return true;
}

if (event.key === 'ArrowDown') {
downHandler();
return true;
}

if (event.key === 'Enter') {
enterHandler();
return true;
}

return false;
},
}));

return (
<Paper>
<List dense disablePadding>
{props.items.length ? (
props.items.map((item, index) => (
<ListItemButton
dense
selected={index === selectedIndex}
key={index}
onClick={() => selectItem(index)}
>
{item}
</ListItemButton>
))
) : (
<ListItem className="item" dense>
<ListItemText>No result</ListItemText>
</ListItem>
)}
</List>
</Paper>
);
});

type MentionListRef = {
onKeyDown: (props: { event: React.KeyboardEvent }) => boolean;
};
const suggestions = tags => {
return {
items: ({ query }) => {
return tags
.filter(item =>
item.toLowerCase().startsWith(query.toLowerCase())
)
.slice(0, 5);
},

render: () => {
let component: ReactRenderer<MentionListRef>;
let popup: TippyInstance[];

return {
onStart: props => {
component = new ReactRenderer(MentionList, {
props,
editor: props.editor,
});

if (!props.clientRect) {
return;
}

popup = tippy('body', {
getReferenceClientRect: props.clientRect,
appendTo: () => document.body,
content: component.element,
showOnCreate: true,
interactive: true,
trigger: 'manual',
placement: 'bottom-start',
});
},

onUpdate(props) {
if (component) {
component.updateProps(props);
}

if (!props.clientRect) {
return;
}

if (popup && popup[0]) {
popup[0].setProps({
getReferenceClientRect: props.clientRect,
});
}
},

onKeyDown(props) {
if (popup && popup[0] && props.event.key === 'Escape') {
popup[0].hide();

return true;
}

if (!component.ref) {
return false;
}

return component.ref.onKeyDown(props);
},

onExit() {
queueMicrotask(() => {
if (popup && popup[0] && !popup[0].state.isDestroyed) {
popup[0].destroy();
}
if (component) {
component.destroy();
}
// Remove references to the old popup and component upon destruction/exit.
// (This should prevent redundant calls to `popup.destroy()`, which Tippy
// warns in the console is a sign of a memory leak, as the `suggestion`
// plugin seems to call `onExit` both when a suggestion menu is closed after
// a user chooses an option, *and* when the editor itself is destroyed.)
popup = undefined;
component = undefined;
});
},
};
},
};
};
46 changes: 13 additions & 33 deletions packages/ra-input-rich-text/src/RichTextInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,18 +97,21 @@ export const RichTextInput = (props: RichTextInputProps) => {
formState: { isSubmitted },
} = useInput({ ...props, source, defaultValue });

const editor = useEditor({
...editorOptions,
editable: !disabled && !readOnly,
content: field.value,
editorProps: {
...editorOptions?.editorProps,
attributes: {
...editorOptions?.editorProps?.attributes,
id,
const editor = useEditor(
{
...editorOptions,
editable: !disabled && !readOnly,
content: field.value,
editorProps: {
...editorOptions?.editorProps,
attributes: {
...editorOptions?.editorProps?.attributes,
id,
},
},
},
});
[disabled, editorOptions, readOnly, id]
);

const { error, invalid, isTouched } = fieldState;

Expand All @@ -120,32 +123,9 @@ export const RichTextInput = (props: RichTextInputProps) => {
editor.commands.setContent(field.value, false, {
preserveWhitespace: true,
});

editor.commands.setTextSelection({ from, to });
}, [editor, field.value]);

useEffect(() => {
if (!editor) return;

editor.setOptions({
editable: !disabled && !readOnly,
editorProps: {
...editorOptions?.editorProps,
attributes: {
...editorOptions?.editorProps?.attributes,
id,
},
},
});
}, [
disabled,
editor,
readOnly,
id,
editorOptions?.editorProps,
editorOptions?.editorProps?.attributes,
]);

useEffect(() => {
if (!editor) {
return;
Expand Down
Loading