@marktiderman/genesis-ui-native 3.4.0 → 3.5.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.
@@ -0,0 +1,171 @@
1
+ // @feat:native-components
2
+ /**
3
+ * NativeResourceView's delete, end to end with genesis-core's real hooks: a real QueryClient, an
4
+ * in-memory provider, nothing of core mocked.
5
+ *
6
+ * On the phone `window` is React Native's global object, and Hermes gives it no
7
+ * `addEventListener`. The test DOM (happy-dom) does, which once hid a delete that threw
8
+ * "undefined is not a function" inside core's optimistic write before the provider was asked.
9
+ * Each test here takes the listener methods away before it renders, as the phone has them.
10
+ */
11
+ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
12
+ import { QueryClient } from "@tanstack/react-query";
13
+ import type { ReactNode } from "react";
14
+ import { Alert, Pressable, Text, View } from "react-native";
15
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
16
+ import {
17
+ defineResource,
18
+ GenesisProvider,
19
+ type BaseRecord,
20
+ type DataProvider,
21
+ type Identifier,
22
+ } from "@marktiderman/genesis-core";
23
+ import { defineView } from "@marktiderman/genesis-core/resource-view";
24
+ import { NativeResourceView, type NativeResourceSwipeableProps } from "../index";
25
+
26
+ type Favorite = { id: string; label: string; created_at: string };
27
+
28
+ const favorites = defineResource<Favorite>()({
29
+ name: "favorites",
30
+ key: "id",
31
+ labelField: "label",
32
+ fields: [
33
+ { name: "id", type: "string", readOnly: true },
34
+ { name: "label", type: "string" },
35
+ { name: "created_at", type: "datetime", hasDefault: true, readOnly: true },
36
+ ],
37
+ });
38
+
39
+ const favoritesView = defineView(favorites, {
40
+ columns: { default: ["label", "created_at"] },
41
+ form: [],
42
+ orderBy: { field: "created_at", direction: "desc" },
43
+ can: { update: () => "A favourite has nothing to change." },
44
+ summary: (f) => ({ title: f.label }),
45
+ });
46
+
47
+ /** A data provider over an array: what it holds is what the next read returns. */
48
+ function memoryProvider(seed: Favorite[]) {
49
+ const rows = seed.map((r) => ({ ...r }));
50
+ const deleted: Identifier[] = [];
51
+ const p: DataProvider = {
52
+ async getList<T extends BaseRecord>() {
53
+ return { data: rows.map((r) => ({ ...r })) as unknown as T[], total: rows.length, nextCursor: null };
54
+ },
55
+ async getOne<T extends BaseRecord>(_resource: string, { id }: { id: Identifier }) {
56
+ return { data: { ...rows.find((r) => r.id === id)! } as unknown as T };
57
+ },
58
+ async getMany<T extends BaseRecord>() {
59
+ return { data: [] as T[] };
60
+ },
61
+ async create<T extends BaseRecord>(_resource: string, { data }: { data: Partial<T> }) {
62
+ const row = { id: `f${rows.length + 1}`, label: "", created_at: "2026-01-01T00:00:00Z", ...(data as object) } as Favorite;
63
+ rows.push(row);
64
+ return { data: row as unknown as T };
65
+ },
66
+ async update<T extends BaseRecord>(_resource: string, { id, data }: { id: Identifier; data: Partial<T> }) {
67
+ const row = rows.find((r) => r.id === id)!;
68
+ Object.assign(row, data);
69
+ return { data: { ...row } as unknown as T };
70
+ },
71
+ async deleteOne(_resource: string, { id }: { id: Identifier }) {
72
+ const at = rows.findIndex((r) => r.id === id);
73
+ if (at >= 0) rows.splice(at, 1);
74
+ deleted.push(id);
75
+ return { data: { id } };
76
+ },
77
+ };
78
+ return { p, rows, deleted };
79
+ }
80
+
81
+ const SEED: Favorite[] = [
82
+ { id: "f1", label: "What made you laugh this week?", created_at: "2026-01-03T10:00:00Z" },
83
+ { id: "f2", label: "Where would you go tomorrow?", created_at: "2026-01-02T10:00:00Z" },
84
+ ];
85
+
86
+ function wrap(p: DataProvider) {
87
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
88
+ return ({ children }: { children: ReactNode }) => (
89
+ <GenesisProvider provider={p} queryClient={queryClient}>
90
+ {children}
91
+ </GenesisProvider>
92
+ );
93
+ }
94
+
95
+ /** A swipe slot that draws its actions as buttons, as a consumer app's gesture wrapper does. */
96
+ function TestSwipe({ actions, testID, children }: NativeResourceSwipeableProps) {
97
+ return (
98
+ <View testID={testID}>
99
+ {children}
100
+ {actions.map((action) => (
101
+ <Pressable key={action.id} testID={`${testID}-${action.id}`} onPress={() => action.onPress()}>
102
+ <Text>{action.label}</Text>
103
+ </Pressable>
104
+ ))}
105
+ </View>
106
+ );
107
+ }
108
+
109
+ const alert = Alert.alert as unknown as ReturnType<typeof vi.fn>;
110
+
111
+ /** Press a button of the last Alert.alert. */
112
+ function pressAlert(text: string) {
113
+ const buttons = alert.mock.calls.at(-1)?.[2] as { text: string; onPress?: () => void }[];
114
+ act(() => buttons.find((b) => b.text === text)?.onPress?.());
115
+ }
116
+
117
+ const listenerMethods = ["addEventListener", "removeEventListener"] as const;
118
+ // The test DOM's own methods, put back after each test.
119
+ const ownMethods = listenerMethods.map((name) => [name, Object.getOwnPropertyDescriptor(window, name)] as const);
120
+ function restoreListenerMethods() {
121
+ for (const [name, descriptor] of ownMethods) {
122
+ if (descriptor) Object.defineProperty(window, name, descriptor);
123
+ else delete (window as unknown as Record<string, unknown>)[name];
124
+ }
125
+ }
126
+ /** The phone's `window`: there, but with no listener methods. */
127
+ function asOnThePhone() {
128
+ for (const name of listenerMethods) {
129
+ Object.defineProperty(window, name, { configurable: true, writable: true, value: undefined });
130
+ }
131
+ }
132
+
133
+ beforeEach(() => {
134
+ alert.mockClear();
135
+ asOnThePhone();
136
+ });
137
+ afterEach(() => {
138
+ restoreListenerMethods();
139
+ });
140
+
141
+ describe("NativeResourceView delete on the phone (real core hooks)", () => {
142
+ it("a swipe Delete reaches deleteOne and the row leaves", async () => {
143
+ const { p, deleted } = memoryProvider(SEED);
144
+ render(<NativeResourceView view={favoritesView} swipeable={TestSwipe} />, { wrapper: wrap(p) });
145
+ const press = await screen.findByTestId("native-resource-view-row-f2-swipe-delete");
146
+ fireEvent.click(press);
147
+ expect(alert.mock.calls.at(-1)?.[0]).toBe("Delete “Where would you go tomorrow?”?");
148
+ pressAlert("Delete");
149
+
150
+ await waitFor(() => expect(deleted).toEqual(["f2"]));
151
+ await waitFor(() => expect(screen.queryByTestId("native-resource-view-row-f2")).toBeNull());
152
+ expect(screen.getByTestId("native-resource-view-row-f1")).toBeTruthy();
153
+ // A failed write would show here: the view reports it inline.
154
+ expect(screen.queryByTestId("native-resource-view-refusal")).toBeNull();
155
+ });
156
+
157
+ it("the row sheet's Delete reaches deleteOne and the row leaves", async () => {
158
+ const { p, deleted } = memoryProvider(SEED);
159
+ render(<NativeResourceView view={favoritesView} />, { wrapper: wrap(p) });
160
+ fireEvent.click(await screen.findByTestId("native-resource-view-row-f1"));
161
+ const button = await screen.findByTestId("native-resource-view-peek-delete");
162
+ fireEvent.click(button);
163
+ pressAlert("Delete");
164
+
165
+ await waitFor(() => expect(deleted).toEqual(["f1"]));
166
+ await waitFor(() => expect(screen.queryByTestId("native-resource-view-row-f1")).toBeNull());
167
+ expect(screen.getByTestId("native-resource-view-row-f2")).toBeTruthy();
168
+ // A failed write would show here: the view reports it inline.
169
+ expect(screen.queryByTestId("native-resource-view-refusal")).toBeNull();
170
+ });
171
+ });
@@ -1,4 +1,4 @@
1
- // @feat:native-components
1
+ // @feat:native-components @feat:native-resource-view-cards
2
2
  /**
3
3
  * NativeResourceView: a genesis-core view on native list pieces.
4
4
  * - summary → NativeListItem (its subtitle only, never a raw column);
@@ -9,7 +9,9 @@
9
9
  * - url and image values go through isSafeUrl (`javascript:` is text);
10
10
  * - a calendar day is the same day west of UTC;
11
11
  * - a refused delete comes back and says why, inline;
12
- * - cursor paging and the 300 ms search.
12
+ * - cursor paging and the 300 ms search;
13
+ * - `mode="grid"` and `renderCard` keep sections, paging, refresh, the empty state, press,
14
+ * long press, accessibility actions and swipe.
13
15
  */
14
16
  // West of UTC, where `new Date("2026-01-02")` is the 1st. Before any import builds a formatter.
15
17
  vi.hoisted(() => {
@@ -64,7 +66,10 @@ import {
64
66
  useNativeResourceView,
65
67
  validateValues,
66
68
  writableValues,
69
+ type NativeResourceCardActions,
70
+ type NativeResourceSwipeableProps,
67
71
  } from "..";
72
+ import { gridLines } from "../NativeResourceView";
68
73
 
69
74
  type Brand = {
70
75
  id: string;
@@ -1108,3 +1113,222 @@ describe("row pictures", () => {
1108
1113
  expect(rowItem(pictured(() => ({ src: "javascript:x" })), ROWS[0]!).picture).toBeNull();
1109
1114
  });
1110
1115
  });
1116
+
1117
+ describe("grid and custom rows", () => {
1118
+ const swipes: string[] = [];
1119
+ const Swipe = ({ actions, testID, children }: NativeResourceSwipeableProps) => {
1120
+ swipes.push(`${testID}:${actions.map((a) => a.id).join(",")}`);
1121
+ return <div data-testid={testID}>{children}</div>;
1122
+ };
1123
+ beforeEach(() => {
1124
+ swipes.length = 0;
1125
+ });
1126
+
1127
+ it("draws cards in numColumns columns, the last line kept at its width", async () => {
1128
+ render(<NativeResourceView view={summaryView} mode="grid" numColumns={2} />, { wrapper: wrap(provider()) });
1129
+ const first = await screen.findByTestId("native-resource-view-grid-line-none-0");
1130
+ expect(within(first).getByTestId("native-resource-view-row-b1")).toBeTruthy();
1131
+ expect(within(first).getByTestId("native-resource-view-row-b2")).toBeTruthy();
1132
+ const second = screen.getByTestId("native-resource-view-grid-line-none-1");
1133
+ expect(within(second).getByTestId("native-resource-view-row-b3")).toBeTruthy();
1134
+ // One card and a spacer: the same two columns as the line above.
1135
+ expect(second.children).toHaveLength(2);
1136
+ // A card reads as the row does, with the summary's chip.
1137
+ expect(screen.getByTestId("native-resource-view-row-b1").getAttribute("aria-label")).toBe("Northwind, Since 2026-01-02, Live");
1138
+ expect(screen.getByTestId("native-resource-view-row-b1-chip").textContent).toBe("Live");
1139
+ // No list items in grid mode.
1140
+ expect(screen.queryByTestId("native-resource-view-row-b1-item")).toBeNull();
1141
+ });
1142
+
1143
+ it("keeps sections, press, accessibility actions and swipe in a grid", async () => {
1144
+ const onRowPress = vi.fn();
1145
+ render(<NativeResourceView view={plainView} mode="grid" numColumns={3} onRowPress={onRowPress} swipeable={Swipe} />, { wrapper: wrap(provider()) });
1146
+ // groupBy: status. Each section is its own grid.
1147
+ expect(await screen.findByTestId("native-resource-view-section-active")).toBeTruthy();
1148
+ expect(screen.getByTestId("native-resource-view-section-archived")).toBeTruthy();
1149
+ const card = screen.getByTestId("native-resource-view-row-b1");
1150
+ fireEvent.click(card);
1151
+ expect(onRowPress).toHaveBeenCalledWith(expect.objectContaining({ id: "b1" }));
1152
+ expect(card.getAttribute("data-a11y-actions")).toBe("edit,delete");
1153
+ act(() => {
1154
+ card.dispatchEvent(new CustomEvent("accessibilityaction", { detail: "delete" }));
1155
+ });
1156
+ expect(alert).toHaveBeenLastCalledWith("Delete", "The default brand stays.");
1157
+ expect(swipes).toContain("native-resource-view-row-b1-swipe:edit,delete");
1158
+ });
1159
+
1160
+ it("defaults to two columns, and never fewer than one", async () => {
1161
+ const { unmount } = render(<NativeResourceView view={summaryView} mode="grid" />, { wrapper: wrap(provider()) });
1162
+ expect(within(await screen.findByTestId("native-resource-view-grid-line-none-0")).getByTestId("native-resource-view-row-b2")).toBeTruthy();
1163
+ unmount();
1164
+ render(<NativeResourceView view={summaryView} mode="grid" numColumns={0} />, { wrapper: wrap(provider()) });
1165
+ expect(await screen.findByTestId("native-resource-view-grid-line-none-1")).toBeTruthy();
1166
+ });
1167
+
1168
+ it("keeps the empty state, pull to refresh and paging in a grid", async () => {
1169
+ const getList = vi.fn(async (_r: string, params: ListParams) =>
1170
+ params.pagination?.cursor ? { data: [ROWS[2]!], total: 3, nextCursor: null } : { data: [ROWS[0]!, ROWS[1]!], total: 3, nextCursor: "c2" },
1171
+ );
1172
+ render(<NativeResourceView view={summaryView} mode="grid" perPage={2} />, { wrapper: wrap(provider({ getList: getList as unknown as DataProvider["getList"] })) });
1173
+ await screen.findByTestId("native-resource-view-row-b2");
1174
+ act(() => {
1175
+ screen.getByTestId("native-resource-view-list").dispatchEvent(new Event("endreached"));
1176
+ });
1177
+ expect(await screen.findByTestId("native-resource-view-row-b3")).toBeTruthy();
1178
+ fireEvent.click(screen.getByTestId("native-resource-view-refresh"));
1179
+ await waitFor(() => expect(getList.mock.calls.length).toBeGreaterThan(2));
1180
+
1181
+ const empty = provider({ getList: vi.fn(async () => ({ data: [], total: 0 })) as unknown as DataProvider["getList"] });
1182
+ render(<NativeResourceView view={summaryView} mode="grid" testID="empty-grid" />, { wrapper: wrap(empty) });
1183
+ expect(await screen.findByTestId("empty-grid-empty")).toBeTruthy();
1184
+ });
1185
+
1186
+ it("draws the app's own rows with renderCard, wired for press, long press, accessibility and swipe", async () => {
1187
+ const onRowPress = vi.fn();
1188
+ const renderCard = vi.fn((row: Brand, index: number, card: NativeResourceCardActions) => (
1189
+ <button type="button" data-testid={card.pressableProps.testID} aria-label={card.pressableProps.accessibilityLabel} onClick={card.pressableProps.onPress} onContextMenu={card.pressableProps.onLongPress}>
1190
+ {`${index}:${card.item.title}:${card.actions.map((a) => a.id).join(",")}:${card.first ? "first" : ""}${card.last ? "last" : ""}`}
1191
+ </button>
1192
+ ));
1193
+ render(<NativeResourceView view={plainView} renderCard={renderCard} onRowPress={onRowPress} swipeable={Swipe} />, { wrapper: wrap(provider()) });
1194
+ const custom = await screen.findByTestId("native-resource-view-row-b1");
1195
+ // Northwind and Fabrikam are the active section; Contoso is alone in archived.
1196
+ expect(custom.textContent).toBe("0:Northwind:edit,delete:first");
1197
+ expect(screen.getByTestId("native-resource-view-row-b3").textContent).toBe("1:Fabrikam:edit,delete:last");
1198
+ expect(screen.getByTestId("native-resource-view-row-b2").textContent).toBe("0:Contoso:edit,delete:firstlast");
1199
+ expect(custom.getAttribute("aria-label")).toBe("Northwind");
1200
+ // The built-in row isn't drawn around it.
1201
+ expect(screen.queryByTestId("native-resource-view-row-b1-cell")).toBeNull();
1202
+ fireEvent.click(custom);
1203
+ expect(onRowPress).toHaveBeenCalledWith(expect.objectContaining({ id: "b1" }));
1204
+ fireEvent.contextMenu(custom);
1205
+ expect(alert).toHaveBeenLastCalledWith("Northwind", undefined, expect.arrayContaining([expect.objectContaining({ text: "Edit" })]));
1206
+ expect(swipes).toContain("native-resource-view-row-b1-swipe:edit,delete");
1207
+ });
1208
+
1209
+ it("opens the peek from a custom card without onRowPress", async () => {
1210
+ const renderCard = (_row: Brand, _index: number, card: NativeResourceCardActions) => (
1211
+ <button type="button" data-testid={card.pressableProps.testID} onClick={card.open}>
1212
+ {card.item.title}
1213
+ </button>
1214
+ );
1215
+ render(<NativeResourceView view={summaryView} renderCard={renderCard} />, { wrapper: wrap(provider()) });
1216
+ fireEvent.click(await screen.findByTestId("native-resource-view-row-b2"));
1217
+ expect((await screen.findByTestId("native-resource-view-peek")).textContent).toContain("Contoso");
1218
+ });
1219
+
1220
+ it("uses renderCard for grid cards too, with each card's index in its section", async () => {
1221
+ const renderCard = (row: Brand, index: number, card: NativeResourceCardActions) => (
1222
+ <span data-testid={`card-${row.id}`}>{`${index}:${card.item.title}`}</span>
1223
+ );
1224
+ render(<NativeResourceView view={summaryView} mode="grid" numColumns={2} renderCard={renderCard} />, { wrapper: wrap(provider()) });
1225
+ const line = await screen.findByTestId("native-resource-view-grid-line-none-1");
1226
+ expect(within(line).getByTestId("card-b3").textContent).toBe("2:Fabrikam");
1227
+ expect(screen.getByTestId("card-b1").textContent).toBe("0:Northwind");
1228
+ });
1229
+
1230
+ it("shows the error state in a grid, with a retry", async () => {
1231
+ const failing = provider({ getList: vi.fn(async () => { throw new Error("network down"); }) as unknown as DataProvider["getList"] });
1232
+ render(<NativeResourceView view={summaryView} mode="grid" />, { wrapper: wrap(failing) });
1233
+ const error = await screen.findByTestId("native-resource-view-error");
1234
+ expect(error.textContent).toContain("These brands couldn't be loaded.");
1235
+ expect(within(error).getByText("Try again")).toBeTruthy();
1236
+ expect(screen.queryByTestId("native-resource-view-grid-line-none-0")).toBeNull();
1237
+ });
1238
+
1239
+ // Nine rows, three a page, by cursor both ways.
1240
+ const many: Brand[] = Array.from({ length: 9 }, (_, i) => ({ ...ROWS[1]!, id: `m${i}`, name: `Brand ${i}` }));
1241
+ function threeAPage() {
1242
+ const page = (n: number) => ({
1243
+ data: many.slice(n * 3, n * 3 + 3),
1244
+ nextCursor: n < 2 ? `p${n + 1}` : null,
1245
+ prevCursor: n > 0 ? `p${n - 1}` : null,
1246
+ total: 9,
1247
+ });
1248
+ const getList = vi.fn(async (_r: string, params: ListParams) => page(Number((params.pagination?.cursor ?? "p0").slice(1))));
1249
+ return { getList, p: provider({ getList: getList as unknown as DataProvider["getList"] }) };
1250
+ }
1251
+ const lineOf = (id: string) => screen.getByTestId(`native-resource-view-row-${id}`).closest("[data-testid^='native-resource-view-grid-line-']")!.getAttribute("data-testid");
1252
+
1253
+ it("keeps every card on its line when maxPages drops a page and when it comes back", async () => {
1254
+ const { getList, p } = threeAPage();
1255
+ const props = { view: summaryView, mode: "grid" as const, numColumns: 2, perPage: 3, maxPages: 2 };
1256
+ const { rerender } = render(<NativeResourceView {...props} />, { wrapper: wrap(p) });
1257
+ await screen.findByTestId("native-resource-view-row-m2");
1258
+ // useInfiniteResource turns maxPages on once a render has seen the provider page by cursor.
1259
+ rerender(<NativeResourceView {...props} />);
1260
+ const list = () => screen.getByTestId("native-resource-view-list");
1261
+ act(() => {
1262
+ list().dispatchEvent(new CustomEvent("endreached"));
1263
+ });
1264
+ await screen.findByTestId("native-resource-view-row-m5");
1265
+ expect(lineOf("m4")).toBe("native-resource-view-grid-line-none-2");
1266
+ const card = screen.getByTestId("native-resource-view-row-m4");
1267
+
1268
+ // Page 3 drops page 1: three rows (not a multiple of two) leave the top.
1269
+ act(() => {
1270
+ list().dispatchEvent(new CustomEvent("endreached"));
1271
+ });
1272
+ await screen.findByTestId("native-resource-view-row-m8");
1273
+ await waitFor(() => expect(screen.queryByTestId("native-resource-view-row-m0")).toBeNull());
1274
+ expect(lineOf("m4")).toBe("native-resource-view-grid-line-none-2");
1275
+ // The same card, not a new one: nothing remounted, so pictures don't reload.
1276
+ expect(screen.getByTestId("native-resource-view-row-m4")).toBe(card);
1277
+ // m3 is the second half of line 1 (m2 was dropped): it stays in its column.
1278
+ const line1 = screen.getByTestId("native-resource-view-grid-line-none-1");
1279
+ expect(line1.children).toHaveLength(2);
1280
+ expect(within(line1.children[1] as HTMLElement).getByTestId("native-resource-view-row-m3")).toBeTruthy();
1281
+ expect(within(line1.children[0] as HTMLElement).queryByTestId(/row-/)).toBeNull();
1282
+
1283
+ // Back to the top: page 1 loads again in front, and the lines are as they were.
1284
+ act(() => {
1285
+ list().dispatchEvent(new CustomEvent("startreached"));
1286
+ });
1287
+ await screen.findByTestId("native-resource-view-row-m0");
1288
+ expect(getList.mock.calls.at(-1)![1].pagination).toMatchObject({ cursor: "p0" });
1289
+ expect(lineOf("m2")).toBe("native-resource-view-grid-line-none-1");
1290
+ expect(lineOf("m3")).toBe("native-resource-view-grid-line-none-1");
1291
+ expect(lineOf("m4")).toBe("native-resource-view-grid-line-none-2");
1292
+ expect(screen.getByTestId("native-resource-view-row-m4")).toBe(card);
1293
+ });
1294
+
1295
+ it("counts the rows maxPages dropped above the list", async () => {
1296
+ const { p } = threeAPage();
1297
+ const { result, rerender } = renderHook(() => useNativeResourceView(summaryView, { perPage: 3, maxPages: 2 }), { wrapper: wrap(p) });
1298
+ await waitFor(() => expect(result.current.rows).toHaveLength(3));
1299
+ rerender();
1300
+ expect(result.current.rowOffset).toBe(0);
1301
+ act(() => result.current.loadMore());
1302
+ await waitFor(() => expect(result.current.rows).toHaveLength(6));
1303
+ act(() => result.current.loadMore());
1304
+ await waitFor(() => expect(result.current.rows[0]!.id).toBe("m3"));
1305
+ expect(result.current.rowOffset).toBe(3);
1306
+ act(() => result.current.loadPrevious());
1307
+ await waitFor(() => expect(result.current.rows[0]!.id).toBe("m0"));
1308
+ expect(result.current.rowOffset).toBe(0);
1309
+ });
1310
+
1311
+ it("cuts lines from the section's real start, and keeps unchanged lines the same objects", () => {
1312
+ const rows = many.slice(0, 5);
1313
+ const first = gridLines("", rows, 0, 2);
1314
+ expect(first.map((l) => [l.key, l.lead, l.rows.map((r) => r.id), l.lastIndex])).toEqual([
1315
+ ["none-0", 0, ["m0", "m1"], -1],
1316
+ ["none-1", 0, ["m2", "m3"], -1],
1317
+ ["none-2", 0, ["m4"], 4],
1318
+ ]);
1319
+ // Three rows dropped above: m3 finishes line 1 in its second column.
1320
+ const cut = gridLines("", many.slice(3, 7), 3, 2);
1321
+ expect(cut.map((l) => [l.key, l.lead, l.rows.map((r) => r.id)])).toEqual([
1322
+ ["none-1", 1, ["m3"]],
1323
+ ["none-2", 0, ["m4", "m5"]],
1324
+ ["none-3", 0, ["m6"]],
1325
+ ]);
1326
+ // A page appended: the full lines are the same objects, only the last one changes.
1327
+ const previous = new Map(first.map((l) => [l.key, l]));
1328
+ const grown = gridLines("", many.slice(0, 6), 0, 2, previous);
1329
+ expect(grown[0]).toBe(first[0]);
1330
+ expect(grown[1]).toBe(first[1]);
1331
+ expect(grown[2]).not.toBe(first[2]);
1332
+ expect(grown[2]!.rows.map((r) => r.id)).toEqual(["m4", "m5"]);
1333
+ });
1334
+ });
@@ -1,5 +1,12 @@
1
1
  // NativeResourceView: ResourceView's native renderer (docs/RESOURCE-VIEW.md, "Native").
2
- export { NativeResourceView, type NativeResourceViewProps, type NativeResourceSwipeableProps } from "./NativeResourceView";
2
+ export {
3
+ NativeResourceView,
4
+ type NativeResourceViewProps,
5
+ type NativeResourceSwipeableProps,
6
+ type NativeResourceViewMode,
7
+ type NativeResourceCardActions,
8
+ type NativeResourceCardPressableProps,
9
+ } from "./NativeResourceView";
3
10
  export {
4
11
  useNativeResourceView,
5
12
  SEARCH_DEBOUNCE_MS,
@@ -3,8 +3,8 @@
3
3
  // share its cache patching, rollback and refusal handling), and the view's rows, sections, swipe
4
4
  // actions and form fields resolved once.
5
5
 
6
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
- import type { BaseRecord, DataRow, FilterParam } from "@marktiderman/genesis-core";
6
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
7
+ import { encodeRecordKey, type BaseRecord, type DataRow, type FilterParam } from "@marktiderman/genesis-core";
8
8
  import { useCapabilities, useInfiniteResource, useResource, useViewer } from "@marktiderman/genesis-core/hooks";
9
9
  import { filterParams as toFilters, type Allowed } from "@marktiderman/genesis-core/resource-view";
10
10
  import { useNativeResourceViewMessages } from "./display";
@@ -28,6 +28,15 @@ import {
28
28
  import { fill } from "./messages";
29
29
 
30
30
  type Row = Record<string, unknown>;
31
+
32
+ /** A row's key from the view's key fields (its id when they can't encode it): the list keys rows by it. */
33
+ export const recordKey = (view: AnyResourceView<Row>, row: Row) => {
34
+ try {
35
+ return String(encodeRecordKey(view.contract, row as DataRow));
36
+ } catch {
37
+ return String((row as DataRow).id);
38
+ }
39
+ };
31
40
  type Filter = Readonly<Record<string, string | number | boolean | null | readonly (string | number)[]>>;
32
41
 
33
42
  /** How long typing waits before the search goes to the server. */
@@ -82,6 +91,11 @@ export interface UseNativeResourceViewReturn<T extends Row = Row> {
82
91
  loadPrevious: () => void;
83
92
  loadingPrevious: boolean;
84
93
  hasPrevious: boolean;
94
+ /**
95
+ * How many rows sit above `rows[0]`: the rows `maxPages` dropped from the front, 0 at the top.
96
+ * A grid cuts its lines from here, so dropping or loading back a page never regroups them.
97
+ */
98
+ rowOffset: number;
85
99
  /** What the search box shows (the server sees it 300 ms after the last keystroke). */
86
100
  search: string;
87
101
  setSearch: (text: string) => void;
@@ -292,6 +306,29 @@ export function useNativeResourceView<T extends Row = Row>(
292
306
 
293
307
  const sections = useMemo(() => sectionsFor(view, pages.rows, messages), [view, pages.rows, messages]);
294
308
 
309
+ // The rows above the loaded window, followed across reads by the first row: still loaded lower
310
+ // down means pages came back in front; the new first row lower down in the last read means
311
+ // pages were dropped. At the top (no previous page) it's 0, whatever happened. Compared with
312
+ // the last committed read: the snapshot is written after commit, so a render React throws away
313
+ // never moves it.
314
+ const loaded = useRef<{ keys: string[]; offset: number }>({ keys: [], offset: 0 });
315
+ const hasPrevious = pages.hasPreviousPage;
316
+ const snapshot = useMemo(() => {
317
+ const keys = pages.rows.map((row) => recordKey(view as AnyResourceView<Row>, row as Row));
318
+ const last = loaded.current;
319
+ let offset = 0;
320
+ if (hasPrevious && keys.length > 0 && last.keys.length > 0) {
321
+ const back = keys.indexOf(last.keys[0]!);
322
+ const dropped = last.keys.indexOf(keys[0]!);
323
+ offset = back >= 0 ? last.offset - back : dropped >= 0 ? last.offset + dropped : last.offset;
324
+ }
325
+ return { keys, offset: Math.max(0, offset) };
326
+ }, [view, pages.rows, hasPrevious]);
327
+ useLayoutEffect(() => {
328
+ loaded.current = snapshot;
329
+ }, [snapshot]);
330
+ const rowOffset = snapshot.offset;
331
+
295
332
  const { query } = pages;
296
333
  const [refreshing, setRefreshing] = useState(false);
297
334
  const refresh = useCallback(async () => {
@@ -322,7 +359,8 @@ export function useNativeResourceView<T extends Row = Row>(
322
359
  hasMore: pages.hasNextPage,
323
360
  loadPrevious: pages.fetchPreviousPage,
324
361
  loadingPrevious: query.isFetchingPreviousPage,
325
- hasPrevious: pages.hasPreviousPage,
362
+ hasPrevious,
363
+ rowOffset,
326
364
  search,
327
365
  setSearch,
328
366
  refusal,
@@ -1,6 +1,6 @@
1
1
  // @feat:native-layouts
2
- import { render, screen } from "@testing-library/react";
3
- import { describe, expect, it } from "vitest";
2
+ import { fireEvent, render, screen } from "@testing-library/react";
3
+ import { describe, expect, it, vi } from "vitest";
4
4
  import {
5
5
  ScreenContainer,
6
6
  composeHeaderOptions,
@@ -35,6 +35,55 @@ describe("ScreenContainer", () => {
35
35
  expect(screen.queryByTestId("screen-scroll")).toBeNull();
36
36
  expect(screen.getByTestId("screen-body")).toBeTruthy();
37
37
  });
38
+
39
+ it("has no pull to refresh unless onRefresh is passed", () => {
40
+ render(
41
+ <ScreenContainer testID="screen" scroll>
42
+ <span>Hello</span>
43
+ </ScreenContainer>,
44
+ );
45
+ expect(screen.queryByTestId("screen-refresh")).toBeNull();
46
+ });
47
+
48
+ it("pulls to refresh with onRefresh, and shows the spinner while refreshing", () => {
49
+ const onRefresh = vi.fn();
50
+ const { rerender } = render(
51
+ <ScreenContainer testID="screen" scroll onRefresh={onRefresh}>
52
+ <span>Hello</span>
53
+ </ScreenContainer>,
54
+ );
55
+ const control = screen.getByTestId("screen-refresh");
56
+ expect(control.dataset.refreshing).toBe("false");
57
+ fireEvent.click(control);
58
+ expect(onRefresh).toHaveBeenCalledTimes(1);
59
+ rerender(
60
+ <ScreenContainer testID="screen" scroll onRefresh={onRefresh} refreshing>
61
+ <span>Hello</span>
62
+ </ScreenContainer>,
63
+ );
64
+ expect(screen.getByTestId("screen-refresh").dataset.refreshing).toBe("true");
65
+ });
66
+
67
+ it("makes the body scroll for onRefresh, since pulling needs a scroll view", () => {
68
+ render(
69
+ <ScreenContainer testID="screen" onRefresh={() => {}}>
70
+ <span>Hello</span>
71
+ </ScreenContainer>,
72
+ );
73
+ expect(screen.getByTestId("screen-scroll")).toBeTruthy();
74
+ expect(screen.queryByTestId("screen-body")).toBeNull();
75
+ expect(screen.getByTestId("screen-refresh")).toBeTruthy();
76
+ });
77
+
78
+ it("shows the loading state over a refreshable body", () => {
79
+ render(
80
+ <ScreenContainer testID="screen" onRefresh={() => {}} loading>
81
+ <span>Hello</span>
82
+ </ScreenContainer>,
83
+ );
84
+ expect(screen.getByTestId("screen-loading")).toBeTruthy();
85
+ expect(screen.queryByTestId("screen-refresh")).toBeNull();
86
+ });
38
87
  });
39
88
 
40
89
  describe("composeHeaderOptions", () => {
@@ -7,6 +7,7 @@
7
7
  * - Scroll vs static body
8
8
  * - Tokens-aware background (`bg-background`)
9
9
  * - A loading state (`loading`): a centred `NativeLoadingState` in place of the body
10
+ * - Pull to refresh (`onRefresh` + `refreshing`): a theme-tinted `NativeRefreshControl`
10
11
  *
11
12
  * Header customization is delegated: pass `headerLeft`, `headerRight`,
12
13
  * `large`, `scrollEdgeBehavior`, `safeAreaEdges`, plus any direct
@@ -33,6 +34,7 @@ import { SafeAreaView } from "react-native-safe-area-context";
33
34
  import { cn } from "../utils";
34
35
  import { useThemeMode } from "../hooks/use-theme-mode";
35
36
  import { NativeLoadingState } from "../components/loading-state";
37
+ import { NativeRefreshControl } from "../components/refresh-control";
36
38
 
37
39
  export type SafeAreaEdge = "top" | "bottom" | "left" | "right";
38
40
 
@@ -75,6 +77,16 @@ export interface ScreenContainerProps {
75
77
  loading?: boolean;
76
78
  /** Text under the spinner while `loading`, and what screen readers announce: pass translated text. */
77
79
  loadingLabel?: string;
80
+ /**
81
+ * Pull to refresh: a theme-tinted `NativeRefreshControl` on the body, as InboxPage and
82
+ * NotificationsPage have. Pulling needs a scroll view, so passing it makes the body scroll
83
+ * (as `scroll`). Off unless passed. Never with a list child (FlatList, SectionList,
84
+ * NativeResourceView, InboxPage): a list inside a ScrollView loses virtualization, and those
85
+ * lists have their own pull to refresh.
86
+ */
87
+ onRefresh?: () => void | Promise<void>;
88
+ /** The refresh spinner shows while `true`: pass your query's refetching state. Default `false`. */
89
+ refreshing?: boolean;
78
90
  /** Style on the root, e.g. a theme-role background color. */
79
91
  style?: ViewStyle;
80
92
  /** testID on the root container. */
@@ -183,6 +195,8 @@ export function ScreenContainer({
183
195
  keyboardShouldPersistTaps = "handled",
184
196
  loading = false,
185
197
  loadingLabel,
198
+ onRefresh,
199
+ refreshing = false,
186
200
  style,
187
201
  testID,
188
202
  }: ScreenContainerProps) {
@@ -194,9 +208,14 @@ export function ScreenContainer({
194
208
  <View testID={testID ? `${testID}-body` : undefined} className={cn("flex-1", contentClassName)}>
195
209
  <NativeLoadingState fullScreen={false} label={loadingLabel} testID={`${testID ?? "screen-container"}-loading`} />
196
210
  </View>
197
- ) : scroll ? (
211
+ ) : scroll || onRefresh ? (
198
212
  <ScrollView
199
213
  testID={testID ? `${testID}-scroll` : undefined}
214
+ refreshControl={
215
+ onRefresh ? (
216
+ <NativeRefreshControl testID={`${testID ?? "screen-container"}-refresh`} refreshing={refreshing} onRefresh={() => void onRefresh()} />
217
+ ) : undefined
218
+ }
200
219
  keyboardShouldPersistTaps={keyboardShouldPersistTaps}
201
220
  contentInsetAdjustmentBehavior="automatic"
202
221
  contentContainerClassName={cn("flex-grow", contentClassName)}