-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspace.js
More file actions
808 lines (700 loc) · 25.8 KB
/
Copy pathspace.js
File metadata and controls
808 lines (700 loc) · 25.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
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
/**
* space.js – Thunderbird Slack Provider UI
*
* Drives the three-pane Slack interface embedded in a Thunderbird Space tab.
*/
"use strict";
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
let currentChannel = null;
const userCache = {};
let disableAvatars = false;
let rateLimitedMode = false;
let workspaceName = "Slack";
let addChannelChoices = [];
let addChannelLoadId = 0;
const ADD_CHANNEL_BUTTON_TEXT = "Add Channel";
// ---------------------------------------------------------------------------
// Startup
// ---------------------------------------------------------------------------
document.addEventListener("DOMContentLoaded", async () => {
// Load display preferences
const stored = await messenger.storage.local.get(["disableAvatars", "rateLimitedMode"]);
disableAvatars = !!stored.disableAvatars;
rateLimitedMode = !!stored.rateLimitedMode;
const res = await bg({ type: "get_token" });
if (res.token) {
showMain();
await loadChannels();
} else {
showAuth();
}
// Wire static buttons
document.getElementById("btn-open-settings").addEventListener("click", () => {
messenger.runtime.openOptionsPage();
});
document.getElementById("btn-refresh-channels").addEventListener("click", () => {
loadChannels();
});
document.getElementById("btn-send").addEventListener("click", sendChannelMessage);
document.getElementById("message-input").addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendChannelMessage();
}
});
// Wire Add Channel dialog buttons
document.getElementById("btn-add-channel-cancel").addEventListener("click", hideAddChannelDialog);
document.getElementById("btn-add-channel-confirm").addEventListener("click", addChannel);
document.getElementById("add-channel-select").addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
addChannel();
}
if (e.key === "Escape") {
hideAddChannelDialog();
}
});
// Dismiss context menu when clicking elsewhere
document.addEventListener("click", hideContextMenu);
document.addEventListener("contextmenu", hideContextMenu);
});
// Listen for unread updates pushed from the background script
messenger.runtime.onMessage.addListener((msg) => {
if (msg.type === "unread_updated") {
refreshUnreadBadges(new Set(msg.unreadChannels));
}
if (msg.type === "no_watched_channels") {
loadChannels();
}
});
// Keep preferences in sync when changed via the options page
messenger.storage.onChanged.addListener((changes) => {
if ("disableAvatars" in changes) {
const change = changes.disableAvatars;
const newVal = "newValue" in change ? !!change.newValue : false;
if (newVal === disableAvatars) { return; }
disableAvatars = newVal;
if (currentChannel) {
loadMessages(currentChannel.id);
}
}
if ("rateLimitedMode" in changes) {
const change = changes.rateLimitedMode;
const newMode = "newValue" in change ? !!change.newValue : false;
if (newMode !== rateLimitedMode) {
rateLimitedMode = newMode;
loadChannels();
}
}
});
// ---------------------------------------------------------------------------
// Panel visibility
// ---------------------------------------------------------------------------
function showAuth() {
document.getElementById("auth-panel").classList.remove("hidden");
document.getElementById("main-panel").classList.add("hidden");
}
function showMain() {
document.getElementById("auth-panel").classList.add("hidden");
document.getElementById("main-panel").classList.remove("hidden");
}
// ---------------------------------------------------------------------------
// Channel list
// ---------------------------------------------------------------------------
async function loadChannels() {
const listEl = document.getElementById("channel-list");
listEl.innerHTML = '<div class="status-msg">Loading channels…</div>';
// Fetch workspace name (best-effort; keep previous name on failure)
const wsRes = await bg({ type: "get_workspace_name" });
if (wsRes.name) {
workspaceName = wsRes.name;
}
let channels;
let unread;
if (rateLimitedMode) {
// In rate-limited mode show only the channels the user has explicitly added
const [watchedRes, unreadRes] = await Promise.all([
bg({ type: "get_watched_channels" }),
bg({ type: "get_unread" }),
]);
channels = watchedRes.channels || [];
unread = new Set(unreadRes.unreadChannels || []);
} else {
const [chanRes, unreadRes] = await Promise.all([
bg({ type: "get_channels" }),
bg({ type: "get_unread" }),
]);
if (chanRes.error) {
listEl.innerHTML = `<div class="error-msg">Error: ${escHtml(chanRes.error)}</div>`;
return;
}
channels = (chanRes.channels || []).filter((c) => c.is_member);
unread = new Set(unreadRes.unreadChannels || []);
}
renderChannelList(channels, unread);
}
function renderChannelList(channels, unreadSet) {
const listEl = document.getElementById("channel-list");
listEl.innerHTML = "";
// ── Workspace section header ──────────────────────────────────────────
const wsHeader = document.createElement("div");
wsHeader.className = "workspace-header";
wsHeader.innerHTML = `
<span class="workspace-name">${escHtml(workspaceName)}</span>
<button class="icon-btn workspace-menu-btn" title="Workspace options" aria-haspopup="true">⋮</button>
`;
listEl.appendChild(wsHeader);
// Right-click on workspace name → context menu
wsHeader.querySelector(".workspace-name").addEventListener("contextmenu", (e) => {
e.preventDefault();
e.stopPropagation();
showWorkspaceContextMenu(e.clientX, e.clientY);
});
// Click the ⋮ button → context menu
wsHeader.querySelector(".workspace-menu-btn").addEventListener("click", (e) => {
e.stopPropagation();
let x = e.clientX;
let y = e.clientY;
if (!x && !y) {
const rect = e.currentTarget.getBoundingClientRect();
x = rect.right;
y = rect.bottom;
}
showWorkspaceContextMenu(x, y);
});
// ── Channel items ─────────────────────────────────────────────────────
const group = document.createElement("div");
group.className = "channels-group";
listEl.appendChild(group);
if (channels.length === 0) {
const empty = document.createElement("div");
empty.className = "status-msg";
empty.textContent = rateLimitedMode
? "No channels added yet. Click ⋮ next to the workspace name to add a channel."
: "No channels found.";
group.appendChild(empty);
return;
}
// Sort: unread first, then alphabetical
const sorted = [...channels].sort((a, b) => {
const au = unreadSet.has(a.id) ? 0 : 1;
const bu = unreadSet.has(b.id) ? 0 : 1;
if (au !== bu) return au - bu;
return a.name.localeCompare(b.name);
});
for (const ch of sorted) {
const item = document.createElement("div");
item.className = "channel-item";
item.setAttribute("role", "option");
item.dataset.channelId = ch.id;
if (unreadSet.has(ch.id)) item.classList.add("unread");
if (currentChannel && currentChannel.id === ch.id) item.classList.add("active");
const prefix = ch.is_private ? "🔒" : "#";
item.textContent = `${prefix} ${ch.name}`;
item.addEventListener("click", () => selectChannel(ch));
// Right-click on channel → context menu
item.addEventListener("contextmenu", (e) => {
e.preventDefault();
e.stopPropagation();
showChannelContextMenu(ch, e.clientX, e.clientY);
});
group.appendChild(item);
}
}
function refreshUnreadBadges(unreadSet) {
document.querySelectorAll(".channel-item").forEach((el) => {
const id = el.dataset.channelId;
if (unreadSet.has(id)) {
el.classList.add("unread");
} else {
el.classList.remove("unread");
}
});
}
// ---------------------------------------------------------------------------
// Context menus
// ---------------------------------------------------------------------------
/** Show a generic context menu at (x, y) with the provided item list. */
function showContextMenu(items, x, y) {
const menu = document.getElementById("context-menu");
const ul = document.getElementById("context-menu-items");
ul.innerHTML = "";
for (const item of items) {
const li = document.createElement("li");
li.setAttribute("role", "presentation");
const btn = document.createElement("button");
btn.className = "context-menu-item" + (item.danger ? " danger" : "");
btn.setAttribute("role", "menuitem");
btn.setAttribute("tabindex", "-1");
btn.textContent = item.label;
btn.addEventListener("click", (e) => {
e.stopPropagation();
hideContextMenu();
item.action();
});
btn.addEventListener("keydown", (e) => {
const btns = [...ul.querySelectorAll("[role='menuitem']")];
const idx = btns.indexOf(document.activeElement);
if (e.key === "ArrowDown") {
e.preventDefault();
btns[(idx + 1) % btns.length].focus();
} else if (e.key === "ArrowUp") {
e.preventDefault();
btns[(idx - 1 + btns.length) % btns.length].focus();
} else if (e.key === "Escape") {
hideContextMenu();
}
});
li.appendChild(btn);
ul.appendChild(li);
}
// Position the menu; adjust if it overflows the viewport
menu.style.left = `${x}px`;
menu.style.top = `${y}px`;
menu.classList.remove("hidden");
window.requestAnimationFrame(() => {
const rect = menu.getBoundingClientRect();
let left = x;
let top = y;
if (rect.right > window.innerWidth) {
left = x - rect.width;
}
if (rect.bottom > window.innerHeight) {
top = y - rect.height;
}
menu.style.left = `${Math.max(0, left)}px`;
menu.style.top = `${Math.max(0, top)}px`;
// Focus the first item for keyboard users
ul.querySelector("[role='menuitem']")?.focus();
});
}
function hideContextMenu() {
document.getElementById("context-menu").classList.add("hidden");
}
/** Context menu for the workspace name header. */
function showWorkspaceContextMenu(x, y) {
showContextMenu(
[{ label: "Add Channel…", action: () => showAddChannelDialog() }],
x,
y
);
}
/** Context menu for an individual channel item. */
function showChannelContextMenu(channel, x, y) {
showContextMenu(
[
{
label: "Remove Channel",
action: async () => {
await bg({ type: "remove_watched_channel", channelId: channel.id });
if (currentChannel && currentChannel.id === channel.id) {
currentChannel = null;
document.getElementById("messages-list").innerHTML = "";
document.getElementById("channel-label").textContent = "";
}
await loadChannels();
},
},
{
label: "Unsubscribe",
danger: true,
action: async () => {
if (!window.confirm(`Leave #${channel.name}? This will remove you from the channel in Slack.`)) { return; }
const res = await bg({ type: "leave_channel", channelId: channel.id });
if (res.error) {
alert(`Failed to leave channel: ${res.error}`);
return;
}
if (currentChannel && currentChannel.id === channel.id) {
currentChannel = null;
document.getElementById("messages-list").innerHTML = "";
document.getElementById("channel-label").textContent = "";
}
await loadChannels();
},
},
],
x,
y
);
}
// ---------------------------------------------------------------------------
// Add Channel dialog
// ---------------------------------------------------------------------------
function _onDialogKeydown(e) {
if (e.key === "Escape") {
hideAddChannelDialog();
}
}
function showAddChannelDialog() {
const dialog = document.getElementById("add-channel-dialog");
const select = document.getElementById("add-channel-select");
const errorEl = document.getElementById("add-channel-error");
const confirmBtn = document.getElementById("btn-add-channel-confirm");
const cancelBtn = document.getElementById("btn-add-channel-cancel");
const loadId = ++addChannelLoadId;
select.innerHTML = '<option value="">Loading channels...</option>';
select.disabled = true;
confirmBtn.disabled = true;
confirmBtn.textContent = ADD_CHANNEL_BUTTON_TEXT;
errorEl.classList.add("hidden");
dialog.classList.remove("hidden");
cancelBtn.focus();
document.addEventListener("keydown", _onDialogKeydown);
Promise.all([
bg({ type: "get_channels" }),
bg({ type: "get_watched_channels" }),
]).then(([chanRes, watchedRes]) => {
if (loadId !== addChannelLoadId) { return; } // Ignore stale async responses
if (dialog.classList.contains("hidden")) { return; } // Ignore updates for closed dialog
if (chanRes.error) {
errorEl.textContent = `Could not load channels: ${chanRes.error}`;
errorEl.classList.remove("hidden");
select.innerHTML = '<option value="">No channels available</option>';
return;
}
if (watchedRes.error) {
errorEl.textContent = `Could not load watched channels: ${watchedRes.error}`;
errorEl.classList.remove("hidden");
select.innerHTML = '<option value="">No channels available</option>';
return;
}
const watchedIds = new Set((watchedRes.channels || []).map((c) => c.id));
addChannelChoices = (chanRes.channels || [])
.filter((c) => c.is_member && !watchedIds.has(c.id))
.sort((a, b) => a.name.localeCompare(b.name));
if (addChannelChoices.length === 0) {
select.innerHTML = '<option value="">No channels available</option>';
return;
}
select.innerHTML = addChannelChoices
.map((c) => `<option value="${escHtml(c.id)}">${c.is_private ? "🔒 " : "#"}${escHtml(c.name)}</option>`)
.join("");
select.disabled = false;
confirmBtn.disabled = false;
select.focus();
}).catch((e) => {
if (loadId !== addChannelLoadId) { return; } // Ignore stale async responses
if (dialog.classList.contains("hidden")) { return; } // Ignore updates for closed dialog
errorEl.textContent = `Could not load channels: ${e.message}`;
errorEl.classList.remove("hidden");
select.innerHTML = '<option value="">No channels available</option>';
});
}
function hideAddChannelDialog() {
document.getElementById("add-channel-dialog").classList.add("hidden");
document.getElementById("btn-add-channel-confirm").textContent = ADD_CHANNEL_BUTTON_TEXT;
addChannelLoadId++;
addChannelChoices = [];
document.removeEventListener("keydown", _onDialogKeydown);
}
async function addChannel() {
const selectedId = document.getElementById("add-channel-select").value;
if (!selectedId) { return; }
const errorEl = document.getElementById("add-channel-error");
const confirmBtn = document.getElementById("btn-add-channel-confirm");
confirmBtn.disabled = true;
confirmBtn.textContent = "Adding…";
errorEl.classList.add("hidden");
try {
const ch = addChannelChoices.find((c) => c.id === selectedId);
if (!ch) {
errorEl.textContent = "Please pick a valid channel.";
errorEl.classList.remove("hidden");
return;
}
await bg({
type: "add_watched_channel",
channel: {
id: ch.id,
name: ch.name,
is_private: !!ch.is_private,
is_member: !!ch.is_member,
},
});
hideAddChannelDialog();
await loadChannels();
// Auto-select the newly added channel
selectChannel(ch);
} catch (e) {
errorEl.textContent = `Error: ${e.message}`;
errorEl.classList.remove("hidden");
} finally {
confirmBtn.disabled = false;
confirmBtn.textContent = ADD_CHANNEL_BUTTON_TEXT;
}
}
// ---------------------------------------------------------------------------
// Message list
// ---------------------------------------------------------------------------
async function selectChannel(channel) {
currentChannel = channel;
// Update header
document.getElementById("channel-label").textContent = `# ${channel.name}`;
document.getElementById("message-input").placeholder =
`Message #${channel.name} — press Enter to send, Shift+Enter for new line`;
// Mark active in sidebar and clear unread badge
document.querySelectorAll(".channel-item").forEach((el) => {
el.classList.remove("active");
if (el.dataset.channelId === channel.id) {
el.classList.add("active");
el.classList.remove("unread");
}
});
await loadMessages(channel.id);
}
async function loadMessages(channelId) {
const listEl = document.getElementById("messages-list");
listEl.innerHTML = '<div class="status-msg">Loading messages…</div>';
const res = await bg({ type: "get_messages", channelId, limit: 50 });
if (res.error) {
listEl.innerHTML = `<div class="error-msg">Error: ${escHtml(res.error)}</div>`;
return;
}
const messages = (res.messages || []).filter(isDisplayableMessage).reverse();
if (messages.length === 0) {
listEl.innerHTML = '<div class="status-msg">No messages in this channel yet.</div>';
return;
}
listEl.innerHTML = "";
for (const msg of messages) {
const el = await buildMessageElement(msg);
listEl.appendChild(el);
}
scrollToBottom();
}
function isDisplayableMessage(msg) {
// Skip join/leave and other system subtypes
const skipTypes = ["channel_join", "channel_leave", "channel_topic", "channel_purpose"];
return !skipTypes.includes(msg.subtype);
}
// ---------------------------------------------------------------------------
// Message element builder
// ---------------------------------------------------------------------------
async function buildMessageElement(msg) {
const wrap = document.createElement("div");
wrap.className = "message";
wrap.dataset.ts = msg.ts;
// Resolve user/bot name
let username = "Unknown";
let avatarHtml = "";
if (msg.user) {
const user = await resolveUser(msg.user);
username = user.profile?.display_name || user.real_name || user.name || msg.user;
const avatarUrl = user.profile?.image_48 || "";
if (!disableAvatars && avatarUrl) {
avatarHtml = `<img src="${avatarUrl}" alt="${escHtml(username)}" />`;
} else {
// Prefer real_name (e.g. "John Doe") for two-letter initials; fall back to name
const initialsName = user.real_name || user.name || msg.user;
avatarHtml = avatarPlaceholder(initialsName);
}
} else if (msg.bot_profile) {
username = msg.bot_profile.name || "Bot";
avatarHtml = avatarPlaceholder(username);
} else if (msg.username) {
username = msg.username;
avatarHtml = avatarPlaceholder(username);
} else {
avatarHtml = avatarPlaceholder("?");
}
// Timestamp
const ts = parseFloat(msg.ts);
const d = new Date(ts * 1000);
const timeStr = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const fullDateTime = d.toLocaleString();
// Reply info
const replyCount = msg.reply_count || 0;
const replyLabel = replyCount === 1 ? "1 reply" : `${replyCount} replies`;
// Safe ID for DOM
const safeTs = safeDomId(msg.ts);
wrap.innerHTML = `
<div class="message-avatar">${avatarHtml}</div>
<div class="message-content">
<div class="message-header">
<span class="message-author">${escHtml(username)}</span>
<span class="message-time" title="${escHtml(fullDateTime)}">${timeStr}</span>
</div>
<div class="message-text">${formatSlackText(msg.text || "", userCache)}</div>
<div class="message-actions">
<button class="btn btn-ghost reply-btn" data-ts="${msg.ts}">
💬 Reply${replyCount > 0 ? ` · <span class="reply-count">${replyLabel}</span>` : ""}
</button>
</div>
<div class="reply-form hidden" id="rf-${safeTs}">
<textarea
class="reply-textarea"
placeholder="Reply to thread (also sent to channel)…"
rows="2"
aria-label="Reply"
></textarea>
<div class="reply-form-actions">
<button class="btn btn-secondary cancel-reply-btn">Cancel</button>
<button class="btn btn-primary send-reply-btn">Send Reply</button>
</div>
</div>
</div>
`;
// Event: toggle reply form
wrap.querySelector(".reply-btn").addEventListener("click", () => {
toggleReplyForm(msg.ts);
});
// Event: send reply
const sendFn = () => submitReply(msg.ts, wrap);
wrap.querySelector(".send-reply-btn").addEventListener("click", sendFn);
wrap.querySelector(".reply-textarea").addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendFn();
}
});
// Event: cancel reply
wrap.querySelector(".cancel-reply-btn").addEventListener("click", () => {
document.getElementById(`rf-${safeTs}`).classList.add("hidden");
});
return wrap;
}
function avatarPlaceholder(name) {
const initials = nameInitials(name);
return `<div class="avatar-placeholder">${escHtml(initials)}</div>`;
}
/** Derive up to two initials from a display name or real name. */
function nameInitials(name) {
const str = String(name || "?").trim();
if (!str || str === "?") return "?";
const words = str.split(/\s+/).filter(Boolean);
if (words.length === 0) return "?";
if (words.length === 1) return words[0][0].toUpperCase();
// First letter of the first word + first letter of the last word
return (words[0][0] + words[words.length - 1][0]).toUpperCase();
}
// ---------------------------------------------------------------------------
// Reply handling
// ---------------------------------------------------------------------------
function toggleReplyForm(ts) {
const form = document.getElementById(`rf-${safeDomId(ts)}`);
if (!form) return;
form.classList.toggle("hidden");
if (!form.classList.contains("hidden")) {
form.querySelector(".reply-textarea")?.focus();
}
}
async function submitReply(threadTs, msgWrap) {
if (!currentChannel) return;
const form = msgWrap.querySelector(".reply-form");
const textarea = form.querySelector(".reply-textarea");
const text = textarea.value.trim();
if (!text) return;
const btn = form.querySelector(".send-reply-btn");
btn.disabled = true;
btn.textContent = "Sending…";
const res = await bg({
type: "send_reply",
channelId: currentChannel.id,
threadTs,
text,
});
btn.disabled = false;
btn.textContent = "Send Reply";
if (res.error) {
alert(`Failed to send reply: ${res.error}`);
return;
}
textarea.value = "";
form.classList.add("hidden");
await loadMessages(currentChannel.id);
}
// ---------------------------------------------------------------------------
// Sending a new channel message
// ---------------------------------------------------------------------------
async function sendChannelMessage() {
if (!currentChannel) return;
const input = document.getElementById("message-input");
const text = input.value.trim();
if (!text) return;
const btn = document.getElementById("btn-send");
btn.disabled = true;
const res = await bg({
type: "send_message",
channelId: currentChannel.id,
text,
});
btn.disabled = false;
if (res.error) {
alert(`Failed to send message: ${res.error}`);
return;
}
input.value = "";
await loadMessages(currentChannel.id);
}
// ---------------------------------------------------------------------------
// User cache
// ---------------------------------------------------------------------------
async function resolveUser(userId) {
if (userCache[userId]) return userCache[userId];
const res = await bg({ type: "get_user", userId });
if (res.user) {
userCache[userId] = res.user;
return res.user;
}
return { name: userId };
}
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
function bg(msg) {
return messenger.runtime.sendMessage(msg);
}
function scrollToBottom() {
const container = document.getElementById("messages-container");
container.scrollTop = container.scrollHeight;
}
function safeDomId(ts) {
return ts.replace(".", "-");
}
function escHtml(text) {
const d = document.createElement("div");
d.textContent = String(text);
return d.innerHTML;
}
/**
* Convert Slack mrkdwn to safe HTML.
* Works on already-escaped HTML (call after escHtml on the raw text).
*/
function formatSlackText(rawText, users) {
// First escape HTML entities
let t = escHtml(rawText);
// Bold *text*
t = t.replace(/\*([^*\n]+)\*/g, "<strong>$1</strong>");
// Italic _text_ (avoid matching snake_case by requiring a non-word boundary)
t = t.replace(/(^|[^a-z0-9])_([^_\n]+)_([^a-z0-9]|$)/gim, "$1<em>$2</em>$3");
// Strikethrough ~text~
t = t.replace(/~([^~\n]+)~/g, "<del>$1</del>");
// Inline code `text`
t = t.replace(/`([^`\n]+)`/g, "<code>$1</code>");
// Blockquote >>
t = t.replace(/^> (.+)/gm, "<blockquote>$1</blockquote>");
// Newlines
t = t.replace(/\n/g, "<br />");
// Slack user mentions <@UXXX>
t = t.replace(/<@([A-Z0-9]+)(?:\|([^&]+))?>/g, (_, uid, label) => {
const u = users[uid];
const name = label || (u && (u.profile?.display_name || u.real_name)) || uid;
return `<span class="mention">@${escHtml(name)}</span>`;
});
// Channel references <#CXXX|name>
t = t.replace(/<#([A-Z0-9]+)\|([^&]+)>/g, (_, _id, name) => {
return `<strong>#${escHtml(name)}</strong>`;
});
// URLs <https://…|label> or <https://…>
t = t.replace(
/<(https?:\/\/[^|&>]+)(?:\|([^&>]+))?>/g,
(_, url, label) => {
const display = label ? escHtml(label) : escHtml(url);
return `<a href="${url}" target="_blank" rel="noreferrer noopener">${display}</a>`;
}
);
return t;
}