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 a2d8f7761e
commit fcabae81e5
14 changed files with 1046 additions and 35 deletions
+3
View File
@@ -5,6 +5,7 @@ import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import type { ContactDirectory } from './contacts' import type { ContactDirectory } from './contacts'
import type { MessageDb, NewMessage } from './db' import type { MessageDb, NewMessage } from './db'
import { reactionPreview } from '@shared/reactions' import { reactionPreview } from '@shared/reactions'
import { editPreview } from '@shared/edits'
// Only messages this recent notify: history imports bring in old ones. // Only messages this recent notify: history imports bring in old ones.
const RECENT = 10 * 60_000 const RECENT = 10 * 60_000
@@ -44,6 +45,8 @@ export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did
function preview(m: NewMessage): string { function preview(m: NewMessage): string {
const reaction = reactionPreview(m.body) const reaction = reactionPreview(m.body)
if (reaction) return reaction if (reaction) return reaction
const edit = editPreview(m.body)
if (edit) return edit
const body = m.body.replace(/\s+/g, ' ').trim() const body = m.body.replace(/\s+/g, ' ').trim()
if (body) return body if (body) return body
return m.media?.length ? '📷 Photo' : '' return m.media?.length ? '📷 Photo' : ''
+3
View File
@@ -55,6 +55,9 @@ export function seedDemo(db: MessageDb): void {
db.upsertMessages([ db.upsertMessages([
v('5415550110', 'in', 'Are we still on for Saturday?', 300), v('5415550110', 'in', 'Are we still on for Saturday?', 300),
v('5415550110', 'out', 'Yep! 10am at the market', 290), 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), v('5415550111', 'in', 'Your table is ready', 2000),
g('5415550120', 'in', 'Package left at the front door', 90), g('5415550120', 'in', 'Package left at the front door', 90),
g('5415550120', 'out', 'Thanks!', 85), g('5415550120', 'out', 'Thanks!', 85),
+2
View File
@@ -189,6 +189,8 @@ export function App() {
version={msgVersion} version={msgVersion}
smsDids={smsDids} smsDids={smsDids}
onChangeDid={(did) => setSelected({ ...selected, did })} onChangeDid={(did) => setSelected({ ...selected, did })}
quickReactions={state.settings.quickReactions}
onQuickReactions={(quickReactions) => void window.api.updateSettings({ ...state.settings, quickReactions }).then(refreshState)}
/> />
) : ( ) : (
<main className="chat empty"> <main className="chat empty">
+76 -4
View File
@@ -9,7 +9,9 @@ import { Composer, type ComposerHandle } from './Composer'
import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons' import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons'
import { Lightbox } from './Lightbox' import { Lightbox } from './Lightbox'
import { MessageBubble } from './MessageBubble' 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 { Via } from './Via'
import { useAddContact } from './AddContact' import { useAddContact } from './AddContact'
import { ContextMenu, type MenuItem } from './ContextMenu' import { ContextMenu, type MenuItem } from './ContextMenu'
@@ -52,9 +54,11 @@ interface Props {
version: number version: number
smsDids: Did[] smsDids: Did[]
onChangeDid: (did: string) => void 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 name = convName(conv.contact, contactMap, ownName)
const addContact = useAddContact() const addContact = useAddContact()
const [menu, setMenu] = useState<{ number: string; x: number; y: number }>() 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) return () => window.removeEventListener('focus', onFocus)
}, [conv.did, conv.contact]) }, [conv.did, conv.contact])
// iPhone tapbacks ("Loved “…”") become reactions on the message they quote. // iPhone tapbacks ("Loved “…”") become reactions on the message they
const folded = useMemo(() => foldReactions(messages ?? []), [messages]) // 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 rows = useMemo(() => buildRows(folded.shown), [folded])
const [reactionList, setReactionList] = useState<{ reactions: Reaction[]; x: number; y: number }>() const [reactionList, setReactionList] = useState<{ reactions: Reaction[]; x: number; y: number }>()
const showReactions = useCallback((reactions: Reaction[], x: number, y: number) => setReactionList({ reactions, x, y }), []) 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) ? (
<ReactionBar
quick={quick}
mine={myReaction(m)}
onReact={(e) => 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 indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows])
const flash = useCallback((id: number) => { 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 [mediaMenu, setMediaMenu] = useState<{ id: number; index: number; x: number; y: number }>()
const showMediaMenu = useCallback((id: number, index: number, e: React.MouseEvent) => { const showMediaMenu = useCallback((id: number, index: number, e: React.MouseEvent) => {
e.preventDefault() e.preventDefault()
e.stopPropagation() // not the message's menu as well
setMediaMenu({ id, index, x: e.clientX, y: e.clientY }) setMediaMenu({ id, index, x: e.clientX, y: e.clientY })
}, []) }, [])
// Images that arrive after layout grow the list; stay pinned to the newest. // 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} onMediaLoad={onMediaLoad}
reactions={folded.reactions.get(r.m.id)} reactions={folded.reactions.get(r.m.id)}
onShowReactions={showReactions} 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
<ContextMenu <ContextMenu
x={mediaMenu.x} x={mediaMenu.x}
y={mediaMenu.y} y={mediaMenu.y}
header={(() => {
const m = folded.shown.find((x) => x.id === mediaMenu.id)
return m && reactionHeader(m, mediaMenu.x, mediaMenu.y)
})()}
items={imageMenuItems(mediaMenu.id, mediaMenu.index)} items={imageMenuItems(mediaMenu.id, mediaMenu.index)}
onClose={() => setMediaMenu(undefined)} onClose={() => setMediaMenu(undefined)}
/> />
)} )}
{msgMenu && (() => {
const header = reactionHeader(msgMenu.m, msgMenu.x, msgMenu.y)
const items = copyItems(msgMenu.m)
return header || items.length ? (
<ContextMenu x={msgMenu.x} y={msgMenu.y} header={header} items={items} onClose={() => setMsgMenu(undefined)} />
) : null
})()}
{picker && (
<EmojiPicker
x={picker.x}
y={picker.y}
quick={quick}
mine={myReaction(picker.m)}
onPick={(e) => react(picker.m, e)}
onQuickChange={onQuickReactions}
onClose={() => setPicker(undefined)}
/>
)}
{editList && <EditHistory {...editList} onClose={() => setEditList(undefined)} />}
{headerMenu && ( {headerMenu && (
<ContextMenu <ContextMenu
x={headerMenu.x} x={headerMenu.x}
+50 -11
View File
@@ -1,4 +1,4 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react' import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'
export interface MenuItem { export interface MenuItem {
label: string label: string
@@ -8,40 +8,79 @@ export interface MenuItem {
shortcut?: string // shown on the right (the menu bar's menus) shortcut?: string // shown on the right (the menu bar's menus)
} }
// A small right-click menu at (x, y), kept inside the window. Closes on any // Something floating at (x, y), kept inside the window. Closes on any outside
// outside click, Escape, scroll, resize or the window losing focus. // click, Escape, scrolling outside it, resize or the window losing focus.
export function ContextMenu({ x, y, items, onClose }: { x: number; y: number; items: MenuItem[]; onClose: () => void }) { export function Popover({
x,
y,
onClose,
className,
role,
children
}: {
x: number
y: number
onClose: () => void
className: string
role?: string
children: ReactNode
}) {
const ref = useRef<HTMLDivElement>(null) const ref = useRef<HTMLDivElement>(null)
const [pos, setPos] = useState({ left: x, top: y }) const [pos, setPos] = useState({ left: x, top: y })
// Again whenever it changes size (the emoji picker grows when customizing).
useLayoutEffect(() => { useLayoutEffect(() => {
const r = ref.current!.getBoundingClientRect() const el = ref.current!
setPos({ left: Math.min(x, window.innerWidth - r.width - 4), top: Math.min(y, window.innerHeight - r.height - 4) }) 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]) }, [x, y])
useEffect(() => { useEffect(() => {
const outside = (e: Event): boolean => !ref.current?.contains(e.target as Node)
const onDown = (e: MouseEvent): void => { const onDown = (e: MouseEvent): void => {
if (!ref.current?.contains(e.target as Node)) onClose() if (outside(e)) onClose()
} }
const onKey = (e: KeyboardEvent): void => { const onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape') onClose() if (e.key === 'Escape') onClose()
} }
const onWheel = (e: WheelEvent): void => {
if (outside(e)) onClose()
}
window.addEventListener('mousedown', onDown, true) window.addEventListener('mousedown', onDown, true)
window.addEventListener('keydown', onKey) window.addEventListener('keydown', onKey)
window.addEventListener('wheel', onClose, { passive: true }) window.addEventListener('wheel', onWheel, { passive: true })
window.addEventListener('resize', onClose) window.addEventListener('resize', onClose)
window.addEventListener('blur', onClose) window.addEventListener('blur', onClose)
return () => { return () => {
window.removeEventListener('mousedown', onDown, true) window.removeEventListener('mousedown', onDown, true)
window.removeEventListener('keydown', onKey) window.removeEventListener('keydown', onKey)
window.removeEventListener('wheel', onClose) window.removeEventListener('wheel', onWheel)
window.removeEventListener('resize', onClose) window.removeEventListener('resize', onClose)
window.removeEventListener('blur', onClose) window.removeEventListener('blur', onClose)
} }
}, [onClose]) }, [onClose])
return ( return (
<div ref={ref} className="context-menu" role="menu" style={pos} onContextMenu={(e) => e.preventDefault()}> <div ref={ref} className={className} role={role} style={pos} onContextMenu={(e) => e.preventDefault()}>
{children}
</div>
)
}
// 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 (
<Popover x={x} y={y} onClose={onClose} className="context-menu" role="menu">
{header}
{items.map((it, i) => [ {items.map((it, i) => [
it.separator && <div key={`sep${i}`} className="menu-sep" />, it.separator && <div key={`sep${i}`} className="menu-sep" />,
<button <button
@@ -57,6 +96,6 @@ export function ContextMenu({ x, y, items, onClose }: { x: number; y: number; it
{it.shortcut && <span className="menu-shortcut">{it.shortcut}</span>} {it.shortcut && <span className="menu-shortcut">{it.shortcut}</span>}
</button> </button>
])} ])}
</div> </Popover>
) )
} }
+11 -1
View File
@@ -2,6 +2,7 @@ import { memo, useState, type ReactNode } from 'react'
import { mediaKind } from '@shared/mime' import { mediaKind } from '@shared/mime'
import type { MediaRef, Message } from '@shared/types' import type { MediaRef, Message } from '@shared/types'
import type { Reaction } from '@shared/reactions' import type { Reaction } from '@shared/reactions'
import type { Version } from '@shared/edits'
import { highlightChunks, timeOfDay } from '../format' import { highlightChunks, timeOfDay } from '../format'
import { AlertIcon, ClockIcon } from './Icons' import { AlertIcon, ClockIcon } from './Icons'
@@ -74,6 +75,9 @@ interface Props {
onSenderMenu?: (e: React.MouseEvent) => void onSenderMenu?: (e: React.MouseEvent) => void
reactions?: Reaction[] reactions?: Reaction[]
onShowReactions?: (reactions: Reaction[], x: number, y: number) => void 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 groupStart: boolean
groupEnd: boolean groupEnd: boolean
flash: boolean flash: boolean
@@ -83,7 +87,7 @@ interface Props {
onMediaLoad: () => void 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 media = m.media ?? []
const cls = [ const cls = [
'msg', 'msg',
@@ -105,6 +109,7 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
<div <div
className={`bubble${media.length ? ' has-media' : ''}${media.length && !m.body ? ' media-only' : ''}`} className={`bubble${media.length ? ' has-media' : ''}${media.length && !m.body ? ' media-only' : ''}`}
title={new Date(m.ts).toLocaleString()} title={new Date(m.ts).toLocaleString()}
onContextMenu={onMenu && ((e) => onMenu(m, e))}
> >
{media.length > 0 && ( {media.length > 0 && (
<div className="media"> <div className="media">
@@ -120,6 +125,11 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
MMS MMS
</span> </span>
)} )}
{versions && (
<button className="edited" title="See what changed" onClick={(e) => onShowEdits?.(versions, e.clientX, e.clientY)}>
Edited
</button>
)}
{timeOfDay(m.ts)} {timeOfDay(m.ts)}
{m.status === 'pending' && ( {m.status === 'pending' && (
<span className="status" title="Sending…"> <span className="status" title="Sending…">
+182
View File
@@ -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 (
<div className="reaction-bar">
{quick.map((e) => (
<button
key={e}
className={`reaction-pick${sameEmoji(mine, e) ? " on" : ""}`}
title={sameEmoji(mine, e) ? "Take back your reaction" : undefined}
onClick={() => onReact(e)}
>
{e}
</button>
))}
<button
className="reaction-pick more"
title="More emoji…"
onClick={onMore}
>
+
</button>
</div>
);
}
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<number>();
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 (
<Popover x={x} y={y} onClose={onClose} className="emoji-picker">
{slot !== undefined && (
<div className="emoji-picker-custom">
<div className="emoji-picker-hint">
Click a spot, then the emoji for it.
</div>
<div className="reaction-bar">
{quick.map((e, i) => (
<button
key={i}
className={`reaction-pick${i === slot ? " on" : ""}`}
onClick={() => setSlot(i)}
>
{e}
</button>
))}
</div>
</div>
)}
<input
className="emoji-picker-search"
autoFocus
value={q}
placeholder="Search emoji"
onChange={(e) => setQ(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && list[0]) choose(list[0]);
}}
/>
<div className="emoji-grid">
{list.map((e) => (
<button
key={e}
className={`emoji-cell${
slot === undefined && sameEmoji(mine, e) ? " on" : ""
}`}
onClick={() => choose(e)}
>
{e}
</button>
))}
{!list.length && (
<div className="emoji-picker-hint">No emoji match.</div>
)}
</div>
<footer className="emoji-picker-foot">
{slot === undefined ? (
<button onClick={() => setSlot(0)}>Customize quick reactions…</button>
) : (
<>
<button onClick={() => onQuickChange([...DEFAULT_QUICK_REACTIONS])}>
Reset
</button>
<button className="primary" onClick={() => setSlot(undefined)}>
Done
</button>
</>
)}
</footer>
</Popover>
);
}
// 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 (
<Popover x={x} y={y} onClose={onClose} className="edit-history">
<div className="edit-history-title">Edit history</div>
{[...versions].reverse().map((v, i, all) => (
<div key={i} className={`edit-version${i === 0 ? " current" : ""}`}>
<div className="edit-version-when">
{i === all.length - 1 ? "Original" : i === 0 ? "Now" : "Edited"} ·{" "}
{day(v.ts)} {timeOfDay(v.ts)}
</div>
<div className="edit-version-text">{v.body}</div>
</div>
))}
</Popover>
);
}
+3
View File
@@ -1,6 +1,7 @@
import { mediaKind } from '@shared/mime' import { mediaKind } from '@shared/mime'
import { formatNumber, groupMembers, isGroup } from '@shared/phone' import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import { reactionPreview } from '@shared/reactions' import { reactionPreview } from '@shared/reactions'
import { editPreview } from '@shared/edits'
import type { ContactInfo, Conversation } from '@shared/types' import type { ContactInfo, Conversation } from '@shared/types'
const DAY = 86_400_000 const DAY = 86_400_000
@@ -52,6 +53,8 @@ const MEDIA_LABELS = { image: '📷 Photo', video: '🎥 Video', audio: '🎤 Au
export function previewText(c: Pick<Conversation, 'lastBody' | 'lastMedia'>): string { export function previewText(c: Pick<Conversation, 'lastBody' | 'lastMedia'>): string {
const reaction = reactionPreview(c.lastBody) const reaction = reactionPreview(c.lastBody)
if (reaction) return reaction if (reaction) return reaction
const edit = editPreview(c.lastBody)
if (edit) return edit
const body = c.lastBody.replace(/\s+/g, ' ').trim() const body = c.lastBody.replace(/\s+/g, ' ').trim()
if (!c.lastMedia) return body if (!c.lastMedia) return body
const label = MEDIA_LABELS[mediaKind(c.lastMedia)] const label = MEDIA_LABELS[mediaKind(c.lastMedia)]
+206
View File
@@ -1314,6 +1314,151 @@ kbd {
font-size: 11px; font-size: 11px;
color: var(--muted); 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 { .group-row-icon {
flex: none; flex: none;
width: calc(40px * var(--s, 1)); width: calc(40px * var(--s, 1));
@@ -3501,6 +3646,67 @@ label.check {
margin: 4px 0; 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) ---------- */ /* ---------- scrollbars: no arrows, the thumb is a button (#scrollbars) ---------- */
::-webkit-scrollbar { ::-webkit-scrollbar {
width: 14px; width: 14px;
+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 };
}
+144 -16
View File
@@ -1,9 +1,15 @@
// iMessage "tapbacks" sent to non-iPhones arrive as plain texts: // iMessage "tapbacks" sent to non-iPhones arrive as plain texts:
// Loved “see you at 9” Laughed at “lol” Reacted 🎉 to “we won” // Loved “see you at 9” Laughed at “lol” Reacted 🎉 to “we won”
// Removed a heart from “see you at 9” Liked an image // 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 // We fold them into emoji reactions on the message they quote (found by
// searching back through the conversation), the way Signal shows reactions. // searching back through the conversation), the way Signal shows reactions.
// A reaction whose message can't be found stays an ordinary message. // 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> = { const VERBS: Record<string, string> = {
loved: '❤️', loved: '❤️',
@@ -24,9 +30,11 @@ const REMOVED: Record<string, string> = {
'a question mark': '❓' 'a question mark': '❓'
} }
// Quotes come curly from iPhones, sometimes straight. // Quotes come curly from iPhones, sometimes straight; «» and „“ elsewhere.
const Q_OPEN = '[“"”]' const Q_OPEN = '[“"”]'
const Q_CLOSE = '[”"“]' const Q_CLOSE = '[”"“]'
const OPENS = '“"”«„‚‘「『'
const CLOSES = '”"“»«‘’」』'
const MEDIA = /^(?:an? )?(?:image|photo|picture|movie|video|attachment|audio message|gif|sticker)$/i const MEDIA = /^(?:an? )?(?:image|photo|picture|movie|video|attachment|audio message|gif|sticker)$/i
export interface ParsedReaction { export interface ParsedReaction {
@@ -34,6 +42,7 @@ export interface ParsedReaction {
removed: boolean removed: boolean
// The quoted text, or `media` for "Loved an image" and the like. // The quoted text, or `media` for "Loved an image" and the like.
target: { text: string } | { media: true } 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}|(.+))$`) 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 return null
} }
export function parseReaction(body: string): ParsedReaction | null { function strict(s: string): ParsedReaction | null {
const s = body.trim()
let m = VERB.exec(s) let m = VERB.exec(s)
if (m) { if (m) {
const t = target(m[2], m[3]) const t = target(m[2], m[3])
return t && { emoji: VERBS[m[1].toLowerCase()], removed: false, target: t } return t && { emoji: VERBS[m[1].toLowerCase()], removed: false, target: t }
} }
m = REACTED.exec(s) m = REACTED.exec(s)
if (m && [...m[1]].length <= 4) { if (m && [...m[1]].length <= 8) {
const t = target(m[2], m[3]) const t = target(m[2], m[3])
return t && { emoji: m[1], removed: false, target: t } return t && { emoji: m[1], removed: false, target: t }
} }
@@ -62,13 +70,84 @@ export function parseReaction(body: string): ParsedReaction | null {
if (m) { if (m) {
const kind = m[1].toLowerCase() const kind = m[1].toLowerCase()
// "Removed a 😂 from …" (newer iOS) names the emoji itself. // "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]) const t = target(m[2], m[3])
return emoji && t ? { emoji, removed: true, target: t } : null return emoji && t ? { emoji, removed: true, target: t } : null
} }
return 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 { export interface Reaction {
emoji: string emoji: string
from: string // the reactor's number, or 'me' from: string // the reactor's number, or 'me'
@@ -82,11 +161,12 @@ interface Foldable {
direction: 'in' | 'out' direction: 'in' | 'out'
contact: string contact: string
sender?: string sender?: string
status?: string
media?: unknown[] media?: unknown[]
} }
// Phones swap straight and curly apostrophes, so compare without the difference. // 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 { function matches(body: string, quoted: string): boolean {
const b = norm(body) 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 // 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 // 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 // person keeps one reaction per message, like iMessage: a newer one replaces
// theirs, a "Removed …" takes it away. // theirs, a "Removed …" takes it away. `earlier` holds an edited message's
export function foldReactions<T extends Foldable>(msgs: T[]): { shown: T[]; reactions: Map<number, Reaction[]> } { // 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 hidden = new Set<number>()
const byTarget = new Map<number, Map<string, Reaction>>() 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) => { msgs.forEach((m, i) => {
const r = parseReaction(m.body) // One that didn't go out stays in view, with its Retry.
if (!r) return if (m.status === 'failed') return
const readings = parseReactions(m.body)
let found: T | undefined let found: T | undefined
let r: ParsedReaction | undefined
for (const reading of readings) {
for (let j = i - 1; j >= 0 && !found; j--) { for (let j = i - 1; j >= 0 && !found; j--) {
const c = msgs[j] const c = msgs[j]
if (hidden.has(c.id) || parseReaction(c.body)) continue if (hidden.has(c.id) || strict(c.body.trim())) continue
if ('media' in r.target ? !!c.media?.length : matches(c.body, r.target.text)) found = c if ('media' in reading.target ? !!c.media?.length : quotes(c, reading.target.text)) found = c
} }
if (!found) return if (found) {
r = reading
break
}
}
if (!found || !r) return
hidden.add(m.id) hidden.add(m.id)
const from = m.direction === 'out' ? 'me' : (m.sender ?? m.contact) const from = m.direction === 'out' ? 'me' : (m.sender ?? m.contact)
const mine = byTarget.get(found.id) ?? new Map<string, Reaction>() const mine = byTarget.get(found.id) ?? new Map<string, Reaction>()
if (r.removed) { 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 { } else {
mine.delete(from)
mine.set(from, { emoji: r.emoji, from, ts: m.ts }) mine.set(from, { emoji: r.emoji, from, ts: m.ts })
} }
byTarget.set(found.id, mine) 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 } 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 { export function reactionPreview(body: string): string | null {
const r = parseReaction(body) 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)}”` const what = 'media' in r.target ? 'a photo' : `“${norm(r.target.text)}”`
return r.removed ? `Removed ${r.emoji} from ${what}` : `${r.emoji} to ${what}` 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 look?: Look // absent = travewave
hideMenuBar?: boolean // until Alt is tapped (design.html#menubar); absent = hidden hideMenuBar?: boolean // until Alt is tapped (design.html#menubar); absent = hidden
showTooltips?: boolean // design.html#tooltips; absent = shown showTooltips?: boolean // design.html#tooltips; absent = shown
quickReactions?: string[] // a message's quick reaction row; absent = ❤️ 👍 👎 😂 ‼️ ❓
} }
export interface Credentials { export interface Credentials {
+95
View File
@@ -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("❤️");
});
});
+97 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest' 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 let nextId = 1
const msg = (body: string, opts: { out?: boolean; sender?: string; media?: boolean; ts?: number } = {}) => ({ const msg = (body: string, opts: { out?: boolean; sender?: string; media?: boolean; ts?: number } = {}) => ({
@@ -97,3 +97,99 @@ describe('reactionPreview', () => {
expect(reactionPreview('just text')).toBeNull() 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)
})
})