swarm-ui: one hook for a read that runs once per set of inputs
Part of the unification order in the UI sweep issue (step d, first of three). Twenty files hand-rolled the same effect: a cancelled flag, a fetch, the problem body on a bad status, a catch that wraps the error. useResource does it once on top of the poller's request discipline: it aborts the request in flight when the inputs change or the page goes away, keeps the last good answer under a failed read and clears the error on the next good one. The agent details move to it (limits, linked accounts, ssh CA, permission catalogue, allowed and denied domains). Hint drops its HintTone alias for the shared Tone.
This commit is contained in:
parent
6f73bf0c55
commit
7f8d6abc58
4 changed files with 279 additions and 134 deletions
|
|
@ -11,8 +11,6 @@ import type { ComponentChildren } from "preact";
|
|||
import type { Tone } from "@hive/shared/tone.js";
|
||||
import "./Hint.css";
|
||||
|
||||
export type HintTone = Tone;
|
||||
|
||||
export function Hint({
|
||||
tone = "neutral",
|
||||
as: Tag = "p",
|
||||
|
|
@ -21,7 +19,7 @@ export function Hint({
|
|||
class: extraClass,
|
||||
children,
|
||||
}: {
|
||||
tone?: HintTone;
|
||||
tone?: Tone;
|
||||
as?: "p" | "span" | "div";
|
||||
role?: "status" | "alert";
|
||||
/** For a control's `aria-describedby`: the hint says why it is off. */
|
||||
|
|
|
|||
|
|
@ -59,3 +59,48 @@ export function createPoller<T>(opts: {
|
|||
stop,
|
||||
};
|
||||
}
|
||||
|
||||
// The state behind `useResource`: a read that runs once per set of inputs, on
|
||||
// top of the poller. `load` fetches (dropping a request in flight), `stop`
|
||||
// drops it; an answer from a dropped request never reaches the state. A failed
|
||||
// read keeps the last good `data` and sets `error`; the next good answer
|
||||
// clears `error`. `problemOf` turns what a fetch threw into the error shown.
|
||||
export interface ResourceState<T, P> {
|
||||
data: T | null;
|
||||
error: P | null;
|
||||
/** True from the start of a request until it ends. */
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export interface Resource<T, P> {
|
||||
state(): ResourceState<T, P>;
|
||||
load(): void;
|
||||
stop(): void;
|
||||
/** Patches `data` without a request. */
|
||||
setData(update: (prev: T | null) => T | null): void;
|
||||
}
|
||||
|
||||
export function createResource<T, P>(opts: {
|
||||
fetch: (signal: AbortSignal) => Promise<T>;
|
||||
problemOf: (error: unknown) => P;
|
||||
/** Called with the new state after every change. */
|
||||
onState: (state: ResourceState<T, P>) => void;
|
||||
}): Resource<T, P> {
|
||||
let state: ResourceState<T, P> = { data: null, error: null, loading: true };
|
||||
function set(next: Partial<ResourceState<T, P>>) {
|
||||
state = { ...state, ...next };
|
||||
opts.onState(state);
|
||||
}
|
||||
const poller = createPoller<T>({
|
||||
fetch: opts.fetch,
|
||||
onData: (data) => set({ data, error: null }),
|
||||
onError: (e) => set({ error: opts.problemOf(e) }),
|
||||
onBusy: (loading) => set({ loading }),
|
||||
});
|
||||
return {
|
||||
state: () => state,
|
||||
load: () => poller.refetch(),
|
||||
stop: () => poller.stop(),
|
||||
setData: (update) => set({ data: update(state.data) }),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ export async function fetchJson<T>(
|
|||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
function toProblem(e: unknown): ProblemDetails {
|
||||
export function toProblem(e: unknown): ProblemDetails {
|
||||
return e instanceof ProblemError ? e.problem : { detail: String(e) };
|
||||
}
|
||||
|
||||
|
|
|
|||
54
frontend/packages/swarm-ui/src/ui/polled/useResource.ts
Normal file
54
frontend/packages/swarm-ui/src/ui/polled/useResource.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// A read that runs once per set of inputs: `{ data, error, loading, reload,
|
||||
// setData }`. Where `usePolled` refetches on a timer, this fetches when `deps`
|
||||
// change, and again when `reload()` is called after a change the page made.
|
||||
// The rules live in `createResource` (`poller.ts`): a change of `deps` or an
|
||||
// unmount drops the request in flight, so a late answer never lands on the
|
||||
// wrong inputs or on a page that is gone.
|
||||
//
|
||||
// `data` is `null` until the first answer. A failed fetch sets `error` and
|
||||
// keeps the last good `data`, so a save that worked is not hidden by a read
|
||||
// that did not; the next good answer clears `error`. `fetcher` gets an
|
||||
// `AbortSignal`; `fetchJson` does a GET with one.
|
||||
import { useEffect, useRef, useState } from "preact/hooks";
|
||||
import type { ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { createResource, type Resource } from "./poller.js";
|
||||
import { toProblem } from "./usePolled.js";
|
||||
|
||||
export function useResource<T>(
|
||||
fetcher: (signal: AbortSignal) => Promise<T>,
|
||||
deps: readonly unknown[],
|
||||
): {
|
||||
data: T | null;
|
||||
error: ProblemDetails | null;
|
||||
/** True from the start of a request until it ends. */
|
||||
loading: boolean;
|
||||
reload: () => void;
|
||||
setData: (update: (prev: T | null) => T | null) => void;
|
||||
} {
|
||||
const [view, setView] = useState({
|
||||
data: null as T | null,
|
||||
error: null as ProblemDetails | null,
|
||||
loading: true,
|
||||
});
|
||||
const fetcherRef = useRef(fetcher);
|
||||
fetcherRef.current = fetcher;
|
||||
const resourceRef = useRef<Resource<T, ProblemDetails> | null>(null);
|
||||
if (resourceRef.current === null) {
|
||||
resourceRef.current = createResource<T, ProblemDetails>({
|
||||
fetch: (signal) => fetcherRef.current(signal),
|
||||
problemOf: toProblem,
|
||||
onState: setView,
|
||||
});
|
||||
}
|
||||
const resource = resourceRef.current;
|
||||
|
||||
// Fetch on the first render and whenever an input changes; drop the request
|
||||
// in flight on the way out.
|
||||
useEffect(() => {
|
||||
resource.load();
|
||||
return () => resource.stop();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [resource, ...deps]);
|
||||
|
||||
return { ...view, reload: () => resource.load(), setData: resource.setData };
|
||||
}
|
||||
Loading…
Reference in a new issue