-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
632 lines (572 loc) · 20.7 KB
/
content.js
File metadata and controls
632 lines (572 loc) · 20.7 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
console.log("SLACTAC Content Script STARTING - Top of file");
// --- Inject CSS for picker highlighting ---
const pickerStyleSheet = document.createElement("style");
pickerStyleSheet.textContent = `
/* Renamed channels during picker mode - show with yellow/accent color */
.slactac-picker-renamed-channel {
background-color: rgba(215, 153, 33, 0.25) !important;
border-left: 3px solid #d79921 !important;
padding-left: 5px !important;
transition: all 0.15s ease-out;
}
`;
document.head.appendChild(pickerStyleSheet);
// --- SLACTAC Name Overriding Variables & Functions ---
function overrideChatroomNames() {
// Load saved overrides from storage
storage.get().then((overrides) => {
const sidebarSelector = ".p-channel_sidebar__list"; // Optional improvement
const nameOverrideSelector = ".p-channel_sidebar__name"; // Selector for channel names
const listContainer = document.querySelector(sidebarSelector);
const nameElements = listContainer
? listContainer.querySelectorAll(nameOverrideSelector)
: document.querySelectorAll(nameOverrideSelector);
nameElements.forEach((element) => {
if (!element.dataset.originalNameSlactac) {
element.dataset.originalNameSlactac = element.innerText.trim();
}
const originalName = element.dataset.originalNameSlactac;
if (overrides[originalName]) {
if (element.innerText.trim() !== overrides[originalName]) {
element.innerText = overrides[originalName];
}
} else {
if (element.innerText.trim() !== originalName) {
element.innerText = originalName;
}
}
});
}).catch(error => {
console.error("SLACTAC: Failed to get overrides for name replacement.", error);
});
}
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
const debouncedOverrideNames = debounce(overrideChatroomNames, 300);
// ============================================================
// --- Channel Picker Logic with Darken/Blur Effect ---
// ============================================================
let channelPickerActive = false;
let originalCursor = null;
const overlayContainerId = "slactac-overlay-container";
const highlightedElementClass = "slactac-picker-highlighted-target";
const renamedChannelClass = "slactac-picker-renamed-channel";
let currentHighlightedElement = null;
let currentHighlightedNameElement = null;
let defaultHighlightedRegion = null;
let channelPickerProcessing = false;
let pickerFailsafeTimer = null;
const LOCAL_PICK_KEY = "lastPickedChannelName";
const CHANNEL_LIST_SELECTORS = [
".p-channel_sidebar__static_list",
".p-channel_sidebar__list",
"[data-qa='channel_sidebar']",
"[data-qa='slack_kit_list']",
".p-channel_sidebar",
".p-workspace__sidebar"
];
const CHANNEL_ITEM_SELECTORS = [
"[data-qa='channel_sidebar_channel']",
"[data-qa-channel-sidebar-channel-id]",
"[role='treeitem']",
".p-channel_sidebar__channel",
".p-channel_sidebar__static_channel",
".p-channel_sidebar__link"
];
const CHANNEL_NAME_SELECTORS = [
".p-channel_sidebar__name",
"[data-qa='channel_sidebar_channel_name']",
"[data-qa='channel_sidebar_name']",
"[data-qa^='channel_sidebar_name_']",
"[data-qa^='channel_sidebar_channel_name_']"
];
function storePickedChannelName(name) {
return new Promise((resolve, reject) => {
const sanitizedName = typeof name === "string" ? name.trim() : "";
if (!sanitizedName) {
browser.storage.local.remove(LOCAL_PICK_KEY).then(
() => {
resolve();
},
(error) => {
reject(new Error(error.message || String(error)));
}
);
return;
}
browser.storage.local.set({ [LOCAL_PICK_KEY]: sanitizedName }).then(
() => {
resolve();
},
(error) => {
reject(new Error(error.message || String(error)));
}
);
});
}
// --- Picker Utility Functions ---
function createPickerOverlays() {
let container = document.getElementById(overlayContainerId);
if (container) {
container.style.display = "block";
return;
}
container = document.createElement("div");
container.id = overlayContainerId;
container.style.position = "fixed";
container.style.top = "0";
container.style.left = "0";
container.style.width = "100vw";
container.style.height = "100vh";
container.style.zIndex = "2147483646";
container.style.pointerEvents = "none";
const overlayStyles = `
position: absolute;
background-color: rgba(0, 0, 0, 0.65);
backdrop-filter: blur(1.5px);
transition: all 0.05s ease-out;
`;
["top", "bottom", "left", "right"].forEach((pos) => {
const overlay = document.createElement("div");
overlay.id = `slactac-picker-overlay-${pos}`;
overlay.style.cssText = overlayStyles;
container.appendChild(overlay);
});
document.body.appendChild(container);
console.log("SLACTAC Picker: Overlays created.");
}
function removePickerOverlays() {
const container = document.getElementById(overlayContainerId);
if (container) {
container.remove();
console.log("SLACTAC Picker: Overlays removed.");
}
if (currentHighlightedElement) {
currentHighlightedElement.classList.remove(highlightedElementClass);
currentHighlightedElement.style.position = "";
currentHighlightedElement.style.zIndex = "";
currentHighlightedElement = null;
currentHighlightedNameElement = null;
}
defaultHighlightedRegion = null;
}
function getElementUnderCursor(event) {
const container = document.getElementById(overlayContainerId);
let originalDisplay = "";
if (container) {
originalDisplay = container.style.display;
container.style.display = "none";
}
const element = document.elementFromPoint(event.clientX, event.clientY);
if (container) {
container.style.display = originalDisplay;
}
return element;
}
function matchFirstSelector(element, selectors) {
if (!element) return null;
for (const selector of selectors) {
if (element.matches && element.matches(selector)) {
return element;
}
}
return null;
}
function queryFirstSelector(selectors, root = document) {
for (const selector of selectors) {
const found = root.querySelector(selector);
if (found) {
return found;
}
}
return null;
}
function getChannelSidebarContainer() {
return queryFirstSelector(CHANNEL_LIST_SELECTORS);
}
function findNearestChannelNameElement(element) {
let current = element;
while (current && current !== document.body && current !== document.documentElement) {
const matched = matchFirstSelector(current, CHANNEL_NAME_SELECTORS);
if (matched) {
return matched;
}
current = current.parentElement;
}
return null;
}
function findEnclosingChannelItem(element) {
if (!element) return null;
if (!element.closest) return null;
const selector = CHANNEL_ITEM_SELECTORS.join(", ");
return element.closest(selector);
}
function resolveChannelTarget(startElement) {
if (!startElement || startElement.id?.startsWith("slactac-picker-overlay")) {
return null;
}
if (startElement.nodeType !== Node.ELEMENT_NODE) {
startElement = startElement.parentElement;
}
if (!startElement) {
return null;
}
const sidebar = getChannelSidebarContainer();
if (sidebar && !sidebar.contains(startElement)) {
return null;
}
// Strategy: Find the encompassing channel item first.
const channelItem = findEnclosingChannelItem(startElement);
if (channelItem) {
// Now find the name within that item.
let nameElement = queryFirstSelector(CHANNEL_NAME_SELECTORS, channelItem);
// If no specific name selector matches, find the most likely text node.
if (!nameElement) {
const textElements = Array.from(channelItem.querySelectorAll("span, div"));
const bestCandidate = textElements.find(
(el) => el.innerText && el.innerText.trim().length > 0
);
nameElement = bestCandidate || channelItem;
}
return {
highlightElement: channelItem,
nameElement: nameElement,
};
}
// Fallback for elements not inside a clear item, but maybe are the item itself.
if (matchFirstSelector(startElement, CHANNEL_ITEM_SELECTORS)) {
const nameElement =
queryFirstSelector(CHANNEL_NAME_SELECTORS, startElement) || startElement;
return {
highlightElement: startElement,
nameElement: nameElement,
};
}
return null;
}
function highlightDefaultChannelRegion() {
const sidebar = getChannelSidebarContainer();
defaultHighlightedRegion = sidebar || null;
if (sidebar) {
highlightPickerElement(sidebar, null, { isDefault: true });
} else {
highlightPickerElement(null, null, { isDefault: true });
}
}
function highlightPickerElement(element, nameElement = null, options = {}) {
const { isDefault = false } = options;
const container = document.getElementById(overlayContainerId);
if (!container) return;
if (element && element.nodeType !== Node.ELEMENT_NODE) {
element = element.parentElement || null;
}
const overlayTop = document.getElementById("slactac-picker-overlay-top");
const overlayBottom = document.getElementById(
"slactac-picker-overlay-bottom"
);
const overlayLeft = document.getElementById("slactac-picker-overlay-left");
const overlayRight = document.getElementById("slactac-picker-overlay-right");
if (currentHighlightedElement && currentHighlightedElement !== element) {
if (currentHighlightedElement === defaultHighlightedRegion) {
defaultHighlightedRegion = null;
}
currentHighlightedElement.classList.remove(highlightedElementClass);
currentHighlightedElement.style.position = "";
currentHighlightedElement.style.zIndex = "";
currentHighlightedElement = null;
currentHighlightedNameElement = null;
}
if (!element) {
overlayTop.style.height = "100%";
overlayTop.style.width = "100%";
overlayTop.style.top = "0";
overlayTop.style.left = "0";
overlayBottom.style.height = "0";
overlayLeft.style.height = "0";
overlayRight.style.height = "0";
if (currentHighlightedElement) {
currentHighlightedElement.classList.remove(highlightedElementClass);
currentHighlightedElement.style.position = "";
currentHighlightedElement.style.zIndex = "";
currentHighlightedElement = null;
currentHighlightedNameElement = null;
}
return;
}
if (element !== currentHighlightedElement) {
element.style.position = "relative";
element.style.zIndex = "2147483647";
element.classList.add(highlightedElementClass);
currentHighlightedElement = element;
}
currentHighlightedNameElement = nameElement;
if (isDefault) {
defaultHighlightedRegion = element;
} else if (element !== defaultHighlightedRegion) {
defaultHighlightedRegion = null;
}
const rect = element.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
overlayTop.style.top = `0px`;
overlayTop.style.left = `0px`;
overlayTop.style.width = `${vw}px`;
overlayTop.style.height = `${rect.top}px`;
overlayBottom.style.top = `${rect.bottom}px`;
overlayBottom.style.left = `0px`;
overlayBottom.style.width = `${vw}px`;
overlayBottom.style.height = `${vh - rect.bottom}px`;
overlayLeft.style.top = `${rect.top}px`;
overlayLeft.style.left = `0px`;
overlayLeft.style.width = `${rect.left}px`;
overlayLeft.style.height = `${rect.height}px`;
overlayRight.style.top = `${rect.top}px`;
overlayRight.style.left = `${rect.right}px`;
overlayRight.style.width = `${vw - rect.right}px`;
overlayRight.style.height = `${rect.height}px`;
}
// --- Updated Extraction Function ---
function extractPickerChannelName(nameElement, fallbackElement = null) {
const element = nameElement || fallbackElement;
if (!element) return null;
const textSource =
typeof element.innerText === "string"
? element.innerText
: typeof element.textContent === "string"
? element.textContent
: "";
const pickedText = textSource.trim();
if (!pickedText || pickedText.length < 1) {
return null;
}
return pickedText;
}
// --- Picker Event Handlers ---
function channelPickerMouseMoveHandler(event) {
if (!channelPickerActive) return;
const elementUnderCursor = getElementUnderCursor(event);
const target = resolveChannelTarget(elementUnderCursor);
if (target) {
highlightPickerElement(target.highlightElement, target.nameElement);
} else {
highlightDefaultChannelRegion();
}
}
async function channelPickerClickHandler(event) {
if (!channelPickerActive || channelPickerProcessing) {
return;
}
console.log("SLACTAC Picker: Click detected. Processing...");
channelPickerProcessing = true;
event.preventDefault();
event.stopPropagation();
// Deactivate picker visuals immediately for a responsive feel
deactivateChannelPicker();
const target = resolveChannelTarget(event.target);
const channelName = extractPickerChannelName(
target ? target.nameElement : null,
target ? target.highlightElement : null
);
try {
if (channelName) {
console.log(`SLACTAC Picker: Storing channel name: ${channelName}`);
await storePickedChannelName(channelName);
console.log("SLACTAC Picker: Stored picked channel in local storage.");
} else {
console.warn(
"SLACTAC Picker: Clicked on a non-channel element. No action taken."
);
}
} catch (error) {
console.error("SLACTAC Picker: Error during click handler execution:", error);
} finally {
console.log("SLACTAC Picker: Click processing finished.");
channelPickerProcessing = false;
}
}
function isSlackPage() {
return window.location.hostname.includes("app.slack.com");
}
function markRenamedChannelsInPicker() {
// Get all overrides from storage
storage.get().then((overrides) => {
// overrides is a map of { originalChannelName: customName, ... }
// We need to check if any displayed channel name matches a custom name (value) in overrides
const allCustomNames = Object.values(overrides); // Get all custom names
console.log("SLACTAC Picker: Stored Tacks (overrides):", overrides);
console.log("SLACTAC Picker: Custom names to look for:", allCustomNames);
// Find all channel items in the sidebar
const sidebarSelector = ".p-channel_sidebar__list";
const nameOverrideSelector = ".p-channel_sidebar__name";
const listContainer = document.querySelector(sidebarSelector);
const nameElements = listContainer
? listContainer.querySelectorAll(nameOverrideSelector)
: document.querySelectorAll(nameOverrideSelector);
console.log(`SLACTAC Picker: Found ${nameElements.length} channel name elements`);
// Mark channels that have been renamed
let markedCount = 0;
nameElements.forEach((element) => {
const displayName = element.innerText.trim();
// Check if this displayed name matches any custom name in Stored Tacks
if (allCustomNames.includes(displayName)) {
console.log(`SLACTAC Picker: MATCH! "${displayName}" found in Stored Tacks (custom name)`);
// Find the channel item that contains this name element
const channelItem = element.closest(CHANNEL_ITEM_SELECTORS.join(", "));
if (channelItem) {
channelItem.classList.add(renamedChannelClass);
channelItem.dataset.renamedBySlactac = "true";
markedCount++;
console.log(`SLACTAC Picker: Highlighted "${displayName}" with yellow`);
}
}
});
console.log(`SLACTAC Picker: Marked ${markedCount} channels with yellow highlight.`);
}).catch(error => {
console.error("SLACTAC: Failed to mark renamed channels in picker.", error);
});
}function activateChannelPicker() {
if (channelPickerActive) {
console.log("SLACTAC Picker: Already active.");
return true;
}
if (!isSlackPage()) {
console.warn("SLACTAC: Not on a Slack page, cannot activate picker.");
return false;
}
console.log("SLACTAC Picker: Activating with visual effects...");
channelPickerActive = true;
originalCursor = document.body.style.cursor;
document.body.style.cursor = "crosshair";
createPickerOverlays();
highlightDefaultChannelRegion();
markRenamedChannelsInPicker(); // Mark renamed channels with yellow
document.addEventListener("mousemove", channelPickerMouseMoveHandler, true);
document.addEventListener("click", channelPickerClickHandler, true);
document.addEventListener("keydown", handleKeyDown, true);
// Failsafe: If the picker is active for too long, deactivate it automatically.
pickerFailsafeTimer = setTimeout(() => {
console.warn("SLACTAC Picker: Failsafe timer triggered. Deactivating picker automatically.");
deactivateChannelPicker(true);
}, 15000); // 15 seconds
console.log("SLACTAC Picker: Activated with visual effects.");
return true;
}
function deactivateChannelPicker(force = false) {
if (!channelPickerActive && !force) {
return;
}
console.log("SLACTAC Picker: Deactivating...");
channelPickerActive = false;
document.body.style.cursor = originalCursor;
removePickerOverlays();
document.removeEventListener("mousemove", channelPickerMouseMoveHandler, true);
document.removeEventListener("click", channelPickerClickHandler, true);
document.removeEventListener("keydown", handleKeyDown, true);
// Remove renamed channel markings
document.querySelectorAll(`.${renamedChannelClass}`).forEach((element) => {
element.classList.remove(renamedChannelClass);
element.removeAttribute("data-renamedBySlactac");
});
// Clear the failsafe timer
if (pickerFailsafeTimer) {
clearTimeout(pickerFailsafeTimer);
pickerFailsafeTimer = null;
}
console.log("SLACTAC Picker: Deactivated.");
}
function handleKeyDown(event) {
if (channelPickerActive && event.key === "Escape") {
console.log("SLACTAC Picker: Escape key pressed. Deactivating picker.");
deactivateChannelPicker(true);
}
}
// ============================================================
// --- End of Picker Logic ---
// ============================================================
// --- Initial Name Override & Observer Setup ---
overrideChatroomNames();
const observer = new MutationObserver((mutationsList, observer) => {
let potentiallyRelevantChange = false;
for (const mutation of mutationsList) {
if (mutation.type === "childList") {
if (mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
const nameOverrideSelector = ".p-channel_sidebar__name";
if (
node.nodeType === Node.ELEMENT_NODE &&
(node.matches(nameOverrideSelector) ||
node.querySelector(nameOverrideSelector))
) {
potentiallyRelevantChange = true;
break;
}
}
}
if (mutation.removedNodes.length > 0) {
potentiallyRelevantChange = true;
}
}
if (potentiallyRelevantChange) break;
}
if (potentiallyRelevantChange) {
debouncedOverrideNames();
}
});
const sidebarTargetSelector = ".p-channel_sidebar__list";
const targetNode =
document.querySelector(sidebarTargetSelector) || document.body;
console.log(
`SLACTAC: Observing ${
targetNode === document.body
? "document.body (fallback)"
: sidebarTargetSelector
} for changes (Name Override).`
);
observer.observe(targetNode, { childList: true, subtree: true });
// --- Combined Message Listener ---
console.log("SLACTAC CONTENT SCRIPT: Setting up message listener...");
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("SLACTAC CONTENT SCRIPT: Message received -> ", request.action);
if (request.action === "refreshNamesSLACTAC") {
console.log("SLACTAC: Handling refreshNamesSLACTAC");
overrideChatroomNames();
sendResponse({ status: "Names refreshed by content script." });
return true;
} else if (request.action === "activateChannelPicker") {
console.log("SLACTAC: Handling activateChannelPicker (with visual FX)");
const activated = activateChannelPicker();
sendResponse({
success: activated,
status: activated
? "Picker Activated (FX)"
: "Failed to activate picker (FX)",
});
return true;
} else if (request.action === "deactivateChannelPicker") {
console.log("SLACTAC: Handling deactivateChannelPicker (with visual FX)");
deactivateChannelPicker();
sendResponse({
success: true,
status: "Picker Deactivated by request (FX)",
});
return true;
}
console.log("SLACTAC: Unknown message action received:", request.action);
return false;
});
// --- Cleanup on Load ---
removePickerOverlays();
if (document.body.style.cursor === "crosshair") {
console.warn("SLACTAC: Found crosshair cursor on load, resetting.");
document.body.style.cursor = "";
}
console.log("SLACTAC: Content script fully initialized.");