feat(admin): archive tab with search, paging and message viewer

- Add paginated archive table with full-text search
- Add message viewer that renders the body as plain text
- Add inline-confirmed deletion
- Warn when archiving is off
This commit is contained in:
tgiachi 2026-11-09 15:37:39 +01:00
commit b3a85a55ea
2 changed files with 364 additions and 1 deletions

View file

@ -0,0 +1,171 @@
import { screen, waitFor, within } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import type { Message } from '@/lib/api'
import { aList, installFakeApi, newState } from '@/test/fakeApi'
import { renderApp } from '@/test/render'
const msg = (id: number, over: Partial<Message> = {}): Message => ({
id,
thread_id: id,
message_id: `<${id}@x>`,
subject: `Subject ${id}`,
sender: `Sender ${id}`,
date: '2030-01-02T03:04:05Z',
size: 2048,
body: `Body of message ${id}`,
...over,
})
async function setup(messages: Message[], list = aList({ id: 1, archive_policy: 'private' })) {
const state = installFakeApi(newState({ lists: [list], archive: { [list.id]: messages } }))
const ctx = renderApp(`/lists/${list.id}/archive`, { token: 'good' })
await screen.findByRole('heading', { name: /^archive/i, level: 2 })
return { ...ctx, state }
}
describe('archive tab', () => {
it('lists messages with sender, date and size', async () => {
await setup([msg(1), msg(2)])
const row = (await screen.findByRole('button', { name: 'Subject 1' })).closest('tr')!
expect(within(row).getByText('Sender 1')).toBeInTheDocument()
expect(within(row).getByText('2030-01-02 03:04 UTC')).toBeInTheDocument()
expect(within(row).getByText('2.0 KB')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Archive (2)', level: 2 })).toBeInTheDocument()
})
it('has an empty state', async () => {
await setup([])
expect(await screen.findByText(/no messages archived yet/i)).toBeInTheDocument()
})
it('warns when archiving is off', async () => {
await setup([], aList({ id: 1, archive_policy: 'off' }))
expect(await screen.findByText(/archiving is off/i)).toBeInTheDocument()
})
it('does not warn when archiving is on', async () => {
await setup([msg(1)])
await screen.findByRole('button', { name: 'Subject 1' })
expect(screen.queryByText(/archiving is off/i)).not.toBeInTheDocument()
})
describe('searching', () => {
it('shows only matches and how many', async () => {
const { user } = await setup([msg(1, { subject: 'Deploy failed' }), msg(2, { subject: 'Lunch' })])
await screen.findByRole('button', { name: 'Lunch' })
await user.type(screen.getByRole('searchbox', { name: /search archive/i }), 'deploy')
await user.click(screen.getByRole('button', { name: /^search$/i }))
expect(await screen.findByText(/1 result for “deploy”/i)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Deploy failed' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Lunch' })).not.toBeInTheDocument()
})
it('submits with Enter and says when nothing matches', async () => {
const { user } = await setup([msg(1)])
await screen.findByRole('button', { name: 'Subject 1' })
await user.type(screen.getByRole('searchbox', { name: /search archive/i }), 'zzz{Enter}')
expect(await screen.findByText(/no messages found/i)).toBeInTheDocument()
})
it('clears the search to show everything again', async () => {
const { user } = await setup([msg(1, { subject: 'Alpha' }), msg(2, { subject: 'Beta' })])
await screen.findByRole('button', { name: 'Beta' })
await user.type(screen.getByRole('searchbox', { name: /search archive/i }), 'alpha{Enter}')
await waitFor(() => expect(screen.queryByRole('button', { name: 'Beta' })).not.toBeInTheDocument())
await user.click(screen.getByRole('button', { name: /clear/i }))
expect(await screen.findByRole('button', { name: 'Beta' })).toBeInTheDocument()
expect(screen.getByRole('searchbox', { name: /search archive/i })).toHaveValue('')
})
})
describe('paging', () => {
const many = Array.from({ length: 60 }, (_, i) => msg(i + 1))
it('shows 25 at a time and moves through the pages', async () => {
const { user, state } = await setup(many)
await screen.findByRole('button', { name: 'Subject 1' })
expect(screen.getAllByRole('button', { name: /^Subject \d+$/ })).toHaveLength(25)
expect(screen.getByText('1–25 of 60')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /previous/i })).toBeDisabled()
await user.click(screen.getByRole('button', { name: /next/i }))
expect(await screen.findByText('26–50 of 60')).toBeInTheDocument()
expect(state.calls).toContain('GET /lists/1/archive')
await user.click(screen.getByRole('button', { name: /next/i }))
expect(await screen.findByText('51–60 of 60')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /next/i })).toBeDisabled()
await user.click(screen.getByRole('button', { name: /previous/i }))
expect(await screen.findByText('26–50 of 60')).toBeInTheDocument()
})
it('goes back to the first page on a new search', async () => {
const { user } = await setup(many)
await screen.findByText('1–25 of 60')
await user.click(screen.getByRole('button', { name: /next/i }))
await screen.findByText('26–50 of 60')
await user.type(screen.getByRole('searchbox', { name: /search archive/i }), 'subject{Enter}')
expect(await screen.findByText('1–25 of 60')).toBeInTheDocument()
})
it('hides the pager when everything fits on one page', async () => {
await setup([msg(1)])
await screen.findByRole('button', { name: 'Subject 1' })
expect(screen.queryByRole('button', { name: /next/i })).not.toBeInTheDocument()
})
})
describe('reading a message', () => {
async function open(messages = [msg(1, { body: 'Hello <script>alert(1)</script> world' }), msg(2)]) {
const ctx = await setup(messages)
await ctx.user.click(await screen.findByRole('button', { name: 'Subject 1' }))
return { ...ctx, dialog: await screen.findByRole('dialog') }
}
it('shows the full text as plain text', async () => {
const { dialog } = await open()
expect(await within(dialog).findByText(/Hello <script>alert\(1\)<\/script> world/)).toBeInTheDocument()
expect(within(dialog).getByRole('heading', { name: 'Subject 1' })).toBeInTheDocument()
expect(within(dialog).getByText(/Sender 1/)).toBeInTheDocument()
expect(dialog.querySelector('script')).toBeNull()
})
it('shows an error when the message cannot be loaded', async () => {
const ctx = await setup([msg(1)])
ctx.state.fail['GET /archive/1'] = { status: 500, error: 'read error' }
await ctx.user.click(await screen.findByRole('button', { name: 'Subject 1' }))
expect(await within(await screen.findByRole('dialog')).findByRole('alert')).toHaveTextContent('read error')
})
it('deletes after an explicit confirmation', async () => {
const { user, state, dialog } = await open()
await within(dialog).findByText(/Hello/)
await user.click(within(dialog).getByRole('button', { name: /delete message/i }))
expect(await within(dialog).findByText(/delete this message permanently/i)).toBeInTheDocument()
expect(state.calls).not.toContain('DELETE /archive/1')
await user.click(within(dialog).getByRole('button', { name: /confirm delete/i }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(state.calls).toContain('DELETE /archive/1')
await waitFor(() => expect(screen.queryByRole('button', { name: 'Subject 1' })).not.toBeInTheDocument())
expect(screen.getByRole('button', { name: 'Subject 2' })).toBeInTheDocument()
})
it('can back out of the confirmation', async () => {
const { user, state, dialog } = await open()
await within(dialog).findByText(/Hello/)
await user.click(within(dialog).getByRole('button', { name: /delete message/i }))
await user.click(await within(dialog).findByRole('button', { name: /keep message/i }))
expect(within(dialog).queryByText(/delete this message permanently/i)).not.toBeInTheDocument()
expect(state.archive[1]).toHaveLength(2)
})
it('shows a server error while deleting and stays open', async () => {
const { user, state, dialog } = await open()
await within(dialog).findByText(/Hello/)
state.fail['DELETE /archive/1'] = { status: 500, error: 'locked' }
await user.click(within(dialog).getByRole('button', { name: /delete message/i }))
await user.click(await within(dialog).findByRole('button', { name: /confirm delete/i }))
expect(await within(dialog).findByRole('alert')).toHaveTextContent('locked')
expect(state.archive[1]).toHaveLength(2)
})
})
})

View file

@ -1,3 +1,195 @@
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState, type FormEvent } from 'react'
import { useOutletContext } from 'react-router'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { api, type List } from '@/lib/api'
import { formatBytes, formatDate } from '@/lib/format'
const PAGE_SIZE = 25
export function ArchiveTab() {
return <h2 className="text-lg font-semibold">Archive</h2>
const list = useOutletContext<List>()
const [input, setInput] = useState('')
const [q, setQ] = useState('')
const [page, setPage] = useState(0)
const [openId, setOpenId] = useState<number | null>(null)
const archive = useQuery({
queryKey: ['archive', list.id, q, page],
queryFn: () => api.archive.list(list.id, { q, limit: PAGE_SIZE, offset: page * PAGE_SIZE }),
placeholderData: keepPreviousData,
})
function search(e: FormEvent) {
e.preventDefault()
setQ(input.trim())
setPage(0)
}
function clear() {
setInput('')
setQ('')
setPage(0)
}
const total = archive.data?.total ?? 0
const messages = archive.data?.messages ?? []
const from = page * PAGE_SIZE + 1
const to = Math.min((page + 1) * PAGE_SIZE, total)
return (
<div className="space-y-4">
<h2 className="text-lg font-semibold">Archive{archive.data && !q ? ` (${total})` : ''}</h2>
{list.archive_policy === 'off' && (
<p className="rounded-md border p-3 text-sm text-muted-foreground">
Archiving is off for this list: new messages are not stored. Set Archive to private or public in Settings.
</p>
)}
<form onSubmit={search} className="flex max-w-md gap-2">
<Input type="search" aria-label="Search archive" placeholder="Search subject, text, sender" value={input} onChange={(e) => setInput(e.target.value)} />
<Button type="submit">Search</Button>
{(q || input) && (
<Button type="button" variant="outline" onClick={clear}>
Clear
</Button>
)}
</form>
{archive.isPending && <p className="text-muted-foreground">Loading…</p>}
{archive.isError && <p role="alert" className="text-destructive">{archive.error.message}</p>}
{archive.data && q && total > 0 && (
<p className="text-sm text-muted-foreground">
{total} {total === 1 ? 'result' : 'results'} for “{q}”
</p>
)}
{archive.data && total === 0 && (
<p className="text-muted-foreground">{q ? 'No messages found.' : 'No messages archived yet.'}</p>
)}
{messages.length > 0 && (
<Table>
<TableHeader>
<TableRow>
<TableHead>Subject</TableHead>
<TableHead>From</TableHead>
<TableHead>Date</TableHead>
<TableHead>Size</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{messages.map((m) => (
<TableRow key={m.id}>
<TableCell>
<button type="button" className="text-left font-medium text-primary underline" onClick={() => setOpenId(m.id)}>
{m.subject}
</button>
</TableCell>
<TableCell>{m.sender}</TableCell>
<TableCell>{formatDate(m.date)}</TableCell>
<TableCell>{formatBytes(m.size)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
{total > PAGE_SIZE && (
<div className="flex items-center gap-3">
<Button variant="outline" size="sm" disabled={page === 0} onClick={() => setPage(page - 1)}>
Previous
</Button>
<span className="text-sm text-muted-foreground">
{from}–{to} of {total}
</span>
<Button variant="outline" size="sm" disabled={to >= total} onClick={() => setPage(page + 1)}>
Next
</Button>
</div>
)}
<MessageDialog listId={list.id} id={openId} onClose={() => setOpenId(null)} />
</div>
)
}
function MessageDialog({ listId, id, onClose }: { listId: number; id: number | null; onClose: () => void }) {
return (
<Dialog open={id !== null} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-2xl">{id !== null && <MessageView listId={listId} id={id} onClose={onClose} />}</DialogContent>
</Dialog>
)
}
function MessageView({ listId, id, onClose }: { listId: number; id: number; onClose: () => void }) {
const queryClient = useQueryClient()
const message = useQuery({ queryKey: ['message', id], queryFn: () => api.archive.get(id) })
const [confirming, setConfirming] = useState(false)
const [error, setError] = useState<string | null>(null)
const remove = useMutation({
mutationFn: () => api.archive.remove(id),
onSuccess: async () => {
queryClient.removeQueries({ queryKey: ['message', id] })
await queryClient.invalidateQueries({ queryKey: ['archive', listId] })
toast.success('Message deleted')
onClose()
},
onError: (e: Error) => setError(e.message),
})
if (message.isPending) {
return (
<DialogHeader>
<DialogTitle>Message</DialogTitle>
<DialogDescription>Loading…</DialogDescription>
</DialogHeader>
)
}
if (message.isError) {
return (
<DialogHeader>
<DialogTitle>Message</DialogTitle>
<p role="alert" className="text-sm text-destructive">
{message.error.message}
</p>
</DialogHeader>
)
}
const m = message.data
return (
<>
<DialogHeader>
<DialogTitle>{m.subject}</DialogTitle>
<DialogDescription>
{m.sender} · {formatDate(m.date)}
</DialogDescription>
</DialogHeader>
{/* React escapes the text; the body is never interpreted as HTML. */}
<pre className="max-h-96 overflow-auto rounded-md bg-muted p-3 text-sm whitespace-pre-wrap">{m.body}</pre>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
{confirming ? (
<div className="space-y-2">
<p className="text-sm">Delete this message permanently? It disappears from the archive and from search.</p>
<div className="flex gap-2">
<Button variant="destructive" disabled={remove.isPending} onClick={() => remove.mutate()}>
Confirm delete
</Button>
<Button variant="outline" onClick={() => setConfirming(false)}>
Keep message
</Button>
</div>
</div>
) : (
<Button variant="outline" onClick={() => { setError(null); setConfirming(true) }}>
Delete message
</Button>
)}
</>
)
}