feat: hive card with SVG, outline, edit sheets and catalog settings (Beute L2)
- lib/hive: frontend port of the hive domain (ops, validator, facts, layout, follow-ups, describe texts, reason texts) running the backend fixtures, API client - hive card on the colony page (same height as Stammdaten): SVG view, accessible outline tree, frame/part sheets with optimistic save, conflict sheet, history with past states, init from template or another colony, inspection draft mode - follow-up toasts prefilling feeding and treatment forms (treatment end only with an open treatment) - settings page "Beutensysteme" (hive-systems:manage) - NumberStepper decimal steps, reactive motion level hook, holo tokens - spec: owner design decision 2026-10-16 (glass hologram, focus mode) The SVG view is the fallback; the 3D scene follows in L3. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
0091b3d28b
commit
c608f5d405
87 files changed
+9493
-43
No files matched your search
@@ -0,0 +1,200 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { berlinCalendarDay } from "@/lib/dates";
|
||||
import { ApiError } from "@/lib/auth/api-client";
|
||||
import { hiveConflictOf, hiveKeys, postHiveChange } from "@/lib/hive/api";
|
||||
import { deriveHiveFacts } from "@/lib/hive/facts";
|
||||
import { applyHiveOps } from "@/lib/hive/ops";
|
||||
import { fetchColonyTreatments } from "@/lib/treatments/api";
|
||||
import { newIdempotencyKey } from "@/lib/offline/idempotency";
|
||||
import type {
|
||||
ClientHiveChangeSource,
|
||||
HiveApplyResult,
|
||||
HiveCatalog,
|
||||
HiveOp,
|
||||
HiveSetupView,
|
||||
HiveState,
|
||||
} from "@/lib/hive/types";
|
||||
import { showHiveFollowUps } from "./follow-up-toast";
|
||||
|
||||
/** The server refused the ops against its newer state (409 HIVE_CONFLICT). */
|
||||
export interface HiveConflict {
|
||||
/** The state the server holds now. */
|
||||
current: { version: number; state: HiveState };
|
||||
/** The user's own ops. */
|
||||
ops: HiveOp[];
|
||||
/** The ops re-applied to `current.state`; a failure carries op index and reason. */
|
||||
preview: HiveApplyResult;
|
||||
}
|
||||
|
||||
export interface HiveMutation {
|
||||
submit(ops: HiveOp[], source: ClientHiveChangeSource, occurredOn?: string): Promise<HiveSetupView>;
|
||||
conflict: HiveConflict | null;
|
||||
/** "retry" sends the ops again against the current state (new key); "discard" drops them. */
|
||||
resolveConflict(action: "retry" | "discard"): Promise<void>;
|
||||
isPending: boolean;
|
||||
}
|
||||
|
||||
interface Attempt {
|
||||
ops: HiveOp[];
|
||||
source: ClientHiveChangeSource;
|
||||
occurredOn: string;
|
||||
}
|
||||
|
||||
/** Thrown for a submit while another one of this hook is still running. */
|
||||
export const HIVE_BUSY_MESSAGE = "HIVE_BUSY";
|
||||
|
||||
/** Same ops, source and day: a manual re-press after a network error. */
|
||||
function signatureOf(attempt: Attempt): string {
|
||||
return JSON.stringify([attempt.source, attempt.occurredOn, attempt.ops]);
|
||||
}
|
||||
|
||||
/** No verdict from the server (network, timeout, 5xx): the change may or may not be saved. */
|
||||
function isAmbiguousFailure(error: unknown): boolean {
|
||||
return !(error instanceof ApiError) || error.status >= 500;
|
||||
}
|
||||
|
||||
function withState(view: HiveSetupView, state: HiveState, version: number, catalog: HiveCatalog): HiveSetupView {
|
||||
return { ...view, version, state, facts: deriveHiveFacts(state, catalog) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts a change of the colony's hive. The cache shows the result at once
|
||||
* (optimistic); a failure refetches it. One submit at a time. An attempt keeps
|
||||
* its idempotency key across manual re-presses after a network error or 5xx;
|
||||
* a retry after a conflict gets a fresh one. Follow-up toasts are suggestions only.
|
||||
*/
|
||||
export function useHiveMutation(colonyId: string, catalog: HiveCatalog): HiveMutation {
|
||||
const queryClient = useQueryClient();
|
||||
const router = useRouter();
|
||||
const [conflict, setConflict] = useState<HiveConflict | null>(null);
|
||||
const [pendingCount, setPendingCount] = useState(0);
|
||||
const lastAttempt = useRef<Attempt | null>(null);
|
||||
const inFlight = useRef(false);
|
||||
// Key of an attempt that failed without a verdict (network, 5xx): a re-press reuses it.
|
||||
const failedKey = useRef<{ signature: string; key: string } | null>(null);
|
||||
const queryKey = hiveKeys.detail(colonyId);
|
||||
|
||||
const hasOpenTreatment = useCallback(async (): Promise<boolean> => {
|
||||
try {
|
||||
const treatments = await queryClient.fetchQuery({
|
||||
queryKey: ["colonies", colonyId, "treatments"],
|
||||
queryFn: () => fetchColonyTreatments(colonyId),
|
||||
});
|
||||
return treatments.some((treatment) => treatment.endDate == null);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, [colonyId, queryClient]);
|
||||
|
||||
const suggestFollowUps = useCallback(
|
||||
async (attempt: Attempt, before: HiveState, after: HiveState): Promise<void> => {
|
||||
const { ops, occurredOn } = attempt;
|
||||
const open = ops.some((op) => op.op === "removePart") ? await hasOpenTreatment() : false;
|
||||
showHiveFollowUps(ops, before, after, catalog, {
|
||||
colonyId,
|
||||
occurredOn,
|
||||
navigate: (href) => router.push(href),
|
||||
hasOpenTreatment: open,
|
||||
});
|
||||
},
|
||||
[catalog, colonyId, hasOpenTreatment, router],
|
||||
);
|
||||
|
||||
const run = useCallback(
|
||||
async (attempt: Attempt): Promise<HiveSetupView> => {
|
||||
if (inFlight.current) throw new Error(HIVE_BUSY_MESSAGE);
|
||||
inFlight.current = true;
|
||||
const { ops, source, occurredOn } = attempt;
|
||||
const signature = signatureOf(attempt);
|
||||
const key =
|
||||
failedKey.current?.signature === signature ? failedKey.current.key : newIdempotencyKey();
|
||||
setPendingCount((count) => count + 1);
|
||||
try {
|
||||
// A running refetch must not overwrite the optimistic state.
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
const previous = queryClient.getQueryData<HiveSetupView>(queryKey);
|
||||
if (previous) {
|
||||
const applied = applyHiveOps(previous.state, ops, catalog);
|
||||
if (applied.ok) {
|
||||
queryClient.setQueryData(queryKey, withState(previous, applied.state, previous.version, catalog));
|
||||
}
|
||||
}
|
||||
let optimistic: HiveSetupView | undefined;
|
||||
if (previous) optimistic = queryClient.getQueryData<HiveSetupView>(queryKey);
|
||||
try {
|
||||
const view = await postHiveChange(colonyId, { occurredOn, source, ops }, key);
|
||||
queryClient.setQueryData(queryKey, view);
|
||||
setConflict(null);
|
||||
lastAttempt.current = null;
|
||||
failedKey.current = null;
|
||||
void queryClient.invalidateQueries({ queryKey: hiveKeys.history(colonyId) });
|
||||
if (previous) {
|
||||
// Follow-ups are best effort: a failing suggestion must not fail the saved change.
|
||||
suggestFollowUps(attempt, previous.state, view.state).catch(() => {});
|
||||
}
|
||||
return view;
|
||||
} catch (error) {
|
||||
const body = hiveConflictOf(error);
|
||||
if (body) {
|
||||
failedKey.current = null;
|
||||
lastAttempt.current = attempt;
|
||||
if (previous) {
|
||||
queryClient.setQueryData(
|
||||
queryKey,
|
||||
withState(previous, body.current.state, body.current.version, catalog),
|
||||
);
|
||||
}
|
||||
setConflict({
|
||||
current: body.current,
|
||||
ops,
|
||||
preview: applyHiveOps(body.current.state, ops, catalog),
|
||||
});
|
||||
} else {
|
||||
failedKey.current = isAmbiguousFailure(error) ? { signature, key } : null;
|
||||
// Restore only if nobody changed the cache since our optimistic write; then refetch.
|
||||
if (previous && optimistic && queryClient.getQueryData(queryKey) === optimistic) {
|
||||
queryClient.setQueryData(queryKey, previous);
|
||||
}
|
||||
void queryClient.invalidateQueries({ queryKey });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setPendingCount((count) => count - 1);
|
||||
}
|
||||
},
|
||||
[catalog, colonyId, queryClient, queryKey, suggestFollowUps],
|
||||
);
|
||||
|
||||
const submit = useCallback(
|
||||
(ops: HiveOp[], source: ClientHiveChangeSource, occurredOn?: string) =>
|
||||
run({ ops, source, occurredOn: occurredOn ?? berlinCalendarDay(new Date().toISOString()) }),
|
||||
[run],
|
||||
);
|
||||
|
||||
const resolveConflict = useCallback(
|
||||
async (action: "retry" | "discard"): Promise<void> => {
|
||||
const attempt = lastAttempt.current;
|
||||
if (action === "discard" || !attempt) {
|
||||
lastAttempt.current = null;
|
||||
setConflict(null);
|
||||
return;
|
||||
}
|
||||
if (conflict && !conflict.preview.ok) return;
|
||||
try {
|
||||
await run(attempt);
|
||||
} catch (error) {
|
||||
// A new conflict is already in `conflict`; anything else is for the caller.
|
||||
if (!hiveConflictOf(error)) throw error;
|
||||
}
|
||||
},
|
||||
[conflict, run],
|
||||
);
|
||||
|
||||
return { submit, conflict, resolveConflict, isPending: pendingCount > 0 };
|
||||
}
|
||||
Reference in new issue
Block a user