Files
archie/ui/src/workflows/BindEvent.vue
T
sam 79f84793c7 fix(ui): keep the workflows toolbar readable on the 36px ladder
The run selector is the only control that gives up width, and beside the
workflow list it had none left: Open and the run's version move into the one
menu at every width, so the picked run stays readable from 390 to 1440.

Step editor and binding fields take the next rung (h-8) so they match the
selects and switches they sit beside.
2026-10-18 22:42:14 +11:00

360 lines
17 KiB
Vue

<script setup lang="ts">
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { computed, onMounted, ref, watch } from "vue";
import { ArrowLeft, Braces, Type } from "@lucide/vue";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { api } from "@/lib/api";
import { useLiveResource } from "@/stores/session";
import { statusKind, statusLabel, takesRepository, type Binding } from "@/bindings/binding-draft";
import type { Capture } from "@/captures/state";
import SourceSecret from "@/sources/SourceSecret.vue";
import { sourceURL, type Source } from "@/sources/source-signing";
import type { EventType } from "@/captures/event-types";
import type { Mapping, Preview } from "@/mappings/state";
import {
bindingInputs,
captureBody,
captureHeaders,
mappingFields,
payloadPaths,
problems,
REPOSITORY_FIELD,
rowsFromBinding,
shortValue,
type InputRow,
type InputSpec,
} from "./bind-event";
import OptionSelect from "./OptionSelect.vue";
import { workflowField } from "./workflow-edit";
const props = defineProps<{ yaml: string; binding: Binding | null }>();
const emit = defineEmits<{ back: []; saved: [] }>();
const NEW_SOURCE = "__new__";
const workflow = computed(() => String(workflowField(props.yaml, "id") ?? ""));
const inputs = computed(() =>
Object.entries((workflowField(props.yaml, "inputs") as Record<string, InputSpec> | undefined) ?? {}),
);
const repository = computed(() => takesRepository({ id: "", name: "", repository: String(workflowField(props.yaml, "repository") ?? "") || undefined }));
const sources = ref<string[]>([]);
// The operator's label for each source path, where one is set.
const sourceNames = ref<Record<string, string>>({});
// The placeholder travels as an empty option, which a Select cannot hold: it
// reserves that value for clearing, so OptionSelect carries it as a sentinel.
const sourceOptions = computed(() => [
{ value: "", label: "Pick a source", disabled: true },
...sources.value.map((path) => ({ value: path, label: sourceNames.value[path] ? `${sourceNames.value[path]} (${path})` : path })),
{ value: NEW_SOURCE, label: "New source…" },
]);
const captures = ref<Capture[]>([]);
const eventTypes = ref<EventType[]>([]);
const mappings = ref<Mapping[]>([]);
const bindings = ref<Binding[]>([]);
const loading = ref(true);
const source = ref("");
const newSource = ref("");
const captureId = ref<string | null>(null);
const rows = ref<Record<string, InputRow>>({});
const repositoryPath = ref("");
const preview = ref<Preview | null>(null);
const saving = ref(false);
const confirmRemove = ref(false);
const creatingSource = ref(false);
const revealed = ref<Source | null>(null);
const error = ref("");
const status = ref(props.binding?.status ?? "");
async function loadCaptures(): Promise<void> {
const listed = await api.captures<{ captures?: Capture[] }>(100).catch(() => null);
captures.value = listed?.captures ?? [];
}
onMounted(async () => {
const [listed, types, mapped, bound] = await Promise.all([
api.sources<{ sources?: { path: string; name?: string }[] }>().catch(() => null),
api.eventTypes<{ event_types?: EventType[] }>().catch(() => null),
api.mappings<{ mappings?: Mapping[] }>().catch(() => null),
api.bindings<{ bindings?: Binding[] }>().catch(() => null),
loadCaptures(),
]);
sources.value = (listed?.sources ?? []).map((s) => s.path);
sourceNames.value = Object.fromEntries((listed?.sources ?? []).filter((s) => s.name).map((s) => [s.path, s.name!]));
eventTypes.value = types?.event_types ?? [];
mappings.value = mapped?.mappings ?? [];
bindings.value = bound?.bindings ?? [];
if (props.binding) {
source.value = props.binding.matcher?.source ?? "";
const mapping = mappings.value.find((m) => String(m.id) === props.binding?.mapping_id);
const filled = rowsFromBinding(props.binding, mapping?.fields ?? []);
rows.value = filled.rows;
repositoryPath.value = filled.repositoryPath;
} else if (sources.value.length === 1) {
source.value = sources.value[0]!;
}
for (const [name] of inputs.value) rows.value[name] ??= { from: "path", path: "", value: "" };
loading.value = false;
});
useLiveResource("captures", () => void loadCaptures(), 500);
const sourcePath = computed(() => (source.value === NEW_SOURCE ? newSource.value.trim() : source.value));
const hookURL = computed(() => sourceURL(window.location.origin, sourcePath.value));
const sourceCaptures = computed(() => captures.value.filter((c) => c.source === sourcePath.value));
// The newest event of the source is the example until another is picked.
watch(sourceCaptures, (list) => {
if (!list.some((c) => c.id === captureId.value)) captureId.value = list[0]?.id ?? null;
}, { immediate: true });
const capture = computed(() => sourceCaptures.value.find((c) => c.id === captureId.value));
const payload = computed(() => captureBody(capture.value));
const paths = computed(() => payloadPaths(payload.value));
const fields = computed(() => mappingFields(inputs.value, rows.value, repository.value ? repositoryPath.value : ""));
let previewTimer: ReturnType<typeof setTimeout> | undefined;
watch([fields, captureId], () => {
clearTimeout(previewTimer);
if (captureId.value === null || !fields.value.length) {
preview.value = null;
return;
}
const id = captureId.value;
previewTimer = setTimeout(async () => {
const result = await api.mappingPreview<Preview>(id, fields.value).catch(() => null);
if (id === captureId.value) preview.value = result;
}, 250);
}, { deep: true, immediate: true });
const blockers = computed(() => {
if (!sourcePath.value) return ["pick a source"];
if (source.value === NEW_SOURCE) return ["create the source first"];
if (!capture.value) return [`no event from ${sourcePath.value} yet to preview against`];
if (payload.value === null) return ["the picked event's body is not JSON"];
return problems(inputs.value, rows.value, preview.value);
});
function resolved(name: string): { value?: string; failure?: string } {
const failure = preview.value?.failures?.find((f) => f.field_name === name);
if (failure) return { failure: failure.reason };
const values = preview.value?.values ?? {};
return name in values ? { value: shortValue(values[name]) } : {};
}
function when(at?: string): string {
return at ? new Date(at).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" }) : "";
}
// A mapping another binding also reads is left as it is: the edit gets its own.
function sharedMapping(id?: string): boolean {
return bindings.value.some((b) => b.mapping_id === id && b.id !== props.binding?.id);
}
// An edit keeps its mapping's event type; a capture that arrived unidentified
// becomes the example of a new one.
async function eventTypeFor(c: Capture): Promise<string> {
const kept = mappings.value.find((m) => String(m.id) === props.binding?.mapping_id)?.event_type_id;
if (kept) return kept;
if (c.event_type) return c.event_type;
const created = await api.eventTypeCreate<EventType>({
source: sourcePath.value,
name: `${sourcePath.value} event`,
example: { headers: captureHeaders(c), body: c.body ?? "" },
});
return created.id;
}
async function createSource(): Promise<void> {
if (!sourcePath.value || creatingSource.value) return;
creatingSource.value = true;
error.value = "";
try {
const created = await api.sourceCreate<Source>(sourcePath.value);
revealed.value = created;
sources.value.push(created.path);
source.value = created.path;
newSource.value = "";
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
} finally {
creatingSource.value = false;
}
}
async function save(): Promise<void> {
if (blockers.value.length || !capture.value) return;
saving.value = true;
error.value = "";
try {
const mappingBody = {
name: `${workflow.value} ← ${sourcePath.value}`,
event_type_id: await eventTypeFor(capture.value),
fields: fields.value,
};
const existing = props.binding?.mapping_id;
const mapping = existing && !sharedMapping(existing)
? await api.mappingUpdate<Mapping>(existing, mappingBody)
: await api.mappingCreate<Mapping>(mappingBody);
const body = {
name: props.binding?.name || `${sourcePath.value} → ${workflow.value}`,
matcher: { source: sourcePath.value },
mapping_id: String(mapping.id),
filter: props.binding?.filter ?? "",
workflow: workflow.value,
repo_param: repository.value && repositoryPath.value.trim() ? REPOSITORY_FIELD : "",
owner: props.binding?.owner ?? "",
repo: props.binding?.repo ?? "",
inputs: bindingInputs(inputs.value, rows.value),
};
if (props.binding) await api.bindingUpdate(props.binding.id, body);
else await api.bindingCreate(body);
emit("saved");
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
} finally {
saving.value = false;
}
}
// transition runs one lifecycle command and shows the status it leads to.
async function transition(command: (id: string) => Promise<unknown>, next: string): Promise<void> {
if (!props.binding) return;
error.value = "";
try {
await command(props.binding.id);
status.value = next;
emit("saved");
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
}
}
async function removeBinding(): Promise<void> {
if (!props.binding) return;
saving.value = true;
error.value = "";
try {
await api.bindingDelete(props.binding.id);
emit("saved");
} catch (cause) {
error.value = cause instanceof Error ? cause.message : String(cause);
} finally {
saving.value = false;
}
}
const approve = () => transition(api.bindingApprove, "armed");
const pause = () => transition(api.bindingPause, "paused");
const resume = () => transition(api.bindingResume, "pending_approval");
</script>
<template>
<div class="flex h-full flex-col">
<AlertDialog v-model:open="confirmRemove">
<AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Remove event binding?</AlertDialogTitle><AlertDialogDescription>This event will stop starting this workflow. The event source and mapping are kept.</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction @click="removeBinding">Remove binding</AlertDialogAction></AlertDialogFooter></AlertDialogContent>
</AlertDialog>
<header class="flex items-center gap-2 border-b border-border px-4 py-3">
<Button type="button" variant="ghost" size="icon-sm" aria-label="Back to settings" @click="emit('back')"><ArrowLeft /></Button>
<div class="min-w-0 flex-1 truncate text-sm font-medium">{{ binding ? binding.name : "Bind an event" }}</div>
<Badge v-if="status" :variant="statusKind(status)">{{ statusLabel(status) }}</Badge>
</header>
<div v-if="loading" class="flex flex-1 items-center justify-center"><Spinner /></div>
<form v-else class="flex-1 space-y-5 overflow-y-auto px-4 py-4" @submit.prevent="save">
<section class="space-y-1.5">
<label for="bind-source" class="text-xs font-medium text-fg-muted">Source</label>
<OptionSelect id="bind-source" aria-label="Source" :model-value="source" :options="sourceOptions" class="w-full" :disabled="!!binding" @update:model-value="source = $event" />
<Input
v-if="source === NEW_SOURCE"
v-model="newSource"
aria-label="New source path"
placeholder="path, e.g. alertmanager"
class="h-8 w-full font-mono text-[13px]"
/>
<Button v-if="source === NEW_SOURCE" type="button" size="sm" :disabled="creatingSource || !sourcePath" @click="createSource"><Spinner v-if="creatingSource" />Create source</Button>
</section>
<SourceSecret v-if="revealed" :source="revealed" @dismiss="revealed = null" />
<section v-if="sourcePath" class="space-y-1.5">
<label for="bind-capture" class="text-xs font-medium text-fg-muted">Example event</label>
<Select v-if="sourceCaptures.length" :model-value="captureId ?? undefined" @update:model-value="captureId = String($event)">
<SelectTrigger id="bind-capture" size="sm" class="w-full" aria-label="Example event"><SelectValue placeholder="Pick an event" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="c in sourceCaptures" :key="c.id" :value="String(c.id)">#{{ c.id }} · {{ when(c.received_at) }}{{ c.event_type ? "" : " · unidentified" }}</SelectItem>
</SelectContent>
</Select>
<p v-else class="text-xs text-fg-subtle" :title="`Send an event to ${hookURL} and it appears here`">No events</p>
</section>
<section class="space-y-1.5">
<div class="text-xs font-medium text-fg-muted">Inputs</div>
<datalist id="bind-paths"><option v-for="path in paths" :key="path" :value="path" /></datalist>
<div class="divide-y divide-border rounded-md border border-border">
<div v-for="[name, spec] in inputs" :key="name" class="space-y-1 px-3 py-2">
<div class="flex items-center gap-1.5 text-xs">
<span class="font-mono">{{ name }}</span>
<span class="text-fg-subtle">{{ spec.type ?? "string" }}</span>
<span v-if="spec.required" class="text-danger" title="Required">*</span>
<Button
type="button"
variant="ghost"
size="icon-xs"
class="ml-auto"
:title="rows[name]!.from === 'path' ? 'Use a fixed value' : 'Read from the event'"
:aria-label="`${name}: ${rows[name]!.from === 'path' ? 'use a fixed value' : 'read from the event'}`"
@click="rows[name]!.from = rows[name]!.from === 'path' ? 'value' : 'path'"
>
<Type v-if="rows[name]!.from === 'path'" /><Braces v-else />
</Button>
</div>
<Input
v-if="rows[name]!.from === 'path'"
v-model="rows[name]!.path"
list="bind-paths"
:aria-label="`${name} payload path`"
placeholder="payload path"
class="h-8 w-full font-mono text-xs"
/>
<Input
v-else
v-model="rows[name]!.value"
:aria-label="`${name} fixed value`"
placeholder="fixed value"
class="h-8 w-full font-mono text-xs"
/>
<p v-if="rows[name]!.from === 'path' && resolved(name).failure" class="text-xs text-danger">{{ resolved(name).failure }}</p>
<p v-else-if="rows[name]!.from === 'path' && resolved(name).value !== undefined" class="truncate font-mono text-xs text-success" :title="resolved(name).value">{{ resolved(name).value }}</p>
</div>
<div v-if="repository" class="space-y-1 px-3 py-2">
<div class="text-xs" title="Optional: owner/name of a configured repository; blank uses the configured one">Repository</div>
<Input
v-model="repositoryPath"
list="bind-paths"
aria-label="Repository payload path"
placeholder="payload path"
class="h-8 w-full font-mono text-xs"
/>
<p v-if="resolved(REPOSITORY_FIELD).failure" class="text-xs text-danger">{{ resolved(REPOSITORY_FIELD).failure }}</p>
<p v-else-if="resolved(REPOSITORY_FIELD).value !== undefined" class="truncate font-mono text-xs text-success">{{ resolved(REPOSITORY_FIELD).value }}</p>
</div>
<p v-if="!inputs.length && !repository" class="px-3 py-2 text-xs text-fg-subtle">No inputs.</p>
</div>
</section>
<div class="space-y-2">
<p v-if="error" role="alert" class="text-xs text-danger">{{ error }}</p>
<p v-else-if="blockers.length" class="text-xs text-fg-subtle">Cannot save: {{ blockers[0] }}</p>
<div class="flex flex-wrap gap-2">
<Button type="submit" size="sm" :disabled="saving || !!blockers.length"><Spinner v-if="saving" />Save binding</Button>
<Button v-if="binding && status === 'pending_approval'" type="button" size="sm" variant="outline" @click="approve">Approve</Button>
<Button v-if="binding && status === 'armed'" type="button" size="sm" variant="outline" @click="pause">Pause</Button>
<Button v-if="binding && status === 'paused'" type="button" size="sm" variant="outline" @click="resume">Resume</Button>
<Button v-if="binding" type="button" size="sm" variant="destructive" :disabled="saving" @click="confirmRemove=true">Remove binding</Button>
</div>
</div>
</form>
</div>
</template>