@planeasyinc/fe-core 0.1.32 → 0.1.34

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