devx-web-widget 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,864 @@
1
+ /*!
2
+ * Feedback Capture Widget - TypeScript Implementation
3
+ * Class-based, configurable widget with style isolation via Shadow DOM
4
+ * Supports multiple widget types (default, chatbot) and positioning (left, right)
5
+ */
6
+
7
+ // ============================================================================
8
+ // Type Definitions
9
+ // ============================================================================
10
+
11
+ type WidgetPosition = 'left' | 'right';
12
+ type WidgetType = 'default' | 'chatbot';
13
+ type WidgetState = 'idle' | 'menu' | 'picking' | 'review';
14
+
15
+ interface FeedbackWidgetConfig {
16
+ buttonLabel?: string;
17
+ backgroundColor?: string;
18
+ textColor?: string;
19
+ accentColor?: string;
20
+ font?: string;
21
+ position?: WidgetPosition;
22
+ widgetType?: WidgetType;
23
+ }
24
+
25
+ interface FeedbackPayload {
26
+ optionType: 'page_item_visible' | 'page_item_hidden';
27
+ elementSelector: string | null;
28
+ pageUrl: string;
29
+ pageTitle: string;
30
+ title: string;
31
+ feedback: string;
32
+ email: string;
33
+ submittedAt: string;
34
+ }
35
+
36
+ interface FeedbackMessageBody {
37
+ title: string;
38
+ body: string;
39
+ user_handle: string;
40
+ }
41
+
42
+ interface ElementRefs {
43
+ tab: HTMLElement;
44
+ menu: HTMLElement;
45
+ banner: HTMLElement;
46
+ highlight: HTMLElement;
47
+ overlay: HTMLElement;
48
+ modal: HTMLElement;
49
+ form: HTMLFormElement;
50
+ itemField: HTMLElement;
51
+ itemBox: HTMLElement;
52
+ title: HTMLInputElement;
53
+ feedback: HTMLTextAreaElement;
54
+ email: HTMLInputElement;
55
+ error: HTMLElement;
56
+ toast: HTMLElement;
57
+ }
58
+
59
+ // ============================================================================
60
+ // Default Configuration
61
+ // ============================================================================
62
+
63
+ const DEFAULT_CONFIG: Required<FeedbackWidgetConfig> = {
64
+ buttonLabel: 'Feedback',
65
+ backgroundColor: '#111827',
66
+ textColor: '#ffffff',
67
+ accentColor: '#2F6FED',
68
+ font: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
69
+ position: 'right',
70
+ widgetType: 'default'
71
+ };
72
+
73
+ // ============================================================================
74
+ // FeedbackWidget Class
75
+ // ============================================================================
76
+
77
+ class FeedbackWidget {
78
+ private config: Required<FeedbackWidgetConfig>;
79
+ private host!: HTMLElement;
80
+ private root!: ShadowRoot;
81
+ private elements!: ElementRefs;
82
+ private state: WidgetState;
83
+ private showItemInForm: boolean;
84
+ private selectedSelector: string | null;
85
+ private selectedEl: Element | null;
86
+ private hoverRafId: number | null;
87
+ private hostId: string;
88
+ private apiKey: string;
89
+ private endPoint: string;
90
+
91
+ constructor(apiKey: string | null = null, config: FeedbackWidgetConfig = {}) {
92
+ this.config = { ...DEFAULT_CONFIG, ...config };
93
+ this.hostId = `feedback-widget-host-${Math.random().toString(36).substr(2, 9)}`;
94
+ this.state = 'idle';
95
+ this.showItemInForm = true;
96
+ this.selectedSelector = null;
97
+ this.selectedEl = null;
98
+ this.hoverRafId = null;
99
+ this.apiKey = apiKey || '';
100
+ this.endPoint = "https://devx.today/v1/widget/ingest";
101
+
102
+ this.initialize();
103
+ }
104
+
105
+ private initialize(): void {
106
+ this.createHostAndShadow();
107
+ this.injectStyles();
108
+ this.createMarkup();
109
+ this.cacheElements();
110
+ this.attachEventListeners();
111
+ }
112
+
113
+ // -------------------------------------------------------------------------
114
+ // Shadow DOM Setup
115
+ // -------------------------------------------------------------------------
116
+
117
+ private createHostAndShadow(): void {
118
+ this.host = document.createElement('div');
119
+ this.host.id = this.hostId;
120
+ document.documentElement.appendChild(this.host);
121
+ this.root = this.host.attachShadow({ mode: 'open' });
122
+ }
123
+
124
+ // -------------------------------------------------------------------------
125
+ // CSS Generation (Dynamic based on config)
126
+ // -------------------------------------------------------------------------
127
+
128
+ private injectStyles(): void {
129
+ const css = this.generateCSS();
130
+ const styleEl = document.createElement('style');
131
+ styleEl.textContent = css;
132
+ this.root.appendChild(styleEl);
133
+ }
134
+
135
+ private generateCSS(): string {
136
+ const { backgroundColor, textColor, accentColor, font, position } = this.config;
137
+ const accentRgba = this.hexToRgba(accentColor, 0.22);
138
+ const accentFocusRgba = this.hexToRgba(accentColor, 0.15);
139
+
140
+ // Position-specific styles
141
+ const tabTransform = position === 'right'
142
+ ? 'translateY(-50%) rotate(180deg)'
143
+ : 'translateY(-50%)';
144
+ const tabBorderRadius = position === 'right'
145
+ ? '8px 0 0 8px'
146
+ : '0 8px 8px 0';
147
+ const tabRight = position === 'right' ? '0' : 'auto';
148
+ const tabLeft = position === 'left' ? '0' : 'auto';
149
+ const menuRight = position === 'right' ? '46px' : 'auto';
150
+ const menuLeft = position === 'left' ? '46px' : 'auto';
151
+
152
+ return `
153
+ :host { all: initial; }
154
+ * { box-sizing: border-box; font-family: ${font}; }
155
+
156
+ .fbw-tab {
157
+ position: fixed;
158
+ top: 50%;
159
+ ${position === 'right' ? 'right' : 'left'}: 0;
160
+ transform: ${tabTransform};
161
+ background: ${backgroundColor};
162
+ color: ${textColor};
163
+ writing-mode: vertical-rl;
164
+ text-orientation: mixed;
165
+ padding: 14px 9px;
166
+ border-radius: ${tabBorderRadius};
167
+ cursor: pointer;
168
+ font-size: 13px;
169
+ font-weight: 600;
170
+ letter-spacing: 0.03em;
171
+ box-shadow: ${position === 'right' ? '-2px' : '2px'} 0 10px rgba(0,0,0,0.18);
172
+ z-index: 2147483000;
173
+ border: none;
174
+ user-select: none;
175
+ transition: padding 0.12s ease, background 0.12s ease;
176
+ }
177
+
178
+ .fbw-tab:hover { padding-right: 13px; background: #1f2937; }
179
+ .fbw-tab:focus-visible { outline: 2px solid ${accentColor}; outline-offset: 2px; }
180
+
181
+ .fbw-menu {
182
+ position: fixed;
183
+ top: 50%;
184
+ right: ${menuRight};
185
+ left: ${menuLeft};
186
+ transform: translateY(-50%);
187
+ background: #fff;
188
+ border-radius: 10px;
189
+ box-shadow: 0 8px 30px rgba(0,0,0,0.22);
190
+ padding: 6px;
191
+ min-width: 220px;
192
+ z-index: 2147483001;
193
+ display: none;
194
+ border: 1px solid #e5e7eb;
195
+ }
196
+
197
+ .fbw-menu.fbw-open { display: block; }
198
+
199
+ .fbw-menu button {
200
+ display: block;
201
+ width: 100%;
202
+ text-align: left;
203
+ background: none;
204
+ border: none;
205
+ padding: 10px 12px;
206
+ font-size: 13.5px;
207
+ color: #111827;
208
+ border-radius: 6px;
209
+ cursor: pointer;
210
+ }
211
+
212
+ .fbw-menu button:hover { background: #f3f4f6; }
213
+ .fbw-menu button small { display: block; color: #6b7280; font-weight: 400; margin-top: 2px; font-size: 11.5px; }
214
+
215
+ .fbw-banner {
216
+ position: fixed;
217
+ top: 18px;
218
+ left: 50%;
219
+ transform: translateX(-50%);
220
+ background: ${backgroundColor};
221
+ color: ${textColor};
222
+ padding: 10px 10px 10px 16px;
223
+ border-radius: 999px;
224
+ font-size: 13px;
225
+ display: none;
226
+ align-items: center;
227
+ gap: 10px;
228
+ z-index: 2147483002;
229
+ box-shadow: 0 8px 24px rgba(0,0,0,0.25);
230
+ }
231
+
232
+ .fbw-banner.fbw-open { display: flex; }
233
+
234
+ .fbw-banner button {
235
+ background: rgba(255,255,255,0.12);
236
+ color: ${textColor};
237
+ border: none;
238
+ padding: 6px 12px;
239
+ border-radius: 999px;
240
+ font-size: 12px;
241
+ cursor: pointer;
242
+ }
243
+
244
+ .fbw-banner button:hover { background: rgba(255,255,255,0.22); }
245
+
246
+ .fbw-highlight {
247
+ position: fixed;
248
+ pointer-events: none;
249
+ border: 2px solid ${accentColor};
250
+ box-shadow: 0 0 0 4px ${accentRgba};
251
+ border-radius: 4px;
252
+ z-index: 2147483000;
253
+ display: none;
254
+ transition: top 0.06s ease, left 0.06s ease, width 0.06s ease, height 0.06s ease;
255
+ }
256
+
257
+ .fbw-overlay {
258
+ position: fixed;
259
+ inset: 0;
260
+ background: rgba(17,24,39,0.5);
261
+ display: none;
262
+ align-items: center;
263
+ justify-content: center;
264
+ z-index: 2147483003;
265
+ }
266
+
267
+ .fbw-overlay.fbw-open { display: flex; }
268
+
269
+ .fbw-modal {
270
+ background: #fff;
271
+ border-radius: 14px;
272
+ width: 420px;
273
+ max-width: 92vw;
274
+ max-height: 88vh;
275
+ overflow-y: auto;
276
+ padding: 22px;
277
+ box-shadow: 0 20px 60px rgba(0,0,0,0.35);
278
+ }
279
+
280
+ .fbw-modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; }
281
+ .fbw-modal-head h2 { font-size: 16px; margin: 0; color: #111827; font-weight: 700; }
282
+ .fbw-close { background: none; border: none; font-size: 18px; color: #6b7280; cursor: pointer; line-height: 1; padding: 4px; }
283
+ .fbw-close:hover { color: #111827; }
284
+
285
+ .fbw-field { margin-bottom: 14px; }
286
+ .fbw-field label { display: block; font-size: 12.5px; font-weight: 600; color: #374151; margin-bottom: 5px; }
287
+
288
+ .fbw-item-box {
289
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
290
+ font-size: 11.5px;
291
+ color: #1f2937;
292
+ background: #f3f4f6;
293
+ border: 1px solid #e5e7eb;
294
+ border-radius: 6px;
295
+ padding: 8px 10px;
296
+ word-break: break-all;
297
+ max-height: 60px;
298
+ overflow-y: auto;
299
+ }
300
+
301
+ .fbw-field textarea, .fbw-field input[type="email"], .fbw-field input[type="text"] {
302
+ width: 100%;
303
+ border: 1px solid #d1d5db;
304
+ border-radius: 8px;
305
+ padding: 9px 10px;
306
+ font-size: 13.5px;
307
+ color: #111827;
308
+ resize: vertical;
309
+ }
310
+
311
+ .fbw-field textarea:focus, .fbw-field input:focus {
312
+ outline: none;
313
+ border-color: ${accentColor};
314
+ box-shadow: 0 0 0 3px ${accentFocusRgba};
315
+ }
316
+
317
+ .fbw-error { color: #dc2626; font-size: 12px; margin: -6px 0 12px; display: none; }
318
+ .fbw-error.fbw-show { display: block; }
319
+
320
+ .fbw-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; }
321
+
322
+ .fbw-btn {
323
+ border: none;
324
+ border-radius: 8px;
325
+ padding: 9px 16px;
326
+ font-size: 13.5px;
327
+ font-weight: 600;
328
+ cursor: pointer;
329
+ }
330
+
331
+ .fbw-btn-primary { background: ${accentColor}; color: #fff; }
332
+ .fbw-btn-primary:hover { filter: brightness(1.08); }
333
+ .fbw-btn-ghost { background: none; color: #4b5563; }
334
+ .fbw-btn-ghost:hover { background: #f3f4f6; }
335
+
336
+ .fbw-toast {
337
+ position: fixed;
338
+ bottom: 22px;
339
+ right: 22px;
340
+ background: ${backgroundColor};
341
+ color: ${textColor};
342
+ padding: 11px 16px;
343
+ border-radius: 10px;
344
+ font-size: 13px;
345
+ z-index: 2147483004;
346
+ box-shadow: 0 8px 24px rgba(0,0,0,0.3);
347
+ opacity: 0;
348
+ transform: translateY(6px);
349
+ transition: opacity 0.18s ease, transform 0.18s ease;
350
+ pointer-events: none;
351
+ }
352
+
353
+ .fbw-toast.fbw-show { opacity: 1; transform: translateY(0); }
354
+ .fbw-hidden { display: none !important; }
355
+ `;
356
+ }
357
+
358
+ private hexToRgba(hex: string, alpha: number): string {
359
+ const h = hex.replace('#', '');
360
+ const expanded = h.length === 3
361
+ ? h.split('').map((c) => c + c).join('')
362
+ : h;
363
+ const r = parseInt(expanded.substring(0, 2), 16);
364
+ const g = parseInt(expanded.substring(2, 4), 16);
365
+ const b = parseInt(expanded.substring(4, 6), 16);
366
+ return `rgba(${r},${g},${b},${alpha})`;
367
+ }
368
+
369
+ // -------------------------------------------------------------------------
370
+ // Markup Creation
371
+ // -------------------------------------------------------------------------
372
+
373
+ private createMarkup(): void {
374
+ const wrap = document.createElement('div');
375
+ wrap.innerHTML = this.getMarkup();
376
+ this.root.appendChild(wrap);
377
+ }
378
+
379
+ private getMarkup(): string {
380
+ const { buttonLabel, widgetType } = this.config;
381
+
382
+ if (widgetType === 'chatbot') {
383
+ return this.getChatbotMarkup(buttonLabel);
384
+ }
385
+
386
+ return this.getDefaultMarkup(buttonLabel);
387
+ }
388
+
389
+ private getDefaultMarkup(buttonLabel: string): string {
390
+ return `
391
+ <button class="fbw-tab" type="button" aria-haspopup="true" aria-expanded="false">${this.escapeHtml(buttonLabel)}</button>
392
+ <div class="fbw-menu" role="menu">
393
+ <button type="button" data-action="pick-visible" role="menuitem">
394
+ Feedback on this page<small>Select any element you have feedback on</small>
395
+ </button>
396
+ <button type="button" data-action="pick-hidden" role="menuitem">
397
+ Quick feedback<small>General feedback on us</small>
398
+ </button>
399
+ </div>
400
+ <div class="fbw-banner">
401
+ <span>Click an element to select it &middot; Esc to cancel</span>
402
+ <button type="button" data-action="cancel-pick">Cancel</button>
403
+ </div>
404
+ <div class="fbw-highlight"></div>
405
+ <div class="fbw-overlay">
406
+ <div class="fbw-modal" role="dialog" aria-modal="true" aria-labelledby="fbw-modal-title">
407
+ <div class="fbw-modal-head">
408
+ <h2 id="fbw-modal-title">Share feedback</h2>
409
+ <button class="fbw-close" type="button" data-action="close-modal" aria-label="Close">&times;</button>
410
+ </div>
411
+ <form data-role="form">
412
+ <div class="fbw-field" data-role="item-field">
413
+ <label>Selected element</label>
414
+ <div class="fbw-item-box" data-role="item-box"></div>
415
+ </div>
416
+ <div class="fbw-field">
417
+ <label for="fbw-title">Title</label>
418
+ <input id="fbw-title" data-role="title" type="text" placeholder="Brief summary of your feedback" required />
419
+ </div>
420
+ <div class="fbw-field">
421
+ <label for="fbw-feedback">What's going on?</label>
422
+ <textarea id="fbw-feedback" data-role="feedback" rows="4" placeholder="Tell us what you noticed..."></textarea>
423
+ </div>
424
+ <div class="fbw-field">
425
+ <label for="fbw-email">Email</label>
426
+ <input id="fbw-email" data-role="email" type="email" placeholder="you@example.com" required />
427
+ </div>
428
+ <div class="fbw-error" data-role="error"></div>
429
+ <div class="fbw-actions">
430
+ <button type="button" class="fbw-btn fbw-btn-ghost" data-action="close-modal">Cancel</button>
431
+ <button type="submit" class="fbw-btn fbw-btn-primary">Submit</button>
432
+ </div>
433
+ </form>
434
+ </div>
435
+ </div>
436
+ <div class="fbw-toast" data-role="toast"></div>
437
+ `;
438
+ }
439
+
440
+ private getChatbotMarkup(buttonLabel: string): string {
441
+ // Placeholder for chatbot interface - can be expanded later
442
+ return `
443
+ <button class="fbw-tab" type="button" aria-haspopup="true" aria-expanded="false">${this.escapeHtml(buttonLabel)}</button>
444
+ <div class="fbw-menu" role="menu">
445
+ <button type="button" data-action="pick-visible" role="menuitem">
446
+ Feedback on this page<small>Select any element you have feedback on</small>
447
+ </button>
448
+ <button type="button" data-action="pick-hidden" role="menuitem">
449
+ Quick feedback<small>General feedback on us</small>
450
+ </button>
451
+ </div>
452
+ <div class="fbw-banner">
453
+ <span>Click an element to select it &middot; Esc to cancel</span>
454
+ <button type="button" data-action="cancel-pick">Cancel</button>
455
+ </div>
456
+ <div class="fbw-highlight"></div>
457
+ <div class="fbw-overlay">
458
+ <div class="fbw-modal" role="dialog" aria-modal="true" aria-labelledby="fbw-modal-title">
459
+ <div class="fbw-modal-head">
460
+ <h2 id="fbw-modal-title">Share feedback</h2>
461
+ <button class="fbw-close" type="button" data-action="close-modal" aria-label="Close">&times;</button>
462
+ </div>
463
+ <form data-role="form">
464
+ <div class="fbw-field" data-role="item-field">
465
+ <label>Selected element</label>
466
+ <div class="fbw-item-box" data-role="item-box"></div>
467
+ </div>
468
+ <div class="fbw-field">
469
+ <label for="fbw-title">Title</label>
470
+ <input id="fbw-title" data-role="title" type="text" placeholder="Brief summary of your feedback" required />
471
+ </div>
472
+ <div class="fbw-field">
473
+ <label for="fbw-feedback">What's going on?</label>
474
+ <textarea id="fbw-feedback" data-role="feedback" rows="4" placeholder="Tell us what you noticed..."></textarea>
475
+ </div>
476
+ <div class="fbw-field">
477
+ <label for="fbw-email">Email</label>
478
+ <input id="fbw-email" data-role="email" type="email" placeholder="you@example.com" required />
479
+ </div>
480
+ <div class="fbw-error" data-role="error"></div>
481
+ <div class="fbw-actions">
482
+ <button type="button" class="fbw-btn fbw-btn-ghost" data-action="close-modal">Cancel</button>
483
+ <button type="submit" class="fbw-btn fbw-btn-primary">Submit</button>
484
+ </div>
485
+ </form>
486
+ </div>
487
+ </div>
488
+ <div class="fbw-toast" data-role="toast"></div>
489
+ `;
490
+ }
491
+
492
+ private escapeHtml(s: string): string {
493
+ const d = document.createElement('div');
494
+ d.textContent = s;
495
+ return d.innerHTML;
496
+ }
497
+
498
+ // -------------------------------------------------------------------------
499
+ // Element Caching
500
+ // -------------------------------------------------------------------------
501
+
502
+ private cacheElements(): void {
503
+ this.elements = {
504
+ tab: this.root.querySelector('.fbw-tab')!,
505
+ menu: this.root.querySelector('.fbw-menu')!,
506
+ banner: this.root.querySelector('.fbw-banner')!,
507
+ highlight: this.root.querySelector('.fbw-highlight')!,
508
+ overlay: this.root.querySelector('.fbw-overlay')!,
509
+ modal: this.root.querySelector('.fbw-modal')!,
510
+ form: this.root.querySelector('[data-role="form"]')!,
511
+ itemField: this.root.querySelector('[data-role="item-field"]')!,
512
+ itemBox: this.root.querySelector('[data-role="item-box"]')!,
513
+ title: this.root.querySelector('[data-role="title"]')!,
514
+ feedback: this.root.querySelector('[data-role="feedback"]')!,
515
+ email: this.root.querySelector('[data-role="email"]')!,
516
+ error: this.root.querySelector('[data-role="error"]')!,
517
+ toast: this.root.querySelector('[data-role="toast"]')!
518
+ };
519
+ }
520
+
521
+ // -------------------------------------------------------------------------
522
+ // Event Listeners
523
+ // -------------------------------------------------------------------------
524
+
525
+ private attachEventListeners(): void {
526
+ this.elements.tab.addEventListener('click', () => this.onTabClick());
527
+ this.elements.menu.addEventListener('click', (e) => this.onMenuClick(e));
528
+ this.elements.banner.addEventListener('click', (e) => this.onBannerClick(e));
529
+ this.elements.overlay.addEventListener('click', (e) => this.onOverlayClick(e));
530
+ this.elements.form.addEventListener('submit', (e) => this.onSubmit(e));
531
+ }
532
+
533
+ // -------------------------------------------------------------------------
534
+ // Menu Handlers
535
+ // -------------------------------------------------------------------------
536
+
537
+ private onTabClick(): void {
538
+ this.state === 'menu' ? this.closeMenu() : this.openMenu();
539
+ }
540
+
541
+ private openMenu(): void {
542
+ this.state = 'menu';
543
+ this.elements.menu.classList.add('fbw-open');
544
+ this.elements.tab.setAttribute('aria-expanded', 'true');
545
+ document.addEventListener('click', this.onOutsideMenuClick, true);
546
+ }
547
+
548
+ private closeMenu(): void {
549
+ if (this.state === 'menu') this.state = 'idle';
550
+ this.elements.menu.classList.remove('fbw-open');
551
+ this.elements.tab.setAttribute('aria-expanded', 'false');
552
+ document.removeEventListener('click', this.onOutsideMenuClick, true);
553
+ }
554
+
555
+ private onOutsideMenuClick = (e: Event): void => {
556
+ if (!this.isInsideWidget(e.target as HTMLElement)) this.closeMenu();
557
+ };
558
+
559
+ private onMenuClick(e: Event): void {
560
+ const btn = (e.target as HTMLElement).closest('button[data-action]');
561
+ if (!btn) return;
562
+
563
+ const action = btn.getAttribute('data-action');
564
+ if (action === 'pick-visible') this.startPicking(true);
565
+ if (action === 'pick-hidden') {
566
+ this.showItemInForm = false;
567
+ this.closeMenu();
568
+ this.openModal();
569
+ }
570
+ }
571
+
572
+ // -------------------------------------------------------------------------
573
+ // Picking Mode
574
+ // -------------------------------------------------------------------------
575
+
576
+ private startPicking(showItem: boolean): void {
577
+ this.showItemInForm = showItem;
578
+ this.closeMenu();
579
+ this.state = 'picking';
580
+ this.elements.banner.classList.add('fbw-open');
581
+ document.addEventListener('mousemove', this.onHoverMove, true);
582
+ document.addEventListener('click', this.onDocumentClickCapture, true);
583
+ document.addEventListener('keydown', this.onKeyDownCapture, true);
584
+ document.addEventListener('scroll', this.onScrollOrResize, true);
585
+ window.addEventListener('resize', this.onScrollOrResize, true);
586
+ }
587
+
588
+ private stopPicking(): void {
589
+ this.elements.banner.classList.remove('fbw-open');
590
+ document.removeEventListener('mousemove', this.onHoverMove, true);
591
+ document.removeEventListener('scroll', this.onScrollOrResize, true);
592
+ window.removeEventListener('resize', this.onScrollOrResize, true);
593
+ }
594
+
595
+ private onBannerClick(e: Event): void {
596
+ if ((e.target as HTMLElement).closest('[data-action="cancel-pick"]')) {
597
+ this.cancelAll();
598
+ }
599
+ }
600
+
601
+ private onHoverMove = (e: MouseEvent): void => {
602
+ if (this.isInsideWidget(e.target as HTMLElement)) return;
603
+ if (this.hoverRafId) cancelAnimationFrame(this.hoverRafId);
604
+ this.hoverRafId = requestAnimationFrame(() => {
605
+ this.positionHighlight(e.target as Element);
606
+ });
607
+ };
608
+
609
+ private positionHighlight(target: Element): void {
610
+ const r = target.getBoundingClientRect();
611
+ this.elements.highlight.style.display = 'block';
612
+ this.elements.highlight.style.top = `${r.top}px`;
613
+ this.elements.highlight.style.left = `${r.left}px`;
614
+ this.elements.highlight.style.width = `${r.width}px`;
615
+ this.elements.highlight.style.height = `${r.height}px`;
616
+ }
617
+
618
+ private onScrollOrResize = (): void => {
619
+ if (this.selectedEl && this.state === 'review') {
620
+ this.positionHighlight(this.selectedEl);
621
+ }
622
+ };
623
+
624
+ private onDocumentClickCapture = (e: Event): void => {
625
+ if (this.isInsideWidget(e.target as HTMLElement)) return;
626
+ e.preventDefault();
627
+ e.stopPropagation();
628
+ if (typeof (e as any).stopImmediatePropagation === 'function') {
629
+ (e as any).stopImmediatePropagation();
630
+ }
631
+
632
+ if (this.state === 'picking') {
633
+ this.finalizeSelection(e.target as Element);
634
+ }
635
+ };
636
+
637
+ private onKeyDownCapture = (e: KeyboardEvent): void => {
638
+ if (e.key === 'Escape') {
639
+ e.preventDefault();
640
+ this.cancelAll();
641
+ }
642
+ };
643
+
644
+ private finalizeSelection(target: Element): void {
645
+ this.selectedEl = target;
646
+ this.selectedSelector = this.getUniqueSelector(target);
647
+ this.stopPicking();
648
+ this.positionHighlight(target);
649
+ this.openModal();
650
+ }
651
+
652
+ // -------------------------------------------------------------------------
653
+ // Unique Selector Generation
654
+ // -------------------------------------------------------------------------
655
+
656
+ private getUniqueSelector(node: Node): string | null {
657
+ if (!(node instanceof Element)) return null;
658
+
659
+ if (node.id) {
660
+ const idSel = `#${this.cssEscape(node.id)}`;
661
+ if (this.safeQueryCount(idSel) === 1) return idSel;
662
+ }
663
+
664
+ const parts: string[] = [];
665
+ let current: Element | null = node;
666
+
667
+ while (current && current.nodeType === 1 && current !== document.documentElement) {
668
+ let part = current.tagName.toLowerCase();
669
+
670
+ if (current.id) {
671
+ part = `#${this.cssEscape(current.id)}`;
672
+ parts.unshift(part);
673
+ break;
674
+ }
675
+
676
+ const classes = Array.from(current.classList).filter((c) => !!c);
677
+ if (classes.length) {
678
+ part += '.' + classes.map(this.cssEscape).join('.');
679
+ }
680
+
681
+ const parent: Element | null = current.parentElement;
682
+ if (parent) {
683
+ const sameTagSiblings = Array.from(parent.children).filter(
684
+ (s: Element) => s.tagName === current!.tagName
685
+ );
686
+ if (sameTagSiblings.length > 1) {
687
+ const idx = sameTagSiblings.indexOf(current!) + 1;
688
+ part += `:nth-of-type(${idx})`;
689
+ }
690
+ }
691
+
692
+ parts.unshift(part);
693
+
694
+ const testSelector = parts.join(' > ');
695
+ if (this.safeQueryCount(testSelector) === 1) return testSelector;
696
+
697
+ current = parent || null;
698
+ }
699
+
700
+ return parts.join(' > ');
701
+ }
702
+
703
+ private cssEscape(str: string): string {
704
+ if (window.CSS && (window.CSS as any).escape) {
705
+ return (window.CSS as any).escape(str);
706
+ }
707
+ return String(str).replace(/([ #.;?%&,.+*~':"!^$[\]()=>|/])/g, '\\$1');
708
+ }
709
+
710
+ private safeQueryCount(selector: string): number {
711
+ try {
712
+ return document.querySelectorAll(selector).length;
713
+ } catch (err) {
714
+ return -1;
715
+ }
716
+ }
717
+
718
+ // -------------------------------------------------------------------------
719
+ // Modal Handlers
720
+ // -------------------------------------------------------------------------
721
+
722
+ private openModal(): void {
723
+ this.state = 'review';
724
+ this.elements.error.classList.remove('fbw-show');
725
+ this.elements.form.reset();
726
+
727
+ if (this.showItemInForm) {
728
+ this.elements.itemField.classList.remove('fbw-hidden');
729
+ this.elements.itemBox.textContent = this.selectedSelector || '(none)';
730
+ } else {
731
+ this.elements.itemField.classList.add('fbw-hidden');
732
+ }
733
+
734
+ this.elements.overlay.classList.add('fbw-open');
735
+ setTimeout(() => this.elements.feedback.focus(), 30);
736
+ }
737
+
738
+ private closeModal(): void {
739
+ this.elements.overlay.classList.remove('fbw-open');
740
+ }
741
+
742
+ private cancelAll(): void {
743
+ this.stopPicking();
744
+ this.closeModal();
745
+ this.elements.highlight.style.display = 'none';
746
+ document.removeEventListener('click', this.onDocumentClickCapture, true);
747
+ document.removeEventListener('keydown', this.onKeyDownCapture, true);
748
+ this.selectedEl = null;
749
+ this.selectedSelector = null;
750
+ this.state = 'idle';
751
+ }
752
+
753
+ private onOverlayClick(e: Event): void {
754
+ const actionBtn = (e.target as HTMLElement).closest('[data-action="close-modal"]');
755
+ if (actionBtn) this.cancelAll();
756
+ }
757
+
758
+ // -------------------------------------------------------------------------
759
+ // Form Submission
760
+ // -------------------------------------------------------------------------
761
+
762
+ private onSubmit(e: Event): void {
763
+ e.preventDefault();
764
+ const title = this.elements.title.value.trim();
765
+ const feedback = this.elements.feedback.value.trim();
766
+ const email = this.elements.email.value.trim();
767
+ const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
768
+
769
+ if (!title || !emailOk) {
770
+ this.elements.error.textContent = !title
771
+ ? 'Please add a title before submitting.'
772
+ : 'Please enter a valid email address.';
773
+ this.elements.error.classList.add('fbw-show');
774
+ return;
775
+ }
776
+
777
+ const payload: FeedbackPayload = {
778
+ optionType: this.showItemInForm ? 'page_item_visible' : 'page_item_hidden',
779
+ elementSelector: this.selectedSelector,
780
+ pageUrl: window.location.href,
781
+ pageTitle: document.title,
782
+ title,
783
+ feedback,
784
+ email,
785
+ submittedAt: new Date().toISOString()
786
+ };
787
+
788
+ this.submitFeedback(payload);
789
+ }
790
+
791
+ private prepareMessageBody(payload: FeedbackPayload): FeedbackMessageBody {
792
+ const user_handle = payload.email;
793
+ const feedbackTitle = payload.title;
794
+ const feedbackBody = payload.feedback || '(No additional details provided)';
795
+ const pageTitle = payload.pageTitle;
796
+ const message = `${feedbackBody}\n\nPage: ${pageTitle}\nURL: ${payload.pageUrl}\nSelector: ${payload.elementSelector}\nOption: ${payload.optionType}\nSubmitted: ${payload.submittedAt}`;
797
+
798
+
799
+ return {
800
+ title: feedbackTitle,
801
+ body: message,
802
+ user_handle: user_handle
803
+ };
804
+ }
805
+
806
+ private submitFeedback(payload: FeedbackPayload): void {
807
+ window.dispatchEvent(new CustomEvent('feedbackwidget:submit', { detail: payload }));
808
+
809
+ if (this.apiKey) {
810
+ const messageBody = this.prepareMessageBody(payload);
811
+ fetch(this.endPoint, {
812
+ method: 'POST',
813
+ headers: {
814
+ 'Content-Type': 'application/json',
815
+ 'Authorization': `Bearer ${this.apiKey}`
816
+ },
817
+ body: JSON.stringify(messageBody)
818
+ }).catch(() => {
819
+ // Swallow network errors, UX already confirmed below
820
+ });
821
+ }
822
+
823
+ this.cancelAll();
824
+ this.showToast('Thanks for the feedback!');
825
+ }
826
+
827
+ private showToast(message: string): void {
828
+ this.elements.toast.textContent = message;
829
+ this.elements.toast.classList.add('fbw-show');
830
+ setTimeout(() => this.elements.toast.classList.remove('fbw-show'), 2400);
831
+ }
832
+
833
+ // -------------------------------------------------------------------------
834
+ // Helper Methods
835
+ // -------------------------------------------------------------------------
836
+
837
+ private isInsideWidget(target: HTMLElement): boolean {
838
+ return target === this.host || this.host.contains(target);
839
+ }
840
+
841
+ // -------------------------------------------------------------------------
842
+ // Public API
843
+ // -------------------------------------------------------------------------
844
+
845
+ public open(mode: 'visible' | 'hidden' = 'visible'): void {
846
+ this.startPicking(mode === 'visible');
847
+ }
848
+
849
+ public close(): void {
850
+ this.cancelAll();
851
+ }
852
+
853
+ public destroy(): void {
854
+ this.cancelAll();
855
+ this.host.remove();
856
+ }
857
+ }
858
+
859
+ // ============================================================================
860
+ // Export
861
+ // ============================================================================
862
+
863
+ export { FeedbackWidget };
864
+ export type { FeedbackWidgetConfig, FeedbackPayload, WidgetPosition, WidgetType };