this is my first TB addOn development and I need a hint for debugging. The addOn is a kind of auto correction or auto text replacement. This means, you can save a shortcut like ‘br’ and it will replaced with ‘Br, John Doe’. This works automaticly and to this point everythings works fine. But I would like to offer in setup the function to replace the shortcut if Enter-Key is pressed only. And here I have a problem, the cursor position, if enterReplace is active, aint get catched correctly and I don’t found the bug. I tried a lot, to asked ChatGPT was aint helpful as well.
This is the Code:
window.addEventListener("keydown", async (event) => {
// Retrieve settings from local storage
let setting_enter = await browser.storage.local.get({ enterReplace: false });
// Get the current cursor position node
let selection = window.getSelection();
let range = selection.getRangeAt(0);
let node = range.startContainer;
// Only handle text nodes if Enter was not pressed
if (node.nodeType !== Node.TEXT_NODE && event.code !== 'Enter') {
return;
}
// Function for text replacement and HTML insertion
const replaceText = async () => {
console.log("Node text content:", node.textContent); // Debugging
console.log("Cursor position (offset):", range.startOffset); // Debugging
// Get text up to the cursor position in the current node
let textBeforeCursor = node.textContent.slice(0, range.startOffset);
console.log("Text before cursor:", textBeforeCursor); // Debugging
// Capture the last word before the cursor
let words = textBeforeCursor.trim().split(/s+/); // Split the text into words
let wordToReplace = words[words.length - 1]; // The last word is what we want to replace
console.log("Word to replace:", wordToReplace); // Debugging
// Retrieve replacements from storage
let data = await browser.storage.local.get({ replacements: [] });
let replacements = data.replacements;
// Check if the last word is a shortcut and should be replaced
let shortcutFound = false; // Variable to determine if a shortcut was found
for (let item of replacements) {
console.log("Checking shortcut:", item.shortcut); // Debugging
if (wordToReplace === item.shortcut) {
shortcutFound = true; // Shortcut found
// Replace line breaks with <br> for HTML context
let replacementText = item.replacement.replace(/n/g, '<br>');
// Replace text in the range
let newText = textBeforeCursor.slice(0, -wordToReplace.length);
// Remove old text up to the shortcut
range.setStart(node, newText.length);
range.setEnd(node, textBeforeCursor.length);
range.deleteContents();
// Insert HTML by creating a new Range object
let fragment = document.createRange().createContextualFragment(replacementText);
range.insertNode(fragment);
// After inserting, set the cursor to the end of the inserted HTML
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
break; // Break the loop after replacing the shortcut
}
}
// If no shortcut was found, we can log a message here
if (!shortcutFound) {
console.log("No matching shortcut found for:", wordToReplace);
}
};
// If 'enterReplace' is active and Enter is pressed
if (setting_enter.enterReplace && event.code === 'Enter') {
event.preventDefault(); // Prevent the default Enter key effect
// Handle replacement and cursor position in one step
await replaceText();
// Optionally: add a new line break after the replacement is done
let brNode = document.createElement("br");
range.insertNode(brNode);
range.collapse(false); // Set the cursor to the end
selection.removeAllRanges();
selection.addRange(range);
} else if (!setting_enter.enterReplace) {
// Apply delay only if 'enterReplace' is not active
setTimeout(async () => {
// Recheck the current selection
selection = window.getSelection();
range = selection.getRangeAt(0);
node = range.startContainer;
await replaceText();
}, 700);
}
});
Where is the bug?
Thx!