- 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.
469 lines
18 KiB
TypeScript
469 lines
18 KiB
TypeScript
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso'
|
|
import { formatNumber, groupMembers, isGroup, didName } from '@shared/phone'
|
|
import type { ContactInfo, Conversation, Did, Message, SearchHit } from '@shared/types'
|
|
import type { ConvKey, Jump } from '../App'
|
|
import { chatsWith, convName, dayLabel, sameDay, senderName, senderShortName } from '../format'
|
|
import { Avatar } from './Avatar'
|
|
import { Composer, type ComposerHandle } from './Composer'
|
|
import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons'
|
|
import { Lightbox } from './Lightbox'
|
|
import { MessageBubble } from './MessageBubble'
|
|
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'
|
|
import { imageMenuItems } from './Lightbox'
|
|
|
|
type Row = { kind: 'day'; key: string; ts: number } | { kind: 'msg'; key: string; m: Message; groupStart: boolean; groupEnd: boolean }
|
|
|
|
const GROUP_GAP = 5 * 60_000
|
|
|
|
// Breathing room between the newest message and the composer.
|
|
const ListFooter = () => <div className="list-footer" />
|
|
|
|
function buildRows(msgs: Message[]): Row[] {
|
|
const rows: Row[] = []
|
|
msgs.forEach((m, i) => {
|
|
const prev = msgs[i - 1]
|
|
const next = msgs[i + 1]
|
|
const newDay = !prev || !sameDay(prev.ts, m.ts)
|
|
if (newDay) rows.push({ kind: 'day', key: `d${m.ts}`, ts: m.ts })
|
|
const groupStart = newDay || prev.direction !== m.direction || prev.sender !== m.sender || m.ts - prev.ts > GROUP_GAP
|
|
const groupEnd =
|
|
!next || !sameDay(m.ts, next.ts) || next.direction !== m.direction || next.sender !== m.sender || next.ts - m.ts > GROUP_GAP
|
|
rows.push({ kind: 'msg', key: String(m.id), m, groupStart, groupEnd })
|
|
})
|
|
return rows
|
|
}
|
|
|
|
interface Props {
|
|
conv: ConvKey
|
|
contact?: ContactInfo
|
|
contactMap: Map<string, ContactInfo>
|
|
conversations: Conversation[]
|
|
onOpen: (key: ConvKey) => void
|
|
name?: string // a name you gave the conversation
|
|
onInfo: () => void
|
|
onExport: () => void
|
|
gvNumber?: string
|
|
jump?: Jump
|
|
highlight: string
|
|
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, quickReactions, onQuickReactions }: Props) {
|
|
const name = convName(conv.contact, contactMap, ownName)
|
|
const addContact = useAddContact()
|
|
const [menu, setMenu] = useState<{ number: string; x: number; y: number }>()
|
|
const [headerMenu, setHeaderMenu] = useState<{ x: number; y: number }>()
|
|
// "Other chats with …": the groups (and other-number 1:1s) someone's in.
|
|
const [others, setOthers] = useState<{ number: string; x: number; y: number }>()
|
|
const othersItem = (number: string, x: number, y: number, label: string): MenuItem => ({
|
|
label,
|
|
onSelect: () => setOthers({ number, x, y })
|
|
})
|
|
const otherChatItems = (number: string): MenuItem[] => {
|
|
const chats = chatsWith(number, conversations, conv)
|
|
if (!chats.length) return [{ label: `No other chats with ${senderShortName(number, contactMap)}`, onSelect: () => undefined, disabled: true }]
|
|
return chats.map((c) => ({
|
|
label:
|
|
(isGroup(c.contact) ? convName(c.contact, contactMap, c.name) : `${senderName(c.contact, contactMap)} (just you two, from ${didName(c.did)})`) +
|
|
(c.archived ? ' — archived' : ''),
|
|
onSelect: () => onOpen({ did: c.did, contact: c.contact })
|
|
}))
|
|
}
|
|
// Right-click a group member's name: other chats with them, and "Add to
|
|
// contacts…" if they aren't in your contacts.
|
|
const numberMenu = (number?: string) => (e: React.MouseEvent) => {
|
|
if (!number) return
|
|
e.preventDefault()
|
|
setMenu({ number, x: e.clientX, y: e.clientY })
|
|
}
|
|
const group = isGroup(conv.contact)
|
|
const members = group ? groupMembers(conv.contact).map((n) => senderName(n, contactMap)) : []
|
|
const [messages, setMessages] = useState<Message[]>()
|
|
const [flashId, setFlashId] = useState<number>()
|
|
const [searchOpen, setSearchOpen] = useState(false)
|
|
const [q, setQ] = useState('')
|
|
const [hits, setHits] = useState<SearchHit[]>([])
|
|
const [hitIdx, setHitIdx] = useState(0)
|
|
const [lightbox, setLightbox] = useState<{ id: number; index: number }>()
|
|
const [dragging, setDragging] = useState(false)
|
|
const virtuoso = useRef<VirtuosoHandle>(null)
|
|
const searchInput = useRef<HTMLInputElement>(null)
|
|
const composer = useRef<ComposerHandle>(null)
|
|
const atBottom = useRef(true)
|
|
|
|
// Load (and reload on any change) the whole conversation.
|
|
useEffect(() => {
|
|
let cancelled = false
|
|
void window.api.getMessages(conv.did, conv.contact).then((m) => {
|
|
if (cancelled) return
|
|
setMessages(m)
|
|
if (document.hasFocus()) void window.api.markRead(conv.did, conv.contact)
|
|
})
|
|
return () => {
|
|
cancelled = true
|
|
}
|
|
}, [conv.did, conv.contact, version])
|
|
|
|
useEffect(() => {
|
|
const onFocus = (): void => void window.api.markRead(conv.did, conv.contact)
|
|
window.addEventListener('focus', onFocus)
|
|
return () => window.removeEventListener('focus', onFocus)
|
|
}, [conv.did, conv.contact])
|
|
|
|
// 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) ? (
|
|
<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 flash = useCallback((id: number) => {
|
|
setFlashId(id)
|
|
setTimeout(() => setFlashId((cur) => (cur === id ? undefined : cur)), 2200)
|
|
}, [])
|
|
|
|
const scrollTo = useCallback(
|
|
(id: number) => {
|
|
const index = indexOf(id)
|
|
if (index < 0) return
|
|
virtuoso.current?.scrollToIndex({ index, align: 'center' })
|
|
flash(id)
|
|
},
|
|
[indexOf, flash]
|
|
)
|
|
|
|
// Jump requests from the sidebar search (including repeat clicks).
|
|
const initialJump = useRef(jump)
|
|
useEffect(() => {
|
|
if (!jump || !messages) return
|
|
if (jump === initialJump.current) {
|
|
flash(jump.id) // initial mount already positioned us
|
|
initialJump.current = undefined
|
|
return
|
|
}
|
|
scrollTo(jump.id)
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [jump, messages !== undefined])
|
|
|
|
// ---- in-chat search ----
|
|
useEffect(() => {
|
|
if (!searchOpen || !q.trim()) {
|
|
setHits([])
|
|
return
|
|
}
|
|
let cancelled = false
|
|
const t = setTimeout(() => {
|
|
void window.api.search(q, conv).then((h) => {
|
|
if (cancelled) return
|
|
setHits(h)
|
|
setHitIdx(0)
|
|
if (h[0]) scrollTo(h[0].id)
|
|
})
|
|
}, 200)
|
|
return () => {
|
|
cancelled = true
|
|
clearTimeout(t)
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [q, searchOpen])
|
|
|
|
const stepHit = (dir: 1 | -1): void => {
|
|
if (!hits.length) return
|
|
const next = (hitIdx + dir + hits.length) % hits.length
|
|
setHitIdx(next)
|
|
scrollTo(hits[next].id)
|
|
}
|
|
|
|
const openSearch = (): void => {
|
|
setSearchOpen(true)
|
|
setTimeout(() => searchInput.current?.focus(), 0)
|
|
}
|
|
|
|
useEffect(() => {
|
|
const onKey = (e: KeyboardEvent): void => {
|
|
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'f') {
|
|
e.preventDefault()
|
|
openSearch()
|
|
}
|
|
}
|
|
window.addEventListener('keydown', onKey)
|
|
return () => window.removeEventListener('keydown', onKey)
|
|
}, [])
|
|
|
|
const openMedia = useCallback((id: number, index: number) => setLightbox({ id, index }), [])
|
|
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.
|
|
const onMediaLoad = useCallback(() => {
|
|
if (atBottom.current) virtuoso.current?.scrollToIndex({ index: 'LAST', align: 'end' })
|
|
}, [])
|
|
|
|
const mark = searchOpen && q.trim() ? q : highlight
|
|
const isNew = messages !== undefined && messages.length === 0
|
|
const initialIndex = jump && messages ? Math.max(0, indexOf(jump.id)) : rows.length - 1
|
|
|
|
return (
|
|
<main
|
|
className={`chat${dragging ? ' dragging' : ''}`}
|
|
onDragOver={(e) => {
|
|
if (!e.dataTransfer.types.includes('Files')) return
|
|
e.preventDefault()
|
|
setDragging(true)
|
|
}}
|
|
onDragLeave={(e) => {
|
|
if (!e.currentTarget.contains(e.relatedTarget as Node)) setDragging(false)
|
|
}}
|
|
onDrop={(e) => {
|
|
e.preventDefault()
|
|
setDragging(false)
|
|
composer.current?.addFiles([...e.dataTransfer.files])
|
|
}}
|
|
>
|
|
<header
|
|
className="chat-header"
|
|
onContextMenu={(e) => {
|
|
e.preventDefault()
|
|
setHeaderMenu({ x: e.clientX, y: e.clientY })
|
|
}}
|
|
>
|
|
<Avatar number={conv.contact} contact={contact} size={36} />
|
|
<div
|
|
className={`chat-title${group ? ' clickable' : ''}`}
|
|
onClick={group ? onInfo : undefined}
|
|
title={group ? 'Get info' : undefined}
|
|
>
|
|
<div className="chat-name">{name}</div>
|
|
<div className="chat-sub">
|
|
{group ? `${members.length} people` : contact ? formatNumber(conv.contact) : ''}
|
|
{smsDids.length > 1 && (
|
|
<span className="chat-via">
|
|
{contact || group ? ' · ' : ''}
|
|
<Via did={conv.did} gvNumber={gvNumber} />
|
|
</span>
|
|
)}
|
|
</div>
|
|
</div>
|
|
<button className="icon-btn" title="Search in chat (Ctrl+Shift+F)" onClick={openSearch}>
|
|
<SearchIcon />
|
|
</button>
|
|
</header>
|
|
|
|
{searchOpen && (
|
|
<div className="chat-search">
|
|
<SearchIcon size={16} />
|
|
<input
|
|
ref={searchInput}
|
|
value={q}
|
|
placeholder={`Search in ${name}`}
|
|
onChange={(e) => setQ(e.target.value)}
|
|
onKeyDown={(e) => {
|
|
if (e.key === 'Enter') stepHit(e.shiftKey ? -1 : 1)
|
|
else if (e.key === 'Escape') {
|
|
setSearchOpen(false)
|
|
setQ('')
|
|
}
|
|
}}
|
|
/>
|
|
<span className="hit-count">{q.trim() ? (hits.length ? `${hitIdx + 1} of ${hits.length}` : 'No results') : ''}</span>
|
|
<div className="tiles">
|
|
<button className="icon-btn small" title="Older (Enter)" disabled={!hits.length} onClick={() => stepHit(1)}>
|
|
<UpIcon />
|
|
</button>
|
|
<button className="icon-btn small" title="Newer (Shift+Enter)" disabled={!hits.length} onClick={() => stepHit(-1)}>
|
|
<DownIcon />
|
|
</button>
|
|
</div>
|
|
<button
|
|
className="icon-btn small"
|
|
title="Close"
|
|
onClick={() => {
|
|
setSearchOpen(false)
|
|
setQ('')
|
|
}}
|
|
>
|
|
<CloseIcon />
|
|
</button>
|
|
</div>
|
|
)}
|
|
|
|
<div className="messages">
|
|
{messages === undefined ? null : isNew ? (
|
|
<div className="new-conv">
|
|
<Avatar number={conv.contact} contact={contact} size={80} />
|
|
<div className="new-conv-name">{name}</div>
|
|
{group ? <div className="new-conv-sub">{members.join(', ')}</div> : contact && <div className="new-conv-sub">{formatNumber(conv.contact)}</div>}
|
|
</div>
|
|
) : (
|
|
<Virtuoso
|
|
ref={virtuoso}
|
|
data={rows}
|
|
className="message-scroller"
|
|
computeItemKey={(_, r) => r.key}
|
|
initialTopMostItemIndex={{ index: initialIndex, align: jump ? 'center' : 'end' }}
|
|
followOutput={(bottom) => (bottom ? 'smooth' : false)}
|
|
atBottomStateChange={(bottom) => (atBottom.current = bottom)}
|
|
atBottomThreshold={80}
|
|
alignToBottom
|
|
increaseViewportBy={{ top: 800, bottom: 800 }}
|
|
components={{ Footer: ListFooter }}
|
|
itemContent={(_, r) =>
|
|
r.kind === 'day' ? (
|
|
<div className="day-sep">
|
|
<span>{dayLabel(r.ts)}</span>
|
|
</div>
|
|
) : (
|
|
<MessageBubble
|
|
m={r.m}
|
|
sender={group && r.m.sender && r.groupStart ? senderName(r.m.sender, contactMap) : undefined}
|
|
onSenderMenu={numberMenu(r.m.sender)}
|
|
groupStart={r.groupStart}
|
|
groupEnd={r.groupEnd}
|
|
flash={flashId === r.m.id}
|
|
highlight={mark}
|
|
onOpenMedia={openMedia}
|
|
onMediaMenu={showMediaMenu}
|
|
onMediaLoad={onMediaLoad}
|
|
reactions={folded.reactions.get(r.m.id)}
|
|
onShowReactions={showReactions}
|
|
onMenu={showMsgMenu}
|
|
versions={folded.versions.get(r.m.id)}
|
|
onShowEdits={showEdits}
|
|
/>
|
|
)
|
|
}
|
|
/>
|
|
)}
|
|
</div>
|
|
|
|
<Composer ref={composer} conv={conv} isNew={isNew} smsDids={smsDids} gvNumber={gvNumber} onChangeDid={onChangeDid} />
|
|
{dragging && <div className="drop-hint">Drop to attach</div>}
|
|
{lightbox && <Lightbox {...lightbox} onClose={() => setLightbox(undefined)} />}
|
|
{reactionList && (
|
|
<ContextMenu
|
|
x={reactionList.x}
|
|
y={reactionList.y}
|
|
items={reactionList.reactions.map((r) => ({
|
|
label: `${r.emoji} ${r.from === 'me' ? 'You' : senderName(r.from, contactMap)}`,
|
|
onSelect: () => undefined
|
|
}))}
|
|
onClose={() => setReactionList(undefined)}
|
|
/>
|
|
)}
|
|
{mediaMenu && (
|
|
<ContextMenu
|
|
x={mediaMenu.x}
|
|
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)}
|
|
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 && (
|
|
<ContextMenu
|
|
x={headerMenu.x}
|
|
y={headerMenu.y}
|
|
items={[
|
|
...(group
|
|
? groupMembers(conv.contact).map((n) =>
|
|
othersItem(n, headerMenu.x, headerMenu.y, `Other chats with ${senderShortName(n, contactMap)}`)
|
|
)
|
|
: [othersItem(conv.contact, headerMenu.x, headerMenu.y, 'Other chats with this person')]),
|
|
...(!group && !contact ? [{ label: 'Add to contacts…', onSelect: () => addContact(conv.contact), separator: true }] : []),
|
|
{ label: 'Export chat…', onSelect: onExport, separator: group || !!contact }
|
|
]}
|
|
onClose={() => setHeaderMenu(undefined)}
|
|
/>
|
|
)}
|
|
{menu && (
|
|
<ContextMenu
|
|
x={menu.x}
|
|
y={menu.y}
|
|
items={[
|
|
othersItem(menu.number, menu.x, menu.y, `Other chats with ${senderShortName(menu.number, contactMap)}`),
|
|
...(contactMap.get(menu.number) ? [] : [{ label: 'Add to contacts…', onSelect: () => addContact(menu.number) }])
|
|
]}
|
|
onClose={() => setMenu(undefined)}
|
|
/>
|
|
)}
|
|
{others && <ContextMenu x={others.x} y={others.y} items={otherChatItems(others.number)} onClose={() => setOthers(undefined)} />}
|
|
</main>
|
|
)
|
|
}
|