NGU-Web/src/lib/useResource.ts
Zaldimmar b816203c0c Accessibility: reading and color blind modes, audit fixes, calendar window
- Accessibility panel: the switch knob stays in its track; the panel
  follows its button in the Tab order and opens on its first switch.
- Reading mode is the page as plain text: one column, no colors,
  pictures, cards or motion; descriptions stay in place.
- Color blind mode (protanopia, deuteranopia, tritanopia, monochrome):
  palette swaps chosen by simulation, applied to code, data and CSS
  colors on public pages only. The newsletter uses the stored palette.
- Audit fixes: focus not hidden by the header, focus on page change
  and in-page jumps, focus return for the menu, day list and people
  details, labelled admin fields and dialogs, keyboard map tiles,
  scrollable tables, and more.
- Calendar asks /events for its six weeks only (?from=&to=); carousels
  take their 12 most recent past events (?past=12).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 14:33:09 -05:00

58 lines
2 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
useResource
The read hook every page uses:
const { data, error, loading } = useResource("/events");
Note the `ignore` flag rather than an AbortController: the
request is shared and cached, so canceling it would throw away
work another component may still want. We just stop writing
state after unmount.
A path asked for before starts from its last answer (api.ts,
peek) and isn't `loading` while it refreshes, so a page opened
again after the TTL doesn't flash its skeleton.
A null path asks for nothing (data stays undefined, not loading),
for a fetch that only some states need.
═══════════════════════════════════════════════════════════════ */
import { useEffect, useState } from "react";
import { get, peek } from "./api.ts";
export function useResource(path, { ttl }: { ttl?: number } = {}) {
const [state, setState] = useState<any>(() => {
const stale = path ? peek(path) : undefined;
return { data: stale, error: null, loading: Boolean(path) && stale === undefined };
});
useEffect(() => {
if (!path) {
setState({ data: undefined, error: null, loading: false });
return undefined;
}
let ignore = false;
const stale = peek(path);
setState((prev) =>
stale === undefined
? { ...prev, loading: true, error: null }
: { data: stale, error: null, loading: false },
);
get(path, { ttl })
.then((data) => {
if (!ignore) setState({ data, error: null, loading: false });
})
.catch((error) => {
if (!ignore) setState((prev) => ({ ...prev, error, loading: false }));
});
return () => {
ignore = true;
};
}, [path, ttl]);
return state;
}