From 710f5f02c820a997f902f46a21b6e084a2ac4a29 Mon Sep 17 00:00:00 2001 From: shivang-16 Date: Mon, 29 Jan 2024 02:40:04 +0530 Subject: [PATCH] fixed toggle functioning in chat input formatting --- .../ChatInput/ChatInputFormattingToolbar.js | 53 ++++++++++++------- 1 file changed, 35 insertions(+), 18 deletions(-) diff --git a/packages/react/src/components/ChatInput/ChatInputFormattingToolbar.js b/packages/react/src/components/ChatInput/ChatInputFormattingToolbar.js index 228a24759..d7a943e4b 100644 --- a/packages/react/src/components/ChatInput/ChatInputFormattingToolbar.js +++ b/packages/react/src/components/ChatInput/ChatInputFormattingToolbar.js @@ -10,7 +10,7 @@ import AudioMessageRecorder from './AudioMessageRecorder'; import { Box } from '../Box'; import { Icon } from '../Icon'; import { ActionButton } from '../ActionButton'; -import { Tooltip } from "../Tooltip" +import { Tooltip } from '../Tooltip'; import useComponentOverrides from '../../theme/useComponentOverrides'; const ChatInputFormattingToolbar = ({ messageRef, inputRef }) => { @@ -41,20 +41,34 @@ const ChatInputFormattingToolbar = ({ messageRef, inputRef }) => { const initText = input.value.slice(0, selectionStart); const selectedText = input.value.slice(selectionStart, selectionEnd); const finalText = input.value.slice(selectionEnd, input.value.length); - if ( - !document.execCommand || - !document.execCommand( - 'insertText', - false, - pattern.replace('{{text}}', selectedText) - ) - ) { + + const startPattern = pattern.slice(0, pattern.indexOf('{{text}}')); + const endPattern = pattern.slice( + pattern.indexOf('{{text}}') + '{{text}}'.length + ); + + const startPatternFound = initText.endsWith(startPattern); + const endPatternFound = finalText.startsWith(endPattern); + + if (startPatternFound && endPatternFound) { + // Text is already wrapped, so unwrap it input.value = - initText + pattern.replace('{{text}}', selectedText) + finalText; - } + initText.slice(0, initText.length - startPattern.length) + + selectedText + + finalText.slice(endPattern.length); + + input.selectionStart = selectionStart - startPattern.length; + input.selectionEnd = input.selectionStart + selectedText.length; + } else { + // Text is not wrapped, so wrap it + const wrappedText = startPattern + selectedText + endPattern; + if (!document.execCommand?.('insertText', false, wrappedText)) { + input.value = initText + wrappedText + finalText; + } - input.selectionStart = selectionStart + pattern.indexOf('{{text}}'); - input.selectionEnd = input.selectionStart + selectedText.length; + input.selectionStart = selectionStart + startPattern.length; + input.selectionEnd = input.selectionStart + selectedText.length; + } }; return ( @@ -102,7 +116,6 @@ const ChatInputFormattingToolbar = ({ messageRef, inputRef }) => { )} {formatter.map((item, index) => ( - { wrapSelection(item.pattern); }} > - - + - ))} - + + +