-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathinstance.ts
More file actions
810 lines (668 loc) · 28.3 KB
/
instance.ts
File metadata and controls
810 lines (668 loc) · 28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
import {
FormMarkupWithSettings,
FormMode,
IComponentRelations,
IComponentsDictionary,
IConfigurableFormComponent,
IFlatComponentsStructure,
IFormSettings,
IFormValidationErrors,
IRawComponentsContainer,
isConfigurableFormComponent,
ISettingsFormFactory,
isRawComponentsContainer,
IToolboxComponent,
IToolboxComponentGroup,
IToolboxComponents,
ROOT_COMPONENT_KEY,
} from "@/interfaces";
import { isDefined, isNullOrWhiteSpace } from "@/utils/nullables";
import { camelcaseDotNotation } from '@/utils/string';
import { nanoid } from "@/utils/uuid";
import { toolbarGroupsToComponents } from "../form/hooks";
import { componentsFlatStructureToTree, createComponentModelForDataProperty, processRecursive, upgradeComponent } from "../form/utils";
import {
FormDesignerFormState,
IAddDataPropertyPayload,
IComponentAddPayload,
IComponentDeletePayload,
IComponentDuplicatePayload,
IComponentUpdatePayload,
IComponentUpdateSettingsValidationPayload,
IFormDesignerInstance,
IUpdateChildComponentsPayload,
} from "./contexts";
import { BaseHistoryItem, FormDesignerSubscription, FormDesignerSubscriptionType, IComponentSettingsEditorsCache } from "./models";
import { IUndoRedoManager, UndoRedoManager } from "./undoRedoManager";
import { IFormPersisterContext } from "../formPersisterProvider/contexts";
export type FormDesignerArgs = {
readOnly: boolean;
toolboxComponentGroups: IToolboxComponentGroup[];
formFlatMarkup: IFlatComponentsStructure;
formSettings: IFormSettings;
logEnabled?: boolean;
formPersister: IFormPersisterContext;
};
const isComponentsArray = (value: unknown): value is IConfigurableFormComponent[] => {
return Array.isArray(value) && value.every(isConfigurableFormComponent);
};
type IPlainComponentsContainer = {
id: string;
components: IConfigurableFormComponent[];
};
const isPlainContainer = (value: unknown): value is IPlainComponentsContainer => {
return isDefined(value) && typeof (value) === 'object' && 'components' in value && isComponentsArray(value.components) &&
'id' in value && typeof (value.id) === 'string';
};
const idArraysEqual = (array1: string[], array2: string[]): boolean => {
return array1.length === array2.length && array1.every((value, index) => value === array2[index]);
};
export class FormDesignerInstance implements IFormDesignerInstance {
undoableState: IUndoRedoManager<FormDesignerFormState>;
toolboxComponentGroups: IToolboxComponentGroup[];
toolboxComponents: IToolboxComponents;
formPersister: IFormPersisterContext;
isDragging: boolean;
hasDragged: boolean;
isDebug: boolean;
readOnly: boolean;
formMode: FormMode;
get state(): FormDesignerFormState {
return this.undoableState.getState();
}
constructor(args: FormDesignerArgs) {
this.toolboxComponentGroups = args.toolboxComponentGroups;
this.toolboxComponents = toolbarGroupsToComponents(args.toolboxComponentGroups);
this.formPersister = args.formPersister;
this.readOnly = args.readOnly;
this.isDebug = false;
this.formMode = 'designer';
this.isDragging = false;
this.hasDragged = false;
this.isDataModified = false;
this.subscriptions = new Map<FormDesignerSubscriptionType, Set<FormDesignerSubscription>>();
// eslint-disable-next-line no-console
this.log = args.logEnabled ? console.log : () => { };
const initialState: FormDesignerFormState = {
formFlatMarkup: args.formFlatMarkup,
formSettings: args.formSettings,
};
this.undoableState = new UndoRedoManager<FormDesignerFormState>(initialState);
}
isDataModified: boolean;
loadAsync = async (): Promise<void> => {
await this.formPersister.loadForm({ skipCache: true });
this.isDataModified = false;
this.notifySubscribers(['data-modified']);
};
saveAsync = async (): Promise<void> => {
const { formFlatMarkup, formSettings } = this.state;
const payload: FormMarkupWithSettings = {
components: componentsFlatStructureToTree(this.toolboxComponents, formFlatMarkup),
formSettings: formSettings,
};
await this.formPersister.saveForm(payload);
this.isDataModified = false;
this.notifySubscribers(['data-modified']);
};
log = (..._args: unknown[]): void => {
// noop
};
setMarkupAndSettings = (flatMarkup: IFlatComponentsStructure, settings: IFormSettings): void => {
this.log('FD: setMarkupAndSettings', flatMarkup, settings);
this.undoableState.setState({
formFlatMarkup: flatMarkup,
formSettings: settings,
});
this.selectedComponentId = undefined;
this.isDataModified = false;
this.notifySubscribers(['markup', 'selection', 'history', 'data-modified']);
};
validationErrors?: IFormValidationErrors | undefined;
selectedComponentId: string | undefined;
settingsPanelElement: HTMLDivElement | null = null;
setSettingsPanelElement = (element: HTMLDivElement | null): void => {
this.settingsPanelElement = element;
this.notifySubscribers(['selection']);
};
private getToolboxComponentOrUndefined = (type: string): IToolboxComponent | undefined => {
return this.toolboxComponents[type];
};
private getToolboxComponent = (type: string): IToolboxComponent => {
const component = this.getToolboxComponentOrUndefined(type);
if (!isDefined(component))
throw new Error(`Cannot find toolbox component with type ${type}`);
return component;
};
private getComponentOrContainer = (id: string): IConfigurableFormComponent | IRawComponentsContainer => {
const { formFlatMarkup } = this.state;
const component = formFlatMarkup.allComponents[id];
if (!isDefined(component))
throw new Error(`Cannot find component with id ${id}`);
return component;
};
private getComponent = (id: string): IConfigurableFormComponent => {
const result = this.getComponentOrContainer(id);
if (!isConfigurableFormComponent(result))
throw new Error(`Item with id ${id} is not a configurable form component`);
return result;
};
private setParentId = (item: IConfigurableFormComponent | IRawComponentsContainer, parentId: string): void => {
if ("parentId" in item && typeof (item.parentId) === "string")
item.parentId = parentId;
};
private cloneComponent = <TC extends IConfigurableFormComponent | IRawComponentsContainer = IConfigurableFormComponent | IRawComponentsContainer>(
component: TC,
nestedComponents: IComponentsDictionary,
nestedRelations: IComponentRelations,
): TC => {
const newId = nanoid();
const clone: TC = { ...component, id: newId };
nestedComponents[newId] = clone;
const { formFlatMarkup } = this.state;
// handle nested components by id of the parent
const srcNestedComponents = formFlatMarkup.componentRelations[component.id];
if (srcNestedComponents) {
const relations: string[] = [];
nestedRelations[clone.id] = relations;
srcNestedComponents.forEach((childId) => {
const child = this.getComponentOrContainer(childId);
const childClone = this.cloneComponent(child, nestedComponents, nestedRelations);
this.setParentId(childClone, clone.id);
relations.push(childClone.id);
});
}
// component.type is empty for raw containers
if (isConfigurableFormComponent(component) && !isNullOrWhiteSpace(component.type)) {
if (!isConfigurableFormComponent(clone))
throw new Error('Clone is not a configurable form component');
const toolboxComponent = this.getToolboxComponent(component.type);
const containers = toolboxComponent.customContainerNames ?? [];
// handle containers
containers.forEach((key) => {
const cntName = key as keyof IConfigurableFormComponent;
const srcContainer = cntName in component && typeof (component[cntName]) === 'object' && (isConfigurableFormComponent(component[cntName]) || isRawComponentsContainer(component[cntName]) || Array.isArray(component[cntName]))
? component[cntName]
: undefined;
if (srcContainer) {
// add clone recursively
const relations: string[] = [];
nestedRelations[clone.id] = relations;
const cloneChild = <T extends IConfigurableFormComponent | IRawComponentsContainer = IConfigurableFormComponent | IRawComponentsContainer>(c: T): T => {
// child may be component or any object with id
const childClone = this.cloneComponent<T>(c, nestedComponents, nestedRelations);
this.setParentId(childClone, clone.id);
relations.push(childClone.id);
return childClone;
};
if (isConfigurableFormComponent(srcContainer)) {
(clone[cntName] as IConfigurableFormComponent) = cloneChild(srcContainer);
} else
if (isRawComponentsContainer(srcContainer)) {
(clone[cntName] as IRawComponentsContainer) = cloneChild(srcContainer);
} else {
if (Array.isArray(srcContainer)) {
(clone[cntName] as IConfigurableFormComponent[]) = srcContainer.map((c) => {
if (!isConfigurableFormComponent(c))
throw new Error('Not configurable form component');
return cloneChild(c);
});
}
}
}
});
}
return clone;
};
private getContainerNames = (toolboxComponent: IToolboxComponent): string[] => {
return toolboxComponent.customContainerNames
? [...(toolboxComponent.customContainerNames ?? [])]
: ['components'];
};
private cloneComponents = (components: IConfigurableFormComponent[]): IConfigurableFormComponent[] => {
const result: IConfigurableFormComponent[] = [];
components.forEach((component) => {
const clone: IConfigurableFormComponent = { ...component, id: nanoid() };
result.push(clone);
const toolboxComponent = this.getToolboxComponent(component.type);
const containers = this.getContainerNames(toolboxComponent);
containers.forEach((cnt) => {
const containerName = cnt as keyof IConfigurableFormComponent;
const container: unknown = clone[containerName];
if (isComponentsArray(container)) {
const newChilds = this.cloneComponents(clone[containerName] as IConfigurableFormComponent[]);
(clone[containerName] as IConfigurableFormComponent[]) = newChilds;
} else
if (isPlainContainer(container)) {
const containerClone = { ...container, id: nanoid() };
containerClone.components = this.cloneComponents(container.components);
(clone[containerName] as IPlainComponentsContainer) = containerClone;
}
});
});
return result;
};
private addComponentToFlatStructure = (
formFlatMarkup: IFlatComponentsStructure,
formComponents: IConfigurableFormComponent[],
containerId: string,
index: number,
): IFlatComponentsStructure => {
// build all components dictionary
const allComponents = { ...formFlatMarkup.allComponents };
const childRelations: IComponentRelations = {};
formComponents.forEach((component) => {
processRecursive(this.toolboxComponentGroups, containerId, component, (cmp, parentId) => {
allComponents[cmp.id] = cmp;
if (parentId !== containerId) {
const relations = childRelations[parentId] ?? [];
childRelations[parentId] = [...relations, cmp.id];
}
});
});
const currentLevel = containerId;
// add component(s) to the parent container
const containerComponents = isDefined(formFlatMarkup.componentRelations[currentLevel])
? [...formFlatMarkup.componentRelations[currentLevel]]
: [];
formComponents.forEach((component) => {
containerComponents.splice(index, 0, component.id);
});
const componentRelations = {
...formFlatMarkup.componentRelations,
[currentLevel]: containerComponents,
...childRelations,
};
return {
allComponents,
componentRelations,
};
};
deleteComponent = (payload: IComponentDeletePayload): void => {
this.log('FD: deleteComponent', payload);
this.updateState((state): FormDesignerFormState => {
const { formFlatMarkup } = state;
const { [payload.componentId]: component, ...allComponents } = formFlatMarkup.allComponents;
if (!component)
throw new Error(`Cannot find component with id ${payload.componentId}`);
// delete self as parent
const componentRelations = { ...formFlatMarkup.componentRelations };
delete componentRelations[payload.componentId];
// delete self as child
if (isConfigurableFormComponent(component) && component.parentId) {
const parentRelations = [...(componentRelations[component.parentId] ?? [])];
const childIndex = parentRelations.indexOf(payload.componentId);
parentRelations.splice(childIndex, 1);
componentRelations[component.parentId] = parentRelations;
} else console.warn(`component ${payload.componentId} has no parent`);
if (this.selectedComponentId === payload.componentId)
this.selectedComponentId = undefined; // clear selection if we delete current component
return {
...state,
formFlatMarkup: {
allComponents,
componentRelations,
},
};
}, `Removed component ${payload.componentId}`);
};
getComponentsCount = (components: IComponentsDictionary, type: string): number => {
let count = 0;
for (const key in components) {
if (isDefined(components[key]) && isConfigurableFormComponent(components[key]) && components[key].type === type)
count++;
}
return count;
};
generateNewComponentName = (components: IComponentsDictionary, toolboxComponent: IToolboxComponent): string => {
const count = this.getComponentsCount(components, toolboxComponent.type);
return `${toolboxComponent.name}${count + 1}`;
};
duplicateComponent = (payload: IComponentDuplicatePayload): void => {
this.log('FD: duplicateComponent', payload);
this.updateState((state): FormDesignerFormState => {
const { formFlatMarkup } = state;
const srcComponent = this.getComponent(payload.componentId);
const nestedComponents: IComponentsDictionary = {};
const nestedRelations: IComponentRelations = {};
const clone = this.cloneComponent(srcComponent, nestedComponents, nestedRelations);
const toolboxComponent = this.getToolboxComponent(clone.type);
const componentName = this.generateNewComponentName(formFlatMarkup.allComponents, toolboxComponent);
clone.componentName = camelcaseDotNotation(componentName);
clone.label = componentName;
const parentRelations = srcComponent.parentId
? [...(formFlatMarkup.componentRelations[srcComponent.parentId] ?? [])]
: [];
const cloneIndex = parentRelations.indexOf(srcComponent.id) + 1;
parentRelations.splice(cloneIndex, 0, clone.id);
const componentRelations = {
...formFlatMarkup.componentRelations,
...(srcComponent.parentId ? { [srcComponent.parentId]: parentRelations } : {}),
...nestedRelations,
};
const allComponents = {
...formFlatMarkup.allComponents,
[clone.id]: clone,
...nestedComponents,
};
this.selectedComponentId = clone.id;
return {
...state,
formFlatMarkup: {
allComponents,
componentRelations,
},
};
}, `Duplicated component ${payload.componentId}`);
};
updateComponent = (payload: IComponentUpdatePayload): void => {
this.log(`FD: updateComponent ${payload.componentId} (${payload.settings.type})`, payload);
// TODO: review validation from Alex
// TODO: restore component validation
this.updateState((state): FormDesignerFormState => {
const { formFlatMarkup } = state;
const component = this.getComponent(payload.componentId);
const newComponent = { ...component, ...payload.settings } as IConfigurableFormComponent;
const toolboxComponent = this.getToolboxComponent(component.type);
const newComponents = { ...formFlatMarkup.allComponents, [payload.componentId]: newComponent };
const componentRelations = { ...formFlatMarkup.componentRelations };
if (isDefined(toolboxComponent.getContainers)) {
// update child components
const oldContainers = toolboxComponent.getContainers(component);
const newContainers = toolboxComponent.getContainers(newComponent);
// remove deleted containers
oldContainers.forEach((oldContainer) => {
if (!isDefined(newContainers.find((nc) => nc.id === oldContainer.id))) {
delete newComponents[oldContainer.id];
delete componentRelations[oldContainer.id];
}
});
// create or update new containers
newContainers.forEach((c) => {
const existingContainer = newComponents[c.id] ?? { propertyName: '', type: '', isDynamic: false };
newComponents[c.id] = { ...existingContainer, ...c };
});
// update component child ids
componentRelations[payload.componentId] = newContainers.map((c) => c.id);
}
return {
...state,
formFlatMarkup: {
allComponents: newComponents,
componentRelations,
},
};
}, `Component ${payload.componentId} updated`);
/*
// ToDo: AS - need to optimize
if (componentInitialization.current) {
// Do not trigger an update if first component initialization (reduce unnecessary re-renders)
componentInitialization.current = false;
return;
}
dispatch(componentUpdateAction(payload));
const component = flatMarkup.allComponents[payload.componentId];
if (!isDefined(component))
return; // TODO: debug validation, component must be defined
const toolboxComponent = getToolboxComponent(component.type);
if (!isDefined(toolboxComponent))
throw new Error('Toolbox component not found');
const { validateSettings } = toolboxComponent;
if (isDefined(validateSettings)) {
validateSettings(payload.settings)
.then(() => {
if (isDefined(component.settingsValidationErrors) && component.settingsValidationErrors.length > 0)
dispatch(componentUpdateSettingsValidationAction({ componentId: payload.componentId, validationErrors: [] }));
})
.catch(({ errors }) => {
const validationErrors = errors as IAsyncValidationError[];
dispatch(
componentUpdateSettingsValidationAction({
componentId: payload.componentId,
validationErrors,
}),
);
});
}
*/
};
componentUpdateSettingsValidation = (payload: IComponentUpdateSettingsValidationPayload): void => {
this.log('FD: componentUpdateSettingsValidation', payload);
this.updateState((state): FormDesignerFormState => {
const { formFlatMarkup } = state;
const component = this.getComponent(payload.componentId);
const newComponent: IConfigurableFormComponent = {
...component,
settingsValidationErrors: payload.validationErrors,
};
return {
...state,
formFlatMarkup: {
...formFlatMarkup,
allComponents: { ...formFlatMarkup.allComponents, [payload.componentId]: newComponent },
},
};
}, `Component validated ${payload.componentId}`);
};
addComponent = (payload: IComponentAddPayload): void => {
this.updateState((state): FormDesignerFormState => {
// create component instance
const { componentType, index, containerId } = payload;
// access to the list of toolbox components
const toolboxComponent = this.getToolboxComponent(componentType);
const { formFlatMarkup } = state;
const newFlatMarkup = {
...formFlatMarkup,
allComponents: { ...formFlatMarkup.allComponents },
componentRelations: { ...formFlatMarkup.componentRelations },
};
let newComponents: IConfigurableFormComponent[] = [];
if (toolboxComponent.isTemplate) {
const allComponents = toolbarGroupsToComponents(this.toolboxComponentGroups);
const builtResult = toolboxComponent.build(allComponents);
newComponents = this.cloneComponents(builtResult);
} else {
// create new component
const componentName = this.generateNewComponentName(newFlatMarkup.allComponents, toolboxComponent);
let formComponent: IConfigurableFormComponent = {
id: nanoid(),
type: toolboxComponent.type,
propertyName: camelcaseDotNotation(componentName),
componentName: camelcaseDotNotation(componentName),
label: componentName,
labelAlign: 'right',
parentId: containerId,
hidden: false,
isDynamic: false,
};
this.log(`FD: addComponent ${formComponent.id} (${formComponent.type})`, payload);
if (toolboxComponent.initModel) formComponent = toolboxComponent.initModel(formComponent);
if (toolboxComponent.migrator) {
formComponent = upgradeComponent(formComponent, toolboxComponent, state.formSettings, {
allComponents: newFlatMarkup.allComponents,
componentRelations: newFlatMarkup.componentRelations,
}, true);
}
newComponents.push(formComponent);
}
const newStructure = this.addComponentToFlatStructure(newFlatMarkup, newComponents, containerId, index);
this.selectedComponentId = newComponents[0]?.id;
return {
...state,
formFlatMarkup: newStructure,
};
}, `Added component ${payload.componentType}`);
};
updateChildComponents = (payload: IUpdateChildComponentsPayload): void => {
this.log('FD: updateChildComponents', payload);
this.updateState((state): FormDesignerFormState => {
const { formFlatMarkup } = state;
const oldChilds = formFlatMarkup.componentRelations[payload.containerId] ?? [];
// if not changed - return state as is
if (idArraysEqual(oldChilds, payload.componentIds)) return state;
// 2. update parentId in new components list
const updatedComponents: IComponentsDictionary = {};
const updatedRelations: IComponentRelations = {
[payload.containerId]: payload.componentIds,
};
payload.componentIds.forEach((id) => {
const component = this.getComponent(id);
if (component.parentId !== payload.containerId) {
// update old parent
const oldParentKey = !isNullOrWhiteSpace(component.parentId) ? component.parentId : ROOT_COMPONENT_KEY;
updatedRelations[oldParentKey] = (formFlatMarkup.componentRelations[oldParentKey] ?? []).filter((i) => i !== id);
// update parent in the current component
const newComponent: IConfigurableFormComponent = { ...component, parentId: payload.containerId };
updatedComponents[id] = newComponent;
}
});
const allComponents = { ...formFlatMarkup.allComponents, ...updatedComponents };
const componentRelations = { ...formFlatMarkup.componentRelations, ...updatedRelations };
return {
...state,
formFlatMarkup: {
componentRelations,
allComponents,
},
};
}, `Updated child components ${payload.containerId}`);
};
startDraggingNewItem = (): void => {
this.hasDragged = true;
};
endDraggingNewItem = (): void => {
this.hasDragged = false;
};
startDragging = (): void => {
this.isDragging = true;
this.hasDragged = true;
};
endDragging = (): void => {
this.isDragging = false;
};
setSelectedComponent = (id: string): void => {
this.selectedComponentId = id;
this.notifySubscribers(['selection']);
};
setValidationErrors = (payload: IFormValidationErrors): void => {
this.updateState((state): FormDesignerFormState => {
return { ...state, validationErrors: payload };
}, 'Validation errors updated');
};
setDebugMode = (isDebug: boolean): void => {
if (this.isDebug === isDebug)
return;
this.isDebug = isDebug;
this.notifySubscribers(['readonly']);
};
updateFormSettings = (settings: IFormSettings): void => {
this.updateState((state): FormDesignerFormState => {
return { ...state, formSettings: settings };
}, 'Form settings updated');
};
addDataProperty = (payload: IAddDataPropertyPayload): void => {
this.updateState((state): FormDesignerFormState => {
const { propertyMetadata, index, containerId } = payload;
const { formFlatMarkup } = state;
const newFlatMarkup = {
...formFlatMarkup,
allComponents: { ...formFlatMarkup.allComponents },
componentRelations: { ...formFlatMarkup.componentRelations },
};
const formComponent = createComponentModelForDataProperty(this.toolboxComponentGroups, propertyMetadata,
(fc, tc) => {
return upgradeComponent(fc, tc, state.formSettings, {
allComponents: formFlatMarkup.allComponents,
componentRelations: formFlatMarkup.componentRelations,
}, true);
},
);
if (!Boolean(formComponent)) return state;
formComponent.parentId = containerId; // set parent
const newStructure = this.addComponentToFlatStructure(newFlatMarkup, [formComponent], containerId, index);
this.selectedComponentId = formComponent.id;
return {
...state,
formFlatMarkup: newStructure,
};
}, `Added data property ${payload.propertyMetadata.path}`);
};
setReadOnly = (value: boolean): void => {
if (this.readOnly === value) return;
this.readOnly = value;
this.notifySubscribers(['readonly']);
};
setFormMode = (value: FormMode): void => {
if (this.formMode === value) return;
this.formMode = value;
this.notifySubscribers(['mode']);
};
componentEditors: IComponentSettingsEditorsCache = {};
getCachedComponentEditor = (type: string, evaluator: () => ISettingsFormFactory): ISettingsFormFactory => {
const existingEditor = this.componentEditors[type];
if (existingEditor !== undefined)
return existingEditor;
return this.componentEditors[type] = evaluator();
};
private updateState = (updater: (state: FormDesignerFormState) => FormDesignerFormState, description: string): void => {
this.undoableState.executeChange(updater, description);
this.isDataModified = true;
this.notifySubscribers(['markup', 'selection', 'history', 'data-modified']);
};
undo = (): void => {
this.log('FD: ◀ undo');
this.undoableState.undo();
this.isDataModified = this.undoableState.index > 0;
this.notifySubscribers(['markup', 'selection', 'history', 'data-modified']);
};
redo = (): void => {
this.log('FD: ▶ redo');
this.undoableState.redo();
this.isDataModified = true;
this.notifySubscribers(['markup', 'selection', 'history', 'data-modified']);
};
get canUndo(): boolean {
return this.undoableState.canUndo;
};
get canRedo(): boolean {
return this.undoableState.canRedo;
};
get past(): BaseHistoryItem[] {
return this.undoableState.past;
}
get future(): BaseHistoryItem[] {
return this.undoableState.future;
}
get history(): BaseHistoryItem[] {
return this.undoableState.history;
}
get historyIndex(): number {
return this.undoableState.index;
}
private subscriptions: Map<FormDesignerSubscriptionType, Set<FormDesignerSubscription>>;
private getSubscriptions = (type: FormDesignerSubscriptionType): Set<FormDesignerSubscription> => {
const existing = this.subscriptions.get(type);
if (existing)
return existing;
const subscriptions = new Set<FormDesignerSubscription>();
this.subscriptions.set(type, subscriptions);
return subscriptions;
};
subscribe(type: FormDesignerSubscriptionType, callback: FormDesignerSubscription): () => void {
const callbacks = this.getSubscriptions(type);
callbacks.add(callback);
return () => this.unsubscribe(type, callback);
}
private unsubscribe(type: FormDesignerSubscriptionType, callback: FormDesignerSubscription): void {
const callbacks = this.getSubscriptions(type);
callbacks.delete(callback);
}
notifySubscribers(types: FormDesignerSubscriptionType[]): void {
const allSubscriptions = new Set<FormDesignerSubscription>();
types.forEach((type) => {
const subscriptions = this.getSubscriptions(type);
subscriptions.forEach((s) => allSubscriptions.add(s));
});
allSubscriptions.forEach((s) => (s(this)));
}
};