feat: Implement recent chats feature with API endpoint and UI integration

This commit is contained in:
Andre Beging
2025-10-07 15:08:33 +02:00
parent 85094f8683
commit ddf29c1d36
7 changed files with 682 additions and 3 deletions

View File

@@ -12,11 +12,32 @@ const hooksListEl = document.querySelector("#hooks-list");
const hookTemplate = document.querySelector("#hook-template");
const createHookForm = document.querySelector("#create-hook-form");
const toggleCreateBtn = document.querySelector("#toggle-create");
const recentChatsBtn = document.querySelector("#recent-chats-btn");
const recentChatsModal = document.querySelector("#recent-chats-modal");
const recentChatsListEl = document.querySelector("#recent-chats-list");
const closeRecentChatsBtn = document.querySelector("#close-recent-chats");
const recentChatsSearchEl = document.querySelector("#recent-chats-search");
let sessionDetailsVisible = false;
let sessionDetailsTouched = false;
let createFormVisible = false;
let createFormTouched = false;
let lastFocusedElement = null;
let recentChatsData = [];
if (recentChatsSearchEl) {
recentChatsSearchEl.disabled = true;
recentChatsSearchEl.addEventListener("input", () => {
applyRecentChatsFilter();
});
recentChatsSearchEl.addEventListener("keydown", (event) => {
if (event.key === "Escape" && recentChatsSearchEl.value) {
event.preventDefault();
recentChatsSearchEl.value = "";
applyRecentChatsFilter();
}
});
}
function setSessionDetailsVisibility(show, { fromUser = false } = {}) {
if (!toggleSessionBtn || !sessionDetailsEl) return;
@@ -66,10 +87,29 @@ async function fetchJSON(url, options = {}) {
...options,
});
if (!response.ok) {
const message = await response.text();
const contentType = response.headers.get("content-type") || "";
let message = "Request failed";
if (contentType.includes("application/json")) {
try {
const payload = await response.json();
if (payload && typeof payload === "object") {
message = payload.detail || JSON.stringify(payload);
}
} catch {
message = await response.text();
}
} else {
const text = await response.text();
if (text) {
message = text;
}
}
throw new Error(message || "Request failed");
}
return response.status === 204 ? null : response.json();
if (response.status === 204) {
return null;
}
return response.json();
}
function updateSessionUI(status) {
@@ -116,6 +156,10 @@ function updateSessionUI(status) {
} else if (shouldShowDetails && !sessionDetailsVisible) {
setSessionDetailsVisibility(true);
}
setRecentChatsAvailability(status.authorized);
if (!status.authorized) {
closeRecentChatsDialog();
}
}
async function refreshAll() {
@@ -128,6 +172,268 @@ async function refreshAll() {
await loadHooks();
}
function setRecentChatsAvailability(isAuthorized) {
if (!recentChatsBtn) return;
recentChatsBtn.disabled = !isAuthorized;
recentChatsBtn.title = isAuthorized
? "Browse your recent Telegram chats"
: "Authorize the session to view recent chats";
if (!isAuthorized && recentChatsSearchEl) {
recentChatsSearchEl.value = "";
recentChatsSearchEl.disabled = true;
}
}
function applyRecentChatsFilter() {
if (!recentChatsListEl) return;
const query = recentChatsSearchEl ? recentChatsSearchEl.value.trim().toLowerCase() : "";
const source = Array.isArray(recentChatsData) ? recentChatsData : [];
const filtered = !query
? source
: source.filter((chat) => {
const parts = [
chat.display_name,
chat.chat_id,
chat.username ? `@${chat.username}` : null,
chat.phone_number,
chat.chat_type,
]
.filter(Boolean)
.map((part) => String(part).toLowerCase());
return parts.some((part) => part.includes(query));
});
renderRecentChats(filtered);
}
async function openRecentChatsDialog() {
if (!recentChatsModal || !recentChatsListEl) return;
if (recentChatsModal.classList.contains("hidden") && document.activeElement instanceof HTMLElement) {
lastFocusedElement = document.activeElement;
}
recentChatsModal.classList.remove("hidden");
recentChatsModal.scrollTop = 0;
recentChatsListEl.innerHTML = "";
recentChatsData = [];
if (recentChatsSearchEl) {
recentChatsSearchEl.value = "";
recentChatsSearchEl.disabled = true;
}
const loading = document.createElement("p");
loading.className = "feedback";
loading.textContent = "Loading recent chats…";
recentChatsListEl.appendChild(loading);
try {
const chats = await fetchJSON("/api/recent-chats");
recentChatsData = Array.isArray(chats) ? chats : [];
if (recentChatsSearchEl) {
recentChatsSearchEl.disabled = false;
recentChatsSearchEl.focus();
}
applyRecentChatsFilter();
} catch (error) {
recentChatsListEl.innerHTML = "";
const message = document.createElement("p");
message.className = "feedback";
const text = typeof error?.message === "string" ? error.message : "Unable to load recent chats.";
message.textContent = text.includes("Session not authorized")
? "Authorize the session to view recent chats."
: `Unable to load recent chats: ${text}`;
recentChatsListEl.appendChild(message);
recentChatsData = [];
if (recentChatsSearchEl) {
recentChatsSearchEl.disabled = true;
}
}
document.addEventListener("keydown", handleRecentChatsKeydown);
if (recentChatsModal && (!recentChatsSearchEl || recentChatsSearchEl.disabled)) {
const focusTarget = recentChatsModal.querySelector("button, [href], input, textarea, [tabindex]:not([tabindex='-1'])");
if (focusTarget instanceof HTMLElement) {
focusTarget.focus();
}
}
}
function renderRecentChats(chats) {
if (!recentChatsListEl) return;
recentChatsListEl.innerHTML = "";
if (!Array.isArray(chats) || !chats.length) {
const empty = document.createElement("p");
empty.className = "feedback";
empty.textContent = "No recent chats available. Start a conversation in Telegram to see it here.";
recentChatsListEl.appendChild(empty);
return;
}
chats.forEach((chat) => {
const item = document.createElement("div");
item.className = "recent-chat-item";
const details = document.createElement("div");
details.className = "recent-chat-details";
const nameEl = document.createElement("span");
nameEl.className = "recent-chat-name";
nameEl.textContent = chat.display_name || chat.chat_id;
const metaEl = document.createElement("span");
metaEl.className = "recent-chat-meta";
const metaParts = [];
if (chat.chat_type) {
metaParts.push(String(chat.chat_type).toUpperCase());
}
if (chat.last_used_at) {
metaParts.push(`Last activity ${new Date(chat.last_used_at).toLocaleString()}`);
}
metaEl.textContent = metaParts.length ? metaParts.join(" • ") : "Unknown chat";
const feedbackEl = document.createElement("span");
feedbackEl.className = "recent-chat-feedback";
let feedbackTimeout;
const setFeedback = (message, isError = false) => {
feedbackEl.textContent = message;
feedbackEl.style.color = isError ? "#ffbac7" : message ? "#64dd9b" : "";
if (feedbackTimeout) {
clearTimeout(feedbackTimeout);
feedbackTimeout = undefined;
}
if (message) {
feedbackTimeout = window.setTimeout(() => {
feedbackEl.textContent = "";
feedbackEl.style.color = "";
feedbackTimeout = undefined;
}, 2400);
}
};
details.appendChild(nameEl);
details.appendChild(metaEl);
details.appendChild(feedbackEl);
item.appendChild(details);
const appendRow = (labelText, displayValue, copyValue, options = {}) => {
const { required = false, valueClasses = [] } = options;
const rawValue = displayValue ?? "";
const valueString = rawValue !== null && rawValue !== undefined ? String(rawValue) : "";
const hasValue = valueString.trim() !== "";
if (!required && !hasValue) {
return;
}
const row = document.createElement("div");
row.className = "recent-chat-row";
const labelEl = document.createElement("span");
labelEl.className = "recent-chat-label";
labelEl.textContent = labelText;
const actionsEl = document.createElement("div");
actionsEl.className = "recent-chat-actions";
const valueButton = document.createElement("button");
valueButton.type = "button";
valueButton.className = "recent-chat-value-button";
if (Array.isArray(valueClasses)) {
valueClasses.forEach((cls) => valueButton.classList.add(cls));
} else if (typeof valueClasses === "string" && valueClasses) {
valueButton.classList.add(valueClasses);
}
valueButton.setAttribute("aria-label", `Copy ${labelText.toLowerCase()} for ${nameEl.textContent}`);
const valueTextEl = document.createElement("span");
valueTextEl.className = "recent-chat-value";
valueTextEl.textContent = hasValue ? valueString : "—";
valueButton.appendChild(valueTextEl);
const iconEl = document.createElement("span");
iconEl.className = "recent-chat-copy-icon";
iconEl.innerHTML = `
<svg class="icon icon-copy" viewBox="0 0 24 24" aria-hidden="true">
<path d="M16 1H4a2 2 0 0 0-2 2v14h2V3h12V1zm3 4H8a2 2 0 0 0-2 2v16h14a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2zm0 18H8V7h11v16z" />
</svg>
`;
valueButton.appendChild(iconEl);
const canCopy = hasValue && copyValue !== null && copyValue !== undefined && copyValue !== "";
if (canCopy) {
valueButton.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(String(copyValue));
setFeedback(`${labelText} copied to clipboard.`);
} catch (err) {
setFeedback(`Copy failed: ${err.message}`, true);
}
});
} else {
valueButton.disabled = true;
valueButton.setAttribute("aria-disabled", "true");
}
actionsEl.appendChild(valueButton);
row.appendChild(labelEl);
row.appendChild(actionsEl);
item.appendChild(row);
};
appendRow(
"Chat ID",
typeof chat.chat_id === "number" || typeof chat.chat_id === "bigint" ? String(chat.chat_id) : chat.chat_id,
chat.chat_id,
{ required: true, valueClasses: ["mono"] },
);
appendRow(
"Username",
chat.username ? `@${chat.username}` : "",
chat.username ? `@${chat.username}` : "",
{},
);
appendRow(
"Phone",
chat.phone_number ? String(chat.phone_number) : "",
chat.phone_number ? String(chat.phone_number) : "",
{},
);
recentChatsListEl.appendChild(item);
});
}
function closeRecentChatsDialog() {
if (!recentChatsModal || recentChatsModal.classList.contains("hidden")) return;
recentChatsModal.classList.add("hidden");
document.removeEventListener("keydown", handleRecentChatsKeydown);
if (lastFocusedElement && typeof lastFocusedElement.focus === "function") {
lastFocusedElement.focus();
}
}
function handleRecentChatsKeydown(event) {
if (event.key === "Escape") {
event.preventDefault();
closeRecentChatsDialog();
}
}
if (recentChatsBtn) {
recentChatsBtn.addEventListener("click", () => {
openRecentChatsDialog();
});
}
if (closeRecentChatsBtn) {
closeRecentChatsBtn.addEventListener("click", () => {
closeRecentChatsDialog();
});
}
if (recentChatsModal) {
recentChatsModal.addEventListener("click", (event) => {
if (event.target === recentChatsModal) {
closeRecentChatsDialog();
}
});
}
async function loadHooks() {
try {
const hooks = await fetchJSON("/api/hooks");