forked from istitutoculturaitaliana/sf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsf.js
1465 lines (1110 loc) · 32.1 KB
/
sf.js
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
/**
*
* @fileoverview
*
* This is the main client-side file
* of Sf, an isomorphic, recursive and
* minimalistic client/server
* side framerwork to easily develop
* modular and light-fast web applications.
*
* The file also contains some utilities to easily
* performs operations on strings or arrays
* using method chaining.
*
*
* @package SF (Simple Framework)
* @copyright (C) 2016 Institute of Italian culture (NGO)
* @see www.istitutoculturaitaliana.org/sf
* @author Thomas de Vivo <[email protected]>
* @version 0.1
* @licence This is an open source software
* conceived within the frame of the Institute of
* Italian culture (NGO), and originally
* implemented by Thomas de Vivo ([email protected])
* It is published under the following license:
* everyone can copy, use, modify and redistribute this
* software provided that every copy of it (including the
* partial use of its code) will retain the current disclaimer
* or in this form, or using the following short notice:
*
* "(C) 2016 Institute of Italian culture (NGO)
* -- www.istitutoculturaitaliana.org/sf"
*
* (even compacted in one line)
* (the provided link will contain a description of the software
* and the complete license.)
*
* The software is provided "as is": without any warranty
* (including its eligibility for whatever kind
* of purpose), and both the copyright owners and the
* contributors are excluded from any liability
* related to the use of it, even if instructions
* and recommendations of use will be provided
* with such software or any derivative or
* related work.
*
*/
/**
*
* @namespace
*
*/
Sf = {};
/**
* @type {object}
* @desc Object containing
* all the controllers' data
*/
Sf.data = {};
/**
* @type {array}
* @desc An array with the identification of
* all the controllers to be queried through
* Ajax
*/
Sf.queue = [];
/**
*
* @type {object}
* @desc An object with the callable functions of
* all the views to be rendered.
*/
Sf.view = {};
/**
* @type {object}
* @desc An object similar
* to Sf.view, with the callable functions
* used to validate FORMS
*/
Sf.validation = {};
/**
* Check if the script is executed server side
* @return {bool} Returns true if server side and false if
* client side
*/
Sf.server_side = function() {
return (typeof window == 'undefined' || typeof PHP != 'undefined');
};
/**
* A "negative" alias of the function above:
* check if the script is executed client-side
*
* @return {bool} Returns true if client side and false if
* server side
*
*/
Sf.client_side = function() {
return !Sf.server_side();
};
/**
* This function will restore client-side
* the controllers data used server-side
* at run-time
*
* @param {string} context
* Can be "data" or "html": "data"
* are the controllers data and "html" the
* data related to the HTML elements
* (see Html.js: we allow the use of javascript
* objects as element's attributes,
* without the need to encode them within
* the HTML element itself)
*
* @param {object} data A base64 encoded
* stringified JSON object --- such data will
* be written in the static HTML document
* inside a script tag
*
*/
Sf.restore_data = function(context,data) {
switch(context) {
case 'data' :
Sf.data = Sf.str(data).base64_decode().json_decode().get();
break;
case 'html' :
Html.data = Sf.str(data).base64_decode().json_decode().get();
break;
}
};
/**
* @classdesc A class to easily handle strings
* and to group string-related functions
*
* @class
*
*
* @param {string} str The string passed
* to the constructor, hereinafter
* indicated as "class argument"
*
* @return {object} the class instance to
* allow method chaining
*
*/
Sf.Str = function(str) {
var str_ = (str ? str + '' : '');
/**
* @method tag_enclose
* Encloses the class argument with html tags
*
* @param {string} tag The tag name
* @param {object} obj An object containing
* a set of attributes / values to be applied
* to the html element
*
* Note that the method uses the function
* Html.element allowing to pass native
* objects as values of the html attributes.
* (see Html.element to find out more)
*
* @return {object} Returns the class instance
* to allow method chaining
*/
this.tag_enclose = function(tag,obj) {
str_ = Html.element(tag,obj).html(str_);
return this;
};
/**
* @method trim
* Ensures that the class argument string is
* without blank characters on its boundaries
*
* @return {object} Returns the class instance
*/
this.trim = function() {
if(str_)
str_ = str_.replace(/^\s\s*/,'').replace(/\s\s*$/,'');
return this;
};
/**
* @method in_array
* @param {array} array The array where to search for
* the class argument
* @return {bool} Returns true if the class argument is
* found in the array, otherwise returns false
*/
this.in_array = function(array) {
for(var i in array) {
if(str_ == array[i])
return true;
}
return false;
};
/**
* @method json_decode
* @return {object} Returns a new Sf.Obj
* with the decoded JSON string as
* class argument
*
* @todo Use a "polyfill" implementation
* where the JSON object is not available
*/
this.json_decode = function() {
return Sf.obj(JSON.parse(str_));
};
/**
* @method base64_encode
* @return {string} Returns the encoded class argument
*/
this.base64_encode = function() {
if(window && window.btoa)
return window.btoa(str_);
else
return Third_parties.base64_encode(str_);
};
/**
* @method base64_decode Decodes a base64 encoded
* class argument
* @return {object} Returns the class instance
*
* @todo Check if the class argument is actually
* a well formed base64 encoded string before
* decoding
*/
this.base64_decode = function() {
if(window && window.atob)
str_ = window.atob(str_);
else
//this is a "polyfill" implementation
str_ = Third_parties.base64_decode(str_);
return this;
};
/**
* @method get
* Returns the transformed class argument
* @return {string} Returns the transformed class argument string
*/
this.get = function() {
return str_;
};
return this;
};
/**
* @classdesc
* A class to easily handle objects and
* to group object-related functions
*
* @class
*
* @param {object} obj The object passed
* to the constructor, hereinafter
* indicated as "class argument"
*
*
* @return {object} the class instance to
* allow method chaining
*/
Sf.Obj = function(obj) {
var obj = obj || {};
// we work on a copy
var obj_ = {};
for(var i in obj)
obj_[i] = obj[i];
/**
* @method stringify
* Encodes the class argument into a
* JSON string
*
* @return {string} Returns a new instance
* of Sf.str (see below) with the encoded
* string as class argument
*/
this.stringify = function() {
var str = JSON.stringify(obj_);
return Sf.str(str);
};
/**
* @method json_encode
* Alias for this.stringify
*/
this.json_encode = this.stringify;
/**
* @method merge
* Merges the provided object with the
* class argument (if the merge object has
* same keys of the class argument, the values
* of the latter will be overwritten)
*
* @param {object} obj The object to be merged
* @return {object} Returns the class instance
*/
this.merge = function(obj) {
for(var i in obj) {
if(!obj_.hasOwnProperty(i))
obj_[i] = obj[i];
}
return this;
};
/**
* @method filter
* Removes from the class argument the
* keys equal to the values of the
* provided array
*
* @param {array} array The array with keys to filter
* @return {object} returns the class' instance
*/
this.filter = function(array) {
for(var i in array) {
if(obj_.hasOwnProperty(array[i]))
delete obj_[array[i]];
}
return this;
};
/**
* @method size
* @return {int} Returns the size of the class
* argument
*/
this.size = function() {
var n = 0;
for(var i in obj_)
n++;
return n;
};
/**
* @method keys_to_array
* Returns an array whose values are
* the properties / keys of the class argument
*
* @return {object} Returns a new instance of
* the Sf.array object with the array of
* keys as class argument
*/
this.keys_to_array = function() {
var output = [];
for(var i in obj_)
output.push(i);
return Sf.array(output);
};
/**
* @method join
* Joins an object in a similar
* way as an array. The
* keys / properties of the object will
* be lost
*
* @return {object} Returns a new instance of
* the Sf.str object with the array of values
* as class argument
*/
this.join = function(token) {
var array = [];
for(var i in obj_)
array.push(obj_[i]);
return Sf.str(array.join(token));
};
/**
* @method assert_m_prop
* Ensures that all the values
* listed in the provided array
* exist as multidimensional (nested) properties
* of the class argument
*
* @param {array} array An array of strings.
* Each string represents the name of a nested property
* of the class argument object
*
* @return {object} Returns the class instance
*/
this.assert_m_prop = function(array) {
var obj = obj_;
for(var i in array) {
if(!obj.hasOwnProperty(array[i]))
obj[array[i]] = {};
obj = obj[array[i]];
}
return this;
};
/**
* @method get
* @return {object} Returns the trasformed object
*/
this.get = function() {
return obj_;
};
return this;
};
/**
* @class
*
* @classdesc
* A class to easily handle arrays
* and to group array-related functions
*
*
* @param {array} array The array passed
* to the constructor, hereinafter
* indicated as "class argument"
*
*
* @return {object} the class instance to
* allow method chaining
*/
Sf.Array = function(array) {
var array = array || [];
//we work on a copy
var array_ = [];
for(var i in array)
array_.push(array[i]);
/**
* @method isset Checks if the lenght
* of the class argument array
* is greater than a specified index
*
* @param {int} i The index value
* @return {bool} Return true if the index exists,
* otherwise returns false
*/
this.isset = function(i) {
return (i < array_.lenght -1);
};
/**
* @method for_each
* A simple iterator
* @param {function} funct The function to be executed on
* every key / value of the array
* @args {array} args The arguments to be passed to that function.
* The current key and value (respectively) will be
* prepended by default to the custom arguments list
* @return {object} Returns the class instance
*/
this.for_each = function(funct,args) {
var context = null;
for(var i in array_)
funct.apply(context,Sf.array([i,array_[i]]).merge(args).get());
return this;
};
/**
* @method merge
* Merges the provided array with the class argument
* @param {array} array The array to merge with-
* @return {object} Returns the class instance
*/
this.merge = function(array) {
for(var i in array)
array_.push(array[i]);
return this;
};
/**
* @method delete
* Deletes the specified value from the class argument
* @param {mixed} value The value to be deleted
* @return {object} Returns the class instance
*/
this.delete = function(value) {
for(var i in array_) {
if(array_[i] == value)
delete array_[i];
}
return this;
};
/**
* @method stringify
* Encodes the class argument in a
* JSON string
*
* @return {string} Returns a new instance
* of Sf.str (see above) with the encoded
* string as class argument
*/
this.stringify = function() {
var str = JSON.stringify(array_);
return Sf.str(str);
};
/**
* @method json_encode
* Alias for this.stringify
*/
this.json_encode = this.stringify;
/**
* @method list
* Transforms the class argument
* in an object with the provided property names
* (the values with index greater than the
* provided array will be discarded)
*
* @param {array} array An array of property / key names
* @return {object} Returns a new instance of the
* Sf.obj (see above) with the new object as
* class argument
*/
this.list = function(array) {
var obj = {};
for(var i in array)
obj[array[i]] = array_[i];
return Sf.obj(obj);
};
/**
* @method get
* @returns array Returns the transformed class argument
*/
this.get = function() {
return array_;
};
return this;
};
/**
* @classdesc
*
* A class to easily select DOM elements
* and to group DOM selectors and DOM
* manipulation functions
*
* Sf encourages to make a moderate
* use of CSS selectors to not bound
* the programming / structure of a web
* application to its design / style.
*
* Specifically, CSS selectors using
* tag and class names should be used only
* when the transformation concerns the style
* / class of the element,
* while in all other cases we should rely
* on the id or some custom attribute.
*
* In no cases we should identify an element
* by its class or tag name when is not concerned
* a modification of specifically its style,
* because the class name and even the tag (and
* their hierarchy) could change for purposes of design.
*
* In short, CSS selectors, or native, or
* through Sizzle (incorporated by JQuery) should be used by
* the design department *on top* of the application,
* while the core and programming department should
* make a minimalist and careful use of them,
* so that a "polyfill" for the querySelector()
* function at this level should be not required
* nor envisaged.
*
*
* @class
*
* @param {element} The reference DOM element
*
*/
Sf.Selector = function(el) {
this.ref_el = el || null;
this.el = null;
/**
* @method attr_up
* Searches for the nearest parent element
* with the specified attribute and value
*
* @param {string} name The attribute name
* @param {string} value The attribute value
*
* @return {object} Returns the class instance
*/
this.attr_up = function(name,value) {
var el = this.ref_el;
while(typeof el.hasAttribute != 'function' || !el.hasAttribute(name) || el.getAttribute(name) != value) {
//console.log(el)
el = el.parentNode;
}
//return el || null;
this.el = el || null;
return this;
};
/**
* @method outerHTML
* Replaces a DOM element with the provided
* text/html
*
* @param {string} html The text/html to be applied
* as outerHTML
*
* @todo use another implementation where outerHTML
* is not available
*/
this.outerHTML = function(html) {
if(this.el)
this.el.outerHTML = html;
};
/**
* @method get
* Gets the class argument
* @return {object} Returns the DOM element
* (can be null)
*/
this.get = function() {
return this.el;
};
return this;
};
/**
* A short for Sf.Str to avoid the use of the 'new' operator
*/
Sf.str = function(str) {
return new Sf.Str(str);
};
/**
* A short for Sf.Obj to avoid the use of the 'new' operator
*/
Sf.obj = function(obj) {
return new Sf.Obj(obj);
};
/**
* A short for Sf.Array to avoid the use of the 'new' operator
*/
Sf.array = function(array) {
return new Sf.Array(array);
};
/**
* A short for Sf.Selector to avoid the use of the 'new' operator
*/
Sf.selector = function(ref_el) {
return new Sf.Selector(ref_el);
};
/**
* The standard method to instantiate
* a native Ajax object
*/
Sf.xhr_object = function() {
try {
return new XMLHttpRequest();
} catch(e) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
return null;
};
/**
* This is the function used to update the view
*
* @todo Rather than to call the function specifying
* an event on the
* HTML element itself, the call to the function
* should be implemented through some custom "sf"
* attribute, for instance in the following way:
*
* sf-update="[event]"
*
* where event can be "onclick", "onchange", and
* so on. (Then on DOM ready the function will be
* attached to the element with the specified
* event)
*
*
* @param {element} parent_el The DOM element to
* which is attached the event which fires the
* function
*
*/
//client side
Sf.update = function(parent_el) {
/**
* @type {object}
*
* @desc First we check for the 'sf-' prefixed attributes
* within the element.
* By default, at the current Sf version, they
* can be the following:
*
* (sf-) load {string} The identification of the view to be loaded;
* in this form: [scope]|[namespace]|[label]
*
* (sf-) load-values {string or object} The values to be passed
* to the view to be loaded
*
* (sf-) validate {string} The validation function to be
* called for instance on form submit
* Still a string in this form:
* [scope]|[namespace]|[label]
*
* (to be found in scope / namespace / validate.js -> label)
*
*
* (sf-) post {string} The controller scope, namespace and
* label to be queried. It should be the same
* controller used to render the view indicated
* by sf-load
*
*
* (sf-) replace {string} The identification of the view to be
* replaced, still in this form:
* [scope]|[namespace]|[label]
*
* (sf-) history {integer} Can be 1, 0, or minus [n] -- The
* value will affect the browser history: if
* negative the navigation history will go back
* of n steps
*
* @todo MUST BE IMPLEMENTED
*
* (sf-) url {string} S custom url, which can replace
* or be added to the page state
*
* @todo MUST BE IMPLEMENTED
*
* (sf-) fading {null or string or object} Specifies the
* fading between the view to be replaced
* and the replacement view
*
* @todo MUST BE IMPLEMENTED
*/
var obj = {
'load': ''
,'load-values': {} //string or object
,'validate': ''
,'post': ''
,'replace': ''
,'history': '-1'
,'url': ''
,'fading': '1'
};
/*
* check if the standard attribute is specified
* and if the value of it is an object stored
* in the global Html.data object
*/
for(var i in obj) {
if(parent_el.hasAttribute('sf-' + i)) {
if(!parent_el.hasAttribute('sf-' + i + '-id'))
obj[i] = parent_el.getAttribute('sf-' + i);
else
obj[i] = Html.data[parent_el.getAttribute('sf-' + i + '-id')];
}
}
/*
* If a validation (sf-validate) function is specified
* and if the parent_el is a FORM, then parse the values
* of it
*/
var form_values = [];
if(Sf.str(obj.validate).trim().get() != '' && parent_el.tagName.toLowerCase() == 'form') {
var form = parent_el;
var allowed_type = ['text','textarea','select-one','hidden'];
/*
* we are using the custom iterator of Sf.Array class
* with as arguments the key "i", the value "value"
* and the custom argument "allowed_type"
*/
Sf.array(form.elements).for_each(function(i,el,form_values,allowed_type) {
if(Sf.str(el.type).in_array(allowed_type))
form_values.push({name: el.name,value: Sf.str(el.value).trim().get(),el: el});
},[form_values,allowed_type]);
/*
* transform the argument of 'sf-validate'
* (the identification of the validation function to be called,
* expressed in this form: [scope]|[namespace]|[label] )
* in an object like this:
*
* {'scope': [scope] ,'namespace': [namespace],'label': [label]}
*/
var obj_validate = Sf.array(obj.validate.split('|')).list(['scope','namespace','label']).get();
/*
* call the specified validation function
* passing the values taken from the FORM
*/
var context = null;
form_values = Sf.validation[obj_validate.scope][obj_validate.namespace].apply(context,[obj_validate.label,form_values]);
/*
* If the result of the validation function associated
* to the FORM is not FALSE, we delete the existing
* controller data specified by sf-post (the identification
* of the controller to be invoked) to ensure that
* the controller will be newly invoked by Ajax
* (in order both to record and to provide data)
*/
//if(typeof form_values == 'object' && Sf.obj(form_values).size()) {
if(form_values !== false) {
/*
* transform the value of 'sf-post'
* (the controller identification expressed in this form:
* [scope]|[namespace]|[label] )
* in an object like this:
*
* {'scope': [scope] ,'namespace': [namespace],'label': [label]}