-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBlapy.js
1688 lines (1501 loc) · 71.5 KB
/
Blapy.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
/**
* -----------------------------------------------------------------------------------------
* INTERSEL - 4 cité d'Hauteville - 75010 PARIS
* RCS PARIS 488 379 660 - NAF 721Z
*
* File : Blapy.js
* Blapy : jQuery plugin that helps you to create and manage ajax and single page web applications (SPA) with almost no javascript coding to do it.
*
* -----------------------------------------------------------------------------------------
* @copyright Intersel 2015-2022
* @fileoverview : Blapy is a jQuery plugin that helps you to create and manage an ajax web application.
* @see {@link https://github.com/intersel/Blapy}
* @author : Emmanuel Podvin - emmanuel.podvin@intersel.fr
* @version : 1.15.0
* @license : donationware - see https://github.com/intersel/Blapy/blob/master/LICENSE
* -----------------------------------------------------------------------------------------
* Modifications :
* - 2024/01/29 - E.Podvin - 1.16.0 - add blapyFirst and blapyLast data if the json data received by rest point is an array
* - 2022/09/06 - E.Podvin - 1.15.0 - now trigger a message 'Blapy_templateReady' when a block has its template ready (loaded)
* + change use of var to let
* + small fixes
* - 2022/05/01 - E.Podvin - 1.14.2 - Fix on detecting if template is provided or not in the blapy block
* - 2022/02/11 - E.Podvin - 1.14.1
* - data-blapy-template-init-processdata may contain several functions to be applied on received json data
* - 2021/11/14 - E.Podvin - 1.14.0
* - Load template files asynchronously
* - if reused in an other blapy block, load only once a given template file
* - 2021/10/11 - E.Podvin - 1.13.8 -
* - fix on xmp detection for multi templating
* - add 'templateId' parameter in 'params' for 'postData' and 'updateBlock' events
* to manage template changes
* - 2021/07/12 - E.Podvin - 1.13.7
* - fix bad injection of xmp when template file contains them
* - fix on sending blapy data according to the status of "noblapy-data"
* - 2021/06/17 - E.Podvin - 1.13.6
* - add log when template void
* - 2019/11/26 - E.Podvin - 1.13.5
* - different log level between ifsm and blapy
* - fix in postData when console log on embeddingBLockId not set (use of aFSM instead of myFSM)
* - 2019/11/15 - E.Podvin - 1.13.4
* - add data-blapy-params property for A tag element to specify data to send to url
* - 2019/11/14 - E.Podvin - 1.13.3
* - use of event.currentTarget instead of event.target
* - use of postData for blapy-link on tag A allowing to define "method" attribute
* - 2019/11/12 - E.Podvin - 1.13.2
* - fixes for compliance with non json blapy blocks after the json dev
* - 2019/11/01 - E.Podvin - 1.13.1
* - alert when htmllBlapyBlock id is not found in embedHtmlPage
* - use of log.warn when error/warning
* - fix load of img or script by the system in setBlapyContainerJsonTemplate
* - 2019/10/26 - E.Podvin - 1.13.0
* - add nested json blocks by escaping xmp tags that does not accept to be nested :-( see demos/demo_json_nested_blocks/
* - fix data-blapy-template-init-purejson to default to 1
* - 2019/10/24 - E.Podvin - 1.12.2
* - add a console report when json template is not html for whatever reason...
* - 2019/10/22 - E.Podvin - 1.12.1
* - remove only external xmp in setBlapyContainerJsonTemplate allowing templates in xmp within templates
* - 2019/10/22 - E.Podvin - 1.12.0
* - add data-blapy-template-mustache-delimiterStart and data-blapy-template-mustache-delimiterEnd to be able to change mustache delimiters when rendering template
* - 2019/10/19 - E.Podvin - 1.11.1
* - set eval of data-blapy-template-init-processdata function out of the catch error test for json validation
* - 2019/10/19 - E.Podvin - 1.11.0
* - add data-blapy-template-init-processdata
* - 2019/10/18 - E.Podvin - 1.10.4
* - remove html comments to test if no template in the block
* - 2019/10/11 - E.Podvin - 1.10.3
* - fix on xmp that did not handle the extended char properly...
* - 2019/10/07 - E.Podvin - 1.10.2
* - fix on xmp to remove in template that could contains data like 'display:none'...
* - 2019/10/02 - E.Podvin - 1.10.1
* - fix on json data that contains html
* - 2019/09/05 - E.Podvin - 1.10.0
* - add data-blapy-template-init-fromproperty and a-blapy-template-init-search options
* - 2019/09/02 - E.Podvin - 1.9.5
* - fix bad blapy fsm to do things when blocks appear
* - 2019/09/02 - E.Podvin - 1.9.4
* - fix on undeclared variable in postDataFunc
* - fix on bad variable initialisation in postData event
* - 2019/09/01 - E.Podvin - 1.9.3
* - fix on tplid == "" in json process
* - add possibility to not send any blapy data on loadURL or postData
* - loadURL now embeds "postData"
* - 2019/08/25 - E.Podvin - 1.9.2
* - fix on search embeding block name id in setBlapyJsonTemplates to set template id to blapy object
* - data-blapy-updateblock-ondisplay works now on json blocks
* - 2019/08/25 - E.Podvin - 1.9.1
* - add automatically property "blapyIndex" for each item in json data that is an array
* - 2019/08/23 - E.Podvin - 1.9.0
* - add multi templating for json blapy blocks
* - 2019/08/23 - E.Podvin - 1.8.0
* - add "reloadBlock" feature
* - embeddingBlockId should be "block container name" (and not DOM id)
* - fix/improvement on json update management (mainly setBlapyContainerJsonTemplate)
* - 2019/08/22 - E.Podvin - 1.7.2
* - fix on header and footer in json template
* - 2019/08/15 - E.Podvin - 1.7.1
* - add fsmExtension option to extend iFSM definition of the blapy object
* - send blapycall=1&blapyaction=updateTpl&blapyobjectid=<dom object id> parameters when loading a json template
* - process templates whether they are using json2html or mustache tags as long as their libraries are loaded
* (carefull: no mix between the two tag syntaxes in the same template file)
* - 2019/08/14 - E.Podvin - 1.7.0
* - Mustache Support
* - 2019/08/10 - E.Podvin - V1.6.4 -
* - use JSON5 instead of JSON
* - store templates in a 'xmp' instead of a div fixing pb when there was comments or special structures
* - fix in setBlapyContainerJsonTemplate the async loading of the template done with $.get, template that could be not there when a loadurl or postdata was just received
* - alert when a blapy block has no id
* - 2018/05/29 - E.Podvin - V1.6.3 - remove all eval by JSON.parse
* - 2018/05/28 - E.Podvin - V1.6.2 - send container name to server when block requests an update with data-blapy-updateblock-time+compliant to $ 3.3.1
* - 2018/05/26 - E.Podvin - V1.6.1 -
* - updateBlock accepts json object or json string as html input
* - add xmp tags support to escape html in a template definition that could generate errors if not escaped
* - fixes on updateBlock when errors were logged
* - 2018/05/18 - E.Podvin - V1.6.0 - add the loading/updating of a blapy block from a local call to blapy. cf. new "updateBlock" event
* - 2017/03/20 - E.Podvin - V1.5.4 - fix on key enter on a field that did not send any info from the submit object to the request
* - 2016/12/20 - E.Podvin - V1.5.3 - fix https://github.com/intersel/Blapy/issues/4 - form should return the value of button/input of submit type
* - 2016/08/01 - E.Podvin - V1.5.2 - fix on blapy objects embedded on other blapy objects
* - 2016/07/31 - E.Podvin - V1.5.1 - fix on blapy objects embedded on other blapy objects
* - 2016/07/31 - E.Podvin - V1.5.0 -
* - add data-blapy-template-header and data-blapy-template-footer in json templating
* - fix on the scope of a blapy links now limited to their blapy object
* - for blapy objects embeded in an blapy object, we can now specify the correct blapy object that applies on a blapy links if needed (if not, will react for all blapy objects)
* - 2016/06/06 - E.Podvin - V1.4.3 - fix on setBlapyUpdateOnDisplay and blapy blocks to appear
* - 2016/04/26 - E.Podvin - V1.4.2 - fix on json file when returned as a string by .ajax (+fix on iFsm)
* - 2016/04/26 - E.Podvin - V1.4.1 - fix on multiple initialization (+fix on iFsm)
* - 2016/04/18 - E.Podvin - V1.4.0 - add pure json answer to define blapy blocks
* - 2016/04/06 - E.Podvin - V1.3.2 - add scripting within json block template with the "<blapyScriptJs>" tag
* - 2016/04/01 - E.Podvin - V1.3.1 - fix on json blocks embedded in json block
* - 2016/03/07 - E.Podvin - V1.3.0 - add block init update when it becomes visible, after a scroll or resize (data-blapy-updateblock-ondisplay option).
* - 2016/02/26 - E.Podvin - V1.2.0 - add block regular updates
* - 2016/02/17 - E.Podvin - V1.1.1 - fix when 'postData' is sent to Blapy while we're not in a "pageReady" state
* - 2016/01/20 - E.Podvin - V1.1.0 - add block update feature from a standard json feed
* - 2015/12/22 - E.Podvin - V1.0.19 - fix on default return for sammy when no blapy route is defined (return now true)
* - 2015/11/09 - E.Podvin - V1.0.18 - fix on routing to 404 error with sammy
* - 2015/11/09 - E.Podvin - V1.0.17 - fix on routing with sammy
* - 2015/11/08 - E.Podvin - V1.0.16 - Add possibility to not use Sammy (sammy may be unplugged so no routing management)
* - 2015/11/05 - E.Podvin - V1.0.15 - small fixes...
* - 2015/11/04 - E.Podvin - V1.0.14 - fix on posted data
* - 2015/11/03 - E.Podvin - V1.0.13 - remove the # duplication of the url
* - 2015/11/03 - E.Podvin - V1.0.12 - fix on the initial URL loosing the querystring part
* - 2015/09/25 - E.Podvin - V1.0.11 - fix on json updates
* - 2015/09/21 - E.Podvin - V1.0.10 - fix on the initialization of json container whose template is defined by an external file
* - 2015/08/29 - E.Podvin - V1.0.7 - add post data capabilities
* - 2015/08/07 - E.Podvin - V1.0.6 - add event Blapy_doCustomChange
* - 2015/08/05 - E.Podvin - V1.0.5 - fix on a double pageready event sent
* - 2015/08/04 - E.Podvin - V1.0.4 - fix on relative URL
* - 2015/08/02 - E.Podvin - V1.0.3 - append/prepend features on Blapy blocks
* - 2015/07/31 - E.Podvin - V1.0.1 - general fixes
* - 2015/07/25 - E.Podvin - V1.0.0 - Creation
*
* -----------------------------------------------------------------------------------------
*/
/**
* How to use it :
* ===============
*
* see README.md content or consult it on https://github.com/intersel/Blapy
*/
(function($) {
/**
* ASCII to Unicode (decode Base64 to original data)
* @param {string} b64
* @return {string}
*/
let atou = function(b64) {
return decodeURIComponent(escape(atob(b64)));
}
/**
* Unicode to ASCII (encode data to Base64)
* @param {string} data
* @return {string}
*/
let utoa = function (data) {
return btoa(unescape(encodeURIComponent(data)));
}
/**
* The Blapy Object that controlls a set of blapy blocks
* @param {jQuery} the jquery object handled with blapy [description]
* @param {Object} options
* @return {Object}
* - opts : set of option
* - myUIObject: Target object of the blapy's FSM
* - myUIObjectID: Id of the target objet
*/
let theBlapy = window.theBlapy = function(anObject, options) {
let $defaults = {
debug: true, //if true, then log things in the console
LogLevel: 1, // log level: 1: error ; 2: warning; 3: notice
debugIfsm: false, // debug mode for ifsm
LogLevelIfsm: 1,
alertError: false,
//function Hooks
pageLoadedFunction: null,
pageReadyFunction: null,
beforePageLoad: null,
beforeContentChange: null, //param: the Blapy block whose content will change
afterContentChange: null, //param: the Blapy block whose content has changed
afterPageChange: null,
doCustomChange: null,
onErrorOnPageChange: null,
theBlapy: this,
/**
* activeSammy- if set, activates 'sammy' routing
* @type {Boolean}
*/
activeSammy: false,
/**
* fsmExtension - an FSM extension to the default blapy FSM definition
* useful to extend the API of the blapy object (in "PageReady" state for example)
* @type {[type]}
*/
fsmExtension: null,
};
// on charge les options passées en paramètre
if (options == undefined) options = null;
this.opts = $.extend({}, $defaults, options || {});
this.optsIfsm = $.extend({}, $defaults, options || {});
// redefine log options for ifsm
this.optsIfsm.debug = this.opts.debugIfsm;
this.optsIfsm.LogLevel = this.opts.LogLevelIfsm;
/**
* @param myUIObject public - Target object of the FSM
*/
this.myUIObject = anObject;
/**
* @param myUIObjectID public
* @type {[type]}
*/
this.myUIObjectID = anObject.attr('id');
if (!this.myUIObjectID) alert('no defined Id on the given jQuery object... Blapy can\'t work properly :-(');
/**
* @param intervalsSet private
* @type {Array}
* intervals of time set to update blapy blocks
*/
this.intervalsSet = new Array();
};
/**
* InitApplication - init the Blapy
* public method
*/
theBlapy.prototype.InitApplication = function() {
this._log('InitApplication');
let myBlapy = this;
if (myBlapy.opts.fsmExtension) {
$.extend(true,manageBlapy, myBlapy.opts.fsmExtension)
}
// Sammy routing if set
if (this.opts.activeSammy) {
//Standard Routing definition
if (typeof Sammy != 'function') {
alert("Sammy is not loaded... can not continue");
return false;
}
let app = Sammy('#' + this.myUIObjectID);
app.get(/(.*)\#blapylink/, function() {
//filter the action to be processed only on the defined active blapy object for the link
if (($(this.target).attr("data-blapy-active-blapyid")) && ($(this.target).attr("data-blapy-active-blapyid") != myBlapy.myUIObjectID))
return;
this.params['embeddingBlockId'] = myBlapy.extractembeddingBlockIdName(myBlapy.hashURL());
if (!this.params['embeddingBlockId']) delete(this.params['embeddingBlockId']);
myBlapy.myUIObject.trigger('loadUrl', {
aUrl: myBlapy.hashURL(),
params: myBlapy.filterAttributes(this.params),
aObjectId: myBlapy.myUIObjectID,
noBlapyData:$(this).attr("data-blapy-noblapydata")
});
});
app.post(/(.*)\#blapylink/, function() {
//filter the action to be processed only on the defined active blapy object for the link
if (($(this.target).attr("data-blapy-active-blapyid")) && ($(this.target).attr("data-blapy-active-blapyid") != myBlapy.myUIObjectID))
return;
this.params['embeddingBlockId'] = myBlapy.extractembeddingBlockIdName(myBlapy.hashURL(this.path));
if (!this.params['embeddingBlockId']) delete(this.params['embeddingBlockId']);
myBlapy.myUIObject.trigger('postData', {
aUrl: myBlapy.hashURL(this.path),
params: myBlapy.filterAttributes(this.params),
aObjectId: myBlapy.myUIObjectID,
method: "post",
});
});
app.put(/(.*)\#blapylink/, function() {
//filter the action to be processed only on the defined active blapy object for the link
if (($(this.target).attr("data-blapy-active-blapyid")) && ($(this.target).attr("data-blapy-active-blapyid") != myBlapy.myUIObjectID))
return;
this.params['embeddingBlockId'] = myBlapy.extractembeddingBlockIdName(myBlapy.hashURL(this.path));
if (!this.params['embeddingBlockId']) delete(this.params['embeddingBlockId']);
myBlapy.myUIObject.trigger('postData', {
aUrl: myBlapy.hashURL(this.path),
params: myBlapy.filterAttributes(this.params),
aObjectId: myBlapy.myUIObjectID,
method: "put"
});
});
app.notFound = function(verb, path) {
//just do nothing! means that the called link is not handle by Blapy (no route for Sammy)...
return true;
};
this.myFsm = this.myUIObject.iFSM(manageBlapy, this.optsIfsm);
app.run();
}
else
// no routing - standard blapy links management
{
//start Blapy Engine
this.myFsm = this.myUIObject.iFSM(manageBlapy, this.optsIfsm);
$(document).on("click", "#" + myBlapy.myUIObjectID + " a[data-blapy-link]", function(event) {
//if requested, filter the action to be processed only to the defined active blapy object for the link
if (($(event.currentTarget).attr("data-blapy-active-blapyid")) && ($(event.currentTarget).attr("data-blapy-active-blapyid") != myBlapy.myUIObjectID))
return;
//use JSON5 if present as JSON5.parse is more cool than JSON.parse (cf. https://github.com/json5/json5)
let jsonFeatures = null;
if (typeof(JSON5) == "undefined") jsonFeatures=JSON;else jsonFeatures=JSON5;
let params = $(this).attr("data-blapy-params");
if (params != undefined) params = jsonFeatures.parse(params);
else params = {};
if ($(this).attr('data-blapy-embedding-blockid'))
params = $.extend(params, {embeddingBlockId: $(this).attr('data-blapy-embedding-blockid')});
event.preventDefault();
myBlapy.myUIObject.trigger('postData', {
aUrl: myBlapy.hashURL($(this).attr('href')),
params: params,
method: $(this).attr("method")||'GET',
aObjectId: myBlapy.myUIObjectID,
noBlapyData:$(this).attr("data-blapy-noblapydata")
});
});
$(document).on("submit", "#" + myBlapy.myUIObjectID + " form[data-blapy-link]", function(event) {
//if requested, filter the action to be processed only to the defined active blapy object for the link
if (($(event.currentTarget).attr("data-blapy-active-blapyid")) && ($(event.currentTarget).attr("data-blapy-active-blapyid") != myBlapy.myUIObjectID))
return;
event.preventDefault();
// get all the inputs into an array.
let $inputs = $(this).serializeArray();
// get an associative array of the values in the form and send it
let formValues = {};
$.each($inputs, function() {
formValues[this.name] = this.value;
});
//add the submit input info that is not given by the serializeArray
if (event.originalEvent) {
aSubmitInput = $(event.originalEvent.currentTarget.activeElement);
if (aSubmitInput) {
//the submit was emitted by an input that is not of submit type (enter on a field perhaps)
if (aSubmitInput.attr('type') != 'submit') {
//let's get the first submit object
aSubmitInput = $(event.originalEvent.target).find("*").filter(':submit:visible:first')
}
if (aSubmitInput && aSubmitInput.attr('name')) formValues[aSubmitInput.attr('name')] = aSubmitInput.attr('value');
}
}
formValues['embeddingBlockId'] = $(this).attr('data-blapy-embedding-blockid');
myBlapy.myUIObject.trigger('postData', {
aUrl: myBlapy.hashURL($(this).attr("action")),
params: formValues,
aObjectId: myBlapy.myUIObjectID,
method: $(this).attr("method"),
noBlapyData:$(this).attr("data-blapy-noblapydata")
});
});//end on submit
}
}; //
/**
* this._log - log function
* private function
* @param message - message to log
* @param error_level (default : 3)
* - 1 : it's an error
* - 2 : it's a warning
* - 3 : it's a notice
*
*/
theBlapy.prototype._log = function(message) {
/*global console:true */
let errorLevel = 3;
if (arguments.length > 1) errorLevel = arguments[1];
//show only errors if debug is not set
if ( (errorLevel >= 2) && (!this.opts.debug) ) return;
if (errorLevel > this.opts.LogLevel) return; //on ne continue que si le nv de message est <= LogLevel
if (window.console && console.log) {
switch (errorLevel)
{
case 1:
console.error('[blapy] ' + message);
break;
case 2:
console.warn('[blapy] ' + message);
break;
default:
case 3:
console.log('[blapy] ' + message);
break;
}
if ((errorLevel == 1) && this.opts.alertError) alert(message);
}
}; //end Log
/**
*
* returns the target block name of the URL if any
*/
theBlapy.prototype.extractembeddingBlockIdName = function(aBlapyUrl) {
regexHashBlapyBlock = /#blapylink#.*/igm;
extractEB = regexHashBlapyBlock.exec(aBlapyUrl);
if (extractEB && extractEB.length) {
extractEB = extractEB[0].replace('#blapylink#', '');
} else extractEB = '';
return extractEB;
};
/**
* embeds a html source with a blapy block definition of aBlapyBlockIdName
* returns the embedded html source
*/
theBlapy.prototype.embedHtmlPage = function(aHtmlSource, aBlapyBlockIdName) {
// htmlBlapyBlock = this.myUIObject.find('#' + aBlapyBlockIdName);
htmlBlapyBlock = this.myUIObject.find("[data-blapy-container-name='" + aBlapyBlockIdName + "']");
if (!htmlBlapyBlock[0])
{
this._log('embedHtmlPage: Error on blapy-container-name... "'+aBlapyBlockIdName+'" does not exist!\n',1);
return '';
}
if ( ($(htmlBlapyBlock[0].outerHTML).attr('data-blapy-update') == 'json')
&& ($(htmlBlapyBlock[0].outerHTML).attr("data-blapy-template-init-purejson") == "0")
)
{
try{
aHtmlSource = $(aHtmlSource).html();
} catch (e) {
this._log('embedHtmlPage: aHtmlSource is perhaps a pure json after all...?\n' + aHtmlSource, 3);
}
}
//embed html source in an xmp to avoid any tampering by the browser
aHtmlSource = '<xmp class="blapybin">'+utoa(aHtmlSource)+'</xmp>';
aHtmlSource = $(htmlBlapyBlock[0].outerHTML).html(aHtmlSource);
aHtmlSource.attr('data-blapy-container-content', aHtmlSource.attr('data-blapy-container-content') + '-' + $.now());
aHtmlSource.attr('id', ''); //remove id in order that it takes the one of the block to change
return aHtmlSource[0].outerHTML;
};
/**
* create a blapy block from a pure json definition
* returns the html source of the blapy block
*
* aJsonObject : array of blapy objects described with the attributes of a blapy block
* the essential attributes are blapy-container-name, blapy-container-content
* the attribute "blapy-data" gives the new data of the block
*/
theBlapy.prototype.createBlapyBlock = function(aJsonObject) {
this._log('createBlapyBlock');
if (!aJsonObject["blapy-container-name"])
{
this._log('createBlapyBlock: Error on received json where blapy-container-name is not defined!\nPerhaps it\'s pure json not defined as such in Blapy block configuration (cf. data-blapy-template-init-purejson)...\n'+JSON.stringify(aJsonObject),1);
}
htmlBlapyBlock = $('<div/>', {
"data-blapy-container": true,
"data-blapy-container-name": aJsonObject["blapy-container-name"],
"data-blapy-container-content": aJsonObject["blapy-container-content"],
"data-blapy-update": "json"
}).html(JSON.stringify(aJsonObject['blapy-data']));
return htmlBlapyBlock;
};
/**
* get the hash part of the URL
* returns 0 if none
*/
theBlapy.prototype.hashURL = function(aURL) {
this._log('hashURL');
if (!aURL) aURL = window.location.href;
return aURL || 0;
};
//creation function of Blapy that embeds jQuery
$.fn.Blapy = function(options) {
if (!this.length) alert("The jquery selector '" + this.selector + "' is void!?\n\n Can\'t start Blapy...\n\n :-(");
return this.each(function() {
let Blapy = new theBlapy($(this), options);
Blapy.InitApplication(); //start it
});
};
/**
* filter to get only usefull attributes
* on a Sammy Object
* returns an object without any function or object
*
*/
theBlapy.prototype.filterAttributes = function(aSammyObject) {
//let sammyKeys=aSammyObject.keys();
let mySammyObject = aSammyObject;
let returnObject = {};
$.each(aSammyObject.keys(),
function(key, value) {
if ((typeof mySammyObject[value] != 'function') && (typeof mySammyObject[value] != 'object')) {
//console.log(value+" "+mySammyObject[value]+(typeof mySammyObject[value]));
returnObject[value] = mySammyObject[value];
//alert(localO);console.log(localO);
};
});
return returnObject;
};
/**
* set # tag in the Blapy Url
* returns 0 if none
*/
theBlapy.prototype.setBlapyUrl = function() {
this._log('setBlapyUrl');
let myBlapy = this;
//change href on blapy-link within the blapy object
$('#' + myBlapy.myUIObjectID + ' [data-blapy-link]').each(function() {
let aHref;
//in case a blapy object is within another blapy object, we need to tell which active blapy object to listen...
if (($(this).attr("data-blapy-active-blapyId")) && ($(this).attr("data-blapy-active-blapyId") != myBlapy.myUIObjectID))
return;
if ($(this)[0].tagName == 'A')
aHref = $(this).attr("href");
else if ($(this)[0].tagName == 'FORM')
aHref = $(this).attr("action");
else
aHref = $(this).attr("data-blapy-href");
if (!aHref) return; //not valid... for now
if (aHref.indexOf('#blapylink') == -1) {
aHref += '#blapylink';
if ($(this).attr('data-blapy-embedding-blockid')
&& ($(this).attr('data-blapy-embedding-blockid') != "")
)
{
aHref += '#' + $(this).attr('data-blapy-embedding-blockid');
}
if ($(this)[0].tagName == 'A')
$(this).attr("href", aHref);
else if ($(this)[0].tagName == 'FORM')
$(this).attr("action", aHref);
else {
if ((aHref.charAt(0) != '/') &&
(aHref.substring(0, 4) != "http")
) {
let aBaseHref = $('base').attr('href');
if (aBaseHref)
aHref = aBaseHref + aHref;
else
aHref = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/") + 1) + aHref;
}
$(this).attr("data-blapy-href", aHref);
$(this).click(function() {
myBlapy.myUIObject.trigger('loadUrl', {
aUrl: aHref,
params: '',
aObjectId: myBlapy.myUIObjectID,
noBlapyData:$(this).attr("data-blapy-noblapydata")
});
});
}
}
});
};
/**
* prepare update block calls on interval time
*
*/
theBlapy.prototype.setBlapyUpdateIntervals = function() {
this._log('setBlapyUpdateIntervals');
let myBlapy = this;
let intervalSetId = 0;
//clear all intervals set
for (i = 0; i < myBlapy.intervalsSet.length; i++) {
clearInterval(myBlapy.intervalsSet[i]);
}
//for any template block
$('#' + myBlapy.myUIObjectID + ' [data-blapy-updateblock-time]').each(function() {
let myContainer = $(this);
let aUpdateBlockTime = myContainer.attr("data-blapy-updateblock-time");
let aUpdateBlockHrefURL = myContainer.attr("data-blapy-href")+'?blapyContainerName='+myContainer.attr('data-blapy-container-name');
if (aUpdateBlockTime) {
myBlapy.intervalsSet[intervalSetId] = setInterval(function() {
$('#' + myBlapy.myUIObjectID).trigger('loadUrl', {
aUrl: aUpdateBlockHrefURL,
noBlapyData:myContainer.attr("data-blapy-noblapydata")
});
}, aUpdateBlockTime);
intervalSetId++;
}
});
}
/**
* prepare update block calls when the block becomes visible
*
*/
theBlapy.prototype.setBlapyUpdateOnDisplay = function() {
this._log('setBlapyUpdateOnDisplay');
if (!window.jQuery.prototype.appear) {
this._log('setBlapyUpdateOnDisplay: jquery.appear.js is not loaded...');
if ($('[data-blapy-updateblock-ondisplay]').length > 0)
alert('Blapy: jquery.appear.js is not loaded. Need it to process data-blapy-updateblock-ondisplay option');
return;
}
let myBlapy = this;
$(myBlapy.myUIObject).off('appear');
$(myBlapy.myUIObject).find('[data-blapy-updateblock-ondisplay]').appear();
$(myBlapy.myUIObject).on('appear', '[data-blapy-updateblock-ondisplay]',
function(event, $all_appeared_elements) {
if (!$(this).attr("data-blapy-appear"))
$(this).attr("data-blapy-appear", 'done');
else return;
if ($(this).attr("data-blapy-href"))
{
myBlapy.myUIObject.trigger('loadUrl', {
aUrl: $(this).attr("data-blapy-href"),
noBlapyData:$(this).attr("data-blapy-noblapydata")
});
}
else if ($(this).attr("data-blapy-template-init"))
{
let myContainerName = $(this).attr("data-blapy-container-name");
myBlapy.myUIObject.trigger('reloadBlock',{
params:{
embeddingBlockId:myContainerName,
}
});
}
}
);
$.force_appear();
}
/**
* setBlapyContainerJsonTemplate - prepare a json container with its template and initial values
* @param {[type]} myContainer [description]
* @param {[type]} myBlapy the
* @return {[type]} [description]
*/
theBlapy.prototype.setBlapyContainerJsonTemplate = function(myContainer, myBlapy, forceReload) {
return new Promise(resolve => {
this._log('setBlapyContainerJsonTemplate');
localBlapy = this;
if (forceReload == undefined) forceReload=false;
/**
* postDataFunc - activate the initialization of the json block
* @return {[type]} [description]
*/
let postDataFunc = function(forceReload) {
//use JSON5 if present as JSON5.parse is more cool than JSON.parse (cf. https://github.com/json5/json5)
let jsonFeatures = null;
if (typeof(JSON5) == "undefined") jsonFeatures=JSON;else jsonFeatures=JSON5;
//do we have to get the data only when block is displayed?
if ( !forceReload
&& myContainer.attr("data-blapy-updateblock-ondisplay")
&& (myContainer.attr("data-blapy-appear") != 'done')
)
{
//$(document).scroll();//force appear to work...
return;
}
let aInitURL = myContainer.attr("data-blapy-template-init");
if (aInitURL)
{
let aInitURL_Param = myContainer.attr("data-blapy-template-init-params");
if (aInitURL_Param != undefined) aInitURL_Param = jsonFeatures.parse(aInitURL_Param);
else aInitURL_Param = {};
let aInitURL_EmbeddingBlockId = myContainer.attr("data-blapy-template-init-purejson");
if ( (aInitURL_EmbeddingBlockId !== "0") ) //default: pure blapy json
aInitURL_Param = $.extend({'embeddingBlockId':myContainer.attr("data-blapy-container-name")}, aInitURL_Param);
let noBlapyData = myContainer.attr("data-blapy-noblapydata");
if ( (noBlapyData == undefined) ) noBlapyData = "0";
let aInitURL_Method = myContainer.attr("data-blapy-template-init-method");
if (aInitURL_Method == undefined) aInitURL_Method = "GET";
$('#' + myBlapy.myUIObjectID).trigger('postData', {
"aUrl": aInitURL,
"params":aInitURL_Param,
"method":aInitURL_Method,
'noBlapyData':noBlapyData
});
}
else {
}
resolve();//promise is fullfilled
//alert that template of blapy block is loaded and ready
if (myContainer.attr('id'))
$('#' + myContainer.attr('id')).trigger('Blapy_templateReady', myContainer);
// localBlapy._log("Blapy_templateReady\n"+myContainer.attr('id'),1);
};
//if block is declared json, then we take local update rule (json)
myContainer.attr('data-blapy-update-rule', 'local');
//Search for a template container already defined within the blapy container
let htmlTpl = myContainer.children('[data-blapy-container-tpl]'); // if still processed, a block data-blapy-container-tpl will be inside
if (htmlTpl.length == 0) // ok so not processed, so let's do it
{
let htmlTplContent = myContainer.html();
//remove any xmp tags (used to escape html in a template definition that could generate errors if not escaped)
//htmlTplContent = htmlTplContent.replace(/(\r\n|\n|\r)?<\/?xmp[^>]*>(\r\n|\n|\r)?/gi, '');
try {
if ($(htmlTplContent).prop("tagName") == "XMP") htmlTplContent = $(htmlTplContent).html();
}
catch(error) {
//htmlTplContent is not html???...
this._log("htmlTplContent from "+myContainer.attr("id")+" is not html template...?\n"+htmlTplContent,1);
}
//if no template defined within the block
if (htmlTplContent
.replace(/(<!--.*?-->)|(<!--[\S\s]+?-->)|(<!--[\S\s]*?$)/g, '')
.replace(/\s{2,}/g, ' ')
.replace(/\t/g, ' ')
.replace(/(\r\n|\n|\r)/g, "")
.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)/g, '')
.trim()
== "")
{
//look for partial template file
let tplFile = myContainer.attr("data-blapy-template-file");
let myBlapy = this;
let blapyData = (myContainer.attr("data-blapy-noblapydata") == '1')//don't send any blapy info
? '' : "blapycall=1&blapyaction=loadTpl&blapyobjectid=" + myContainer.attr('id');
if (tplFile && (!myBlapy.tplFile || !myBlapy.tplFile[tplFile]))
{
$.get(
{
url: tplFile,
data: blapyData,
success: function(htmlTplContent) {
//replace img by anything in order that the system don't want to load them... same for script
// as we only want to know if there are siblings...
htmlTplContent = htmlTplContent.replace(/<!--(.*?)-->/gm, "").replaceAll("\n\n",'\n').replaceAll("\t\t","\t");
let tmpHtmlContent = htmlTplContent
.replace(/{{(.*?)}}/gm, "")
.split("script")
.join("scriptblapy")
.split("img")
.join("imgblapy");
if (
$(tmpHtmlContent).prop("tagName") != "XMP"
)
{
//store the template in comment in a hidden xmp
htmlTplContent = '<xmp style="display:none" data-blapy-container-tpl="true">' + htmlTplContent + '</xmp>';
myContainer.html(htmlTplContent);
}
else
{
myContainer.html(htmlTplContent);
}
if (!myBlapy.tplFile) myBlapy.tplFile={};
myBlapy.tplFile[tplFile] = htmlTplContent;
postDataFunc();
},
//async: false,
});
}//end if (tplFile)
else if (tplFile && myBlapy.tplFile && myBlapy.tplFile[tplFile]) {
myContainer.html(myBlapy.tplFile[tplFile]);
postDataFunc();
}
else // no defined template...?
{
postDataFunc();
}
}//end if
else //template is defined in the block
{
htmlTplContent = htmlTplContent.replace(/<!--(.*?)-->/gm, "").replaceAll("\n\n",'\n').replaceAll("\t\t","\t");
let tmpHtmlContent = htmlTplContent
.replace(/{{(.*?)}}/gm, "")
.split("script")
.join("scriptblapy")
.split("img")
.join("imgblapy");
if (
$(tmpHtmlContent).prop("tagName") != "XMP"
)
{
//store the template in comment in a hidden xmp
myContainer.html('<xmp style="display:none" data-blapy-container-tpl="true">' + htmlTplContent + '</xmp>');
}
else
{
myContainer.html(htmlTplContent);
}
postDataFunc();
}//end else //template is defined in the block
}//end if (htmlTpl.length == 0)
else if (forceReload)
{
postDataFunc(forceReload);
}
});//end Promise
};
/**
* setBlapyJsonTemplates - prepare the json templates of the blapy blocks controlled with json (cf [data-blapy-update="json"])
* json templates are stored in a hidden xmp with a "data-blapy-container-tpl" attribute set
*
* @param boolean forceReload reload initial json content
* @param string (option/default:undefined) aEmbeddingBlock a specific block container name
* @param string (option/default:undefined) aTemplateId default template to set on the block
* @return void
*/
theBlapy.prototype.setBlapyJsonTemplates = function(forceReload,aEmbeddingBlock,aTemplateId) {
this._log('setBlapyJsonTemplates');
let myBlapy = this;
if (forceReload == undefined) forceReload=false;
if (aEmbeddingBlock) aEmbeddingBlock="[data-blapy-container-name='"+aEmbeddingBlock+"']";
else aEmbeddingBlock="";
// set the default template
if (aTemplateId)
{
$(myBlapy.myUIObject).find('[data-blapy-update="json"]'+aEmbeddingBlock)
.attr('data-blapy-template-default-id',aTemplateId);
}
//for any json template block
let jsonBlocks = $(myBlapy.myUIObject).find('[data-blapy-update="json"]'+aEmbeddingBlock);
if (jsonBlocks.length > 0)
{
(function(){
jsonBlocks.each(async function() {
let myContainer = $(this);
await myBlapy.setBlapyContainerJsonTemplate(myContainer, myBlapy, forceReload);
});
myBlapy.myFSM.trigger('blapyJsonTemplatesIsSet');
})();
}
else
{
myBlapy.myFSM.trigger('blapyJsonTemplatesIsSet');
}
};
/**
* getObjects - return an array of objects according to key, value, or key and value matching
* @param {Object} obj a json object
* @param {string} key a json property
* @param {string} val a json value
* @return {Array} results of the search
* @example
* this.getObjects(js,'ID','SGML');// look for sub objects whose properties 'ID' in the json tree have their value == 'SGML'
* this.getObjects(js,'ID',''); // look for sub objects whose properties 'ID' in the json tree with any value
* this.getObjects(js,'','SGML');// look for any sub object that contains a property with the value == 'SGML'
*/
theBlapy.prototype.getObjects = function (obj, key, val) {
let objects = [];
for (let i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(this.getObjects(obj[i], key, val));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(obj);
}
}
}
return objects;
}
/* let & function definitions */
/**
* manageBlapy
* @type {Object} Blapy state machine definition
*/
let manageBlapy = {
PageLoaded: {
enterState: {
init_function: function() {
//store the iFSM in Blapy
this.opts.theBlapy.myFSM = this;
//process interval updates
this.opts.theBlapy.setBlapyUpdateIntervals();
if (this.opts.pageLoadedFunction) this.opts.pageLoadedFunction();
this.myUIObject.trigger('Blapy_PageLoaded');
},
next_state: 'PreparePage',
},
/* postData: 'loadUrl',
updateBlock: 'loadUrl',
loadUrl: //no load URL at first load of the page (generated by sammy)
{
propagate_event: true,
next_state: 'PageReady',
},
*/
},
PreparePage: {
enterState: {
init_function: function() {
},
propagate_event: 'setBlapyUrl'
},
setBlapyUrl: {
init_function: function() {
// set #tag to the Blapy url