diff --git a/src/main/notify.ts b/src/main/notify.ts index 5661688..fe146aa 100644 --- a/src/main/notify.ts +++ b/src/main/notify.ts @@ -5,6 +5,7 @@ import { formatNumber, groupMembers, isGroup } from '@shared/phone' import type { ContactDirectory } from './contacts' import type { MessageDb, NewMessage } from './db' import { reactionPreview } from '@shared/reactions' +import { editPreview } from '@shared/edits' // Only messages this recent notify: history imports bring in old ones. const RECENT = 10 * 60_000 @@ -44,6 +45,8 @@ export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did function preview(m: NewMessage): string { const reaction = reactionPreview(m.body) if (reaction) return reaction + const edit = editPreview(m.body) + if (edit) return edit const body = m.body.replace(/\s+/g, ' ').trim() if (body) return body return m.media?.length ? '📷 Photo' : '' diff --git a/src/main/sandbox.ts b/src/main/sandbox.ts index ab60c33..21a57e3 100644 --- a/src/main/sandbox.ts +++ b/src/main/sandbox.ts @@ -55,6 +55,9 @@ export function seedDemo(db: MessageDb): void { db.upsertMessages([ v('5415550110', 'in', 'Are we still on for Saturday?', 300), v('5415550110', 'out', 'Yep! 10am at the market', 290), + v('5415550110', 'in', 'Le encanta “Yep! 10am at the market”', 289), + v('5415550110', 'in', 'Can you grab coffee on the way', 288), + v('5415550110', 'in', 'Edited to “Can you grab coffee and bagels on the way?”', 286), v('5415550111', 'in', 'Your table is ready', 2000), g('5415550120', 'in', 'Package left at the front door', 90), g('5415550120', 'out', 'Thanks!', 85), diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 761e757..6d4d790 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -189,6 +189,8 @@ export function App() { version={msgVersion} smsDids={smsDids} onChangeDid={(did) => setSelected({ ...selected, did })} + quickReactions={state.settings.quickReactions} + onQuickReactions={(quickReactions) => void window.api.updateSettings({ ...state.settings, quickReactions }).then(refreshState)} /> ) : (
diff --git a/src/renderer/src/components/ChatView.tsx b/src/renderer/src/components/ChatView.tsx index 5010040..698fbaa 100644 --- a/src/renderer/src/components/ChatView.tsx +++ b/src/renderer/src/components/ChatView.tsx @@ -9,7 +9,9 @@ import { Composer, type ComposerHandle } from './Composer' import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons' import { Lightbox } from './Lightbox' import { MessageBubble } from './MessageBubble' -import { foldReactions, type Reaction } from '@shared/reactions' +import { DEFAULT_QUICK_REACTIONS, reactionText, sameEmoji, type Reaction } from '@shared/reactions' +import { foldConversation, type Version } from '@shared/edits' +import { EditHistory, EmojiPicker, ReactionBar } from './Reactions' import { Via } from './Via' import { useAddContact } from './AddContact' import { ContextMenu, type MenuItem } from './ContextMenu' @@ -52,9 +54,11 @@ interface Props { version: number smsDids: Did[] onChangeDid: (did: string) => void + quickReactions?: string[] // the row on a message's menu; absent = the iPhone six + onQuickReactions: (quick: string[]) => void } -export function ChatView({ conv, contact, contactMap, conversations, onOpen, name: ownName, onInfo, onExport, gvNumber, jump, highlight, version, smsDids, onChangeDid }: Props) { +export function ChatView({ conv, contact, contactMap, conversations, onOpen, name: ownName, onInfo, onExport, gvNumber, jump, highlight, version, smsDids, onChangeDid, quickReactions, onQuickReactions }: Props) { const name = convName(conv.contact, contactMap, ownName) const addContact = useAddContact() const [menu, setMenu] = useState<{ number: string; x: number; y: number }>() @@ -116,11 +120,52 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam return () => window.removeEventListener('focus', onFocus) }, [conv.did, conv.contact]) - // iPhone tapbacks ("Loved “…”") become reactions on the message they quote. - const folded = useMemo(() => foldReactions(messages ?? []), [messages]) + // iPhone tapbacks ("Loved “…”") become reactions on the message they + // quote, and "Edited to “…”" texts edit the message they're about. + const folded = useMemo(() => foldConversation(messages ?? []), [messages]) const rows = useMemo(() => buildRows(folded.shown), [folded]) const [reactionList, setReactionList] = useState<{ reactions: Reaction[]; x: number; y: number }>() const showReactions = useCallback((reactions: Reaction[], x: number, y: number) => setReactionList({ reactions, x, y }), []) + const [editList, setEditList] = useState<{ versions: Version[]; x: number; y: number }>() + const showEdits = useCallback((versions: Version[], x: number, y: number) => setEditList({ versions, x, y }), []) + + // ---- reacting ---- + const quick = quickReactions?.length ? quickReactions : DEFAULT_QUICK_REACTIONS + const [msgMenu, setMsgMenu] = useState<{ m: Message; x: number; y: number }>() + const [picker, setPicker] = useState<{ m: Message; x: number; y: number }>() + const showMsgMenu = useCallback((m: Message, e: React.MouseEvent) => { + // Right-clicking selected text keeps the selection (for Copy). + e.preventDefault() + setMsgMenu({ m, x: e.clientX, y: e.clientY }) + }, []) + const myReaction = (m: Message): string | undefined => folded.reactions.get(m.id)?.find((r) => r.from === 'me')?.emoji + // Sent as an ordinary text worded like an iPhone's ("Loved “…”"); the same + // emoji again takes it back. + const react = (m: Message, emoji: string): void => { + setMsgMenu(undefined) + setMediaMenu(undefined) + const removed = sameEmoji(myReaction(m), emoji) + void window.api.send(conv.did, conv.contact, reactionText(emoji, m, removed)).catch(() => undefined) + } + const reactionHeader = (m: Message, x: number, y: number) => + m.status === 'delivered' && (m.body.trim() || m.media?.length) ? ( + react(m, e)} + onMore={() => { + setMsgMenu(undefined) + setMediaMenu(undefined) + setPicker({ m, x, y }) + }} + /> + ) : undefined + const copyItems = (m: Message): MenuItem[] => { + const sel = window.getSelection()?.toString() ?? '' + if (!m.body) return [] + return [{ label: sel ? 'Copy' : 'Copy text', onSelect: () => void navigator.clipboard.writeText(sel || m.body) }] + } + const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows]) const flash = useCallback((id: number) => { @@ -200,6 +245,7 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam const [mediaMenu, setMediaMenu] = useState<{ id: number; index: number; x: number; y: number }>() const showMediaMenu = useCallback((id: number, index: number, e: React.MouseEvent) => { e.preventDefault() + e.stopPropagation() // not the message's menu as well setMediaMenu({ id, index, x: e.clientX, y: e.clientY }) }, []) // Images that arrive after layout grow the list; stay pinned to the newest. @@ -334,6 +380,9 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam onMediaLoad={onMediaLoad} reactions={folded.reactions.get(r.m.id)} onShowReactions={showReactions} + onMenu={showMsgMenu} + versions={folded.versions.get(r.m.id)} + onShowEdits={showEdits} /> ) } @@ -359,10 +408,33 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam { + const m = folded.shown.find((x) => x.id === mediaMenu.id) + return m && reactionHeader(m, mediaMenu.x, mediaMenu.y) + })()} items={imageMenuItems(mediaMenu.id, mediaMenu.index)} onClose={() => setMediaMenu(undefined)} /> )} + {msgMenu && (() => { + const header = reactionHeader(msgMenu.m, msgMenu.x, msgMenu.y) + const items = copyItems(msgMenu.m) + return header || items.length ? ( + setMsgMenu(undefined)} /> + ) : null + })()} + {picker && ( + react(picker.m, e)} + onQuickChange={onQuickReactions} + onClose={() => setPicker(undefined)} + /> + )} + {editList && setEditList(undefined)} />} {headerMenu && ( void }) { +// Something floating at (x, y), kept inside the window. Closes on any outside +// click, Escape, scrolling outside it, resize or the window losing focus. +export function Popover({ + x, + y, + onClose, + className, + role, + children +}: { + x: number + y: number + onClose: () => void + className: string + role?: string + children: ReactNode +}) { const ref = useRef(null) const [pos, setPos] = useState({ left: x, top: y }) + // Again whenever it changes size (the emoji picker grows when customizing). useLayoutEffect(() => { - const r = ref.current!.getBoundingClientRect() - setPos({ left: Math.min(x, window.innerWidth - r.width - 4), top: Math.min(y, window.innerHeight - r.height - 4) }) + const el = ref.current! + const place = (): void => { + const r = el.getBoundingClientRect() + const left = Math.max(4, Math.min(x, window.innerWidth - r.width - 4)) + const top = Math.max(4, Math.min(y, window.innerHeight - r.height - 4)) + setPos((p) => (p.left === left && p.top === top ? p : { left, top })) + } + place() + const ro = new ResizeObserver(place) + ro.observe(el) + return () => ro.disconnect() }, [x, y]) useEffect(() => { + const outside = (e: Event): boolean => !ref.current?.contains(e.target as Node) const onDown = (e: MouseEvent): void => { - if (!ref.current?.contains(e.target as Node)) onClose() + if (outside(e)) onClose() } const onKey = (e: KeyboardEvent): void => { if (e.key === 'Escape') onClose() } + const onWheel = (e: WheelEvent): void => { + if (outside(e)) onClose() + } window.addEventListener('mousedown', onDown, true) window.addEventListener('keydown', onKey) - window.addEventListener('wheel', onClose, { passive: true }) + window.addEventListener('wheel', onWheel, { passive: true }) window.addEventListener('resize', onClose) window.addEventListener('blur', onClose) return () => { window.removeEventListener('mousedown', onDown, true) window.removeEventListener('keydown', onKey) - window.removeEventListener('wheel', onClose) + window.removeEventListener('wheel', onWheel) window.removeEventListener('resize', onClose) window.removeEventListener('blur', onClose) } }, [onClose]) return ( -
e.preventDefault()}> +
e.preventDefault()}> + {children} +
+ ) +} + +// A small right-click menu at (x, y). `header` goes above the items (the +// quick reactions on a message's menu). +export function ContextMenu({ x, y, items, onClose, header }: { x: number; y: number; items: MenuItem[]; onClose: () => void; header?: ReactNode }) { + return ( + + {header} {items.map((it, i) => [ it.separator &&
, ])} -
+
) } diff --git a/src/renderer/src/components/MessageBubble.tsx b/src/renderer/src/components/MessageBubble.tsx index ab83757..d4f1d29 100644 --- a/src/renderer/src/components/MessageBubble.tsx +++ b/src/renderer/src/components/MessageBubble.tsx @@ -2,6 +2,7 @@ import { memo, useState, type ReactNode } from 'react' import { mediaKind } from '@shared/mime' import type { MediaRef, Message } from '@shared/types' import type { Reaction } from '@shared/reactions' +import type { Version } from '@shared/edits' import { highlightChunks, timeOfDay } from '../format' import { AlertIcon, ClockIcon } from './Icons' @@ -74,6 +75,9 @@ interface Props { onSenderMenu?: (e: React.MouseEvent) => void reactions?: Reaction[] onShowReactions?: (reactions: Reaction[], x: number, y: number) => void + onMenu?: (m: Message, e: React.MouseEvent) => void // right-click: react, copy + versions?: Version[] // edited: its texts, oldest first + onShowEdits?: (versions: Version[], x: number, y: number) => void groupStart: boolean groupEnd: boolean flash: boolean @@ -83,7 +87,7 @@ interface Props { onMediaLoad: () => void } -export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad }: Props) { +export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, onMenu, versions, onShowEdits, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad }: Props) { const media = m.media ?? [] const cls = [ 'msg', @@ -105,6 +109,7 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
onMenu(m, e))} > {media.length > 0 && (
@@ -120,6 +125,11 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe MMS )} + {versions && ( + + )} {timeOfDay(m.ts)} {m.status === 'pending' && ( diff --git a/src/renderer/src/components/Reactions.tsx b/src/renderer/src/components/Reactions.tsx new file mode 100644 index 0000000..ef8bb0f --- /dev/null +++ b/src/renderer/src/components/Reactions.tsx @@ -0,0 +1,182 @@ +// Reacting to a message, Signal-style: right-click a message for the quick +// row (yours sunk, click it again to take it back), + for every emoji, and +// "Customize" there to change the quick row. Plus "Edited": a message's +// earlier texts. +import { useMemo, useState } from "react"; +import { DEFAULT_QUICK_REACTIONS, sameEmoji } from "@shared/reactions"; +import type { Version } from "@shared/edits"; +import data from "../emoji-data.json"; +import { searchEmoji } from "../emoji"; +import { timeOfDay } from "../format"; +import { Popover } from "./ContextMenu"; + +const ALL = (data as [string, string[]][]).map(([char]) => char); + +export function ReactionBar({ + quick, + mine, + onReact, + onMore, +}: { + quick: string[]; + mine?: string; + onReact: (emoji: string) => void; + onMore: () => void; +}) { + return ( +
+ {quick.map((e) => ( + + ))} + +
+ ); +} + +export function EmojiPicker({ + x, + y, + quick, + mine, + onPick, + onQuickChange, + onClose, +}: { + x: number; + y: number; + quick: string[]; + mine?: string; + onPick: (emoji: string) => void; + onQuickChange: (quick: string[]) => void; + onClose: () => void; +}) { + const [q, setQ] = useState(""); + // Customizing: the slot in the quick row the next emoji goes into. + const [slot, setSlot] = useState(); + const list = useMemo( + () => (q.trim() ? searchEmoji(q.trim(), 300).map((m) => m.char) : ALL), + [q], + ); + const choose = (e: string): void => { + if (slot === undefined) { + onClose(); + onPick(e); + return; + } + const next = [...quick]; + // Already in the row: the two swap places. + const at = next.findIndex((x) => sameEmoji(x, e)); + if (at >= 0) next[at] = next[slot]; + next[slot] = e; + onQuickChange(next); + setSlot((slot + 1) % next.length); + }; + return ( + + {slot !== undefined && ( +
+
+ Click a spot, then the emoji for it. +
+
+ {quick.map((e, i) => ( + + ))} +
+
+ )} + setQ(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && list[0]) choose(list[0]); + }} + /> +
+ {list.map((e) => ( + + ))} + {!list.length && ( +
No emoji match.
+ )} +
+
+ {slot === undefined ? ( + + ) : ( + <> + + + + )} +
+
+ ); +} + +// A message's texts, newest first, like Signal's edit history. +export function EditHistory({ + x, + y, + versions, + onClose, +}: { + x: number; + y: number; + versions: Version[]; + onClose: () => void; +}) { + const day = (ts: number): string => + new Date(ts).toLocaleDateString(undefined, { + month: "short", + day: "numeric", + }); + return ( + +
Edit history
+ {[...versions].reverse().map((v, i, all) => ( +
+
+ {i === all.length - 1 ? "Original" : i === 0 ? "Now" : "Edited"} ·{" "} + {day(v.ts)} {timeOfDay(v.ts)} +
+
{v.body}
+
+ ))} +
+ ); +} diff --git a/src/renderer/src/format.ts b/src/renderer/src/format.ts index 4969b1e..0958297 100644 --- a/src/renderer/src/format.ts +++ b/src/renderer/src/format.ts @@ -1,6 +1,7 @@ import { mediaKind } from '@shared/mime' import { formatNumber, groupMembers, isGroup } from '@shared/phone' import { reactionPreview } from '@shared/reactions' +import { editPreview } from '@shared/edits' import type { ContactInfo, Conversation } from '@shared/types' const DAY = 86_400_000 @@ -52,6 +53,8 @@ const MEDIA_LABELS = { image: '📷 Photo', video: '🎥 Video', audio: '🎤 Au export function previewText(c: Pick): string { const reaction = reactionPreview(c.lastBody) if (reaction) return reaction + const edit = editPreview(c.lastBody) + if (edit) return edit const body = c.lastBody.replace(/\s+/g, ' ').trim() if (!c.lastMedia) return body const label = MEDIA_LABELS[mediaKind(c.lastMedia)] diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css index 02c206d..2781857 100644 --- a/src/renderer/src/styles.css +++ b/src/renderer/src/styles.css @@ -1314,6 +1314,151 @@ kbd { font-size: 11px; color: var(--muted); } + +/* ---------- reacting and edits (right-click a message; Reactions.tsx) ---------- */ +.reaction-bar { + display: flex; + gap: 2px; + padding: 2px 4px; +} +.context-menu .reaction-bar { + padding-bottom: 6px; + margin-bottom: 4px; + border-bottom: 1px solid var(--border); +} +.context-menu .reaction-bar:last-child { + margin-bottom: 0; + border-bottom: 0; +} +.reaction-bar .reaction-pick { + flex: none; + width: 34px; + height: 34px; + padding: 0; + border: 0; + border-radius: 999px; + background: transparent; + font-size: 20px; + line-height: 1; + display: flex; + align-items: center; + justify-content: center; +} +.reaction-bar .reaction-pick:hover { + background: var(--row-hover); +} +.reaction-bar .reaction-pick.on { + background: var(--row-active); +} +.reaction-bar .reaction-pick.more { + font-size: 17px; + color: var(--muted); +} +.emoji-picker, +.edit-history { + position: fixed; + z-index: 31; + padding: 8px; + background: var(--menu-bg); + border: 1px solid var(--border); + border-radius: 8px; + box-shadow: var(--shadow); +} +.emoji-picker { + width: 340px; + display: flex; + flex-direction: column; + gap: 6px; +} +.emoji-picker-search { + padding: 6px 8px; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--input-bg); + outline: none; +} +.emoji-grid { + display: grid; + grid-template-columns: repeat(9, 1fr); + align-content: start; + height: 260px; + overflow-y: auto; +} +.emoji-grid .emoji-cell { + height: 34px; + padding: 0; + border: 0; + border-radius: 6px; + background: transparent; + font-size: 22px; + line-height: 1; +} +.emoji-grid .emoji-cell:hover { + background: var(--row-hover); +} +.emoji-grid .emoji-cell.on { + background: var(--row-active); +} +.emoji-picker-hint { + grid-column: 1 / -1; + padding: 2px 4px; + font-size: 12px; + color: var(--muted); +} +.emoji-picker-custom { + padding-bottom: 6px; + border-bottom: 1px solid var(--border); +} +.emoji-picker-foot { + display: flex; + justify-content: flex-end; + gap: 6px; +} +.emoji-picker-foot button:not(.primary) { + padding: 5px 10px; + border: 1px solid var(--border); + border-radius: 6px; + background: transparent; +} +.emoji-picker-foot button.primary { + padding: 5px 14px; +} +.meta .edited { + padding: 0; + margin-right: 4px; + border: 0; + background: transparent; + font: inherit; + color: inherit; + text-decoration: underline; + text-underline-offset: 2px; +} +.edit-history { + width: 300px; + max-height: 380px; + overflow-y: auto; + user-select: text; +} +.edit-history-title { + font-weight: 600; + padding: 0 2px 6px; +} +.edit-version { + padding: 6px 2px; + border-top: 1px solid var(--border); +} +.edit-version-when { + font-size: 12px; + color: var(--muted); + margin-bottom: 2px; +} +.edit-version-text { + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.edit-version:not(.current) .edit-version-text { + color: var(--muted); +} .group-row-icon { flex: none; width: calc(40px * var(--s, 1)); @@ -3501,6 +3646,67 @@ label.check { margin: 4px 0; } +/* ---------- reacting and edits: flat until hovered, yours sunk (#clickable, #toggles) ---------- */ +.context-menu .reaction-bar { + padding: 2px 6px 6px; + border-bottom-color: var(--frame); +} +.reaction-bar .reaction-pick, +.emoji-grid .emoji-cell { + border: 1px solid transparent; + border-radius: 4px; +} +.reaction-bar .reaction-pick:hover, +.emoji-grid .emoji-cell:hover { + background: var(--btn-hover); + border-color: var(--btn-edge); + border-bottom-color: var(--btn-edge2); +} +.reaction-bar .reaction-pick:active, +.emoji-grid .emoji-cell:active { + background: var(--btn-down); + border-color: var(--btn-down-edge); + border-top-color: var(--btn-down-edge2); +} +.reaction-bar .reaction-pick.on, +.emoji-grid .emoji-cell.on { + background: var(--btn-chosen); + border-color: var(--btn-chosen-edge); + border-top-color: var(--btn-chosen-edge2); +} +.reaction-bar .reaction-pick.more { + color: var(--glyph); +} +.emoji-picker, +.edit-history { + background: var(--list); + border-color: var(--frame); +} +.emoji-picker-search { + border-color: var(--input-edge); + border-radius: 4px; +} +.emoji-picker-custom, +.edit-version { + border-color: var(--frame); +} +.emoji-picker-foot button:not(.primary) { + background: var(--btn); + border: 1px solid var(--btn-edge); + border-bottom-color: var(--btn-edge2); + border-radius: 4px; + padding: 3px 12px; + min-height: 28px; +} +.emoji-picker-foot button:not(.primary):hover { + background: var(--btn-hover); +} +.emoji-picker-foot button:not(.primary):active { + background: var(--btn-down); + border-color: var(--btn-down-edge); + border-top-color: var(--btn-down-edge2); +} + /* ---------- scrollbars: no arrows, the thumb is a button (#scrollbars) ---------- */ ::-webkit-scrollbar { width: 14px; diff --git a/src/shared/edits.ts b/src/shared/edits.ts new file mode 100644 index 0000000..e15de74 --- /dev/null +++ b/src/shared/edits.ts @@ -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( + msgs: T[], +): { shown: T[]; versions: Map } { + const hidden = new Set(); + const current = new Map(); + const versions = new Map(); + 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( + msgs: T[], +): { + shown: T[]; + reactions: Map; + versions: Map; +} { + 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 }; +} diff --git a/src/shared/reactions.ts b/src/shared/reactions.ts index 5a6ab0a..e5dbdb4 100644 --- a/src/shared/reactions.ts +++ b/src/shared/reactions.ts @@ -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 = { loved: '❤️', @@ -24,9 +30,11 @@ const REMOVED: Record = { '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(`(? 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(msgs: T[]): { shown: T[]; reactions: Map } { +// theirs, a "Removed …" takes it away. `earlier` holds an edited message's +// older texts, which a reaction may still quote. +export function foldReactions(msgs: T[], earlier?: Map): { shown: T[]; reactions: Map } { const hidden = new Set() const byTarget = new Map>() + 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() 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(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 = { + '❤': ['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}` +} diff --git a/src/shared/types.ts b/src/shared/types.ts index 7256a54..994ce4d 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -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 { diff --git a/test/edits.test.ts b/test/edits.test.ts new file mode 100644 index 0000000..9ec29b1 --- /dev/null +++ b/test/edits.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; +import { + editPreview, + foldConversation, + foldEdits, + likeness, + parseEdit, +} from "@shared/edits"; + +const MIN = 60_000; +let nextId = 1; +const msg = ( + body: string, + min: number, + opts: { out?: boolean; sender?: string } = {}, +) => ({ + id: nextId++, + body, + ts: 1_700_000_000_000 + min * MIN, + direction: (opts.out ? "out" : "in") as "in" | "out", + contact: "5550001111", + ...(opts.sender ? { sender: opts.sender } : {}), +}); + +describe("parseEdit", () => { + it("reads the new text", () => { + expect(parseEdit("Edited to “see you at 9:30”")).toBe("see you at 9:30"); + expect(parseEdit('Edited to "ok"')).toBe("ok"); + expect(parseEdit("Editado a “nos vemos”")).toBe("nos vemos"); + expect(parseEdit("Edited the plan")).toBeNull(); + expect(editPreview("Edited to “see you”")).toBe("✏️ see you"); + }); + it("likeness", () => { + expect(likeness("abc", "abc")).toBe(1); + expect(likeness("see you at 9", "see you at 9:30")).toBeGreaterThan(0.7); + }); +}); + +describe("foldEdits", () => { + it("applies a small edit and keeps the history", () => { + const a = msg("see you at 9", 0); + const b = msg("sounds good", 1, { out: true }); + const e = msg("Edited to “see you at 9:30”", 3); + const { shown, versions } = foldEdits([a, b, e]); + expect(shown.map((m) => m.body)).toEqual([ + "see you at 9:30", + "sounds good", + ]); + expect(versions.get(a.id)?.map((v) => v.body)).toEqual([ + "see you at 9", + "see you at 9:30", + ]); + }); + + it("chains edits and picks the most alike of several", () => { + const a = msg("grab milk", 0); + const b = msg("and the dog food from the shelf", 1); + const e1 = msg("Edited to “and the cat food from the shelf”", 2); + const e2 = msg("Edited to “and the cat food from the top shelf”", 4); + const { shown, versions } = foldEdits([a, b, e1, e2]); + expect(shown.map((m) => m.body)).toEqual([ + "grab milk", + "and the cat food from the top shelf", + ]); + expect(versions.get(b.id)?.length).toBe(3); + }); + + it("takes a big change when theirs is the only message in the window", () => { + const a = msg("yes", 0); + const e = msg("Edited to “actually no, sorry”", 2); + expect(foldEdits([a, e]).shown.map((m) => m.body)).toEqual([ + "actually no, sorry", + ]); + }); + + it("leaves it when it can't tell", () => { + const a = msg("pizza tonight?", 0); + const b = msg("or tacos", 1); + const e = msg("Edited to “never mind, I am busy”", 2); + expect(foldEdits([a, b, e]).shown).toHaveLength(3); + // someone else's message is never the one edited + const c = msg("hello there", 0, { out: true }); + const f = msg("Edited to “hello there!”", 1); + expect(foldEdits([c, f]).shown).toHaveLength(2); + }); + + it("reactions to the old text still land", () => { + const a = msg("see you at 9", 0); + const r = msg("Loved “see you at 9”", 1, { out: true }); + const e = msg("Edited to “see you at 9:30”", 2); + const { shown, reactions } = foldConversation([a, r, e]); + expect(shown.map((m) => m.body)).toEqual(["see you at 9:30"]); + expect(reactions.get(a.id)?.[0].emoji).toBe("❤️"); + }); +}); diff --git a/test/reactions.test.ts b/test/reactions.test.ts index 78b7ab4..2ee835e 100644 --- a/test/reactions.test.ts +++ b/test/reactions.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { foldReactions, parseReaction, reactionPreview } from '@shared/reactions' +import { foldReactions, parseReaction, parseReactions, reactionPreview, reactionText, sameEmoji } from '@shared/reactions' let nextId = 1 const msg = (body: string, opts: { out?: boolean; sender?: string; media?: boolean; ts?: number } = {}) => ({ @@ -97,3 +97,99 @@ describe('reactionPreview', () => { expect(reactionPreview('just text')).toBeNull() }) }) + +describe('other languages', () => { + const emoji = (body: string) => parseReaction(body)?.emoji + it('reads Spanish, Portuguese, French, German, Italian tapbacks', () => { + expect(emoji('Le encanta “nos vemos”')).toBe('❤️') + expect(emoji('Le encantó “nos vemos”')).toBe('❤️') + expect(emoji('Le gusta “nos vemos”')).toBe('👍') + expect(emoji('No le gustó “nos vemos”')).toBe('👎') + expect(emoji('Le hace gracia “nos vemos”')).toBe('😂') + expect(emoji('Se rió de “nos vemos”')).toBe('😂') + expect(emoji('Enfatizó “nos vemos”')).toBe('‼️') + expect(emoji('Cuestionó “nos vemos”')).toBe('❓') + expect(emoji('Reaccionó con 🎉 a “nos vemos”')).toBe('🎉') + expect(emoji('Amou “até já”')).toBe('❤️') + expect(emoji('Curtiu “até já”')).toBe('👍') + expect(emoji('Não curtiu “até já”')).toBe('👎') + expect(emoji('Riu de “até já”')).toBe('😂') + expect(emoji('A adoré « à plus »')).toBe('❤️') + expect(emoji('A aimé « à plus »')).toBe('👍') + expect(emoji('N’a pas aimé « à plus »')).toBe('👎') + expect(parseReaction('A aimé « à plus »')?.target).toEqual({ text: 'à plus' }) + expect(emoji('Hat „bis dann“ geliebt')).toBe('❤️') + expect(emoji('Hat über „bis dann“ gelacht')).toBe('😂') + expect(emoji('Gefällt „bis dann“ nicht')).toBe('👎') + expect(emoji('Ha messo Mi piace a “a dopo”')).toBe('👍') + expect(emoji('Le encantó una imagen')).toBe('❤️') + expect(parseReaction('Le encantó una imagen')?.target).toEqual({ media: true }) + }) + + it('reads removals, even with the reaction quoted too', () => { + const r = parseReactions('Quitó un “me gusta” de “nos vemos”') + expect(r.some((x) => x.removed && x.emoji === '👍' && 'text' in x.target && x.target.text === 'nos vemos')).toBe(true) + expect(parseReaction('Quitó un corazón de “nos vemos”')).toMatchObject({ emoji: '❤️', removed: true }) + }) + + it('leaves people writing alone', () => { + expect(parseReaction('Me encanta “Bad Bunny”')).toBeNull() + expect(parseReaction('I love “Bad Bunny”')).toBeNull() + expect(parseReaction('Mi canción favorita es “Despacito”, ¿y la tuya?')).toBeNull() + expect(parseReaction('nos vemos')).toBeNull() + }) + + it('folds only onto a message it quotes', () => { + const a = msg('nos vemos a las 9', { out: true }) + const b = msg('Le encanta “nos vemos a las 9”', { sender: '5550001111' }) + const c = msg('Le encanta “Bad Bunny”', { sender: '5550002222' }) + const { shown, reactions } = foldReactions([a, b, c]) + expect(shown).toEqual([a, c]) + expect(reactions.get(a.id)?.[0].emoji).toBe('❤️') + }) + + it('keeps a failed reaction in view', () => { + const a = msg('hi') + const r = { ...msg('Loved “hi”', { out: true }), status: 'failed' } + expect(foldReactions([a, r]).shown).toEqual([a, r]) + }) + + it('shows loose readings in previews only once placed', () => { + expect(reactionPreview('Le encanta “nos vemos”')).toBeNull() + }) +}) + +describe('reactionText', () => { + it('words a reaction like an iPhone', () => { + expect(reactionText('❤️', { body: 'see you at 9' })).toBe('Loved “see you at 9”') + expect(reactionText('❤', { body: 'x' })).toBe('Loved “x”') + expect(reactionText('😂', { body: 'lol' })).toBe('Laughed at “lol”') + expect(reactionText('🎉', { body: 'we won' })).toBe('Reacted 🎉 to “we won”') + expect(reactionText('👍', { body: '', media: [{}] })).toBe('Liked an image') + expect(reactionText('❤️', { body: 'hi' }, true)).toBe('Removed a heart from “hi”') + expect(reactionText('🎉', { body: 'hi' }, true)).toBe('Removed a 🎉 from “hi”') + }) + + it('round-trips through the parser, long messages cut short', () => { + const long = 'word '.repeat(60).trim() + for (const e of ['❤️', '👍', '👎', '😂', '‼️', '❓', '🎉', '👨‍👩‍👧']) { + for (const removed of [false, true]) { + const a = msg(long) + const r = msg(reactionText(e, a, removed), { out: true }) + const p = parseReaction(r.body) + expect(p?.removed).toBe(removed) + expect(sameEmoji(p?.emoji, e)).toBe(true) + if (!removed) expect(foldReactions([a, r]).reactions.get(a.id)?.[0].emoji).toBe(p?.emoji) + } + } + }) + + it('a second reaction replaces mine; the same one again takes it back', () => { + const a = msg('dinner?') + const r1 = msg(reactionText('👍', a), { out: true }) + const r2 = msg(reactionText('❤️', a), { out: true }) + expect(foldReactions([a, r1, r2]).reactions.get(a.id)?.map((r) => r.emoji)).toEqual(['❤️']) + const r3 = msg(reactionText('❤️', a, true), { out: true }) + expect(foldReactions([a, r1, r2, r3]).reactions.has(a.id)).toBe(false) + }) +})