-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerateThread.tsx
More file actions
547 lines (461 loc) · 16.8 KB
/
generateThread.tsx
File metadata and controls
547 lines (461 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/** @jsxImportSource preact */
import { render } from "preact";
import { css } from "goober";
import CollabIndicator from "../components/Collab/CollabIndicator";
import Config from "../../configManager/configManager";
import { IThreadDTO, IThreadRenderStatus } from "../types/collab.types";
import {
MissingThreadsInfo,
toggleCollabPopupEvent,
} from "../types/collab.types";
import visualBuilderPostMessage from "../utils/visualBuilderPostMessage";
import { VisualBuilderPostMessageEvents } from "../utils/types/postMessage.types";
import { adjustPositionToViewport } from "../utils/collabUtils";
const popupTopOffset = 43;
const popupLeftOffset = 9;
const hiddenClass = css`
display: none;
`;
function createPopupContainer(
resolvedXPath: string,
relativeX: number,
relativeY: number,
top: number,
left: number,
updateConfig: boolean,
hidden: boolean,
payload: IThreadDTO | any
): HTMLDivElement {
const popupContainer = document.createElement("div");
popupContainer.setAttribute("field-path", resolvedXPath);
popupContainer.setAttribute("relative", `x: ${relativeX}, y: ${relativeY}`);
popupContainer.style.position = "absolute";
popupContainer.style.top = `${top - popupTopOffset}px`;
popupContainer.style.left = `${left - popupLeftOffset}px`;
popupContainer.style.zIndex = updateConfig ? "1000" : "999";
popupContainer.style.cursor = "pointer";
popupContainer.className = "collab-thread";
if (hidden) popupContainer.classList.add(hiddenClass);
if (payload?._id) popupContainer.setAttribute("threaduid", payload._id);
return popupContainer;
}
function appendPopupContainer(popupContainer: HTMLDivElement): void {
const visualBuilderContainer = document.querySelector(
".visual-builder__container"
);
if (visualBuilderContainer) {
let highlightCommentWrapper = visualBuilderContainer.querySelector(
".visual-builder__collab-wrapper"
);
if (!highlightCommentWrapper) {
highlightCommentWrapper = document.createElement("div");
highlightCommentWrapper.className =
"visual-builder__collab-wrapper";
visualBuilderContainer.appendChild(highlightCommentWrapper);
}
highlightCommentWrapper.appendChild(popupContainer);
} else {
document.body.appendChild(popupContainer);
}
}
export function generateThread(
payload: IThreadDTO | any,
options: {
isNewThread?: boolean;
updateConfig?: boolean;
hidden?: boolean;
} = {}
): string | undefined {
const {
isNewThread = false,
updateConfig = false,
hidden = false,
} = options;
const config = Config.get?.();
let relativeX: number, relativeY: number, resolvedXPath: string;
if (isNewThread) {
({ relativeX, relativeY, xpath: resolvedXPath } = payload);
} else {
const { position, elementXPath } = payload;
({ x: relativeX, y: relativeY } = position);
resolvedXPath = elementXPath;
}
// Filter to remove already rendered threads
if (payload?._id) {
const existingThread = document.querySelector(
`div[threaduid='${payload._id}']`
);
if (existingThread) {
return undefined;
}
}
const element = getElementByXpath(resolvedXPath);
if (!element) {
return payload._id;
}
const rect = element.getBoundingClientRect();
let top = rect.top + window.scrollY + relativeY * rect.height;
let left = rect.left + window.scrollX + relativeX * rect.width;
const adjustedPosition = adjustPositionToViewport({ top, left });
top = adjustedPosition.top;
left = adjustedPosition.left;
const popupContainer = createPopupContainer(
resolvedXPath,
relativeX,
relativeY,
top,
left,
updateConfig,
hidden,
payload
);
if (updateConfig && config?.collab?.enable) {
if (config?.collab.isFeedbackMode) {
Config.set("collab.isFeedbackMode", false);
}
}
render(
<CollabIndicator
activeThread={!isNewThread ? payload : undefined}
newThread={isNewThread}
/>,
popupContainer
);
appendPopupContainer(popupContainer);
return undefined;
}
export function updateCollabIconPosition() {
const icons = document.querySelectorAll(
".visual-builder__collab-wrapper .collab-thread"
);
const config = Config.get?.();
if (config?.collab?.pauseFeedback) return;
icons.forEach((icon) => {
if (!(icon instanceof HTMLElement)) return;
const path = icon.getAttribute("field-path");
const relative = icon.getAttribute("relative");
if (!path || !relative) {
console.error("Missing field-path or relative attribute.");
return;
}
const match = relative.match(/x: ([\d.]+), y: ([\d.]+)/);
if (!match) {
console.error("Invalid relative attribute format.");
return;
}
const relativeX = parseFloat(match[1]);
const relativeY = parseFloat(match[2]);
const targetElement = getElementByXpath(path);
if (!targetElement) {
icon.classList.add(hiddenClass);
return;
}
const rect = targetElement.getBoundingClientRect();
let left = rect.left + rect.width * relativeX + window.scrollX;
let top = rect.top + rect.height * relativeY + window.scrollY;
const adjustedPosition = adjustPositionToViewport({ top, left });
top = adjustedPosition.top;
left = adjustedPosition.left;
icon.style.top = `${top - popupTopOffset}px`;
icon.style.left = `${left - popupLeftOffset}px`;
icon.classList.remove(hiddenClass);
});
}
export function updatePopupPositions() {
const popups = document.querySelectorAll(
".visual-builder__collab-wrapper .collab-thread .collab-popup"
);
const config = Config.get?.();
if (config?.collab?.pauseFeedback) return;
popups.forEach((popup) => {
if (popup && popup instanceof HTMLElement) {
const parent = popup.closest(
".visual-builder__collab-wrapper .collab-thread"
);
if (!parent) {
console.error(
"Parent element with class 'collab-thread' not found."
);
return;
}
const button = parent.querySelector(
".visual-builder__collab-wrapper .collab-thread .collab-indicator"
);
if (!button || !(button instanceof HTMLElement)) {
console.error(
"Button with class 'collab-indicator' not found."
);
return;
}
calculatePopupPosition(button, popup);
}
});
}
export function updateSuggestionListPosition() {
const suggestionLists = document.querySelectorAll(
".collab-thread-body--input--textarea--suggestionsList"
);
if (!suggestionLists.length) return;
suggestionLists.forEach((list) => {
if (!(list instanceof HTMLElement)) return;
const textarea = document.querySelector(
".collab-thread-body--input--textarea"
) as HTMLTextAreaElement | null;
if (!textarea) return;
const positionData = list.getAttribute("data-position");
const parsedData = positionData ? JSON.parse(positionData) : null;
const showAbove = window.getComputedStyle(list).bottom !== "auto";
const textareaRect = textarea.getBoundingClientRect();
if (showAbove) {
const lineHeight =
parseInt(window.getComputedStyle(textarea).lineHeight) || 20;
const paddingTop =
parseInt(window.getComputedStyle(textarea).paddingTop) || 8;
const cursorLineY =
parsedData?.cursorLineY || paddingTop + lineHeight;
list.style.position = "fixed";
list.style.bottom = `${window.innerHeight - textareaRect.top - cursorLineY + lineHeight}px`;
list.style.top = "auto";
} else {
const lineHeight =
parseInt(window.getComputedStyle(textarea).lineHeight) || 20;
const paddingTop =
parseInt(window.getComputedStyle(textarea).paddingTop) || 8;
const cursorLineY =
parsedData?.cursorLineY || paddingTop + lineHeight;
list.style.position = "fixed";
list.style.top = `${textareaRect.top + cursorLineY}px`;
list.style.bottom = "auto";
}
if (!positionData && textareaRect) {
const lineHeight =
parseInt(window.getComputedStyle(textarea).lineHeight) || 20;
const paddingTop =
parseInt(window.getComputedStyle(textarea).paddingTop) || 8;
const positionInfo = {
showAbove: showAbove,
cursorLineY: paddingTop + lineHeight,
};
list.setAttribute("data-position", JSON.stringify(positionInfo));
}
const listRect = list.getBoundingClientRect();
if (!showAbove && listRect.bottom > window.innerHeight) {
const lineHeight =
parseInt(window.getComputedStyle(textarea).lineHeight) || 20;
const paddingTop =
parseInt(window.getComputedStyle(textarea).paddingTop) || 8;
const cursorLineY =
parsedData?.cursorLineY || paddingTop + lineHeight;
list.style.bottom = `${window.innerHeight - textareaRect.top - cursorLineY + lineHeight}px`;
list.style.top = "auto";
if (positionData) {
const updatedData = JSON.parse(positionData);
updatedData.showAbove = true;
list.setAttribute("data-position", JSON.stringify(updatedData));
}
} else if (showAbove && listRect.top < 0) {
const lineHeight =
parseInt(window.getComputedStyle(textarea).lineHeight) || 20;
const paddingTop =
parseInt(window.getComputedStyle(textarea).paddingTop) || 8;
const cursorLineY =
parsedData?.cursorLineY || paddingTop + lineHeight;
list.style.top = `${textareaRect.top + cursorLineY}px`;
list.style.bottom = "auto";
if (positionData) {
const updatedData = JSON.parse(positionData);
updatedData.showAbove = false;
list.setAttribute("data-position", JSON.stringify(updatedData));
}
}
});
}
export function calculatePopupPosition(
button: HTMLElement,
popup: HTMLElement
) {
const buttonRect = button.getBoundingClientRect();
const viewportHeight = window.innerHeight;
const viewportWidth = window.innerWidth;
let popupHeight = popup.offsetHeight || 198;
let popupWidth = popup.offsetWidth || 334;
const spaceAbove = buttonRect.top;
const spaceBelow = viewportHeight - buttonRect.bottom;
let top, left;
if (spaceAbove >= popupHeight) {
top = buttonRect.top - popupHeight - 8;
} else if (spaceBelow >= popupHeight) {
top = buttonRect.bottom + 8;
} else {
top =
spaceBelow > spaceAbove
? buttonRect.bottom + 8
: Math.max(buttonRect.top - popupHeight - 8, 0);
}
left = buttonRect.left + buttonRect.width / 2 - popupWidth / 2;
top = Math.max(top, 0);
left = Math.max(left, 0);
left = Math.min(left, viewportWidth - popupWidth);
popup.style.top = `${top}px`;
popup.style.left = `${left}px`;
requestAnimationFrame(() => {
const newPopupHeight = popup.offsetHeight;
if (newPopupHeight !== popupHeight) {
calculatePopupPosition(button, popup);
}
});
}
export function removeAllCollabIcons(): void {
const icons = document.querySelectorAll(
".visual-builder__collab-wrapper .collab-thread"
);
icons?.forEach((icon) => icon?.remove());
}
export function hideAllCollabIcons(): void {
const icons = document.querySelectorAll(
".visual-builder__collab-wrapper .collab-thread"
);
icons?.forEach((icon) => icon?.classList.add(hiddenClass));
toggleCollabPopup({ threadUid: "", action: "close" });
}
export function showAllCollabIcons(): void {
const icons = document.querySelectorAll(
".visual-builder__collab-wrapper .collab-thread"
);
icons?.forEach((icon) => icon?.classList.remove(hiddenClass));
}
export function removeCollabIcon(threadUid: string): void {
const thread = document.querySelector(`div[threaduid='${threadUid}']`);
thread?.remove();
}
export function toggleCollabPopup({
threadUid = "",
action,
}: toggleCollabPopupEvent): void {
document.dispatchEvent(
new CustomEvent("toggleCollabPopup", {
detail: { threadUid, action },
})
);
}
export function HighlightThread(threadUid: string): void {
toggleCollabPopup({ threadUid, action: "open" });
}
export function isCollabThread(target: HTMLElement): boolean {
return Array.from(target.classList).some((className) =>
className.startsWith("collab")
);
}
export function handleMissingThreads(payload: MissingThreadsInfo) {
visualBuilderPostMessage?.send(
VisualBuilderPostMessageEvents.COLLAB_MISSING_THREADS,
payload
);
}
export function handleEmptyThreads() {
const icons = document.querySelectorAll(
".visual-builder__collab-wrapper .collab-thread"
);
icons?.forEach((icon) => {
if (!icon.hasAttribute("threaduid")) {
icon.remove();
}
});
}
const retryConfig = {
maxRetries: 5,
retryDelay: 1000,
};
let isProcessingThreads = false;
export const threadRenderStatus = new Map<string, IThreadRenderStatus>();
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function getRenderStatus(threadId: string): IThreadRenderStatus {
if (!threadRenderStatus.has(threadId)) {
threadRenderStatus.set(threadId, {
threadId,
attempts: 0,
isRendered: false,
});
}
return threadRenderStatus.get(threadId)!;
}
function updateRenderStatus(threadId: string, isRendered: boolean): void {
const status = getRenderStatus(threadId);
status.isRendered = isRendered;
threadRenderStatus.set(threadId, status);
}
export function clearThreadStatus(threadId: string): void {
threadRenderStatus.delete(threadId);
}
export function clearAllThreadStatus(): void {
threadRenderStatus.clear();
isProcessingThreads = false;
}
async function processThread(thread: IThreadDTO): Promise<string | undefined> {
let status = getRenderStatus(thread._id);
while (status.attempts < retryConfig.maxRetries) {
try {
const result = generateThread(thread);
if (result === undefined) {
updateRenderStatus(thread._id, true);
return undefined;
}
status.attempts++;
updateRenderStatus(thread._id, false);
if (status.attempts < retryConfig.maxRetries) {
await delay(retryConfig.retryDelay);
}
} catch (error) {
console.error(`Error rendering thread ${thread._id}:`, error);
status.attempts++;
if (status.attempts >= retryConfig.maxRetries) {
break;
}
await delay(retryConfig.retryDelay);
}
}
return thread._id;
}
export async function processThreadsBatch(
threads: IThreadDTO[]
): Promise<string[]> {
if (isProcessingThreads) return [];
try {
isProcessingThreads = true;
const unrenderedThreads = filterUnrenderedThreads(threads);
if (unrenderedThreads.length === 0) return [];
const missingThreadIds = (
await Promise.all(
unrenderedThreads.map((thread) => processThread(thread))
)
).filter(Boolean) as string[];
missingThreadIds.forEach(clearThreadStatus);
return missingThreadIds;
} finally {
isProcessingThreads = false;
}
}
export function filterUnrenderedThreads(threads: IThreadDTO[]): IThreadDTO[] {
return threads.filter((thread) => {
const existingThread = document.querySelector(
`[threaduid="${thread._id}"]`
);
if (existingThread) {
updateRenderStatus(thread._id, true);
return false;
}
return true;
});
}
function getElementByXpath(xpath: string): HTMLElement | null {
const result = document.evaluate(
xpath,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
);
return result.singleNodeValue as HTMLElement | null;
}