Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
58 changes: 53 additions & 5 deletions src/generic/inplace-text-editor/InplaceTextEditor.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { fireEvent, render as baseRender, screen } from '@testing-library/react';
import {
act,
fireEvent,
render as baseRender,
screen,
} from '@testing-library/react';
import { InplaceTextEditor } from '.';

const mockOnSave = jest.fn();
Expand All @@ -24,8 +29,8 @@ describe('<InplaceTextEditor />', () => {
expect(screen.queryByRole('button', { name: /edit/ })).not.toBeInTheDocument();
});

it('should render the edit button if alwaysShowEditButton is true', () => {
render(<InplaceTextEditor text="Test text" onSave={mockOnSave} alwaysShowEditButton />);
it('should render the edit button', () => {
render(<InplaceTextEditor text="Test text" onSave={mockOnSave} />);

expect(screen.getByText('Test text')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /edit/i })).toBeInTheDocument();
Expand All @@ -36,7 +41,10 @@ describe('<InplaceTextEditor />', () => {

const title = screen.getByText('Test text');
expect(title).toBeInTheDocument();
fireEvent.click(title);

const editButton = screen.getByRole('button', { name: /edit/i });
expect(editButton).toBeInTheDocument();
fireEvent.click(editButton);

const textBox = screen.getByRole('textbox');

Expand All @@ -52,7 +60,10 @@ describe('<InplaceTextEditor />', () => {

const title = screen.getByText('Test text');
expect(title).toBeInTheDocument();
fireEvent.click(title);

const editButton = screen.getByRole('button', { name: /edit/i });
expect(editButton).toBeInTheDocument();
fireEvent.click(editButton);

const textBox = screen.getByRole('textbox');

Expand All @@ -62,4 +73,41 @@ describe('<InplaceTextEditor />', () => {
expect(textBox).not.toBeInTheDocument();
expect(mockOnSave).not.toHaveBeenCalled();
});

it('should show the new text while processing and roolback in case of error', async () => {
let rejecter: (err: Error) => void;
const longMockOnSave = jest.fn().mockReturnValue(
new Promise<void>((_resolve, reject) => {
rejecter = reject;
}),
);
render(<InplaceTextEditor text="Test text" onSave={longMockOnSave} />);

const text = screen.getByText('Test text');
expect(text).toBeInTheDocument();

const editButton = screen.getByRole('button', { name: /edit/i });
expect(editButton).toBeInTheDocument();
fireEvent.click(editButton);

const textBox = screen.getByRole('textbox');

fireEvent.change(textBox, { target: { value: 'New text' } });
fireEvent.keyDown(textBox, { key: 'Enter', code: 'Enter', charCode: 13 });

expect(textBox).not.toBeInTheDocument();
expect(longMockOnSave).toHaveBeenCalledWith('New text');

// Show pending new text
const newText = screen.getByText('New text');
expect(newText).toBeInTheDocument();

await act(async () => { rejecter(new Error('error')); });

// Remove pending new text on error
expect(newText).not.toBeInTheDocument();

// Show original text
expect(screen.getByText('Test text')).toBeInTheDocument();
});
});
148 changes: 43 additions & 105 deletions src/generic/inplace-text-editor/index.tsx
Original file line number Diff line number Diff line change
@@ -1,67 +1,49 @@
import React, {
useCallback,
useEffect,
useState,
forwardRef,
} from 'react';
import {
Form,
Icon,
IconButton,
OverlayTrigger,
Stack,
} from '@openedx/paragon';
import { Edit } from '@openedx/paragon/icons';
import { useIntl } from '@edx/frontend-platform/i18n';

import messages from './messages';

interface IconWrapperProps {
popper: any;
children: React.ReactNode;
[key: string]: any;
}

const IconWrapper = forwardRef<HTMLDivElement, IconWrapperProps>(({ popper, children, ...props }, ref) => {
useEffect(() => {
// This is a workaround to force the popper to update its position when
// the editor is opened.
// Ref: https://react-bootstrap.netlify.app/docs/components/overlays/#updating-position-dynamically
popper.scheduleUpdate();
}, [popper, children]);

return (
<div ref={ref} {...props}>
{children}
</div>
);
});

interface InplaceTextEditorProps {
text: string;
onSave: (newText: string) => void;
onSave: (newText: string) => Promise<void>;
readOnly?: boolean;
textClassName?: string;
alwaysShowEditButton?: boolean;
}

export const InplaceTextEditor: React.FC<InplaceTextEditorProps> = ({
text,
onSave,
readOnly = false,
textClassName,
alwaysShowEditButton = false,
}) => {
const intl = useIntl();
const [inputIsActive, setIsActive] = useState(false);
const [newText, setNewText] = useState<string>(); // state with the new text while updating

const handleOnChangeText = useCallback(
(event) => {
const newText = event.target.value;
if (newText && newText !== text) {
onSave(newText);
}
async (event: React.ChangeEvent<HTMLInputElement> | React.KeyboardEvent<HTMLInputElement>) => {
const inputText = event.currentTarget.value;
setIsActive(false);
if (inputText && inputText !== text) {
setNewText(inputText);
try {
await onSave(inputText);
} catch {
// don't propagate the exception
} finally {
setNewText(undefined);
}

@rpenido rpenido May 14, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Using the optimistic update from react query works for most cases, but sometimes the updated data is too deep in the cache (the title of a block inside a unit is stored on the container children array).
To help with these cases, we are using the newText state here to show the pending new text until the onSave promise resolves.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could you add a comment here to explain this? Otherwise we might be scratching our heads about it later :)

}
},
[text],
);
Expand All @@ -78,86 +60,42 @@ export const InplaceTextEditor: React.FC<InplaceTextEditorProps> = ({
}
};

if (readOnly) {
if (readOnly || newText) {
return (
<span className={textClassName}>
{text}
{newText || text}
</span>
);
}

if (alwaysShowEditButton) {
return (
<Stack
direction="horizontal"
gap={1}
>
{inputIsActive
? (
<Form.Control
autoFocus
type="text"
aria-label="Text input"
defaultValue={text}
onBlur={handleOnChangeText}
onKeyDown={handleOnKeyDown}
/>
)
: (
<span className={textClassName}>
{text}
</span>
)}
<IconButton
src={Edit}
iconAs={Icon}
alt={intl.formatMessage(messages.editTextButtonAlt)}
onClick={handleEdit}
size="inline"
/>
</Stack>
);
}

return (
<OverlayTrigger
trigger={['hover', 'focus']}
placement="right"
overlay={(
<IconWrapper>
<Icon
id="edit-text-icon"
src={Edit}
className="ml-1.5"
onClick={handleEdit}
/>
</IconWrapper>
)}
<Stack
direction="horizontal"
gap={1}
>
<div>
{inputIsActive
? (
<Form.Control
autoFocus
type="text"
aria-label="Text input"
defaultValue={text}
onBlur={handleOnChangeText}
onKeyDown={handleOnKeyDown}
/>
)
: (
<span
onClick={handleEdit}
onKeyDown={handleEdit}
className={textClassName}
role="button"
tabIndex={0}
>
{text}
</span>
)}
</div>
</OverlayTrigger>
{inputIsActive
? (
<Form.Control
autoFocus
type="text"
aria-label="Text input"
defaultValue={text}
onBlur={handleOnChangeText}
onKeyDown={handleOnKeyDown}
/>
)
: (
<span className={textClassName}>
{text}
</span>
)}
<IconButton
src={Edit}
iconAs={Icon}
alt={intl.formatMessage(messages.editTextButtonAlt)}
onClick={handleEdit}
size="inline"
/>
</Stack>
);
};
15 changes: 8 additions & 7 deletions src/library-authoring/collections/CollectionInfoHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@ const CollectionInfoHeader = () => {
const updateMutation = useUpdateCollection(libraryId, collectionId);
const { showToast } = useContext(ToastContext);

const handleSaveTitle = (newTitle: string) => {
updateMutation.mutateAsync({
title: newTitle,
}).then(() => {
const handleSaveTitle = async (newTitle: string) => {
try {
await updateMutation.mutateAsync({
title: newTitle,
});
showToast(intl.formatMessage(messages.updateCollectionSuccessMsg));
}).catch(() => {
} catch (err) {
showToast(intl.formatMessage(messages.updateCollectionErrorMsg));
});
throw err;
}
};

if (!collection) {
Expand All @@ -46,7 +48,6 @@ const CollectionInfoHeader = () => {
text={collection.title}
readOnly={readOnly}
textClassName="font-weight-bold m-1.5"
alwaysShowEditButton
/>
);
};
Expand Down
19 changes: 10 additions & 9 deletions src/library-authoring/component-info/ComponentInfoHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,18 @@ const ComponentInfoHeader = () => {
const updateMutation = useUpdateXBlockFields(usageKey);
const { showToast } = useContext(ToastContext);

const handleSaveDisplayName = (newDisplayName: string) => {
updateMutation.mutateAsync({
metadata: {
display_name: newDisplayName,
},
}).then(() => {
const handleSaveDisplayName = async (newDisplayName: string) => {
try {
await updateMutation.mutateAsync({
metadata: {
display_name: newDisplayName,
},
});
showToast(intl.formatMessage(messages.updateComponentSuccessMsg));
}).catch(() => {
} catch (err) {
showToast(intl.formatMessage(messages.updateComponentErrorMsg));
});
throw err;
}
};

if (!xblockFields) {
Expand All @@ -48,7 +50,6 @@ const ComponentInfoHeader = () => {
text={xblockFields?.displayName}
readOnly={readOnly}
textClassName="font-weight-bold m-1.5"
alwaysShowEditButton
/>
);
};
Expand Down
15 changes: 8 additions & 7 deletions src/library-authoring/containers/ContainerInfoHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,16 @@ const ContainerInfoHeader = () => {
const updateMutation = useUpdateContainer(containerId);
const { showToast } = useContext(ToastContext);

const handleSaveDisplayName = (newDisplayName: string) => {
updateMutation.mutateAsync({
displayName: newDisplayName,
}).then(() => {
const handleSaveDisplayName = async (newDisplayName: string) => {
try {
await updateMutation.mutateAsync({
displayName: newDisplayName,
});
showToast(intl.formatMessage(messages.updateContainerSuccessMsg));
}).catch(() => {
} catch (err) {
showToast(intl.formatMessage(messages.updateContainerErrorMsg));
});
throw err;
}
};

if (!container) {
Expand All @@ -45,7 +47,6 @@ const ContainerInfoHeader = () => {
text={container.displayName}
readOnly={readOnly}
textClassName="font-weight-bold m-1.5"
alwaysShowEditButton
/>
);
};
Expand Down
2 changes: 1 addition & 1 deletion src/library-authoring/containers/UnitInfo.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,6 @@ describe('<UnitInfo />', () => {
it('show only published content', async () => {
render(true);
expect(await screen.findByTestId('unit-info-menu-toggle')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /text block published 1/i })).toBeInTheDocument();
expect(screen.getByText(/text block published 1/i)).toBeInTheDocument();
});
});
Loading