Files
ianitor/apps/web/src/components/ChangeBar.svelte
T

166 lines
8.3 KiB
Svelte

<!-- SPDX-License-Identifier: CPAL-1.0
- Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
- License 1.0: see LICENSE (its Exhibit A is this file's notice). -->
<script lang="ts">
// Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not
// applied banner that stands in for its first line.
import { Banner, Button, Details, Icon, Progress } from "@ianitor/ui";
import { ApiError, call, del, newKey, post, sentence } from "../lib/api";
import { app, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { atTime, firstSentence, when } from "../lib/format";
import type { ApplyView } from "../lib/types";
let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props();
const o = $derived(app.overview);
const last = $derived(o?.last_apply ?? null);
const active = $derived(o?.active_apply ?? null);
const undo = $derived(o?.undo ?? null);
let moved = $state<string | null>(null);
let undoing = $state(false);
let pushing = $state(false);
const dismissKey = $derived(last ? `apply:${last.id}` : "");
function runningHeading(summary: string, a: { kind: string; hosts: string[]; summary: string } | null): string {
if (!a) return summary;
const h = a.hosts[0] ?? "";
switch (a.kind) {
case "add": return `Adding ${h}`;
case "remove": return `Removing ${h}`;
case "edit": return `Changing ${h}`;
case "share_links": return `Turning on share links for ${h}`;
case "undo": return `Undoing: ${a.summary.replace(/^Undid: /, "")}`;
case "restore": return a.summary.replace(/^Restored /, "Restoring ");
default: return summary;
}
}
async function doUndo() {
if (!undo?.target) return;
undoing = true;
moved = null;
try {
await post("/undo", { target_change_id: undo.target.change_id });
await refresh();
} catch (e) {
if (e instanceof ApiError && e.code === "undo.target_moved") {
moved = e.body.message;
await refresh();
} else {
moved = sentence(e);
}
} finally {
undoing = false;
}
}
async function pushNow() {
pushing = true;
try {
await call("POST", "/repo/push", {}, { idem: newKey() });
} catch {
/* the bar shows the push state on the next poll */
} finally {
pushing = false;
await refresh();
}
}
async function cancel(id: string) {
try {
await del(`/applies/${encodeURIComponent(id)}`);
toast("Cancelled before it started. Nothing changed.");
await refresh();
} catch (e) {
moved = sentence(e);
}
}
const keptLine = $derived.by(() => {
if (!last || last.state !== "kept") return "";
const t = when(last.finished_at ?? last.created_at, app.now);
const code = last.reason?.code ?? "";
if (code === "apply.kept.no_watch") return `${last.hosts[0] ?? ""} has no health check, so Ianitor only checked that it answers.`;
const what = code === "apply.kept.removed" ? "removed" : code === "apply.kept.no_edge" ? "saved, nothing checked (development mode)" : `health checks passed for ${o?.site?.watch_seconds ?? 60} s`;
const push = last.push?.state === "pushed" ? `pushed to Gitea as ${last.commit_short}` : last.push?.state === "pending" ? "sending to Gitea" : last.commit_short ? `saved as commit ${last.commit_short}` : "";
return [t, what, push].filter(Boolean).join(" · ");
});
const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed");
const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null);
// Ticks every second on the local clock (§7.2), not only on the 5 s poll.
const watchLeft = $derived(
active?.watch_ends_at ? secondsLeft(active.watch_ends_at) : active?.seconds_left != null ? active.seconds_left : null,
);
// The outcome's offer, by code (§7.5).
const offer = $derived.by(() => {
const c = last?.reason?.code ?? "";
if (/^apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
if (/^apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: last?.reason?.field ?? undefined };
if (/^apply\.failed\.(reload|build|edge_unreachable)$/.test(c)) return null;
if (last?.attempted_host) return { label: "Edit and try again", field: last?.reason?.field ?? undefined };
return null;
});
const pushLine = $derived.by(() => {
const p = last?.push;
const remote = "Gitea";
switch (p?.error_code) {
case "push.failed.rejected": return `Kept, but ${remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server.`;
case "push.failed.auth": return `Kept, but ${remote} refused Ianitor's access key. Check the key in Custos.`;
default: return `Kept, but not yet saved to ${remote}: ${remote} did not answer.${p?.next_try_at ? ` Ianitor tries again ${atTime(p.next_try_at, app.now)}.` : " Ianitor tries again by itself."}`;
}
});
const canPushNow = $derived(pushFailed && last?.push?.error_code !== "push.failed.rejected");
</script>
{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
{@const parts = firstSentence(last.reason?.message ?? "")}
<Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}>
{#snippet title()}<span class="ia-status" data-s="reverted"><Icon name="undo" /><span class="word">{last.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
{#if parts[1]}Reason: {parts[1]}{/if}
{#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}<Details detail={last.reason.detail} />{/if}
{#snippet actions()}
{#if offer}<Button variant="outline" onclick={() => onedit(last, offer?.field)}>{offer.label}</Button>{/if}
{/snippet}
</Banner>
{/if}
{#if last || active}
<section class="ia-bar" aria-label="Last change">
{#if active}
<div class="grow">
<div class="ia-status" data-s="running"><Icon name="clock" /><span class="word">{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}</span>
<span>{runningHeading(active.summary, active.kind ? active : null)}</span></div>
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}</div>
{#if active.state === "watching" && watchLeft != null}
{@const total = o?.site?.watch_seconds ?? 60}
<Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" />
{/if}
</div>
{#if active.state === "queued"}<Button onclick={() => cancel(active.id)}>Cancel</Button>{:else}<button type="button" class="ia-link" onclick={() => onshowsteps(active.id)}>Show steps</button>{/if}
{:else if last}
<div class="grow">
{#if last.state === "kept"}
<div><span class="ia-status" data-s="kept"><Icon name="check" /><span class="word">kept</span></span> {last.summary}</div>
<div class="ia-sub" class:warn={pushFailed}>{pushFailed ? pushLine : keptLine}</div>
{:else if undo?.target}
<div>Undo: {undo.target.summary}</div>
{/if}
{#if undo?.effect && (last.state !== "kept" || undo?.target?.change_id !== last.change_id)}<div class="ia-sub">{undo.effect}</div>{/if}
{#if moved}<div class="ia-sub" role="status">{moved}</div>{/if}
{#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</div>{/if}
{#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if}
</div>
{#if canPushNow}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
{#if undo?.target}
<Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available}
describedby={undoReason ? "undo-reason" : undefined}
label="Undo: {undo.target.summary}.{undo.effect ? ' ' + undo.effect + '.' : ''}">Undo</Button>
{/if}
{/if}
</section>
{/if}
<style>
.warn { color: var(--domi-warning); }
</style>