@aventoapp/framework 0.1.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 (160) hide show
  1. package/dist/index.js +6 -0
  2. package/dist/index.js.map +7 -0
  3. package/dist/native/index.js +2522 -0
  4. package/dist/native/index.js.map +7 -0
  5. package/dist/server/index.js +2776 -0
  6. package/dist/server/index.js.map +7 -0
  7. package/dist/server/workflow/index.js +537 -0
  8. package/dist/server/workflow/index.js.map +7 -0
  9. package/dist/shared/index.js +62 -0
  10. package/dist/shared/index.js.map +7 -0
  11. package/dist/web/index.js +7323 -0
  12. package/dist/web/index.js.map +7 -0
  13. package/package.json +81 -0
  14. package/schemas/Workflow.json +14 -0
  15. package/schemas/WorkflowHistory.json +22 -0
  16. package/schemas/WorkflowInstance.json +16 -0
  17. package/schemas/WorkflowState.json +18 -0
  18. package/schemas/WorkflowTransition.json +27 -0
  19. package/src/index.js +8 -0
  20. package/src/native/components/NativeAuthProvider.jsx +249 -0
  21. package/src/native/components/NativeDetail.jsx +270 -0
  22. package/src/native/components/NativeForm.jsx +543 -0
  23. package/src/native/components/NativeGrid.jsx +90 -0
  24. package/src/native/components/NativeJsonGrid.jsx +213 -0
  25. package/src/native/components/NativeJsonView.jsx +454 -0
  26. package/src/native/components/NativeJsonViewContext.js +17 -0
  27. package/src/native/components/NativeShell.jsx +68 -0
  28. package/src/native/components/NativeViewComponent.jsx +351 -0
  29. package/src/native/extensions/NativeExtensionRegistry.js +81 -0
  30. package/src/native/hooks/useNativeStore.js +72 -0
  31. package/src/native/index.js +15 -0
  32. package/src/native/layouts/NativeStackLayout.jsx +30 -0
  33. package/src/native/layouts/NativeTabLayout.jsx +96 -0
  34. package/src/native/storage.js +13 -0
  35. package/src/native/stores/NativeBaseStore.js +348 -0
  36. package/src/native/stores/NativeStoreContext.jsx +53 -0
  37. package/src/server/ai/capabilities-routes.js +106 -0
  38. package/src/server/ai/index.js +1 -0
  39. package/src/server/cache/MemoryCache.js +153 -0
  40. package/src/server/cache/index.js +2 -0
  41. package/src/server/cache/middleware.js +12 -0
  42. package/src/server/db/index.js +14 -0
  43. package/src/server/db/mongo.js +137 -0
  44. package/src/server/db/postgres.js +144 -0
  45. package/src/server/index.js +38 -0
  46. package/src/server/middleware/auth.js +682 -0
  47. package/src/server/middleware/can-flags.js +132 -0
  48. package/src/server/middleware/entityRoles.js +105 -0
  49. package/src/server/middleware/index.js +58 -0
  50. package/src/server/middleware/permissions.js +240 -0
  51. package/src/server/middleware/tenant.js +203 -0
  52. package/src/server/realtime/EventBus.js +45 -0
  53. package/src/server/realtime/WebSocketServer.js +105 -0
  54. package/src/server/realtime/index.js +3 -0
  55. package/src/server/realtime/middleware.js +18 -0
  56. package/src/server/services/email-templates.js +157 -0
  57. package/src/server/services/email.js +78 -0
  58. package/src/server/services/index.js +15 -0
  59. package/src/server/services/storage.js +119 -0
  60. package/src/server/utils/index.js +16 -0
  61. package/src/server/utils/paginate.js +65 -0
  62. package/src/server/utils/query-builder.js +293 -0
  63. package/src/server/utils/route-loader.js +61 -0
  64. package/src/server/workflow/WorkflowEngine.js +494 -0
  65. package/src/server/workflow/index.js +2 -0
  66. package/src/server/workflow/workflow-routes.js +174 -0
  67. package/src/shared/index.js +10 -0
  68. package/src/shared/utils/field-accessor.js +108 -0
  69. package/src/shared/utils/index.js +7 -0
  70. package/src/shared/utils/validation-utils.js +83 -0
  71. package/src/web/components/AppRouter/AppRouter.jsx +130 -0
  72. package/src/web/components/AppRouter/index.js +1 -0
  73. package/src/web/components/AppShell/AppShell.jsx +101 -0
  74. package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -0
  75. package/src/web/components/AppShell/ShellConfig.js +53 -0
  76. package/src/web/components/AppShell/index.js +3 -0
  77. package/src/web/components/AuthProvider.jsx +426 -0
  78. package/src/web/components/CardList/CardList.jsx +272 -0
  79. package/src/web/components/CardList/index.js +2 -0
  80. package/src/web/components/DetailView/DetailView.jsx +281 -0
  81. package/src/web/components/DetailView/index.js +2 -0
  82. package/src/web/components/Form/Form.jsx +300 -0
  83. package/src/web/components/Form/FormField.jsx +226 -0
  84. package/src/web/components/Form/index.js +3 -0
  85. package/src/web/components/Grid/Grid.jsx +304 -0
  86. package/src/web/components/Grid/index.js +2 -0
  87. package/src/web/components/IconRegistry/IconRegistry.jsx +127 -0
  88. package/src/web/components/IconRegistry/index.js +1 -0
  89. package/src/web/components/JsonView/JsonView.jsx +647 -0
  90. package/src/web/components/JsonView/ViewComponent.jsx +1045 -0
  91. package/src/web/components/JsonView/ViewToolbar.jsx +141 -0
  92. package/src/web/components/JsonView/index.js +14 -0
  93. package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -0
  94. package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -0
  95. package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -0
  96. package/src/web/components/JsonView/layouts/index.js +8 -0
  97. package/src/web/components/Layout.jsx +265 -0
  98. package/src/web/components/MobileLayout/MobileLayout.jsx +385 -0
  99. package/src/web/components/MobileLayout/index.js +1 -0
  100. package/src/web/components/Navigation/Navigation.jsx +248 -0
  101. package/src/web/components/Navigation/index.js +1 -0
  102. package/src/web/components/NotificationProvider.jsx +55 -0
  103. package/src/web/components/Pagination/InfiniteScroll.jsx +82 -0
  104. package/src/web/components/Pagination/Pagination.jsx +73 -0
  105. package/src/web/components/Pagination/index.js +8 -0
  106. package/src/web/components/SimpleList/SimpleList.jsx +177 -0
  107. package/src/web/components/SimpleList/index.js +2 -0
  108. package/src/web/components/TenantProvider.jsx +121 -0
  109. package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -0
  110. package/src/web/components/WorkflowActions/index.js +1 -0
  111. package/src/web/components/WorkflowField/WorkflowField.jsx +176 -0
  112. package/src/web/components/WorkflowField/index.js +2 -0
  113. package/src/web/components/WorkflowField/workflowColors.js +32 -0
  114. package/src/web/components/auth/DevTenantSelector.jsx +90 -0
  115. package/src/web/components/auth/ForgotPasswordForm.jsx +94 -0
  116. package/src/web/components/auth/RegisterForm.jsx +168 -0
  117. package/src/web/components/auth/ResetPasswordForm.jsx +121 -0
  118. package/src/web/components/auth/VerifyEmailView.jsx +85 -0
  119. package/src/web/components/auth/index.js +5 -0
  120. package/src/web/components/index.js +39 -0
  121. package/src/web/components/layouts/CardListLayout.jsx +68 -0
  122. package/src/web/components/layouts/FullscreenLayout.jsx +30 -0
  123. package/src/web/components/layouts/MobileStackLayout.jsx +28 -0
  124. package/src/web/components/layouts/WizardLayout.jsx +86 -0
  125. package/src/web/components/layouts/index.js +4 -0
  126. package/src/web/components/mobile/Badge.jsx +105 -0
  127. package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -0
  128. package/src/web/components/mobile/EmptyState.jsx +30 -0
  129. package/src/web/components/mobile/QuickActionButton.jsx +77 -0
  130. package/src/web/components/mobile/ServerAutocomplete.jsx +123 -0
  131. package/src/web/components/mobile/StarRating.jsx +42 -0
  132. package/src/web/components/mobile/StatCard.jsx +65 -0
  133. package/src/web/components/mobile/index.js +7 -0
  134. package/src/web/extensions/ExtensionRegistry.js +79 -0
  135. package/src/web/extensions/index.js +7 -0
  136. package/src/web/hooks/index.js +15 -0
  137. package/src/web/hooks/useApi.js +76 -0
  138. package/src/web/hooks/useAuth.js +37 -0
  139. package/src/web/hooks/useDebouncedSave.js +158 -0
  140. package/src/web/hooks/useIsMobile.js +14 -0
  141. package/src/web/hooks/useOfflineQueue.js +99 -0
  142. package/src/web/hooks/useSelectionModel.js +143 -0
  143. package/src/web/hooks/useServerAutocomplete.js +146 -0
  144. package/src/web/hooks/useStore.js +107 -0
  145. package/src/web/hooks/useSubscription.js +130 -0
  146. package/src/web/hooks/useTenant.js +39 -0
  147. package/src/web/hooks/useTenantResolver.js +65 -0
  148. package/src/web/hooks/useUndoRedo.js +77 -0
  149. package/src/web/hooks/useViews.js +113 -0
  150. package/src/web/hooks/useWorkflow.js +190 -0
  151. package/src/web/index.js +117 -0
  152. package/src/web/stores/BaseStore.js +439 -0
  153. package/src/web/stores/StoreContext.jsx +93 -0
  154. package/src/web/stores/index.js +3 -0
  155. package/src/web/theme/index.js +3 -0
  156. package/src/web/theme/mui-theme.js +228 -0
  157. package/src/web/utils/formatTimeAgo.js +22 -0
  158. package/src/web/utils/index.js +1 -0
  159. package/src/web/views/ViewRegistry.js +235 -0
  160. package/src/web/views/index.js +2 -0
@@ -0,0 +1,2522 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/native/components/NativeAuthProvider.jsx
10
+ import { jsx } from "react/jsx-runtime";
11
+ import React, { createContext, useState, useCallback, useEffect, useMemo, useContext } from "react";
12
+ var _storage = null;
13
+ function getStorage() {
14
+ if (!_storage) {
15
+ try {
16
+ _storage = __require("@react-native-async-storage/async-storage").default;
17
+ } catch {
18
+ _storage = {
19
+ getItem: async () => null,
20
+ setItem: async () => {
21
+ },
22
+ removeItem: async () => {
23
+ }
24
+ };
25
+ }
26
+ }
27
+ return _storage;
28
+ }
29
+ var NativeAuthContext = createContext(null);
30
+ function useNativeAuth() {
31
+ const ctx = useContext(NativeAuthContext);
32
+ if (!ctx)
33
+ throw new Error("useNativeAuth must be used within NativeAuthProvider");
34
+ return ctx;
35
+ }
36
+ var TOKEN_KEY = "avento_token";
37
+ var REFRESH_TOKEN_KEY = "avento_refresh_token";
38
+ var USER_KEY = "avento_user";
39
+ function parseTokenExpiry(token) {
40
+ try {
41
+ const payload = token.split(".")[1];
42
+ const decoded = JSON.parse(atob(payload));
43
+ return decoded.exp ? decoded.exp * 1e3 : null;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+ function friendlyErrorMessage(err) {
49
+ if (err.name === "AbortError") {
50
+ return "Request timed out. Check your connection and try again.";
51
+ }
52
+ if (err instanceof TypeError && /Failed to fetch|Load failed|Network request failed/i.test(err.message)) {
53
+ return "Unable to connect to server. Check your connection and try again.";
54
+ }
55
+ return err.message;
56
+ }
57
+ function NativeAuthProvider({ children, apiUrl, onAuthChange, refreshBeforeMs = 5 * 60 * 1e3 }) {
58
+ const [user, setUser] = useState(null);
59
+ const [token, setToken] = useState(null);
60
+ const [refreshToken, setRefreshToken] = useState(null);
61
+ const [loading, setLoading] = useState(true);
62
+ const [error, setError] = useState(null);
63
+ const [sessionExpired, setSessionExpired] = useState(false);
64
+ useEffect(() => {
65
+ const storage = getStorage();
66
+ let cancelled = false;
67
+ storage.getItem(TOKEN_KEY).then((storedToken) => {
68
+ if (cancelled)
69
+ return;
70
+ if (!storedToken) {
71
+ setLoading(false);
72
+ return;
73
+ }
74
+ return Promise.all([
75
+ Promise.resolve(storedToken),
76
+ storage.getItem(REFRESH_TOKEN_KEY),
77
+ storage.getItem(USER_KEY)
78
+ ]).then(([tk, rt, usr]) => {
79
+ if (cancelled)
80
+ return;
81
+ if (tk && usr) {
82
+ setToken(tk);
83
+ setRefreshToken(rt);
84
+ try {
85
+ setUser(JSON.parse(usr));
86
+ } catch {
87
+ }
88
+ }
89
+ setLoading(false);
90
+ });
91
+ }).catch(() => {
92
+ if (!cancelled)
93
+ setLoading(false);
94
+ });
95
+ return () => {
96
+ cancelled = true;
97
+ };
98
+ }, []);
99
+ useEffect(() => {
100
+ if (onAuthChange && !loading) {
101
+ onAuthChange({ user, isAuthenticated: !!user });
102
+ }
103
+ }, [user, loading, onAuthChange]);
104
+ const login = useCallback(async (email, password, tenantId) => {
105
+ setLoading(true);
106
+ setError(null);
107
+ try {
108
+ const controller = new AbortController();
109
+ const timeoutId = setTimeout(() => controller.abort(), 3e4);
110
+ const response = await fetch(`${apiUrl}/auth/login`, {
111
+ method: "POST",
112
+ headers: { "Content-Type": "application/json" },
113
+ body: JSON.stringify({ email, password, tenant_id: tenantId }),
114
+ signal: controller.signal
115
+ });
116
+ clearTimeout(timeoutId);
117
+ const data = await response.json();
118
+ if (!response.ok)
119
+ throw new Error(data.message || "Login failed");
120
+ setToken(data.token);
121
+ setRefreshToken(data.refreshToken);
122
+ setUser(data.user);
123
+ const storage = getStorage();
124
+ await Promise.all([
125
+ storage.setItem(TOKEN_KEY, data.token),
126
+ data.refreshToken ? storage.setItem(REFRESH_TOKEN_KEY, data.refreshToken) : Promise.resolve(),
127
+ storage.setItem(USER_KEY, JSON.stringify(data.user))
128
+ ]);
129
+ return { success: true, user: data.user, tenant: data.tenant };
130
+ } catch (err) {
131
+ const msg = friendlyErrorMessage(err);
132
+ setError(msg);
133
+ return { success: false, error: msg };
134
+ } finally {
135
+ setLoading(false);
136
+ }
137
+ }, [apiUrl]);
138
+ const loginWithToken = useCallback(async (tokenData) => {
139
+ setToken(tokenData.token);
140
+ setRefreshToken(tokenData.refreshToken);
141
+ setUser(tokenData.user);
142
+ const storage = getStorage();
143
+ await Promise.all([
144
+ storage.setItem(TOKEN_KEY, tokenData.token),
145
+ tokenData.refreshToken ? storage.setItem(REFRESH_TOKEN_KEY, tokenData.refreshToken) : Promise.resolve(),
146
+ storage.setItem(USER_KEY, JSON.stringify(tokenData.user))
147
+ ]);
148
+ return { success: true };
149
+ }, []);
150
+ const logout = useCallback(async () => {
151
+ setToken(null);
152
+ setRefreshToken(null);
153
+ setUser(null);
154
+ setError(null);
155
+ setSessionExpired(false);
156
+ const storage = getStorage();
157
+ await Promise.all([
158
+ storage.removeItem(TOKEN_KEY),
159
+ storage.removeItem(REFRESH_TOKEN_KEY),
160
+ storage.removeItem(USER_KEY)
161
+ ]);
162
+ }, []);
163
+ const refresh = useCallback(async () => {
164
+ if (!refreshToken)
165
+ return { success: false, error: "No refresh token" };
166
+ try {
167
+ const response = await fetch(`${apiUrl}/auth/refresh`, {
168
+ method: "POST",
169
+ headers: { "Content-Type": "application/json" },
170
+ body: JSON.stringify({ refreshToken })
171
+ });
172
+ const data = await response.json();
173
+ if (!response.ok)
174
+ throw new Error(data.message || "Token refresh failed");
175
+ setToken(data.token);
176
+ setSessionExpired(false);
177
+ await getStorage().setItem(TOKEN_KEY, data.token);
178
+ return { success: true };
179
+ } catch (err) {
180
+ setSessionExpired(true);
181
+ const msg = friendlyErrorMessage(err);
182
+ return { success: false, error: msg };
183
+ }
184
+ }, [apiUrl, refreshToken]);
185
+ useEffect(() => {
186
+ if (!token)
187
+ return;
188
+ const expiresAt = parseTokenExpiry(token);
189
+ if (!expiresAt)
190
+ return;
191
+ const msUntilRefresh = expiresAt - Date.now() - refreshBeforeMs;
192
+ if (msUntilRefresh <= 0) {
193
+ refresh();
194
+ return;
195
+ }
196
+ const timerId = setTimeout(() => refresh(), msUntilRefresh);
197
+ return () => clearTimeout(timerId);
198
+ }, [token, refreshBeforeMs, refresh]);
199
+ const hasRole = useCallback((role) => user?.roles?.includes(role) || false, [user]);
200
+ const hasAnyRole = useCallback((roles) => {
201
+ if (!user?.roles)
202
+ return false;
203
+ return roles.some((r) => user.roles.includes(r));
204
+ }, [user]);
205
+ const getAuthHeader = useCallback(() => {
206
+ return token ? { Authorization: `Bearer ${token}` } : {};
207
+ }, [token]);
208
+ const value = useMemo(() => ({
209
+ user,
210
+ token,
211
+ isAuthenticated: !!user,
212
+ loading,
213
+ error,
214
+ sessionExpired,
215
+ login,
216
+ loginWithToken,
217
+ logout,
218
+ refresh,
219
+ hasRole,
220
+ hasAnyRole,
221
+ getAuthHeader
222
+ }), [user, token, loading, error, sessionExpired, login, loginWithToken, logout, refresh, hasRole, hasAnyRole, getAuthHeader]);
223
+ return /* @__PURE__ */ jsx(NativeAuthContext.Provider, { value, children });
224
+ }
225
+
226
+ // src/native/components/NativeShell.jsx
227
+ import { jsx as jsx2 } from "react/jsx-runtime";
228
+ import React2 from "react";
229
+ import { NavigationContainer } from "@react-navigation/native";
230
+ import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
231
+ import Ionicons from "@expo/vector-icons/Ionicons";
232
+ var Tab = createBottomTabNavigator();
233
+ var ICON_MAP = {
234
+ home: "home",
235
+ settings: "settings",
236
+ list: "list",
237
+ person: "person",
238
+ golf: "golf",
239
+ map: "map",
240
+ stats: "stats-chart",
241
+ add: "add-circle",
242
+ search: "search",
243
+ trophy: "trophy",
244
+ calendar: "calendar",
245
+ flag: "flag",
246
+ disc: "disc",
247
+ "ellipsis-horizontal": "ellipsis-horizontal",
248
+ "bar-chart": "bar-chart",
249
+ play: "play",
250
+ navigate: "navigate"
251
+ };
252
+ function resolveIcon(name) {
253
+ return ICON_MAP[name] || name;
254
+ }
255
+ var linking = { enabled: false };
256
+ function NativeShell({ title = "App", tabs = [], loginScreen: LoginScreen }) {
257
+ const { isAuthenticated, loading } = useNativeAuth();
258
+ if (loading)
259
+ return null;
260
+ if (!isAuthenticated && LoginScreen) {
261
+ return /* @__PURE__ */ jsx2(LoginScreen, {});
262
+ }
263
+ return /* @__PURE__ */ jsx2(NavigationContainer, { linking, children: /* @__PURE__ */ jsx2(
264
+ Tab.Navigator,
265
+ {
266
+ screenOptions: ({ route }) => ({
267
+ headerTitle: title,
268
+ tabBarIcon: ({ focused, color, size }) => {
269
+ const tab = tabs.find((t) => t.id === route.name);
270
+ const iconName = resolveIcon(tab?.icon || "home");
271
+ return /* @__PURE__ */ jsx2(Ionicons, { name: focused ? iconName : `${iconName}-outline`, size, color });
272
+ }
273
+ }),
274
+ children: tabs.map((tab) => /* @__PURE__ */ jsx2(
275
+ Tab.Screen,
276
+ {
277
+ name: tab.id,
278
+ component: tab.screen,
279
+ options: { tabBarLabel: tab.label }
280
+ },
281
+ tab.id
282
+ ))
283
+ }
284
+ ) });
285
+ }
286
+
287
+ // src/native/components/NativeGrid.jsx
288
+ import { jsx as jsx3, jsxs } from "react/jsx-runtime";
289
+ import React3, { useState as useState2, useCallback as useCallback2 } from "react";
290
+ import { FlatList, View, Text, StyleSheet, RefreshControl, TouchableOpacity } from "react-native";
291
+ var styles = StyleSheet.create({
292
+ container: { flex: 1, backgroundColor: "#fff" },
293
+ card: {
294
+ padding: 16,
295
+ marginHorizontal: 12,
296
+ marginVertical: 6,
297
+ backgroundColor: "#fff",
298
+ borderRadius: 8,
299
+ shadowColor: "#000",
300
+ shadowOffset: { width: 0, height: 1 },
301
+ shadowOpacity: 0.1,
302
+ shadowRadius: 2,
303
+ elevation: 2
304
+ },
305
+ primary: { fontSize: 16, fontWeight: "600", color: "#1a1a1a" },
306
+ secondary: { fontSize: 14, color: "#666", marginTop: 2 },
307
+ empty: { flex: 1, justifyContent: "center", alignItems: "center", padding: 40 },
308
+ emptyText: { fontSize: 16, color: "#999" }
309
+ });
310
+ function DefaultRowCard({ item, config, onPress }) {
311
+ const primaryField = config.columns?.[0]?.field;
312
+ const secondaryFields = config.columns?.slice(1, 3) || [];
313
+ return /* @__PURE__ */ jsxs(TouchableOpacity, { style: styles.card, onPress: () => onPress?.(item), activeOpacity: 0.7, children: [
314
+ /* @__PURE__ */ jsx3(Text, { style: styles.primary, children: primaryField ? item[primaryField] : JSON.stringify(item) }),
315
+ secondaryFields.map((col) => /* @__PURE__ */ jsxs(Text, { style: styles.secondary, children: [
316
+ col.header ? `${col.header}: ` : "",
317
+ item[col.field]
318
+ ] }, col.field))
319
+ ] });
320
+ }
321
+ function NativeGrid({
322
+ config = {},
323
+ data = [],
324
+ loading = false,
325
+ onRefresh,
326
+ onEndReached,
327
+ onRowPress,
328
+ renderItem: renderItemProp,
329
+ keyExtractor
330
+ }) {
331
+ const [refreshing, setRefreshing] = useState2(false);
332
+ const handleRefresh = useCallback2(async () => {
333
+ if (!onRefresh)
334
+ return;
335
+ setRefreshing(true);
336
+ try {
337
+ await onRefresh();
338
+ } finally {
339
+ setRefreshing(false);
340
+ }
341
+ }, [onRefresh]);
342
+ const defaultKeyExtractor = useCallback2((item) => {
343
+ return item.id?.toString() || item._id?.toString() || JSON.stringify(item);
344
+ }, []);
345
+ const renderItem = useCallback2(({ item }) => {
346
+ if (renderItemProp)
347
+ return renderItemProp({ item, config });
348
+ return /* @__PURE__ */ jsx3(DefaultRowCard, { item, config, onPress: onRowPress });
349
+ }, [config, onRowPress, renderItemProp]);
350
+ if (!loading && data.length === 0) {
351
+ return /* @__PURE__ */ jsx3(View, { style: styles.empty, children: /* @__PURE__ */ jsx3(Text, { style: styles.emptyText, children: config.emptyMessage || "No items found" }) });
352
+ }
353
+ return /* @__PURE__ */ jsx3(
354
+ FlatList,
355
+ {
356
+ style: styles.container,
357
+ data,
358
+ renderItem,
359
+ keyExtractor: keyExtractor || defaultKeyExtractor,
360
+ refreshControl: onRefresh ? /* @__PURE__ */ jsx3(RefreshControl, { refreshing, onRefresh: handleRefresh }) : void 0,
361
+ onEndReached,
362
+ onEndReachedThreshold: 0.5
363
+ }
364
+ );
365
+ }
366
+
367
+ // src/native/components/NativeJsonView.jsx
368
+ import { jsx as jsx11 } from "react/jsx-runtime";
369
+
370
+ // src/native/stores/NativeStoreContext.jsx
371
+ import { jsx as jsx4 } from "react/jsx-runtime";
372
+ import React4, { createContext as createContext2, useContext as useContext2, useMemo as useMemo2, useRef } from "react";
373
+ var NativeStoreContext = createContext2(null);
374
+ function NativeStoreProvider({ stores = {}, children }) {
375
+ const { getAuthHeader } = useNativeAuth();
376
+ const storesRef = useRef(stores);
377
+ const getAuthHeaderRef = useRef(getAuthHeader);
378
+ getAuthHeaderRef.current = getAuthHeader;
379
+ const initializedRef = useRef(false);
380
+ if (!initializedRef.current) {
381
+ Object.values(storesRef.current).forEach((store) => {
382
+ if (store && typeof store._initialize === "function") {
383
+ store._initialize(
384
+ () => getAuthHeaderRef.current()
385
+ );
386
+ }
387
+ });
388
+ initializedRef.current = true;
389
+ }
390
+ const contextValue = useMemo2(() => ({
391
+ stores: storesRef.current,
392
+ getStore: (name) => storesRef.current[name] || null
393
+ }), []);
394
+ return /* @__PURE__ */ jsx4(NativeStoreContext.Provider, { value: contextValue, children });
395
+ }
396
+ var NativeStoreContext_default = NativeStoreProvider;
397
+
398
+ // src/native/hooks/useNativeStore.js
399
+ import { useContext as useContext3, useEffect as useEffect2, useState as useState3, useCallback as useCallback3 } from "react";
400
+ function useNativeStore(storeOrName) {
401
+ const context = useContext3(NativeStoreContext);
402
+ const store = typeof storeOrName === "string" ? context?.getStore(storeOrName) : storeOrName;
403
+ if (!store) {
404
+ throw new Error(
405
+ typeof storeOrName === "string" ? `Store "${storeOrName}" not found. Make sure it's registered with NativeStoreProvider.` : "useNativeStore requires a valid store name or store instance"
406
+ );
407
+ }
408
+ const [state, setState] = useState3(() => store.getState());
409
+ useEffect2(() => {
410
+ setState(store.getState());
411
+ const unsubscribe = store.subscribe((newState) => {
412
+ setState(newState);
413
+ });
414
+ return unsubscribe;
415
+ }, [store]);
416
+ const list = useCallback3((options) => store.list(options), [store]);
417
+ const get = useCallback3((id) => store.get(id), [store]);
418
+ const create = useCallback3((data) => store.create(data), [store]);
419
+ const update = useCallback3((id, data) => store.update(id, data), [store]);
420
+ const remove = useCallback3((id) => store.delete(id), [store]);
421
+ const select = useCallback3((item) => store.select(item), [store]);
422
+ const clearSelection = useCallback3(() => store.clearSelection(), [store]);
423
+ const clearError = useCallback3(() => store.clearError(), [store]);
424
+ const reset = useCallback3(() => store.reset(), [store]);
425
+ const loadMore = useCallback3(() => store.loadMore(), [store]);
426
+ const setPageSize = useCallback3((size) => store.setPageSize(size), [store]);
427
+ return {
428
+ items: state.items,
429
+ selectedItem: state.selectedItem,
430
+ loading: state.loading,
431
+ error: state.error,
432
+ pagination: state.pagination,
433
+ list,
434
+ get,
435
+ create,
436
+ update,
437
+ delete: remove,
438
+ select,
439
+ clearSelection,
440
+ clearError,
441
+ reset,
442
+ loadMore,
443
+ setPageSize,
444
+ store
445
+ };
446
+ }
447
+ var useNativeStore_default = useNativeStore;
448
+
449
+ // src/native/layouts/NativeStackLayout.jsx
450
+ import { jsx as jsx9 } from "react/jsx-runtime";
451
+
452
+ // src/native/components/NativeViewComponent.jsx
453
+ import { jsx as jsx8, jsxs as jsxs5 } from "react/jsx-runtime";
454
+
455
+ // src/native/components/NativeJsonViewContext.js
456
+ import { createContext as createContext3, useContext as useContext4 } from "react";
457
+ var NativeJsonViewContext = createContext3(null);
458
+ function useNativeJsonView() {
459
+ const context = useContext4(NativeJsonViewContext);
460
+ if (!context) {
461
+ throw new Error("useNativeJsonView must be used within a NativeJsonView");
462
+ }
463
+ return context;
464
+ }
465
+
466
+ // src/native/components/NativeJsonGrid.jsx
467
+ import { jsx as jsx5, jsxs as jsxs2 } from "react/jsx-runtime";
468
+ import React5, { useState as useState4, useCallback as useCallback4 } from "react";
469
+ import {
470
+ FlatList as FlatList2,
471
+ View as View2,
472
+ Text as Text2,
473
+ StyleSheet as StyleSheet2,
474
+ RefreshControl as RefreshControl2,
475
+ TouchableOpacity as TouchableOpacity2,
476
+ ActivityIndicator,
477
+ ActionSheetIOS,
478
+ Platform,
479
+ Alert
480
+ } from "react-native";
481
+ import Ionicons2 from "@expo/vector-icons/Ionicons";
482
+ function showActionSheet(options, onSelect) {
483
+ if (Platform.OS === "ios") {
484
+ ActionSheetIOS.showActionSheetWithOptions(
485
+ {
486
+ options: [...options.map((o) => o.label), "Cancel"],
487
+ destructiveButtonIndex: options.findIndex((o) => o.destructive),
488
+ cancelButtonIndex: options.length
489
+ },
490
+ (buttonIndex) => {
491
+ if (buttonIndex < options.length) {
492
+ options[buttonIndex].onPress();
493
+ }
494
+ }
495
+ );
496
+ } else {
497
+ Alert.alert(
498
+ "Actions",
499
+ void 0,
500
+ [
501
+ ...options.map((o) => ({
502
+ text: o.label,
503
+ style: o.destructive ? "destructive" : "default",
504
+ onPress: o.onPress
505
+ })),
506
+ { text: "Cancel", style: "cancel" }
507
+ ]
508
+ );
509
+ }
510
+ }
511
+ function RowCard({ item, config, selected, onPress, onLongPress }) {
512
+ const primaryField = config?.columns?.[0]?.field;
513
+ const secondaryFields = config?.columns?.slice(1, 3) || [];
514
+ return /* @__PURE__ */ jsx5(
515
+ TouchableOpacity2,
516
+ {
517
+ style: [styles2.card, selected && styles2.cardSelected],
518
+ onPress: () => onPress?.(item),
519
+ onLongPress: () => onLongPress?.(item),
520
+ activeOpacity: 0.7,
521
+ children: /* @__PURE__ */ jsxs2(View2, { style: styles2.cardContent, children: [
522
+ /* @__PURE__ */ jsxs2(View2, { style: styles2.cardText, children: [
523
+ /* @__PURE__ */ jsx5(Text2, { style: styles2.primary, numberOfLines: 1, children: primaryField ? item[primaryField] : item.name || item.title || JSON.stringify(item) }),
524
+ secondaryFields.map((col) => /* @__PURE__ */ jsxs2(Text2, { style: styles2.secondary, numberOfLines: 1, children: [
525
+ col.header ? `${col.header}: ` : "",
526
+ item[col.field] != null ? String(item[col.field]) : ""
527
+ ] }, col.field))
528
+ ] }),
529
+ /* @__PURE__ */ jsx5(Ionicons2, { name: "chevron-forward", size: 18, color: "#999" })
530
+ ] })
531
+ }
532
+ );
533
+ }
534
+ function NativeJsonGrid({
535
+ config = {},
536
+ data = [],
537
+ loading = false,
538
+ selectedId,
539
+ hasMore = false,
540
+ onRowPress,
541
+ onRefresh,
542
+ onEndReached,
543
+ onEdit,
544
+ onDelete
545
+ }) {
546
+ const [refreshing, setRefreshing] = useState4(false);
547
+ const handleRefresh = useCallback4(async () => {
548
+ if (!onRefresh)
549
+ return;
550
+ setRefreshing(true);
551
+ try {
552
+ await onRefresh();
553
+ } finally {
554
+ setRefreshing(false);
555
+ }
556
+ }, [onRefresh]);
557
+ const handleLongPress = useCallback4((item) => {
558
+ const options = [];
559
+ if (onEdit) {
560
+ options.push({ label: "Edit", onPress: () => onEdit(item) });
561
+ }
562
+ if (onDelete) {
563
+ options.push({ label: "Delete", destructive: true, onPress: () => onDelete(item) });
564
+ }
565
+ if (options.length > 0) {
566
+ showActionSheet(options, () => {
567
+ });
568
+ }
569
+ }, [onEdit, onDelete]);
570
+ const keyExtractor = useCallback4((item) => {
571
+ return item.id?.toString() || item._id?.toString() || JSON.stringify(item);
572
+ }, []);
573
+ const renderItem = useCallback4(({ item }) => {
574
+ return /* @__PURE__ */ jsx5(
575
+ RowCard,
576
+ {
577
+ item,
578
+ config,
579
+ selected: item.id === selectedId,
580
+ onPress: onRowPress,
581
+ onLongPress: handleLongPress
582
+ }
583
+ );
584
+ }, [config, selectedId, onRowPress, handleLongPress]);
585
+ const renderFooter = useCallback4(() => {
586
+ if (!loading || refreshing)
587
+ return null;
588
+ return /* @__PURE__ */ jsx5(View2, { style: styles2.footer, children: /* @__PURE__ */ jsx5(ActivityIndicator, { size: "small", color: "#1b5e20" }) });
589
+ }, [loading, refreshing]);
590
+ if (!loading && data.length === 0) {
591
+ return /* @__PURE__ */ jsxs2(View2, { style: styles2.empty, children: [
592
+ /* @__PURE__ */ jsx5(Ionicons2, { name: "file-tray-outline", size: 48, color: "#ccc" }),
593
+ /* @__PURE__ */ jsx5(Text2, { style: styles2.emptyText, children: config.emptyMessage || "No items found" })
594
+ ] });
595
+ }
596
+ return /* @__PURE__ */ jsx5(
597
+ FlatList2,
598
+ {
599
+ style: styles2.container,
600
+ data,
601
+ renderItem,
602
+ keyExtractor,
603
+ refreshControl: onRefresh ? /* @__PURE__ */ jsx5(RefreshControl2, { refreshing, onRefresh: handleRefresh, tintColor: "#1b5e20" }) : void 0,
604
+ onEndReached: hasMore ? onEndReached : void 0,
605
+ onEndReachedThreshold: 0.5,
606
+ ListFooterComponent: renderFooter
607
+ }
608
+ );
609
+ }
610
+ var styles2 = StyleSheet2.create({
611
+ container: {
612
+ flex: 1,
613
+ backgroundColor: "#f5f5f5"
614
+ },
615
+ card: {
616
+ padding: 16,
617
+ marginHorizontal: 12,
618
+ marginVertical: 6,
619
+ backgroundColor: "#fff",
620
+ borderRadius: 8,
621
+ shadowColor: "#000",
622
+ shadowOffset: { width: 0, height: 1 },
623
+ shadowOpacity: 0.1,
624
+ shadowRadius: 2,
625
+ elevation: 2
626
+ },
627
+ cardSelected: {
628
+ borderLeftWidth: 4,
629
+ borderLeftColor: "#1b5e20"
630
+ },
631
+ cardContent: {
632
+ flexDirection: "row",
633
+ alignItems: "center"
634
+ },
635
+ cardText: {
636
+ flex: 1
637
+ },
638
+ primary: {
639
+ fontSize: 16,
640
+ fontWeight: "600",
641
+ color: "#1a1a1a"
642
+ },
643
+ secondary: {
644
+ fontSize: 14,
645
+ color: "#666",
646
+ marginTop: 2
647
+ },
648
+ empty: {
649
+ flex: 1,
650
+ justifyContent: "center",
651
+ alignItems: "center",
652
+ padding: 40
653
+ },
654
+ emptyText: {
655
+ fontSize: 16,
656
+ color: "#999",
657
+ marginTop: 12
658
+ },
659
+ footer: {
660
+ paddingVertical: 16,
661
+ alignItems: "center"
662
+ }
663
+ });
664
+ var NativeJsonGrid_default = NativeJsonGrid;
665
+
666
+ // src/native/components/NativeForm.jsx
667
+ import { jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
668
+ import React6, { useState as useState5, useCallback as useCallback5, useEffect as useEffect3, useMemo as useMemo3 } from "react";
669
+ import {
670
+ Modal,
671
+ View as View3,
672
+ Text as Text3,
673
+ StyleSheet as StyleSheet3,
674
+ ScrollView,
675
+ TextInput,
676
+ TouchableOpacity as TouchableOpacity3,
677
+ Switch,
678
+ SafeAreaView,
679
+ FlatList as FlatList3,
680
+ KeyboardAvoidingView,
681
+ Platform as Platform2,
682
+ ActivityIndicator as ActivityIndicator2
683
+ } from "react-native";
684
+ import Ionicons3 from "@expo/vector-icons/Ionicons";
685
+ function getDefaultValues(fields) {
686
+ const defaults = {};
687
+ fields.forEach((field) => {
688
+ if (field.defaultValue !== void 0) {
689
+ defaults[field.field] = field.defaultValue;
690
+ } else {
691
+ switch (field.type) {
692
+ case "boolean":
693
+ defaults[field.field] = false;
694
+ break;
695
+ case "number":
696
+ case "decimal":
697
+ defaults[field.field] = field.defaultValue ?? null;
698
+ break;
699
+ default:
700
+ defaults[field.field] = "";
701
+ }
702
+ }
703
+ });
704
+ return defaults;
705
+ }
706
+ function validateField(value, field) {
707
+ const errors = [];
708
+ if (field.required && (value == null || value === "")) {
709
+ errors.push(`${field.label || field.field} is required`);
710
+ return errors;
711
+ }
712
+ if (value == null || value === "")
713
+ return errors;
714
+ const strValue = String(value);
715
+ if (field.minLength && strValue.length < field.minLength) {
716
+ errors.push(`Minimum ${field.minLength} characters`);
717
+ }
718
+ if (field.maxLength && strValue.length > field.maxLength) {
719
+ errors.push(`Maximum ${field.maxLength} characters`);
720
+ }
721
+ if ((field.type === "number" || field.type === "decimal") && field.min != null) {
722
+ if (Number(value) < field.min) {
723
+ errors.push(`Minimum value is ${field.min}`);
724
+ }
725
+ }
726
+ if ((field.type === "number" || field.type === "decimal") && field.max != null) {
727
+ if (Number(value) > field.max) {
728
+ errors.push(`Maximum value is ${field.max}`);
729
+ }
730
+ }
731
+ if (field.pattern) {
732
+ const regex = new RegExp(field.pattern);
733
+ if (!regex.test(strValue)) {
734
+ errors.push(field.patternMessage || "Invalid format");
735
+ }
736
+ }
737
+ return errors;
738
+ }
739
+ function validateForm(values, fields) {
740
+ const errors = {};
741
+ let hasErrors = false;
742
+ fields.forEach((field) => {
743
+ if (field.readOnly)
744
+ return;
745
+ const fieldErrors = validateField(values[field.field], field);
746
+ if (fieldErrors.length > 0) {
747
+ errors[field.field] = fieldErrors;
748
+ hasErrors = true;
749
+ }
750
+ });
751
+ return { errors, hasErrors };
752
+ }
753
+ function EnumPicker({ visible, options, value, onSelect, onClose, label }) {
754
+ return /* @__PURE__ */ jsx6(Modal, { visible, animationType: "slide", presentationStyle: "pageSheet", onRequestClose: onClose, children: /* @__PURE__ */ jsxs3(SafeAreaView, { style: pickerStyles.container, children: [
755
+ /* @__PURE__ */ jsxs3(View3, { style: pickerStyles.header, children: [
756
+ /* @__PURE__ */ jsx6(TouchableOpacity3, { onPress: onClose, activeOpacity: 0.7, children: /* @__PURE__ */ jsx6(Text3, { style: pickerStyles.cancelText, children: "Cancel" }) }),
757
+ /* @__PURE__ */ jsx6(Text3, { style: pickerStyles.title, children: label || "Select" }),
758
+ /* @__PURE__ */ jsx6(View3, { style: { width: 60 } })
759
+ ] }),
760
+ /* @__PURE__ */ jsx6(
761
+ FlatList3,
762
+ {
763
+ data: options || [],
764
+ keyExtractor: (item) => String(item.value),
765
+ renderItem: ({ item }) => /* @__PURE__ */ jsxs3(
766
+ TouchableOpacity3,
767
+ {
768
+ style: pickerStyles.option,
769
+ onPress: () => {
770
+ onSelect(item.value);
771
+ onClose();
772
+ },
773
+ activeOpacity: 0.7,
774
+ children: [
775
+ /* @__PURE__ */ jsx6(Text3, { style: pickerStyles.optionText, children: item.label }),
776
+ item.value === value && /* @__PURE__ */ jsx6(Ionicons3, { name: "checkmark", size: 22, color: "#1b5e20" })
777
+ ]
778
+ }
779
+ )
780
+ }
781
+ )
782
+ ] }) });
783
+ }
784
+ var pickerStyles = StyleSheet3.create({
785
+ container: { flex: 1, backgroundColor: "#f5f5f5" },
786
+ header: {
787
+ flexDirection: "row",
788
+ alignItems: "center",
789
+ justifyContent: "space-between",
790
+ paddingHorizontal: 16,
791
+ paddingVertical: 12,
792
+ backgroundColor: "#fff",
793
+ borderBottomWidth: StyleSheet3.hairlineWidth,
794
+ borderBottomColor: "#e0e0e0"
795
+ },
796
+ cancelText: { fontSize: 16, color: "#1b5e20" },
797
+ title: { fontSize: 18, fontWeight: "600", color: "#1a1a1a" },
798
+ option: {
799
+ flexDirection: "row",
800
+ alignItems: "center",
801
+ justifyContent: "space-between",
802
+ padding: 16,
803
+ backgroundColor: "#fff",
804
+ borderBottomWidth: StyleSheet3.hairlineWidth,
805
+ borderBottomColor: "#e0e0e0"
806
+ },
807
+ optionText: { fontSize: 16, color: "#1a1a1a" }
808
+ });
809
+ function FormField({ field, value, errors, onChange, onOpenPicker }) {
810
+ const hasError = errors && errors.length > 0;
811
+ switch (field.type) {
812
+ case "boolean":
813
+ return /* @__PURE__ */ jsxs3(View3, { style: styles3.fieldContainer, children: [
814
+ /* @__PURE__ */ jsxs3(View3, { style: styles3.switchRow, children: [
815
+ /* @__PURE__ */ jsx6(Text3, { style: styles3.fieldLabel, children: field.label || field.field }),
816
+ /* @__PURE__ */ jsx6(
817
+ Switch,
818
+ {
819
+ value: !!value,
820
+ onValueChange: onChange,
821
+ trackColor: { false: "#ddd", true: "#81c784" },
822
+ thumbColor: value ? "#1b5e20" : "#f4f3f4",
823
+ disabled: field.readOnly
824
+ }
825
+ )
826
+ ] }),
827
+ hasError && errors.map((e, i) => /* @__PURE__ */ jsx6(Text3, { style: styles3.errorText, children: e }, i))
828
+ ] });
829
+ case "enum":
830
+ const selectedOption = field.options?.find((o) => o.value === value);
831
+ return /* @__PURE__ */ jsxs3(View3, { style: styles3.fieldContainer, children: [
832
+ /* @__PURE__ */ jsxs3(Text3, { style: styles3.fieldLabel, children: [
833
+ field.label || field.field,
834
+ field.required ? " *" : ""
835
+ ] }),
836
+ /* @__PURE__ */ jsxs3(
837
+ TouchableOpacity3,
838
+ {
839
+ style: [styles3.input, styles3.enumInput, hasError && styles3.inputError],
840
+ onPress: () => onOpenPicker(field),
841
+ activeOpacity: 0.7,
842
+ disabled: field.readOnly,
843
+ children: [
844
+ /* @__PURE__ */ jsx6(Text3, { style: [styles3.enumText, !selectedOption && styles3.placeholderText], children: selectedOption?.label || field.placeholder || "Select..." }),
845
+ /* @__PURE__ */ jsx6(Ionicons3, { name: "chevron-down", size: 18, color: "#666" })
846
+ ]
847
+ }
848
+ ),
849
+ hasError && errors.map((e, i) => /* @__PURE__ */ jsx6(Text3, { style: styles3.errorText, children: e }, i))
850
+ ] });
851
+ case "number":
852
+ case "decimal":
853
+ return /* @__PURE__ */ jsxs3(View3, { style: styles3.fieldContainer, children: [
854
+ /* @__PURE__ */ jsxs3(Text3, { style: styles3.fieldLabel, children: [
855
+ field.label || field.field,
856
+ field.required ? " *" : ""
857
+ ] }),
858
+ /* @__PURE__ */ jsx6(
859
+ TextInput,
860
+ {
861
+ style: [styles3.input, hasError && styles3.inputError],
862
+ value: value != null ? String(value) : "",
863
+ onChangeText: (text) => {
864
+ if (text === "" || text === "-") {
865
+ onChange(text);
866
+ } else {
867
+ const num = field.type === "decimal" ? parseFloat(text) : parseInt(text, 10);
868
+ onChange(isNaN(num) ? text : num);
869
+ }
870
+ },
871
+ keyboardType: "numeric",
872
+ placeholder: field.placeholder,
873
+ placeholderTextColor: "#aaa",
874
+ editable: !field.readOnly
875
+ }
876
+ ),
877
+ hasError && errors.map((e, i) => /* @__PURE__ */ jsx6(Text3, { style: styles3.errorText, children: e }, i))
878
+ ] });
879
+ case "date":
880
+ case "datetime":
881
+ return /* @__PURE__ */ jsxs3(View3, { style: styles3.fieldContainer, children: [
882
+ /* @__PURE__ */ jsxs3(Text3, { style: styles3.fieldLabel, children: [
883
+ field.label || field.field,
884
+ field.required ? " *" : ""
885
+ ] }),
886
+ /* @__PURE__ */ jsx6(
887
+ TextInput,
888
+ {
889
+ style: [styles3.input, hasError && styles3.inputError],
890
+ value: value != null ? String(value) : "",
891
+ onChangeText: onChange,
892
+ placeholder: field.type === "date" ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm",
893
+ placeholderTextColor: "#aaa",
894
+ editable: !field.readOnly
895
+ }
896
+ ),
897
+ hasError && errors.map((e, i) => /* @__PURE__ */ jsx6(Text3, { style: styles3.errorText, children: e }, i))
898
+ ] });
899
+ default:
900
+ return /* @__PURE__ */ jsxs3(View3, { style: styles3.fieldContainer, children: [
901
+ /* @__PURE__ */ jsxs3(Text3, { style: styles3.fieldLabel, children: [
902
+ field.label || field.field,
903
+ field.required ? " *" : ""
904
+ ] }),
905
+ /* @__PURE__ */ jsx6(
906
+ TextInput,
907
+ {
908
+ style: [
909
+ styles3.input,
910
+ field.multiline && styles3.inputMultiline,
911
+ hasError && styles3.inputError
912
+ ],
913
+ value: value != null ? String(value) : "",
914
+ onChangeText: onChange,
915
+ placeholder: field.placeholder,
916
+ placeholderTextColor: "#aaa",
917
+ multiline: field.multiline,
918
+ numberOfLines: field.multiline ? 4 : 1,
919
+ editable: !field.readOnly,
920
+ autoCapitalize: field.autoCapitalize || "sentences"
921
+ }
922
+ ),
923
+ hasError && errors.map((e, i) => /* @__PURE__ */ jsx6(Text3, { style: styles3.errorText, children: e }, i))
924
+ ] });
925
+ }
926
+ }
927
+ function NativeForm({
928
+ config = {},
929
+ data,
930
+ visible = false,
931
+ onClose,
932
+ onSubmit
933
+ }) {
934
+ const fields = config.fields || [];
935
+ const isEdit = data != null && data.id != null;
936
+ const title = config.title || (isEdit ? `Edit ${config.entityName || "Item"}` : `New ${config.entityName || "Item"}`);
937
+ const [values, setValues] = useState5({});
938
+ const [errors, setErrors] = useState5({});
939
+ const [submitting, setSubmitting] = useState5(false);
940
+ const [submitError, setSubmitError] = useState5(null);
941
+ const [pickerField, setPickerField] = useState5(null);
942
+ useEffect3(() => {
943
+ if (visible) {
944
+ if (data) {
945
+ const initialValues = {};
946
+ fields.forEach((field) => {
947
+ initialValues[field.field] = data[field.field] !== void 0 ? data[field.field] : "";
948
+ });
949
+ setValues(initialValues);
950
+ } else {
951
+ setValues(getDefaultValues(fields));
952
+ }
953
+ setErrors({});
954
+ setSubmitError(null);
955
+ }
956
+ }, [visible, data]);
957
+ const handleFieldChange = useCallback5((fieldName, value) => {
958
+ setValues((prev) => ({ ...prev, [fieldName]: value }));
959
+ setErrors((prev) => {
960
+ if (prev[fieldName]) {
961
+ const next = { ...prev };
962
+ delete next[fieldName];
963
+ return next;
964
+ }
965
+ return prev;
966
+ });
967
+ }, []);
968
+ const handleSubmit = useCallback5(async () => {
969
+ const { errors: validationErrors, hasErrors } = validateForm(values, fields);
970
+ if (hasErrors) {
971
+ setErrors(validationErrors);
972
+ return;
973
+ }
974
+ setSubmitting(true);
975
+ setSubmitError(null);
976
+ try {
977
+ const submitData = {};
978
+ fields.forEach((field) => {
979
+ if (!field.readOnly) {
980
+ submitData[field.field] = values[field.field];
981
+ }
982
+ });
983
+ await onSubmit(submitData, isEdit ? data.id : null);
984
+ } catch (err) {
985
+ setSubmitError(err.message || "Failed to save");
986
+ } finally {
987
+ setSubmitting(false);
988
+ }
989
+ }, [values, fields, isEdit, data, onSubmit]);
990
+ return /* @__PURE__ */ jsx6(Modal, { visible, animationType: "slide", presentationStyle: "fullScreen", onRequestClose: onClose, children: /* @__PURE__ */ jsxs3(SafeAreaView, { style: styles3.container, children: [
991
+ /* @__PURE__ */ jsxs3(
992
+ KeyboardAvoidingView,
993
+ {
994
+ style: styles3.flex,
995
+ behavior: Platform2.OS === "ios" ? "padding" : void 0,
996
+ children: [
997
+ /* @__PURE__ */ jsxs3(View3, { style: styles3.header, children: [
998
+ /* @__PURE__ */ jsx6(TouchableOpacity3, { onPress: onClose, activeOpacity: 0.7, style: styles3.headerSide, children: /* @__PURE__ */ jsx6(Text3, { style: styles3.cancelText, children: "Cancel" }) }),
999
+ /* @__PURE__ */ jsx6(Text3, { style: styles3.headerTitle, numberOfLines: 1, children: title }),
1000
+ /* @__PURE__ */ jsx6(
1001
+ TouchableOpacity3,
1002
+ {
1003
+ onPress: handleSubmit,
1004
+ activeOpacity: 0.7,
1005
+ style: styles3.headerSide,
1006
+ disabled: submitting,
1007
+ children: submitting ? /* @__PURE__ */ jsx6(ActivityIndicator2, { size: "small", color: "#1b5e20" }) : /* @__PURE__ */ jsx6(Text3, { style: styles3.saveText, children: "Save" })
1008
+ }
1009
+ )
1010
+ ] }),
1011
+ submitError && /* @__PURE__ */ jsx6(View3, { style: styles3.submitError, children: /* @__PURE__ */ jsx6(Text3, { style: styles3.submitErrorText, children: submitError }) }),
1012
+ /* @__PURE__ */ jsx6(
1013
+ ScrollView,
1014
+ {
1015
+ style: styles3.content,
1016
+ contentContainerStyle: styles3.contentInner,
1017
+ keyboardShouldPersistTaps: "handled",
1018
+ children: fields.filter((f) => !f.hidden).map((field) => /* @__PURE__ */ jsx6(
1019
+ FormField,
1020
+ {
1021
+ field,
1022
+ value: values[field.field],
1023
+ errors: errors[field.field],
1024
+ onChange: (val) => handleFieldChange(field.field, val),
1025
+ onOpenPicker: setPickerField
1026
+ },
1027
+ field.field
1028
+ ))
1029
+ }
1030
+ )
1031
+ ]
1032
+ }
1033
+ ),
1034
+ /* @__PURE__ */ jsx6(
1035
+ EnumPicker,
1036
+ {
1037
+ visible: !!pickerField,
1038
+ options: pickerField?.options,
1039
+ value: pickerField ? values[pickerField.field] : null,
1040
+ label: pickerField?.label || pickerField?.field,
1041
+ onSelect: (val) => {
1042
+ if (pickerField) {
1043
+ handleFieldChange(pickerField.field, val);
1044
+ }
1045
+ },
1046
+ onClose: () => setPickerField(null)
1047
+ }
1048
+ )
1049
+ ] }) });
1050
+ }
1051
+ var styles3 = StyleSheet3.create({
1052
+ container: {
1053
+ flex: 1,
1054
+ backgroundColor: "#f5f5f5"
1055
+ },
1056
+ flex: {
1057
+ flex: 1
1058
+ },
1059
+ header: {
1060
+ flexDirection: "row",
1061
+ alignItems: "center",
1062
+ paddingHorizontal: 8,
1063
+ paddingVertical: 12,
1064
+ backgroundColor: "#fff",
1065
+ borderBottomWidth: StyleSheet3.hairlineWidth,
1066
+ borderBottomColor: "#e0e0e0"
1067
+ },
1068
+ headerSide: {
1069
+ width: 70,
1070
+ alignItems: "center",
1071
+ justifyContent: "center"
1072
+ },
1073
+ headerTitle: {
1074
+ flex: 1,
1075
+ fontSize: 18,
1076
+ fontWeight: "600",
1077
+ color: "#1a1a1a",
1078
+ textAlign: "center"
1079
+ },
1080
+ cancelText: {
1081
+ fontSize: 16,
1082
+ color: "#666"
1083
+ },
1084
+ saveText: {
1085
+ fontSize: 16,
1086
+ fontWeight: "600",
1087
+ color: "#1b5e20"
1088
+ },
1089
+ submitError: {
1090
+ backgroundColor: "#fce4ec",
1091
+ paddingHorizontal: 16,
1092
+ paddingVertical: 10
1093
+ },
1094
+ submitErrorText: {
1095
+ fontSize: 14,
1096
+ color: "#d32f2f"
1097
+ },
1098
+ content: {
1099
+ flex: 1
1100
+ },
1101
+ contentInner: {
1102
+ padding: 16
1103
+ },
1104
+ fieldContainer: {
1105
+ marginBottom: 16
1106
+ },
1107
+ fieldLabel: {
1108
+ fontSize: 14,
1109
+ fontWeight: "500",
1110
+ color: "#1a1a1a",
1111
+ marginBottom: 6
1112
+ },
1113
+ input: {
1114
+ backgroundColor: "#fff",
1115
+ borderWidth: 1,
1116
+ borderColor: "#ddd",
1117
+ borderRadius: 8,
1118
+ paddingHorizontal: 12,
1119
+ paddingVertical: 10,
1120
+ fontSize: 16,
1121
+ color: "#1a1a1a"
1122
+ },
1123
+ inputMultiline: {
1124
+ height: 100,
1125
+ textAlignVertical: "top"
1126
+ },
1127
+ inputError: {
1128
+ borderColor: "#d32f2f"
1129
+ },
1130
+ enumInput: {
1131
+ flexDirection: "row",
1132
+ alignItems: "center",
1133
+ justifyContent: "space-between"
1134
+ },
1135
+ enumText: {
1136
+ fontSize: 16,
1137
+ color: "#1a1a1a",
1138
+ flex: 1
1139
+ },
1140
+ placeholderText: {
1141
+ color: "#aaa"
1142
+ },
1143
+ switchRow: {
1144
+ flexDirection: "row",
1145
+ alignItems: "center",
1146
+ justifyContent: "space-between",
1147
+ backgroundColor: "#fff",
1148
+ borderWidth: 1,
1149
+ borderColor: "#ddd",
1150
+ borderRadius: 8,
1151
+ paddingHorizontal: 12,
1152
+ paddingVertical: 10
1153
+ },
1154
+ errorText: {
1155
+ fontSize: 12,
1156
+ color: "#d32f2f",
1157
+ marginTop: 4
1158
+ }
1159
+ });
1160
+ var NativeForm_default = NativeForm;
1161
+
1162
+ // src/native/components/NativeDetail.jsx
1163
+ import { jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
1164
+ import React7 from "react";
1165
+ import {
1166
+ Modal as Modal2,
1167
+ View as View4,
1168
+ Text as Text4,
1169
+ StyleSheet as StyleSheet4,
1170
+ ScrollView as ScrollView2,
1171
+ TouchableOpacity as TouchableOpacity4,
1172
+ SafeAreaView as SafeAreaView2
1173
+ } from "react-native";
1174
+ import Ionicons4 from "@expo/vector-icons/Ionicons";
1175
+ function formatValue(value, field) {
1176
+ if (value == null)
1177
+ return "\u2014";
1178
+ switch (field.type) {
1179
+ case "boolean":
1180
+ return value ? "Yes" : "No";
1181
+ case "date":
1182
+ try {
1183
+ return new Date(value).toLocaleDateString();
1184
+ } catch {
1185
+ return String(value);
1186
+ }
1187
+ case "datetime":
1188
+ try {
1189
+ return new Date(value).toLocaleString();
1190
+ } catch {
1191
+ return String(value);
1192
+ }
1193
+ case "enum": {
1194
+ const option = field.options?.find((o) => o.value === value);
1195
+ return option?.label || String(value);
1196
+ }
1197
+ case "number":
1198
+ case "decimal":
1199
+ return String(value);
1200
+ default:
1201
+ return String(value);
1202
+ }
1203
+ }
1204
+ function FieldRow({ field, value }) {
1205
+ const formatted = formatValue(value, field);
1206
+ if (field.type === "enum") {
1207
+ const option = field.options?.find((o) => o.value === value);
1208
+ const badgeColor = option?.color || "#1b5e20";
1209
+ return /* @__PURE__ */ jsxs4(View4, { style: styles4.fieldRow, children: [
1210
+ /* @__PURE__ */ jsx7(Text4, { style: styles4.fieldLabel, children: field.label || field.field }),
1211
+ /* @__PURE__ */ jsx7(View4, { style: [styles4.badge, { backgroundColor: badgeColor + "20" }], children: /* @__PURE__ */ jsx7(Text4, { style: [styles4.badgeText, { color: badgeColor }], children: formatted }) })
1212
+ ] });
1213
+ }
1214
+ if (field.type === "boolean") {
1215
+ return /* @__PURE__ */ jsxs4(View4, { style: styles4.fieldRow, children: [
1216
+ /* @__PURE__ */ jsx7(Text4, { style: styles4.fieldLabel, children: field.label || field.field }),
1217
+ /* @__PURE__ */ jsxs4(View4, { style: styles4.booleanRow, children: [
1218
+ /* @__PURE__ */ jsx7(
1219
+ Ionicons4,
1220
+ {
1221
+ name: value ? "checkmark-circle" : "close-circle",
1222
+ size: 18,
1223
+ color: value ? "#1b5e20" : "#999"
1224
+ }
1225
+ ),
1226
+ /* @__PURE__ */ jsxs4(Text4, { style: styles4.fieldValue, children: [
1227
+ " ",
1228
+ formatted
1229
+ ] })
1230
+ ] })
1231
+ ] });
1232
+ }
1233
+ const isMultiline = field.type === "text" || field.multiline;
1234
+ return /* @__PURE__ */ jsxs4(View4, { style: styles4.fieldRow, children: [
1235
+ /* @__PURE__ */ jsx7(Text4, { style: styles4.fieldLabel, children: field.label || field.field }),
1236
+ /* @__PURE__ */ jsx7(Text4, { style: [styles4.fieldValue, isMultiline && styles4.fieldValueMultiline], children: formatted })
1237
+ ] });
1238
+ }
1239
+ function NativeDetail({
1240
+ config = {},
1241
+ data,
1242
+ visible = false,
1243
+ onEdit,
1244
+ onDelete,
1245
+ onClose
1246
+ }) {
1247
+ if (!data)
1248
+ return null;
1249
+ const fields = config.fields || [];
1250
+ const title = data[config.titleField] || data.title || data.name || "Detail";
1251
+ return /* @__PURE__ */ jsx7(
1252
+ Modal2,
1253
+ {
1254
+ visible,
1255
+ animationType: "slide",
1256
+ presentationStyle: "pageSheet",
1257
+ onRequestClose: onClose,
1258
+ children: /* @__PURE__ */ jsxs4(SafeAreaView2, { style: styles4.container, children: [
1259
+ /* @__PURE__ */ jsxs4(View4, { style: styles4.header, children: [
1260
+ /* @__PURE__ */ jsx7(TouchableOpacity4, { onPress: onClose, activeOpacity: 0.7, style: styles4.headerButton, children: /* @__PURE__ */ jsx7(Ionicons4, { name: "close", size: 24, color: "#1a1a1a" }) }),
1261
+ /* @__PURE__ */ jsx7(Text4, { style: styles4.headerTitle, numberOfLines: 1, children: title }),
1262
+ /* @__PURE__ */ jsx7(View4, { style: styles4.headerButton })
1263
+ ] }),
1264
+ /* @__PURE__ */ jsxs4(ScrollView2, { style: styles4.content, contentContainerStyle: styles4.contentInner, children: [
1265
+ fields.map((field) => /* @__PURE__ */ jsx7(
1266
+ FieldRow,
1267
+ {
1268
+ field,
1269
+ value: data[field.field]
1270
+ },
1271
+ field.field
1272
+ )),
1273
+ fields.length === 0 && /* @__PURE__ */ jsx7(View4, { style: styles4.noFields, children: /* @__PURE__ */ jsx7(Text4, { style: styles4.noFieldsText, children: "No fields configured" }) })
1274
+ ] }),
1275
+ /* @__PURE__ */ jsxs4(View4, { style: styles4.actionBar, children: [
1276
+ onEdit && /* @__PURE__ */ jsxs4(
1277
+ TouchableOpacity4,
1278
+ {
1279
+ style: [styles4.actionButton, styles4.editButton],
1280
+ onPress: () => onEdit(data),
1281
+ activeOpacity: 0.7,
1282
+ children: [
1283
+ /* @__PURE__ */ jsx7(Ionicons4, { name: "create-outline", size: 20, color: "#fff" }),
1284
+ /* @__PURE__ */ jsx7(Text4, { style: styles4.actionButtonText, children: "Edit" })
1285
+ ]
1286
+ }
1287
+ ),
1288
+ onDelete && /* @__PURE__ */ jsxs4(
1289
+ TouchableOpacity4,
1290
+ {
1291
+ style: [styles4.actionButton, styles4.deleteButton],
1292
+ onPress: () => onDelete(data),
1293
+ activeOpacity: 0.7,
1294
+ children: [
1295
+ /* @__PURE__ */ jsx7(Ionicons4, { name: "trash-outline", size: 20, color: "#fff" }),
1296
+ /* @__PURE__ */ jsx7(Text4, { style: styles4.actionButtonText, children: "Delete" })
1297
+ ]
1298
+ }
1299
+ )
1300
+ ] })
1301
+ ] })
1302
+ }
1303
+ );
1304
+ }
1305
+ var styles4 = StyleSheet4.create({
1306
+ container: {
1307
+ flex: 1,
1308
+ backgroundColor: "#f5f5f5"
1309
+ },
1310
+ header: {
1311
+ flexDirection: "row",
1312
+ alignItems: "center",
1313
+ paddingHorizontal: 8,
1314
+ paddingVertical: 12,
1315
+ backgroundColor: "#fff",
1316
+ borderBottomWidth: StyleSheet4.hairlineWidth,
1317
+ borderBottomColor: "#e0e0e0"
1318
+ },
1319
+ headerButton: {
1320
+ width: 44,
1321
+ height: 44,
1322
+ justifyContent: "center",
1323
+ alignItems: "center"
1324
+ },
1325
+ headerTitle: {
1326
+ flex: 1,
1327
+ fontSize: 18,
1328
+ fontWeight: "600",
1329
+ color: "#1a1a1a",
1330
+ textAlign: "center"
1331
+ },
1332
+ content: {
1333
+ flex: 1
1334
+ },
1335
+ contentInner: {
1336
+ padding: 16
1337
+ },
1338
+ fieldRow: {
1339
+ backgroundColor: "#fff",
1340
+ padding: 16,
1341
+ marginBottom: 1,
1342
+ borderRadius: 0
1343
+ },
1344
+ fieldLabel: {
1345
+ fontSize: 12,
1346
+ fontWeight: "600",
1347
+ color: "#666",
1348
+ textTransform: "uppercase",
1349
+ letterSpacing: 0.5,
1350
+ marginBottom: 4
1351
+ },
1352
+ fieldValue: {
1353
+ fontSize: 16,
1354
+ color: "#1a1a1a"
1355
+ },
1356
+ fieldValueMultiline: {
1357
+ lineHeight: 22
1358
+ },
1359
+ booleanRow: {
1360
+ flexDirection: "row",
1361
+ alignItems: "center"
1362
+ },
1363
+ badge: {
1364
+ alignSelf: "flex-start",
1365
+ paddingHorizontal: 10,
1366
+ paddingVertical: 4,
1367
+ borderRadius: 12
1368
+ },
1369
+ badgeText: {
1370
+ fontSize: 14,
1371
+ fontWeight: "500"
1372
+ },
1373
+ noFields: {
1374
+ padding: 40,
1375
+ alignItems: "center"
1376
+ },
1377
+ noFieldsText: {
1378
+ fontSize: 14,
1379
+ color: "#999"
1380
+ },
1381
+ actionBar: {
1382
+ flexDirection: "row",
1383
+ padding: 16,
1384
+ gap: 12,
1385
+ backgroundColor: "#fff",
1386
+ borderTopWidth: StyleSheet4.hairlineWidth,
1387
+ borderTopColor: "#e0e0e0"
1388
+ },
1389
+ actionButton: {
1390
+ flex: 1,
1391
+ flexDirection: "row",
1392
+ alignItems: "center",
1393
+ justifyContent: "center",
1394
+ paddingVertical: 12,
1395
+ borderRadius: 8,
1396
+ gap: 6
1397
+ },
1398
+ editButton: {
1399
+ backgroundColor: "#1b5e20"
1400
+ },
1401
+ deleteButton: {
1402
+ backgroundColor: "#d32f2f"
1403
+ },
1404
+ actionButtonText: {
1405
+ fontSize: 16,
1406
+ fontWeight: "600",
1407
+ color: "#fff"
1408
+ }
1409
+ });
1410
+ var NativeDetail_default = NativeDetail;
1411
+
1412
+ // src/native/components/NativeViewComponent.jsx
1413
+ import React8, { useMemo as useMemo4, useCallback as useCallback6 } from "react";
1414
+ import { View as View5, Text as Text5, Alert as Alert2, StyleSheet as StyleSheet5 } from "react-native";
1415
+ function resolveListenTo(listenTo, viewState) {
1416
+ if (!listenTo)
1417
+ return {};
1418
+ const resolved = {};
1419
+ Object.entries(listenTo).forEach(([binding, targetProp]) => {
1420
+ const [componentId, property] = binding.split(".");
1421
+ let value = null;
1422
+ switch (property) {
1423
+ case "selection":
1424
+ value = viewState.selections[componentId];
1425
+ break;
1426
+ case "editItem":
1427
+ value = viewState.editItems[componentId];
1428
+ break;
1429
+ default:
1430
+ value = viewState.componentStates[componentId]?.[property];
1431
+ }
1432
+ resolved[targetProp] = value;
1433
+ });
1434
+ return resolved;
1435
+ }
1436
+ function evaluateShowWhen(showWhen, viewState) {
1437
+ if (!showWhen)
1438
+ return true;
1439
+ const [componentId, property] = showWhen.split(".");
1440
+ switch (property) {
1441
+ case "selection":
1442
+ return !!viewState.selections[componentId];
1443
+ case "editItem":
1444
+ return !!viewState.editItems[componentId];
1445
+ default:
1446
+ return !!viewState.componentStates[componentId]?.[property];
1447
+ }
1448
+ }
1449
+ function GridComponent({ componentConfig }) {
1450
+ const {
1451
+ items,
1452
+ loading,
1453
+ storeActions,
1454
+ setSelection,
1455
+ setEditItem,
1456
+ openDialog,
1457
+ viewState,
1458
+ pagination,
1459
+ paginationConfig,
1460
+ onLoadMore,
1461
+ config: viewConfig
1462
+ } = useNativeJsonView();
1463
+ const { id, config, onAction } = componentConfig;
1464
+ const handleRowPress = useCallback6((row) => {
1465
+ setSelection(id, row);
1466
+ storeActions.select?.(row);
1467
+ }, [id, setSelection, storeActions]);
1468
+ const handleRefresh = useCallback6(() => {
1469
+ const sliceId = viewConfig?.dataSource?.sliceId;
1470
+ return storeActions.list?.(sliceId ? { sliceId } : void 0);
1471
+ }, [storeActions, viewConfig?.dataSource?.sliceId]);
1472
+ const handleLoadMore = useCallback6(() => {
1473
+ onLoadMore?.();
1474
+ }, [onLoadMore]);
1475
+ const handleEdit = useCallback6((row) => {
1476
+ setEditItem(id, row);
1477
+ const actionConfig = onAction?.edit;
1478
+ if (actionConfig?.open) {
1479
+ openDialog(actionConfig.open, row);
1480
+ } else {
1481
+ openDialog(`${id}_form`, row);
1482
+ }
1483
+ }, [id, setEditItem, onAction, openDialog]);
1484
+ const handleDelete = useCallback6((row) => {
1485
+ const entityName = config?.entityName || viewConfig?.dataSource?.entityName || "item";
1486
+ Alert2.alert(
1487
+ "Confirm Delete",
1488
+ `Are you sure you want to delete this ${entityName.toLowerCase()}?${row.title ? ` "${row.title}"` : row.name ? ` "${row.name}"` : ""}`,
1489
+ [
1490
+ { text: "Cancel", style: "cancel" },
1491
+ {
1492
+ text: "Delete",
1493
+ style: "destructive",
1494
+ onPress: () => {
1495
+ storeActions.delete?.(row.id).then(() => {
1496
+ const sliceId = viewConfig?.dataSource?.sliceId;
1497
+ storeActions.list?.(sliceId ? { sliceId } : void 0);
1498
+ });
1499
+ }
1500
+ }
1501
+ ]
1502
+ );
1503
+ }, [config?.entityName, viewConfig?.dataSource, storeActions]);
1504
+ const selectedId = viewState.selections[id]?.id;
1505
+ return /* @__PURE__ */ jsx8(
1506
+ NativeJsonGrid,
1507
+ {
1508
+ config,
1509
+ data: items,
1510
+ loading,
1511
+ selectedId,
1512
+ hasMore: pagination?.hasNext || false,
1513
+ onRowPress: handleRowPress,
1514
+ onRefresh: handleRefresh,
1515
+ onEndReached: handleLoadMore,
1516
+ onEdit: handleEdit,
1517
+ onDelete: handleDelete
1518
+ }
1519
+ );
1520
+ }
1521
+ function FormComponent({ componentConfig, boundData }) {
1522
+ const {
1523
+ storeActions,
1524
+ clearEditItem,
1525
+ closeDialog,
1526
+ dialogs,
1527
+ config: viewConfig
1528
+ } = useNativeJsonView();
1529
+ const { id, config, onSubmit } = componentConfig;
1530
+ const dialogState = dialogs[id];
1531
+ const formData = boundData?.data || dialogState?.data || null;
1532
+ const isOpen = dialogState?.open || false;
1533
+ const sliceId = viewConfig?.dataSource?.sliceId;
1534
+ const handleSubmit = useCallback6(async (data, editId) => {
1535
+ try {
1536
+ if (editId) {
1537
+ await storeActions.update?.(editId, data);
1538
+ } else {
1539
+ await storeActions.create?.(data);
1540
+ }
1541
+ storeActions.list?.(sliceId ? { sliceId } : void 0);
1542
+ if (onSubmit?.closeOnSuccess !== false) {
1543
+ clearEditItem(id);
1544
+ closeDialog(id);
1545
+ }
1546
+ } catch (err) {
1547
+ throw err;
1548
+ }
1549
+ }, [id, storeActions, clearEditItem, closeDialog, onSubmit, sliceId]);
1550
+ const handleClose = useCallback6(() => {
1551
+ clearEditItem(id);
1552
+ closeDialog(id);
1553
+ }, [id, clearEditItem, closeDialog]);
1554
+ return /* @__PURE__ */ jsx8(
1555
+ NativeForm,
1556
+ {
1557
+ config,
1558
+ data: formData,
1559
+ visible: isOpen,
1560
+ onClose: handleClose,
1561
+ onSubmit: handleSubmit
1562
+ }
1563
+ );
1564
+ }
1565
+ function DetailComponent({ componentConfig, boundData }) {
1566
+ const {
1567
+ storeActions,
1568
+ setEditItem,
1569
+ openDialog,
1570
+ closeDialog,
1571
+ config: viewConfig
1572
+ } = useNativeJsonView();
1573
+ const { id, config, onAction } = componentConfig;
1574
+ const detailData = boundData?.data || null;
1575
+ const handleEdit = useCallback6((data) => {
1576
+ setEditItem(id, data);
1577
+ const actionConfig = onAction?.edit;
1578
+ if (actionConfig?.open) {
1579
+ openDialog(actionConfig.open, data);
1580
+ } else {
1581
+ openDialog(`${id}_form`, data);
1582
+ }
1583
+ }, [id, setEditItem, onAction, openDialog]);
1584
+ const handleDelete = useCallback6((data) => {
1585
+ const entityName = config?.entityName || viewConfig?.dataSource?.entityName || "item";
1586
+ Alert2.alert(
1587
+ "Confirm Delete",
1588
+ `Are you sure you want to delete this ${entityName.toLowerCase()}?${data.title ? ` "${data.title}"` : data.name ? ` "${data.name}"` : ""}`,
1589
+ [
1590
+ { text: "Cancel", style: "cancel" },
1591
+ {
1592
+ text: "Delete",
1593
+ style: "destructive",
1594
+ onPress: () => {
1595
+ storeActions.delete?.(data.id).then(() => {
1596
+ const sliceId = viewConfig?.dataSource?.sliceId;
1597
+ storeActions.list?.(sliceId ? { sliceId } : void 0);
1598
+ closeDialog(id);
1599
+ });
1600
+ }
1601
+ }
1602
+ ]
1603
+ );
1604
+ }, [id, config?.entityName, viewConfig?.dataSource, storeActions, closeDialog]);
1605
+ const handleClose = useCallback6(() => {
1606
+ closeDialog(id);
1607
+ }, [id, closeDialog]);
1608
+ if (!detailData)
1609
+ return null;
1610
+ return /* @__PURE__ */ jsx8(
1611
+ NativeDetail,
1612
+ {
1613
+ config,
1614
+ data: detailData,
1615
+ visible: true,
1616
+ onEdit: handleEdit,
1617
+ onDelete: handleDelete,
1618
+ onClose: handleClose
1619
+ }
1620
+ );
1621
+ }
1622
+ function NativeViewComponent({ componentConfig }) {
1623
+ const { viewState, extensionComponents, dialogs, closeDialog, executeCustomAction } = useNativeJsonView();
1624
+ const { id, type, listenTo, showWhen } = componentConfig;
1625
+ const boundData = useMemo4(
1626
+ () => resolveListenTo(listenTo, viewState),
1627
+ [listenTo, viewState]
1628
+ );
1629
+ const isVisible = useMemo4(
1630
+ () => evaluateShowWhen(showWhen, viewState),
1631
+ [showWhen, viewState]
1632
+ );
1633
+ let content;
1634
+ switch (type) {
1635
+ case "grid":
1636
+ content = /* @__PURE__ */ jsx8(GridComponent, { componentConfig });
1637
+ break;
1638
+ case "form":
1639
+ content = /* @__PURE__ */ jsx8(FormComponent, { componentConfig, boundData });
1640
+ break;
1641
+ case "detail":
1642
+ if (!isVisible)
1643
+ return null;
1644
+ content = /* @__PURE__ */ jsx8(DetailComponent, { componentConfig, boundData });
1645
+ break;
1646
+ case "custom": {
1647
+ const CustomComponent = extensionComponents?.[componentConfig.component];
1648
+ if (CustomComponent) {
1649
+ const dialogState = dialogs[id];
1650
+ const isDialogOpen = dialogState?.open || false;
1651
+ const dialogData = dialogState?.data || boundData?.data;
1652
+ content = /* @__PURE__ */ jsx8(
1653
+ CustomComponent,
1654
+ {
1655
+ id,
1656
+ config: componentConfig.config,
1657
+ data: dialogData,
1658
+ boundData,
1659
+ open: isDialogOpen,
1660
+ onClose: () => closeDialog(id)
1661
+ }
1662
+ );
1663
+ } else {
1664
+ content = /* @__PURE__ */ jsx8(View5, { style: styles5.unknownType, children: /* @__PURE__ */ jsxs5(Text5, { style: styles5.unknownTypeText, children: [
1665
+ "Custom component not found: ",
1666
+ componentConfig.component
1667
+ ] }) });
1668
+ }
1669
+ break;
1670
+ }
1671
+ default:
1672
+ content = /* @__PURE__ */ jsx8(View5, { style: styles5.unknownType, children: /* @__PURE__ */ jsxs5(Text5, { style: styles5.unknownTypeText, children: [
1673
+ "Unknown component type: ",
1674
+ type
1675
+ ] }) });
1676
+ }
1677
+ return content;
1678
+ }
1679
+ var styles5 = StyleSheet5.create({
1680
+ unknownType: {
1681
+ padding: 16,
1682
+ alignItems: "center"
1683
+ },
1684
+ unknownTypeText: {
1685
+ fontSize: 14,
1686
+ color: "#d32f2f"
1687
+ }
1688
+ });
1689
+ var NativeViewComponent_default = NativeViewComponent;
1690
+
1691
+ // src/native/layouts/NativeStackLayout.jsx
1692
+ import React9 from "react";
1693
+ import { View as View6, StyleSheet as StyleSheet6 } from "react-native";
1694
+ function NativeStackLayout({ config = {}, components = [] }) {
1695
+ return /* @__PURE__ */ jsx9(View6, { style: styles6.container, children: components.map((componentConfig) => /* @__PURE__ */ jsx9(
1696
+ NativeViewComponent,
1697
+ {
1698
+ componentConfig
1699
+ },
1700
+ componentConfig.id
1701
+ )) });
1702
+ }
1703
+ var styles6 = StyleSheet6.create({
1704
+ container: {
1705
+ flex: 1
1706
+ }
1707
+ });
1708
+ var NativeStackLayout_default = NativeStackLayout;
1709
+
1710
+ // src/native/layouts/NativeTabLayout.jsx
1711
+ import { jsx as jsx10, jsxs as jsxs6 } from "react/jsx-runtime";
1712
+ import React10, { useState as useState6, useCallback as useCallback7 } from "react";
1713
+ import { View as View7, Text as Text6, ScrollView as ScrollView3, TouchableOpacity as TouchableOpacity5, StyleSheet as StyleSheet7 } from "react-native";
1714
+ function NativeTabLayout({ config = {}, components = [] }) {
1715
+ const [activeIndex, setActiveIndex] = useState6(0);
1716
+ const handleTabPress = useCallback7((index) => {
1717
+ setActiveIndex(index);
1718
+ }, []);
1719
+ if (components.length === 0)
1720
+ return null;
1721
+ const activeComponent = components[activeIndex] || components[0];
1722
+ return /* @__PURE__ */ jsxs6(View7, { style: styles7.container, children: [
1723
+ /* @__PURE__ */ jsx10(View7, { style: styles7.tabBarContainer, children: /* @__PURE__ */ jsx10(
1724
+ ScrollView3,
1725
+ {
1726
+ horizontal: true,
1727
+ showsHorizontalScrollIndicator: false,
1728
+ contentContainerStyle: styles7.tabBar,
1729
+ children: components.map((comp, index) => {
1730
+ const isActive = index === activeIndex;
1731
+ return /* @__PURE__ */ jsx10(
1732
+ TouchableOpacity5,
1733
+ {
1734
+ style: [styles7.tab, isActive && styles7.tabActive],
1735
+ onPress: () => handleTabPress(index),
1736
+ activeOpacity: 0.7,
1737
+ children: /* @__PURE__ */ jsx10(Text6, { style: [styles7.tabText, isActive && styles7.tabTextActive], children: comp.title || comp.config?.title || comp.id })
1738
+ },
1739
+ comp.id
1740
+ );
1741
+ })
1742
+ }
1743
+ ) }),
1744
+ /* @__PURE__ */ jsx10(View7, { style: styles7.content, children: /* @__PURE__ */ jsx10(
1745
+ NativeViewComponent,
1746
+ {
1747
+ componentConfig: activeComponent
1748
+ },
1749
+ activeComponent.id
1750
+ ) })
1751
+ ] });
1752
+ }
1753
+ var styles7 = StyleSheet7.create({
1754
+ container: {
1755
+ flex: 1
1756
+ },
1757
+ tabBarContainer: {
1758
+ backgroundColor: "#fff",
1759
+ borderBottomWidth: StyleSheet7.hairlineWidth,
1760
+ borderBottomColor: "#e0e0e0"
1761
+ },
1762
+ tabBar: {
1763
+ flexDirection: "row",
1764
+ paddingHorizontal: 12
1765
+ },
1766
+ tab: {
1767
+ paddingHorizontal: 16,
1768
+ paddingVertical: 12,
1769
+ borderBottomWidth: 2,
1770
+ borderBottomColor: "transparent"
1771
+ },
1772
+ tabActive: {
1773
+ borderBottomColor: "#1b5e20"
1774
+ },
1775
+ tabText: {
1776
+ fontSize: 14,
1777
+ fontWeight: "500",
1778
+ color: "#666"
1779
+ },
1780
+ tabTextActive: {
1781
+ color: "#1b5e20",
1782
+ fontWeight: "600"
1783
+ },
1784
+ content: {
1785
+ flex: 1
1786
+ }
1787
+ });
1788
+ var NativeTabLayout_default = NativeTabLayout;
1789
+
1790
+ // src/native/extensions/NativeExtensionRegistry.js
1791
+ var NativeExtensionRegistry = class {
1792
+ constructor() {
1793
+ this._extensions = /* @__PURE__ */ new Map();
1794
+ }
1795
+ /**
1796
+ * Register an extension hook
1797
+ * @param {string} name - Extension name (referenced in JSON config)
1798
+ * @param {Function} useExtension - Hook function that returns { actions, components, ...state }
1799
+ */
1800
+ register(name, useExtension) {
1801
+ if (typeof useExtension !== "function") {
1802
+ throw new Error(`Extension "${name}" must be a function (hook)`);
1803
+ }
1804
+ this._extensions.set(name, useExtension);
1805
+ }
1806
+ /**
1807
+ * Register multiple extensions at once
1808
+ * @param {Object} extensions - Object of { name: useExtension }
1809
+ */
1810
+ registerAll(extensions) {
1811
+ Object.entries(extensions).forEach(([name, hook]) => {
1812
+ this.register(name, hook);
1813
+ });
1814
+ }
1815
+ /**
1816
+ * Get an extension hook by name
1817
+ * @param {string} name - Extension name
1818
+ * @returns {Function|null} Extension hook or null if not found
1819
+ */
1820
+ get(name) {
1821
+ return this._extensions.get(name) || null;
1822
+ }
1823
+ /**
1824
+ * Check if an extension is registered
1825
+ * @param {string} name - Extension name
1826
+ * @returns {boolean}
1827
+ */
1828
+ has(name) {
1829
+ return this._extensions.has(name);
1830
+ }
1831
+ /**
1832
+ * Get all registered extension names
1833
+ * @returns {string[]}
1834
+ */
1835
+ getNames() {
1836
+ return Array.from(this._extensions.keys());
1837
+ }
1838
+ /**
1839
+ * Clear all registered extensions
1840
+ */
1841
+ clear() {
1842
+ this._extensions.clear();
1843
+ }
1844
+ };
1845
+ var nativeExtensionRegistry = new NativeExtensionRegistry();
1846
+ var NativeExtensionRegistry_default = NativeExtensionRegistry;
1847
+
1848
+ // src/native/components/NativeJsonView.jsx
1849
+ import React11, { useReducer, useEffect as useEffect4, useMemo as useMemo5, useCallback as useCallback8 } from "react";
1850
+ import { View as View8, Text as Text7, ActivityIndicator as ActivityIndicator3, StyleSheet as StyleSheet8 } from "react-native";
1851
+ var ActionTypes = {
1852
+ SET_SELECTION: "SET_SELECTION",
1853
+ CLEAR_SELECTION: "CLEAR_SELECTION",
1854
+ SET_EDIT_ITEM: "SET_EDIT_ITEM",
1855
+ CLEAR_EDIT_ITEM: "CLEAR_EDIT_ITEM",
1856
+ OPEN_DIALOG: "OPEN_DIALOG",
1857
+ CLOSE_DIALOG: "CLOSE_DIALOG",
1858
+ SET_COMPONENT_STATE: "SET_COMPONENT_STATE",
1859
+ SET_PAGINATION: "SET_PAGINATION"
1860
+ };
1861
+ function getInitialPaginationState(paginationConfig) {
1862
+ if (!paginationConfig || paginationConfig.mode === "none") {
1863
+ return null;
1864
+ }
1865
+ return {
1866
+ mode: paginationConfig.mode || "infinite",
1867
+ page: 1,
1868
+ pageSize: paginationConfig.pageSize || 25,
1869
+ total: 0,
1870
+ totalPages: 0,
1871
+ hasNext: false,
1872
+ hasPrev: false
1873
+ };
1874
+ }
1875
+ var initialState = {
1876
+ selections: {},
1877
+ editItems: {},
1878
+ dialogs: {},
1879
+ componentStates: {},
1880
+ pagination: null
1881
+ };
1882
+ function viewReducer(state, action) {
1883
+ switch (action.type) {
1884
+ case ActionTypes.SET_SELECTION:
1885
+ return {
1886
+ ...state,
1887
+ selections: { ...state.selections, [action.componentId]: action.data }
1888
+ };
1889
+ case ActionTypes.CLEAR_SELECTION:
1890
+ return {
1891
+ ...state,
1892
+ selections: { ...state.selections, [action.componentId]: null }
1893
+ };
1894
+ case ActionTypes.SET_EDIT_ITEM:
1895
+ return {
1896
+ ...state,
1897
+ editItems: { ...state.editItems, [action.componentId]: action.data }
1898
+ };
1899
+ case ActionTypes.CLEAR_EDIT_ITEM:
1900
+ return {
1901
+ ...state,
1902
+ editItems: { ...state.editItems, [action.componentId]: null }
1903
+ };
1904
+ case ActionTypes.OPEN_DIALOG:
1905
+ return {
1906
+ ...state,
1907
+ dialogs: { ...state.dialogs, [action.dialogId]: { open: true, data: action.data } }
1908
+ };
1909
+ case ActionTypes.CLOSE_DIALOG:
1910
+ return {
1911
+ ...state,
1912
+ dialogs: { ...state.dialogs, [action.dialogId]: { open: false, data: null } }
1913
+ };
1914
+ case ActionTypes.SET_COMPONENT_STATE:
1915
+ return {
1916
+ ...state,
1917
+ componentStates: {
1918
+ ...state.componentStates,
1919
+ [action.componentId]: {
1920
+ ...state.componentStates[action.componentId],
1921
+ ...action.state
1922
+ }
1923
+ }
1924
+ };
1925
+ case ActionTypes.SET_PAGINATION:
1926
+ return {
1927
+ ...state,
1928
+ pagination: { ...state.pagination, ...action.pagination }
1929
+ };
1930
+ default:
1931
+ return state;
1932
+ }
1933
+ }
1934
+ var LAYOUTS = {
1935
+ stack: NativeStackLayout,
1936
+ tabs: NativeTabLayout,
1937
+ single: NativeStackLayout,
1938
+ split: NativeStackLayout
1939
+ };
1940
+ function NativeJsonViewWithStore({ config, storeName }) {
1941
+ const store = useNativeStore(storeName);
1942
+ const {
1943
+ id: viewId,
1944
+ layout = "stack",
1945
+ layoutConfig = {},
1946
+ dataSource = {},
1947
+ components = [],
1948
+ extension: extensionName
1949
+ } = config || {};
1950
+ const useExtension = extensionName ? nativeExtensionRegistry.get(extensionName) : null;
1951
+ const initialStateWithPagination = useMemo5(() => ({
1952
+ ...initialState,
1953
+ pagination: getInitialPaginationState(dataSource?.pagination)
1954
+ }), []);
1955
+ const [viewState, dispatch] = useReducer(viewReducer, initialStateWithPagination);
1956
+ const storeLoading = store.loading;
1957
+ const storeError = store.error;
1958
+ const storePagination = store.pagination;
1959
+ const storeActions = useMemo5(() => ({
1960
+ list: store.list,
1961
+ get: store.get,
1962
+ create: store.create,
1963
+ update: store.update,
1964
+ delete: store.delete,
1965
+ select: store.select,
1966
+ clearSelection: store.clearSelection,
1967
+ loadMore: store.loadMore,
1968
+ setPageSize: store.setPageSize
1969
+ }), [store]);
1970
+ useEffect4(() => {
1971
+ if (viewState.pagination && storePagination) {
1972
+ dispatch({
1973
+ type: ActionTypes.SET_PAGINATION,
1974
+ pagination: {
1975
+ page: storePagination.page,
1976
+ pageSize: storePagination.pageSize,
1977
+ total: storePagination.total,
1978
+ totalPages: storePagination.totalPages,
1979
+ hasNext: storePagination.hasNext,
1980
+ hasPrev: storePagination.hasPrev
1981
+ }
1982
+ });
1983
+ }
1984
+ }, [storePagination, viewState.pagination !== null]);
1985
+ const storeItems = store.items;
1986
+ useEffect4(() => {
1987
+ if (!storeItems?.length)
1988
+ return;
1989
+ Object.entries(viewState.selections).forEach(([componentId, selectedItem]) => {
1990
+ if (!selectedItem?.id)
1991
+ return;
1992
+ const updatedItem = storeItems.find((item) => item.id === selectedItem.id);
1993
+ if (updatedItem && updatedItem !== selectedItem) {
1994
+ dispatch({
1995
+ type: ActionTypes.SET_SELECTION,
1996
+ componentId,
1997
+ data: updatedItem
1998
+ });
1999
+ }
2000
+ });
2001
+ }, [storeItems]);
2002
+ useEffect4(() => {
2003
+ if (dataSource?.autoLoad) {
2004
+ const loadOptions = {};
2005
+ if (viewState.pagination) {
2006
+ loadOptions.page = viewState.pagination.page;
2007
+ loadOptions.pageSize = viewState.pagination.pageSize;
2008
+ }
2009
+ if (dataSource.sliceId) {
2010
+ loadOptions.sliceId = dataSource.sliceId;
2011
+ }
2012
+ store.list(loadOptions);
2013
+ }
2014
+ }, []);
2015
+ return /* @__PURE__ */ jsx11(
2016
+ NativeJsonViewInner,
2017
+ {
2018
+ config,
2019
+ viewId,
2020
+ layout,
2021
+ layoutConfig,
2022
+ dataSource,
2023
+ components,
2024
+ viewState,
2025
+ dispatch,
2026
+ storeData: store,
2027
+ storeLoading,
2028
+ storeError,
2029
+ storeActions,
2030
+ useExtension
2031
+ }
2032
+ );
2033
+ }
2034
+ function NativeJsonViewWithoutStore({ config }) {
2035
+ const [viewState, dispatch] = useReducer(viewReducer, initialState);
2036
+ const {
2037
+ id: viewId,
2038
+ layout = "stack",
2039
+ layoutConfig = {},
2040
+ dataSource = {},
2041
+ components = [],
2042
+ extension: extensionName
2043
+ } = config || {};
2044
+ const useExtension = extensionName ? nativeExtensionRegistry.get(extensionName) : null;
2045
+ return /* @__PURE__ */ jsx11(
2046
+ NativeJsonViewInner,
2047
+ {
2048
+ config,
2049
+ viewId,
2050
+ layout,
2051
+ layoutConfig,
2052
+ dataSource,
2053
+ components,
2054
+ viewState,
2055
+ dispatch,
2056
+ storeData: null,
2057
+ storeLoading: false,
2058
+ storeError: null,
2059
+ storeActions: {},
2060
+ useExtension
2061
+ }
2062
+ );
2063
+ }
2064
+ function NativeJsonView({ config }) {
2065
+ const storeName = config?.dataSource?.store;
2066
+ if (storeName) {
2067
+ return /* @__PURE__ */ jsx11(NativeJsonViewWithStore, { config, storeName });
2068
+ }
2069
+ return /* @__PURE__ */ jsx11(NativeJsonViewWithoutStore, { config });
2070
+ }
2071
+ function NativeJsonViewInner({
2072
+ config,
2073
+ viewId,
2074
+ layout,
2075
+ layoutConfig,
2076
+ dataSource,
2077
+ components,
2078
+ viewState,
2079
+ dispatch,
2080
+ storeData,
2081
+ storeLoading,
2082
+ storeError,
2083
+ storeActions,
2084
+ useExtension
2085
+ }) {
2086
+ const setSelection = useCallback8((componentId, data) => {
2087
+ dispatch({ type: ActionTypes.SET_SELECTION, componentId, data });
2088
+ }, []);
2089
+ const clearSelection = useCallback8((componentId) => {
2090
+ dispatch({ type: ActionTypes.CLEAR_SELECTION, componentId });
2091
+ }, []);
2092
+ const setEditItem = useCallback8((componentId, data) => {
2093
+ dispatch({ type: ActionTypes.SET_EDIT_ITEM, componentId, data });
2094
+ }, []);
2095
+ const clearEditItem = useCallback8((componentId) => {
2096
+ dispatch({ type: ActionTypes.CLEAR_EDIT_ITEM, componentId });
2097
+ }, []);
2098
+ const openDialog = useCallback8((dialogId, data = null) => {
2099
+ dispatch({ type: ActionTypes.OPEN_DIALOG, dialogId, data });
2100
+ }, []);
2101
+ const closeDialog = useCallback8((dialogId) => {
2102
+ dispatch({ type: ActionTypes.CLOSE_DIALOG, dialogId });
2103
+ }, []);
2104
+ const setComponentState = useCallback8((componentId, state) => {
2105
+ dispatch({ type: ActionTypes.SET_COMPONENT_STATE, componentId, state });
2106
+ }, []);
2107
+ const handleLoadMore = useCallback8(() => {
2108
+ storeActions.loadMore?.();
2109
+ }, [storeActions]);
2110
+ const extensionContext = useMemo5(() => ({
2111
+ store: storeData,
2112
+ storeActions,
2113
+ viewState,
2114
+ openDialog,
2115
+ closeDialog,
2116
+ setSelection,
2117
+ setEditItem
2118
+ }), [storeData, storeActions, viewState, openDialog, closeDialog, setSelection, setEditItem]);
2119
+ const extension = useExtension ? useExtension(extensionContext) : null;
2120
+ const extensionActions = extension?.actions || {};
2121
+ const extensionComponents = extension?.components || {};
2122
+ const executeCustomAction = useCallback8(async (actionConfig, data) => {
2123
+ if (actionConfig.handler && extensionActions[actionConfig.handler]) {
2124
+ return extensionActions[actionConfig.handler](data);
2125
+ }
2126
+ if (actionConfig.serverAction) {
2127
+ const endpoint = actionConfig.endpoint.replace(":id", data?.id);
2128
+ const method = actionConfig.method || "POST";
2129
+ const response = await fetch(endpoint, {
2130
+ method,
2131
+ headers: { "Content-Type": "application/json" },
2132
+ body: method !== "GET" ? JSON.stringify(data) : void 0
2133
+ });
2134
+ if (!response.ok) {
2135
+ throw new Error(`Server action failed: ${response.statusText}`);
2136
+ }
2137
+ if (actionConfig.refreshAfter !== false) {
2138
+ storeActions.list?.(dataSource?.sliceId ? { sliceId: dataSource.sliceId } : void 0);
2139
+ }
2140
+ return response.json().catch(() => ({}));
2141
+ }
2142
+ }, [extensionActions, storeActions, dataSource?.sliceId]);
2143
+ const contextValue = useMemo5(() => ({
2144
+ viewId,
2145
+ config,
2146
+ components,
2147
+ viewState,
2148
+ selections: viewState.selections,
2149
+ editItems: viewState.editItems,
2150
+ dialogs: viewState.dialogs,
2151
+ pagination: viewState.pagination,
2152
+ paginationConfig: dataSource?.pagination,
2153
+ onLoadMore: handleLoadMore,
2154
+ setSelection,
2155
+ clearSelection,
2156
+ setEditItem,
2157
+ clearEditItem,
2158
+ openDialog,
2159
+ closeDialog,
2160
+ setComponentState,
2161
+ store: storeData,
2162
+ storeActions,
2163
+ items: storeData?.items || [],
2164
+ loading: storeLoading,
2165
+ error: storeError,
2166
+ // Extension data
2167
+ extension,
2168
+ extensionActions,
2169
+ extensionComponents,
2170
+ executeCustomAction
2171
+ }), [
2172
+ viewId,
2173
+ config,
2174
+ components,
2175
+ viewState,
2176
+ dataSource?.pagination,
2177
+ storeData,
2178
+ storeLoading,
2179
+ storeError,
2180
+ setSelection,
2181
+ clearSelection,
2182
+ setEditItem,
2183
+ clearEditItem,
2184
+ openDialog,
2185
+ closeDialog,
2186
+ setComponentState,
2187
+ storeActions,
2188
+ handleLoadMore,
2189
+ extension,
2190
+ extensionActions,
2191
+ extensionComponents,
2192
+ executeCustomAction
2193
+ ]);
2194
+ if (storeError && !storeData?.items?.length) {
2195
+ return /* @__PURE__ */ jsx11(View8, { style: styles8.errorContainer, children: /* @__PURE__ */ jsx11(Text7, { style: styles8.errorText, children: storeError }) });
2196
+ }
2197
+ const LayoutComponent = LAYOUTS[layout] || NativeStackLayout;
2198
+ return /* @__PURE__ */ jsx11(NativeJsonViewContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx11(View8, { style: styles8.container, children: /* @__PURE__ */ jsx11(
2199
+ LayoutComponent,
2200
+ {
2201
+ config: layoutConfig,
2202
+ components
2203
+ }
2204
+ ) }) });
2205
+ }
2206
+ var styles8 = StyleSheet8.create({
2207
+ container: {
2208
+ flex: 1,
2209
+ backgroundColor: "#f5f5f5"
2210
+ },
2211
+ errorContainer: {
2212
+ flex: 1,
2213
+ justifyContent: "center",
2214
+ alignItems: "center",
2215
+ padding: 24
2216
+ },
2217
+ errorText: {
2218
+ fontSize: 16,
2219
+ color: "#d32f2f",
2220
+ textAlign: "center"
2221
+ }
2222
+ });
2223
+ var NativeJsonView_default = NativeJsonView;
2224
+
2225
+ // src/native/stores/NativeBaseStore.js
2226
+ function toSnakeCase(str) {
2227
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
2228
+ }
2229
+ function toCamelCase(str) {
2230
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
2231
+ }
2232
+ function toSnakeCaseKeys(obj) {
2233
+ if (obj === null || typeof obj !== "object")
2234
+ return obj;
2235
+ if (Array.isArray(obj))
2236
+ return obj.map(toSnakeCaseKeys);
2237
+ return Object.keys(obj).reduce((acc, key) => {
2238
+ acc[toSnakeCase(key)] = toSnakeCaseKeys(obj[key]);
2239
+ return acc;
2240
+ }, {});
2241
+ }
2242
+ function toCamelCaseKeys(obj) {
2243
+ if (obj === null || typeof obj !== "object")
2244
+ return obj;
2245
+ if (Array.isArray(obj))
2246
+ return obj.map(toCamelCaseKeys);
2247
+ return Object.keys(obj).reduce((acc, key) => {
2248
+ acc[toCamelCase(key)] = toCamelCaseKeys(obj[key]);
2249
+ return acc;
2250
+ }, {});
2251
+ }
2252
+ var NativeBaseStore = class {
2253
+ constructor(entityName, endpoint) {
2254
+ this.entityName = entityName;
2255
+ this.endpoint = endpoint;
2256
+ this._getAuthHeader = null;
2257
+ this._state = {
2258
+ items: [],
2259
+ selectedItem: null,
2260
+ loading: false,
2261
+ error: null,
2262
+ pagination: {
2263
+ page: 1,
2264
+ pageSize: 25,
2265
+ total: 0,
2266
+ totalPages: 0,
2267
+ hasNext: false,
2268
+ hasPrev: false
2269
+ }
2270
+ };
2271
+ this._subscribers = /* @__PURE__ */ new Set();
2272
+ }
2273
+ _initialize(getAuthHeader) {
2274
+ this._getAuthHeader = getAuthHeader;
2275
+ }
2276
+ _getHeaders() {
2277
+ const headers = {
2278
+ "Content-Type": "application/json"
2279
+ };
2280
+ if (this._getAuthHeader) {
2281
+ const authHeader = this._getAuthHeader();
2282
+ if (authHeader.Authorization) {
2283
+ headers.Authorization = authHeader.Authorization;
2284
+ }
2285
+ }
2286
+ return headers;
2287
+ }
2288
+ getState() {
2289
+ return this._state;
2290
+ }
2291
+ _setState(updates) {
2292
+ this._state = { ...this._state, ...updates };
2293
+ this._notifySubscribers();
2294
+ }
2295
+ subscribe(callback) {
2296
+ this._subscribers.add(callback);
2297
+ return () => this._subscribers.delete(callback);
2298
+ }
2299
+ _notifySubscribers() {
2300
+ this._subscribers.forEach((callback) => callback(this._state));
2301
+ }
2302
+ async _handleResponse(response) {
2303
+ if (!response.ok) {
2304
+ const error = await response.json().catch(() => ({ message: "Request failed" }));
2305
+ throw new Error(error.message || `HTTP ${response.status}`);
2306
+ }
2307
+ return response.json();
2308
+ }
2309
+ async list(options = {}) {
2310
+ this._setState({ loading: true, error: null });
2311
+ try {
2312
+ const queryParams = new URLSearchParams();
2313
+ if (options.page)
2314
+ queryParams.set("page", options.page);
2315
+ if (options.pageSize)
2316
+ queryParams.set("pageSize", options.pageSize);
2317
+ if (options.sort)
2318
+ queryParams.set("sort", options.sort);
2319
+ if (options.sortDirection)
2320
+ queryParams.set("sortDirection", options.sortDirection);
2321
+ if (options.sliceId)
2322
+ queryParams.set("slice", options.sliceId);
2323
+ if (options.filters) {
2324
+ for (const [key, value] of Object.entries(options.filters)) {
2325
+ queryParams.set(key, value);
2326
+ }
2327
+ }
2328
+ const url = queryParams.toString() ? `${this.endpoint}?${queryParams}` : this.endpoint;
2329
+ const response = await fetch(url, {
2330
+ method: "GET",
2331
+ headers: this._getHeaders()
2332
+ });
2333
+ const data = await this._handleResponse(response);
2334
+ let items, paginationInfo;
2335
+ if (Array.isArray(data)) {
2336
+ items = data;
2337
+ paginationInfo = {
2338
+ page: options.page || 1,
2339
+ pageSize: options.pageSize || this._state.pagination.pageSize,
2340
+ total: items.length,
2341
+ totalPages: 1,
2342
+ hasNext: false,
2343
+ hasPrev: false
2344
+ };
2345
+ } else {
2346
+ items = data.data || data.items || [];
2347
+ paginationInfo = data.pagination || {
2348
+ page: options.page || 1,
2349
+ pageSize: options.pageSize || this._state.pagination.pageSize,
2350
+ total: data.total || items.length,
2351
+ totalPages: Math.ceil((data.total || items.length) / (options.pageSize || this._state.pagination.pageSize)),
2352
+ hasNext: false,
2353
+ hasPrev: false
2354
+ };
2355
+ }
2356
+ const transformedItems = items.map(toCamelCaseKeys);
2357
+ const finalItems = options.append ? [...this._state.items, ...transformedItems] : transformedItems;
2358
+ this._setState({
2359
+ items: finalItems,
2360
+ loading: false,
2361
+ pagination: paginationInfo
2362
+ });
2363
+ return this._state.items;
2364
+ } catch (error) {
2365
+ this._setState({ loading: false, error: error.message });
2366
+ throw error;
2367
+ }
2368
+ }
2369
+ async loadMore() {
2370
+ const { pagination } = this._state;
2371
+ if (this._state.loading || !pagination.hasNext) {
2372
+ return this._state.items;
2373
+ }
2374
+ return this.list({
2375
+ page: pagination.page + 1,
2376
+ pageSize: pagination.pageSize,
2377
+ append: true
2378
+ });
2379
+ }
2380
+ async get(id, options = {}) {
2381
+ this._setState({ loading: true, error: null });
2382
+ try {
2383
+ const queryParams = new URLSearchParams();
2384
+ if (options.sliceId)
2385
+ queryParams.set("slice", options.sliceId);
2386
+ const url = queryParams.toString() ? `${this.endpoint}/${id}?${queryParams}` : `${this.endpoint}/${id}`;
2387
+ const response = await fetch(url, {
2388
+ method: "GET",
2389
+ headers: this._getHeaders()
2390
+ });
2391
+ const data = await this._handleResponse(response);
2392
+ const item = toCamelCaseKeys(data);
2393
+ this._setState({
2394
+ selectedItem: item,
2395
+ loading: false
2396
+ });
2397
+ return item;
2398
+ } catch (error) {
2399
+ this._setState({ loading: false, error: error.message });
2400
+ throw error;
2401
+ }
2402
+ }
2403
+ async create(data) {
2404
+ this._setState({ loading: true, error: null });
2405
+ try {
2406
+ const response = await fetch(this.endpoint, {
2407
+ method: "POST",
2408
+ headers: this._getHeaders(),
2409
+ body: JSON.stringify(toSnakeCaseKeys(data))
2410
+ });
2411
+ const result = await this._handleResponse(response);
2412
+ const item = toCamelCaseKeys(result);
2413
+ this._setState({
2414
+ items: [item, ...this._state.items],
2415
+ loading: false
2416
+ });
2417
+ return item;
2418
+ } catch (error) {
2419
+ this._setState({ loading: false, error: error.message });
2420
+ throw error;
2421
+ }
2422
+ }
2423
+ async update(id, data) {
2424
+ this._setState({ loading: true, error: null });
2425
+ try {
2426
+ const response = await fetch(`${this.endpoint}/${id}`, {
2427
+ method: "PUT",
2428
+ headers: this._getHeaders(),
2429
+ body: JSON.stringify(toSnakeCaseKeys(data))
2430
+ });
2431
+ const result = await this._handleResponse(response);
2432
+ const item = toCamelCaseKeys(result);
2433
+ this._setState({
2434
+ items: this._state.items.map((i) => i.id === id ? item : i),
2435
+ selectedItem: this._state.selectedItem?.id === id ? item : this._state.selectedItem,
2436
+ loading: false
2437
+ });
2438
+ return item;
2439
+ } catch (error) {
2440
+ this._setState({ loading: false, error: error.message });
2441
+ throw error;
2442
+ }
2443
+ }
2444
+ async delete(id) {
2445
+ this._setState({ loading: true, error: null });
2446
+ try {
2447
+ const response = await fetch(`${this.endpoint}/${id}`, {
2448
+ method: "DELETE",
2449
+ headers: this._getHeaders()
2450
+ });
2451
+ if (!response.ok && response.status !== 204) {
2452
+ await this._handleResponse(response);
2453
+ }
2454
+ this._setState({
2455
+ items: this._state.items.filter((i) => i.id !== id),
2456
+ selectedItem: this._state.selectedItem?.id === id ? null : this._state.selectedItem,
2457
+ loading: false
2458
+ });
2459
+ return true;
2460
+ } catch (error) {
2461
+ this._setState({ loading: false, error: error.message });
2462
+ throw error;
2463
+ }
2464
+ }
2465
+ select(item) {
2466
+ this._setState({ selectedItem: item });
2467
+ }
2468
+ clearSelection() {
2469
+ this._setState({ selectedItem: null });
2470
+ }
2471
+ clearError() {
2472
+ this._setState({ error: null });
2473
+ }
2474
+ reset() {
2475
+ this._setState({
2476
+ items: [],
2477
+ selectedItem: null,
2478
+ loading: false,
2479
+ error: null,
2480
+ pagination: {
2481
+ page: 1,
2482
+ pageSize: 25,
2483
+ total: 0,
2484
+ totalPages: 0,
2485
+ hasNext: false,
2486
+ hasPrev: false
2487
+ }
2488
+ });
2489
+ }
2490
+ setPageSize(pageSize) {
2491
+ this._setState({
2492
+ pagination: {
2493
+ ...this._state.pagination,
2494
+ pageSize
2495
+ }
2496
+ });
2497
+ }
2498
+ };
2499
+ var NativeBaseStore_default = NativeBaseStore;
2500
+ export {
2501
+ NativeAuthContext,
2502
+ NativeAuthProvider,
2503
+ NativeBaseStore,
2504
+ NativeDetail,
2505
+ NativeExtensionRegistry_default as NativeExtensionRegistry,
2506
+ NativeForm,
2507
+ NativeGrid,
2508
+ NativeJsonGrid,
2509
+ NativeJsonView,
2510
+ NativeJsonViewContext,
2511
+ NativeShell,
2512
+ NativeStackLayout,
2513
+ NativeStoreContext,
2514
+ NativeStoreProvider,
2515
+ NativeTabLayout,
2516
+ NativeViewComponent,
2517
+ nativeExtensionRegistry,
2518
+ useNativeAuth,
2519
+ useNativeJsonView,
2520
+ useNativeStore
2521
+ };
2522
+ //# sourceMappingURL=index.js.map