fix: do not create <mark> elements, just wrap found words in <span> and add .css styling

This commit is contained in:
2025-10-06 14:53:24 +03:00
parent 21a120e494
commit 6ba0d2eb7c
7 changed files with 1064 additions and 102 deletions

View File

@@ -1,10 +1,10 @@
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete" && /^https?:/.test(tab.url)) {
if (changeInfo.status === 'complete' && /^https?:/.test(tab.url)) {
chrome.scripting.executeScript({
target: { tabId },
files: ["main.js"]
files: ['main.js']
}).catch(err => {
console.warn("Injection failed:", err);
console.warn('Injection failed:', err);
});
}
});

31
eslint.config.mjs Normal file
View File

@@ -0,0 +1,31 @@
import globals from 'globals';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import js from '@eslint/js';
import { FlatCompat } from '@eslint/eslintrc';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
});
export default [...compat.extends('eslint:recommended'), {
languageOptions: {
globals: {
...globals.browser,
...globals.webextensions,
chrome: 'readonly',
},
ecmaVersion: 12,
sourceType: 'module',
},
rules: {
semi: ['error', 'always'],
quotes: ['error', 'single'],
},
}];

74
main.js
View File

@@ -2,20 +2,54 @@ let currentLists = [];
let isGlobalHighlightEnabled = true;
let matchCase = false;
let matchWhole = false;
let styleSheet = null;
let wordStyleMap = new Map();
function escapeRegex(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function initializeStyleSheet() {
if (!styleSheet) {
const style = document.createElement('style');
style.id = 'goose-highlighter-styles';
document.head.appendChild(style);
styleSheet = style.sheet;
}
}
function updateWordStyles(activeWords) {
initializeStyleSheet();
while (styleSheet.cssRules.length > 0) {
styleSheet.deleteRule(0);
}
wordStyleMap.clear();
const uniqueStyles = new Map();
for (const word of activeWords) {
const styleKey = `${word.background}-${word.foreground}`;
if (!uniqueStyles.has(styleKey)) {
const className = `highlighted-word-${uniqueStyles.size}`;
uniqueStyles.set(styleKey, className);
const rule = `.${className} { background: ${word.background}; color: ${word.foreground}; padding: 0 2px; }`;
styleSheet.insertRule(rule, styleSheet.cssRules.length);
}
const lookup = matchCase ? word.text : word.text.toLowerCase();
wordStyleMap.set(lookup, uniqueStyles.get(styleKey));
}
}
function clearHighlights() {
// Remove all <mark> elements added by the highlighter
const marks = document.querySelectorAll('mark[data-gh]');
for (const mark of marks) {
// Replace the <mark> with its text content
const parent = mark.parentNode;
const highlightedElements = document.querySelectorAll('[data-gh]');
for (const element of highlightedElements) {
const parent = element.parentNode;
if (parent) {
parent.replaceChild(document.createTextNode(mark.textContent), mark);
parent.normalize(); // Merge adjacent text nodes
parent.replaceChild(document.createTextNode(element.textContent), element);
parent.normalize();
}
}
}
@@ -25,7 +59,6 @@ function processNodes() {
observer.disconnect();
clearHighlights();
// If global highlighting is disabled, skip processing
if (!isGlobalHighlightEnabled) {
observer.observe(document.body, {
childList: true,
@@ -38,7 +71,7 @@ function processNodes() {
const textNodes = [];
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
acceptNode: node => {
if (node.parentNode && node.parentNode.nodeName === 'MARK') return NodeFilter.FILTER_REJECT;
if (node.parentNode && node.parentNode.hasAttribute('data-gh')) return NodeFilter.FILTER_REJECT;
if (node.parentNode && ['SCRIPT', 'STYLE', 'NOSCRIPT', 'IFRAME'].includes(node.parentNode.nodeName)) return NodeFilter.FILTER_REJECT;
if (!node.nodeValue.trim()) return NodeFilter.FILTER_SKIP;
return NodeFilter.FILTER_ACCEPT;
@@ -61,6 +94,8 @@ function processNodes() {
}
if (activeWords.length > 0) {
updateWordStyles(activeWords);
const wordMap = new Map();
for (const word of activeWords) {
wordMap.set(matchCase ? word.text : word.text.toLowerCase(), word);
@@ -82,14 +117,14 @@ if (activeWords.length > 0) {
const span = document.createElement('span');
span.innerHTML = node.nodeValue.replace(pattern, match => {
const lookup = matchCase ? match : match.toLowerCase();
const word = wordMap.get(lookup) || { background: '#ffff00', foreground: '#000000' };
return `<mark data-gh style="background:${word.background};color:${word.foreground};padding:0 2px;">${match}</mark>`;
const className = wordStyleMap.get(lookup) || 'highlighted-word-0';
return `<span data-gh class="${className}">${match}</span>`;
});
node.parentNode.replaceChild(span, node);
}
} catch (e) {
console.error("Regex error:", e);
console.error('Regex error:', e);
}
}
@@ -107,7 +142,6 @@ function setListsAndUpdate(lists) {
debouncedProcessNodes();
}
// Debounce helper function
function debounce(func, wait) {
let timeout;
return function () {
@@ -118,7 +152,7 @@ function debounce(func, wait) {
}
// Initial highlight on load
chrome.storage.local.get(["lists", "globalHighlightEnabled", "matchCaseEnabled", "matchWholeEnabled"], ({ lists, globalHighlightEnabled, matchCaseEnabled, matchWholeEnabled }) => {
chrome.storage.local.get(['lists', 'globalHighlightEnabled', 'matchCaseEnabled', 'matchWholeEnabled'], ({ lists, globalHighlightEnabled, matchCaseEnabled, matchWholeEnabled }) => {
if (Array.isArray(lists)) setListsAndUpdate(lists);
if (globalHighlightEnabled !== undefined) {
isGlobalHighlightEnabled = globalHighlightEnabled;
@@ -129,15 +163,15 @@ chrome.storage.local.get(["lists", "globalHighlightEnabled", "matchCaseEnabled",
});
// Listen for updates from the popup and re-apply highlights
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "WORD_LIST_UPDATED") {
chrome.storage.local.get("lists", ({ lists }) => {
chrome.runtime.onMessage.addListener((message) => {
if (message.type === 'WORD_LIST_UPDATED') {
chrome.storage.local.get('lists', ({ lists }) => {
if (Array.isArray(lists)) setListsAndUpdate(lists);
});
} else if (message.type === "GLOBAL_TOGGLE_UPDATED") {
} else if (message.type === 'GLOBAL_TOGGLE_UPDATED') {
isGlobalHighlightEnabled = message.enabled;
processNodes();
} else if (message.type === "MATCH_OPTIONS_UPDATED") {
} else if (message.type === 'MATCH_OPTIONS_UPDATED') {
matchCase = !!message.matchCase;
matchWhole = !!message.matchWhole;
processNodes();

909
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,12 @@
{
"devDependencies": {
"@eslint/css": "^0.9.0",
"@eslint/js": "^9.30.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/exec": "^7.1.0",
"@semantic-release/git": "^10.0.1",
"eslint": "^9.30.0",
"globals": "^16.2.0",
"semantic-release": "^24.2.5"
},
"scripts": {

View File

@@ -1,19 +1,18 @@
const listSelect = document.getElementById("listSelect");
const listName = document.getElementById("listName");
const listBg = document.getElementById("listBg");
const listFg = document.getElementById("listFg");
const listActive = document.getElementById("listActive");
const bulkPaste = document.getElementById("bulkPaste");
const wordList = document.getElementById("wordList");
const importInput = document.getElementById("importInput");
const matchCase = document.getElementById("matchCase");
const matchWhole = document.getElementById("matchWhole");
const listSelect = document.getElementById('listSelect');
const listName = document.getElementById('listName');
const listBg = document.getElementById('listBg');
const listFg = document.getElementById('listFg');
const listActive = document.getElementById('listActive');
const bulkPaste = document.getElementById('bulkPaste');
const wordList = document.getElementById('wordList');
const importInput = document.getElementById('importInput');
const matchCase = document.getElementById('matchCase');
const matchWhole = document.getElementById('matchWhole');
let lists = [];
let currentListIndex = 0;
let saveTimeout;
let selectedCheckboxes = new Set();
let globalHighlightEnabled = true;
let wordSearchQuery = "";
let wordSearchQuery = '';
let matchCaseEnabled = false;
let matchWholeEnabled = false;
@@ -24,18 +23,11 @@ function escapeHtml(str) {
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
'\'': '&#39;'
})[m];
});
}
async function debouncedSave() {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(async () => {
await chrome.storage.local.set({ lists });
}, 500);
}
async function save() {
await chrome.storage.local.set({
lists: lists,
@@ -49,13 +41,13 @@ async function save() {
chrome.tabs.query({}, function (tabs) {
for (let tab of tabs) {
if (tab.id) {
chrome.tabs.sendMessage(tab.id, { type: "WORD_LIST_UPDATED" });
chrome.tabs.sendMessage(tab.id, { type: 'WORD_LIST_UPDATED' });
chrome.tabs.sendMessage(tab.id, {
type: "GLOBAL_TOGGLE_UPDATED",
type: 'GLOBAL_TOGGLE_UPDATED',
enabled: globalHighlightEnabled
});
chrome.tabs.sendMessage(tab.id, {
type: "MATCH_OPTIONS_UPDATED",
type: 'MATCH_OPTIONS_UPDATED',
matchCase: matchCaseEnabled,
matchWhole: matchWholeEnabled
});
@@ -70,7 +62,7 @@ async function updateGlobalToggleState() {
for (let tab of tabs) {
if (tab.id) {
chrome.tabs.sendMessage(tab.id, {
type: "GLOBAL_TOGGLE_UPDATED",
type: 'GLOBAL_TOGGLE_UPDATED',
enabled: globalHighlightEnabled
});
}
@@ -95,9 +87,9 @@ async function load() {
if (!lists.length) {
lists.push({
id: Date.now(),
name: chrome.i18n.getMessage("default_list_name"),
background: "#ffff00",
foreground: "#000000",
name: chrome.i18n.getMessage('default_list_name'),
background: '#ffff00',
foreground: '#000000',
active: true,
words: []
});
@@ -105,13 +97,13 @@ async function load() {
renderLists();
renderWords();
document.getElementById("globalHighlightToggle").checked = globalHighlightEnabled;
document.getElementById('globalHighlightToggle').checked = globalHighlightEnabled;
}
function renderLists() {
listSelect.innerHTML = lists.map((list, index) =>
`<option value="${index}">${escapeHtml(list.name)}</option>`
).join("");
).join('');
listSelect.value = currentListIndex;
updateListForm();
}
@@ -152,7 +144,7 @@ function renderWords() {
for (let i = startIndex; i < endIndex; i++) {
const w = filteredWords[i];
if (!w) continue;
const container = document.createElement("div");
const container = document.createElement('div');
container.style.height = `${itemHeight}px`;
container.style.position = 'absolute';
container.style.top = `${i * itemHeight}px`;
@@ -169,16 +161,16 @@ function renderWords() {
const realIndex = list.words.indexOf(w);
const cbSelect = document.createElement("input");
cbSelect.type = "checkbox";
cbSelect.className = "word-checkbox";
const cbSelect = document.createElement('input');
cbSelect.type = 'checkbox';
cbSelect.className = 'word-checkbox';
cbSelect.dataset.index = realIndex;
if (selectedCheckboxes.has(realIndex)) {
cbSelect.checked = true;
}
const inputWord = document.createElement("input");
inputWord.type = "text";
const inputWord = document.createElement('input');
inputWord.type = 'text';
inputWord.value = w.wordStr;
inputWord.dataset.wordEdit = realIndex;
inputWord.style.flexGrow = '1';
@@ -189,34 +181,34 @@ function renderWords() {
inputWord.style.backgroundColor = 'var(--input-bg)';
inputWord.style.color = 'var(--text-color)';
const inputBg = document.createElement("input");
inputBg.type = "color";
const inputBg = document.createElement('input');
inputBg.type = 'color';
inputBg.value = w.background || list.background;
inputBg.dataset.bgEdit = realIndex;
inputBg.style.width = '24px';
inputBg.style.height = '24px';
inputBg.style.flexShrink = '0';
const inputFg = document.createElement("input");
inputFg.type = "color";
const inputFg = document.createElement('input');
inputFg.type = 'color';
inputFg.value = w.foreground || list.foreground;
inputFg.dataset.fgEdit = realIndex;
inputFg.style.width = '24px';
inputFg.style.height = '24px';
inputFg.style.flexShrink = '0';
const activeContainer = document.createElement("label");
activeContainer.className = "word-active";
const activeContainer = document.createElement('label');
activeContainer.className = 'word-active';
activeContainer.style.display = 'flex';
activeContainer.style.alignItems = 'center';
activeContainer.style.gap = '4px';
activeContainer.style.flexShrink = '0';
const cbActive = document.createElement("input");
cbActive.type = "checkbox";
const cbActive = document.createElement('input');
cbActive.type = 'checkbox';
cbActive.checked = w.active !== false;
cbActive.dataset.activeEdit = realIndex;
cbActive.className = "switch";
cbActive.className = 'switch';
activeContainer.appendChild(cbActive);
@@ -239,7 +231,7 @@ function renderWords() {
document.addEventListener('DOMContentLoaded', () => {
localizePage();
document.getElementById("selectAllBtn").onclick = () => {
document.getElementById('selectAllBtn').onclick = () => {
const list = lists[currentListIndex];
list.words.forEach((_, index) => {
selectedCheckboxes.add(index);
@@ -247,13 +239,13 @@ document.addEventListener('DOMContentLoaded', () => {
renderWords();
};
document.getElementById("globalHighlightToggle").addEventListener('change', function () {
document.getElementById('globalHighlightToggle').addEventListener('change', function () {
globalHighlightEnabled = this.checked;
updateGlobalToggleState();
});
wordList.addEventListener("change", e => {
if (e.target.type === "checkbox") {
wordList.addEventListener('change', e => {
if (e.target.type === 'checkbox') {
if (e.target.dataset.index != null) {
if (e.target.checked) {
selectedCheckboxes.add(+e.target.dataset.index);
@@ -286,12 +278,12 @@ document.addEventListener('DOMContentLoaded', () => {
updateListForm();
};
document.getElementById("newListBtn").onclick = () => {
document.getElementById('newListBtn').onclick = () => {
lists.push({
id: Date.now(),
name: chrome.i18n.getMessage("new_list_name"),
background: "#ffff00",
foreground: "#000000",
name: chrome.i18n.getMessage('new_list_name'),
background: '#ffff00',
foreground: '#000000',
active: true,
words: []
});
@@ -299,8 +291,8 @@ document.addEventListener('DOMContentLoaded', () => {
save();
};
document.getElementById("deleteListBtn").onclick = () => {
if (confirm(chrome.i18n.getMessage("confirm_delete_list"))) {
document.getElementById('deleteListBtn').onclick = () => {
if (confirm(chrome.i18n.getMessage('confirm_delete_list'))) {
lists.splice(currentListIndex, 1);
currentListIndex = Math.max(0, currentListIndex - 1);
save();
@@ -312,16 +304,16 @@ document.addEventListener('DOMContentLoaded', () => {
listFg.oninput = () => { lists[currentListIndex].foreground = listFg.value; save(); };
listActive.onchange = () => { lists[currentListIndex].active = listActive.checked; save(); };
document.getElementById("addWordsBtn").onclick = () => {
document.getElementById('addWordsBtn').onclick = () => {
const words = bulkPaste.value.split(/\n+/).map(w => w.trim()).filter(Boolean);
const list = lists[currentListIndex];
for (const w of words) list.words.push({ wordStr: w, background: "", foreground: "", active: true });
bulkPaste.value = "";
for (const w of words) list.words.push({ wordStr: w, background: '', foreground: '', active: true });
bulkPaste.value = '';
save();
};
document.getElementById("deleteSelectedBtn").onclick = () => {
if (confirm(chrome.i18n.getMessage("confirm_delete_words"))) {
document.getElementById('deleteSelectedBtn').onclick = () => {
if (confirm(chrome.i18n.getMessage('confirm_delete_words'))) {
const list = lists[currentListIndex];
const toDelete = Array.from(selectedCheckboxes);
lists[currentListIndex].words = list.words.filter((_, i) => !toDelete.includes(i));
@@ -331,7 +323,7 @@ document.addEventListener('DOMContentLoaded', () => {
}
};
document.getElementById("disableSelectedBtn").onclick = () => {
document.getElementById('disableSelectedBtn').onclick = () => {
const list = lists[currentListIndex];
selectedCheckboxes.forEach(index => {
list.words[index].active = false;
@@ -340,7 +332,7 @@ document.addEventListener('DOMContentLoaded', () => {
renderWords();
};
document.getElementById("enableSelectedBtn").onclick = () => {
document.getElementById('enableSelectedBtn').onclick = () => {
const list = lists[currentListIndex];
selectedCheckboxes.forEach(index => {
list.words[index].active = true;
@@ -349,7 +341,7 @@ document.addEventListener('DOMContentLoaded', () => {
renderWords();
};
wordList.addEventListener("input", e => {
wordList.addEventListener('input', e => {
const index = e.target.dataset.wordEdit ?? e.target.dataset.bgEdit ?? e.target.dataset.fgEdit;
if (index == null) return;
@@ -361,18 +353,18 @@ document.addEventListener('DOMContentLoaded', () => {
save();
});
const exportBtn = document.getElementById("exportBtn");
const exportBtn = document.getElementById('exportBtn');
exportBtn.onclick = () => {
const blob = new Blob([JSON.stringify(lists, null, 2)], { type: "application/json" });
const blob = new Blob([JSON.stringify(lists, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
const a = document.createElement('a');
a.href = url;
a.download = "highlight-lists.json";
a.download = 'highlight-lists.json';
a.click();
URL.revokeObjectURL(url);
};
const importBtn = document.getElementById("importBtn");
const importBtn = document.getElementById('importBtn');
importBtn.onclick = () => importInput.click();
importInput.onchange = e => {
@@ -388,7 +380,7 @@ document.addEventListener('DOMContentLoaded', () => {
save();
}
} catch (err) {
alert(chrome.i18n.getMessage("invalid_json_error"));
alert(chrome.i18n.getMessage('invalid_json_error:' + err.message));
}
};
reader.readAsText(file);
@@ -435,13 +427,13 @@ document.addEventListener('DOMContentLoaded', () => {
}
});
document.getElementById("deselectAllBtn").onclick = () => {
document.getElementById('deselectAllBtn').onclick = () => {
selectedCheckboxes.clear();
renderWords();
};
const wordSearch = document.getElementById("wordSearch");
wordSearch.addEventListener("input", (e) => {
const wordSearch = document.getElementById('wordSearch');
wordSearch.addEventListener('input', (e) => {
wordSearchQuery = e.target.value;
renderWords();
});

View File

@@ -1,8 +0,0 @@
async function getLists() {
const { lists } = await chrome.storage.local.get("lists");
return lists || [];
}
async function saveLists(lists) {
await chrome.storage.local.set({ lists });
}