-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanax.js
1967 lines (1803 loc) · 107 KB
/
panax.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
/* microsoft sign-in */
const msalConfig = {
auth: {
clientId: (window.document.querySelector(`meta[name="microsoft-signin-client_id"]`) || window.document.createElement("p")).getAttribute("content"),
redirectUri: location.origin
}
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
const login_function = () => {
msalInstance.loginPopup({ scopes: ["User.Read"] }).then(response => {
onMicrosoftLogin(response)
console.log('User logged in:', response);
}).catch(error => {
// Handle login error
console.error('Login error:', error);
});
}
onMicrosoftLogin = function (response) {
if (response.accessToken && xo.session.id_token != response.accessToken) {
xo.session.user_login = response.account.username;
xo.session.id_token = response.accessToken;
document.forms[0].username.value = response.account.username;
xo.session.login(xo.session.user_login, response.accessToken).then(() => {
document.forms[0].submit()
}).catch(() => {
xo.session.id_token = undefined;
})
}
}
/* google sign-in */
onGoogleLogin = function (response) {
const responsePayload = xover.cryptography.decodeJwt(response.credential);
let username = document.querySelector('.form-signin #username');
username = (xover.session.debug && username && !username.disabled && username.value || responsePayload.email);
xover.session.user_login = username;
xover.session.id_token = response.credential;
xover.session.login(xover.session.user_login, response.credential).then(() => {
if (xo.site.seed == '#login') { window.location = '#' } else { xover.stores.seed.render() }
}).catch((e) => {
xover.session.id_token = undefined;
return Promise.reject(e);
})
}
xover.listener.on('beforeRender::#login', function () {
if (xo.session.status != 'authorizing') {
[...document.querySelectorAll(`script[src*="accounts.google.com"]`)].remove()
}
})
xover.listener.on('logout', function () {
delete xover.session.id_token
})
px = {}
//px.configurations = {};
//px.configurations.nodes = new Map();
//Object.defineProperty(px.configurations, 'add', {
// value: function (node, action, config = {}) {
// px.configurations.nodes.set(node, px.configurations.nodes.get(node) || new Map());
// px.configurations.nodes.get(node).set(config.mode || '', action);
// ...
// }, writable: true, configurable: true
//})
xover.qrl = xover.QUERI;
xover.QRL = xover.QUERI;
/* Binding */
//xover.spaces["source"] = "http://panax.io/source"
xover.spaces["binding"] = "http://panax.io/xover/binding"
xover.spaces["changed"] = "http://panax.io/xover/binding/changed"
xover.spaces["source_text"] = "http://panax.io/source/request/text"
xover.spaces["source_prefix"] = "http://panax.io/source/request/prefix"
xover.spaces["source_value"] = "http://panax.io/source/request/value"
xover.spaces["source_filters"] = "http://panax.io/source/request/filters"
xover.spaces["source_fields"] = "http://panax.io/source/request/fields"
/* Values */
xover.spaces["exception"] = "http://panax.io/state/exception"
xover.spaces["confirmation"] = "http://panax.io/state/confirmation"
xover.spaces["readonly"] = "http://panax.io/state/readonly"
xover.spaces["suggested"] = "http://panax.io/state/suggested"
xover.spaces["initial"] = "http://panax.io/state/initial"
xover.spaces["search"] = "http://panax.io/state/search"
xover.spaces["filter"] = "http://panax.io/state/filter"
xover.spaces["prev"] = "http://panax.io/state/previous"
xover.spaces["sort"] = "http://panax.io/state/sort"
xover.spaces["fixed"] = "http://panax.io/state/fixed"
xover.spaces["draft"] = "http://panax.io/state/draft"
xover.spaces["text"] = "http://panax.io/state/text"
xover.spaces["context"] = "http://panax.io/context"
xover.spaces["width"] = "http://panax.io/state/width"
xover.spaces["height"] = "http://panax.io/state/height"
xo.spaces["px"] = "http://panax.io/entity";
xo.spaces["data"] = "http://panax.io/source";
xover.listener.on('ErrorEvent', function () {
let args = { message: event.message, filename: event.filename, lineno: event.lineno, colno: event.colno };
xover.dom.alert(args);
event.stopPropagation();
})
xo.listener.on(`fetch?path=server/&document`, function () {
for (let stylesheet of this.stylesheets) {
if (stylesheet.href[0] !== '/') {
stylesheet.href = '/' + stylesheet.href
}
}
})
Object.defineProperty(xo.session, 'login', {
value: async function (username, password, connection_id = window.location.hostname) {
try {
let _username = (username.value || username).trimEnd()
let _password = (password.value || password).trimEnd()
xover.session.user_login = _username
xover.session.status = 'authorizing';
let response = await xover.server.login(new URLSearchParams({ 'connection_id': connection_id }), { headers: { authorization: `Basic ${btoa(_username + ':' + _password)}` } });
xover.session.status = 'authorized';
if (xover.site.seed === '#login') {
xover.site.seed = '#';
} else {
xover.stores.active.render();
}
} catch (e) {
xover.session.status = 'unauthorized';
Promise.reject(e);
}
}, writable: true, configurable: true
})
Object.defineProperty(xo.session, 'logout', {
value: async function () {
try {
let response = await xover.server.logout();
let positions = -xo.site.position + 1;
//if (positions) {
// history.go(positions);
//}
for (store in xo.stores) {
xo.stores[store].remove()
}
xover.session.status = 'unauthorized';
} catch (e) {
Promise.reject(e);
}
}, writable: true, configurable: true
})
xo.listener.on(['beforeRender::#shell.xslt', 'beforeAppendTo::html:main', 'beforeAppendTo::html:body'], function ({ target }) {
if (!(event.detail.args || []).filter(el => !(el instanceof Comment || el instanceof HTMLStyleElement || el instanceof HTMLScriptElement || el.matches("dialog,.modal-backdrop,[role=alertdialog],[role=alert],[role=dialog],[role=status],[role=progressbar]"))).length) return;
[...target.childNodes].filter(el => el.matches && !el.matches(`script,dialog,[role=alertdialog],[role=alert],[role=dialog],[role=status],[role=progressbar]`)).removeAll()
})
xo.listener.on([`beforeRemove::html:div[@role='alertdialog'][contains(*/@class,'modal')]`], function () {
let removed_from = this;
let store = removed_from.getAttribute("xo-source");
if (store && store in xover.stores) {
delete xover.stores[store];
}
let scope = this.scope;
scope instanceof Attr && scope.remove()
})
//xo.listener.on(['focus::input'], function () {
// this.select();
//})
xo.listener.on(['transform::*[//button[not(@type)]]'], function () {
this.selectNodes("//button[not(@type)]").forEach(el => el.set("type", "button")) //default behavior
})
xo.listener.on(['render::#px-Entity.xslt'], function ({ node, old }) {
let current_step = (node.querySelector(".wizard li.active") || document.createElement("p")).getAttribute("data-position")
let old_step = (old.querySelector(".wizard li.active") || document.createElement("p")).getAttribute("data-position");
if (current_step && old_step != current_step) {
node.closest('main').scrollTo(0, 0)
}
node.querySelectorAll(`.association-ref`).toArray().map(ref => ref.scope).filter(scope => scope).forEach(scope => scope.dispatch("downloadCatalog"))
})
xo.listener.on(['removeFrom::data:rows'], function ({ }) {
if (!this.select("*").length) {
this.setAttribute("xsi:nil", true)
}
})
xo.listener.on([`set::xo:r[@state:new="true"]/@state:checked[.="false"]`, `remove::xo:r[@state:new="true"]/@state:checked`], function () {
this.parentNode.remove();
})
xo.listener.on([`set::px:Association[@DataType='junctionTable']/px:Entity/px:Record/px:Association[@Name=../../*[local-name()='layout']/association:ref/@Name]/px:Entity/data:rows/xo:r/@state:checked`], function ({ element }) {
let association_ref = element.selectFirst(`ancestor::px:Association[1]`);
let target = association_ref.selectFirst(`ancestor::px:Entity[1]/data:rows`);
let referencers = association_ref.select('px:Mappings/px:Mapping/@Referencer').map(referencer => [referencer.value, referencer.parentNode.getAttribute("Referencee")]);
let node = xo.xml.createNode(`<xo:r xmlns:xo="http://panax.io/xover" xmlns:state="http://panax.io/state" state:checked="true" state:new="true" state:dirty="true" ${target.select(`../px:Record/*/@Name`).map(attr => `${attr.matches("px:Association/@Name") ? 'meta:' : ''}${attr.value}=""`).join(" ")}/>`).seed();
for (let [referencer, referencee] of referencers) {
node.setAttribute(referencer, element.getAttribute(referencee))
node.srcElement = element;
}
node.setAttribute(`meta:${association_ref.getAttribute("Name")}`, element.getAttribute("meta:text"), { silent: true });
target && target.append(node);
event.preventDefault();
})
xo.listener.on(['change::px:Association[@DataType="junctionTable"]/px:Entity/data:rows/xo:r[(@meta:id!="")]/@state:checked[.="false"]', 'remove::px:Association[@DataType="junctionTable"]/px:Entity/data:rows/xo:r[(@meta:id!="")]/@state:checked'], function ({ element }) {
element.set("state:delete", "true");
})
xo.listener.on(['change::@meta:pageIndex', 'change::@meta:pageSize', 'downloadCatalog::data:rows'], function ({ element, value }) {
let command = element.get(`command`);
if (command) {
command = xo.QUERI(command)
this instanceof Attr && command.headers.set(this.localName, value);
}
command.update()
})
/*xo.listener.on(['change::@meta:*[.=""]'], function ({ element: row }) { //disabled
let association = this.schema;
if (!association) return;
for (let mapping of association.select("px:Mappings/px:Mapping/@Referencer")) {
row.set(mapping.value, "");
}
})*/
xo.listener.on(['beforeTransform::px:Entity'], function () {
let node = this;
for (let association_ref of node.select(`//px:Association[@DataType='junctionTable']/px:Entity/px:Record/px:Association[@Name=../../*[local-name()='layout']/association:ref/@Name][px:Entity/data:rows/xo:r]`)) {
let selected_options = association_ref.select(`ancestor::px:Association[1]/px:Entity/data:rows/xo:r`);
if (!selected_options.length) continue;
let referencers = association_ref.select('px:Mappings/px:Mapping/@Referencer').map(referencer => [referencer.value, referencer.parentNode.getAttribute("Referencee")]);
if (!referencers.length) return;
for (let row of association_ref.select(`px:Entity/data:rows/xo:r`)) {
let match = selected_options.find(selected_row => referencers.every(([referencer, referencee]) => selected_row.getAttribute(referencer) == row.getAttribute(referencee)));
if (match) {
match.disconnect();
match.setAttribute("meta:position", row.getAttribute("meta:position"));
row.remove({ silent: true });
}
}
}
for (let association_ref of node.select(`//px:Entity/px:Record/px:Association[@Type="belongsTo"][px:Mappings/px:Mapping[not(@Referencee=ancestor::px:Entity[1]/@IdentityKey)][2]]`)) {
if (!xo.site.sections[event.detail.stylesheet.href].find(section => section.querySelector(`[xo-slot="meta:${association_ref.getAttribute("Name")}"]`))) continue;
let referencers = association_ref.select('px:Association[px:Entity/@IdentityKey]/px:Mappings/px:Mapping[not(@Referencee=ancestor::px:Association[1]/px:Entity/@IdentityKey)]/@Referencer').concat(association_ref.select(`self::px:Association[not(px:Entity/@IdentityKey)]/px:Mappings/px:Mapping[not(position()=last())]/@Referencer`)).map(referencer => [referencer.value, referencer.parentNode.getAttribute("Referencee")]);
if (!referencers.length) continue;
referencers = Object.fromEntries(referencers);
let row = Object.fromEntries(association_ref.select(`ancestor::px:Entity[1]/data:rows/xo:r/@*`).filter(attr => Object.keys(referencers).includes(attr.name)).map(attr => [attr.name, attr.value]));
let data_rows = association_ref.selectFirst(`px:Entity/data:rows`);
let rows = data_rows && data_rows.select(`xo:r`).filter(_row => ![...Object.entries(referencers)].every(([referencer, referencee]) => !row[referencer] || row[referencer] === _row.getAttribute(referencee))) || [];
if (rows.length) {
rows.removeAll({ silent: true });
if (!data_rows.select("xo:r").length) {
data_rows.setAttribute("xsi:nil", true);
//row.map(attr => store.find(attr.parentNode).getAttributeNode(`meta:${association_ref.getAttribute("AssociationName")}`)).filter(el => el.value).forEach(attr => attr.set(""));
}
}
}
})
xo.listener.on(`change::xo:r/@*[not(contains(namespace-uri(),'http://panax.io/state') or contains(namespace-uri(),'http://panax.io/metadata'))]`, function ({ element: row, attribute, old, value }) {
row.select(`@xsi:type[.="mock"]`).remove();
let initial_value = row.getAttributeNodeNS('http://panax.io/state/initial', attribute.nodeName.replace(':', '-'));
if (!initial_value) {
row.set(`initial:${attribute.nodeName.replace(':', '-')}`, old);
} else if (value == initial_value.value) {
initial_value.remove();
}
row.set(`prev:${attribute.nodeName.replace(':', '-')}`, old);
let initial_attributes = row.select(".//@initial:*");
if (initial_attributes.some(el => el.value != el.parentNode.getAttribute(el.localName))) {
row.set(`state:dirty`, 1);
} else {
row.removeAttribute(`state:dirty`)
}
})
xo.listener.on([`blur::input[xo-slot^=draft]`], function () {
let scope = this.scope;
if (!document.querySelector(`input[xo-slot="${scope.localName}"]`)) {
xo.delay(300).then(() => document.querySelectorAll(`input[xo-slot="${scope.localName}"]`).forEach(el => el.focus()));
}
})
xo.listener.on([`input::input[xo-slot^=draft]`], function () {
let scope = this.scope;
let row = scope && scope.selectFirst(`ancestor-or-self::xo:r[1]`);
if (!row) return;
//let draft_value = row.getAttributeNodeOrMock(`draft:${scope.localName}`);
////if (['deleteContentBackward'].includes(event.inputType)) draft_value.remove();
//let real_value = row.getAttributeNode(scope.localName);
//let initial_value = row.getAttributeNode(`initial:${scope.localName}`);
//if (initial_value && real_value.value !== initial_value.value) {
// real_value.set(initial_value.value, { silent: true })
//}
document.querySelectorAll(`input[xo-slot="${scope.localName}"]`).forEach(el => el.value = "");
//if (event.data != undefined && this.value.length <= 1) {
// //!draft_value.ownerElement && draft_value.set(this.value)
// xo.delay(300).then(() => {
// let draft_input = document.querySelector(`input[xo-slot^="${scope.name}"]`)
// draft_input.selectionStart = draft_input.value.length;
// draft_input.selectionEnd = draft_input.value.length;
// draft_input && draft_input.focus();
// })
//}
})
xo.listener.on([`change::xo:r/@draft:*`, `set::xo:r/@*[not(namespace-uri()) and local-name()=local-name(../@draft:*)]`], function ({ element: row, attribute, old = '', value = '' }) {
//if (!value || this.namespaceURI && row.getAttribute(`initial:${this.localName}`) == null) return;
let draft = row.getAttributeNode(`draft:${this.localName}`);
let draft_value = draft && draft.value || null;
//value = value.length == 32 ? value : xover.cryptography.encodeMD5(value);
//old = old.length == 32 ? old : xover.cryptography.encodeMD5(old);
//draft_value = draft_value.length == 32 ? draft_value : xover.cryptography.encodeMD5(draft_value);
let real_value = row.getAttributeNode(this.localName);
if (real_value == this && old != value) {
draft.remove();
if (draft_value != value) {
real_value.set(row.getAttribute(`initial:${this.localName}`) || real_value);
event.preventDefault();
return Promise.reject("No coincide el valor")
}
}
return value;
})
xo.listener.on([`set::xo:r[@fixed:*]/@*[not(namespace-uri())]`], function ({ element: row, attribute, value }) {
value = row.get(`fixed:${this.name}`) || value;
return value
})
xo.listener.on([`change::xo:r/@draft:*`], function ({ value = '' }) {
if (!value) {
let row = this.parentNode;
this.remove()
let real_value = row.getAttributeNode(this.localName);
real_value.set(row.getAttribute(`initial:${this.localName}`) || real_value)
}
})
//xover.listener.on(['focusin::input', 'focusin::textarea'], function () {
// let scope = this.scope;
// this.value = (scope && scope.value || this.value)
//})
xo.listener.on([`set::xo:r/@*[not(namespace-uri()) or contains(namespace-uri(),'http://panax.io/state/draft')][local-name()='Password']`], function ({ value = '' }) {
if (event.srcElement !== document.activeElement && value) {
value = value.length == 32 ? value : xover.cryptography.encodeMD5(value);
}
return value;
})
//xo.listener.on(`change::xo:r/@meta:*`, function ({ node, element, attribute, old, value }) {
// let referencers = element.$$(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName="${node.localName}"]/px:Mappings/px:Mapping/@Referencer`);
// let options = element.select(`ancestor-or-self::px:Entity[1]/px:Record/px:Association[@Type="belongsTo"][@AssociationName="${node.localName}"]/px:Entity/data:rows/xo:r`);
// let matches = options.filter(option => referencers.every(referencer => selected_record.getAttribute(referencer.value) == option.getAttribute(referencer.ownerElement.getAttribute("Referencee"))));
// console.log("here!")
//})
//xo.listener.on(`beforeChange::xo:r/@meta:*`, function ({ node, element, attribute, old, value }) {
// let src_element = event.srcEvent.target;
// if (!src_element instanceof HTMLElement) return;
// let selected_record = src_element instanceof HTMLSelectElement && src_element[src_element.selectedIndex].scope.filter("self::xo:r") || src_element instanceof HTMLLIElement && src_element.scope.filter("self::xo:r") || undefined;
// if (selected_record) {
// this.parentNode.set(`selected:${this.localName}`, selected_record.getAttribute("xo:id"));
// px.selectRecord(selected_record, node);
// if (src_element instanceof HTMLSelectElement) {
// let option = src_element[src_element.selectedIndex]
// this.value = option.value && option.text || "";
// } else if (src_element instanceof HTMLLIElement) {
// let option = src_element;
// this.value = option.textContent;
// }
// }
//})
xo.listener.on(`change::select,input[type=checkbox],input[type=radio]`, function ({ node, element, attribute, old, value }) {
let src_element = this;
if (!src_element instanceof HTMLElement) return;
let scope = src_element.scope;
if (!(scope instanceof Attr)) return;
let selected_option = src_element;
let selected_record = (selected_option.options ? selected_option[selected_option.selectedIndex] : selected_option.closest('.data-row') || document.createElement("p")).scope;
selected_record = selected_record instanceof Node && selected_record.select('ancestor-or-self::xo:r[1]').map(node => node.selectFirst("self::xo:r"))[0] || xover.xml.createNode("<xo:r/>");
//px.selectRecord(selected_record instanceof Element && selected_record || null, scope);
scope.set(selected_record);
})
xo.listener.on(`click::html:li`, function ({ node, element, attribute, old, value }) {
let src_element = this;
if (!src_element instanceof HTMLElement) return;
let scope = (src_element.closest('ul,ol') || {}).scope;
let selected_record = src_element instanceof HTMLLIElement && src_element.scope && src_element.scope.filter("self::xo:r").pop();
if (scope && selected_record instanceof Element && selected_record && !selected_record.parentNode.selectFirst("ancestor::xo:r")) {
src_element.parentNode.scope.dispatch('selectRecord', selected_record);
//px.selectRecord(selected_record, src_element.parentNode.scope);
let option = src_element;
scope.set(option.textContent);
}
})
//xo.listener.on([`selectRecord::@*`, `selectRecord::*`], function ({ args, event }) {
// let target = this;
// let element = target.ownerElement || target;
// let selected_record = args[0];
// if (!element) {
// event.preventDefault();
// event.returnValue = false;
// };
// let referencers = element.$$(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName="${target.localName}"]/px:Mappings/px:Mapping/@Referencer`);
// for (let referencer of referencers) {
// element.set(referencer.value, selected_record instanceof Element && selected_record.getAttribute(referencer.parentNode.getAttribute("Referencee")) || "");
// }
//})
px.getAssociatedRef = function () {
let prev = xo.site.history[0] || {};
let reference = prev.reference || {};
let prev_store = prev.store || '';
let ref_store = prev_store && xo.stores[prev_store];
if (ref_store && prev_store) {
if (ref_store.document.firstChild) {
ref_store.save()
} else {
ref_store.ready;
}
}
ref_node = ref_store && ref_store.findById(reference.id) || null;
return ref_node;
}
xo.listener.on([`set::xo:r/@meta:*`], function ({ value, old, element: row }) {
if (old == value) return value;
value = value || "";
if (!(value instanceof Node && value.matches && value.matches("xo:r|@IsNullable"))) return value;
let scope = this;
let association = row.selectFirst(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName="${scope.localName}"]`);
let referencers = association.select(`px:Mappings/px:Mapping/@Referencer`).map(referencer => [referencer.value, referencer.parentNode.getAttribute("Referencee")]);
let selected_record = value instanceof Node && value.matches("xo:r") ? value : value instanceof Node && value.matches("@IsNullable[.=1]") ? '' : typeof (value) === 'string' && value ? referencers[0].selectFirst(`ancestor::px:Association[1]/px:Entity/data:rows/xo:r[@meta:text="${value}"]`) : null;
//if (selected_record === null) {
// referencers = referencers.filter(referencer => referencer.parentNode.getAttribute("Referencee") == referencer.selectFirst(`ancestor::px:Association[1]/px:Entity/@IdentityKey`));
//}
if (selected_record instanceof Element) {
let attribs = new Map()
if (!selected_record.select("@*").length) {
let filter = association.selectFirst(`px:Entity/data:rows/@state:filter`);
filter && filter.remove();
for (let association of row.select(`ancestor::px:Entity[1]/px:Record/px:Association[@Type='belongsTo']`).sort((node1, node2) => node2.select(`px:Mappings/px:Mapping`).length - node1.select(`px:Mappings/px:Mapping`).length)) {
for (let [referencer] of association.select(`px:Mappings/px:Mapping/@Referencer`).map(referencer => [referencer.value])) {
if (referencers.every(([referencer]) => association.selectFirst(`px:Mappings/px:Mapping/@Referencer[.="${referencer}"]`))) {
attribs.set(referencer, row.get(referencer).cloneNode().set(''))
} else {
attribs.set(referencer, row.get(referencer))
}
}
}
}
for (let [referencer, referencee] of referencers) {
let new_value = row.get(`fixed:${referencer}`) || selected_record.get(referencee) || attribs.get(referencer) || row.get(referencer) || "";
//if (!new_value && row.select(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName!="${scope.localName}"][px:Mappings/px:Mapping/@Referencer="${referencer}"]`).filter(association => !related_associations.includes(association))[0]) continue;
if (row.getAttribute(referencer) != new_value) {
row.set(referencer, new_value.value)
}
}
}
selected_record = selected_record instanceof Node && selected_record.getAttributeNode("meta:text") || selected_record || "";
/*scope.dispatch('selectRecord', selected_record instanceof Node && selected_record.selectFirst(`ancestor-or-self::xo:r[1]`) || null);*/
return selected_record;
})
px.selectRecord = function (selected_record, target) {
let element = target.ownerElement || target;
if (!element) {
event.preventDefault();
event.returnValue = false;
};
let referencers = element.$$(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName="${target.localName}"]/px:Mappings/px:Mapping/@Referencer`);
for (let referencer of referencers) {
element.set(referencer.value, selected_record instanceof Element && selected_record.getAttribute(referencer.parentNode.getAttribute("Referencee")) || "");
}
//let associations = element.$$(`ancestor::px:Entity[1]/px:Record/px:Association[@Type='belongsTo']/px:Mappings/px:Mapping/@Referencer[.="${node.name}"]`);
}
xo.listener.on(`change::xo:r/@*[not(contains(namespace-uri(),'http://panax.io/state')) and not(contains(namespace-uri(),'http://panax.io/metadata')) and not(contains(namespace-uri(),'http://www.w3.org'))]`, async function ({ node, element: row, value, attributes: changes }) {
let field = (node.schema || {});
if (!field) return;
let references = row.select(`ancestor::px:Entity[1]/px:Record/px:Association[@Type='belongsTo'][px:Mappings/px:Mapping/@Referencer="${node.name}"]/px:Mappings/px:Mapping/@Referencer`).distinct(String)
let associations = row.select(`ancestor::px:Entity[1]/px:Record/px:Association[@Type='belongsTo']/px:Mappings/px:Mapping/@Referencer`).filter(referencer => references.includes(referencer.value)).map(referencer => referencer.selectFirst('ancestor::px:Association[1]')).distinct().sort((node1, node2) => node1.select(`px:Mappings/px:Mapping`).length - node2.select(`px:Mappings/px:Mapping`).length)//.reverse();
let attribs = {};
for (let association of associations) {
let meta_attribute_name = `meta:${association.attributes.Name}`;
let data_rows = association.selectFirst(`px:Entity[1]/data:rows`);
if (!data_rows) continue;
let filter = data_rows.getAttribute("state:filter")
let qri = data_rows && xo.QUERI(data_rows.get("command"));
qri.predicate.delete('AND')
let referencers = association.select('px:Mappings/px:Mapping/@Referencer').map(referencer => [referencer.value, referencer.parentNode.getAttribute("Referencee")]);
let options = data_rows && data_rows.select(`xo:r`).filter(_row => referencers.every(([referencer, referencee]) => (row.getAttribute(referencer) /*|| row.getAttribute(`prev:${referencer}`)*/) == _row.get(referencee))) || [];
if (options.length <= 1) {
attribs[meta_attribute_name] = options.length == 1 && options[0].get("meta:text") || "";
for (let [referencer, referencee] of referencers) {
//let field = association.selectFirst(`px:Entity/px:Record/px:Field[@Name="${referencer}"]`);
//if (field && !attribs[meta_attribute_name] && attribs[referencer] instanceof Node) {
// field.setAttribute("state:filter", !options.length && attribs[referencer].value || null, {silent: true})
//}
if (!options.length) {
if (attribs[referencer]) {
if (attribs[referencer].value) {
qri.predicate.set(referencee, attribs[referencer]);
} else {
qri.predicate.delete(referencee);
}
} else {
let attr = row.getAttributeNode(referencer);
if ((changes[attr.namespaceURI] || {}).hasOwnProperty(attr.localName)/*qri.predicate.has(referencer) disabled because it prevents empty value to be selected*/) {
//data_rows.select(`xo:r`).some(_row => row.getAttribute(referencer) == _row.get(referencer))
//qri.predicate.set(referencer, row.getAttribute(referencer))
if (row.getAttribute(referencer)) {
qri.predicate.append('AND', `"@${referencer}"='${row.getAttribute(referencer).replace(/'/g, "''")}'`);
} else {
qri.predicate.delete(referencer);
}
} else if (this.name != referencer) {
if (!qri.predicate.has(referencer)) {//qri.predicate.get(referencer) != row.getAttribute(referencer)) {
attribs[referencer] = row.getAttributeNode(referencer).cloneNode().set('')
}
}
}
}
attribs[referencer] = options.length == 1 ? options[0].get(referencee) : this.name == referencer ? this : attribs[referencer] || row.get(referencer) || "";
}
}
//let dependencies = association.select('self::px:Association[px:Entity/@IdentityKey]/px:Mappings[px:Mapping[2]]/px:Mapping[not(@Referencee=ancestor::px:Association[1]/px:Entity/@IdentityKey)]/@Referencer').concat(association.select(`self::px:Association[not(px:Entity/@IdentityKey)]/px:Mappings[px:Mapping[2]]/px:Mapping[not(position()=last())]/@Referencer`)).map(referencer => [referencer.value, referencer.parentNode.getAttribute("Referencee")]);
//if (!dependencies.length) continue;
//dependencies = Object.fromEntries(dependencies);
//if (qri) {
// //qri.predicate.delete("AND")
// for (let [referencer] of [...Object.entries(dependencies)].filter(([referencer]) => row.getAttribute(referencer))) {
// qri.predicate.set(referencer, row.getAttribute(referencer))
// }
if (!options.length) {
if (filter && !qri.predicate.size) {
qri.predicate.append('AND', `"@meta:text" LIKE '%${filter.replace(/'/g, "''")}%' COLLATE Latin1_General_CI_AI`);
}
qri.update();
}
//}
}
for (let [key, value] of Object.entries(attribs)) {
if (row.getAttribute(key, value) != value) {
row.setAttribute(key, value)
}
}
/*for (let association_ref of row.select(`ancestor::px:Entity[1]/px:Record/px:Association[@Type="belongsTo"][px:Mappings/px:Mapping[not(@Referencee=ancestor::px:Entity[1]/@IdentityKey)][2]]`)) {
let dependencies = association_ref.select('px:Association[px:Entity/@IdentityKey]/px:Mappings/px:Mapping[not(@Referencee=ancestor::px:Association[1]/px:Entity/@IdentityKey)]/@Referencer').concat(association_ref.select(`self::px:Association[not(px:Entity/@IdentityKey)]/px:Mappings/px:Mapping[not(position()=last())]/@Referencer`)).map(referencer => [referencer.value, referencer.parentNode.getAttribute("Referencee")]);
if (!dependencies.length) continue;
dependencies = Object.fromEntries(dependencies);
let row = Object.fromEntries(association_ref.select(`ancestor::px:Entity[1]/data:rows/xo:r/@*`).filter(attr => Object.keys(dependencies).includes(attr.name)).map(attr => [attr.name, attr.value]));
let data_rows = association_ref.selectFirst(`px:Entity/data:rows`);
let rows = data_rows && data_rows.select(`xo:r`).filter(_row => ![...Object.entries(dependencies)].every(([referencer, referencee]) => row[referencer] === _row.getAttribute(referencee))) || [];
if (data_rows) {
let qri = xo.QUERI(data_rows.get("command"));
let predicate = [...Object.entries(dependencies)].filter(([referencer]) => row[referencer]).map(([referencer, referencee]) => ["WHERE", `"${referencee}"='${row[referencer]}'`])
predicate.forEach(([key, value]) => qri.searchParams.append(key, value));
qri.update();
}
}*/
let associated_references = row.$$(`px:Association[contains(@DataType,'Table')]/px:Mappings/px:Mapping/@Referencer[.="${node.name}"]`);
for (let referencer of associated_references) {
let associated_records = referencer.select(`ancestor::px:Entity[1]/data:rows/xo:r/@*[name()="${referencer.value}"]`)
associated_records.forEach(attr => attr.value = value)
}
})
xo.listener.on(`change::px:Entity[px:Record/px:Field/@formula]/data:rows/xo:r/@*[not(contains(namespace-uri(),'http://panax.io/'))]`, function ({ element: row, attribute, old, value }) {
const CONVERT = function (type, ...args) {
if (args.length != 1) return args;
let value = args[0];
let [, base_type, precision, scale] = type.match(/^([^\)]+)(?:\((\d+),(\d+)\))?$/);
if (type.indexOf('(') != -1) {
if (isNumber(value) && scale) {
return value.toFixed(scale)
}
return value
} else {
return value
}
}
const nullif = function (value, assertion) {
if (value == assertion) {
return null
}
return value;
}
const isnull = function (value, failover) {
return value != null && value || failover;
}
const datediff = function (intervalType, first_date, last_date) {
// Parse the input dates
if (!(first_date && last_date)) return undefined;
const first = first_date instanceof Date ? first_date : first_date.parseDate();
const last = last_date instanceof Date ? last_date : last_date.parseDate();
// Calculate the difference in milliseconds
const diffMs = last - first;
// Convert milliseconds to the specified interval type
let diffInterval;
switch (intervalType) {
case 'year':
diffInterval = diffMs / (1000 * 60 * 60 * 24 * 365.25);
break;
case 'month':
diffInterval = diffMs / (1000 * 60 * 60 * 24 * 30.44);
break;
case 'day':
diffInterval = diffMs / (1000 * 60 * 60 * 24);
break;
case 'hour':
diffInterval = diffMs / (1000 * 60 * 60);
break;
case 'minute':
diffInterval = diffMs / (1000 * 60);
break;
case 'second':
diffInterval = diffMs / 1000;
break;
default:
throw new Error('Invalid interval type');
}
// Return the result rounded to 2 decimal places
return Math.floor(Math.round(diffInterval * 100) / 100);
}
const year = 'year';
if (old != value) {
row.$$(`ancestor::px:Entity[1]/px:Record/px:Field/@formula`).map(attr => [attr.parentNode.get("Name"), attr.value.replace(/\[([^\]]+)\](\([^\)]+\))?/g, (field) => {
let ref = attr.parentNode.parentNode.selectFirst(`px:Field[@Name="${field.substring(1, field.length - 1)}"]`);
let formatValue = (value => {
value = value.value || value;
value = !ref && value || (value === null) && String(value) || value !== undefined && (isFinite(value) && value || value[0] != "'" && `'${value || ''}'`) || '';
return value;
});
let value = formatValue(row.getAttribute(field.substring(1, field.length - 1)) || (ref ? (['varchar', 'nvarchar', 'date'].includes(ref.getAttribute("DataType")) ? '' : 0) : `'${field}'`));
return value;
})]).forEach(([key, formula]) => {
try {
let value = eval(formula);
value = isFinite(value) ? value : undefined;
row.set(key.value, [value, ''].coalesce())
} catch (e) {
if (e instanceof ReferenceError) {
Promise.reject(e)
} else {
row.set(key.value, "")
}
}
})
}
})
xo.listener.on('remove::px:Entity//data:rows', function () {
let command = this.get("command")
let previous_parent = this.formerParentNode;
if (!this.formerParentNode.$(`data:rows[@command="${command}"]`) && previous_parent.getAttribute(`@data:rows`) == command) {
let data_rows = xover.xml.createNode(`<data:rows xmlns:data="http://panax.io/source"/>`);
data_rows.seed();
this.formerParentNode.append(data_rows);
data_rows.set("command", command);
}
})
xo.listener.on('render::px:Entity', function () {
this.select(`//*[@data:rows and not(data:rows)]`).forEach(node => node.set("data:rows", node.get("data:rows")))
})
xo.listener.on('set::@data:rows', function ({ value, old: prev }) {
let current = this.parentNode && this.parentNode.$(`data:rows`);
current && current.remove();
if (!this.parentNode.$(`data:rows`)) {
let data_rows = xover.xml.createNode(`<data:rows xmlns:data="http://panax.io/source"/>`).seed();
this.parentNode.append(data_rows);
data_rows.set("command", value);
}
})
xo.listener.on(['append::data:rows[@command][not(xo:r) and not(@xsi:nil)]', 'change::data:rows/@command', 'remove::data:rows[not(xo:r)]/@xsi:nil'], async function ({ value, old: prev }) {
let node = this.selectFirst(`ancestor-or-self::data:rows[1]`);
let targetNode = node
let command = node.get("command");
let headers = new Headers({
"Accept": content_type.xml
})
let response;
try {
//node.context && node.context.controller && node.context.controller.abort();
source = xover.sources.get(command);
//let source = xover.sources[`${node.nodeName}:=${command.value}`];//.cloneNode(true);
node.context = source;
response = await source.fetch();
response.seed();
let firstElementChild = response.cloneNode(true).firstElementChild;
if (firstElementChild) {
targetNode.ownerDocument.disconnect()
firstElementChild.select('@xo:id').remove();
firstElementChild.select('@*').forEach(attr => targetNode.setAttributeNS(attr.namespaceURI, attr.name, attr.value));
targetNode.ownerDocument.connect()
targetNode.replaceChildren(...firstElementChild.childNodes);
} else {
targetNode.replaceChildren()
}
if (!targetNode.firstElementChild) {
targetNode.set("xsi:nil", true);
}
} catch (e) {
if (e instanceof Response && e.status == 499) {
e = ''
}
return Promise.reject(e)
}
})
//xo.listener.on('change::px:Entity/data:rows/@command', function ({ old: prev }) {
// this.parentNode.select('xo:r').removeAll()
// if (!this.parentNode.$('xo:r')) {
// let data_rows = xover.xml.createNode(`<data:rows xmlns:data="http://panax.io/source"/>`);
// data_rows.seed();
// data_rows.set("command", this.value);
// this.parentNode.append(data_rows);
// }
//})
xo.listener.on('appendTo::data:rows', function ({ addedNodes }) {
//let empty_node = node.$('xo:empty')
//if (empty_node) {
// let entity = node.parentElement.$('self::px:Entity[@mode="add"][not(parent::px:Association)]')
// if (entity) {
// let fields = [...new Set(entity.$$('px:Record/px:Field|px:Record/px:Association[@Type="belongsTo"]/px:Mappings/px:Mapping|px:Record/px:Association[@Type="belongsTo"]').map(field => field.$("@Name|@Referencer").value + '=""'))].join(' ')
// empty_node.replace(xo.xml.createNode(`<xo:r xmlns:xo="http://panax.io/xover" ${fields}/>`))
// }
//}
if (this.matches(`/px:Entity/data:rows`) && addedNodes.length == 1) {
let row = addedNodes[0];
let ref_node = px.getAssociatedRef()
let ref_record = ref_node && ref_node.selectFirst(`ancestor::px:Association[1]/parent::xo:r`);
let referencees = ref_node && ref_node.select(`ancestor::px:Association[1][not(@DataType="belongsTo" or @DataType="foreignKey")]/px:Mappings/px:Mapping/@Referencee`).map(referencee => [referencee.value, referencee.parentNode.getAttribute("Referencer")]) || [];
for (let [referencee, referencer] of referencees) {
let current_value = row.getAttribute(referencee);
let new_value = current_value || ref_record && ref_record.getAttribute(referencer);
row.setAttribute(`fixed:${referencee}`, new_value)
if (current_value != new_value) {
row.setAttribute(referencee, new_value)
}
}
}
if (this.$(`self::*[not(xo:r)]/xo:empty`)) {
let entity = this.$(`ancestor::px:Entity[parent::px:Association[@Type="hasOne"]]`);
if (entity) {
this.append(px.createEmptyRow(entity))
}
}
let data_rows = this;
let association = this.selectFirst(`ancestor::px:Association[1][@Type="belongsTo"]`);
if (association) {
let referencers = Object.fromEntries(association.select('px:Mappings/px:Mapping/@Referencer').map(referencer => [referencer.value, referencer.parentNode.getAttribute("Referencee")]));
for (let attr of this.select(`ancestor::px:Entity[2]/data:rows/xo:r/@meta:${association.getAttribute("Name")}`)) {
let row = attr.parentNode;
let options = data_rows && data_rows.select(`xo:r`).filter(_row => [...Object.entries(referencers)].every(([referencer, referencee]) => (row.getAttribute(referencer) || row.getAttribute(`prev:${referencer}`)) == _row.get(referencee))) || [];
if (options.length == 1) {
attr.set(options[0])
}
}
}
if (this.matches('px:Association[@DataType="junctionTable"]/px:Entity/data:rows')) {
/*Remove mock records when there is a persisted record*/
let referencers = (this.select(`parent::px:Entity[parent::px:Association[@DataType="junctionTable"]]/px:Record/px:Association`).filter(fks => {
let pks = fks.select(`ancestor::px:Entity[1]/px:PrimaryKeys/px:PrimaryKey/@Field_Name`).map(pk => pk.value);
return fks.select(`px:Mappings/px:Mapping/@Referencer`).every(referencer => pks.includes(referencer.value))
}).map(association => association.select(`px:Mappings/px:Mapping/@Referencer`).map(referencer => referencer.value))).flat()
let persisted_records = new Map(this.select(`../data:rows/xo:r[@meta:id!='']`).map(row => [JSON.stringify(Object.fromEntries(referencers.map(ref => [ref, row.getAttribute(ref)]))), true]));
this.select(`../data:rows/xo:r[@meta:id='']`).filter(row => persisted_records.get(JSON.stringify(Object.fromEntries(referencers.map(ref => [ref, row.getAttribute(ref)]))))).removeAll();
}
for (let association of this.parentNode.$$(`*[local-name()="layout"]//association:ref`).map(node => node.$(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName="${node.get("Name")}"][not(@Type="belongsTo")]`)).filter(el => el)) {
//let identity_value, primary_values
//association.$$('px:Mappings/px:Mapping').map(mapping => association.get("DataType") == 'belongsTo' && [mapping.get("Referencer"), node.get(mapping.get("Referencer"))] || mapping.get())
if (!["belongsTo"].includes(association.getAttribute("Type"))) {
let target_rows = this.select(`xo:r[not(px:Association[@AssociationName="${association.get("AssociationName")}"])]`);
if (target_rows.length) {
for (let row of target_rows) {
let association_copy = association.cloneNode(true);
//let field_association = xo.xml.createNode(`<xo:f Name="${association.getAttribute("AssociationName")}"/>`)
association_copy.select(".//@xo:id").remove();
association_copy.seed();
row.append(association_copy);
let entity = association_copy.$(`px:Entity`);
px.loadData(entity);
}
} else {
let entity = association.$(`px:Entity`);
px.loadData(entity);
}
};
//let store = this.ownerDocument.store;
//if (store && !this.selectFirst("px:Association")) {
// store.render()
//}
////if (this.parentNode instanceof Document) {
//// console.log(this)
////}
}
})
xo.listener.on(['beforeChange::@headerText', 'change::px:Record/px:*/@*'], function ({ element, attribute, value, old }) {
if (!element.has(`initial:${attribute.prefix && attribute.prefix + '-' || ''}${attribute.localName}`)) {
element.set(`initial:${attribute.prefix && attribute.prefix + '-' || ''}${attribute.localName}`, `${old}`)
}
//element.set(`prev:${attribute.prefix && attribute.prefix + '-' || ''}${attribute.localName}`, old)
return value.replace(/:/g, '').trim()
})
xo.listener.on(['set::xo:r/@state:delete'], function ({ element, attribute, value, old, event }) {
let primary_value = px.getPrimaryValue(element);
if (primary_value && primary_value.substr(1)) {
event.preventDefault()
} else {
element.remove()
}
})
app = {}
app.request = async function (object_name, mode) {
let parts = object_name.split('/') || [];
let name = parts.pop();
let schema = parts.pop();
return xo.sources.defaults["#" + name] || xo.xml.createDocument(`<?xml-stylesheet type="text/xsl" href="form.xslt" target="@#shell main"?><?xml-stylesheet type="text/xsl" href="shell_buttons.xslt" target="@#shell #shell_buttons" action="replace"?><${name} schema="${schema}"/>`)
}
px.getPrimaryValue = function (record, entity) {
entity = entity || record.$(`ancestor::px:Entity[1]`)
if (!entity) return null;
if (entity.matches(`px:Association`)) {
let association_ref = entity;
let referencees = Object.fromEntries(association_ref.select('px:Mappings/px:Mapping[not(@Referencee=ancestor::px:Entity[1]/@IdentityKey)]/@Referencee').map(referencee => [referencee.value, referencee.parentNode.getAttribute("Referencer")]));
id = entity.$$(`px:Entity/px:Record/px:Field[@IsIdentity="1"]/@Name`).map(key => record.get(referencees[key.value]));
pks = entity.$$(`px:Entity/px:PrimaryKeys/px:PrimaryKey/@Field_Name`).map(key => record.get(referencees[key.value]));
} else {
id = entity.$$(`px:Record/px:Field[@IsIdentity="1"]/@Name`).map(key => record.get(key.value));
pks = entity.$$(`px:PrimaryKeys/px:PrimaryKey/@Field_Name`).map(key => record.get(key.value));
}
if (id.length) {
return ":" + id.join("/")
} else if (pks.length) {
return "/" + pks.join("/")
} else {
return ""
}
}
px.editSelectedOption = async function (src_element) {
let selected_record = src_element instanceof HTMLSelectElement && (src_element[src_element.selectedIndex].scope || []).filter("self::xo:r").filter(el => el instanceof Element).pop();
let scope = src_element.scope;
if (!scope) {
return Promise.reject("No hay scope asociado")
};
if (!selected_record) {
return Promise.reject("No hay registro asociado")
}
let scope_entity = scope.parentNode.selectFirst("ancestor::px:Entity[1]");
let selected_record_entity = selected_record.$(`ancestor::px:Entity[1]`);
let primary_value;
let href;
let foreign_entity;
if (scope_entity === selected_record_entity) {
let association = scope.select(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName="${scope.localName}"]`)[0];
primary_value = px.getPrimaryValue(selected_record, association);
foreign_entity = association.$(`px:Entity`);
} else {
primary_value = px.getPrimaryValue(selected_record, selected_record_entity);
foreign_entity = selected_record_entity;
}
if (primary_value.substr(1)) {
href = `#${foreign_entity.get("Schema")}/${foreign_entity.get("Name")}${primary_value}~edit`
} else {
return Promise.reject("No se puede editar el registro")
}
xo.site.seed = href
}
px.editSelectedOption = async function (src_element = this) {
if (event.cancelBubble || !src_element instanceof HTMLElement) return;
event.preventDefault(); event.stopPropagation();
let data_context = src_element.closest('.data-field,.data-row');
let selected_option = (data_context || document.createElement("p")).find('.data-row [checked],.data-row[selected],tr.data-row');
let selected_record = ((selected_option || document.createElement("p")).closest('.data-row') || {}).scope;
if (!selected_record) {
return Promise.reject("No hay ningún registro asociado")
}
selected_record = selected_record instanceof Node && selected_record.selectFirst('ancestor-or-self::xo:r[1]') || selected_record;
let selected_record_entity = selected_record.$(`ancestor::px:Entity[1]`);
primary_value = px.getPrimaryValue(selected_record, selected_record_entity) || '';
let entity = selected_record_entity;
if (primary_value.substr(1)) {
href = `#${entity.get("Schema")}/${entity.get("Name")}${primary_value}~edit`
} else {
return Promise.reject("No se puede editar el registro")
}
xo.site.seed = href
}
xo.listener.on("update::@command", function () {
let command = xo.QUERI(this);
return command.update();
});
xo.listener.on("downloadCatalog::xo:r/@meta:*|association:ref/@*|field:ref/@*", function () {
let scope = this;
let association_name = scope.matches("@meta:*") && scope.localName || scope.value;
let association = scope.select(`ancestor::px:Entity[1]/px:Record/px:Association[@Type="belongsTo"][@AssociationName="${association_name}"]`)[0];
if (!association) return;
let commands = association.select("px:Entity/data:rows[not(xo:r) and not(@xsi:nil)]/@command");
let return_value;
if (commands.length) {
return_value = commands.map(command => xover.sources.get(command).ready)
} else {
return_value = px.loadData.call(this, scope.$(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName="${association_name}"]/px:Entity`))
}
return return_value
});
Object.defineProperty(Attr.prototype, 'schema', {
get: function () {
let scope = this;
let field_name
if (!scope) return null;
if (scope.parentNode.matches("self::field:ref|self::association:ref")) {
field_name = scope.value
} else if (!scope.matches('xo:r/@*')) {
return null
} else if (['http://panax.io/metadata', 'http://panax.io/state/search'].includes(scope.namespaceURI)) {
field_name = scope.localName
} else {
field_name = scope.name
}
if (!field_name) return null;
return scope.selectFirst(`ancestor::px:Entity[1]/px:Record/px:*[@Name="${field_name}"]`);
}
});
px.refreshCatalog = function (src_element) {
src_element.scope.select(`ancestor::px:Entity[1]/px:Record/px:Association[@AssociationName="${src_element.scope.localName}"]/px:Entity/data:rows/@command`).forEach(command => command.set(command => command.value));
}
px.getEntityInfo = function (input_document) {
let current_document = (input_document || ((event || {}).target || {}).store || xover.stores[(window.location.hash || "#")]);
if (!current_document) return undefined;
let entity;
current_document = (current_document.documentElement || current_document)
if (current_document && current_document.getAttribute && current_document.getAttribute("mode") && current_document.getAttribute("Name")) {
entity = {}
entity["schema"] = current_document.getAttribute("Schema");
entity["name"] = current_document.getAttribute("Name");
entity["mode"] = current_document.getAttribute("mode");
entity["pageIndex"] = current_document.getAttribute("pageIndex");
entity["pageSize"] = current_document.getAttribute("pageSize");
entity["filters"] = (current_document.getAttribute("filters") || ''); //Se reemplazan las comillas simples por dobles comillas simples. Revisar si esto se puede hacer en px.request
}
return entity;