-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
824 lines (692 loc) · 31.1 KB
/
content.js
File metadata and controls
824 lines (692 loc) · 31.1 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
/**
* Content script for LinkedIn Zip Solver
* Detects when user is on LinkedIn Zip page and injects solution popup
*/
// Zip Solver Extension loaded
// Global mutation observer to avoid creating multiple observers
let arrowMutationObserver = null;
// Extract puzzle data from LinkedIn page
function extractPuzzleFromPage() {
const numberedCells = {};
const walls = [];
// Find all cells in the grid
const cells = document.querySelectorAll('[data-testid^="cell-"]');
// Detect grid size dynamically - calculate from total number of cells (more reliable)
const gridSize = Math.sqrt(cells.length);
console.log('📐 Grid size calculation: Total cells =', cells.length, '→ Grid size =', gridSize);
// Process cells to find walls using geometry-based detection
cells.forEach(cell => {
const cellIdx = parseInt(cell.getAttribute('data-cell-idx'));
const row = Math.floor(cellIdx / gridSize);
const col = cellIdx % gridSize;
// Check if this cell has a number
const numberElement = cell.querySelector('[data-cell-content="true"]');
if (numberElement) {
const number = parseInt(numberElement.textContent.trim());
numberedCells[number] = [row, col];
}
// Check for walls - they have base class '_7b4afabe'
const wallDivs = cell.querySelectorAll('div._7b4afabe');
wallDivs.forEach((wallDiv) => {
const classes = wallDiv.className;
// Check the ::after pseudo-element's border widths to determine wall orientation
const afterStyle = window.getComputedStyle(wallDiv, '::after');
const borderTop = parseFloat(afterStyle.borderTopWidth);
const borderRight = parseFloat(afterStyle.borderRightWidth);
const borderBottom = parseFloat(afterStyle.borderBottomWidth);
const borderLeft = parseFloat(afterStyle.borderLeftWidth);
const maxBorder = Math.max(borderTop, borderRight, borderBottom, borderLeft);
if (maxBorder > 5) {
console.log(` Cell [${row},${col}] borders: top=${borderTop} right=${borderRight} bottom=${borderBottom} left=${borderLeft} classes=${classes}`);
// Vertical walls: only add if RIGHT border is thick
// This prevents duplicates (same wall detected on adjacent cells)
if (borderRight > 5) {
console.log(` ✅ VERTICAL wall at [${row},${col}]`);
walls.push({ type: 'vertical', row, col });
}
// Horizontal walls: only add if BOTTOM border is thick
// This prevents duplicates (same wall detected on adjacent cells)
else if (borderBottom > 5) {
console.log(` ✅ HORIZONTAL wall at [${row},${col}]`);
walls.push({ type: 'horizontal', row, col });
}
// Debug: log if we have top or left borders (might be duplicates)
else if (borderTop > 5) {
console.log(` ⚠️ Top border detected (might be duplicate horizontal from cell above)`);
} else if (borderLeft > 5) {
console.log(` ⚠️ Left border detected (might be duplicate vertical from cell to left)`);
}
}
});
});
const puzzleData = {
numberedCells,
walls,
gridSize
};
// Log extracted puzzle data
console.log('🔍 Extracted Puzzle Data:');
console.log(' Grid Size:', gridSize + 'x' + gridSize);
console.log(' Total Cells:', cells.length);
console.log(' Numbered Cells:', numberedCells);
// Check if all numbered cells are within bounds
for (const [num, [r, c]] of Object.entries(numberedCells)) {
if (r >= gridSize || c >= gridSize) {
console.error(`❌ Cell ${num} at [${r},${c}] is OUT OF BOUNDS for ${gridSize}x${gridSize} grid!`);
}
}
console.log(' Total Walls:', walls.length);
const horizontalWalls = walls.filter(w => w.type === 'horizontal');
const verticalWalls = walls.filter(w => w.type === 'vertical');
console.log(' Horizontal Walls:', horizontalWalls.length);
console.log(' Vertical Walls:', verticalWalls.length);
console.log(' Horizontal wall positions:', horizontalWalls);
console.log(' Vertical wall positions:', verticalWalls);
return puzzleData;
}
// Check if we're on the LinkedIn Zip page
function isZipPage() {
return window.location.href.includes('linkedin.com/games/zip');
}
// Solve the puzzle
function solvePuzzle(puzzleData) {
console.log('🧩 Starting solver with grid size:', puzzleData.gridSize);
const solver = new ZipSolver(puzzleData.gridSize);
// Set numbered cells
console.log('📍 Setting numbered cells...');
for (const [number, [row, col]] of Object.entries(puzzleData.numberedCells)) {
console.log(` Cell ${number} at [${row}, ${col}]`);
solver.setNumberedCell(row, col, parseInt(number));
}
// Add walls if any
console.log('🧱 Adding', puzzleData.walls.length, 'walls...');
for (const wall of puzzleData.walls) {
if (wall.type === 'horizontal') {
// Wall below cell [row, col]
console.log(` Horizontal wall below [${wall.row}, ${wall.col}]`);
solver.addWallHorizontal(wall.row, wall.col);
} else if (wall.type === 'vertical') {
// Wall to the right of cell [row, col]
console.log(` Vertical wall right of [${wall.row}, ${wall.col}]`);
solver.addWallVertical(wall.row, wall.col);
}
}
// Solve and return path
console.log('🔄 Starting solve...');
const result = solver.solve();
console.log('✅ Solve result:', result ? `Found path with ${result.length} steps` : 'No solution found');
return result;
}
// Create floating action button to reopen the panel
function createFAB() {
// Check if FAB already exists
if (document.getElementById('zip-solver-fab')) {
return;
}
const fab = document.createElement('button');
fab.id = 'zip-solver-fab';
fab.className = 'zip-solver-fab';
// Use the icon image
const icon = document.createElement('img');
const iconUrl = chrome.runtime.getURL('icon.png');
icon.src = iconUrl;
icon.alt = 'Show Zip Solution';
icon.style.width = '100%';
icon.style.height = '100%';
icon.style.objectFit = 'contain';
icon.style.borderRadius = '16px';
fab.appendChild(icon);
// Start hidden, will show when panel closes
fab.style.display = 'none';
document.body.appendChild(fab);
fab.addEventListener('click', () => {
fab.style.display = 'none';
showSolution();
});
}
// Create the side panel showing the solution
function createSidePanel(solution, puzzleData) {
// Check if panel already exists
if (document.getElementById('zip-solver-panel')) {
return;
}
// Create side panel container
const panel = document.createElement('div');
panel.id = 'zip-solver-panel';
panel.className = 'zip-solver-panel';
// Create drag handle
const dragHandle = document.createElement('div');
dragHandle.className = 'zip-drag-handle';
dragHandle.id = 'zip-drag-handle';
// Create resize handle
const resizeHandle = document.createElement('div');
resizeHandle.className = 'zip-resize-handle';
resizeHandle.innerHTML = '↘';
// Create close button
const header = document.createElement('div');
header.className = 'zip-solver-header';
header.innerHTML = `
<button class="zip-solver-close" id="zip-close-btn">×</button>
`;
// Create grid display
const gridContainer = document.createElement('div');
gridContainer.className = 'zip-solver-grid';
// Always show the grid (with or without solution)
const grid = createSolutionGrid(solution, puzzleData);
gridContainer.appendChild(grid);
// Add "no solution" message if needed
if (!solution) {
const message = document.createElement('div');
message.className = 'no-solution-message';
message.textContent = '😢 No solution found';
message.style.cssText = 'text-align: center; padding: 10px; color: #ff6b6b; font-weight: bold;';
gridContainer.insertBefore(message, grid);
}
// Assemble panel
panel.appendChild(dragHandle);
panel.appendChild(resizeHandle);
panel.appendChild(header);
panel.appendChild(gridContainer);
// Add to page
document.body.appendChild(panel);
// Add close button functionality
document.getElementById('zip-close-btn').addEventListener('click', () => {
panel.remove();
// Show the FAB when panel is closed
const fab = document.getElementById('zip-solver-fab');
if (fab) {
fab.style.display = 'flex';
}
});
// Make panel draggable only from drag handle
let isDragging = false;
let currentX;
let currentY;
let initialX;
let initialY;
dragHandle.addEventListener('mousedown', (e) => {
isDragging = true;
initialX = e.clientX - panel.offsetLeft;
initialY = e.clientY - panel.offsetTop;
dragHandle.style.cursor = 'grabbing';
});
document.addEventListener('mousemove', (e) => {
if (isDragging) {
e.preventDefault();
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
panel.style.left = `${currentX}px`;
panel.style.top = `${currentY}px`;
panel.style.right = 'auto';
}
});
document.addEventListener('mouseup', () => {
if (isDragging) {
isDragging = false;
dragHandle.style.cursor = 'grab';
}
});
// Enforce square aspect ratio on resize with better handling
let resizing = false;
const resizeObserver = new ResizeObserver(entries => {
if (resizing) return; // Prevent infinite loop
for (let entry of entries) {
const width = entry.contentRect.width;
const height = entry.contentRect.height;
// If dimensions don't match (user is resizing), force square
if (Math.abs(width - height) > 2) {
resizing = true;
// Use the larger dimension to maintain square
const size = Math.max(width, height);
// Clamp size to min/max
const clampedSize = Math.max(300, Math.min(800, size));
requestAnimationFrame(() => {
panel.style.width = `${clampedSize}px`;
panel.style.height = `${clampedSize}px`;
resizing = false;
});
}
}
});
resizeObserver.observe(panel);
// Custom resize handle functionality
let isResizing = false;
let startX, startY, startWidth;
resizeHandle.addEventListener('mousedown', (e) => {
isResizing = true;
startX = e.clientX;
startY = e.clientY;
startWidth = panel.offsetWidth;
e.preventDefault();
resizeHandle.style.cursor = 'nwse-resize';
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
e.preventDefault();
const deltaX = e.clientX - startX;
const deltaY = e.clientY - startY;
// Use the larger delta to maintain square
const delta = Math.max(deltaX, deltaY);
const newSize = Math.max(300, Math.min(800, startWidth + delta));
panel.style.width = `${newSize}px`;
panel.style.height = `${newSize}px`;
panel.style.setProperty('--panel-size', `${newSize}px`);
});
document.addEventListener('mouseup', () => {
if (isResizing) {
isResizing = false;
resizeHandle.style.cursor = 'nwse-resize';
}
});
}
// Create the visual grid showing the solution
function createSolutionGrid(path, puzzleData) {
const container = document.createElement('div');
container.className = 'zip-grid-container';
const grid = document.createElement('div');
grid.className = 'zip-grid';
const gridSize = puzzleData.gridSize || 6;
grid.style.gridTemplateColumns = `repeat(${gridSize}, 1fr)`;
grid.style.gridTemplateRows = `repeat(${gridSize}, 1fr)`;
// Get numbered cells map
const numberedCells = {};
for (const [number, [r, c]] of Object.entries(puzzleData.numberedCells)) {
numberedCells[`${r},${c}`] = parseInt(number);
}
// Create walls map for easy lookup
const wallsMap = {
horizontal: new Set(),
vertical: new Set()
};
if (puzzleData.walls) {
puzzleData.walls.forEach(wall => {
if (wall.type === 'horizontal') {
wallsMap.horizontal.add(`${wall.row},${wall.col}`);
} else if (wall.type === 'vertical') {
wallsMap.vertical.add(`${wall.row},${wall.col}`);
}
});
}
// Create HTML grid - all cells are white
for (let row = 0; row < gridSize; row++) {
for (let col = 0; col < gridSize; col++) {
const cell = document.createElement('div');
cell.className = 'zip-cell';
const cellKey = `${row},${col}`;
const cellNumber = numberedCells[cellKey];
if (cellNumber) {
// Cell has a number - add numbered class and data attribute
cell.classList.add('numbered');
cell.setAttribute('data-number', cellNumber);
}
// Add wall indicators
const hasHorizontal = wallsMap.horizontal.has(cellKey);
const hasVertical = wallsMap.vertical.has(cellKey);
// If this cell has horizontal wall → wall on bottom
if (hasHorizontal) {
cell.classList.add('wall-below');
}
// If this cell has vertical wall → wall on right
if (hasVertical) {
cell.classList.add('wall-right');
}
grid.appendChild(cell);
}
}
// Create SVG overlay for the path
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('class', 'zip-path-svg');
svg.setAttribute('viewBox', '0 0 100 100');
// Create path string
if (path && path.length > 0) {
const pathData = [];
// Match the CSS grid values: 6% padding and 1% gap
const padding = 6; // 6% padding to match CSS
const gapSize = 1; // 1% gap to match CSS
const availableSpace = 100 - (padding * 2);
const numGaps = gridSize - 1;
const cellSize = (availableSpace - (gapSize * numGaps)) / gridSize;
const cellCenter = cellSize / 2;
for (let i = 0; i < path.length; i++) {
const [row, col] = path[i];
const x = padding + (col * (cellSize + gapSize)) + cellCenter;
const y = padding + (row * (cellSize + gapSize)) + cellCenter;
if (i === 0) {
pathData.push(`M ${x} ${y}`);
} else {
pathData.push(`L ${x} ${y}`);
}
}
// Create gradient for the path
const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
const gradient = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient');
gradient.setAttribute('id', 'pathGradient');
gradient.setAttribute('x1', '0%');
gradient.setAttribute('y1', '0%');
gradient.setAttribute('x2', '100%');
gradient.setAttribute('y2', '100%');
const stop1 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
stop1.setAttribute('offset', '0%');
stop1.setAttribute('style', 'stop-color:#E85D4A;stop-opacity:1');
const stop2 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
stop2.setAttribute('offset', '50%');
stop2.setAttribute('style', 'stop-color:#FF6B35;stop-opacity:1');
const stop3 = document.createElementNS('http://www.w3.org/2000/svg', 'stop');
stop3.setAttribute('offset', '100%');
stop3.setAttribute('style', 'stop-color:#F7931E;stop-opacity:1');
gradient.appendChild(stop1);
gradient.appendChild(stop2);
gradient.appendChild(stop3);
defs.appendChild(gradient);
svg.appendChild(defs);
// Create the path element
const pathElement = document.createElementNS('http://www.w3.org/2000/svg', 'path');
pathElement.setAttribute('d', pathData.join(' '));
pathElement.setAttribute('stroke', 'url(#pathGradient)');
pathElement.setAttribute('stroke-width', '8'); // Thin enough to show walls clearly
pathElement.setAttribute('stroke-linecap', 'round');
pathElement.setAttribute('stroke-linejoin', 'round');
pathElement.setAttribute('fill', 'none');
svg.appendChild(pathElement);
}
container.appendChild(grid);
container.appendChild(svg);
return container;
}
// Show the solution automatically
function showSolution() {
try {
// Extract puzzle from page
const puzzleData = extractPuzzleFromPage();
if (Object.keys(puzzleData.numberedCells).length === 0) {
alert('😢 Could not find puzzle data on this page');
return;
}
const solution = solvePuzzle(puzzleData);
// Always show the side panel with the game board (even without solution)
createSidePanel(solution, puzzleData);
if (solution) {
// Only overlay arrows if we have a solution
overlayArrowsOnLinkedInGrid(solution, puzzleData);
}
} catch (error) {
alert('😢 Error: ' + error.message);
}
}
// Check if puzzle is completed (all cells filled)
function isPuzzleCompleted() {
const allCells = document.querySelectorAll('[data-testid^="cell-"]');
const filledCells = document.querySelectorAll('[data-testid="filled-cell"]');
return allCells.length > 0 && allCells.length === filledCells.length;
}
// Overlay arrows directly on LinkedIn's game grid
function overlayArrowsOnLinkedInGrid(path, puzzleData) {
// Remove any existing overlays
const existingOverlay = document.getElementById('zippy-arrow-overlay');
if (existingOverlay) {
existingOverlay.remove();
}
// Find the LinkedIn grid container
const gridContainer = document.querySelector('[data-testid="interactive-grid"]');
if (!gridContainer) {
return; // Grid not found
}
// Create overlay container
const overlay = document.createElement('div');
overlay.id = 'zippy-arrow-overlay';
overlay.style.position = 'absolute';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.pointerEvents = 'none';
overlay.style.zIndex = '1000';
// Add pulsing effect to the starting cell (minimum numbered cell) only if puzzle is not completed
if (!isPuzzleCompleted()) {
// Find the minimum numbered cell (the starting cell)
const numberedKeys = Object.keys(puzzleData.numberedCells).map(Number);
const minNumber = Math.min(...numberedKeys);
const startCellPosition = puzzleData.numberedCells[minNumber];
if (startCellPosition) {
const [row, col] = startCellPosition;
const gridSize = puzzleData.gridSize || 6;
const cellIdx = row * gridSize + col;
const cell1Element = document.querySelector(`[data-cell-idx="${cellIdx}"]`);
if (cell1Element) {
// Find the numbered circle element inside the cell
const numberCircle = cell1Element.querySelector('[data-cell-content="true"]');
if (numberCircle) {
// Add pulsing glow animation to the circle - using orange/red gradient colors
const pulseStyle = document.createElement('style');
pulseStyle.id = 'zippy-pulse-style';
pulseStyle.textContent = `
@keyframes zippy-pulse-ring {
0%, 100% {
box-shadow: 0 0 0 0px rgba(247, 147, 30, 1),
0 0 30px 8px rgba(255, 107, 53, 0.8),
0 0 50px 15px rgba(247, 147, 30, 0.4);
}
50% {
box-shadow: 0 0 0 12px rgba(247, 147, 30, 0.3),
0 0 50px 20px rgba(255, 107, 53, 0.9),
0 0 80px 30px rgba(247, 147, 30, 0.6);
}
}
.zippy-pulse-circle {
animation: zippy-pulse-ring 1.5s ease-in-out infinite !important;
}
`;
document.head.appendChild(pulseStyle);
numberCircle.classList.add('zippy-pulse-circle');
}
}
}
}
// Create a set of numbered cell positions to skip
const numberedPositions = new Set();
for (const [, [row, col]] of Object.entries(puzzleData.numberedCells)) {
numberedPositions.add(`${row},${col}`);
}
// Add arrows between consecutive cells in the path
const gridSize = puzzleData.gridSize || 6;
for (let i = 0; i < path.length - 1; i++) {
const [fromRow, fromCol] = path[i];
const [toRow, toCol] = path[i + 1];
// Skip if this cell has a numbered circle
if (numberedPositions.has(`${fromRow},${fromCol}`)) {
continue;
}
const fromIdx = fromRow * gridSize + fromCol;
const fromCell = document.querySelector(`[data-cell-idx="${fromIdx}"]`);
// Skip if this cell is already filled
if (fromCell && fromCell.querySelector('[data-testid="filled-cell"]')) {
continue;
}
if (fromCell) {
// Calculate arrow direction
const arrow = document.createElement('div');
arrow.className = 'zippy-arrow';
arrow.style.position = 'absolute';
arrow.style.pointerEvents = 'none';
let isCorner = false;
let rotation = 0;
let scaleX = 1;
let scaleY = 1;
// Check if this is a corner
if (i > 0) {
const [prevRow, prevCol] = path[i - 1];
// prev -> curr (fromRow, fromCol) -> next (toRow, toCol)
console.log(`Cell [${fromRow},${fromCol}]: prev=[${prevRow},${prevCol}] curr=[${fromRow},${fromCol}] next=[${toRow},${toCol}]`);
// Calculate direction vectors
const incomingDirRow = fromRow - prevRow; // -1 = came from below, +1 = came from above, 0 = horizontal
const incomingDirCol = fromCol - prevCol; // -1 = came from right, +1 = came from left, 0 = vertical
const outgoingDirRow = toRow - fromRow; // -1 = going up, +1 = going down, 0 = horizontal
const outgoingDirCol = toCol - fromCol; // -1 = going left, +1 = going right, 0 = vertical
console.log(` incoming: [${incomingDirRow},${incomingDirCol}] outgoing: [${outgoingDirRow},${outgoingDirCol}]`);
// Corner if direction changes: incoming and outgoing directions are different
if (incomingDirRow !== outgoingDirRow || incomingDirCol !== outgoingDirCol) {
isCorner = true;
console.log(` ✓ CORNER detected`);
const comingFromAbove = incomingDirRow === 1; // prev is above curr
const comingFromBelow = incomingDirRow === -1; // prev is below curr
const comingFromLeft = incomingDirCol === 1; // prev is left of curr
const comingFromRight = incomingDirCol === -1; // prev is right of curr
const goingRight = outgoingDirCol === 1; // next is right of curr
const goingLeft = outgoingDirCol === -1; // next is left of curr
const goingDown = outgoingDirRow === 1; // next is below curr
const goingUp = outgoingDirRow === -1; // next is above curr
console.log(` directions: from=${comingFromAbove?'above':comingFromBelow?'below':comingFromLeft?'left':'right'} to=${goingUp?'up':goingDown?'down':goingLeft?'left':'right'}`);
// Determine rotation and reflection for SVG based on direction
// Base SVG is right-up, so we need to rotate/reflect for other directions
if (comingFromAbove && goingRight) {
// Down-right: rotate 90° clockwise GOOD
rotation = 90;
}
else if (comingFromAbove && goingLeft) {
// Down-left: rotate 90° and flip horizontally GOOD
rotation = -90;
scaleX = -1;
}
else if (comingFromBelow && goingRight) {
// Up-right: base orientation GOOD
rotation = 90;
scaleX = -1;
}
else if (comingFromBelow && goingLeft) {
// Up-left: flip horizontally
rotation = -90;
}
else if (comingFromLeft && goingDown) {
// Right-down: rotate 90° clockwise
scaleY = -1;
}
else if (comingFromLeft && goingUp) {
// Right-up: base orientation GOOD
rotation = 0;
}
else if (comingFromRight && goingDown) {
// Left-down: rotate 90° and flip horizontally
rotation = 180;
}
else if (comingFromRight && goingUp) {
// Left-up: flip horizontally
scaleX = -1;
}
}
} else {
console.log(`Cell [${fromRow},${fromCol}]: first cell, next=[${toRow},${toCol}]`);
}
console.log(` isCorner=${isCorner} rotation=${rotation} scaleX=${scaleX} scaleY=${scaleY}`);
if (isCorner) {
// Use SVG for corner arrows
const img = document.createElement('img');
const svgUrl = chrome.runtime.getURL('corner-right-up.svg');
console.log(` → Loading corner SVG from: ${svgUrl}`);
img.src = svgUrl;
img.style.width = '50px';
img.style.height = '50px';
img.style.transform = `rotate(${rotation}deg) scale(${scaleX}, ${scaleY})`;
img.style.filter = 'brightness(0)'; // Make it black
img.style.display = 'block'; // Remove inline spacing
img.onerror = () => console.error(` ✗ Failed to load SVG: ${svgUrl}`);
img.onload = () => console.log(` ✓ SVG loaded successfully`);
arrow.appendChild(img);
console.log(` → Added corner arrow to DOM`);
} else {
// Use text arrows for straight directions
arrow.style.fontSize = '32px';
arrow.style.color = '#000';
arrow.style.fontWeight = 'bold';
let arrowChar = '';
if (toRow < fromRow) arrowChar = '↑';
else if (toRow > fromRow) arrowChar = '↓';
else if (toCol < fromCol) arrowChar = '←';
else if (toCol > fromCol) arrowChar = '→';
arrow.textContent = arrowChar;
}
// Position arrow in the center of fromCell
const fromRect = fromCell.getBoundingClientRect();
const gridRect = gridContainer.getBoundingClientRect();
if (isCorner) {
// Use flexbox for perfect centering of SVG
arrow.style.display = 'flex';
arrow.style.alignItems = 'center';
arrow.style.justifyContent = 'center';
arrow.style.width = `${fromRect.width}px`;
arrow.style.height = `${fromRect.height}px`;
arrow.style.left = `${fromRect.left - gridRect.left}px`;
arrow.style.top = `${fromRect.top - gridRect.top}px`;
} else {
// Center text arrows
arrow.style.left = `${fromRect.left - gridRect.left + fromRect.width / 2 - 16}px`;
arrow.style.top = `${fromRect.top - gridRect.top + fromRect.height / 2 - 16}px`;
}
overlay.appendChild(arrow);
}
}
// Make grid container position relative if it isn't already
if (getComputedStyle(gridContainer).position === 'static') {
gridContainer.style.position = 'relative';
}
gridContainer.appendChild(overlay);
// Disconnect any existing observer to avoid duplicates
if (arrowMutationObserver) {
arrowMutationObserver.disconnect();
}
// Watch for cell fills and update arrows dynamically
arrowMutationObserver = new MutationObserver(() => {
// Re-render the overlay when cells change
overlayArrowsOnLinkedInGrid(path, puzzleData);
});
// Observe all cells for changes
const cells = document.querySelectorAll('[data-testid^="cell-"]');
cells.forEach(cell => {
arrowMutationObserver.observe(cell, { childList: true, subtree: true });
});
}
// Initialize when page loads
function init() {
if (isZipPage()) {
// Remove any existing panel/FAB first to avoid duplicates
const existingPanel = document.getElementById('zip-solver-panel');
if (existingPanel) {
existingPanel.remove();
}
// Create the FAB first
createFAB();
// Wait for the grid to be fully loaded on the page
// Use multiple attempts in case the grid loads slowly
let attempts = 0;
const maxAttempts = 10;
const tryShowSolution = () => {
const gridExists = document.querySelector('[data-testid^="cell-"]');
if (gridExists) {
showSolution();
} else if (attempts < maxAttempts) {
attempts++;
setTimeout(tryShowSolution, 500);
}
};
setTimeout(tryShowSolution, 500);
}
}
// Run on page load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
// Aggressive URL monitoring - check constantly
setInterval(() => {
const onZipPage = isZipPage();
const panelExists = !!document.getElementById('zip-solver-panel');
const fab = document.getElementById('zip-solver-fab');
const fabVisible = fab && fab.style.display !== 'none';
// Only init if:
// 1. We're on the Zip page
// 2. No panel exists
// 3. FAB is NOT visible (if FAB is visible, user closed the panel intentionally)
if (onZipPage && !panelExists && !fabVisible) {
init();
}
}, 500);