Desktop: react to messages, reactions in other languages, and edits

- Right-click a message (or photo): a quick reaction row above Copy, + for
  every emoji, and "Customize quick reactions…" there to change the row
  (saved in settings as quickReactions; default ❤️ 👍 👎 😂 ‼️ ❓). Yours
  shows sunk; clicking it again takes it back. A reaction goes out as an
  ordinary text worded like an iPhone's ("Loved “…”", "Reacted 🎉 to “…”",
  "Removed a heart from “…”"), long messages quoted cut short.
- Tapbacks in other languages ("Le encanta “…”", "Hat „…“ geliebt",
  "A aimé « … »"...): read from the words around the quote, and only folded
  when the quote matches an earlier message. A failed reaction stays in view.
- "Edited to “…”": applied to the sender's message from the last 20 minutes
  that reads most like it (or their only one); the bubble says "Edited", and
  clicking it shows the earlier texts. Reactions to the old text still land.
- Popovers re-fit the window when they grow.
This commit is contained in:
2026-11-10 17:33:48 -08:00
parent 23abc9fa6d
commit fe34c50101
14 changed files with 1046 additions and 35 deletions
+171
View File
@@ -0,0 +1,171 @@
// An iPhone that edits a message sent to a non-iPhone sends the new text on
// its own: Edited to “see you at 9:30”. It doesn't say which message, so we
// look for it: the same person's message from the last few minutes (iPhones
// only allow edits for 15) that reads most like the new text. Found, the
// "Edited to" text is hidden, the message shows its new text, and it keeps
// its older texts for "Edited" to show, the way Signal does. Not found (or
// changed past recognising, with other messages around), it stays a text.
import { foldReactions, norm, parseReaction, type Reaction } from "./reactions";
const PREFIXES = [
"edited to",
"editado a",
"editó a",
"se editó a",
"editado para",
"editou para",
"a modifié en",
"modifié en",
"a été modifié en",
"bearbeitet zu",
"bearbeitet",
"geändert in",
"geändert zu",
"modificato in",
"ha modificato in",
"bewerkt naar",
"gewijzigd in",
];
const EDIT = new RegExp(
`^(${PREFIXES.join("|")}):?\\s*[“"”«„‚]([\\s\\S]*)[”"“»‘’]$`,
"iu",
);
// The new text of an "Edited to “…”" message.
export function parseEdit(body: string): string | null {
const m = EDIT.exec(body.trim());
const text = m?.[2].replace(/^[\s  ]+|[\s  ]+$/g, "");
return text || null;
}
export function editPreview(body: string): string | null {
const text = parseEdit(body);
return text === null ? null : `✏️ ${norm(text)}`;
}
export interface Version {
body: string;
ts: number;
}
interface Foldable {
id: number;
body: string;
ts: number;
direction: "in" | "out";
contact: string;
sender?: string;
status?: string;
}
// iPhones allow edits for 15 minutes; a little more for slow delivery.
const WINDOW = 20 * 60_000;
// Past the window (a delayed edit), only a near-copy counts.
const LATE_WINDOW = 24 * 60 * 60_000;
const LIKENESS = 0.4;
const LATE_LIKENESS = 0.6;
const LOOK_BACK = 40;
// How alike two texts are: 1 = the same, 0 = nothing in common
// (one minus the edit distance over the longer length).
export function likeness(a: string, b: string): number {
const x = [...norm(a).toLowerCase()].slice(0, 600);
const y = [...norm(b).toLowerCase()].slice(0, 600);
if (!x.length && !y.length) return 1;
let prev = Array.from({ length: y.length + 1 }, (_, j) => j);
for (let i = 1; i <= x.length; i++) {
const cur = [i];
for (let j = 1; j <= y.length; j++)
cur[j] = Math.min(
prev[j] + 1,
cur[j - 1] + 1,
prev[j - 1] + (x[i - 1] === y[j - 1] ? 0 : 1),
);
prev = cur;
}
return 1 - prev[y.length] / Math.max(x.length, y.length);
}
const isTapback = (body: string): boolean => {
const r = parseReaction(body);
return !!r && !r.loose;
};
const who = (m: Foldable): string =>
m.direction === "out" ? "me" : m.sender ?? m.contact;
// The conversation (oldest first) with the edits applied: "Edited to" texts
// we could place are gone and their messages show the new text. `versions`
// has each edited message's texts, oldest first, the shown one last.
export function foldEdits<T extends Foldable>(
msgs: T[],
): { shown: T[]; versions: Map<number, Version[]> } {
const hidden = new Set<number>();
const current = new Map<number, string>();
const versions = new Map<number, Version[]>();
msgs.forEach((m, i) => {
if (m.status === "failed") return;
const text = parseEdit(m.body);
if (text === null) return;
const from = who(m);
const near: { c: T; score: number }[] = [];
const late: { c: T; score: number }[] = [];
for (let j = i - 1; j >= 0 && j >= i - LOOK_BACK; j--) {
const c = msgs[j];
if (m.ts - c.ts > LATE_WINDOW) break;
if (
hidden.has(c.id) ||
who(c) !== from ||
parseEdit(c.body) !== null ||
isTapback(c.body)
)
continue;
const body = current.get(c.id) ?? c.body;
if (!body.trim()) continue;
const score = likeness(body, text);
(m.ts - c.ts <= WINDOW ? near : late).push({ c, score });
}
const best = (xs: { c: T; score: number }[]) =>
xs.reduce<{ c: T; score: number } | undefined>(
(a, b) => (!a || b.score > a.score ? b : a),
undefined,
);
const n = best(near);
const l = best(late);
// Only one of theirs in the window: that's the one, however much it changed.
const hit =
n && (n.score >= LIKENESS || near.length === 1)
? n.c
: l && l.score >= LATE_LIKENESS
? l.c
: undefined;
if (!hit) return;
hidden.add(m.id);
const list = versions.get(hit.id) ?? [{ body: hit.body, ts: hit.ts }];
list.push({ body: text, ts: m.ts });
versions.set(hit.id, list);
current.set(hit.id, text);
});
if (!hidden.size) return { shown: msgs, versions };
const shown = msgs
.filter((m) => !hidden.has(m.id))
.map((m) => (current.has(m.id) ? { ...m, body: current.get(m.id)! } : m));
return { shown, versions };
}
// Edits, then reactions (which may quote a message's text from before its edit).
export function foldConversation<T extends Foldable & { media?: unknown[] }>(
msgs: T[],
): {
shown: T[];
reactions: Map<number, Reaction[]>;
versions: Map<number, Version[]>;
} {
const e = foldEdits(msgs);
const earlier = new Map(
[...e.versions].map(([id, v]) => [id, v.slice(0, -1).map((x) => x.body)]),
);
const r = foldReactions(e.shown, earlier);
return { shown: r.shown, reactions: r.reactions, versions: e.versions };
}
+146 -18
View File
@@ -1,9 +1,15 @@
// iMessage "tapbacks" sent to non-iPhones arrive as plain texts:
// Loved “see you at 9” Laughed at “lol” Reacted 🎉 to “we won”
// Removed a heart from “see you at 9” Liked an image
// in the sender's phone language too ("Le encanta “…”", "Hat „…“ geliebt").
// We fold them into emoji reactions on the message they quote (found by
// searching back through the conversation), the way Signal shows reactions.
// A reaction whose message can't be found stays an ordinary message.
//
// English is read exactly. Other languages are read loosely, since their
// wording varies by phone and OS version: a short frame around a quote, whose
// words name the reaction (see LOOSE). A loose reading only counts when the
// quote matches an earlier message, so ordinary texts stay put.
const VERBS: Record<string, string> = {
loved: '❤️',
@@ -24,9 +30,11 @@ const REMOVED: Record<string, string> = {
'a question mark': '❓'
}
// Quotes come curly from iPhones, sometimes straight.
// Quotes come curly from iPhones, sometimes straight; «» and „“ elsewhere.
const Q_OPEN = '[“"”]'
const Q_CLOSE = '[”"“]'
const OPENS = '“"”«„‚‘「『'
const CLOSES = '”"“»«‘’」』'
const MEDIA = /^(?:an? )?(?:image|photo|picture|movie|video|attachment|audio message|gif|sticker)$/i
export interface ParsedReaction {
@@ -34,6 +42,7 @@ export interface ParsedReaction {
removed: boolean
// The quoted text, or `media` for "Loved an image" and the like.
target: { text: string } | { media: true }
loose?: boolean // read from a non-English frame: needs a matching message to count
}
const REACTED = new RegExp(`^Reacted (.+?) to (?:${Q_OPEN}([\\s\\S]*)${Q_CLOSE}|(.+))$`)
@@ -46,15 +55,14 @@ function target(quoted: string | undefined, bare: string | undefined): ParsedRea
return null
}
export function parseReaction(body: string): ParsedReaction | null {
const s = body.trim()
function strict(s: string): ParsedReaction | null {
let m = VERB.exec(s)
if (m) {
const t = target(m[2], m[3])
return t && { emoji: VERBS[m[1].toLowerCase()], removed: false, target: t }
}
m = REACTED.exec(s)
if (m && [...m[1]].length <= 4) {
if (m && [...m[1]].length <= 8) {
const t = target(m[2], m[3])
return t && { emoji: m[1], removed: false, target: t }
}
@@ -62,13 +70,84 @@ export function parseReaction(body: string): ParsedReaction | null {
if (m) {
const kind = m[1].toLowerCase()
// "Removed a 😂 from …" (newer iOS) names the emoji itself.
const emoji = REMOVED[kind] ?? (/^an? (.{1,4})$/u.exec(m[1])?.[1] ?? '')
const emoji = REMOVED[kind] ?? (/^an? (.{1,8})$/u.exec(m[1])?.[1] ?? '')
const t = target(m[2], m[3])
return emoji && t ? { emoji, removed: true, target: t } : null
}
return null
}
// ---- other languages ----
// A word (stem) that starts a word: JS's \b doesn't know accented letters.
const w = (alts: string): RegExp => new RegExp(`(?<!\\p{L})(?:${alts})`, 'iu')
// Checked in order; the first that fits names the reaction. Stems cover
// Spanish, Portuguese, French, German, Italian and Dutch, past and present
// ("Le encantó" / "Le encanta"), and the nouns removals use ("un corazón").
const LOOSE: [string, RegExp][] = [
['👎', w("no les? gust|não (?:curt|gost)|n['’]a pas (?:aimé|apprécié)|n['’]aime pas|nicht gemocht|mag\\b.{0,30}\\bnicht|gefällt\\b.{0,30}\\bnicht|nicht gefallen|non (?:gli |le )?piac|non mi piace|niet leuk|dislike|daumen runter|pulgar abajo")],
['❤️', w('encant|amou|adorou|ama(?!\\p{L})|adora|adoré|adore|geliebt|liebt|herz|ha amato|amato|adorato|ama |coraz[oó]n|cora[cç][aã]o|c[oœ]ur|cuore|hart|houdt van|heart|love')],
['😂', w('ri[oó] de|r[ií]e de|se ri[oó]|se r[ií]e|gracia|riu|ri de|gra[cç]a|a ri|rit de|rire|dr[oô]le|gelacht|lacht|ha riso|riso|ride di|risata|risa|lach|laugh')],
['‼️', w('emphasi|enfatiz|destac|resalt|real[cç]|soulign|mis en [ée]vidence|met en [ée]vidence|insist|hervorgehoben|hebt\\b.{0,30}\\bhervor|betont|evidenzi|sottoline|exclama|esclama|ausrufe|benadrukt|nadruk')],
['❓', w('question|cuestion|dud|d[uú]vida|doute|interrog|infrage|in frage|hinterfrag|fragezeichen|dubbio|domanda|vraagteken|twijfel')],
['👍', w('gust|curt|gost|aim[eé]|aime|gemocht|mag(?!\\p{L})|gef[aä]ll|piac|like|leuk|daumen')]
]
const REMOVE_WORDS = w('removed|quit[oó]|elimin[oó]|retir[oó]|borr[oó]|removeu|retirou|tirou|excluiu|a retiré|a supprimé|a enlevé|retire|supprime|entfernt|ha rimosso|ha tolto|rimosso|tolto|verwijderd')
// Tapbacks are worded about the sender, never "I"/"you": a frame in the
// first or second person is someone writing, not a phone reporting.
const PERSONAL = w("i(?!\\p{L})|i['’]m|me(?!\\p{L})|my(?!\\p{L})|you|yo(?!\\p{L})|tú(?!\\p{L})|eu(?!\\p{L})|je(?!\\p{L})|j['’]|moi(?!\\p{L})|ich(?!\\p{L})|du(?!\\p{L})|io(?!\\p{L})|ik(?!\\p{L})|jij(?!\\p{L})")
const EMOJI = /\p{Extended_Pictographic}(?:️|\p{Emoji_Modifier}|‍\p{Extended_Pictographic}️?)*/u
// "Le encantó una imagen", "Hat ein Bild geliebt": the indefinite article is
// what phones write and people rarely do.
const MEDIA_LOOSE = w("(?:an?|una?|uma?|une|ein(?:e[nm]?)?|un['’])\\s+(?:image|imagen|imagem|photo|foto|bild|immagine|picture|video|vídeo|vidéo|movie|película|filme|film|attachment|archivo adjunto|anexo|pièce jointe|anhang|allegato|audio message|mensaje de audio|mensagem de áudio|message audio|sprachnachricht|messaggio audio|gif|sticker|autocollant)(?!\\p{L})")
// The reaction a frame like "Le encanta" or "Hat … geliebt" names.
function classify(frame: string): { emoji: string; removed: boolean } | null {
const f = frame.replace(/\s+/g, ' ').trim().replace(/[::]$/, '').trim()
// A quoted reaction name ("un “me gusta”") is the phone's words, not the sender's.
const own = f.replace(/[“"”«„‚‘「『][^“"”»«„‚‘’」』]*[”"“»«‘’」』]/g, '')
if (!f || f.length > 60 || f.split(' ').length > 8 || /[\n?.]/.test(f) || PERSONAL.test(own)) return null
const removed = REMOVE_WORDS.test(f)
const emoji = EMOJI.exec(f)?.[0] ?? LOOSE.find(([, re]) => re.test(f))?.[0]
return emoji ? { emoji, removed } : null
}
// Every way to read `s` as a non-English reaction: each opening quote could
// be where the quote starts ("Quitó un “me gusta” de “…”" has two).
function loose(s: string): ParsedReaction[] {
const out: ParsedReaction[] = []
let close = -1
for (let i = s.length - 1; i >= 0; i--)
if (CLOSES.includes(s[i])) {
close = i
break
}
for (let i = 0; i < close; i++) {
if (!OPENS.includes(s[i])) continue
const c = classify(`${s.slice(0, i)} ${s.slice(close + 1)}`)
const text = s.slice(i + 1, close).replace(/^[\s  ]+|[\s  ]+$/g, '')
if (c && text) out.push({ ...c, target: { text }, loose: true })
}
if (!out.length && s.length <= 80) {
const m = MEDIA_LOOSE.exec(s)
const c = m && classify(s.slice(0, m.index) + ' ' + s.slice(m.index + m[0].length))
if (c) out.push({ ...c, target: { media: true }, loose: true })
}
return out
}
// All plausible readings, the likeliest first. English ones are certain.
export function parseReactions(body: string): ParsedReaction[] {
const s = body.trim()
const r = strict(s)
return r ? [r] : loose(s)
}
export function parseReaction(body: string): ParsedReaction | null {
return parseReactions(body)[0] ?? null
}
export interface Reaction {
emoji: string
from: string // the reactor's number, or 'me'
@@ -82,11 +161,12 @@ interface Foldable {
direction: 'in' | 'out'
contact: string
sender?: string
status?: string
media?: unknown[]
}
// Phones swap straight and curly apostrophes, so compare without the difference.
const norm = (s: string): string => s.replace(/[‘’]/g, "'").replace(/\s+/g, ' ').trim()
export const norm = (s: string): string => s.replace(/[‘’]/g, "'").replace(/\s+/g, ' ').trim()
function matches(body: string, quoted: string): boolean {
const b = norm(body)
@@ -101,26 +181,37 @@ function matches(body: string, quoted: string): boolean {
// The conversation's messages (oldest first) without the reaction texts we
// could place, plus each placed reaction keyed by the message it's on. Each
// person keeps one reaction per message, like iMessage: a newer one replaces
// theirs, a "Removed …" takes it away.
export function foldReactions<T extends Foldable>(msgs: T[]): { shown: T[]; reactions: Map<number, Reaction[]> } {
// theirs, a "Removed …" takes it away. `earlier` holds an edited message's
// older texts, which a reaction may still quote.
export function foldReactions<T extends Foldable>(msgs: T[], earlier?: Map<number, string[]>): { shown: T[]; reactions: Map<number, Reaction[]> } {
const hidden = new Set<number>()
const byTarget = new Map<number, Map<string, Reaction>>()
const quotes = (c: T, text: string): boolean => matches(c.body, text) || !!earlier?.get(c.id)?.some((b) => matches(b, text))
msgs.forEach((m, i) => {
const r = parseReaction(m.body)
if (!r) return
// One that didn't go out stays in view, with its Retry.
if (m.status === 'failed') return
const readings = parseReactions(m.body)
let found: T | undefined
for (let j = i - 1; j >= 0 && !found; j--) {
const c = msgs[j]
if (hidden.has(c.id) || parseReaction(c.body)) continue
if ('media' in r.target ? !!c.media?.length : matches(c.body, r.target.text)) found = c
let r: ParsedReaction | undefined
for (const reading of readings) {
for (let j = i - 1; j >= 0 && !found; j--) {
const c = msgs[j]
if (hidden.has(c.id) || strict(c.body.trim())) continue
if ('media' in reading.target ? !!c.media?.length : quotes(c, reading.target.text)) found = c
}
if (found) {
r = reading
break
}
}
if (!found) return
if (!found || !r) return
hidden.add(m.id)
const from = m.direction === 'out' ? 'me' : (m.sender ?? m.contact)
const mine = byTarget.get(found.id) ?? new Map<string, Reaction>()
if (r.removed) {
if (mine.get(from)?.emoji === r.emoji) mine.delete(from)
if (sameEmoji(mine.get(from)?.emoji, r.emoji)) mine.delete(from)
} else {
mine.delete(from)
mine.set(from, { emoji: r.emoji, from, ts: m.ts })
}
byTarget.set(found.id, mine)
@@ -130,10 +221,47 @@ export function foldReactions<T extends Foldable>(msgs: T[]): { shown: T[]; reac
return { shown: hidden.size ? msgs.filter((m) => !hidden.has(m.id)) : msgs, reactions }
}
// A reaction text as a short preview line: "❤️ to “see you at 9”".
// "❤" and "❤️" are the same reaction.
export const sameEmoji = (a: string | undefined, b: string | undefined): boolean =>
a !== undefined && b !== undefined && a.replace(/️/g, '') === b.replace(/️/g, '')
// A reaction text as a short preview line: "❤️ to “see you at 9”". Loose
// (non-English) readings only once they're known to be reactions, so not here.
export function reactionPreview(body: string): string | null {
const r = parseReaction(body)
if (!r) return null
if (!r || r.loose) return null
const what = 'media' in r.target ? 'a photo' : `“${norm(r.target.text)}”`
return r.removed ? `Removed ${r.emoji} from ${what}` : `${r.emoji} to ${what}`
}
// ---- sending ----
// The emoji a phone can show as its own reaction, and how an iPhone words it.
const SEND_VERBS: Record<string, [string, string]> = {
'❤': ['Loved', 'a heart'],
'👍': ['Liked', 'a like'],
'👎': ['Disliked', 'a dislike'],
'😂': ['Laughed at', 'a laugh'],
'‼': ['Emphasized', 'an exclamation'],
'❓': ['Questioned', 'a question mark']
}
// Long messages are quoted cut short, as iPhones do (and `matches` allows).
const MAX_QUOTE = 100
export const DEFAULT_QUICK_REACTIONS = ['❤️', '👍', '👎', '😂', '‼️', '❓']
// The text that reacts with `emoji` to a message (or takes that reaction
// back), worded the way iPhones send it, so iPhones and Google Messages show
// it as a reaction and everything else as "Loved “…”".
export function reactionText(emoji: string, msg: { body: string; media?: unknown[] }, removed = false): string {
const body = norm(msg.body)
const what = body
? `“${[...body].length > MAX_QUOTE ? [...body].slice(0, MAX_QUOTE).join('').trimEnd() + '…' : body}”`
: msg.media?.length
? 'an image'
: '“”'
const classic = SEND_VERBS[emoji.replace(/️/g, '')]
if (removed) return `Removed ${classic ? classic[1] : `a ${emoji}`} from ${what}`
return classic ? `${classic[0]} ${what}` : `Reacted ${emoji} to ${what}`
}
+1
View File
@@ -138,6 +138,7 @@ export interface Settings {
look?: Look // absent = travewave
hideMenuBar?: boolean // until Alt is tapped (design.html#menubar); absent = hidden
showTooltips?: boolean // design.html#tooltips; absent = shown
quickReactions?: string[] // a message's quick reaction row; absent = ❤️ 👍 👎 😂 ‼️ ❓
}
export interface Credentials {