@planeasyinc/fe-core 0.1.31 → 0.1.33

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 (189) hide show
  1. package/dist/conditions.d.ts.map +1 -1
  2. package/dist/conditions.js +7 -19
  3. package/dist/conditions.js.map +1 -1
  4. package/dist/constants/index.d.ts +1 -2
  5. package/dist/constants/index.d.ts.map +1 -1
  6. package/dist/constants/index.js +1 -43
  7. package/dist/constants/index.js.map +1 -1
  8. package/dist/constants/type-list.d.ts +3 -0
  9. package/dist/constants/type-list.d.ts.map +1 -0
  10. package/dist/constants/type-list.js +44 -0
  11. package/dist/constants/type-list.js.map +1 -0
  12. package/dist/engine.d.ts +53 -97
  13. package/dist/engine.d.ts.map +1 -1
  14. package/dist/engine.js +305 -461
  15. package/dist/engine.js.map +1 -1
  16. package/dist/guards/index.d.ts +4 -0
  17. package/dist/guards/index.d.ts.map +1 -1
  18. package/dist/guards/index.js +4 -0
  19. package/dist/guards/index.js.map +1 -1
  20. package/dist/guards/is-action-with-context.d.ts +3 -0
  21. package/dist/guards/is-action-with-context.d.ts.map +1 -0
  22. package/dist/guards/is-action-with-context.js +4 -0
  23. package/dist/guards/is-action-with-context.js.map +1 -0
  24. package/dist/guards/is-condition-group.d.ts +3 -0
  25. package/dist/guards/is-condition-group.d.ts.map +1 -0
  26. package/dist/guards/is-condition-group.js +4 -0
  27. package/dist/guards/is-condition-group.js.map +1 -0
  28. package/dist/guards/is-data-rows.d.ts +2 -0
  29. package/dist/guards/is-data-rows.d.ts.map +1 -0
  30. package/dist/guards/is-data-rows.js +4 -0
  31. package/dist/guards/is-data-rows.js.map +1 -0
  32. package/dist/guards/is-editable-control.d.ts +1 -1
  33. package/dist/guards/is-object-reference.d.ts +3 -0
  34. package/dist/guards/is-object-reference.d.ts.map +1 -0
  35. package/dist/guards/is-object-reference.js +5 -0
  36. package/dist/guards/is-object-reference.js.map +1 -0
  37. package/dist/guards/schema-guard.d.ts +2 -2
  38. package/dist/guards/schema-guard.d.ts.map +1 -1
  39. package/dist/index.d.ts +5 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +5 -1
  42. package/dist/index.js.map +1 -1
  43. package/dist/model/control-config.d.ts +217 -0
  44. package/dist/model/control-config.d.ts.map +1 -0
  45. package/dist/model/control-config.js +2 -0
  46. package/dist/model/control-config.js.map +1 -0
  47. package/dist/model/form-engine-commands.d.ts +7 -0
  48. package/dist/model/form-engine-commands.d.ts.map +1 -0
  49. package/dist/model/form-engine-commands.js +2 -0
  50. package/dist/model/form-engine-commands.js.map +1 -0
  51. package/dist/model/form-engine-events.d.ts +24 -0
  52. package/dist/model/form-engine-events.d.ts.map +1 -0
  53. package/dist/model/form-engine-events.js +2 -0
  54. package/dist/model/form-engine-events.js.map +1 -0
  55. package/dist/model/form-engine-options.d.ts +5 -0
  56. package/dist/model/form-engine-options.d.ts.map +1 -0
  57. package/dist/model/form-engine-options.js +2 -0
  58. package/dist/model/form-engine-options.js.map +1 -0
  59. package/dist/model/form-engine-resolvers.d.ts +6 -0
  60. package/dist/model/form-engine-resolvers.d.ts.map +1 -0
  61. package/dist/model/form-engine-resolvers.js +2 -0
  62. package/dist/model/form-engine-resolvers.js.map +1 -0
  63. package/dist/model/form-engine-state.d.ts +68 -0
  64. package/dist/model/form-engine-state.d.ts.map +1 -0
  65. package/dist/model/form-engine-state.js +2 -0
  66. package/dist/model/form-engine-state.js.map +1 -0
  67. package/dist/model/index.d.ts +7 -0
  68. package/dist/model/index.d.ts.map +1 -0
  69. package/dist/model/index.js +7 -0
  70. package/dist/model/index.js.map +1 -0
  71. package/dist/services/form-batch.service.d.ts +26 -0
  72. package/dist/services/form-batch.service.d.ts.map +1 -0
  73. package/dist/services/form-batch.service.js +81 -0
  74. package/dist/services/form-batch.service.js.map +1 -0
  75. package/dist/services/form-conditions.service.d.ts +18 -0
  76. package/dist/services/form-conditions.service.d.ts.map +1 -0
  77. package/dist/services/form-conditions.service.js +114 -0
  78. package/dist/services/form-conditions.service.js.map +1 -0
  79. package/dist/services/form-model.service.d.ts +20 -0
  80. package/dist/services/form-model.service.d.ts.map +1 -0
  81. package/dist/services/form-model.service.js +57 -0
  82. package/dist/services/form-model.service.js.map +1 -0
  83. package/dist/services/form-state.service.d.ts +29 -0
  84. package/dist/services/form-state.service.d.ts.map +1 -0
  85. package/dist/services/form-state.service.js +171 -0
  86. package/dist/services/form-state.service.js.map +1 -0
  87. package/dist/services/form-streaming.service.d.ts +11 -0
  88. package/dist/services/form-streaming.service.d.ts.map +1 -0
  89. package/dist/services/form-streaming.service.js +26 -0
  90. package/dist/services/form-streaming.service.js.map +1 -0
  91. package/dist/services/form-validation.service.d.ts +31 -0
  92. package/dist/services/form-validation.service.d.ts.map +1 -0
  93. package/dist/services/form-validation.service.js +158 -0
  94. package/dist/services/form-validation.service.js.map +1 -0
  95. package/dist/streaming/index.d.ts +6 -0
  96. package/dist/streaming/index.d.ts.map +1 -0
  97. package/dist/streaming/index.js +6 -0
  98. package/dist/streaming/index.js.map +1 -0
  99. package/dist/streaming/message-assembler.d.ts +47 -0
  100. package/dist/streaming/message-assembler.d.ts.map +1 -0
  101. package/dist/streaming/message-assembler.js +79 -0
  102. package/dist/streaming/message-assembler.js.map +1 -0
  103. package/dist/streaming/run-state.d.ts +43 -0
  104. package/dist/streaming/run-state.d.ts.map +1 -0
  105. package/dist/streaming/run-state.js +107 -0
  106. package/dist/streaming/run-state.js.map +1 -0
  107. package/dist/streaming/sse-frame-reader.d.ts +17 -0
  108. package/dist/streaming/sse-frame-reader.d.ts.map +1 -0
  109. package/dist/streaming/sse-frame-reader.js +108 -0
  110. package/dist/streaming/sse-frame-reader.js.map +1 -0
  111. package/dist/streaming/stream-event.guard.d.ts +3 -0
  112. package/dist/streaming/stream-event.guard.d.ts.map +1 -0
  113. package/dist/streaming/stream-event.guard.js +16 -0
  114. package/dist/streaming/stream-event.guard.js.map +1 -0
  115. package/dist/streaming/stream-slot.d.ts +16 -0
  116. package/dist/streaming/stream-slot.d.ts.map +1 -0
  117. package/dist/streaming/stream-slot.js +2 -0
  118. package/dist/streaming/stream-slot.js.map +1 -0
  119. package/dist/types/control-action.type.d.ts +43 -4
  120. package/dist/types/control-action.type.d.ts.map +1 -1
  121. package/dist/types/control-condition.type.d.ts +15 -6
  122. package/dist/types/control-condition.type.d.ts.map +1 -1
  123. package/dist/types/control-value.type.d.ts +10 -1
  124. package/dist/types/control-value.type.d.ts.map +1 -1
  125. package/dist/types/index.d.ts +2 -1
  126. package/dist/types/index.d.ts.map +1 -1
  127. package/dist/types/index.js +2 -1
  128. package/dist/types/index.js.map +1 -1
  129. package/dist/types/stream-event.type.d.ts +116 -0
  130. package/dist/types/stream-event.type.d.ts.map +1 -0
  131. package/dist/types/stream-event.type.js +2 -0
  132. package/dist/types/stream-event.type.js.map +1 -0
  133. package/dist/utils/date-serializer.d.ts +16 -0
  134. package/dist/utils/date-serializer.d.ts.map +1 -0
  135. package/dist/utils/date-serializer.js +75 -0
  136. package/dist/utils/date-serializer.js.map +1 -0
  137. package/dist/utils/get-condition-target-id.d.ts +3 -0
  138. package/dist/utils/get-condition-target-id.d.ts.map +1 -0
  139. package/dist/utils/get-condition-target-id.js +15 -0
  140. package/dist/utils/get-condition-target-id.js.map +1 -0
  141. package/dist/utils/has-property.d.ts +2 -0
  142. package/dist/utils/has-property.d.ts.map +1 -0
  143. package/dist/utils/has-property.js +14 -0
  144. package/dist/utils/has-property.js.map +1 -0
  145. package/dist/utils/instantiate.d.ts +2 -0
  146. package/dist/utils/instantiate.d.ts.map +1 -0
  147. package/dist/utils/instantiate.js +4 -0
  148. package/dist/utils/instantiate.js.map +1 -0
  149. package/dist/utils/is-control-required.d.ts +3 -0
  150. package/dist/utils/is-control-required.d.ts.map +1 -0
  151. package/dist/utils/is-control-required.js +5 -0
  152. package/dist/utils/is-control-required.js.map +1 -0
  153. package/dist/utils/is-deeply-equal.d.ts +2 -0
  154. package/dist/utils/is-deeply-equal.d.ts.map +1 -0
  155. package/dist/utils/is-deeply-equal.js +65 -0
  156. package/dist/utils/is-deeply-equal.js.map +1 -0
  157. package/dist/utils/is-object-with-property.d.ts +2 -0
  158. package/dist/utils/is-object-with-property.d.ts.map +1 -0
  159. package/dist/utils/is-object-with-property.js +4 -0
  160. package/dist/utils/is-object-with-property.js.map +1 -0
  161. package/dist/utils/normalize-value.d.ts +2 -0
  162. package/dist/utils/normalize-value.d.ts.map +1 -0
  163. package/dist/utils/normalize-value.js +18 -0
  164. package/dist/utils/normalize-value.js.map +1 -0
  165. package/dist/utils/pub-sub.d.ts +8 -0
  166. package/dist/utils/pub-sub.d.ts.map +1 -0
  167. package/dist/utils/pub-sub.js +35 -0
  168. package/dist/utils/pub-sub.js.map +1 -0
  169. package/dist/utils/simple-conditions.mapper.d.ts +3 -0
  170. package/dist/utils/simple-conditions.mapper.d.ts.map +1 -0
  171. package/dist/utils/simple-conditions.mapper.js +43 -0
  172. package/dist/utils/simple-conditions.mapper.js.map +1 -0
  173. package/package.json +4 -3
  174. package/dist/runtime.d.ts +0 -41
  175. package/dist/runtime.d.ts.map +0 -1
  176. package/dist/runtime.js +0 -98
  177. package/dist/runtime.js.map +0 -1
  178. package/dist/types/control-config.type.d.ts +0 -240
  179. package/dist/types/control-config.type.d.ts.map +0 -1
  180. package/dist/types/control-config.type.js +0 -2
  181. package/dist/types/control-config.type.js.map +0 -1
  182. package/dist/types/types.d.ts +0 -1
  183. package/dist/types/types.d.ts.map +0 -1
  184. package/dist/types/types.js +0 -2
  185. package/dist/types/types.js.map +0 -1
  186. package/dist/utils/control-traverser.d.ts +0 -3
  187. package/dist/utils/control-traverser.d.ts.map +0 -1
  188. package/dist/utils/control-traverser.js +0 -15
  189. package/dist/utils/control-traverser.js.map +0 -1
package/dist/engine.js CHANGED
@@ -1,516 +1,360 @@
1
- import { createRuntime } from './runtime';
2
- import { defaultRegistry, } from './validators';
1
+ import { FormConditionsService } from './services/form-conditions.service';
2
+ import { FormStateService } from './services/form-state.service';
3
+ import { FormModelService } from './services/form-model.service';
4
+ import { FormBatchService } from './services/form-batch.service';
5
+ import { FormStreamingService } from './services/form-streaming.service';
6
+ import { FormValidationService } from './services/form-validation.service';
3
7
  import { assertFeForm } from './guards';
4
- import { evaluateCondition, isBackendConditionGroup } from './conditions';
5
- import { traverseControl } from './utils/control-traverser';
8
+ import { PubSub } from './utils/pub-sub';
9
+ import { instantiate } from './utils/instantiate';
10
+ import { isControlRequired } from './utils/is-control-required';
11
+ import { isDeeplyEqual } from './utils/is-deeply-equal';
6
12
  export class FeFormEngine {
7
- schema;
8
- state;
9
- runtime;
10
- registry;
11
- listeners = new Map();
12
- batchMode = false;
13
- pendingEmits = new Set();
14
- pendingValueChanges = false;
15
- pendingFieldStateChanges = new Map();
16
- pendingErrorsChanges = new Map();
17
- asyncValidators = new Map();
18
- conditions = new Map();
19
- valuesApi;
13
+ _eventBus = instantiate(PubSub);
14
+ _commandBus = instantiate(PubSub);
15
+ stateService = instantiate(FormStateService);
16
+ streamingService = instantiate(FormStreamingService);
17
+ conditionsService = instantiate(FormConditionsService);
18
+ modelService = instantiate(FormModelService);
19
+ validationService = instantiate(FormValidationService, this.stateService);
20
+ batchService = instantiate(FormBatchService, this.stateService, this._eventBus);
21
+ options = {};
20
22
  resolvers;
21
- constructor(schema, options = {}, resolvers = {}, registry = defaultRegistry) {
22
- assertFeForm(schema);
23
- this.schema = schema;
24
- const { state: runtimeState, api: runtimeAPI } = createRuntime();
25
- this.runtime = runtimeAPI;
26
- this.resolvers = resolvers;
27
- this.registry = registry;
28
- this.state = {
29
- values: options.initialValues || this.extractInitialValues(),
30
- errors: {},
31
- touched: {},
32
- dirty: {},
33
- valid: true,
23
+ get commandBus() {
24
+ return {
25
+ execute: (event, ...args) => this._commandBus.emit(event, ...args),
26
+ register: (event, callback) => {
27
+ return this._commandBus.on(event, callback);
28
+ },
34
29
  };
35
- this.valuesApi = {
36
- get: (id, ctx) => {
37
- if (ctx?.index !== undefined) {
38
- return this.state.values[id]?.[ctx.index];
39
- }
40
- else if (ctx?.key !== undefined) {
41
- return this.state.values[id]?.[ctx.key];
42
- }
43
- else {
44
- return this.state.values[id];
45
- }
30
+ }
31
+ get eventBus() {
32
+ return {
33
+ on: (event, listener) => {
34
+ return this._eventBus.on(event, listener);
46
35
  },
47
- set: (id, value, ctx) => {
48
- if (ctx?.index !== undefined) {
49
- if (!Array.isArray(this.state.values[id])) {
50
- this.state.values[id] = [];
51
- }
52
- this.state.values[id][ctx.index] = value;
53
- }
54
- else if (ctx?.key !== undefined) {
55
- if (this.state.values[id] == null || typeof this.state.values[id] !== 'object') {
56
- this.state.values[id] = {};
57
- }
58
- this.state.values[id][ctx.key] = value;
59
- }
60
- else {
61
- this.state.values[id] = value;
62
- }
63
- this.state.dirty[id] = true;
64
- this.runtime.setDirty(id, true);
65
- if (this.batchMode) {
66
- const state = this.runtime.getFieldState(id);
67
- if (state) {
68
- this.pendingFieldStateChanges.set(id, state);
69
- }
70
- }
71
- this.reevaluateDependents(id);
72
- if (this.batchMode) {
73
- this.pendingValueChanges = true;
74
- this.pendingEmits.add('valueChanges');
75
- }
76
- else {
77
- this.emit('valueChanges', { ...this.state.values });
78
- this.validate();
79
- }
36
+ emit: (event, ...args) => {
37
+ this._eventBus.emit(event, ...args);
80
38
  },
81
- getAll: () => ({ ...this.state.values }),
82
39
  };
83
- this.initializeFieldStates();
84
- this.processConditions();
85
- if (options.validateOnChange !== false) {
86
- this.validate();
87
- }
88
- }
89
- triggerAction(e) {
90
- this.emit('action', e);
91
40
  }
92
- processConditions() {
93
- this.buildDependencyGraph();
94
- this.executeConditions();
41
+ get validators() {
42
+ return {
43
+ register: (name, fn) => {
44
+ this.validationService.registerValidator(name, fn);
45
+ },
46
+ registerAsync: (name, fn) => {
47
+ this.validationService.registerAsyncValidator(name, fn);
48
+ },
49
+ };
95
50
  }
96
- initializeFieldStates() {
97
- this.traverseSchema((control) => {
98
- const fieldState = this.runtime.ensureFieldState(control.id);
99
- fieldState.required = this.isControlRequired(control);
100
- fieldState.visible = true;
101
- fieldState.enabled = true;
102
- });
51
+ get form() {
52
+ return {
53
+ getConfig: () => this.modelService.getModel(),
54
+ getState: () => this.stateService.getState(),
55
+ isValid: () => this.stateService.getStatus().valid,
56
+ getDirty: () => this.stateService.getStatus().dirty,
57
+ getErrors: () => this.stateService.getStatus().errors,
58
+ getValue: () => this.stateService.getAllValues(),
59
+ validate: () => this.validate(),
60
+ markTouched: () => {
61
+ this.stateService.markAllTouched((id) => {
62
+ this.emitFieldStateChanges(id);
63
+ });
64
+ },
65
+ markDirty: () => {
66
+ this.stateService.markAllDirty((id) => {
67
+ this.emitFieldStateChanges(id);
68
+ });
69
+ },
70
+ submit: () => this.submitForm(),
71
+ reset: () => this.resetForm(),
72
+ evaluateDependencies: () => this.evaluateAllDependencies(),
73
+ };
103
74
  }
104
- isControlRequired(control) {
105
- return (!!control.required ||
106
- (control.validators ?? []).some((v) => 'function' in v && v.function === 'required'));
75
+ // Live run snapshots
76
+ get stream() {
77
+ return {
78
+ get: (id) => {
79
+ return this.streamingService.getById(id);
80
+ },
81
+ set: (id, snapshot) => {
82
+ this.streamingService.setById(id, snapshot);
83
+ this.emitStreamChanges(id);
84
+ },
85
+ clear: (id) => {
86
+ this.streamingService.clearById(id);
87
+ this.emitStreamChanges(id);
88
+ },
89
+ getAll: () => {
90
+ return this.streamingService.getAll();
91
+ },
92
+ };
107
93
  }
108
- buildDependencyGraph() {
109
- this.traverseSchema((control) => {
110
- if ('condition' in control && control.condition) {
111
- this.extractCondition(control.condition, control.id);
112
- this.extractConditionPaths(control.condition, control.id);
113
- }
94
+ constructor(model, options = {}, resolvers = {}, registry) {
95
+ assertFeForm(model);
96
+ this.resolvers = resolvers;
97
+ this.options = options;
98
+ this.modelService.setModel(model);
99
+ if (registry) {
100
+ this.validationService.setRegistry(registry);
101
+ }
102
+ this.init();
103
+ this.evaluateAllDependencies();
104
+ if (options.validateOnChange !== false) {
105
+ this.validate();
106
+ }
107
+ this._commandBus.on('updateControl', (id, config) => {
108
+ this.updateControlById(id, config);
114
109
  });
115
- }
116
- executeConditions() {
117
- const keys = this.runtime.getDependenciesKeys();
118
- keys.forEach((key) => {
119
- this.reevaluateDependents(key);
110
+ this.validationService.on('fieldStateChanges', (id) => {
111
+ this.emitFieldStateChanges(id);
112
+ });
113
+ this.validationService.on('errorsChanges', (id) => {
114
+ this.emitErrorsChanges(id);
115
+ });
116
+ this.validationService.on('statusChanges', () => {
117
+ this.emitStatusChanges();
120
118
  });
121
119
  }
122
- extractCondition(condition, targetId) {
123
- this.conditions.set(targetId, condition);
124
- }
125
- extractConditionPaths(condition, targetId) {
126
- // FeBackendConditionGroup
127
- if (isBackendConditionGroup(condition)) {
128
- if ('conditions' in condition && condition.conditions) {
129
- for (const cond of condition.conditions) {
130
- this.extractConditionPaths(cond, targetId);
120
+ control(id, ctx) {
121
+ return {
122
+ getConfig: () => this.modelService.getControlById(id),
123
+ getState: () => this.stateService.ensureFieldState(id),
124
+ isTouched: () => this.stateService.ensureFieldState(id).touched,
125
+ getStatus: () => this.stateService.ensureFieldState(id).status,
126
+ isDirty: () => this.stateService.ensureFieldState(id).dirty,
127
+ isRequired: () => this.stateService.ensureFieldState(id).required,
128
+ isVisible: () => this.stateService.ensureFieldState(id).visible,
129
+ isEnabled: () => this.stateService.ensureFieldState(id).enabled,
130
+ isValid: () => this.stateService.ensureFieldState(id).status === 'VALID',
131
+ getValue: () => this.stateService.getFieldValue(id, ctx),
132
+ setValue: (value) => {
133
+ this.stateService.setFieldValue(id, value, ctx);
134
+ this.stateService.setFieldDirty(id, true);
135
+ if (this.batchService.isBatching) {
136
+ const state = this.stateService.getFieldState(id);
137
+ if (state) {
138
+ this.batchService.setFieldStateChanges(id, state);
139
+ }
131
140
  }
132
- }
133
- }
134
- // FeBackendSimpleCondition
135
- if ('target_id' in condition && condition.target_id) {
136
- this.runtime.addDependency(condition.target_id, targetId);
137
- }
138
- }
139
- reevaluateDependents(changedId) {
140
- const visited = new Set();
141
- const queue = [changedId];
142
- while (queue.length > 0) {
143
- const currentId = queue.shift();
144
- if (visited.has(currentId))
145
- continue;
146
- visited.add(currentId);
147
- const dependents = this.runtime.getDependents(currentId);
148
- for (const dependentId of dependents) {
149
- if (!visited.has(dependentId)) {
150
- queue.push(dependentId);
151
- this.evaluateFieldConditions(dependentId);
141
+ this.evaluateDependencyById(id);
142
+ if (this.batchService.isBatching) {
143
+ this.batchService.setValuesChanges(true);
152
144
  }
153
- }
154
- }
155
- }
156
- evaluateFieldConditions(id) {
157
- const condition = this.conditions.get(id);
158
- if (!condition)
159
- return; // no condition → nothing to evaluate → no change
160
- const result = this.evaluateCondition(condition);
161
- const fieldState = this.runtime.getFieldState(id);
162
- if (!fieldState)
163
- return;
164
- const wasVisible = fieldState.visible;
165
- if (wasVisible === result)
166
- return; // no change → no emission
167
- this.runtime.setVisible(id, result);
168
- this.emitFieldStateChange(id);
169
- }
170
- evaluateCondition(condition) {
171
- return evaluateCondition(condition, this.state.values);
172
- }
173
- emitFieldStateChange(id) {
174
- const state = this.runtime.getFieldState(id);
175
- if (!state)
176
- return;
177
- if (this.batchMode) {
178
- this.pendingFieldStateChanges.set(id, state);
179
- this.pendingEmits.add('fieldStateChanges');
180
- }
181
- else {
182
- this.emit('fieldStateChanges', id, state);
183
- }
184
- }
185
- emitErrorsChange(id, errors) {
186
- if (this.batchMode) {
187
- this.pendingErrorsChanges.set(id, errors);
188
- this.pendingEmits.add('errorsChanges');
189
- }
190
- else {
191
- this.emit('errorsChanges', id, errors);
192
- }
145
+ else {
146
+ this._eventBus.emit('valueChanges', this.stateService.getAllValues());
147
+ this._eventBus.emit('fieldValueChanges', id, value, ctx);
148
+ this.validate();
149
+ }
150
+ },
151
+ setEnabled: (enabled) => {
152
+ const state = this.stateService.getFieldState(id);
153
+ if (state && state.enabled === enabled)
154
+ return;
155
+ this.stateService.setFieldEnabled(id, enabled);
156
+ this.emitFieldStateChanges(id);
157
+ // Turning a field off takes it out of the validation pass, turning it on puts it back:
158
+ // either way the form's verdict changes, and the field's own errors are from the last
159
+ // pass that saw it. Run one now rather than leave both to be read stale.
160
+ this.validate();
161
+ },
162
+ validate: () => this.validateByControlId(id),
163
+ getErrors: () => this.stateService.ensureFieldState(id).errors,
164
+ markTouched: () => {
165
+ this.stateService.setFieldTouched(id, true);
166
+ this.emitFieldStateChanges(id);
167
+ this.emitStatusChanges();
168
+ },
169
+ markDirty: () => {
170
+ this.stateService.setFieldDirty(id, true);
171
+ this.emitFieldStateChanges(id);
172
+ },
173
+ evaluateDependencies: () => {
174
+ this.evaluateDependencyById(id);
175
+ },
176
+ reset: () => {
177
+ this.stateService.setFieldTouched(id, false);
178
+ this.stateService.setFieldDirty(id, false);
179
+ this.emitFieldStateChanges(id);
180
+ },
181
+ };
193
182
  }
194
- extractInitialValues() {
195
- const values = {};
196
- this.traverseSchema((control) => {
197
- if ('value' in control && control.value !== undefined) {
198
- values[control.id] = control.value;
199
- }
200
- });
201
- return values;
183
+ batch(fn) {
184
+ this.batchService.batch(fn, () => this.validate());
202
185
  }
203
- get values() {
204
- return this.valuesApi;
186
+ dispose() {
187
+ this._eventBus.dispose();
188
+ this._commandBus.dispose();
205
189
  }
206
- get status() {
207
- return {
208
- valid: this.state.valid,
209
- errors: { ...this.state.errors },
210
- touched: { ...this.state.touched },
211
- dirty: { ...this.state.dirty },
190
+ validateByControlId(id) {
191
+ const validationState = {
192
+ isValid: true,
193
+ errors: {},
212
194
  };
195
+ const control = this.modelService.getControlById(id);
196
+ if (!control)
197
+ return undefined;
198
+ this.processFieldValidation(control, validationState);
199
+ return validationState.isValid;
213
200
  }
214
- getFieldState(id) {
215
- return this.runtime.ensureFieldState(id);
201
+ validate() {
202
+ const validationState = {
203
+ isValid: true,
204
+ errors: {},
205
+ };
206
+ this.modelService.traverse((control) => {
207
+ this.processFieldValidation(control, validationState);
208
+ }, {
209
+ shouldTraverseDeep: (control) => {
210
+ // Skip hidden controls and children
211
+ const state = this.stateService.getFieldState(control.id);
212
+ return !!state?.visible;
213
+ },
214
+ shouldVisit: (control) => {
215
+ const state = this.stateService.getFieldState(control.id);
216
+ return !!state && state.enabled;
217
+ },
218
+ });
219
+ this.emitStatusChanges();
220
+ return validationState.isValid;
216
221
  }
217
- registerValidator(name, fn) {
218
- this.registry.register(name, fn);
222
+ evaluateDependencyById(id) {
223
+ this.processEvaluationResults(this.conditionsService.evaluateDependencyById(id, this.stateService.getAllValues()));
219
224
  }
220
- registerAsyncValidator(name, fn) {
221
- this.registry.registerAsync(name, fn);
225
+ evaluateAllDependencies() {
226
+ this.processEvaluationResults(this.conditionsService.evaluateAllDependencies(this.stateService.getAllValues()));
222
227
  }
223
- batch(fn) {
224
- const wasBatching = this.batchMode;
225
- this.batchMode = true;
226
- if (!wasBatching) {
227
- this.pendingEmits.clear();
228
- this.pendingValueChanges = false;
229
- this.pendingFieldStateChanges.clear();
230
- this.pendingErrorsChanges.clear();
231
- }
232
- try {
233
- fn();
234
- }
235
- finally {
236
- this.batchMode = wasBatching;
237
- if (!wasBatching) {
238
- if (this.pendingValueChanges) {
239
- this.emit('valueChanges', { ...this.state.values });
240
- }
241
- const affectedIds = new Set();
242
- for (const id of this.pendingFieldStateChanges.keys()) {
243
- affectedIds.add(id);
244
- }
245
- for (const id of affectedIds) {
246
- const state = this.runtime.getFieldState(id);
247
- if (state) {
248
- this.emit('fieldStateChanges', id, state);
249
- }
250
- }
251
- this.validate();
252
- for (const [id, errors] of this.pendingErrorsChanges) {
253
- this.emit('errorsChanges', id, errors);
254
- }
255
- // for (const id of affectedIds) {
256
- // const state = this.runtime.getFieldState(id);
257
- // if (state && !this.pendingFieldStateChanges.has(id)) {
258
- // this.emit('fieldStateChanges', id, state);
259
- // }
260
- // }
261
- }
228
+ submitForm() {
229
+ this.form.markTouched();
230
+ if (!this.validate()) {
231
+ return null;
262
232
  }
233
+ const values = this.stateService.getAllValues();
234
+ this._eventBus.emit('submit', values);
235
+ return values;
236
+ }
237
+ resetForm() {
238
+ this.validationService.clear();
239
+ this.stateService.clear();
240
+ this.clearAllStreams();
241
+ this.init();
242
+ this._eventBus.emit('valueChanges', this.stateService.getAllValues());
243
+ this.validate();
263
244
  }
264
- on(event, listener) {
265
- if (!this.listeners.has(event)) {
266
- this.listeners.set(event, new Set());
245
+ /**
246
+ * A reset ends whatever was on screen, live runs included - and every control that was
247
+ * drawing one has to be told, or it keeps showing the answer that was being written.
248
+ */
249
+ clearAllStreams() {
250
+ const runningIds = this.streamingService.getIds();
251
+ this.streamingService.clearAll();
252
+ for (const id of runningIds) {
253
+ this.emitStreamChanges(id);
267
254
  }
268
- this.listeners.get(event).add(listener);
269
- return () => {
270
- this.listeners.get(event)?.delete(listener);
271
- };
272
255
  }
273
- emit(event, ...args) {
274
- this.listeners.get(event)?.forEach((listener) => {
275
- try {
276
- listener(...args);
256
+ init() {
257
+ this.modelService.traverse((control) => {
258
+ const initialValue = this.options.initialValues?.[control.id];
259
+ // Only an absent key means "no initial value": `false`, `0` and `''` are values a form
260
+ // carries like any other, and a truthy check would silently drop them.
261
+ if (initialValue !== undefined) {
262
+ control.value = initialValue;
277
263
  }
278
- catch (error) {
279
- console.error(`Error in "${event}" listener:`, error);
264
+ this.initControlState(control);
265
+ this.initControlConditions(control);
266
+ });
267
+ this.evaluateAllDependencies();
268
+ }
269
+ processEvaluationResults(results) {
270
+ results.forEach((result, id) => {
271
+ const state = this.stateService.getFieldState(id);
272
+ if (state && typeof result !== 'undefined' && state.visible !== result) {
273
+ this.stateService.setFieldVisible(id, result);
274
+ this.emitFieldStateChanges(id);
280
275
  }
281
276
  });
282
277
  }
283
- validate() {
284
- const validationState = {
285
- isValid: true,
286
- errors: {},
287
- };
288
- const visitor = (control) => {
289
- const fieldErrors = [];
290
- if (control.validators) {
291
- for (const validatorConfig of control.validators) {
292
- if ('function' in validatorConfig) {
293
- const syncValidator = this.registry.get(validatorConfig.function);
294
- const asyncValidator = this.registry.getAsync(validatorConfig.function);
295
- if (syncValidator) {
296
- this.validateSync(control, syncValidator, validatorConfig, fieldErrors, validationState);
297
- }
298
- else {
299
- // Fallback to built-in validator
300
- this.validateSyncWithBuildInValidators(control, validatorConfig, fieldErrors, validationState);
301
- }
302
- if (asyncValidator && validationState.isValid && !fieldErrors.length) {
303
- this.validateAsync(control, asyncValidator, validatorConfig);
304
- }
305
- }
306
- }
307
- }
308
- if ('validation' in control && control.validation) {
309
- const error = this.validateBackend(control.validation);
310
- if (error) {
311
- validationState.errors[control.id] = error;
312
- validationState.isValid = false;
313
- fieldErrors.push({
314
- code: 'backendValidation',
315
- args: error,
316
- });
317
- }
318
- }
319
- const fieldState = this.runtime.getFieldState(control.id);
320
- if (fieldState) {
321
- const hadErrors = fieldState.errors.length > 0;
322
- this.runtime.setErrors(control.id, fieldErrors);
323
- this.runtime.setStatus(control.id, fieldErrors.length > 0 ? 'INVALID' : 'VALID');
324
- if (hadErrors !== fieldErrors.length > 0) {
325
- this.emitErrorsChange(control.id, fieldErrors);
326
- }
327
- }
328
- };
329
- // Validate only visible controls
330
- const shouldVisit = (control) => {
331
- const state = this.runtime.getFieldState(control.id);
332
- return !!state?.visible;
333
- };
334
- this.traverseSchema(visitor, shouldVisit);
335
- this.state.errors = validationState.errors;
336
- this.state.valid = validationState.isValid;
337
- if (!this.batchMode) {
338
- this.emit('statusChanges', {
339
- valid: validationState.isValid,
340
- errors: validationState.errors,
341
- });
278
+ initControlState(control) {
279
+ this.stateService.ensureFieldState(control.id);
280
+ if (typeof control.value !== 'undefined') {
281
+ this.stateService.setFieldValue(control.id, control.value);
342
282
  }
343
- else {
344
- this.pendingEmits.add('statusChanges');
283
+ if (typeof control.meta.readOnly !== 'undefined') {
284
+ this.stateService.setFieldEnabled(control.id, !control.meta.readOnly);
345
285
  }
346
- return validationState.isValid;
286
+ this.stateService.setFieldRequired(control.id, isControlRequired(control));
347
287
  }
348
- validateSync(control, validator, config, fieldErrors, validationState) {
349
- const value = this.state.values[control.id];
350
- const result = validator(value, config.value, {
351
- get: (id) => this.state.values[id],
352
- });
353
- if (!result.valid && result.error) {
354
- validationState.errors[control.id] = result.error.args || { [result.error.code]: true };
355
- validationState.isValid = false;
356
- fieldErrors.push({
357
- code: result.error.code,
358
- message: result.error.message,
359
- args: result.error.args,
360
- });
361
- this.emitFieldStateChange(control.id);
288
+ initControlConditions(control) {
289
+ if (control.meta.condition) {
290
+ this.conditionsService.setByControlId(control.id, control.meta.condition);
362
291
  }
363
292
  }
364
- validateSyncWithBuildInValidators(control, config, fieldErrors, validationState) {
365
- const registryFn = defaultRegistry.get(config.function);
366
- if (!registryFn)
293
+ emitFieldStateChanges(id) {
294
+ const state = this.stateService.getFieldState(id);
295
+ if (!state)
367
296
  return;
368
- const value = this.state.values[control.id];
369
- const result = registryFn(value, config.value, { get: (id) => this.state.values[id] });
370
- if (!result.valid && result.error) {
371
- validationState.errors[control.id] = result.error.args ?? { [result.error.code]: true };
372
- validationState.isValid = false;
373
- fieldErrors.push({
374
- code: result.error.code,
375
- message: result.error.message,
376
- args: result.error.args,
377
- });
378
- this.emitFieldStateChange(control.id);
297
+ if (this.batchService.isBatching) {
298
+ this.batchService.setFieldStateChanges(id, state);
299
+ }
300
+ else {
301
+ this._eventBus.emit('fieldStateChanges', id, state);
379
302
  }
380
303
  }
381
- validateAsync(control, validator, config) {
382
- const value = this.state.values[control.id];
383
- const existingController = this.asyncValidators.get(control.id);
384
- if (existingController) {
385
- existingController.abort();
304
+ emitErrorsChanges(id) {
305
+ const fieldState = this.stateService.getFieldState(id);
306
+ if (!fieldState)
307
+ return;
308
+ if (this.batchService.isBatching) {
309
+ this.batchService.setErrorsChanges(id, fieldState.errors);
386
310
  }
387
- const fieldState = this.runtime.getFieldState(control.id);
388
- if (fieldState) {
389
- this.runtime.setStatus(control.id, 'PENDING');
390
- this.emitFieldStateChange(control.id);
311
+ else {
312
+ this._eventBus.emit('errorsChanges', id, fieldState.errors);
391
313
  }
392
- const controller = new AbortController();
393
- this.asyncValidators.set(control.id, controller);
394
- const ctx = {
395
- get: (id) => this.state.values[id],
396
- signal: controller.signal,
397
- };
398
- validator(value, config.value, ctx)
399
- .then((result) => {
400
- if (controller.signal.aborted || this.asyncValidators.get(control.id) !== controller) {
401
- return;
402
- }
403
- this.asyncValidators.delete(control.id);
404
- if (!result.valid && result.error) {
405
- const fieldErrors = [
406
- {
407
- code: result.error.code,
408
- message: result.error.message,
409
- args: result.error.args,
410
- },
411
- ];
412
- this.state.errors = {
413
- ...this.state.errors,
414
- [control.id]: result.error.args ?? { [result.error.code]: true },
415
- };
416
- this.runtime.setErrors(control.id, fieldErrors);
417
- this.runtime.setStatus(control.id, 'INVALID');
418
- this.emitErrorsChange(control.id, fieldErrors);
419
- }
420
- else {
421
- // SUCCESS: actively clear any prior error for this field
422
- const { [control.id]: _removed, ...rest } = this.state.errors;
423
- this.state.errors = rest;
424
- this.runtime.setErrors(control.id, []);
425
- this.runtime.setStatus(control.id, 'VALID');
426
- this.emitErrorsChange(control.id, []);
427
- }
428
- this.state.valid = Object.keys(this.state.errors).length === 0;
429
- this.emitFieldStateChange(control.id);
430
- this.emit('statusChanges', { valid: this.state.valid, errors: this.state.errors });
431
- })
432
- .catch((error) => {
433
- if (!controller.signal.aborted) {
434
- console.error(`Async validator error for ${control.id}:`, error);
435
- this.runtime.setStatus(control.id, 'VALID');
436
- this.asyncValidators.delete(control.id);
437
- }
438
- });
439
314
  }
440
- validateBackend(validation) {
441
- const ok = evaluateCondition(validation, this.state.values);
442
- if (!ok) {
443
- return { backendValidation: { message: 'Validation failed', validation } };
315
+ emitStatusChanges() {
316
+ if (this.batchService.isBatching) {
317
+ this.batchService.setEmits('statusChanges');
444
318
  }
445
- return null;
446
- }
447
- markTouched(id) {
448
- this.state.touched[id] = true;
449
- this.runtime.setTouched(id, true);
450
- this.emitFieldStateChange(id);
451
- if (!this.batchMode) {
452
- this.emit('statusChanges', { valid: this.state.valid, errors: this.state.errors });
319
+ else {
320
+ this._eventBus.emit('statusChanges', this.stateService.getStatus());
453
321
  }
454
322
  }
455
- markAllTouched() {
456
- this.traverseSchema((control) => {
457
- this.markTouched(control.id);
458
- });
459
- }
460
- markAsDirty(id) {
461
- this.runtime.setDirty(id, true);
462
- this.state.dirty[id] = true;
463
- this.emitFieldStateChange(id);
464
- }
465
- markAllAsDirty() {
466
- this.traverseSchema((control) => {
467
- this.markAsDirty(control.id);
468
- });
469
- }
470
- resetById(id) {
471
- this.state.touched[id] = false;
472
- this.state.dirty[id] = false;
473
- this.runtime.setTouched(id, false);
474
- this.runtime.setDirty(id, false);
475
- this.emitFieldStateChange(id);
476
- }
477
- submit() {
478
- this.markAllTouched();
479
- if (!this.validate()) {
480
- return null;
323
+ emitStreamChanges(id) {
324
+ const snapshot = this.streamingService.getById(id);
325
+ if (this.batchService.isBatching) {
326
+ this.batchService.setStreamChanges(id, snapshot);
327
+ }
328
+ else {
329
+ this._eventBus.emit('streamChanges', id, snapshot);
481
330
  }
482
- const values = this.values.getAll();
483
- this.emit('submit', values);
484
- return values;
485
331
  }
486
- reset(values) {
487
- for (const controller of this.asyncValidators.values())
488
- controller.abort();
489
- this.asyncValidators.clear();
490
- this.state.values = values || this.extractInitialValues();
491
- this.state.errors = {};
492
- this.state.touched = {};
493
- this.state.dirty = {};
494
- this.state.valid = true;
495
- this.traverseSchema((control) => {
496
- this.runtime.setTouched(control.id, false);
497
- this.runtime.setDirty(control.id, false);
498
- this.runtime.setErrors(control.id, []);
499
- this.runtime.setStatus(control.id, 'VALID');
332
+ updateControlById(id, value) {
333
+ this.modelService.traverse((control) => {
334
+ if (control.id === id) {
335
+ Object.assign(control, value);
336
+ this.stateService.setFieldValue(control.id, value);
337
+ this.initControlState(control);
338
+ }
339
+ this.initControlConditions(control);
500
340
  });
501
- this.emit('valueChanges', { ...this.state.values });
502
- this.validate();
341
+ this.modelService.refresh();
342
+ this.evaluateAllDependencies();
503
343
  }
504
- traverseSchema(visit, shouldVisit = () => true) {
505
- this.schema.sections.forEach((section) => {
506
- section.controls.forEach((control) => traverseControl(control, visit, shouldVisit));
507
- });
508
- if (this.schema.controls) {
509
- this.schema.controls.forEach((control) => traverseControl(control, visit, shouldVisit));
344
+ processFieldValidation(control, validationState) {
345
+ const fieldState = this.stateService.getFieldState(control.id);
346
+ if (!fieldState)
347
+ return;
348
+ const prevErrors = fieldState.errors.slice();
349
+ const errors = this.validationService.validateControl(control, validationState);
350
+ this.stateService.setFieldErrors(control.id, errors);
351
+ this.stateService.setFieldStatus(control.id, errors.length > 0 ? 'INVALID' : 'VALID');
352
+ if (!isDeeplyEqual(prevErrors, fieldState.errors)) {
353
+ this.emitErrorsChanges(control.id);
510
354
  }
511
355
  }
512
356
  }
513
- export function createEngine(schema, options, resolvers) {
514
- return new FeFormEngine(schema, options, resolvers);
357
+ export function createEngine(model, options, resolvers) {
358
+ return new FeFormEngine(model, options, resolvers);
515
359
  }
516
360
  //# sourceMappingURL=engine.js.map