-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlighttrail.js
More file actions
754 lines (636 loc) · 22.1 KB
/
lighttrail.js
File metadata and controls
754 lines (636 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
const LT_SERVER = "http://localhost:3000";
const LT_WS = "ws://localhost:3000";
let topZIndex = 9000;
/*
* Adds the LightTrail styling for comments and HUD.
*/
(function injectStyles() {
const style = document.createElement("style");
style.textContent = `
.lt-selected-source {
background-color: rgba(245, 66, 66, 0.3);
}
.lt-dialog-box {
position: absolute;
width: 300px;
padding: 10px;
padding-top: 25px;
background-color: #fff;
border: 1px solid #ccc;
border-bottom: 4px solid rgb(245, 66, 66);
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
border-radius: 5px;
z-index: ${topZIndex};
overflow: hidden;
user-select: none;
}
.lt-dialog-box * {
font-family: monospace;
}
.lt-other-user.lt-dialog-box {
border-bottom: 4px solid #f5c542;
}
.lt-label {
color: black;
margin-bottom: 8px;
font-size: 16px;
font-style: italic;
text-align: left;
font-family: 'Jost', sans-serif;
}
.lt-dialog-input {
width: 100%;
box-sizing: border-box;
border-radius: 4px;
field-sizing: content;
padding: 4px;
resize: none;
}
.lt-submit-button, .lt-submit-button button {
background-color: white;
color: black;
padding: 3px 12px;
border-radius: 4px;
transition: background-color 0.2s;
}
.lt-submit-button:hover, .lt-submit-button:hover button {
background-color: rgb(181, 181, 181);
}
.lt-dialog-input, .lt-submit-button, .lt-submit-button button {
font-family: monospace;
}
.lt-close-button {
color: red;
float: right;
cursor: default;
padding: 1px;
border-radius: 4px;
}
.lt-close-button:hover {
background-color: rgb(181, 181, 181);
}
#lt-HUD * {
font-family: 'Jost', sans-serif;
}
#lt-HUD {
font-family: 'Jost', sans-serif;
position: fixed;
bottom: 20px;
right: 20px;
z-index: ${topZIndex+1000};
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 20px;
background: #fff;
border: 1.5px solid rgb(255, 255, 255);
border-radius: 50px;
cursor: pointer;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
font-size: 14px;
font-weight: 500;
color: black;
transition: background 0.25s, color 0.25s, box-shadow 0.25s;
user-select: none;
}
#lt-HUD.hiding {
background: rgb(245, 66, 66);
background: linear-gradient(90deg, rgb(245,66,66), rgb(255, 215, 137));
color: #fff;
box-shadow: 0 2px 12px rgba(245,66,66,0.3);
}
#lt-HUD-badge {
font-size: 11px;
padding: 1px 7px;
border-radius: 20px;
font-weight: 500;
background: rgb(245, 66, 66);
background: linear-gradient(90deg, rgb(245,66,66), rgb(255, 215, 137));
color: #fff;
transition: background 0.25s;
}
#lt-HUD.hiding #lt-HUD-badge {
background: rgb(255, 255, 255);
color: black;
}
#lt-HUD-window {
position: fixed;
bottom: 70px;
right: 20px;
width: 280px;
max-height: 400px;
display: none;
flex-direction: column;
background: #fff;
border: 0.5px solid rgba(0,0,0,0.12);
border-radius: 5px;
box-shadow: 0 4px 20px rgba(0,0,0,0.12);
overflow: hidden;
z-index: ${topZIndex+1000};
}
#lt-HUD.hiding #lt-HUD-window {
display: flex;
}
#lt-HUD-window-header {
padding: 12px 16px;
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
#lt-HUD-window-list {
overflow-y: auto;
flex: 1;
}
.lt-HUD-item {
padding: 10px 16px;
display: flex;
align-items: flex-start;
gap: 10px;
border-bottom: 0.5px solid rgba(0,0,0,0.06);
cursor: pointer;
}
.lt-HUD-item:last-child { border-bottom: none; }
.lt-HUD-item:hover { background: rgba(0,0,0,0.03); }
.lt-HUD-dot {
width: 8px;
height: 8px;
border-radius: 50%;
margin-top: 4px;
flex-shrink: 0;
}
.lt-HUD-item-selected {
font-size: 12px;
color: gray;
font-style: italic;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin: 0 0 2px;
}
.lt-HUD-item-comment {
font-size: 13px;
margin: 0;
color: black;
}
#lt-HUD-window-footer {
padding: 8px 16px;
border-top: 0.5px solid rgba(0,0,0,0.08);
font-size: 12px;
color: gray;
text-align: center;
flex-shrink: 0;
}
`
document.head.appendChild(style);
})();
/*
* Gets the parent element of the selected text.
*/
function getSelectedEl(){
const selection = window.getSelection();
if(selection.rangeCount > 0){
const commonAncestor = selection.getRangeAt(0).commonAncestorContainer;
if(commonAncestor.nodeType === Node.TEXT_NODE){
return commonAncestor.parentNode;
}
return commonAncestor;
}
return null;
}
/*
Passed element is brought to the top of display.
*/
function bringToFront(el){
topZIndex += 1;
el.style.zIndex = String(topZIndex);
}
/*
Gets author id from local storage, or creates and stores it if doesn't exist.
*/
function getAuthorID(){
let id = localStorage.getItem("lt-author-id");
if(!id) {
try {
id = crypto.randomUUID();
}
catch (err){
id = "test";
}
localStorage.setItem("lt-author-id", id);
}
return id;
}
/*
* Gets the DOM path for the element.
*/
function getDOMPath(el){
if(!el) return null;
const stack = [];
while(el.parentNode != null){
let siblingCount = 0;
let siblingIndex = 0;
for(let i = 0; i < el.parentNode.children.length; i++){
const sibling = el.parentNode.children[i];
if(sibling.nodeName === el.nodeName){
if(sibling === el){
siblingIndex = siblingCount;
}
siblingCount++;
}
}
const nodeName = el.nodeName.toLowerCase();
if(siblingCount > 1){
stack.unshift(`${nodeName}:nth-of-type(${siblingIndex+1})`)
}
else {
stack.unshift(nodeName);
}
el = el.parentNode;
}
return stack.join(" > ");
}
/*
Creates popup dialog box for comments.
*/
function makeDialogBox(e, dialogText, sourceElement, userOwns=true, dialogComment=null){
var dialogBox = document.createElement("div");
dialogBox.className = "lt-dialog-box";
/*
Marks selected element's source element.
Highlights source elements red and adds event listener to display
connected dialog box.
*/
sourceElement.classList.add("lt-selected-source");
// Clicking the source element will unhide its dialog box.
sourceElement.addEventListener("click", () => {
dialogBox.style.display = "initial";
});
dialogBox.sourceElement = sourceElement;
Object.assign(dialogBox.style, {
left: e.pageX + "px",
top: (e.pageY + 10) + "px",
zIndex: String(topZIndex + 1)
});
// --- DRAG LOGIC ---
let isDragging = false;
let offsetX, offsetY;
/*
Start dragging logic
*/
dialogBox.addEventListener("mousedown", (e) => {
bringToFront(dialogBox);
if(userOwns){
submitBtn.style.display = "initial";
}
closeBtn.disabled = false;
closeBtn.style.display = "initial";
if(e.target.tagName === "TEXTAREA" || e.target.tagName === "SPAN" || e.target.tagName === "BUTTON") return; // so these elements can still function.
isDragging = true;
dialogBox.style.cursor = "grabbing";
// Calculate where the mouse is relative to the box's top-left corner
offsetX = e.clientX - dialogBox.offsetLeft;
offsetY = e.clientY - dialogBox.offsetTop;
// Prevent text selection while dragging
e.preventDefault();
dialogBox.style.opacity = "50%";
});
/*
Actual dragging around logic.
*/
document.addEventListener("mousemove", (e) => {
if (!isDragging) return;
dialogBox.style.left = (e.clientX - offsetX) + "px";
dialogBox.style.top = (e.clientY - offsetY) + "px";
});
/*
Stop dragging logic.
*/
document.addEventListener("mouseup", () => {
isDragging = false;
dialogBox.style.cursor = "auto";
dialogBox.style.opacity = "100%";
});
/*
Displays what was specifically selected by user.
*/
const label = document.createElement("div");
const numChars = 25;
const labelText = dialogText.length > numChars ? dialogText.substring(0,numChars) + "..." : dialogText;
label.className = "lt-label";
label.innerHTML = `<strong>Selected: </strong>"<span style="color:red;">${labelText}</span>"`;
/*
Form (Input field and submit button) for comments.
*/
const form = document.createElement("form");
form.className = "lt-dialog-form";
const inputField = document.createElement("textarea");
inputField.className = "lt-dialog-input";
inputField.placeholder = "Type here...";
inputField.name = "comment";
const submitBtn = document.createElement("button");
submitBtn.className = "lt-submit-button";
submitBtn.type = "submit";
submitBtn.innerText = "Comment";
/*
Saves comment to database.
*/
submitBtn.addEventListener("click", async (e) => {
e.preventDefault();
const comment = inputField.value.trim();
if(!comment) return;
const domPath = getDOMPath(sourceElement);
const commentID = dialogBox.dataset.commentID;
if(!commentID){
// new comment being added
const response = await fetch(`${LT_SERVER}/comments`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
page_url: window.location.origin + window.location.pathname, // url without sections or params
dom_path: domPath,
selected_text: dialogText,
comment_text: comment,
pos_x: dialogBox.offsetLeft,
pos_y: dialogBox.offsetTop,
author_id: authorID
})
});
const saved = await response.json();
dialogBox.dataset.commentID = saved.id;
refreshHUD();
}
else {
if(comment === ""){ // existing comment made empty, deleting comment box.
await fetch(`${LT_SERVER}/comments/${commentID}`, { method: "DELETE" });
refreshHUD();
}
else { // existing comment being updated.
await fetch(`${LT_SERVER}/comments/${commentID}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
comment_text: comment,
pos_x: dialogBox.offsetLeft,
pos_y: dialogBox.offsetTop,
})
});
refreshHUD();
}
}
// Hides and disables submit and close buttons when comment inputted.
submitBtn.disabled = true;
submitBtn.style.display = "none";
closeBtn.disabled = true;
closeBtn.style.display = "none";
});
/*
Delete comment button.
*/
const closeBtn = document.createElement("span");
closeBtn.innerText = "❌";
closeBtn.className = "lt-close-button";
closeBtn.addEventListener("click", async () => {
const commentID = dialogBox.dataset.commentID;
if(commentID) {
await fetch(`${LT_SERVER}/comments/${commentID}`, { method: "DELETE" });
}
dialogBox.remove();
const hasComments = Array.from(document.querySelectorAll(".lt-dialog-box"))
.some(box => box.sourceElement === sourceElement);
if(!hasComments){
sourceElement.classList.remove("lt-selected-source");
}
refreshHUD();
});
// If an existing comment, input field is loaded with comment.
if(dialogComment){
inputField.value = dialogComment;
submitBtn.style.display = "none";
closeBtn.style.display = "none";
}
// If the comment is from someone other than the user, its styled accordingly and its input field is uneditable.
if(!userOwns){
dialogBox.classList.add("lt-other-user");
inputField.disabled = true;
}
else {
// submit button is enabled and displayed when the input is changed.
inputField.addEventListener("input", () => {
submitBtn.disabled = false;
submitBtn.style.display = "initial";
});
}
form.appendChild(inputField);
if(userOwns) {
form.appendChild(submitBtn);
}
form.appendChild(closeBtn);
dialogBox.appendChild(label);
dialogBox.appendChild(form);
return dialogBox;
}
/*
When mouse unclicked after highlighting, this creates the dialog box and adds it to the website.
*/
document.onmouseup = function(e) {
if(e.target.closest(".lt-dialog-box")) return;
const selectedElement = getSelectedEl();
const selectedText = window.getSelection().toString().trim();
if(selectedText){
var dialogBox = makeDialogBox(e, selectedText, selectedElement);
document.body.appendChild(dialogBox);
dialogBox.querySelector("textarea").focus();
}
};
/*
When mouse clicked outside of a dialog box.
*/
document.addEventListener("mousedown", function(e) {
const allDialogBoxes = document.querySelectorAll(".lt-dialog-box");
allDialogBoxes.forEach(box => {
try {
const input = box.querySelector(".lt-dialog-input");
// Dialog box is deleted if comment is empty.
if(!box.contains(e.target) && input.value.trim() === ""){
if(box.sourceElement){
box.sourceElement.classList.remove("lt-selected-source");
}
box.remove();
}
else if (!box.contains(e.target) && !document.getElementById("lt-HUD").classList.contains("hiding")) {
try {
box.querySelector('.lt-submit-button').style.display = "none";
} catch (err){};
box.querySelector('.lt-close-button').style.display = "none";
if( !(e.target.classList.contains("lt-selected-source") || e.target.closest(".lt-dialog-box")) ) box.style.display = "none"; // Dialog boxes (and buttons) are hidden when clicked off.
}
}
catch (TypeError) {
box.style.display = "none";
}
});
});
/*
Gets saved comments from database and loads into website.
*/
async function loadComments() {
const res = await fetch(
`${LT_SERVER}/comments?page_url=` + encodeURIComponent(window.location.origin + window.location.pathname)
);
const comments = await res.json();
comments.forEach(c => {
const fEvent = {
pageX: c.pos_x,
pageY: c.pos_y
};
const element = document.querySelector(c.dom_path);
const ownership = c.author_id === authorID;
const box = makeDialogBox(e=fEvent, dialogText=c.selected_text, sourceElement=element, userOwns=ownership, dialogComment=c.comment_text);
box.dataset.commentID = c.id;
document.body.appendChild(box);
});
refreshHUD();
}
let boxesVisible = false;
function makeHUD() {
const HUD = document.createElement("div");
HUD.id = "lt-HUD";
const label = document.createElement("span");
label.textContent = "LightTrail";
const badge = document.createElement("span");
badge.id = "lt-HUD-badge";
badge.textContent = "0";
// Panel
const panel = document.createElement("div");
panel.id = "lt-HUD-window";
const header = document.createElement("div");
header.id = "lt-HUD-window-header";
const list = document.createElement("div");
list.id = "lt-HUD-window-list";
const footer = document.createElement("div");
footer.id = "lt-HUD-window-footer";
footer.textContent = "highlight text to add a comment";
panel.appendChild(header);
panel.appendChild(list);
panel.appendChild(footer);
// HUD.appendChild(icon);
HUD.appendChild(label);
HUD.appendChild(badge);
HUD.appendChild(panel);
HUD.addEventListener("click", (e) => {
e.stopPropagation();
boxesVisible = !boxesVisible;
HUD.classList.toggle("hiding", boxesVisible);
const display = boxesVisible ? "initial" : "none";
document.querySelectorAll(".lt-dialog-box").forEach(box => {
box.style.display = display;
});
if (boxesVisible) refreshHUD();
});
document.body.appendChild(HUD);
}
function refreshHUD() {
const list = document.getElementById("lt-HUD-window-list");
const badge = document.getElementById("lt-HUD-badge");
if (!list) return;
const boxes = Array.from(document.querySelectorAll(".lt-dialog-box"));
const saved = boxes.filter(b => b.dataset.commentID);
badge.textContent = saved.length;
list.innerHTML = "";
if (saved.length === 0) {
list.innerHTML = `<p style="font-size:13px;color:gray;text-align:center;padding:16px;margin:0;">no comments yet</p>`;
return;
}
saved.forEach(box => {
const isOwn = !box.classList.contains("lt-other-user");
const selectedText = box.querySelector(".lt-label span")?.textContent || "";
const commentText = box.querySelector("textarea")?.value || "";
const item = document.createElement("div");
item.className = "lt-HUD-item";
item.innerHTML = `
<div class="lt-HUD-dot" style="background:${isOwn ? "rgb(245,66,66)" : "rgb(245,197,66)"}"></div>
<div style="flex:1;min-width:0;">
<p class="lt-HUD-item-selected">"${selectedText}"</p>
<p class="lt-HUD-item-comment">${commentText}</p>
</div>`;
const closeBtn = document.createElement("span");
closeBtn.innerText = "❌";
closeBtn.className = "lt-close-button";
closeBtn.addEventListener("click", async () => {
const commentID = box.dataset.commentID;
if(commentID) {
await fetch(`${LT_SERVER}/comments/${commentID}`, { method: "DELETE" });
}
refreshHUD();
});
item.appendChild(closeBtn);
// Clicking a HUD item scrolls to and reveals its dialog box
item.addEventListener("click", (e) => {
/* if(e.target.tagName === "SPAN") return; */
e.stopPropagation();
box.style.display = "initial";
box.scrollIntoView({ behavior: "smooth", block: "center" });
});
list.appendChild(item);
});
}
/*
WebSocket connection to server. All changes (adding, deleting, posting commeents) are shared, allowing for realtime updates.
*/
const ws = new WebSocket(`${LT_WS}`);
ws.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
if(data.type === 'comment_created'){
if(data.comment.page_url === window.location.origin + window.location.pathname && data.comment.author_id !== localStorage.getItem("lt-author-id")){
const fEvent = { pageX: data.comment.pos_x, pageY: data.comment.pos_y };
const element = document.querySelector(data.comment.dom_path);
const box = makeDialogBox(e=fEvent, dialogText=data.comment.selected_text, sourceElement=element, userOwns=false, dialogComment=data.comment.comment_text);
box.dataset.commentID = data.comment.id;
document.body.appendChild(box);
}
}
if(data.type === 'comment_deleted'){
document.querySelectorAll('.lt-dialog-box').forEach(box => {
if(box.dataset.commentID == data.comment.id){
const sourceElement = document.querySelector(data.comment.dom_path);
box.remove();
const hasComments = Array.from(document.querySelectorAll(".lt-dialog-box"))
.some(b => b.sourceElement === sourceElement);
if(!hasComments){
sourceElement.classList.remove("lt-selected-source");
}
}
});
}
if(data.type === 'comment_updated'){
document.querySelectorAll('.lt-dialog-box').forEach(box => {
if(box.dataset.commentID == data.comment.id && data.comment.author_id !== localStorage.getItem("lt-author-id")) {
box.querySelector('textarea').value = data.comment.comment_text;
box.style.left = `${data.comment.pos_x}px`;
box.style.top = `${data.comment.pos_y}px`;
}
});
}
if(data.type === 'comment_created' || data.type === 'comment_deleted' || data.type === 'comment_updated'){
refreshHUD();
}
});
const welcome_message = `\nThis page includes LightTrail, a tool that enables users to add comments to webpages.
This tool is meant for web developers and clients to better communicate ideas, changes, and feedback,
enhancing and refining the collaborative process.
LightTrail was developed by Ayaan Modak (GitHub: Iced-code). Learn more at https://iced-code.github.io/LightTrail/.
**Note: This tool must be removed before publishing this website.**
☀️
`;
const isMobile = /Mobi|Android|iPhone|iPod|iPad/i.test(navigator.userAgent) || window.innerWidth < 768;
console.log(welcome_message);
const authorID = getAuthorID();
if(!isMobile){
loadComments();
makeHUD();
}