@punica/form 2.1.1 → 2.2.0-next.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.
@@ -0,0 +1,41 @@
1
+ import { FormClassDecorator, FormPropertyDecorator } from './decorator';
2
+ /** A property of a form defined with `defineForm`. */
3
+ export type FormField<T> = {
4
+ /** The value a new form starts with. */
5
+ value: T;
6
+ decorators: FormPropertyDecorator[];
7
+ };
8
+ /** The entity of a form defined with `defineForm`. */
9
+ export type FormValues<S extends Record<string, FormField<unknown>>> = {
10
+ -readonly [K in keyof S]: S[K]['value'];
11
+ };
12
+ /**
13
+ * A property of a form defined with `defineForm`: the value it starts with
14
+ * and the decorators a form class would have on the property.
15
+ *
16
+ * field('', Text({ label: 'Name' }))
17
+ * field<number | undefined>(undefined, NumberField({ label: 'Age' }))
18
+ */
19
+ export declare const field: <T>(value: T, ...decorators: FormPropertyDecorator[]) => FormField<T>;
20
+ /**
21
+ * Defines a form class without decorator syntax, for projects whose build
22
+ * does not compile decorators. The class is what a decorated class would
23
+ * be: give its instances to `FormController.fromEntity`.
24
+ *
25
+ * const UserForm = defineForm(
26
+ * { name: field('', Text({ label: 'Name' })) },
27
+ * Services([GetValues, SetValue])
28
+ * );
29
+ * type User = InstanceType<typeof UserForm>;
30
+ *
31
+ * const controller = await FormController.fromEntity(new UserForm());
32
+ * Decorators are applied like the ones written above a class or a property:
33
+ * the last one first. The value of a field is read once, when the form is
34
+ * defined, and copied for every instance; give values that differ between
35
+ * instances, such as the current date, to the constructor.
36
+ * @param fields - The properties of the form, in the order of its items
37
+ * @param decorators - What a form class would have above it: `Services`, `Readers`, …
38
+ * @returns A class whose constructor takes values that replace the initial
39
+ * ones; a value that is `undefined` leaves the initial one in place
40
+ */
41
+ export declare const defineForm: <S extends Record<string, FormField<unknown>>>(fields: S, ...decorators: FormClassDecorator[]) => new (values?: Partial<FormValues<S>>) => FormValues<S>;
@@ -1,4 +1,6 @@
1
1
  export type { FormClassDecorator, FormPropertyDecorator } from './decorator';
2
+ export type { FormField, FormValues } from './Form';
3
+ export { defineForm, field } from './Form';
2
4
  export { default as defineFormItem } from './FormItem';
3
5
  export { default as defineFormItemProperty } from './FormItemProperty';
4
6
  export { default as defineFormProperty } from './FormProperty';
package/dist/index.js CHANGED
@@ -50,14 +50,17 @@ __export(index_exports, {
50
50
  createInitialReader: () => createInitialReader,
51
51
  deepCopy: () => deepCopy,
52
52
  defaultFormItemRegister: () => defaultFormItemRegister,
53
+ defineForm: () => defineForm,
53
54
  defineFormItem: () => FormItem_default,
54
55
  defineFormItemProperty: () => FormItemProperty_default,
55
56
  defineFormProperty: () => FormProperty_default,
56
57
  disableDevTools: () => disableDevTools,
57
58
  enableDevTools: () => enableDevTools,
59
+ field: () => field,
58
60
  getFormItemProperties: () => getFormItemProperties,
59
61
  getFormProperty: () => getFormProperty,
60
62
  isDevToolsEnabled: () => isDevToolsEnabled,
63
+ isEqual: () => isEqual,
61
64
  readPropertyPath: () => readPropertyPath,
62
65
  writeToPropertyPath: () => writeToPropertyPath
63
66
  });
@@ -112,6 +115,61 @@ var getFormItemProperties = (entity, key) => {
112
115
  }, {});
113
116
  };
114
117
 
118
+ // lib/utils/deepCopy.ts
119
+ var deepCopy = (value, seen = /* @__PURE__ */ new WeakMap()) => {
120
+ if (typeof value !== "object" || value === null) {
121
+ return value;
122
+ }
123
+ if (seen.has(value)) {
124
+ return seen.get(value);
125
+ }
126
+ if (value instanceof Date) {
127
+ return new Date(value.getTime());
128
+ }
129
+ if (value instanceof RegExp) {
130
+ return new RegExp(value.source, value.flags);
131
+ }
132
+ if (value instanceof Map) {
133
+ const copy2 = /* @__PURE__ */ new Map();
134
+ seen.set(value, copy2);
135
+ value.forEach((v, k) => copy2.set(deepCopy(k, seen), deepCopy(v, seen)));
136
+ return copy2;
137
+ }
138
+ if (value instanceof Set) {
139
+ const copy2 = /* @__PURE__ */ new Set();
140
+ seen.set(value, copy2);
141
+ value.forEach((v) => copy2.add(deepCopy(v, seen)));
142
+ return copy2;
143
+ }
144
+ const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
145
+ seen.set(value, copy);
146
+ for (const key of Object.keys(value)) {
147
+ copy[key] = deepCopy(value[key], seen);
148
+ }
149
+ return copy;
150
+ };
151
+
152
+ // lib/define/Form.ts
153
+ var field = (value, ...decorators) => ({ value, decorators });
154
+ var defineForm = (fields, ...decorators) => {
155
+ class DefinedForm {
156
+ constructor(values = {}) {
157
+ for (const [property, { value }] of Object.entries(fields)) {
158
+ this[property] = Object.prototype.hasOwnProperty.call(values, property) && values[property] !== void 0 ? values[property] : deepCopy(value);
159
+ }
160
+ }
161
+ }
162
+ for (const [property, { decorators: decorators2 }] of Object.entries(fields)) {
163
+ for (const decorate of [...decorators2].reverse()) {
164
+ decorate(DefinedForm.prototype, property);
165
+ }
166
+ }
167
+ for (const decorate of [...decorators].reverse()) {
168
+ decorate(DefinedForm);
169
+ }
170
+ return DefinedForm;
171
+ };
172
+
115
173
  // lib/register/index.ts
116
174
  var _items;
117
175
  var FormItemRegister = class {
@@ -269,8 +327,18 @@ var sendToDevTools = (formId, type, data, formItemKey) => {
269
327
  };
270
328
 
271
329
  // lib/controller/index.ts
330
+ var DOCS_URL = "https://form.punicalab.com";
272
331
  var formCount = 0;
273
- var _form, _initialItems, _itemsMap, _services, _started, _batching, _dirty, _epoch, _writes, _subscribers, _listeners, _initialEntity, _register, _name, _FormController_instances, mapItems_fn, _getItem, _setItems, notify_fn, _supersede, _emit, _createCommandItem, _createCommandService, sendEntityToDevTools_fn;
332
+ var INITIAL_STATE = {
333
+ dirty: false,
334
+ touched: false,
335
+ valid: true,
336
+ validating: false,
337
+ submitting: false,
338
+ submitCount: 0,
339
+ errors: []
340
+ };
341
+ var _form, _initialItems, _itemsMap, _services, _started, _batching, _pending, _epoch, _writes, _subscribers, _listeners, _initialEntity, _register, _name, _FormController_instances, mapItems_fn, _getItem, _setItems, _setState, deriveState_fn, commit_fn, notify_fn, _supersede, _emit, _createCommandItem, _createCommandService, sendEntityToDevTools_fn;
274
342
  var _FormController = class _FormController {
275
343
  constructor(form, entity, options) {
276
344
  __privateAdd(this, _FormController_instances);
@@ -281,7 +349,7 @@ var _FormController = class _FormController {
281
349
  __privateAdd(this, _services, /* @__PURE__ */ new Map());
282
350
  __privateAdd(this, _started, false);
283
351
  __privateAdd(this, _batching, 0);
284
- __privateAdd(this, _dirty, false);
352
+ __privateAdd(this, _pending, false);
285
353
  __privateAdd(this, _epoch, 0);
286
354
  __privateAdd(this, _writes, /* @__PURE__ */ new Map());
287
355
  __privateAdd(this, _subscribers, /* @__PURE__ */ new Set());
@@ -310,8 +378,8 @@ var _FormController = class _FormController {
310
378
  */
311
379
  this.batch = (change) => {
312
380
  const done = () => {
313
- if (--__privateWrapper(this, _batching)._ === 0 && __privateGet(this, _dirty)) {
314
- __privateSet(this, _dirty, false);
381
+ if (--__privateWrapper(this, _batching)._ === 0 && __privateGet(this, _pending)) {
382
+ __privateSet(this, _pending, false);
315
383
  __privateMethod(this, _FormController_instances, notify_fn).call(this);
316
384
  }
317
385
  };
@@ -340,18 +408,24 @@ var _FormController = class _FormController {
340
408
  for (const item of items) {
341
409
  const index = __privateGet(this, _itemsMap).get(item.property);
342
410
  if (index !== void 0) {
343
- next[index] = item;
411
+ const initial = __privateGet(this, _initialItems)[index];
412
+ const dirty = Boolean(initial) && !isEqual(item.value, initial.value);
413
+ next[index] = dirty === Boolean(item.dirty) ? item : { ...item, dirty };
344
414
  changed = true;
345
415
  }
346
416
  }
347
- if (!changed) {
348
- return;
417
+ if (changed) {
418
+ __privateMethod(this, _FormController_instances, commit_fn).call(this, {
419
+ ...__privateGet(this, _form),
420
+ items: next,
421
+ state: __privateMethod(this, _FormController_instances, deriveState_fn).call(this, next)
422
+ });
349
423
  }
350
- __privateSet(this, _form, { ...__privateGet(this, _form), items: next });
351
- if (__privateGet(this, _batching)) {
352
- __privateSet(this, _dirty, true);
353
- } else {
354
- __privateMethod(this, _FormController_instances, notify_fn).call(this);
424
+ });
425
+ __privateAdd(this, _setState, (patch) => {
426
+ const state = __privateMethod(this, _FormController_instances, deriveState_fn).call(this, __privateGet(this, _form).items, patch);
427
+ if (state !== __privateGet(this, _form).state) {
428
+ __privateMethod(this, _FormController_instances, commit_fn).call(this, { ...__privateGet(this, _form), state });
355
429
  }
356
430
  });
357
431
  __privateAdd(this, _supersede, (property) => {
@@ -398,6 +472,7 @@ var _FormController = class _FormController {
398
472
  getInitialItems: () => __privateGet(this, _initialItems),
399
473
  getItem: __privateGet(this, _getItem),
400
474
  setItems: __privateGet(this, _setItems),
475
+ setState: __privateGet(this, _setState),
401
476
  supersede: __privateGet(this, _supersede),
402
477
  emit: __privateGet(this, _emit),
403
478
  createCommandItem: __privateGet(this, _createCommandItem)
@@ -422,6 +497,11 @@ var _FormController = class _FormController {
422
497
  static async fromEntity(entity, options = {}) {
423
498
  const form = { items: [] };
424
499
  await createInitialReader().read(entity, form);
500
+ if (!form.items.length && !form.readers?.length && !form.starters?.length) {
501
+ console.warn(
502
+ `[punica-form] ${options.name ?? entity.constructor?.name ?? "The form"} has no form items. Its properties need a form item decorator. If they have one, the build of the project does not apply decorators: see ${DOCS_URL}/docs/installation, or define the form with defineForm, which needs no decorator syntax.`
503
+ );
504
+ }
425
505
  return new _FormController(form, entity, options);
426
506
  }
427
507
  /**
@@ -484,6 +564,10 @@ var _FormController = class _FormController {
484
564
  );
485
565
  }
486
566
  __privateSet(this, _initialItems, deepCopy(__privateGet(this, _form).items));
567
+ __privateSet(this, _form, {
568
+ ...__privateGet(this, _form),
569
+ state: __privateMethod(this, _FormController_instances, deriveState_fn).call(this, __privateGet(this, _form).items)
570
+ });
487
571
  __privateSet(this, _started, true);
488
572
  sendToDevTools(__privateGet(this, _name), "@@INIT", __privateGet(this, _form));
489
573
  __privateMethod(this, _FormController_instances, notify_fn).call(this);
@@ -496,7 +580,7 @@ _itemsMap = new WeakMap();
496
580
  _services = new WeakMap();
497
581
  _started = new WeakMap();
498
582
  _batching = new WeakMap();
499
- _dirty = new WeakMap();
583
+ _pending = new WeakMap();
500
584
  _epoch = new WeakMap();
501
585
  _writes = new WeakMap();
502
586
  _subscribers = new WeakMap();
@@ -512,6 +596,36 @@ mapItems_fn = function() {
512
596
  };
513
597
  _getItem = new WeakMap();
514
598
  _setItems = new WeakMap();
599
+ _setState = new WeakMap();
600
+ /**
601
+ * The state of the form for its items. The current state object is
602
+ * returned when nothing changed, so it can be compared by reference.
603
+ */
604
+ deriveState_fn = function(items, patch = {}) {
605
+ const known = Array.isArray(__privateGet(this, _form).state?.errors);
606
+ const current = known ? __privateGet(this, _form).state : INITIAL_STATE;
607
+ const next = {
608
+ ...current,
609
+ ...patch,
610
+ dirty: items.some((item) => item.dirty),
611
+ touched: items.some((item) => item.touched),
612
+ validating: items.some((item) => item.validating),
613
+ // Like the validation, which skips items the user cannot change
614
+ valid: items.every((item) => !item.error || item.hidden || item.disabled)
615
+ };
616
+ const same = Object.keys(next).every(
617
+ (key) => isEqual(next[key], current[key])
618
+ );
619
+ return same && known ? current : next;
620
+ };
621
+ commit_fn = function(form) {
622
+ __privateSet(this, _form, form);
623
+ if (__privateGet(this, _batching)) {
624
+ __privateSet(this, _pending, true);
625
+ } else {
626
+ __privateMethod(this, _FormController_instances, notify_fn).call(this);
627
+ }
628
+ };
515
629
  /** Tells everyone who follows the form that it changed. */
516
630
  notify_fn = function() {
517
631
  __privateGet(this, _subscribers).forEach((listener) => listener());
@@ -534,38 +648,46 @@ sendEntityToDevTools_fn = function() {
534
648
  };
535
649
  var FormController = _FormController;
536
650
 
537
- // lib/utils/deepCopy.ts
538
- var deepCopy = (value, seen = /* @__PURE__ */ new WeakMap()) => {
539
- if (typeof value !== "object" || value === null) {
540
- return value;
651
+ // lib/utils/isEqual.ts
652
+ var isEqual = (a, b, seen = /* @__PURE__ */ new WeakMap()) => {
653
+ if (Object.is(a, b)) {
654
+ return true;
541
655
  }
542
- if (seen.has(value)) {
543
- return seen.get(value);
656
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null || Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) {
657
+ return false;
544
658
  }
545
- if (value instanceof Date) {
546
- return new Date(value.getTime());
659
+ if (seen.get(a)?.has(b)) {
660
+ return true;
547
661
  }
548
- if (value instanceof RegExp) {
549
- return new RegExp(value.source, value.flags);
662
+ seen.set(a, (seen.get(a) ?? /* @__PURE__ */ new WeakSet()).add(b));
663
+ if (a instanceof Date) {
664
+ return a.getTime() === b.getTime();
550
665
  }
551
- if (value instanceof Map) {
552
- const copy2 = /* @__PURE__ */ new Map();
553
- seen.set(value, copy2);
554
- value.forEach((v, k) => copy2.set(deepCopy(k, seen), deepCopy(v, seen)));
555
- return copy2;
666
+ if (a instanceof RegExp) {
667
+ return String(a) === String(b);
556
668
  }
557
- if (value instanceof Set) {
558
- const copy2 = /* @__PURE__ */ new Set();
559
- seen.set(value, copy2);
560
- value.forEach((v) => copy2.add(deepCopy(v, seen)));
561
- return copy2;
669
+ if (a instanceof Set) {
670
+ const other = [...b];
671
+ return a.size === other.length && [...a].every(
672
+ (value) => b.has(value) || other.some((candidate) => isEqual(value, candidate, seen))
673
+ );
562
674
  }
563
- const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
564
- seen.set(value, copy);
565
- for (const key of Object.keys(value)) {
566
- copy[key] = deepCopy(value[key], seen);
675
+ if (a instanceof Map) {
676
+ const other = [...b];
677
+ return a.size === other.length && [...a].every(
678
+ ([key, value]) => other.some(
679
+ ([otherKey, otherValue]) => isEqual(key, otherKey, seen) && isEqual(value, otherValue, seen)
680
+ )
681
+ );
567
682
  }
568
- return copy;
683
+ const keys = Object.keys(a);
684
+ const left = a;
685
+ const right = b;
686
+ const prototype = Object.getPrototypeOf(a);
687
+ if (keys.length === 0 && prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null) {
688
+ return false;
689
+ }
690
+ return keys.length === Object.keys(right).length && keys.every((key) => key in right && isEqual(left[key], right[key], seen));
569
691
  };
570
692
 
571
693
  // lib/utils/path.ts
@@ -609,14 +731,17 @@ var writeToPropertyPath = (entity, path, value) => {
609
731
  createInitialReader,
610
732
  deepCopy,
611
733
  defaultFormItemRegister,
734
+ defineForm,
612
735
  defineFormItem,
613
736
  defineFormItemProperty,
614
737
  defineFormProperty,
615
738
  disableDevTools,
616
739
  enableDevTools,
740
+ field,
617
741
  getFormItemProperties,
618
742
  getFormProperty,
619
743
  isDevToolsEnabled,
744
+ isEqual,
620
745
  readPropertyPath,
621
746
  writeToPropertyPath
622
747
  });
package/dist/index.mjs CHANGED
@@ -64,6 +64,61 @@ var getFormItemProperties = (entity, key) => {
64
64
  }, {});
65
65
  };
66
66
 
67
+ // lib/utils/deepCopy.ts
68
+ var deepCopy = (value, seen = /* @__PURE__ */ new WeakMap()) => {
69
+ if (typeof value !== "object" || value === null) {
70
+ return value;
71
+ }
72
+ if (seen.has(value)) {
73
+ return seen.get(value);
74
+ }
75
+ if (value instanceof Date) {
76
+ return new Date(value.getTime());
77
+ }
78
+ if (value instanceof RegExp) {
79
+ return new RegExp(value.source, value.flags);
80
+ }
81
+ if (value instanceof Map) {
82
+ const copy2 = /* @__PURE__ */ new Map();
83
+ seen.set(value, copy2);
84
+ value.forEach((v, k) => copy2.set(deepCopy(k, seen), deepCopy(v, seen)));
85
+ return copy2;
86
+ }
87
+ if (value instanceof Set) {
88
+ const copy2 = /* @__PURE__ */ new Set();
89
+ seen.set(value, copy2);
90
+ value.forEach((v) => copy2.add(deepCopy(v, seen)));
91
+ return copy2;
92
+ }
93
+ const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
94
+ seen.set(value, copy);
95
+ for (const key of Object.keys(value)) {
96
+ copy[key] = deepCopy(value[key], seen);
97
+ }
98
+ return copy;
99
+ };
100
+
101
+ // lib/define/Form.ts
102
+ var field = (value, ...decorators) => ({ value, decorators });
103
+ var defineForm = (fields, ...decorators) => {
104
+ class DefinedForm {
105
+ constructor(values = {}) {
106
+ for (const [property, { value }] of Object.entries(fields)) {
107
+ this[property] = Object.prototype.hasOwnProperty.call(values, property) && values[property] !== void 0 ? values[property] : deepCopy(value);
108
+ }
109
+ }
110
+ }
111
+ for (const [property, { decorators: decorators2 }] of Object.entries(fields)) {
112
+ for (const decorate of [...decorators2].reverse()) {
113
+ decorate(DefinedForm.prototype, property);
114
+ }
115
+ }
116
+ for (const decorate of [...decorators].reverse()) {
117
+ decorate(DefinedForm);
118
+ }
119
+ return DefinedForm;
120
+ };
121
+
67
122
  // lib/register/index.ts
68
123
  var _items;
69
124
  var FormItemRegister = class {
@@ -221,8 +276,18 @@ var sendToDevTools = (formId, type, data, formItemKey) => {
221
276
  };
222
277
 
223
278
  // lib/controller/index.ts
279
+ var DOCS_URL = "https://form.punicalab.com";
224
280
  var formCount = 0;
225
- var _form, _initialItems, _itemsMap, _services, _started, _batching, _dirty, _epoch, _writes, _subscribers, _listeners, _initialEntity, _register, _name, _FormController_instances, mapItems_fn, _getItem, _setItems, notify_fn, _supersede, _emit, _createCommandItem, _createCommandService, sendEntityToDevTools_fn;
281
+ var INITIAL_STATE = {
282
+ dirty: false,
283
+ touched: false,
284
+ valid: true,
285
+ validating: false,
286
+ submitting: false,
287
+ submitCount: 0,
288
+ errors: []
289
+ };
290
+ var _form, _initialItems, _itemsMap, _services, _started, _batching, _pending, _epoch, _writes, _subscribers, _listeners, _initialEntity, _register, _name, _FormController_instances, mapItems_fn, _getItem, _setItems, _setState, deriveState_fn, commit_fn, notify_fn, _supersede, _emit, _createCommandItem, _createCommandService, sendEntityToDevTools_fn;
226
291
  var _FormController = class _FormController {
227
292
  constructor(form, entity, options) {
228
293
  __privateAdd(this, _FormController_instances);
@@ -233,7 +298,7 @@ var _FormController = class _FormController {
233
298
  __privateAdd(this, _services, /* @__PURE__ */ new Map());
234
299
  __privateAdd(this, _started, false);
235
300
  __privateAdd(this, _batching, 0);
236
- __privateAdd(this, _dirty, false);
301
+ __privateAdd(this, _pending, false);
237
302
  __privateAdd(this, _epoch, 0);
238
303
  __privateAdd(this, _writes, /* @__PURE__ */ new Map());
239
304
  __privateAdd(this, _subscribers, /* @__PURE__ */ new Set());
@@ -262,8 +327,8 @@ var _FormController = class _FormController {
262
327
  */
263
328
  this.batch = (change) => {
264
329
  const done = () => {
265
- if (--__privateWrapper(this, _batching)._ === 0 && __privateGet(this, _dirty)) {
266
- __privateSet(this, _dirty, false);
330
+ if (--__privateWrapper(this, _batching)._ === 0 && __privateGet(this, _pending)) {
331
+ __privateSet(this, _pending, false);
267
332
  __privateMethod(this, _FormController_instances, notify_fn).call(this);
268
333
  }
269
334
  };
@@ -292,18 +357,24 @@ var _FormController = class _FormController {
292
357
  for (const item of items) {
293
358
  const index = __privateGet(this, _itemsMap).get(item.property);
294
359
  if (index !== void 0) {
295
- next[index] = item;
360
+ const initial = __privateGet(this, _initialItems)[index];
361
+ const dirty = Boolean(initial) && !isEqual(item.value, initial.value);
362
+ next[index] = dirty === Boolean(item.dirty) ? item : { ...item, dirty };
296
363
  changed = true;
297
364
  }
298
365
  }
299
- if (!changed) {
300
- return;
366
+ if (changed) {
367
+ __privateMethod(this, _FormController_instances, commit_fn).call(this, {
368
+ ...__privateGet(this, _form),
369
+ items: next,
370
+ state: __privateMethod(this, _FormController_instances, deriveState_fn).call(this, next)
371
+ });
301
372
  }
302
- __privateSet(this, _form, { ...__privateGet(this, _form), items: next });
303
- if (__privateGet(this, _batching)) {
304
- __privateSet(this, _dirty, true);
305
- } else {
306
- __privateMethod(this, _FormController_instances, notify_fn).call(this);
373
+ });
374
+ __privateAdd(this, _setState, (patch) => {
375
+ const state = __privateMethod(this, _FormController_instances, deriveState_fn).call(this, __privateGet(this, _form).items, patch);
376
+ if (state !== __privateGet(this, _form).state) {
377
+ __privateMethod(this, _FormController_instances, commit_fn).call(this, { ...__privateGet(this, _form), state });
307
378
  }
308
379
  });
309
380
  __privateAdd(this, _supersede, (property) => {
@@ -350,6 +421,7 @@ var _FormController = class _FormController {
350
421
  getInitialItems: () => __privateGet(this, _initialItems),
351
422
  getItem: __privateGet(this, _getItem),
352
423
  setItems: __privateGet(this, _setItems),
424
+ setState: __privateGet(this, _setState),
353
425
  supersede: __privateGet(this, _supersede),
354
426
  emit: __privateGet(this, _emit),
355
427
  createCommandItem: __privateGet(this, _createCommandItem)
@@ -374,6 +446,11 @@ var _FormController = class _FormController {
374
446
  static async fromEntity(entity, options = {}) {
375
447
  const form = { items: [] };
376
448
  await createInitialReader().read(entity, form);
449
+ if (!form.items.length && !form.readers?.length && !form.starters?.length) {
450
+ console.warn(
451
+ `[punica-form] ${options.name ?? entity.constructor?.name ?? "The form"} has no form items. Its properties need a form item decorator. If they have one, the build of the project does not apply decorators: see ${DOCS_URL}/docs/installation, or define the form with defineForm, which needs no decorator syntax.`
452
+ );
453
+ }
377
454
  return new _FormController(form, entity, options);
378
455
  }
379
456
  /**
@@ -436,6 +513,10 @@ var _FormController = class _FormController {
436
513
  );
437
514
  }
438
515
  __privateSet(this, _initialItems, deepCopy(__privateGet(this, _form).items));
516
+ __privateSet(this, _form, {
517
+ ...__privateGet(this, _form),
518
+ state: __privateMethod(this, _FormController_instances, deriveState_fn).call(this, __privateGet(this, _form).items)
519
+ });
439
520
  __privateSet(this, _started, true);
440
521
  sendToDevTools(__privateGet(this, _name), "@@INIT", __privateGet(this, _form));
441
522
  __privateMethod(this, _FormController_instances, notify_fn).call(this);
@@ -448,7 +529,7 @@ _itemsMap = new WeakMap();
448
529
  _services = new WeakMap();
449
530
  _started = new WeakMap();
450
531
  _batching = new WeakMap();
451
- _dirty = new WeakMap();
532
+ _pending = new WeakMap();
452
533
  _epoch = new WeakMap();
453
534
  _writes = new WeakMap();
454
535
  _subscribers = new WeakMap();
@@ -464,6 +545,36 @@ mapItems_fn = function() {
464
545
  };
465
546
  _getItem = new WeakMap();
466
547
  _setItems = new WeakMap();
548
+ _setState = new WeakMap();
549
+ /**
550
+ * The state of the form for its items. The current state object is
551
+ * returned when nothing changed, so it can be compared by reference.
552
+ */
553
+ deriveState_fn = function(items, patch = {}) {
554
+ const known = Array.isArray(__privateGet(this, _form).state?.errors);
555
+ const current = known ? __privateGet(this, _form).state : INITIAL_STATE;
556
+ const next = {
557
+ ...current,
558
+ ...patch,
559
+ dirty: items.some((item) => item.dirty),
560
+ touched: items.some((item) => item.touched),
561
+ validating: items.some((item) => item.validating),
562
+ // Like the validation, which skips items the user cannot change
563
+ valid: items.every((item) => !item.error || item.hidden || item.disabled)
564
+ };
565
+ const same = Object.keys(next).every(
566
+ (key) => isEqual(next[key], current[key])
567
+ );
568
+ return same && known ? current : next;
569
+ };
570
+ commit_fn = function(form) {
571
+ __privateSet(this, _form, form);
572
+ if (__privateGet(this, _batching)) {
573
+ __privateSet(this, _pending, true);
574
+ } else {
575
+ __privateMethod(this, _FormController_instances, notify_fn).call(this);
576
+ }
577
+ };
467
578
  /** Tells everyone who follows the form that it changed. */
468
579
  notify_fn = function() {
469
580
  __privateGet(this, _subscribers).forEach((listener) => listener());
@@ -486,38 +597,46 @@ sendEntityToDevTools_fn = function() {
486
597
  };
487
598
  var FormController = _FormController;
488
599
 
489
- // lib/utils/deepCopy.ts
490
- var deepCopy = (value, seen = /* @__PURE__ */ new WeakMap()) => {
491
- if (typeof value !== "object" || value === null) {
492
- return value;
600
+ // lib/utils/isEqual.ts
601
+ var isEqual = (a, b, seen = /* @__PURE__ */ new WeakMap()) => {
602
+ if (Object.is(a, b)) {
603
+ return true;
493
604
  }
494
- if (seen.has(value)) {
495
- return seen.get(value);
605
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null || Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) {
606
+ return false;
496
607
  }
497
- if (value instanceof Date) {
498
- return new Date(value.getTime());
608
+ if (seen.get(a)?.has(b)) {
609
+ return true;
499
610
  }
500
- if (value instanceof RegExp) {
501
- return new RegExp(value.source, value.flags);
611
+ seen.set(a, (seen.get(a) ?? /* @__PURE__ */ new WeakSet()).add(b));
612
+ if (a instanceof Date) {
613
+ return a.getTime() === b.getTime();
502
614
  }
503
- if (value instanceof Map) {
504
- const copy2 = /* @__PURE__ */ new Map();
505
- seen.set(value, copy2);
506
- value.forEach((v, k) => copy2.set(deepCopy(k, seen), deepCopy(v, seen)));
507
- return copy2;
615
+ if (a instanceof RegExp) {
616
+ return String(a) === String(b);
508
617
  }
509
- if (value instanceof Set) {
510
- const copy2 = /* @__PURE__ */ new Set();
511
- seen.set(value, copy2);
512
- value.forEach((v) => copy2.add(deepCopy(v, seen)));
513
- return copy2;
618
+ if (a instanceof Set) {
619
+ const other = [...b];
620
+ return a.size === other.length && [...a].every(
621
+ (value) => b.has(value) || other.some((candidate) => isEqual(value, candidate, seen))
622
+ );
514
623
  }
515
- const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
516
- seen.set(value, copy);
517
- for (const key of Object.keys(value)) {
518
- copy[key] = deepCopy(value[key], seen);
624
+ if (a instanceof Map) {
625
+ const other = [...b];
626
+ return a.size === other.length && [...a].every(
627
+ ([key, value]) => other.some(
628
+ ([otherKey, otherValue]) => isEqual(key, otherKey, seen) && isEqual(value, otherValue, seen)
629
+ )
630
+ );
519
631
  }
520
- return copy;
632
+ const keys = Object.keys(a);
633
+ const left = a;
634
+ const right = b;
635
+ const prototype = Object.getPrototypeOf(a);
636
+ if (keys.length === 0 && prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null) {
637
+ return false;
638
+ }
639
+ return keys.length === Object.keys(right).length && keys.every((key) => key in right && isEqual(left[key], right[key], seen));
521
640
  };
522
641
 
523
642
  // lib/utils/path.ts
@@ -560,14 +679,17 @@ export {
560
679
  createInitialReader,
561
680
  deepCopy,
562
681
  defaultFormItemRegister,
682
+ defineForm,
563
683
  FormItem_default as defineFormItem,
564
684
  FormItemProperty_default as defineFormItemProperty,
565
685
  FormProperty_default as defineFormProperty,
566
686
  disableDevTools,
567
687
  enableDevTools,
688
+ field,
568
689
  getFormItemProperties,
569
690
  getFormProperty,
570
691
  isDevToolsEnabled,
692
+ isEqual,
571
693
  readPropertyPath,
572
694
  writeToPropertyPath
573
695
  };
@@ -1,4 +1,4 @@
1
- import { CommandItem, Form, FormEventMap, FormItem } from '..';
1
+ import { CommandItem, Form, FormEventMap, FormItem, FormStatePatch } from '..';
2
2
  /**
3
3
  * What a service receives when it is initialized: the only way to read and
4
4
  * change the state of the form.
@@ -15,8 +15,14 @@ export type CommandService<E, F extends FormItem<E>> = {
15
15
  /**
16
16
  * Replaces the items with the same properties. The form gets a new
17
17
  * reference and UPDATE_FORM is fired. Unknown properties are ignored.
18
+ * `dirty` of the items is set by comparing their values with the initial ones.
18
19
  */
19
20
  setItems: (items: Array<FormItem<E>>) => void;
21
+ /**
22
+ * Changes the state of the form as a whole. The form gets a new reference
23
+ * and UPDATE_FORM is fired, unless nothing changed.
24
+ */
25
+ setState: (state: FormStatePatch) => void;
20
26
  /**
21
27
  * Marks the pending asynchronous writes of a property, or of the whole
22
28
  * form when no property is given, as superseded by a newer one.
@@ -9,6 +9,10 @@ export type FormEventMap<E, F extends FormItem<E>> = {
9
9
  RESET: Form<E, F>;
10
10
  /** A value was set: the changed item, then the items its control returned. */
11
11
  UPDATE_ITEM: F[];
12
+ /** The form was submitted: the values the submit handler received. */
13
+ SUBMIT: E;
14
+ /** A submit failed: what the validation or the submit handler threw. */
15
+ SUBMIT_ERROR: unknown;
12
16
  /** The registered form item types. Fired at the beginning of start(). */
13
17
  REGISTER_ITEMS: string[];
14
18
  };
@@ -1,10 +1,33 @@
1
1
  import { FormItem, IReader, IService, IStarter } from '../..';
2
+ /**
3
+ * What a form knows about itself as a whole. A started form always has it.
4
+ */
5
+ export type FormState = {
6
+ /** Whether the value of an item differs from the one the form was started with. */
7
+ dirty: boolean;
8
+ /** Whether the user has left a field. */
9
+ touched: boolean;
10
+ /** Whether no item is in error. */
11
+ valid: boolean;
12
+ /** Whether an item is being validated. */
13
+ validating: boolean;
14
+ /** Whether the form is being submitted. */
15
+ submitting: boolean;
16
+ /** How many times a submit was attempted. */
17
+ submitCount: number;
18
+ /** Errors of the form as a whole, such as a rejected submit. */
19
+ errors: string[];
20
+ };
21
+ /** The part of the state services write; the rest follows from the items. */
22
+ export type FormStatePatch = Partial<Pick<FormState, 'submitting' | 'submitCount' | 'errors'>>;
2
23
  /**
3
24
  * The state of a form. Readers and starters may attach their own properties
4
25
  * (a title, a layout, …), which are read back as `unknown`.
5
26
  */
6
27
  export type Form<E, F extends FormItem<E> = FormItem<E>> = {
7
28
  items: F[];
29
+ /** Set when the form is started and kept up to date after every change. */
30
+ state?: FormState;
8
31
  /** Service classes (one instance per form) or instances. */
9
32
  services?: Array<IService | (new () => IService)>;
10
33
  readers?: Array<IReader<E, F>>;
@@ -20,6 +20,18 @@ export type FormItem<E> = {
20
20
  required?: boolean;
21
21
  disabled?: boolean;
22
22
  hidden?: boolean;
23
+ /** Whether the value differs from the one the form was started with. */
24
+ dirty?: boolean;
25
+ /** Whether the user has left the field. Set by the `Touch` service. */
26
+ touched?: boolean;
27
+ /** Whether the item is being validated. */
28
+ validating?: boolean;
29
+ /**
30
+ * Milliseconds the `Trigger` service waits before it validates the item.
31
+ * A validation triggered again meanwhile starts the wait anew, so a
32
+ * validation that asks a server runs once the user stops typing.
33
+ */
34
+ validateDebounce?: number;
23
35
  /** Whether the last validation of the item failed. */
24
36
  error?: boolean;
25
37
  /** The messages of the last failed validation. */
@@ -28,8 +40,12 @@ export type FormItem<E> = {
28
40
  initialize?(command: CommandItem<E, FormItem<E>>): Promise<Array<FormItem<E>>>;
29
41
  /** Runs after the value of the item was set; the returned items are written to the form. */
30
42
  control?(command: CommandItem<E, FormItem<E>>): Promise<Array<FormItem<E>>>;
31
- /** Validates the item. */
32
- validation?(command: CommandItem<E, FormItem<E>>): Promise<ErrorDetail>;
43
+ /**
44
+ * Validates the item. The services pass a context whose signal is aborted
45
+ * when the result is not needed any more; give it to `fetch` to cancel
46
+ * the request: `fetch(url, { signal: context?.signal })`.
47
+ */
48
+ validation?(command: CommandItem<E, FormItem<E>>, context?: ValidationContext): Promise<ErrorDetail>;
33
49
  };
34
50
  /**
35
51
  * A form item whose `value` has the type of its property. Use it as the item
@@ -45,6 +61,16 @@ export type TypedFormItem<E, F extends FormItem<E> = FormItem<E>> = {
45
61
  value?: E[K];
46
62
  };
47
63
  }[keyof E];
64
+ /**
65
+ * What a validation function receives besides its command.
66
+ */
67
+ export type ValidationContext = {
68
+ /**
69
+ * Aborted when the item is validated again, changed or reset while the
70
+ * validation is running.
71
+ */
72
+ signal: AbortSignal;
73
+ };
48
74
  /**
49
75
  * The result of a validation.
50
76
  */
@@ -1,3 +1,4 @@
1
1
  export { DEVTOOLS_MESSAGE_SOURCE, DEVTOOLS_PROTOCOL_VERSION, disableDevTools, enableDevTools, isDevToolsEnabled } from './devtools';
2
2
  export * from './deepCopy';
3
+ export * from './isEqual';
3
4
  export * from './path';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Whether two values are deeply equal. Objects, arrays, dates, regular
3
+ * expressions, maps and sets are compared by their content, circular
4
+ * references included. Objects without own properties that are not plain,
5
+ * such as a `File`, are only equal to themselves.
6
+ */
7
+ export declare const isEqual: (a: unknown, b: unknown, seen?: WeakMap<object, WeakSet<object>>) => boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@punica/form",
3
- "version": "2.1.1",
3
+ "version": "2.2.0-next.0",
4
4
  "description": "Headless, framework-agnostic form engine",
5
5
  "author": {
6
6
  "name": "Uryan Sezgin TEKE",