-
Notifications
You must be signed in to change notification settings - Fork 0
/
%ZHTML.CacheLib.CLS
2489 lines (2321 loc) · 105 KB
/
%ZHTML.CacheLib.CLS
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
///
/// <br>Скрипт(JS):
/// <br> <script type="text/javascript" src='%25ZHTML.CacheLib.cls'></script>
/// <br>
/// <br> <!-- <script language="JavaScript" type="text/javascript" src="%25ZHTML.CacheLib.cls"></script> -->
/// Описание:
/// 1) Реализована трансляция Cache` классов в JS функции глобальные.
/// 2) Реализована трансляция Cache` классов в прототипы JS при инициализации страницы и в коде
/// 3) Реализована функция динамического подключения библиотек (js и css - файлы)
/// 4) Реализована функция динамического подключения прототипов и глобальных функция.
/// 5) Реализована возможность запуска класс методов с передачей в функцией (callback) обработки результата в качестве аргумента.
/// <br>
///
/// <pre>
/// Динамическое подключение библиотек в JS коде:
/// а) Подключаем базовую библиотеку на CSP странице:
/// <script src='%25ZHTML.CacheLib.cls' type='text/javascript' ></script>
/// б) Подключение библиотек JS,CSS,cls:
/// </pre>
/// <example>
/// <script language="JavaScript">
/// // Подключаем библиотеку JS из класса
/// includeClass('HTML.js.WebGL.BabylonJS.babylon.cls','javascript');
/// // Подключаем JS библиотеку из файла
/// includeFile('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js','javascript');
/// // Подключаем JS библиотеку из файла
/// includeFile('https://jQuery.min.js');
/// // Подключаем CSS библиотеку из файла
/// includeFile('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css','css');
/// </script>
/// </example>
/// <pre>
///
/// Примечание : Функции расположенные внутри, подключаемых классов, станут доступны после полной инициализации страницы.
///
///
/// Применение функции runMethod :
///
/// а) Создаем классметод:
/// </pre>
/// <example>
/// Class User.test
/// {
/// ClassMethod Test1 (arg) As %String
/// {
/// w "Test Message:" _arg
/// q ""
/// }
/// }g
/// </example>
/// <pre>
///
/// б) Подключаем базовую библиотеку на CSP странице:
/// <script src='%25ZHTML.CacheLib.cls' type='text/javascript' ></script>
/// в) Синхронный вызов класс метода:
/// </pre>
/// <example>
/// <script language="JavaScript">
/// alert ( runMethod('User.test.Test1', 'arg1233') );
/// </script>
/// </example>
/// г) Асинхронный вызов класс метода:
/// <example>
/// <script language="JavaScript">
/// /// функция обработки ответа
/// resultFun=function(txt){ alert(txt); }
/// runMethod('User.test.Test1',resultFun,'arg1233');
/// </script>
/// </example>
/// д) Вызов класс метода Test2 расположенного на странице CSP:
/// <example>
/// <script language="JavaScript">
/// /// функция обработки ответа
/// resultFun=function(txt){ alert(txt); }
/// runMethod('Test2',resultFun,'arg1233');
/// </script>
/// </example>
///
/// Расположение глобальной JS функции в Cache` классе:
/// а) Создаем класс:
/// <example>
/// Class User.test Extends %ZHTML.CacheLib
/// {
/// ClassMethod Test1(fff,ddd) [ Language = cache, WebMethod ]
/// {
/// w fff_"---"_ddd
/// }
/// ClassMethod Test2(Arg1,Arg2) As %String [ Language = cache, WebMethod ]
/// {
/// q Arg1_"----Вар2----"_Arg2
/// }
/// ClientMethod Test3(Arg1) As %String [ Language = javascript, WebMethod ]
/// {
/// alert(Arg1);
/// }
/// }
/// </example>
/// <pre>
///
/// б) Подключаем базовую библиотеку на CSP странице:
/// <script src='User.test.cls' type='text/javascript' ></script>
/// в) Синхронный вызов класс метода:
/// <script language="JavaScript">
/// alert (Test1('arg1233'));
/// </script>
/// г) Асинхронный вызов класс метода:
/// </pre>
/// <example>
/// <script language="JavaScript">
/// /// функция обработки ответа
/// resultFun=function(txt){ alert(txt); }
/// Test1(resultFun,'arg1233');
/// </script>
/// </example>
/// <pre>
/// Примечание : в ClassMethod и ClientMethod необходимо указывать параметр WebMethod и язык написания кода Language = javascript .
/// Создание JS прототипа в Cache` классе
/// а) Создаем класс:
/// </pre>
/// <example>
/// Class User.Prototyp Extends (%ZHTML.CacheLib, User.Prototype2, User.NewClass2)
/// {
/// /// Альтернативное название прототипа.
/// /// Если этого параметра нет, тогда имя прототипа
/// /// берется из имени класса “Prototyp”
/// Parameter ClassName = "ClassName";
/// /// Публичные переменные прототипа
/// Property Pole1 As %String [ InitialExpression = "Value1", Internal ];
/// Property Pole2 As %String [ InitialExpression = "Value2", Internal ];
/// Property Pole3 As %String [ Internal ];
/// /// Конструктор прототипа
/// ClientMethod Prototyp(arg1 = "") As %String [ Internal, Language = javascript ]
/// {
/// this.Pole1=arg1;
/// }
/// ClassMethod Test() As %String [ Internal, Language = cache ]
/// {
/// zw
/// q ""
/// }
/// ClientMethod Test3(arg1 = "") As %String [ Internal, Language = javascript ]
/// {
/// alert(arg1);
/// }
/// }
/// </example>
/// <pre>
///
/// б) Подключаем базовую библиотеку на CSP странице:
/// <script src='User.Prototyp.cls' type='text/javascript' ></script>
/// в) Применение прототипа:
/// </pre>
/// <example>
/// <script language="JavaScript">
/// var edit=new Prototyp('Test-Prototyp');// Создаем экземпляр прототипа
/// alert(edit.Pole1); // обращение к переменной
/// alert(edit.Test());// синхронный вызов функции
/// retunFun=function(txt){ alert(txt); }
/// edit.Test(retunFun); // асинхронный вызов
/// edit.Test3(retunFun,'Args123')// асинхронный вызов
/// </script>
/// </example>
///
/// <pre>
/// Примечание :
/// 1) При наследовании прототипов все свойства и методы родителей, так же наследуются.
/// 2) Для включения элемента в состав прототипа необходимо указать параметр “ Internal” и название языка написания кода “Language = javascript”.
/// 3) Из класс метода Cache невозможно напрямую обращаться к полям прототипа. В ClientMethod поля прототипа доступны по JS правилам.
/// 4) Если в прототипе описана глобальная функция (с параметром WebMethod ) она будет интерпретирована как глобальная функция
/// Пример создания глобальной переменной JS в классе Cache
/// Добавляем в параметр Property свойство "[ServerOnly = 1]" при интерпритации класса это поле превратится в глобальную JS переменную.
/// </pre>
/// <example>
/// Class Demo.Three.Panarama2 Extends %CSP.Page
/// {
/// Property GlobalVar1 As %String [ InitialExpression = {$h}, ServerOnly = 1 ];
/// Property GlobalVar2 As %String [ InitialExpression = "Тестовый текст инициируется при загрузке страницы", ServerOnly = 1 ];
/// ClientMethod MyAlert(arg) [ Language = javascript, WebMethod ]
/// {
/// alert(arg);
/// }
/// ClassMethod OnPage() As %Status
/// {
/// &html<
/// <script src='%25ZHTML.CacheLib.cls' type='text/javascript' ></script>
/// <script type='text/javascript' >
/// alert(GlobalVar1);
/// MyAlert(GlobalVar2);
/// </script>
/// >
/// q $$$OK
/// }
/// }
/// </example>
/// <pre>
///
/// Пример вызова Cache сода из JS клиент метода
/// Добавляем в параметр Property свойство "[ServerOnly = 1]" при интерпритации класса это поле превратится в глобальную JS переменную.
/// </pre>
/// <example>
/// Class Demo.Delete Extends %CSP.Page
/// {
/// ClientMethod MyAlert(arg) [ Language = javascript, WebMethod ]
/// {
/// // /*( 'Команда cache' )*/
/// // Выполнить однострочную команду
/// alert(' /*( w $zdt($h))*/ '+arg)
/// }
/// ClassMethod OnPage() As %Status
/// {
/// &html<
/// <script src='%25ZHTML.CacheLib.cls' type='text/javascript' ></script>
/// <script language='javascript'>
/// MyAlert('Тестовое сообщение');
/// </script>
/// >
/// Quit $$$OK
/// }
/// }
/// </example>
///
/// <h3>Создание собственного HTML элемента в Cache классе (работа с прототипами). </h3>
/// Создаем прототип HTML элемента:
/// <example>
/// Class User.Prototyp2 Extends %ZHTML.CacheLib
/// {
/// /// Название класса для создания элемента из JS
/// Parameter ClassName = "TestHtmlTag";
/// /// имя тэга <my-input>0</my-input>
/// Parameter tagName = "my-input";
/// Property timer As %Integer [ InitialExpression = 0, Internal ];
/// /// содержимое Тэга
/// Property innerHTML As %String [ InitialExpression = "Value1", Internal ];
/// /// JS Конструктор HTML элемента
/// ClientMethod prototyp2(arg1 = "") As %String [ Internal, Language = javascript ]
/// {
/// this.Pole1=arg1;
/// }
/// /// запуск таймера
/// ClientMethod attachedCallback() As %String [ Internal, Language = javascript ]
/// {
/// setInterval(this.tick.bind(this), 1000);
/// }
/// /// Функция срабатывает после создания элемента (инициализация)
/// ClientMethod createdCallback() As %String [ Internal, Language = javascript ]
/// {
/// this.timer = 0;
/// }
/// /// функция инкремента
/// ClientMethod tick() As %String [ Internal, Language = javascript ]
/// {
/// this.timer++;
/// this.innerHTML = this.timer;
/// }
///
/// }
///
/// </example>
/// Создание HTML элемента в CSP файле
/// <example>
/// <html>
/// <head>
/// <title> Cache Server Page </title>
/// </head>
/// <body>
/// <script src='%25ZHTML.CacheLib.cls' type='text/javascript' ></script>
/// <script src='User.Prototyp2.cls' type='text/javascript' ></script>
/// <my-input>222222</my-input>
/// </body>
/// </html>
/// </example>
/// <h3> Подключение JS библиотек из классов </h3>
/// <example>
///
/// /// Подключаемый класс
/// Class User.Test
/// {
/// ClientMethod MyAlert(txt) [ Language = javascript, WebMethod ]
/// {
/// alert(txt);
/// }
///
/// }
///
/// /// Применение <include-js src="User.Test"></include-js>
/// Class User.includeTest Extends %CSP.Page
/// {
///
/// ClassMethod OnPage() As %Status
/// {
/// &html<
/// <script src='%25ZHTML.CacheLib.cls' type='text/javascript' ></script>
/// <include-js src="User.Test"></include-js>
/// <include-css src='User.Test'></include-css>
/// >
/// &html<
/// <script type='text/javascript' >
/// MyAlert('ssssssssssss');
/// </script>
/// >
/// Quit $$$OK
/// }
///
/// }
/// </example>
Class %ZHTML.CacheLib Extends %CSP.Page
{
/// d ##class(%ZHTML.CacheLib).ExportUDL()
ClassMethod ExportUDL(path = "")
{
if $l(path)=0 d $system.OBJ.ExportUDL(##this_".CLS", "C:\TMP\"_##this_".CLS","/diffexport")
e d $system.OBJ.ExportUDL(##this_".CLS", path,"/diffexport")
}
ClassMethod OnPreHTTP() As %Library.Boolean
{
; s %response.CharSet="CP1251"
if %request.Get("cspIntRunMethod",0)=1 {
if %response.ContentType="text/html" {
Do %response.SetHeader("Content-Type","text/plain")
}
q 1
}
Do %response.SetHeader("Content-Type","application/javascript")
q 1
}
ClassMethod OnPage() As %Status
{
if $d(%request.Data("include")){
s includeClassName=%request.Get("include","")
if $e(includeClassName,$l(includeClassName)-3,$l(includeClassName))=".cls"{
s includeClassName=$e(includeClassName,1,$l(includeClassName)-4)
}
d ..readJSFunctionFromCacheClass(includeClassName)
q $$$OK
}
#define cspEncode(%k,%d) $translate($System.Encryption.AESBase64Encode(%d,%k),"+=/"_$char(32,13,10),"_-$")
#define cspDecode(%k,%d) $System.Encryption.AESBase64Decode($translate(%d,"_-$","+=/"),%k)
; k ^SPOOL($job)
; O 2:($job)
; U 2:($job)
; ; zw head
; zw %request
; c 2:($job)
; USE $ZUTIL(53):(::"M")
if %request.Get("cspIntRunMethod",0)=1 {
s WEVENT=%request.Get("WEVENT","")
s %method=$p(WEVENT,".",$l(WEVENT,"."))
s %class=$e(WEVENT,1,$l(WEVENT)-$l(%method)-1)
if %class="."{
s:$d(%request.CgiEnvs("HTTP_REFERER")) %class= $SYSTEM.CSP.GetClassName(%request.CgiEnvs("HTTP_REFERER"))
}
s WEVENT=$c(1)_WEVENT
s WEVENT= $$$cspEncode(%session.Key,"1"_WEVENT)
d %request.Set("WEVENT",WEVENT)
s %sc=""
s %isNewMethod=1
d ..ExecRunMethod()
Quit $$$OK
}
if ##this="%ZHTML.CacheLib"{
s ParentClassName=""
s:$d(%request.CgiEnvs("HTTP_REFERER")) ParentClassName= $SYSTEM.CSP.GetClassName(%request.CgiEnvs("HTTP_REFERER"))
if ParentClassName'=""{ w "var ParentClassName="""_ParentClassName_".cls"";" }
if $d(%request.CgiEnvs("Referer")),$d(%request.CgiEnvs("Host")){
s ref=$P(%request.CgiEnvs("Referer"),%request.CgiEnvs("Host"),2)
s ParentClassName=$SYSTEM.CSP.GetClassName(ref)
if ParentClassName'="" { w " var ParentClassName="""_ParentClassName_".cls"";"_$c(13,10)
}else{ w " var ParentClassName="""_ref_".cls"";"_$c(13,10) }
}
w " var ThisClassName="""_$ZCVT(##this,"O","URL")_".cls""; " _$c(13,10)
k filtrPrototyp,filtrLib
d $system.OBJ.GetDependencies(##this,.included)
s ClassParentTmp=""
for {
s ClassParentTmp=$o(included(ClassParentTmp))
q:ClassParentTmp=""
continue:$d(filtrLib(ClassParentTmp))
d ..readJSFunctionFromCacheClass(ClassParentTmp)
s filtrLib(ClassParentTmp)=1
}
s ClassParentTmp=""
for {
s ClassParentTmp=$o(included(ClassParentTmp))
q:ClassParentTmp=""
continue:$d(filtrPrototyp(ClassParentTmp))
d ..readJSPrototypeFromCacheClass(ClassParentTmp)
s filtrPrototyp(ClassParentTmp)=1
}
k included
s ParentClassName1="%ZHTML.CacheLib"
s MethodName="InitCacheLib"
for ind=1:1:^oddDEF(ParentClassName1,"m",MethodName,30) {
w ^oddDEF(ParentClassName1,"m",MethodName,30,ind)_$c(13,10)
}
d $system.OBJ.GetDependencies(ParentClassName,.included)
s ClassParentTmp=""
for {
s ClassParentTmp=$o(included(ClassParentTmp))
q:ClassParentTmp=""
continue:$d(filtrPrototyp(ClassParentTmp))
d ..readJSPrototypeFromCacheClass(ClassParentTmp)
s filtrPrototyp(ClassParentTmp)=1
}
s ClassParentTmp=""
for {
s ClassParentTmp=$o(included(ClassParentTmp))
q:ClassParentTmp=""
continue:$d(filtrLib(ClassParentTmp))
d ..readJSFunctionFromCacheClass(ClassParentTmp)
s filtrLib(ClassParentTmp)=1
}
k included
q $$$OK
}
// запуск
if $d(%request.Data("prototyp")){
s ProtopypeClassName=%request.Get("prototyp","")
d ..readJSPrototypeFromCacheClass(ProtopypeClassName)
}
s ParentClassName=""
s ref=""
s:$d(%request.CgiEnvs("HTTP_REFERER")) ParentClassName= $SYSTEM.CSP.GetClassName(%request.CgiEnvs("HTTP_REFERER"))
if ParentClassName'=""{ w "var ParentClassName="""_ParentClassName_".cls"";"_$c(13,10) }
if $d(%request.CgiEnvs("Referer")),$d(%request.CgiEnvs("Host")){
s ref=$P(%request.CgiEnvs("Referer"),%request.CgiEnvs("Host"),2)
s ParentClassName=$SYSTEM.CSP.GetClassName(ref)
if ParentClassName'="" { w " var ParentClassName="""_ParentClassName_".cls"";"_$c(13,10)
}else{ w " var ParentClassName="""_ref_".cls"";"_$c(13,10) }
}
w " var ThisClassName="""_$ZCVT(##this,"O","URL")_".cls""; "_$c(13,10)
/// Пробигаем по родителям и создаем функции от них
if $d(^oddDEF(##this,60)) {
for i=1:1:$l(^oddDEF(##this,60),",") {
s SubClass=$p(^oddDEF(##this,60),",",i)
continue:SubClass="%ZHTML.CacheLib" ; пропускаем основную бублиотеку
d ..readJSFunctionFromCacheClass(SubClass,,0)
}
}
d ..readJSPrototypeFromCacheClass(ParentClassName)
d ..readJSFunctionFromCacheClass(ParentClassName)
d ..readJSFunctionFromCacheClass(##this)
d ..readJSPrototypeFromCacheClass(##this)
Quit $$$OK
}
ClassMethod ExecRunMethod()
{
; Set newList="",setList=""
; #; Get class and method name from event assume if WARGC is not present it is 0
; Set count=$Get(%request.Data("WARGC",1),0)
; if '$d(^oddDEF(%class,"m",%method,42)) {
; Set code="Do ##class("_%class_")."_%method_"("
; } Else {
; Set code="w ##class("_%class_")."_%method_"("
; }
; #; get arguments for method; 'null' values become undefined
; For i=1:1:count {
; If i>1 Set code=code_","
; Set arg="WARG_"_i
; If $Data(%request.Data(arg,1)) {
; Set code=code_"%request.Data("""_arg_""",1)"
; } ElseIf $Data(%request.Data("WLIST"_i,1)) {
; Set var="W"_i
; Set code=code_"."_var
; Set newList=newList_$select(newList="":"new ",1:",")_var
; For j=1:1:%request.Data("WLIST"_i,1) {
; If $Data(%request.Data(var,j)) {
; Set setList=setList_" set "_var_"("_j_")=%request.Data("""_var_""","_j_") "
; }
; }
; }
; }
; Set code=newList_$select(newList="":"",1:" ")_setList_code_")"
; x code
Set count=$Get(%request.Data("WARGC",1),0)
set args=count
s numArg=0
For i=1:1:count {
Set arg="WARG_"_i
If $Data(%request.Data(arg,1)) {
s numArg=numArg+1
set args(numArg) = %request.Data(arg,1)
} ElseIf $Data(%request.Data("WLIST"_i,1)) {
Set var="W"_i
For j=1:1:%request.Data("WLIST"_i,1) {
If $Data(%request.Data(var,j)) {
s numArg=numArg+1
set args(numArg) = %request.Data(var,j)
}
}
}
}
if '$d(^oddDEF(%class,"m",%method,42)) {
do $classmethod(%class, %method, args...)
} Else {
w $classmethod(%class, %method, args...)
}
}
/// <pre>
///
/// Варианты параметров классов
/// 1) [ Language = cache, WebMethod ]
/// 2) [ Language = javascript, WebMethod ]
///
/// Пример классов , которые будут интерпритированы в JS функции:
/// ClassMethod test2() [ Language = cache, WebMethod ]{ zw }
/// ClientMethod test3() [ Language = javascript, WebMethod ]{ alert('test3()');}
/// Property cspXMLHttp As %String [ ServerOnly = 1 ];
/// Property cspUseGetMethod As %Boolean [ InitialExpression = 0, ServerOnly = 1 ];
/// Property cspMozilla As %Boolean [ InitialExpression = "nill", ServerOnly = 1 ];
///
/// </pre>
ClassMethod readJSFunctionFromCacheClass(ParentClassName = "", MethodName = "", DrawDescript = 1) As %String
{
s onEventFun=",onblur,onerror,onfocus,onload,onresize,onscroll,onbeforeunload,onhashchange,onlanguagechange,onmessage,onoffline,ononline,onpagehide,onpageshow,onpopstate,onrejectionhandled,onstorage,onunhandledrejection,onunload,onabort,oncancel,oncanplay,oncanplaythrough,onchange,onclick,onclose,oncontextmenu,oncuechange,ondblclick,ondrag,ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,oninput,oninvalid,onkeydown,onkeypress,onkeyup,onloadeddata,onloadedmetadata,onloadstart,onmousedown,onmouseenter,onmouseleave,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,onpause,onplay,onplaying,onprogress,onratechange,onreset,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,onsuspend,ontimeupdate,ontoggle,onvolumechange,onwaiting,onauxclick,ongotpointercapture,onlostpointercapture,onpointercancel,onpointerdown,onpointerenter,onpointerleave,onpointermove,onpointerout,onpointerover,onpointerup,onbeforecopy,onbeforecut,onbeforepaste,oncopy,oncut,onpaste,onsearch,onselectstart,onwheel,onwebkitfullscreenchange,onwebkitfullscreenerror"
s ClassOref=##class(%ClassDefinition).%OpenId(ParentClassName)
if ClassOref {
s ConstructMethod=$p(ParentClassName,".",$l(ParentClassName,"."))
s count=ClassOref.Properties.Count()
for i=1:1:count {
s nam=ClassOref.Properties.GetAt(i).Name
continue:'$d(^oddDEF(ParentClassName,"a",nam,57))
continue:^oddDEF(ParentClassName,"a",nam,57)'=1
w " var "_ClassOref.Properties.GetAt(i).Name_" "
if $d(^oddDEF(ParentClassName,"a",nam,31)) {
s val=^oddDEF(ParentClassName,"a",nam,31)
if val="""null""" w "=null;"_$c(13,10) continue
s typ=""
if $d(^oddDEF(ParentClassName,"a",nam,5)) {
s typ=^oddDEF(ParentClassName,"a",nam,5)
if $e(typ,1,1)="%",$l(typ,".")=1 {
s typ=$REPLACE(typ,"%","%Library.")
}
}
if typ="" {
if $l(typ ," ")=1 { w "="_$e(val,2,$l(val)-1)_";"_$c(13,10) continue }
try { x "w "_val }catch(e){ w "="_$e(val,2,$l(val)-1)_";"_$c(13,10) continue }
}
if typ="%Library.Boolean" {
if $e(val,1,1)="""" {
w "="
try { x "w "_val }catch(e){ if +val=1 { w "=true" }else { w "=false" } }
}else {
if val=1 { w "=true" }else { w "=false" }
}
}elseif typ="%Library.Integer" {
if $e(val,1,1)="""" {
w "="
try { x "w "_val }catch(e){ s val=+val w val }
} else {
s val=+val w val
}
}else{
if $e(val,1,1)'="""" {
w "="""
try { x "w "_val }catch(e){ w val }
w """"
} else {
w "="_val
}
}
}
w ";"_$c(13,10)
}
s ConstructMethodIndex=""
s count=ClassOref.Methods.Count()
for i=1:1:count {
if (MethodName=""){
continue:$l(ClassOref.Methods.GetAt(i).Name,"OnPage")'=1
continue:ClassOref.Methods.GetAt(i).Name="OnPreHTTP"
continue:ClassOref.Methods.GetAt(i).Name="OnPostHTTP"
continue:ClassOref.Methods.GetAt(i).Name="getLibOne"
continue:ClassOref.Methods.GetAt(i).Name="GetJSMethodFromClientMethod"
continue:ClassOref.Methods.GetAt(i).Name="readJSFunctionFromCacheClass"
}else{
continue:ClassOref.Methods.GetAt(i).Name'=MethodName
}
/// [ ServerOnly = 1 ]
// continue:'$d(^oddDEF(ParentClassName,"m",ClassOref.Methods.GetAt(i).Name,59))
// continue:^oddDEF(ParentClassName,"m",ClassOref.Methods.GetAt(i).Name,59)'=1
/// [ WebMethod ]
continue:'$d(^oddDEF(ParentClassName,"m",ClassOref.Methods.GetAt(i).Name,51))
continue:^oddDEF(ParentClassName,"m",ClassOref.Methods.GetAt(i).Name,51)'=1
if $ZCVT(ClassOref.Methods.GetAt(i).Name,"L")=$ZCVT(ConstructMethod,"L"){
s ConstructMethodIndex=i
continue
}
if DrawDescript=1 {
if $l(ClassOref.Methods.GetAt(i).Description)>0,ParentClassName'=##this{
w !,"/*",!
w $replace(ClassOref.Methods.GetAt(i).Description,"*/","-/-")
w !,"*/"
}
}
// Получаем JS представление Cache клиент метода
if ClassOref.Methods.GetAt(i).Language="javascript" {
w !,"var "_ClassOref.Methods.GetAt(i).Name_"=function("
s param=ClassOref.Methods.GetAt(i).FormalSpec
for ind=1:1:$l(param,","){
s subParam=$p(param,",",ind)
s subParam=$p(subParam,":",1)
s subParam=$p(subParam,"=",1)
w:ind'=1 ","
w subParam
}
w "){",!
d ..ExecFrag(ClassOref.Methods.GetAt(i).Code,"/*(",")*/")
// w ClassOref.Methods.GetAt(i).Code
w !,"};"
}
// Получаем JS представление Cache класс метода
if ClassOref.Methods.GetAt(i).Language="cache" {
w !,"var "_ClassOref.Methods.GetAt(i).Name_"=function(){",!
; if $d(^oddDEF(ParentClassName,"m",ClassOref.Methods.GetAt(i).Name,42)){ w "return "}
w " return runMethod('"_ParentClassName_"."_ClassOref.Methods.GetAt(i).Name_"',arguments);"
w !,"};"
}
}
// После отрисовки функций, создаем конструктор( если конечно он встретился ранее)
if ConstructMethodIndex'="" {
s i=ConstructMethodIndex
if ClassOref.Methods.GetAt(i).Language="javascript" {
d ..ExecFrag(ClassOref.Methods.GetAt(i).Code,"/*(",")*/")
}
if ClassOref.Methods.GetAt(i).Language="cache" {
w " runMethod('"_ParentClassName_"."_ClassOref.Methods.GetAt(i).Name_"',arguments);"
}
}
}
q ""
}
/// Метод создания прототипа JS из Cache класса
ClassMethod readJSPrototypeFromCacheClass(ParentClassName = "") As %String
{
if $l(ParentClassName,":")=1 {
s NamePrototupe=""
}else{
s NamePrototupe=$p(ParentClassName,":",2)
s ParentClassName=$p(ParentClassName,":",1)
}
if ParentClassName = "" s ParentClassName=##this
s onEventFun=",onblur,onerror,onfocus,onload,onresize,onscroll,onbeforeunload,onhashchange,onlanguagechange,onmessage,onoffline,ononline,onpagehide,onpageshow,onpopstate,onrejectionhandled,onstorage,onunhandledrejection,onunload,onabort,oncancel,oncanplay,oncanplaythrough,onchange,onclick,onclose,oncontextmenu,oncuechange,ondblclick,ondrag,ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,oninput,oninvalid,onkeydown,onkeypress,onkeyup,onloadeddata,onloadedmetadata,onloadstart,onmousedown,onmouseenter,onmouseleave,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,onpause,onplay,onplaying,onprogress,onratechange,onreset,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,onsuspend,ontimeupdate,ontoggle,onvolumechange,onwaiting,onauxclick,ongotpointercapture,onlostpointercapture,onpointercancel,onpointerdown,onpointerenter,onpointerleave,onpointermove,onpointerout,onpointerover,onpointerup,onbeforecopy,onbeforecut,onbeforepaste,oncopy,oncut,onpaste,onsearch,onselectstart,onwheel,onwebkitfullscreenchange,onwebkitfullscreenerror"
if $d(^oddDEF(ParentClassName)) {
/// проверяем есть-ли объекты для добавления в JS прототипы
/// если нет, тогда выходим из обработчика
s isAddPrototype=0
s MethodName=""
for {
s MethodName=$o(^oddDEF(ParentClassName,"m",MethodName))
q:MethodName=""
if $d(^oddDEF(ParentClassName,"m",MethodName,14)) {
s isAddPrototype=1
}
}
q:isAddPrototype=0 ""
///-------------------------------------------------------------------
/// Если в классе существует тэг "tagName" тогда обрабатывваем класс как HTML компонент
if $d(^oddDEF(ParentClassName,"p","tagName")){
s NamePrototupe=..readJSPrototypeHTMLComponentFromCacheClass(ParentClassName)
q NamePrototupe
}
/// -----------------------------------------------------------------------------------
/// Создаем протатипы родителей
if $d(^oddDEF(ParentClassName,60)){
s SupperClassList=^oddDEF(ParentClassName,60)
k filtrSupperClass
for ind=1:1:$l(SupperClassList,","){
s SupperClass=$p(SupperClassList,",",ind)
continue:$l(SupperClass,"%ZHTML.CacheLib")=2
; continue:$l(SupperClass,"%")=2
if '$d(filtrSupperClass(SupperClass)) {
s filtrSupperClass(SupperClass)=1
s SupperClassNamePrototype=..readJSPrototypeFromCacheClass(SupperClass)
if $l(SupperClassNamePrototype)>0 s SupperClassNamePrototypeList(SupperClassNamePrototype)=SupperClass
}
}
}
/// Получаем список родительских классов
if NamePrototupe = "" {
if $d(^oddDEF(ParentClassName,"p","ClassName",22)){
s NamePrototupe=^oddDEF(ParentClassName,"p","ClassName",22)
}else{
s NamePrototupe=$p(ParentClassName,".",$l(ParentClassName,"."))
}
}
///-------------------------------------------------------------------
/// Добавляем описание класса
; if $d(^oddDEF(ParentClassName,4)){
; w !,"/* Class:"_ParentClassName_" "
; s Description=^oddDEF(ParentClassName,4)
; s Description=$replace(Description,$c(13,10),$c(10))
; s Description=$replace(Description,"*/","-/")
; s Description=$replace(Description,"/*","/-")
; w !,Description,!
; w "*/"
; }
///-------------------------------------------------------------------
///-------------------------------------------------------------------
/// Поиск конструктора(входящие аргументы)
s isFoundConstructor=0
s MethodName=""
for {
s MethodName=$o(^oddDEF(ParentClassName,"m",MethodName))
q:MethodName=""
if NamePrototupe=MethodName {
if $d(^oddDEF(ParentClassName,"m",MethodName,70)) {
w " var "_NamePrototupe_" = function("
if $d(^oddDEF(ParentClassName,"m",MethodName,27)){ ; входные агргументы
s Args=^oddDEF(ParentClassName,"m",MethodName,27)
for ind=1:1:$l(Args,","){
s arg=$p(Args,",",ind)
s arg=$p(arg,":",1)
s arg=$p(arg,"=",1)
w:ind'=1 ","
w arg
}
}
w "){",!
}
s isFoundConstructor=1
}
}
w:isFoundConstructor=0 !," var "_NamePrototupe_" = function() { "
k isFoundConstructor
///-------------------------------------------------------------------
///-------------------------------------------------------------------
/// Наследуем свойства суперклассов (прототипов)
s ind=""
for {
s ind =$o(SupperClassNamePrototypeList(ind))
q:ind=""
w !," "_ind_".call(this);"
}
w !," var self=this; "
///-------------------------------------------------------------------
/// Если в параметре есть название "prototype" тогда указываем его как родителя
if $d(^oddDEF(ParentClassName,"p","prototype",22)){
w !," "_^oddDEF(ParentClassName,"p","prototype",22)_".call(this);"
}
///---------------------------------------------------------------
///-------------------------------------------------------------------
/// Добавляем поля класса как JS переменные
s PoleName=""
for {
s PoleName=$o(^oddDEF(ParentClassName,"a",PoleName))
q:PoleName=""
continue:PoleName="prototype"
continue:'$d(^oddDEF(ParentClassName,"a",PoleName,14))
s value=""
if $d(^oddDEF(ParentClassName,"a",PoleName,31)){
s value=^oddDEF(ParentClassName,"a",PoleName,31)
}else{
k value
}
; ^oddDEF(ParentClassName,"a",PoleName,35)=1 ; - private
if $d(^oddDEF(ParentClassName,"a",PoleName,35)){
w !," var "_PoleName_""
}else{
w !," this."_PoleName_""
}
if $d(value){
w "="_value_""
}else{
w "=null"
}
w ";"
}
///-------------------------------------------------------------------
///-------------------------------------------------------------------
/// добавляем методы класса
s MethodName=""
for {
s MethodName=$o(^oddDEF(ParentClassName,"m",MethodName))
q:MethodName=""
continue:'$d(^oddDEF(ParentClassName,"m",MethodName,14)) ; Internal
; continue:'$d(^oddDEF(ParentClassName,"m",MethodName,32)) ; Language = javascript
; continue:'$d(^oddDEF(ParentClassName,"m",MethodName,70)) ; ClientMethod
; if ^oddDEF(ParentClassName,"m",MethodName,32)="javascript" {
if $d(^oddDEF(ParentClassName,"m",MethodName,70)) {
if NamePrototupe'=MethodName {
// private поле
if $d(^oddDEF(ParentClassName,"m",MethodName,39)){
w !," var "_MethodName_"=function("
}else{
w !," this."_MethodName_"=function("
}
if $d(^oddDEF(ParentClassName,"m",MethodName,27)){ ; входные агргументы
s Args=^oddDEF(ParentClassName,"m",MethodName,27)
for ind=1:1:$l(Args,","){
s arg=$p(Args,",",ind)
s arg=$p(arg,":",1)
s arg=$p(arg,"=",1)
w:ind'=1 ","
w arg
}
}
w ")",!
w " {"
}
if $d(^oddDEF(ParentClassName,"m",MethodName,30)){
for ind=1:1:^oddDEF(ParentClassName,"m",MethodName,30){
if $d(^oddDEF(ParentClassName,"m",MethodName,30,ind)){
w !,^oddDEF(ParentClassName,"m",MethodName,30,ind)
}
}
}
w:NamePrototupe'=MethodName !," }"
}else{
; if ^oddDEF(ParentClassName,"m",MethodName,32)="cache" {
if NamePrototupe'=MethodName {
// private метод
if $d(^oddDEF(ParentClassName,"m",MethodName,39)){
w !," var "_MethodName_"=function(){",!
}else{
w !," this."_MethodName_"=function(){",!
}
; if $d(^oddDEF(ParentClassName,"m",MethodName,42)){
; w " return runMethod('"_ParentClassName_"."_MethodName_"',arguments);"
; }else{
; w " runMethod('"_ParentClassName_"."_MethodName_"',arguments);"
; }
w " return runMethod('"_ParentClassName_"."_MethodName_"',arguments);"
w !," };"
}else{
w " runMethod('"_ParentClassName_"."_MethodName_"',arguments);"
}
}
}
///-------------------------------------------------------------------
w !," }"
}
q NamePrototupe
}
/// Метод создания прототипа JS HTML компотнента из Cache класса
ClassMethod readJSPrototypeHTMLComponentFromCacheClass(ParentClassName = "") As %String
{
if $l(ParentClassName,":")=1 {
s NamePrototupe=""
}else{
s NamePrototupe=$p(ParentClassName,":",2)
s ParentClassName=$p(ParentClassName,":",1)
}
if ParentClassName = "" s ParentClassName=##this
s onEventFun=",onblur,onerror,onfocus,onload,onresize,onscroll,onbeforeunload,onhashchange,onlanguagechange,onmessage,onoffline,ononline,onpagehide,onpageshow,onpopstate,onrejectionhandled,onstorage,onunhandledrejection,onunload,onabort,oncancel,oncanplay,oncanplaythrough,onchange,onclick,onclose,oncontextmenu,oncuechange,ondblclick,ondrag,ondragend,ondragenter,ondragleave,ondragover,ondragstart,ondrop,ondurationchange,onemptied,onended,oninput,oninvalid,onkeydown,onkeypress,onkeyup,onloadeddata,onloadedmetadata,onloadstart,onmousedown,onmouseenter,onmouseleave,onmousemove,onmouseout,onmouseover,onmouseup,onmousewheel,onpause,onplay,onplaying,onprogress,onratechange,onreset,onseeked,onseeking,onselect,onshow,onstalled,onsubmit,onsuspend,ontimeupdate,ontoggle,onvolumechange,onwaiting,onauxclick,ongotpointercapture,onlostpointercapture,onpointercancel,onpointerdown,onpointerenter,onpointerleave,onpointermove,onpointerout,onpointerover,onpointerup,onbeforecopy,onbeforecut,onbeforepaste,oncopy,oncut,onpaste,onsearch,onselectstart,onwheel,onwebkitfullscreenchange,onwebkitfullscreenerror"
// s ClassOref=##class(%ClassDefinition).%OpenId(ParentClassName)
// if ClassOref {
if $d(^oddDEF(ParentClassName)) {
/// проверяем есть-ли объекты для добавления в JS прототипы
/// если нет, тогда выходим из обработчика
s isAddPrototype=0
s MethodName=""
for {
s MethodName=$o(^oddDEF(ParentClassName,"m",MethodName))
q:MethodName=""
if $d(^oddDEF(ParentClassName,"m",MethodName,14)) {
s isAddPrototype=1
}
}
q:isAddPrototype=0 ""
///-------------------------------------------------------------------
/// Создаем протатипы родителей
if $d(^oddDEF(ParentClassName,60)){
s SupperClassList=^oddDEF(ParentClassName,60)
for ind=1:1:$l(SupperClassList,","){
s SupperClass=$p(SupperClassList,",",ind)
continue:$l(SupperClass,"%")=2
s SupperClassNamePrototype=..readJSPrototypeFromCacheClass(SupperClass)
if $l(SupperClassNamePrototype)>0 s SupperClassNamePrototypeList(SupperClassNamePrototype)=SupperClass
}
}
/// Получаем список родительских классов
if NamePrototupe = "" {
if $d(^oddDEF(ParentClassName,"p","ClassName",22)){
s NamePrototupe=^oddDEF(ParentClassName,"p","ClassName",22)
}else{
s NamePrototupe=$p(ParentClassName,".",$l(ParentClassName,"."))
}
}
/// Если в параметре есть название "prototype" тогда указываем его как родителя
s ParamName=""
s isFoundsetTimeOut=1000
s isFoundParam=0
for {
s ParamName=$o(^oddDEF(ParentClassName,"p",ParamName))
q:ParamName=""
if $d(^oddDEF(ParentClassName,"p","prototype",22)){
w !," var "_NamePrototupe_"=Object.create(HTML"_^oddDEF(ParentClassName,"p","prototype",22)_"Element.prototype); "
s isFoundParam=1
}
}
if isFoundParam=0 {
w " var elementPrototype = typeof HTMLElement !== 'undefined' ? HTMLElement.prototype : Element.prototype; " _$c(13,10)
w " var "_NamePrototupe_"=Object.create(elementPrototype); "
}
///---------------------------------------------------------------
/// поиск метода loop и параметра loopInterval
/// setInterval(this.tick.bind(this), 1000);
s TextLoopFunction=""
s MethodName=""
for {
s MethodName=$o(^oddDEF(ParentClassName,"m",MethodName))
q:MethodName=""
if "setinterval"=$ZCVT(MethodName,"L") {
s ParamName=""
s isFoundsetTimeOut=1000
for {
s ParamName=$o(^oddDEF(ParentClassName,"p",ParamName))
q:ParamName=""
if $zcvt(ParamName,"L")="setinterval",$d(^oddDEF(ParentClassName,"p",ParamName,22)) {
s isFoundsetTimeOut=^oddDEF(ParentClassName,"p",ParamName,22)
q
}
}
s TextLoopFunction=TextLoopFunction_$c(10)_" setInterval("_NamePrototupe_"."_MethodName_".bind(this), "_isFoundsetTimeOut_"); "
}
if "settimeout"=$ZCVT(MethodName,"L") {
s TextLoopFunction=TextLoopFunction_$c(10)_" setTimeout( "_NamePrototupe_"."_MethodName_".bind(this)"
s ParamName=""
s isFoundsetTimeOut=1000
for {
s ParamName=$o(^oddDEF(ParentClassName,"p",ParamName))
q:ParamName=""
if $zcvt(ParamName,"L")="settimeout",$d(^oddDEF(ParentClassName,"p",ParamName,22)) {
s isFoundsetTimeOut=^oddDEF(ParentClassName,"p",ParamName,22)
q
}
}
s TextLoopFunction=TextLoopFunction_$c(10)_" ,"_isFoundsetTimeOut_"); "
}
}
///-------------------------------------------------------------------
/// Поиск конструктора
s isFoundConstructor=0
s MethodName=""
for {
s MethodName=$o(^oddDEF(ParentClassName,"m",MethodName))