@matija2209/payload-plugin-admin-feedback 1.0.0 → 1.0.4

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.
@@ -1,1438 +0,0 @@
1
- 'use client';
2
-
3
- import React from 'react';
4
-
5
- type CapturePolicy = 'current-tab-first' | 'strict-current-tab' | 'any-surface';
6
-
7
- type SubmitPayload = {
8
- message: string;
9
- pagePath: string;
10
- selector?: string;
11
- selectedText?: string;
12
- screenshotId?: number | null;
13
- meta?: {
14
- userAgent?: string;
15
- locale?: string;
16
- viewport?: string;
17
- };
18
- };
19
-
20
- type SubmitResult = { success: true } | { success: false; error: string };
21
- type UploadResult = { success: true; mediaId: number } | { success: false; error: string };
22
- type DeleteResult = { success: true } | { success: false; error: string };
23
-
24
- type FeedbackWidgetProps = {
25
- title?: string;
26
- submitLabel?: string;
27
- uploadLabel?: string;
28
- allowScreenshotUpload?: boolean;
29
- screenshotMaxFileSizeBytes?: number;
30
- screenshotAllowedMimeTypes?: string[];
31
- capturePolicy?: CapturePolicy;
32
- onSubmit: (payload: SubmitPayload) => Promise<SubmitResult>;
33
- onUpload?: (formData: FormData) => Promise<UploadResult>;
34
- onDeleteScreenshot?: (mediaId: number) => Promise<DeleteResult>;
35
- };
36
-
37
- type CaptureData = {
38
- selector: string;
39
- selectedText: string;
40
- };
41
-
42
- type AnnotationPoint = {
43
- x: number;
44
- y: number;
45
- };
46
-
47
- type AnnotationStyle = {
48
- color: string;
49
- size: number;
50
- };
51
-
52
- type PenOperation = {
53
- id: string;
54
- type: 'pen';
55
- style: AnnotationStyle;
56
- points: AnnotationPoint[];
57
- };
58
-
59
- type RectangleOperation = {
60
- id: string;
61
- type: 'rectangle';
62
- style: AnnotationStyle;
63
- start: AnnotationPoint;
64
- end: AnnotationPoint;
65
- };
66
-
67
- type ArrowOperation = {
68
- id: string;
69
- type: 'arrow';
70
- style: AnnotationStyle;
71
- start: AnnotationPoint;
72
- end: AnnotationPoint;
73
- };
74
-
75
- type TextOperation = {
76
- id: string;
77
- type: 'text';
78
- style: AnnotationStyle;
79
- point: AnnotationPoint;
80
- text: string;
81
- };
82
-
83
- type AnnotationOperation = PenOperation | RectangleOperation | ArrowOperation | TextOperation;
84
- type DrawableDraftOperation = PenOperation | RectangleOperation | ArrowOperation;
85
- type AnnotationTool = AnnotationOperation['type'];
86
-
87
- type EditorImage = {
88
- element: HTMLImageElement;
89
- fileName: string;
90
- height: number;
91
- src: string;
92
- width: number;
93
- };
94
-
95
- type EditorHistory = {
96
- operations: AnnotationOperation[];
97
- redoStack: AnnotationOperation[][];
98
- undoStack: AnnotationOperation[][];
99
- };
100
-
101
- type ExtendedDisplayMediaStreamOptions = DisplayMediaStreamOptions & {
102
- preferCurrentTab?: boolean;
103
- selfBrowserSurface?: 'include' | 'exclude';
104
- surfaceSwitching?: 'include' | 'exclude';
105
- };
106
-
107
- type ExtendedMediaTrackSettings = MediaTrackSettings & {
108
- displaySurface?: string;
109
- };
110
-
111
- const DEFAULT_COLORS = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6', '#a855f7'];
112
- const DEFAULT_HISTORY: EditorHistory = {
113
- operations: [],
114
- redoStack: [],
115
- undoStack: [],
116
- };
117
-
118
- const createOperationId = (): string =>
119
- `annotation-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
120
-
121
- const getCssSelector = (element: Element): string => {
122
- if (element.id) {
123
- return `#${element.id}`;
124
- }
125
-
126
- const parts: string[] = [];
127
- let current: Element | null = element;
128
- while (current && current.nodeType === Node.ELEMENT_NODE && current !== document.body) {
129
- let part = current.tagName.toLowerCase();
130
- const className = current.className;
131
- if (typeof className === 'string') {
132
- const firstClass = className
133
- .split(' ')
134
- .map((value) => value.trim())
135
- .filter(Boolean)[0];
136
- if (firstClass) {
137
- part += `.${firstClass}`;
138
- }
139
- }
140
-
141
- const parent = current.parentElement;
142
- if (parent) {
143
- const siblings = Array.from(parent.children).filter(
144
- (candidate) => candidate.tagName === current?.tagName,
145
- );
146
- if (siblings.length > 1) {
147
- const index = siblings.indexOf(current);
148
- part += `:nth-of-type(${index + 1})`;
149
- }
150
- }
151
-
152
- parts.unshift(part);
153
- current = current.parentElement;
154
- }
155
-
156
- return parts.join(' > ');
157
- };
158
-
159
- const fileToDataUrl = async (file: File): Promise<string> =>
160
- new Promise((resolve, reject) => {
161
- const reader = new FileReader();
162
- reader.onload = () => {
163
- if (typeof reader.result === 'string') {
164
- resolve(reader.result);
165
- return;
166
- }
167
-
168
- reject(new Error('Unsupported image format.'));
169
- };
170
- reader.onerror = () => reject(new Error('Could not read image.'));
171
- reader.readAsDataURL(file);
172
- });
173
-
174
- const loadImage = async (src: string): Promise<HTMLImageElement> =>
175
- new Promise((resolve, reject) => {
176
- const image = new Image();
177
- image.onload = () => resolve(image);
178
- image.onerror = () => reject(new Error('Could not load image.'));
179
- image.src = src;
180
- });
181
-
182
- const createEditorImage = async (file: File): Promise<EditorImage> => {
183
- const src = await fileToDataUrl(file);
184
- const element = await loadImage(src);
185
-
186
- return {
187
- element,
188
- fileName: file.name,
189
- height: element.naturalHeight || element.height,
190
- src,
191
- width: element.naturalWidth || element.width,
192
- };
193
- };
194
-
195
- const canvasToFile = async (
196
- canvas: HTMLCanvasElement,
197
- fileName = `feedback-${Date.now()}.png`,
198
- ): Promise<File> => {
199
- const blob = await new Promise<Blob | null>((resolve) => {
200
- canvas.toBlob((nextBlob) => resolve(nextBlob), 'image/png');
201
- });
202
-
203
- if (!blob) {
204
- throw new Error('Failed to prepare annotated screenshot.');
205
- }
206
-
207
- return new File([blob], fileName.replace(/\.[a-z0-9]+$/i, '') + '.png', { type: 'image/png' });
208
- };
209
-
210
- const waitForRenderedVideoFrame = async (video: HTMLVideoElement): Promise<void> => {
211
- if ('requestVideoFrameCallback' in video) {
212
- await new Promise<void>((resolve) => {
213
- (
214
- video as HTMLVideoElement & {
215
- requestVideoFrameCallback: (callback: () => void) => number;
216
- }
217
- ).requestVideoFrameCallback(() => resolve());
218
- });
219
- return;
220
- }
221
-
222
- await new Promise<void>((resolve) => {
223
- window.requestAnimationFrame(() => resolve());
224
- });
225
- };
226
-
227
- const captureScreenshotFile = async (
228
- capturePolicy: CapturePolicy,
229
- ): Promise<{ file: File; surface: string | null }> => {
230
- if (!navigator.mediaDevices?.getDisplayMedia) {
231
- throw new Error('Browser does not support screen capture.');
232
- }
233
-
234
- const options: ExtendedDisplayMediaStreamOptions =
235
- capturePolicy === 'any-surface'
236
- ? {
237
- video: true,
238
- audio: false,
239
- }
240
- : {
241
- video: {
242
- displaySurface: 'browser' as const,
243
- },
244
- audio: false,
245
- preferCurrentTab: true,
246
- selfBrowserSurface: 'include',
247
- surfaceSwitching: 'exclude',
248
- };
249
-
250
- const stream = await navigator.mediaDevices.getDisplayMedia(options);
251
- const track = stream.getVideoTracks()[0];
252
- if (!track) {
253
- stream.getTracks().forEach((item) => item.stop());
254
- throw new Error('Screen capture failed.');
255
- }
256
-
257
- const settings = track.getSettings() as ExtendedMediaTrackSettings;
258
- const surface = typeof settings.displaySurface === 'string' ? settings.displaySurface : null;
259
-
260
- if (capturePolicy === 'strict-current-tab' && surface !== 'browser') {
261
- stream.getTracks().forEach((item) => item.stop());
262
- throw new Error('Please share the current browser tab to capture a screenshot.');
263
- }
264
-
265
- const video = document.createElement('video');
266
-
267
- try {
268
- video.srcObject = stream;
269
- video.muted = true;
270
- video.playsInline = true;
271
- await video.play();
272
- await waitForRenderedVideoFrame(video);
273
-
274
- const width = video.videoWidth || window.innerWidth;
275
- const height = video.videoHeight || window.innerHeight;
276
- if (!width || !height) {
277
- throw new Error('Screen capture failed.');
278
- }
279
-
280
- const canvas = document.createElement('canvas');
281
- canvas.width = width;
282
- canvas.height = height;
283
-
284
- const context = canvas.getContext('2d');
285
- if (!context) {
286
- throw new Error('Browser does not support canvas context.');
287
- }
288
-
289
- context.drawImage(video, 0, 0, width, height);
290
-
291
- return {
292
- file: await canvasToFile(canvas),
293
- surface,
294
- };
295
- } finally {
296
- video.pause();
297
- video.srcObject = null;
298
- stream.getTracks().forEach((item) => item.stop());
299
- }
300
- };
301
-
302
- const getCanvasPoint = (
303
- event: React.PointerEvent<HTMLCanvasElement>,
304
- canvas: HTMLCanvasElement,
305
- ): AnnotationPoint => {
306
- const bounds = canvas.getBoundingClientRect();
307
- const scaleX = bounds.width === 0 ? 1 : canvas.width / bounds.width;
308
- const scaleY = bounds.height === 0 ? 1 : canvas.height / bounds.height;
309
-
310
- return {
311
- x: (event.clientX - bounds.left) * scaleX,
312
- y: (event.clientY - bounds.top) * scaleY,
313
- };
314
- };
315
-
316
- const drawPenOperation = (
317
- context: CanvasRenderingContext2D,
318
- operation: PenOperation,
319
- ): void => {
320
- if (operation.points.length === 0) {
321
- return;
322
- }
323
-
324
- context.save();
325
- context.strokeStyle = operation.style.color;
326
- context.lineWidth = operation.style.size;
327
- context.lineCap = 'round';
328
- context.lineJoin = 'round';
329
- context.beginPath();
330
- context.moveTo(operation.points[0].x, operation.points[0].y);
331
-
332
- for (const point of operation.points.slice(1)) {
333
- context.lineTo(point.x, point.y);
334
- }
335
-
336
- if (operation.points.length === 1) {
337
- const point = operation.points[0];
338
- context.lineTo(point.x + 0.01, point.y + 0.01);
339
- }
340
-
341
- context.stroke();
342
- context.restore();
343
- };
344
-
345
- const drawRectangleOperation = (
346
- context: CanvasRenderingContext2D,
347
- operation: RectangleOperation,
348
- ): void => {
349
- const left = Math.min(operation.start.x, operation.end.x);
350
- const top = Math.min(operation.start.y, operation.end.y);
351
- const width = Math.abs(operation.end.x - operation.start.x);
352
- const height = Math.abs(operation.end.y - operation.start.y);
353
-
354
- context.save();
355
- context.strokeStyle = operation.style.color;
356
- context.lineWidth = operation.style.size;
357
- context.strokeRect(left, top, width, height);
358
- context.restore();
359
- };
360
-
361
- const drawArrowOperation = (
362
- context: CanvasRenderingContext2D,
363
- operation: ArrowOperation,
364
- ): void => {
365
- const angle = Math.atan2(operation.end.y - operation.start.y, operation.end.x - operation.start.x);
366
- const headLength = Math.max(14, operation.style.size * 4);
367
-
368
- context.save();
369
- context.strokeStyle = operation.style.color;
370
- context.fillStyle = operation.style.color;
371
- context.lineWidth = operation.style.size;
372
- context.lineCap = 'round';
373
- context.lineJoin = 'round';
374
- context.beginPath();
375
- context.moveTo(operation.start.x, operation.start.y);
376
- context.lineTo(operation.end.x, operation.end.y);
377
- context.stroke();
378
-
379
- context.beginPath();
380
- context.moveTo(operation.end.x, operation.end.y);
381
- context.lineTo(
382
- operation.end.x - headLength * Math.cos(angle - Math.PI / 6),
383
- operation.end.y - headLength * Math.sin(angle - Math.PI / 6),
384
- );
385
- context.lineTo(
386
- operation.end.x - headLength * Math.cos(angle + Math.PI / 6),
387
- operation.end.y - headLength * Math.sin(angle + Math.PI / 6),
388
- );
389
- context.closePath();
390
- context.fill();
391
- context.restore();
392
- };
393
-
394
- const drawTextOperation = (
395
- context: CanvasRenderingContext2D,
396
- operation: TextOperation,
397
- ): void => {
398
- const fontSize = Math.max(16, operation.style.size * 6);
399
-
400
- context.save();
401
- context.fillStyle = operation.style.color;
402
- context.font = `600 ${fontSize}px ui-sans-serif, system-ui, sans-serif`;
403
- context.textBaseline = 'top';
404
- context.fillText(operation.text, operation.point.x, operation.point.y);
405
- context.restore();
406
- };
407
-
408
- const drawOperation = (
409
- context: CanvasRenderingContext2D,
410
- operation: AnnotationOperation,
411
- ): void => {
412
- switch (operation.type) {
413
- case 'pen':
414
- drawPenOperation(context, operation);
415
- return;
416
- case 'rectangle':
417
- drawRectangleOperation(context, operation);
418
- return;
419
- case 'arrow':
420
- drawArrowOperation(context, operation);
421
- return;
422
- case 'text':
423
- drawTextOperation(context, operation);
424
- return;
425
- }
426
- };
427
-
428
- const isShapeMeaningful = (start: AnnotationPoint, end: AnnotationPoint): boolean =>
429
- Math.abs(end.x - start.x) > 3 || Math.abs(end.y - start.y) > 3;
430
-
431
- export function FeedbackWidget({
432
- title = 'Admin feedback',
433
- submitLabel = 'Send',
434
- uploadLabel = 'Upload image',
435
- allowScreenshotUpload = true,
436
- screenshotMaxFileSizeBytes = 5 * 1024 * 1024,
437
- screenshotAllowedMimeTypes = ['image/png', 'image/jpeg', 'image/webp'],
438
- capturePolicy = 'current-tab-first',
439
- onSubmit,
440
- onUpload,
441
- onDeleteScreenshot,
442
- }: FeedbackWidgetProps) {
443
- const [open, setOpen] = React.useState(false);
444
- const [message, setMessage] = React.useState('');
445
- const [captureMode, setCaptureMode] = React.useState(false);
446
- const [captureData, setCaptureData] = React.useState<CaptureData | null>(null);
447
- const [screenshotId, setScreenshotId] = React.useState<number | null>(null);
448
- const [screenshotPreviewUrl, setScreenshotPreviewUrl] = React.useState<string | null>(null);
449
- const [uploading, setUploading] = React.useState(false);
450
- const [deletingScreenshot, setDeletingScreenshot] = React.useState(false);
451
- const [submitting, setSubmitting] = React.useState(false);
452
- const [error, setError] = React.useState<string | null>(null);
453
- const [notice, setNotice] = React.useState<string | null>(null);
454
- const [annotating, setAnnotating] = React.useState(false);
455
- const [editorImage, setEditorImage] = React.useState<EditorImage | null>(null);
456
- const [editorHistory, setEditorHistory] = React.useState<EditorHistory>(DEFAULT_HISTORY);
457
- const [draftOperation, setDraftOperation] = React.useState<DrawableDraftOperation | null>(null);
458
- const [annotationTool, setAnnotationTool] = React.useState<AnnotationTool>('pen');
459
- const [annotationColor, setAnnotationColor] = React.useState(DEFAULT_COLORS[0]);
460
- const [annotationSize, setAnnotationSize] = React.useState(4);
461
- const [annotationText, setAnnotationText] = React.useState('');
462
- const hoverTargetRef = React.useRef<Element | null>(null);
463
- const annotationCanvasRef = React.useRef<HTMLCanvasElement | null>(null);
464
- const pointerIdRef = React.useRef<number | null>(null);
465
- const draftOperationRef = React.useRef<DrawableDraftOperation | null>(null);
466
-
467
- React.useEffect(() => {
468
- draftOperationRef.current = draftOperation;
469
- }, [draftOperation]);
470
-
471
- React.useEffect(() => {
472
- if (!captureMode) {
473
- return;
474
- }
475
-
476
- const clearOutline = (): void => {
477
- if (hoverTargetRef.current instanceof HTMLElement) {
478
- hoverTargetRef.current.style.outline = '';
479
- }
480
- hoverTargetRef.current = null;
481
- };
482
-
483
- const onMouseMove = (event: MouseEvent): void => {
484
- const target = event.target;
485
- if (!(target instanceof HTMLElement)) {
486
- return;
487
- }
488
-
489
- if (hoverTargetRef.current !== target) {
490
- clearOutline();
491
- target.style.outline = '2px dashed #22c55e';
492
- hoverTargetRef.current = target;
493
- }
494
- };
495
-
496
- const onClick = (event: MouseEvent): void => {
497
- event.preventDefault();
498
- event.stopPropagation();
499
- const target = event.target;
500
- if (!(target instanceof HTMLElement)) {
501
- return;
502
- }
503
-
504
- setCaptureData({
505
- selector: getCssSelector(target),
506
- selectedText: target.textContent?.trim().slice(0, 200) || '',
507
- });
508
- clearOutline();
509
- setCaptureMode(false);
510
- };
511
-
512
- document.addEventListener('mousemove', onMouseMove, true);
513
- document.addEventListener('click', onClick, true);
514
-
515
- return () => {
516
- clearOutline();
517
- document.removeEventListener('mousemove', onMouseMove, true);
518
- document.removeEventListener('click', onClick, true);
519
- };
520
- }, [captureMode]);
521
-
522
- React.useEffect(() => {
523
- if (!annotating) {
524
- return;
525
- }
526
-
527
- const previousOverflow = document.body.style.overflow;
528
- document.body.style.overflow = 'hidden';
529
-
530
- return () => {
531
- document.body.style.overflow = previousOverflow;
532
- };
533
- }, [annotating]);
534
-
535
- React.useEffect(() => {
536
- if (!annotating || !editorImage || !annotationCanvasRef.current) {
537
- return;
538
- }
539
-
540
- const canvas = annotationCanvasRef.current;
541
- canvas.width = editorImage.width;
542
- canvas.height = editorImage.height;
543
-
544
- const context = canvas.getContext('2d');
545
- if (!context) {
546
- setError('Browser does not support canvas context.');
547
- return;
548
- }
549
-
550
- context.clearRect(0, 0, canvas.width, canvas.height);
551
- context.drawImage(editorImage.element, 0, 0, canvas.width, canvas.height);
552
-
553
- for (const operation of editorHistory.operations) {
554
- drawOperation(context, operation);
555
- }
556
-
557
- if (draftOperation) {
558
- drawOperation(context, draftOperation);
559
- }
560
- }, [annotating, draftOperation, editorHistory.operations, editorImage]);
561
-
562
- const validateImageFile = React.useCallback(
563
- (file: File): string | null => {
564
- if (!screenshotAllowedMimeTypes.includes(file.type)) {
565
- return `Supported image types: ${screenshotAllowedMimeTypes.join(', ')}`;
566
- }
567
-
568
- if (file.size > screenshotMaxFileSizeBytes) {
569
- return `Image is too large. Maximum size: ${Math.round(screenshotMaxFileSizeBytes / 1024 / 1024)}MB.`;
570
- }
571
-
572
- return null;
573
- },
574
- [screenshotAllowedMimeTypes, screenshotMaxFileSizeBytes],
575
- );
576
-
577
- const uploadImageFile = React.useCallback(
578
- async (file: File): Promise<boolean> => {
579
- if (!onUpload) {
580
- return false;
581
- }
582
-
583
- setError(null);
584
- setUploading(true);
585
-
586
- try {
587
- const formData = new FormData();
588
- formData.append('file', file);
589
- formData.append('alt', file.name);
590
- const result = await onUpload(formData);
591
-
592
- if (result.success) {
593
- setScreenshotId(result.mediaId);
594
- setNotice('Annotated screenshot uploaded.');
595
- return true;
596
- }
597
-
598
- setError(result.error);
599
- return false;
600
- } finally {
601
- setUploading(false);
602
- }
603
- },
604
- [onUpload],
605
- );
606
-
607
- const closeAnnotationEditor = React.useCallback((): void => {
608
- setAnnotating(false);
609
- setEditorImage(null);
610
- setEditorHistory(DEFAULT_HISTORY);
611
- setDraftOperation(null);
612
- draftOperationRef.current = null;
613
- }, []);
614
-
615
- const handleStartAnnotation = React.useCallback(
616
- async (file: File): Promise<void> => {
617
- const validationError = validateImageFile(file);
618
- if (validationError) {
619
- setError(validationError);
620
- return;
621
- }
622
-
623
- try {
624
- const nextImage = await createEditorImage(file);
625
- setEditorImage(nextImage);
626
- setEditorHistory(DEFAULT_HISTORY);
627
- setDraftOperation(null);
628
- draftOperationRef.current = null;
629
- setAnnotating(true);
630
- setError(null);
631
- } catch (nextError) {
632
- setError(nextError instanceof Error ? nextError.message : 'Failed to process image.');
633
- }
634
- },
635
- [validateImageFile],
636
- );
637
-
638
- React.useEffect(() => {
639
- if (!open || !allowScreenshotUpload) {
640
- return;
641
- }
642
-
643
- const onPaste = async (event: ClipboardEvent): Promise<void> => {
644
- const file = Array.from(event.clipboardData?.items || [])
645
- .find((item) => item.type.startsWith('image/'))
646
- ?.getAsFile();
647
-
648
- if (!file) {
649
- return;
650
- }
651
-
652
- event.preventDefault();
653
- await handleStartAnnotation(file);
654
- };
655
-
656
- window.addEventListener('paste', onPaste);
657
- return () => window.removeEventListener('paste', onPaste);
658
- }, [allowScreenshotUpload, handleStartAnnotation, open]);
659
-
660
- const commitOperations = React.useCallback((nextOperations: AnnotationOperation[]): void => {
661
- setEditorHistory((current) => ({
662
- operations: nextOperations,
663
- redoStack: [],
664
- undoStack: [...current.undoStack, current.operations],
665
- }));
666
- }, []);
667
-
668
- const appendOperation = React.useCallback((operation: AnnotationOperation): void => {
669
- setEditorHistory((current) => ({
670
- operations: [...current.operations, operation],
671
- redoStack: [],
672
- undoStack: [...current.undoStack, current.operations],
673
- }));
674
- }, []);
675
-
676
- const handleUpload = async (event: React.ChangeEvent<HTMLInputElement>): Promise<void> => {
677
- const file = event.target.files?.[0];
678
- if (file) {
679
- await handleStartAnnotation(file);
680
- }
681
- event.target.value = '';
682
- };
683
-
684
- const handleCaptureScreenshot = async (): Promise<void> => {
685
- try {
686
- setError(null);
687
- const { file, surface } = await captureScreenshotFile(capturePolicy);
688
- if (capturePolicy === 'current-tab-first') {
689
- if (surface === 'browser') {
690
- setNotice('Captured the current tab.');
691
- } else if (surface) {
692
- setNotice(`Captured a ${surface} surface because the browser allowed a broader selection.`);
693
- } else {
694
- setNotice('Captured a screenshot.');
695
- }
696
- } else if (capturePolicy === 'strict-current-tab') {
697
- setNotice('Captured the current tab.');
698
- } else {
699
- setNotice('Captured a screenshot.');
700
- }
701
-
702
- await handleStartAnnotation(file);
703
- } catch (nextError) {
704
- setError(nextError instanceof Error ? nextError.message : 'Screen capture failed.');
705
- }
706
- };
707
-
708
- const handleUndo = (): void => {
709
- setEditorHistory((current) => {
710
- if (current.undoStack.length === 0) {
711
- return current;
712
- }
713
-
714
- const previousOperations = current.undoStack[current.undoStack.length - 1];
715
- return {
716
- operations: previousOperations,
717
- redoStack: [current.operations, ...current.redoStack],
718
- undoStack: current.undoStack.slice(0, -1),
719
- };
720
- });
721
- };
722
-
723
- const handleRedo = (): void => {
724
- setEditorHistory((current) => {
725
- if (current.redoStack.length === 0) {
726
- return current;
727
- }
728
-
729
- const [nextOperations, ...remainingRedo] = current.redoStack;
730
- return {
731
- operations: nextOperations,
732
- redoStack: remainingRedo,
733
- undoStack: [...current.undoStack, current.operations],
734
- };
735
- });
736
- };
737
-
738
- const handleClearAnnotations = (): void => {
739
- if (editorHistory.operations.length === 0) {
740
- return;
741
- }
742
-
743
- commitOperations([]);
744
- };
745
-
746
- const handleRevertLastAnnotation = (): void => {
747
- setDraftOperation(null);
748
- draftOperationRef.current = null;
749
- pointerIdRef.current = null;
750
-
751
- setEditorHistory((current) => {
752
- if (current.operations.length === 0) {
753
- return current;
754
- }
755
-
756
- return {
757
- operations: current.operations.slice(0, -1),
758
- redoStack: [],
759
- undoStack: [...current.undoStack, current.operations],
760
- };
761
- });
762
- };
763
-
764
- const handleCanvasPointerDown = (event: React.PointerEvent<HTMLCanvasElement>): void => {
765
- if (!annotationCanvasRef.current) {
766
- return;
767
- }
768
-
769
- setError(null);
770
-
771
- const canvas = annotationCanvasRef.current;
772
- const point = getCanvasPoint(event, canvas);
773
-
774
- if (annotationTool === 'text') {
775
- const text = annotationText.trim();
776
- if (!text) {
777
- setError('Enter text before placing it on the image.');
778
- return;
779
- }
780
-
781
- const operation: TextOperation = {
782
- id: createOperationId(),
783
- type: 'text',
784
- style: { color: annotationColor, size: annotationSize },
785
- point,
786
- text,
787
- };
788
- appendOperation(operation);
789
- return;
790
- }
791
-
792
- event.preventDefault();
793
- canvas.setPointerCapture(event.pointerId);
794
- pointerIdRef.current = event.pointerId;
795
-
796
- const style = { color: annotationColor, size: annotationSize };
797
- const nextDraft: DrawableDraftOperation =
798
- annotationTool === 'pen'
799
- ? {
800
- id: createOperationId(),
801
- type: 'pen',
802
- style,
803
- points: [point],
804
- }
805
- : annotationTool === 'rectangle'
806
- ? {
807
- id: createOperationId(),
808
- type: 'rectangle',
809
- style,
810
- start: point,
811
- end: point,
812
- }
813
- : {
814
- id: createOperationId(),
815
- type: 'arrow',
816
- style,
817
- start: point,
818
- end: point,
819
- };
820
-
821
- draftOperationRef.current = nextDraft;
822
- setDraftOperation(nextDraft);
823
- };
824
-
825
- const handleCanvasPointerMove = (event: React.PointerEvent<HTMLCanvasElement>): void => {
826
- if (!annotationCanvasRef.current || pointerIdRef.current !== event.pointerId) {
827
- return;
828
- }
829
-
830
- const activeDraft = draftOperationRef.current;
831
- if (!activeDraft) {
832
- return;
833
- }
834
-
835
- const point = getCanvasPoint(event, annotationCanvasRef.current);
836
- const nextDraft: DrawableDraftOperation =
837
- activeDraft.type === 'pen'
838
- ? {
839
- ...activeDraft,
840
- points: [...activeDraft.points, point],
841
- }
842
- : {
843
- ...activeDraft,
844
- end: point,
845
- };
846
-
847
- draftOperationRef.current = nextDraft;
848
- setDraftOperation(nextDraft);
849
- };
850
-
851
- const handleCanvasPointerUp = (event: React.PointerEvent<HTMLCanvasElement>): void => {
852
- if (!annotationCanvasRef.current || pointerIdRef.current !== event.pointerId) {
853
- return;
854
- }
855
-
856
- const canvas = annotationCanvasRef.current;
857
- if (canvas.hasPointerCapture(event.pointerId)) {
858
- canvas.releasePointerCapture(event.pointerId);
859
- }
860
-
861
- pointerIdRef.current = null;
862
- const activeDraft = draftOperationRef.current;
863
- draftOperationRef.current = null;
864
- setDraftOperation(null);
865
-
866
- if (!activeDraft) {
867
- return;
868
- }
869
-
870
- if (activeDraft.type === 'pen') {
871
- const points =
872
- activeDraft.points.length === 1
873
- ? [...activeDraft.points, activeDraft.points[0]]
874
- : activeDraft.points;
875
- appendOperation({ ...activeDraft, points });
876
- return;
877
- }
878
-
879
- if (!isShapeMeaningful(activeDraft.start, activeDraft.end)) {
880
- return;
881
- }
882
-
883
- appendOperation(activeDraft);
884
- };
885
-
886
- const handleCanvasPointerCancel = (event: React.PointerEvent<HTMLCanvasElement>): void => {
887
- if (
888
- annotationCanvasRef.current &&
889
- pointerIdRef.current === event.pointerId &&
890
- annotationCanvasRef.current.hasPointerCapture(event.pointerId)
891
- ) {
892
- annotationCanvasRef.current.releasePointerCapture(event.pointerId);
893
- }
894
-
895
- pointerIdRef.current = null;
896
- draftOperationRef.current = null;
897
- setDraftOperation(null);
898
- };
899
-
900
- const handleApplyAnnotation = async (): Promise<void> => {
901
- if (!annotationCanvasRef.current || !editorImage) {
902
- return;
903
- }
904
-
905
- try {
906
- const previewUrl = annotationCanvasRef.current.toDataURL('image/png');
907
- const file = await canvasToFile(annotationCanvasRef.current, editorImage.fileName);
908
- const uploaded = await uploadImageFile(file);
909
- if (uploaded) {
910
- setScreenshotPreviewUrl(previewUrl);
911
- closeAnnotationEditor();
912
- }
913
- } catch (nextError) {
914
- setError(nextError instanceof Error ? nextError.message : 'Failed to export image.');
915
- }
916
- };
917
-
918
- const handleRemoveScreenshot = async (): Promise<void> => {
919
- if (!screenshotId) {
920
- setScreenshotPreviewUrl(null);
921
- return;
922
- }
923
-
924
- if (!onDeleteScreenshot) {
925
- setScreenshotId(null);
926
- setScreenshotPreviewUrl(null);
927
- return;
928
- }
929
-
930
- setDeletingScreenshot(true);
931
- setError(null);
932
-
933
- try {
934
- const result = await onDeleteScreenshot(screenshotId);
935
- if (!result.success) {
936
- setError(result.error);
937
- return;
938
- }
939
-
940
- setScreenshotId(null);
941
- setScreenshotPreviewUrl(null);
942
- setNotice('Screenshot removed.');
943
- } finally {
944
- setDeletingScreenshot(false);
945
- }
946
- };
947
-
948
- const handleSubmit = async (): Promise<void> => {
949
- if (!message.trim()) {
950
- setError('Please enter a message.');
951
- return;
952
- }
953
-
954
- setSubmitting(true);
955
- setError(null);
956
- const result = await onSubmit({
957
- message: message.trim(),
958
- pagePath: typeof window !== 'undefined' ? window.location.pathname : '/',
959
- selector: captureData?.selector,
960
- selectedText: captureData?.selectedText,
961
- screenshotId,
962
- meta: {
963
- userAgent: window.navigator.userAgent,
964
- locale: window.navigator.language,
965
- viewport: `${window.innerWidth}x${window.innerHeight}`,
966
- },
967
- });
968
- setSubmitting(false);
969
-
970
- if (!result.success) {
971
- setError(result.error);
972
- return;
973
- }
974
-
975
- setMessage('');
976
- setCaptureData(null);
977
- setScreenshotId(null);
978
- setScreenshotPreviewUrl(null);
979
- setNotice(null);
980
- setOpen(false);
981
- };
982
-
983
- const currentHasUndo = editorHistory.undoStack.length > 0;
984
- const currentHasRedo = editorHistory.redoStack.length > 0;
985
- const hasAnnotations = editorHistory.operations.length > 0;
986
-
987
- return (
988
- <>
989
- <button
990
- type="button"
991
- onClick={() => setOpen((value) => !value)}
992
- style={{
993
- position: 'fixed',
994
- right: '20px',
995
- bottom: '20px',
996
- zIndex: 9999,
997
- borderRadius: '999px',
998
- backgroundColor: '#166534',
999
- color: '#ffffff',
1000
- border: 'none',
1001
- padding: '10px 14px',
1002
- fontWeight: 600,
1003
- cursor: 'pointer',
1004
- }}
1005
- >
1006
- Feedback
1007
- </button>
1008
- {open ? (
1009
- <div
1010
- style={{
1011
- position: 'fixed',
1012
- right: '20px',
1013
- bottom: '72px',
1014
- width: '360px',
1015
- background: '#111827',
1016
- color: '#f9fafb',
1017
- borderRadius: '12px',
1018
- border: '1px solid #374151',
1019
- padding: '12px',
1020
- zIndex: 9999,
1021
- boxShadow: '0 10px 30px rgba(0,0,0,0.35)',
1022
- }}
1023
- >
1024
- <h3 style={{ margin: '0 0 8px', fontSize: '16px' }}>{title}</h3>
1025
- <p style={{ margin: '0 0 8px', fontSize: '12px', opacity: 0.8 }}>
1026
- {typeof window !== 'undefined' ? window.location.pathname : '/'}
1027
- </p>
1028
- <textarea
1029
- value={message}
1030
- onChange={(event) => setMessage(event.target.value)}
1031
- rows={5}
1032
- placeholder="Describe the issue..."
1033
- style={{
1034
- width: '100%',
1035
- borderRadius: '8px',
1036
- border: '1px solid #4b5563',
1037
- background: '#1f2937',
1038
- color: '#f9fafb',
1039
- padding: '8px',
1040
- resize: 'vertical',
1041
- }}
1042
- />
1043
- <div style={{ display: 'flex', gap: '8px', marginTop: '8px', flexWrap: 'wrap' }}>
1044
- {allowScreenshotUpload && onUpload ? (
1045
- <button
1046
- type="button"
1047
- onClick={handleCaptureScreenshot}
1048
- style={{
1049
- borderRadius: '8px',
1050
- border: '1px solid #4b5563',
1051
- background: '#1f2937',
1052
- color: '#f9fafb',
1053
- padding: '6px 8px',
1054
- cursor: 'pointer',
1055
- }}
1056
- >
1057
- Capture screen
1058
- </button>
1059
- ) : null}
1060
- <button
1061
- type="button"
1062
- onClick={() => setCaptureMode((value) => !value)}
1063
- style={{
1064
- borderRadius: '8px',
1065
- border: '1px solid #4b5563',
1066
- background: captureMode ? '#14532d' : '#1f2937',
1067
- color: '#f9fafb',
1068
- padding: '6px 8px',
1069
- cursor: 'pointer',
1070
- }}
1071
- >
1072
- {captureMode ? 'Click an element...' : 'Capture element'}
1073
- </button>
1074
- {allowScreenshotUpload && onUpload ? (
1075
- <label
1076
- style={{
1077
- borderRadius: '8px',
1078
- border: '1px solid #4b5563',
1079
- background: '#1f2937',
1080
- color: '#f9fafb',
1081
- padding: '6px 8px',
1082
- cursor: 'pointer',
1083
- }}
1084
- >
1085
- {uploading ? 'Uploading...' : uploadLabel}
1086
- <input
1087
- type="file"
1088
- accept={screenshotAllowedMimeTypes.join(',')}
1089
- onChange={handleUpload}
1090
- hidden
1091
- />
1092
- </label>
1093
- ) : null}
1094
- </div>
1095
- {allowScreenshotUpload && onUpload ? (
1096
- <p style={{ margin: '8px 0 0', fontSize: '11px', opacity: 0.8 }}>
1097
- Paste an image with Ctrl/Cmd+V or capture the current tab first.
1098
- </p>
1099
- ) : null}
1100
- {captureData ? (
1101
- <p style={{ margin: '8px 0 0', fontSize: '12px', opacity: 0.8 }}>
1102
- Selector: {captureData.selector}
1103
- </p>
1104
- ) : null}
1105
- {screenshotId ? (
1106
- <div
1107
- style={{
1108
- marginTop: '8px',
1109
- borderRadius: '10px',
1110
- border: '1px solid #374151',
1111
- background: '#0f172a',
1112
- padding: '8px',
1113
- }}
1114
- >
1115
- {screenshotPreviewUrl ? (
1116
- <div style={{ marginBottom: '8px', borderRadius: '8px', overflow: 'hidden' }}>
1117
- {/* eslint-disable-next-line @next/next/no-img-element */}
1118
- <img
1119
- src={screenshotPreviewUrl}
1120
- alt="Annotated screenshot preview"
1121
- style={{ width: '100%', height: 'auto', display: 'block' }}
1122
- />
1123
- </div>
1124
- ) : null}
1125
- <div
1126
- style={{
1127
- display: 'flex',
1128
- justifyContent: 'space-between',
1129
- alignItems: 'center',
1130
- gap: '8px',
1131
- }}
1132
- >
1133
- <p style={{ margin: 0, fontSize: '12px', opacity: 0.8 }}>Media ID: {screenshotId}</p>
1134
- <button
1135
- type="button"
1136
- onClick={handleRemoveScreenshot}
1137
- disabled={deletingScreenshot}
1138
- style={{
1139
- borderRadius: '8px',
1140
- border: '1px solid #7f1d1d',
1141
- background: '#450a0a',
1142
- color: '#fecaca',
1143
- padding: '4px 8px',
1144
- cursor: deletingScreenshot ? 'wait' : 'pointer',
1145
- opacity: deletingScreenshot ? 0.7 : 1,
1146
- fontSize: '12px',
1147
- }}
1148
- >
1149
- {deletingScreenshot ? 'Removing...' : 'Remove'}
1150
- </button>
1151
- </div>
1152
- </div>
1153
- ) : null}
1154
- {notice ? (
1155
- <p style={{ margin: '8px 0 0', color: '#bfdbfe', fontSize: '12px' }}>{notice}</p>
1156
- ) : null}
1157
- {error ? (
1158
- <p style={{ margin: '8px 0 0', color: '#fca5a5', fontSize: '12px' }}>{error}</p>
1159
- ) : null}
1160
- <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '10px', gap: '8px' }}>
1161
- <button
1162
- type="button"
1163
- onClick={() => setOpen(false)}
1164
- style={{
1165
- borderRadius: '8px',
1166
- border: '1px solid #4b5563',
1167
- background: '#1f2937',
1168
- color: '#f9fafb',
1169
- padding: '6px 10px',
1170
- cursor: 'pointer',
1171
- }}
1172
- >
1173
- Close
1174
- </button>
1175
- <button
1176
- type="button"
1177
- onClick={handleSubmit}
1178
- disabled={submitting}
1179
- style={{
1180
- borderRadius: '8px',
1181
- border: 'none',
1182
- background: '#16a34a',
1183
- color: '#f9fafb',
1184
- padding: '6px 10px',
1185
- cursor: 'pointer',
1186
- }}
1187
- >
1188
- {submitting ? 'Sending...' : submitLabel}
1189
- </button>
1190
- </div>
1191
- </div>
1192
- ) : null}
1193
- {annotating && editorImage ? (
1194
- <div
1195
- style={{
1196
- position: 'fixed',
1197
- inset: '0',
1198
- zIndex: 10000,
1199
- background: 'rgba(3, 7, 18, 0.94)',
1200
- color: '#f9fafb',
1201
- display: 'flex',
1202
- flexDirection: 'column',
1203
- }}
1204
- >
1205
- <div
1206
- style={{
1207
- display: 'flex',
1208
- flexWrap: 'wrap',
1209
- gap: '12px',
1210
- alignItems: 'center',
1211
- justifyContent: 'space-between',
1212
- padding: '12px 16px',
1213
- borderBottom: '1px solid rgba(148, 163, 184, 0.2)',
1214
- background: 'rgba(15, 23, 42, 0.92)',
1215
- }}
1216
- >
1217
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
1218
- <strong style={{ fontSize: '15px' }}>Annotate screenshot</strong>
1219
- <span style={{ fontSize: '12px', opacity: 0.75 }}>{editorImage.fileName}</span>
1220
- </div>
1221
- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', alignItems: 'center' }}>
1222
- <select
1223
- value={annotationTool}
1224
- onChange={(event) => setAnnotationTool(event.target.value as AnnotationTool)}
1225
- aria-label="Annotation tool"
1226
- style={{
1227
- borderRadius: '8px',
1228
- border: '1px solid #475569',
1229
- background: '#0f172a',
1230
- color: '#f8fafc',
1231
- padding: '6px 8px',
1232
- }}
1233
- >
1234
- <option value="pen">Pen</option>
1235
- <option value="rectangle">Rectangle</option>
1236
- <option value="arrow">Arrow</option>
1237
- <option value="text">Text</option>
1238
- </select>
1239
- <div style={{ display: 'flex', gap: '6px', alignItems: 'center', flexWrap: 'wrap' }}>
1240
- {DEFAULT_COLORS.map((color) => (
1241
- <button
1242
- key={color}
1243
- type="button"
1244
- onClick={() => setAnnotationColor(color)}
1245
- aria-label={`Select ${color} color`}
1246
- style={{
1247
- width: '24px',
1248
- height: '24px',
1249
- borderRadius: '999px',
1250
- border: annotationColor === color ? '2px solid #f8fafc' : '1px solid #334155',
1251
- background: color,
1252
- cursor: 'pointer',
1253
- }}
1254
- />
1255
- ))}
1256
- <input
1257
- type="color"
1258
- value={annotationColor}
1259
- onChange={(event) => setAnnotationColor(event.target.value)}
1260
- aria-label="Annotation color"
1261
- style={{ width: '34px', height: '34px', border: 'none', background: 'transparent' }}
1262
- />
1263
- </div>
1264
- <label style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px' }}>
1265
- Size
1266
- <input
1267
- type="range"
1268
- min={1}
1269
- max={18}
1270
- value={annotationSize}
1271
- onChange={(event) => setAnnotationSize(Number(event.target.value))}
1272
- aria-label="Annotation size"
1273
- />
1274
- </label>
1275
- {annotationTool === 'text' ? (
1276
- <input
1277
- type="text"
1278
- value={annotationText}
1279
- onChange={(event) => setAnnotationText(event.target.value)}
1280
- placeholder="Text to place"
1281
- aria-label="Annotation text"
1282
- style={{
1283
- minWidth: '160px',
1284
- borderRadius: '8px',
1285
- border: '1px solid #475569',
1286
- background: '#0f172a',
1287
- color: '#f8fafc',
1288
- padding: '6px 8px',
1289
- }}
1290
- />
1291
- ) : null}
1292
- <button
1293
- type="button"
1294
- onClick={handleUndo}
1295
- disabled={!currentHasUndo}
1296
- style={{
1297
- borderRadius: '8px',
1298
- border: '1px solid #475569',
1299
- background: '#0f172a',
1300
- color: '#f8fafc',
1301
- padding: '6px 10px',
1302
- cursor: currentHasUndo ? 'pointer' : 'not-allowed',
1303
- opacity: currentHasUndo ? 1 : 0.5,
1304
- }}
1305
- >
1306
- Undo
1307
- </button>
1308
- <button
1309
- type="button"
1310
- onClick={handleRedo}
1311
- disabled={!currentHasRedo}
1312
- style={{
1313
- borderRadius: '8px',
1314
- border: '1px solid #475569',
1315
- background: '#0f172a',
1316
- color: '#f8fafc',
1317
- padding: '6px 10px',
1318
- cursor: currentHasRedo ? 'pointer' : 'not-allowed',
1319
- opacity: currentHasRedo ? 1 : 0.5,
1320
- }}
1321
- >
1322
- Redo
1323
- </button>
1324
- <button
1325
- type="button"
1326
- onClick={handleClearAnnotations}
1327
- disabled={!hasAnnotations}
1328
- style={{
1329
- borderRadius: '8px',
1330
- border: '1px solid #475569',
1331
- background: '#0f172a',
1332
- color: '#f8fafc',
1333
- padding: '6px 10px',
1334
- cursor: hasAnnotations ? 'pointer' : 'not-allowed',
1335
- opacity: hasAnnotations ? 1 : 0.5,
1336
- }}
1337
- >
1338
- Clear
1339
- </button>
1340
- <button
1341
- type="button"
1342
- onClick={handleRevertLastAnnotation}
1343
- disabled={!hasAnnotations}
1344
- style={{
1345
- borderRadius: '8px',
1346
- border: '1px solid #475569',
1347
- background: '#0f172a',
1348
- color: '#f8fafc',
1349
- padding: '6px 10px',
1350
- cursor: hasAnnotations ? 'pointer' : 'not-allowed',
1351
- opacity: hasAnnotations ? 1 : 0.5,
1352
- }}
1353
- >
1354
- Revert last
1355
- </button>
1356
- </div>
1357
- </div>
1358
- <div
1359
- style={{
1360
- flex: 1,
1361
- overflow: 'auto',
1362
- padding: '16px',
1363
- display: 'flex',
1364
- alignItems: 'flex-start',
1365
- justifyContent: 'center',
1366
- }}
1367
- >
1368
- <canvas
1369
- ref={annotationCanvasRef}
1370
- onPointerDown={handleCanvasPointerDown}
1371
- onPointerMove={handleCanvasPointerMove}
1372
- onPointerUp={handleCanvasPointerUp}
1373
- onPointerCancel={handleCanvasPointerCancel}
1374
- style={{
1375
- width: 'min(100%, 1400px)',
1376
- height: 'auto',
1377
- display: 'block',
1378
- borderRadius: '16px',
1379
- background: '#ffffff',
1380
- boxShadow: '0 24px 80px rgba(15, 23, 42, 0.45)',
1381
- touchAction: 'none',
1382
- cursor: annotationTool === 'text' ? 'copy' : 'crosshair',
1383
- }}
1384
- />
1385
- </div>
1386
- <div
1387
- style={{
1388
- display: 'flex',
1389
- justifyContent: 'space-between',
1390
- alignItems: 'center',
1391
- gap: '12px',
1392
- flexWrap: 'wrap',
1393
- padding: '12px 16px',
1394
- borderTop: '1px solid rgba(148, 163, 184, 0.2)',
1395
- background: 'rgba(15, 23, 42, 0.92)',
1396
- }}
1397
- >
1398
- <p style={{ margin: 0, fontSize: '12px', opacity: 0.75 }}>
1399
- Use mouse, touch, or pen input. Text is placed where you click on the image.
1400
- </p>
1401
- <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
1402
- <button
1403
- type="button"
1404
- onClick={closeAnnotationEditor}
1405
- style={{
1406
- borderRadius: '8px',
1407
- border: '1px solid #475569',
1408
- background: '#0f172a',
1409
- color: '#f8fafc',
1410
- padding: '8px 12px',
1411
- cursor: 'pointer',
1412
- }}
1413
- >
1414
- Cancel
1415
- </button>
1416
- <button
1417
- type="button"
1418
- onClick={handleApplyAnnotation}
1419
- disabled={uploading}
1420
- style={{
1421
- borderRadius: '8px',
1422
- border: 'none',
1423
- background: '#16a34a',
1424
- color: '#f8fafc',
1425
- padding: '8px 12px',
1426
- cursor: uploading ? 'wait' : 'pointer',
1427
- opacity: uploading ? 0.8 : 1,
1428
- }}
1429
- >
1430
- {uploading ? 'Uploading...' : 'Save screenshot'}
1431
- </button>
1432
- </div>
1433
- </div>
1434
- </div>
1435
- ) : null}
1436
- </>
1437
- );
1438
- }