-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
hudson-behavior.js
2790 lines (2528 loc) · 78.5 KB
/
hudson-behavior.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
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Daniel Dyer, Yahoo! Inc., Alan Harder, InfraDNA, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
//
//
// JavaScript for Jenkins
// See http://www.ibm.com/developerworks/web/library/wa-memleak/?ca=dgr-lnxw97JavascriptLeaks
// for memory leak patterns and how to prevent them.
//
if (window.isRunAsTest) {
// Disable postMessage when running in test mode (HtmlUnit).
window.postMessage = false;
}
// create a new object whose prototype is the given object
// eslint-disable-next-line no-unused-vars
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function TryEach(fn) {
return function (name) {
try {
fn(name);
} catch (e) {
console.error(e);
}
};
}
/**
* A function that returns false if the page is known to be invisible.
*/
var isPageVisible = (function () {
// @see https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
// By default, visibility set to true
var pageIsVisible = true;
// If the page is hidden, prevent any polling
// if the page is shown, restore pollings
function onVisibilityChange() {
pageIsVisible = !document[hidden];
}
// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (
typeof document.addEventListener !== "undefined" &&
typeof hidden !== "undefined"
) {
// Init the value to the real state of the page
pageIsVisible = !document[hidden];
// Handle page visibility change
document.addEventListener(visibilityChange, onVisibilityChange, false);
}
return function () {
return pageIsVisible;
};
})();
// id generator
var iota = 0;
// crumb information
var crumb = {
fieldName: null,
value: null,
init: function (crumbField, crumbValue) {
if (crumbField == "") {
// layout.jelly passes in "" whereas it means null.
return;
}
this.fieldName = crumbField;
this.value = crumbValue;
},
/**
* Adds the crumb value into the given hash or array and returns it.
*/
wrap: function (headers) {
if (this.fieldName != null) {
if (headers instanceof Array) {
// TODO prototype.js only seems to interpret object
headers.push(this.fieldName, this.value);
} else {
headers[this.fieldName] = this.value;
}
}
// TODO return value unused
return headers;
},
/**
* Puts a hidden input field to the form so that the form submission will have the crumb value
*/
appendToForm: function (form) {
if (this.fieldName == null) {
// noop
return;
}
var div = document.createElement("div");
div.classList.add("jenkins-!-display-contents");
div.innerHTML =
"<input type=hidden name='" +
this.fieldName +
"' value='" +
this.value +
"'>";
form.appendChild(div);
if (form.enctype == "multipart/form-data") {
if (form.action.indexOf("?") != -1) {
form.action = form.action + "&" + this.fieldName + "=" + this.value;
} else {
form.action = form.action + "?" + this.fieldName + "=" + this.value;
}
}
},
};
(function initializeCrumb() {
var extensionsAvailable = document.head.getAttribute(
"data-extensions-available",
);
if (extensionsAvailable === "true") {
var crumbHeaderName = document.head.getAttribute("data-crumb-header");
var crumbValue = document.head.getAttribute("data-crumb-value");
if (crumbHeaderName && crumbValue) {
crumb.init(crumbHeaderName, crumbValue);
}
}
// else, the instance is starting, restarting, etc.
})();
var isRunAsTest = undefined;
// Be careful, this variable does not include the absolute root URL as in Java part of Jenkins,
// but the contextPath only, like /jenkins
var rootURL = "not-defined-yet"; // eslint-disable-line no-unused-vars
var resURL = "not-defined-yet"; // eslint-disable-line no-unused-vars
(function initializeUnitTestAndURLs() {
var dataUnitTest = document.head.getAttribute("data-unit-test");
if (dataUnitTest !== null) {
isRunAsTest = dataUnitTest === "true";
}
var dataRootURL = document.head.getAttribute("data-rooturl");
if (dataRootURL !== null) {
rootURL = dataRootURL;
}
var dataResURL = document.head.getAttribute("data-resurl");
if (dataResURL !== null) {
resURL = dataResURL;
}
})();
(function initializeYUIDebugLogReader() {
Behaviour.addLoadEvent(function () {
var logReaderElement = document.getElementById("yui-logreader");
if (logReaderElement !== null) {
var logReader = new YAHOO.widget.LogReader("yui-logreader");
logReader.collapse();
}
});
})();
// Form check code
//========================================================
var FormChecker = {
// pending requests
queue: [],
// conceptually boolean, but doing so create concurrency problem.
// that is, during unit tests, the AJAX.send works synchronously, so
// the onComplete happens before the send method returns. On a real environment,
// more likely it's the other way around. So setting a boolean flag to true or false
// won't work.
inProgress: 0,
// defines the maximum number of parallel checks to be run
// should be '1' when http1.1 is used as browsers will usually throttle the number of connections
// and having a higher value can even have a negative impact. But with http2 enabled, this can
// be a great performance improvement
maxParallel: 1,
/**
* Schedules a form field check. Executions are serialized to reduce the bandwidth impact.
*
* @param url
* Remote doXYZ URL that performs the check. Query string should include the field value.
* @param method
* HTTP method. GET or POST. I haven't confirmed specifics, but some browsers seem to cache GET requests.
* @param target
* HTML element whose innerHTML will be overwritten when the check is completed.
*/
delayedCheck: function (url, method, target) {
if (url == null || method == null || target == null) {
// don't know whether we should throw an exception or ignore this. some broken plugins have illegal parameters
return;
}
this.queue.push({ url: url, method: method, target: target });
this.schedule();
},
sendRequest: function (url, params) {
const method = params.method.toLowerCase();
if (method !== "get") {
var idx = url.indexOf("?");
params.parameters = url.substring(idx + 1);
url = url.substring(0, idx);
}
fetch(url, {
method: params.method,
headers: crumb.wrap({
"Content-Type": "application/x-www-form-urlencoded",
}),
body: method !== "get" ? params.parameters : null,
}).then((response) => {
params.onComplete(response);
});
},
schedule: function () {
if (this.inProgress >= this.maxParallel) {
return;
}
if (this.queue.length === 0) {
return;
}
var next = this.queue.shift();
this.sendRequest(next.url, {
method: next.method,
onComplete: function (x) {
x.text().then((responseText) => {
updateValidationArea(next.target, responseText);
FormChecker.inProgress--;
FormChecker.schedule();
layoutUpdateCallback.call();
});
},
});
this.inProgress++;
},
};
/**
* Converts a JavaScript object to a URL form encoded string.
*/
function objectToUrlFormEncoded(parameters) {
// https://stackoverflow.com/a/37562814/4951015
// Code could be simplified if support for HTMLUnit is dropped
// body: new URLSearchParams(parameters) is enough then, but it doesn't work in HTMLUnit currently
let formBody = [];
for (const property in parameters) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(parameters[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
return formBody.join("&");
}
/**
* Detects if http2 protocol is enabled.
*/
function isHttp2Enabled() {
try {
const p = performance.getEntriesByType("resource");
if (p.length > 0) {
if ("nextHopProtocol" in p[0] && p[0].nextHopProtocol === "h2") {
return true;
}
}
} catch (e) {
console.error(e.stack || e);
}
return false;
}
// detect if we're using http2 and if yes increase the maxParallel connections
// of the FormChecker
if (isHttp2Enabled()) {
FormChecker.maxParallel = 30;
}
/**
* Find the sibling (in the sense of the structured form submission) form item of the given name,
* and returns that DOM node.
*
* @param {HTMLElement} e
* @param {string} name
* Name of the control to find. Can include "../../" etc in the prefix.
* See @RelativePath.
*
* We assume that the name is normalized and doesn't contain any redundant component.
* That is, ".." can only appear as prefix, and "foo/../bar" is not OK (because it can be reduced to "bar")
*/
function findNearBy(e, name) {
while (name.startsWith("../")) {
name = name.substring(3);
e = findFormParent(e, null, true);
}
// name="foo/bar/zot" -> prefixes=["bar","foo"] & name="zot"
var prefixes = name.split("/");
name = prefixes.pop();
prefixes = prefixes.reverse();
// does 'e' itself match the criteria?
// as some plugins use the field name as a parameter value, instead of 'value'
var p = findFormItem(e, name, function (e, filter) {
return filter(e) ? e : null;
});
if (p != null && prefixes.length == 0) {
return p;
}
var owner = findFormParent(e, null, true);
function locate(iterator, e) {
// keep finding elements until we find the good match
// eslint-disable-next-line no-constant-condition
while (true) {
e = iterator(e, name);
if (e == null) {
return null;
}
// make sure this candidate element 'e' is in the right point in the hierarchy
var p = e;
for (var i = 0; i < prefixes.length; i++) {
p = findFormParent(p, null, true);
if (p.getAttribute("name") != prefixes[i]) {
return null;
}
}
if (findFormParent(p, null, true) == owner) {
return e;
}
}
}
return locate(findPreviousFormItem, e) || locate(findNextFormItem, e);
}
function controlValue(e) {
if (e == null) {
return null;
}
// compute the form validation value to be sent to the server
var type = e.getAttribute("type");
if (type != null && type.toLowerCase() == "checkbox") {
return e.checked;
}
return e.value;
}
function toValue(e) {
return encodeURIComponent(controlValue(e));
}
/**
* Builds a query string in a fluent API pattern.
* @param {HTMLElement} owner
* The 'this' control.
*/
function qs(owner) {
return {
params: "",
append: function (s) {
if (this.params.length == 0) {
this.params += "?";
} else {
this.params += "&";
}
this.params += s;
return this;
},
nearBy: function (name) {
var e = findNearBy(owner, name);
if (e == null) {
// skip
return this;
}
return this.append(Path.tail(name) + "=" + toValue(e));
},
addThis: function () {
return this.append("value=" + toValue(owner));
},
toString: function () {
return this.params;
},
};
}
// @deprecated Use standard javascript method `e.closest(tagName)` instead
// eslint-disable-next-line no-unused-vars
function findAncestor(e, tagName) {
console.warn(
"Deprecated call to findAncestor - use standard javascript method `e.closest(tagName)` instead",
);
return e.closest(tagName);
}
// @deprecated Use standard javascript method `e.closest(className)` instead
// eslint-disable-next-line no-unused-vars
function findAncestorClass(e, cssClass) {
console.warn(
"Deprecated call to findAncestorClass - use standard javascript method `e.closest(className)` instead",
);
return e.closest("." + cssClass);
}
function isTR(tr, nodeClass) {
return (
tr.tagName == "TR" ||
tr.classList.contains(nodeClass || "tr") ||
tr.classList.contains("jenkins-form-item")
);
}
function findFollowingTR(node, className, nodeClass) {
// identify the parent TR
var tr = node;
while (!isTR(tr, nodeClass)) {
tr = tr.parentNode;
if (!(tr instanceof Element)) {
return null;
}
}
// then next TR that matches the CSS
do {
// Supports plugins with custom variants of <f:entry> that call
// findFollowingTR(element, 'validation-error-area') and haven't migrated
// to use querySelector
if (className === "validation-error-area" || className === "help-area") {
var queryChildren = tr.getElementsByClassName(className);
if (
queryChildren.length > 0 &&
(isTR(queryChildren[0]) ||
queryChildren[0].classList.contains(className))
) {
return queryChildren[0];
}
}
tr = tr.nextElementSibling;
} while (tr != null && (!isTR(tr) || !tr.classList.contains(className)));
return tr;
}
function findInFollowingTR(input, className) {
var node = findFollowingTR(input, className);
if (node.tagName == "TR") {
node = node.firstElementChild.nextSibling;
} else {
node = node.firstElementChild;
}
return node;
}
function find(src, filter, traversalF) {
while (src != null) {
src = traversalF(src);
if (src != null && filter(src)) {
return src;
}
}
return null;
}
/**
* Traverses a form in the reverse document order starting from the given element (but excluding it),
* until the given filter matches, or run out of an element.
*/
function findPrevious(src, filter) {
return find(src, filter, function (e) {
var p = e.previousSibling;
if (p == null) {
return e.parentNode;
}
while (p.lastElementChild != null) {
p = p.lastElementChild;
}
return p;
});
}
function findNext(src, filter) {
return find(src, filter, function (e) {
var n = e.nextSibling;
if (n == null) {
return e.parentNode;
}
while (n.firstElementChild != null) {
n = n.firstElementChild;
}
return n;
});
}
function findFormItem(src, name, directionF) {
var name2 = "_." + name; // handles <textbox field="..." /> notation silently
return directionF(src, function (e) {
if (e.tagName == "INPUT" && e.type == "radio" && e.checked == true) {
var r = 0;
while (e.name.substring(r, r + 8) == "removeme") {
//radio buttons have must be unique in repeatable blocks so name is prefixed
r = e.name.indexOf("_", r + 8) + 1;
}
return name == e.name.substring(r);
}
return (
(e.tagName == "INPUT" ||
e.tagName == "TEXTAREA" ||
e.tagName == "SELECT") &&
(e.name == name || e.name == name2)
);
});
}
/**
* Traverses a form in the reverse document order and finds an INPUT element that matches the given name.
*/
function findPreviousFormItem(src, name) {
return findFormItem(src, name, findPrevious);
}
function findNextFormItem(src, name) {
return findFormItem(src, name, findNext);
}
// This method seems unused in the ecosystem, only grails-plugin was using it but it's blacklisted now
/**
* Parse HTML into DOM.
*/
// eslint-disable-next-line no-unused-vars
function parseHtml(html) {
var c = document.createElement("div");
c.innerHTML = html;
return c.firstElementChild;
}
/**
* Evaluates the script in global context.
*/
function geval(script) {
// execScript chokes on "" but eval doesn't, so we need to reject it first.
if (script == null || script == "") {
return;
}
// see http://perfectionkills.com/global-eval-what-are-the-options/
// note that execScript cannot return value
(this.execScript || eval)(script);
}
/**
* Emulate the firing of an event.
*
* @param {HTMLElement} element
* The element that will fire the event
* @param {String} event
* like 'change', 'blur', etc.
*/
// eslint-disable-next-line no-unused-vars
function fireEvent(element, event) {
return !element.dispatchEvent(
new Event(event, {
bubbles: true,
cancelable: true,
}),
);
}
// Behavior rules
//========================================================
// using tag names in CSS selector makes the processing faster
/**
* Updates the validation area for a form element
* @param {HTMLElement} validationArea The validation area for a given form element
* @param {string} content The content to update the validation area with
*/
function updateValidationArea(validationArea, content) {
validationArea.classList.add("validation-error-area--visible");
if (content === "<div/>") {
validationArea.classList.remove("validation-error-area--visible");
validationArea.style.height = "0px";
validationArea.innerHTML = content;
} else {
// Only change content if different, causes an unnecessary animation otherwise
if (validationArea.innerHTML !== content) {
validationArea.innerHTML = content;
validationArea.style.height = "auto";
Behaviour.applySubtree(validationArea);
// For errors with additional details, apply the subtree to the expandable details pane
if (validationArea.nextElementSibling) {
Behaviour.applySubtree(validationArea.nextElementSibling);
}
}
}
}
function registerValidator(e) {
// Retrieve the validation error area
var tr = e
.closest(".jenkins-form-item")
.querySelector(".validation-error-area");
if (!tr) {
console.warn(
"Couldn't find the expected validation element (.validation-error-area) for element",
e.closest(".jenkins-form-item"),
);
return;
}
// find the validation-error-area
e.targetElement = tr;
e.targetUrl = function () {
var url = this.getAttribute("checkUrl");
var depends = this.getAttribute("checkDependsOn");
if (depends == null) {
// legacy behaviour where checkUrl is a JavaScript
try {
return eval(url); // need access to 'this', so no 'geval'
} catch (e) {
if (window.console != null) {
console.warn(
"Legacy checkUrl '" + url + "' is not valid JavaScript: " + e,
);
}
if (window.YUI != null) {
YUI.log(
"Legacy checkUrl '" + url + "' is not valid JavaScript: " + e,
"warn",
);
}
return url; // return plain url as fallback
}
} else {
var q = qs(this).addThis();
if (depends.length > 0) {
depends.split(" ").forEach(
TryEach(function (n) {
q.nearBy(n);
}),
);
}
return url + q.toString();
}
};
var method = e.getAttribute("checkMethod") || "post";
var url = e.targetUrl();
try {
FormChecker.delayedCheck(url, method, e.targetElement);
} catch (x) {
// this happens if the checkUrl refers to a non-existing element.
// don't let this kill off the entire JavaScript
console.warn(
"Failed to register validation method: " +
e.getAttribute("checkUrl") +
" : " +
e,
);
return;
}
var checker = function () {
const validationArea = this.targetElement;
FormChecker.sendRequest(this.targetUrl(), {
method: method,
onComplete: function (response) {
// TODO Add i18n support
response.text().then((responseText) => {
const errorMessage = `<div class="error">An internal error occurred during form field validation (HTTP ${response.status}). Please reload the page and if the problem persists, ask the administrator for help.</div>`;
updateValidationArea(
validationArea,
response.status === 200 ? responseText : errorMessage,
);
});
},
});
};
var oldOnchange = e.onchange;
if (typeof oldOnchange == "function") {
e.onchange = function () {
checker.call(this);
oldOnchange.call(this);
};
} else {
e.onchange = checker;
}
var v = e.getAttribute("checkDependsOn");
if (v) {
v.split(" ").forEach(
TryEach(function (name) {
var c = findNearBy(e, name);
if (c == null) {
if (window.console != null) {
console.warn("Unable to find nearby " + name);
}
if (window.YUI != null) {
YUI.log(
"Unable to find a nearby control of the name " + name,
"warn",
);
}
return;
}
c.addEventListener("change", checker.bind(e));
}),
);
}
e = null; // avoid memory leak
}
function registerRegexpValidator(e, regexp, message) {
var tr = e
.closest(".jenkins-form-item")
.querySelector(".validation-error-area");
if (!tr) {
console.warn(
"Couldn't find the expected parent element (.setting-main) for element",
e.closest(".jenkins-form-item"),
);
return;
}
// find the validation-error-area
e.targetElement = tr;
var checkMessage = e.getAttribute("checkMessage");
if (checkMessage) {
message = checkMessage;
}
var oldOnchange = e.onchange;
e.onchange = function () {
var set = oldOnchange != null ? oldOnchange.call(this) : false;
if (this.value.match(regexp)) {
if (!set) {
updateValidationArea(this.targetElement, `<div/>`);
}
} else {
updateValidationArea(
this.targetElement,
`<div class="error">${message}</div>`,
);
set = true;
}
return set;
};
e.onchange.call(e);
e = null; // avoid memory leak
}
/**
* Add a validator for number fields which contains 'min', 'max' attribute
* @param e Input element
*/
function registerMinMaxValidator(e) {
var tr = e
.closest(".jenkins-form-item")
.querySelector(".validation-error-area");
if (!tr) {
console.warn(
"Couldn't find the expected parent element (.setting-main) for element",
e.closest(".jenkins-form-item"),
);
return;
}
// find the validation-error-area
e.targetElement = tr;
var checkMessage = e.getAttribute("checkMessage");
if (checkMessage) {
// eslint-disable-next-line no-undef
message = checkMessage;
}
var oldOnchange = e.onchange;
e.onchange = function () {
var set = oldOnchange != null ? oldOnchange.call(this) : false;
const min = this.getAttribute("min");
const max = this.getAttribute("max");
function isInteger(str) {
return str.match(/^-?\d*$/) !== null;
}
if (isInteger(this.value)) {
// Ensure the value is an integer
if (min !== null && isInteger(min) && max !== null && isInteger(max)) {
// Both min and max attributes are available
if (min <= max) {
// Add the validator if min <= max
if (
parseInt(min) > parseInt(this.value) ||
parseInt(this.value) > parseInt(max)
) {
// The value is out of range
updateValidationArea(
this.targetElement,
`<div class="error">This value should be between ${min} and ${max}</div>`,
);
set = true;
} else {
if (!set) {
updateValidationArea(this.targetElement, `<div/>`);
}
}
}
} else if (
min !== null &&
isInteger(min) &&
(max === null || !isInteger(max))
) {
// There is only 'min' available
if (parseInt(min) > parseInt(this.value)) {
updateValidationArea(
this.targetElement,
`<div class="error">This value should be larger than ${min}</div>`,
);
set = true;
} else {
if (!set) {
updateValidationArea(this.targetElement, `<div/>`);
}
}
} else if (
(min === null || !isInteger(min)) &&
max !== null &&
isInteger(max)
) {
// There is only 'max' available
if (parseInt(max) < parseInt(this.value)) {
updateValidationArea(
this.targetElement,
`<div class="error">This value should be less than ${max}</div>`,
);
set = true;
} else {
if (!set) {
updateValidationArea(this.targetElement, `<div/>`);
}
}
}
}
return set;
};
e.onchange.call(e);
e = null; // avoid memory leak
}
/**
* Prevent user input 'e' or 'E' in <f:number>
* @param event Input event
*/
function preventInputEe(event) {
if (event.which === 69 || event.which === 101) {
event.preventDefault();
}
}
function escapeHTML(html) {
return html
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
/**
* Wraps a <button> into YUI button.
*
* @param e
* button element
* @param onclick
* onclick handler
* @return
* YUI Button widget.
*/
function makeButton(e, onclick) {
var h = e.onclick;
var clsName = e.className;
var n = e.name;
var attributes = {};
// YUI Button class interprets value attribute of <input> as HTML
// similar to how the child nodes of a <button> are treated as HTML.
// in standard HTML, we wouldn't expect the former case, yet here we are!
if (e.tagName === "INPUT") {
attributes.label = escapeHTML(e.value);
}
var btn = new YAHOO.widget.Button(e, attributes);
if (onclick != null) {
btn.addListener("click", onclick);
}
if (h != null) {
btn.addListener("click", h);
}
var be = btn.get("element");
var classesSeparatedByWhitespace = clsName.split(" ");
for (let i = 0; i < classesSeparatedByWhitespace.length; i++) {
var singleClass = classesSeparatedByWhitespace[i];
if (singleClass) {
be.classList.add(singleClass);
}
}
if (n) {
// copy the name
be.setAttribute("name", n);
}
// keep the data-* attributes from the source
var length = e.attributes.length;
for (let i = 0; i < length; i++) {
var attribute = e.attributes[i];
var attributeName = attribute.name;
if (attributeName.startsWith("data-")) {
btn._button.setAttribute(attributeName, attribute.value);
}
}
return btn;
}
/*
If we are inside 'to-be-removed' class, some HTML altering behaviors interact badly, because
the behavior re-executes when the removed master copy gets reinserted later.
*/
function isInsideRemovable(e) {
return !!e.closest(".to-be-removed");
}
/**
* Render the template captured by <l:renderOnDemand> at the element 'e' and replace 'e' by the content.
*
* @param {HTMLElement} e
* The place holder element to be lazy-rendered.
* @param {boolean} noBehaviour
* if specified, skip the application of behaviour rule.
*/
function renderOnDemand(e, callback, noBehaviour) {
if (!e || !e.classList.contains("render-on-demand")) {
return;
}
var proxy = eval(e.getAttribute("proxy"));
proxy.render(function (t) {