forked from DiwasKhatri07/KnightSense-Chess-Engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
364 lines (336 loc) · 16.3 KB
/
Copy pathpopup.js
File metadata and controls
364 lines (336 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/* KnightSense popup controller */
document.addEventListener('DOMContentLoaded', () => {
const $ = (id) => document.getElementById(id);
// -------- tabs
const tabs = Array.from(document.querySelectorAll('.tab'));
const panels = Array.from(document.querySelectorAll('.panel'));
tabs.forEach((t) => {
t.addEventListener('click', () => {
tabs.forEach(x => x.classList.toggle('active', x === t));
panels.forEach((p) => p.classList.toggle('active', p.id === 'panel-' + t.dataset.tab));
});
});
// -------- elements
const engineToggle = $('toggle-engine');
const statusDot = $('status-dot');
const statusText = $('status-text');
const depthSlider = $('depth-slider'), depthValue = $('depth-value');
const timeSlider = $('time-slider'), timeValue = $('time-value');
const sideBtns = Array.from(document.querySelectorAll('.seg-btn'));
const sideValue = $('side-value');
const bestMsg = $('best-moves-message'), bestList = $('best-moves'), bestSub = $('best-sub');
const arrowColorInputs = Array.from(document.querySelectorAll('.color-input.lc'));
const paletteGrid = $('palette-grid');
const widthSlider = $('width-slider'), widthValue = $('width-value');
const opacitySlider = $('opacity-slider'), opacityValue = $('opacity-value');
const headSlider = $('head-slider'), headValue = $('head-value');
const linesSlider = $('lines-slider'), linesValue = $('lines-value');
const highlightToggle = $('toggle-highlight'), highlightColor = $('highlight-color'), chipToggle = $('toggle-chip');
const stealthToggle = $('toggle-stealth');
const hideNow = $('btn-hide-now');
const toggleTheme = $('toggle-theme');
const popupBody = document.body;
// analysis info + saved games
const infoGrid = $('info-grid'), infoEval = $('info-eval'), infoDepth = $('info-depth'), infoNodes = $('info-nodes'), infoMove = $('info-move');
const saveBtn = $('btn-save'), savedList = $('saved-list'), savedEmpty = $('saved-empty');
let lastFen = null;
const PREFS = [
'engineEnabled','engineDepth','engineTime','analysisSide',
'arrowColors','arrowWidth','arrowHeadSize','arrowOpacity',
'numLines','highlightEnabled','highlightColor','evalChipEnabled','overlayHidden','popupTheme'
];
function applyNepalTheme(on) {
popupBody.classList.toggle('theme-nepal', !!on);
}
const PALETTES = {
nepal: { label: 'Nepal', colors: ['#c8102e','#003893','#ffd400','#39c26e','#ffffff'] },
amber: { label: 'Amber', colors: ['#ffaa00','#39c26e','#4aa8ff','#ff5b5b','#c99aff'] },
fire: { label: 'Fire', colors: ['#ff5722','#ff8a00','#ffc107','#ff5252','#ff6e40'] },
ocean: { label: 'Ocean', colors: ['#00bcd4','#4fc3f7','#2979ff','#3f51b5','#00e5ff'] },
royal: { label: 'Royal', colors: ['#7c4dff','#ff6ec7','#00e5ff','#ffd740','#9d00ff'] },
mint: { label: 'Mint', colors: ['#4caf50','#8bc34a','#b38803','#00e676','#66bb6a'] },
slate: { label: 'Slate', colors: ['#ffffff','#cfcfcf','#9a9a9a','#6a6a6a','#444444'] }
};
function getArrowColors(r) {
if (Array.isArray(r.arrowColors) && r.arrowColors.length >= 3) return r.arrowColors.slice(0, 5);
return PALETTES.nepal.colors.slice();
}
function applyArrowColors(colors) {
arrowColorInputs.forEach((inp) => {
const idx = parseInt(inp.dataset.line, 10);
if (colors[idx]) inp.value = colors[idx];
});
}
function persistArrowColors() {
const colors = arrowColorInputs.map((inp) => inp.value);
while (colors.length < 5) colors.push('#888888');
chrome.storage.local.set({ arrowColors: colors });
}
function buildPalette() {
if (!paletteGrid) return;
paletteGrid.innerHTML = '';
Object.keys(PALETTES).forEach((key) => {
const p = PALETTES[key];
const btn = document.createElement('button');
btn.className = 'pal-btn';
const sw = document.createElement('span'); sw.className = 'pal-swatches';
p.colors.slice(0, 3).forEach((c) => {
const s = document.createElement('span'); s.className = 'pal-swatch'; s.style.background = c; sw.appendChild(s);
});
const lab = document.createElement('span'); lab.textContent = p.label;
btn.appendChild(sw); btn.appendChild(lab);
btn.addEventListener('click', () => { applyArrowColors(p.colors); persistArrowColors(); buildPalette(); });
paletteGrid.appendChild(btn);
});
}
// -------- load
chrome.storage.local.get(PREFS, (r) => {
engineToggle.checked = r.engineEnabled !== false;
updateStatus(r.engineEnabled !== false ? 'active' : 'off');
const depth = r.engineDepth || 15;
const time = r.engineTime || 1000;
depthSlider.value = depth; depthValue.textContent = depth;
timeSlider.value = time; timeValue.textContent = time + ' ms';
setSide(r.analysisSide === 'b' ? 'b' : 'w');
applyArrowColors(getArrowColors(r));
buildPalette();
widthSlider.value = r.arrowWidth || 2.5; widthValue.textContent = (r.arrowWidth || 2.5);
opacitySlider.value = r.arrowOpacity ? Math.round(r.arrowOpacity * 100) : 90; opacityValue.textContent = opacitySlider.value + '%';
headSlider.value = r.arrowHeadSize || 3; headValue.textContent = (r.arrowHeadSize || 3);
linesSlider.value = r.numLines || 1; linesValue.textContent = (r.numLines || 1);
highlightToggle.checked = r.highlightEnabled !== false;
chipToggle.checked = r.evalChipEnabled !== false;
highlightColor.value = r.highlightColor || '#003893';
stealthToggle.checked = !!r.overlayHidden;
applyNepalTheme(r.popupTheme !== false);
if (toggleTheme) toggleTheme.checked = r.popupTheme !== false;
if (Array.isArray(r.bestLines) && r.bestLines.length) {
renderBest(r.bestLines, r.analysisState || 'ready');
}
});
// ---------- helpers
function isChessTab(tab) { return !!(tab && tab.url && tab.url.indexOf('chess.com') !== -1); }
function send(msg, cb) {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const t = tabs && tabs[0];
if (!isChessTab(t)) { if (cb) cb(false); return; }
chrome.tabs.sendMessage(t.id, msg, () => {
if (chrome.runtime.lastError) { if (cb) cb(false); return; }
if (cb) cb(true);
});
});
}
function updateStatus(state) {
if (state === 'active') { statusDot.className = 'dot'; statusText.textContent = 'Engine active'; }
else if (state === 'off') { statusDot.className = 'dot off'; statusText.textContent = 'Engine off'; }
else if (state === 'err') { statusDot.className = 'dot err'; statusText.textContent = 'Engine error'; }
else if (state === 'proc') { statusDot.className = 'dot'; statusText.textContent = 'Analyzing…'; }
else { statusDot.className = 'dot off'; statusText.textContent = 'No board'; }
}
function setSide(v) {
const side = (v === 'b') ? 'Black' : 'White';
sideValue.textContent = side;
sideBtns.forEach((b) => b.classList.toggle('active', (v === 'b') ? b.dataset.side === 'b' : b.dataset.side === 'w'));
}
function renderBest(lines, state) {
const L = lines || [];
if (L.length) {
bestMsg.style.display = 'none';
bestList.innerHTML = '';
L.forEach((item, i) => {
const li = document.createElement('li');
li.className = 'best-item';
const mv = document.createElement('span');
mv.className = 'mv'; mv.textContent = (i + 1) + '. ' + item.move;
const sc = document.createElement('span');
sc.className = 'sc'; sc.textContent = item.score || '';
const left = document.createElement('span');
left.style.display = 'flex'; left.style.alignItems = 'center'; left.style.gap = '6px';
left.appendChild(mv);
if (item.depth) { const d = document.createElement('span'); d.className = 'score'; d.style.cssText='color:var(--muted);font-size:10px;'; d.textContent = 'd' + item.depth; left.appendChild(d); }
li.appendChild(left); li.appendChild(sc);
bestList.appendChild(li);
});
bestSub.textContent = state === 'proc' ? 'Analyzing…' : (state === 'ready' ? 'Ready' : state);
updateInfo(L[0]);
} else {
bestList.innerHTML = '';
if (infoGrid) infoGrid.style.display = 'none';
bestMsg.style.display = 'block';
bestMsg.classList.remove('err');
if (state === 'proc') bestMsg.textContent = 'Analyzing…';
else if (state === 'err') { bestMsg.classList.add('err'); bestMsg.textContent = 'Engine error'; }
else if (state === 'off') bestMsg.textContent = 'Engine disabled';
else bestMsg.textContent = 'Open a Chess.com game';
bestSub.textContent = state || '—';
}
}
function updateInfo(line) {
if (!infoGrid) return;
if (line && line.move) {
infoGrid.style.display = 'grid';
if (infoEval) infoEval.textContent = line.score || '0.00';
if (infoDepth) infoDepth.textContent = line.depth ? 'd' + line.depth : '—';
if (infoNodes) infoNodes.textContent = line.nodes ? fmtNodes(line.nodes) : '—';
if (infoMove) infoMove.textContent = line.move || '—';
} else {
infoGrid.style.display = 'none';
}
}
function fmtNodes(n) {
const v = parseInt(n, 10); if (isNaN(v)) return n;
if (v >= 1e6) return (v / 1e6).toFixed(1) + 'M';
if (v >= 1e3) return (v / 1e3).toFixed(1) + 'K';
return String(v);
}
// ---------- engine tab
engineToggle.addEventListener('change', (e) => {
const on = e.target.checked;
chrome.storage.local.set({ engineEnabled: on });
updateStatus(on ? 'active' : 'off');
send({ type: 'TOGGLE_ENGINE', enabled: on });
});
sideBtns.forEach((b) => b.addEventListener('click', () => {
const v = b.dataset.side;
setSide(v);
chrome.storage.local.set({ analysisSide: v });
if (v !== 'auto') send({ type: 'SET_ANALYSIS_SIDE', turn: v });
}));
depthSlider.addEventListener('input', () => depthValue.textContent = depthSlider.value);
depthSlider.addEventListener('change', () => {
const d = parseInt(depthSlider.value, 10);
chrome.storage.local.set({ engineDepth: d });
send({ type: 'UPDATE_SETTINGS', depth: d, time: parseInt(timeSlider.value, 10), numLines: parseInt(linesSlider.value, 10) });
});
timeSlider.addEventListener('input', () => timeValue.textContent = timeSlider.value + ' ms');
timeSlider.addEventListener('change', () => {
const t = parseInt(timeSlider.value, 10);
chrome.storage.local.set({ engineTime: t });
send({ type: 'UPDATE_SETTINGS', depth: parseInt(depthSlider.value, 10), time: t, numLines: parseInt(linesSlider.value, 10) });
});
// ---------- arrows tab
function persistAppearance() {
persistArrowColors();
chrome.storage.local.set({
arrowWidth: parseFloat(widthSlider.value),
arrowHeadSize: parseFloat(headSlider.value),
arrowOpacity: parseInt(opacitySlider.value, 10) / 100,
numLines: parseInt(linesSlider.value, 10),
highlightEnabled: highlightToggle.checked,
highlightColor: highlightColor.value,
evalChipEnabled: chipToggle.checked
});
}
arrowColorInputs.forEach((inp) => inp.addEventListener('input', persistAppearance));
widthSlider.addEventListener('input', () => widthValue.textContent = widthSlider.value);
widthSlider.addEventListener('change', persistAppearance);
opacitySlider.addEventListener('input', () => opacityValue.textContent = opacitySlider.value + '%');
opacitySlider.addEventListener('change', persistAppearance);
headSlider.addEventListener('input', () => headValue.textContent = headSlider.value);
headSlider.addEventListener('change', persistAppearance);
linesSlider.addEventListener('input', () => { linesValue.textContent = linesSlider.value; });
linesSlider.addEventListener('change', () => {
persistAppearance();
send({ type: 'UPDATE_SETTINGS', depth: parseInt(depthSlider.value,10), time: parseInt(timeSlider.value,10), numLines: parseInt(linesSlider.value,10) });
});
highlightToggle.addEventListener('change', persistAppearance);
highlightColor.addEventListener('input', persistAppearance);
chipToggle.addEventListener('change', persistAppearance);
// ---------- privacy tab
// Content script watches storage.onChanged for overlayHidden, so the
// popup just persists the value and the board updates automatically.
stealthToggle.addEventListener('change', (e) => {
chrome.storage.local.set({ overlayHidden: e.target.checked });
});
hideNow.addEventListener('click', () => {
chrome.storage.local.get('overlayHidden', (s) => {
const next = !s.overlayHidden;
stealthToggle.checked = next;
chrome.storage.local.set({ overlayHidden: next });
});
});
// ---------- theme
if (toggleTheme) {
toggleTheme.addEventListener('change', (e) => {
applyNepalTheme(e.target.checked);
chrome.storage.local.set({ popupTheme: e.target.checked });
});
}
// ---------- incoming engine updates
chrome.runtime.onMessage.addListener((msg) => {
if (!msg || msg.type !== 'ENGINE_BEST_LINES') return;
renderBest(msg.lines || [], msg.state);
updateStatus(msg.state === 'ready' ? 'active' : msg.state === 'processing' ? 'proc' : msg.state === 'error' ? 'err' : msg.state === 'off' ? 'off' : 'no');
chrome.storage.local.set({ bestLines: msg.lines || [], analysisState: msg.state });
});
// ---------- saved games
function loadSavedGames() {
chrome.storage.local.get('savedGames', (s) => renderSavedGames(s.savedGames || []));
}
function renderSavedGames(list) {
if (!savedList) return;
savedList.innerHTML = '';
if (!list || !list.length) { if (savedEmpty) savedEmpty.style.display = 'block'; return; }
if (savedEmpty) savedEmpty.style.display = 'none';
list.slice().reverse().forEach((g) => {
const li = document.createElement('li');
li.className = 'saved-item';
const top = document.createElement('div'); top.className = 'saved-top';
const nm = document.createElement('span'); nm.className = 'saved-name'; nm.textContent = g.name || ('Position ' + g.id.slice(1, 7));
const tm = document.createElement('span'); tm.className = 'saved-time'; tm.textContent = new Date(g.time).toLocaleDateString();
top.appendChild(nm); top.appendChild(tm);
const actions = document.createElement('div'); actions.className = 'saved-actions';
const loadB = document.createElement('button'); loadB.className = 'load'; loadB.textContent = 'Analyze';
loadB.addEventListener('click', () => send({ type: 'ANALYZE_FEN', fen: g.fen }));
const delB = document.createElement('button'); delB.className = 'del'; delB.textContent = 'Delete';
delB.addEventListener('click', () => {
chrome.storage.local.get('savedGames', (s) => {
const next = (s.savedGames || []).filter((x) => x.id !== g.id);
chrome.storage.local.set({ savedGames: next });
renderSavedGames(next);
});
});
actions.appendChild(loadB); actions.appendChild(delB);
li.appendChild(top); li.appendChild(actions);
savedList.appendChild(li);
});
}
saveBtn.addEventListener('click', () => {
const persist = (fen) => {
const name = 'Position ' + new Date().toLocaleTimeString();
chrome.storage.local.get('savedGames', (s) => {
const arr = s.savedGames || [];
arr.push({ id: 'g' + Date.now(), name, fen, time: Date.now() });
const capped = arr.slice(-30);
chrome.storage.local.set({ savedGames: capped });
renderSavedGames(capped);
});
};
if (lastFen) { persist(lastFen); return; }
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const t = tabs && tabs[0];
if (!isChessTab(t)) { persist('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'); return; }
chrome.tabs.sendMessage(t.id, { type: 'GET_FEN' }, (r) => {
if (!chrome.runtime.lastError && r && r.fen) { lastFen = r.fen; persist(r.fen); }
else persist('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1');
});
});
});
loadSavedGames();
// ---------- request current on open
send({ type: 'GET_ENGINE_BEST_LINES' }, (ok) => {
if (!ok) updateStatus('no');
});
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const t = tabs && tabs[0];
if (!isChessTab(t)) return;
chrome.tabs.sendMessage(t.id, { type: 'GET_FEN' }, (r) => {
if (!chrome.runtime.lastError && r && r.fen) lastFen = r.fen;
});
});
send({ type: 'GET_OVERLAY_STATE' }, (ok) => {
if (ok) {
chrome.storage.local.get('overlayHidden', (s) => { stealthToggle.checked = !!s.overlayHidden; });
}
});
});