forked from retoor/devplacepy
The topnav Messages icon opens a Chats panel (people search, recent conversations, New message, link to the full page). Picking a person opens a small chat window docked bottom-right; windows minimize to avatar heads with unread counts and survive navigation within the tab. Profile Send Message, the live message toast and message notifications on /notifications open the same window. Phones and /messages keep the full page. Each window is dp-chat in mode="window", sharing one WebSocket through chat/ChatSocketHub.js; chat/ConversationItem.js is the shared row builder. No server changes. The message input becomes [+] [text + emoji] [send] everywhere: + reveals the attach and GIF buttons, which tuck away while typing. Also fixes linked toasts never receiving clicks (pointer-events). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
577 lines
21 KiB
JavaScript
577 lines
21 KiB
JavaScript
// retoor <retoor@molodetz.nl>
|
||
|
||
import { Component } from "./Component.js";
|
||
import { Avatar } from "../Avatar.js";
|
||
import { Http } from "../Http.js";
|
||
import { ListNav } from "../ListNav.js";
|
||
import { ChatSocket } from "../chat/ChatSocket.js";
|
||
import { ChatSocketHub } from "../chat/ChatSocketHub.js";
|
||
import { ConversationItem } from "../chat/ConversationItem.js";
|
||
|
||
const MOBILE_BREAKPOINT_PX = 768;
|
||
const WINDOW_SLOT_PX = 336;
|
||
const DOCK_RESERVED_PX = 96;
|
||
const MAX_OPEN_WINDOWS = 3;
|
||
const MAX_ENTRIES = 8;
|
||
const MAX_SEEN_FRAMES = 500;
|
||
const SEARCH_DEBOUNCE_MS = 200;
|
||
const STORAGE_PREFIX = "devplace.chat-dock.";
|
||
|
||
export class AppChatDock extends Component {
|
||
constructor() {
|
||
super();
|
||
this._built = false;
|
||
this.entries = [];
|
||
this.windows = new Map();
|
||
this.heads = new Map();
|
||
this.seenFrames = new Set();
|
||
this.channel = null;
|
||
this.compose = null;
|
||
this.conversations = null;
|
||
this.panelOpen = false;
|
||
this._resizeFrame = null;
|
||
}
|
||
|
||
connectedCallback() {
|
||
if (this._built) return;
|
||
this._built = true;
|
||
this.selfUid = this.attr("self-uid");
|
||
this.selfIsAdmin = this.attr("self-admin", "false") === "true";
|
||
this.conversationsUrl = this.attr("conversations-url", "/messages/conversations");
|
||
this.searchUrl = this.attr("search-url", "/messages/search");
|
||
this.hub = new ChatSocketHub(ChatSocket.resolveUrl(this.attr("ws-url", "/messages/ws")));
|
||
this._buildPanel();
|
||
this._buildTray();
|
||
this._bindDocument();
|
||
this._bindToggles();
|
||
this.entries = this._restore();
|
||
if (!this._isMobile()) this._enforceLimits();
|
||
this._render();
|
||
}
|
||
|
||
disconnectedCallback() {
|
||
for (const entry of this.windows.values()) entry.section.remove();
|
||
this.windows.clear();
|
||
if (this.channel) this.channel.close();
|
||
this.channel = null;
|
||
}
|
||
|
||
open(user, { focus = true } = {}) {
|
||
if (!user || !user.uid || user.uid === this.selfUid || this._isMobile()) return false;
|
||
this._closePanel();
|
||
let entry = this.entries.find((item) => item.uid === user.uid);
|
||
if (entry) {
|
||
this.entries.splice(this.entries.indexOf(entry), 1);
|
||
entry.username = user.username || entry.username;
|
||
entry.avatar_seed = user.avatar_seed || entry.avatar_seed;
|
||
} else {
|
||
entry = { uid: user.uid, username: user.username || "", avatar_seed: user.avatar_seed || "" };
|
||
}
|
||
entry.minimized = false;
|
||
entry.unread = 0;
|
||
this.entries.unshift(entry);
|
||
this._enforceLimits();
|
||
this._commit();
|
||
const win = this.windows.get(entry.uid);
|
||
if (focus && win) win.chat.focusComposer();
|
||
return true;
|
||
}
|
||
|
||
minimize(uid) {
|
||
const entry = this.entries.find((item) => item.uid === uid);
|
||
if (!entry) return;
|
||
entry.minimized = true;
|
||
this._commit();
|
||
}
|
||
|
||
close(uid) {
|
||
this.entries = this.entries.filter((item) => item.uid !== uid);
|
||
this._commit();
|
||
}
|
||
|
||
togglePanel() {
|
||
if (this.panelOpen) this._closePanel();
|
||
else this._openPanel();
|
||
}
|
||
|
||
openCompose() {
|
||
this._closePanel();
|
||
if (!this.compose) {
|
||
this.compose = this._buildCompose();
|
||
this._enforceLimits();
|
||
this._commit();
|
||
}
|
||
this.compose.querySelector(".chat-compose-input").focus({ preventScroll: true });
|
||
}
|
||
|
||
closeCompose() {
|
||
if (!this.compose) return;
|
||
this.compose.remove();
|
||
this.compose = null;
|
||
}
|
||
|
||
_isMobile() {
|
||
return window.innerWidth <= MOBILE_BREAKPOINT_PX;
|
||
}
|
||
|
||
_maxOpen() {
|
||
const fit = Math.floor((window.innerWidth - DOCK_RESERVED_PX) / WINDOW_SLOT_PX);
|
||
return Math.max(1, Math.min(MAX_OPEN_WINDOWS, fit));
|
||
}
|
||
|
||
_enforceLimits() {
|
||
const slots = Math.max(1, this._maxOpen() - (this.compose ? 1 : 0));
|
||
let expanded = 0;
|
||
for (const entry of this.entries) {
|
||
if (entry.minimized) continue;
|
||
expanded += 1;
|
||
if (expanded > slots) entry.minimized = true;
|
||
}
|
||
this.entries = this.entries.slice(0, MAX_ENTRIES);
|
||
}
|
||
|
||
_commit() {
|
||
this._persist();
|
||
this._render();
|
||
}
|
||
|
||
_storageKey() {
|
||
return `${STORAGE_PREFIX}${this.selfUid}`;
|
||
}
|
||
|
||
_restore() {
|
||
try {
|
||
const parsed = JSON.parse(window.sessionStorage.getItem(this._storageKey()) || "[]");
|
||
if (!Array.isArray(parsed)) return [];
|
||
return parsed
|
||
.filter((item) => item && item.uid && item.uid !== this.selfUid)
|
||
.slice(0, MAX_ENTRIES)
|
||
.map((item) => ({
|
||
uid: String(item.uid),
|
||
username: String(item.username || ""),
|
||
avatar_seed: String(item.avatar_seed || ""),
|
||
minimized: !!item.minimized,
|
||
unread: Number(item.unread) || 0,
|
||
}));
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
_persist() {
|
||
try {
|
||
window.sessionStorage.setItem(this._storageKey(), JSON.stringify(this.entries));
|
||
} catch {
|
||
/* storage unavailable: the dock still works for this page */
|
||
}
|
||
}
|
||
|
||
_render() {
|
||
const visible = this._isMobile() ? [] : this.entries;
|
||
if (this._isMobile()) this.closeCompose();
|
||
const expanded = visible.filter((entry) => !entry.minimized);
|
||
const minimized = visible.filter((entry) => entry.minimized);
|
||
|
||
for (const [uid, win] of this.windows) {
|
||
if (expanded.some((entry) => entry.uid === uid)) continue;
|
||
win.section.remove();
|
||
this.windows.delete(uid);
|
||
}
|
||
for (const entry of [...expanded].reverse()) {
|
||
if (!this.windows.has(entry.uid)) this.windows.set(entry.uid, this._buildWindow(entry));
|
||
}
|
||
|
||
for (const [uid, head] of this.heads) {
|
||
if (minimized.some((entry) => entry.uid === uid)) continue;
|
||
head.remove();
|
||
this.heads.delete(uid);
|
||
}
|
||
for (const entry of minimized) {
|
||
let head = this.heads.get(entry.uid);
|
||
if (!head) {
|
||
head = this._buildHead(entry);
|
||
this.heads.set(entry.uid, head);
|
||
}
|
||
this._updateHead(head, entry);
|
||
this.headColumn.appendChild(head);
|
||
}
|
||
|
||
this._syncChannel(visible.length > 0);
|
||
}
|
||
|
||
_syncChannel(wanted) {
|
||
if (wanted && !this.channel) {
|
||
this.channel = this.hub.subscribe({ onMessage: (frame) => this._onFrame(frame) });
|
||
} else if (!wanted && this.channel) {
|
||
this.channel.close();
|
||
this.channel = null;
|
||
}
|
||
}
|
||
|
||
_onFrame(frame) {
|
||
if (!frame || frame.type !== "message" || !frame.uid || frame.sender_uid === this.selfUid) return;
|
||
if (this.seenFrames.has(frame.uid)) return;
|
||
if (this.seenFrames.size >= MAX_SEEN_FRAMES) this.seenFrames.clear();
|
||
this.seenFrames.add(frame.uid);
|
||
const entry = this.entries.find((item) => item.uid === frame.sender_uid);
|
||
if (!entry || !entry.minimized) return;
|
||
entry.unread = (entry.unread || 0) + 1;
|
||
this._persist();
|
||
const head = this.heads.get(entry.uid);
|
||
if (head) this._updateHead(head, entry);
|
||
}
|
||
|
||
_buildTray() {
|
||
this.tray = document.createElement("div");
|
||
this.tray.className = "chat-dock-tray";
|
||
this.windowRow = document.createElement("div");
|
||
this.windowRow.className = "chat-dock-windows";
|
||
this.headColumn = document.createElement("div");
|
||
this.headColumn.className = "chat-dock-heads";
|
||
this.tray.append(this.windowRow, this.headColumn);
|
||
this.appendChild(this.tray);
|
||
}
|
||
|
||
_buildWindow(entry) {
|
||
const section = document.createElement("section");
|
||
section.className = "chat-window";
|
||
section.dataset.chatUid = entry.uid;
|
||
section.setAttribute("aria-label", `Chat with ${entry.username || "member"}`);
|
||
this.windowRow.insertBefore(section, this.compose);
|
||
|
||
const chat = document.createElement("dp-chat");
|
||
chat.setAttribute("mode", "window");
|
||
chat.setAttribute("self-uid", this.selfUid);
|
||
chat.setAttribute("self-admin", this.selfIsAdmin ? "true" : "false");
|
||
chat.setAttribute("with-uid", entry.uid);
|
||
chat.setAttribute("ai-indicator", "true");
|
||
chat.hub = this.hub;
|
||
chat.partner = { uid: entry.uid, username: entry.username, avatar_seed: entry.avatar_seed };
|
||
section.addEventListener("dp-chat:conversation", (event) => this._onConversation(entry.uid, event.detail.user));
|
||
section.appendChild(chat);
|
||
|
||
const header = chat.querySelector(".messages-main-header");
|
||
if (header) {
|
||
header.appendChild(this._windowActions([
|
||
this._iconButton("chat-window-minimize", "Minimize chat", "–", () => this.minimize(entry.uid)),
|
||
this._iconButton("chat-window-close", "Close chat", "âś•", () => this.close(entry.uid)),
|
||
]));
|
||
header.addEventListener("click", (event) => {
|
||
if (event.target.closest("a, button")) return;
|
||
this.minimize(entry.uid);
|
||
});
|
||
}
|
||
return { section, chat };
|
||
}
|
||
|
||
_onConversation(uid, user) {
|
||
const entry = this.entries.find((item) => item.uid === uid);
|
||
if (entry && user) {
|
||
entry.username = user.username || entry.username;
|
||
entry.avatar_seed = user.avatar_seed || entry.avatar_seed;
|
||
this._persist();
|
||
const win = this.windows.get(uid);
|
||
if (win) win.section.setAttribute("aria-label", `Chat with ${entry.username || "member"}`);
|
||
}
|
||
if (window.app && window.app.counters) window.app.counters.poll();
|
||
}
|
||
|
||
_buildCompose() {
|
||
const section = document.createElement("section");
|
||
section.className = "chat-window chat-window-compose";
|
||
section.setAttribute("aria-label", "New message");
|
||
|
||
const header = document.createElement("div");
|
||
header.className = "messages-main-header";
|
||
const title = document.createElement("h3");
|
||
title.textContent = "New message";
|
||
header.append(title, this._windowActions([
|
||
this._iconButton("chat-window-close", "Close new message", "âś•", () => this.closeCompose()),
|
||
]));
|
||
|
||
const to = document.createElement("div");
|
||
to.className = "chat-compose-to";
|
||
const label = document.createElement("label");
|
||
label.textContent = "To:";
|
||
const input = document.createElement("input");
|
||
input.type = "search";
|
||
input.className = "chat-compose-input";
|
||
input.placeholder = "Search people...";
|
||
input.autocomplete = "off";
|
||
input.setAttribute("aria-label", "Search people to message");
|
||
label.appendChild(input);
|
||
to.appendChild(label);
|
||
|
||
const results = document.createElement("div");
|
||
results.className = "chat-compose-results";
|
||
results.setAttribute("role", "listbox");
|
||
results.setAttribute("aria-label", "People");
|
||
|
||
section.append(header, to, results);
|
||
this.windowRow.appendChild(section);
|
||
this._bindPeopleSearch(input, results, {
|
||
onEmpty: () => results.replaceChildren(),
|
||
onChoose: (user) => {
|
||
this.closeCompose();
|
||
this.open(user);
|
||
},
|
||
});
|
||
return section;
|
||
}
|
||
|
||
_windowActions(buttons) {
|
||
const actions = document.createElement("div");
|
||
actions.className = "chat-window-actions";
|
||
actions.append(...buttons);
|
||
return actions;
|
||
}
|
||
|
||
_iconButton(className, label, glyph, onClick) {
|
||
const btn = document.createElement("button");
|
||
btn.type = "button";
|
||
btn.className = `chat-icon-btn ${className}`;
|
||
btn.setAttribute("aria-label", label);
|
||
btn.title = label;
|
||
btn.textContent = glyph;
|
||
btn.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
onClick();
|
||
});
|
||
return btn;
|
||
}
|
||
|
||
_buildHead(entry) {
|
||
const head = document.createElement("div");
|
||
head.className = "chat-head";
|
||
head.dataset.chatUid = entry.uid;
|
||
|
||
const openBtn = document.createElement("button");
|
||
openBtn.type = "button";
|
||
openBtn.className = "chat-head-open";
|
||
openBtn.setAttribute("aria-label", `Open chat with ${entry.username || "member"}`);
|
||
openBtn.title = entry.username || "";
|
||
openBtn.appendChild(Avatar.badgeElement(entry, 40, "md"));
|
||
const badge = document.createElement("span");
|
||
badge.className = "nav-badge chat-head-badge";
|
||
badge.hidden = true;
|
||
openBtn.appendChild(badge);
|
||
openBtn.addEventListener("click", () => this.open(entry));
|
||
|
||
const closeBtn = this._iconButton("chat-head-close", `Close chat with ${entry.username || "member"}`, "âś•", () => this.close(entry.uid));
|
||
head.append(openBtn, closeBtn);
|
||
return head;
|
||
}
|
||
|
||
_updateHead(head, entry) {
|
||
const badge = head.querySelector(".chat-head-badge");
|
||
const unread = entry.unread || 0;
|
||
badge.textContent = String(unread);
|
||
badge.hidden = unread === 0;
|
||
const label = `Open chat with ${entry.username || "member"}`;
|
||
head.querySelector(".chat-head-open").setAttribute("aria-label", unread ? `${label}, ${unread} unread` : label);
|
||
}
|
||
|
||
_buildPanel() {
|
||
this.panel = document.createElement("div");
|
||
this.panel.className = "chat-panel";
|
||
this.panel.id = "chat-panel";
|
||
this.panel.hidden = true;
|
||
this.panel.setAttribute("role", "dialog");
|
||
this.panel.setAttribute("aria-label", "Chats");
|
||
|
||
const header = document.createElement("div");
|
||
header.className = "chat-panel-header";
|
||
const title = document.createElement("h2");
|
||
title.className = "chat-panel-title";
|
||
title.textContent = "Chats";
|
||
const compose = this._iconButton("chat-panel-compose", "New message", "✎", () => this.openCompose());
|
||
const expand = document.createElement("a");
|
||
expand.className = "chat-icon-btn chat-panel-expand";
|
||
expand.href = "/messages";
|
||
expand.title = "Open Messages";
|
||
expand.setAttribute("aria-label", "Open Messages");
|
||
expand.textContent = "↗";
|
||
header.append(title, this._windowActions([compose, expand]));
|
||
|
||
const search = document.createElement("div");
|
||
search.className = "chat-panel-search";
|
||
this.searchInput = document.createElement("input");
|
||
this.searchInput.type = "search";
|
||
this.searchInput.className = "chat-panel-search-input";
|
||
this.searchInput.placeholder = "Search people...";
|
||
this.searchInput.autocomplete = "off";
|
||
this.searchInput.setAttribute("aria-label", "Search people");
|
||
search.appendChild(this.searchInput);
|
||
|
||
this.panelList = document.createElement("div");
|
||
this.panelList.className = "chat-panel-list";
|
||
this.panelList.setAttribute("role", "listbox");
|
||
this.panelList.setAttribute("aria-label", "Conversations");
|
||
|
||
const footer = document.createElement("a");
|
||
footer.className = "chat-panel-footer";
|
||
footer.href = "/messages";
|
||
footer.textContent = "See all in Messages";
|
||
|
||
this.panel.append(header, search, this.panelList, footer);
|
||
this.appendChild(this.panel);
|
||
this.panelNav = this._bindPeopleSearch(this.searchInput, this.panelList, {
|
||
onEmpty: () => this._showConversations(),
|
||
onChoose: (user) => this.open(user),
|
||
});
|
||
}
|
||
|
||
_bindPeopleSearch(input, list, { onEmpty, onChoose }) {
|
||
const nav = new ListNav(input, list, {
|
||
itemSelector: ".conversation-item",
|
||
activeClass: "active",
|
||
firstDefault: false,
|
||
chooseOnTab: false,
|
||
isOpen: () => true,
|
||
onChoose: (item) => onChoose(ConversationItem.user(item)),
|
||
});
|
||
let timer = null;
|
||
let sequence = 0;
|
||
input.addEventListener("input", () => {
|
||
clearTimeout(timer);
|
||
const query = input.value.trim();
|
||
sequence += 1;
|
||
if (!query) {
|
||
onEmpty();
|
||
return;
|
||
}
|
||
const token = sequence;
|
||
timer = window.setTimeout(async () => {
|
||
let results = [];
|
||
try {
|
||
const data = await Http.getJson(`${this.searchUrl}?q=${encodeURIComponent(query)}`);
|
||
results = data.results || [];
|
||
} catch {
|
||
results = [];
|
||
}
|
||
if (token !== sequence) return;
|
||
this._fillList(list, results.map((user) => ({ other_user: user })), "No people found");
|
||
nav.opened();
|
||
if (results.length) nav.setActive(0);
|
||
}, SEARCH_DEBOUNCE_MS);
|
||
});
|
||
list.addEventListener("click", (event) => {
|
||
const item = event.target.closest(".conversation-item");
|
||
if (!item || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||
event.preventDefault();
|
||
onChoose(ConversationItem.user(item));
|
||
});
|
||
return nav;
|
||
}
|
||
|
||
_fillList(list, conversations, emptyText) {
|
||
list.replaceChildren(...conversations.map((conv) => ConversationItem.build(conv)));
|
||
if (conversations.length) return;
|
||
const empty = document.createElement("div");
|
||
empty.className = "empty-state empty-state-borderless";
|
||
empty.textContent = emptyText;
|
||
list.appendChild(empty);
|
||
}
|
||
|
||
_showConversations() {
|
||
if (this.conversations === null) {
|
||
this._fillList(this.panelList, [], "Loading…");
|
||
return;
|
||
}
|
||
this._fillList(this.panelList, this.conversations, "No conversations yet");
|
||
this.panelNav.opened();
|
||
}
|
||
|
||
async _loadConversations() {
|
||
try {
|
||
const data = await Http.getJson(this.conversationsUrl);
|
||
this.conversations = data.conversations || [];
|
||
} catch {
|
||
this.conversations = this.conversations || [];
|
||
}
|
||
if (this.panelOpen && !this.searchInput.value.trim()) this._showConversations();
|
||
}
|
||
|
||
_openPanel() {
|
||
this.panelOpen = true;
|
||
this.panel.hidden = false;
|
||
this._setToggleState(true);
|
||
this.searchInput.value = "";
|
||
this._showConversations();
|
||
this._loadConversations();
|
||
this.searchInput.focus({ preventScroll: true });
|
||
}
|
||
|
||
_closePanel() {
|
||
if (!this.panelOpen) return;
|
||
this.panelOpen = false;
|
||
this.panel.hidden = true;
|
||
this._setToggleState(false);
|
||
}
|
||
|
||
_toggles() {
|
||
return document.querySelectorAll("[data-chat-panel-toggle]");
|
||
}
|
||
|
||
_bindToggles() {
|
||
this._toggles().forEach((toggle) => {
|
||
toggle.setAttribute("aria-haspopup", "dialog");
|
||
toggle.setAttribute("aria-controls", this.panel.id);
|
||
toggle.setAttribute("aria-expanded", "false");
|
||
});
|
||
}
|
||
|
||
_setToggleState(open) {
|
||
this._toggles().forEach((toggle) => toggle.setAttribute("aria-expanded", open ? "true" : "false"));
|
||
}
|
||
|
||
_intercepts(event) {
|
||
if (this._isMobile() || event.button !== 0) return false;
|
||
return !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey);
|
||
}
|
||
|
||
_bindDocument() {
|
||
document.addEventListener("click", (event) => {
|
||
const toggle = event.target.closest("[data-chat-panel-toggle]");
|
||
if (toggle) {
|
||
if (!this._intercepts(event)) return;
|
||
event.preventDefault();
|
||
this.togglePanel();
|
||
return;
|
||
}
|
||
const opener = event.target.closest("[data-chat-open]");
|
||
if (opener) {
|
||
if (!this._intercepts(event)) return;
|
||
event.preventDefault();
|
||
this.open({
|
||
uid: opener.dataset.chatOpen,
|
||
username: opener.dataset.chatUsername || "",
|
||
avatar_seed: opener.dataset.chatAvatarSeed || "",
|
||
});
|
||
return;
|
||
}
|
||
if (this.panelOpen && !this.panel.contains(event.target)) this._closePanel();
|
||
});
|
||
document.addEventListener("keydown", (event) => {
|
||
if (event.key !== "Escape" || !this.panelOpen) return;
|
||
this._closePanel();
|
||
const toggle = this._toggles()[0];
|
||
if (toggle) toggle.focus();
|
||
});
|
||
window.addEventListener("resize", () => {
|
||
cancelAnimationFrame(this._resizeFrame);
|
||
this._resizeFrame = requestAnimationFrame(() => {
|
||
if (this._isMobile()) {
|
||
this._closePanel();
|
||
} else {
|
||
this._enforceLimits();
|
||
this._persist();
|
||
}
|
||
this._render();
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
customElements.define("dp-chat-dock", AppChatDock);
|