import { diff } from 'deep-diff'; import { IEvent } from 'interfaces/event'; import { useTheme } from '@mui/system'; import { CSSProperties } from 'react'; const DIFF_PREFIXES: Record = { A: ' ', E: ' ', D: '-', N: '+', }; interface IEventDiffProps { entry: IEvent; } const EventDiff = ({ entry }: IEventDiffProps) => { const theme = useTheme(); const styles: Record = { A: { color: theme.palette.code.edited }, // array edited E: { color: theme.palette.code.edited }, // edited D: { color: theme.palette.code.diffSub }, // deleted N: { color: theme.palette.code.diffAdd }, // added }; const diffs = entry.data && entry.preData ? diff(entry.preData, entry.data) : undefined; const buildItemDiff = (diff: any, key: string) => { let change; if (diff.lhs !== undefined) { change = (
- {key}: {JSON.stringify(diff.lhs)}
); } else if (diff.rhs !== undefined) { change = (
+ {key}: {JSON.stringify(diff.rhs)}
); } return change; }; const buildDiff = (diff: any, idx: number) => { let change; const key = diff.path.join('.'); if (diff.item) { change = buildItemDiff(diff.item, key); } else if (diff.lhs !== undefined && diff.rhs !== undefined) { change = (
- {key}: {JSON.stringify(diff.lhs)}
+ {key}: {JSON.stringify(diff.rhs)}
); } else { change = (
{DIFF_PREFIXES[diff.kind]} {key}:{' '} {JSON.stringify(diff.rhs || diff.item)}
); } return
{change}
; }; let changes; if (diffs) { changes = diffs.map(buildDiff); } else { // Just show the data if there is no diff yet. const data = entry.data || entry.preData; changes = [
{JSON.stringify(data, null, 2)}
, ]; } return (
            {changes.length === 0 ? '(no changes)' : changes}
        
); }; export default EventDiff;