add new chat logic and message service

This commit is contained in:
JCEEE
2026-08-05 11:20:27 +01:00
parent 3378e1dce7
commit fed2f32258
11 changed files with 1013 additions and 14 deletions
+353
View File
@@ -0,0 +1,353 @@
<script lang="ts">
import { onMount } from 'svelte';
import { chatStore } from '$lib/stores/chat.svelte';
import { chatIcon, sendIcon } from './icons';
import { formatWeekday, formatHumanDate } from '$lib/format';
let { role = 'child' }: { role?: string } = $props();
let draft = $state('');
let sending = $state(false);
let error = $state('');
let container: HTMLDivElement | undefined = $state();
let idleTimer: ReturnType<typeof setTimeout> | undefined;
const isOwn = (msg: any) => msg.authorId === chatStore.actorId;
function scrollToBottom(instant = false) {
if (!container) return;
container.scrollTo({
top: container.scrollHeight,
behavior: instant ? 'auto' : 'smooth'
});
}
$effect(() => {
const n = chatStore.messages.length;
if (n > 0) {
const last = chatStore.messages[n - 1];
// Only auto-scroll when the newest message is ours, or on open.
if (isOwn(last) || chatStore.open) scrollToBottom(true);
}
});
async function send() {
const text = draft.trim();
if (!text || sending) return;
sending = true;
error = '';
draft = '';
clearIdle();
chatStore.setTyping(false).catch(() => {});
try {
await chatStore.send(text);
scrollToBottom(true);
} catch {
error = 'Could not send. Try again.';
} finally {
sending = false;
requestAnimationFrame(() => scrollToBottom(true));
}
}
function onInput() {
chatStore.setTyping(true).catch(() => {});
clearIdle();
idleTimer = setTimeout(() => {
chatStore.setTyping(false).catch(() => {});
}, 2500);
}
function clearIdle() {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = undefined;
}
function onClose() {
clearIdle();
chatStore.setTyping(false).catch(() => {});
chatStore.closeChat();
}
function insertMention(name: string) {
draft = draft.trimEnd();
draft = (draft ? draft + ' ' : '') + '@' + name + ' ';
}
// Render content, wrapping @mentions in a styled token.
function renderContent(text: string) {
const segs: { text: string; mention: boolean }[] = [];
const re = /(@[A-Za-z0-9_.-]+)/g;
let last = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
if (m.index > last) segs.push({ text: text.slice(last, m.index), mention: false });
segs.push({ text: m[1], mention: true });
last = m.index + m[0].length;
}
if (last < text.length) segs.push({ text: text.slice(last), mention: false });
return segs;
}
onMount(() => {
requestAnimationFrame(() => scrollToBottom(true));
});
</script>
<div class="chat-panel" class:open={chatStore.open}>
<div class="chat-head">
<span class="chat-title">Family Chat</span>
<button class="chat-close" onclick={onClose} aria-label="Close chat"></button>
</div>
<div class="chat-messages" bind:this={container}>
{#if chatStore.messages.length === 0}
<p class="chat-empty">No messages yet. Say hi! 👋</p>
{:else}
{#each chatStore.messages as msg (msg.id)}
<div class="msg-row" class:own={isOwn(msg)}>
{#if !isOwn(msg)}
<span class="avatar" style="background:{msg.authorColor || '#6366f1'}">
{msg.authorName?.charAt(0).toUpperCase()}
</span>
{/if}
<div class="bubble-wrap">
{#if !isOwn(msg)}
<span class="msg-author">{msg.authorName}</span>
{/if}
<div class="bubble">
{#each renderContent(msg.content) as seg (msg.id + ':' + seg.text)}
{#if seg.mention}
<button class="mention" onclick={() => insertMention(seg.text.slice(1))}
>{seg.text}</button
>
{:else}
{seg.text}
{/if}
{/each}
<span class="msg-time">{formatWeekday(msg.createdAt)}</span>
</div>
</div>
</div>
{/each}
{/if}
</div>
<div class="chat-typing">
{#if chatStore.typingNames.length > 0}
<span class="typing-text">
{chatStore.typingNames.join(', ')}
{chatStore.typingNames.length === 1 ? 'is' : 'are'} typing…
</span>
{:else}
<span class="typing-text"></span>
{/if}
</div>
<div class="chat-composer">
{#if error}<div class="chat-error">{error}</div>{/if}
<input
type="text"
class="chat-input"
placeholder="Message the family…"
bind:value={draft}
oninput={onInput}
onkeydown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
send();
}
}}
disabled={sending}
/>
<button class="chat-send" onclick={send} disabled={sending || !draft.trim()} aria-label="Send">
{@html sendIcon}
</button>
</div>
</div>
<style>
.chat-panel {
position: fixed;
top: 0;
right: 0;
height: 100dvh;
width: 500px;
background: #fff;
border-left: 1px solid #e5e7eb;
display: flex;
flex-direction: column;
z-index: 110;
transform: translateX(100%);
transition: transform 0.25s ease;
box-shadow: -8px 0 24px rgba(0, 0, 0, 0.08);
}
.chat-panel.open {
transform: translateX(0);
}
/* Mobile: full-screen fixed layer. */
@media (max-width: 767.98px) {
.chat-panel {
width: 100vw;
}
}
.chat-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.85rem 1.25rem;
border-bottom: 1px solid #e5e7eb;
background: #4338ca;
color: #fff;
}
.chat-title {
font-weight: 700;
font-size: 1rem;
}
.chat-close {
background: none;
border: none;
color: #c7d2fe;
font-size: 1.1rem;
cursor: pointer;
padding: 0.25rem 0.5rem;
}
.chat-close:hover {
color: #fff;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 1rem 1.25rem;
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.chat-empty {
color: #9ca3af;
text-align: center;
margin-top: 3rem;
}
.msg-row {
display: flex;
align-items: flex-end;
gap: 0.5rem;
}
.msg-row.own {
justify-content: flex-end;
}
.avatar {
width: 28px;
height: 28px;
border-radius: 50%;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8rem;
font-weight: 700;
flex-shrink: 0;
}
.bubble-wrap {
max-width: 72%;
display: flex;
flex-direction: column;
}
.msg-row.own .bubble-wrap {
align-items: flex-end;
}
.msg-author {
font-size: 0.72rem;
color: #6b7280;
margin: 0 0 0.15rem 0.35rem;
font-weight: 600;
}
.bubble {
background: #f3f4f6;
border-radius: 14px;
border-bottom-left-radius: 4px;
padding: 0.5rem 0.75rem;
font-size: 0.9rem;
color: #111827;
line-height: 1.4;
word-break: break-word;
position: relative;
}
.msg-row.own .bubble {
background: #6366f1;
color: #fff;
border-bottom-left-radius: 14px;
border-bottom-right-radius: 4px;
}
.msg-time {
display: block;
font-size: 0.62rem;
color: #9ca3af;
margin-top: 0.25rem;
text-align: right;
text-transform: capitalize;
}
.msg-row.own .msg-time {
color: rgba(255, 255, 255, 0.7);
}
.mention {
background: #ede9fe;
color: #6d28d9;
border: none;
border-radius: 6px;
padding: 0 0.25rem;
font-weight: 600;
font-size: 0.85rem;
cursor: pointer;
}
.chat-typing {
min-height: 1.5rem;
padding: 0 1.25rem;
}
.typing-text {
font-size: 0.75rem;
color: #6b7280;
font-style: italic;
}
.chat-composer {
display: flex;
gap: 0.5rem;
padding: 0.75rem 1.25rem 1rem;
border-top: 1px solid #e5e7eb;
align-items: center;
}
.chat-error {
position: absolute;
bottom: 4.5rem;
color: #dc2626;
font-size: 0.75rem;
}
.chat-input {
flex: 1;
padding: 0.6rem 0.9rem;
border: 1px solid #d1d5db;
border-radius: 999px;
font-size: 0.9rem;
outline: none;
}
.chat-input:focus {
border-color: #6366f1;
}
.chat-send {
width: 40px;
height: 40px;
border-radius: 50%;
border: none;
background: #6366f1;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
flex-shrink: 0;
}
.chat-send:disabled {
opacity: 0.5;
cursor: default;
}
</style>
+2
View File
@@ -9,3 +9,5 @@ export const prefsIcon = '<svg width="18" height="18" viewBox="0 0 24 24" fill="
export const chevronLeft = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg>'
export const chevronRight = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>'
export const bellIcon = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg>'
export const chatIcon = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>'
export const sendIcon = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>'
+1
View File
@@ -6,3 +6,4 @@ export { default as Card } from './Card.svelte';
export { default as CardGrid } from './CardGrid.svelte';
export { default as Button } from './Button.svelte';
export { default as Accordion } from './Accordion.svelte';
export { default as Chat } from './Chat.svelte';
+257
View File
@@ -0,0 +1,257 @@
import { pb } from '$lib/pocketbase';
import type { ChatMessage, TypingRow } from '$lib/types';
interface ChatInit {
famId: string;
actorId: string;
actorType: 'admin' | 'member';
actorName: string;
actorColor: string;
deviceToken?: string;
memberId?: string;
}
class ChatStore {
famId = $state('');
messages = $state<ChatMessage[]>([]);
typing = $state<Record<string, TypingRow>>({});
unread = $state(0);
open = $state(false);
initialized = $state(false);
actorId = $state('');
actorType = $state<'admin' | 'member'>('member');
actorName = $state('');
actorColor = $state('');
deviceToken = $state('');
memberId = $state('');
private unsubs: (() => void)[] = [];
private destroyed = false;
private initPromise: Promise<void> | null = null;
private lastSeenAt = 0;
private typingTimers = new Map<string, ReturnType<typeof setTimeout>>();
typingNames = $derived.by(() => {
const names: string[] = [];
for (const row of Object.values(this.typing)) {
if (row.actorId !== this.actorId) names.push(row.authorName);
}
return names;
});
async init(opts: ChatInit) {
this.famId = opts.famId;
this.actorId = opts.actorId;
this.actorType = opts.actorType;
this.actorName = opts.actorName;
this.actorColor = opts.actorColor;
this.deviceToken = opts.deviceToken || '';
this.memberId = opts.memberId || '';
if (this.initialized && this.famId === opts.famId) return;
if (this.initPromise) {
await this.initPromise;
if (this.initialized && this.famId === opts.famId) return;
}
this.cleanup();
this.destroyed = false;
this.lastSeenAt = Date.now();
this.initPromise = (async () => {
try {
// Last week + this week of history (custom createdAt field — the
// auto `created` field can't be filtered in this PB version).
const since = new Date(Date.now() - 14 * 86400000).toISOString();
const msgs = (await pb.collection('messages').getFullList({
filter: `famId = '${opts.famId}' && createdAt >= '${since}'`,
sort: 'createdAt'
})) as ChatMessage[];
this.messages = msgs;
this.initialized = true;
} catch (e) {
console.error('ChatStore.init failed:', e);
this.initPromise = null;
throw e;
}
await this.subscribe();
this.initPromise = null;
})();
return this.initPromise!;
}
private async subscribe() {
const msgSub = pb
.collection('messages')
.subscribe('*', (data: any) => {
if (this.destroyed) return;
this.onMessage(data.action, data.record);
})
.then((unsub) => this.unsubs.push(unsub))
.catch((err: Error) => console.error('[chatStore] messages subscribe failed:', err));
const typingSub = pb
.collection('chat_typing')
.subscribe('*', (data: any) => {
if (this.destroyed) return;
this.onTyping(data.action, data.record);
})
.then((unsub) => this.unsubs.push(unsub))
.catch((err: Error) => console.error('[chatStore] typing subscribe failed:', err));
await Promise.allSettled([msgSub, typingSub]);
}
private onMessage(action: string, record: ChatMessage) {
if (record.famId !== this.famId) return;
if (action === 'delete') {
this.messages = this.messages.filter((m) => m.id !== record.id);
return;
}
if (action === 'update') {
this.messages = this.messages.map((m) => (m.id === record.id ? { ...m, ...record } : m));
return;
}
// create
if (!this.messages.some((m) => m.id === record.id)) {
this.messages = [...this.messages, record].sort((a, b) =>
a.createdAt.localeCompare(b.createdAt)
);
}
// Stop showing their typing indicator once the message lands.
this.clearTyping(record.authorId);
if (record.authorId !== this.actorId && !this.open) {
this.unread++;
}
}
private onTyping(action: string, record: TypingRow) {
if (record.famId !== this.famId) return;
if (action === 'delete') {
this.removeTyping(record.actorId);
return;
}
if (!record.typing) {
this.removeTyping(record.actorId);
return;
}
this.typing = { ...this.typing, [record.actorId]: record };
const prev = this.typingTimers.get(record.actorId);
if (prev) clearTimeout(prev);
this.typingTimers.set(
record.actorId,
setTimeout(() => this.removeTyping(record.actorId), 5000)
);
}
private clearTyping(actorId: string) {
if (this.typing[actorId]) this.removeTyping(actorId);
}
private removeTyping(actorId: string) {
if (!this.typing[actorId]) return;
const next = { ...this.typing };
delete next[actorId];
this.typing = next;
const t = this.typingTimers.get(actorId);
if (t) clearTimeout(t);
this.typingTimers.delete(actorId);
}
// ── Writes via proxy ──
private async chatFetch(method: string, path: string, body?: unknown) {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (this.actorType === 'member' && this.deviceToken) {
headers['x-device-token'] = this.deviceToken;
headers['x-device-famid'] = this.famId;
}
const res = await fetch(path, {
method,
headers,
body: body ? JSON.stringify(body) : undefined
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || `${method} ${path} failed`);
return data;
}
async send(content: string) {
const text = content.trim();
if (!text || !this.famId) return;
const temp: ChatMessage = {
id: 'temp-' + Date.now(),
famId: this.famId,
authorType: this.actorType,
authorId: this.actorId,
authorName: this.actorName,
authorColor: this.actorColor,
content: text,
createdAt: new Date().toISOString()
};
this.messages = [...this.messages, temp];
this.lastSeenAt = Date.now();
// Signal we stopped typing (message sent).
this.setTyping(false).catch(() => {});
try {
const saved = await this.chatFetch('POST', `/api/chat/${this.famId}/messages`, {
content: text
});
// SSE may have already delivered the real record via onMessage, so
// drop both the temp and any pre-existing copy of the saved id to
// avoid duplicate keys in the keyed each block.
this.messages = this.messages
.filter((m) => m.id !== temp.id && m.id !== saved.id)
.concat([{ ...saved, authorName: temp.authorName, authorColor: temp.authorColor }])
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
} catch (e) {
this.messages = this.messages.filter((m) => m.id !== temp.id);
console.error('Chat send failed:', e);
throw e;
}
}
private typingThrottle = 0;
async setTyping(typing: boolean) {
if (!this.famId) return;
const now = Date.now();
if (typing && now - this.typingThrottle < 1500) return;
this.typingThrottle = now;
try {
await this.chatFetch('POST', `/api/chat/${this.famId}/typing`, { typing });
} catch (e) {
console.error('Chat typing failed:', e);
}
}
toggle() {
this.open = !this.open;
if (this.open) {
this.unread = 0;
this.lastSeenAt = Date.now();
}
}
openChat() {
this.open = true;
this.unread = 0;
this.lastSeenAt = Date.now();
}
closeChat() {
this.open = false;
}
cleanup() {
this.destroyed = true;
for (const unsub of this.unsubs) unsub();
this.unsubs = [];
for (const t of this.typingTimers.values()) clearTimeout(t);
this.typingTimers.clear();
this.initialized = false;
}
}
export const chatStore = new ChatStore();
+22 -1
View File
@@ -74,7 +74,7 @@ export interface ChoreTemplate {
updated: string;
}
export interface AssignedChore {
export interface AssignedChore {
id: string;
famId: string;
memberId: string;
@@ -172,6 +172,27 @@ export interface Settings {
simulateEow?: boolean;
}
export interface ChatMessage {
id: string;
famId: string;
authorType: 'admin' | 'member';
authorId: string;
authorName: string;
authorColor?: string;
content: string;
createdAt: string;
}
export interface TypingRow {
id: string;
famId: string;
actorId: string;
actorType: 'admin' | 'member';
authorName: string;
authorColor?: string;
typing: boolean;
}
export interface Session {
famId: string;
userId: string;