Files
shared/media-webui/src/lib/components/AnalyzerHistory.svelte
T

207 lines
7.9 KiB
Svelte
Raw Normal View History

<script lang="ts">
import { onMount } from 'svelte'
import { get } from '$lib/api'
import { Badge, Button, Card, EmptyState, SectionTitle } from '@gabriel20xx/web-ui'
type Json = Record<string, unknown>
type MediaType = 'image' | 'video' | 'audio' | 'funscript'
// mediaType fixes the card to one media type and hides the type filter entirely - used by the
// Images/Videos/Audios/Funscripts tabs, which have no business filtering across types. Every
// other page (dashboard, schedules, discover) omits it and gets the full type filter instead.
let {
mediaType,
title = 'Processing history',
description = 'Recently processed elements and their results.',
pageSize = 10,
}: {
mediaType?: MediaType
title?: string
description?: string
pageSize?: number
} = $props()
const TYPE_OPTIONS: { value: string; label: string }[] = [
{ value: '', label: 'All types' },
{ value: 'image', label: 'Images' },
{ value: 'video', label: 'Videos' },
{ value: 'audio', label: 'Audios' },
{ value: 'funscript', label: 'Funscripts' },
]
const STATUS_OPTIONS: { value: string; label: string }[] = [
{ value: '', label: 'All statuses' },
{ value: 'queued', label: 'Queued' },
{ value: 'processing', label: 'Processing' },
{ value: 'done', label: 'Done' },
{ value: 'error', label: 'Error' },
]
let typeFilter = $state('')
let statusFilter = $state('')
let currentPage = $state(1)
let entries = $state<Json[]>([])
let total = $state(0)
let loading = $state(true)
let error = $state('')
// The type filter is only ever shown (and only ever meaningful) when the parent hasn't already
// fixed one - once it's fixed, the fixed value always wins over whatever's left in the dropdown
// state from a previous type-agnostic usage of this same component instance.
const effectiveType = $derived(mediaType ?? typeFilter)
function firstValue(entry: Json, keys: string[], fallback: string) {
for (const key of keys) {
const value = entry[key]
if (value !== undefined && value !== null && String(value).trim() !== '') {
return String(value)
}
}
return fallback
}
function statusTone(status: string): 'default' | 'primary' | 'success' | 'warning' | 'danger' {
const normalized = status.toLowerCase()
if (normalized.includes('error') || normalized.includes('fail')) return 'danger'
if (normalized.includes('process') || normalized.includes('running')) return 'primary'
if (normalized.includes('queue') || normalized.includes('pending')) return 'warning'
if (normalized.includes('done') || normalized.includes('complete') || normalized.includes('success'))
return 'success'
return 'default'
}
async function load({ background = false } = {}) {
if (!background) loading = true
error = ''
try {
const params: [string, string][] = [
['limit', String(pageSize)],
['offset', String((currentPage - 1) * pageSize)],
]
if (effectiveType) params.push(['mediaType', effectiveType])
if (statusFilter) params.push(['status', statusFilter])
const query = params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&')
const response = await get<Json>(`/api/history?${query}`)
const rawEntries = response.items || response.history || response.rows
entries = Array.isArray(rawEntries) ? (rawEntries as Json[]) : []
total = Number(response.total ?? entries.length) || 0
} catch (reason) {
error = reason instanceof Error ? reason.message : 'Unable to load processing history.'
entries = []
total = 0
} finally {
if (!background) loading = false
}
}
function goToPage(next: number) {
const target = Math.max(1, next)
if (target === currentPage) return
currentPage = target
void load()
}
function applyTypeFilter(value: string) {
typeFilter = value
currentPage = 1
void load()
}
function applyStatusFilter(value: string) {
statusFilter = value
currentPage = 1
void load()
}
// Re-fetches whenever the mediaType *prop* changes - the Images/Videos/Audios/Funscripts tabs
// all reuse one component instance across tab switches (same position in the parent's template),
// so this is what makes switching tabs actually reload that tab's own history instead of still
// showing the previous tab's entries. Also covers the initial load on mount.
$effect(() => {
void mediaType
currentPage = 1
void load()
})
onMount(() => {
const timer = window.setInterval(() => void load({ background: true }), 10_000)
return () => window.clearInterval(timer)
})
</script>
<Card class="space-y-4">
<SectionTitle {title} {description} />
<div class="flex flex-wrap items-center gap-3">
{#if !mediaType}
<select
class="field h-8 w-40 text-sm"
value={typeFilter}
onchange={(event) => applyTypeFilter(event.currentTarget.value)}
>
{#each TYPE_OPTIONS as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
</select>
{/if}
<select
class="field h-8 w-40 text-sm"
value={statusFilter}
onchange={(event) => applyStatusFilter(event.currentTarget.value)}
>
{#each STATUS_OPTIONS as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
</select>
</div>
{#if error}
<p class="rounded-md border border-danger/30 bg-danger/10 p-3 text-xs text-danger">{error}</p>
{/if}
{#if loading}
<p class="text-sm text-muted-fg">Loading history…</p>
{:else if entries.length === 0}
<EmptyState title="No processed elements" message="Processed files and their results will appear here." />
{:else}
<div class="space-y-2">
{#each entries as entry, index (String(entry.id || entry.file_path || index))}
{@const name = firstValue(entry, ['file_name', 'fileName', 'file', 'type', 'action'], 'Processed element')}
{@const path = firstValue(entry, ['file_path', 'filePath', 'path'], '')}
{@const entryMediaType = firstValue(entry, ['media_type', 'mediaType', 'type'], '')}
{@const status = firstValue(entry, ['status', 'state'], 'recorded')}
{@const progress = firstValue(entry, ['progress'], '')}
{@const timestamp = firstValue(
entry,
['finished_at', 'finishedAt', 'created_at', 'createdAt', 'queued_at', 'queuedAt', 'timestamp'],
'',
)}
{@const message = firstValue(entry, ['error', 'error_message', 'message'], '')}
<div class="rounded-md border border-border bg-bg p-3">
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<p class="truncate text-sm font-medium text-fg">{name}</p>
{#if path}<p class="mt-1 truncate text-xs text-muted-fg">{path}</p>{/if}
</div>
<Badge variant={statusTone(status)}>{status}</Badge>
</div>
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-fg">
{#if entryMediaType}<span>{entryMediaType}</span>{/if}
{#if progress}<span>{progress}% complete</span>{/if}
{#if timestamp}<span>{timestamp}</span>{/if}
</div>
{#if message}<p class="mt-2 truncate text-xs text-danger">{message}</p>{/if}
</div>
{/each}
</div>
<div class="flex items-center justify-between border-t border-border pt-3">
<p class="text-xs text-muted-fg">Showing {entries.length} of {total.toLocaleString()}</p>
<div class="flex gap-2">
<Button variant="secondary" size="sm" disabled={currentPage <= 1} onclick={() => goToPage(currentPage - 1)}
>Previous</Button
><Button
variant="secondary"
size="sm"
disabled={currentPage * pageSize >= total}
onclick={() => goToPage(currentPage + 1)}>Next</Button
>
</div>
</div>
{/if}
</Card>