@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.
@@ -0,0 +1,1630 @@
1
+ 'use client';
2
+ import React from 'react';
3
+ import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
4
+ import { usePathname } from 'next/navigation';
5
+
6
+ var DEFAULT_COLORS = ["#ef4444", "#f97316", "#eab308", "#22c55e", "#06b6d4", "#3b82f6", "#a855f7"];
7
+ var DEFAULT_HISTORY = {
8
+ operations: [],
9
+ redoStack: [],
10
+ undoStack: []
11
+ };
12
+ var createOperationId = () => `annotation-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
13
+ var getCssSelector = (element) => {
14
+ if (element.id) {
15
+ return `#${element.id}`;
16
+ }
17
+ const parts = [];
18
+ let current = element;
19
+ while (current && current.nodeType === Node.ELEMENT_NODE && current !== document.body) {
20
+ let part = current.tagName.toLowerCase();
21
+ const className = current.className;
22
+ if (typeof className === "string") {
23
+ const firstClass = className.split(" ").map((value) => value.trim()).filter(Boolean)[0];
24
+ if (firstClass) {
25
+ part += `.${firstClass}`;
26
+ }
27
+ }
28
+ const parent = current.parentElement;
29
+ if (parent) {
30
+ const siblings = Array.from(parent.children).filter(
31
+ (candidate) => candidate.tagName === current?.tagName
32
+ );
33
+ if (siblings.length > 1) {
34
+ const index = siblings.indexOf(current);
35
+ part += `:nth-of-type(${index + 1})`;
36
+ }
37
+ }
38
+ parts.unshift(part);
39
+ current = current.parentElement;
40
+ }
41
+ return parts.join(" > ");
42
+ };
43
+ var fileToDataUrl = async (file) => new Promise((resolve, reject) => {
44
+ const reader = new FileReader();
45
+ reader.onload = () => {
46
+ if (typeof reader.result === "string") {
47
+ resolve(reader.result);
48
+ return;
49
+ }
50
+ reject(new Error("Unsupported image format."));
51
+ };
52
+ reader.onerror = () => reject(new Error("Could not read image."));
53
+ reader.readAsDataURL(file);
54
+ });
55
+ var loadImage = async (src) => new Promise((resolve, reject) => {
56
+ const image = new Image();
57
+ image.onload = () => resolve(image);
58
+ image.onerror = () => reject(new Error("Could not load image."));
59
+ image.src = src;
60
+ });
61
+ var createEditorImage = async (file) => {
62
+ const src = await fileToDataUrl(file);
63
+ const element = await loadImage(src);
64
+ return {
65
+ element,
66
+ fileName: file.name,
67
+ height: element.naturalHeight || element.height,
68
+ src,
69
+ width: element.naturalWidth || element.width
70
+ };
71
+ };
72
+ var canvasToFile = async (canvas, fileName = `feedback-${Date.now()}.png`) => {
73
+ const blob = await new Promise((resolve) => {
74
+ canvas.toBlob((nextBlob) => resolve(nextBlob), "image/png");
75
+ });
76
+ if (!blob) {
77
+ throw new Error("Failed to prepare annotated screenshot.");
78
+ }
79
+ return new File([blob], fileName.replace(/\.[a-z0-9]+$/i, "") + ".png", { type: "image/png" });
80
+ };
81
+ var waitForRenderedVideoFrame = async (video) => {
82
+ if ("requestVideoFrameCallback" in video) {
83
+ await new Promise((resolve) => {
84
+ video.requestVideoFrameCallback(() => resolve());
85
+ });
86
+ return;
87
+ }
88
+ await new Promise((resolve) => {
89
+ window.requestAnimationFrame(() => resolve());
90
+ });
91
+ };
92
+ var captureScreenshotFile = async (capturePolicy) => {
93
+ if (!navigator.mediaDevices?.getDisplayMedia) {
94
+ throw new Error("Browser does not support screen capture.");
95
+ }
96
+ const options = capturePolicy === "any-surface" ? {
97
+ video: true,
98
+ audio: false
99
+ } : {
100
+ video: {
101
+ displaySurface: "browser"
102
+ },
103
+ audio: false,
104
+ preferCurrentTab: true,
105
+ selfBrowserSurface: "include",
106
+ surfaceSwitching: "exclude"
107
+ };
108
+ const stream = await navigator.mediaDevices.getDisplayMedia(options);
109
+ const track = stream.getVideoTracks()[0];
110
+ if (!track) {
111
+ stream.getTracks().forEach((item) => item.stop());
112
+ throw new Error("Screen capture failed.");
113
+ }
114
+ const settings = track.getSettings();
115
+ const surface = typeof settings.displaySurface === "string" ? settings.displaySurface : null;
116
+ if (capturePolicy === "strict-current-tab" && surface !== "browser") {
117
+ stream.getTracks().forEach((item) => item.stop());
118
+ throw new Error("Please share the current browser tab to capture a screenshot.");
119
+ }
120
+ const video = document.createElement("video");
121
+ try {
122
+ video.srcObject = stream;
123
+ video.muted = true;
124
+ video.playsInline = true;
125
+ await video.play();
126
+ await waitForRenderedVideoFrame(video);
127
+ const width = video.videoWidth || window.innerWidth;
128
+ const height = video.videoHeight || window.innerHeight;
129
+ if (!width || !height) {
130
+ throw new Error("Screen capture failed.");
131
+ }
132
+ const canvas = document.createElement("canvas");
133
+ canvas.width = width;
134
+ canvas.height = height;
135
+ const context = canvas.getContext("2d");
136
+ if (!context) {
137
+ throw new Error("Browser does not support canvas context.");
138
+ }
139
+ context.drawImage(video, 0, 0, width, height);
140
+ return {
141
+ file: await canvasToFile(canvas),
142
+ surface
143
+ };
144
+ } finally {
145
+ video.pause();
146
+ video.srcObject = null;
147
+ stream.getTracks().forEach((item) => item.stop());
148
+ }
149
+ };
150
+ var getCanvasPoint = (event, canvas) => {
151
+ const bounds = canvas.getBoundingClientRect();
152
+ const scaleX = bounds.width === 0 ? 1 : canvas.width / bounds.width;
153
+ const scaleY = bounds.height === 0 ? 1 : canvas.height / bounds.height;
154
+ return {
155
+ x: (event.clientX - bounds.left) * scaleX,
156
+ y: (event.clientY - bounds.top) * scaleY
157
+ };
158
+ };
159
+ var drawPenOperation = (context, operation) => {
160
+ if (operation.points.length === 0) {
161
+ return;
162
+ }
163
+ context.save();
164
+ context.strokeStyle = operation.style.color;
165
+ context.lineWidth = operation.style.size;
166
+ context.lineCap = "round";
167
+ context.lineJoin = "round";
168
+ context.beginPath();
169
+ context.moveTo(operation.points[0].x, operation.points[0].y);
170
+ for (const point of operation.points.slice(1)) {
171
+ context.lineTo(point.x, point.y);
172
+ }
173
+ if (operation.points.length === 1) {
174
+ const point = operation.points[0];
175
+ context.lineTo(point.x + 0.01, point.y + 0.01);
176
+ }
177
+ context.stroke();
178
+ context.restore();
179
+ };
180
+ var drawRectangleOperation = (context, operation) => {
181
+ const left = Math.min(operation.start.x, operation.end.x);
182
+ const top = Math.min(operation.start.y, operation.end.y);
183
+ const width = Math.abs(operation.end.x - operation.start.x);
184
+ const height = Math.abs(operation.end.y - operation.start.y);
185
+ context.save();
186
+ context.strokeStyle = operation.style.color;
187
+ context.lineWidth = operation.style.size;
188
+ context.strokeRect(left, top, width, height);
189
+ context.restore();
190
+ };
191
+ var drawArrowOperation = (context, operation) => {
192
+ const angle = Math.atan2(operation.end.y - operation.start.y, operation.end.x - operation.start.x);
193
+ const headLength = Math.max(14, operation.style.size * 4);
194
+ context.save();
195
+ context.strokeStyle = operation.style.color;
196
+ context.fillStyle = operation.style.color;
197
+ context.lineWidth = operation.style.size;
198
+ context.lineCap = "round";
199
+ context.lineJoin = "round";
200
+ context.beginPath();
201
+ context.moveTo(operation.start.x, operation.start.y);
202
+ context.lineTo(operation.end.x, operation.end.y);
203
+ context.stroke();
204
+ context.beginPath();
205
+ context.moveTo(operation.end.x, operation.end.y);
206
+ context.lineTo(
207
+ operation.end.x - headLength * Math.cos(angle - Math.PI / 6),
208
+ operation.end.y - headLength * Math.sin(angle - Math.PI / 6)
209
+ );
210
+ context.lineTo(
211
+ operation.end.x - headLength * Math.cos(angle + Math.PI / 6),
212
+ operation.end.y - headLength * Math.sin(angle + Math.PI / 6)
213
+ );
214
+ context.closePath();
215
+ context.fill();
216
+ context.restore();
217
+ };
218
+ var drawTextOperation = (context, operation) => {
219
+ const fontSize = Math.max(16, operation.style.size * 6);
220
+ context.save();
221
+ context.fillStyle = operation.style.color;
222
+ context.font = `600 ${fontSize}px ui-sans-serif, system-ui, sans-serif`;
223
+ context.textBaseline = "top";
224
+ context.fillText(operation.text, operation.point.x, operation.point.y);
225
+ context.restore();
226
+ };
227
+ var drawOperation = (context, operation) => {
228
+ switch (operation.type) {
229
+ case "pen":
230
+ drawPenOperation(context, operation);
231
+ return;
232
+ case "rectangle":
233
+ drawRectangleOperation(context, operation);
234
+ return;
235
+ case "arrow":
236
+ drawArrowOperation(context, operation);
237
+ return;
238
+ case "text":
239
+ drawTextOperation(context, operation);
240
+ return;
241
+ }
242
+ };
243
+ var isShapeMeaningful = (start, end) => Math.abs(end.x - start.x) > 3 || Math.abs(end.y - start.y) > 3;
244
+ function ChatIcon() {
245
+ return /* @__PURE__ */ jsx("svg", { width: "22", height: "22", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }) });
246
+ }
247
+ function XIcon({ size = 18 }) {
248
+ return /* @__PURE__ */ jsxs("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.5", strokeLinecap: "round", strokeLinejoin: "round", children: [
249
+ /* @__PURE__ */ jsx("line", { x1: "18", y1: "6", x2: "6", y2: "18" }),
250
+ /* @__PURE__ */ jsx("line", { x1: "6", y1: "6", x2: "18", y2: "18" })
251
+ ] });
252
+ }
253
+ function CameraIcon() {
254
+ return /* @__PURE__ */ jsxs("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
255
+ /* @__PURE__ */ jsx("path", { d: "M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" }),
256
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "13", r: "4" })
257
+ ] });
258
+ }
259
+ function CursorIcon() {
260
+ return /* @__PURE__ */ jsx("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx("path", { d: "M4 4l7.07 17 2.51-7.39L21 11.07z" }) });
261
+ }
262
+ function UploadIcon() {
263
+ return /* @__PURE__ */ jsxs("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
264
+ /* @__PURE__ */ jsx("polyline", { points: "16 16 12 12 8 16" }),
265
+ /* @__PURE__ */ jsx("line", { x1: "12", y1: "12", x2: "12", y2: "21" }),
266
+ /* @__PURE__ */ jsx("path", { d: "M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3" })
267
+ ] });
268
+ }
269
+ function SendIcon() {
270
+ return /* @__PURE__ */ jsxs("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
271
+ /* @__PURE__ */ jsx("line", { x1: "22", y1: "2", x2: "11", y2: "13" }),
272
+ /* @__PURE__ */ jsx("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
273
+ ] });
274
+ }
275
+ function CheckCircleIcon() {
276
+ return /* @__PURE__ */ jsxs("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", children: [
277
+ /* @__PURE__ */ jsx("path", { d: "M22 11.08V12a10 10 0 1 1-5.93-9.14" }),
278
+ /* @__PURE__ */ jsx("polyline", { points: "22 4 12 14.01 9 11.01" })
279
+ ] });
280
+ }
281
+ function PenIcon() {
282
+ return /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
283
+ /* @__PURE__ */ jsx("path", { d: "M12 19l7-7 3 3-7 7-3-3z" }),
284
+ /* @__PURE__ */ jsx("path", { d: "M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z" }),
285
+ /* @__PURE__ */ jsx("path", { d: "M2 2l7.586 7.586" }),
286
+ /* @__PURE__ */ jsx("circle", { cx: "11", cy: "11", r: "2" })
287
+ ] });
288
+ }
289
+ function RectIcon() {
290
+ return /* @__PURE__ */ jsx("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: /* @__PURE__ */ jsx("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2", ry: "2" }) });
291
+ }
292
+ function ArrowIcon() {
293
+ return /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
294
+ /* @__PURE__ */ jsx("line", { x1: "5", y1: "19", x2: "19", y2: "5" }),
295
+ /* @__PURE__ */ jsx("polyline", { points: "13 5 19 5 19 11" })
296
+ ] });
297
+ }
298
+ function TextIcon() {
299
+ return /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
300
+ /* @__PURE__ */ jsx("polyline", { points: "4 7 4 4 20 4 20 7" }),
301
+ /* @__PURE__ */ jsx("line", { x1: "9", y1: "20", x2: "15", y2: "20" }),
302
+ /* @__PURE__ */ jsx("line", { x1: "12", y1: "4", x2: "12", y2: "20" })
303
+ ] });
304
+ }
305
+ function UndoIcon() {
306
+ return /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
307
+ /* @__PURE__ */ jsx("polyline", { points: "9 14 4 9 9 4" }),
308
+ /* @__PURE__ */ jsx("path", { d: "M20 20v-7a4 4 0 0 0-4-4H4" })
309
+ ] });
310
+ }
311
+ function RedoIcon() {
312
+ return /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
313
+ /* @__PURE__ */ jsx("polyline", { points: "15 14 20 9 15 4" }),
314
+ /* @__PURE__ */ jsx("path", { d: "M4 20v-7a4 4 0 0 1 4-4h12" })
315
+ ] });
316
+ }
317
+ function TrashIcon() {
318
+ return /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [
319
+ /* @__PURE__ */ jsx("polyline", { points: "3 6 5 6 21 6" }),
320
+ /* @__PURE__ */ jsx("path", { d: "M19 6l-1 14H6L5 6" }),
321
+ /* @__PURE__ */ jsx("path", { d: "M10 11v6M14 11v6" }),
322
+ /* @__PURE__ */ jsx("path", { d: "M9 6V4h6v2" })
323
+ ] });
324
+ }
325
+ function FeedbackWidget({
326
+ title = "Admin feedback",
327
+ submitLabel = "Send",
328
+ uploadLabel = "Upload image",
329
+ allowScreenshotUpload = true,
330
+ screenshotMaxFileSizeBytes = 5 * 1024 * 1024,
331
+ screenshotAllowedMimeTypes = ["image/png", "image/jpeg", "image/webp"],
332
+ capturePolicy = "current-tab-first",
333
+ onSubmit,
334
+ onUpload,
335
+ onDeleteScreenshot
336
+ }) {
337
+ const [open, setOpen] = React.useState(false);
338
+ const [message, setMessage] = React.useState("");
339
+ const [captureMode, setCaptureMode] = React.useState(false);
340
+ const [captureData, setCaptureData] = React.useState(null);
341
+ const [screenshotId, setScreenshotId] = React.useState(null);
342
+ const [screenshotPreviewUrl, setScreenshotPreviewUrl] = React.useState(null);
343
+ const [uploading, setUploading] = React.useState(false);
344
+ const [deletingScreenshot, setDeletingScreenshot] = React.useState(false);
345
+ const [submitting, setSubmitting] = React.useState(false);
346
+ const [submitted, setSubmitted] = React.useState(false);
347
+ const [currentPath, setCurrentPath] = React.useState("");
348
+ const [capturingScreen, setCapturingScreen] = React.useState(false);
349
+ const [error, setError] = React.useState(null);
350
+ const [notice, setNotice] = React.useState(null);
351
+ const [annotating, setAnnotating] = React.useState(false);
352
+ const [editorImage, setEditorImage] = React.useState(null);
353
+ const [editorHistory, setEditorHistory] = React.useState(DEFAULT_HISTORY);
354
+ const [draftOperation, setDraftOperation] = React.useState(null);
355
+ const [annotationTool, setAnnotationTool] = React.useState("pen");
356
+ const [annotationColor, setAnnotationColor] = React.useState(DEFAULT_COLORS[0]);
357
+ const [annotationSize, setAnnotationSize] = React.useState(4);
358
+ const [textCursor, setTextCursor] = React.useState(null);
359
+ const [inlineText, setInlineText] = React.useState("");
360
+ const hoverTargetRef = React.useRef(null);
361
+ const annotationCanvasRef = React.useRef(null);
362
+ const annotationScrollRef = React.useRef(null);
363
+ const textInputRef = React.useRef(null);
364
+ const pointerIdRef = React.useRef(null);
365
+ const draftOperationRef = React.useRef(null);
366
+ const inlineTextRef = React.useRef("");
367
+ const textCursorRef = React.useRef(null);
368
+ const annotationColorRef = React.useRef(DEFAULT_COLORS[0]);
369
+ const annotationSizeRef = React.useRef(4);
370
+ React.useEffect(() => {
371
+ draftOperationRef.current = draftOperation;
372
+ }, [draftOperation]);
373
+ React.useEffect(() => {
374
+ inlineTextRef.current = inlineText;
375
+ }, [inlineText]);
376
+ React.useEffect(() => {
377
+ textCursorRef.current = textCursor;
378
+ }, [textCursor]);
379
+ React.useEffect(() => {
380
+ annotationColorRef.current = annotationColor;
381
+ }, [annotationColor]);
382
+ React.useEffect(() => {
383
+ annotationSizeRef.current = annotationSize;
384
+ }, [annotationSize]);
385
+ React.useEffect(() => {
386
+ if (!captureMode) {
387
+ return;
388
+ }
389
+ const clearOutline = () => {
390
+ if (hoverTargetRef.current instanceof HTMLElement) {
391
+ hoverTargetRef.current.style.outline = "";
392
+ }
393
+ hoverTargetRef.current = null;
394
+ };
395
+ const onMouseMove = (event) => {
396
+ const target = event.target;
397
+ if (!(target instanceof HTMLElement)) {
398
+ return;
399
+ }
400
+ if (hoverTargetRef.current !== target) {
401
+ clearOutline();
402
+ target.style.outline = "2px dashed #22c55e";
403
+ hoverTargetRef.current = target;
404
+ }
405
+ };
406
+ const onClick = (event) => {
407
+ event.preventDefault();
408
+ event.stopPropagation();
409
+ const target = event.target;
410
+ if (!(target instanceof HTMLElement)) {
411
+ return;
412
+ }
413
+ setCaptureData({
414
+ selector: getCssSelector(target),
415
+ selectedText: target.textContent?.trim().slice(0, 200) || ""
416
+ });
417
+ clearOutline();
418
+ setCaptureMode(false);
419
+ };
420
+ document.addEventListener("mousemove", onMouseMove, true);
421
+ document.addEventListener("click", onClick, true);
422
+ return () => {
423
+ clearOutline();
424
+ document.removeEventListener("mousemove", onMouseMove, true);
425
+ document.removeEventListener("click", onClick, true);
426
+ };
427
+ }, [captureMode]);
428
+ React.useEffect(() => {
429
+ if (!annotating) {
430
+ return;
431
+ }
432
+ const previousOverflow = document.body.style.overflow;
433
+ document.body.style.overflow = "hidden";
434
+ return () => {
435
+ document.body.style.overflow = previousOverflow;
436
+ };
437
+ }, [annotating]);
438
+ React.useEffect(() => {
439
+ if (!annotating || !editorImage || !annotationCanvasRef.current) {
440
+ return;
441
+ }
442
+ const canvas = annotationCanvasRef.current;
443
+ canvas.width = editorImage.width;
444
+ canvas.height = editorImage.height;
445
+ const context = canvas.getContext("2d");
446
+ if (!context) {
447
+ setError("Browser does not support canvas context.");
448
+ return;
449
+ }
450
+ context.clearRect(0, 0, canvas.width, canvas.height);
451
+ context.drawImage(editorImage.element, 0, 0, canvas.width, canvas.height);
452
+ for (const operation of editorHistory.operations) {
453
+ drawOperation(context, operation);
454
+ }
455
+ if (draftOperation) {
456
+ drawOperation(context, draftOperation);
457
+ }
458
+ }, [annotating, draftOperation, editorHistory.operations, editorImage]);
459
+ React.useEffect(() => {
460
+ setCurrentPath(window.location.pathname);
461
+ }, []);
462
+ React.useEffect(() => {
463
+ if (!submitted) return;
464
+ const timer = setTimeout(() => {
465
+ setOpen(false);
466
+ setSubmitted(false);
467
+ }, 2500);
468
+ return () => clearTimeout(timer);
469
+ }, [submitted]);
470
+ const validateImageFile = React.useCallback(
471
+ (file) => {
472
+ if (!screenshotAllowedMimeTypes.includes(file.type)) {
473
+ return `Supported image types: ${screenshotAllowedMimeTypes.join(", ")}`;
474
+ }
475
+ if (file.size > screenshotMaxFileSizeBytes) {
476
+ return `Image is too large. Maximum size: ${Math.round(screenshotMaxFileSizeBytes / 1024 / 1024)}MB.`;
477
+ }
478
+ return null;
479
+ },
480
+ [screenshotAllowedMimeTypes, screenshotMaxFileSizeBytes]
481
+ );
482
+ const uploadImageFile = React.useCallback(
483
+ async (file) => {
484
+ if (!onUpload) {
485
+ return false;
486
+ }
487
+ setError(null);
488
+ setUploading(true);
489
+ try {
490
+ const formData = new FormData();
491
+ formData.append("file", file);
492
+ formData.append("alt", file.name);
493
+ const result = await onUpload(formData);
494
+ if (result.success) {
495
+ setScreenshotId(result.mediaId);
496
+ setNotice("Annotated screenshot uploaded.");
497
+ return true;
498
+ }
499
+ setError(result.error);
500
+ return false;
501
+ } finally {
502
+ setUploading(false);
503
+ }
504
+ },
505
+ [onUpload]
506
+ );
507
+ const closeAnnotationEditor = React.useCallback(() => {
508
+ setAnnotating(false);
509
+ setEditorImage(null);
510
+ setEditorHistory(DEFAULT_HISTORY);
511
+ setDraftOperation(null);
512
+ setTextCursor(null);
513
+ setInlineText("");
514
+ draftOperationRef.current = null;
515
+ }, []);
516
+ const handleStartAnnotation = React.useCallback(
517
+ async (file) => {
518
+ const validationError = validateImageFile(file);
519
+ if (validationError) {
520
+ setError(validationError);
521
+ return;
522
+ }
523
+ try {
524
+ const nextImage = await createEditorImage(file);
525
+ setEditorImage(nextImage);
526
+ setEditorHistory(DEFAULT_HISTORY);
527
+ setDraftOperation(null);
528
+ setTextCursor(null);
529
+ setInlineText("");
530
+ draftOperationRef.current = null;
531
+ setAnnotating(true);
532
+ setError(null);
533
+ } catch (nextError) {
534
+ setError(nextError instanceof Error ? nextError.message : "Failed to process image.");
535
+ }
536
+ },
537
+ [validateImageFile]
538
+ );
539
+ React.useEffect(() => {
540
+ if (!open || !allowScreenshotUpload) {
541
+ return;
542
+ }
543
+ const onPaste = async (event) => {
544
+ const file = Array.from(event.clipboardData?.items || []).find((item) => item.type.startsWith("image/"))?.getAsFile();
545
+ if (!file) {
546
+ return;
547
+ }
548
+ event.preventDefault();
549
+ await handleStartAnnotation(file);
550
+ };
551
+ window.addEventListener("paste", onPaste);
552
+ return () => window.removeEventListener("paste", onPaste);
553
+ }, [allowScreenshotUpload, handleStartAnnotation, open]);
554
+ const commitOperations = React.useCallback((nextOperations) => {
555
+ setEditorHistory((current) => ({
556
+ operations: nextOperations,
557
+ redoStack: [],
558
+ undoStack: [...current.undoStack, current.operations]
559
+ }));
560
+ }, []);
561
+ const appendOperation = React.useCallback((operation) => {
562
+ setEditorHistory((current) => ({
563
+ operations: [...current.operations, operation],
564
+ redoStack: [],
565
+ undoStack: [...current.undoStack, current.operations]
566
+ }));
567
+ }, []);
568
+ const commitTextInput = React.useCallback(() => {
569
+ const text = inlineTextRef.current.trim();
570
+ const cursor = textCursorRef.current;
571
+ if (text && cursor) {
572
+ const operation = {
573
+ id: createOperationId(),
574
+ type: "text",
575
+ style: { color: annotationColorRef.current, size: annotationSizeRef.current },
576
+ point: cursor.canvasPoint,
577
+ text
578
+ };
579
+ appendOperation(operation);
580
+ }
581
+ textCursorRef.current = null;
582
+ setTextCursor(null);
583
+ setInlineText("");
584
+ }, [appendOperation]);
585
+ const handleUpload = async (event) => {
586
+ const file = event.target.files?.[0];
587
+ if (file) {
588
+ await handleStartAnnotation(file);
589
+ }
590
+ event.target.value = "";
591
+ };
592
+ const handleCaptureScreenshot = async () => {
593
+ try {
594
+ setError(null);
595
+ setCapturingScreen(true);
596
+ await new Promise((resolve) => setTimeout(resolve, 120));
597
+ const { file, surface } = await captureScreenshotFile(capturePolicy);
598
+ if (capturePolicy === "current-tab-first") {
599
+ if (surface === "browser") {
600
+ setNotice("Captured the current tab.");
601
+ } else if (surface) {
602
+ setNotice(`Captured a ${surface} surface because the browser allowed a broader selection.`);
603
+ } else {
604
+ setNotice("Captured a screenshot.");
605
+ }
606
+ } else if (capturePolicy === "strict-current-tab") {
607
+ setNotice("Captured the current tab.");
608
+ } else {
609
+ setNotice("Captured a screenshot.");
610
+ }
611
+ await handleStartAnnotation(file);
612
+ } catch (nextError) {
613
+ setError(nextError instanceof Error ? nextError.message : "Screen capture failed.");
614
+ } finally {
615
+ setCapturingScreen(false);
616
+ }
617
+ };
618
+ const handleUndo = () => {
619
+ setEditorHistory((current) => {
620
+ if (current.undoStack.length === 0) {
621
+ return current;
622
+ }
623
+ const previousOperations = current.undoStack[current.undoStack.length - 1];
624
+ return {
625
+ operations: previousOperations,
626
+ redoStack: [current.operations, ...current.redoStack],
627
+ undoStack: current.undoStack.slice(0, -1)
628
+ };
629
+ });
630
+ };
631
+ const handleRedo = () => {
632
+ setEditorHistory((current) => {
633
+ if (current.redoStack.length === 0) {
634
+ return current;
635
+ }
636
+ const [nextOperations, ...remainingRedo] = current.redoStack;
637
+ return {
638
+ operations: nextOperations,
639
+ redoStack: remainingRedo,
640
+ undoStack: [...current.undoStack, current.operations]
641
+ };
642
+ });
643
+ };
644
+ const handleClearAnnotations = () => {
645
+ if (editorHistory.operations.length === 0) {
646
+ return;
647
+ }
648
+ commitOperations([]);
649
+ };
650
+ const handleCanvasPointerDown = (event) => {
651
+ if (!annotationCanvasRef.current) {
652
+ return;
653
+ }
654
+ setError(null);
655
+ const canvas = annotationCanvasRef.current;
656
+ const canvasPoint = getCanvasPoint(event, canvas);
657
+ if (annotationTool === "text") {
658
+ const existingText = inlineTextRef.current.trim();
659
+ const existingCursor = textCursorRef.current;
660
+ if (existingText && existingCursor) {
661
+ appendOperation({
662
+ id: createOperationId(),
663
+ type: "text",
664
+ style: { color: annotationColorRef.current, size: annotationSizeRef.current },
665
+ point: existingCursor.canvasPoint,
666
+ text: existingText
667
+ });
668
+ }
669
+ const domX = event.clientX;
670
+ const domY = event.clientY;
671
+ inlineTextRef.current = "";
672
+ textCursorRef.current = { domX, domY, canvasPoint };
673
+ setInlineText("");
674
+ setTextCursor({ domX, domY, canvasPoint });
675
+ return;
676
+ }
677
+ event.preventDefault();
678
+ canvas.setPointerCapture(event.pointerId);
679
+ pointerIdRef.current = event.pointerId;
680
+ const style = { color: annotationColor, size: annotationSize };
681
+ const nextDraft = annotationTool === "pen" ? {
682
+ id: createOperationId(),
683
+ type: "pen",
684
+ style,
685
+ points: [canvasPoint]
686
+ } : annotationTool === "rectangle" ? {
687
+ id: createOperationId(),
688
+ type: "rectangle",
689
+ style,
690
+ start: canvasPoint,
691
+ end: canvasPoint
692
+ } : {
693
+ id: createOperationId(),
694
+ type: "arrow",
695
+ style,
696
+ start: canvasPoint,
697
+ end: canvasPoint
698
+ };
699
+ draftOperationRef.current = nextDraft;
700
+ setDraftOperation(nextDraft);
701
+ };
702
+ const handleCanvasPointerMove = (event) => {
703
+ if (!annotationCanvasRef.current || pointerIdRef.current !== event.pointerId) {
704
+ return;
705
+ }
706
+ const activeDraft = draftOperationRef.current;
707
+ if (!activeDraft) {
708
+ return;
709
+ }
710
+ const point = getCanvasPoint(event, annotationCanvasRef.current);
711
+ const nextDraft = activeDraft.type === "pen" ? {
712
+ ...activeDraft,
713
+ points: [...activeDraft.points, point]
714
+ } : {
715
+ ...activeDraft,
716
+ end: point
717
+ };
718
+ draftOperationRef.current = nextDraft;
719
+ setDraftOperation(nextDraft);
720
+ };
721
+ const handleCanvasPointerUp = (event) => {
722
+ if (!annotationCanvasRef.current || pointerIdRef.current !== event.pointerId) {
723
+ return;
724
+ }
725
+ const canvas = annotationCanvasRef.current;
726
+ if (canvas.hasPointerCapture(event.pointerId)) {
727
+ canvas.releasePointerCapture(event.pointerId);
728
+ }
729
+ pointerIdRef.current = null;
730
+ const activeDraft = draftOperationRef.current;
731
+ draftOperationRef.current = null;
732
+ setDraftOperation(null);
733
+ if (!activeDraft) {
734
+ return;
735
+ }
736
+ if (activeDraft.type === "pen") {
737
+ const points = activeDraft.points.length === 1 ? [...activeDraft.points, activeDraft.points[0]] : activeDraft.points;
738
+ appendOperation({ ...activeDraft, points });
739
+ return;
740
+ }
741
+ if (!isShapeMeaningful(activeDraft.start, activeDraft.end)) {
742
+ return;
743
+ }
744
+ appendOperation(activeDraft);
745
+ };
746
+ const handleCanvasPointerCancel = (event) => {
747
+ if (annotationCanvasRef.current && pointerIdRef.current === event.pointerId && annotationCanvasRef.current.hasPointerCapture(event.pointerId)) {
748
+ annotationCanvasRef.current.releasePointerCapture(event.pointerId);
749
+ }
750
+ pointerIdRef.current = null;
751
+ draftOperationRef.current = null;
752
+ setDraftOperation(null);
753
+ };
754
+ const handleApplyAnnotation = async () => {
755
+ if (!annotationCanvasRef.current || !editorImage) {
756
+ return;
757
+ }
758
+ try {
759
+ const previewUrl = annotationCanvasRef.current.toDataURL("image/png");
760
+ const file = await canvasToFile(annotationCanvasRef.current, editorImage.fileName);
761
+ const uploaded = await uploadImageFile(file);
762
+ if (uploaded) {
763
+ setScreenshotPreviewUrl(previewUrl);
764
+ closeAnnotationEditor();
765
+ }
766
+ } catch (nextError) {
767
+ setError(nextError instanceof Error ? nextError.message : "Failed to export image.");
768
+ }
769
+ };
770
+ const handleRemoveScreenshot = async () => {
771
+ if (!screenshotId) {
772
+ setScreenshotPreviewUrl(null);
773
+ return;
774
+ }
775
+ if (!onDeleteScreenshot) {
776
+ setScreenshotId(null);
777
+ setScreenshotPreviewUrl(null);
778
+ return;
779
+ }
780
+ setDeletingScreenshot(true);
781
+ setError(null);
782
+ try {
783
+ const result = await onDeleteScreenshot(screenshotId);
784
+ if (!result.success) {
785
+ setError(result.error);
786
+ return;
787
+ }
788
+ setScreenshotId(null);
789
+ setScreenshotPreviewUrl(null);
790
+ setNotice("Screenshot removed.");
791
+ } finally {
792
+ setDeletingScreenshot(false);
793
+ }
794
+ };
795
+ const handleSubmit = async () => {
796
+ if (!message.trim()) {
797
+ setError("Please enter a message.");
798
+ return;
799
+ }
800
+ setSubmitting(true);
801
+ setError(null);
802
+ const result = await onSubmit({
803
+ message: message.trim(),
804
+ pagePath: currentPath,
805
+ selector: captureData?.selector,
806
+ selectedText: captureData?.selectedText,
807
+ screenshotId,
808
+ meta: {
809
+ userAgent: window.navigator.userAgent,
810
+ locale: window.navigator.language,
811
+ viewport: `${window.innerWidth}x${window.innerHeight}`
812
+ }
813
+ });
814
+ setSubmitting(false);
815
+ if (!result.success) {
816
+ setError(result.error);
817
+ return;
818
+ }
819
+ setMessage("");
820
+ setCaptureData(null);
821
+ setScreenshotId(null);
822
+ setScreenshotPreviewUrl(null);
823
+ setNotice(null);
824
+ setSubmitted(true);
825
+ };
826
+ const currentHasUndo = editorHistory.undoStack.length > 0;
827
+ const currentHasRedo = editorHistory.redoStack.length > 0;
828
+ const hasAnnotations = editorHistory.operations.length > 0;
829
+ const toolBtn = (tool, icon, label) => /* @__PURE__ */ jsxs(
830
+ "button",
831
+ {
832
+ type: "button",
833
+ title: label,
834
+ onClick: () => setAnnotationTool(tool),
835
+ style: {
836
+ display: "flex",
837
+ alignItems: "center",
838
+ gap: "5px",
839
+ borderRadius: "6px",
840
+ border: annotationTool === tool ? "1px solid #4ade80" : "1px solid #334155",
841
+ background: annotationTool === tool ? "rgba(74,222,128,0.12)" : "#0f172a",
842
+ color: annotationTool === tool ? "#4ade80" : "#94a3b8",
843
+ padding: "5px 9px",
844
+ cursor: "pointer",
845
+ fontSize: "12px",
846
+ fontWeight: 500
847
+ },
848
+ children: [
849
+ icon,
850
+ label
851
+ ]
852
+ },
853
+ tool
854
+ );
855
+ const iconBtn = (onClick, icon, label, disabled = false) => /* @__PURE__ */ jsxs(
856
+ "button",
857
+ {
858
+ type: "button",
859
+ title: label,
860
+ onClick,
861
+ disabled,
862
+ style: {
863
+ display: "flex",
864
+ alignItems: "center",
865
+ gap: "4px",
866
+ borderRadius: "6px",
867
+ border: "1px solid #334155",
868
+ background: "#0f172a",
869
+ color: disabled ? "#475569" : "#94a3b8",
870
+ padding: "5px 9px",
871
+ cursor: disabled ? "not-allowed" : "pointer",
872
+ fontSize: "12px"
873
+ },
874
+ children: [
875
+ icon,
876
+ label
877
+ ]
878
+ }
879
+ );
880
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
881
+ /* @__PURE__ */ jsx("style", { children: `
882
+ @keyframes afb-spin-in {
883
+ from { transform: rotate(-90deg) scale(0.7); opacity: 0; }
884
+ to { transform: rotate(0deg) scale(1); opacity: 1; }
885
+ }
886
+ .afb-icon-enter {
887
+ animation: afb-spin-in 0.18s ease forwards;
888
+ }
889
+ ` }),
890
+ /* @__PURE__ */ jsx(
891
+ "button",
892
+ {
893
+ type: "button",
894
+ onClick: () => {
895
+ if (submitted) return;
896
+ setOpen((v) => !v);
897
+ },
898
+ title: open ? "Close feedback" : "Send feedback",
899
+ style: {
900
+ position: "fixed",
901
+ right: "20px",
902
+ bottom: "20px",
903
+ zIndex: 9999,
904
+ width: "48px",
905
+ height: "48px",
906
+ borderRadius: "50%",
907
+ backgroundColor: open ? "#374151" : "#15803d",
908
+ color: "#ffffff",
909
+ border: "none",
910
+ display: "flex",
911
+ alignItems: "center",
912
+ justifyContent: "center",
913
+ cursor: "pointer",
914
+ boxShadow: "0 4px 14px rgba(0,0,0,0.4)",
915
+ transition: "background-color 0.2s ease, transform 0.15s ease",
916
+ visibility: capturingScreen ? "hidden" : "visible"
917
+ },
918
+ children: /* @__PURE__ */ jsx("span", { className: "afb-icon-enter", children: open ? /* @__PURE__ */ jsx(XIcon, { size: 20 }) : /* @__PURE__ */ jsx(ChatIcon, {}) }, open ? "x" : "chat")
919
+ }
920
+ ),
921
+ /* @__PURE__ */ jsx(
922
+ "div",
923
+ {
924
+ style: {
925
+ position: "fixed",
926
+ right: "20px",
927
+ bottom: "80px",
928
+ width: "360px",
929
+ background: "#0f172a",
930
+ color: "#f1f5f9",
931
+ borderRadius: "14px",
932
+ border: "1px solid #1e293b",
933
+ padding: "0",
934
+ zIndex: 9999,
935
+ boxShadow: "0 16px 48px rgba(0,0,0,0.55)",
936
+ display: "flex",
937
+ flexDirection: "column",
938
+ maxHeight: "calc(100vh - 110px)",
939
+ opacity: open ? 1 : 0,
940
+ transform: open ? "scale(1) translateY(0)" : "scale(0.92) translateY(8px)",
941
+ pointerEvents: open ? "auto" : "none",
942
+ transformOrigin: "bottom right",
943
+ transition: "opacity 0.18s ease, transform 0.18s ease",
944
+ visibility: capturingScreen ? "hidden" : "visible",
945
+ overflow: "hidden"
946
+ },
947
+ children: submitted ? (
948
+ /* ── Success screen ── */
949
+ /* @__PURE__ */ jsxs(
950
+ "div",
951
+ {
952
+ style: {
953
+ display: "flex",
954
+ flexDirection: "column",
955
+ alignItems: "center",
956
+ justifyContent: "center",
957
+ gap: "12px",
958
+ padding: "40px 24px",
959
+ textAlign: "center",
960
+ color: "#4ade80"
961
+ },
962
+ children: [
963
+ /* @__PURE__ */ jsx(CheckCircleIcon, {}),
964
+ /* @__PURE__ */ jsxs("div", { children: [
965
+ /* @__PURE__ */ jsx("p", { style: { margin: "0 0 4px", fontSize: "16px", fontWeight: 600, color: "#f1f5f9" }, children: "Feedback sent!" }),
966
+ /* @__PURE__ */ jsx("p", { style: { margin: 0, fontSize: "13px", color: "#94a3b8" }, children: "Thank you \u2014 we'll take a look." })
967
+ ] })
968
+ ]
969
+ }
970
+ )
971
+ ) : /* @__PURE__ */ jsxs(Fragment, { children: [
972
+ /* @__PURE__ */ jsxs(
973
+ "div",
974
+ {
975
+ style: {
976
+ display: "flex",
977
+ alignItems: "center",
978
+ justifyContent: "space-between",
979
+ padding: "12px 14px 10px",
980
+ borderBottom: "1px solid #1e293b"
981
+ },
982
+ children: [
983
+ /* @__PURE__ */ jsxs("div", { children: [
984
+ /* @__PURE__ */ jsx("p", { style: { margin: 0, fontSize: "14px", fontWeight: 600, color: "#f1f5f9" }, children: title }),
985
+ /* @__PURE__ */ jsx("p", { style: { margin: "2px 0 0", fontSize: "11px", color: "#64748b" }, children: currentPath })
986
+ ] }),
987
+ /* @__PURE__ */ jsx(
988
+ "button",
989
+ {
990
+ type: "button",
991
+ onClick: () => setOpen(false),
992
+ title: "Close",
993
+ style: {
994
+ background: "none",
995
+ border: "none",
996
+ color: "#64748b",
997
+ cursor: "pointer",
998
+ padding: "4px",
999
+ display: "flex",
1000
+ alignItems: "center",
1001
+ borderRadius: "6px"
1002
+ },
1003
+ children: /* @__PURE__ */ jsx(XIcon, { size: 16 })
1004
+ }
1005
+ )
1006
+ ]
1007
+ }
1008
+ ),
1009
+ /* @__PURE__ */ jsxs("div", { style: { padding: "12px 14px", display: "flex", flexDirection: "column", gap: "10px", overflowY: "auto", minHeight: 0 }, children: [
1010
+ /* @__PURE__ */ jsx(
1011
+ "textarea",
1012
+ {
1013
+ value: message,
1014
+ onChange: (event) => setMessage(event.target.value),
1015
+ rows: 5,
1016
+ placeholder: "Describe the issue or share your thoughts\u2026",
1017
+ style: {
1018
+ width: "100%",
1019
+ borderRadius: "8px",
1020
+ border: "1px solid #1e293b",
1021
+ background: "#1e293b",
1022
+ color: "#f1f5f9",
1023
+ padding: "10px",
1024
+ resize: "vertical",
1025
+ fontSize: "13px",
1026
+ lineHeight: "1.5",
1027
+ outline: "none",
1028
+ boxSizing: "border-box"
1029
+ }
1030
+ }
1031
+ ),
1032
+ allowScreenshotUpload && onUpload ? /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "6px", flexWrap: "wrap" }, children: [
1033
+ /* @__PURE__ */ jsxs(
1034
+ "button",
1035
+ {
1036
+ type: "button",
1037
+ onClick: handleCaptureScreenshot,
1038
+ style: {
1039
+ display: "flex",
1040
+ alignItems: "center",
1041
+ gap: "5px",
1042
+ borderRadius: "7px",
1043
+ border: "1px solid #1e293b",
1044
+ background: "#1e293b",
1045
+ color: "#94a3b8",
1046
+ padding: "5px 9px",
1047
+ cursor: "pointer",
1048
+ fontSize: "12px"
1049
+ },
1050
+ children: [
1051
+ /* @__PURE__ */ jsx(CameraIcon, {}),
1052
+ "Capture screen"
1053
+ ]
1054
+ }
1055
+ ),
1056
+ /* @__PURE__ */ jsxs(
1057
+ "button",
1058
+ {
1059
+ type: "button",
1060
+ onClick: () => setCaptureMode((v) => !v),
1061
+ style: {
1062
+ display: "flex",
1063
+ alignItems: "center",
1064
+ gap: "5px",
1065
+ borderRadius: "7px",
1066
+ border: captureMode ? "1px solid #4ade80" : "1px solid #1e293b",
1067
+ background: captureMode ? "rgba(74,222,128,0.08)" : "#1e293b",
1068
+ color: captureMode ? "#4ade80" : "#94a3b8",
1069
+ padding: "5px 9px",
1070
+ cursor: "pointer",
1071
+ fontSize: "12px"
1072
+ },
1073
+ children: [
1074
+ /* @__PURE__ */ jsx(CursorIcon, {}),
1075
+ captureMode ? "Click an element\u2026" : "Capture element"
1076
+ ]
1077
+ }
1078
+ ),
1079
+ /* @__PURE__ */ jsxs(
1080
+ "label",
1081
+ {
1082
+ style: {
1083
+ display: "flex",
1084
+ alignItems: "center",
1085
+ gap: "5px",
1086
+ borderRadius: "7px",
1087
+ border: "1px solid #1e293b",
1088
+ background: "#1e293b",
1089
+ color: "#94a3b8",
1090
+ padding: "5px 9px",
1091
+ cursor: "pointer",
1092
+ fontSize: "12px"
1093
+ },
1094
+ children: [
1095
+ /* @__PURE__ */ jsx(UploadIcon, {}),
1096
+ uploading ? "Uploading\u2026" : uploadLabel,
1097
+ /* @__PURE__ */ jsx(
1098
+ "input",
1099
+ {
1100
+ type: "file",
1101
+ accept: screenshotAllowedMimeTypes.join(","),
1102
+ onChange: handleUpload,
1103
+ hidden: true
1104
+ }
1105
+ )
1106
+ ]
1107
+ }
1108
+ )
1109
+ ] }) : /* @__PURE__ */ jsx("div", { style: { display: "flex", gap: "6px", flexWrap: "wrap" }, children: /* @__PURE__ */ jsxs(
1110
+ "button",
1111
+ {
1112
+ type: "button",
1113
+ onClick: () => setCaptureMode((v) => !v),
1114
+ style: {
1115
+ display: "flex",
1116
+ alignItems: "center",
1117
+ gap: "5px",
1118
+ borderRadius: "7px",
1119
+ border: captureMode ? "1px solid #4ade80" : "1px solid #1e293b",
1120
+ background: captureMode ? "rgba(74,222,128,0.08)" : "#1e293b",
1121
+ color: captureMode ? "#4ade80" : "#94a3b8",
1122
+ padding: "5px 9px",
1123
+ cursor: "pointer",
1124
+ fontSize: "12px"
1125
+ },
1126
+ children: [
1127
+ /* @__PURE__ */ jsx(CursorIcon, {}),
1128
+ captureMode ? "Click an element\u2026" : "Capture element"
1129
+ ]
1130
+ }
1131
+ ) }),
1132
+ allowScreenshotUpload && onUpload ? /* @__PURE__ */ jsx("p", { style: { margin: 0, fontSize: "11px", color: "#475569" }, children: "Paste an image with Ctrl/Cmd+V or capture the current tab first." }) : null,
1133
+ captureData ? /* @__PURE__ */ jsxs("p", { style: { margin: 0, fontSize: "11px", color: "#64748b", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: [
1134
+ "Element: ",
1135
+ /* @__PURE__ */ jsx("code", { style: { color: "#94a3b8" }, children: captureData.selector })
1136
+ ] }) : null,
1137
+ screenshotId ? /* @__PURE__ */ jsxs(
1138
+ "div",
1139
+ {
1140
+ style: {
1141
+ borderRadius: "10px",
1142
+ border: "1px solid #1e293b",
1143
+ background: "#0a0f1e",
1144
+ padding: "8px"
1145
+ },
1146
+ children: [
1147
+ screenshotPreviewUrl ? /* @__PURE__ */ jsx("div", { style: { marginBottom: "8px", borderRadius: "6px", overflow: "hidden" }, children: /* @__PURE__ */ jsx(
1148
+ "img",
1149
+ {
1150
+ src: screenshotPreviewUrl,
1151
+ alt: "Annotated screenshot preview",
1152
+ style: { width: "100%", height: "auto", display: "block" }
1153
+ }
1154
+ ) }) : null,
1155
+ /* @__PURE__ */ jsxs(
1156
+ "div",
1157
+ {
1158
+ style: {
1159
+ display: "flex",
1160
+ justifyContent: "space-between",
1161
+ alignItems: "center"
1162
+ },
1163
+ children: [
1164
+ /* @__PURE__ */ jsx("p", { style: { margin: 0, fontSize: "11px", color: "#64748b" }, children: "Screenshot attached" }),
1165
+ /* @__PURE__ */ jsxs(
1166
+ "button",
1167
+ {
1168
+ type: "button",
1169
+ onClick: handleRemoveScreenshot,
1170
+ disabled: deletingScreenshot,
1171
+ style: {
1172
+ display: "flex",
1173
+ alignItems: "center",
1174
+ gap: "4px",
1175
+ borderRadius: "6px",
1176
+ border: "1px solid #7f1d1d",
1177
+ background: "#450a0a",
1178
+ color: "#fca5a5",
1179
+ padding: "3px 8px",
1180
+ cursor: deletingScreenshot ? "wait" : "pointer",
1181
+ opacity: deletingScreenshot ? 0.7 : 1,
1182
+ fontSize: "11px"
1183
+ },
1184
+ children: [
1185
+ /* @__PURE__ */ jsx(TrashIcon, {}),
1186
+ deletingScreenshot ? "Removing\u2026" : "Remove"
1187
+ ]
1188
+ }
1189
+ )
1190
+ ]
1191
+ }
1192
+ )
1193
+ ]
1194
+ }
1195
+ ) : null,
1196
+ notice ? /* @__PURE__ */ jsx("p", { style: { margin: 0, color: "#93c5fd", fontSize: "12px" }, children: notice }) : null,
1197
+ error ? /* @__PURE__ */ jsx("p", { style: { margin: 0, color: "#fca5a5", fontSize: "12px" }, children: error }) : null
1198
+ ] }),
1199
+ /* @__PURE__ */ jsx(
1200
+ "div",
1201
+ {
1202
+ style: {
1203
+ display: "flex",
1204
+ justifyContent: "flex-end",
1205
+ padding: "10px 14px 14px",
1206
+ borderTop: "1px solid #1e293b"
1207
+ },
1208
+ children: /* @__PURE__ */ jsxs(
1209
+ "button",
1210
+ {
1211
+ type: "button",
1212
+ onClick: handleSubmit,
1213
+ disabled: submitting,
1214
+ style: {
1215
+ display: "flex",
1216
+ alignItems: "center",
1217
+ gap: "7px",
1218
+ borderRadius: "8px",
1219
+ border: "none",
1220
+ background: "#15803d",
1221
+ color: "#f1f5f9",
1222
+ padding: "8px 16px",
1223
+ cursor: submitting ? "wait" : "pointer",
1224
+ fontWeight: 600,
1225
+ fontSize: "13px",
1226
+ opacity: submitting ? 0.75 : 1,
1227
+ transition: "opacity 0.15s ease"
1228
+ },
1229
+ children: [
1230
+ /* @__PURE__ */ jsx(SendIcon, {}),
1231
+ submitting ? "Sending\u2026" : submitLabel
1232
+ ]
1233
+ }
1234
+ )
1235
+ }
1236
+ )
1237
+ ] })
1238
+ }
1239
+ ),
1240
+ annotating && editorImage ? /* @__PURE__ */ jsxs(
1241
+ "div",
1242
+ {
1243
+ style: {
1244
+ position: "fixed",
1245
+ inset: "0",
1246
+ zIndex: 1e4,
1247
+ background: "rgba(3, 7, 18, 0.96)",
1248
+ color: "#f8fafc",
1249
+ display: "flex",
1250
+ flexDirection: "column"
1251
+ },
1252
+ children: [
1253
+ /* @__PURE__ */ jsxs(
1254
+ "div",
1255
+ {
1256
+ style: {
1257
+ display: "flex",
1258
+ flexWrap: "wrap",
1259
+ gap: "10px",
1260
+ alignItems: "center",
1261
+ justifyContent: "space-between",
1262
+ padding: "10px 16px",
1263
+ borderBottom: "1px solid rgba(148, 163, 184, 0.15)",
1264
+ background: "rgba(15, 23, 42, 0.97)"
1265
+ },
1266
+ children: [
1267
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", alignItems: "center", gap: "12px" }, children: [
1268
+ /* @__PURE__ */ jsx("strong", { style: { fontSize: "14px", color: "#f1f5f9" }, children: "Annotate screenshot" }),
1269
+ /* @__PURE__ */ jsx("span", { style: { fontSize: "11px", color: "#475569" }, children: editorImage.fileName })
1270
+ ] }),
1271
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", flexWrap: "wrap", gap: "6px", alignItems: "center" }, children: [
1272
+ toolBtn("pen", /* @__PURE__ */ jsx(PenIcon, {}), "Pen"),
1273
+ toolBtn("rectangle", /* @__PURE__ */ jsx(RectIcon, {}), "Rect"),
1274
+ toolBtn("arrow", /* @__PURE__ */ jsx(ArrowIcon, {}), "Arrow"),
1275
+ toolBtn("text", /* @__PURE__ */ jsx(TextIcon, {}), "Text"),
1276
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "4px", alignItems: "center" }, children: [
1277
+ DEFAULT_COLORS.map((color) => /* @__PURE__ */ jsx(
1278
+ "button",
1279
+ {
1280
+ type: "button",
1281
+ onClick: () => setAnnotationColor(color),
1282
+ "aria-label": `Select ${color} color`,
1283
+ style: {
1284
+ width: "20px",
1285
+ height: "20px",
1286
+ borderRadius: "50%",
1287
+ border: annotationColor === color ? "2px solid #f8fafc" : "1px solid #334155",
1288
+ background: color,
1289
+ cursor: "pointer",
1290
+ flexShrink: 0
1291
+ }
1292
+ },
1293
+ color
1294
+ )),
1295
+ /* @__PURE__ */ jsx(
1296
+ "input",
1297
+ {
1298
+ type: "color",
1299
+ value: annotationColor,
1300
+ onChange: (e) => setAnnotationColor(e.target.value),
1301
+ "aria-label": "Custom color",
1302
+ title: "Custom color",
1303
+ style: { width: "28px", height: "28px", border: "none", background: "transparent", cursor: "pointer" }
1304
+ }
1305
+ )
1306
+ ] }),
1307
+ /* @__PURE__ */ jsxs("label", { style: { display: "flex", alignItems: "center", gap: "6px", fontSize: "11px", color: "#64748b" }, children: [
1308
+ "Size",
1309
+ /* @__PURE__ */ jsx(
1310
+ "input",
1311
+ {
1312
+ type: "range",
1313
+ min: 1,
1314
+ max: 18,
1315
+ value: annotationSize,
1316
+ onChange: (e) => setAnnotationSize(Number(e.target.value)),
1317
+ "aria-label": "Stroke size",
1318
+ style: { width: "72px" }
1319
+ }
1320
+ )
1321
+ ] }),
1322
+ iconBtn(handleUndo, /* @__PURE__ */ jsx(UndoIcon, {}), "Undo", !currentHasUndo),
1323
+ iconBtn(handleRedo, /* @__PURE__ */ jsx(RedoIcon, {}), "Redo", !currentHasRedo),
1324
+ iconBtn(handleClearAnnotations, /* @__PURE__ */ jsx(TrashIcon, {}), "Clear", !hasAnnotations)
1325
+ ] })
1326
+ ]
1327
+ }
1328
+ ),
1329
+ /* @__PURE__ */ jsxs(
1330
+ "div",
1331
+ {
1332
+ ref: annotationScrollRef,
1333
+ style: {
1334
+ flex: 1,
1335
+ overflow: "auto",
1336
+ padding: "16px",
1337
+ display: "flex",
1338
+ alignItems: "flex-start",
1339
+ justifyContent: "center",
1340
+ position: "relative"
1341
+ },
1342
+ children: [
1343
+ /* @__PURE__ */ jsx(
1344
+ "canvas",
1345
+ {
1346
+ ref: annotationCanvasRef,
1347
+ onPointerDown: handleCanvasPointerDown,
1348
+ onPointerMove: handleCanvasPointerMove,
1349
+ onPointerUp: handleCanvasPointerUp,
1350
+ onPointerCancel: handleCanvasPointerCancel,
1351
+ style: {
1352
+ width: "min(100%, 1400px)",
1353
+ height: "auto",
1354
+ display: "block",
1355
+ borderRadius: "12px",
1356
+ background: "#ffffff",
1357
+ boxShadow: "0 24px 80px rgba(15, 23, 42, 0.6)",
1358
+ touchAction: "none",
1359
+ cursor: annotationTool === "text" ? "text" : "crosshair"
1360
+ }
1361
+ }
1362
+ ),
1363
+ textCursor ? /* @__PURE__ */ jsx(
1364
+ "input",
1365
+ {
1366
+ autoFocus: true,
1367
+ ref: textInputRef,
1368
+ type: "text",
1369
+ value: inlineText,
1370
+ onChange: (e) => {
1371
+ inlineTextRef.current = e.target.value;
1372
+ setInlineText(e.target.value);
1373
+ },
1374
+ onKeyDown: (e) => {
1375
+ if (e.key === "Enter") {
1376
+ e.preventDefault();
1377
+ commitTextInput();
1378
+ }
1379
+ if (e.key === "Escape") {
1380
+ textCursorRef.current = null;
1381
+ setTextCursor(null);
1382
+ setInlineText("");
1383
+ inlineTextRef.current = "";
1384
+ }
1385
+ },
1386
+ placeholder: "Type \u2192 Enter to place",
1387
+ style: {
1388
+ position: "fixed",
1389
+ left: textCursor.domX,
1390
+ top: textCursor.domY,
1391
+ minWidth: "180px",
1392
+ background: "rgba(15, 23, 42, 0.92)",
1393
+ color: annotationColor,
1394
+ border: "1px dashed rgba(255,255,255,0.6)",
1395
+ borderRadius: "4px",
1396
+ padding: "4px 8px",
1397
+ fontSize: `${Math.max(14, annotationSize * 4)}px`,
1398
+ fontWeight: 600,
1399
+ outline: "none",
1400
+ zIndex: 10002,
1401
+ backdropFilter: "blur(6px)",
1402
+ boxShadow: "0 2px 12px rgba(0,0,0,0.4)"
1403
+ }
1404
+ }
1405
+ ) : null
1406
+ ]
1407
+ }
1408
+ ),
1409
+ /* @__PURE__ */ jsxs(
1410
+ "div",
1411
+ {
1412
+ style: {
1413
+ display: "flex",
1414
+ justifyContent: "space-between",
1415
+ alignItems: "center",
1416
+ gap: "12px",
1417
+ flexWrap: "wrap",
1418
+ padding: "10px 16px",
1419
+ borderTop: "1px solid rgba(148, 163, 184, 0.15)",
1420
+ background: "rgba(15, 23, 42, 0.97)"
1421
+ },
1422
+ children: [
1423
+ annotationTool === "text" ? /* @__PURE__ */ jsx("p", { style: { margin: 0, fontSize: "12px", color: "#64748b" }, children: "Click on the image to place text at that position." }) : /* @__PURE__ */ jsx("p", { style: { margin: 0, fontSize: "12px", color: "#64748b" }, children: "Draw on the image, then save when done." }),
1424
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "8px" }, children: [
1425
+ /* @__PURE__ */ jsx(
1426
+ "button",
1427
+ {
1428
+ type: "button",
1429
+ onClick: closeAnnotationEditor,
1430
+ style: {
1431
+ borderRadius: "8px",
1432
+ border: "1px solid #334155",
1433
+ background: "#0f172a",
1434
+ color: "#94a3b8",
1435
+ padding: "7px 14px",
1436
+ cursor: "pointer",
1437
+ fontSize: "13px"
1438
+ },
1439
+ children: "Cancel"
1440
+ }
1441
+ ),
1442
+ /* @__PURE__ */ jsxs(
1443
+ "button",
1444
+ {
1445
+ type: "button",
1446
+ onClick: handleApplyAnnotation,
1447
+ disabled: uploading,
1448
+ style: {
1449
+ display: "flex",
1450
+ alignItems: "center",
1451
+ gap: "6px",
1452
+ borderRadius: "8px",
1453
+ border: "none",
1454
+ background: "#15803d",
1455
+ color: "#f1f5f9",
1456
+ padding: "7px 14px",
1457
+ cursor: uploading ? "wait" : "pointer",
1458
+ opacity: uploading ? 0.8 : 1,
1459
+ fontWeight: 600,
1460
+ fontSize: "13px"
1461
+ },
1462
+ children: [
1463
+ /* @__PURE__ */ jsx(SendIcon, {}),
1464
+ uploading ? "Uploading\u2026" : "Save screenshot"
1465
+ ]
1466
+ }
1467
+ )
1468
+ ] })
1469
+ ]
1470
+ }
1471
+ )
1472
+ ]
1473
+ }
1474
+ ) : null
1475
+ ] });
1476
+ }
1477
+ function AdminFeedbackWidget() {
1478
+ return /* @__PURE__ */ jsx(
1479
+ FeedbackWidget,
1480
+ {
1481
+ title: "Admin feedback",
1482
+ submitLabel: "Send",
1483
+ uploadLabel: "Upload image",
1484
+ allowScreenshotUpload: true,
1485
+ onSubmit: async (payload) => {
1486
+ const response = await fetch("/api/admin-feedback/submit", {
1487
+ method: "POST",
1488
+ credentials: "include",
1489
+ headers: { "content-type": "application/json" },
1490
+ body: JSON.stringify(payload)
1491
+ });
1492
+ const result = await response.json();
1493
+ if (!result.success) {
1494
+ return { success: false, error: result.error || "Submit failed." };
1495
+ }
1496
+ return { success: true };
1497
+ },
1498
+ onUpload: async (formData) => {
1499
+ const response = await fetch("/api/admin-feedback/upload", {
1500
+ method: "POST",
1501
+ credentials: "include",
1502
+ body: formData
1503
+ });
1504
+ const result = await response.json();
1505
+ if (!result.success || typeof result.mediaId !== "number") {
1506
+ return { success: false, error: result.error || "Upload failed." };
1507
+ }
1508
+ return { success: true, mediaId: result.mediaId };
1509
+ },
1510
+ onDeleteScreenshot: async (mediaId) => {
1511
+ const response = await fetch(`/api/admin-feedback/upload/${mediaId}`, {
1512
+ method: "DELETE",
1513
+ credentials: "include"
1514
+ });
1515
+ const result = await response.json();
1516
+ if (!result.success) {
1517
+ return { success: false, error: result.error || "Delete failed." };
1518
+ }
1519
+ return { success: true };
1520
+ }
1521
+ }
1522
+ );
1523
+ }
1524
+
1525
+ // src/tenant/extractTenantSlug.ts
1526
+ var extractTenantSlugFromPathname = (pathname, pathMarkers) => {
1527
+ if (pathMarkers.length === 0) {
1528
+ return null;
1529
+ }
1530
+ const segments = pathname.split("?")[0].split("/").filter(Boolean);
1531
+ for (const marker of pathMarkers) {
1532
+ const markerIndex = segments.indexOf(marker);
1533
+ if (markerIndex > 0) {
1534
+ return segments[markerIndex - 1] ?? null;
1535
+ }
1536
+ }
1537
+ return null;
1538
+ };
1539
+
1540
+ // src/client/routeMatcher.ts
1541
+ var escapeRegex = (input) => input.replace(/[.+^${}()|[\]\\]/g, "\\$&");
1542
+ var toRegExp = (pattern) => {
1543
+ const escaped = pattern.split("*").map((segment) => escapeRegex(segment)).join(".*");
1544
+ return new RegExp(`^${escaped}$`);
1545
+ };
1546
+ var pathMatchesAllowlist = (pathname, patterns) => {
1547
+ if (patterns.length === 0) {
1548
+ return false;
1549
+ }
1550
+ return patterns.some((pattern) => toRegExp(pattern).test(pathname));
1551
+ };
1552
+ var normalizePathname = (pathname, locales) => {
1553
+ if (locales.length === 0) {
1554
+ return pathname;
1555
+ }
1556
+ const segments = pathname.split("/").filter(Boolean);
1557
+ const maybeLocale = segments[0];
1558
+ if (maybeLocale && locales.includes(maybeLocale)) {
1559
+ return `/${segments.slice(1).join("/")}`;
1560
+ }
1561
+ return pathname;
1562
+ };
1563
+ function FrontendFeedbackWidget({
1564
+ include,
1565
+ locales = [],
1566
+ title = "Feedback",
1567
+ submitLabel = "Send",
1568
+ uploadLabel = "Upload image",
1569
+ tenantPathMarkers = [],
1570
+ tenantFormDataKey = "tenant"
1571
+ }) {
1572
+ const pathname = usePathname();
1573
+ const normalizedPathname = normalizePathname(pathname, locales);
1574
+ if (!pathMatchesAllowlist(normalizedPathname, include)) {
1575
+ return null;
1576
+ }
1577
+ return /* @__PURE__ */ jsx(
1578
+ FeedbackWidget,
1579
+ {
1580
+ title,
1581
+ submitLabel,
1582
+ uploadLabel,
1583
+ allowScreenshotUpload: true,
1584
+ onSubmit: async (payload) => {
1585
+ const response = await fetch("/api/admin-feedback/submit", {
1586
+ method: "POST",
1587
+ credentials: "include",
1588
+ headers: { "content-type": "application/json" },
1589
+ body: JSON.stringify(payload)
1590
+ });
1591
+ const result = await response.json();
1592
+ if (!result.success) {
1593
+ return { success: false, error: result.error || "Submit failed." };
1594
+ }
1595
+ return { success: true };
1596
+ },
1597
+ onUpload: async (formData) => {
1598
+ if (tenantPathMarkers.length > 0) {
1599
+ const tenantSlug = extractTenantSlugFromPathname(pathname, tenantPathMarkers);
1600
+ if (tenantSlug) {
1601
+ formData.set(tenantFormDataKey, tenantSlug);
1602
+ }
1603
+ }
1604
+ const response = await fetch("/api/admin-feedback/upload", {
1605
+ method: "POST",
1606
+ credentials: "include",
1607
+ body: formData
1608
+ });
1609
+ const result = await response.json();
1610
+ if (!result.success || typeof result.mediaId !== "number") {
1611
+ return { success: false, error: result.error || "Upload failed." };
1612
+ }
1613
+ return { success: true, mediaId: result.mediaId };
1614
+ },
1615
+ onDeleteScreenshot: async (mediaId) => {
1616
+ const response = await fetch(`/api/admin-feedback/upload/${mediaId}`, {
1617
+ method: "DELETE",
1618
+ credentials: "include"
1619
+ });
1620
+ const result = await response.json();
1621
+ if (!result.success) {
1622
+ return { success: false, error: result.error || "Delete failed." };
1623
+ }
1624
+ return { success: true };
1625
+ }
1626
+ }
1627
+ );
1628
+ }
1629
+
1630
+ export { AdminFeedbackWidget, FeedbackWidget, FrontendFeedbackWidget };