Repository navigation
Expand file tree
/
Copy pathObjective-UI.js
More file actions
4624 lines (4613 loc) · 167 KB
/
Copy pathObjective-UI.js
File metadata and controls
4624 lines (4613 loc) · 167 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
//Object.defineProperty(exports, "__esModule", { value: true });
//exports.UILabelBinder = //exports.UIImage = //exports.UIImageBinder = //exports.UICheckBoxBS5 = //exports.UICheckBox = //exports.UICheckBoxBinder = //exports.UIButton = //exports.UIRadioOptionBS5 = //exports.RadioOption = //exports.UIRadioGroup = //exports.UIRadioGroupBinder = //exports.ModalAction = //exports.UIHead = //exports.UIHeadBinder = //exports.DefaultExceptionPage = //exports.jQuery = //exports.VirtualFunction = //exports.WidgetMessage = //exports.WidgetFragment = //exports.ViewLayout = //exports.ViewDictionaryEntry = //exports.SelectOption = //exports.RhabooStorageWrapper = //exports.RhabooInstance = //exports.AppStorage = //exports.Misc = //exports.Row = //exports.RowOptions = //exports.PageShell = //exports.NativeLib = //exports.DefaultLayoutPresenter = //exports.Col = //exports.ColOptions = //exports.WebAPISimulator = //exports.SimulatedAPIRoute = //exports.WebAPI = //exports.APIResponse = //exports.Bearer = //exports.WidgetBinder = //exports.WidgetBinderBehavior = //exports.BindingContext = //exports.WidgetContext = //exports.Widget = //exports.ViewCache = //exports.ViewBuilder = //exports.UIFlatView = //exports.FlatListItem = //exports.FlatList = //exports.UIView = //exports.UIPage = void 0;
//exports.HtmlLayout = //exports.YordViewContext = //exports.YordView = //exports.YordManagedView = //exports.DivContent = //exports.UIDataGrid = //exports.UIDataGridBinder = //exports.DataGridColumnDefinition = //exports.UITemplateView = //exports.ListItem = //exports.UIToolBar = //exports.ToolbarState = //exports.DataGridItem = //exports.UIToast = //exports.UITextArea = //exports.UITextAreaBinder = //exports.UITextBox = //exports.UITextBoxBinder = //exports.Mask = //exports.UISwitcher = //exports.UISpinner = //exports.UISelect = //exports.UISelectBinder = //exports.UIProgressBar = //exports.UINavBar = //exports.UIDialogBS5 = //exports.UIDialog = //exports.UIList = //exports.UIListBinder = //exports.UILabel = void 0;
/**
* A UIPage implementation is the first
* Objective-UI class that is instantiated once the page loads.
*
* This class is responsible for initializing the rest of the
* Objective-UI library and navigating to the first UIView to be displayed.
*
* Here it is also possible to enable features such as Splitting, Storage,
* and also import native JavaScript-CSS libraries
*
* UIPage will initialize a `PageShell` and act in conjunction with it
* to manipulate the DOM of the page as a general.
*/
class UIPage {
constructor(doc) {
this.mainShell = new PageShell(doc, this);
UIPage.shell = this.mainShell;
console.info(`* * * Objective-UI v${UIPage.PRODUCT_VERSION} * * *`);
}
setStorageProvider(provider) {
this.mainShell.setStorageProvider(provider);
}
enableSplitting(appContainerId, splitContainerId) {
this.mainShell.enableSplitting(appContainerId, splitContainerId);
}
setLibRoot(rootPath) {
PageShell.LIB_ROOT = rootPath;
}
importLib({ libName, cssPath, jsPath }) {
this.mainShell.import(new NativeLib({ libName, cssPath, jsPath }));
}
navigateToView(view) {
try {
view.initialize(this.mainShell);
}
catch (error) {
new DefaultExceptionPage(error);
}
}
}
//exports.UIPage = UIPage;
UIPage.PRODUCT_VERSION = '1.0.16';
UIPage.DISABLE_EXCEPTION_PAGE = false;
UIPage.DEBUG_MODE = false;
/**
* A UIView represents an interface view set of user controls.
* UIView's are loaded and unloaded all the time and they
* house a set of Widgets that give meaning to the view in
* front of the user.
*
* We can say in general terms that
* "this is a 'screen' of the application"
*/
class UIView {
constructor(customLayoutPresenter) {
this.customPresenter = customLayoutPresenter;
}
/**
* (Optional overwrite) occurs when a Widget sends a message
*/
onWidgetMessage(message) { }
/**
* Request an instance of the Storage implementation
* for Session or Local storage by implementing IAppStorageProvider
*
* see:
*
* ```
* interface IAppStorageProvider
* ```
* @param schemaName A unique id-name to determine the data scope
*/
requestLocalStorage(schemaName) {
return this.shellPage.requestStorage('local', schemaName);
}
requestSessionStorage(schemaName) {
return this.shellPage.requestStorage('session', schemaName);
}
viewContext() {
return this.widgetContext;
}
inflateTemplateView(rawHtml) {
return new UITemplateView(rawHtml, this.shellPage);
}
showDialog(title, text) {
var diag = new UIDialog(this.shellPage)
.setTitle(title)
.setText(text)
.action(new ModalAction({
buttonText: 'Ok',
dataDismiss: true
}));
diag.show();
}
createDialog(title) {
var diag = new UIDialog(this.shellPage)
.setTitle(title);
return diag;
}
onNotified(sender, args) {
if (sender == 'FSWidgetContext')
this.onViewDidLoad();
}
initialize(mainShell) {
this.shellPage = mainShell;
this.buildedLayout = this.buildLayout();
this.buildedLayout.render(mainShell, this.customPresenter);
var layoutCollection = this.buildedLayout.ElementsIdCollection();
this.widgetContext = new WidgetContext(this.shellPage, layoutCollection, this.onWidgetMessage);
this.view = this;
this.view.composeView();
this.widgetContext.build(this);
}
/**
* Get all Widgets attached and managed in this UIView
*/
managedWidgets() {
if (this.widgetContext == null || this.widgetContext == undefined)
return [];
return this.widgetContext.getManagedWidgets();
}
/**
* Adds one or more Widgets to a div specified in `ViewLayout`
* @param layoutId An 'Id' of div contained in the `ViewLayout` class
* @param widgets An array of Widget objects that will be bound to 'layoutId'
*/
addWidgets(layoutId, ...widgets) {
for (var i = 0; i < widgets.length; i++)
this.widgetContext.addWidget(layoutId, widgets[i]);
return this;
}
/**
* Remove a Widget managed by this UIView
*/
removeWidget(widget) {
this.viewContext().removeWidget(widget);
}
/**
* Finds a Widget managed by this UIView
*
* @param layoutId An 'Id' div contained in the `ViewLayout`class
* @param widgetName The name of a Widget managed by this UIView and previously attached to the ViewLayout through the specified 'layoutId'
*/
findWidget(layoutId, widgetName) {
return this.viewContext().findWidget(layoutId, widgetName);
}
/**
* Create an alternative Widget Context that allows controlling
* a set of Widgets that are outside the main Div-app or that
* are in a different Div than the one used by the original
* Context of this UIView
* @param managedDivIds The set of 'Id' divs managed by this Context Widget
* @param messageProtocol A function that responds to the message triggered by this context indicating its complete loading
*/
createWidgetContext(managedDivIds, messageProtocol) {
if (null == this.shellPage || undefined == this.shellPage)
throw 'FSView.createWidgetContext(): It is not possible to do this as the View is not yet initialized. If you are making this call inside the constructor(), move it inside the composeView() function.';
return new WidgetContext(this.shellPage, managedDivIds, messageProtocol);
}
}
//exports.UIView = UIView;
class FlatList {
constructor(fn) {
this.callFn = fn;
}
getListItemTemplate(sender, viewModel) {
if (Misc.isNull(viewModel))
return;
var item = new FlatListItem(viewModel);
this.callFn(item);
return item;
}
}
//exports.FlatList = FlatList;
class FlatListItem {
constructor(vm) {
this.value = vm;
}
/** define o callback para isSelected() */
onCheckSelected(fn) {
this.fn_isSelected = fn;
return this;
}
/** define o callback para select()*/
onSelect(fn) {
this.fn_select = fn;
return this;
}
/** define o callback para unSelect()*/
onUnSelect(fn) {
this.fn_unSelect = fn;
return this;
}
/** define o callback para itemTemplate()*/
onItemTemplate(fn) {
this.fn_itemTemplate = fn;
return this;
}
/** define o um trecho html para ser usado pela funcão itemTemplate()*/
withHTML(htmlString) {
this.fn_itemTemplateString = htmlString;
return this;
}
containsCssClass(className) {
return this.anchorElement.classList.contains(className);
}
addCssClass(className) {
this.anchorElement.classList.add(className);
}
removeCssClass(className) {
this.anchorElement.classList.remove(className);
}
setOwnerList(listView) {
this.sh = listView.getPageShell();
}
isSelected() {
if (Misc.isNull(this.fn_isSelected))
return false;
return this.fn_isSelected(this);
}
select() {
if (Misc.isNull(this.fn_isSelected))
return;
this.fn_select(this);
}
unSelect() {
if (Misc.isNull(this.fn_isSelected))
return;
this.fn_unSelect(this);
}
itemTemplate() {
if (!Misc.isNull(this.fn_itemTemplate))
return this.fn_itemTemplate(this);
if (!Misc.isNull(this.fn_itemTemplateString)) {
const templ = new UITemplateView(this.fn_itemTemplateString, this.sh, this.value);
var anchor = templ.elementById('anchor');
this.anchorElement = anchor;
return anchor;
}
}
}
//exports.FlatListItem = FlatListItem;
class UIFlatView extends UIView {
static findCached(path) {
for (var c = 0; c < this.caches.length; c++) {
const cached = this.caches[c];
if (cached.path == path)
return cached;
}
return null;
}
static load(view) {
view.builder = view.buildView();
const cached = this.findCached(view.builder.layoutPath);
if (!Misc.isNull(cached)) {
view.builder.layoutHtml = cached.content;
UIPage.shell.navigateToView(view);
}
else
ViewLayout.load(view.builder.layoutPath, function (html) {
if (Misc.isNullOrEmpty(html) || html.indexOf('<title>Error</title>') > -1)
throw new DefaultExceptionPage(new Error(`No html-layout found for '${view.builder.layoutPath}'`));
view.builder.layoutHtml = html;
UIPage.shell.navigateToView(view);
UIFlatView.caches.push(new ViewCache(view.builder.layoutPath, html));
});
}
buildLayout() {
return new ViewLayout(this.builder.targetId).fromHTML(this.builder.layoutHtml);
}
composeView() {
for (var c = 0; c < this.builder.viewContent.length; c++) {
var content = this.builder.viewContent[c];
this.addWidgets(content.id, ...content.w);
}
}
onViewDidLoad() {
if (this.builder.hasBinding())
this.binding = this.builder.getBinding(this);
this.builder.callLoadFn(this.viewContext());
}
getViewModel(callValidations = true) {
return this.binding.getViewModel(callValidations);
}
setViewModel(instance, updateUI = true) {
this.binding.setViewModel(instance, updateUI);
}
getBindingFor(modelPropertyName) {
return this.binding.getBindingFor(modelPropertyName);
}
}
//exports.UIFlatView = UIFlatView;
UIFlatView.caches = [];
class ViewBuilder {
constructor(layoutPath) {
this.layoutPath = '';
this.viewContent = [];
this.layoutHtml = null;
this.viewModelBind = null;
this.modelValidations = [];
if (Misc.isNullOrEmpty(layoutPath))
throw new Error('UIFlatView build failed: layoutPath is required.');
this.layoutPath = layoutPath;
}
static from(layoutPath) {
return new ViewBuilder(layoutPath);
}
to(targetDivID) {
this.targetId = targetDivID;
return this;
}
with(...content) {
if (!Misc.isNull(content))
this.viewContent = content;
return this;
}
bindWith(instance) {
this.viewModelBind = instance;
return this;
}
validate(propertyName, validateFn) {
if (Misc.isNull(this.viewModelBind))
throw new DefaultExceptionPage(new Error(`UIFlatViewBuilder: invalid call validate() function before calling bindingWith<>()`));
this.modelValidations.push({ propertyName, validateFn });
return this;
}
hasBinding() {
return Misc.isNull(this.viewModelBind) == false;
}
getBinding(view) {
const ctx = new BindingContext(this.viewModelBind, view);
for (var v = 0; v < this.modelValidations.length; v++) {
const valid = this.modelValidations[v];
ctx.hasValidation(valid.propertyName, valid.validateFn);
}
return ctx;
}
put(divId, ...w) {
this.viewContent.push(new DivContent(divId, ...w));
return this;
}
onLoad(fn) {
this.onLoadFn = fn;
return this;
}
callLoadFn(ctx) {
if (!Misc.isNull(this.onLoadFn))
this.onLoadFn(ctx);
}
}
//exports.ViewBuilder = ViewBuilder;
class ViewCache {
constructor(path, content) {
this.path = '';
this.content = '';
this.path = path;
this.content = content;
}
}
//exports.ViewCache = ViewCache;
/**
A Widget is a TS object that represents a piece of HTML. It is able to
fetch that piece of html into a webdir and bring it to the MainPage.
of a WidgetContext and can manage several child Widgets.
It is also able to manage the elements marked with "id" attribute within that piece of HTML,
and then make them available to the inherited class as DOM objects.
*
*/
class Widget {
/**
*
* @param resourceName The name of the html resource that will be fetched from the webdir and linked to this Widget
* @param widgetName A name for this Widget instance
*/
constructor(widgetName) {
this.widgetName = widgetName;
this.viewDictionary = [];
this.DOM;
}
/**
* Occurs when the Widget is detached from the WidgetContext
*/
onWidgetDetached() { }
/**
* Gets the default value of this widget; Note that not every Widget will implement the return of its value by this function.
*/
value() { }
;
setEnabled(enabled) { }
;
/**
* Determines if this Widget is visible on the page
* @param visible True or False
*/
setVisible(visible) { }
;
/**
* Add a CSS class by name; Some Widgets may not implement this eventually.
* @param className CSS class name
*/
addCSSClass(className) { }
/**
* Remove a CSS class by name; Some Widgets may not implement this eventually.
* @param className CSS class name
*/
removeCSSClass(className) { }
/**
* Applies a CSS property value; Some Widgets may not implement this eventually.
* @param propertyName CSS property name
* @param propertyValue Property value
*/
applyCSS(propertyName, propertyValue) { }
/**
* Change Widget Position
* @param position Position mode. Valid values are: 'absolute', 'relative', 'fixed', 'sticky', 'static' https://developer.mozilla.org/pt-BR/docs/Web/CSS/position
* @param marginBottom A margin bottom value
* @param marginLeft A margin left value
* @param transform (optional) indicates the CSS value of 'Transform' https://developer.mozilla.org/pt-BR/docs/Web/CSS/transform
*/
setPosition(position, marginLeft, marginTop, marginRight, marginBottom, transform) { }
/**
*
* @param propertyPairs Array item: [{ p: 'xxx', v: 'vvv'}, ...]
*/
applyAllCSS(propertyPairs) {
for (var i = 0; i < propertyPairs.length; i++) {
var css = propertyPairs[i];
this.applyCSS(css.p, css.v);
}
}
cssFromString(cssString) {
var statements = cssString.split(';');
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement == '')
continue;
var parts = statement.split(':');
if (parts.length == 0)
continue;
var key = parts[0].trim();
if (key == '')
continue;
var value = parts[1].trim();
this.applyCSS(key, value);
}
}
replaceCSSClass(oldClass, newClass) {
this.removeCSSClass(oldClass);
this.addCSSClass(newClass);
}
getPageShell() {
try {
return this.getOwnerFragment()
.contextRoot
.shellPage;
}
catch (error) {
throw new Error(`Attempt to access or manipulate an unattached Widget (name '${this.widgetName}'). Check if the Widget was attached during the composeView() function of the respective View that originated this call.`);
}
}
/**
* Get the fragment (page div) that this widget owns
* @returns WidgetFragment
*/
getOwnerFragment() {
return this.parentFragment;
}
/**
* Determines the fragment (page div) that this widget owns
*/
setParentFragment(parentFragment) {
this.parentFragment = parentFragment;
}
/**
* Sends a message from the inherited object towards the WidgetContext,
* which then makes it available to the UIView in the "onWidgetMessage()" function call
* @param messageId Set a default identifier for this message. This allows the receiver to determine the type of message (your widget may have some)
* @param messageText A text for your message
* @param messageAnyObject A custom data object
*/
sendMessage(messageId, messageText, messageAnyObject) {
var _a;
(_a = this.parentFragment) === null || _a === void 0 ? void 0 : _a.pushMessageToRoot(this.widgetName, messageId, messageText, messageAnyObject);
}
processError(error) {
new DefaultExceptionPage(error);
throw error;
}
/**
* Get the Element object (DOM) respective to the entire html
* resource linked to the Widget
*
* If the HTML contains more than one element, you must use a DIV
* involving all of them and marked with an "id" attribute
* @returns Element instance
*/
getDOMElement() {
if (this.viewDictionary.length == 0)
return null;
var firstId = this.viewDictionary[0].getOriginalId();
return this.elementById(firstId);
}
/**
* Gets a DOM object element from the value of the "id" attribute.
* @param elementId Element id inside of the html template provided by inherited class
* @returns
*/
elementById(elementId) {
var pageShell = this.getPageShell();
for (var i = 0; i < this.viewDictionary.length; i++) {
var entry = this.viewDictionary[i];
if (entry.getOriginalId() == elementId) {
var elementResult = pageShell.elementById(entry.getManagedId());
return elementResult;
}
}
return null;
}
/**
Adds an entry in the Id's dictionary.
The dictionary is used to prevent conflicting element IDs across the page.
Before elements are attached to the page, a unique Id value is generated and (re)set
to the element.
The dictionary maintains exactly the parity of the auto-generated Id
with the original one, so that the inherited object can normally access
the elements present in the HTML resource by the original name.
* @param originalId The Id of the element present in the HTML resource
* @param generatedId The self-generated Id value
*/
addDictionaryEntry(originalId, generatedId) {
var entry = new ViewDictionaryEntry(originalId, generatedId);
this.viewDictionary.push(entry);
}
/**
* This function is triggered by WidgetFragment and is responsible
* for use the HTML template and linking it to this Widget.
*
* From here, all elements present in the HTML marked with some "Id"
* attribute will be made availableas DOM Elements to the inherited object when
* "onWidgetDidLoad()" is invoked
* @param onloadNotifiable An Notifiable to receive a notification when the Widget is rendered
*/
renderView(onloadNotifiable) {
var self = this;
this.viewDictionary = [];
var html = this.htmlTemplate();
if (Misc.isNullOrEmpty(html))
new Error(`Cannot render a Widget named '${this.widgetName}' because the html-template is empty. Ensure that function htmlTemplate() returns a valid html string.`);
var parser = new DOMParser();
var domObj = parser.parseFromString(html, "text/html");
var allIds = domObj.querySelectorAll('*[id]');
for (var i = 0; i < allIds.length; i++) {
var element = allIds[i];
var currentId = element.getAttribute('id');
if (currentId != null) {
var newId = `${currentId}_${Misc.generateUUID()}`;
self.addDictionaryEntry(currentId, newId);
element.setAttribute('id', newId);
}
}
self.DOM = domObj;
var child = domObj.documentElement.childNodes[1].firstChild;
if (UIPage.DEBUG_MODE) {
var lb = document.createElement('label');
lb.textContent = `Widget: ${this.widgetName}`;
child.appendChild(lb);
}
self.parentFragment.appendChildElementToContainer(child);
self.onWidgetDidLoad();
onloadNotifiable.onNotified('FSWidget', [self, domObj]);
}
onNotified(sender, args) { }
/**
* @deprecated Now, call this function from "Misc" class. Ex.:
* ```
* var uid = Misc.generateUUID();
* ```
*/
static generateUUID() {
return Misc.generateUUID();
}
}
//exports.Widget = Widget;
/**
* A WidgetContext is able to manage a
* set of widgets linked in a div
* contained in a `ViewLayout`
*
* This is automatically managed by the UIView,
* but new WidgetContext's can be dynamically
* created to manage another portion of Widgets
* located in other Divs.
*/
class WidgetContext {
constructor(shellPage, managedElementsIds, messageProtocolFunction) {
this.contextLoaded = false;
this.fragments = [];
this.messageProtocolFunction = messageProtocolFunction;
var self = this;
self.shellPage = shellPage;
for (var i = 0; i < managedElementsIds.length; i++) {
var elementId = managedElementsIds[i];
var divElement = shellPage.elementById(elementId);
self.fragments.push(new WidgetFragment(self, divElement));
}
}
onNotified(sender, args) {
}
contextShell() {
return this.shellPage;
}
findFragment(fragmentName) {
for (var i = 0; i < this.fragments.length; i++) {
var fragment = this.fragments[i];
if (fragment.fragmentId == fragmentName)
return fragment;
}
return null;
}
findWidget(fragmentName, widgetName) {
var fragment = this.findFragment(fragmentName);
var widget = fragment.findWidget(widgetName);
return widget;
}
get(path) {
const fragmentName = path.split('/')[0];
const widgetName = path.split('/')[1];
var fragment = this.findFragment(fragmentName);
var widget = fragment.findWidget(widgetName);
return widget;
}
pushMessage(widgetName, messageId, messageText, messageAnyObject) {
if (this.messageProtocolFunction != null) {
this.messageProtocolFunction(new WidgetMessage(widgetName, messageId, messageText, messageAnyObject));
}
}
/**
* Attaches a Widget to a `WidgetFragment`.
* A `WidgetFragment` is the direct controller of ONE
* div and can manage multiple Widgets related to this div
*/
addWidget(fragmentName, widget) {
var fragment = this.findFragment(fragmentName);
if (Misc.isNull(fragment))
throw new Error(`Cannot add a Widget named '${widget.widgetName}' to WidgetFragment '${fragmentName}'. Ensure that layout-html contains a div with Id="${fragmentName}"`);
fragment.attatchWidget(widget);
if (this.contextLoaded) {
let last = fragment.widgets.length - 1;
fragment.widgets[last].renderView(this);
}
return this;
}
getManagedWidgets() {
try {
var widgets = [];
for (var frg = 0; frg < this.fragments.length; frg++) {
var fragment = this.fragments[frg];
for (var wdg = 0; wdg < fragment.widgets.length; wdg++) {
var widget = fragment.widgets[wdg];
widgets.push(widget);
}
}
return widgets;
}
catch (e) {
return [];
}
}
removeWidget(widget) {
if (widget == null)
return;
var fragment = widget.getOwnerFragment();
if (fragment == null)
return;
fragment.dettatchwidget(widget);
}
onFragmentLoad() {
this.fragmentsLoaded += 1;
if (this.fragmentsLoaded == this.fragments.length) {
this.contextLoaded = true;
if (this.notifiableView != null)
this.notifiableView.onNotified('FSWidgetContext', []);
}
}
clear() {
for (var i = 0; i < this.fragments.length; i++) {
var fragment = this.fragments[i];
fragment.clear();
}
}
/**
* Performs the rendering of the Widgets attached to this Context.
* Immediately orders the Fragments managed by this Context to draw
* the Widgets they manage.
* @param notifiable
*/
build(notifiable, clear = false) {
this.notifiableView = notifiable;
if (this.contextLoaded) {
if (this.notifiableView != null)
this.notifiableView.onNotified('FSWidgetContext', []);
return;
}
this.fragmentsLoaded = 0;
for (var i = 0; i < this.fragments.length; i++) {
var fragment = this.fragments[i];
if (clear == true)
fragment.clear();
fragment.renderFragmentwidgets();
}
}
}
//exports.WidgetContext = WidgetContext;
/**
* An efficient system of data binding and object synchronization (aka 'ViewModel')
* with the User Interface
*
*/
class BindingContext {
/**
* This is a concrete class and you should instantiate it normally,
* You must provide an instance of the ViewModel and the inherited UIView currently displayed.
* But ATTENTION you must do this INSIDE the onViewDidload() function of your UIView inherited class.
*
* ```
* export class MyView extends UIView {
* private binding: BindingContext<ModelType>;
* ...
* onViewDidload(): void {
* //Here Widgets attached in UIView will be linked with `ModelType`
* this.binding = new BindingContext<ModelType>(new ModelType(), this);
* ...
* }
* ```
* @param viewModel An instance of the ViewModel object
* @param view UIView instance inherits class (the currently displayed UIView)
*/
constructor(viewModel, view) {
this._binders = [];
this.viewModelInstance = viewModel;
this.scanViewModel(view);
}
toString() {
return '[BINDING-CONTEXT]';
}
/**
*
* @param modelPropertyName
* @param validateFn
```
function(propVal: any) {
// check value
// apply UI changes
// return true|false;
}
```
*/
hasValidation(modelPropertyName, validateFn) {
const binder = this.getBinder(modelPropertyName);
if (Misc.isNull(binder))
throw new DefaultExceptionPage(new Error(`BindingContext<${typeof (this.viewModelInstance)}> : not found a WidgetBinder for model property '${modelPropertyName}'`));
binder.addValidation(validateFn);
}
getBinder(modelPropertyName) {
for (var i = 0; i < this._binders.length; i++) {
var binder = this._binders[i];
if (binder.modelPropertyName == modelPropertyName)
return binder;
}
}
/**
* Gets a WidgetBinderBehavior from which the behavior of data bindings will be changed.
* @param modelPropertyName The name of the property/key present in the ViewModelType type
* @returns `WidgetBinderBehavior`
*/
getBindingFor(modelPropertyName) {
var propBinders = [];
for (var i = 0; i < this._binders.length; i++) {
var binder = this._binders[i];
if (binder.modelPropertyName == modelPropertyName)
propBinders.push(binder);
}
return new WidgetBinderBehavior(propBinders);
}
/**
* Causes a UI refresh on all Widgets managed by this Data Binding Context
* based on the current values of the properties/keys of the ViewModelType instance \
* \
* (remember that the ViewModelType instance is managed by this context as well)
*/
refreshAll() {
for (var b = 0; b < this._binders.length; b++) {
var binder = this._binders[b];
binder.refreshUI();
}
}
/**
* Get an instance of `ViewModel` based on Widgets values
* @returns `ViewModel`
*/
getViewModel(callValidations = true) {
for (var i = 0; i < this._binders.length; i++) {
const binder = this._binders[i];
binder.fillPropertyModel();
if (callValidations) {
if (binder.hasValidation())
if (!binder.validate())
return null;
}
}
return this.viewModelInstance;
}
/**
* Defines an instance of `ViewModel`.\
* This causes an immediate UI refresh on all widgets managed by this context. \
* \
* You can also use this to reset (say 'clear') the Widgets state by passing a `new ViewModel()`
* @param viewModelInstance `ViewModel`
* @returns
*/
setViewModel(viewModelInstance, updateUI = true) {
this.viewModelInstance = viewModelInstance;
if (updateUI) {
for (var b = 0; b < this._binders.length; b++) {
var binder = this._binders[b];
binder.setModel(this.viewModelInstance, binder.modelPropertyName);
}
this.refreshAll();
}
return this;
}
/**
* Scans the Widgets managed in a UIView for matches with
* properties/keys present in the ViewModel type object
* managed by this Context
*/
scanViewModel(view) {
var self = this;
var widgets = view.managedWidgets();
if (widgets == null || widgets == undefined || widgets.length == 0)
throw new Error("Illegal declaration: BindingContext cannot be initialized by the View's constructor. Consider instantiating it in onViewDidLoad()");
for (var key in self.viewModelInstance) {
for (var w = 0; w < widgets.length; w++) {
var widget = widgets[w];
var keyMatch = self.isModelPropertyMatchWithWidget(widget, key);
if (keyMatch)
this.bindWidget(widget, key);
}
}
}
isModelPropertyMatchWithWidget(widget, modelKey) {
var widgetName = widget.widgetName;
if (widgetName.indexOf(modelKey) < 0)
return false;
var replaced = widgetName.replace(modelKey, '');
var propLength = modelKey.length;
var replacedLength = replaced.length;
return (replacedLength < propLength);
}
bindWidget(widget, modelKey) {
try {
var binder = widget.getBinder();
if (binder == null || binder == undefined)
return null;
binder.setModel(this.viewModelInstance, modelKey);
this._binders.push(binder);
return binder;
}
catch (_a) {
return null;
}
}
}
//exports.BindingContext = BindingContext;
/**
* Allows you to define binding behaviors for a
* set of `WidgetBinder`
* classes that are bound to a property/key of
* the object-model being managed by the `BindingContext<T>`
*/
class WidgetBinderBehavior {
constructor(binders) {
this._binders = binders;
}
/**
* When data binding is done based on a list of model objects,
* it may be necessary to specify a binding path INSIDE that model
* object via its properties/keys.
*
* This happens for example when binding a
* list of `'Contact'` in `UISelect` or `UIList`:
* although they are able to load an Array<Contact>,
* they won't know that they should use the prop/key 'Id'
* like selection value and the 'Name' prop/key as
* the display value.
* @param displayPropertyName The prop/key on the model object that will be displayed in the control
* @param valuePropertyName The prop/key in the model object that will be used as the selected value in the Widget
*/
hasPath(displayPropertyName, valuePropertyName) {
for (var i = 0; i < this._binders.length; i++)
this._binders[i].hasPath(displayPropertyName, valuePropertyName);
return this;
}
/**
* Set a target when you want the selected Widget
* value to be transferred to a given property/key
* in the same model-object.
* @param targetValuePropertyName Property/key in the model-class to which the selected Widget-value will be transferred.
*/
hasTarget(targetValuePropertyName) {
for (var i = 0; i < this._binders.length; i++)
this._binders[i].hasTarget(targetValuePropertyName);
return this;
}
}
//exports.WidgetBinderBehavior = WidgetBinderBehavior;
/**
* It acts as a bridge between the `BindingContext<T>`
* and the respective Widget.
*
* This allows the Widget to incorporate Data Binding
* functionality with model-objects.
*
* If you have a custom `Widget` created in your project,
* you will need to provide a `WidgetBinder` implementation
* to provide Data Binding functionality
*/
class WidgetBinder {
constructor(widget) {
this.widget = widget;
this.widgetName = widget.widgetName;
this.bindingName = `${typeof (widget)}Binding ${this.widgetName} => ${typeof (widget)}`;
}
addValidation(validateFn) {
this.validateFn = validateFn;
}
hasValidation() {
return !Misc.isNull(this.validateFn);
}
validate() {
var val = this.getModelPropertyValue();
var result = this.validateFn(val);
if (Misc.isNull(result))
throw new DefaultExceptionPage(new Error(`WidgetBinder: invalid result of validation function for property '${this.modelPropertyName}'. Check if validation function contains a 'return true|false' instruction. `));
if (result == true || result == false)
return result;
throw new DefaultExceptionPage(new Error(`WidgetBinder: invalid result of validation function for property '${this.modelPropertyName}'. Check if validation function contains a 'return true|false' instruction. `));
}
getModelPropertyValue() {
if (this._viewModel == null || this.modelPropertyName == null || this.modelPropertyName == '')
return null;
var value = this._viewModel[this.modelPropertyName];
return value;
}
setModelPropertyValue(value) {
if (this._viewModel == null || this.modelPropertyName == null || this.modelPropertyName == '')
return;
this._viewModel[this.modelPropertyName] = value;
}
toString() {
return this.bindingName;
}
hasPath(displayPropertyName, valuePropertyName) {
this.bindingHasPath = true;
this.displayProperty = displayPropertyName;
this.valueProperty = valuePropertyName;
this.refreshUI();
return this;
}
hasTarget(targetValuePropertyName) {
this.modelTargetPropertyName = targetValuePropertyName;
return this;
}
isTargetDefined() {
return this.modelTargetPropertyName != null;
}
fillModelTargetPropertyValue() {
if (this.isTargetDefined() == false)
return;
var value = this.getWidgetValue();
this._viewModel[this.modelTargetPropertyName] = value;
}
getModelTargetPropertyValue() {
if (this.isTargetDefined() == false)
return;
var value = this._viewModel[this.modelTargetPropertyName];
return value;
}
setModel(viewModelInstance, propertyName) {
this._viewModel = viewModelInstance;
this.modelPropertyName = propertyName;
this.bindingName = `${typeof (this.widget)}Binding ${this.widgetName} => ${typeof (this.widget)}.${this.modelPropertyName}`;
this.refreshUI();
}
}
//exports.WidgetBinder = WidgetBinder;