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
14 changed files with 279 additions and 134 deletions
|
|
@ -103,6 +103,12 @@ problem to opt out of correctly, not something the next adopter
|
|||
discovers by shipping a bug.
|
||||
<!-- vale write-good.Passive = YES -->
|
||||
|
||||
A read that runs once per set of inputs, and again after a change the page
|
||||
made, uses `useResource` (next to `usePolled` in `src/ui/polled/`). 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. A
|
||||
component doesn't hand-roll that effect with its own `cancelled` flag.
|
||||
|
||||
## Errors
|
||||
|
||||
**`ApiErrorPanel` + the RFC 9457 `ProblemDetails` shape it renders is
|
||||
|
|
|
|||
|
|
@ -12,10 +12,12 @@
|
|||
//
|
||||
// Its state belongs to one agent: callers key it by agent name, so switching
|
||||
// agents remounts it instead of showing the previous agent's caps.
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { useState } from "preact/hooks";
|
||||
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { Badge } from "@hive/shared/badge.js";
|
||||
import { fetchJson } from "../../ui/polled/usePolled.js";
|
||||
import { useResource } from "../../ui/polled/useResource.js";
|
||||
import { ActionRow } from "../../ui/action-row/ActionRow.js";
|
||||
import { Button } from "../../ui/button/Button.js";
|
||||
import { FormStack } from "../../ui/form-stack/FormStack.js";
|
||||
|
|
@ -93,31 +95,17 @@ export function LimitsFields({
|
|||
}
|
||||
|
||||
export function AgentLimits({ agent }: { agent: string }) {
|
||||
const [caps, setCaps] = useState<Caps | null>(null);
|
||||
const [error, setError] = useState<ProblemDetails | null>(null);
|
||||
// Bumped after a save or a clear, so the caps are fetched again.
|
||||
const [reload, setReload] = useState(0);
|
||||
const [editing, setEditing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const r = await fetch(limitsUrl(agent));
|
||||
if (!r.ok) {
|
||||
if (!cancelled) setError(await readApiError(r));
|
||||
return;
|
||||
}
|
||||
const body = (await r.json()) as Caps;
|
||||
if (cancelled) return;
|
||||
setCaps(body);
|
||||
setError(null);
|
||||
})().catch((e: unknown) => {
|
||||
if (!cancelled) setError({ detail: String(e) });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [agent, reload]);
|
||||
// Read again after a save or a clear.
|
||||
const {
|
||||
data: caps,
|
||||
error,
|
||||
reload,
|
||||
} = useResource(
|
||||
(signal) => fetchJson<Caps>(limitsUrl(agent), signal),
|
||||
[agent],
|
||||
);
|
||||
|
||||
// Shown as text, not a hover title. Caps already loaded stay under a
|
||||
// failed refetch, so a save that worked is not hidden by a read that did not.
|
||||
|
|
@ -127,7 +115,7 @@ export function AgentLimits({ agent }: { agent: string }) {
|
|||
context="reading the resource caps failed"
|
||||
problem={error}
|
||||
/>
|
||||
<Button onClick={() => setReload((n) => n + 1)}>retry</Button>
|
||||
<Button onClick={() => reload()}>retry</Button>
|
||||
</>
|
||||
) : null;
|
||||
if (caps === null) {
|
||||
|
|
@ -168,7 +156,7 @@ export function AgentLimits({ agent }: { agent: string }) {
|
|||
onClose={() => setEditing(false)}
|
||||
onSaved={() => {
|
||||
setEditing(false);
|
||||
setReload((n) => n + 1);
|
||||
reload();
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@ import { useEffect, useState } from "preact/hooks";
|
|||
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { Badge } from "@hive/shared/badge.js";
|
||||
import { fetchJson } from "../../ui/polled/usePolled.js";
|
||||
import { useResource } from "../../ui/polled/useResource.js";
|
||||
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
|
||||
import { Button } from "../../ui/button/Button.js";
|
||||
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
|
||||
|
|
@ -157,31 +159,13 @@ export function AgentPermissions({
|
|||
g: GrantState;
|
||||
}) {
|
||||
const { grant, busy, saveError, loading, send } = g;
|
||||
const [catalogue, setCatalogue] = useState<Catalogue | null>(null);
|
||||
const [catalogueError, setCatalogueError] = useState<ProblemDetails | null>(
|
||||
null,
|
||||
const { data: catalogue, error: catalogueError } = useResource(
|
||||
(signal) => fetchJson<Catalogue>("/api/permissions", signal),
|
||||
[],
|
||||
);
|
||||
// The boxes as ticked while a change is being saved; null shows the stored grant.
|
||||
const [selected, setSelected] = useState<string[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const r = await fetch("/api/permissions");
|
||||
if (!r.ok) {
|
||||
if (!cancelled) setCatalogueError(await readApiError(r));
|
||||
return;
|
||||
}
|
||||
const data = (await r.json()) as Catalogue;
|
||||
if (!cancelled) setCatalogue(data);
|
||||
})().catch((e: unknown) => {
|
||||
if (!cancelled) setCatalogueError({ detail: String(e) });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (grant === null) return loading;
|
||||
|
||||
const stored = grant.permissions;
|
||||
|
|
|
|||
|
|
@ -10,10 +10,11 @@
|
|||
// built in `ssh.ts`, prefilled with the key and this agent's name.
|
||||
//
|
||||
// Its state belongs to one agent: callers key it by agent name.
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { useState } from "preact/hooks";
|
||||
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { Badge } from "@hive/shared/badge.js";
|
||||
import { fetchJson } from "../../ui/polled/usePolled.js";
|
||||
import { useResource } from "../../ui/polled/useResource.js";
|
||||
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
|
||||
import { Button } from "../../ui/button/Button.js";
|
||||
import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js";
|
||||
|
|
@ -35,26 +36,12 @@ export function AgentSsh({ agent, g }: { agent: string; g: GrantState }) {
|
|||
const [form, setForm] = useState<TargetForm>("nixos");
|
||||
const [copied, setCopied] = useState(false);
|
||||
// The CA key, or why there is none: a store without a CA yet answers 404.
|
||||
const [ca, setCa] = useState<string | null>(null);
|
||||
const [caError, setCaError] = useState<ProblemDetails | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const r = await fetch("/api/ssh/ca");
|
||||
if (!r.ok) {
|
||||
if (!cancelled) setCaError(await readApiError(r));
|
||||
return;
|
||||
}
|
||||
const body = (await r.json()) as { public_key: string };
|
||||
if (!cancelled) setCa(body.public_key);
|
||||
})().catch((e: unknown) => {
|
||||
if (!cancelled) setCaError({ detail: String(e) });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
const { data: caKey, error: caError } = useResource(
|
||||
(signal) => fetchJson<{ public_key: string }>("/api/ssh/ca", signal),
|
||||
[],
|
||||
);
|
||||
const ca = caKey?.public_key ?? null;
|
||||
|
||||
if (grant === null) return loading;
|
||||
|
||||
|
|
|
|||
|
|
@ -9,13 +9,15 @@
|
|||
//
|
||||
// Its state belongs to one agent: callers key it by hive and agent, so
|
||||
// switching agents remounts it instead of showing the previous agent's rows.
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { useState } from "preact/hooks";
|
||||
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { Badge } from "@hive/shared/badge.js";
|
||||
import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js";
|
||||
import { ConfirmDialog } from "../../ui/confirm-dialog/ConfirmDialog.js";
|
||||
import { Hint } from "../../ui/hint/Hint.js";
|
||||
import { fetchJson } from "../../ui/polled/usePolled.js";
|
||||
import { useResource } from "../../ui/polled/useResource.js";
|
||||
import { accountKindLabel } from "./account-kind.js";
|
||||
import { deleteUrl, listUrl } from "./account-api.js";
|
||||
import "./LinkedAccounts.css";
|
||||
|
|
@ -39,10 +41,6 @@ export function LinkedAccounts({
|
|||
agent: string;
|
||||
version: number;
|
||||
}) {
|
||||
const [accounts, setAccounts] = useState<LinkedAccount[] | null>(null);
|
||||
const [error, setError] = useState<ProblemDetails | null>(null);
|
||||
// Bumped after a delete, so the list is fetched again.
|
||||
const [reload, setReload] = useState(0);
|
||||
// The row whose delete confirmation is open; null means closed.
|
||||
const [deleteTarget, setDeleteTarget] = useState<LinkedAccount | null>(null);
|
||||
// Matrix only: log the token out at its homeserver before deleting.
|
||||
|
|
@ -50,25 +48,14 @@ export function LinkedAccounts({
|
|||
const [deleting, setDeleting] = useState(false);
|
||||
const [deleteError, setDeleteError] = useState<ProblemDetails | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const r = await fetch(listUrl(hive, agent));
|
||||
if (!r.ok) {
|
||||
if (!cancelled) setError(await readApiError(r));
|
||||
return;
|
||||
}
|
||||
const data = (await r.json()) as LinkedAccount[];
|
||||
if (cancelled) return;
|
||||
setAccounts(data);
|
||||
setError(null);
|
||||
})().catch((e: unknown) => {
|
||||
if (!cancelled) setError({ detail: String(e) });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [hive, agent, version, reload]);
|
||||
const {
|
||||
data: accounts,
|
||||
error,
|
||||
reload,
|
||||
} = useResource(
|
||||
(signal) => fetchJson<LinkedAccount[]>(listUrl(hive, agent), signal),
|
||||
[hive, agent, version],
|
||||
);
|
||||
|
||||
function openDelete(a: LinkedAccount) {
|
||||
setDeleteTarget(a);
|
||||
|
|
@ -92,7 +79,7 @@ export function LinkedAccounts({
|
|||
return;
|
||||
}
|
||||
setDeleteTarget(null);
|
||||
setReload((n) => n + 1);
|
||||
reload();
|
||||
} catch (e: unknown) {
|
||||
setDeleteError({ detail: String(e) });
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -106,3 +106,14 @@ export function behindNote(behind: string[]): string | null {
|
|||
? `${names} has not applied this list yet, so its proxy may still let these names through.`
|
||||
: `${names} have not applied this list yet, so their proxies may still let these names through.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The error the list shows: a failed removal first, since it is the newer
|
||||
* answer to what the operator just did; otherwise a failed read.
|
||||
*/
|
||||
export function shownError<P>(
|
||||
removeError: P | null,
|
||||
readError: P | null,
|
||||
): P | null {
|
||||
return removeError ?? readError;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,11 +7,14 @@
|
|||
// entry, each answering the whole list. `refetch` reads the list again, for a
|
||||
// caller that added an entry through its own form. The deny list also reports
|
||||
// `behind`, the hives that have not taken its current revision yet.
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { useState } from "preact/hooks";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { fetchJson } from "../../ui/polled/usePolled.js";
|
||||
import { useResource } from "../../ui/polled/useResource.js";
|
||||
import {
|
||||
ALLOWED_DOMAINS_URL,
|
||||
DENIED_DOMAINS_URL,
|
||||
shownError,
|
||||
type AllowedDomain,
|
||||
} from "./allowed-domains.js";
|
||||
|
||||
|
|
@ -21,33 +24,15 @@ interface Listing {
|
|||
}
|
||||
|
||||
function useDomainList(url: string) {
|
||||
const [entries, setEntries] = useState<AllowedDomain[] | null>(null);
|
||||
const [behind, setBehind] = useState<string[]>([]);
|
||||
const [error, setError] = useState<ProblemDetails | null>(null);
|
||||
// Bumped after an add or a removal, so the list is fetched again.
|
||||
const [reload, setReload] = useState(0);
|
||||
// The error of a removal; a read that fails shows its own.
|
||||
const [removeError, setRemoveError] = useState<ProblemDetails | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const r = await fetch(url);
|
||||
if (!r.ok) {
|
||||
if (!cancelled) setError(await readApiError(r));
|
||||
return;
|
||||
}
|
||||
const body = (await r.json()) as Listing;
|
||||
if (cancelled) return;
|
||||
setEntries(body.entries);
|
||||
setBehind(body.behind ?? []);
|
||||
setError(null);
|
||||
})().catch((e: unknown) => {
|
||||
if (!cancelled) setError({ detail: String(e) });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [url, reload]);
|
||||
const {
|
||||
data,
|
||||
error: readError,
|
||||
reload,
|
||||
} = useResource((signal) => fetchJson<Listing>(url, signal), [url]);
|
||||
|
||||
async function remove(entry: AllowedDomain) {
|
||||
if (busy) return;
|
||||
|
|
@ -59,24 +44,28 @@ function useDomainList(url: string) {
|
|||
body: JSON.stringify(entry),
|
||||
});
|
||||
if (!r.ok) {
|
||||
setError(await readApiError(r));
|
||||
setRemoveError(await readApiError(r));
|
||||
return;
|
||||
}
|
||||
setReload((n) => n + 1);
|
||||
setRemoveError(null);
|
||||
reload();
|
||||
} catch (e: unknown) {
|
||||
setError({ detail: String(e) });
|
||||
setRemoveError({ detail: String(e) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
entries,
|
||||
behind,
|
||||
error,
|
||||
entries: data?.entries ?? null,
|
||||
behind: data?.behind ?? [],
|
||||
error: shownError(removeError, readError),
|
||||
busy,
|
||||
remove,
|
||||
refetch: () => setReload((n) => n + 1),
|
||||
refetch: () => {
|
||||
setRemoveError(null);
|
||||
reload();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ import {
|
|||
import { ExternalLink } from "../ui/external-link/ExternalLink.js";
|
||||
import { FieldGrid, FieldGridFull } from "../ui/field-grid/FieldGrid.js";
|
||||
import { FormStack } from "../ui/form-stack/FormStack.js";
|
||||
import { Hint, type HintTone } from "../ui/hint/Hint.js";
|
||||
import { Hint } from "../ui/hint/Hint.js";
|
||||
import { FormResult } from "../ui/submit/FormResult.js";
|
||||
import type { SubmitState } from "../ui/submit/submit.js";
|
||||
import { Preformatted } from "../ui/preformatted/Preformatted.js";
|
||||
|
|
@ -55,10 +55,10 @@ import { Popover } from "../ui/popover/Popover.js";
|
|||
import { Badge, type BadgeTone } from "@hive/shared/badge.js";
|
||||
import { GearIcon } from "@hive/shared/icons.js";
|
||||
import { Dropdown, type DropdownOption } from "@hive/shared/dropdown.js";
|
||||
import { TONES } from "@hive/shared/tone.js";
|
||||
import { TONES, type Tone } from "@hive/shared/tone.js";
|
||||
import "./ComponentsPage.css";
|
||||
|
||||
const HINT_TONES: HintTone[] = [...TONES];
|
||||
const HINT_TONES: Tone[] = [...TONES];
|
||||
|
||||
const SUBMIT_SAMPLES: [string, SubmitState][] = [
|
||||
["done", { status: "done", value: undefined }],
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ import {
|
|||
behindNote,
|
||||
entriesFor,
|
||||
entryBody,
|
||||
shownError,
|
||||
} from "../src/agent/detail/allowed-domains.ts";
|
||||
|
||||
const all = [
|
||||
|
|
@ -114,3 +115,10 @@ test("the deny list names the hives that have not applied it, and says nothing w
|
|||
/^pr1ma, mu3de have not applied this list yet/,
|
||||
);
|
||||
});
|
||||
|
||||
test("a failed removal shows before a failed read, and a read shows alone", () => {
|
||||
assert.equal(shownError("remove", "read"), "remove");
|
||||
assert.equal(shownError(null, "read"), "read");
|
||||
assert.equal(shownError("remove", null), "remove");
|
||||
assert.equal(shownError(null, null), null);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
// imported as it is.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createPoller } from "../src/ui/polled/poller.ts";
|
||||
import { createPoller, createResource } from "../src/ui/polled/poller.ts";
|
||||
|
||||
// A fetch whose answers the test settles by hand, in any order.
|
||||
function manualFetch() {
|
||||
|
|
@ -114,3 +114,91 @@ test("onBusy follows a request in flight, however it ends", async () => {
|
|||
poller.stop();
|
||||
assert.equal(busy.length, 6);
|
||||
});
|
||||
|
||||
// The state behind `useResource`.
|
||||
function resourceRun() {
|
||||
const m = manualFetch();
|
||||
const states = [];
|
||||
const resource = createResource({
|
||||
fetch: m.fetch,
|
||||
problemOf: (e) => `problem: ${e}`,
|
||||
onState: (s) => states.push(s),
|
||||
});
|
||||
return { m, states, resource };
|
||||
}
|
||||
|
||||
test("a resource starts loading with nothing, and a good answer fills it", async () => {
|
||||
const { m, resource } = resourceRun();
|
||||
assert.deepEqual(resource.state(), {
|
||||
data: null,
|
||||
error: null,
|
||||
loading: true,
|
||||
});
|
||||
resource.load();
|
||||
m.calls[0].resolve("one");
|
||||
await flush();
|
||||
assert.deepEqual(resource.state(), {
|
||||
data: "one",
|
||||
error: null,
|
||||
loading: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("a failed read keeps the last good data and the next good answer clears the error", async () => {
|
||||
const { m, resource } = resourceRun();
|
||||
resource.load();
|
||||
m.calls[0].resolve("one");
|
||||
await flush();
|
||||
resource.load();
|
||||
m.calls[1].reject("boom");
|
||||
await flush();
|
||||
assert.deepEqual(resource.state(), {
|
||||
data: "one",
|
||||
error: "problem: boom",
|
||||
loading: false,
|
||||
});
|
||||
resource.load();
|
||||
m.calls[2].resolve("two");
|
||||
await flush();
|
||||
assert.deepEqual(resource.state(), {
|
||||
data: "two",
|
||||
error: null,
|
||||
loading: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("a read for old inputs never lands once the inputs changed", async () => {
|
||||
const { m, resource } = resourceRun();
|
||||
resource.load();
|
||||
resource.load();
|
||||
assert.equal(m.calls[0].signal.aborted, true);
|
||||
m.calls[0].resolve("stale");
|
||||
m.calls[1].resolve("fresh");
|
||||
await flush();
|
||||
assert.equal(resource.state().data, "fresh");
|
||||
});
|
||||
|
||||
test("stop drops the request in flight, so an unmounted page hears nothing", async () => {
|
||||
const { m, states, resource } = resourceRun();
|
||||
resource.load();
|
||||
const before = states.length;
|
||||
resource.stop();
|
||||
m.calls[0].resolve("late");
|
||||
await flush();
|
||||
assert.equal(m.calls[0].signal.aborted, true);
|
||||
assert.equal(resource.state().data, null);
|
||||
assert.equal(
|
||||
states.slice(before).some((s) => s.data !== null),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("setData patches what is shown without a request", async () => {
|
||||
const { m, resource } = resourceRun();
|
||||
resource.load();
|
||||
m.calls[0].resolve([1]);
|
||||
await flush();
|
||||
resource.setData((prev) => [...(prev ?? []), 2]);
|
||||
assert.deepEqual(resource.state().data, [1, 2]);
|
||||
assert.equal(m.calls.length, 1);
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue