loopable / web /src /views-trash /TrashPanel.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
071ce2b verified
Raw History Blame Contribute Delete
16 kB
// ---------------------------------------------------------------------------
// views-trash/TrashPanel.tsx - W50-T26, ruling R9, contract C4.
//
// ⭐⭐ R9, verbatim: *"Saved views get Trash (30 days, one-click Restore) + an
// audit trail (who, when, what, from where) … + an Administrator trail view"*.
// Two tabs, one component: "Trash" for everyone, "Trail" for Administrators.
//
// ⛔ THIS TICKET SHIPS THE COMPONENT, NOT ITS MOUNT. `ViewSidebar.tsx` opens it
// from the database "..." menu in W50-T27, a declared handover in another lane's
// fence. `platform/verify_shared_views.py` carries a RED-until-wired leg that
// goes green the moment that lands - and that leg is driven through all three
// states inside the gate, so it is a check rather than a decoration.
//
// ⛔ IT IMPORTS NOTHING FROM `customer-grid/**`, deliberately: that tree is
// another lane's and the combine merges them separately. Every fetch lives in
// `trashApi.ts` and there is not one route string below.
//
// ⛔ THE TRAIL TAB HIDES ITSELF ON 403. A non-Administrator is not shown a tab
// that answers an error; "you may not read this" is a fact about the account,
// not a failure to report. `trashApi.fetchTrail` returns TRAIL_FORBIDDEN rather
// than throwing, so the two cases stay distinguishable here.
//
// ⛔ NO EM DASH AND NO EN DASH in any string below (standing rule 2), no
// emojis, sentence case throughout, and every size and colour is an --lp-*
// token in `trash.css`.
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useRef, useState } from 'react'
import { ConfirmDialog } from '../ui/ConfirmDialog'
import { useEscapeClose } from '../ui/useEscapeClose'
import { TOAST_EVENT } from '../apiContract'
import {
fetchTrail,
fetchTrash,
previewPurge,
purgeView,
restoreView,
TRAIL_FORBIDDEN,
type TrailRow,
type TrashRow,
} from './trashApi'
import './trash.css'
export type TrashPanelProps = {
/** The database whose deleted views this panel lists. */
tableKey: string
/** Called with the view id after a successful restore, so the host can
* refresh its own rail without this component knowing one exists. */
onRestored?: (viewId: string) => void
/** Called when the reader asks to close the panel (Escape). Optional: a host
* that renders this inline rather than as an overlay simply omits it, and
* the panel then claims no key at all. */
onClose?: () => void
}
/** W51-T26 / R11 — the body of the "Delete forever" confirm, given the SERVER's count.
*
* ⛔⛔ A PURE FUNCTION OF THE COUNT, exported so the gate can drive all three branches
* without a DOM. There are three because there are three different facts, and collapsing
* them is how a dialog ends up claiming something it does not know:
*
* n > 0 the cells that will keep this view's filter, named with their number.
* n === 0 nothing depends on it, so the dialog says only that this cannot be undone.
* null the count could NOT be taken. That is NOT zero, and rendering it as zero would
* tell somebody nothing depends on a view while the scan that would have said so
* never ran.
*
* ⛔ NO EM DASH AND NO EN DASH (standing rule 2), sentence case, and the number is the one
* the server counted rather than anything this component worked out.
*/
export function purgeConfirmBody(cells: number | null): string {
const undone = 'This cannot be undone.'
if (cells === null) {
return `We could not count the Sheet cells that use this view, so we cannot say how many will keep its filter. ${undone}`
}
if (cells > 0) {
const noun = cells === 1 ? 'Sheet cell' : 'Sheet cells'
return `${cells} ${noun} will keep this view's filter. ${undone}`
}
return `No Sheet cell uses this view. ${undone}`
}
/** The view "Delete forever" is asking about, with the count already taken. */
type PurgeTarget = {
id: string
name: string
cells: number | null
}
type Tab = 'trash' | 'trail'
const MINUTE = 60
const HOUR = 60 * MINUTE
const DAY = 24 * HOUR
/** "3 days ago" - a relative age, in the plainest words that are still exact. */
function relativeAge(epochSeconds: number, now: number): string {
const secs = Math.max(0, now - epochSeconds)
if (secs < MINUTE) return 'just now'
if (secs < HOUR) {
const mins = Math.floor(secs / MINUTE)
return `${mins} minute${mins === 1 ? '' : 's'} ago`
}
if (secs < DAY) {
const hours = Math.floor(secs / HOUR)
return `${hours} hour${hours === 1 ? '' : 's'} ago`
}
const days = Math.floor(secs / DAY)
return `${days} day${days === 1 ? '' : 's'} ago`
}
/** The absolute date beside the relative one. A relative age alone cannot be
* checked against anything; an absolute one alone has to be worked out. */
function absoluteDate(epochSeconds: number): string {
const when = new Date(epochSeconds * 1000)
if (Number.isNaN(when.getTime())) return ''
return when.toLocaleDateString(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric',
})
}
function isoStamp(epochSeconds: number): string {
const when = new Date(epochSeconds * 1000)
return Number.isNaN(when.getTime()) ? '' : when.toISOString()
}
/** The trail's verbs, as a person would say them. */
const ACTION_LABEL: Record<string, string> = {
create: 'Created',
rename: 'Renamed',
move: 'Moved',
duplicate: 'Duplicated',
share: 'Shared',
delete: 'Deleted',
restore: 'Restored',
}
function trailName(row: TrailRow): string {
return row.after?.name || row.before?.name || row.view_id || 'a view'
}
function TrashIcon() {
return (
<svg className="vt-icon" viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<path d="M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8h5.8l.6-8" />
</svg>
)
}
function useRefusalToast() {
const [messages, setMessages] = useState<{ id: number; text: string }[]>([])
const sequence = useRef(0)
const delivered = useRef(0)
useEffect(() => {
if (!messages.length) return
const through = messages[messages.length - 1].id
for (const message of messages) {
if (message.id <= delivered.current) continue
delivered.current = message.id
const text = message.text
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: 'error' } }))
}
setMessages((current) => current.filter((message) => message.id > through))
}, [messages])
return (text: string) => {
if (!text) return
const message = { id: ++sequence.current, text }
setMessages((current) => [...current, message])
}
}
export function TrashPanel({ tableKey, onRestored, onClose }: TrashPanelProps) {
const refuse = useRefusalToast()
const [tab, setTab] = useState<Tab>('trash')
const [rows, setRows] = useState<TrashRow[] | null>(null)
const [retentionDays, setRetentionDays] = useState(30)
const [trail, setTrail] = useState<TrailRow[] | null>(null)
const [isAdmin, setIsAdmin] = useState(false)
const [busyId, setBusyId] = useState('')
const [problem, setProblem] = useState('')
const [purging, setPurging] = useState<PurgeTarget | null>(null)
const [purgeBusy, setPurgeBusy] = useState(false)
const alive = useRef(true)
// ⚠ READ AT RENDER, NOT MEMOISED. A memo over [rows, trail] recomputes only when a
// fetch lands, so a panel left open would freeze at "3 days ago" for as long as it is
// open. Date.now() is the same cost as reading the memo, and no interval is added: the
// ages refresh on the next render, which is what any interaction already causes.
const now = Date.now() / 1000
useEffect(() => {
alive.current = true
return () => {
alive.current = false
}
}, [])
const loadTrash = useCallback(async () => {
setProblem('')
try {
const answer = await fetchTrash(tableKey)
if (!alive.current) return
setRows(answer.rows)
setRetentionDays(answer.retentionDays)
} catch (err) {
if (!alive.current) return
setRows([])
setProblem(err instanceof Error ? err.message : 'the deleted views could not be read.')
}
}, [tableKey])
useEffect(() => {
void loadTrash()
}, [loadTrash])
// ⛔ THE ROUTE DECIDES WHO IS AN ADMINISTRATOR, not the client. Asking it once
// is both the capability probe and the first page of the trail, so a
// non-Administrator costs one refused request and sees no tab.
useEffect(() => {
let cancelled = false
void (async () => {
try {
const answer = await fetchTrail(tableKey)
if (cancelled || !alive.current) return
if (answer === TRAIL_FORBIDDEN) {
setIsAdmin(false)
setTrail(null)
return
}
setIsAdmin(true)
setTrail(answer)
} catch {
// An unreadable trail is not this panel's subject. The Trash tab, which
// is what the user opened, keeps working and the tab stays hidden.
if (!cancelled && alive.current) setIsAdmin(false)
}
})()
return () => {
cancelled = true
}
}, [tableKey])
const restore = useCallback(
async (viewId: string) => {
setProblem('')
setBusyId(viewId)
try {
await restoreView(tableKey, viewId)
if (!alive.current) return
setRows((current) => (current || []).filter((row) => row.id !== viewId))
onRestored?.(viewId)
} catch (err) {
if (!alive.current) return
const text = err instanceof Error ? err.message : 'That view could not be restored.'
refuse(text)
} finally {
if (alive.current) setBusyId('')
}
},
[onRestored, tableKey],
)
// ⛔ THE COUNT IS FETCHED BEFORE THE DIALOG OPENS, not after. A dialog that appears first and
// fills its own sentence in a moment later is a dialog somebody can confirm while it still says
// nothing, which is the one moment the number was for.
const askDeleteForever = useCallback(
async (row: TrashRow) => {
setProblem('')
setBusyId(row.id)
try {
const preview = await previewPurge(tableKey, row.id)
if (!alive.current) return
setPurging({ id: row.id, name: preview.name || row.name, cells: preview.cells })
} catch (err) {
if (!alive.current) return
const text = err instanceof Error ? err.message : 'That view could not be read.'
refuse(text)
} finally {
if (alive.current) setBusyId('')
}
},
[tableKey],
)
const confirmDeleteForever = useCallback(async () => {
if (!purging) return
const viewId = purging.id
setPurgeBusy(true)
try {
await purgeView(tableKey, viewId)
if (!alive.current) return
setRows((current) => (current || []).filter((row) => row.id !== viewId))
setPurging(null)
} catch (err) {
if (!alive.current) return
const text = err instanceof Error ? err.message : 'That view could not be deleted.'
refuse(text)
setPurging(null)
} finally {
if (alive.current) setPurgeBusy(false)
}
}, [purging, tableKey])
// ⛔ ESCAPE CLOSES THE PANEL THROUGH THE ONE ARBITER (contract C8), and it is claimed ONLY when
// a host gave us somewhere to close to. The open ConfirmDialog pushes itself on top of the same
// stack, so topmost-wins already means the first Escape closes the dialog and the second closes
// the panel; no ordering is decided here.
const requestClose = useCallback(() => {
onClose?.()
}, [onClose])
useEscapeClose(!!onClose, requestClose)
const showTrail = isAdmin && tab === 'trail'
const listed = rows || []
return (
<div className="vt-panel">
<div className="vt-tabs" role="tablist" aria-label="Deleted views">
<button
type="button"
role="tab"
id="vt-tab-trash"
className={'vt-tab' + (tab === 'trash' ? ' vt-tab-on' : '')}
aria-selected={tab === 'trash'}
aria-controls="vt-pane"
onClick={() => setTab('trash')}
>
Trash
</button>
{isAdmin ? (
<button
type="button"
role="tab"
id="vt-tab-trail"
className={'vt-tab' + (tab === 'trail' ? ' vt-tab-on' : '')}
aria-selected={tab === 'trail'}
aria-controls="vt-pane"
onClick={() => setTab('trail')}
>
Trail
</button>
) : null}
</div>
{problem ? (
<p className="vt-problem" role="alert">
{problem}
{' '}
<button type="button" className="vt-restore" onClick={() => void loadTrash()}>Retry</button>
</p>
) : null}
<div
className="vt-pane"
id="vt-pane"
role="tabpanel"
aria-labelledby={showTrail ? 'vt-tab-trail' : 'vt-tab-trash'}
>
{showTrail ? (
<ul className="vt-list">
{(trail || []).map((row, index) => (
<li className="vt-trail-row" key={`${row.ts}-${row.view_id}-${index}`}>
<span className="vt-trail-what">
{ACTION_LABEL[row.action] || row.action} {trailName(row)}
</span>
<span className="vt-meta">
{row.actor || 'somebody'}
{' · '}
<time dateTime={isoStamp(row.ts)}>{relativeAge(row.ts, now)}</time>
{row.from?.client ? ` · ${row.from.client}` : ''}
</span>
</li>
))}
{(trail || []).length === 0 ? (
<li className="vt-empty">Nothing has happened to a view on this database yet.</li>
) : null}
</ul>
) : (
<ul className="vt-list">
{listed.map((row) => (
<li className="vt-row" key={row.id}>
<span className="vt-row-mark">
<TrashIcon />
</span>
<span className="vt-row-body">
<span className="vt-name">{row.name}</span>
<span className="vt-meta">
Deleted <time dateTime={isoStamp(row.deletedAt)}>
{relativeAge(row.deletedAt, now)}
</time>
{absoluteDate(row.deletedAt) ? ` · ${absoluteDate(row.deletedAt)}` : ''}
{row.deletedBy ? ` · ${row.deletedBy}` : ''}
{row.sharedCount > 0
? ` · ${row.sharedCount} share${row.sharedCount === 1 ? '' : 's'}`
: ''}
</span>
</span>
<button
type="button"
className="vt-restore"
disabled={busyId === row.id}
onClick={() => void restore(row.id)}
>
{busyId === row.id ? 'Restoring' : 'Restore'}
</button>
<button
type="button"
className="vt-purge"
disabled={busyId === row.id}
onClick={() => void askDeleteForever(row)}
>
Delete forever
</button>
</li>
))}
{rows !== null && listed.length === 0 ? (
<li className="vt-empty">
Nothing has been deleted in the last {retentionDays} days.
</li>
) : null}
</ul>
)}
</div>
<ConfirmDialog
open={purging !== null}
title={purging ? `Delete ${purging.name} forever` : 'Delete this view forever'}
body={purging ? purgeConfirmBody(purging.cells) : null}
confirmLabel="Delete forever"
tone="destructive"
busy={purgeBusy}
onConfirm={() => void confirmDeleteForever()}
onCancel={() => setPurging(null)}
/>
</div>
)
}
export default TrashPanel