Convert project to TypeScript; add workflow to build with Vite then publish to GH Pages.

This commit is contained in:
天クマ 2026-07-20 11:18:19 -03:00
commit e615234325
30 changed files with 1932 additions and 443 deletions

39
.github/workflows/build.yml vendored Normal file
View file

@ -0,0 +1,39 @@
name: Build Vite
on:
push:
branches:
- master
workflow_dispatch:
permissions:
contents: write
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [24.x]
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- name: Install dependencies & build
run: |
npm ci
npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v4
with:
publish_dir: ./dist
github_token: ${{ secrets.GITHUB_TOKEN }}

29
.gitignore vendored
View file

@ -1,29 +1,2 @@
# Licensed to the Apache Software Foundation (ASF) under one dist/
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
.DS_Store
# Generated by package manager
node_modules/ node_modules/
# Generated by Cordova
/plugins/
/platforms/
pandora.apks
/android/app/build/
test-upload-key.jks

1249
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

18
package.json Normal file
View file

@ -0,0 +1,18 @@
{
"name": "pandora",
"version": "1.0.0",
"description": "<img width=\"1920\" height=\"auto\" alt=\"PANDORA\" src=\"https://github.com/user-attachments/assets/d9d7ba36-4510-47e1-8c49-b1977a26c448\" />",
"main": "index.js",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"typescript": "^7.0.2",
"vite": "^8.1.5"
}
}

20
tsconfig.json Normal file
View file

@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"isolatedModules": true,
"skipLibCheck": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"outDir": "./dist",
"rootDir": "./web/src",
"sourceMap": true
},
"include": ["web/src"]
}

9
vite.config.ts Normal file
View file

@ -0,0 +1,9 @@
import { defineConfig } from 'vite';
export default defineConfig({
root: 'web',
build: {
outDir: '../dist',
emptyOutDir: true,
},
});

View file

@ -169,6 +169,6 @@
</div> </div>
<!-- Client-side script loaded as ES Module --> <!-- Client-side script loaded as ES Module -->
<script type="module" src="./js/app.js"></script> <script type="module" src="./src/app.ts"></script>
</body> </body>
</html> </html>

View file

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Before After
Before After

View file

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Before After
Before After

View file

@ -1,17 +1,18 @@
import { config } from "./config.js"; import { config } from "./config";
import { waha } from "./waha.js"; import { waha } from "./waha";
import { ui, elements } from "./ui.js"; import { ui, elements } from "./ui";
import { websocket } from "./websocket.js"; import { websocket } from "./websocket";
import { compensateMessageOrdering, debounce, formatTime, normalizeId } from "./utils.js"; import { compensateMessageOrdering, debounce, formatTime, normalizeId } from "./utils";
import { fetchChats, getAppUser, getChatMessages, getChatPicture, getChats, getUser, getUserAbout, markRead, sendStatus, updateOnlineStatus } from "./storage.js"; import { fetchChats, getAppUser, getChatMessages, getChatPicture, getChats, getUser, getUserAbout, markRead, sendStatus, updateOnlineStatus } from "./storage";
import { upsertMessages } from "./db.js"; import { upsertMessages } from "./db";
import { showNotification } from "./notification.js"; import { showNotification } from "./notification";
import type { Chat, Message, WebSocketEvent } from "./types";
let activeChatState = null; let activeChatState: Chat | null = null;
const messageTone = new Audio("./message.ogg"); const messageTone = new Audio("./message.ogg");
const longPressEvent = new CustomEvent("longpress"); const longPressEvent = new CustomEvent("longpress");
export let isLoadingChat = false; export let isLoadingChat = false;
export let notificationAuthorization = false; export let notificationAuthorization: NotificationPermission = "default";
document.addEventListener('DOMContentLoaded', async () => { document.addEventListener('DOMContentLoaded', async () => {
askForNotificationPermission(); askForNotificationPermission();
@ -45,18 +46,18 @@ async function setupElementsData() {
const usrInfo = await getUser(usr.id); const usrInfo = await getUser(usr.id);
const usrAbout = (await getUserAbout(usr.id))?.about; const usrAbout = (await getUserAbout(usr.id))?.about;
elements.contentUserName.forEach(e => { elements.contentUserName.forEach(e => {
e.innerHTML = usr.pushName; e.innerHTML = usr.pushName || usr.name || '';
}) })
elements.contentUserNumber.forEach(async e => { elements.contentUserNumber.forEach(async e => {
e.innerHTML = usrInfo.number; if (usrInfo) e.innerHTML = usrInfo.number;
}) })
elements.resourceUserPic.forEach(async e => { elements.resourceUserPic.forEach(async e => {
e.src = usrPic; if (usrPic) e.src = usrPic;
}) })
elements.valueUserStatus.forEach(async e => { elements.valueUserStatus.forEach(async e => {
e.value = usrAbout.trim(); if (usrAbout) e.value = usrAbout.trim();
}) })
} catch (error) { } catch (error: any) {
console.error(error.message); console.error(error.message);
} }
} }
@ -76,7 +77,7 @@ function loadChats() {
} }
} }
}); });
} catch (error) { } catch (error: any) {
console.error('Failed to load chats:', error); console.error('Failed to load chats:', error);
elements.chatList.innerHTML = ` elements.chatList.innerHTML = `
<li class="loading-chats" style="color: var(--text-primary); text-align: center; padding: 20px;"> <li class="loading-chats" style="color: var(--text-primary); text-align: center; padding: 20px;">
@ -93,7 +94,7 @@ function loadChats() {
} }
let isScrollingProgrammatically = false; let isScrollingProgrammatically = false;
let scrollTimeout = null; let scrollTimeout: ReturnType<typeof setTimeout> | null = null;
function scrollToChat(smooth = true) { function scrollToChat(smooth = true) {
isScrollingProgrammatically = true; isScrollingProgrammatically = true;
@ -135,7 +136,7 @@ function setupEventListeners() {
if (window.innerWidth > 768) return; if (window.innerWidth > 768) return;
if (isScrollingProgrammatically) return; if (isScrollingProgrammatically) return;
clearTimeout(scrollTimeout); if (scrollTimeout) clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(() => { scrollTimeout = setTimeout(() => {
const scrollLeft = elements.appContainer.scrollLeft; const scrollLeft = elements.appContainer.scrollLeft;
const width = elements.appContainer.clientWidth; const width = elements.appContainer.clientWidth;
@ -156,8 +157,8 @@ function setupEventListeners() {
} }
}); });
elements.chatSearch.addEventListener('input', (e) => { elements.chatSearch.addEventListener('input', (e: Event) => {
const query = e.target.value.toLowerCase(); const query = (e.target as HTMLInputElement).value.toLowerCase();
const filtered = getChats().filter(chat => const filtered = getChats().filter(chat =>
chat.name.toLowerCase().includes(query) chat.name.toLowerCase().includes(query)
); );
@ -181,15 +182,18 @@ function setupEventListeners() {
if (e.target == e.currentTarget) ui.toggleChatBottomBar(); if (e.target == e.currentTarget) ui.toggleChatBottomBar();
}); });
elements.markreadBtn.addEventListener('click', () => { elements.markreadBtn.addEventListener('click', async () => {
markRead(activeChatState.id); if (activeChatState) {
const result = await markRead(activeChatState.id);
if (result) ui.updateChatInChatList2(result);
}
}) })
elements.attachmentBtn.addEventListener('click', () => { elements.attachmentBtn.addEventListener('click', () => {
elements.attachmentInput.click(); elements.attachmentInput.click();
}) })
elements.attachmentInput.addEventListener('change', function () { elements.attachmentInput.addEventListener('change', function (this: HTMLInputElement) {
const firstFile = this.files[0]; const firstFile = this.files?.[0];
sendFileMessage(firstFile); if (firstFile) sendFileMessage(firstFile);
}) })
elements.backToSidebarBtn.addEventListener('click', () => { elements.backToSidebarBtn.addEventListener('click', () => {
@ -198,7 +202,8 @@ function setupEventListeners() {
elements.desktopSidebarButtons.forEach(sidebarBtn => { elements.desktopSidebarButtons.forEach(sidebarBtn => {
sidebarBtn.addEventListener('click', () => { sidebarBtn.addEventListener('click', () => {
ui.showExtraPage(sidebarBtn.dataset.page); const page = sidebarBtn.dataset.page;
if (page) ui.showExtraPage(page);
}) })
}) })
@ -215,7 +220,7 @@ function setupEventListeners() {
}, 2000)) }, 2000))
elements.selectable.forEach(e => { elements.selectable.forEach(e => {
let timerId, longPressed; let timerId: ReturnType<typeof setTimeout>, longPressed: boolean;
e.addEventListener('mousedown', () => { e.addEventListener('mousedown', () => {
longPressed = false; longPressed = false;
@ -223,12 +228,12 @@ function setupEventListeners() {
timerId = setTimeout(() => { timerId = setTimeout(() => {
longPressed = true; longPressed = true;
e.dispatchEvent(longPressEvent); e.dispatchEvent(longPressEvent);
}) }, 500); // 500ms for long press
}) })
e.addEventListener('click', () => { e.addEventListener('click', (event) => {
if (longPressed) { if (longPressed) {
e.preventDefault(); event.preventDefault();
clearTimeout(timerId); clearTimeout(timerId);
} }
}) })
@ -240,8 +245,7 @@ function setupEventListeners() {
} }
function initWebSocket() { function initWebSocket() {
websocket.connect((data) => { websocket.connect((data: WebSocketEvent) => {
// console.log('[WS] Received event:', data.event, data);
const ev = data.event; const ev = data.event;
if (ev === 'message' || ev === 'message.any' || ev === 'message.ack') { if (ev === 'message' || ev === 'message.any' || ev === 'message.ack') {
handleIncomingMessage(data.payload); handleIncomingMessage(data.payload);
@ -251,31 +255,31 @@ function initWebSocket() {
} }
async function handleIncomingMessage(msg) { async function handleIncomingMessage(msg: Message) {
if (!msg) return; if (!msg) return;
ui.updateChatInChatList(msg); ui.updateChatInChatList(msg);
const rawChatId = msg.chatId || msg.from || (msg.chat && msg.chat.id); const rawChatId = msg.chatId || (typeof msg.from === 'string' ? msg.from : (msg.from as any)?._serialized) || (msg.chat && msg.chat.id);
const msgChatId = normalizeId(rawChatId); const msgChatId = normalizeId(rawChatId);
if (!msgChatId) { if (!msgChatId) {
console.warn('[WS] Could not resolve chatId from payload:', msg); console.warn('[WS] Could not resolve chatId from payload:', msg);
return; return;
} }
// console.log('[WS] Resolved msgChatId:', msgChatId, '| activeChatState:', activeChatState?.id);
if (!msg.fromMe) { if (!msg.fromMe) {
messageTone.play(); messageTone.play();
} }
if (notificationAuthorization) { if (notificationAuthorization === "granted") {
new Notification("New message", { body: msg.body }); new Notification("New message", { body: msg.body || msg.text });
} }
if (activeChatState && activeChatState.id === msgChatId) { if (activeChatState && activeChatState.id === msgChatId) {
const msgId = normalizeId(msg.id) || msg.id; const msgId = normalizeId(msg.id as any) || (msg.id as string);
const exists = document.getElementById(msgId); const exists = document.getElementById(msgId);
if (!exists) { if (!exists) {
const scrolled = elements.messagesContainer.scrollTop == elements.messagesContainer.scrollTopMax; const container = elements.messagesContainer;
const scrolled = container.scrollTop === (container.scrollHeight - container.clientHeight);
ui.appendSingleMessage({ ...msg, chatId: msgChatId }, activeChatState.name, (await getAppUser()).id); ui.appendSingleMessage({ ...msg, chatId: msgChatId }, activeChatState.name, (await getAppUser()).id);
if (scrolled) { if (scrolled) {
ui.scrollToBottom(); ui.scrollToBottom();
@ -284,7 +288,7 @@ async function handleIncomingMessage(msg) {
} }
} }
async function selectChat(chat, isPopState = false, smoothScroll = true) { async function selectChat(chat: Chat, isPopState = false, smoothScroll = true) {
if (isLoadingChat) return; if (isLoadingChat) return;
isLoadingChat = true; isLoadingChat = true;
@ -292,8 +296,6 @@ async function selectChat(chat, isPopState = false, smoothScroll = true) {
chat.unreadCount = 0; chat.unreadCount = 0;
// ui.renderChatList(chatsState, activeChatState, selectChat);
ui.toggleChatState(true); ui.toggleChatState(true);
elements.activeChatName.textContent = chat.name.toUpperCase(); elements.activeChatName.textContent = chat.name.toUpperCase();
elements.activeChatAvatar.textContent = chat.name ? chat.name.substring(0, 1).toUpperCase() : '?'; elements.activeChatAvatar.textContent = chat.name ? chat.name.substring(0, 1).toUpperCase() : '?';
@ -363,7 +365,7 @@ async function sendMessage() {
sender: 'me', sender: 'me',
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
status: 'sending' status: 'sending'
}; } as any;
ui.appendSingleMessage(tempMsg, activeChatState.name, (await getAppUser()).id); ui.appendSingleMessage(tempMsg, activeChatState.name, (await getAppUser()).id);
ui.scrollToBottom(); ui.scrollToBottom();
@ -387,7 +389,7 @@ async function sendMessage() {
if (!activeChatState.id.endsWith('@lid')) { if (!activeChatState.id.endsWith('@lid')) {
await waha.readChat(activeChatState.id); await waha.readChat(activeChatState.id);
} }
} catch (e) { } catch (e: any) {
console.warn('readChat failed (non-fatal):', e.message); console.warn('readChat failed (non-fatal):', e.message);
} }
@ -396,25 +398,26 @@ async function sendMessage() {
const tempBubble = document.getElementById(tempMsg.id); const tempBubble = document.getElementById(tempMsg.id);
if (tempBubble) { if (tempBubble) {
if (responseData && responseData.id) { if (responseData && responseData.id) {
tempBubble.id = normalizeId(responseData.id); tempBubble.id = normalizeId(responseData.id as any) || tempBubble.id;
} }
const meta = tempBubble.querySelector('.message-meta'); const meta = tempBubble.querySelector('.message-meta');
meta.innerHTML = `<span>${formatTime(new Date())}</span><span style="width:14px; height:14px;" class="mif-done">`; if (meta) meta.innerHTML = `<span>${formatTime(new Date())}</span><span style="width:14px; height:14px;" class="mif-done">`;
} }
activeChatState.lastMessage = text; activeChatState.lastMessage = text;
activeChatState.timestamp = new Date(); activeChatState.timestamp = new Date().toISOString();
} catch (error) { } catch (error) {
console.error('Failed to send message:', error); console.error('Failed to send message:', error);
const tempBubble = document.getElementById(tempMsg.id); const tempBubble = document.getElementById(tempMsg.id);
if (tempBubble) { if (tempBubble) {
const meta = tempBubble.querySelector('.message-meta'); const meta = tempBubble.querySelector('.message-meta');
meta.innerHTML = `<span style="color: #ef4444;">Failed to send</span>`; if (meta) meta.innerHTML = `<span style="color: #ef4444;">Failed to send</span>`;
} }
} }
} }
async function sendFileMessage(file) { async function sendFileMessage(file: File) {
if (!activeChatState) return;
try { try {
const tempId = 'temp-' + Date.now(); const tempId = 'temp-' + Date.now();
const tempMsg = { const tempMsg = {
@ -432,15 +435,15 @@ async function sendFileMessage(file) {
url: URL.createObjectURL(file), url: URL.createObjectURL(file),
filename: file.name filename: file.name
} }
}; } as any;
ui.appendSingleMessage(tempMsg, activeChatState.name, (await getAppUser()).id, activeChatState.id, true); ui.appendSingleMessage(tempMsg, activeChatState.name, (await getAppUser()).id, true);
ui.scrollToBottom(); ui.scrollToBottom();
const result = await waha.sendFileMessage(activeChatState.id, file); const result = await waha.sendFileMessage(activeChatState.id, file);
ui.removeChatMessage(tempId); ui.removeChatMessage(tempId);
ui.appendSingleMessage(result.id, activeChatState.name, (await getAppUser()).id, activeChatState.id); ui.appendSingleMessage(result, activeChatState.name, (await getAppUser()).id);
} catch (error) { } catch (error: any) {
console.error(error.message); console.error(error.message);
} }
} }

View file

@ -1,13 +1,20 @@
// Client Configuration State & Storage Manager export interface Config {
wahaUrl: string;
session: string;
apiKey: string;
bgImg: string;
bgOpacity: string;
save(url: string, session: string, apiKey: string, bgImg: string, bgOpacity: string): void;
}
export const config = { export const config: Config = {
wahaUrl: localStorage.getItem('waha_url') || 'http://inspiran.beetal-castor.ts.net:3100', wahaUrl: localStorage.getItem('waha_url') || 'http://inspiran.beetal-castor.ts.net:3100',
session: localStorage.getItem('waha_session') || 'session_01kxc62bk5fs8vh4v127k88a7j', session: localStorage.getItem('waha_session') || 'session_01kxc62bk5fs8vh4v127k88a7j',
apiKey: localStorage.getItem('waha_api_key') || '', apiKey: localStorage.getItem('waha_api_key') || '',
bgImg: localStorage.getItem('background_image') || '', bgImg: localStorage.getItem('background_image') || '',
bgOpacity: localStorage.getItem('background_opacity') || '0.4', bgOpacity: localStorage.getItem('background_opacity') || '0.4',
save(url, session, apiKey, bgImg, bgOpacity) { save(url: string, session: string, apiKey: string, bgImg: string, bgOpacity: string): void {
this.wahaUrl = url.trim().replace(/\/$/, ""); this.wahaUrl = url.trim().replace(/\/$/, "");
this.session = session.trim(); this.session = session.trim();
this.apiKey = apiKey.trim(); this.apiKey = apiKey.trim();

View file

@ -1,25 +1,26 @@
import { normalizeId } from "./utils.js"; import { normalizeId } from "./utils";
import type { Chat, Message, StoredMedia } from "./types";
const DB_NAME = "pandora"; const DB_NAME = "pandora";
const DB_VERSION = 6; const DB_VERSION = 6;
let dbPromise = null; let dbPromise: Promise<IDBDatabase> | null = null;
function openDb() { function openDb(): Promise<IDBDatabase> {
if (dbPromise) return dbPromise; if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve, reject) => { dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION); const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = (e) => { req.onupgradeneeded = () => {
const db = req.result; const db = req.result;
const tx = req.transaction; const tx = req.transaction!;
if (!db.objectStoreNames.contains("chats")) { if (!db.objectStoreNames.contains("chats")) {
const store = db.createObjectStore("chats", { keyPath: "id" }); const store = db.createObjectStore("chats", { keyPath: "id" });
store.createIndex("timestamp", "timestamp", { unique: false }); store.createIndex("timestamp", "timestamp", { unique: false });
} }
let msgStore; let msgStore: IDBObjectStore;
if (!db.objectStoreNames.contains("messages")) { if (!db.objectStoreNames.contains("messages")) {
msgStore = db.createObjectStore("messages", { keyPath: "id" }); msgStore = db.createObjectStore("messages", { keyPath: "id" });
msgStore.createIndex("from", "from", { unique: false }); msgStore.createIndex("from", "from", { unique: false });
@ -33,11 +34,11 @@ function openDb() {
msgStore.createIndex("chatId_timestamp", ["chatId", "timestamp"], { unique: false }); msgStore.createIndex("chatId_timestamp", ["chatId", "timestamp"], { unique: false });
} }
if (db.objectStoreNames.contains("messages")) { // Migration logic
msgStore.openCursor().onsuccess = (event) => { msgStore.openCursor().onsuccess = (event) => {
const cursor = event.target.result; const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>).result;
if (cursor) { if (cursor) {
const m = cursor.value; const m = cursor.value as Message;
const from = normalizeId(m.from); const from = normalizeId(m.from);
const to = normalizeId(m.to); const to = normalizeId(m.to);
const chatId = normalizeId(m.chatId) || (m.fromMe ? to : from); const chatId = normalizeId(m.chatId) || (m.fromMe ? to : from);
@ -48,7 +49,6 @@ function openDb() {
cursor.continue(); cursor.continue();
} }
}; };
}
if (!db.objectStoreNames.contains("media")) { if (!db.objectStoreNames.contains("media")) {
db.createObjectStore("media", { keyPath: "reqId" }); db.createObjectStore("media", { keyPath: "reqId" });
@ -62,7 +62,7 @@ function openDb() {
return dbPromise; return dbPromise;
} }
export async function upsertChats(chats) { export async function upsertChats(chats: Chat[]): Promise<void> {
const db = await openDb(); const db = await openDb();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -84,7 +84,7 @@ export async function upsertChats(chats) {
}); });
} }
export async function loadChatsSorted() { export async function loadChatsSorted(): Promise<Chat[]> {
const db = await openDb(); const db = await openDb();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -92,9 +92,9 @@ export async function loadChatsSorted() {
const store = tx.objectStore("chats"); const store = tx.objectStore("chats");
const idx = store.index("timestamp"); const idx = store.index("timestamp");
const result = []; const result: Chat[] = [];
idx.openCursor(null, "prev").onsuccess = (e) => { idx.openCursor(null, "prev").onsuccess = (e) => {
const cursor = e.target.result; const cursor = (e.target as IDBRequest<IDBCursorWithValue | null>).result;
if (cursor) { if (cursor) {
result.push(cursor.value); result.push(cursor.value);
cursor.continue(); cursor.continue();
@ -107,7 +107,7 @@ export async function loadChatsSorted() {
}); });
} }
export async function loadChat(chatId) { export async function loadChat(chatId: string): Promise<Chat | undefined> {
const db = await openDb(); const db = await openDb();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -115,12 +115,12 @@ export async function loadChat(chatId) {
const store = tx.objectStore("chats"); const store = tx.objectStore("chats");
const req = store.get(chatId); const req = store.get(chatId);
tx.oncomplete = () => resolve(req.result) req.onsuccess = () => resolve(req.result);
tx.onerror = () => reject(req.error); req.onerror = () => reject(req.error);
}); });
} }
function mapMessage(m) { function mapMessage(m: Message): any {
const from = normalizeId(m.from); const from = normalizeId(m.from);
const to = normalizeId(m.to); const to = normalizeId(m.to);
const chatId = normalizeId(m.chatId) || (m.fromMe ? to : from); const chatId = normalizeId(m.chatId) || (m.fromMe ? to : from);
@ -139,7 +139,7 @@ function mapMessage(m) {
} }
} }
export async function upsertMessages(messages) { export async function upsertMessages(messages: Message[]): Promise<void> {
const db = await openDb(); const db = await openDb();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -155,7 +155,7 @@ export async function upsertMessages(messages) {
}); });
} }
export async function loadLatestMessages(chatId, limit = 50) { export async function loadLatestMessages(chatId: string, limit: number = 50): Promise<Message[]> {
const db = await openDb(); const db = await openDb();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -163,12 +163,12 @@ export async function loadLatestMessages(chatId, limit = 50) {
const store = tx.objectStore("messages"); const store = tx.objectStore("messages");
const idx = store.index("chatId_timestamp"); const idx = store.index("chatId_timestamp");
const out = []; const out: Message[] = [];
const range = IDBKeyRange.bound([chatId, -Infinity], [chatId, Infinity]); const range = IDBKeyRange.bound([chatId, -Infinity], [chatId, Infinity]);
idx.openCursor(range, "prev").onsuccess = (e) => { idx.openCursor(range, "prev").onsuccess = (e) => {
const cursor = e.target.result; const cursor = (e.target as IDBRequest<IDBCursorWithValue | null>).result;
if (!cursor) return resolve(out); if (!cursor) return resolve(out);
out.push(cursor.value); out.push(cursor.value);
@ -180,7 +180,7 @@ export async function loadLatestMessages(chatId, limit = 50) {
}); });
} }
export async function loadOlderMessages(chatId, oldestTimestamp, oldestId, limit = 50) { export async function loadOlderMessages(chatId: string, oldestTimestamp: any, oldestId: string, limit: number = 50): Promise<Message[]> {
const db = await openDb(); const db = await openDb();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -188,7 +188,7 @@ export async function loadOlderMessages(chatId, oldestTimestamp, oldestId, limit
const store = tx.objectStore("messages"); const store = tx.objectStore("messages");
const idx = store.index("cidTimestampId"); const idx = store.index("cidTimestampId");
const out = []; const out: Message[] = [];
const parsedTimestamp = isNaN(oldestTimestamp) ? oldestTimestamp : Number(oldestTimestamp); const parsedTimestamp = isNaN(oldestTimestamp) ? oldestTimestamp : Number(oldestTimestamp);
@ -200,7 +200,7 @@ export async function loadOlderMessages(chatId, oldestTimestamp, oldestId, limit
); );
idx.openCursor(range, "prev").onsuccess = (e) => { idx.openCursor(range, "prev").onsuccess = (e) => {
const cursor = e.target.result; const cursor = (e.target as IDBRequest<IDBCursorWithValue | null>).result;
if (!cursor) return resolve(out); if (!cursor) return resolve(out);
out.push(cursor.value); out.push(cursor.value);
@ -213,7 +213,7 @@ export async function loadOlderMessages(chatId, oldestTimestamp, oldestId, limit
}); });
} }
export async function upsertMedia(reqId, blob, filename) { export async function upsertMedia(reqId: string, blob: Blob, filename: string): Promise<void> {
const db = await openDb(); const db = await openDb();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -231,7 +231,7 @@ export async function upsertMedia(reqId, blob, filename) {
}); });
} }
export async function loadMedia(reqId) { export async function loadMedia(reqId: string): Promise<StoredMedia | undefined> {
const db = await openDb(); const db = await openDb();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

View file

@ -1,4 +1,4 @@
export async function showNotification(title, subtitle, time = 5000, hint) { export async function showNotification(title: string, subtitle: string, time: number = 5000, _hint?: string): Promise<void> {
const notificationBox = document.createElement('div'); const notificationBox = document.createElement('div');
notificationBox.classList.add('notification-box'); notificationBox.classList.add('notification-box');
@ -12,25 +12,26 @@ export async function showNotification(title, subtitle, time = 5000, hint) {
if (subtitle) { if (subtitle) {
notificationBox.appendChild(notificationSubtitle); notificationBox.appendChild(notificationSubtitle);
} }
document.querySelector('body').appendChild(notificationBox); document.querySelector('body')!.appendChild(notificationBox);
let clicked = false; let clicked = false;
notificationBox.addEventListener('click', () => { notificationBox.addEventListener('click', () => {
clicked = true;
hideNotification(notificationBox); hideNotification(notificationBox);
}) })
await new Promise(requestAnimationFrame); await new Promise(requestAnimationFrame);
notificationBox.classList.add("shown"); notificationBox.classList.add("shown");
await new Promise(r => setTimeout(r, time)); await new Promise<void>(r => setTimeout(r, time));
if (!clicked) { if (!clicked) {
hideNotification(notificationBox); hideNotification(notificationBox);
} }
} }
async function hideNotification(notificationBox) { async function hideNotification(notificationBox: HTMLDivElement): Promise<void> {
notificationBox.classList.remove('shown'); notificationBox.classList.remove('shown');
await new Promise(r => setTimeout(r, 1000)); await new Promise<void>(r => setTimeout(r, 1000));
notificationBox.remove(); notificationBox.remove();
} }

View file

@ -1,10 +1,11 @@
import { loadChat, loadChatsSorted, loadLatestMessages, loadMedia, loadOlderMessages, upsertChats, upsertMedia, upsertMessages } from "./db.js"; import { loadChat, loadChatsSorted, loadLatestMessages, loadMedia, loadOlderMessages, upsertChats, upsertMedia, upsertMessages } from "./db";
import { waha } from "./waha.js"; import { waha } from "./waha";
import type { Chat, Message, AppUser, ContactInfo, UserAboutResponse, ChatPictureResponse, StatusResponse, DownloadedMedia } from "./types";
let online = false; let online = false;
let chats = []; let chats: Chat[] = [];
export async function updateOnlineStatus() { export async function updateOnlineStatus(): Promise<void> {
try { try {
await waha.getVersion(); await waha.getVersion();
online = true; online = true;
@ -14,17 +15,17 @@ export async function updateOnlineStatus() {
} }
} }
export async function fetchChats() { export async function fetchChats(): Promise<void> {
if (online) { if (online) {
await getRemoteChats() await getRemoteChats()
} }
chats = await loadChatsSorted(); chats = await loadChatsSorted();
} }
export async function getRemoteChats() { export async function getRemoteChats(): Promise<void> {
const u = await waha.getChats(); const u = await waha.getChats();
const mapped = u.map(chat => ({ const mapped: Chat[] = u.map(chat => ({
id: chat.id, id: chat.id,
name: chat.name, name: chat.name,
lastMessage: chat.lastMessage, lastMessage: chat.lastMessage,
@ -35,15 +36,15 @@ export async function getRemoteChats() {
await upsertChats(mapped); await upsertChats(mapped);
} }
export function getUsers() { export function getUsers(): Chat[] {
return chats.filter(c => c.id.endsWith("@c.us")); return chats.filter(c => c.id.endsWith("@c.us"));
} }
export function getGroups() { export function getGroups(): Chat[] {
return chats.filter(c => c.id.endsWith("@g.us")); return chats.filter(c => c.id.endsWith("@g.us"));
} }
export async function getUser(number) { export async function getUser(number: string): Promise<ContactInfo | undefined> {
if (online) { if (online) {
return await waha.getUser(number); return await waha.getUser(number);
} else { } else {
@ -51,7 +52,7 @@ export async function getUser(number) {
} }
} }
export async function getUserAbout(userId) { export async function getUserAbout(userId: string): Promise<UserAboutResponse | undefined> {
if (online) { if (online) {
return await waha.getUserAbout(userId); return await waha.getUserAbout(userId);
} else { } else {
@ -59,25 +60,26 @@ export async function getUserAbout(userId) {
} }
} }
export function getChats() { export function getChats(): Chat[] {
return chats; return chats;
} }
export async function getAppUser() { export async function getAppUser(): Promise<AppUser> {
if (online) { if (online) {
const info = await waha.getMyInfo(); const info = await waha.getMyInfo();
localStorage.setItem('pandora-last-username', info.name); localStorage.setItem('pandora-last-username', info.pushName || info.name || '');
localStorage.setItem('pandora-last-userid', info.id); localStorage.setItem('pandora-last-userid', info.id);
return info; return info;
} else { } else {
return { return {
pushName: localStorage.getItem('pandora-last-username') || 'Unknown', pushName: localStorage.getItem('pandora-last-username') || 'Unknown',
name: localStorage.getItem('pandora-last-username') || 'Unknown',
id: localStorage.getItem('pandora-last-userid') || 'Unknown' id: localStorage.getItem('pandora-last-userid') || 'Unknown'
} } as AppUser;
} }
} }
export async function getMessage(chatId, msgId, downloadMedia) { export async function getMessage(chatId: string, msgId: string, downloadMedia: boolean): Promise<Message> {
if (online) { if (online) {
const newMessage = await waha.getSingleChatMessage(chatId, msgId, downloadMedia); const newMessage = await waha.getSingleChatMessage(chatId, msgId, downloadMedia);
upsertMessages([newMessage]); upsertMessages([newMessage]);
@ -88,14 +90,14 @@ export async function getMessage(chatId, msgId, downloadMedia) {
body: "You're offline", body: "You're offline",
from: "system", from: "system",
timestamp: new Date().toISOString() timestamp: new Date().toISOString()
}; } as Message;
} }
} }
export async function getMedia(reqId) { export async function getMedia(reqId: string): Promise<DownloadedMedia | undefined> {
const cached = await loadMedia(reqId); const cached = await loadMedia(reqId);
if (cached) { if (cached) {
return cached; return { blob: cached.blob, filename: cached.filename };
} }
try { try {
@ -109,7 +111,7 @@ export async function getMedia(reqId) {
} }
} }
export async function getChatMessages(chatId) { export async function getChatMessages(chatId: string): Promise<Message[]> {
if (online) { if (online) {
const newMessages = await waha.getChatMessages(chatId); const newMessages = await waha.getChatMessages(chatId);
upsertMessages(newMessages); upsertMessages(newMessages);
@ -119,7 +121,7 @@ export async function getChatMessages(chatId) {
} }
} }
export async function getMoreChatMessages(chatId, oldestTimestamp, oldestId, limit = 50) { export async function getMoreChatMessages(chatId: string, oldestTimestamp: any, oldestId: string): Promise<Message[]> {
if (online) { if (online) {
return waha.getChatMessages(chatId, oldestTimestamp); return waha.getChatMessages(chatId, oldestTimestamp);
} else { } else {
@ -127,7 +129,7 @@ export async function getMoreChatMessages(chatId, oldestTimestamp, oldestId, lim
} }
} }
export async function getChatPicture(chatId) { export async function getChatPicture(chatId: string): Promise<ChatPictureResponse> {
if (online) { if (online) {
return await waha.getChatPicture(chatId); return await waha.getChatPicture(chatId);
} else { } else {
@ -135,11 +137,11 @@ export async function getChatPicture(chatId) {
} }
} }
export function isOnline() { export function isOnline(): boolean {
return online; return online;
} }
export async function sendStatus(text) { export async function sendStatus(text: string): Promise<StatusResponse> {
if (online) { if (online) {
return await waha.setStatus(text); return await waha.setStatus(text);
} else { } else {
@ -149,12 +151,17 @@ export async function sendStatus(text) {
} }
} }
export async function markRead(chatId) { export async function markRead(chatId: string): Promise<Chat | undefined> {
if (online) { if (online) {
await waha.readChat(chatId); await waha.readChat(chatId);
} }
const chat = await loadChat(chatId); const chat = await loadChat(chatId);
if (chat) {
chat.unreadCount = 0; chat.unreadCount = 0;
upsertMessages([chat]); // Note: upsertMessages was called with [chat] in JS, but chat is a Chat object, not Message.
// Keeping JS behavior but chat is Chat type here.
await upsertChats([chat]);
}
return chat;
} }

124
web/src/types.ts Normal file
View file

@ -0,0 +1,124 @@
/** Represents a chat entry in the sidebar */
export interface Chat {
id: string;
name: string;
lastMessage: string;
timestamp: number | string | Date;
unreadCount: number;
}
/** Raw chat object returned from the WAHA API */
export interface WahaChat {
id: string | { _serialized?: string; user?: string };
chatId?: string;
name?: string;
unreadCount?: number;
lastMessage?: {
body?: string;
timestamp?: number | string;
};
lastMessageText?: string;
}
/** Message data sub-object (_data field) */
export interface MessageData {
notifyName?: string;
mimetype?: string;
[key: string]: unknown;
}
/** Media attachment info */
export interface MediaInfo {
url: string;
filename?: string;
}
/** A WhatsApp message */
export interface Message {
_data?: MessageData;
_serialized?: string | { _serialized?: string; user?: string };
id: string | { _serialized?: string; user?: string };
body?: string;
text?: string;
from?: string;
to?: string;
fromMe?: boolean;
sender?: string;
timestamp: number | string;
status?: string;
ack?: number;
hasMedia?: boolean;
media?: MediaInfo;
chatId?: string;
chat?: { id: string };
participant?: string;
}
/** Temporary message used for optimistic UI updates */
export interface TempMessage extends Message {
status: string;
}
/** File-sending temporary message */
export interface TempFileMessage extends TempMessage {
_data: MessageData;
hasMedia: true;
media: MediaInfo;
}
/** WAHA version response */
export interface VersionResponse {
version?: string;
}
/** WAHA user info (getMyInfo) */
export interface AppUser {
id: string;
pushName?: string;
name?: string;
}
/** WAHA contact info */
export interface ContactInfo {
number: string;
[key: string]: unknown;
}
/** WAHA user about response */
export interface UserAboutResponse {
about?: string;
}
/** Chat picture response */
export interface ChatPictureResponse {
url?: string;
}
/** Status update response */
export interface StatusResponse {
success?: boolean;
}
/** WebSocket event payload envelope */
export interface WebSocketEvent {
event: string;
payload: Message;
}
/** IndexedDB stored media record */
export interface StoredMedia {
reqId: string;
blob: Blob;
filename: string;
}
/** Downloaded media result */
export interface DownloadedMedia {
blob: Blob;
filename: string;
}
/** Message with _time field used during ordering compensation */
export interface MessageWithTime extends Message {
_time: number;
}

View file

@ -1,50 +1,51 @@
import { formatTime, normalizeId } from "./utils.js"; import { formatTime, normalizeId } from "./utils";
import { getChatPicture, getMessage, getMedia, getMoreChatMessages } from "./storage.js"; import { getChatPicture, getMessage, getMedia, getMoreChatMessages } from "./storage";
import { getCurrentChat } from "./app.js"; import { getCurrentChat } from "./app";
import type { Chat, Message } from "./types";
export const elements = { export const elements = {
chatList: document.getElementById('chat-list'), chatList: document.getElementById('chat-list') as HTMLUListElement,
chatsLoader: document.getElementById('chats-loader'), chatsLoader: document.getElementById('chats-loader') as HTMLDivElement,
chatSearch: document.getElementById('chat-search'), chatSearch: document.getElementById('chat-search') as HTMLInputElement,
backendStatusText: document.getElementById('backend-status-text'), backendStatusText: document.getElementById('backend-status-text') as HTMLSpanElement,
apiStatusIndicator: document.querySelector('.pulse-dot'), apiStatusIndicator: document.querySelector('.pulse-dot') as HTMLSpanElement,
noChatState: document.getElementById('no-chat-state'), noChatState: document.getElementById('no-chat-state') as HTMLDivElement,
activeChatContainer: document.getElementById('active-chat-container'), activeChatContainer: document.getElementById('active-chat-container') as HTMLDivElement,
activeChatName: document.getElementById('active-chat-name'), activeChatName: document.getElementById('active-chat-name') as HTMLHeadingElement,
activeChatAvatar: document.getElementById('active-chat-avatar'), activeChatAvatar: document.getElementById('active-chat-avatar') as HTMLDivElement,
messagesContainer: document.getElementById('messages-container'), messagesContainer: document.getElementById('messages-container') as HTMLDivElement,
messageForm: document.getElementById('message-form'), messageForm: document.getElementById('message-form') as HTMLFormElement,
messageInput: document.getElementById('message-input'), messageInput: document.getElementById('message-input') as HTMLInputElement,
backToSidebarBtn: document.querySelector('.chat-header'), backToSidebarBtn: document.querySelector('.chat-header') as HTMLElement,
sidebar: document.querySelector('.sidebar'), sidebar: document.querySelector('.sidebar') as HTMLElement,
appContainer: document.querySelector('.app-container'), appContainer: document.querySelector('.app-container') as HTMLElement,
settingsModal: document.getElementById('settings-page'), settingsModal: document.getElementById('settings-page') as HTMLElement,
settingsIconBtn: document.getElementById('settings-sidebar-btn'), settingsIconBtn: document.getElementById('settings-sidebar-btn') as HTMLButtonElement,
saveSettingsBtn: document.getElementById('save-settings'), saveSettingsBtn: document.getElementById('save-settings') as HTMLButtonElement,
inputWahaUrl: document.getElementById('settings-waha-url'), inputWahaUrl: document.getElementById('settings-waha-url') as HTMLInputElement,
inputSession: document.getElementById('settings-session'), inputSession: document.getElementById('settings-session') as HTMLInputElement,
inputApiKey: document.getElementById('settings-api-key'), inputApiKey: document.getElementById('settings-api-key') as HTMLInputElement,
inputBackgroundImage: document.getElementById('settings-background-image'), inputBackgroundImage: document.getElementById('settings-background-image') as HTMLInputElement,
inputBackgroundOpacity: document.getElementById('settings-background-opacity'), inputBackgroundOpacity: document.getElementById('settings-background-opacity') as HTMLInputElement,
loggedUserName: document.getElementById('pandora-username'), loggedUserName: document.getElementById('pandora-username') as HTMLHeadingElement,
chatBottomBar: document.getElementById('chat-bottom-bar'), chatBottomBar: document.getElementById('chat-bottom-bar') as HTMLElement,
chatBottomBarBtn: document.getElementById('chat-bottom-bar-btn'), chatBottomBarBtn: document.getElementById('chat-bottom-bar-btn') as HTMLButtonElement,
chatInputPanel: document.getElementById('chat-input-panel'), chatInputPanel: document.getElementById('chat-input-panel') as HTMLElement,
attachmentInput: document.getElementById('attachment-input'), attachmentInput: document.getElementById('attachment-input') as HTMLInputElement,
attachmentBtn: document.getElementById('attachment-btn'), attachmentBtn: document.getElementById('attachment-btn') as HTMLButtonElement,
markreadBtn: document.getElementById('markread-btn'), markreadBtn: document.getElementById('markread-btn') as HTMLButtonElement,
extraPages: document.querySelectorAll('.extra-page'), extraPages: document.querySelectorAll('.extra-page') as NodeListOf<HTMLElement>,
desktopSidebarButtons: document.querySelectorAll("#desktop-aside button"), desktopSidebarButtons: document.querySelectorAll("#desktop-aside button") as NodeListOf<HTMLButtonElement>,
contentUserName: document.querySelectorAll('[data-content="app-user"]'), contentUserName: document.querySelectorAll('[data-content="app-user"]') as NodeListOf<HTMLElement>,
contentUserNumber: document.querySelectorAll('[data-content="app-user-number"]'), contentUserNumber: document.querySelectorAll('[data-content="app-user-number"]') as NodeListOf<HTMLElement>,
resourceUserPic: document.querySelectorAll('[data-resource="app-user-image"]'), resourceUserPic: document.querySelectorAll('[data-resource="app-user-image"]') as NodeListOf<HTMLImageElement>,
valueUserStatus: document.querySelectorAll('[data-value="app-user-status"]'), valueUserStatus: document.querySelectorAll('[data-value="app-user-status"]') as NodeListOf<HTMLInputElement>,
inputUserStatus: document.getElementById('profile-page-status-input'), inputUserStatus: document.getElementById('profile-page-status-input') as HTMLInputElement,
selectable: document.querySelectorAll('.selectable'), selectable: document.querySelectorAll('.selectable') as NodeListOf<HTMLElement>,
}; };
export const ui = { export const ui = {
showExtraPage(pageId) { showExtraPage(pageId: string) {
elements.extraPages.forEach(page => { elements.extraPages.forEach(page => {
if (page.id != pageId) { if (page.id != pageId) {
page.style.display = "none"; page.style.display = "none";
@ -57,7 +58,7 @@ export const ui = {
/** /**
* Switch view state when a contact chat is opened or closed * Switch view state when a contact chat is opened or closed
*/ */
toggleChatState(hasActive) { toggleChatState(hasActive: boolean) {
if (hasActive) { if (hasActive) {
elements.noChatState.classList.add('hidden'); elements.noChatState.classList.add('hidden');
elements.activeChatContainer.classList.remove('hidden'); elements.activeChatContainer.classList.remove('hidden');
@ -77,7 +78,7 @@ export const ui = {
/** /**
* Update connection status badge in sidebar footer * Update connection status badge in sidebar footer
*/ */
updateConnectionStatus(isConnected, text) { updateConnectionStatus(isConnected: boolean, text: string) {
elements.backendStatusText.textContent = text; elements.backendStatusText.textContent = text;
if (isConnected) { if (isConnected) {
elements.apiStatusIndicator.style.backgroundColor = 'var(--online-color)'; elements.apiStatusIndicator.style.backgroundColor = 'var(--online-color)';
@ -88,9 +89,13 @@ export const ui = {
} }
}, },
async renderChatList(chats, activeChat, onChatSelect) { async renderChatList(chats: Chat[], activeChat: Chat | null, onChatSelect: (chat: Chat) => void) {
elements.chatList.innerHTML = ''; elements.chatList.innerHTML = '';
chats.sort((a, b) => b.timestamp - a.timestamp); chats.sort((a, b) => {
const timeA = new Date(a.timestamp).getTime();
const timeB = new Date(b.timestamp).getTime();
return timeB - timeA;
});
if (chats.length === 0) { if (chats.length === 0) {
elements.chatList.innerHTML = `<li class="loading-chats">No chats found</li>`; elements.chatList.innerHTML = `<li class="loading-chats">No chats found</li>`;
@ -134,7 +139,7 @@ export const ui = {
(async () => { (async () => {
try { try {
const picture = await getChatPicture(chat.id); const picture = await getChatPicture(chat.id);
const img = li.querySelector(`img[data-chat-avatar="${chat.id}"]`); const img = li.querySelector(`img[data-chat-avatar="${chat.id}"]`) as HTMLImageElement;
if (img) img.src = picture.url ? picture.url : ''; if (img) img.src = picture.url ? picture.url : '';
} catch (e) { } catch (e) {
} }
@ -142,20 +147,46 @@ export const ui = {
} }
}, },
async updateChatInChatList(msg) { async updateChatInChatList(msg: Message) {
const chat = document.querySelector(`.chat-item[data-id="${msg.fromMe ? msg.to : msg.from}"]`); const chatNode = document.querySelector(`.chat-item[data-id="${msg.fromMe ? msg.to : msg.from}"]`) as HTMLElement;
if (chat) { if (chatNode) {
const messageItem = chat.querySelector('.chat-item-msg'); const messageItem = chatNode.querySelector('.chat-item-msg') as HTMLElement;
const time = chat.querySelector('.chat-item-time') const time = chatNode.querySelector('.chat-item-time') as HTMLElement;
messageItem.innerText = msg.body || msg.text || 'Media message'; messageItem.innerText = msg.body || msg.text || 'Media message';
time.innerText = msg.timestamp ? formatTime(msg.timestamp) : Date.now(); time.innerText = msg.timestamp ? formatTime(msg.timestamp) : formatTime(Date.now());
const activeChatState = getCurrentChat(); const activeChatState = getCurrentChat();
if (!msg.fromMe && (!activeChatState || activeChatState.id !== (msg.fromMe ? msg.to : msg.from))) { if (!msg.fromMe && (!activeChatState || activeChatState.id !== (msg.fromMe ? msg.to : msg.from))) {
const unreadBadge = chat.querySelector('.unread-badge'); const unreadBadge = chatNode.querySelector('.unread-badge') as HTMLElement;
if (unreadBadge) unreadBadge.innerText = (Number(unreadBadge.innerHTML) || 0) + 1; if (unreadBadge) {
unreadBadge.innerText = (Number(unreadBadge.innerHTML) || 0) + 1 + "";
} else {
const preview = chatNode.querySelector('.chat-item-preview') as HTMLElement;
const badge = document.createElement('span');
badge.className = 'unread-badge';
badge.innerText = '1';
preview.appendChild(badge);
}
}
}
},
async updateChatInChatList2(chat: Chat) {
const chatNode = document.querySelector(`.chat-item[data-id="${chat.id}"]`) as HTMLElement;
if (chatNode) {
const messageItem = chatNode.querySelector('.chat-item-msg') as HTMLElement;
const time = chatNode.querySelector('.chat-item-time') as HTMLElement;
messageItem.innerText = chat.lastMessage || 'Media message';
time.innerText = chat.timestamp ? formatTime(chat.timestamp) : formatTime(Date.now());
const unreadBadge = chatNode.querySelector('.unread-badge') as HTMLElement;
const newCount = (Number(unreadBadge?.innerHTML) || 0);
if (unreadBadge && newCount != 0) {
unreadBadge.innerText = newCount + "";
} else {
if (unreadBadge) unreadBadge.remove();
} }
} }
}, },
@ -163,7 +194,7 @@ export const ui = {
/** /**
* Render chat message log inside chat view container * Render chat message log inside chat view container
*/ */
async renderMessages(messages, activeChatName, userID, chatId) { async renderMessages(messages: Message[], _activeChatName: string, userID: string, chatId: string) {
elements.messagesContainer.innerHTML = ''; elements.messagesContainer.innerHTML = '';
if (messages.length === 0) { if (messages.length === 0) {
@ -174,9 +205,9 @@ export const ui = {
const loadMore = document.createElement("button"); const loadMore = document.createElement("button");
loadMore.classList.add("load-more-btn"); loadMore.classList.add("load-more-btn");
loadMore.innerText = "Load more"; loadMore.innerText = "Load more";
loadMore.addEventListener('click', () => { loadMore.onclick = () => {
this.loadMoreMessages(chatId, userID); this.loadMoreMessages(chatId, userID);
}); };
elements.messagesContainer.appendChild(loadMore); elements.messagesContainer.appendChild(loadMore);
for (const msg of messages) { for (const msg of messages) {
@ -186,37 +217,34 @@ export const ui = {
this.scrollToBottom(); this.scrollToBottom();
}, },
async loadMoreMessages(chatId, userId) { async loadMoreMessages(chatId: string, userId: string) {
const oldest = document.querySelector('.message-group:first-of-type'); const oldest = document.querySelector('.message-group:first-of-type') as HTMLElement;
if (!oldest) return;
const oldestTimestamp = oldest.dataset.timestamp; const oldestTimestamp = oldest.dataset.timestamp;
const oldestId = oldest.id; const oldestId = oldest.id;
console.log(oldest)
console.log(oldestId)
console.log(oldestTimestamp)
const loadMoreButton = document.querySelector('.load-more-btn'); const loadMoreButton = document.querySelector('.load-more-btn') as HTMLButtonElement;
loadMoreButton.removeEventListener('click', this.loadMoreMessages);
const msgs = await getMoreChatMessages(chatId, oldestTimestamp, oldestId); const msgs = await getMoreChatMessages(chatId, oldestTimestamp, oldestId);
// JS version had msgs.shift(), probably to avoid duplication of the oldest message
msgs.shift(); msgs.shift();
msgs.forEach(async msg => { msgs.forEach(async msg => {
loadMoreButton.after(this.generateMessage(msg, userId, chatId)); loadMoreButton.after(this.generateMessage(msg, userId, chatId));
}); });
loadMoreButton.addEventListener('click', this.loadMoreMessages);
}, },
/** /**
* Append a single message (used for optimistic updates immediately upon sending) * Append a single message (used for optimistic updates immediately upon sending)
*/ */
appendSingleMessage(msg, userID, chatId, isLocal = false) { appendSingleMessage(msg: Message, userID: string, chatId: string, isLocal: boolean = false) {
elements.messagesContainer.appendChild(this.generateMessage(msg, userID, chatId, isLocal)) elements.messagesContainer.appendChild(this.generateMessage(msg, userID, chatId, isLocal))
}, },
generateTempMessageLink(msg) { generateTempMessageLink(msg: Message) {
const a = document.createElement('a'); const a = document.createElement('a');
a.target = "_blank"; a.target = "_blank";
if (msg.media) {
a.href = msg.media.url; a.href = msg.media.url;
if (msg._data?.mimetype?.startsWith('image/')) { if (msg._data?.mimetype?.startsWith('image/')) {
@ -226,28 +254,29 @@ export const ui = {
a.appendChild(img); a.appendChild(img);
} else { } else {
a.textContent = msg.media.filename || "Download file"; a.textContent = msg.media.filename || "Download file";
a.download = msg.media.filename; a.download = msg.media.filename || "file";
}
} }
return a; return a;
}, },
generateMessage(msg, userID, chatId, isLocal = false) { generateMessage(msg: Message, userID: string, chatId: string, isLocal: boolean = false) {
const isOutgoing = msg.fromMe || msg.sender === 'me'; const isOutgoing = msg.fromMe || msg.sender === 'me';
function getPrevMessageElem() { function getPrevMessageElem() {
return elements.messagesContainer.lastElementChild; return elements.messagesContainer.lastElementChild as HTMLElement | null;
} }
const prevMsgEl = getPrevMessageElem(); const prevMsgEl = getPrevMessageElem();
const groupDiv = document.createElement('div'); const groupDiv = document.createElement('div');
groupDiv.className = `message-group selectable ${isOutgoing ? 'outgoing' : 'incoming'}`; groupDiv.className = `message-group selectable ${isOutgoing ? 'outgoing' : 'incoming'}`;
groupDiv.id = normalizeId(msg._serialized ? msg : msg.id); groupDiv.id = normalizeId(msg._serialized ? (msg._serialized as any) : msg.id) || "msg-id";
groupDiv.dataset.timestamp = msg.timestamp; groupDiv.dataset.timestamp = msg.timestamp?.toString();
groupDiv.dataset.from = msg.participant || msg.from; groupDiv.dataset.from = msg.participant || (msg.from as string);
const senderName = isOutgoing ? userID : (msg._data.notifyName || msg.from); const senderName = isOutgoing ? userID : (msg._data?.notifyName || (msg.from as string));
const timeStr = formatTime(msg.timestamp || new Date()); const timeStr = formatTime(msg.timestamp || new Date());
let statusCheck = ''; let statusCheck = '';
@ -266,12 +295,12 @@ export const ui = {
const bubble = document.createElement('div'); const bubble = document.createElement('div');
bubble.className = 'message-bubble'; bubble.className = 'message-bubble';
let prevUid; let prevUid: string | undefined;
if (msg.participant) { if (msg.participant) {
prevUid = msg.participant; prevUid = msg.participant;
} else { } else {
prevUid = msg.from; prevUid = msg.from as string;
} }
if (!isOutgoing && (!prevMsgEl || prevUid !== prevMsgEl.dataset.from)) { if (!isOutgoing && (!prevMsgEl || prevUid !== prevMsgEl.dataset.from)) {
@ -289,7 +318,7 @@ export const ui = {
bubble.appendChild(contentEl); bubble.appendChild(contentEl);
if (msg.hasMedia) { if (msg.hasMedia) {
let a; let a: HTMLAnchorElement;
if (isLocal) { if (isLocal) {
a = this.generateTempMessageLink(msg); a = this.generateTempMessageLink(msg);
@ -298,11 +327,11 @@ export const ui = {
a.innerText = `[Request media]`; a.innerText = `[Request media]`;
a.target = "_blank"; a.target = "_blank";
const clickListener = async (e) => { const clickListener = async (e: MouseEvent) => {
a.removeEventListener('click', clickListener); a.removeEventListener('click', clickListener);
a.innerText = `[Downloading]`; a.innerText = `[Downloading]`;
const mediaMsg = msg.media ? msg : await getMessage(chatId, normalizeId(msg._serialized ? msg : msg.id), true); const mediaMsg = msg.media ? msg : await getMessage(chatId, normalizeId(msg._serialized ? (msg._serialized as any) : msg.id) || "", true);
if (!mediaMsg || !mediaMsg?.media.url) { if (!mediaMsg || !mediaMsg?.media?.url) {
a.addEventListener('click', clickListener); a.addEventListener('click', clickListener);
a.innerText = `[Error, click to try again]` a.innerText = `[Error, click to try again]`
return; return;
@ -310,20 +339,23 @@ export const ui = {
const url = new URL(mediaMsg.media.url); const url = new URL(mediaMsg.media.url);
const reqID = url.pathname.split('/').filter(Boolean).pop(); const reqID = url.pathname.split('/').filter(Boolean).pop();
const { blob, filename } = await getMedia(reqID); if (!reqID) return;
const media = await getMedia(reqID);
if (!media) return;
const objectUrl = URL.createObjectURL(blob); const objectUrl = URL.createObjectURL(media.blob);
e.target.href = objectUrl; (e.target as HTMLAnchorElement).href = objectUrl;
if (blob.type.startsWith('image/')) { if (media.blob.type.startsWith('image/')) {
a.textContent = ""; a.textContent = "";
const img = document.createElement('img'); const img = document.createElement('img');
img.classList.add('message-image-attachement'); img.classList.add('message-image-attachement');
img.src = objectUrl; img.src = objectUrl;
bubble.after(img); bubble.after(img);
bubble.querySelector('.message-content').remove(); const content = bubble.querySelector('.message-content');
if (content) content.remove();
} else { } else {
e.target.textContent = filename || `Download ${mediaMsg.media.filename}`; (e.target as HTMLAnchorElement).textContent = media.filename || `Download ${mediaMsg.media.filename}`;
} }
} }
@ -348,15 +380,21 @@ export const ui = {
if (prevMsgEl && prevMsgEl.classList.contains('outgoing')) { if (prevMsgEl && prevMsgEl.classList.contains('outgoing')) {
groupDiv.classList.add('same-sender'); groupDiv.classList.add('same-sender');
} else { } else {
groupDiv.appendChild(document.createElement('div')).className = 'message-indicator'; const indicator = document.createElement('div');
indicator.className = 'message-indicator';
groupDiv.appendChild(indicator);
} }
} else if (msg.participant) { } else if (msg.participant) {
if (!prevMsgEl || prevUid !== prevMsgEl.dataset.from) { if (!prevMsgEl || prevUid !== prevMsgEl.dataset.from) {
groupDiv.appendChild(document.createElement('div')).className = 'message-indicator'; const indicator = document.createElement('div');
indicator.className = 'message-indicator';
groupDiv.appendChild(indicator);
} else groupDiv.classList.add('same-sender'); } else groupDiv.classList.add('same-sender');
} else { } else {
if (!prevMsgEl || prevUid !== prevMsgEl.dataset.from) { if (!prevMsgEl || prevUid !== prevMsgEl.dataset.from) {
groupDiv.appendChild(document.createElement('div')).className = 'message-indicator'; const indicator = document.createElement('div');
indicator.className = 'message-indicator';
groupDiv.appendChild(indicator);
} else groupDiv.classList.add('same-sender'); } else groupDiv.classList.add('same-sender');
} }
@ -364,14 +402,14 @@ export const ui = {
return groupDiv; return groupDiv;
}, },
updateMessage(originalMsgId, generatedMsg) { updateMessage(originalMsgId: string, generatedMsg: HTMLElement) {
const originalMsg = document.querySelector(`#${originalMsgId}`); const originalMsg = document.querySelector(`#${originalMsgId}`);
if (originalMsg) { if (originalMsg) {
originalMsg.replaceWith(generatedMsg) originalMsg.replaceWith(generatedMsg)
} }
}, },
updateMessageTick(id, status) { updateMessageTick(id: string, status: string) {
let statusCheck; let statusCheck;
if (status === 'read') { if (status === 'read') {
statusCheck = '<span class="mif-done_all" style="color: var(--online-color); width:14px; height:14px;"></span>'; statusCheck = '<span class="mif-done_all" style="color: var(--online-color); width:14px; height:14px;"></span>';
@ -383,14 +421,18 @@ export const ui = {
statusCheck = '<span class="mif-done" style="width:14px; height:14px;"></span>'; statusCheck = '<span class="mif-done" style="width:14px; height:14px;"></span>';
} }
document.getElementById(id).querySelector('.message-meta').outerHTML = statusCheck; const msgNode = document.getElementById(id);
if (msgNode) {
const meta = msgNode.querySelector('.message-meta');
if (meta) meta.outerHTML = statusCheck;
}
}, },
toggleChatBottomBar() { toggleChatBottomBar() {
elements.chatBottomBar.classList.toggle("collapsed"); elements.chatBottomBar.classList.toggle("collapsed");
}, },
removeChatMessage(msgId) { removeChatMessage(msgId: string) {
const message = document.getElementById(msgId); const message = document.getElementById(msgId);
if (message) message.remove(); if (message) message.remove();
} }

View file

@ -1,13 +1,13 @@
// Helper utilities and algorithms import type { Message, MessageWithTime } from "./types";
/** /**
* Format timestamps (supports Unix epoch seconds/ms, strings and ISO dates) * Format timestamps (supports Unix epoch seconds/ms, strings and ISO dates)
* @param {string|number|Date} dateVal * @param {string|number|Date} dateVal
* @returns {string} Formatted HH:MM AM/PM string * @returns {string} Formatted HH:MM AM/PM string
*/ */
export function formatTime(dateVal) { export function formatTime(dateVal: string | number | Date): string {
if (!dateVal) return ''; if (!dateVal) return '';
let date; let date: Date;
if (typeof dateVal === 'number') { if (typeof dateVal === 'number') {
date = new Date(dateVal < 10000000000 ? dateVal * 1000 : dateVal); date = new Date(dateVal < 10000000000 ? dateVal * 1000 : dateVal);
} else if (typeof dateVal === 'string' && /^\d+$/.test(dateVal)) { } else if (typeof dateVal === 'string' && /^\d+$/.test(dateVal)) {
@ -18,12 +18,12 @@ export function formatTime(dateVal) {
} }
let hours = date.getHours(); let hours = date.getHours();
let minutes = date.getMinutes(); const minutes = date.getMinutes();
const ampm = hours >= 12 ? 'PM' : 'AM'; const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12; hours = hours % 12;
hours = hours ? hours : 12; hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes; const minutesStr = minutes < 10 ? '0' + minutes : String(minutes);
return `${hours}:${minutes} ${ampm}`; return `${hours}:${minutesStr} ${ampm}`;
} }
/** /**
@ -32,24 +32,22 @@ export function formatTime(dateVal) {
* @param {Array} messages List of raw messages from WAHA * @param {Array} messages List of raw messages from WAHA
* @returns {Array} Compensated chronological message array * @returns {Array} Compensated chronological message array
*/ */
export function compensateMessageOrdering(messages) { export function compensateMessageOrdering(messages: Message[]): Message[] {
if (!Array.isArray(messages)) return []; if (!Array.isArray(messages)) return [];
// Convert timestamps to numeric milliseconds for stable comparison // convert to ms
const msgs = messages.map(m => { const msgs: MessageWithTime[] = messages.map(m => {
let t = m.timestamp; let t: number;
if (typeof t === 'number') { if (typeof m.timestamp === 'number') {
if (t < 10000000000) t = t * 1000; t = m.timestamp < 10000000000 ? m.timestamp * 1000 : m.timestamp;
} else { } else {
t = new Date(t).getTime(); t = new Date(m.timestamp).getTime();
} }
return { ...m, _time: t }; return { ...m, _time: t };
}); });
// Initial chronological sort
msgs.sort((a, b) => a._time - b._time); msgs.sort((a, b) => a._time - b._time);
// Apply drift bubble adjustments
let changed = true; let changed = true;
while (changed) { while (changed) {
changed = false; changed = false;
@ -58,12 +56,12 @@ export function compensateMessageOrdering(messages) {
const next = msgs[i + 1]; const next = msgs[i + 1];
const timeDiff = next._time - current._time; const timeDiff = next._time - current._time;
// Swap if an outgoing message is sorted before an incoming message within a 30-sec window // swap if outgoing message is sorted before incoming message within 30-sec window
if (current.fromMe && !next.fromMe && timeDiff >= 0 && timeDiff <= 30000) { if (current.fromMe && !next.fromMe && timeDiff >= 0 && timeDiff <= 30000) {
msgs[i] = next; msgs[i] = next;
msgs[i + 1] = current; msgs[i + 1] = current;
// Advance the outgoing message's timestamp to be exactly 1 second after the incoming one // advance the outgoing message timestamp to exactly 1 sec after the incoming
current._time = next._time + 1000; current._time = next._time + 1000;
if (typeof current.timestamp === 'number') { if (typeof current.timestamp === 'number') {
current.timestamp = Math.floor(current._time / 1000); current.timestamp = Math.floor(current._time / 1000);
@ -76,16 +74,16 @@ export function compensateMessageOrdering(messages) {
} }
} }
// Clean up temporary property // clean temp property
return msgs.map(({ _time, ...m }) => m); return msgs.map(({ _time, ...m }) => m);
} }
export function getBase64(file) { export function getBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = () => { reader.onload = () => {
resolve(reader.result.split(",")[1]); resolve((reader.result as string).split(",")[1]);
}; };
reader.onerror = (e) => { reader.onerror = (e) => {
@ -106,7 +104,7 @@ export function getBase64(file) {
* @param {string|object} raw * @param {string|object} raw
* @returns {string|null} * @returns {string|null}
*/ */
export function normalizeId(raw) { export function normalizeId(raw: string | { _serialized?: string; user?: string } | null | undefined): string | null {
if (!raw) return null; if (!raw) return null;
if (typeof raw === 'object') { if (typeof raw === 'object') {
return raw._serialized || raw.user || JSON.stringify(raw); return raw._serialized || raw.user || JSON.stringify(raw);
@ -114,8 +112,8 @@ export function normalizeId(raw) {
return raw; return raw;
} }
export function debounce(func, delay) { export function debounce(func: () => void, delay: number): () => void {
let timeoutId; let timeoutId: ReturnType<typeof setTimeout>;
return function() { return function() {
clearTimeout(timeoutId); clearTimeout(timeoutId);
timeoutId = setTimeout(func, delay); timeoutId = setTimeout(func, delay);

View file

@ -1,20 +1,19 @@
import { config } from "./config.js"; import { config } from "./config";
import { showNotification } from "./notification.js"; import { showNotification } from "./notification";
import { getBase64 } from "./utils.js"; import { getBase64 } from "./utils";
import type { Message, VersionResponse, AppUser, ContactInfo, UserAboutResponse, ChatPictureResponse, StatusResponse } from "./types";
async function request(path, options = {}) { async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${config.wahaUrl}${path}`; const url = `${config.wahaUrl}${path}`;
const headers = { const headers: Record<string, string> = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'accept': '*/*', 'accept': '*/*',
...options.headers ...(options.headers as Record<string, string>)
}; };
if (config.apiKey) { if (config.apiKey) {
headers['X-Api-Key'] = config.apiKey; headers['X-Api-Key'] = config.apiKey;
} }
// console.log(`[WAHA] ${options.method || 'GET'} ${url}`, options.body ? JSON.parse(options.body) : '');
const response = await fetch(url, { ...options, headers }); const response = await fetch(url, { ...options, headers });
if (!response.ok) { if (!response.ok) {
let errorDetail = ''; let errorDetail = '';
@ -26,25 +25,23 @@ async function request(path, options = {}) {
errorDetail = await response.text().catch(() => ''); errorDetail = await response.text().catch(() => '');
} }
showNotification("API Error", `WAHA API returned ${response.status}: ${response.statusText}${errorDetail}`, 2000); showNotification("API Error", `WAHA API returned ${response.status}: ${response.statusText}${errorDetail}`, 4000);
throw new Error(`WAHA API returned ${response.status}: ${response.statusText}${errorDetail}`); throw new Error(`WAHA API returned ${response.status}: ${response.statusText}${errorDetail}`);
} }
return response.json(); return response.json();
} }
async function downloadFile(path, options = {}) { async function downloadFile(path: string, options: RequestInit = {}): Promise<{ blob: Blob, filename: string }> {
const url = `${config.wahaUrl}${path}`; const url = `${config.wahaUrl}${path}`;
const headers = { const headers: Record<string, string> = {
'Content-Type': options.headers?.['Content-Type'] ?? 'application/json', 'Content-Type': (options.headers as Record<string, string> | undefined)?.['Content-Type'] ?? 'application/json',
'accept': '*/*', 'accept': '*/*',
...options.headers ...(options.headers as Record<string, string>)
}; };
if (config.apiKey) headers['X-Api-Key'] = config.apiKey; if (config.apiKey) headers['X-Api-Key'] = config.apiKey;
// console.log(`[WAHA] ${options.method || 'GET'} ${url}`);
const response = await fetch(url, { ...options, headers }); const response = await fetch(url, { ...options, headers });
if (!response.ok) { if (!response.ok) {
@ -69,14 +66,13 @@ async function downloadFile(path, options = {}) {
return { blob, filename }; return { blob, filename };
} }
export const waha = { export const waha = {
async getVersion() { async getVersion(): Promise<VersionResponse> {
return await request('/api/version'); return await request<VersionResponse>('/api/version');
}, },
async getChats() { async getChats(): Promise<any[]> {
const data = await request(`/api/${config.session}/chats`); const data = await request<any[]>(`/api/${config.session}/chats`);
return data.map(chat => { return data.map(chat => {
let chatId = chat.id; let chatId = chat.id;
if (chatId && typeof chatId === "object") { if (chatId && typeof chatId === "object") {
@ -92,59 +88,58 @@ export const waha = {
}); });
}, },
async getChatMessages(chatId, beforeTimestamp) { async getChatMessages(chatId: string, beforeTimestamp?: any): Promise<Message[]> {
console.log(`/api/${config.session}/chats/${chatId}/messages?downloadMedia=false&limit=40&sortBy=timestamp${beforeTimestamp ? `&filter.timestamp.gte=${beforeTimestamp}` : "" }`); return request<Message[]>(`/api/${config.session}/chats/${chatId}/messages?downloadMedia=false&limit=40${beforeTimestamp ? `&filter.timestamp.lte=${beforeTimestamp}` : "" }`);
return request(`/api/${config.session}/chats/${chatId}/messages?downloadMedia=false&limit=40${beforeTimestamp ? `&filter.timestamp.lte=${beforeTimestamp}` : "" }`);
}, },
async getSingleChatMessage(chatId, messageId, downladMedia) { async getSingleChatMessage(chatId: string, messageId: string, downloadMedia: boolean): Promise<Message> {
return request(`/api/${config.session}/chats/${chatId}/messages/${messageId}?downloadMedia=${downladMedia}`); return request<Message>(`/api/${config.session}/chats/${chatId}/messages/${messageId}?downloadMedia=${downloadMedia}`);
}, },
async getChatPicture(chatId) { async getChatPicture(chatId: string): Promise<ChatPictureResponse> {
return request(`/api/${config.session}/chats/${chatId}/picture`); return request<ChatPictureResponse>(`/api/${config.session}/chats/${chatId}/picture`);
}, },
async getUser(chatId) { async getUser(chatId: string): Promise<ContactInfo> {
return request(`/api/${config.session}/contacts/${chatId}`); return request<ContactInfo>(`/api/${config.session}/contacts/${chatId}`);
}, },
async getUserAbout(chatId) { async getUserAbout(chatId: string): Promise<UserAboutResponse> {
return request(`/api/contacts/about?contactId=${chatId}&session=${config.session}`); return request<UserAboutResponse>(`/api/contacts/about?contactId=${chatId}&session=${config.session}`);
}, },
async readChat(chatId) { async readChat(chatId: string): Promise<any> {
return request('/api/sendSeen', { return request('/api/sendSeen', {
method: 'POST', method: 'POST',
body: JSON.stringify({ chatId, session: config.session }) body: JSON.stringify({ chatId, session: config.session })
}); });
}, },
async downloadMedia(file) { async downloadMedia(file: string): Promise<{ blob: Blob, filename: string }> {
const { blob, filename } = await downloadFile(`/api/files/${config.session}/${file}`); const { blob, filename } = await downloadFile(`/api/files/${config.session}/${file}`);
return { blob, filename }; return { blob, filename };
}, },
async getMyInfo() { async getMyInfo(): Promise<AppUser> {
return request(`/api/sessions/${config.session}/me`); return request<AppUser>(`/api/sessions/${config.session}/me`);
}, },
async startTyping(chatId) { async startTyping(chatId: string): Promise<any> {
return request('/api/startTyping', { return request('/api/startTyping', {
method: 'POST', method: 'POST',
body: JSON.stringify({ chatId, session: config.session }) body: JSON.stringify({ chatId, session: config.session })
}); });
}, },
async stopTyping(chatId) { async stopTyping(chatId: string): Promise<any> {
return request('/api/stopTyping', { return request('/api/stopTyping', {
method: 'POST', method: 'POST',
body: JSON.stringify({ chatId, session: config.session }) body: JSON.stringify({ chatId, session: config.session })
}); });
}, },
async sendTextMessage(chatId, text) { async sendTextMessage(chatId: string, text: string): Promise<Message> {
return request('/api/sendText', { return request<Message>('/api/sendText', {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
chatId, chatId,
@ -154,8 +149,8 @@ export const waha = {
}); });
}, },
async setStatus(text) { async setStatus(text: string): Promise<StatusResponse> {
return request(`/api/${config.session}/profile/status`, { return request<StatusResponse>(`/api/${config.session}/profile/status`, {
method: 'PUT', method: 'PUT',
body: JSON.stringify({ body: JSON.stringify({
status: text status: text
@ -163,9 +158,9 @@ export const waha = {
}); });
}, },
async sendFileMessage(chatId, file) { async sendFileMessage(chatId: string, file: File): Promise<Message> {
const fileBase64 = await getBase64(file); const fileBase64 = await getBase64(file);
const body = { const body: RequestInit = {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
chatId, chatId,
@ -183,7 +178,7 @@ export const waha = {
if (file.type.startsWith('image/')) endpoint = '/api/sendImage'; if (file.type.startsWith('image/')) endpoint = '/api/sendImage';
if (file.type.startsWith('video/')) endpoint = '/api/sendVideo'; if (file.type.startsWith('video/')) endpoint = '/api/sendVideo';
const result = await request(endpoint, body); const result = await request<Message>(endpoint, body);
return result; return result;
} }
}; };

View file

@ -1,13 +1,14 @@
import { config } from "./config.js"; import { config } from "./config";
import { isOnline, updateOnlineStatus } from "./storage.js"; import { isOnline, updateOnlineStatus } from "./storage";
import type { WebSocketEvent } from "./types";
let socket = null; let socket: WebSocket | null = null;
let reconnectTimer = null; let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let currentOnMessageCallback = null; let currentOnMessageCallback: ((data: WebSocketEvent) => void) | null = null;
export const websocket = { export const websocket = {
connect(onMessageCallback) { connect(onMessageCallback: (data: WebSocketEvent) => void) {
if (!isOnline) return; if (!isOnline()) return;
currentOnMessageCallback = onMessageCallback; currentOnMessageCallback = onMessageCallback;
this.disconnect(false); this.disconnect(false);
@ -48,7 +49,7 @@ export const websocket = {
socket.onmessage = (event) => { socket.onmessage = (event) => {
try { try {
const data = JSON.parse(event.data); const data = JSON.parse(event.data) as WebSocketEvent;
if (currentOnMessageCallback) { if (currentOnMessageCallback) {
currentOnMessageCallback(data); currentOnMessageCallback(data);
} }
@ -66,8 +67,11 @@ export const websocket = {
socket = null; socket = null;
reconnectTimer = setTimeout(() => { reconnectTimer = setTimeout(() => {
updateOnlineStatus(); updateOnlineStatus().then(() => {
if (currentOnMessageCallback) {
this.connect(currentOnMessageCallback); this.connect(currentOnMessageCallback);
}
});
}, 5000); }, 5000);
}; };
} catch (e) { } catch (e) {

View file

@ -233,11 +233,11 @@ input:focus {
.icon-btn:hover { .icon-btn:hover {
background: rgba(255, 255, 255, 0.08); background: rgba(255, 255, 255, 0.08);
color: var(--bg-main); color: var(--text-primary);
border-color: var(--border-hover); border-color: var(--border-hover);
} }
.icon-btn:hover::before { #chat-bottom-bar .icon-btn:hover::before {
color: var(--bg-main); color: var(--bg-main);
} }