| 1 | /** |
| 2 | * `@handle` mentions in a message: people by username, agents by handle. |
| 3 | * Pure, so they are tested apart from the service. |
| 4 | * |
| 5 | * A message keeps the handles it mentions as ` a b ` (spaces around each), |
| 6 | * so the sidebar finds a viewer's mentions with `LIKE '% name %'` without |
| 7 | * matching `@bobby` for `@bob`. |
| 8 | */ |
| 9 | |
| 10 | /** |
| 11 | * `@` after the start or a character that cannot be part of an address |
| 12 | * or a word (so `me@example.com` is not a mention), then the handle. |
| 13 | */ |
| 14 | const MENTION = /(^|[^a-z0-9_.@-])@([a-z0-9](?:[a-z0-9_-]{0,38}[a-z0-9_])?)/gi; |
| 15 | |
| 16 | /** The handles `body` mentions, lowercased, each once, in order. */ |
| 17 | export function mentionedHandles(body: string): string[] { |
| 18 | const found = new Set<string>(); |
| 19 | for (const match of String(body ?? "").matchAll(MENTION)) found.add(match[2].toLowerCase()); |
| 20 | return [...found]; |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * The same, ending where a handle ends: `@ana/web` (a team) is not a |
| 25 | * mention of `@ana`, and a shorter match can't be taken from a longer one. |
| 26 | */ |
| 27 | const MENTION_WHOLE = /(^|[^a-z0-9_.@-])@([a-z0-9](?:[a-z0-9_-]{0,38}[a-z0-9_])?)(?![a-z0-9_/-])/gi; |
| 28 | |
| 29 | /** Code, which is never a mention: fenced blocks (to the end, if unclosed) and inline spans. */ |
| 30 | const CODE = /```[\s\S]*?(?:```|$)|`[^`\n]*`/g; |
| 31 | |
| 32 | /** |
| 33 | * An agent's message as it is kept: a mention of anyone who is not a |
| 34 | * member of the conversation (`members`, lowercased handles and |
| 35 | * usernames) loses its `@`, so it reads as a plain name, shows no pill and |
| 36 | * notifies nobody. Code and team mentions are left as written. |
| 37 | */ |
| 38 | export function plainOutside(body: string, members: ReadonlySet<string>): string { |
| 39 | const text = String(body ?? ""); |
| 40 | const plain = (part: string) => |
| 41 | part.replace(MENTION_WHOLE, (whole, before: string, handle: string) => (members.has(handle.toLowerCase()) ? whole : `${before}${handle}`)); |
| 42 | let out = ""; |
| 43 | let at = 0; |
| 44 | for (const code of text.matchAll(CODE)) { |
| 45 | out += plain(text.slice(at, code.index)) + code[0]; |
| 46 | at = code.index! + code[0].length; |
| 47 | } |
| 48 | return out + plain(text.slice(at)); |
| 49 | } |
| 50 | |
| 51 | /** How a message's mentions are kept: `` (none) or ` a b `. */ |
| 52 | export function mentionsColumn(handles: string[]): string { |
| 53 | return handles.length ? ` ${handles.join(" ")} ` : ""; |
| 54 | } |
| 55 | |
| 56 | /** Whether a kept mentions column names `handle`. */ |
| 57 | export function mentions(column: string | null | undefined, handle: string): boolean { |
| 58 | return !!column && column.includes(` ${handle.toLowerCase()} `); |
| 59 | } |