| 1 | /** |
| 2 | * Chat as the site draws it: which messages sit together under one name, |
| 3 | * where a day starts, what an `@…` being typed could become, and a |
| 4 | * message's text as safe blocks and spans. Pure, so it is tested on its |
| 5 | * own (chat.test.ts); the components are in components/chat. |
| 6 | * |
| 7 | * Message bodies are never HTML: they are parsed here into a small tree |
| 8 | * that React renders as text, so nothing anyone writes can run. |
| 9 | */ |
| 10 | import type { ChatMessage, ChatSidebarEntry, MemberProfile, Principal } from "@g1t/contracts"; |
| 11 | |
| 12 | /** Two messages from the same author this close together share one header. */ |
| 13 | export const GROUP_GAP_MS = 5 * 60 * 1000; |
| 14 | |
| 15 | /** A message on its way: shown at once, then swapped for what the service saved. */ |
| 16 | export type ShownMessage = ChatMessage & { pending?: boolean; failed?: boolean; client_id?: string }; |
| 17 | |
| 18 | export type TimelineRow = |
| 19 | | { kind: "day"; key: string; label: string } |
| 20 | | { kind: "message"; key: string; message: ShownMessage; head: boolean }; |
| 21 | |
| 22 | function sameAuthor(a: ChatMessage["author"], b: ChatMessage["author"]): boolean { |
| 23 | return a.kind === b.kind && a.id === b.id; |
| 24 | } |
| 25 | |
| 26 | /** The calendar day of an instant, in the reader's time zone (or `zone`). */ |
| 27 | export function dayKey(at: string | Date, zone?: string): string { |
| 28 | const date = typeof at === "string" ? new Date(at) : at; |
| 29 | return new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).format(date); |
| 30 | } |
| 31 | |
| 32 | /** "Today", "Yesterday", or the date, for the rule between days. */ |
| 33 | export function dayLabel(at: string, now: Date = new Date(), zone?: string): string { |
| 34 | const key = dayKey(at, zone); |
| 35 | if (key === dayKey(now, zone)) return "Today"; |
| 36 | const yesterday = new Date(now.getTime() - 86_400_000); |
| 37 | if (key === dayKey(yesterday, zone)) return "Yesterday"; |
| 38 | const date = new Date(at); |
| 39 | const sameYear = dayKey(date, zone).slice(0, 4) === dayKey(now, zone).slice(0, 4); |
| 40 | return new Intl.DateTimeFormat("en-US", { |
| 41 | timeZone: zone, |
| 42 | weekday: "long", |
| 43 | month: "long", |
| 44 | day: "numeric", |
| 45 | year: sameYear ? undefined : "numeric", |
| 46 | }).format(date); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * The channel's messages, oldest first, as rows: a rule where each day |
| 51 | * starts, and each message marked with whether it starts a group (and so |
| 52 | * shows its author's name and avatar). A card always starts one. |
| 53 | */ |
| 54 | export function timeline(messages: ShownMessage[], now: Date = new Date(), zone?: string): TimelineRow[] { |
| 55 | const rows: TimelineRow[] = []; |
| 56 | let previous: ShownMessage | null = null; |
| 57 | let day: string | null = null; |
| 58 | for (const message of messages) { |
| 59 | if (message.deleted_at) continue; |
| 60 | const today = dayKey(message.created_at, zone); |
| 61 | if (today !== day) { |
| 62 | rows.push({ kind: "day", key: `day:${today}`, label: dayLabel(message.created_at, now, zone) }); |
| 63 | day = today; |
| 64 | previous = null; |
| 65 | } |
| 66 | const head = |
| 67 | previous == null || |
| 68 | message.kind === "card" || |
| 69 | previous.kind === "card" || |
| 70 | !sameAuthor(previous.author, message.author) || |
| 71 | new Date(message.created_at).getTime() - new Date(previous.created_at).getTime() > GROUP_GAP_MS; |
| 72 | rows.push({ kind: "message", key: message.client_id ?? message.id, message, head }); |
| 73 | previous = message; |
| 74 | } |
| 75 | return rows; |
| 76 | } |
| 77 | |
| 78 | /** |
| 79 | * Messages merged by id, oldest first: what the page had, what arrived |
| 80 | * live and what a reload brought. A newer copy (an edit) wins; a pending |
| 81 | * message is dropped once the saved one with its `client_id` is there. |
| 82 | */ |
| 83 | export function mergeMessages(current: ShownMessage[], incoming: ShownMessage[]): ShownMessage[] { |
| 84 | const byId = new Map<string, ShownMessage>(); |
| 85 | for (const message of [...current, ...incoming]) { |
| 86 | const key = message.id; |
| 87 | const had = byId.get(key); |
| 88 | if (!had || !message.pending || had.pending) byId.set(key, message); |
| 89 | } |
| 90 | const saved = new Set([...byId.values()].filter((m) => !m.pending).map((m) => m.client_id).filter(Boolean)); |
| 91 | return [...byId.values()] |
| 92 | .filter((message) => !(message.pending && message.client_id && saved.has(message.client_id))) |
| 93 | .sort((a, b) => (a.pending === b.pending ? (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) : a.pending ? 1 : -1)); |
| 94 | } |
| 95 | |
| 96 | /** Someone who can be mentioned: a person by username, an agent by handle. */ |
| 97 | export type Mentionable = { |
| 98 | kind: "user" | "agent"; |
| 99 | /** What follows the `@`: lowercased, as it is kept. */ |
| 100 | name: string; |
| 101 | /** A person's username as they wrote it, when that differs from `name`. */ |
| 102 | display_username?: string | null; |
| 103 | display_name: string; |
| 104 | avatar: string | null; |
| 105 | /** An agent's role, shown beside it. */ |
| 106 | role?: string | null; |
| 107 | }; |
| 108 | |
| 109 | export type MentionQuery = { start: number; typed: string; options: Mentionable[] }; |
| 110 | |
| 111 | /** Most suggestions at once. */ |
| 112 | export const MAX_MENTIONS = 6; |
| 113 | |
| 114 | /** |
| 115 | * The `@…` just before the caret and who it could be: names that start with |
| 116 | * what is typed first, then display names with a word that does. Null when |
| 117 | * the caret is not in a mention, or nothing fits. |
| 118 | */ |
| 119 | export function mentionQuery(text: string, caret: number, people: readonly Mentionable[]): MentionQuery | null { |
| 120 | const match = /(?:^|[\s(])@([\w.-]{0,40})$/.exec(text.slice(0, caret)); |
| 121 | if (!match) return null; |
| 122 | const typed = match[1]!.toLowerCase(); |
| 123 | const start = caret - match[1]!.length - 1; |
| 124 | const first: Mentionable[] = []; |
| 125 | const then: Mentionable[] = []; |
| 126 | for (const person of people) { |
| 127 | const name = person.name.toLowerCase(); |
| 128 | if (name === typed) continue; |
| 129 | if (name.startsWith(typed)) first.push(person); |
| 130 | else if (typed && person.display_name.toLowerCase().split(/\s+/).some((word) => word.startsWith(typed))) then.push(person); |
| 131 | } |
| 132 | const options = [...first, ...then].slice(0, MAX_MENTIONS); |
| 133 | return options.length > 0 ? { start, typed, options } : null; |
| 134 | } |
| 135 | |
| 136 | // --------------------------------------------------------------------------- |
| 137 | // A message's text: its Markdown, parsed by the rule every part of g1t reads it with. |
| 138 | |
| 139 | export { type Block, type Span, blocks, inline, plainText, safeHref, spansText } from "@g1t/contracts/chat-markdown"; |
| 140 | |
| 141 | /** Whether a message is only emoji, a few of them: shown larger, as people expect. */ |
| 142 | export function onlyEmoji(text: string): boolean { |
| 143 | const trimmed = text.trim(); |
| 144 | if (!trimmed || trimmed.length > 24) return false; |
| 145 | return /^(?:\p{Extended_Pictographic}|\p{Emoji_Component}||️|\s)+$/u.test(trimmed) && /\p{Extended_Pictographic}/u.test(trimmed); |
| 146 | } |
| 147 | |
| 148 | // --------------------------------------------------------------------------- |
| 149 | // The sidebar. |
| 150 | |
| 151 | export type ChatFilter = "all" | "unread" | "mentions"; |
| 152 | |
| 153 | /** The sidebar's rows that pass the filter and the "Jump to" text. */ |
| 154 | export function filterEntries(entries: ChatSidebarEntry[], filter: ChatFilter, query: string): ChatSidebarEntry[] { |
| 155 | const q = query.trim().toLowerCase().replace(/^[#@]/, ""); |
| 156 | return entries.filter((entry) => { |
| 157 | if (filter === "unread" && entry.unread === 0 && entry.mentions === 0) return false; |
| 158 | if (filter === "mentions" && entry.mentions === 0) return false; |
| 159 | if (!q) return true; |
| 160 | if (entry.title.toLowerCase().includes(q)) return true; |
| 161 | return entry.others.some((member) => member.name.toLowerCase().includes(q) || member.display_name.toLowerCase().includes(q)); |
| 162 | }); |
| 163 | } |
| 164 | |
| 165 | /** The agent a conversation is a direct message with, when it is with one agent alone; else null. */ |
| 166 | export function agentDmOf(entry: ChatSidebarEntry): string | null { |
| 167 | const only = entry.others.length === 1 ? entry.others[0]! : null; |
| 168 | return entry.channel.kind === "dm" && only?.kind === "agent" ? only.id : null; |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * The sidebar's sections, in the order they show: what is pinned (the |
| 173 | * `starred` preference), channels, and direct messages, the latest first, |
| 174 | * with people and agents alike (an agent is a member you message like |
| 175 | * anyone). `agentDms` finds the direct message with each agent, by agent |
| 176 | * id, so the Agents section lists only the agents you have not talked to. |
| 177 | */ |
| 178 | export function sections(entries: ChatSidebarEntry[]): { |
| 179 | pinned: ChatSidebarEntry[]; |
| 180 | channels: ChatSidebarEntry[]; |
| 181 | agentDms: Map<string, ChatSidebarEntry>; |
| 182 | dms: ChatSidebarEntry[]; |
| 183 | } { |
| 184 | const byName = (a: ChatSidebarEntry, b: ChatSidebarEntry) => a.title.localeCompare(b.title); |
| 185 | // Direct messages: the latest conversation first, as people scan them. |
| 186 | const byRecent = (a: ChatSidebarEntry, b: ChatSidebarEntry) => |
| 187 | (b.channel.last_message_at ?? b.channel.created_at).localeCompare(a.channel.last_message_at ?? a.channel.created_at); |
| 188 | const agentDms = new Map<string, ChatSidebarEntry>(); |
| 189 | for (const entry of entries) { |
| 190 | const agent = agentDmOf(entry); |
| 191 | if (agent) agentDms.set(agent, entry); |
| 192 | } |
| 193 | return { |
| 194 | pinned: entries.filter((e) => e.starred).sort(byName), |
| 195 | channels: entries.filter((e) => !e.starred && e.channel.kind === "channel").sort(byName), |
| 196 | agentDms, |
| 197 | dms: entries.filter((e) => !e.starred && e.channel.kind === "dm").sort(byRecent), |
| 198 | }; |
| 199 | } |
| 200 | |
| 201 | /** Where a conversation is, under the workspace. */ |
| 202 | export function channelPath(slug: string, channel: { id: string; kind: "channel" | "dm"; name: string | null }): string { |
| 203 | return channel.kind === "dm" || !channel.name ? `/${slug}/-/chat/dm/${channel.id}` : `/${slug}/-/chat/${channel.name}`; |
| 204 | } |
| 205 | |
| 206 | /** Unread across the sidebar, leaving out what is muted: the rail's badge. */ |
| 207 | export function unreadTotals(entries: ChatSidebarEntry[]): { unread: number; mentions: number } { |
| 208 | let unread = 0; |
| 209 | let mentions = 0; |
| 210 | for (const entry of entries) { |
| 211 | mentions += entry.mentions; |
| 212 | if (!entry.muted) unread += entry.unread; |
| 213 | } |
| 214 | return { unread, mentions }; |
| 215 | } |
| 216 | |
| 217 | /** Channel names: lowercase words and digits joined by dashes, as people type them. */ |
| 218 | export function channelName(typed: string): string { |
| 219 | return typed |
| 220 | .toLowerCase() |
| 221 | .replace(/^#/, "") |
| 222 | .replace(/[\s_]+/g, "-") |
| 223 | .replace(/[^a-z0-9-]/g, "") |
| 224 | .replace(/-{2,}/g, "-") |
| 225 | .slice(0, 80); |
| 226 | } |
| 227 | |
| 228 | /** Paths under `-/chat/` that are pages, not channels: never a channel's name. */ |
| 229 | export const RESERVED_CHANNEL_NAMES = ["dm", "browse", "live", "api", "new"] as const; |
| 230 | |
| 231 | /** A principal as a form field carries it: `user:<username>` or `agent:<id>`. */ |
| 232 | export function principalField(kind: Principal["kind"], key: string): string { |
| 233 | return `${kind}:${key}`; |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * A member's handle as it shows after `@`: a person's username in its |
| 238 | * chosen case, an agent's handle. The same rule as `memberHandle` in |
| 239 | * @g1t/contracts, kept here so this file stays pure for its tests. |
| 240 | */ |
| 241 | export function shownHandle(member: { name: string; display_username?: string | null }): string { |
| 242 | const display = member.display_username; |
| 243 | return display && display.toLowerCase() === member.name.toLowerCase() ? display : member.name; |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * The name shown for a member, everywhere in chat (messages, the sidebar, |
| 248 | * typing, cards): their display name, else their handle in its chosen |
| 249 | * case. The same rule as `memberName` in @g1t/contracts, which the chat |
| 250 | * service and its notifications follow. |
| 251 | */ |
| 252 | export function shownName(member: Pick<MemberProfile, "display_name" | "name"> & { display_username?: string | null }): string { |
| 253 | return member.display_name?.trim() || shownHandle(member); |
| 254 | } |
| 255 | |
| 256 | /** |
| 257 | * Who each lowercased handle is, for drawing `@name` as the name people |
| 258 | * know: the workspace's people and agents. |
| 259 | */ |
| 260 | export function mentionNames(people: readonly Mentionable[]): Map<string, string> { |
| 261 | const names = new Map<string, string>(); |
| 262 | for (const person of people) names.set(person.name.toLowerCase(), shownName(person)); |
| 263 | return names; |
| 264 | } |
| 265 | |
| 266 | /** Reconnect delays for the live socket: doubling from one second to thirty, with jitter. */ |
| 267 | export function backoff(attempt: number, random: () => number = Math.random): number { |
| 268 | const base = Math.min(30_000, 1000 * 2 ** Math.max(0, attempt)); |
| 269 | return Math.round(base * (0.75 + random() * 0.5)); |
| 270 | } |