mirror of
https://github.com/mattermost/mattermost.git
synced 2026-08-28 18:19:38 +08:00
[MM-63470] Fix messages being sent to the previous channel after /msg or Cmd+K (#37928)
This commit is contained in:
@@ -0,0 +1,201 @@
|
|||||||
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||||
|
// See LICENSE.txt for license information.
|
||||||
|
|
||||||
|
import {expect, test} from '@mattermost/playwright-lib';
|
||||||
|
|
||||||
|
test.describe('draft channel switch', () => {
|
||||||
|
/**
|
||||||
|
* @objective Verify a typed draft on one channel persists, restores after
|
||||||
|
* switching away and back, and posts only to the origin channel.
|
||||||
|
*/
|
||||||
|
test('typed draft stays on the origin channel after switching away and back', {tag: '@messaging'}, async ({pw}) => {
|
||||||
|
const {team, user} = await pw.initSetup();
|
||||||
|
const {channelsPage} = await pw.testBrowser.login(user);
|
||||||
|
await channelsPage.goto(team.name, 'off-topic');
|
||||||
|
await channelsPage.toBeVisible();
|
||||||
|
|
||||||
|
const originDraft = `origin-draft-${pw.random.id()}`;
|
||||||
|
const destinationMessage = `town-square-${pw.random.id()}`;
|
||||||
|
|
||||||
|
// # Type a draft in Off-Topic and do not send it
|
||||||
|
await channelsPage.centerView.postCreate.writeMessage(originDraft);
|
||||||
|
|
||||||
|
// # Switch to Town Square via the sidebar
|
||||||
|
await channelsPage.sidebarLeft.goToItem('town-square');
|
||||||
|
await channelsPage.centerView.header.toHaveTitle('Town Square');
|
||||||
|
|
||||||
|
// * Destination composer must not inherit the origin draft
|
||||||
|
expect(await channelsPage.centerView.postCreate.getInputValue()).toBe('');
|
||||||
|
|
||||||
|
// * Origin draft was persisted: the channel pencil is in the DOM
|
||||||
|
// (often CSS-hidden until hover) and the Drafts sidebar link appears
|
||||||
|
await expect(channelsPage.sidebarLeft.item('off-topic').getByTestId('draftIcon')).toHaveCount(1);
|
||||||
|
await channelsPage.sidebarLeft.draftsVisible();
|
||||||
|
|
||||||
|
// # Send a different message from Town Square
|
||||||
|
await channelsPage.centerView.postCreate.writeMessage(destinationMessage);
|
||||||
|
await channelsPage.centerView.postCreate.sendMessage();
|
||||||
|
|
||||||
|
// * Town Square shows the destination message
|
||||||
|
await channelsPage.centerView.waitUntilLastPostContains(destinationMessage);
|
||||||
|
|
||||||
|
// # Return to Off-Topic
|
||||||
|
await channelsPage.sidebarLeft.goToItem('off-topic');
|
||||||
|
await channelsPage.centerView.header.toHaveTitle('Off-Topic');
|
||||||
|
|
||||||
|
// * Origin draft is still in the composer
|
||||||
|
expect(await channelsPage.centerView.postCreate.getInputValue()).toBe(originDraft);
|
||||||
|
|
||||||
|
// # Send the restored draft
|
||||||
|
await channelsPage.centerView.postCreate.sendMessage();
|
||||||
|
|
||||||
|
// * Off-Topic shows the origin draft message
|
||||||
|
await channelsPage.centerView.waitUntilLastPostContains(originDraft);
|
||||||
|
|
||||||
|
// # Return to Town Square
|
||||||
|
await channelsPage.sidebarLeft.goToItem('town-square');
|
||||||
|
await channelsPage.centerView.header.toHaveTitle('Town Square');
|
||||||
|
|
||||||
|
// * Origin draft did not post to Town Square
|
||||||
|
await expect(channelsPage.centerView.container).not.toContainText(originDraft);
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @objective Verify Ctrl/Cmd+K restores the destination draft and routes
|
||||||
|
* messages to the selected channel with concurrent React enabled.
|
||||||
|
*/
|
||||||
|
test(
|
||||||
|
'quick switcher keeps drafts and messages scoped to their channels with concurrent React',
|
||||||
|
{tag: '@messaging'},
|
||||||
|
async ({pw}) => {
|
||||||
|
await pw.ensureFeatureFlag('EnableConcurrentReact', true);
|
||||||
|
|
||||||
|
const {team, user} = await pw.initSetup();
|
||||||
|
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||||
|
|
||||||
|
await channelsPage.goto(team.name, 'off-topic');
|
||||||
|
await channelsPage.toBeVisible();
|
||||||
|
|
||||||
|
const originDraft = `quick-switch-origin-${pw.random.id()}`;
|
||||||
|
const destinationMessage = `quick-switch-destination-${pw.random.id()}`;
|
||||||
|
|
||||||
|
// # Leave a draft in Off-Topic
|
||||||
|
await channelsPage.centerView.postCreate.writeMessage(originDraft);
|
||||||
|
|
||||||
|
// # Switch to Town Square using Ctrl/Cmd+K
|
||||||
|
await page.keyboard.press('ControlOrMeta+K');
|
||||||
|
await expect(channelsPage.findChannelsModal.input).toBeVisible();
|
||||||
|
await channelsPage.findChannelsModal.input.fill('town');
|
||||||
|
await channelsPage.findChannelsModal.selectChannel('town-square');
|
||||||
|
await channelsPage.centerView.header.toHaveTitle('Town Square');
|
||||||
|
|
||||||
|
// * Town Square did not inherit the Off-Topic draft
|
||||||
|
expect(await channelsPage.centerView.postCreate.getInputValue()).toBe('');
|
||||||
|
|
||||||
|
// # Send a destination-owned message
|
||||||
|
await channelsPage.centerView.postCreate.writeMessage(destinationMessage);
|
||||||
|
await channelsPage.centerView.postCreate.sendMessage();
|
||||||
|
await channelsPage.centerView.waitUntilLastPostContains(destinationMessage);
|
||||||
|
|
||||||
|
// # Return to Off-Topic using Ctrl/Cmd+K
|
||||||
|
await page.keyboard.press('ControlOrMeta+K');
|
||||||
|
await expect(channelsPage.findChannelsModal.input).toBeVisible();
|
||||||
|
await channelsPage.findChannelsModal.input.fill('off');
|
||||||
|
await channelsPage.findChannelsModal.selectChannel('off-topic');
|
||||||
|
await channelsPage.centerView.header.toHaveTitle('Off-Topic');
|
||||||
|
|
||||||
|
// * The origin draft was restored and the destination message was not misrouted
|
||||||
|
expect(await channelsPage.centerView.postCreate.getInputValue()).toBe(originDraft);
|
||||||
|
await expect(channelsPage.centerView.container).not.toContainText(destinationMessage);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @objective Verify sending /msg to an existing DM clears the origin
|
||||||
|
* channel draft instead of leaving it behind for later restoration.
|
||||||
|
*
|
||||||
|
* @precondition
|
||||||
|
* The DM channel already exists so the redirect uses the fast path with no
|
||||||
|
* createDirectChannel round trip.
|
||||||
|
*/
|
||||||
|
test(
|
||||||
|
'sending /msg to an existing DM clears the origin draft instead of restoring it',
|
||||||
|
{tag: '@slash_commands'},
|
||||||
|
async ({pw}) => {
|
||||||
|
const {adminClient, userClient, team, user} = await pw.initSetup();
|
||||||
|
const [target] = await adminClient.createUsers(team.id, 1, 'draft-msg');
|
||||||
|
|
||||||
|
await userClient.createDirectChannel([user.id, target.id]);
|
||||||
|
|
||||||
|
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||||
|
await channelsPage.goto(team.name, 'off-topic');
|
||||||
|
await channelsPage.toBeVisible();
|
||||||
|
|
||||||
|
// Trailing space dismisses the @mention autocomplete.
|
||||||
|
await channelsPage.centerView.postCreate.writeMessage(`/msg @${target.username} `);
|
||||||
|
await channelsPage.centerView.postCreate.sendMessage();
|
||||||
|
|
||||||
|
await channelsPage.centerView.header.toHaveTitle(target.username);
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/${team.name}/messages/@${target.username}`));
|
||||||
|
|
||||||
|
// * Destination composer is empty — it did not adopt the /msg text
|
||||||
|
expect(await channelsPage.centerView.postCreate.getInputValue()).toBe('');
|
||||||
|
|
||||||
|
// # Return to Off-Topic
|
||||||
|
await channelsPage.sidebarLeft.goToItem('off-topic');
|
||||||
|
await channelsPage.centerView.header.toHaveTitle('Off-Topic');
|
||||||
|
|
||||||
|
// * Origin draft was cleared by the submit, not left behind as /msg
|
||||||
|
expect(await channelsPage.centerView.postCreate.getInputValue()).toBe('');
|
||||||
|
await expect(channelsPage.sidebarLeft.item('off-topic').getByTestId('draftIcon')).toHaveCount(0);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @objective Verify a message typed after a settled /msg redirect to an
|
||||||
|
* existing DM posts to the DM, not the origin channel.
|
||||||
|
*
|
||||||
|
* @precondition
|
||||||
|
* The DM channel already exists so the redirect uses the fast path with no
|
||||||
|
* createDirectChannel round trip.
|
||||||
|
*/
|
||||||
|
test(
|
||||||
|
'posts a later message to the DM rather than the origin channel after /msg',
|
||||||
|
{tag: '@slash_commands'},
|
||||||
|
async ({pw}) => {
|
||||||
|
const {adminClient, userClient, team, user} = await pw.initSetup();
|
||||||
|
const [target] = await adminClient.createUsers(team.id, 1, 'stale-dm');
|
||||||
|
|
||||||
|
const dmChannel = await userClient.createDirectChannel([user.id, target.id]);
|
||||||
|
await userClient.createPost({
|
||||||
|
channel_id: dmChannel.id,
|
||||||
|
message: 'seeding the existing DM',
|
||||||
|
} as Parameters<typeof userClient.createPost>[0]);
|
||||||
|
|
||||||
|
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||||
|
await channelsPage.goto(team.name, 'off-topic');
|
||||||
|
await channelsPage.toBeVisible();
|
||||||
|
|
||||||
|
// Trailing space dismisses the @mention autocomplete.
|
||||||
|
await channelsPage.centerView.postCreate.writeMessage(`/msg @${target.username} `);
|
||||||
|
await channelsPage.centerView.postCreate.sendMessage();
|
||||||
|
|
||||||
|
await channelsPage.centerView.header.toHaveTitle(target.username);
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/${team.name}/messages/@${target.username}`));
|
||||||
|
|
||||||
|
const message = `stale-draft-${pw.random.id()}`;
|
||||||
|
await channelsPage.centerView.postCreate.writeMessage(message);
|
||||||
|
await channelsPage.centerView.postCreate.sendMessage();
|
||||||
|
|
||||||
|
// * Follow-up message appears in the DM
|
||||||
|
await channelsPage.centerView.waitUntilLastPostContains(message);
|
||||||
|
|
||||||
|
// # Return to Off-Topic
|
||||||
|
await channelsPage.sidebarLeft.goToItem('off-topic');
|
||||||
|
await channelsPage.centerView.header.toHaveTitle('Off-Topic');
|
||||||
|
|
||||||
|
// * Follow-up message did not post to the origin channel
|
||||||
|
await expect(channelsPage.centerView.container).not.toContainText(message);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -279,7 +279,7 @@ describe('rhs view actions', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
test('it adds message into history', () => {
|
test('it adds message into history', () => {
|
||||||
store.dispatch(onSubmit(draft, {}));
|
store.dispatch(onSubmit(channelId, rootId, draft, {}));
|
||||||
|
|
||||||
const testStore = mockStore(initialState);
|
const testStore = mockStore(initialState);
|
||||||
testStore.dispatch(addMessageIntoHistory('test'));
|
testStore.dispatch(addMessageIntoHistory('test'));
|
||||||
@@ -290,7 +290,7 @@ describe('rhs view actions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('it submits a command when message is /away', () => {
|
test('it submits a command when message is /away', () => {
|
||||||
store.dispatch(onSubmit({
|
store.dispatch(onSubmit(channelId, rootId, {
|
||||||
message: '/away',
|
message: '/away',
|
||||||
fileInfos: [],
|
fileInfos: [],
|
||||||
uploadsInProgress: [],
|
uploadsInProgress: [],
|
||||||
@@ -307,7 +307,7 @@ describe('rhs view actions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('it submits a regular post when options.ignoreSlash is true', () => {
|
test('it submits a regular post when options.ignoreSlash is true', () => {
|
||||||
store.dispatch(onSubmit({
|
store.dispatch(onSubmit(channelId, rootId, {
|
||||||
message: '/fakecommand',
|
message: '/fakecommand',
|
||||||
fileInfos: [],
|
fileInfos: [],
|
||||||
uploadsInProgress: [],
|
uploadsInProgress: [],
|
||||||
@@ -323,7 +323,7 @@ describe('rhs view actions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('it submits a regular post when message is something else', () => {
|
test('it submits a regular post when message is something else', () => {
|
||||||
store.dispatch(onSubmit({
|
store.dispatch(onSubmit(channelId, rootId, {
|
||||||
message: 'test msg',
|
message: 'test msg',
|
||||||
fileInfos: [],
|
fileInfos: [],
|
||||||
uploadsInProgress: [],
|
uploadsInProgress: [],
|
||||||
|
|||||||
@@ -175,12 +175,14 @@ export type OnSubmitOptions = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function onSubmit(
|
export function onSubmit(
|
||||||
|
channelId: string,
|
||||||
|
rootId: string,
|
||||||
draft: PostDraft,
|
draft: PostDraft,
|
||||||
options: OnSubmitOptions,
|
options: OnSubmitOptions,
|
||||||
schedulingInfo?: SchedulingInfo,
|
schedulingInfo?: SchedulingInfo,
|
||||||
): ActionFuncAsync<SubmitPostReturnType> {
|
): ActionFuncAsync<SubmitPostReturnType> {
|
||||||
return async (dispatch, getState) => {
|
return async (dispatch, getState) => {
|
||||||
const {message, channelId, rootId} = draft;
|
const {message} = draft;
|
||||||
const state = getState();
|
const state = getState();
|
||||||
|
|
||||||
dispatch(addMessageIntoHistory(message));
|
dispatch(addMessageIntoHistory(message));
|
||||||
|
|||||||
@@ -3,16 +3,20 @@
|
|||||||
|
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
|
import type {PostType} from '@mattermost/types/posts';
|
||||||
|
import {PostPriority} from '@mattermost/types/posts';
|
||||||
|
|
||||||
import Permissions from 'mattermost-redux/constants/permissions';
|
import Permissions from 'mattermost-redux/constants/permissions';
|
||||||
|
|
||||||
|
import {onSubmit} from 'actions/views/create_comment';
|
||||||
import {removeDraft, updateDraft} from 'actions/views/drafts';
|
import {removeDraft, updateDraft} from 'actions/views/drafts';
|
||||||
|
|
||||||
import type {FileUpload} from 'components/file_upload/file_upload';
|
import type {FileUpload} from 'components/file_upload/file_upload';
|
||||||
import type Textbox from 'components/textbox/textbox';
|
import type Textbox from 'components/textbox/textbox';
|
||||||
|
|
||||||
import mergeObjects from 'packages/mattermost-redux/test/merge_objects';
|
import mergeObjects from 'packages/mattermost-redux/test/merge_objects';
|
||||||
import {renderWithContext, userEvent, screen} from 'tests/react_testing_utils';
|
import {renderWithContext, userEvent, screen, act, fireEvent} from 'tests/react_testing_utils';
|
||||||
import Constants, {Locations, StoragePrefixes} from 'utils/constants';
|
import Constants, {Locations, PostTypes, StoragePrefixes} from 'utils/constants';
|
||||||
import {TestHelper} from 'utils/test_helper';
|
import {TestHelper} from 'utils/test_helper';
|
||||||
|
|
||||||
import type {PostDraft} from 'types/store/draft';
|
import type {PostDraft} from 'types/store/draft';
|
||||||
@@ -26,6 +30,11 @@ jest.mock('actions/views/drafts', () => ({
|
|||||||
removeDraft: jest.fn((...args) => ({type: 'MOCK_REMOVE_DRAFT', args})),
|
removeDraft: jest.fn((...args) => ({type: 'MOCK_REMOVE_DRAFT', args})),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
jest.mock('actions/views/create_comment', () => ({
|
||||||
|
...jest.requireActual('actions/views/create_comment'),
|
||||||
|
onSubmit: jest.fn(() => () => Promise.resolve({data: true})),
|
||||||
|
}));
|
||||||
|
|
||||||
jest.mock('utils/exec_commands.ts', () => ({
|
jest.mock('utils/exec_commands.ts', () => ({
|
||||||
focusAndInsertText: (element: HTMLElement, text: string) => {
|
focusAndInsertText: (element: HTMLElement, text: string) => {
|
||||||
element.focus();
|
element.focus();
|
||||||
@@ -44,6 +53,7 @@ jest.mock('utils/exec_commands.ts', () => ({
|
|||||||
|
|
||||||
const mockedRemoveDraft = jest.mocked(removeDraft);
|
const mockedRemoveDraft = jest.mocked(removeDraft);
|
||||||
const mockedUpdateDraft = jest.mocked(updateDraft);
|
const mockedUpdateDraft = jest.mocked(updateDraft);
|
||||||
|
const mockedOnSubmit = jest.mocked(onSubmit);
|
||||||
|
|
||||||
const currentUserId = 'current_user_id';
|
const currentUserId = 'current_user_id';
|
||||||
const channelId = 'current_channel_id';
|
const channelId = 'current_channel_id';
|
||||||
@@ -195,6 +205,10 @@ const baseProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
describe('components/avanced_text_editor/advanced_text_editor', () => {
|
describe('components/avanced_text_editor/advanced_text_editor', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
describe('keyDown behavior', () => {
|
describe('keyDown behavior', () => {
|
||||||
it('ESC should blur the input', async () => {
|
it('ESC should blur the input', async () => {
|
||||||
renderWithContext(
|
renderWithContext(
|
||||||
@@ -247,8 +261,6 @@ describe('components/avanced_text_editor/advanced_text_editor', () => {
|
|||||||
jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT + 50);
|
jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT + 50);
|
||||||
expect(mockedRemoveDraft).toHaveBeenCalled();
|
expect(mockedRemoveDraft).toHaveBeenCalled();
|
||||||
expect(mockedUpdateDraft).not.toHaveBeenCalled();
|
expect(mockedUpdateDraft).not.toHaveBeenCalled();
|
||||||
|
|
||||||
jest.useRealTimers();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -287,6 +299,225 @@ describe('components/avanced_text_editor/advanced_text_editor', () => {
|
|||||||
expect(screen.getByPlaceholderText('Write to Other Channel')).toHaveValue('a different draft');
|
expect(screen.getByPlaceholderText('Write to Other Channel')).toHaveValue('a different draft');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should submit a destination-owned draft while the textbox still holds the previous channel value', async () => {
|
||||||
|
const sourceDraft = 'stale draft from the source channel';
|
||||||
|
const destinationMessage = 'new message composed for the destination channel';
|
||||||
|
const sourceFileInfo = TestHelper.getFileInfoMock({id: 'source-file-id', name: 'source-file.txt'});
|
||||||
|
const destinationFileInfo = TestHelper.getFileInfoMock({id: 'destination-file-id', name: 'destination-file.txt'});
|
||||||
|
const sourceMetadata = {priority: {priority: PostPriority.URGENT}, files: [sourceFileInfo]};
|
||||||
|
const destinationMetadata = {priority: {priority: PostPriority.IMPORTANT}, files: [destinationFileInfo]};
|
||||||
|
const sourceProps = {sourceOnly: 'source-prop'};
|
||||||
|
const destinationProps = {destinationOnly: 'destination-prop'};
|
||||||
|
const typeOnSwitchRef = {current: false};
|
||||||
|
|
||||||
|
function Harness({editorChannelId}: {editorChannelId: string}) {
|
||||||
|
const [sendDestinationMessage, setSendDestinationMessage] = React.useState(false);
|
||||||
|
|
||||||
|
// Cmd+K can focus the composer after channelId updates but before the
|
||||||
|
// composer's effect replaces the local draft. Layout effects run before
|
||||||
|
// that effect, so typing here lands in the window the user reported.
|
||||||
|
React.useLayoutEffect(() => {
|
||||||
|
if (!typeOnSwitchRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
typeOnSwitchRef.current = false;
|
||||||
|
|
||||||
|
const textbox = screen.getByPlaceholderText('Write to Other Channel');
|
||||||
|
expect(textbox).toHaveValue(sourceDraft);
|
||||||
|
|
||||||
|
// SuggestionBox listens to onInput, not onChange.
|
||||||
|
fireEvent.input(textbox, {target: {value: destinationMessage}});
|
||||||
|
setSendDestinationMessage(true);
|
||||||
|
}, [editorChannelId]);
|
||||||
|
|
||||||
|
// The typed message is applied on the next render, still before the
|
||||||
|
// draft-swap effect, so sending from this layout effect submits while
|
||||||
|
// draft.channelId is still the source channel.
|
||||||
|
React.useLayoutEffect(() => {
|
||||||
|
if (!sendDestinationMessage) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByTestId('SendMessageButton'));
|
||||||
|
}, [sendDestinationMessage]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AdvancedTextEditor
|
||||||
|
{...baseProps}
|
||||||
|
channelId={editorChannelId}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const {rerender} = renderWithContext(
|
||||||
|
<Harness editorChannelId={channelId}/>,
|
||||||
|
mergeObjects(initialState, {
|
||||||
|
storage: {
|
||||||
|
storage: {
|
||||||
|
[StoragePrefixes.DRAFT + channelId]: {
|
||||||
|
value: TestHelper.getPostDraftMock({
|
||||||
|
message: sourceDraft,
|
||||||
|
channelId,
|
||||||
|
metadata: sourceMetadata,
|
||||||
|
type: PostTypes.BURN_ON_READ as PostType,
|
||||||
|
props: sourceProps,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
[StoragePrefixes.DRAFT + otherChannelId]: {
|
||||||
|
value: TestHelper.getPostDraftMock({
|
||||||
|
message: '',
|
||||||
|
channelId: otherChannelId,
|
||||||
|
metadata: destinationMetadata,
|
||||||
|
type: PostTypes.ME as PostType,
|
||||||
|
props: destinationProps,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByPlaceholderText('Write to Test Channel')).toHaveValue(sourceDraft);
|
||||||
|
|
||||||
|
typeOnSwitchRef.current = true;
|
||||||
|
rerender(<Harness editorChannelId={otherChannelId}/>);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mockedOnSubmit).toHaveBeenCalledWith(
|
||||||
|
otherChannelId,
|
||||||
|
'',
|
||||||
|
expect.objectContaining({
|
||||||
|
message: destinationMessage,
|
||||||
|
channelId: otherChannelId,
|
||||||
|
rootId: '',
|
||||||
|
fileInfos: [destinationFileInfo],
|
||||||
|
metadata: destinationMetadata,
|
||||||
|
type: PostTypes.ME,
|
||||||
|
props: destinationProps,
|
||||||
|
}),
|
||||||
|
expect.anything(),
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
expect(mockedOnSubmit).toHaveBeenCalledWith(
|
||||||
|
otherChannelId,
|
||||||
|
'',
|
||||||
|
expect.not.objectContaining({
|
||||||
|
fileInfos: [sourceFileInfo],
|
||||||
|
metadata: sourceMetadata,
|
||||||
|
type: PostTypes.BURN_ON_READ,
|
||||||
|
props: sourceProps,
|
||||||
|
}),
|
||||||
|
expect.anything(),
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should persist text typed during a channel switch only under the destination draft', async () => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
|
||||||
|
const sourceDraft = 'stale draft from the source channel';
|
||||||
|
const destinationMessage = 'new message composed for the destination channel';
|
||||||
|
const sourceFileInfo = TestHelper.getFileInfoMock({id: 'source-file-id', name: 'source-file.txt'});
|
||||||
|
const destinationFileInfo = TestHelper.getFileInfoMock({id: 'destination-file-id', name: 'destination-file.txt'});
|
||||||
|
const sourceMetadata = {priority: {priority: PostPriority.URGENT}, files: [sourceFileInfo]};
|
||||||
|
const destinationMetadata = {priority: {priority: PostPriority.IMPORTANT}, files: [destinationFileInfo]};
|
||||||
|
const sourceProps = {sourceOnly: 'source-prop'};
|
||||||
|
const destinationProps = {destinationOnly: 'destination-prop'};
|
||||||
|
const typeOnSwitchRef = {current: false};
|
||||||
|
|
||||||
|
function Harness({editorChannelId}: {editorChannelId: string}) {
|
||||||
|
React.useLayoutEffect(() => {
|
||||||
|
if (!typeOnSwitchRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
typeOnSwitchRef.current = false;
|
||||||
|
|
||||||
|
const textbox = screen.getByPlaceholderText('Write to Other Channel');
|
||||||
|
expect(textbox).toHaveValue(sourceDraft);
|
||||||
|
fireEvent.input(textbox, {target: {value: destinationMessage}});
|
||||||
|
}, [editorChannelId]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AdvancedTextEditor
|
||||||
|
{...baseProps}
|
||||||
|
channelId={editorChannelId}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const {rerender} = renderWithContext(
|
||||||
|
<Harness editorChannelId={channelId}/>,
|
||||||
|
mergeObjects(initialState, {
|
||||||
|
storage: {
|
||||||
|
storage: {
|
||||||
|
[StoragePrefixes.DRAFT + channelId]: {
|
||||||
|
value: TestHelper.getPostDraftMock({
|
||||||
|
message: sourceDraft,
|
||||||
|
channelId,
|
||||||
|
metadata: sourceMetadata,
|
||||||
|
type: PostTypes.BURN_ON_READ as PostType,
|
||||||
|
props: sourceProps,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
[StoragePrefixes.DRAFT + otherChannelId]: {
|
||||||
|
value: TestHelper.getPostDraftMock({
|
||||||
|
message: '',
|
||||||
|
channelId: otherChannelId,
|
||||||
|
metadata: destinationMetadata,
|
||||||
|
type: PostTypes.ME as PostType,
|
||||||
|
props: destinationProps,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
mockedUpdateDraft.mockClear();
|
||||||
|
typeOnSwitchRef.current = true;
|
||||||
|
rerender(<Harness editorChannelId={otherChannelId}/>);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
jest.advanceTimersByTime(Constants.SAVE_DRAFT_TIMEOUT + 50);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(mockedUpdateDraft).toHaveBeenCalledWith(
|
||||||
|
StoragePrefixes.DRAFT + otherChannelId,
|
||||||
|
expect.objectContaining({
|
||||||
|
message: destinationMessage,
|
||||||
|
channelId: otherChannelId,
|
||||||
|
rootId: '',
|
||||||
|
fileInfos: [destinationFileInfo],
|
||||||
|
metadata: destinationMetadata,
|
||||||
|
type: PostTypes.ME,
|
||||||
|
props: destinationProps,
|
||||||
|
}),
|
||||||
|
'',
|
||||||
|
);
|
||||||
|
expect(mockedUpdateDraft).not.toHaveBeenCalledWith(
|
||||||
|
StoragePrefixes.DRAFT + channelId,
|
||||||
|
expect.objectContaining({message: destinationMessage}),
|
||||||
|
expect.anything(),
|
||||||
|
);
|
||||||
|
expect(mockedUpdateDraft).not.toHaveBeenCalledWith(
|
||||||
|
StoragePrefixes.DRAFT + otherChannelId,
|
||||||
|
expect.objectContaining({
|
||||||
|
fileInfos: [sourceFileInfo],
|
||||||
|
metadata: sourceMetadata,
|
||||||
|
type: PostTypes.BURN_ON_READ,
|
||||||
|
props: sourceProps,
|
||||||
|
}),
|
||||||
|
expect.anything(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('should save a new draft when changing channels', async () => {
|
it('should save a new draft when changing channels', async () => {
|
||||||
const {rerender} = renderWithContext(
|
const {rerender} = renderWithContext(
|
||||||
<AdvancedTextEditor
|
<AdvancedTextEditor
|
||||||
@@ -313,6 +544,105 @@ describe('components/avanced_text_editor/advanced_text_editor', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should not adopt the previous channel draft when a submit resolves after a channel switch', async () => {
|
||||||
|
let resolveSubmit = () => {};
|
||||||
|
mockedOnSubmit.mockImplementation((() => () => new Promise((resolve) => {
|
||||||
|
resolveSubmit = () => resolve({data: true});
|
||||||
|
})) as unknown as typeof onSubmit);
|
||||||
|
|
||||||
|
const {rerender} = renderWithContext(
|
||||||
|
<AdvancedTextEditor
|
||||||
|
{...baseProps}
|
||||||
|
/>,
|
||||||
|
initialState,
|
||||||
|
);
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByPlaceholderText('Write to Test Channel'), 'first message');
|
||||||
|
await userEvent.click(screen.getByTestId('SendMessageButton'));
|
||||||
|
|
||||||
|
// The channel switches while that submit is still in flight, exactly as
|
||||||
|
// /msg does when redirecting to a DM that already exists in the store.
|
||||||
|
rerender(
|
||||||
|
<AdvancedTextEditor
|
||||||
|
{...baseProps}
|
||||||
|
channelId={otherChannelId}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Now the in-flight submit resolves and clears the origin channel's draft.
|
||||||
|
await act(async () => {
|
||||||
|
resolveSubmit();
|
||||||
|
});
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByPlaceholderText('Write to Other Channel'), 'second message');
|
||||||
|
|
||||||
|
// Switching away flushes the composer's draft, revealing which channel it
|
||||||
|
// believes it belongs to. Before the fix this was the origin channel, so
|
||||||
|
// the message would have posted there.
|
||||||
|
mockedUpdateDraft.mockClear();
|
||||||
|
rerender(
|
||||||
|
<AdvancedTextEditor
|
||||||
|
{...baseProps}
|
||||||
|
channelId={channelId}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(mockedUpdateDraft).toHaveBeenCalled();
|
||||||
|
expect(mockedUpdateDraft.mock.calls[0][1]).toMatchObject({
|
||||||
|
message: 'second message',
|
||||||
|
channelId: otherChannelId,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not adopt the previous thread draft when a submit resolves after a thread switch', async () => {
|
||||||
|
let resolveSubmit = () => {};
|
||||||
|
mockedOnSubmit.mockImplementation((() => () => new Promise((resolve) => {
|
||||||
|
resolveSubmit = () => resolve({data: true});
|
||||||
|
})) as unknown as typeof onSubmit);
|
||||||
|
|
||||||
|
const firstThreadId = 'thread_1';
|
||||||
|
const secondThreadId = 'thread_2';
|
||||||
|
|
||||||
|
const {rerender} = renderWithContext(
|
||||||
|
<AdvancedTextEditor
|
||||||
|
{...baseProps}
|
||||||
|
rootId={firstThreadId}
|
||||||
|
/>,
|
||||||
|
initialState,
|
||||||
|
);
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByPlaceholderText('Reply to this thread...'), 'first reply');
|
||||||
|
await userEvent.click(screen.getByTestId('SendMessageButton'));
|
||||||
|
|
||||||
|
rerender(
|
||||||
|
<AdvancedTextEditor
|
||||||
|
{...baseProps}
|
||||||
|
rootId={secondThreadId}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
resolveSubmit();
|
||||||
|
});
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByPlaceholderText('Reply to this thread...'), 'second reply');
|
||||||
|
|
||||||
|
mockedUpdateDraft.mockClear();
|
||||||
|
rerender(
|
||||||
|
<AdvancedTextEditor
|
||||||
|
{...baseProps}
|
||||||
|
rootId={firstThreadId}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(mockedUpdateDraft).toHaveBeenCalled();
|
||||||
|
expect(mockedUpdateDraft.mock.calls[0][1]).toMatchObject({
|
||||||
|
message: 'second reply',
|
||||||
|
channelId,
|
||||||
|
rootId: secondThreadId,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('MM-60541 should not save an unmodified draft when changing channels', async () => {
|
it('MM-60541 should not save an unmodified draft when changing channels', async () => {
|
||||||
const {rerender} = renderWithContext(
|
const {rerender} = renderWithContext(
|
||||||
<AdvancedTextEditor
|
<AdvancedTextEditor
|
||||||
|
|||||||
@@ -242,6 +242,10 @@ const AdvancedTextEditor = ({
|
|||||||
const codeBlockOnCtrlEnter = useSelector((state: GlobalState) => getBool(state, Preferences.CATEGORY_ADVANCED_SETTINGS, 'code_block_ctrl_enter', true));
|
const codeBlockOnCtrlEnter = useSelector((state: GlobalState) => getBool(state, Preferences.CATEGORY_ADVANCED_SETTINGS, 'code_block_ctrl_enter', true));
|
||||||
const isDMOrGMRemote = isChannelShared && (channelType === Constants.DM_CHANNEL || channelType === Constants.GM_CHANNEL);
|
const isDMOrGMRemote = isChannelShared && (channelType === Constants.DM_CHANNEL || channelType === Constants.GM_CHANNEL);
|
||||||
|
|
||||||
|
if (draft.channelId !== channelId || draft.rootId !== rootId) {
|
||||||
|
setDraft(draftFromStore);
|
||||||
|
}
|
||||||
|
|
||||||
const handleShowPreview = useCallback(() => {
|
const handleShowPreview = useCallback(() => {
|
||||||
setShowPreview((prev) => !prev);
|
setShowPreview((prev) => !prev);
|
||||||
}, []);
|
}, []);
|
||||||
@@ -255,7 +259,17 @@ const AdvancedTextEditor = ({
|
|||||||
clearTimeout(saveDraftFrame.current);
|
clearTimeout(saveDraftFrame.current);
|
||||||
}
|
}
|
||||||
|
|
||||||
setDraft(draftToChange);
|
// A late async callback (slow submit, finished file upload) may call handleDraftChange
|
||||||
|
// with the channelId/rootId captured when it started. If the user has since moved to
|
||||||
|
// another channel or thread, do not overwrite the text they have typed here.
|
||||||
|
setDraft((currentDraft) => {
|
||||||
|
if (currentDraft.channelId !== draftToChange.channelId || currentDraft.rootId !== draftToChange.rootId) {
|
||||||
|
// The current channel/thread has changed, so don't update the draft displayed to the user
|
||||||
|
return currentDraft;
|
||||||
|
}
|
||||||
|
|
||||||
|
return draftToChange;
|
||||||
|
});
|
||||||
|
|
||||||
const saveDraft = () => {
|
const saveDraft = () => {
|
||||||
let prefix = StoragePrefixes.DRAFT;
|
let prefix = StoragePrefixes.DRAFT;
|
||||||
@@ -695,13 +709,11 @@ const AdvancedTextEditor = ({
|
|||||||
handleSubmitWithErrorHandling(undefined, schedulingInfo);
|
handleSubmitWithErrorHandling(undefined, schedulingInfo);
|
||||||
}, [handleSubmitWithErrorHandling]);
|
}, [handleSubmitWithErrorHandling]);
|
||||||
|
|
||||||
// Set the draft from store when changing post or channels, and store the previous one
|
// Store the previous draft when changing post or channels
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Store the draft that existed when we opened the channel to know if it should be saved
|
// Store the draft that existed when we opened the channel to know if it should be saved
|
||||||
const draftOnOpen = draftFromStore;
|
const draftOnOpen = draftFromStore;
|
||||||
|
|
||||||
setDraft(draftOnOpen);
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (draftOnOpen !== draftRef.current) {
|
if (draftOnOpen !== draftRef.current) {
|
||||||
handleDraftChange(draftRef.current, {instant: true, show: true});
|
handleDraftChange(draftRef.current, {instant: true, show: true});
|
||||||
|
|||||||
@@ -19,6 +19,11 @@ jest.mock('actions/views/modals', () => ({
|
|||||||
openModal: jest.fn(() => ({type: ''})),
|
openModal: jest.fn(() => ({type: ''})),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
jest.mock('actions/views/create_comment', () => ({
|
||||||
|
...jest.requireActual('actions/views/create_comment'),
|
||||||
|
onSubmit: jest.fn(() => () => Promise.resolve({data: true})),
|
||||||
|
}));
|
||||||
|
|
||||||
describe('useSubmit', () => {
|
describe('useSubmit', () => {
|
||||||
const mockDraft: PostDraft = {
|
const mockDraft: PostDraft = {
|
||||||
message: 'Test message',
|
message: 'Test message',
|
||||||
|
|||||||
@@ -204,7 +204,7 @@ const useSubmit = (
|
|||||||
response = await dispatch(editPost(submittingDraft as unknown as Post));
|
response = await dispatch(editPost(submittingDraft as unknown as Post));
|
||||||
handleFileChange(submittingDraft);
|
handleFileChange(submittingDraft);
|
||||||
} else {
|
} else {
|
||||||
response = await dispatch(onSubmit(submittingDraft, options, schedulingInfo));
|
response = await dispatch(onSubmit(channelId, rootId, submittingDraft, options, schedulingInfo));
|
||||||
}
|
}
|
||||||
if (response?.error) {
|
if (response?.error) {
|
||||||
throw response.error;
|
throw response.error;
|
||||||
|
|||||||
Reference in New Issue
Block a user