-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
857 lines (711 loc) · 26 KB
/
content.js
File metadata and controls
857 lines (711 loc) · 26 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
/**
* Dev Feedback Capture - Content Script
* Injected on demand into the current tab for in-page UI and element capture.
*/
(function() {
'use strict';
if (window.__DEV_FEEDBACK_CAPTURE_LOADED__) {
return;
}
window.__DEV_FEEDBACK_CAPTURE_LOADED__ = true;
const {
CAPTURE_TYPE_ELEMENT,
CAPTURE_TYPE_REGION,
MAX_NOTE_LENGTH,
buildAiPromptExport,
buildFeedbackId,
buildMarkdownExport,
escapeCssIdentifier,
formatTimestamp,
makeStorageKey,
sanitizeFeedbackItems
} = globalThis.DevFeedbackShared;
const UI_IDS = {
panel: 'dev-feedback-panel',
modal: 'dev-feedback-modal',
markerLayer: 'dev-feedback-marker-layer',
elementDetails: 'dev-feedback-element-details',
note: 'dev-feedback-note'
};
const SELECTORS = {
panel: `#${UI_IDS.panel}`,
modal: `#${UI_IDS.modal}`,
markerLayer: `#${UI_IDS.markerLayer}`
};
let feedbackMode = false;
let feedbackItems = [];
let currentElement = null;
let isDragging = false;
let dragOffset = { x: 0, y: 0 };
let feedbackPanel = null;
let captureModal = null;
let markerLayer = null;
let decorationFrame = 0;
function init() {
if (!document.body) {
return;
}
createFeedbackPanel();
createCaptureModal();
createMarkerLayer();
attachGlobalListeners();
loadFeedbackItems();
console.log('Dev Feedback Capture initialized');
}
function createFeedbackPanel() {
feedbackPanel = document.createElement('div');
feedbackPanel.id = UI_IDS.panel;
feedbackPanel.innerHTML = `
<div class="dev-feedback-panel-header">
<div class="dev-feedback-panel-header-title">
<span>Feedback Items</span>
<span class="dev-feedback-count">0</span>
</div>
</div>
<div class="dev-feedback-panel-actions">
<button class="dev-feedback-btn dev-feedback-btn-primary" id="dev-feedback-copy-json">Copy JSON</button>
<button class="dev-feedback-btn dev-feedback-btn-secondary" id="dev-feedback-copy-markdown">Copy Markdown</button>
<button class="dev-feedback-btn dev-feedback-btn-secondary" id="dev-feedback-copy-ai">Copy AI Prompt</button>
<button class="dev-feedback-btn dev-feedback-btn-primary" id="dev-feedback-capture-region">Capture Region</button>
<button class="dev-feedback-btn dev-feedback-btn-danger" id="dev-feedback-clear">Clear All</button>
</div>
<div class="dev-feedback-items"></div>
`;
document.body.appendChild(feedbackPanel);
feedbackPanel.querySelector('.dev-feedback-panel-header').addEventListener('mousedown', startDragging);
feedbackPanel.querySelector('#dev-feedback-copy-json').addEventListener('click', copyAsJSON);
feedbackPanel.querySelector('#dev-feedback-copy-markdown').addEventListener('click', copyAsMarkdown);
feedbackPanel.querySelector('#dev-feedback-copy-ai').addEventListener('click', copyAsAiPrompt);
feedbackPanel.querySelector('#dev-feedback-capture-region').addEventListener('click', startRegionCapture);
feedbackPanel.querySelector('#dev-feedback-clear').addEventListener('click', clearAllFeedback);
}
function createCaptureModal() {
captureModal = document.createElement('div');
captureModal.id = UI_IDS.modal;
captureModal.innerHTML = `
<div class="dev-feedback-modal-content" role="dialog" aria-modal="true" aria-labelledby="dev-feedback-modal-title">
<h2 class="dev-feedback-modal-title" id="dev-feedback-modal-title">Capture Element Feedback</h2>
<div class="dev-feedback-modal-section">
<div class="dev-feedback-modal-section-title">Element Information</div>
<div class="dev-feedback-element-info" id="${UI_IDS.elementDetails}"></div>
</div>
<div class="dev-feedback-modal-section">
<div class="dev-feedback-modal-section-title">What do you want changed?</div>
<textarea
class="dev-feedback-textarea"
id="${UI_IDS.note}"
maxlength="${MAX_NOTE_LENGTH}"
placeholder="Describe the changes you'd like to see..."
></textarea>
<div class="dev-feedback-help-text">Up to ${MAX_NOTE_LENGTH} characters.</div>
</div>
<div class="dev-feedback-modal-actions">
<button class="dev-feedback-btn dev-feedback-btn-large dev-feedback-btn-primary" id="dev-feedback-save">Save Feedback</button>
<button class="dev-feedback-btn dev-feedback-btn-large dev-feedback-btn-secondary" id="dev-feedback-cancel">Cancel</button>
</div>
</div>
`;
document.body.appendChild(captureModal);
captureModal.querySelector('#dev-feedback-save').addEventListener('click', saveFeedback);
captureModal.querySelector('#dev-feedback-cancel').addEventListener('click', closeCaptureModal);
captureModal.addEventListener('click', (event) => {
if (event.target === captureModal) {
closeCaptureModal();
}
});
}
function createMarkerLayer() {
markerLayer = document.createElement('div');
markerLayer.id = UI_IDS.markerLayer;
document.body.appendChild(markerLayer);
}
function attachGlobalListeners() {
window.addEventListener('resize', scheduleDecorationRefresh, { passive: true });
window.addEventListener('scroll', scheduleDecorationRefresh, true);
document.addEventListener('keydown', handleGlobalKeydown);
}
function handleGlobalKeydown(event) {
if (event.key === 'Escape' && captureModal.classList.contains('visible')) {
event.preventDefault();
closeCaptureModal();
}
}
function toggleFeedbackMode() {
feedbackMode = !feedbackMode;
feedbackPanel.classList.toggle('visible', feedbackMode);
if (feedbackMode) {
enableElementHighlighting();
} else {
disableElementHighlighting();
closeCaptureModal();
}
scheduleDecorationRefresh();
}
function setFeedbackMode(enabled) {
if (feedbackMode !== enabled) {
toggleFeedbackMode();
}
}
function enableElementHighlighting() {
document.addEventListener('mouseover', handleMouseOver);
document.addEventListener('mouseout', handleMouseOut);
document.addEventListener('click', handleElementClick, true);
}
function disableElementHighlighting() {
document.removeEventListener('mouseover', handleMouseOver);
document.removeEventListener('mouseout', handleMouseOut);
document.removeEventListener('click', handleElementClick, true);
document.querySelectorAll('.dev-feedback-highlight').forEach((element) => {
element.classList.remove('dev-feedback-highlight');
});
}
function handleMouseOver(event) {
if (!feedbackMode || isOurElement(event.target)) {
return;
}
event.target.classList.add('dev-feedback-highlight');
}
function handleMouseOut(event) {
if (!feedbackMode || isOurElement(event.target)) {
return;
}
event.target.classList.remove('dev-feedback-highlight');
}
function handleElementClick(event) {
if (!feedbackMode) {
return;
}
const target = event.target;
if (isOurElement(target)) {
return;
}
event.preventDefault();
event.stopPropagation();
captureElement(target);
}
function isOurElement(element) {
return Boolean(
element &&
(
(element.id && element.id.startsWith('dev-feedback')) ||
(typeof element.closest === 'function' && element.closest(SELECTORS.panel)) ||
(typeof element.closest === 'function' && element.closest(SELECTORS.modal)) ||
(typeof element.closest === 'function' && element.closest(SELECTORS.markerLayer))
)
);
}
function captureElement(element) {
currentElement = element;
const elementInfo = {
selector: getElementSelector(element),
tag: element.tagName.toLowerCase(),
classes: Array.from(element.classList).filter((className) => !className.startsWith('dev-feedback')),
text: (element.innerText || element.textContent || '').trim().slice(0, 100),
styles: pickTrackedStyles(window.getComputedStyle(element)),
position: getElementPosition(element)
};
displayElementInfo(elementInfo);
showCaptureModal();
}
function pickTrackedStyles(computedStyles) {
return {
'background-color': computedStyles.backgroundColor,
'color': computedStyles.color,
'font-size': computedStyles.fontSize,
'width': computedStyles.width,
'height': computedStyles.height,
'margin': computedStyles.margin,
'padding': computedStyles.padding
};
}
function getElementPosition(element) {
const rect = element.getBoundingClientRect();
return {
x: Math.round(rect.left + window.scrollX),
y: Math.round(rect.top + window.scrollY)
};
}
function getElementSelector(element) {
if (element.id) {
return `#${escapeCssIdentifier(element.id)}`;
}
const path = [];
let current = element;
while (current && current.nodeType === Node.ELEMENT_NODE && path.length < 5) {
let selector = current.tagName.toLowerCase();
const classNames = Array.from(current.classList)
.filter((className) => !className.startsWith('dev-feedback'))
.slice(0, 2);
if (classNames.length > 0) {
selector += `.${classNames.map(escapeCssIdentifier).join('.')}`;
}
if (current.parentElement) {
const sameTypeSiblings = Array.from(current.parentElement.children).filter(
(sibling) => sibling.tagName === current.tagName
);
if (sameTypeSiblings.length > 1) {
selector += `:nth-of-type(${sameTypeSiblings.indexOf(current) + 1})`;
}
}
path.unshift(selector);
const candidate = path.join(' > ');
if (isUniqueSelector(candidate)) {
return candidate;
}
current = current.parentElement;
}
return path.join(' > ');
}
function isUniqueSelector(selector) {
try {
return document.querySelectorAll(selector).length === 1;
} catch (error) {
return false;
}
}
function displayElementInfo(elementInfo) {
const detailsContainer = captureModal.querySelector(`#${UI_IDS.elementDetails}`);
const fragment = document.createDocumentFragment();
addInfoRow(fragment, 'Selector', elementInfo.selector);
addInfoRow(fragment, 'Tag', elementInfo.tag);
addInfoRow(fragment, 'Classes', elementInfo.classes.join(', ') || 'none');
addInfoRow(fragment, 'Text', elementInfo.text || '(empty)');
addInfoRow(fragment, 'Position', `x: ${elementInfo.position.x}, y: ${elementInfo.position.y}`);
const stylesText = Object.entries(elementInfo.styles)
.map(([key, value]) => `${key}: ${value}`)
.join('; ');
addInfoRow(fragment, 'Styles', stylesText);
detailsContainer.replaceChildren(fragment);
captureModal.dataset.elementInfo = JSON.stringify(elementInfo);
}
function addInfoRow(fragment, label, value) {
const row = document.createElement('div');
row.className = 'dev-feedback-element-info-row';
const labelElement = document.createElement('span');
labelElement.className = 'dev-feedback-element-info-label';
labelElement.textContent = `${label}:`;
const valueElement = document.createElement('span');
valueElement.className = 'dev-feedback-element-info-value';
valueElement.textContent = value;
row.appendChild(labelElement);
row.appendChild(valueElement);
fragment.appendChild(row);
}
function showCaptureModal() {
captureModal.classList.add('visible');
const noteField = captureModal.querySelector(`#${UI_IDS.note}`);
noteField.value = '';
noteField.focus();
}
function closeCaptureModal() {
captureModal.classList.remove('visible');
if (currentElement) {
currentElement.classList.remove('dev-feedback-highlight');
currentElement = null;
}
}
async function saveFeedback() {
const noteField = captureModal.querySelector(`#${UI_IDS.note}`);
const note = noteField.value.trim();
if (!note) {
showNotification('Add a short description before saving.', 'error');
noteField.focus();
return;
}
let elementInfo;
try {
elementInfo = JSON.parse(captureModal.dataset.elementInfo || '{}');
} catch (error) {
showNotification('Unable to read the captured element details.', 'error');
return;
}
const nextItems = feedbackItems.concat({
id: buildFeedbackId(),
type: CAPTURE_TYPE_ELEMENT,
captureType: CAPTURE_TYPE_ELEMENT,
selector: elementInfo.selector,
pageUrl: window.location.href,
pageTitle: document.title,
elementInfo: {
tag: elementInfo.tag,
classes: elementInfo.classes,
text: elementInfo.text,
styles: elementInfo.styles
},
position: elementInfo.position,
note: note.slice(0, MAX_NOTE_LENGTH),
timestamp: new Date().toISOString()
});
if (!(await persistFeedbackItems(nextItems))) {
return;
}
feedbackItems = sanitizeFeedbackItems(nextItems, window.location.href, document.title);
updateFeedbackPanel();
closeCaptureModal();
scheduleDecorationRefresh();
showNotification('Feedback saved.');
}
async function startRegionCapture() {
try {
const response = await chrome.runtime.sendMessage({
action: 'start-region-capture',
viewportMetrics: getViewportMetrics()
});
if (!response || !response.ok) {
showNotification(response?.reason || 'Unable to start region capture.', 'error');
return;
}
showNotification('Region capture opened in a new tab.');
} catch (error) {
showNotification('Unable to start region capture.', 'error');
}
}
function updateFeedbackPanel() {
const itemsContainer = feedbackPanel.querySelector('.dev-feedback-items');
const countBadge = feedbackPanel.querySelector('.dev-feedback-count');
countBadge.textContent = String(feedbackItems.length);
itemsContainer.replaceChildren();
if (feedbackItems.length === 0) {
const emptyState = document.createElement('div');
emptyState.className = 'dev-feedback-empty';
emptyState.textContent = 'No feedback items yet. Capture an element or use region capture from the panel or popup.';
itemsContainer.appendChild(emptyState);
return;
}
const fragment = document.createDocumentFragment();
feedbackItems.forEach((item, index) => {
fragment.appendChild(createFeedbackItemElement(item, index));
});
itemsContainer.appendChild(fragment);
}
function createFeedbackItemElement(item, index) {
const itemElement = document.createElement('div');
itemElement.className = 'dev-feedback-item';
const header = document.createElement('div');
header.className = 'dev-feedback-item-header';
const number = document.createElement('span');
number.className = 'dev-feedback-item-number';
number.textContent = String(index + 1);
const deleteButton = document.createElement('button');
deleteButton.className = 'dev-feedback-item-delete';
deleteButton.title = 'Delete';
deleteButton.textContent = '×';
deleteButton.addEventListener('click', () => {
deleteFeedbackItem(index);
});
header.appendChild(number);
header.appendChild(deleteButton);
itemElement.appendChild(header);
if (item.type === CAPTURE_TYPE_REGION) {
populateRegionItem(itemElement, item);
} else {
populateElementItem(itemElement, item);
}
const note = document.createElement('div');
note.className = 'dev-feedback-item-note';
note.textContent = item.note;
itemElement.appendChild(note);
const timestamp = document.createElement('div');
timestamp.className = 'dev-feedback-item-timestamp';
timestamp.textContent = formatTimestamp(item.timestamp);
itemElement.appendChild(timestamp);
const pageHint = getPageHint(item.pageUrl);
if (pageHint) {
const locationHint = document.createElement('div');
locationHint.className = 'dev-feedback-item-location';
locationHint.textContent = pageHint;
itemElement.appendChild(locationHint);
}
if (item.type === CAPTURE_TYPE_ELEMENT && !findCapturedElement(item.selector)) {
const status = document.createElement('div');
status.className = 'dev-feedback-item-status';
status.textContent = 'Element not currently found on this page';
itemElement.appendChild(status);
}
return itemElement;
}
function populateElementItem(itemElement, item) {
const selector = document.createElement('div');
selector.className = 'dev-feedback-item-selector';
selector.textContent = item.selector;
itemElement.appendChild(selector);
}
function populateRegionItem(itemElement, item) {
const label = document.createElement('div');
label.className = 'dev-feedback-item-selector';
label.textContent = `Region capture (${item.sourceKind})`;
itemElement.appendChild(label);
if (item.screenshot.dataUrl) {
const thumbnail = document.createElement('img');
thumbnail.className = 'dev-feedback-item-thumbnail';
thumbnail.src = item.screenshot.dataUrl;
thumbnail.alt = 'Captured region preview';
itemElement.appendChild(thumbnail);
}
const meta = document.createElement('div');
meta.className = 'dev-feedback-item-location';
meta.textContent = `Rect ${item.viewportRect.width}×${item.viewportRect.height} at (${item.viewportRect.x}, ${item.viewportRect.y})`;
itemElement.appendChild(meta);
if (item.tabContext?.url) {
const source = document.createElement('div');
source.className = 'dev-feedback-item-location';
source.textContent = item.tabContext.url;
itemElement.appendChild(source);
}
}
function getPageHint(rawUrl) {
try {
const capturedUrl = new URL(rawUrl);
const currentUrl = new URL(window.location.href);
const capturedPath = `${capturedUrl.pathname}${capturedUrl.search}`;
const currentPath = `${currentUrl.pathname}${currentUrl.search}`;
if (capturedPath !== currentPath) {
return `Captured on ${capturedPath || '/'}`;
}
} catch (error) {
return '';
}
return '';
}
async function deleteFeedbackItem(index) {
if (!confirm('Delete this feedback item?')) {
return;
}
const nextItems = feedbackItems.filter((_, itemIndex) => itemIndex !== index);
if (!(await persistFeedbackItems(nextItems))) {
return;
}
feedbackItems = sanitizeFeedbackItems(nextItems, window.location.href, document.title);
updateFeedbackPanel();
scheduleDecorationRefresh();
}
async function copyAsJSON() {
const data = {
url: window.location.href,
timestamp: new Date().toISOString(),
feedback: feedbackItems
};
try {
await copyToClipboard(JSON.stringify(data, null, 2));
showNotification('Copied as JSON.');
} catch (error) {
showNotification('Unable to copy JSON to the clipboard.', 'error');
}
}
async function copyAsMarkdown() {
try {
await copyToClipboard(buildMarkdownExport(window.location.href, feedbackItems));
showNotification('Copied as Markdown.');
} catch (error) {
showNotification('Unable to copy Markdown to the clipboard.', 'error');
}
}
async function copyAsAiPrompt() {
try {
await copyToClipboard(buildAiPromptExport(window.location.href, feedbackItems));
showNotification('Copied as AI prompt.');
} catch (error) {
showNotification('Unable to copy the AI prompt to the clipboard.', 'error');
}
}
async function clearAllFeedback() {
if (feedbackItems.length === 0) {
return;
}
if (!confirm(`Delete all ${feedbackItems.length} feedback items?`)) {
return;
}
if (!(await persistFeedbackItems([]))) {
return;
}
feedbackItems = [];
updateFeedbackPanel();
clearDecorations();
showNotification('All feedback cleared.');
}
async function copyToClipboard(text) {
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
try {
await navigator.clipboard.writeText(text);
return;
} catch (error) {
// Fall through to the legacy copy path.
}
}
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', 'true');
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
textarea.style.pointerEvents = 'none';
document.body.appendChild(textarea);
textarea.select();
const copied = document.execCommand('copy');
textarea.remove();
if (!copied) {
throw new Error('Clipboard copy failed');
}
}
function showNotification(message, type) {
const notification = document.createElement('div');
notification.className = `dev-feedback-notification dev-feedback-notification-${type || 'success'}`;
notification.textContent = message;
document.body.appendChild(notification);
requestAnimationFrame(() => {
notification.classList.add('visible');
});
window.setTimeout(() => {
notification.classList.remove('visible');
window.setTimeout(() => notification.remove(), 220);
}, 2200);
}
async function persistFeedbackItems(nextItems) {
const storageKey = makeStorageKey(window.location.href);
return new Promise((resolve) => {
chrome.storage.local.set({ [storageKey]: nextItems }, () => {
if (chrome.runtime.lastError) {
console.error('Unable to persist feedback items:', chrome.runtime.lastError.message);
showNotification('Unable to save feedback right now.', 'error');
resolve(false);
return;
}
resolve(true);
});
});
}
function loadFeedbackItems() {
const storageKey = makeStorageKey(window.location.href);
chrome.storage.local.get([storageKey], (result) => {
if (chrome.runtime.lastError) {
console.error('Unable to load feedback items:', chrome.runtime.lastError.message);
showNotification('Unable to load saved feedback.', 'error');
return;
}
feedbackItems = sanitizeFeedbackItems(result[storageKey], window.location.href, document.title);
updateFeedbackPanel();
scheduleDecorationRefresh();
});
}
function scheduleDecorationRefresh() {
if (decorationFrame) {
return;
}
decorationFrame = window.requestAnimationFrame(() => {
decorationFrame = 0;
applyDecorations();
});
}
function applyDecorations() {
clearDecorations();
if (!feedbackItems.length) {
return;
}
const fragment = document.createDocumentFragment();
feedbackItems.forEach((item, index) => {
if (item.type !== CAPTURE_TYPE_ELEMENT) {
return;
}
const element = findCapturedElement(item.selector);
if (!element || isOurElement(element)) {
return;
}
element.classList.add('dev-feedback-selected');
const rect = element.getBoundingClientRect();
const badge = document.createElement('div');
badge.className = 'dev-feedback-badge';
badge.textContent = String(index + 1);
badge.style.top = `${clamp(rect.top - 12, 8, Math.max(8, window.innerHeight - 32))}px`;
badge.style.left = `${clamp(rect.right - 12, 8, Math.max(8, window.innerWidth - 32))}px`;
fragment.appendChild(badge);
});
markerLayer.replaceChildren(fragment);
}
function clearDecorations() {
document.querySelectorAll('.dev-feedback-selected').forEach((element) => {
if (!isOurElement(element)) {
element.classList.remove('dev-feedback-selected');
}
});
if (markerLayer) {
markerLayer.replaceChildren();
}
}
function findCapturedElement(selector) {
try {
return document.querySelector(selector);
} catch (error) {
return null;
}
}
function startDragging(event) {
if (event.button !== 0) {
return;
}
isDragging = true;
feedbackPanel.classList.add('dragging');
const rect = feedbackPanel.getBoundingClientRect();
dragOffset.x = event.clientX - rect.left;
dragOffset.y = event.clientY - rect.top;
document.addEventListener('mousemove', handleDragging);
document.addEventListener('mouseup', stopDragging);
event.preventDefault();
}
function handleDragging(event) {
if (!isDragging) {
return;
}
const maxX = Math.max(8, window.innerWidth - feedbackPanel.offsetWidth - 8);
const maxY = Math.max(8, window.innerHeight - feedbackPanel.offsetHeight - 8);
const x = clamp(event.clientX - dragOffset.x, 8, maxX);
const y = clamp(event.clientY - dragOffset.y, 8, maxY);
feedbackPanel.style.left = `${x}px`;
feedbackPanel.style.top = `${y}px`;
feedbackPanel.style.right = 'auto';
feedbackPanel.style.bottom = 'auto';
}
function stopDragging() {
isDragging = false;
feedbackPanel.classList.remove('dragging');
document.removeEventListener('mousemove', handleDragging);
document.removeEventListener('mouseup', stopDragging);
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
function getViewportMetrics() {
return {
width: window.innerWidth,
height: window.innerHeight,
devicePixelRatio: window.devicePixelRatio || 1
};
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'toggle-feedback-mode') {
toggleFeedbackMode();
sendResponse({ feedbackMode, itemCount: feedbackItems.length });
return;
}
if (request.action === 'get-state') {
sendResponse({ feedbackMode, itemCount: feedbackItems.length });
return;
}
if (request.action === 'set-feedback-mode') {
setFeedbackMode(Boolean(request.enabled));
sendResponse({ feedbackMode, itemCount: feedbackItems.length });
return;
}
if (request.action === 'refresh-feedback') {
loadFeedbackItems();
sendResponse({ feedbackMode, itemCount: feedbackItems.length });
return;
}
if (request.action === 'get-viewport-metrics') {
sendResponse(getViewportMetrics());
}
});
})();