From f5efa858827bd12cf4e531f6a0a667b7d31f9ce4 Mon Sep 17 00:00:00 2001 From: Florian Duros Date: Mon, 5 Dec 2022 17:40:33 +0100 Subject: [PATCH] Fix types and console.log --- .../wysiwyg_composer/hooks/useSelection.ts | 31 ++++++++++++------- .../SendWysiwygComposer-test.tsx | 1 - 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/src/components/views/rooms/wysiwyg_composer/hooks/useSelection.ts b/src/components/views/rooms/wysiwyg_composer/hooks/useSelection.ts index faddc1c1a5..62d5d1a3cb 100644 --- a/src/components/views/rooms/wysiwyg_composer/hooks/useSelection.ts +++ b/src/components/views/rooms/wysiwyg_composer/hooks/useSelection.ts @@ -18,8 +18,10 @@ import { useCallback, useEffect, useRef } from "react"; import useFocus from "../../../../../hooks/useFocus"; +type SubSelection = Pick; + export function useSelection() { - const selectionRef = useRef({ + const selectionRef = useRef({ anchorNode: null, anchorOffset: 0, focusNode: null, @@ -30,12 +32,15 @@ export function useSelection() { useEffect(() => { function onSelectionChange() { const selection = document.getSelection(); - selectionRef.current = { - anchorNode: selection.anchorNode, - anchorOffset: selection.anchorOffset, - focusNode: selection.focusNode, - focusOffset: selection.focusOffset, - }; + + if (selection) { + selectionRef.current = { + anchorNode: selection.anchorNode, + anchorOffset: selection.anchorOffset, + focusNode: selection.focusNode, + focusOffset: selection.focusOffset, + }; + } } if (isFocused) { @@ -47,10 +52,14 @@ export function useSelection() { const selectPreviousSelection = useCallback(() => { const range = new Range(); - range.setStart(selectionRef.current.anchorNode, selectionRef.current.anchorOffset); - range.setEnd(selectionRef.current.focusNode, selectionRef.current.focusOffset); - document.getSelection().removeAllRanges(); - document.getSelection().addRange(range); + const selection = selectionRef.current; + + if (selection.anchorNode && selection.focusNode) { + range.setStart(selection.anchorNode, selectionRef.current.anchorOffset); + range.setEnd(selection.focusNode, selectionRef.current.focusOffset); + document.getSelection()?.removeAllRanges(); + document.getSelection()?.addRange(range); + } }, [selectionRef]); return { ...focusProps, selectPreviousSelection }; diff --git a/test/components/views/rooms/wysiwyg_composer/SendWysiwygComposer-test.tsx b/test/components/views/rooms/wysiwyg_composer/SendWysiwygComposer-test.tsx index e51bd3bc6c..bd080331a9 100644 --- a/test/components/views/rooms/wysiwyg_composer/SendWysiwygComposer-test.tsx +++ b/test/components/views/rooms/wysiwyg_composer/SendWysiwygComposer-test.tsx @@ -177,7 +177,6 @@ describe('SendWysiwygComposer', () => { it('Should not has placeholder', async () => { // When - console.log('here'); customRender(jest.fn(), jest.fn(), false, isRichTextEnabled); await waitFor(() => expect(screen.getByRole('textbox')).toHaveAttribute('contentEditable', "true"));