Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
3765 lines (3348 loc) · 170 KB
/
Copy pathcontent.js
File metadata and controls
3765 lines (3348 loc) · 170 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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2026 John Kost
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
"use strict";
// ReMixr Injection Versioning
window.REMIXR_VERSION = (window.REMIXR_VERSION || 0) + 1;
const myVersion = window.REMIXR_VERSION;
// Lifecycle: Cleanup previous instances if they left a cleanup hook
if (window.REMIXR_CLEANUP) {
window.REMIXR_CLEANUP();
}
console.log(`[ReMixr] Content Script Injection v${myVersion} starting...`);
// ReMixr Analysis Content Script
// Handles interactive inspection of the target page
// Using var for top-level to allow extension re-injection without SyntaxErrors
var inspectorActive = window.inspectorActive || false;
var godModeActive = window.godModeActive || false;
var gravityActive = window.gravityActive || false;
var xrayActive = window.xrayActive || false;
var heatmapActive = window.heatmapActive || false;
var ghostActive = window.ghostActive || false;
var overlay = window.overlay || document.getElementById('remixr-inspector-overlay');
var lastHighlighted = window.lastHighlighted || null;
var heatmapCanvas = window.heatmapCanvas || null;
var gravityInterval = window.gravityInterval || null;
var physicsElements = window.physicsElements || [];
var mouseTrace = window.mouseTrace || [];
var godModeStyle = window.godModeStyle || null;
var sessionEvents = window.sessionEvents || [];
const sanitizeForTransport = (obj, seen = new WeakSet()) => {
if (typeof obj === 'function') return '[Function]';
if (obj === null || typeof obj !== 'object') return obj;
try { if (seen.has(obj)) return '[Circular Reference]'; } catch(e) { return '[Unserializable]'; }
// Skip DOM nodes - very common cause of serialization errors
if (typeof Node !== 'undefined' && obj instanceof Node) {
return `[DOM Node: ${obj.nodeName}${obj.id ? '#' + obj.id : ''}${obj.className ? '.' + obj.className.split(' ')[0] : ''}]`;
}
// Handle Arrays
if (Array.isArray(obj)) {
seen.add(obj);
return obj.map(item => sanitizeForTransport(item, seen));
}
// Handle Objects
seen.add(obj);
const result = {};
for (const [key, value] of Object.entries(obj)) {
// Skip large/private internal properties — except _meta, which
// carries layer accounting consumed by validation cards.
if (key.startsWith('_') && key !== '_meta') continue;
result[key] = sanitizeForTransport(value, seen);
}
return result;
};
const MAX_TRACE = 100;
// Initialize Overlay (Diagnostic HUD)
function createOverlay() {
if (overlay) return;
overlay = document.createElement('div');
overlay.id = 'remixr-inspector-overlay';
// Base styles (Programmatic for CSP safety)
Object.assign(overlay.style, {
position: 'fixed',
top: '20px',
right: '20px',
background: 'rgba(15, 23, 42, 0.98)',
color: 'white',
padding: '18px',
borderRadius: '12px',
fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
fontSize: '11px',
zIndex: '999999',
pointerEvents: 'none',
boxShadow: '0 15px 40px rgba(0,0,0,0.4)',
border: '1px solid rgba(255,255,255,0.15)',
width: '300px',
display: 'none',
backdropFilter: 'blur(20px)',
transition: 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)',
transform: 'translateY(-20px)',
opacity: '0'
});
const idle = document.createElement('div');
idle.id = 'remixr-hud-idle';
idle.style.textAlign = 'center';
idle.style.padding = '20px 0';
idle.innerHTML = `<div style="font-size:24px; margin-bottom:10px;">🔮</div><div>READY TO SCAN</div><div style="font-size:9px; opacity:0.6; margin-top:8px;">Hover over any element...</div>`;
overlay.appendChild(idle);
document.body.appendChild(overlay);
}
// Generate unique CSS selector (Enhanced for Robustness)
function getSelector(el) {
if (!el || el === document) return 'html';
if (el.id) return '#' + el.id;
// Try stable attributes first
const stableAttrs = ['data-testid', 'data-qa', 'aria-label', 'name', 'title'];
for (const attr of stableAttrs) {
const val = el.getAttribute(attr);
if (val) return `${el.tagName.toLowerCase()}[${attr}="${val}"]`;
}
// Try classes (filtering out common dynamic utility classes)
const classAttr = el.getAttribute('class');
if (classAttr && typeof classAttr === 'string') {
const classes = classAttr.split(' ').filter(c => {
const isDynamic = /^(css-|emotion-|react-|v-|_|js-|hover:|focus:|active:|dark:|lg:|sm:|md:|xl:)/i.test(c);
return c.trim() && !isDynamic;
});
if (classes.length > 0) return '.' + classes.join('.');
}
// Fallback to hierarchical path
let tagName = el.tagName.toLowerCase();
let siblingIndex = 1;
let sibling = el;
while (sibling = sibling.previousElementSibling) {
if (sibling.tagName.toLowerCase() === tagName) siblingIndex++;
}
const path = (siblingIndex > 1) ? `${tagName}:nth-of-type(${siblingIndex})` : tagName;
if (el.parentElement && el.parentElement !== document.body) {
return getSelector(el.parentElement) + ' > ' + path;
}
return path;
}
// Highlight element
// HUD text is page-derived (selectors, classes): escape before innerHTML
// so a hostile class name cannot break out of the overlay markup.
const escHud = (v) => String(v == null ? '' : v).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
function highlightElement(e) {
if (!inspectorActive) return;
const target = e.target;
if (target === overlay || target === lastHighlighted) return;
// Remove old highlight
if (lastHighlighted) {
lastHighlighted.style.outline = lastHighlighted.dataset.remixrOutline || '';
lastHighlighted.style.cursor = lastHighlighted.dataset.remixrCursor || '';
lastHighlighted.style.outlineOffset = lastHighlighted.dataset.remixrOutlineOffset || '';
}
// Apply new highlight
target.dataset.remixrOutline = target.style.outline;
target.dataset.remixrCursor = target.style.cursor;
target.dataset.remixrOutlineOffset = target.style.outlineOffset;
target.style.outline = '2px dashed #6366f1';
target.style.outlineOffset = '2px';
target.style.cursor = 'crosshair';
lastHighlighted = target;
// Update HUD
const rect = target.getBoundingClientRect();
const selector = getSelector(target);
const style = window.getComputedStyle(target);
const hexColor = (c) => (typeof CoreUtils !== 'undefined' && CoreUtils.rgbToHex) ? CoreUtils.rgbToHex(c) : c;
overlay.style.display = 'block';
overlay.style.opacity = '1';
overlay.style.transform = 'translateY(0)';
// Clear and rebuild for maximum stability (prevents broken innerHTML states)
overlay.innerHTML = '';
const content = document.createElement('div');
content.innerHTML = `
<div style="background:linear-gradient(135deg, #6366f1 0%, #a855f7 100%); padding:6px 12px; border-radius:8px 8px 0 0; margin:-18px -18px 15px -18px; font-size:10px; font-weight:bold; letter-spacing:1.5px; color:#fff; display:flex; justify-content:space-between; align-items:center;">
<span>REMIX: ON-SITE DIAGNOSTICS</span>
<span style="background:rgba(0,0,0,0.2); padding:2px 6px; border-radius:4px;">${target.tagName.toUpperCase()}</span>
</div>
<div style="margin-bottom: 12px;">
<div style="font-size:9px; color:#94a3b8; text-transform:uppercase; margin-bottom:4px; font-weight:700;">Selector Path</div>
<div style="font-family:monospace; font-size:10px; color:#60a5fa; word-break:break-all; background:rgba(0,0,0,0.3); padding:6px; border-radius:4px; border:1px solid rgba(255,255,255,0.05);">${escHud(selector)}</div>
</div>
<div style="display:grid; grid-template-columns: 1fr 1fr; gap:10px; border-top:1px solid rgba(255,255,255,0.05); padding-top:12px;">
<div>
<div style="font-size:8px; color:#94a3b8; text-transform:uppercase;">Geometry content</div>
<div style="color:#fff; font-size:11px; font-weight:bold;">${Math.round(rect.width)} px</div>
</div>
<div>
<div style="font-size:8px; color:#94a3b8; text-transform:uppercase;">Height</div>
<div style="color:#fff; font-size:11px; font-weight:bold;">${Math.round(rect.height)} px</div>
</div>
<div>
<div style="font-size:8px; color:#94a3b8; text-transform:uppercase;">Text</div>
<div style="color:#fff; font-size:10px; display:flex; align-items:center; gap:4px;">
<span style="width:7px; height:7px; background:${escHud(style.color)}; border-radius:50%;"></span> ${escHud(hexColor(style.color))}
</div>
</div>
<div>
<div style="font-size:8px; color:#94a3b8; text-transform:uppercase;">Fill</div>
<div style="color:#fff; font-size:10px; display:flex; align-items:center; gap:4px;">
<span style="width:7px; height:7px; background:${escHud(style.backgroundColor)}; border-radius:50%;"></span> ${escHud(hexColor(style.backgroundColor))}
</div>
</div>
</div>
<div style="font-size:9px; color:#a855f7; border-top: 1px solid rgba(255,255,255,0.05); margin-top:12px; padding-top:10px; font-weight:bold; letter-spacing:0.5px; text-align:center;">
🖱️ CLICK TO CAPTURE
</div>
`;
overlay.appendChild(content);
}
// Click to copy
// Unified Element Selection Handler
function handleClick(e) {
if (!inspectorActive) return;
e.preventDefault();
e.stopPropagation();
const target = e.target;
const selector = getSelector(target);
const styles = window.getComputedStyle(target);
const cssVars = typeof getCssVariables === 'function' ? getCssVariables(target) : {};
const styleData = {
selector: selector,
tagName: target.tagName.toLowerCase(),
attributes: Array.from(target.attributes).map(attr => ({ name: attr.name, value: attr.value })),
variables: cssVars,
accessibility: {
role: target.getAttribute('role') || target.tagName.toLowerCase(),
label: target.getAttribute('aria-label') || target.innerText.slice(0, 30),
hidden: target.getAttribute('aria-hidden') === 'true',
tabIndex: target.tabIndex
},
context: {
parent: target.parentElement?.tagName.toLowerCase() || 'none',
siblings: target.parentElement?.children.length || 0,
childCount: target.children.length,
depth: getDepth(target)
},
styles: {
color: styles.color,
backgroundColor: styles.backgroundColor,
fontSize: styles.fontSize,
fontWeight: styles.fontWeight,
fontFamily: styles.fontFamily,
padding: styles.padding,
margin: styles.margin,
border: styles.border,
borderRadius: styles.borderRadius,
display: styles.display,
position: styles.position,
zIndex: styles.zIndex,
top: styles.top,
left: styles.left,
width: styles.width,
height: styles.height,
opacity: styles.opacity,
boxShadow: styles.boxShadow,
visibility: styles.visibility,
cursor: styles.cursor,
flexDirection: styles.flexDirection,
justifyContent: styles.justifyContent,
alignItems: styles.alignItems,
gap: styles.gap
}
};
chrome.runtime.sendMessage({
action: 'elementSelected',
data: styleData
});
// Provide visual feedback and copy selector
navigator.clipboard.writeText(selector).then(() => {
const hud = document.getElementById('remixr-inspector-overlay');
if (hud) {
const originalContent = hud.innerHTML;
hud.innerHTML = `<div style="color:#4ade80; text-align:center; padding: 10px; font-weight:bold;">✨ ELEMENT TRACE CAPTURED</div>`;
setTimeout(() => {
hud.innerHTML = originalContent;
}, 1000);
}
});
}
// Toggle Inspector
function toggleInspector(active) {
inspectorActive = active;
window.inspectorActive = active;
createOverlay();
if (active) {
document.addEventListener('mouseover', highlightElement);
document.addEventListener('click', handleClick, true);
overlay.style.display = 'none'; // Hidden until hover
} else {
document.removeEventListener('mouseover', highlightElement);
document.removeEventListener('click', handleClick, true);
if (overlay) overlay.style.display = 'none';
if (lastHighlighted) {
lastHighlighted.style.outline = lastHighlighted.dataset.remixrOutline || '';
lastHighlighted.style.cursor = lastHighlighted.dataset.remixrCursor || '';
lastHighlighted.style.outlineOffset = lastHighlighted.dataset.remixrOutlineOffset || '';
lastHighlighted = null;
}
}
}
// Register Cleanup Hook
window.REMIXR_CLEANUP = () => {
log(`Cleaning up context v${myVersion}...`);
document.removeEventListener('mouseover', highlightElement);
document.removeEventListener('click', handleClick, true);
if (window.remixrEditHandler) document.removeEventListener('click', window.remixrEditHandler, true);
if (window.remixrZapHandler) document.removeEventListener('click', window.remixrZapHandler, true);
// Remove old UI elements if they shouldn't persist
// We keep 'overlay' IDed elements but we can reset them
const oldOverlay = document.getElementById('remixr-inspector-overlay');
if (oldOverlay) oldOverlay.innerHTML = '';
};
// --- Message Dispatcher (Robust re-injection & version locking) ---
window.messageHandlers = window.messageHandlers || {};
Object.assign(window.messageHandlers, {
'ping': () => ({ pong: true, version: myVersion, inspectorActive, godModeActive }),
'extractSiteContext': generateLLMSiteContext,
'toggleInspector': (req) => {
const newState = req.state !== undefined ? req.state : !inspectorActive;
toggleInspector(newState);
return { active: newState };
},
'analyzePsyche': () => analyzePsychologicalPatterns(),
'analyzeArchetype': analyzeBrandArchetype,
'analyzeSoul': analyzeSoul,
'analyzeShadow': analyzeShadow,
'analyzeRhetoric': () => analyzeRhetoric(),
'analyzeEmotion': () => analyzeEmotionalDesign(),
'analyzeStrategy': () => analyzeStrategicArchitecture(),
// Inspector Kernels (Consolidated from popup.js)
'analyzeStructure': () => InspectorKernels.analyzeStructure(),
'analyzePalette': () => InspectorKernels.analyzePalette(),
'analyzeAssets': () => InspectorKernels.analyzeAssets(),
'analyzeFonts': () => InspectorKernels.analyzeFonts(),
'analyzeStorage': () => InspectorKernels.analyzeStorage(),
'analyzePerf': () => InspectorKernels.analyzePerf(),
'analyzeStack': () => InspectorKernels.analyzeStack(),
'analyzeDomTree': () => InspectorKernels.analyzeDomTree(),
'analyzeA11y': () => InspectorKernels.analyzeA11y(),
'analyzeSEO': () => InspectorKernels.analyzeSEO(),
'analyzeSequence': () => InspectorKernels.analyzeSequence(),
'analyzeWorkers': async () => {
if ('serviceWorker' in navigator) {
try {
const regs = await navigator.serviceWorker.getRegistrations();
return { serviceWorkers: regs.map(r => r.active ? r.active.scriptURL : 'Registered') };
} catch(e) { return { Math, error: e.message, serviceWorkers: [] }; }
}
return { serviceWorkers: [] };
},
'analyzeCode': () => {
const scripts = document.querySelectorAll('script');
const inline = Array.from(scripts).filter(s => !s.src).length;
const external = Array.from(scripts).filter(s => s.src).length;
return { scripts: { inline, external }, totalElements: document.querySelectorAll('*').length };
},
'analyzeNet': extractAPISurface,
'visualizeStrategy': (req) => { visualizeStrategicMapping(); return { success: true }; },
'analyzeOmniscience': async () => {
return {
strategy: analyzeStrategicArchitecture(),
psyche: analyzePsychologicalPatterns(),
specimen: analyzeSpecimen(),
soul: analyzeSoul(),
shadow: analyzeShadow(),
archetype: analyzeBrandArchetype(),
rhetoric: analyzeRhetoric(),
emotion: analyzeEmotionalDesign(),
objectModel: extractCompleteObjectModel(),
frameworkState: extractFrameworkState(),
apiSurface: extractAPISurface(),
domain: window.location.hostname,
url: window.location.href,
timestamp: new Date().toISOString()
};
},
'startSessionRecording': () => {
flowRecording = true;
window.flowRecording = true;
sessionEvents = [];
window.sessionEvents = [];
document.addEventListener('click', recordEvent, true);
document.addEventListener('input', recordEvent, true);
console.log('[ReMixr] Session Recording started...');
return { active: true };
},
'stopSessionRecording': () => {
flowRecording = false;
window.flowRecording = false;
document.removeEventListener('click', recordEvent, true);
document.removeEventListener('input', recordEvent, true);
console.log('[ReMixr] Session Recording stopped. Events:', sessionEvents.length);
return { events: sessionEvents };
},
'toggleXRay': () => ({ active: toggleXRayMode() }),
'toggleHeatmap': () => ({ active: toggleHeatmap() }),
'analyzeSpecimen': analyzeSpecimen,
'extractCompleteModel': extractCompleteObjectModel,
'extractFrameworkState': extractFrameworkState,
'extractAPISurface': extractAPISurface,
'extractSiteDNA': generateSiteDNA,
'generateLLMContext': (req) => {
const dna = generateSiteDNA(req.layers);
const markdown = generateLLMSiteContext(dna);
return { markdown, dna, wordCount: markdown.split(/\s+/).length };
},
'toggleContrastMap': () => ({ active: toggleContrastMap() }),
'toggleEventSniffer': () => ({ active: toggleEventSniffer() }),
'applyReality': (req) => ({ success: true, style: applyReality(req.style) }),
'toggleGodMode': () => ({ active: toggleGodMode() }),
'toggleWireframe': () => {
document.body.classList.toggle('remixr-wireframe');
if (!document.getElementById('remixr-wireframe-style')) {
const style = document.createElement('style');
style.id = 'remixr-wireframe-style';
style.textContent = `
.remixr-wireframe * { background: none !important; color: #0f0 !important; border: 1px solid #0f0 !important; box-shadow: none !important; }
.remixr-wireframe img, .remixr-wireframe video { display: none !important; }
.remixr-wireframe { background-color: #000 !important; }
`;
document.head.appendChild(style);
return { status: 'active' };
} else {
document.getElementById('remixr-wireframe-style').remove();
return { status: 'inactive' };
}
},
'toggleImages': () => {
const hide = document.body.getAttribute('data-remixr-images') !== 'hidden';
document.querySelectorAll('img').forEach(img => img.style.opacity = hide ? '0' : '1');
if (hide) document.body.setAttribute('data-remixr-images', 'hidden');
else document.body.removeAttribute('data-remixr-images');
return { status: hide ? 'hidden' : 'visible' };
},
'enableInputs': () => {
const els = document.querySelectorAll('input[disabled], button[disabled], textarea[disabled]');
els.forEach(el => { el.removeAttribute('disabled'); el.style.border = '2px solid #4ade80'; });
return { count: els.length };
},
'showPasswords': () => {
const pwds = document.querySelectorAll('input[type="password"]');
pwds.forEach(el => { el.type = 'text'; el.style.border = '2px solid #ef4444'; });
return { count: pwds.length };
},
'killStickies': () => {
const els = document.querySelectorAll('*');
let count = 0;
els.forEach(el => {
const s = window.getComputedStyle(el);
if (s.position === 'fixed' || s.position === 'sticky') { el.style.position = 'static'; count++; }
});
return { count };
},
'toggleEditMode': () => {
if (window.remixrEditHandler) {
document.removeEventListener('click', window.remixrEditHandler, true);
window.remixrEditHandler = null;
document.body.style.cursor = 'default';
return { active: false };
} else {
window.remixrEditHandler = (e) => { e.preventDefault(); e.target.contentEditable = true; e.target.focus(); };
document.addEventListener('click', window.remixrEditHandler, true);
document.body.style.cursor = 'cell';
return { active: true };
}
},
'toggleGravity': () => ({ active: toggleGravityMode() }),
'toggleNeural': () => ({ active: toggleNeuralLink() }),
'toggleGhost': () => ({ active: toggleGhostTrace() }),
'zapElement': () => {
if (window.remixrZapHandler) {
document.removeEventListener('click', window.remixrZapHandler, true);
window.remixrZapHandler = null;
document.body.style.cursor = 'default';
return { active: false };
} else {
window.remixrZapHandler = (e) => { e.preventDefault(); e.stopPropagation(); e.target.remove(); };
document.addEventListener('click', window.remixrZapHandler, true);
document.body.style.cursor = 'crosshair';
return { active: true };
}
},
'updateStyle': (req) => {
const el = document.querySelector(req.selector);
if (el) { el.style[req.property] = req.value; return { success: true }; }
return { success: false, error: 'Element lost' };
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// Version Lock: Only the most recently injected script responds
if (myVersion !== window.REMIXR_VERSION) {
console.log(`[ReMixr] Context v${myVersion} ignoring message - newer context v${window.REMIXR_VERSION} exists.`);
return false;
}
const handler = window.messageHandlers[request.action];
if (handler) {
try {
const rawResult = handler(request);
const finalizeResult = (res) => {
const sanitized = sanitizeForTransport(res);
const size = JSON.stringify(sanitized).length;
if (size > 500000) {
console.warn(`[ReMixr] Large payload detected for [${request.action}]: ${(size / 1024 / 1024).toFixed(2)}MB`);
}
sendResponse(sanitized);
};
if (rawResult instanceof Promise) {
rawResult.then(finalizeResult).catch(err => {
console.error(`[ReMixr] Handler Async Error [${request.action}]:`, err);
sendResponse({ error: err.message });
});
return true;
}
finalizeResult(rawResult);
} catch (err) {
console.error(`[ReMixr] Handler Sync Error [${request.action}]:`, err);
sendResponse({ error: err.message });
}
} else {
console.warn(`[ReMixr] No handler for action: ${request.action}`);
sendResponse({ error: 'Unknown action' });
}
});
console.log(`[ReMixr] Content script v${myVersion} fully initialized.`);
// ============================================
// BRAND SPECIMEN ANALYSIS
// ============================================
function analyzeSpecimen() {
const specimen = {
fonts: [],
colors: {
brand: [],
text: [],
bg: []
},
buttons: [],
spacing: new Set()
};
// Fonts
const fontSet = new Set();
document.querySelectorAll('h1, h2, h3, p, span, a, button').forEach(el => {
const style = window.getComputedStyle(el);
const font = style.fontFamily.split(',')[0].replace(/['"]/g, '').trim();
if (font) fontSet.add(font);
// Spacing
specimen.spacing.add(style.paddingTop);
specimen.spacing.add(style.gap);
});
specimen.fonts = Array.from(fontSet).slice(0, 10);
specimen.spacing = Array.from(specimen.spacing).filter(s => s !== '0px' && s !== 'normal').slice(0, 10);
// Colors
const colors = extractDominantColors();
specimen.colors.brand = colors.slice(0, 12);
// UI Specimens
const mainButtons = Array.from(document.querySelectorAll('button, .btn, .button')).slice(0, 5);
specimen.buttons = mainButtons.map(btn => {
const style = window.getComputedStyle(btn);
return {
text: btn.innerText.trim().slice(0, 20) || 'Action',
bg: style.backgroundColor,
color: style.color,
radius: style.borderRadius,
padding: style.padding,
font: style.fontFamily.split(',')[0]
};
});
return specimen;
}
// ============================================
// VISUAL WEALTH: 3D X-RAY (DOM EXPLODER)
// ============================================
function toggleXRayMode() {
xrayActive = !xrayActive;
window.xrayActive = xrayActive;
const body = document.body;
if (xrayActive) {
body.style.transition = 'transform 1s ease-in-out';
body.style.transformStyle = 'preserve-3d';
body.style.perspective = '2000px';
body.style.transform = 'rotateY(20deg) rotateX(10deg) scale(0.8)';
const all = document.querySelectorAll('*');
all.forEach((el, i) => {
if (el.tagName === 'BODY' || el.tagName === 'HTML' || el.id?.startsWith('remixr')) return;
const depth = getDepth(el) * 20;
el.style.transition = 'transform 0.5s ease-out';
el.style.transform = `translateZ(${depth}px)`;
el.style.boxShadow = '0 0 10px rgba(99, 102, 241, 0.2)';
el.style.backgroundColor = 'rgba(255, 255, 255, 0.05)';
});
} else {
body.style.transform = '';
const all = document.querySelectorAll('*');
all.forEach(el => {
el.style.transform = '';
el.style.boxShadow = '';
el.style.backgroundColor = '';
});
}
return xrayActive;
}
function getDepth(el) {
let d = 0;
while (el.parentElement) {
el = el.parentElement;
d++;
}
return d;
}
// ============================================
// VISUAL WEALTH: ATTENTION HEATMAP
// ============================================
function toggleHeatmap() {
heatmapActive = !heatmapActive;
window.heatmapActive = heatmapActive;
if (heatmapActive) {
heatmapCanvas = document.createElement('canvas');
heatmapCanvas.id = 'remixr-heatmap';
heatmapCanvas.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 999997;
opacity: 0.6;
mix-blend-mode: multiply;
`;
document.body.appendChild(heatmapCanvas);
renderHeatmap();
} else {
if (heatmapCanvas) heatmapCanvas.remove();
}
return heatmapActive;
}
function renderHeatmap() {
if (!heatmapCanvas) return;
const ctx = heatmapCanvas.getContext('2d');
const w = window.innerWidth;
const h = window.innerHeight;
heatmapCanvas.width = w;
heatmapCanvas.height = h;
const elements = Array.from(document.querySelectorAll('h1, h2, h3, button, img, a, [role="button"]'));
// Draw base
ctx.fillStyle = 'rgba(0, 50, 100, 0.1)';
ctx.fillRect(0, 0, w, h);
elements.forEach(el => {
const rect = el.getBoundingClientRect();
if (rect.top > h || rect.bottom < 0) return;
const weight = (rect.width * rect.height) / 1000 + 20;
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, weight * 3);
gradient.addColorStop(0, 'rgba(255, 0, 0, 0.5)');
gradient.addColorStop(0.5, 'rgba(255, 255, 0, 0.2)');
gradient.addColorStop(1, 'transparent');
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(centerX, centerY, weight * 3, 0, Math.PI * 2);
ctx.fill();
});
}
// ============================================
// ENHANCED ELEMENT DATA (CSS VARIABLES)
// ============================================
function getCssVariables(el) {
const vars = {};
const styles = window.getComputedStyle(el);
for (const prop of styles) {
if (prop.startsWith('--')) {
vars[prop] = styles.getPropertyValue(prop);
}
}
// Also check parent variables that might be inherited
let parent = el.parentElement;
while (parent && Object.keys(vars).length < 20) {
const pStyles = window.getComputedStyle(parent);
for (const prop of pStyles) {
if (prop.startsWith('--') && !vars[prop]) {
vars[prop] = pStyles.getPropertyValue(prop);
}
}
parent = parent.parentElement;
}
return vars;
}
// ============================================
// VISUAL WEALTH: GRAVITY MODE (DOM PHYSICS)
// ============================================
function toggleGravityMode() {
gravityActive = !gravityActive;
window.gravityActive = gravityActive;
if (gravityActive) {
const all = document.querySelectorAll('div, p, span, h1, h2, h3, button, img, a');
physicsElements = Array.from(all).filter(el => {
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0 &&
window.getComputedStyle(el).position !== 'fixed' &&
!el.id?.startsWith('remixr');
}).map(el => {
const rect = el.getBoundingClientRect();
el.dataset.remixrPrev = JSON.stringify({ position: el.style.position, top: el.style.top, left: el.style.left, width: el.style.width, height: el.style.height, margin: el.style.margin, zIndex: el.style.zIndex });
el.style.position = 'fixed';
el.style.top = rect.top + 'px';
el.style.left = rect.left + 'px';
el.style.width = rect.width + 'px';
el.style.height = rect.height + 'px';
el.style.margin = '0';
el.style.zIndex = '999990';
return {
el,
y: rect.top,
x: rect.left,
vy: 0,
vx: (Math.random() - 0.5) * 5,
w: rect.width,
h: rect.height
};
});
const gravity = 0.5;
const friction = 0.98;
const bounce = 0.7;
gravityInterval = setInterval(() => {
const floor = window.innerHeight;
const wall = window.innerWidth;
physicsElements.forEach(p => {
p.vy += gravity;
p.y += p.vy;
p.x += p.vx;
if (p.y + p.h > floor) {
p.y = floor - p.h;
p.vy *= -bounce;
p.vx *= friction;
}
if (p.x + p.w > wall || p.x < 0) {
p.vx *= -bounce;
}
p.el.style.top = p.y + 'px';
p.el.style.left = p.x + 'px';
});
}, 16);
} else {
clearInterval(gravityInterval);
physicsElements.forEach(p => {
try {
const prev = JSON.parse(p.el.dataset.remixrPrev || '{}');
['position', 'top', 'left', 'width', 'height', 'margin', 'zIndex'].forEach(k => { p.el.style[k] = prev[k] || ''; });
delete p.el.dataset.remixrPrev;
} catch (e) { p.el.style.position = ''; }
/* top restored from dataset above */
/* left restored from dataset above */
/* width restored from dataset above */
/* height restored from dataset above */
});
physicsElements = [];
}
return gravityActive;
}
// ============================================
// VISUAL WEALTH: NEURAL LINK (LOGIC CONNECTIONS)
// ============================================
let neuralActive = false;
let neuralCanvas = null;
function toggleNeuralLink() {
neuralActive = !neuralActive;
if (neuralActive) {
neuralCanvas = document.createElement('canvas');
neuralCanvas.id = 'remixr-neural-canvas';
neuralCanvas.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 999995;
opacity: 0.8;
`;
document.body.appendChild(neuralCanvas);
renderNeuralLink();
window.addEventListener('resize', renderNeuralLink);
} else {
if (neuralCanvas) neuralCanvas.remove();
window.removeEventListener('resize', renderNeuralLink);
}
return neuralActive;
}
function renderNeuralLink() {
if (!neuralCanvas) return;
const ctx = neuralCanvas.getContext('2d');
const w = window.innerWidth;
const h = window.innerHeight;
neuralCanvas.width = w;
neuralCanvas.height = h;
ctx.strokeStyle = '#6366f1';
ctx.lineWidth = 1;
ctx.shadowBlur = 5;
ctx.shadowColor = '#6366f1';
// Link interactive elements to their conceptual targets
const anchors = document.querySelectorAll('a[href^="#"]');
anchors.forEach(a => {
const targetId = a.getAttribute('href').substring(1);
const target = document.getElementById(targetId);
if (target) {
drawLine(ctx, a, target, '#6366f1');
}
});
// Link labels to inputs
const labels = document.querySelectorAll('label[for]');
labels.forEach(l => {
const target = document.getElementById(l.getAttribute('for'));
if (target) {
drawLine(ctx, l, target, '#4ade80');
}
});
// Link buttons to forms
const buttons = document.querySelectorAll('button[type="submit"], input[type="submit"]');
buttons.forEach(b => {
const form = b.closest('form');
if (form) {
drawLine(ctx, b, form, '#f87171');
}
});
}
function drawLine(ctx, el1, el2, color) {
const r1 = el1.getBoundingClientRect();
const r2 = el2.getBoundingClientRect();
if (r1.width === 0 || r2.width === 0) return;
ctx.beginPath();
ctx.strokeStyle = color;
ctx.moveTo(r1.left + r1.width / 2, r1.top + r1.height / 2);
// Curved line
const cp1x = r1.left + r1.width / 2;
const cp1y = r2.top + r2.height / 2;
ctx.quadraticCurveTo(cp1x, cp1y, r2.left + r2.width / 2, r2.top + r2.height / 2);
ctx.stroke();
// Draw particles along line
const dotPos = (Date.now() / 1000) % 1;
const px = Math.pow(1 - dotPos, 2) * (r1.left + r1.width / 2) + 2 * (1 - dotPos) * dotPos * cp1x + Math.pow(dotPos, 2) * (r2.left + r2.width / 2);
const py = Math.pow(1 - dotPos, 2) * (r1.top + r1.height / 2) + 2 * (1 - dotPos) * dotPos * cp1y + Math.pow(dotPos, 2) * (r2.top + r2.height / 2);
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(px, py, 3, 0, Math.PI * 2);
ctx.fill();
}
// ============================================
// VISUAL WEALTH: GHOST TRACE (INTERACTION REPLAY)
// ============================================
function toggleGhostTrace() {
ghostActive = !ghostActive;
window.ghostActive = ghostActive;
if (ghostActive) {
document.addEventListener('mousemove', recordTrace);
document.addEventListener('click', recordClick);
animateGhost();
} else {
document.removeEventListener('mousemove', recordTrace);
document.removeEventListener('click', recordClick);
}
return ghostActive;
}
function recordTrace(e) {
mouseTrace.push({ x: e.clientX, y: e.clientY, type: 'move', time: Date.now() });
if (mouseTrace.length > MAX_TRACE) mouseTrace.shift();
}
function recordClick(e) {
mouseTrace.push({ x: e.clientX, y: e.clientY, type: 'click', time: Date.now() });
if (mouseTrace.length > MAX_TRACE) mouseTrace.shift();
}
function animateGhost() {
if (!ghostActive) {
const existing = document.querySelectorAll('.remixr-ghost-dot');
existing.forEach(d => d.remove());
return;
}
const existing = document.querySelectorAll('.remixr-ghost-dot');
existing.forEach(d => d.remove());
const now = Date.now();
mouseTrace.forEach((point, i) => {
const age = now - point.time;
if (age > 5000) return; // Only show last 5 seconds
const dot = document.createElement('div');
dot.className = 'remixr-ghost-dot';
dot.style.cssText = `
position: fixed;
top: ${point.y}px;
left: ${point.x}px;
width: ${point.type === 'click' ? '20px' : '4px'}px;
height: ${point.type === 'click' ? '20px' : '4px'}px;
background: ${point.type === 'click' ? '#f87171' : '#6366f1'};
border-radius: 50%;
pointer-events: none;
z-index: 999999;
opacity: ${1 - age / 5000};
transform: translate(-50%, -50%);
box-shadow: 0 0 10px ${point.type === 'click' ? '#f87171' : '#6366f1'};
`;