@object-ui/plugin-form 0.3.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ObjectQL
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,256 @@
1
+ # @object-ui/plugin-form
2
+
3
+ Form plugin for Object UI - Advanced form components with validation, multi-step forms, and field-level control.
4
+
5
+ ## Features
6
+
7
+ - **Form Builder** - Create complex forms from schemas
8
+ - **Validation** - Built-in validation with error messages
9
+ - **Multi-Step Forms** - Wizard-style multi-step forms
10
+ - **Field Types** - Support for all standard field types
11
+ - **Form State** - Automatic form state management
12
+ - **Customizable** - Tailwind CSS styling support
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pnpm add @object-ui/plugin-form
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ### Automatic Registration (Side-Effect Import)
23
+
24
+ ```typescript
25
+ // In your app entry point (e.g., App.tsx or main.tsx)
26
+ import '@object-ui/plugin-form';
27
+
28
+ // Now you can use form types in your schemas
29
+ const schema = {
30
+ type: 'form',
31
+ fields: [
32
+ { name: 'email', type: 'input', label: 'Email', required: true },
33
+ { name: 'password', type: 'input', inputType: 'password', label: 'Password', required: true }
34
+ ]
35
+ };
36
+ ```
37
+
38
+ ### Manual Registration
39
+
40
+ ```typescript
41
+ import { formComponents } from '@object-ui/plugin-form';
42
+ import { ComponentRegistry } from '@object-ui/core';
43
+
44
+ // Register form components
45
+ Object.entries(formComponents).forEach(([type, component]) => {
46
+ ComponentRegistry.register(type, component);
47
+ });
48
+ ```
49
+
50
+ ## Schema API
51
+
52
+ ### Form
53
+
54
+ Complete form with fields and validation:
55
+
56
+ ```typescript
57
+ {
58
+ type: 'form',
59
+ fields: FormField[],
60
+ submitLabel?: string,
61
+ cancelLabel?: string,
62
+ onSubmit?: (data) => void,
63
+ onCancel?: () => void,
64
+ className?: string
65
+ }
66
+ ```
67
+
68
+ ### Form Field
69
+
70
+ Individual form field configuration:
71
+
72
+ ```typescript
73
+ interface FormField {
74
+ name: string;
75
+ type: string; // 'input', 'select', 'checkbox', etc.
76
+ label: string;
77
+ placeholder?: string;
78
+ required?: boolean;
79
+ validation?: ValidationRule[];
80
+ defaultValue?: any;
81
+ disabled?: boolean;
82
+ className?: string;
83
+ }
84
+ ```
85
+
86
+ ## Examples
87
+
88
+ ### Basic Form
89
+
90
+ ```typescript
91
+ const schema = {
92
+ type: 'form',
93
+ fields: [
94
+ {
95
+ name: 'name',
96
+ type: 'input',
97
+ label: 'Full Name',
98
+ placeholder: 'Enter your name',
99
+ required: true
100
+ },
101
+ {
102
+ name: 'email',
103
+ type: 'input',
104
+ inputType: 'email',
105
+ label: 'Email Address',
106
+ required: true,
107
+ validation: [
108
+ { type: 'email', message: 'Invalid email format' }
109
+ ]
110
+ },
111
+ {
112
+ name: 'country',
113
+ type: 'select',
114
+ label: 'Country',
115
+ options: [
116
+ { label: 'United States', value: 'us' },
117
+ { label: 'Canada', value: 'ca' },
118
+ { label: 'United Kingdom', value: 'uk' }
119
+ ]
120
+ },
121
+ {
122
+ name: 'subscribe',
123
+ type: 'checkbox',
124
+ label: 'Subscribe to newsletter'
125
+ }
126
+ ],
127
+ submitLabel: 'Register',
128
+ onSubmit: (data) => {
129
+ console.log('Form submitted:', data);
130
+ }
131
+ };
132
+ ```
133
+
134
+ ### Multi-Step Form
135
+
136
+ ```typescript
137
+ const schema = {
138
+ type: 'multi-step-form',
139
+ steps: [
140
+ {
141
+ title: 'Personal Info',
142
+ fields: [
143
+ { name: 'firstName', type: 'input', label: 'First Name', required: true },
144
+ { name: 'lastName', type: 'input', label: 'Last Name', required: true }
145
+ ]
146
+ },
147
+ {
148
+ title: 'Contact Info',
149
+ fields: [
150
+ { name: 'email', type: 'input', inputType: 'email', label: 'Email', required: true },
151
+ { name: 'phone', type: 'input', inputType: 'tel', label: 'Phone' }
152
+ ]
153
+ },
154
+ {
155
+ title: 'Review',
156
+ fields: []
157
+ }
158
+ ],
159
+ onSubmit: (data) => {
160
+ console.log('Multi-step form completed:', data);
161
+ }
162
+ };
163
+ ```
164
+
165
+ ### Form with Validation
166
+
167
+ ```typescript
168
+ const schema = {
169
+ type: 'form',
170
+ fields: [
171
+ {
172
+ name: 'username',
173
+ type: 'input',
174
+ label: 'Username',
175
+ required: true,
176
+ validation: [
177
+ { type: 'minLength', value: 3, message: 'Username must be at least 3 characters' },
178
+ { type: 'maxLength', value: 20, message: 'Username must be less than 20 characters' },
179
+ { type: 'pattern', value: '^[a-zA-Z0-9_]+$', message: 'Only letters, numbers, and underscores' }
180
+ ]
181
+ },
182
+ {
183
+ name: 'password',
184
+ type: 'input',
185
+ inputType: 'password',
186
+ label: 'Password',
187
+ required: true,
188
+ validation: [
189
+ { type: 'minLength', value: 8, message: 'Password must be at least 8 characters' },
190
+ { type: 'pattern', value: '(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])', message: 'Must contain uppercase, lowercase, and number' }
191
+ ]
192
+ }
193
+ ]
194
+ };
195
+ ```
196
+
197
+ ## Integration with Data Sources
198
+
199
+ Connect forms to backend APIs:
200
+
201
+ ```typescript
202
+ import { createObjectStackAdapter } from '@object-ui/data-objectstack';
203
+
204
+ const dataSource = createObjectStackAdapter({
205
+ baseUrl: 'https://api.example.com',
206
+ token: 'your-auth-token'
207
+ });
208
+
209
+ const schema = {
210
+ type: 'form',
211
+ dataSource,
212
+ resource: 'users',
213
+ fields: [/* fields */],
214
+ onSubmit: async (data) => {
215
+ await dataSource.create('users', data);
216
+ }
217
+ };
218
+ ```
219
+
220
+ ## TypeScript Support
221
+
222
+ ```typescript
223
+ import type { FormSchema, FormField } from '@object-ui/plugin-form';
224
+
225
+ const emailField: FormField = {
226
+ name: 'email',
227
+ type: 'input',
228
+ inputType: 'email',
229
+ label: 'Email',
230
+ required: true
231
+ };
232
+
233
+ const loginForm: FormSchema = {
234
+ type: 'form',
235
+ fields: [emailField],
236
+ submitLabel: 'Sign In'
237
+ };
238
+ ```
239
+
240
+ ## Field Components
241
+
242
+ The plugin includes these field components:
243
+ - Text input
244
+ - Email input
245
+ - Password input
246
+ - Number input
247
+ - Textarea
248
+ - Select dropdown
249
+ - Checkbox
250
+ - Radio group
251
+ - Date picker
252
+ - File upload
253
+
254
+ ## License
255
+
256
+ MIT
@@ -0,0 +1,2 @@
1
+ export * from './plugin-form/src/index'
2
+ export {}
package/dist/index.js ADDED
@@ -0,0 +1,394 @@
1
+ import ie, { useState as O, useEffect as F, useCallback as X } from "react";
2
+ import { ComponentRegistry as Z } from "@object-ui/core";
3
+ import { SchemaRenderer as ae } from "@object-ui/react";
4
+ import { buildValidationRules as le, mapFieldTypeToFormType as se, formatFileSize as ue, evaluateCondition as ce } from "@object-ui/fields";
5
+ var C = { exports: {} }, k = {};
6
+ var H;
7
+ function fe() {
8
+ if (H) return k;
9
+ H = 1;
10
+ var r = /* @__PURE__ */ Symbol.for("react.transitional.element"), u = /* @__PURE__ */ Symbol.for("react.fragment");
11
+ function m(E, d, p) {
12
+ var v = null;
13
+ if (p !== void 0 && (v = "" + p), d.key !== void 0 && (v = "" + d.key), "key" in d) {
14
+ p = {};
15
+ for (var b in d)
16
+ b !== "key" && (p[b] = d[b]);
17
+ } else p = d;
18
+ return d = p.ref, {
19
+ $$typeof: r,
20
+ type: E,
21
+ key: v,
22
+ ref: d !== void 0 ? d : null,
23
+ props: p
24
+ };
25
+ }
26
+ return k.Fragment = u, k.jsx = m, k.jsxs = m, k;
27
+ }
28
+ var S = {};
29
+ var B;
30
+ function de() {
31
+ return B || (B = 1, process.env.NODE_ENV !== "production" && (function() {
32
+ function r(e) {
33
+ if (e == null) return null;
34
+ if (typeof e == "function")
35
+ return e.$$typeof === te ? null : e.displayName || e.name || null;
36
+ if (typeof e == "string") return e;
37
+ switch (e) {
38
+ case c:
39
+ return "Fragment";
40
+ case w:
41
+ return "Profiler";
42
+ case a:
43
+ return "StrictMode";
44
+ case o:
45
+ return "Suspense";
46
+ case j:
47
+ return "SuspenseList";
48
+ case re:
49
+ return "Activity";
50
+ }
51
+ if (typeof e == "object")
52
+ switch (typeof e.tag == "number" && console.error(
53
+ "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
54
+ ), e.$$typeof) {
55
+ case I:
56
+ return "Portal";
57
+ case D:
58
+ return e.displayName || "Context";
59
+ case t:
60
+ return (e._context.displayName || "Context") + ".Consumer";
61
+ case A:
62
+ var n = e.render;
63
+ return e = e.displayName, e || (e = n.displayName || n.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
64
+ case ee:
65
+ return n = e.displayName || null, n !== null ? n : r(e.type) || "Memo";
66
+ case Y:
67
+ n = e._payload, e = e._init;
68
+ try {
69
+ return r(e(n));
70
+ } catch {
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+ function u(e) {
76
+ return "" + e;
77
+ }
78
+ function m(e) {
79
+ try {
80
+ u(e);
81
+ var n = !1;
82
+ } catch {
83
+ n = !0;
84
+ }
85
+ if (n) {
86
+ n = console;
87
+ var i = n.error, l = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
88
+ return i.call(
89
+ n,
90
+ "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
91
+ l
92
+ ), u(e);
93
+ }
94
+ }
95
+ function E(e) {
96
+ if (e === c) return "<>";
97
+ if (typeof e == "object" && e !== null && e.$$typeof === Y)
98
+ return "<...>";
99
+ try {
100
+ var n = r(e);
101
+ return n ? "<" + n + ">" : "<...>";
102
+ } catch {
103
+ return "<...>";
104
+ }
105
+ }
106
+ function d() {
107
+ var e = $.A;
108
+ return e === null ? null : e.getOwner();
109
+ }
110
+ function p() {
111
+ return Error("react-stack-top-frame");
112
+ }
113
+ function v(e) {
114
+ if (z.call(e, "key")) {
115
+ var n = Object.getOwnPropertyDescriptor(e, "key").get;
116
+ if (n && n.isReactWarning) return !1;
117
+ }
118
+ return e.key !== void 0;
119
+ }
120
+ function b(e, n) {
121
+ function i() {
122
+ M || (M = !0, console.error(
123
+ "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
124
+ n
125
+ ));
126
+ }
127
+ i.isReactWarning = !0, Object.defineProperty(e, "key", {
128
+ get: i,
129
+ configurable: !0
130
+ });
131
+ }
132
+ function h() {
133
+ var e = r(this.type);
134
+ return W[e] || (W[e] = !0, console.error(
135
+ "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
136
+ )), e = this.props.ref, e !== void 0 ? e : null;
137
+ }
138
+ function _(e, n, i, l, P, V) {
139
+ var s = i.ref;
140
+ return e = {
141
+ $$typeof: N,
142
+ type: e,
143
+ key: n,
144
+ props: i,
145
+ _owner: l
146
+ }, (s !== void 0 ? s : null) !== null ? Object.defineProperty(e, "ref", {
147
+ enumerable: !1,
148
+ get: h
149
+ }) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
150
+ configurable: !1,
151
+ enumerable: !1,
152
+ writable: !0,
153
+ value: 0
154
+ }), Object.defineProperty(e, "_debugInfo", {
155
+ configurable: !1,
156
+ enumerable: !1,
157
+ writable: !0,
158
+ value: null
159
+ }), Object.defineProperty(e, "_debugStack", {
160
+ configurable: !1,
161
+ enumerable: !1,
162
+ writable: !0,
163
+ value: P
164
+ }), Object.defineProperty(e, "_debugTask", {
165
+ configurable: !1,
166
+ enumerable: !1,
167
+ writable: !0,
168
+ value: V
169
+ }), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
170
+ }
171
+ function g(e, n, i, l, P, V) {
172
+ var s = n.children;
173
+ if (s !== void 0)
174
+ if (l)
175
+ if (ne(s)) {
176
+ for (l = 0; l < s.length; l++)
177
+ R(s[l]);
178
+ Object.freeze && Object.freeze(s);
179
+ } else
180
+ console.error(
181
+ "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
182
+ );
183
+ else R(s);
184
+ if (z.call(n, "key")) {
185
+ s = r(e);
186
+ var x = Object.keys(n).filter(function(oe) {
187
+ return oe !== "key";
188
+ });
189
+ l = 0 < x.length ? "{key: someKey, " + x.join(": ..., ") + ": ...}" : "{key: someKey}", G[s + l] || (x = 0 < x.length ? "{" + x.join(": ..., ") + ": ...}" : "{}", console.error(
190
+ `A props object containing a "key" prop is being spread into JSX:
191
+ let props = %s;
192
+ <%s {...props} />
193
+ React keys must be passed directly to JSX without using spread:
194
+ let props = %s;
195
+ <%s key={someKey} {...props} />`,
196
+ l,
197
+ s,
198
+ x,
199
+ s
200
+ ), G[s + l] = !0);
201
+ }
202
+ if (s = null, i !== void 0 && (m(i), s = "" + i), v(n) && (m(n.key), s = "" + n.key), "key" in n) {
203
+ i = {};
204
+ for (var q in n)
205
+ q !== "key" && (i[q] = n[q]);
206
+ } else i = n;
207
+ return s && b(
208
+ i,
209
+ typeof e == "function" ? e.displayName || e.name || "Unknown" : e
210
+ ), _(
211
+ e,
212
+ s,
213
+ i,
214
+ d(),
215
+ P,
216
+ V
217
+ );
218
+ }
219
+ function R(e) {
220
+ f(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === Y && (e._payload.status === "fulfilled" ? f(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
221
+ }
222
+ function f(e) {
223
+ return typeof e == "object" && e !== null && e.$$typeof === N;
224
+ }
225
+ var T = ie, N = /* @__PURE__ */ Symbol.for("react.transitional.element"), I = /* @__PURE__ */ Symbol.for("react.portal"), c = /* @__PURE__ */ Symbol.for("react.fragment"), a = /* @__PURE__ */ Symbol.for("react.strict_mode"), w = /* @__PURE__ */ Symbol.for("react.profiler"), t = /* @__PURE__ */ Symbol.for("react.consumer"), D = /* @__PURE__ */ Symbol.for("react.context"), A = /* @__PURE__ */ Symbol.for("react.forward_ref"), o = /* @__PURE__ */ Symbol.for("react.suspense"), j = /* @__PURE__ */ Symbol.for("react.suspense_list"), ee = /* @__PURE__ */ Symbol.for("react.memo"), Y = /* @__PURE__ */ Symbol.for("react.lazy"), re = /* @__PURE__ */ Symbol.for("react.activity"), te = /* @__PURE__ */ Symbol.for("react.client.reference"), $ = T.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, z = Object.prototype.hasOwnProperty, ne = Array.isArray, L = console.createTask ? console.createTask : function() {
226
+ return null;
227
+ };
228
+ T = {
229
+ react_stack_bottom_frame: function(e) {
230
+ return e();
231
+ }
232
+ };
233
+ var M, W = {}, U = T.react_stack_bottom_frame.bind(
234
+ T,
235
+ p
236
+ )(), J = L(E(p)), G = {};
237
+ S.Fragment = c, S.jsx = function(e, n, i) {
238
+ var l = 1e4 > $.recentlyCreatedOwnerStacks++;
239
+ return g(
240
+ e,
241
+ n,
242
+ i,
243
+ !1,
244
+ l ? Error("react-stack-top-frame") : U,
245
+ l ? L(E(e)) : J
246
+ );
247
+ }, S.jsxs = function(e, n, i) {
248
+ var l = 1e4 > $.recentlyCreatedOwnerStacks++;
249
+ return g(
250
+ e,
251
+ n,
252
+ i,
253
+ !0,
254
+ l ? Error("react-stack-top-frame") : U,
255
+ l ? L(E(e)) : J
256
+ );
257
+ };
258
+ })()), S;
259
+ }
260
+ var Q;
261
+ function pe() {
262
+ return Q || (Q = 1, process.env.NODE_ENV === "production" ? C.exports = fe() : C.exports = de()), C.exports;
263
+ }
264
+ var y = pe();
265
+ const me = ({
266
+ schema: r,
267
+ dataSource: u
268
+ }) => {
269
+ const [m, E] = O(null), [d, p] = O([]), [v, b] = O(null), [h, _] = O(!0), [g, R] = O(null), f = r.customFields && r.customFields.length > 0;
270
+ F(() => {
271
+ f && (b(r.initialData || r.initialValues || {}), _(!1));
272
+ }, [f, r.initialData, r.initialValues]), F(() => {
273
+ const c = async () => {
274
+ try {
275
+ if (!u)
276
+ throw new Error("DataSource is required when using ObjectQL schema fetching (inline fields not provided)");
277
+ const a = await u.getObjectSchema(r.objectName);
278
+ E(a);
279
+ } catch (a) {
280
+ console.error("Failed to fetch object schema:", a), R(a);
281
+ }
282
+ };
283
+ f ? E({
284
+ name: r.objectName,
285
+ fields: {}
286
+ }) : r.objectName && u && c();
287
+ }, [r.objectName, u, f]), F(() => {
288
+ m && !f && (async () => {
289
+ if (!r.recordId || r.mode === "create") {
290
+ b(r.initialData || r.initialValues || {});
291
+ return;
292
+ }
293
+ if (!f) {
294
+ if (!u) {
295
+ R(new Error("DataSource is required for fetching record data (inline data not provided)")), _(!1);
296
+ return;
297
+ }
298
+ _(!0);
299
+ try {
300
+ const a = await u.findOne(r.objectName, r.recordId);
301
+ b(a);
302
+ } catch (a) {
303
+ console.error("Failed to fetch record:", a), R(a);
304
+ } finally {
305
+ _(!1);
306
+ }
307
+ }
308
+ })();
309
+ }, [r.objectName, r.recordId, r.mode, r.initialValues, r.initialData, u, m, f]), F(() => {
310
+ if (f && r.customFields) {
311
+ p(r.customFields), _(!1);
312
+ return;
313
+ }
314
+ if (!m) return;
315
+ const c = [];
316
+ (r.fields || Object.keys(m.fields || {})).forEach((w) => {
317
+ const t = m.fields?.[w];
318
+ if (!t) return;
319
+ const D = !t.permissions || t.permissions.write !== !1;
320
+ if (r.mode !== "view" && !D) return;
321
+ const A = r.customFields?.find((o) => o.name === w);
322
+ if (A)
323
+ c.push(A);
324
+ else {
325
+ const o = {
326
+ name: w,
327
+ label: t.label || w,
328
+ type: se(t.type),
329
+ required: t.required || !1,
330
+ disabled: r.readOnly || r.mode === "view" || t.readonly,
331
+ placeholder: t.placeholder,
332
+ description: t.help || t.description,
333
+ validation: le(t)
334
+ };
335
+ if ((t.type === "select" || t.type === "lookup" || t.type === "master_detail") && (o.options = t.options || [], o.multiple = t.multiple), (t.type === "number" || t.type === "currency" || t.type === "percent") && (o.min = t.min, o.max = t.max, o.step = t.precision ? Math.pow(10, -t.precision) : void 0), (t.type === "text" || t.type === "textarea" || t.type === "markdown" || t.type === "html") && (o.maxLength = t.max_length, o.minLength = t.min_length), (t.type === "file" || t.type === "image") && (o.multiple = t.multiple, o.accept = t.accept ? t.accept.join(",") : void 0, t.max_size)) {
336
+ const j = `Max size: ${ue(t.max_size)}`;
337
+ o.description = o.description ? `${o.description} (${j})` : j;
338
+ }
339
+ t.type === "email" && (o.inputType = "email"), t.type === "phone" && (o.inputType = "tel"), t.type === "url" && (o.inputType = "url"), t.type === "password" && (o.inputType = "password"), t.type === "time" && (o.inputType = "time"), (t.type === "formula" || t.type === "summary" || t.type === "auto_number") && (o.disabled = !0), t.visible_on && (o.visible = (j) => ce(t.visible_on, j)), c.push(o);
340
+ }
341
+ }), p(c), _(!1);
342
+ }, [m, r.fields, r.customFields, r.readOnly, r.mode, f]);
343
+ const T = X(async (c) => {
344
+ if (f && !u)
345
+ return r.onSuccess && await r.onSuccess(c), c;
346
+ if (!u)
347
+ throw new Error("DataSource is required for form submission (inline mode not configured)");
348
+ try {
349
+ let a;
350
+ if (r.mode === "create")
351
+ a = await u.create(r.objectName, c);
352
+ else if (r.mode === "edit" && r.recordId)
353
+ a = await u.update(r.objectName, r.recordId, c);
354
+ else
355
+ throw new Error("Invalid form mode or missing record ID");
356
+ return r.onSuccess && await r.onSuccess(a), a;
357
+ } catch (a) {
358
+ throw console.error("Failed to submit form:", a), r.onError && r.onError(a), a;
359
+ }
360
+ }, [r, u, f]), N = X(() => {
361
+ r.onCancel && r.onCancel();
362
+ }, [r]);
363
+ if (g)
364
+ return /* @__PURE__ */ y.jsxs("div", { className: "p-4 border border-red-300 bg-red-50 rounded-md", children: [
365
+ /* @__PURE__ */ y.jsx("h3", { className: "text-red-800 font-semibold", children: "Error loading form" }),
366
+ /* @__PURE__ */ y.jsx("p", { className: "text-red-600 text-sm mt-1", children: g.message })
367
+ ] });
368
+ if (h)
369
+ return /* @__PURE__ */ y.jsxs("div", { className: "p-8 text-center", children: [
370
+ /* @__PURE__ */ y.jsx("div", { className: "inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" }),
371
+ /* @__PURE__ */ y.jsx("p", { className: "mt-2 text-sm text-gray-600", children: "Loading form..." })
372
+ ] });
373
+ const I = {
374
+ type: "form",
375
+ fields: d,
376
+ layout: r.layout === "vertical" || r.layout === "horizontal" ? r.layout : "vertical",
377
+ columns: r.columns,
378
+ submitLabel: r.submitText || (r.mode === "create" ? "Create" : "Update"),
379
+ cancelLabel: r.cancelText,
380
+ showSubmit: r.showSubmit !== !1 && r.mode !== "view",
381
+ showCancel: r.showCancel !== !1,
382
+ resetOnSubmit: r.showReset,
383
+ defaultValues: v,
384
+ onSubmit: T,
385
+ onCancel: N,
386
+ className: r.className
387
+ };
388
+ return /* @__PURE__ */ y.jsx("div", { className: "w-full", children: /* @__PURE__ */ y.jsx(ae, { schema: I }) });
389
+ }, K = ({ schema: r }) => /* @__PURE__ */ y.jsx(me, { schema: r });
390
+ Z.register("object-form", K);
391
+ Z.register("form", K);
392
+ export {
393
+ me as ObjectForm
394
+ };
@@ -0,0 +1,6 @@
1
+ (function(y,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("react"),require("@object-ui/core"),require("@object-ui/react"),require("@object-ui/fields")):typeof define=="function"&&define.amd?define(["exports","react","@object-ui/core","@object-ui/react","@object-ui/fields"],c):(y=typeof globalThis<"u"?globalThis:y||self,c(y.ObjectUIPluginForm={},y.React,y.core,y.react,y.fields))})(this,(function(y,c,W,re,P){"use strict";var A={exports:{}},S={};var J;function te(){if(J)return S;J=1;var r=Symbol.for("react.transitional.element"),u=Symbol.for("react.fragment");function b(v,p,m){var T=null;if(m!==void 0&&(T=""+m),p.key!==void 0&&(T=""+p.key),"key"in p){m={};for(var _ in p)_!=="key"&&(m[_]=p[_])}else m=p;return p=m.ref,{$$typeof:r,type:v,key:T,ref:p!==void 0?p:null,props:m}}return S.Fragment=u,S.jsx=b,S.jsxs=b,S}var k={};var G;function ne(){return G||(G=1,process.env.NODE_ENV!=="production"&&(function(){function r(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===le?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case f:return"Fragment";case x:return"Profiler";case a:return"StrictMode";case o:return"Suspense";case g:return"SuspenseList";case ae:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case D:return"Portal";case Y:return e.displayName||"Context";case t:return(e._context.displayName||"Context")+".Consumer";case h:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ie:return n=e.displayName||null,n!==null?n:r(e.type)||"Memo";case L:n=e._payload,e=e._init;try{return r(e(n))}catch{}}return null}function u(e){return""+e}function b(e){try{u(e);var n=!1}catch{n=!0}if(n){n=console;var i=n.error,l=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",l),u(e)}}function v(e){if(e===f)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===L)return"<...>";try{var n=r(e);return n?"<"+n+">":"<...>"}catch{return"<...>"}}function p(){var e=M.A;return e===null?null:e.getOwner()}function m(){return Error("react-stack-top-frame")}function T(e){if(B.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function _(e,n){function i(){Q||(Q=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",n))}i.isReactWarning=!0,Object.defineProperty(e,"key",{get:i,configurable:!0})}function I(){var e=r(this.type);return Z[e]||(Z[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function R(e,n,i,l,C,z){var s=i.ref;return e={$$typeof:F,type:e,key:n,props:i,_owner:l},(s!==void 0?s:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:I}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:C}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:z}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function N(e,n,i,l,C,z){var s=n.children;if(s!==void 0)if(l)if(se(s)){for(l=0;l<s.length;l++)j(s[l]);Object.freeze&&Object.freeze(s)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else j(s);if(B.call(n,"key")){s=r(e);var O=Object.keys(n).filter(function(ue){return ue!=="key"});l=0<O.length?"{key: someKey, "+O.join(": ..., ")+": ...}":"{key: someKey}",ee[s+l]||(O=0<O.length?"{"+O.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
+ let props = %s;
3
+ <%s {...props} />
4
+ React keys must be passed directly to JSX without using spread:
5
+ let props = %s;
6
+ <%s key={someKey} {...props} />`,l,s,O,s),ee[s+l]=!0)}if(s=null,i!==void 0&&(b(i),s=""+i),T(n)&&(b(n.key),s=""+n.key),"key"in n){i={};for(var U in n)U!=="key"&&(i[U]=n[U])}else i=n;return s&&_(i,typeof e=="function"?e.displayName||e.name||"Unknown":e),R(e,s,i,p(),C,z)}function j(e){d(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===L&&(e._payload.status==="fulfilled"?d(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function d(e){return typeof e=="object"&&e!==null&&e.$$typeof===F}var w=c,F=Symbol.for("react.transitional.element"),D=Symbol.for("react.portal"),f=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),t=Symbol.for("react.consumer"),Y=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),o=Symbol.for("react.suspense"),g=Symbol.for("react.suspense_list"),ie=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),ae=Symbol.for("react.activity"),le=Symbol.for("react.client.reference"),M=w.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B=Object.prototype.hasOwnProperty,se=Array.isArray,V=console.createTask?console.createTask:function(){return null};w={react_stack_bottom_frame:function(e){return e()}};var Q,Z={},K=w.react_stack_bottom_frame.bind(w,m)(),$=V(v(m)),ee={};k.Fragment=f,k.jsx=function(e,n,i){var l=1e4>M.recentlyCreatedOwnerStacks++;return N(e,n,i,!1,l?Error("react-stack-top-frame"):K,l?V(v(e)):$)},k.jsxs=function(e,n,i){var l=1e4>M.recentlyCreatedOwnerStacks++;return N(e,n,i,!0,l?Error("react-stack-top-frame"):K,l?V(v(e)):$)}})()),k}var q;function oe(){return q||(q=1,process.env.NODE_ENV==="production"?A.exports=te():A.exports=ne()),A.exports}var E=oe();const X=({schema:r,dataSource:u})=>{const[b,v]=c.useState(null),[p,m]=c.useState([]),[T,_]=c.useState(null),[I,R]=c.useState(!0),[N,j]=c.useState(null),d=r.customFields&&r.customFields.length>0;c.useEffect(()=>{d&&(_(r.initialData||r.initialValues||{}),R(!1))},[d,r.initialData,r.initialValues]),c.useEffect(()=>{const f=async()=>{try{if(!u)throw new Error("DataSource is required when using ObjectQL schema fetching (inline fields not provided)");const a=await u.getObjectSchema(r.objectName);v(a)}catch(a){console.error("Failed to fetch object schema:",a),j(a)}};d?v({name:r.objectName,fields:{}}):r.objectName&&u&&f()},[r.objectName,u,d]),c.useEffect(()=>{b&&!d&&(async()=>{if(!r.recordId||r.mode==="create"){_(r.initialData||r.initialValues||{});return}if(!d){if(!u){j(new Error("DataSource is required for fetching record data (inline data not provided)")),R(!1);return}R(!0);try{const a=await u.findOne(r.objectName,r.recordId);_(a)}catch(a){console.error("Failed to fetch record:",a),j(a)}finally{R(!1)}}})()},[r.objectName,r.recordId,r.mode,r.initialValues,r.initialData,u,b,d]),c.useEffect(()=>{if(d&&r.customFields){m(r.customFields),R(!1);return}if(!b)return;const f=[];(r.fields||Object.keys(b.fields||{})).forEach(x=>{const t=b.fields?.[x];if(!t)return;const Y=!t.permissions||t.permissions.write!==!1;if(r.mode!=="view"&&!Y)return;const h=r.customFields?.find(o=>o.name===x);if(h)f.push(h);else{const o={name:x,label:t.label||x,type:P.mapFieldTypeToFormType(t.type),required:t.required||!1,disabled:r.readOnly||r.mode==="view"||t.readonly,placeholder:t.placeholder,description:t.help||t.description,validation:P.buildValidationRules(t)};if((t.type==="select"||t.type==="lookup"||t.type==="master_detail")&&(o.options=t.options||[],o.multiple=t.multiple),(t.type==="number"||t.type==="currency"||t.type==="percent")&&(o.min=t.min,o.max=t.max,o.step=t.precision?Math.pow(10,-t.precision):void 0),(t.type==="text"||t.type==="textarea"||t.type==="markdown"||t.type==="html")&&(o.maxLength=t.max_length,o.minLength=t.min_length),(t.type==="file"||t.type==="image")&&(o.multiple=t.multiple,o.accept=t.accept?t.accept.join(","):void 0,t.max_size)){const g=`Max size: ${P.formatFileSize(t.max_size)}`;o.description=o.description?`${o.description} (${g})`:g}t.type==="email"&&(o.inputType="email"),t.type==="phone"&&(o.inputType="tel"),t.type==="url"&&(o.inputType="url"),t.type==="password"&&(o.inputType="password"),t.type==="time"&&(o.inputType="time"),(t.type==="formula"||t.type==="summary"||t.type==="auto_number")&&(o.disabled=!0),t.visible_on&&(o.visible=g=>P.evaluateCondition(t.visible_on,g)),f.push(o)}}),m(f),R(!1)},[b,r.fields,r.customFields,r.readOnly,r.mode,d]);const w=c.useCallback(async f=>{if(d&&!u)return r.onSuccess&&await r.onSuccess(f),f;if(!u)throw new Error("DataSource is required for form submission (inline mode not configured)");try{let a;if(r.mode==="create")a=await u.create(r.objectName,f);else if(r.mode==="edit"&&r.recordId)a=await u.update(r.objectName,r.recordId,f);else throw new Error("Invalid form mode or missing record ID");return r.onSuccess&&await r.onSuccess(a),a}catch(a){throw console.error("Failed to submit form:",a),r.onError&&r.onError(a),a}},[r,u,d]),F=c.useCallback(()=>{r.onCancel&&r.onCancel()},[r]);if(N)return E.jsxs("div",{className:"p-4 border border-red-300 bg-red-50 rounded-md",children:[E.jsx("h3",{className:"text-red-800 font-semibold",children:"Error loading form"}),E.jsx("p",{className:"text-red-600 text-sm mt-1",children:N.message})]});if(I)return E.jsxs("div",{className:"p-8 text-center",children:[E.jsx("div",{className:"inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"}),E.jsx("p",{className:"mt-2 text-sm text-gray-600",children:"Loading form..."})]});const D={type:"form",fields:p,layout:r.layout==="vertical"||r.layout==="horizontal"?r.layout:"vertical",columns:r.columns,submitLabel:r.submitText||(r.mode==="create"?"Create":"Update"),cancelLabel:r.cancelText,showSubmit:r.showSubmit!==!1&&r.mode!=="view",showCancel:r.showCancel!==!1,resetOnSubmit:r.showReset,defaultValues:T,onSubmit:w,onCancel:F,className:r.className};return E.jsx("div",{className:"w-full",children:E.jsx(re.SchemaRenderer,{schema:D})})},H=({schema:r})=>E.jsx(X,{schema:r});W.ComponentRegistry.register("object-form",H),W.ComponentRegistry.register("form",H),y.ObjectForm=X,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
@@ -0,0 +1,36 @@
1
+ import { default as React } from 'react';
2
+ import { ObjectFormSchema, DataSource } from '../../types/src';
3
+ export interface ObjectFormProps {
4
+ /**
5
+ * The schema configuration for the form
6
+ */
7
+ schema: ObjectFormSchema;
8
+ /**
9
+ * Data source (ObjectQL or ObjectStack adapter)
10
+ * Optional when using inline field definitions (customFields or fields array with field objects)
11
+ */
12
+ dataSource?: DataSource;
13
+ /**
14
+ * Additional CSS class
15
+ */
16
+ className?: string;
17
+ }
18
+ /**
19
+ * ObjectForm Component
20
+ *
21
+ * Renders a form for an ObjectQL object with automatic schema integration.
22
+ *
23
+ * @example
24
+ * ```tsx
25
+ * <ObjectForm
26
+ * schema={{
27
+ * type: 'object-form',
28
+ * objectName: 'users',
29
+ * mode: 'create',
30
+ * fields: ['name', 'email', 'status']
31
+ * }}
32
+ * dataSource={dataSource}
33
+ * />
34
+ * ```
35
+ */
36
+ export declare const ObjectForm: React.FC<ObjectFormProps>;
@@ -0,0 +1,3 @@
1
+ import { ObjectForm } from './ObjectForm';
2
+ export { ObjectForm };
3
+ export type { ObjectFormProps } from './ObjectForm';
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@object-ui/plugin-form",
3
+ "version": "0.3.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "Form plugin for Object UI",
7
+ "main": "dist/index.umd.cjs",
8
+ "module": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.umd.cjs"
15
+ }
16
+ },
17
+ "dependencies": {
18
+ "lucide-react": "^0.563.0",
19
+ "@object-ui/components": "0.3.0",
20
+ "@object-ui/core": "0.3.0",
21
+ "@object-ui/fields": "0.3.0",
22
+ "@object-ui/react": "0.3.0",
23
+ "@object-ui/types": "0.3.0"
24
+ },
25
+ "peerDependencies": {
26
+ "react": "^18.0.0 || ^19.0.0",
27
+ "react-dom": "^18.0.0 || ^19.0.0"
28
+ },
29
+ "devDependencies": {
30
+ "@vitejs/plugin-react": "^4.2.1",
31
+ "typescript": "^5.9.3",
32
+ "vite": "^7.3.1",
33
+ "vite-plugin-dts": "^4.5.4"
34
+ },
35
+ "scripts": {
36
+ "build": "vite build",
37
+ "test": "vitest run",
38
+ "lint": "eslint ."
39
+ }
40
+ }
@@ -0,0 +1,349 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ /**
10
+ * ObjectForm Component
11
+ *
12
+ * A smart form component that generates forms from ObjectQL object schemas.
13
+ * It automatically creates form fields based on object metadata.
14
+ */
15
+
16
+ import React, { useEffect, useState, useCallback } from 'react';
17
+ import type { ObjectFormSchema, FormField, FormSchema, DataSource } from '@object-ui/types';
18
+ import { SchemaRenderer } from '@object-ui/react';
19
+ import { mapFieldTypeToFormType, buildValidationRules, evaluateCondition, formatFileSize } from '@object-ui/fields';
20
+
21
+ export interface ObjectFormProps {
22
+ /**
23
+ * The schema configuration for the form
24
+ */
25
+ schema: ObjectFormSchema;
26
+
27
+ /**
28
+ * Data source (ObjectQL or ObjectStack adapter)
29
+ * Optional when using inline field definitions (customFields or fields array with field objects)
30
+ */
31
+ dataSource?: DataSource;
32
+
33
+ /**
34
+ * Additional CSS class
35
+ */
36
+ className?: string;
37
+ }
38
+
39
+ /**
40
+ * ObjectForm Component
41
+ *
42
+ * Renders a form for an ObjectQL object with automatic schema integration.
43
+ *
44
+ * @example
45
+ * ```tsx
46
+ * <ObjectForm
47
+ * schema={{
48
+ * type: 'object-form',
49
+ * objectName: 'users',
50
+ * mode: 'create',
51
+ * fields: ['name', 'email', 'status']
52
+ * }}
53
+ * dataSource={dataSource}
54
+ * />
55
+ * ```
56
+ */
57
+ export const ObjectForm: React.FC<ObjectFormProps> = ({
58
+ schema,
59
+ dataSource,
60
+ }) => {
61
+ const [objectSchema, setObjectSchema] = useState<any>(null);
62
+ const [formFields, setFormFields] = useState<FormField[]>([]);
63
+ const [initialData, setInitialData] = useState<any>(null);
64
+ const [loading, setLoading] = useState(true);
65
+ const [error, setError] = useState<Error | null>(null);
66
+
67
+ // Check if using inline fields (fields defined as objects, not just names)
68
+ const hasInlineFields = schema.customFields && schema.customFields.length > 0;
69
+
70
+ // Initialize with inline data if provided
71
+ useEffect(() => {
72
+ if (hasInlineFields) {
73
+ setInitialData(schema.initialData || schema.initialValues || {});
74
+ setLoading(false);
75
+ }
76
+ }, [hasInlineFields, schema.initialData, schema.initialValues]);
77
+
78
+ // Fetch object schema from ObjectQL/ObjectStack (skip if using inline fields)
79
+ useEffect(() => {
80
+ const fetchObjectSchema = async () => {
81
+ try {
82
+ if (!dataSource) {
83
+ throw new Error('DataSource is required when using ObjectQL schema fetching (inline fields not provided)');
84
+ }
85
+ const schemaData = await dataSource.getObjectSchema(schema.objectName);
86
+ setObjectSchema(schemaData);
87
+ } catch (err) {
88
+ console.error('Failed to fetch object schema:', err);
89
+ setError(err as Error);
90
+ }
91
+ };
92
+
93
+ // Skip fetching if we have inline fields
94
+ if (hasInlineFields) {
95
+ // Use a minimal schema for inline fields
96
+ setObjectSchema({
97
+ name: schema.objectName,
98
+ fields: {} as Record<string, any>,
99
+ });
100
+ } else if (schema.objectName && dataSource) {
101
+ fetchObjectSchema();
102
+ }
103
+ }, [schema.objectName, dataSource, hasInlineFields]);
104
+
105
+ // Fetch initial data for edit/view modes (skip if using inline data)
106
+ useEffect(() => {
107
+ const fetchInitialData = async () => {
108
+ if (!schema.recordId || schema.mode === 'create') {
109
+ setInitialData(schema.initialData || schema.initialValues || {});
110
+ return;
111
+ }
112
+
113
+ // Skip fetching if using inline data
114
+ if (hasInlineFields) {
115
+ return;
116
+ }
117
+
118
+ if (!dataSource) {
119
+ setError(new Error('DataSource is required for fetching record data (inline data not provided)'));
120
+ setLoading(false);
121
+ return;
122
+ }
123
+
124
+ setLoading(true);
125
+ try {
126
+ const data = await dataSource.findOne(schema.objectName, schema.recordId);
127
+ setInitialData(data);
128
+ } catch (err) {
129
+ console.error('Failed to fetch record:', err);
130
+ setError(err as Error);
131
+ } finally {
132
+ setLoading(false);
133
+ }
134
+ };
135
+
136
+ if (objectSchema && !hasInlineFields) {
137
+ fetchInitialData();
138
+ }
139
+ }, [schema.objectName, schema.recordId, schema.mode, schema.initialValues, schema.initialData, dataSource, objectSchema, hasInlineFields]);
140
+
141
+ // Generate form fields from object schema or inline fields
142
+ useEffect(() => {
143
+ // For inline fields, use them directly
144
+ if (hasInlineFields && schema.customFields) {
145
+ setFormFields(schema.customFields);
146
+ setLoading(false);
147
+ return;
148
+ }
149
+
150
+ if (!objectSchema) return;
151
+
152
+ const generatedFields: FormField[] = [];
153
+
154
+ // Determine which fields to include
155
+ const fieldsToShow = schema.fields || Object.keys(objectSchema.fields || {});
156
+
157
+ fieldsToShow.forEach((fieldName) => {
158
+ const field = objectSchema.fields?.[fieldName];
159
+ if (!field) return;
160
+
161
+ // Check field-level permissions for create/edit modes
162
+ const hasWritePermission = !field.permissions || field.permissions.write !== false;
163
+ if (schema.mode !== 'view' && !hasWritePermission) return; // Skip fields without write permission
164
+
165
+ // Check if there's a custom field configuration
166
+ const customField = schema.customFields?.find(f => f.name === fieldName);
167
+
168
+ if (customField) {
169
+ generatedFields.push(customField);
170
+ } else {
171
+ // Auto-generate field from schema
172
+ const formField: FormField = {
173
+ name: fieldName,
174
+ label: field.label || fieldName,
175
+ type: mapFieldTypeToFormType(field.type),
176
+ required: field.required || false,
177
+ disabled: schema.readOnly || schema.mode === 'view' || field.readonly,
178
+ placeholder: field.placeholder,
179
+ description: field.help || field.description,
180
+ validation: buildValidationRules(field),
181
+ };
182
+
183
+ // Add field-specific properties
184
+ if (field.type === 'select' || field.type === 'lookup' || field.type === 'master_detail') {
185
+ formField.options = field.options || [];
186
+ formField.multiple = field.multiple;
187
+ }
188
+
189
+ if (field.type === 'number' || field.type === 'currency' || field.type === 'percent') {
190
+ formField.min = field.min;
191
+ formField.max = field.max;
192
+ formField.step = field.precision ? Math.pow(10, -field.precision) : undefined;
193
+ }
194
+
195
+ if (field.type === 'text' || field.type === 'textarea' || field.type === 'markdown' || field.type === 'html') {
196
+ formField.maxLength = field.max_length;
197
+ formField.minLength = field.min_length;
198
+ }
199
+
200
+ if (field.type === 'file' || field.type === 'image') {
201
+ formField.multiple = field.multiple;
202
+ formField.accept = field.accept ? field.accept.join(',') : undefined;
203
+ // Add validation hints for file size and dimensions
204
+ if (field.max_size) {
205
+ const sizeHint = `Max size: ${formatFileSize(field.max_size)}`;
206
+ formField.description = formField.description
207
+ ? `${formField.description} (${sizeHint})`
208
+ : sizeHint;
209
+ }
210
+ }
211
+
212
+ if (field.type === 'email') {
213
+ formField.inputType = 'email';
214
+ }
215
+
216
+ if (field.type === 'phone') {
217
+ formField.inputType = 'tel';
218
+ }
219
+
220
+ if (field.type === 'url') {
221
+ formField.inputType = 'url';
222
+ }
223
+
224
+ if (field.type === 'password') {
225
+ formField.inputType = 'password';
226
+ }
227
+
228
+ if (field.type === 'time') {
229
+ formField.inputType = 'time';
230
+ }
231
+
232
+ // Read-only fields for computed types
233
+ if (field.type === 'formula' || field.type === 'summary' || field.type === 'auto_number') {
234
+ formField.disabled = true;
235
+ }
236
+
237
+ // Add conditional visibility based on field dependencies
238
+ if (field.visible_on) {
239
+ formField.visible = (formData: any) => {
240
+ return evaluateCondition(field.visible_on, formData);
241
+ };
242
+ }
243
+
244
+ generatedFields.push(formField);
245
+ }
246
+ });
247
+
248
+ setFormFields(generatedFields);
249
+ setLoading(false);
250
+ }, [objectSchema, schema.fields, schema.customFields, schema.readOnly, schema.mode, hasInlineFields]);
251
+
252
+ // Handle form submission
253
+ const handleSubmit = useCallback(async (formData: any) => {
254
+ // For inline fields without a dataSource, just call the success callback
255
+ if (hasInlineFields && !dataSource) {
256
+ if (schema.onSuccess) {
257
+ await schema.onSuccess(formData);
258
+ }
259
+ return formData;
260
+ }
261
+
262
+ if (!dataSource) {
263
+ throw new Error('DataSource is required for form submission (inline mode not configured)');
264
+ }
265
+
266
+ try {
267
+ let result;
268
+
269
+ if (schema.mode === 'create') {
270
+ result = await dataSource.create(schema.objectName, formData);
271
+ } else if (schema.mode === 'edit' && schema.recordId) {
272
+ result = await dataSource.update(schema.objectName, schema.recordId, formData);
273
+ } else {
274
+ throw new Error('Invalid form mode or missing record ID');
275
+ }
276
+
277
+ // Call success callback if provided
278
+ if (schema.onSuccess) {
279
+ await schema.onSuccess(result);
280
+ }
281
+
282
+ return result;
283
+ } catch (err) {
284
+ console.error('Failed to submit form:', err);
285
+
286
+ // Call error callback if provided
287
+ if (schema.onError) {
288
+ schema.onError(err as Error);
289
+ }
290
+
291
+ throw err;
292
+ }
293
+ }, [schema, dataSource, hasInlineFields]);
294
+
295
+ // Handle form cancellation
296
+ const handleCancel = useCallback(() => {
297
+ if (schema.onCancel) {
298
+ schema.onCancel();
299
+ }
300
+ }, [schema]);
301
+
302
+ // Render error state
303
+ if (error) {
304
+ return (
305
+ <div className="p-4 border border-red-300 bg-red-50 rounded-md">
306
+ <h3 className="text-red-800 font-semibold">Error loading form</h3>
307
+ <p className="text-red-600 text-sm mt-1">{error.message}</p>
308
+ </div>
309
+ );
310
+ }
311
+
312
+ // Render loading state
313
+ if (loading) {
314
+ return (
315
+ <div className="p-8 text-center">
316
+ <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
317
+ <p className="mt-2 text-sm text-gray-600">Loading form...</p>
318
+ </div>
319
+ );
320
+ }
321
+
322
+ // Convert to FormSchema
323
+ // Note: FormSchema currently only supports 'vertical' and 'horizontal' layouts
324
+ // Map 'grid' and 'inline' to 'vertical' as fallback
325
+ const formSchema: FormSchema = {
326
+ type: 'form',
327
+ fields: formFields,
328
+ layout: (schema.layout === 'vertical' || schema.layout === 'horizontal')
329
+ ? schema.layout
330
+ : 'vertical',
331
+ columns: schema.columns,
332
+ submitLabel: schema.submitText || (schema.mode === 'create' ? 'Create' : 'Update'),
333
+ cancelLabel: schema.cancelText,
334
+ showSubmit: schema.showSubmit !== false && schema.mode !== 'view',
335
+ showCancel: schema.showCancel !== false,
336
+ resetOnSubmit: schema.showReset,
337
+ defaultValues: initialData,
338
+ onSubmit: handleSubmit,
339
+ onCancel: handleCancel,
340
+ className: schema.className,
341
+ };
342
+
343
+ return (
344
+ <div className="w-full">
345
+ <SchemaRenderer schema={formSchema} />
346
+ </div>
347
+ );
348
+ };
349
+
package/src/index.tsx ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import React from 'react';
10
+ import { ComponentRegistry } from '@object-ui/core';
11
+ import { ObjectForm } from './ObjectForm';
12
+
13
+ export { ObjectForm };
14
+ export type { ObjectFormProps } from './ObjectForm';
15
+
16
+ // Register object-form component
17
+ const ObjectFormRenderer: React.FC<{ schema: any }> = ({ schema }) => {
18
+ return <ObjectForm schema={schema} />;
19
+ };
20
+
21
+ ComponentRegistry.register('object-form', ObjectFormRenderer);
22
+ ComponentRegistry.register('form', ObjectFormRenderer); // Alias
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "jsx": "react-jsx"
6
+ },
7
+ "include": ["src"]
8
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { defineConfig } from 'vite';
2
+ import react from '@vitejs/plugin-react';
3
+ import dts from 'vite-plugin-dts';
4
+ import { resolve } from 'path';
5
+
6
+ export default defineConfig({
7
+ plugins: [
8
+ react(),
9
+ dts({
10
+ insertTypesEntry: true,
11
+ include: ['src'],
12
+ }),
13
+ ],
14
+ build: {
15
+ lib: {
16
+ entry: resolve(__dirname, 'src/index.tsx'),
17
+ name: 'ObjectUIPluginForm',
18
+ fileName: 'index',
19
+ },
20
+ rollupOptions: {
21
+ external: [
22
+ 'react',
23
+ 'react-dom',
24
+ '@object-ui/components',
25
+ '@object-ui/core',
26
+ '@object-ui/fields',
27
+ '@object-ui/react',
28
+ '@object-ui/types',
29
+ 'lucide-react'
30
+ ],
31
+ output: {
32
+ globals: {
33
+ react: 'React',
34
+ 'react-dom': 'ReactDOM',
35
+ },
36
+ },
37
+ },
38
+ },
39
+ });