diff --git a/apps/web/src/components/views/rooms/BasicMessageComposer.tsx b/apps/web/src/components/views/rooms/BasicMessageComposer.tsx index 05d446cc92..226d470b9c 100644 --- a/apps/web/src/components/views/rooms/BasicMessageComposer.tsx +++ b/apps/web/src/components/views/rooms/BasicMessageComposer.tsx @@ -392,6 +392,20 @@ export default class BasicMessageEditor extends React.Component private insertText(textToInsert: string, inputType = "insertText"): void { if (!this.editorRef.current) return; const sel = document.getSelection()!; + + if (!sel.isCollapsed) { + // A caret offset cannot describe a selected range, so splicing at it would leave the + // selected text in place. Replace the range instead, as onPaste does. + const model = this.props.model; + const range = getRangeForSelection(this.editorRef.current, model, sel); + this.modifiedFlag = true; + replaceRangeAndMoveCaret( + range, + parsePlainTextMessage(textToInsert, model.partCreator, { shouldEscape: false }), + ); + return; + } + const { caret, text } = getCaretOffsetAndText(this.editorRef.current, sel); const newText = text.slice(0, caret.offset) + textToInsert + text.slice(caret.offset); caret.offset += textToInsert.length; diff --git a/apps/web/test/unit-tests/components/views/rooms/BasicMessageComposer-test.tsx b/apps/web/test/unit-tests/components/views/rooms/BasicMessageComposer-test.tsx index caedd8cede..aab6266b24 100644 --- a/apps/web/test/unit-tests/components/views/rooms/BasicMessageComposer-test.tsx +++ b/apps/web/test/unit-tests/components/views/rooms/BasicMessageComposer-test.tsx @@ -104,6 +104,38 @@ describe("BasicMessageComposer", () => { expect(transformedText).toBe("/plain foobar\n"); }); + it("should replace the selected text when inserting a new line", async () => { + const model = new EditorModel([], pc, renderer); + render(, { + wrapper: ({ children }) => ( + {children} + ), + }); + + const input = screen.getByRole("textbox"); + await userEvent.type(input, "hello world"); + + // Select "world". + const textNode = document.createTreeWalker(input, NodeFilter.SHOW_TEXT).nextNode()!; + const range = document.createRange(); + range.setStart(textNode, 6); + range.setEnd(textNode, 11); + // jsdom does not implement Range.getBoundingClientRect, which the format bar asks for when + // the selection changes. + range.getBoundingClientRect = jest.fn().mockReturnValue({ top: 0, left: 0, width: 0, height: 0 }); + const selection = document.getSelection()!; + selection.removeAllRanges(); + selection.addRange(range); + + // Guard: without a real selection this test would only be exercising the caret path. + expect(selection.isCollapsed).toBe(false); + expect(selection.toString()).toBe("world"); + + await userEvent.keyboard("{Shift>}{Enter}{/Shift}"); + + expect(model.parts.map((part) => part.text).join("")).toBe("hello \n"); + }); + it("should escape single quote in placeholder", async () => { const model = new EditorModel([], pc, renderer); const composer = render(, {