Skip to content

Commit

Permalink
Merge pull request #47 from geekychandan/addLink-bugfix
Browse files Browse the repository at this point in the history
fix: link formatting issue
  • Loading branch information
deepakyadav-01 authored Oct 28, 2024
2 parents ab2b0f4 + 4dd1041 commit eb70b7f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
32 changes: 26 additions & 6 deletions component/src/hooks/useEditorFormatting.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,17 @@ export const useEditorFormatting = (editorRef) => {
(linkText, linkUrl) => {
const editor = editorRef.current;
if (editor) {
const button = document.createElement("button");
button.textContent = linkText;
button.className = "link-btn";
button.onclick = () =>
window.open(linkUrl, "_blank", "noopener,noreferrer");
editor.appendChild(button);
// Focus the editor to ensure the link is inserted at the right position
editor.focus();

// Create an anchor element instead of button
const linkElement = document.createElement("a");
linkElement.textContent = linkText;
linkElement.href = linkUrl;
linkElement.target = "_blank";
linkElement.rel = "noopener noreferrer"; // Prevent security issues
linkElement.className = "link-btn";
editor.appendChild(linkElement);
editor.appendChild(document.createElement("br"));

updateActiveStyles();
Expand All @@ -180,11 +185,26 @@ export const useEditorFormatting = (editorRef) => {
useEffect(() => {
const editor = editorRef.current;
if (editor) {
// Handle link clicks to open them in a new tab
const handleLinkClick = (e) => {
const target = e.target;
// The element that was clicked is checked to see if it’s an <a> (anchor) tag.
if (target.tagName === "A") {
e.preventDefault(); // Prevent default editing behavior
window.open(target.href, "_blank", "noopener,noreferrer"); // Open the link in a new tab
}
};

editor.addEventListener("keyup", updateActiveStyles);
editor.addEventListener("mouseup", updateActiveStyles);
// Attach the click event listener to the editor for anchor elements
editor.addEventListener("click", handleLinkClick);

// Cleanup event listeners when the component unmounts or the editor changes
return () => {
editor.removeEventListener("keyup", updateActiveStyles);
editor.removeEventListener("mouseup", updateActiveStyles);
editor.removeEventListener("click", handleLinkClick);
};
}
}, [editorRef, updateActiveStyles]);
Expand Down
1 change: 1 addition & 0 deletions component/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ code {
background-color: transparent;
border: none;
color: blue;
cursor: pointer;
}

0 comments on commit eb70b7f

Please sign in to comment.