@terpjs/react-core 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/theme.tsx CHANGED
@@ -85,6 +85,23 @@ export function ThemeProvider({ defaultTheme = "system", children }: ThemeProvid
85
85
  } else {
86
86
  root.setAttribute("data-theme", theme);
87
87
  }
88
+ // And the pre-paint bootstrap's bridge comes back here.
89
+ //
90
+ // A generated app serves `public/theme-bootstrap.js` blocking in the document head, so a
91
+ // stored choice reaches `<html>` before the first paint instead of arriving with this
92
+ // effect — the reason being that the body is empty until React commits, so the browser
93
+ // has already painted a light canvas by the time this runs. That script also declares
94
+ // `color-scheme` INLINE, because the token sheet is imported by the entry point and in a
95
+ // dev server therefore arrives with the bundle: without it the attribute is right and
96
+ // there is still no palette to paint from.
97
+ //
98
+ // Inline is exactly why it has to be given back. A style attribute outranks every rule
99
+ // in every layer, so the value the bootstrap wrote would go on governing the native
100
+ // chrome for the whole session: pick a light palette after loading on a dark one and the
101
+ // scrollbars, the caret and the select popup stay dark, against a page that is not.
102
+ // Removing it hands `color-scheme` back to the theme blocks in the token sheet, which is
103
+ // where it is declared per palette. A no-op on every load after the first.
104
+ root.style.removeProperty("color-scheme");
88
105
  }, [theme]);
89
106
 
90
107
  const setTheme = useCallback((next: Theme) => {
@@ -134,7 +134,7 @@ const UNREAD_TOKENS: Record<string, string[]> = {
134
134
  * prose scale.
135
135
  */
136
136
  const BARE_TYPE_LITERALS: Record<string, Record<string, number>> = {
137
- "line-height": { "0": 2, "1": 5, "1.2": 4, "1.25": 7, "1.3": 2, "1.4": 3, "1.5": 4 },
137
+ "line-height": { "0": 2, "1": 5, "1.2": 4, "1.25": 7, "1.3": 1, "1.4": 3, "1.5": 4 },
138
138
  // `inherit` is recorded rather than tokenised, and it is the one value here that is not
139
139
  // debt: the sort button in a table header must render the tracking its own `th` sets, and
140
140
  // naming a token would pin it to whatever that header uses TODAY. The UA stylesheet resets
@@ -17,6 +17,62 @@ describe("useResource", () => {
17
17
  expect(result.current.error).toBeNull();
18
18
  });
19
19
 
20
+ it("carries the total when the source hands over the page", async () => {
21
+ // The backend has always sent it -- the Page envelope is {items, total, skip, limit}.
22
+ // The documented recipe unwrapped .items and dropped the rest, so every "showing N of
23
+ // M" re-derived an answer the server had computed.
24
+ const { result } = renderHook(() =>
25
+ useResource<string, string>({ list: async () => ({ items: ["a", "b"], total: 57 }) }),
26
+ );
27
+
28
+ await waitFor(() => expect(result.current.loading).toBe(false));
29
+
30
+ expect(result.current.items).toEqual(["a", "b"]);
31
+ expect(result.current.total).toBe(57);
32
+ });
33
+
34
+ it("leaves the total unknown when the source hands over rows", async () => {
35
+ // Not zero. A source that returns an array has said nothing about how many rows there
36
+ // are, and a screen reading undefined as 0 announces an empty result set over a full
37
+ // page of them.
38
+ const { result } = renderHook(() =>
39
+ useResource<string, string>({ list: async () => ["a", "b"] }),
40
+ );
41
+
42
+ await waitFor(() => expect(result.current.loading).toBe(false));
43
+
44
+ expect(result.current.total).toBeUndefined();
45
+ });
46
+
47
+ it("leaves the total unknown when the page did not count", async () => {
48
+ // The cursor envelope computes the total only on include_total=true, so a page with no
49
+ // total is the ordinary case rather than a malformed one -- and it must not collapse
50
+ // into the same answer as a page of zero rows.
51
+ const { result } = renderHook(() =>
52
+ useResource<string, string>({ list: async () => ({ items: ["a"] }) }),
53
+ );
54
+
55
+ await waitFor(() => expect(result.current.loading).toBe(false));
56
+
57
+ expect(result.current.items).toEqual(["a"]);
58
+ expect(result.current.total).toBeUndefined();
59
+ });
60
+
61
+ it("updates the total on reload", async () => {
62
+ let total = 2;
63
+ const { result } = renderHook(() =>
64
+ useResource<string, string>({ list: async () => ({ items: ["a"], total }) }),
65
+ );
66
+ await waitFor(() => expect(result.current.total).toBe(2));
67
+
68
+ total = 9;
69
+ await act(async () => {
70
+ await result.current.reload();
71
+ });
72
+
73
+ expect(result.current.total).toBe(9);
74
+ });
75
+
20
76
  it("reloads when a declared dependency changes (in-place route-param navigation)", async () => {
21
77
  // A detail view keyed by a route param must refetch when the param changes
22
78
  // without a remount — otherwise the previous record's data lingers.
@@ -4,6 +4,21 @@ import { useCallback, useEffect, useRef, useState } from "react";
4
4
  export interface Resource<T, TCreate> {
5
5
  /** The loaded rows (empty until the first load resolves). */
6
6
  items: T[];
7
+ /**
8
+ * How many rows match the query in total, when the source said -- `undefined` when it
9
+ * did not, which is not the same as zero and must not be rendered as one.
10
+ *
11
+ * The backend has always sent it: the `Page` envelope is `{items, total, skip, limit}`.
12
+ * The documented recipe for `list` unwrapped `.items` and dropped the rest, so every
13
+ * "showing N of M" and every "at least N" warning was left to re-derive an answer the
14
+ * server had computed -- usually as `items.length >= limit`, which is a heuristic
15
+ * standing in for a number.
16
+ *
17
+ * Optional because the cursor envelope computes it only when the caller asks
18
+ * (`include_total=true`), so "unknown" is a real and common answer rather than a gap.
19
+ * A screen that cannot tell the difference should say "N shown", not "N of 0".
20
+ */
21
+ total?: number;
7
22
  /** True while the initial load or a reload is in flight. */
8
23
  loading: boolean;
9
24
  /** The last error message, or `null` when the most recent load succeeded. */
@@ -23,10 +38,34 @@ export interface Resource<T, TCreate> {
23
38
  mutate: (operation: () => Promise<void>) => Promise<void>;
24
39
  }
25
40
 
41
+ /**
42
+ * A server page as the backend's own envelope shapes it: rows plus how many there are.
43
+ *
44
+ * Deliberately structural rather than an import from the generated client — react-core
45
+ * has no contract dependency, and this has to describe an app's client as readily as the
46
+ * framework's own.
47
+ */
48
+ export interface ResourcePage<T> {
49
+ items: T[];
50
+ /** Absent when the server was not asked to count; never 0 standing in for unknown. */
51
+ total?: number;
52
+ }
53
+
26
54
  /** How a module fetches (and optionally creates) its rows — typically typed contract-client calls. */
27
55
  export interface ResourceSource<T, TCreate> {
28
- /** Fetch the current rows (e.g. `(await client.GET("/api/v1/notes/", {})).data?.items ?? []`). */
29
- list: () => Promise<T[]>;
56
+ /**
57
+ * Fetch the current rows -- either the rows alone, or the page the server sent.
58
+ *
59
+ * `(await client.GET("/api/v1/notes/", {})).data?.items ?? []` still works and still
60
+ * means what it did. Returning the page instead
61
+ * (`(await client.GET(...)).data ?? { items: [] }`) additionally carries `total`
62
+ * through to {@link Resource.total}, because the envelope already has it.
63
+ *
64
+ * A union rather than a second method: one call site, one decision, and every existing
65
+ * source keeps compiling. `Array.isArray` tells the two apart at runtime, which is
66
+ * exact -- a page is an object and rows are an array, with nothing in between.
67
+ */
68
+ list: () => Promise<T[] | ResourcePage<T>>;
30
69
  /** Optional create (e.g. a typed client POST); omit for a read-only resource. */
31
70
  create?: (input: TCreate) => Promise<void>;
32
71
  }
@@ -50,6 +89,7 @@ export function useResource<T, TCreate = void>(
50
89
  sourceRef.current = source;
51
90
 
52
91
  const [items, setItems] = useState<T[]>([]);
92
+ const [total, setTotal] = useState<number | undefined>(undefined);
53
93
  const [loading, setLoading] = useState(true);
54
94
  const [error, setError] = useState<string | null>(null);
55
95
  const [cause, setCause] = useState<unknown>(null);
@@ -64,7 +104,12 @@ export function useResource<T, TCreate = void>(
64
104
  setError(null);
65
105
  setCause(null);
66
106
  try {
67
- setItems(await sourceRef.current.list());
107
+ const answer = await sourceRef.current.list();
108
+ // Rows alone leave the total unknown rather than zero: a source that does not
109
+ // report one has said nothing about how many there are, and a screen that reads
110
+ // `undefined` as 0 announces an empty result set over a full page of rows.
111
+ setItems(Array.isArray(answer) ? answer : answer.items);
112
+ setTotal(Array.isArray(answer) ? undefined : answer.total);
68
113
  } catch (caught) {
69
114
  fail(caught);
70
115
  } finally {
@@ -106,5 +151,5 @@ export function useResource<T, TCreate = void>(
106
151
  [mutate],
107
152
  );
108
153
 
109
- return { items, loading, error, cause, reload, create, mutate };
154
+ return { items, total, loading, error, cause, reload, create, mutate };
110
155
  }