17 Commits

Author SHA1 Message Date
semantic-release-bot
a1701a3504 chore(release): 1.7.2
## [1.7.2](https://github.com/obsqrbtz/goose-highlighter/compare/v1.7.1...v1.7.2) (2025-10-06)

### Bug Fixes

* do not create <mark> elements, just wrap found words in <span> and add .css styling ([6ba0d2e](6ba0d2eb7c))
2025-10-06 14:53:36 +03:00
6ba0d2eb7c fix: do not create <mark> elements, just wrap found words in <span> and add .css styling 2025-10-06 14:53:24 +03:00
21a120e494 ci: corected auto commit message 2025-06-27 14:09:15 +03:00
semantic-release-bot
1ef21d0975 chore(release): 1.7.1 [skip ci]
## [1.7.1](https://github.com/obsqrbtz/goose-highlighter/compare/v1.7.0...v1.7.1) (2025-06-27)

### Bug Fixes

* unicode support in regex ([ae1cf48](ae1cf48c53))
2025-06-27 14:05:56 +03:00
ae1cf48c53 fix: unicode support in regex 2025-06-27 14:05:12 +03:00
bca37e690f Trigger Build 2025-06-27 00:51:41 +03:00
semantic-release-bot
50c3facfae chore(release): 1.7.0 [skip ci]
# [1.7.0](https://github.com/obsqrbtz/goose-highlighter/compare/v1.6.0...v1.7.0) (2025-06-26)

### Bug Fixes

* colorbox styling ([1e704b5](1e704b51a8))
* colorbox styling ([08ad7c4](08ad7c4325))
* moved import/export to options section ([fe15965](fe15965e89))
* wordlist scrollbar styling ([b30fac5](b30fac5ded))

### Features

* add word search ([80d4bff](80d4bff0b4))
* added matching flags ([759307f](759307f983))
2025-06-27 00:49:54 +03:00
fe15965e89 fix: moved import/export to options section 2025-06-27 00:46:09 +03:00
759307f983 feat: added matching flags 2025-06-27 00:43:31 +03:00
b766f61b0c ci: publish on push to master 2025-06-27 00:00:24 +03:00
1e704b51a8 fix: colorbox styling 2025-06-26 23:59:12 +03:00
b30fac5ded fix: wordlist scrollbar styling 2025-06-26 23:40:15 +03:00
08ad7c4325 fix: colorbox styling 2025-06-26 23:35:49 +03:00
80d4bff0b4 feat: add word search 2025-06-25 16:25:52 +03:00
dbb6806a78 corrected russian summary, chore(release): 1.6.0 2025-06-25 16:00:50 +03:00
e9c7d58273 corrected portuguese and korean locales, chore(release): 1.6.0 2025-06-25 15:57:40 +03:00
19ab6eec0b trigger release, chore(release): 1.6.0 2025-06-25 15:51:30 +03:00
27 changed files with 1472 additions and 129 deletions

View File

@@ -8,7 +8,6 @@ jobs:
publish:
name: Pack and Upload Extension
runs-on: ubuntu-latest
if: "contains(github.event.head_commit.message, 'chore(release):')"
env:
EXTENSION_ID: ${{ secrets.GOOGLE_EXTENSION_ID }}

View File

@@ -19,7 +19,7 @@
"manifest.json",
"CHANGELOG.md"
],
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
"message": "chore(release): ${nextRelease.version}\n\n${nextRelease.notes}"
}
]
]

View File

@@ -1,3 +1,33 @@
## [1.7.2](https://github.com/obsqrbtz/goose-highlighter/compare/v1.7.1...v1.7.2) (2025-10-06)
### Bug Fixes
* do not create <mark> elements, just wrap found words in <span> and add .css styling ([6ba0d2e](https://github.com/obsqrbtz/goose-highlighter/commit/6ba0d2eb7c7346cdca3921a12d300a714439efa5))
## [1.7.1](https://github.com/obsqrbtz/goose-highlighter/compare/v1.7.0...v1.7.1) (2025-06-27)
### Bug Fixes
* unicode support in regex ([ae1cf48](https://github.com/obsqrbtz/goose-highlighter/commit/ae1cf48c53cd42e65279cf2acde1a2860d8a31ee))
# [1.7.0](https://github.com/obsqrbtz/goose-highlighter/compare/v1.6.0...v1.7.0) (2025-06-26)
### Bug Fixes
* colorbox styling ([1e704b5](https://github.com/obsqrbtz/goose-highlighter/commit/1e704b51a859845e539224aeb389a4e493d64520))
* colorbox styling ([08ad7c4](https://github.com/obsqrbtz/goose-highlighter/commit/08ad7c432541ea4240dec05a340ad0b3279ce82f))
* moved import/export to options section ([fe15965](https://github.com/obsqrbtz/goose-highlighter/commit/fe15965e89e8483f6b96eb779617053664c9d5b1))
* wordlist scrollbar styling ([b30fac5](https://github.com/obsqrbtz/goose-highlighter/commit/b30fac5deda7941035d8ae23001c998c2584c03e))
### Features
* add word search ([80d4bff](https://github.com/obsqrbtz/goose-highlighter/commit/80d4bff0b4ef7c9e97506d1fe43a827bcc4b28fd))
* added matching flags ([759307f](https://github.com/obsqrbtz/goose-highlighter/commit/759307f9834a2bbb23e963e2042b7d41d5cfda44))
# [1.6.0](https://github.com/obsqrbtz/goose-highlighter/compare/v1.5.0...v1.6.0) (2025-06-25)

View File

@@ -88,5 +88,11 @@
},
"global_highlight_toggle": {
"message": "Aktivieren"
}
},
"search_placeholder": {
"message": "Suchen..."
},
"options": { "message": "Optionen" },
"match_case": { "message": "Groß-/Kleinschreibung beachten" },
"match_whole": { "message": "Ganzes Wort übereinstimmen" }
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "Enable"
},
"search_placeholder": {
"message": "Search..."
},
"options": {
"message": "Options"
},
"match_case": {
"message": "Match Case"
},
"match_whole": {
"message": "Match Whole Word"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "Activar"
},
"search_placeholder": {
"message": "Buscar..."
},
"options": {
"message": "Opciones"
},
"match_case": {
"message": "Coincidir mayúsculas/minúsculas"
},
"match_whole": {
"message": "Coincidir palabra completa"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "Activer"
},
"search_placeholder": {
"message": "Rechercher..."
},
"options": {
"message": "Options"
},
"match_case": {
"message": "Respecter la casse"
},
"match_whole": {
"message": "Mot entier seulement"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "सक्षम करें"
},
"search_placeholder": {
"message": "खोजें..."
},
"options": {
"message": "विकल्प"
},
"match_case": {
"message": "केस मिलाएं"
},
"match_whole": {
"message": "पूरा शब्द मिलाएं"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "Attiva"
},
"search_placeholder": {
"message": "Cerca..."
},
"options": {
"message": "Opzioni"
},
"match_case": {
"message": "Maiuscole/minuscole"
},
"match_whole": {
"message": "Solo parola intera"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "有効にする"
},
"search_placeholder": {
"message": "検索..."
},
"options": {
"message": "オプション"
},
"match_case": {
"message": "大文字と小文字を区別"
},
"match_whole": {
"message": "完全一致"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "활성화"
},
"search_placeholder": {
"message": "검색..."
},
"options": {
"message": "옵션"
},
"match_case": {
"message": "대소문자 구분"
},
"match_whole": {
"message": "전체 단어 일치"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "Inschakelen"
},
"search_placeholder": {
"message": "Zoeken..."
},
"options": {
"message": "Opties"
},
"match_case": {
"message": "Hoofdlettergevoelig"
},
"match_whole": {
"message": "Alleen volledig woord"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "Włącz"
},
"search_placeholder": {
"message": "Szukaj..."
},
"options": {
"message": "Opcje"
},
"match_case": {
"message": "Uwzględnij wielkość liter"
},
"match_whole": {
"message": "Tylko całe słowo"
}
}

View File

@@ -88,5 +88,11 @@
},
"global_highlight_toggle": {
"message": "Ativar"
}
},
"search_placeholder": {
"message": "Pesquisar..."
},
"options": { "message": "Opções" },
"match_case": { "message": "Diferenciar maiúsculas/minúsculas" },
"match_whole": { "message": "Palavra inteira" }
}

View File

@@ -2,6 +2,9 @@
"extension_name": {
"message": "Goose Highlighter"
},
"extension_description": {
"message": "Выделяйте слова и фразы на любом сайте. Создавайте собственные списки, используйте цвета, импортируйте и экспортируйте данные."
},
"select_list": {
"message": "Выберите список:"
},
@@ -85,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "Вкл"
},
"search_placeholder": {
"message": "Поиск..."
},
"options": {
"message": "Опции"
},
"match_case": {
"message": "С учетом регистра"
},
"match_whole": {
"message": "Слово целиком"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "Etkinleştir"
},
"search_placeholder": {
"message": "Ara..."
},
"options": {
"message": "Seçenekler"
},
"match_case": {
"message": "Büyük/küçük harf duyarlı"
},
"match_whole": {
"message": "Tüm kelimeyle eşleş"
}
}

View File

@@ -88,5 +88,17 @@
},
"global_highlight_toggle": {
"message": "启用"
},
"search_placeholder": {
"message": "搜索..."
},
"options": {
"message": "选项"
},
"match_case": {
"message": "区分大小写"
},
"match_whole": {
"message": "全词匹配"
}
}

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'],
},
}];

104
main.js
View File

@@ -1,19 +1,55 @@
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();
}
}
}
@@ -23,7 +59,6 @@ function processNodes() {
observer.disconnect();
clearHighlights();
// If global highlighting is disabled, skip processing
if (!isGlobalHighlightEnabled) {
observer.observe(document.body, {
childList: true,
@@ -36,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;
@@ -58,24 +93,40 @@ function processNodes() {
}
}
if (activeWords.length > 0) {
const wordMap = new Map();
for (const word of activeWords) wordMap.set(word.text.toLowerCase(), word);
if (activeWords.length > 0) {
updateWordStyles(activeWords);
const pattern = new RegExp(`(${Array.from(wordMap.keys()).map(escapeRegex).join('|')})`, 'gi');
const wordMap = new Map();
for (const word of activeWords) {
wordMap.set(matchCase ? word.text : word.text.toLowerCase(), word);
}
let flags = matchCase ? 'gu' : 'giu';
let wordsPattern = Array.from(wordMap.keys()).map(escapeRegex).join('|');
if (matchWhole) {
wordsPattern = `(?:(?<!\\p{L})|^)(${wordsPattern})(?:(?!\\p{L})|$)`;
}
try {
const pattern = new RegExp(`(${wordsPattern})`, flags);
for (const node of textNodes) {
if (!pattern.test(node.nodeValue)) continue;
if (!node.nodeValue || !pattern.test(node.nodeValue)) continue;
const span = document.createElement('span');
span.innerHTML = node.nodeValue.replace(pattern, match => {
const word = wordMap.get(match.toLowerCase()) || { background: '#ffff00', foreground: '#000000' };
return `<mark data-gh style="background:${word.background};color:${word.foreground};padding:0 2px;">${match}</mark>`;
const lookup = matchCase ? match : match.toLowerCase();
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);
}
}
observer.observe(document.body, {
childList: true,
@@ -91,7 +142,6 @@ function setListsAndUpdate(lists) {
debouncedProcessNodes();
}
// Debounce helper function
function debounce(func, wait) {
let timeout;
return function () {
@@ -102,23 +152,29 @@ function debounce(func, wait) {
}
// Initial highlight on load
chrome.storage.local.get(["lists", "globalHighlightEnabled"], ({ lists, globalHighlightEnabled }) => {
chrome.storage.local.get(['lists', 'globalHighlightEnabled', 'matchCaseEnabled', 'matchWholeEnabled'], ({ lists, globalHighlightEnabled, matchCaseEnabled, matchWholeEnabled }) => {
if (Array.isArray(lists)) setListsAndUpdate(lists);
if (globalHighlightEnabled !== undefined) {
isGlobalHighlightEnabled = globalHighlightEnabled;
}
processNodes(); // Initial processing
matchCase = !!matchCaseEnabled;
matchWhole = !!matchWholeEnabled;
processNodes();
});
// 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') {
matchCase = !!message.matchCase;
matchWhole = !!message.matchWhole;
processNodes();
}
});

View File

@@ -2,7 +2,7 @@
"manifest_version": 3,
"name": "__MSG_extension_name__",
"description": "__MSG_extension_description__",
"version": "1.6.0",
"version": "1.7.2",
"default_locale": "en",
"permissions": [
"scripting",

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

@@ -7,6 +7,7 @@
--button-hover: #444;
--button-text: white;
--accent: #ec9c23;
--accent-hover: #ffb84d;
--accent-text: #000;
--highlight-tag: #292929;
--highlight-tag-border: #444;
@@ -18,6 +19,10 @@
--switch-bg: #444;
--checkbox-accent: #ec9c23;
--checkbox-border: #666;
--scrollbar-bg: var(--section-bg);
--scrollbar-thumb: var(--accent);
--scrollbar-thumb-hover: var(--accent-hover);
--scrollbar-thumb-border: var(--section-bg);
}
body {
@@ -115,11 +120,40 @@ textarea {
input[type="color"] {
background: none;
border: none;
cursor: pointer;
border: 2px solid var(--input-border);
border-radius: 8px;
box-shadow: 0 1px 4px rgba(0,0,0,0.10);
width: 36px;
height: 36px;
margin-left: 6px;
cursor: pointer;
padding: 0;
transition: border 0.2s, box-shadow 0.2s;
appearance: none;
-webkit-appearance: none;
overflow: hidden;
}
input[type="color"]::-webkit-color-swatch-wrapper {
padding: 0;
border-radius: 0;
}
input[type="color"]::-webkit-color-swatch {
border-radius: 0;
border: none;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
input[type="color"]::-moz-color-swatch {
border-radius: 0;
border: none;
padding: 0;
width: 100%;
height: 100%;
}
input[type="checkbox"] {
@@ -128,9 +162,9 @@ input[type="checkbox"] {
background-color: var(--input-bg);
border: 1px solid var(--checkbox-border);
border-radius: 4px;
width: 16px;
height: 16px;
transform: scale(1.2);
width: 12px;
height: 12px;
transform: scale(1);
cursor: pointer;
position: relative;
}
@@ -138,10 +172,10 @@ input[type="checkbox"] {
input[type="checkbox"]:checked::after {
content: "";
position: absolute;
top: 2px;
left: 5px;
width: 4px;
height: 9px;
top: 1px;
left: 3px;
width: 3px;
height: 7px;
border: solid var(--checkbox-accent);
border-width: 0 2px 2px 0;
transform: rotate(45deg);
@@ -223,6 +257,19 @@ button.danger:hover {
flex-wrap: wrap;
}
.button-row label {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
font-size: 1em;
}
.button-row input[type="checkbox"] {
margin: 0;
vertical-align: middle;
}
.color-row {
display: flex;
gap: 24px;
@@ -236,6 +283,12 @@ button.danger:hover {
gap: 6px;
}
#wordSearch{
width:100%;
margin-bottom:8px;
margin-top: 8px;
}
#wordList {
margin-top: 8px;
position: relative;
@@ -381,3 +434,75 @@ label:has(input.switch) {
align-items: center;
gap: 8px;
}
#wordList,
body {
scrollbar-width: thin;
scrollbar-color: var(--accent) var(--section-bg);
}
#wordList::-webkit-scrollbar,
body::-webkit-scrollbar {
width: 8px;
background: var(--section-bg);
border-radius: 8px;
}
#wordList::-webkit-scrollbar-thumb,
body::-webkit-scrollbar-thumb {
background: var(--accent);
border-radius: 8px;
min-height: 24px;
border: 2px solid var(--section-bg);
}
#wordList::-webkit-scrollbar-thumb:hover,
body::-webkit-scrollbar-thumb:hover {
background: var(--accent-hover);
}
#wordList::-webkit-scrollbar-corner,
body::-webkit-scrollbar-corner {
background: var(--section-bg);
}
:root {
--scrollbar-bg: var(--section-bg);
--scrollbar-thumb: var(--accent);
--scrollbar-thumb-hover: var(--accent-hover);
--scrollbar-thumb-border: var(--section-bg);
}
html, body, #wordList {
scrollbar-width: thin;
scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-bg);
}
html::-webkit-scrollbar,
body::-webkit-scrollbar,
#wordList::-webkit-scrollbar {
width: 8px;
background: var(--scrollbar-bg);
border-radius: 8px;
}
html::-webkit-scrollbar-thumb,
body::-webkit-scrollbar-thumb,
#wordList::-webkit-scrollbar-thumb {
background: var(--scrollbar-thumb);
border-radius: 8px;
min-height: 24px;
border: 2px solid var(--scrollbar-thumb-border);
}
html::-webkit-scrollbar-thumb:hover,
body::-webkit-scrollbar-thumb:hover,
#wordList::-webkit-scrollbar-thumb:hover {
background: var(--scrollbar-thumb-hover);
}
html::-webkit-scrollbar-corner,
body::-webkit-scrollbar-corner,
#wordList::-webkit-scrollbar-corner {
background: var(--scrollbar-bg);
}

View File

@@ -77,10 +77,16 @@
<button id="disableSelectedBtn"><span data-i18n="disable_selected">Disable</span></button>
<button id="deleteSelectedBtn" class="danger"><span data-i18n="delete_selected">Delete</span></button>
</div>
<input type="text" id="wordSearch" data-i18n="search_placeholder" placeholder="Search..." />
<div id="wordList"></div>
</div>
<div class="section">
<h2><i class="fa-solid fa-sliders"></i> <span data-i18n="options">Options</span></h2>
<div class="button-row" style="margin-bottom:8px;">
<label><input type="checkbox" id="matchCase" /> <span data-i18n="match_case">Match Case</span></label>
<label><input type="checkbox" id="matchWhole" /> <span data-i18n="match_whole">Match Whole Word</span></label>
</div>
<div class="button-row">
<button id="importBtn"><i class="fa-solid fa-upload"></i> <span data-i18n="import_list">Import</span></button>
<input type="file" id="importInput" accept="application/json" hidden />

View File

@@ -1,16 +1,20 @@
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 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 matchCaseEnabled = false;
let matchWholeEnabled = false;
function escapeHtml(str) {
return str.replace(/[&<>"']/g, function (m) {
@@ -19,22 +23,17 @@ 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,
globalHighlightEnabled: globalHighlightEnabled
globalHighlightEnabled: globalHighlightEnabled,
matchCaseEnabled,
matchWholeEnabled
});
renderLists();
renderWords();
@@ -42,11 +41,16 @@ 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',
matchCase: matchCaseEnabled,
matchWhole: matchWholeEnabled
});
}
}
});
@@ -58,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
});
}
@@ -69,17 +73,23 @@ async function updateGlobalToggleState() {
async function load() {
const res = await chrome.storage.local.get({
lists: [],
globalHighlightEnabled: true
globalHighlightEnabled: true,
matchCaseEnabled: false,
matchWholeEnabled: false
});
lists = res.lists;
globalHighlightEnabled = res.globalHighlightEnabled !== false; // Default to true if undefined
globalHighlightEnabled = res.globalHighlightEnabled !== false;
matchCaseEnabled = !!res.matchCaseEnabled;
matchWholeEnabled = !!res.matchWholeEnabled;
matchCase.checked = matchCaseEnabled;
matchWhole.checked = matchWholeEnabled;
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: []
});
@@ -87,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();
}
@@ -108,7 +118,12 @@ function updateListForm() {
function renderWords() {
const list = lists[currentListIndex];
const fragment = document.createDocumentFragment();
let filteredWords = list.words;
if (wordSearchQuery.trim()) {
const q = wordSearchQuery.trim().toLowerCase();
filteredWords = list.words.filter(w => w.wordStr.toLowerCase().includes(q));
}
const itemHeight = 32;
const containerHeight = wordList.clientHeight;
@@ -116,19 +131,20 @@ function renderWords() {
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = Math.min(
startIndex + Math.ceil(containerHeight / itemHeight) + 2,
list.words.length
filteredWords.length
);
wordList.innerHTML = '';
const spacer = document.createElement('div');
spacer.style.position = 'relative';
spacer.style.height = `${list.words.length * itemHeight}px`;
spacer.style.height = `${filteredWords.length * itemHeight}px`;
spacer.style.width = '100%';
for (let i = startIndex; i < endIndex; i++) {
const w = list.words[i];
const container = document.createElement("div");
const w = filteredWords[i];
if (!w) continue;
const container = document.createElement('div');
container.style.height = `${itemHeight}px`;
container.style.position = 'absolute';
container.style.top = `${i * itemHeight}px`;
@@ -143,18 +159,20 @@ function renderWords() {
container.style.background = 'var(--highlight-tag)';
container.style.border = '1px solid var(--highlight-tag-border)';
const cbSelect = document.createElement("input");
cbSelect.type = "checkbox";
cbSelect.className = "word-checkbox";
cbSelect.dataset.index = i;
if (selectedCheckboxes.has(i)) {
const realIndex = list.words.indexOf(w);
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 = i;
inputWord.dataset.wordEdit = realIndex;
inputWord.style.flexGrow = '1';
inputWord.style.minWidth = '0';
inputWord.style.padding = '4px 8px';
@@ -163,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 = i;
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 = i;
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 = i;
cbActive.className = "switch";
cbActive.dataset.activeEdit = realIndex;
cbActive.className = 'switch';
activeContainer.appendChild(cbActive);
@@ -207,13 +225,13 @@ function renderWords() {
const wordCount = document.getElementById('wordCount');
if (wordCount) {
wordCount.textContent = list.words.length;
wordCount.textContent = filteredWords.length;
}
}
document.addEventListener('DOMContentLoaded', () => {
localizePage();
document.getElementById("selectAllBtn").onclick = () => {
document.getElementById('selectAllBtn').onclick = () => {
const list = lists[currentListIndex];
list.words.forEach((_, index) => {
selectedCheckboxes.add(index);
@@ -221,14 +239,13 @@ document.addEventListener('DOMContentLoaded', () => {
renderWords();
};
// Add event listener for the global toggle
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);
@@ -261,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: []
});
@@ -274,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();
@@ -287,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));
@@ -306,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;
@@ -315,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;
@@ -324,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;
@@ -336,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 => {
@@ -363,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);
@@ -410,10 +427,25 @@ document.addEventListener('DOMContentLoaded', () => {
}
});
document.getElementById("deselectAllBtn").onclick = () => {
document.getElementById('deselectAllBtn').onclick = () => {
selectedCheckboxes.clear();
renderWords();
};
const wordSearch = document.getElementById('wordSearch');
wordSearch.addEventListener('input', (e) => {
wordSearchQuery = e.target.value;
renderWords();
});
matchCase.addEventListener('change', () => {
matchCaseEnabled = matchCase.checked;
save();
});
matchWhole.addEventListener('change', () => {
matchWholeEnabled = matchWhole.checked;
save();
});
load();
});

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 });
}