import { Head, InfiniteScroll, router, usePage } from '@inertiajs/react';
import { Check, Flag, Undo2, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import {
destroy as undoEscalateRoute,
store as escalateRoute,
} from '@/actions/App/Http/Controllers/CommitEscalationController';
import { store as reject } from '@/actions/App/Http/Controllers/CommitRejectionController';
import { destroy } from '@/actions/App/Http/Controllers/CommitReportController';
import { CommitCard } from '@/components/commit-card';
import { EmptyFeed } from '@/components/commit-feed';
import { CommitPoster } from '@/components/commit-poster';
import { GraphCanvas } from '@/components/graph-canvas';
import { ModerationTabs } from '@/components/moderation-tabs';
import { Button } from '@/components/ui/button';
import { useMarkCommitDeleted } from '@/hooks/use-deleted-resources';
import { idsOf, useRealtime } from '@/hooks/use-realtime';
import AppLayout from '@/layouts/app-layout';
import { reloadInBackground } from '@/lib/background-poll';
import { changesSince, readAt } from '@/lib/commit-changes';
import { userChannel } from '@/lib/realtime';
import { formatFullDateTime } from '@/lib/utils';
import type { Commit, CursorPaginated } from '@/types';
type ReportChanges = { filed: string[]; dismissed: string[] };
type Report = {
id: string;
reason: string;
details: string | null;
attachments: {
url: string;
description: string | null;
width: number;
height: number;
}[];
created_at: string;
commit: Commit;
};
export default function Reports({
reports,
reasons,
}: {
reports: CursorPaginated;
reasons: Record;
}) {
const markCommitDeleted = useMarkCommitDeleted();
const { auth, now } = usePage().props;
const [hasChanged, setHasChanged] = useState(false);
const [readSince] = useState(() => Math.min(now - 5_000, readAt()));
const changesOf = useRef<
((since: number) => Promise) | null
>(null);
useEffect(() => {
const controller = new AbortController();
changesOf.current = async (since) => {
let changes: ReportChanges | null = null;
await reloadInBackground(
{
only: ['reportChanges'],
data: { since: Math.floor(since) },
preserveUrl: true,
onSuccess: (page) => {
changes =
(page.props.reportChanges as
| ReportChanges
| undefined) ?? null;
},
},
controller.signal,
);
return changes;
};
return () => {
controller.abort();
changesOf.current = null;
};
}, []);
const takeOff = (ids: string[]) => {
const loaded = new Set(reports.data.map((report) => report.id));
const dismissed = new Set(ids.filter((id) => loaded.has(id)));
if (dismissed.size > 0) {
router.replaceProp('reports', (value: CursorPaginated) => ({
...value,
data: value.data.filter((report) => !dismissed.has(report.id)),
}));
}
};
// A report another moderator dismissed leaves the queue where it is. New reports, and decisions on reported
// commits that may take them off, wait for a deliberate refresh, keeping the pages loaded until then.
useRealtime(
auth.user === null ? null : userChannel(auth.user.id),
['moderation'],
(_event, payload) => {
const loaded = new Set(reports.data.map((report) => report.id));
takeOff(idsOf(payload, 'reports'));
const commits = new Set(idsOf(payload, 'commits'));
if (
idsOf(payload, 'reports').some((id) => !loaded.has(id)) ||
reports.data.some((report) => commits.has(report.commit.id))
) {
setHasChanged(true);
}
},
(isFirst) => {
if (!isFirst) {
setHasChanged(true);
return;
}
// Read before listening: reports dismissed since leave where they are, and those filed since, or decisions
// on the commits it shows, are offered as a refresh.
const loaded = new Set(reports.data.map((report) => report.id));
void changesOf.current?.(readSince).then((changes) => {
if (changes === null) {
setHasChanged(true);
return;
}
takeOff(changes.dismissed);
if (changes.filed.some((id) => !loaded.has(id))) {
setHasChanged(true);
}
});
void Promise.all(
reports.data.map((report) =>
changesSince(report.commit.id, readSince),
),
).then((changes) => {
if (
changes.some((change) => change === null || change.changed)
) {
setHasChanged(true);
}
});
},
);
const refreshQueue = () =>
router.reload({
only: ['reports'],
reset: ['reports'],
onSuccess: () => setHasChanged(false),
});
const resolve = (
route: ReturnType | ReturnType,
isResolved: (report: Report) => boolean,
onNotFound: () => void,
) =>
router
.optimistic((props: { reports: CursorPaginated }) => ({
reports: {
...props.reports,
data: props.reports.data.filter(
(report) => !isResolved(report),
),
},
}))
.visit(route, {
preserveScroll: true,
reset: ['reports'],
onHttpException: (response) => {
if (response.status !== 404) {
return;
}
onNotFound();
return false;
},
});
/**
* A dismissal is about the report, which leaves the queue once its commit is gone or no longer published, while the
* commit itself may still be live.
*/
const dismiss = (report: Report) =>
resolve(
destroy(report.id),
({ id }) => id === report.id,
() => {
toast('This report is no longer in the queue.');
router.reload({ only: ['reports'], reset: ['reports'] });
},
);
// Unlike a dismissal, an escalation keeps the report: it flags the commit for an admin.
const escalate = (report: Report) =>
router.visit(escalateRoute(report.commit), {
preserveScroll: true,
only: ['reports'],
onError: () =>
toast.error('Could not escalate this commit. Try again.'),
});
const undoEscalate = (report: Report) =>
router.visit(undoEscalateRoute(report.commit), {
preserveScroll: true,
only: ['reports'],
onError: () =>
toast.error('Could not undo the escalation. Try again.'),
});
return (
<>
Moderation
{hasChanged ? (
) : (
Oldest first
)}
Private reports on published commits. Dismiss a report to keep
the commit, or reject the original.
{reports.data.length === 0 ? (
No reports are waiting for review.
) : (
Loading reports…
}
>
{reports.data.map((report) => (
// A canvas each: reports are unrelated to each other, and two can be about the same commit,
// whose node they would otherwise share.