Files
electric-cherry/src/routes/campaigns/+page.svelte
T

188 lines
12 KiB
Svelte

<script lang="ts">
import { contextHref } from '$lib/navigation-context.js';
import { timeFormat } from '$ui/stores/time-zone.js';
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { pollVisible } from '$ui/poll.js';
import { campaignOutcome, campaignTitle, fetchCampaigns, type CampaignSummary } from '$ui/campaigns.js';
import Badge from '$ui/components/primitives/Badge.svelte';
import Button from '$ui/components/primitives/Button.svelte';
import SectionHeader from '$ui/components/primitives/SectionHeader.svelte';
import EmptyState from '$ui/components/primitives/EmptyState.svelte';
interface Deployment extends CampaignSummary { id: string; started_at: string }
let loadError = $state('');
let limit = $state(25);
let historyTotal = $state(0);
let loadSequence = 0;
let active = $state<Deployment[]>([]);
let history = $state<Deployment[]>([]);
let loading = $state(true);
let refreshing = $state(false);
let refreshedAt = $state(Date.now());
let query = $state('');
let status = $state('');
let action = $state('');
const filtered = $derived(Boolean(query.trim() || status || action));
$effect(() => {
query = $page.url.searchParams.get('q') ?? $page.url.searchParams.get('server') ?? '';
status = $page.url.searchParams.get('status') ?? '';
action = $page.url.searchParams.get('action') ?? '';
const requestedLimit = Number($page.url.searchParams.get('limit'));
limit = Number.isFinite(requestedLimit) ? Math.max(25, Math.floor(requestedLimit)) : 25;
});
function saveContext(reset = false) {
if (reset) limit = 25;
const url = new URL($page.url);
url.searchParams.delete('server');
for (const [key, value] of Object.entries({ q: query, status, action, limit: limit > 25 ? String(limit) : '' })) {
if (value) url.searchParams.set(key, value); else url.searchParams.delete(key);
}
void goto(url, { replaceState: true, noScroll: true, keepFocus: true });
}
function clearFilters() { query = ''; status = ''; action = ''; saveContext(true); }
async function loadCampaigns(signal?: AbortSignal): Promise<boolean> {
const sequence = ++loadSequence;
refreshing = true;
try {
const filters = { q: query, status, action };
const [historyPage, activePage] = await Promise.all([
fetchCampaigns<Deployment>({ ...filters, view: 'history' }, limit, signal),
fetchCampaigns<Deployment>({ ...filters, active: 'true' }, Infinity, signal)
]);
if (sequence !== loadSequence || signal?.aborted) return true;
active = activePage.deployments; history = historyPage.deployments;
historyTotal = historyPage.total; loadError = ''; refreshedAt = Date.now();
return true;
} catch (error) {
if (sequence === loadSequence && !signal?.aborted) loadError = (error as Error).message;
return false;
} finally {
if (sequence === loadSequence && !signal?.aborted) { loading = false; refreshing = false; }
}
}
$effect(() => {
void limit; void query; void status; void action;
return pollVisible(loadCampaigns, 15000);
});
function ago(iso: string): string {
const elapsed = refreshedAt - new Date(iso).getTime();
if (elapsed < 60_000) return 'Just now';
if (elapsed < 3_600_000) return `${Math.floor(elapsed / 60_000)} min ago`;
if (elapsed < 86_400_000) return `${Math.floor(elapsed / 3_600_000)} hr ago`;
const days = Math.floor(elapsed / 86_400_000);
return `${days} day${days === 1 ? '' : 's'} ago`;
}
</script>
<svelte:head><title>Campaigns | Electric Cherry</title></svelte:head>
<div class="page">
<SectionHeader title="Campaigns" />
<div class="toolbar">
<label class="search">Search<input type="search" bind:value={query} oninput={() => saveContext(true)} placeholder="Script, campaign, or server" maxlength="100" /></label>
<label>Status<select bind:value={status} onchange={() => saveContext(true)}>
<option value="">All statuses</option><option value="progress">In progress</option><option value="attention">Needs attention</option><option value="complete">Complete</option><option value="rolled-back">Rolled back</option><option value="inactive">Inactive</option>
</select></label>
<label>Type<select bind:value={action} onchange={() => saveContext(true)}>
<option value="">All types</option><option value="promote">Promote</option><option value="rollback">Rollback</option><option value="drift">Maintenance repair</option>
</select></label>
{#if filtered}<Button variant="ghost" onclick={clearFilters}>Clear filters</Button>{/if}
</div>
{#if loadError}<div class="ui-error" role="alert">{loadError}<Button size="sm" onclick={() => loadCampaigns()}>Retry</Button></div>{/if}
{#if loading}
<div class="loading">Loading campaigns…</div>
{:else}
<div class="results" aria-busy={refreshing}>
{#if active.length}
<section class="section" aria-labelledby="active-heading">
<h2 id="active-heading">Active <span>{active.length}</span></h2>
{@render campaignTable(active, true)}
</section>
{:else}
<p class="quiet">{filtered ? 'No active campaigns match these filters.' : 'No active campaigns.'}</p>
{/if}
<section class="section" aria-labelledby="history-heading">
<h2 id="history-heading">History <span>{historyTotal}</span></h2>
{#if history.length}
{@render campaignTable(history)}
{#if historyTotal > 25}
<div class="list-footer"><span role="status">Showing {history.length} of {historyTotal} campaigns</span>
{#if history.length < historyTotal}<Button size="sm" disabled={refreshing} onclick={() => { limit += 25; saveContext(); }}>Load more</Button>{/if}
</div>
{/if}
{:else}
<EmptyState title={filtered ? 'No matching campaign history' : 'No campaign history yet'} description={filtered ? 'Try a different search or clear the filters.' : 'Past campaigns appear here while their history is retained.'} />
{/if}
</section>
</div>
{/if}
</div>
{#snippet campaignTable(rows: Deployment[], showProgress = false)}
<div class="table-scroll">
<table>
<caption class="sr-only">{showProgress ? 'Active campaigns' : 'Campaign history'}</caption>
<colgroup><col class="campaign-col" /><col class="servers-col" /><col class="status-col" /><col class="started-col" /></colgroup>
<thead><tr><th scope="col">Campaign</th><th scope="col" class="server-count">Servers</th><th scope="col">Status</th><th scope="col" class="started">Started</th></tr></thead>
<tbody>
{#each rows as campaign (campaign.id)}
{@const outcome = campaignOutcome(campaign)}
<tr>
<td><a class="campaign-link" href={contextHref(`/campaigns/${encodeURIComponent(campaign.id)}`, $page.url)}>{campaignTitle(campaign)}</a></td>
<td class="server-count">{campaign.servers.length}</td>
<td><div class="status"><Badge variant={outcome.tone} size="md">{outcome.label}</Badge>
{#if showProgress}<progress max={campaign.servers.length || 1} value={outcome.completed} aria-label={`${outcome.completed} of ${campaign.servers.length} servers complete`}></progress>{/if}
</div></td>
<td class="started"><button type="button" class="timestamp" aria-label={`Started ${$timeFormat.dateTime(campaign.started_at)}`}><time datetime={campaign.started_at}>{ago(campaign.started_at)}</time><span class="exact-time" aria-hidden="true">{$timeFormat.dateTime(campaign.started_at)}</span></button></td>
</tr>
{/each}
</tbody>
</table>
</div>
{/snippet}
<style>
.page, .results { display: grid; gap: var(--space-6); min-width: 0; }
.toolbar { display: flex; align-items: flex-end; flex-wrap: wrap; gap: 12px; }
label { display: grid; gap: 6px; font-size: var(--text-xs); color: var(--text-secondary); }
.search { flex: 1; min-width: 220px; }
input, select { padding: 10px 12px; min-height: 40px; background: var(--surface-sunken); color: var(--text-primary); border: 1px solid var(--border-control); border-radius: var(--radius-sm); font: inherit; font-size: var(--text-sm); }
input:focus-visible, select:focus-visible, .timestamp:focus-visible { outline: 2px solid var(--accent-primary); outline-offset: 2px; }
.section { display: grid; gap: 12px; min-width: 0; }
h2 { margin: 0; font-size: var(--text-md); font-weight: var(--weight-semibold); }
h2 span { margin-left: 8px; color: var(--text-tertiary); font-size: var(--text-sm); font-weight: var(--weight-regular); }
.quiet { margin: 0; color: var(--text-tertiary); font-size: var(--text-sm); }
.table-scroll { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; table-layout: fixed; font-size: var(--text-sm); text-align: left; }
.campaign-col { width: 46%; }.servers-col { width: 12%; }.status-col { width: 25%; }.started-col { width: 17%; }
th { padding: 10px 16px; border-bottom: 1px solid var(--border-strong); font-size: var(--text-xs); font-weight: var(--weight-medium); color: var(--text-tertiary); }
td { padding: 16px; border-bottom: 1px solid var(--border-subtle); vertical-align: middle; }
tbody tr:hover { background: var(--surface); }
.campaign-link { color: var(--text-primary); font-weight: var(--weight-semibold); text-decoration: none; overflow-wrap: anywhere; }
.campaign-link:hover { color: var(--accent-primary-hover); text-decoration: underline; text-underline-offset: 4px; }
.server-count { text-align: right; font-variant-numeric: tabular-nums; }
.status { display: grid; justify-items: start; gap: 8px; }
progress { width: 130px; max-width: 100%; height: 4px; appearance: none; border: 0; border-radius: var(--radius-pill); overflow: hidden; background: var(--surface-raised); }
progress::-webkit-progress-bar { background: var(--surface-raised); }
progress::-webkit-progress-value { background: var(--accent-primary); }
progress::-moz-progress-bar { background: var(--accent-primary); }
.started { text-align: right; color: var(--text-secondary); }
.timestamp { position: relative; display: inline-block; white-space: nowrap; cursor: help; background: transparent; color: inherit; font: inherit; border: 0; padding: 0; }
.exact-time { display: none; position: absolute; right: 0; bottom: 100%; z-index: 1; background: var(--surface-overlay); color: var(--text-primary); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); padding: 6px 10px; font-size: var(--text-xs); }
.timestamp:hover .exact-time, .timestamp:focus .exact-time { display: block; }
.list-footer { display: flex; justify-content: space-between; align-items: center; gap: 16px; color: var(--text-secondary); font-size: var(--text-sm); }
.loading { text-align: center; padding: var(--space-16); color: var(--text-tertiary); }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
@media (max-width: 720px) {
table { min-width: 580px; }
th, td { padding: 12px 8px; }
.search { flex-basis: 100%; }
.toolbar > label:not(.search) { flex: 1; }
}
</style>