import React, { ReactNode, useCallback, useEffect, useMemo, useState } from 'react'; import parse from 'html-react-parser'; import Linkify from 'linkify-react'; import FocusTrap from 'focus-trap-react'; import { Box, Button, Header, Icon, IconButton, Icons, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Spinner, Switch, Text, color, config, } from 'folds'; import { MatrixEvent, Room } from 'matrix-js-sdk'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { stopPropagation } from '../../../utils/keyboard'; import { useModalStyle } from '../../../hooks/useModalStyle'; import { sanitizeCustomHtml } from '../../../utils/sanitize'; import { LINKIFY_OPTS } from '../../../plugins/react-custom-html-parser'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { timeDayMonYear, timeHourMinute } from '../../../utils/time'; import { useSetting } from '../../../state/hooks/settings'; import { settingsAtom } from '../../../state/settings'; import { diffWords } from '../../../utils/textDiff'; type RawEditEvent = { type: string; content: Record; origin_server_ts: number; event_id: string; }; type EditHistoryResponse = { chunk: Array>; next_batch?: string; }; type EditHistoryModalProps = { room: Room; mEvent: MatrixEvent; onClose: () => void; }; function isRawEditEvent(raw: unknown): raw is RawEditEvent { if (typeof raw !== 'object' || raw === null) return false; const r = raw as Record; return typeof r.event_id === 'string' && typeof r.origin_server_ts === 'number'; } function renderContent(source: Record): ReactNode { const format = source.format; const formattedBody = source.formatted_body; if ( format === 'org.matrix.custom.html' && typeof formattedBody === 'string' && formattedBody.trim() ) { return parse(sanitizeCustomHtml(formattedBody)); } const body = source.body; const text = typeof body === 'string' ? body : '(no text)'; return {text}; } function getOriginalContent(evt: MatrixEvent): ReactNode { // For E2EE events, evt.event.content is the ciphertext (no body field) — "(no text)" bug. // getClearContent() returns the decrypted original content, bypassing _replacingEvent, // so it gives us the pre-edit body even when the SDK has an edit applied. // For unencrypted events, getClearContent() returns null, so we fall back to event.content. const raw = (evt.getClearContent() as Record | null) ?? (evt.event as { content?: Record }).content ?? {}; return renderContent(raw); } function getVersionContent(evt: MatrixEvent): ReactNode { // Edit events carry the new text in m.new_content per Matrix spec. const content = evt.getContent(); const newContent = content['m.new_content'] as Record | undefined; return renderContent(newContent ?? content); } const asText = (source: Record | null | undefined): string => { const body = source?.body; return typeof body === 'string' ? body : ''; }; // Plain-text (body) of the pre-edit message — mirrors getOriginalContent, but // returns the raw string for diffing rather than a rendered node. function getOriginalText(evt: MatrixEvent): string { const raw = (evt.getClearContent() as Record | null) ?? (evt.event as { content?: Record }).content ?? {}; return asText(raw); } // Plain-text (body) of an edit's new content. function getVersionText(evt: MatrixEvent): string { const content = evt.getContent(); const newContent = content['m.new_content'] as Record | undefined; return asText(newContent ?? content); } // Renders a word-level diff of prev -> next: added words highlighted, removed // words struck-through, using semantic / elements. Plain-text only // (formatting isn't diffed — see the "Highlight changes" toggle). function DiffText({ prev, next }: { prev: string; next: string }) { const segments = useMemo(() => diffWords(prev, next), [prev, next]); if (segments.length === 0) return <>(no text); return ( <> {segments.map((seg, i) => { const key = `${i}-${seg.type}`; if (seg.type === 'added') { return ( {seg.text} ); } if (seg.type === 'removed') { return ( {seg.text} ); } return {seg.text}; })} ); } export function EditHistoryModal({ room, mEvent, onClose }: EditHistoryModalProps) { const mx = useMatrixClient(); const modalStyle = useModalStyle(560); const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); const [showDiff, setShowDiff] = useState(true); const eventId = mEvent.getId(); const roomId = room.roomId; // Accumulated, de-duplicated edits across paginated fetches. const [edits, setEdits] = useState([]); const [nextBatch, setNextBatch] = useState(undefined); const parseRawEvents = useCallback( (rawEvents: Array>): Promise => Promise.all( rawEvents.filter(isRawEditEvent).map(async (raw) => { const existing = room.findEventById(raw.event_id); if (existing) return existing; const evt = new MatrixEvent({ type: raw.type, content: raw.content, origin_server_ts: raw.origin_server_ts, event_id: raw.event_id, room_id: roomId, sender: mEvent.getSender() ?? '', }); if (evt.isEncrypted()) { await mx.decryptEventIfNeeded(evt); } return evt; }), ), [room, roomId, mEvent, mx], ); const [historyState, fetchHistory] = useAsyncCallback( useCallback( async (from?: string) => { if (!eventId) return; // Relations API lives at /_matrix/client/v1/ (not v3); use raw fetch to avoid SDK prefix const token = mx.getAccessToken(); const baseUrl = mx.getHomeserverUrl(); const fromParam = from ? `&from=${encodeURIComponent(from)}` : ''; const url = `${baseUrl}/_matrix/client/v1/rooms/${encodeURIComponent(roomId)}/relations/${encodeURIComponent(eventId)}/m.replace?limit=50${fromParam}`; const fetchRes = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); if (!fetchRes.ok) throw new Error(`HTTP ${fetchRes.status}`); const res = (await fetchRes.json()) as EditHistoryResponse; const newEvents = await parseRawEvents(res.chunk ?? []); // Merge with prior pages, de-dupe by event id, sort chronologically so // page ordering across batches is always correct. setEdits((prev) => { const byId = new Map(); [...prev, ...newEvents].forEach((evt) => { const id = evt.getId(); if (id) byId.set(id, evt); }); return Array.from(byId.values()).sort((a, b) => a.getTs() - b.getTs()); }); setNextBatch(res.next_batch); }, [mx, roomId, eventId, parseRawEvents], ), ); useEffect(() => { fetchHistory(undefined).catch(() => undefined); }, [fetchHistory]); const initialLoading = historyState.status === AsyncStatus.Loading && edits.length === 0; const loadingMore = historyState.status === AsyncStatus.Loading && edits.length > 0; const formatTs = (ts: number): string => { const time = timeHourMinute(ts, hour24Clock); const date = timeDayMonYear(ts, dateFormatString); return `${date} at ${time}`; }; const originalContent = getOriginalContent(mEvent); const originalTs = mEvent.getTs(); // Ordered plain-text of every version: [original, ...each edit]. Edit i diffs // against versionTexts[i] (the version immediately before it). const versionTexts = [getOriginalText(mEvent), ...edits.map(getVersionText)]; return ( }>
Edit History Highlight changes
{initialLoading && ( )} {historyState.status === AsyncStatus.Error && edits.length === 0 && ( Failed to load edit history. )} {!initialLoading && historyState.status !== AsyncStatus.Error && ( Original {formatTs(originalTs)} {originalContent} {edits.map((editEvt, index) => ( {index === edits.length - 1 ? `Edit ${index + 1} (current)` : `Edit ${index + 1}`} {formatTs(editEvt.getTs())} {showDiff ? ( ) : ( getVersionContent(editEvt) )} ))} {edits.length === 0 && ( No edit history found. )} {nextBatch && ( )} )}
); }