@terreno/admin-frontend 0.9.3 → 0.11.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.
Files changed (46) hide show
  1. package/dist/AdminFieldRenderer.js +7 -2
  2. package/dist/AdminFieldRenderer.js.map +1 -1
  3. package/dist/AdminObjectPicker.d.ts +14 -0
  4. package/dist/AdminObjectPicker.js +128 -0
  5. package/dist/AdminObjectPicker.js.map +1 -0
  6. package/dist/AdminPrimitiveArrayField.d.ts +26 -0
  7. package/dist/AdminPrimitiveArrayField.js +55 -0
  8. package/dist/AdminPrimitiveArrayField.js.map +1 -0
  9. package/dist/AdminRefField.d.ts +0 -35
  10. package/dist/AdminRefField.js +2 -75
  11. package/dist/AdminRefField.js.map +1 -1
  12. package/dist/index.d.ts +2 -0
  13. package/dist/index.js +2 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/types.d.ts +8 -1
  16. package/dist/types.js.map +1 -1
  17. package/package.json +5 -4
  18. package/src/AdminFieldRenderer.test.tsx +445 -0
  19. package/src/AdminFieldRenderer.tsx +22 -2
  20. package/src/AdminModelForm.test.tsx +541 -0
  21. package/src/AdminModelList.test.tsx +81 -0
  22. package/src/AdminModelTable.test.tsx +267 -0
  23. package/src/AdminObjectPicker.tsx +253 -0
  24. package/src/AdminPrimitiveArrayField.test.tsx +186 -0
  25. package/src/AdminPrimitiveArrayField.tsx +186 -0
  26. package/src/AdminRefField.tsx +6 -81
  27. package/src/AdminScriptList.test.tsx +49 -2
  28. package/src/AdminVersionConfig.test.tsx +196 -0
  29. package/src/CheckboxListEditor.test.tsx +80 -0
  30. package/src/ConfigurationScreen.test.tsx +140 -0
  31. package/src/ConsentFormEditor.test.tsx +512 -0
  32. package/src/ConsentFormList.test.tsx +115 -0
  33. package/src/ConsentResponseViewer.test.tsx +115 -0
  34. package/src/DocumentStorageBrowser.test.tsx +398 -0
  35. package/src/LocaleContentEditor.test.tsx +143 -0
  36. package/src/index.tsx +2 -0
  37. package/src/isolated/AdminFieldRenderer.isolated.tsx +289 -0
  38. package/src/isolated/AdminNestedArrayField.isolated.tsx +297 -0
  39. package/src/isolated/AdminObjectPicker.isolated.tsx +382 -0
  40. package/src/isolated/AdminRefField.isolated.tsx +29 -0
  41. package/src/isolated/AdminScriptRunModal.isolated.tsx +414 -0
  42. package/src/isolated/DocumentStorageBrowser.isolated.tsx +680 -0
  43. package/src/isolated/generateConsentPdf.isolated.ts +295 -0
  44. package/src/isolated/hooks.isolated.tsx +390 -0
  45. package/src/types.ts +8 -1
  46. package/src/AdminScriptRunModal.test.tsx +0 -69
@@ -0,0 +1,267 @@
1
+ import {beforeEach, describe, expect, it, mock} from "bun:test";
2
+ import {renderWithTheme} from "@terreno/ui/src/test-utils";
3
+ import React from "react";
4
+ import {act, fireEvent} from "../../ui/node_modules/@testing-library/react-native";
5
+
6
+ const routerPush = mock(() => {});
7
+ const setOptions = mock((_: any) => {});
8
+ mock.module("expo-router", () => ({
9
+ router: {push: routerPush},
10
+ useNavigation: () => ({setOptions}),
11
+ }));
12
+
13
+ const configState: {config: any; isLoading: boolean} = {
14
+ config: null,
15
+ isLoading: false,
16
+ };
17
+ mock.module("./useAdminConfig", () => ({
18
+ useAdminConfig: () => ({
19
+ config: configState.config,
20
+ error: null,
21
+ isLoading: configState.isLoading,
22
+ }),
23
+ }));
24
+
25
+ const listState: {data: any; isLoading: boolean} = {
26
+ data: {data: [], total: 0},
27
+ isLoading: false,
28
+ };
29
+ const deleteFn = mock(() => ({unwrap: async () => ({})}));
30
+ mock.module("./useAdminApi", () => ({
31
+ useAdminApi: () => ({
32
+ useCreateMutation: () => [mock(() => ({unwrap: async () => ({})})), {isLoading: false}],
33
+ useDeleteMutation: () => [deleteFn, {isLoading: false}],
34
+ useListQuery: () => ({
35
+ data: listState.data,
36
+ error: null,
37
+ isLoading: listState.isLoading,
38
+ }),
39
+ useReadQuery: () => ({data: null, error: null, isLoading: false}),
40
+ useUpdateMutation: () => [mock(() => ({unwrap: async () => ({})})), {isLoading: false}],
41
+ }),
42
+ }));
43
+
44
+ import {AdminModelTable} from "./AdminModelTable";
45
+
46
+ const fullConfig = {
47
+ customScreens: [],
48
+ models: [
49
+ {
50
+ defaultSort: "-created",
51
+ displayName: "User",
52
+ fields: {
53
+ _id: {required: true, type: "string"},
54
+ active: {required: false, type: "boolean"},
55
+ age: {required: false, type: "number"},
56
+ created: {required: false, type: "date"},
57
+ email: {required: false, type: "string"},
58
+ tags: {required: false, type: "array"},
59
+ },
60
+ listFields: ["email", "active", "age", "created", "tags"],
61
+ name: "User",
62
+ routePath: "/admin/users",
63
+ },
64
+ ],
65
+ scripts: [],
66
+ };
67
+
68
+ describe("AdminModelTable", () => {
69
+ beforeEach(() => {
70
+ routerPush.mockClear();
71
+ setOptions.mockClear();
72
+ deleteFn.mockClear();
73
+ configState.config = null;
74
+ configState.isLoading = false;
75
+ listState.data = {data: [], total: 0};
76
+ listState.isLoading = false;
77
+ });
78
+
79
+ it("renders loading page while config is loading", () => {
80
+ configState.isLoading = true;
81
+ const {toJSON} = renderWithTheme(
82
+ <AdminModelTable api={{} as any} baseUrl="/admin" modelName="User" />
83
+ );
84
+ expect(toJSON()).toBeDefined();
85
+ });
86
+
87
+ it("renders loading page when model config is missing", () => {
88
+ configState.config = {customScreens: [], models: [], scripts: []};
89
+ const {toJSON} = renderWithTheme(
90
+ <AdminModelTable api={{} as any} baseUrl="/admin" modelName="User" />
91
+ );
92
+ expect(toJSON()).toBeDefined();
93
+ });
94
+
95
+ it("renders empty state when no data present", () => {
96
+ configState.config = fullConfig;
97
+ const {toJSON} = renderWithTheme(
98
+ <AdminModelTable api={{} as any} baseUrl="/admin" modelName="User" />
99
+ );
100
+ expect(toJSON()).toBeDefined();
101
+ expect(setOptions).toHaveBeenCalled();
102
+ });
103
+
104
+ it("renders loading state when the list query is loading", () => {
105
+ configState.config = fullConfig;
106
+ listState.isLoading = true;
107
+ const {toJSON} = renderWithTheme(
108
+ <AdminModelTable api={{} as any} baseUrl="/admin" modelName="User" />
109
+ );
110
+ expect(toJSON()).toBeDefined();
111
+ });
112
+
113
+ it("renders data with various column types and formats values", () => {
114
+ configState.config = fullConfig;
115
+ listState.data = {
116
+ data: [
117
+ {
118
+ _id: "u1",
119
+ active: true,
120
+ age: 42,
121
+ created: "2024-01-01T00:00:00Z",
122
+ email: "a@b.com",
123
+ tags: ["x", "y"],
124
+ },
125
+ {
126
+ _id: "u2",
127
+ active: false,
128
+ age: null,
129
+ created: null,
130
+ email: "c@d.com",
131
+ tags: {_id: "nested", other: "value"},
132
+ },
133
+ ],
134
+ total: 2,
135
+ };
136
+ const {toJSON} = renderWithTheme(
137
+ <AdminModelTable api={{} as any} baseUrl="/admin" modelName="User" />
138
+ );
139
+ expect(toJSON()).toBeDefined();
140
+ });
141
+
142
+ it("supports custom column overrides", () => {
143
+ configState.config = fullConfig;
144
+ listState.data = {
145
+ data: [{_id: "u1", email: "a@b.com"}],
146
+ total: 1,
147
+ };
148
+ const {toJSON} = renderWithTheme(
149
+ <AdminModelTable api={{} as any} baseUrl="/admin" columns={["email"]} modelName="User" />
150
+ );
151
+ expect(toJSON()).toBeDefined();
152
+ });
153
+
154
+ it("treats DATE_FIELD_NAMES without explicit type as date columns and widens _id", () => {
155
+ // "created" and "updated" should be recognized as date fields even without an
156
+ // explicit fieldConfig.type of "date"; "_id" should use the wider column width.
157
+ configState.config = {
158
+ customScreens: [],
159
+ models: [
160
+ {
161
+ defaultSort: undefined,
162
+ displayName: "Plain",
163
+ fields: {
164
+ _id: {required: true, type: "string"},
165
+ // Intentionally mark created/updated as "string" so the DATE_FIELD_NAMES
166
+ // branch (line 49) must be the branch that classifies them as "date".
167
+ created: {required: false, type: "string"},
168
+ name: {required: false, type: "string"},
169
+ updated: {required: false, type: "string"},
170
+ },
171
+ listFields: ["_id", "name", "created", "updated"],
172
+ name: "Plain",
173
+ routePath: "/admin/plain",
174
+ },
175
+ ],
176
+ scripts: [],
177
+ };
178
+ listState.data = {
179
+ data: [
180
+ {
181
+ _id: "p1",
182
+ created: "2024-01-02T00:00:00Z",
183
+ name: "thing",
184
+ updated: "2024-02-03T00:00:00Z",
185
+ },
186
+ ],
187
+ total: 1,
188
+ };
189
+ const {toJSON} = renderWithTheme(
190
+ <AdminModelTable api={{} as any} baseUrl="/admin" modelName="Plain" />
191
+ );
192
+ expect(toJSON()).toBeDefined();
193
+ });
194
+
195
+ it("renders the headerRight create button and pushes to the create route on click", async () => {
196
+ configState.config = fullConfig;
197
+ let headerRight: React.ReactElement | null = null;
198
+ setOptions.mockImplementation((opts: any) => {
199
+ if (opts?.headerRight) {
200
+ headerRight = opts.headerRight();
201
+ }
202
+ });
203
+ renderWithTheme(<AdminModelTable api={{} as any} baseUrl="/admin" modelName="User" />);
204
+ expect(headerRight).not.toBeNull();
205
+ const header = renderWithTheme(headerRight as unknown as React.ReactElement);
206
+ await act(async () => {
207
+ fireEvent.press(header.getByTestId("admin-create-button"));
208
+ await new Promise((r) => setTimeout(r, 50));
209
+ });
210
+ expect(routerPush).toHaveBeenCalledWith("/admin/User/create");
211
+ });
212
+
213
+ it("handles delete errors without throwing via the actions cell", async () => {
214
+ configState.config = fullConfig;
215
+ listState.data = {
216
+ data: [{_id: "u1", active: true, age: 1, created: null, email: "a@b.com", tags: []}],
217
+ total: 1,
218
+ };
219
+ // Force delete to fail so the catch branch runs.
220
+ deleteFn.mockImplementationOnce(() => ({
221
+ unwrap: async () => {
222
+ throw new Error("nope");
223
+ },
224
+ }));
225
+ const {UNSAFE_root} = renderWithTheme(
226
+ <AdminModelTable api={{} as any} baseUrl="/admin" modelName="User" />
227
+ );
228
+ // Find the actions cellData.onDelete handler and invoke it directly.
229
+ const nodes = UNSAFE_root.findAll((n: any) => {
230
+ const v = n.props?.cellData?.value;
231
+ return v && typeof v.onDelete === "function" && v.id === "u1";
232
+ });
233
+ expect(nodes.length).toBeGreaterThan(0);
234
+ await act(async () => {
235
+ (nodes[0] as any).props.cellData.value.onDelete("u1");
236
+ await new Promise((r) => setTimeout(r, 50));
237
+ });
238
+ expect(deleteFn).toHaveBeenCalled();
239
+ });
240
+
241
+ it("builds a descending sort string and falls back when column is out of range", async () => {
242
+ configState.config = fullConfig;
243
+ // Render data so DataTable mounts; then capture the setSortColumn via a dummy
244
+ // rendering. We instead verify the pure helper via a specially-crafted sort
245
+ // that maps to an out-of-range column by using columns override with only one field.
246
+ listState.data = {
247
+ data: [{_id: "u1", email: "a@b.com"}],
248
+ total: 1,
249
+ };
250
+ const {UNSAFE_root, toJSON} = renderWithTheme(
251
+ <AdminModelTable api={{} as any} baseUrl="/admin" columns={["email"]} modelName="User" />
252
+ );
253
+ // Grab setSortColumn from the rendered DataTable and apply a sort with
254
+ // direction "desc" on column 0 (valid) and then column 5 (out of range).
255
+ const table = UNSAFE_root.findAll((n: any) => typeof n.props?.setSortColumn === "function");
256
+ expect(table.length).toBeGreaterThan(0);
257
+ await act(async () => {
258
+ (table[0] as any).props.setSortColumn({column: 0, direction: "desc"});
259
+ await new Promise((r) => setTimeout(r, 10));
260
+ });
261
+ await act(async () => {
262
+ (table[0] as any).props.setSortColumn({column: 99, direction: "asc"});
263
+ await new Promise((r) => setTimeout(r, 10));
264
+ });
265
+ expect(toJSON()).toBeDefined();
266
+ });
267
+ });
@@ -0,0 +1,253 @@
1
+ import type {Api} from "@reduxjs/toolkit/query/react";
2
+ import {Box, IconButton, Spinner, Text, TextField} from "@terreno/ui";
3
+ import React, {useCallback, useEffect, useMemo, useRef, useState} from "react";
4
+
5
+ interface AdminObjectPickerProps {
6
+ api: Api<any, any, any, any>;
7
+ routePath: string;
8
+ refModelName: string;
9
+ title: string;
10
+ value: string;
11
+ onChange: (value: string) => void;
12
+ errorText?: string;
13
+ helperText?: string;
14
+ }
15
+
16
+ const DISPLAY_FIELDS = ["name", "title", "email", "label", "displayName"];
17
+
18
+ const getDisplayValue = (item: any): string => {
19
+ for (const field of DISPLAY_FIELDS) {
20
+ if (item[field]) {
21
+ return String(item[field]);
22
+ }
23
+ }
24
+ return item._id ?? String(item);
25
+ };
26
+
27
+ const getSecondaryText = (item: any, primaryField: string): string | undefined => {
28
+ for (const field of DISPLAY_FIELDS) {
29
+ if (field !== primaryField && item[field]) {
30
+ return String(item[field]);
31
+ }
32
+ }
33
+ return undefined;
34
+ };
35
+
36
+ const getPrimaryField = (item: any): string => {
37
+ for (const field of DISPLAY_FIELDS) {
38
+ if (item[field]) {
39
+ return field;
40
+ }
41
+ }
42
+ return "_id";
43
+ };
44
+
45
+ export const AdminObjectPicker: React.FC<AdminObjectPickerProps> = ({
46
+ api,
47
+ routePath,
48
+ refModelName,
49
+ title,
50
+ value,
51
+ onChange,
52
+ errorText,
53
+ helperText,
54
+ }) => {
55
+ const [searchText, setSearchText] = useState("");
56
+ const [isOpen, setIsOpen] = useState(false);
57
+ const [isChanging, setIsChanging] = useState(false);
58
+ const [selectedDisplay, setSelectedDisplay] = useState("");
59
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
60
+ const [debouncedQuery, setDebouncedQuery] = useState("");
61
+
62
+ // Clear pending debounce on unmount
63
+ useEffect(() => {
64
+ return () => {
65
+ if (debounceRef.current) {
66
+ clearTimeout(debounceRef.current);
67
+ }
68
+ };
69
+ }, []);
70
+
71
+ const searchEndpointKey = `adminSearch_${refModelName}`;
72
+ const readEndpointKey = `adminSearchRead_${refModelName}`;
73
+
74
+ const enhancedApi = useMemo(() => {
75
+ return api.injectEndpoints({
76
+ endpoints: (build: any) => ({
77
+ [searchEndpointKey]: build.query({
78
+ query: (q: string) => ({
79
+ method: "GET",
80
+ params: {q},
81
+ url: `${routePath}/search`,
82
+ }),
83
+ }),
84
+ [readEndpointKey]: build.query({
85
+ query: (id: string) => ({
86
+ method: "GET",
87
+ url: `${routePath}/${id}`,
88
+ }),
89
+ }),
90
+ }),
91
+ overrideExisting: true,
92
+ });
93
+ }, [api, routePath, searchEndpointKey, readEndpointKey]);
94
+
95
+ const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
96
+ const useSearchQuery = (enhancedApi as any)[`use${capitalize(searchEndpointKey)}Query`];
97
+ const useReadQuery = (enhancedApi as any)[`use${capitalize(readEndpointKey)}Query`];
98
+
99
+ const {data: searchData, isFetching: isSearching} = useSearchQuery(debouncedQuery, {
100
+ skip: !debouncedQuery,
101
+ });
102
+
103
+ // Fetch the currently selected item to display its name
104
+ const {data: selectedItem} = useReadQuery(value, {
105
+ skip: !value,
106
+ });
107
+
108
+ // Update display when selected item loads
109
+ useEffect(() => {
110
+ if (selectedItem && value) {
111
+ setSelectedDisplay(getDisplayValue(selectedItem));
112
+ }
113
+ }, [selectedItem, value]);
114
+
115
+ const handleSearchChange = useCallback((text: string) => {
116
+ setSearchText(text);
117
+ setIsOpen(true);
118
+
119
+ if (debounceRef.current) {
120
+ clearTimeout(debounceRef.current);
121
+ }
122
+ debounceRef.current = setTimeout(() => {
123
+ setDebouncedQuery(text);
124
+ }, 300);
125
+ }, []);
126
+
127
+ const handleSelect = useCallback(
128
+ (item: any) => {
129
+ onChange(item._id);
130
+ setSelectedDisplay(getDisplayValue(item));
131
+ setSearchText("");
132
+ setDebouncedQuery("");
133
+ setIsOpen(false);
134
+ setIsChanging(false);
135
+ },
136
+ [onChange]
137
+ );
138
+
139
+ const handleClear = useCallback(() => {
140
+ onChange("");
141
+ setSelectedDisplay("");
142
+ setSearchText("");
143
+ setDebouncedQuery("");
144
+ setIsOpen(false);
145
+ setIsChanging(false);
146
+ }, [onChange]);
147
+
148
+ const handleChange = useCallback(() => {
149
+ setSearchText("");
150
+ setDebouncedQuery("");
151
+ setIsChanging(true);
152
+ setIsOpen(true);
153
+ }, []);
154
+
155
+ // emptyApi unwraps `{data: T}` unless the body has `more` (paginated list). Search returns only
156
+ // `{data: [...]}`, so `searchData` is already the result array.
157
+ const results = Array.isArray(searchData)
158
+ ? searchData
159
+ : ((searchData as {data?: unknown[]} | undefined)?.data ?? []);
160
+
161
+ return (
162
+ <Box gap={1}>
163
+ {value && selectedDisplay && !isChanging ? (
164
+ <Box alignItems="center" direction="row" gap={2}>
165
+ <Box flex="grow">
166
+ <TextField
167
+ disabled
168
+ helperText={helperText}
169
+ onChange={() => {}}
170
+ testID={`admin-picker-${refModelName}-display`}
171
+ title={title}
172
+ value={selectedDisplay}
173
+ />
174
+ </Box>
175
+ <IconButton
176
+ accessibilityHint="Opens search to pick a different value"
177
+ accessibilityLabel="Change selection"
178
+ iconName="pencil"
179
+ onClick={handleChange}
180
+ testID={`admin-picker-${refModelName}-change`}
181
+ />
182
+ <IconButton
183
+ accessibilityHint="Clears the current selection"
184
+ accessibilityLabel="Clear selection"
185
+ iconName="xmark"
186
+ onClick={handleClear}
187
+ testID={`admin-picker-${refModelName}-clear`}
188
+ />
189
+ </Box>
190
+ ) : (
191
+ <TextField
192
+ errorText={errorText}
193
+ helperText={isOpen ? "Type to search" : helperText}
194
+ onChange={handleSearchChange}
195
+ onFocus={() => setIsOpen(true)}
196
+ testID={`admin-picker-${refModelName}-search`}
197
+ title={title}
198
+ value={searchText}
199
+ />
200
+ )}
201
+
202
+ {isOpen && (
203
+ <Box border="default" maxHeight={250} overflow="scrollY" rounding="md">
204
+ {isSearching && (
205
+ <Box alignItems="center" padding={3}>
206
+ <Spinner />
207
+ </Box>
208
+ )}
209
+
210
+ {!isSearching && debouncedQuery && results.length === 0 && (
211
+ <Box padding={3}>
212
+ <Text color="secondaryDark" size="sm">
213
+ No results found
214
+ </Text>
215
+ </Box>
216
+ )}
217
+
218
+ {!isSearching &&
219
+ results.map((item: any) => {
220
+ const primaryField = getPrimaryField(item);
221
+ const secondary = getSecondaryText(item, primaryField);
222
+ return (
223
+ <Box
224
+ accessibilityHint={`Selects ${getDisplayValue(item)}`}
225
+ accessibilityLabel={`Select ${getDisplayValue(item)}`}
226
+ key={item._id}
227
+ onClick={() => handleSelect(item)}
228
+ paddingX={3}
229
+ paddingY={2}
230
+ testID={`admin-picker-${refModelName}-result-${item._id}`}
231
+ >
232
+ <Text size="sm">{getDisplayValue(item)}</Text>
233
+ {secondary && (
234
+ <Text color="secondaryDark" size="sm">
235
+ {secondary}
236
+ </Text>
237
+ )}
238
+ </Box>
239
+ );
240
+ })}
241
+
242
+ {!isSearching && !debouncedQuery && (
243
+ <Box padding={3}>
244
+ <Text color="secondaryDark" size="sm">
245
+ Start typing to search
246
+ </Text>
247
+ </Box>
248
+ )}
249
+ </Box>
250
+ )}
251
+ </Box>
252
+ );
253
+ };
@@ -0,0 +1,186 @@
1
+ import {describe, expect, it, mock} from "bun:test";
2
+ import {renderWithTheme} from "@terreno/ui/src/test-utils";
3
+ import React from "react";
4
+ import {act, fireEvent} from "../../ui/node_modules/@testing-library/react-native";
5
+ import {AdminPrimitiveArrayField} from "./AdminPrimitiveArrayField";
6
+
7
+ const press = async (el: any): Promise<void> => {
8
+ await act(async () => {
9
+ fireEvent.press(el);
10
+ await new Promise((r) => setTimeout(r, 150));
11
+ });
12
+ };
13
+
14
+ const mockApi: any = {
15
+ endpoints: {},
16
+ reducerPath: "test",
17
+ };
18
+
19
+ describe("AdminPrimitiveArrayField", () => {
20
+ it("renders empty state when no items", () => {
21
+ const {getByText, getByTestId} = renderWithTheme(
22
+ <AdminPrimitiveArrayField
23
+ api={mockApi}
24
+ baseUrl="/admin"
25
+ itemType="string"
26
+ onChange={() => {}}
27
+ title="Tags"
28
+ value={[]}
29
+ />
30
+ );
31
+ expect(getByText(/No items/i)).toBeDefined();
32
+ expect(getByTestId("admin-array-add-Tags")).toBeDefined();
33
+ });
34
+
35
+ it("renders existing string items as TextFields", () => {
36
+ const {getByTestId} = renderWithTheme(
37
+ <AdminPrimitiveArrayField
38
+ api={mockApi}
39
+ baseUrl="/admin"
40
+ itemType="string"
41
+ onChange={() => {}}
42
+ title="Tags"
43
+ value={["foo", "bar"]}
44
+ />
45
+ );
46
+ expect(getByTestId("admin-array-item-0")).toBeDefined();
47
+ expect(getByTestId("admin-array-item-1")).toBeDefined();
48
+ expect(getByTestId("admin-array-remove-0")).toBeDefined();
49
+ expect(getByTestId("admin-array-remove-1")).toBeDefined();
50
+ });
51
+
52
+ it("adds a new item with the type's default", async () => {
53
+ const onChange = mock((_: unknown) => undefined);
54
+ const {getByTestId} = renderWithTheme(
55
+ <AdminPrimitiveArrayField
56
+ api={mockApi}
57
+ baseUrl="/admin"
58
+ itemType="string"
59
+ onChange={onChange}
60
+ title="Tags"
61
+ value={["foo"]}
62
+ />
63
+ );
64
+ await press(getByTestId("admin-array-add-Tags"));
65
+ expect(onChange).toHaveBeenCalled();
66
+ const next = (onChange.mock.calls[0] as any)[0];
67
+ expect(next).toEqual(["foo", ""]);
68
+ });
69
+
70
+ it("removes an item when the remove button is pressed", async () => {
71
+ const onChange = mock((_: unknown) => undefined);
72
+ const {getByTestId} = renderWithTheme(
73
+ <AdminPrimitiveArrayField
74
+ api={mockApi}
75
+ baseUrl="/admin"
76
+ itemType="string"
77
+ onChange={onChange}
78
+ title="Tags"
79
+ value={["a", "b", "c"]}
80
+ />
81
+ );
82
+ await press(getByTestId("admin-array-remove-1"));
83
+ expect(onChange).toHaveBeenCalled();
84
+ const next = (onChange.mock.calls[0] as any)[0];
85
+ expect(next).toEqual(["a", "c"]);
86
+ });
87
+
88
+ it("updates a string item when its TextField changes", () => {
89
+ const onChange = mock((_: unknown) => undefined);
90
+ const {getByTestId} = renderWithTheme(
91
+ <AdminPrimitiveArrayField
92
+ api={mockApi}
93
+ baseUrl="/admin"
94
+ itemType="string"
95
+ onChange={onChange}
96
+ title="Tags"
97
+ value={["old"]}
98
+ />
99
+ );
100
+ fireEvent.changeText(getByTestId("admin-array-item-0"), "new");
101
+ expect(onChange).toHaveBeenCalled();
102
+ const next = (onChange.mock.calls[0] as any)[0];
103
+ expect(next).toEqual(["new"]);
104
+ });
105
+
106
+ it("coerces number input via Number()", () => {
107
+ const onChange = mock((_: unknown) => undefined);
108
+ const {getByTestId} = renderWithTheme(
109
+ <AdminPrimitiveArrayField
110
+ api={mockApi}
111
+ baseUrl="/admin"
112
+ itemType="number"
113
+ onChange={onChange}
114
+ title="Scores"
115
+ value={[1, 2]}
116
+ />
117
+ );
118
+ fireEvent.changeText(getByTestId("admin-array-item-0"), "42");
119
+ const next = (onChange.mock.calls[0] as any)[0];
120
+ expect(next).toEqual([42, 2]);
121
+ });
122
+
123
+ it("uses the boolean default when adding to a [Boolean] field", async () => {
124
+ const onChange = mock((_: unknown) => undefined);
125
+ const {getByTestId} = renderWithTheme(
126
+ <AdminPrimitiveArrayField
127
+ api={mockApi}
128
+ baseUrl="/admin"
129
+ itemType="boolean"
130
+ onChange={onChange}
131
+ title="Flags"
132
+ value={[]}
133
+ />
134
+ );
135
+ await press(getByTestId("admin-array-add-Flags"));
136
+ const next = (onChange.mock.calls[0] as any)[0];
137
+ expect(next).toEqual([false]);
138
+ });
139
+
140
+ it("uses the number default when adding to a [Number] field", async () => {
141
+ const onChange = mock((_: unknown) => undefined);
142
+ const {getByTestId} = renderWithTheme(
143
+ <AdminPrimitiveArrayField
144
+ api={mockApi}
145
+ baseUrl="/admin"
146
+ itemType="number"
147
+ onChange={onChange}
148
+ title="Scores"
149
+ value={[]}
150
+ />
151
+ );
152
+ await press(getByTestId("admin-array-add-Scores"));
153
+ const next = (onChange.mock.calls[0] as any)[0];
154
+ expect(next).toEqual([0]);
155
+ });
156
+
157
+ it("renders enum items as a SelectField", () => {
158
+ const {toJSON} = renderWithTheme(
159
+ <AdminPrimitiveArrayField
160
+ api={mockApi}
161
+ baseUrl="/admin"
162
+ itemEnum={["low", "medium", "high"]}
163
+ itemType="string"
164
+ onChange={() => {}}
165
+ title="Levels"
166
+ value={["low"]}
167
+ />
168
+ );
169
+ // SelectField has no testID prop here, so just sanity-check the tree renders
170
+ expect(toJSON()).toBeDefined();
171
+ });
172
+
173
+ it("handles non-array values gracefully", () => {
174
+ const {toJSON} = renderWithTheme(
175
+ <AdminPrimitiveArrayField
176
+ api={mockApi}
177
+ baseUrl="/admin"
178
+ itemType="string"
179
+ onChange={() => {}}
180
+ title="Tags"
181
+ value={undefined as any}
182
+ />
183
+ );
184
+ expect(toJSON()).toBeDefined();
185
+ });
186
+ });