@terreno/admin-frontend 0.11.6 → 0.11.8

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 (40) hide show
  1. package/dist/AdminFieldRenderer.d.ts +9 -1
  2. package/dist/AdminFieldRenderer.js +10 -6
  3. package/dist/AdminFieldRenderer.js.map +1 -1
  4. package/dist/AdminModelForm.d.ts +7 -0
  5. package/dist/AdminModelForm.js +2 -2
  6. package/dist/AdminModelForm.js.map +1 -1
  7. package/dist/AdminModelTable.d.ts +7 -0
  8. package/dist/AdminModelTable.js +4 -2
  9. package/dist/AdminModelTable.js.map +1 -1
  10. package/dist/AdminNestedArrayField.d.ts +3 -1
  11. package/dist/AdminNestedArrayField.js +3 -2
  12. package/dist/AdminNestedArrayField.js.map +1 -1
  13. package/dist/AdminPrimitiveArrayField.d.ts +7 -0
  14. package/dist/AdminPrimitiveArrayField.js +10 -3
  15. package/dist/AdminPrimitiveArrayField.js.map +1 -1
  16. package/dist/AdminRefField.d.ts +7 -14
  17. package/dist/AdminRefField.js.map +1 -1
  18. package/dist/AdminScriptList.js +1 -1
  19. package/dist/AdminScriptList.js.map +1 -1
  20. package/dist/AdminScriptRunModal.d.ts +3 -0
  21. package/dist/AdminScriptRunModal.js +42 -34
  22. package/dist/AdminScriptRunModal.js.map +1 -1
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/types.d.ts +26 -0
  26. package/dist/types.js.map +1 -1
  27. package/package.json +2 -2
  28. package/src/AdminFieldRenderer.test.tsx +50 -0
  29. package/src/AdminFieldRenderer.tsx +30 -3
  30. package/src/AdminModelForm.tsx +9 -1
  31. package/src/AdminModelTable.test.tsx +65 -0
  32. package/src/AdminModelTable.tsx +10 -1
  33. package/src/AdminNestedArrayField.tsx +6 -1
  34. package/src/AdminPrimitiveArrayField.tsx +36 -12
  35. package/src/AdminRefField.tsx +7 -13
  36. package/src/AdminScriptList.tsx +1 -0
  37. package/src/AdminScriptRunModal.test.tsx +129 -0
  38. package/src/AdminScriptRunModal.tsx +91 -33
  39. package/src/index.tsx +3 -1
  40. package/src/types.ts +28 -0
@@ -1,20 +1,14 @@
1
- import type {Api} from "@reduxjs/toolkit/query/react";
2
1
  import React from "react";
3
2
  import {AdminObjectPicker} from "./AdminObjectPicker";
3
+ import type {RefFieldRendererProps} from "./types";
4
4
 
5
- interface AdminRefFieldProps {
6
- api: Api<any, any, any, any>;
7
- baseUrl: string;
8
- routePath: string;
9
- refModelName: string;
10
- title: string;
11
- value: string;
12
- onChange: (value: string) => void;
13
- errorText?: string;
14
- helperText?: string;
15
- }
5
+ /**
6
+ * Props for the built-in {@link AdminRefField} renderer. Re-exported as the
7
+ * shape custom ref renderers should accept (see {@link RefFieldRendererProps}).
8
+ */
9
+ export type AdminRefFieldProps = RefFieldRendererProps;
16
10
 
17
- export const AdminRefField: React.FC<AdminRefFieldProps> = ({
11
+ export const AdminRefField: React.FC<RefFieldRendererProps> = ({
18
12
  api,
19
13
  routePath,
20
14
  refModelName,
@@ -88,6 +88,7 @@ export const AdminScriptList: React.FC<AdminScriptListProps> = ({baseUrl, api, i
88
88
  api={api}
89
89
  baseUrl={baseUrl}
90
90
  onDismiss={handleDismiss}
91
+ scriptDescription={selectedScript?.description}
91
92
  scriptName={selectedScript?.name ?? null}
92
93
  visible={modalVisible}
93
94
  />
@@ -0,0 +1,129 @@
1
+ import {beforeEach, describe, expect, it, mock} from "bun:test";
2
+ import * as terrenoUi from "@terreno/ui";
3
+ import {renderWithTheme} from "@terreno/ui/src/test-utils";
4
+ import React from "react";
5
+ import {act, fireEvent} from "../../ui/node_modules/@testing-library/react-native";
6
+ import {AdminScriptRunModal} from "./AdminScriptRunModal";
7
+
8
+ // Render Modal children inline so we can interact with them in tests
9
+ mock.module("@terreno/ui", () => ({
10
+ ...terrenoUi,
11
+ Modal: ({children, visible}: {children?: React.ReactNode; visible?: boolean}) =>
12
+ visible ? <>{children}</> : null,
13
+ }));
14
+
15
+ const mockRunScript = mock((_args: {name: string; wetRun: boolean}) => ({
16
+ unwrap: async () => ({taskId: "task-123"}),
17
+ }));
18
+ const mockCancelTask = mock((_taskId: string) => ({
19
+ unwrap: async () => ({}),
20
+ }));
21
+
22
+ const mockUseAdminScripts = mock(() => ({
23
+ useCancelScriptTaskMutation: () => [mockCancelTask, {isLoading: false}],
24
+ useGetScriptTaskQuery: () => ({data: undefined, isLoading: false, error: null}),
25
+ useRunScriptMutation: () => [mockRunScript, {isLoading: false}],
26
+ }));
27
+
28
+ mock.module("./useAdminScripts", () => ({
29
+ useAdminScripts: (...args: any[]) => mockUseAdminScripts(...args),
30
+ }));
31
+
32
+ const mockApi = {} as any;
33
+
34
+ describe("AdminScriptRunModal", () => {
35
+ beforeEach(() => {
36
+ mockRunScript.mockClear();
37
+ mockCancelTask.mockClear();
38
+ mockUseAdminScripts.mockClear();
39
+ });
40
+
41
+ it("renders Dry Run, Run, and Cancel buttons in confirm phase", () => {
42
+ const {getByTestId} = renderWithTheme(
43
+ <AdminScriptRunModal
44
+ api={mockApi}
45
+ baseUrl="/admin"
46
+ onDismiss={() => undefined}
47
+ scriptName="my-script"
48
+ visible
49
+ />
50
+ );
51
+
52
+ expect(getByTestId("admin-script-dry-run-button")).toBeTruthy();
53
+ expect(getByTestId("admin-script-wet-run-button")).toBeTruthy();
54
+ expect(getByTestId("admin-script-confirm-cancel-button")).toBeTruthy();
55
+ });
56
+
57
+ it("calls onDismiss when Cancel is pressed without invoking runScript", async () => {
58
+ const onDismiss = mock(() => undefined);
59
+
60
+ const {getByTestId} = renderWithTheme(
61
+ <AdminScriptRunModal
62
+ api={mockApi}
63
+ baseUrl="/admin"
64
+ onDismiss={onDismiss}
65
+ scriptName="my-script"
66
+ visible
67
+ />
68
+ );
69
+
70
+ await act(async () => {
71
+ fireEvent.press(getByTestId("admin-script-confirm-cancel-button"));
72
+ });
73
+
74
+ expect(onDismiss).toHaveBeenCalled();
75
+ expect(mockRunScript).not.toHaveBeenCalled();
76
+ });
77
+
78
+ it("dispatches a dry run when the Dry Run button is pressed", async () => {
79
+ const {getByTestId} = renderWithTheme(
80
+ <AdminScriptRunModal
81
+ api={mockApi}
82
+ baseUrl="/admin"
83
+ onDismiss={() => undefined}
84
+ scriptName="my-script"
85
+ visible
86
+ />
87
+ );
88
+
89
+ await act(async () => {
90
+ fireEvent.press(getByTestId("admin-script-dry-run-button"));
91
+ });
92
+
93
+ expect(mockRunScript).toHaveBeenCalledTimes(1);
94
+ expect(mockRunScript.mock.calls[0]?.[0]).toEqual({name: "my-script", wetRun: false});
95
+ });
96
+
97
+ it("hides the wet-run button when dryRunOnly is true", () => {
98
+ const {getByTestId, queryByTestId} = renderWithTheme(
99
+ <AdminScriptRunModal
100
+ api={mockApi}
101
+ baseUrl="/admin"
102
+ dryRunOnly
103
+ onDismiss={() => undefined}
104
+ scriptName="my-script"
105
+ visible
106
+ />
107
+ );
108
+
109
+ expect(getByTestId("admin-script-dry-run-button")).toBeTruthy();
110
+ expect(getByTestId("admin-script-confirm-cancel-button")).toBeTruthy();
111
+ expect(queryByTestId("admin-script-wet-run-button")).toBeNull();
112
+ });
113
+
114
+ it("renders the script description in the confirm phase", () => {
115
+ const {getByText} = renderWithTheme(
116
+ <AdminScriptRunModal
117
+ api={mockApi}
118
+ baseUrl="/admin"
119
+ onDismiss={() => undefined}
120
+ scriptDescription="Migrates legacy records"
121
+ scriptName="migrate-data"
122
+ visible
123
+ />
124
+ );
125
+
126
+ expect(getByText("Migrates legacy records")).toBeTruthy();
127
+ expect(getByText("migrate-data")).toBeTruthy();
128
+ });
129
+ });
@@ -1,5 +1,5 @@
1
1
  import type {Api} from "@reduxjs/toolkit/query/react";
2
- import {Box, Button, Heading, Icon, Modal, Spinner, Text} from "@terreno/ui";
2
+ import {Badge, Box, Button, Heading, Icon, Modal, Spinner, Text} from "@terreno/ui";
3
3
  import React, {useCallback, useEffect, useRef, useState} from "react";
4
4
  import type {BackgroundTask} from "./types";
5
5
  import {useAdminScripts} from "./useAdminScripts";
@@ -8,8 +8,11 @@ interface AdminScriptRunModalProps {
8
8
  baseUrl: string;
9
9
  api: Api<any, any, any, any>;
10
10
  scriptName: string | null;
11
+ scriptDescription?: string;
11
12
  visible: boolean;
12
13
  onDismiss: () => void;
14
+ /** When true, skip the confirmation step and only allow a dry run. */
15
+ dryRunOnly?: boolean;
13
16
  }
14
17
 
15
18
  const POLL_INTERVAL_MS = 2000;
@@ -17,17 +20,22 @@ const POLL_INTERVAL_MS = 2000;
17
20
  const isTerminalStatus = (status?: string): boolean =>
18
21
  status === "completed" || status === "failed" || status === "cancelled";
19
22
 
23
+ type Phase = "confirm" | "running" | "done";
24
+
20
25
  export const AdminScriptRunModal: React.FC<AdminScriptRunModalProps> = ({
21
26
  baseUrl,
22
27
  api,
23
28
  scriptName,
29
+ scriptDescription,
24
30
  visible,
25
31
  onDismiss,
32
+ dryRunOnly = false,
26
33
  }) => {
27
34
  const [taskId, setTaskId] = useState<string | null>(null);
28
- const [phase, setPhase] = useState<"running" | "done">("running");
35
+ const [phase, setPhase] = useState<Phase>("confirm");
36
+ const [isDryRun, setIsDryRun] = useState(false);
29
37
  const [startError, setStartError] = useState<string | null>(null);
30
- const hasStartedRef = useRef(false);
38
+ const startingRef = useRef(false);
31
39
 
32
40
  const {useRunScriptMutation, useGetScriptTaskQuery, useCancelScriptTaskMutation} =
33
41
  useAdminScripts(api, baseUrl);
@@ -43,34 +51,14 @@ export const AdminScriptRunModal: React.FC<AdminScriptRunModalProps> = ({
43
51
 
44
52
  const task: BackgroundTask | undefined = taskData?.task;
45
53
 
46
- // Auto-start wet run when modal opens
47
- useEffect(() => {
48
- if (!visible || !scriptName || hasStartedRef.current) {
49
- return;
50
- }
51
- hasStartedRef.current = true;
52
- setTaskId(null);
53
- setPhase("running");
54
- setStartError(null);
55
-
56
- void (async () => {
57
- try {
58
- const result = await runScript({name: scriptName, wetRun: true}).unwrap();
59
- setTaskId(result.taskId);
60
- } catch (err: unknown) {
61
- const errData = (err as {data?: {title?: string; detail?: string}})?.data;
62
- const message = errData?.detail ?? errData?.title ?? "Failed to start script";
63
- setStartError(message);
64
- setPhase("done");
65
- hasStartedRef.current = false;
66
- }
67
- })();
68
- }, [visible, scriptName, runScript]);
69
-
70
- // Reset when modal closes
54
+ // Reset modal state whenever it becomes hidden
71
55
  useEffect(() => {
72
56
  if (!visible) {
73
- hasStartedRef.current = false;
57
+ setTaskId(null);
58
+ setPhase("confirm");
59
+ setIsDryRun(false);
60
+ setStartError(null);
61
+ startingRef.current = false;
74
62
  }
75
63
  }, [visible]);
76
64
 
@@ -81,7 +69,32 @@ export const AdminScriptRunModal: React.FC<AdminScriptRunModalProps> = ({
81
69
  }
82
70
  }, [task?.status]);
83
71
 
84
- const handleCancel = useCallback(async () => {
72
+ const startRun = useCallback(
73
+ async (wetRun: boolean) => {
74
+ if (!scriptName || startingRef.current) {
75
+ return;
76
+ }
77
+ startingRef.current = true;
78
+ setIsDryRun(!wetRun);
79
+ setTaskId(null);
80
+ setStartError(null);
81
+ setPhase("running");
82
+ try {
83
+ const result = await runScript({name: scriptName, wetRun}).unwrap();
84
+ setTaskId(result.taskId);
85
+ } catch (err: unknown) {
86
+ const errData = (err as {data?: {title?: string; detail?: string}})?.data;
87
+ const message = errData?.detail ?? errData?.title ?? "Failed to start script";
88
+ setStartError(message);
89
+ setPhase("done");
90
+ } finally {
91
+ startingRef.current = false;
92
+ }
93
+ },
94
+ [scriptName, runScript]
95
+ );
96
+
97
+ const handleCancelTask = useCallback(async () => {
85
98
  if (!taskId) {
86
99
  return;
87
100
  }
@@ -92,11 +105,54 @@ export const AdminScriptRunModal: React.FC<AdminScriptRunModalProps> = ({
92
105
  }
93
106
  }, [taskId, cancelTask]);
94
107
 
108
+ const renderConfirm = (): React.ReactElement => (
109
+ <Box gap={4} paddingY={4}>
110
+ <Heading align="center" size="md">
111
+ {scriptName}
112
+ </Heading>
113
+ {scriptDescription && (
114
+ <Text align="center" color="secondaryDark">
115
+ {scriptDescription}
116
+ </Text>
117
+ )}
118
+ <Text align="center" size="sm">
119
+ {dryRunOnly
120
+ ? "Dry runs simulate the script without persisting any changes."
121
+ : "Run a dry run first to preview changes, or run the script for real."}
122
+ </Text>
123
+ <Box direction="row" gap={2} justifyContent="center" wrap>
124
+ <Button
125
+ onClick={() => startRun(false)}
126
+ testID="admin-script-dry-run-button"
127
+ text="Dry Run"
128
+ variant={dryRunOnly ? "primary" : "secondary"}
129
+ />
130
+ {!dryRunOnly && (
131
+ <Button
132
+ confirmationText={`Run "${scriptName}" for real? This will persist changes.`}
133
+ onClick={() => startRun(true)}
134
+ testID="admin-script-wet-run-button"
135
+ text="Run"
136
+ variant="primary"
137
+ withConfirmation
138
+ />
139
+ )}
140
+ <Button
141
+ onClick={onDismiss}
142
+ testID="admin-script-confirm-cancel-button"
143
+ text="Cancel"
144
+ variant="muted"
145
+ />
146
+ </Box>
147
+ </Box>
148
+ );
149
+
95
150
  const renderRunning = (): React.ReactElement => (
96
151
  <Box alignItems="center" gap={4} paddingY={4}>
97
152
  <Heading align="center" size="md">
98
153
  {scriptName}
99
154
  </Heading>
155
+ <Badge status={isDryRun ? "info" : "warning"} value={isDryRun ? "Dry Run" : "Live Run"} />
100
156
  <Spinner size="md" />
101
157
  {task?.progress?.message && <Text align="center">{task.progress.message}</Text>}
102
158
  {task?.progress?.stage && (
@@ -110,9 +166,9 @@ export const AdminScriptRunModal: React.FC<AdminScriptRunModalProps> = ({
110
166
  </Text>
111
167
  )}
112
168
  <Button
113
- disabled={isCancelling}
169
+ disabled={isCancelling || !taskId}
114
170
  loading={isCancelling}
115
- onClick={handleCancel}
171
+ onClick={handleCancelTask}
116
172
  testID="admin-script-cancel-button"
117
173
  text="Cancel"
118
174
  variant="destructive"
@@ -139,6 +195,7 @@ export const AdminScriptRunModal: React.FC<AdminScriptRunModalProps> = ({
139
195
  {scriptName}
140
196
  </Heading>
141
197
  <Box alignItems="center" gap={2}>
198
+ <Badge status={isDryRun ? "info" : "warning"} value={isDryRun ? "Dry Run" : "Live Run"} />
142
199
  <Icon color={iconColor} iconName={iconName} size="md" />
143
200
  <Text align="center" bold>
144
201
  {statusLabel}
@@ -175,11 +232,12 @@ export const AdminScriptRunModal: React.FC<AdminScriptRunModalProps> = ({
175
232
  <Modal
176
233
  onDismiss={onDismiss}
177
234
  persistOnBackgroundClick={!isComplete}
178
- primaryButtonOnClick={onDismiss}
235
+ primaryButtonOnClick={isComplete ? onDismiss : undefined}
179
236
  primaryButtonText={isComplete ? "Close" : undefined}
180
237
  visible={visible}
181
238
  >
182
239
  <Box minHeight={200} padding={2}>
240
+ {phase === "confirm" && renderConfirm()}
183
241
  {phase === "running" && renderRunning()}
184
242
  {phase === "done" && renderDone()}
185
243
  </Box>
package/src/index.tsx CHANGED
@@ -5,7 +5,7 @@ export {AdminModelTable} from "./AdminModelTable";
5
5
  export {AdminNestedArrayField} from "./AdminNestedArrayField";
6
6
  export {AdminObjectPicker} from "./AdminObjectPicker";
7
7
  export {AdminPrimitiveArrayField} from "./AdminPrimitiveArrayField";
8
- export {AdminRefField} from "./AdminRefField";
8
+ export {AdminRefField, type AdminRefFieldProps} from "./AdminRefField";
9
9
  export {AdminScriptList} from "./AdminScriptList";
10
10
  export {AdminScriptRunModal} from "./AdminScriptRunModal";
11
11
  export {AdminVersionConfig} from "./AdminVersionConfig";
@@ -27,6 +27,8 @@ export type {
27
27
  DocumentFile,
28
28
  DocumentListResponse,
29
29
  DocumentStorageBrowserProps,
30
+ RefFieldRendererProps,
31
+ RefRendererMap,
30
32
  } from "./types";
31
33
  export {SYSTEM_FIELDS} from "./types";
32
34
  export {useAdminApi} from "./useAdminApi";
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type {Api} from "@reduxjs/toolkit/query/react";
2
+ import type React from "react";
2
3
 
3
4
  export interface AdminFieldConfig {
4
5
  type: string;
@@ -27,6 +28,8 @@ export interface AdminModelConfig {
27
28
  defaultSort: string;
28
29
  fields: Record<string, AdminFieldConfig>;
29
30
  fieldOrder?: string[];
31
+ /** Optional per-column pixel widths used by AdminModelTable when rendering listFields. */
32
+ listColumnWidths?: Record<string, number>;
30
33
  }
31
34
 
32
35
  export interface AdminCustomScreen {
@@ -78,6 +81,31 @@ export interface AdminScreenProps {
78
81
  api: Api<any, any, any, any>;
79
82
  }
80
83
 
84
+ /**
85
+ * Props passed to a custom ref-field renderer. Matches AdminRefField's interface so a
86
+ * custom renderer is a drop-in replacement.
87
+ */
88
+ export interface RefFieldRendererProps {
89
+ api: Api<any, any, any, any>;
90
+ baseUrl: string;
91
+ routePath: string;
92
+ refModelName: string;
93
+ title: string;
94
+ value: string;
95
+ onChange: (value: string) => void;
96
+ errorText?: string;
97
+ helperText?: string;
98
+ }
99
+
100
+ /**
101
+ * Map from referenced model name (e.g. "User") to a custom component used to render
102
+ * fields that reference that model. When a key matches `fieldConfig.ref` (single ref)
103
+ * or `fieldConfig.itemRef` (primitive array of refs), the custom component renders in
104
+ * place of the built-in {@link AdminRefField}. Falls back to AdminRefField when no
105
+ * key matches.
106
+ */
107
+ export type RefRendererMap = Record<string, React.ComponentType<RefFieldRendererProps>>;
108
+
81
109
  // System fields that should be skipped in forms
82
110
  export const SYSTEM_FIELDS = new Set(["_id", "id", "__v", "created", "updated", "deleted"]);
83
111