@@ -149,12 +149,17 @@ export const useEditorFormatting = (editorRef) => {
149149 ( linkText , linkUrl ) => {
150150 const editor = editorRef . current ;
151151 if ( editor ) {
152- const button = document . createElement ( "button" ) ;
153- button . textContent = linkText ;
154- button . className = "link-btn" ;
155- button . onclick = ( ) =>
156- window . open ( linkUrl , "_blank" , "noopener,noreferrer" ) ;
157- editor . appendChild ( button ) ;
152+ // Focus the editor to ensure the link is inserted at the right position
153+ editor . focus ( ) ;
154+
155+ // Create an anchor element instead of button
156+ const linkElement = document . createElement ( "a" ) ;
157+ linkElement . textContent = linkText ;
158+ linkElement . href = linkUrl ;
159+ linkElement . target = "_blank" ;
160+ linkElement . rel = "noopener noreferrer" ; // Prevent security issues
161+ linkElement . className = "link-btn" ;
162+ editor . appendChild ( linkElement ) ;
158163 editor . appendChild ( document . createElement ( "br" ) ) ;
159164
160165 updateActiveStyles ( ) ;
@@ -180,11 +185,26 @@ export const useEditorFormatting = (editorRef) => {
180185 useEffect ( ( ) => {
181186 const editor = editorRef . current ;
182187 if ( editor ) {
188+ // Handle link clicks to open them in a new tab
189+ const handleLinkClick = ( e ) => {
190+ const target = e . target ;
191+ // The element that was clicked is checked to see if it’s an <a> (anchor) tag.
192+ if ( target . tagName === "A" ) {
193+ e . preventDefault ( ) ; // Prevent default editing behavior
194+ window . open ( target . href , "_blank" , "noopener,noreferrer" ) ; // Open the link in a new tab
195+ }
196+ } ;
197+
183198 editor . addEventListener ( "keyup" , updateActiveStyles ) ;
184199 editor . addEventListener ( "mouseup" , updateActiveStyles ) ;
200+ // Attach the click event listener to the editor for anchor elements
201+ editor . addEventListener ( "click" , handleLinkClick ) ;
202+
203+ // Cleanup event listeners when the component unmounts or the editor changes
185204 return ( ) => {
186205 editor . removeEventListener ( "keyup" , updateActiveStyles ) ;
187206 editor . removeEventListener ( "mouseup" , updateActiveStyles ) ;
207+ editor . removeEventListener ( "click" , handleLinkClick ) ;
188208 } ;
189209 }
190210 } , [ editorRef , updateActiveStyles ] ) ;
0 commit comments