chore: auto-commit (21 archivos)
- app.md - backend/dist/assets/index-D_Kep7Fb.js - backend/dist/index.html - backend/handlers.go - backend/main.go - frontend/src/App.tsx - frontend/src/api.ts - frontend/src/components/CardChatPanel.tsx - frontend/src/components/LoginPage.tsx - frontend/src/types.ts - ... Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import {
|
||||
ActionIcon,
|
||||
Avatar,
|
||||
Badge,
|
||||
Box,
|
||||
Combobox,
|
||||
Group,
|
||||
Loader,
|
||||
Paper,
|
||||
@@ -10,10 +12,19 @@ import {
|
||||
Text,
|
||||
Textarea,
|
||||
Tooltip,
|
||||
useCombobox,
|
||||
} from "@mantine/core";
|
||||
import { IconSend, IconTrash } from "@tabler/icons-react";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { KeyboardEvent, useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
KeyboardEvent,
|
||||
ReactNode,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import * as api from "../api";
|
||||
import type { CardMessage, User } from "../types";
|
||||
import { tagColor } from "./colors";
|
||||
@@ -26,14 +37,81 @@ interface Props {
|
||||
onMessagesChange?: (messages: CardMessage[]) => void;
|
||||
}
|
||||
|
||||
// Window for considering a peer "actively typing" after its last event.
|
||||
const TYPING_LIFETIME_MS = 4000;
|
||||
// Minimum gap between successive typing pings emitted while the user types.
|
||||
const TYPING_THROTTLE_MS = 1500;
|
||||
|
||||
interface MentionMatch {
|
||||
start: number; // index of '@' in the textarea value
|
||||
query: string; // text after '@', lowercased
|
||||
}
|
||||
|
||||
function detectMention(value: string, cursor: number): MentionMatch | null {
|
||||
// Look backwards from cursor for an '@' that starts a word.
|
||||
for (let i = cursor - 1; i >= 0 && cursor - i <= 64; i--) {
|
||||
const ch = value[i];
|
||||
if (ch === "@") {
|
||||
// Valid start: beginning of string or whitespace before.
|
||||
if (i === 0 || /\s/.test(value[i - 1])) {
|
||||
const q = value.slice(i + 1, cursor);
|
||||
if (/^[a-z0-9_.-]*$/i.test(q)) {
|
||||
return { start: i, query: q.toLowerCase() };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (/\s/.test(ch)) return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const mentionRegex = /(^|\s)(@[a-z0-9][a-z0-9_.-]{0,63})/gi;
|
||||
|
||||
function renderBody(body: string, knownUsers: Map<string, User>): ReactNode {
|
||||
const out: ReactNode[] = [];
|
||||
let last = 0;
|
||||
let key = 0;
|
||||
for (const m of body.matchAll(mentionRegex)) {
|
||||
const handle = m[2].slice(1).toLowerCase();
|
||||
const idx = (m.index ?? 0) + m[1].length;
|
||||
if (idx > last) out.push(body.slice(last, idx));
|
||||
const user = knownUsers.get(handle);
|
||||
if (user) {
|
||||
out.push(
|
||||
<Badge
|
||||
key={`m${key++}`}
|
||||
size="xs"
|
||||
variant="light"
|
||||
color={user.color || tagColor(user.username)}
|
||||
style={{ verticalAlign: "middle" }}
|
||||
>
|
||||
@{user.username}
|
||||
</Badge>,
|
||||
);
|
||||
} else {
|
||||
out.push(`@${handle}`);
|
||||
}
|
||||
last = idx + m[2].length;
|
||||
}
|
||||
if (last < body.length) out.push(body.slice(last));
|
||||
return out;
|
||||
}
|
||||
|
||||
export function CardChatPanel({ cardId, users, currentUserId, onMessagesChange }: Props) {
|
||||
const [messages, setMessages] = useState<CardMessage[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [body, setBody] = useState("");
|
||||
const [sending, setSending] = useState(false);
|
||||
const [typingUsers, setTypingUsers] = useState<Record<string, number>>({});
|
||||
const [mention, setMention] = useState<MentionMatch | null>(null);
|
||||
const viewportRef = useRef<HTMLDivElement | null>(null);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const lastTypingEmitRef = useRef(0);
|
||||
|
||||
const usersById = new Map(users.map((u) => [u.id, u]));
|
||||
const usersById = useMemo(() => new Map(users.map((u) => [u.id, u])), [users]);
|
||||
const usersByUsername = useMemo(() => new Map(users.map((u) => [u.username.toLowerCase(), u])), [users]);
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
try {
|
||||
@@ -51,22 +129,126 @@ export function CardChatPanel({ cardId, users, currentUserId, onMessagesChange }
|
||||
reload();
|
||||
}, [reload]);
|
||||
|
||||
// Open one WebSocket per cardId for realtime chat + typing.
|
||||
useEffect(() => {
|
||||
const ws = new WebSocket(api.cardChatWSURL(cardId));
|
||||
wsRef.current = ws;
|
||||
ws.onmessage = (ev) => {
|
||||
try {
|
||||
const data = JSON.parse(ev.data) as
|
||||
| { type: "message.created"; message: CardMessage }
|
||||
| { type: "typing"; user_id: string }
|
||||
| { type: "error"; error: string };
|
||||
if (data.type === "message.created" && data.message) {
|
||||
setMessages((prev) => {
|
||||
if (prev.some((m) => m.id === data.message!.id)) return prev;
|
||||
const next = [...prev, data.message!];
|
||||
onMessagesChange?.(next);
|
||||
return next;
|
||||
});
|
||||
} else if (data.type === "typing" && data.user_id) {
|
||||
setTypingUsers((prev) => ({ ...prev, [data.user_id]: Date.now() }));
|
||||
} else if (data.type === "error") {
|
||||
notifications.show({ color: "red", message: data.error });
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed
|
||||
}
|
||||
};
|
||||
ws.onerror = () => {
|
||||
// browser will report; we keep the panel functional via REST fallback
|
||||
};
|
||||
return () => {
|
||||
ws.close();
|
||||
wsRef.current = null;
|
||||
};
|
||||
}, [cardId, onMessagesChange]);
|
||||
|
||||
// Sweep stale typing entries.
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => {
|
||||
const now = Date.now();
|
||||
setTypingUsers((prev) => {
|
||||
const next: Record<string, number> = {};
|
||||
for (const [k, v] of Object.entries(prev)) {
|
||||
if (now - v < TYPING_LIFETIME_MS) next[k] = v;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, 1000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (viewportRef.current) {
|
||||
viewportRef.current.scrollTo({ top: viewportRef.current.scrollHeight, behavior: "smooth" });
|
||||
}
|
||||
}, [messages.length]);
|
||||
|
||||
const sendTypingPing = () => {
|
||||
const ws = wsRef.current;
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
const now = Date.now();
|
||||
if (now - lastTypingEmitRef.current < TYPING_THROTTLE_MS) return;
|
||||
lastTypingEmitRef.current = now;
|
||||
ws.send(JSON.stringify({ type: "typing" }));
|
||||
};
|
||||
|
||||
const combobox = useCombobox({
|
||||
onDropdownClose: () => setMention(null),
|
||||
});
|
||||
|
||||
const mentionCandidates = useMemo(() => {
|
||||
if (!mention) return [] as User[];
|
||||
return users
|
||||
.filter((u) => u.username.toLowerCase().startsWith(mention.query))
|
||||
.slice(0, 8);
|
||||
}, [users, mention]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mention && mentionCandidates.length > 0) {
|
||||
combobox.openDropdown();
|
||||
combobox.selectFirstOption();
|
||||
} else {
|
||||
combobox.closeDropdown();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [mention?.query, mentionCandidates.length]);
|
||||
|
||||
const insertMention = (username: string) => {
|
||||
if (!mention) return;
|
||||
const before = body.slice(0, mention.start);
|
||||
const after = body.slice(mention.start + 1 + mention.query.length);
|
||||
const inserted = `@${username} `;
|
||||
const next = before + inserted + after;
|
||||
setBody(next);
|
||||
setMention(null);
|
||||
// Restore caret right after the inserted mention.
|
||||
requestAnimationFrame(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) return;
|
||||
const pos = (before + inserted).length;
|
||||
el.focus();
|
||||
el.setSelectionRange(pos, pos);
|
||||
});
|
||||
};
|
||||
|
||||
const send = async () => {
|
||||
const text = body.trim();
|
||||
if (!text || sending) return;
|
||||
setSending(true);
|
||||
const ws = wsRef.current;
|
||||
try {
|
||||
const m = await api.createCardMessage(cardId, text);
|
||||
const next = [...messages, m];
|
||||
setMessages(next);
|
||||
onMessagesChange?.(next);
|
||||
setBody("");
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: "send", body: text }));
|
||||
// Optimistic clear; server will broadcast the persisted message.
|
||||
setBody("");
|
||||
} else {
|
||||
const m = await api.createCardMessage(cardId, text);
|
||||
setMessages((prev) => [...prev, m]);
|
||||
onMessagesChange?.([...messages, m]);
|
||||
setBody("");
|
||||
}
|
||||
} catch (e) {
|
||||
notifications.show({ color: "red", message: (e as Error).message });
|
||||
} finally {
|
||||
@@ -85,13 +267,38 @@ export function CardChatPanel({ cardId, users, currentUserId, onMessagesChange }
|
||||
}
|
||||
};
|
||||
|
||||
const onChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
setBody(e.currentTarget.value);
|
||||
sendTypingPing();
|
||||
const cursor = e.currentTarget.selectionStart ?? e.currentTarget.value.length;
|
||||
setMention(detectMention(e.currentTarget.value, cursor));
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (mention && mentionCandidates.length > 0 && (e.key === "Enter" || e.key === "Tab")) {
|
||||
e.preventDefault();
|
||||
const sel = combobox.getSelectedOptionIndex();
|
||||
const pick = mentionCandidates[Math.max(0, sel)];
|
||||
if (pick) insertMention(pick.username);
|
||||
return;
|
||||
}
|
||||
if (mention && e.key === "Escape") {
|
||||
setMention(null);
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
send();
|
||||
}
|
||||
};
|
||||
|
||||
const typingNames = Object.keys(typingUsers)
|
||||
.filter((uid) => uid !== currentUserId)
|
||||
.map((uid) => {
|
||||
const u = usersById.get(uid);
|
||||
return u?.display_name || u?.username || "alguien";
|
||||
});
|
||||
|
||||
return (
|
||||
<Stack gap="xs" style={{ height: "100%", minHeight: 0 }}>
|
||||
<ScrollArea
|
||||
@@ -139,7 +346,7 @@ export function CardChatPanel({ cardId, users, currentUserId, onMessagesChange }
|
||||
)}
|
||||
</Group>
|
||||
<Text size="sm" style={{ whiteSpace: "pre-wrap", wordBreak: "break-word" }}>
|
||||
{m.body}
|
||||
{renderBody(m.body, usersByUsername)}
|
||||
</Text>
|
||||
</Box>
|
||||
</Group>
|
||||
@@ -149,31 +356,65 @@ export function CardChatPanel({ cardId, users, currentUserId, onMessagesChange }
|
||||
</Stack>
|
||||
)}
|
||||
</ScrollArea>
|
||||
<Group gap="xs" align="flex-end">
|
||||
<Textarea
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.currentTarget.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder="Escribe un mensaje (Enter = enviar, Shift+Enter = salto)"
|
||||
autosize
|
||||
minRows={1}
|
||||
maxRows={6}
|
||||
style={{ flex: 1 }}
|
||||
disabled={sending}
|
||||
/>
|
||||
<Tooltip label="Enviar" withArrow>
|
||||
<ActionIcon
|
||||
size="lg"
|
||||
variant="filled"
|
||||
color="blue"
|
||||
onClick={send}
|
||||
disabled={!body.trim() || sending}
|
||||
aria-label="Enviar"
|
||||
>
|
||||
<IconSend size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
{typingNames.length > 0 && (
|
||||
<Text size="xs" c="dimmed" px={6}>
|
||||
{typingNames.length === 1
|
||||
? `${typingNames[0]} esta escribiendo...`
|
||||
: `${typingNames.slice(0, 2).join(", ")}${typingNames.length > 2 ? "..." : ""} estan escribiendo...`}
|
||||
</Text>
|
||||
)}
|
||||
<Combobox
|
||||
store={combobox}
|
||||
onOptionSubmit={(value) => insertMention(value)}
|
||||
position="top-start"
|
||||
withinPortal={false}
|
||||
>
|
||||
<Combobox.DropdownTarget>
|
||||
<Group gap="xs" align="flex-end">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={body}
|
||||
onChange={onChange}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder="Escribe un mensaje (Enter = enviar, @ para mencionar)"
|
||||
autosize
|
||||
minRows={1}
|
||||
maxRows={6}
|
||||
style={{ flex: 1 }}
|
||||
disabled={sending}
|
||||
/>
|
||||
<Tooltip label="Enviar" withArrow>
|
||||
<ActionIcon
|
||||
size="lg"
|
||||
variant="filled"
|
||||
color="blue"
|
||||
onClick={send}
|
||||
disabled={!body.trim() || sending}
|
||||
aria-label="Enviar"
|
||||
>
|
||||
<IconSend size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Combobox.DropdownTarget>
|
||||
<Combobox.Dropdown hidden={!mention || mentionCandidates.length === 0}>
|
||||
<Combobox.Options>
|
||||
{mentionCandidates.map((u) => (
|
||||
<Combobox.Option key={u.id} value={u.username}>
|
||||
<Group gap={6} wrap="nowrap">
|
||||
<Avatar size={18} radius="xl" color={u.color || tagColor(u.username)}>
|
||||
{(u.display_name || u.username).slice(0, 2).toUpperCase()}
|
||||
</Avatar>
|
||||
<Text size="sm" fw={600}>@{u.username}</Text>
|
||||
{u.display_name && u.display_name !== u.username && (
|
||||
<Text size="xs" c="dimmed">{u.display_name}</Text>
|
||||
)}
|
||||
</Group>
|
||||
</Combobox.Option>
|
||||
))}
|
||||
</Combobox.Options>
|
||||
</Combobox.Dropdown>
|
||||
</Combobox>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user