-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
795 lines (654 loc) · 19.9 KB
/
Copy pathcontent.js
File metadata and controls
795 lines (654 loc) · 19.9 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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
// Main content script - coordinates PII detection and highlighting
// Global service state
let serviceEnabled = false;
let siteProtectionEnabled = false;
let bulkActionsAllowedForSite = false;
// Track attached elements for cleanup
const attachedElements = new Set();
// Load initial service state
chrome.storage.local.get("serviceEnabled").then((result) => {
serviceEnabled = result.serviceEnabled === true;
if (!serviceEnabled) {
// Remove all overlays if service is disabled
for (const el of attachedElements) {
removeOverlay(el);
}
}
});
// ---------------- ACTIVE TARGET logic ----------------
let activeEl = null;
let applying = false;
let bulkActionsPanel = null;
let bulkPanelRaf = null;
const bulkActionsAnchorMap = new WeakMap();
const BULK_ACTIONS_BOTTOM_INSET = 8;
const CONTROL_ROW_CLUSTER_TOLERANCE = 18;
const CONTROL_ROW_MAX_OFFSET = 140;
const COMPOSER_CONTROL_SELECTOR = [
"button",
"[role='button']",
"[aria-label*='send' i]",
"[aria-label*='attach' i]",
"[aria-label*='file' i]",
"[aria-label*='microphone' i]",
"[aria-label*='voice' i]",
"[data-testid*='send' i]",
"[data-testid*='attach' i]",
"[data-testid*='composer' i]",
].join(", ");
function setApplyingState(value) {
applying = value;
if (!bulkActionsPanel) return;
const buttons = bulkActionsPanel.querySelectorAll("button");
for (const btn of buttons) {
btn.disabled = value;
}
}
function getVisibleEntitiesFor(el) {
if (!el) return [];
const snapshot = getSnapshot(el);
if (!snapshot?.entities?.length) return [];
const ignored = getIgnoreSet(el);
return snapshot.entities.filter((entity) => !ignored.has(ignoreKey(entity)));
}
function buildMaskedText(text, entities) {
const sorted = [...entities].sort((a, b) => a.start - b.start);
let out = "";
let cursor = 0;
for (const entity of sorted) {
const start = Number(entity?.start);
const end = Number(entity?.end);
if (!Number.isFinite(start) || !Number.isFinite(end)) continue;
if (start < cursor || end < start || end > text.length) continue;
out += text.slice(cursor, start);
out += `[${entity.type}]`;
cursor = end;
}
out += text.slice(cursor);
return out;
}
function ensureBulkActionsPanel() {
if (bulkActionsPanel && document.documentElement.contains(bulkActionsPanel)) {
return bulkActionsPanel;
}
// Clean up any stale/duplicate panels left behind by prior script runs.
const stalePanels = document.querySelectorAll(".redactosaurus-bulk-actions");
for (const stale of stalePanels) {
stale.remove();
}
const panel = document.createElement("div");
panel.className = "redactosaurus-bulk-actions";
panel.innerHTML = `
<button type="button" class="mask-all">Mask All</button>
<button type="button" class="ignore-all">Ignore All</button>
`;
panel.querySelector(".mask-all").addEventListener("click", async () => {
const el = activeEl;
if (!el) return;
const visible = getVisibleEntitiesFor(el);
if (visible.length === 0) {
updateBulkActionsPanel();
return;
}
const snapshot = getSnapshot(el);
const baseText = snapshot?.text ?? readText(el);
const maskedText = buildMaskedText(baseText, visible);
const ignoreSet = getIgnoreSet(el);
for (const entity of visible) {
ignoreSet.add(ignoreKey(entity));
}
hideGlobalTooltip();
setApplyingState(true);
try {
writeReplace(el, maskedText);
setSnapshot(el, { text: maskedText, entities: [] });
await refreshOverlayFor(el);
} finally {
setApplyingState(false);
updateBulkActionsPanel();
}
});
panel.querySelector(".ignore-all").addEventListener("click", async () => {
const el = activeEl;
if (!el) return;
const visible = getVisibleEntitiesFor(el);
if (visible.length === 0) {
updateBulkActionsPanel();
return;
}
const ignoreSet = getIgnoreSet(el);
for (const entity of visible) {
ignoreSet.add(ignoreKey(entity));
}
const snapshot = getSnapshot(el);
if (snapshot?.entities?.length) {
snapshot.entities = snapshot.entities.filter(
(entity) => !ignoreSet.has(ignoreKey(entity)),
);
snapshot.text = readText(el);
setSnapshot(el, snapshot);
}
hideGlobalTooltip();
await refreshOverlayFor(el);
updateBulkActionsPanel();
});
document.documentElement.appendChild(panel);
bulkActionsPanel = panel;
return panel;
}
function nextAncestorElement(el) {
if (!el) return null;
if (el.parentElement) return el.parentElement;
const root = el.getRootNode?.();
if (root?.host && root.host.nodeType === Node.ELEMENT_NODE) {
return root.host;
}
return null;
}
function isDisplayedControl(el) {
if (!el) return false;
const cs = window.getComputedStyle(el);
if (cs.display === "none" || cs.visibility === "hidden") return false;
const rect = el.getBoundingClientRect();
return rect.width >= 12 && rect.height >= 12;
}
function collectComposerControls(anchor, inputEl, inputRect) {
const controlsInRow = [];
const controls = anchor.querySelectorAll(COMPOSER_CONTROL_SELECTOR);
for (const control of controls) {
if (control.closest(".redactosaurus-bulk-actions")) continue;
if (inputEl.contains(control)) continue;
if (!isDisplayedControl(control)) continue;
const r = control.getBoundingClientRect();
const centerY = (r.top + r.bottom) / 2;
// Prefer controls in the lower composer region (under/near the input).
if (r.bottom < inputRect.bottom - 24) continue;
if (centerY > inputRect.bottom + CONTROL_ROW_MAX_OFFSET) continue;
controlsInRow.push({ el: control, rect: r, centerY });
}
return controlsInRow;
}
function resolveComposerControlRow(anchor, inputEl, inputRect) {
const controls = collectComposerControls(anchor, inputEl, inputRect);
if (controls.length === 0) return null;
controls.sort((a, b) => a.centerY - b.centerY);
const rows = [];
for (const item of controls) {
let row = rows.find(
(candidate) =>
Math.abs(candidate.centerY - item.centerY) <=
CONTROL_ROW_CLUSTER_TOLERANCE,
);
if (!row) {
row = {
centerY: item.centerY,
controls: [],
minX: item.rect.left,
maxX: item.rect.right,
};
rows.push(row);
}
row.controls.push(item);
row.minX = Math.min(row.minX, item.rect.left);
row.maxX = Math.max(row.maxX, item.rect.right);
const count = row.controls.length;
row.centerY = ((row.centerY * (count - 1)) + item.centerY) / count;
}
rows.sort((a, b) => {
if (b.controls.length !== a.controls.length) {
return b.controls.length - a.controls.length;
}
return (
Math.abs(a.centerY - inputRect.bottom) -
Math.abs(b.centerY - inputRect.bottom)
);
});
return rows[0] || null;
}
function countComposerControls(anchor, inputEl, inputRect) {
return collectComposerControls(anchor, inputEl, inputRect).length;
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
function resolveControlRowCenterX(row, anchorRect, panelWidth) {
if (!row?.controls?.length) {
return anchorRect.width / 2;
}
const controls = [...row.controls].sort((a, b) => a.rect.left - b.rect.left);
let bestGap = 0;
let bestCenter = anchorRect.width / 2;
for (let i = 0; i < controls.length - 1; i++) {
const gapStart = controls[i].rect.right;
const gapEnd = controls[i + 1].rect.left;
const gap = gapEnd - gapStart;
if (gap <= bestGap) continue;
bestGap = gap;
bestCenter = (gapStart + gapEnd) / 2 - anchorRect.left;
}
// If controls are tightly packed, keep centered in composer.
if (bestGap < panelWidth * 0.55) {
bestCenter = anchorRect.width / 2;
}
const horizontalPadding = Math.min(10, panelWidth / 4);
const minX = panelWidth / 2 + horizontalPadding;
const maxX = anchorRect.width - panelWidth / 2 - horizontalPadding;
return clamp(bestCenter, minX, maxX);
}
function resolveBulkActionsAnchor(inputEl) {
const cached = bulkActionsAnchorMap.get(inputEl);
if (
cached &&
document.documentElement.contains(cached) &&
document.documentElement.contains(inputEl) &&
cached.contains(inputEl)
) {
return cached;
}
const fallback = inputEl.parentElement;
const inputRect = inputEl.getBoundingClientRect();
let best = null;
let current = fallback;
let depth = 0;
while (
current &&
current !== document.body &&
current !== document.documentElement &&
depth < 10
) {
const rect = current.getBoundingClientRect();
const extendsBelowInput = rect.bottom - inputRect.bottom >= 18;
const controlCount = extendsBelowInput
? countComposerControls(current, inputEl, inputRect)
: 0;
if (controlCount >= 2) {
best = current;
break;
}
current = nextAncestorElement(current);
depth++;
}
const anchor = best || fallback;
if (anchor) {
bulkActionsAnchorMap.set(inputEl, anchor);
}
return anchor;
}
function positionBulkActionsPanel(panel, el) {
if (!panel || !el) return false;
const anchor = resolveBulkActionsAnchor(el);
if (!anchor) return false;
if (!document.documentElement.contains(anchor)) return false;
const inputRect = el.getBoundingClientRect();
const row = resolveComposerControlRow(anchor, el, inputRect);
// Attach inside composer container so editor internal scrolling does not move the panel.
if (panel.parentElement !== anchor) {
anchor.appendChild(panel);
}
// Absolute child needs a positioned container.
if (window.getComputedStyle(anchor).position === "static") {
anchor.style.position = "relative";
}
const anchorRect = anchor.getBoundingClientRect();
const panelWidth = Math.max(panel.offsetWidth || 0, 120);
if (row) {
const x = resolveControlRowCenterX(row, anchorRect, panelWidth);
const y = clamp(row.centerY - anchorRect.top, 0, anchorRect.height);
panel.style.left = `${x}px`;
panel.style.top = `${y}px`;
panel.style.bottom = "auto";
panel.style.right = "auto";
panel.style.transform = "translate(-50%, -50%)";
return true;
}
// Fallback when a control row cannot be detected.
panel.style.left = "50%";
panel.style.right = "auto";
panel.style.top = "auto";
panel.style.bottom = `${BULK_ACTIONS_BOTTOM_INSET}px`;
panel.style.transform = "translateX(-50%)";
return true;
}
function scheduleBulkActionsPanelUpdate() {
if (bulkPanelRaf != null) return;
bulkPanelRaf = requestAnimationFrame(() => {
bulkPanelRaf = null;
updateBulkActionsPanel();
});
}
function updateBulkActionsPanel() {
const panel = ensureBulkActionsPanel();
if (!serviceEnabled || !activeEl || !isVisible(activeEl)) {
panel.style.display = "none";
panel.style.visibility = "";
return;
}
if (!bulkActionsAllowedForSite) {
panel.style.display = "none";
panel.style.visibility = "";
return;
}
if (readText(activeEl).trim().length === 0) {
panel.style.display = "none";
panel.style.visibility = "";
return;
}
const visible = getVisibleEntitiesFor(activeEl);
if (visible.length === 0) {
panel.style.display = "none";
panel.style.visibility = "";
return;
}
panel.style.visibility = "hidden";
panel.style.display = "flex";
if (!positionBulkActionsPanel(panel, activeEl)) {
panel.style.display = "none";
panel.style.visibility = "";
return;
}
panel.style.visibility = "visible";
}
function setActiveEl(el) {
const candidate = resolveCandidateInput(el);
if (!candidate || !isVisible(candidate)) return;
if (activeEl === candidate) return;
// Hide tooltips on previous active element
if (activeEl) {
hideGlobalTooltip();
}
activeEl = candidate;
scheduleBulkActionsPanelUpdate();
}
// Bind tooltip buttons with callbacks that need access to module state
bindGlobalTooltipButtonsOnce(getIgnoreSet, (val) => {
setApplyingState(val);
});
document.addEventListener(
"focusin",
(ev) => {
if (!serviceEnabled || !siteProtectionEnabled) return;
const candidate = resolveCandidateInput(ev.target);
if (!candidate) return;
attach(candidate);
setActiveEl(candidate);
},
true,
);
document.addEventListener(
"pointerdown",
(ev) => {
if (!serviceEnabled || !siteProtectionEnabled) return;
const path = ev.composedPath?.() || [];
let candidate = null;
for (const node of path) {
candidate = resolveCandidateInput(node);
if (candidate) break;
}
if (!candidate) {
candidate = resolveCandidateInput(ev.target);
}
if (!candidate) return;
attach(candidate);
setActiveEl(candidate);
},
true,
);
// ---------------- main attachment ----------------
const attached = new WeakSet();
const MUTATION_INIT_DEBOUNCE_MS = 400;
let initRunning = false;
let initQueued = false;
let mutationInitTimer = null;
const TARGET_SELECTORS = [
"textarea",
"input[type='text']",
"input[type='search']",
"input[type='email']",
"input[type='url']",
"input[type='tel']",
"input:not([type])",
"[contenteditable='true']",
"[contenteditable='plaintext-only']",
"[role='textbox']",
"[aria-multiline='true']",
".ProseMirror",
".ql-editor",
"[data-lexical-editor='true']",
"[data-slate-editor='true']",
"[data-testid*='prompt']",
"[data-testid*='composer']",
"[aria-label*='prompt' i]",
"[aria-label*='message' i]",
"[placeholder*='ask' i]",
"[placeholder*='message' i]",
"[placeholder*='prompt' i]",
].join(", ");
function findTargets() {
const targets = [];
const seen = new Set();
for (const el of document.querySelectorAll(TARGET_SELECTORS)) {
const candidate = resolveCandidateInput(el);
if (!candidate || !isVisible(candidate)) continue;
if (seen.has(candidate)) continue;
// Skip Google AI Search chat elements
if (isGoogleAISearch(candidate)) continue;
// Skip Meta AI elements
if (isMetaAI(candidate)) continue;
// Skip DeepSeek elements
if (isDeepSeek(candidate)) continue;
seen.add(candidate);
targets.push(candidate);
}
return targets;
}
async function runInitCycle() {
if (initRunning) {
initQueued = true;
return;
}
initRunning = true;
try {
await init();
} catch (err) {
console.warn("[Redactosaurus] init failed:", err);
} finally {
initRunning = false;
if (initQueued) {
initQueued = false;
void runInitCycle();
}
}
}
function requestInit() {
void runInitCycle();
}
function requestInitFromMutation() {
clearTimeout(mutationInitTimer);
mutationInitTimer = setTimeout(() => {
mutationInitTimer = null;
requestInit();
}, MUTATION_INIT_DEBOUNCE_MS);
}
async function refreshOverlayFor(el) {
// Check global service state first
if (!serviceEnabled) {
removeOverlay(el);
updateBulkActionsPanel();
return;
}
const s = await getSiteSettings();
bulkActionsAllowedForSite = s.source === "allowlist";
if (!s.enabled) {
removeOverlay(el);
updateBulkActionsPanel();
return;
}
if (activeEl && el !== activeEl) {
updateBulkActionsPanel();
return;
}
const obj = ensureOverlay(el);
const text = readText(el);
const snapshot = getSnapshot(el);
const entities = snapshot?.entities || [];
const ignored = getIgnoreSet(el);
renderUnderlineOverlay(text, entities, obj.overlay, ignored);
obj.syncScroll();
// Always rebind events with fresh entities to handle text edits
bindOverlayEvents(obj.overlay, el, entities, ignored);
updateBulkActionsPanel();
}
async function clearDetectionsFor(el) {
if (!el) return;
const text = readText(el);
setSnapshot(el, { text, entities: [] });
await refreshOverlayFor(el);
updateBulkActionsPanel();
}
function attach(el) {
if (attached.has(el)) return;
if (!siteProtectionEnabled) return;
// Skip Google AI Search chat elements
if (isGoogleAISearch(el)) return;
// Skip Meta AI elements
if (isMetaAI(el)) return;
// Skip DeepSeek elements
if (isDeepSeek(el)) return;
attached.add(el);
attachedElements.add(el); // Track for cleanup
el.addEventListener("focus", () => setActiveEl(el), true);
let lastDetectedText = "";
let detectTimer = null;
let nextInputForceDetect = false;
let detectRevision = 0;
function scheduleClearIfEmpty() {
setTimeout(() => {
const text = readText(el);
if (text.trim().length !== 0) return;
detectRevision++;
clearTimeout(detectTimer);
lastDetectedText = "";
void clearDetectionsFor(el);
}, 0);
}
async function queueDetection(forceDetect = false) {
const revision = ++detectRevision;
if (applying) return;
// Check global service state
if (!serviceEnabled) {
removeOverlay(el);
return;
}
const s = await getSiteSettings();
bulkActionsAllowedForSite = s.source === "allowlist";
if (!s.enabled) {
removeOverlay(el);
return;
}
const text = readText(el);
await clearDetectionsFor(el);
clearTimeout(detectTimer);
if (text.trim().length === 0) {
lastDetectedText = "";
return;
}
detectTimer = setTimeout(async () => {
if (revision !== detectRevision) return;
const latestText = readText(el);
if (latestText.trim().length === 0) {
if (revision !== detectRevision) return;
lastDetectedText = "";
await clearDetectionsFor(el);
return;
}
// Skip detection if text hasn't changed
if (!forceDetect && latestText === lastDetectedText) return;
lastDetectedText = latestText;
const resp = await requestDetect(latestText);
if (revision !== detectRevision) return;
if (!resp?.ok) return;
const snapshot = { text: latestText, entities: resp.result?.entities || [] };
setSnapshot(el, snapshot);
await refreshOverlayFor(el);
updateBulkActionsPanel();
}, forceDetect ? 120 : 500);
}
el.addEventListener("beforeinput", (ev) => {
const inputType = ev?.inputType || "";
if (inputType === "insertFromPaste" || inputType === "insertFromDrop") {
nextInputForceDetect = true;
}
if (inputType.startsWith("delete") || inputType === "deleteByCut") {
scheduleClearIfEmpty();
}
});
el.addEventListener("paste", () => {
nextInputForceDetect = true;
setTimeout(() => {
void queueDetection(true);
}, 0);
});
el.addEventListener("drop", () => {
nextInputForceDetect = true;
setTimeout(() => {
void queueDetection(true);
}, 0);
});
el.addEventListener("cut", () => {
scheduleClearIfEmpty();
});
el.addEventListener("input", () => {
const forceDetect = nextInputForceDetect;
nextInputForceDetect = false;
void queueDetection(forceDetect);
});
}
async function init() {
const s = await getSiteSettings();
siteProtectionEnabled = !!s.enabled;
bulkActionsAllowedForSite = s.source === "allowlist";
if (!s.enabled) {
for (const el of attachedElements) {
removeOverlay(el);
}
updateBulkActionsPanel();
return;
}
const targets = findTargets();
for (const el of targets) attach(el);
const focused = resolveCandidateInput(document.activeElement);
if (focused && isVisible(focused)) {
attach(focused);
setActiveEl(focused);
}
updateBulkActionsPanel();
}
chrome.runtime.onMessage.addListener((msg) => {
if (msg?.type === "PII_SITE_SETTINGS_UPDATED") {
requestInit();
}
if (msg?.type === "SERVICE_STATE_CHANGED") {
serviceEnabled = msg.enabled;
if (!serviceEnabled) {
// Remove all overlays when service is disabled
for (const el of attachedElements) {
removeOverlay(el);
}
// Also hide any open tooltips
hideGlobalTooltip();
updateBulkActionsPanel();
} else {
// Re-initialize when service is enabled
requestInit();
}
}
});
const obs = new MutationObserver(() => {
if (!serviceEnabled || !siteProtectionEnabled) return;
requestInitFromMutation();
});
obs.observe(document.documentElement, { childList: true, subtree: true });
window.addEventListener("resize", scheduleBulkActionsPanelUpdate, {
passive: true,
});
requestInit();