@terreno/admin-frontend 0.3.2

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,308 @@
1
+ import type {Api} from "@reduxjs/toolkit/query/react";
2
+ import {
3
+ Box,
4
+ Button,
5
+ type ColumnSortInterface,
6
+ DataTable,
7
+ type DataTableCellData,
8
+ type DataTableColumn,
9
+ type DataTableCustomComponentMap,
10
+ IconButton,
11
+ Link,
12
+ Page,
13
+ Spinner,
14
+ Text,
15
+ } from "@terreno/ui";
16
+ import {router, useNavigation} from "expo-router";
17
+ import startCase from "lodash/startCase";
18
+ import {DateTime} from "luxon";
19
+ import React, {useCallback, useEffect, useMemo, useState} from "react";
20
+ import type {AdminFieldConfig, AdminModelConfig} from "./types";
21
+ import {useAdminApi} from "./useAdminApi";
22
+ import {useAdminConfig} from "./useAdminConfig";
23
+
24
+ interface AdminModelTableProps {
25
+ baseUrl: string;
26
+ api: Api<any, any, any, any>;
27
+ modelName: string;
28
+ columns?: string[];
29
+ }
30
+
31
+ const ACTIONS_COLUMN_TYPE = "adminActions";
32
+ const LINK_COLUMN_TYPE = "adminLink";
33
+ const DEFAULT_LIMIT = 20;
34
+
35
+ const mapFieldTypeToColumnType = (fieldConfig: AdminFieldConfig): string => {
36
+ if (fieldConfig.type === "boolean") {
37
+ return "boolean";
38
+ }
39
+ if (fieldConfig.type === "number") {
40
+ return "number";
41
+ }
42
+ if (fieldConfig.type === "date" || fieldConfig.type === "datetime") {
43
+ return "date";
44
+ }
45
+ return "text";
46
+ };
47
+
48
+ const getColumnWidth = (fieldKey: string, fieldConfig: AdminFieldConfig): number => {
49
+ if (fieldConfig.type === "boolean") {
50
+ return 100;
51
+ }
52
+ if (fieldConfig.type === "number") {
53
+ return 120;
54
+ }
55
+ if (fieldConfig.type === "date" || fieldConfig.type === "datetime") {
56
+ return 180;
57
+ }
58
+ if (fieldKey === "_id") {
59
+ return 240;
60
+ }
61
+ return 200;
62
+ };
63
+
64
+ const formatCellValue = (value: any, fieldConfig: AdminFieldConfig): string => {
65
+ if (value == null) {
66
+ return "";
67
+ }
68
+ if (fieldConfig.type === "boolean") {
69
+ return value ? "\u2713" : "";
70
+ }
71
+ if (fieldConfig.type === "date" || fieldConfig.type === "datetime") {
72
+ const dt = DateTime.fromISO(String(value));
73
+ return dt.isValid ? dt.toLocaleString(DateTime.DATETIME_SHORT) : String(value);
74
+ }
75
+ if (typeof value === "object") {
76
+ return value._id ?? JSON.stringify(value);
77
+ }
78
+ return String(value);
79
+ };
80
+
81
+ const buildSortString = (
82
+ sort: ColumnSortInterface | undefined,
83
+ listFields: string[]
84
+ ): string | undefined => {
85
+ if (!sort) {
86
+ return undefined;
87
+ }
88
+ const fieldKey = listFields[sort.column];
89
+ if (!fieldKey) {
90
+ return undefined;
91
+ }
92
+ return sort.direction === "desc" ? `-${fieldKey}` : fieldKey;
93
+ };
94
+
95
+ const AdminLinkCell: React.FC<{column: DataTableColumn; cellData: DataTableCellData}> = ({
96
+ cellData,
97
+ }) => {
98
+ const {text, href} = cellData.value as {text: string; href: string};
99
+ return <Link onClick={() => router.push(href as any)} text={text} />;
100
+ };
101
+
102
+ export const AdminModelTable: React.FC<AdminModelTableProps> = ({
103
+ baseUrl,
104
+ api,
105
+ modelName,
106
+ columns: columnsProp,
107
+ }) => {
108
+ const {config, isLoading: isConfigLoading} = useAdminConfig(api, baseUrl);
109
+ const [page, setPage] = useState(1);
110
+ const [sortColumn, setSortColumn] = useState<ColumnSortInterface | undefined>();
111
+ const navigation = useNavigation();
112
+
113
+ const modelConfig: AdminModelConfig | undefined = useMemo(
114
+ () => config?.models.find((m: AdminModelConfig) => m.name === modelName),
115
+ [config, modelName]
116
+ );
117
+
118
+ // Set the navigation header title to the model display name
119
+ useEffect(() => {
120
+ if (!modelConfig) {
121
+ return;
122
+ }
123
+ navigation.setOptions({title: modelConfig.displayName});
124
+ }, [navigation, modelConfig]);
125
+
126
+ const displayFields = useMemo(
127
+ () => columnsProp ?? modelConfig?.listFields ?? [],
128
+ [columnsProp, modelConfig]
129
+ );
130
+
131
+ const sortString = useMemo(
132
+ () => buildSortString(sortColumn, displayFields) ?? modelConfig?.defaultSort,
133
+ [sortColumn, displayFields, modelConfig]
134
+ );
135
+
136
+ const {useListQuery, useDeleteMutation} = useAdminApi(
137
+ api,
138
+ modelConfig?.routePath ?? "",
139
+ modelName
140
+ );
141
+ const {data: listData, isLoading: isListLoading} = useListQuery(
142
+ {limit: DEFAULT_LIMIT, page, sort: sortString},
143
+ {skip: !modelConfig}
144
+ );
145
+ const [deleteItem] = useDeleteMutation();
146
+
147
+ const handleCreate = useCallback(() => {
148
+ router.push(`${baseUrl}/${modelName}/create` as any);
149
+ }, [baseUrl, modelName]);
150
+
151
+ const handleDelete = useCallback(
152
+ async (id: string) => {
153
+ try {
154
+ await deleteItem(id).unwrap();
155
+ } catch (err) {
156
+ console.error("Failed to delete:", err);
157
+ }
158
+ },
159
+ [deleteItem]
160
+ );
161
+
162
+ const AdminActionsCell: React.FC<{column: DataTableColumn; cellData: DataTableCellData}> =
163
+ useCallback(
164
+ ({cellData}: {column: DataTableColumn; cellData: DataTableCellData}) => {
165
+ const {id} = cellData.value as {id: string};
166
+ const viewHref = `${baseUrl}/${modelName}/${id}`;
167
+ const editHref = `${baseUrl}/${modelName}/${id}`;
168
+ return (
169
+ <Box alignItems="center" direction="row" gap={1} justifyContent="end">
170
+ <IconButton
171
+ accessibilityLabel="View"
172
+ iconName="eye"
173
+ onClick={() => router.push(viewHref as any)}
174
+ tooltipText="View"
175
+ variant="muted"
176
+ />
177
+ <IconButton
178
+ accessibilityLabel="Edit"
179
+ iconName="pen-to-square"
180
+ onClick={() => router.push(editHref as any)}
181
+ tooltipText="Edit"
182
+ variant="muted"
183
+ />
184
+ <IconButton
185
+ accessibilityLabel="Delete"
186
+ confirmationText="Are you sure you want to delete this item?"
187
+ iconName="trash"
188
+ onClick={() => handleDelete(id)}
189
+ tooltipText="Delete"
190
+ variant="destructive"
191
+ withConfirmation
192
+ />
193
+ </Box>
194
+ );
195
+ },
196
+ [baseUrl, modelName, handleDelete]
197
+ );
198
+
199
+ const customColumnComponentMap: DataTableCustomComponentMap = useMemo(
200
+ () => ({
201
+ [ACTIONS_COLUMN_TYPE]: AdminActionsCell,
202
+ [LINK_COLUMN_TYPE]: AdminLinkCell,
203
+ }),
204
+ [AdminActionsCell]
205
+ );
206
+
207
+ if (isConfigLoading || !modelConfig) {
208
+ return (
209
+ <Page maxWidth="100%">
210
+ <Box alignItems="center" justifyContent="center" padding={6}>
211
+ <Spinner />
212
+ </Box>
213
+ </Page>
214
+ );
215
+ }
216
+
217
+ const dataColumns: DataTableColumn[] = displayFields.map((fieldKey, index) => {
218
+ const fieldConfig = modelConfig.fields[fieldKey];
219
+ const isFirst = index === 0;
220
+ return {
221
+ columnType: isFirst
222
+ ? LINK_COLUMN_TYPE
223
+ : fieldConfig
224
+ ? mapFieldTypeToColumnType(fieldConfig)
225
+ : "text",
226
+ sortable: true,
227
+ title: startCase(fieldKey),
228
+ width: fieldConfig ? getColumnWidth(fieldKey, fieldConfig) : 200,
229
+ };
230
+ });
231
+
232
+ const columns: DataTableColumn[] = [
233
+ ...dataColumns,
234
+ {
235
+ columnType: ACTIONS_COLUMN_TYPE,
236
+ sortable: false,
237
+ title: "",
238
+ width: 140,
239
+ },
240
+ ];
241
+
242
+ const data = (listData?.data ?? []).map((item: any) => {
243
+ const fieldCells = displayFields.map((fieldKey, index) => {
244
+ const fieldConfig = modelConfig.fields[fieldKey];
245
+ const isFirst = index === 0;
246
+
247
+ if (isFirst) {
248
+ const displayText = fieldConfig
249
+ ? formatCellValue(item[fieldKey], fieldConfig)
250
+ : String(item[fieldKey] ?? "");
251
+ return {
252
+ value: {
253
+ href: `${baseUrl}/${modelName}/${item._id}`,
254
+ text: displayText,
255
+ },
256
+ };
257
+ }
258
+
259
+ return {
260
+ value: fieldConfig
261
+ ? formatCellValue(item[fieldKey], fieldConfig)
262
+ : String(item[fieldKey] ?? ""),
263
+ };
264
+ });
265
+
266
+ const actionsCell = {value: {id: item._id}};
267
+ return [...fieldCells, actionsCell];
268
+ });
269
+
270
+ const totalPages = listData ? Math.ceil(listData.total / DEFAULT_LIMIT) : 1;
271
+
272
+ return (
273
+ <Page
274
+ footer={
275
+ <Box direction="row" justifyContent="end" padding={2}>
276
+ <Button
277
+ onClick={handleCreate}
278
+ testID="admin-create-button"
279
+ text="Create"
280
+ variant="primary"
281
+ />
282
+ </Box>
283
+ }
284
+ maxWidth="100%"
285
+ >
286
+ {isListLoading ? (
287
+ <Box alignItems="center" justifyContent="center" padding={6}>
288
+ <Spinner />
289
+ </Box>
290
+ ) : data.length === 0 ? (
291
+ <Box alignItems="center" padding={6}>
292
+ <Text color="secondaryDark">No items found.</Text>
293
+ </Box>
294
+ ) : (
295
+ <DataTable
296
+ columns={columns}
297
+ customColumnComponentMap={customColumnComponentMap}
298
+ data={data}
299
+ page={page}
300
+ setPage={setPage}
301
+ setSortColumn={setSortColumn}
302
+ sortColumn={sortColumn}
303
+ totalPages={totalPages}
304
+ />
305
+ )}
306
+ </Page>
307
+ );
308
+ };
@@ -0,0 +1,79 @@
1
+ import type {Api} from "@reduxjs/toolkit/query/react";
2
+ import {SelectField} from "@terreno/ui";
3
+ import React, {useMemo} from "react";
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
+ }
16
+
17
+ // Heuristic to find a display field from an item
18
+ const getDisplayValue = (item: any): string => {
19
+ for (const field of ["name", "title", "email", "label", "displayName"]) {
20
+ if (item[field]) {
21
+ return String(item[field]);
22
+ }
23
+ }
24
+ return item._id ?? String(item);
25
+ };
26
+
27
+ export const AdminRefField: React.FC<AdminRefFieldProps> = ({
28
+ api,
29
+ routePath,
30
+ refModelName,
31
+ title,
32
+ value,
33
+ onChange,
34
+ errorText,
35
+ helperText,
36
+ }) => {
37
+ const endpointKey = `adminRefList_${refModelName}`;
38
+
39
+ const enhancedApi = useMemo(() => {
40
+ return api.injectEndpoints({
41
+ endpoints: (build: any) => ({
42
+ [endpointKey]: build.query({
43
+ query: () => ({
44
+ method: "GET",
45
+ params: {limit: 100},
46
+ url: routePath,
47
+ }),
48
+ }),
49
+ }),
50
+ overrideExisting: false,
51
+ });
52
+ }, [api, routePath, endpointKey]);
53
+
54
+ const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
55
+ const useRefQuery = (enhancedApi as any)[`use${capitalize(endpointKey)}Query`];
56
+ const {data, isLoading} = useRefQuery();
57
+
58
+ const options = useMemo(() => {
59
+ if (!data?.data) {
60
+ return [];
61
+ }
62
+ return data.data.map((item: any) => ({
63
+ label: getDisplayValue(item),
64
+ value: item._id,
65
+ }));
66
+ }, [data]);
67
+
68
+ return (
69
+ <SelectField
70
+ disabled={isLoading}
71
+ errorText={errorText}
72
+ helperText={helperText}
73
+ onChange={onChange}
74
+ options={options}
75
+ title={title}
76
+ value={value}
77
+ />
78
+ );
79
+ };
package/src/index.tsx ADDED
@@ -0,0 +1,14 @@
1
+ export {AdminFieldRenderer} from "./AdminFieldRenderer";
2
+ export {AdminModelForm} from "./AdminModelForm";
3
+ export {AdminModelList} from "./AdminModelList";
4
+ export {AdminModelTable} from "./AdminModelTable";
5
+ export {AdminRefField} from "./AdminRefField";
6
+ export type {
7
+ AdminConfigResponse,
8
+ AdminFieldConfig,
9
+ AdminModelConfig,
10
+ AdminScreenProps,
11
+ } from "./types";
12
+ export {SYSTEM_FIELDS} from "./types";
13
+ export {useAdminApi} from "./useAdminApi";
14
+ export {useAdminConfig} from "./useAdminConfig";
package/src/types.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type {Api} from "@reduxjs/toolkit/query/react";
2
+
3
+ export interface AdminFieldConfig {
4
+ type: string;
5
+ required: boolean;
6
+ description?: string;
7
+ enum?: string[];
8
+ default?: any;
9
+ ref?: string;
10
+ }
11
+
12
+ export interface AdminModelConfig {
13
+ name: string;
14
+ routePath: string;
15
+ displayName: string;
16
+ listFields: string[];
17
+ defaultSort: string;
18
+ fields: Record<string, AdminFieldConfig>;
19
+ }
20
+
21
+ export interface AdminConfigResponse {
22
+ models: AdminModelConfig[];
23
+ }
24
+
25
+ export interface AdminScreenProps {
26
+ baseUrl: string;
27
+ api: Api<any, any, any, any>;
28
+ }
29
+
30
+ // System fields that should be skipped in forms
31
+ export const SYSTEM_FIELDS = new Set(["_id", "id", "__v", "created", "updated", "deleted"]);
@@ -0,0 +1,77 @@
1
+ import type {Api} from "@reduxjs/toolkit/query/react";
2
+ import {useMemo} from "react";
3
+
4
+ export const useAdminApi = (api: Api<any, any, any, any>, routePath: string, modelName: string) => {
5
+ const enhancedApi = useMemo(() => {
6
+ const listKey = `adminList_${modelName}`;
7
+ const readKey = `adminRead_${modelName}`;
8
+ const createKey = `adminCreate_${modelName}`;
9
+ const updateKey = `adminUpdate_${modelName}`;
10
+ const deleteKey = `adminDelete_${modelName}`;
11
+
12
+ return api.injectEndpoints({
13
+ endpoints: (build: any) => ({
14
+ [listKey]: build.query({
15
+ providesTags: [`admin_${modelName}`],
16
+ query: (params: any) => ({
17
+ method: "GET",
18
+ params: params ?? {},
19
+ url: routePath,
20
+ }),
21
+ }),
22
+ [readKey]: build.query({
23
+ providesTags: (_result: any, _error: any, id: string) => [
24
+ {id, type: `admin_${modelName}`},
25
+ ],
26
+ query: (id: string) => ({
27
+ method: "GET",
28
+ url: `${routePath}/${id}`,
29
+ }),
30
+ }),
31
+ [createKey]: build.mutation({
32
+ invalidatesTags: [`admin_${modelName}`],
33
+ query: (body: any) => ({
34
+ body,
35
+ method: "POST",
36
+ url: routePath,
37
+ }),
38
+ }),
39
+ [updateKey]: build.mutation({
40
+ invalidatesTags: (_result: any, _error: any, {id}: {id: string}) => [
41
+ {id, type: `admin_${modelName}`},
42
+ `admin_${modelName}`,
43
+ ],
44
+ query: ({id, body}: {id: string; body: any}) => ({
45
+ body,
46
+ method: "PATCH",
47
+ url: `${routePath}/${id}`,
48
+ }),
49
+ }),
50
+ [deleteKey]: build.mutation({
51
+ invalidatesTags: [`admin_${modelName}`],
52
+ query: (id: string) => ({
53
+ method: "DELETE",
54
+ url: `${routePath}/${id}`,
55
+ }),
56
+ }),
57
+ }),
58
+ overrideExisting: false,
59
+ });
60
+ }, [api, routePath, modelName]);
61
+
62
+ // Extract the generated hooks dynamically
63
+ const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
64
+ const listKey = `adminList_${modelName}`;
65
+ const readKey = `adminRead_${modelName}`;
66
+ const createKey = `adminCreate_${modelName}`;
67
+ const updateKey = `adminUpdate_${modelName}`;
68
+ const deleteKey = `adminDelete_${modelName}`;
69
+
70
+ return {
71
+ useCreateMutation: (enhancedApi as any)[`use${capitalize(createKey)}Mutation`],
72
+ useDeleteMutation: (enhancedApi as any)[`use${capitalize(deleteKey)}Mutation`],
73
+ useListQuery: (enhancedApi as any)[`use${capitalize(listKey)}Query`],
74
+ useReadQuery: (enhancedApi as any)[`use${capitalize(readKey)}Query`],
75
+ useUpdateMutation: (enhancedApi as any)[`use${capitalize(updateKey)}Mutation`],
76
+ };
77
+ };
@@ -0,0 +1,27 @@
1
+ import type {Api} from "@reduxjs/toolkit/query/react";
2
+ import {useMemo} from "react";
3
+ import type {AdminConfigResponse} from "./types";
4
+
5
+ const ENDPOINT_NAME = "adminConfig";
6
+
7
+ export const useAdminConfig = (api: Api<any, any, any, any>, baseUrl: string) => {
8
+ const enhancedApi = useMemo(() => {
9
+ return api.injectEndpoints({
10
+ endpoints: (build: any) => ({
11
+ [ENDPOINT_NAME]: build.query({
12
+ query: () => ({
13
+ method: "GET",
14
+ url: `${baseUrl}/config`,
15
+ }),
16
+ }),
17
+ }),
18
+ overrideExisting: false,
19
+ });
20
+ }, [api, baseUrl]);
21
+
22
+ const useConfigQuery = (enhancedApi as any).useAdminConfigQuery;
23
+
24
+ const {data, isLoading, error} = useConfigQuery();
25
+
26
+ return {config: data as AdminConfigResponse | null, error, isLoading};
27
+ };