-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
711 lines (582 loc) · 20.7 KB
/
Copy pathscript.js
File metadata and controls
711 lines (582 loc) · 20.7 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
class TimeUtil {
static now() {
return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
}
}
class MessageGrouper {
static shouldConnect(prev, curr) {
if (!prev || !curr) return false
if (prev.user !== curr.user) return false
if (curr.reply_to) return false
const t1 = (prev.timestamp || 0) * 1000
const t2 = (curr.timestamp || 0) * 1000
return Math.abs(t2 - t1) < 5 * 60 * 1000
}
}
class ElementFactory {
static div(cls, text) {
const el = document.createElement("div")
if (cls) el.className = cls
if (text !== undefined) el.textContent = text
return el
}
static img(cls, src) {
const el = document.createElement("img")
el.className = cls
el.src = src
return el
}
static link(text) {
const el = document.createElement("a")
el.textContent = text
return el
}
static icnBtn(icon, text) {
const el = document.createElement("a");
el.className = "icon";
el.setAttribute("data-tooltip", text)
el.textContent = icon;
return el
}
}
class ReplyBuilder {
static build(message) {
if (!message.reply_to) return null
let replyId = null
let hintedUser = ""
if (typeof message.reply_to === "object") {
replyId = message.reply_to.id || null
hintedUser = message.reply_to.user || ""
}
if (!replyId) return null
const ref =
message.reply_to_message ||
state.messages[replyId] ||
findMessageById(replyId)
const el = ElementFactory.div("reply-excerpt")
el.dataset.ref = replyId
const arrow = ElementFactory.div("rplarrow")
el.appendChild(arrow)
if (!ref) {
el.classList.add("missing")
const text = document.createElement("span")
if (hintedUser) {
const user = document.createElement("span")
user.className = "reply-user"
user.style.color = getUserColor(hintedUser)
user.textContent = "@" + hintedUser
text.textContent = "Replying to "
el.append(text, user)
} else {
text.textContent = "Replying to unknown message"
el.appendChild(text)
}
return el
}
if (!state.messages[replyId]) state.messages[replyId] = ref
const user = document.createElement("span")
user.className = "reply-user"
user.style.color = getUserColor(ref.user || hintedUser || "")
user.textContent = "@" + (ref.user || hintedUser || "unknown")
const preview = document.createElement("span")
preview.className = "reply-preview"
preview.textContent = stripHtml(ref.content || "").slice(0, 120)
el.append(user, preview)
return el
}
}
class MessageActions {
static build(message) {
const actions = ElementFactory.div("msg_actions")
const reply = ElementFactory.icnBtn("reply", "reply")
reply.dataset.action = "reply"
reply.dataset.id = message.id
const del = ElementFactory.icnBtn("delete", "delete")
del.dataset.action = "delete"
del.dataset.id = message.id
const edit = ElementFactory.icnBtn("edit", "edit")
edit.dataset.action = "edit"
edit.dataset.id = message.id
const copy = ElementFactory.icnBtn("content_copy", "copy")
copy.dataset.action = "copy"
copy.dataset.id = message.id
actions.append(reply, del, edit, copy)
return actions
}
}
class MessageBuilder {
static message({ avatar, username, timeStr, timeout, text, message, prevMessage }) {
const connected = MessageGrouper.shouldConnect(prevMessage, message)
const root = ElementFactory.div("msg")
if (connected) root.classList.add("connected")
root.setAttribute("data-id", message.id)
root.dataset.context = "message";
const data = ElementFactory.div("data")
if (!connected) {
const img = ElementFactory.img("pfp", avatar)
const name = ElementFactory.div("inline bold", username);
name.style.color = state.users[username]?.color;
name.dataset.username = username;
name.classList.add("username");
const time = ElementFactory.div("time", timeStr)
const fill = ElementFactory.div("fill")
const actions = MessageActions.build(message)
data.append(img, name, fill, actions, time)
} else {
root.classList.add("connected")
const actions = MessageActions.build(message)
const time = ElementFactory.div("time", timeStr)
data.append(actions, time)
}
let msg = ElementFactory.div("inline p")
if (text && text.trim()) {
msg.classList.add("contains_text")
const parsed = ContentParser.parse(text)
msg.appendChild(parsed)
}
const reply = ReplyBuilder.build(message)
const attachments = AttachmentBuilder.build(message.attachments)
if (attachments) msg.append(attachments || "");
if (connected) {
root.append(
msg || "",
data
)
} else {
root.append(
reply || "",
data,
msg || ""
)
}
return root
}
static action(args) {
return ActionBuilder.build(args)
}
}
class ActionBuilder {
static lastAction = null
static build({ icon, username, action, expiry }) {
const last = this.lastAction
if (
last &&
last.icon === icon &&
last.username === username &&
last.action === action
) {
last.count++
last.timeNode.textContent = TimeUtil.now()
last.actNode.textContent = `${action} x${last.count}`
if (last.timer) clearTimeout(last.timer)
if (expiry) {
last.bar.style.animation = "none"
last.bar.offsetHeight
last.bar.style.animation = `timeout-shrink ${expiry}ms linear forwards`
last.timer = setTimeout(() => {
last.root.style.overflow = "hidden"
last.root.style.transition = "transform 200ms ease, opacity 200ms ease"
last.root.style.transform = "scaleY(0)"
last.root.style.opacity = "0"
setTimeout(() => {
last.root.remove()
if (this.lastAction === last) this.lastAction = null
}, 200)
}, expiry)
}
return last.root
}
const root = ElementFactory.div("msg action")
const data = ElementFactory.div("data")
const ic = ElementFactory.div("icon", icon || "info_i")
const name = ElementFactory.div("inline bold")
name.innerHTML = username
const act = ElementFactory.div("inline")
act.innerHTML = action
username && data.appendChild(name)
action && data.appendChild(act)
const time = ElementFactory.div("time", TimeUtil.now())
root.append(ic, data, time)
let timer = null
let bar = null
if (expiry) {
bar = ElementFactory.div("timeout-bar")
root.appendChild(bar)
bar.style.animation = `timeout-shrink ${expiry}ms linear forwards`
timer = setTimeout(() => {
root.style.overflow = "hidden"
root.style.transition = "transform 200ms ease, opacity 200ms ease"
root.style.transform = "scaleY(0)"
root.style.opacity = "0"
setTimeout(() => {
root.remove()
if (this.lastAction && this.lastAction.root === root) this.lastAction = null
}, 200)
}, expiry)
}
this.lastAction = {
icon,
username,
action,
root,
timeNode: time,
actNode: act,
count: 1,
timer,
bar
}
return root
}
}
class ContentParser {
static imageRegex = /(https?:\/\/[^\s]+)/gi
static _probeCache = new Map();
static parse(text) {
const container = document.createElement("div")
container.innerHTML = text
this.replaceTextLinks(container)
return container
}
static isLikelyImage(url) {
return /\.(png|jpg|jpeg|gif|webp|svg|bmp|avif)(\?|$)/i.test(url)
}
static createImage(url) {
const img = document.createElement("img")
img.src = url
img.className = "msg_img"
img.loading = "lazy"
return img
}
static async probe(url) {
if (this._probeCache.has(url)) return this._probeCache.get(url);
return new Promise(res => {
const img = new Image();
img.onload = () => { this._probeCache.set(url, true); res(true); };
img.onerror = () => { this._probeCache.set(url, false); res(false); };
img.src = url;
});
}
static replaceTextLinks(root) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
const nodes = []
while (walker.nextNode()) nodes.push(walker.currentNode)
nodes.forEach(node => {
const matches = [...node.nodeValue.matchAll(this.imageRegex)]
if (!matches.length) return
const frag = document.createDocumentFragment()
let lastIndex = 0
matches.forEach(match => {
const url = match[0]
const start = match.index
const end = start + url.length
if (start > lastIndex) {
frag.appendChild(document.createTextNode(node.nodeValue.slice(lastIndex, start)))
}
if (this.isLikelyImage(url)) {
frag.appendChild(this.createImage(url))
} else {
if (this._probeCache.get(url) === true) {
frag.appendChild(this.createImage(url));
} else if (this._probeCache.get(url) === false) {
const a = document.createElement("a");
a.href = url; a.textContent = url;
frag.appendChild(a);
} else {
const a = document.createElement("a");
a.href = url; a.textContent = url;
this.probe(url).then(ok => {
if (ok && a.parentNode) a.replaceWith(this.createImage(url));
});
frag.appendChild(a);
}
}
lastIndex = end
})
if (lastIndex < node.nodeValue.length) {
frag.appendChild(document.createTextNode(node.nodeValue.slice(lastIndex)))
}
node.replaceWith(frag)
})
const links = root.querySelectorAll("a[href]")
links.forEach(a => {
const url = a.href
if (this.isLikelyImage(url)) {
a.replaceWith(this.createImage(url))
} else {
this.probe(url).then(ok => {
if (ok && a.parentNode) {
a.replaceWith(this.createImage(url))
}
})
}
})
}
}
class AttachmentBuilder {
static isImage(att) {
return att.mime_type && att.mime_type.startsWith("image/")
}
static scrollNearestFill(el) {
const fill = el.closest(".fill")
if (!fill) return
requestAnimationFrame(() => {
fill.scrollTop = fill.scrollHeight
})
}
static build(attachments) {
if (!attachments || !attachments.length) return null
const wrap = document.createElement("div")
wrap.className = "attachments"
attachments.forEach(att => {
if (this.isImage(att)) {
const img = document.createElement("img")
img.onload = () => {
this.scrollNearestFill(img)
}
img.src = att.url
img.className = "msg_img"
img.loading = "lazy"
wrap.appendChild(img)
} else {
const a = document.createElement("a")
a.href = att.url
a.textContent = att.name || "attachment"
a.target = "_blank"
wrap.appendChild(a)
}
})
return wrap
}
}
const tooltip = document.createElement("div")
tooltip.style.position = "fixed"
tooltip.style.pointerEvents = "none"
tooltip.style.zIndex = "999999"
tooltip.style.padding = "6px 10px"
tooltip.style.background = "var(--two)"
tooltip.style.color = "#fff"
tooltip.style.borderRadius = "4px"
tooltip.style.fontSize = "12px"
tooltip.style.whiteSpace = "pre-line"
tooltip.style.transition = "opacity 0.1s ease"
tooltip.style.opacity = "0"
document.body.appendChild(tooltip)
let active = null
const gap = 12
const pull = 0.22
const offset = 18
const drift = 8
document.addEventListener("mouseover", e => {
const el = e.target.closest("[data-tooltip]")
if (!el) return
active = el
tooltip.textContent = el.dataset.tooltip.replace(/\\n/g, "\n")
tooltip.style.opacity = "1"
})
document.addEventListener("mousemove", e => {
if (!active) return
const host = active.getBoundingClientRect()
const rect = tooltip.getBoundingClientRect()
const dir = active.dataset.tooltipDirection || "top"
const cx = host.left + host.width / 2
const cy = host.top + host.height / 2
let x = cx
let y = cy
let tx = "-50%"
let ty = "-100%"
if (dir === "top" || dir === "bottom") {
x = cx + (e.clientX - cx) * pull
const half = rect.width / 2
if (x - half < gap) x = half + gap
if (x + half > innerWidth - gap) x = innerWidth - half - gap
}
if (dir === "top") {
y = host.top - offset + Math.max(-drift, Math.min(drift, (e.clientY - cy) * 0.08))
ty = "-100%"
}
if (dir === "bottom") {
y = host.bottom + offset + Math.max(-drift, Math.min(drift, (e.clientY - cy) * 0.08))
ty = "0"
}
if (dir === "left") {
x = host.left - offset + Math.max(-drift, Math.min(drift, (e.clientX - cx) * 0.08))
y = cy + (e.clientY - cy) * pull
if (y < gap) y = gap
if (y + rect.height > innerHeight - gap) y = innerHeight - rect.height - gap
tx = "-100%"
ty = "-50%"
}
if (dir === "right") {
x = host.right + offset + Math.max(-drift, Math.min(drift, (e.clientX - cx) * 0.08))
y = cy + (e.clientY - cy) * pull
if (y < gap) y = gap
if (y + rect.height > innerHeight - gap) y = innerHeight - rect.height - gap
tx = "0"
ty = "-50%"
}
tooltip.style.transform = `translate(${tx}, ${ty})`
tooltip.style.left = x + "px"
tooltip.style.top = y + "px"
})
document.addEventListener("mouseout", e => {
if (!active) return
if (!e.relatedTarget || !active.contains(e.relatedTarget)) {
tooltip.style.opacity = "0"
active = null
}
})
function attachAutoResize(textarea, max = 300, offset = 32) {
if (!textarea || textarea._autoResizeAttached) return;
textarea.addEventListener("input", function () {
this.style.height = "auto";
this.style.height = Math.min(this.scrollHeight - offset, max) + "px";
});
textarea._autoResizeAttached = true;
}
function loadServers() {
const localServers = settings.get("servers_index") || [];
const list = document.getElementById("servers_list");
list.innerHTML = "";
const sName = "Direct Messages";
const sIcon = "assets/logo_vector.svg";
const sURL = "wss://dms.mistium.com";
const filtered = localServers.filter(server => server.url !== sURL);
const servers = [
{
name: sName,
icon: sIcon,
url: sURL
},
...filtered
];
settings.set("servers_index", servers);
servers.forEach(server => {
const img = document.createElement("img");
img.className = "server_shortcut";
img.dataset.tooltip = server.name + "\n" + server.url;
img.dataset.tooltipDirection = "right";
img.dataset.context = "server";
img.dataset.name = server.name;
img.dataset.url = server.url;
img.src = server.icon || "";
list.appendChild(img);
});
list.addEventListener("click", (e) => {
const el = e.target.closest(".server_shortcut");
if (!el || !list.contains(el)) return;
const url = el.dataset.url;
if (!url) return;
runcmd("cls");
runcmd("server " + url);
});
}
document.addEventListener("DOMContentLoaded", () => {
loadServers();
document.addEventListener("click", async e => {
const reply = e.target.closest(".reply-excerpt");
if (reply) {
const mid = reply.dataset.ref;
if (mid) jumpToMessage(mid);
return;
}
const btn = e.target.closest("[data-action]");
if (btn) {
const id = btn.dataset.id;
const action = btn.dataset.action;
if (action === "reply") runcmd(`reply ${id}`);
else if (action === "delete") runcmd(`delete ${id}`);
else if (action === "edit") runcmd(`edit ${id}`);
else if (action === "copy") {
try {
await navigator.clipboard.writeText(id);
const original = btn.textContent;
btn.textContent = "check";
setTimeout(() => {
btn.textContent = original;
}, 2000);
} catch (err) { }
}
return;
}
const user = e.target.closest(".username");
if (user) {
const username = user.dataset.username;
if (username) runcmd(`profile ${username.toLowerCase()}`);
}
});
});
function deleteServer(url) {
const localServers = settings.get("servers_index") || [];
const updated = localServers.filter(server => server.url !== url);
settings.set("servers_index", updated);
loadServers()
}
const menu = document.getElementById("contextMenu")
const menus = {
server: [
{ text: "Open Server", action: el => el.click },
{
text: "Copy URL", action: el => {
navigator.clipboard.writeText(text);
say("Copied URL!")
}
},
{ text: "Reload Icon", action: el => el.src = el.src },
{ text: "Delete Server", action: el => deleteServer(el.dataset.url) }
],
message: [
{ text: "Reply", action: el => console.log("reply", el) },
{ text: "Edit", action: el => console.log("edit", el) },
{ text: "Delete", action: el => console.log("delete message", el) }
],
default: [
{ text: "Refresh", action: el => location.reload() }
]
}
let currentTarget = null
function buildMenu(type, target) {
menu.innerHTML = ""
const items = menus[type] || menus.default
items.forEach(item => {
const div = document.createElement("div")
div.className = "context-item"
div.textContent = item.text
div.onclick = () => {
item.action(target)
hideMenu()
}
menu.appendChild(div)
})
}
function showMenu(x, y) {
menu.style.display = "block"
const w = menu.offsetWidth
const h = menu.offsetHeight
const px = Math.min(x, window.innerWidth - w - 8)
const py = Math.min(y, window.innerHeight - h - 8)
menu.style.left = px + "px"
menu.style.top = py + "px"
}
function hideMenu() {
if (currentTarget) {
currentTarget.classList.remove("context-active")
currentTarget = null
}
menu.style.display = "none"
}
document.addEventListener("contextmenu", e => {
const target = e.target.closest("[data-context]")
if (!target) return hideMenu()
e.preventDefault()
if (currentTarget && currentTarget !== target) {
currentTarget.classList.remove("context-active")
}
currentTarget = target
currentTarget.classList.add("context-active")
const type = target.dataset.context
buildMenu(type, target)
showMenu(e.clientX, e.clientY)
})
document.addEventListener("click", hideMenu)
window.addEventListener("resize", hideMenu)
document.addEventListener("scroll", hideMenu, true)