Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

RTE drafts #12674

Merged
merged 21 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
4e0ad16
Add drafts to the RTE and tests
langleyd Jun 24, 2024
4b367dc
Merge branch 'develop' into langleyd/rte_drafts
langleyd Jun 24, 2024
2c92308
test drafts in threads
langleyd Jun 24, 2024
c9e8fc5
Merge branch 'langleyd/rte_drafts' of https://github.com/matrix-org/m…
langleyd Jun 24, 2024
ba9523d
lint
langleyd Jun 24, 2024
7b5eb7a
Merge branch 'develop' into langleyd/rte_drafts
langleyd Jun 24, 2024
57b51a0
Add unit test.
langleyd Jun 24, 2024
c084c86
Merge branch 'langleyd/rte_drafts' of https://github.com/matrix-org/m…
langleyd Jun 24, 2024
cd973b2
Fix test failure
florianduros Jun 25, 2024
e385502
Merge branch 'develop' into langleyd/rte_drafts
langleyd Jun 25, 2024
2741659
Remove unused import
langleyd Jun 25, 2024
880de62
Merge branch 'develop' of https://github.com/matrix-org/matrix-react-…
langleyd Aug 7, 2024
482268e
Clean up wysiwyg drafts and add test.
langleyd Aug 7, 2024
d5bbaa1
Merge branch 'develop' into langleyd/rte_drafts
langleyd Aug 8, 2024
06da902
Merge branch 'develop' of https://github.com/matrix-org/matrix-react-…
langleyd Aug 8, 2024
6dab422
Merge branch 'langleyd/rte_drafts' of https://github.com/matrix-org/m…
langleyd Aug 8, 2024
53e0523
Fix typo
florianduros Aug 19, 2024
7489ecf
Merge branch 'langleyd/rte_drafts' of https://github.com/matrix-org/m…
langleyd Aug 21, 2024
c96b9e2
Merge branch 'develop' of https://github.com/matrix-org/matrix-react-…
langleyd Aug 21, 2024
97aa83a
Merge branch 'develop' into langleyd/rte_drafts
langleyd Aug 21, 2024
48c6a99
Add timeout to allow for wasm loading.
langleyd Aug 22, 2024
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
105 changes: 105 additions & 0 deletions playwright/e2e/composer/composer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,5 +319,110 @@ test.describe("Composer", () => {
);
});
});

test.describe("Drafts", () => {
test("drafts with rich and plain text", async ({ page, app }) => {
// Set up a second room to swtich to, to test drafts
const firstRoomname = "Composing Room";
const secondRoomname = "Second Composing Room";
await app.client.createRoom({ name: secondRoomname });

// Composer is visible
const composer = page.locator("div[contenteditable=true]");
await expect(composer).toBeVisible();

// Type some formatted text
await composer.pressSequentially("my ");
await composer.press(`${CtrlOrMeta}+KeyB`);
await composer.pressSequentially("bold");

// Change to plain text mode
await page.getByRole("button", { name: "Hide formatting" }).click();

// Change to another room and back again
await app.viewRoomByName(secondRoomname);
await app.viewRoomByName(firstRoomname);

// assert the markdown
await expect(page.locator("div[contenteditable=true]", { hasText: "my __bold__" })).toBeVisible();

// Change to plain text mode and assert the markdown
await page.getByRole("button", { name: "Show formatting" }).click();

// Change to another room and back again
await app.viewRoomByName(secondRoomname);
await app.viewRoomByName(firstRoomname);

// Send the message and assert the message
await page.getByRole("button", { name: "Send message" }).click();
await expect(page.locator(".mx_EventTile_last .mx_EventTile_body").getByText("my bold")).toBeVisible();
});

test("draft with replies", async ({ page, app }) => {
// Set up a second room to swtich to, to test drafts
const firstRoomname = "Composing Room";
const secondRoomname = "Second Composing Room";
await app.client.createRoom({ name: secondRoomname });

// Composer is visible
const composer = page.locator("div[contenteditable=true]");
await expect(composer).toBeVisible();

// Send a message
await composer.pressSequentially("my first message");
await page.getByRole("button", { name: "Send message" }).click();

// Click reply
const tile = page.locator(".mx_EventTile_last");
await tile.hover();
await tile.getByRole("button", { name: "Reply", exact: true }).click();

// Type reply text
await composer.pressSequentially("my reply");

// Change to another room and back again
await app.viewRoomByName(secondRoomname);
await app.viewRoomByName(firstRoomname);

// Assert reply mode and reply text
await expect(page.getByText("Replying")).toBeVisible();
await expect(page.locator("div[contenteditable=true]", { hasText: "my reply" })).toBeVisible();
});

test("draft in threads", async ({ page, app }) => {
// Set up a second room to swtich to, to test drafts
const firstRoomname = "Composing Room";
const secondRoomname = "Second Composing Room";
await app.client.createRoom({ name: secondRoomname });

// Composer is visible
const composer = page.locator("div[contenteditable=true]");
await expect(composer).toBeVisible();

// Send a message
await composer.pressSequentially("my first message");
await page.getByRole("button", { name: "Send message" }).click();

// Click reply
const tile = page.locator(".mx_EventTile_last");
await tile.hover();
await tile.getByRole("button", { name: "Reply in thread" }).click();

const thread = page.locator(".mx_ThreadView");
const threadComposer = thread.locator("div[contenteditable=true]");

// Type threaded text
await threadComposer.pressSequentially("my threaded message");

// Change to another room and back again
await app.viewRoomByName(secondRoomname);
await app.viewRoomByName(firstRoomname);

// Assert threaded draft
await expect(
thread.locator("div[contenteditable=true]", { hasText: "my threaded message" }),
).toBeVisible();
});
});
});
});
90 changes: 83 additions & 7 deletions src/components/views/rooms/MessageComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
} from "matrix-js-sdk/src/matrix";
import { Optional } from "matrix-events-sdk";
import { Tooltip } from "@vector-im/compound-web";
import { logger } from "matrix-js-sdk/src/logger";

import { _t } from "../../../languageHandler";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
Expand Down Expand Up @@ -109,6 +110,12 @@ interface IState {
initialComposerContent: string;
}

type WysiwygComposerState = {
content: string;
isRichText: boolean;
replyEventId?: string;
};

export class MessageComposer extends React.Component<IProps, IState> {
private dispatcherRef?: string;
private messageComposerInput = createRef<SendMessageComposerClass>();
Expand All @@ -127,23 +134,44 @@ export class MessageComposer extends React.Component<IProps, IState> {
isRichTextEnabled: true,
};

public constructor(props: IProps) {
super(props);
public constructor(props: IProps, context: React.ContextType<typeof RoomContext>) {
super(props, context);
this.context = context; // otherwise React will only set it prior to render due to type def above

VoiceRecordingStore.instance.on(UPDATE_EVENT, this.onVoiceStoreUpdate);

window.addEventListener("beforeunload", this.saveWysiwygEditorState);
const isWysiwygLabEnabled = SettingsStore.getValue<boolean>("feature_wysiwyg_composer");
let isRichTextEnabled = true;
let initialComposerContent = "";
if (isWysiwygLabEnabled) {
const wysiwygState = this.restoreWysiwygEditorState();
if (wysiwygState) {
isRichTextEnabled = wysiwygState.isRichText;
initialComposerContent = wysiwygState.content;
if (wysiwygState.replyEventId) {
dis.dispatch({
action: "reply_to_event",
event: this.props.room.findEventById(wysiwygState.replyEventId),
context: this.context.timelineRenderingType,
});
}
}
}

this.state = {
isComposerEmpty: true,
composerContent: "",
isComposerEmpty: initialComposerContent?.length === 0,
composerContent: initialComposerContent,
haveRecording: false,
recordingTimeLeftSeconds: undefined, // when set to a number, shows a toast
isMenuOpen: false,
isStickerPickerOpen: false,
showStickersButton: SettingsStore.getValue("MessageComposerInput.showStickersButton"),
showPollsButton: SettingsStore.getValue("MessageComposerInput.showPollsButton"),
showVoiceBroadcastButton: SettingsStore.getValue(Features.VoiceBroadcast),
isWysiwygLabEnabled: SettingsStore.getValue<boolean>("feature_wysiwyg_composer"),
isRichTextEnabled: true,
initialComposerContent: "",
isWysiwygLabEnabled: isWysiwygLabEnabled,
isRichTextEnabled: isRichTextEnabled,
initialComposerContent: initialComposerContent,
};

this.instanceId = instanceCount++;
Expand All @@ -154,6 +182,52 @@ export class MessageComposer extends React.Component<IProps, IState> {
SettingsStore.monitorSetting("feature_wysiwyg_composer", null);
}

private get editorStateKey(): string {
let key = `mx_wysiwyg_state_${this.props.room.roomId}`;
Copy link
Member

Choose a reason for hiding this comment

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

Given there's no code to clean up drafts from rooms which you are no longer in can we move it to IDB where we have less space pressure?

Copy link
Contributor Author

@langleyd langleyd Jun 26, 2024

Choose a reason for hiding this comment

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

@t3chguy IDB appears to be a bit slower for small values than localstorage and because it's async setting the initial content outside of the constructor makes the initialisation of the editor feel a bit slow/janky. And introduced a weird issue where the initial text is sometimes selected.

Maybe we could stick with localstorage for consistency between it and CIDER but then look to add the cleanup for both? Is it just clearing the data when we leave or are kicked from a room?

Any other ideas?

Copy link
Member

Choose a reason for hiding this comment

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

It'd have to be a periodic scan comparing the drafts stored vs known rooms at a known good client state, as the client may not receive kicks/leaves depending on if the room was forgotten via another client before it syncs

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added

if (this.props.relation?.rel_type === THREAD_RELATION_TYPE.name) {
key += `_${this.props.relation.event_id}`;
}
return key;
}

private restoreWysiwygEditorState(): WysiwygComposerState | undefined {
const json = localStorage.getItem(this.editorStateKey);
if (json) {
try {
const state: WysiwygComposerState = JSON.parse(json);
return state;
} catch (e) {
logger.error(e);
}
}
return undefined;
}

private saveWysiwygEditorState = (): void => {
if (this.shouldSaveWysiwygEditorState()) {
const { isRichTextEnabled, composerContent } = this.state;
const replyEventId = this.props.replyToEvent ? this.props.replyToEvent.getId() : undefined;
const item: WysiwygComposerState = {
content: composerContent,
isRichText: isRichTextEnabled,
replyEventId: replyEventId,
};
localStorage.setItem(this.editorStateKey, JSON.stringify(item));
} else {
this.clearStoredEditorState();
}
};

// should save state when wysiwyg is enabled and has contents or reply is open
private shouldSaveWysiwygEditorState = (): boolean => {
const { isWysiwygLabEnabled, isComposerEmpty } = this.state;
return isWysiwygLabEnabled && (!isComposerEmpty || !!this.props.replyToEvent);
};

private clearStoredEditorState(): void {
localStorage.removeItem(this.editorStateKey);
}

private get voiceRecording(): Optional<VoiceMessageRecording> {
return this._voiceRecording;
}
Expand Down Expand Up @@ -265,6 +339,8 @@ export class MessageComposer extends React.Component<IProps, IState> {
UIStore.instance.stopTrackingElementDimensions(`MessageComposer${this.instanceId}`);
UIStore.instance.removeListener(`MessageComposer${this.instanceId}`, this.onResize);

window.removeEventListener("beforeunload", this.saveWysiwygEditorState);
this.saveWysiwygEditorState();
// clean up our listeners by setting our cached recording to falsy (see internal setter)
this.voiceRecording = null;
}
Expand Down
82 changes: 53 additions & 29 deletions test/components/views/rooms/MessageComposer-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ limitations under the License.

import * as React from "react";
import { EventType, MatrixEvent, Room, RoomMember, THREAD_RELATION_TYPE } from "matrix-js-sdk/src/matrix";
import { act, render, screen } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import {
Expand Down Expand Up @@ -49,10 +49,6 @@ import { VoiceBroadcastInfoState, VoiceBroadcastRecording } from "../../../../sr
import { mkVoiceBroadcastInfoStateEvent } from "../../../voice-broadcast/utils/test-utils";
import { SdkContextClass } from "../../../../src/contexts/SDKContext";

jest.mock("../../../../src/components/views/rooms/wysiwyg_composer", () => ({
SendWysiwygComposer: jest.fn().mockImplementation(() => <div data-testid="wysiwyg-composer" />),
}));

const openStickerPicker = async (): Promise<void> => {
await act(async () => {
await userEvent.click(screen.getByLabelText("More options"));
Expand All @@ -76,12 +72,6 @@ const setCurrentBroadcastRecording = (room: Room, state: VoiceBroadcastInfoState
SdkContextClass.instance.voiceBroadcastRecordingsStore.setCurrent(recording);
};

const shouldClearModal = async (): Promise<void> => {
afterEach(async () => {
await clearAllModals();
});
};

const expectVoiceMessageRecordingTriggered = (): void => {
// Checking for the voice message dialog text, if no mic can be found.
// By this we know at least that starting a voice message was triggered.
Expand All @@ -96,7 +86,8 @@ describe("MessageComposer", () => {
mockPlatformPeg();
});

afterEach(() => {
afterEach(async () => {
await clearAllModals();
jest.useRealTimers();

SdkContextClass.instance.voiceBroadcastRecordingsStore.clearCurrent();
Expand Down Expand Up @@ -415,8 +406,6 @@ describe("MessageComposer", () => {
await flushPromises();
});

shouldClearModal();

it("should try to start a voice message", () => {
expectVoiceMessageRecordingTriggered();
});
Expand All @@ -430,8 +419,6 @@ describe("MessageComposer", () => {
await waitEnoughCyclesForModal();
});

shouldClearModal();

it("should not start a voice message and display the info dialog", async () => {
expect(screen.queryByLabelText("Stop recording")).not.toBeInTheDocument();
expect(screen.getByText("Can't start voice message")).toBeInTheDocument();
Expand All @@ -446,8 +433,6 @@ describe("MessageComposer", () => {
await waitEnoughCyclesForModal();
});

shouldClearModal();

it("should try to start a voice message and should not display the info dialog", async () => {
expect(screen.queryByText("Can't start voice message")).not.toBeInTheDocument();
expectVoiceMessageRecordingTriggered();
Expand All @@ -467,12 +452,49 @@ describe("MessageComposer", () => {
});
});

it("should render SendWysiwygComposer when enabled", () => {
it("wysiwyg correctly persists state to and from localStorage", async () => {
const room = mkStubRoom("!roomId:server", "Room 1", cli);
SettingsStore.setValue("feature_wysiwyg_composer", null, SettingLevel.DEVICE, true);
const messateText = "Test Text";
await SettingsStore.setValue("feature_wysiwyg_composer", null, SettingLevel.DEVICE, true);
const { renderResult, rawComponent } = wrapAndRender({ room });
const { unmount, rerender } = renderResult;

await act(async () => {
await flushPromises();
});

wrapAndRender({ room });
expect(screen.getByTestId("wysiwyg-composer")).toBeInTheDocument();
const key = `mx_wysiwyg_state_${room.roomId}`;

await act(async () => {
await userEvent.click(screen.getByRole("textbox"));
});
fireEvent.input(screen.getByRole("textbox"), {
data: messateText,
inputType: "insertText",
});

await waitFor(() => expect(screen.getByRole("textbox")).toHaveTextContent(messateText));

// Wait for event dispatch to happen
await act(async () => {
await flushPromises();
});

// assert there is state persisted
expect(localStorage.getItem(key)).toBeNull();

// ensure the right state was persisted to localStorage
unmount();

// assert the persisted state
expect(JSON.parse(localStorage.getItem(key)!)).toStrictEqual({
content: messateText,
isRichText: true,
});

// ensure the correct state is re-loaded
rerender(rawComponent);
await waitFor(() => expect(screen.getByRole("textbox")).toHaveTextContent(messateText));
});
});

Expand Down Expand Up @@ -506,14 +528,16 @@ function wrapAndRender(
permalinkCreator: new RoomPermalinkCreator(room),
};

const getRawComponent = (props = {}, context = roomContext, client = mockClient) => (
<MatrixClientContext.Provider value={client}>
<RoomContext.Provider value={context}>
<MessageComposer {...defaultProps} {...props} />
</RoomContext.Provider>
</MatrixClientContext.Provider>
);
return {
renderResult: render(
<MatrixClientContext.Provider value={mockClient}>
<RoomContext.Provider value={roomContext}>
<MessageComposer {...defaultProps} {...props} />
</RoomContext.Provider>
</MatrixClientContext.Provider>,
),
rawComponent: getRawComponent(props, roomContext, mockClient),
renderResult: render(getRawComponent(props, roomContext, mockClient)),
roomContext,
};
}
Loading