hudson-behavior.js 49.0 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * The MIT License
 * 
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Daniel Dyer, Dean Yu
 * 
 * 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.
 */
K
kohsuke 已提交
24
//
25
initOptionalBlock//
K
kohsuke 已提交
26 27 28 29 30
// JavaScript for Hudson
//     See http://www.ibm.com/developerworks/web/library/wa-memleak/?ca=dgr-lnxw97JavascriptLeaks
//     for memory leak patterns and how to prevent them.
//

31 32 33 34 35 36 37
// create a new object whose prototype is the given object
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

K
kohsuke 已提交
38 39 40
// id generator
var iota = 0;

K
kohsuke 已提交
41 42
// Form check code
//========================================================
K
kohsuke 已提交
43
var FormChecker = {
K
kohsuke 已提交
44 45
    // pending requests
    queue : [],
K
kohsuke 已提交
46

K
kohsuke 已提交
47
    inProgress : false,
K
kohsuke 已提交
48

49 50 51 52 53 54 55 56 57 58
    /**
     * 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.
     */
K
kohsuke 已提交
59
    delayedCheck : function(url, method, target) {
60 61
        if(url==null || method==null || target==null)
            return; // don't know whether we should throw an exception or ignore this. some broken plugins have illegal parameters
K
kohsuke 已提交
62 63 64
        this.queue.push({url:url, method:method, target:target});
        this.schedule();
    },
K
kohsuke 已提交
65

K
kohsuke 已提交
66 67 68 69 70
    sendRequest : function(url, params) {
        if (params.method == "post") {
            var idx = url.indexOf('?');
            params.parameters = url.substring(idx + 1);
            url = url.substring(0, idx);
K
kohsuke 已提交
71
        }
K
kohsuke 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
        new Ajax.Request(url, params);
    },

    schedule : function() {
        if (this.inProgress)  return;
        if (this.queue.length == 0) return;

        var next = this.queue.shift();
        this.sendRequest(next.url, {
            method : next.method,
            onComplete : function(x) {
                next.target.innerHTML = x.responseText;
                FormChecker.inProgress = false;
                FormChecker.schedule();
            }
        });
88
        this.inProgress = true;
K
kohsuke 已提交
89
    }
K
kohsuke 已提交
90 91
}

K
kohsuke 已提交
92 93 94 95 96 97 98 99
// find the nearest ancestor node that has the given tag name
function findAncestor(e, tagName) {
    do {
        e = e.parentNode;
    } while(e.tagName!=tagName);
    return e;
}

K
kohsuke 已提交
100 101 102 103 104
function findFollowingTR(input, className) {
    // identify the parent TR
    var tr = input;
    while (tr.tagName != "TR")
        tr = tr.parentNode;
K
kohsuke 已提交
105

K
kohsuke 已提交
106 107 108 109
    // then next TR that matches the CSS
    do {
        tr = tr.nextSibling;
    } while (tr.tagName != "TR" || tr.className != className);
K
kohsuke 已提交
110

K
kohsuke 已提交
111
    return tr;
K
kohsuke 已提交
112 113
}

K
kohsuke 已提交
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
/**
 * 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) {
    function prev(e) {
        var p = e.previousSibling;
        if(p==null) return e.parentNode;
        while(p.lastChild!=null)
            p = p.lastChild;
        return p;
    }

    while(src!=null) {
        src = prev(src);
        if(filter(src))
            return src;
    }
    return null;
}
/**
 * Traverses a form in the reverse document order and finds an INPUT element that matches the given name.
 */
function findPreviousFormItem(src,name) {
    var name2 = "_."+name; // handles <textbox field="..." /> notation silently
    return findPrevious(src,function(e){ return e.tagName=="INPUT" && (e.name==name || e.name==name2); });
}


143 144
// shared tooltip object
var tooltip;
K
kohsuke 已提交
145 146 147 148 149



// Behavior rules
//========================================================
K
kohsuke 已提交
150
// using tag names in CSS selector makes the processing faster
151
function registerValidator(e) {
K
kohsuke 已提交
152 153 154 155
    e.targetElement = findFollowingTR(e, "validation-error-area").firstChild.nextSibling;
    e.targetUrl = function() {
        return eval(this.getAttribute("checkUrl"));
    };
156
    var method = e.getAttribute("checkMethod");
K
kohsuke 已提交
157
    if (!method) method = "get";
158 159 160

    FormChecker.delayedCheck(e.targetUrl(), method, e.targetElement);

161
    var checker = function() {
K
kohsuke 已提交
162 163 164 165 166 167 168
        var target = this.targetElement;
        FormChecker.sendRequest(this.targetUrl(), {
            method : method,
            onComplete : function(x) {
                target.innerHTML = x.responseText;
            }
        });
169
    }
170 171 172 173
    var oldOnchange = e.onchange;
    if(typeof oldOnchange=="function") {
        e.onchange = function() { checker.call(this); oldOnchange.call(this); }
    } else
174
        e.onchange = checker;
175 176
    e.onblur = checker;

K
kohsuke 已提交
177
    e = null; // avoid memory leak
K
kohsuke 已提交
178
}
179

180 181 182 183 184 185 186 187 188
/**
 * Wraps a <button> into YUI button.
 *
 * @param e
 *      button element
 * @param onclick
 *      onclick handler
 */
function makeButton(e,onclick) {
K
kohsuke 已提交
189
    var h = e.onclick;
190 191
    var clsName = e.className;
    var btn = new YAHOO.widget.Button(e,{});
K
kohsuke 已提交
192 193
    if(onclick!=null)
        btn.addListener("click",onclick);
K
kohsuke 已提交
194 195
    if(h!=null)
        btn.addListener("click",h);
196
    Element.addClassName(btn.get("element"),clsName);
K
kohsuke 已提交
197
    return btn;
198 199
}

K
kohsuke 已提交
200
var hudsonRules = {
K
kohsuke 已提交
201
    "BODY" : function() {
202
        tooltip = new YAHOO.widget.Tooltip("tt", {context:[], zindex:999});
K
kohsuke 已提交
203
    },
204

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
// do the ones that extract innerHTML so that they can get their original HTML before
// other behavior rules change them (like YUI buttons.)

    "DIV.hetero-list-container" : function(e) {
        // components for the add button
        var menu = document.createElement("SELECT");
        var btn = findElementsBySelector(e,"INPUT.hetero-list-add")[0];
        YAHOO.util.Dom.insertAfter(menu,btn);

        var prototypes = e.lastChild;
        while(!Element.hasClassName(prototypes,"prototypes"))
            prototypes = prototypes.previousSibling;
        var insertionPoint = prototypes.previousSibling;    // this is where the new item is inserted.

        // extract templates
        var templates = []; var i=0;
        for(var n=prototypes.firstChild;n!=null;n=n.nextSibling,i++) {
            var name = n.getAttribute("name");
223
            var tooltip = n.getAttribute("tooltip");
224
            menu.options[i] = new Option(n.getAttribute("title"),""+i);
225
            templates.push({html:n.innerHTML, name:name, tooltip:tooltip});
226 227 228
        }
        Element.remove(prototypes);

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        // D&D support
        function prepareDD(e) {
            var dd = new DragDrop(e);
            var h = e;
            // locate a handle
            while(!Element.hasClassName(h,"dd-handle"))
                h = h.firstChild;
            dd.setHandleElId(h);
        }
        var withDragDrop = Element.hasClassName(e,"with-drag-drop");
        if(withDragDrop) {
            for(e=e.firstChild; e!=null; e=e.nextSibling) {
                if(Element.hasClassName(e,"repeated-chunk"))
                    prepareDD(e);
            }
        }

246 247 248 249 250 251 252 253 254
        var menuButton = new YAHOO.widget.Button(btn, { type: "menu", menu: menu });
        menuButton.getMenu().clickEvent.subscribe(function(type,args,value) {
            var t = templates[parseInt(args[1].value)]; // where this args[1] comes is a real mystery

            var nc = document.createElement("div");
            nc.className = "repeated-chunk";
            nc.setAttribute("name",t.name);
            nc.innerHTML = t.html;
            insertionPoint.parentNode.insertBefore(nc, insertionPoint);
255 256
            if(withDragDrop)    prepareDD(nc);
            
257 258
            Behaviour.applySubtree(nc);
        });
259 260 261 262 263 264 265 266 267 268

        menuButton.getMenu().renderEvent.subscribe(function(type,args,value) {
            // hook up tooltip for menu items
            var items = menuButton.getMenu().getItems();
            for(i=0; i<items.length; i++) {
                var t = templates[i].tooltip;
                if(t!=null)
                    applyTooltip(items[i].element,t);
            }
        });
269 270 271 272 273 274 275 276 277 278 279 280
    },

    "DIV.repeated-container" : function(e) {
        // compute the insertion point
        var ip = e.lastChild;
        while (!Element.hasClassName(ip, "repeatable-insertion-point"))
            ip = ip.previousSibling;
        // set up the logic
        object(repeatableSupport).init(e, e.firstChild, ip);
    },


K
kohsuke 已提交
281 282 283 284
    "TABLE.sortable" : function(e) {// sortable table
        ts_makeSortable(e);
    },

K
kohsuke 已提交
285 286 287
    "TABLE.progress-bar" : function(e) {// sortable table
        e.onclick = function() {
            var href = this.getAttribute("href");
K
kohsuke 已提交
288
            if(href!=null)      window.location = href;
K
kohsuke 已提交
289 290 291 292
        }
        e = null; // avoid memory leak
    },

K
kohsuke 已提交
293
    "INPUT.advancedButton" : function(e) {
294
        makeButton(e,function(e) {
K
kohsuke 已提交
295 296 297
            var link = e.target;
            while(!Element.hasClassName(link,"advancedLink"))
                link = link.parentNode;
K
kohsuke 已提交
298
            link.style.display = "none"; // hide the button
K
kohsuke 已提交
299

K
kohsuke 已提交
300
            var container = link.nextSibling.firstChild; // TABLE -> TBODY
K
kohsuke 已提交
301

K
kohsuke 已提交
302 303 304
            var tr = link;
            while (tr.tagName != "TR")
                tr = tr.parentNode;
K
kohsuke 已提交
305

K
kohsuke 已提交
306
            // move the contents of the advanced portion into the main table
307 308 309 310 311 312 313
            var nameRef = tr.getAttribute("nameref");
            while (container.lastChild != null) {
                var row = container.lastChild;
                if(nameRef!=null)
                    row.setAttribute("nameref",nameRef);
                tr.parentNode.insertBefore(row, tr.nextSibling);
            }
314
        });
K
kohsuke 已提交
315 316
        e = null; // avoid memory leak
    },
K
kohsuke 已提交
317

K
kohsuke 已提交
318 319 320 321 322 323 324 325 326 327 328
    "INPUT.expandButton" : function(e) {
        makeButton(e,function(e) {
            var link = e.target;
            while(!Element.hasClassName(link,"advancedLink"))
                link = link.parentNode;
            link.style.display = "none";
            link.nextSibling.style.display="block";
        });
        e = null; // avoid memory leak
    },

K
kohsuke 已提交
329 330 331 332 333 334 335
// scripting for having default value in the input field
    "INPUT.has-default-text" : function(e) {
        var defaultValue = e.value;
        Element.addClassName(e, "defaulted");
        e.onfocus = function() {
            if (this.value == defaultValue) {
                this.value = "";
K
kohsuke 已提交
336
                Element.removeClassName(this, "defaulted");
K
kohsuke 已提交
337 338 339 340 341
            }
        }
        e.onblur = function() {
            if (this.value == "") {
                this.value = defaultValue;
K
kohsuke 已提交
342
                Element.addClassName(this, "defaulted");
K
kohsuke 已提交
343 344 345 346
            }
        }
        e = null; // avoid memory leak
    },
K
kohsuke 已提交
347

348 349 350 351 352 353 354 355 356 357 358
// <label> that doesn't use ID, so that it can be copied in <repeatable>
    "LABEL.attach-previous" : function(e) {
        e.onclick = function() {
            var e = this;
            while(e.tagName!="INPUT")
                e=e.previousSibling;
            e.click();
        }
        e = null;
    },

K
kohsuke 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
// form fields that are validated via AJAX call to the server
// elements with this class should have two attributes 'checkUrl' that evaluates to the server URL.
    "INPUT.validated" : registerValidator,
    "SELECT.validated" : registerValidator,
    "TEXTAREA.validated" : registerValidator,

// validate form values to be a number
    "INPUT.number" : function(e) {
        e.targetElement = findFollowingTR(e, "validation-error-area").firstChild.nextSibling;
        e.onchange = function() {
            if (this.value.match(/^(\d+|)$/)) {
                this.targetElement.innerHTML = "";
            } else {
                this.targetElement.innerHTML = "<div class=error>Not a number</div>";
            }
        }
        e = null; // avoid memory leak
    },
K
kohsuke 已提交
377

K
kohsuke 已提交
378 379 380 381
    "A.help-button" : function(e) {
        e.onclick = function() {
            var tr = findFollowingTR(this, "help-area");
            var div = tr.firstChild.nextSibling.firstChild;
K
kohsuke 已提交
382

K
kohsuke 已提交
383 384
            if (div.style.display != "block") {
                div.style.display = "block";
K
kohsuke 已提交
385
                // make it visible
K
kohsuke 已提交
386 387 388 389 390 391
                new Ajax.Request(this.getAttribute("helpURL"), {
                    method : 'get',
                    onComplete : function(x) {
                        div.innerHTML = x.responseText;
                    }
                });
K
kohsuke 已提交
392 393
            } else {
                div.style.display = "none";
K
kohsuke 已提交
394 395
            }

K
kohsuke 已提交
396 397 398 399 400 401 402 403 404 405 406 407
            return false;
        }
        e = null; // avoid memory leak
    },

// deferred client-side clickable map.
// this is useful where the generation of <map> element is time consuming
    "IMG[lazymap]" : function(e) {
        new Ajax.Request(
            e.getAttribute("lazymap"),
            {
                method : 'get',
408
                onSuccess : function(x) {
K
kohsuke 已提交
409 410 411 412 413 414 415 416 417
                    var div = document.createElement("div");
                    document.body.appendChild(div);
                    div.innerHTML = x.responseText;
                    var id = "map" + (iota++);
                    div.firstChild.setAttribute("name", id);
                    e.setAttribute("usemap", "#" + id);
                }
            });
    },
418 419 420

    // button to add a new repeatable block
    "INPUT.repeatable-add" : function(e) {
421
        makeButton(e,function(e) {
K
kohsuke 已提交
422
            repeatableSupport.onAdd(e.target);
423
        });
K
kohsuke 已提交
424
        e = null; // avoid memory leak
425 426 427
    },

    "INPUT.repeatable-delete" : function(e) {
428
        makeButton(e,function(e) {
K
kohsuke 已提交
429
            repeatableSupport.onDelete(e.target);
430
        });
K
kohsuke 已提交
431
        e = null; // avoid memory leak
432 433
    },

K
kohsuke 已提交
434 435
    // resizable text area
    "TEXTAREA" : function(textarea) {
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
        if(Element.hasClassName(textarea,"rich-editor")) {
            // rich HTML editor
            try {
                var editor = new YAHOO.widget.Editor(textarea, {
                    dompath: true,
                    animate: true,
                    handleSubmit: true
                });
                // probably due to the timing issue, we need to let the editor know
                // that DOM is ready
                editor.DOMReady=true;
                editor.fireQueue();
                editor.render();
            } catch(e) {
                alert(e);
            }
            return;
        }

K
kohsuke 已提交
455 456 457 458 459
        var handle = textarea.nextSibling;
        if(handle==null || handle.className!="textarea-handle") return;

        var Event = YAHOO.util.Event;

K
kohsuke 已提交
460
        handle.onmousedown = function(ev) {
K
kohsuke 已提交
461 462
            ev = Event.getEvent(ev);
            var offset = textarea.offsetHeight-Event.getPageY(ev);
K
kohsuke 已提交
463 464
            textarea.style.opacity = 0.5;
            document.onmousemove = function(ev) {
K
kohsuke 已提交
465
                ev = Event.getEvent(ev);
K
kohsuke 已提交
466
                function max(a,b) { if(a<b) return b; else return a; }
K
kohsuke 已提交
467 468
                textarea.style.height = max(32, offset + Event.getPageY(ev)) + 'px';
                return false;
K
kohsuke 已提交
469 470 471 472 473 474
            };
            document.onmouseup = function() {
                document.onmousemove = null;
                document.onmouseup = null;
                textarea.style.opacity = 1;
            }
K
kohsuke 已提交
475 476 477 478
        };
        handle.ondblclick = function() {
            textarea.style.height = "";
            textarea.rows = textarea.value.split("\n").length;
K
kohsuke 已提交
479 480 481
        }
    },

482 483
    // structured form submission
    "FORM" : function(form) {
484 485
        if(Element.hasClassName("no-json"))
            return;
K
kohsuke 已提交
486
        // add the hidden 'json' input field, which receives the form structure in JSON
487
        var div = document.createElement("div");
488
        div.innerHTML = "<input type=hidden name=json value=init>";
489 490 491 492 493 494
        form.appendChild(div);
        
        form.onsubmit = function() { buildFormTree(this) };
        form = null; // memory leak prevention
    },

495 496
    // hook up tooltip.
    //   add nodismiss="" if you'd like to display the tooltip forever as long as the mouse is on the element.
497
    "[tooltip]" : function(e) {
498 499 500 501 502
        applyTooltip(e,e.getAttribute("tooltip"));
    },

    "INPUT.submit-button" : function(e) {
        makeButton(e);
K
kohsuke 已提交
503 504 505 506
    },

    "INPUT.yui-button" : function(e) {
        makeButton(e);
K
kohsuke 已提交
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
    },

    // image that shows [+] or [-], with hover effect.
    // oncollapsed and onexpanded will be called when the button is triggered.
    "IMG.fold-control" : function(e) {
        function changeTo(e,img) {
            var src = e.src;
            e.src = src.substring(0,src.lastIndexOf('/'))+"/"+e.getAttribute("state")+img;
        }
        e.onmouseover = function() {
            changeTo(this,"-hover.png");
        };
        e.onmouseout = function() {
            changeTo(this,".png");
        };
        e.parentNode.onclick = function(event) {
            var e = this.firstChild;
            var s = e.getAttribute("state");
            if(s=="plus") {
                e.setAttribute("state","minus");
                if(e.onexpanded)    e.onexpanded();
            } else {
                e.setAttribute("state","plus");
                if(e.oncollapsed)    e.oncollapsed();
            }
            changeTo(e,"-hover.png");
            YAHOO.util.Event.stopEvent(event);
            return false;
        };
        e = null; // memory leak prevention
537 538 539 540
    }
};

function applyTooltip(e,text) {
541
        // copied from YAHOO.widget.Tooltip.prototype.configContext to efficiently add a new element
K
kohsuke 已提交
542
        // event registration via YAHOO.util.Event.addListener leaks memory, so do it by ourselves here
543 544 545 546 547
        e.onmouseover = function(ev) {
            var delay = this.getAttribute("nodismiss")!=null ? 99999999 : 5000;
            tooltip.cfg.setProperty("autodismissdelay",delay);
            return tooltip.onContextMouseOver.call(this,YAHOO.util.Event.getEvent(ev),tooltip);
        }
548 549
        e.onmousemove = function(ev) { return tooltip.onContextMouseMove.call(this,YAHOO.util.Event.getEvent(ev),tooltip); }
        e.onmouseout  = function(ev) { return tooltip.onContextMouseOut .call(this,YAHOO.util.Event.getEvent(ev),tooltip); }
550
        e.title = text;
K
kohsuke 已提交
551
        e = null; // avoid memory leak
552
    }
K
kohsuke 已提交
553 554 555 556

Behaviour.register(hudsonRules);


K
kohsuke 已提交
557 558 559 560 561 562

function xor(a,b) {
    // convert both values to boolean by '!' and then do a!=b
    return !a != !b;
}

K
kohsuke 已提交
563 564 565 566 567 568 569
// used by editableDescription.jelly to replace the description field with a form
function replaceDescription() {
    var d = document.getElementById("description");
    d.firstChild.nextSibling.innerHTML = "<div class='spinner-right'>loading...</div>";
    new Ajax.Request(
        "./descriptionForm",
        {
570
          method : 'post',
K
kohsuke 已提交
571 572
          onComplete : function(x) {
            d.innerHTML = x.responseText;
K
kohsuke 已提交
573
            Behaviour.applySubtree(d);
574
            d.getElementsByTagName("TEXTAREA")[0].focus();
K
kohsuke 已提交
575 576 577 578
          }
        }
    );
    return false;
K
kohsuke 已提交
579 580
}

581 582 583
function applyNameRef(s,e,id) {
    $(id).groupingNode = true;
    // s contains the node itself
584 585 586 587 588
    for(var x=s.nextSibling; x!=e; x=x.nextSibling) {
        // to handle nested <f:rowSet> correctly, don't overwrite the existing value
        if(x.getAttribute("nameRef")==null)
            x.setAttribute("nameRef",id);
    }
589 590
}

591 592
function initOptionalBlock(sid, eid, cid) {
    applyNameRef($(sid),$(eid),cid);
593
    updateOptionalBlock($(cid),false);
594
}
K
kohsuke 已提交
595 596

// used by optionalBlock.jelly to update the form status
597
//   @param c     checkbox element
598
function updateOptionalBlock(c,scroll) {
599 600
    // find the start TR
    var s = c;
601
    while(!Element.hasClassName(s, "optional-block-start"))
602 603
        s = s.parentNode;
    var tbl = s.parentNode;
K
kohsuke 已提交
604 605 606
    var i = false;
    var o = false;

K
kohsuke 已提交
607
    var checked = xor(c.checked,Element.hasClassName(c,"negative"));
K
kohsuke 已提交
608
    var lastRow = null;
K
kohsuke 已提交
609 610 611 612

    for (var j = 0; tbl.rows[j]; j++) {
        var n = tbl.rows[j];

613
        if (i && Element.hasClassName(n, "optional-block-end"))
K
kohsuke 已提交
614 615 616
            o = true;

        if (i && !o) {
K
kohsuke 已提交
617
            if (checked) {
K
kohsuke 已提交
618
                n.style.display = "";
K
kohsuke 已提交
619
                lastRow = n;
620
            } else
K
kohsuke 已提交
621 622 623
                n.style.display = "none";
        }

624
        if (n==s) {
K
kohsuke 已提交
625 626 627 628 629
            if (n.getAttribute('hasHelp') == 'true')
                j++;
            i = true;
        }
    }
630

K
kohsuke 已提交
631 632 633 634 635 636 637
    if(checked && scroll) {
        var D = YAHOO.util.Dom;

        var r = D.getRegion(s);
        if(lastRow!=null)   r = r.union(D.getRegion(lastRow));
        scrollIntoView(r);
    }
K
kohsuke 已提交
638
}
K
kohsuke 已提交
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


//
// Auto-scroll support for progressive log output.
//   See http://radio.javaranch.com/pascarello/2006/08/17/1155837038219.html
//
function AutoScroller(scrollContainer) {
    // get the height of the viewport.
    // See http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
    function getViewportHeight() {
        if (typeof( window.innerWidth ) == 'number') {
            //Non-IE
            return window.innerHeight;
        } else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
            //IE 6+ in 'standards compliant mode'
            return document.documentElement.clientHeight;
        } else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
            //IE 4 compatible
            return document.body.clientHeight;
        }
        return null;
    }

    return {
        bottomThreshold : 25,
        scrollContainer: scrollContainer,

        getCurrentHeight : function() {
            var scrollDiv = $(this.scrollContainer);

            if (scrollDiv.scrollHeight > 0)
                return scrollDiv.scrollHeight;
            else
                if (objDiv.offsetHeight > 0)
                    return scrollDiv.offsetHeight;

            return null; // huh?
        },

        // return true if we are in the "stick to bottom" mode
        isSticking : function() {
            var scrollDiv = $(this.scrollContainer);
            var currentHeight = this.getCurrentHeight();

            // when used with the BODY tag, the height needs to be the viewport height, instead of
            // the element height.
            //var height = ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight);
            var height = getViewportHeight();
            var diff = currentHeight - scrollDiv.scrollTop - height;
            // window.alert("currentHeight=" + currentHeight + ",scrollTop=" + scrollDiv.scrollTop + ",height=" + height);

            return diff < this.bottomThreshold;
        },

        scrollToBottom : function() {
            var scrollDiv = $(this.scrollContainer);
            scrollDiv.scrollTop = this.getCurrentHeight();
        }
    };
}
699

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
// scroll the current window to display the given element or the region.
function scrollIntoView(e) {
    function calcDelta(ex1,ex2,vx1,vw) {
        var vx2=vx1+vw;
        var a;
        a = Math.min(vx1-ex1,vx2-ex2);
        if(a>0)     return -a;
        a = Math.min(ex1-vx1,ex2-vx2);
        if(a>0)     return a;
        return 0;
    }

    var D = YAHOO.util.Dom;

    var r;
    if(e.tagName!=null) r = D.getRegion(e);
    else                r = e;

    var dx = calcDelta(r.left,r.right, document.body.scrollLeft, D.getViewportWidth());
    var dy = calcDelta(r.top, r.bottom,document.body.scrollTop,  D.getViewportHeight());
    window.scrollBy(dx,dy);
}
722 723 724 725 726 727

// used in expandableTextbox.jelly to change a input field into a text area
function expandTextArea(button,id) {
    button.style.display="none";
    var field = document.getElementById(id);
    var value = field.value.replace(/ +/g,'\n');
K
kohsuke 已提交
728 729 730 731
    var n = field;
    while(n.tagName!="TABLE")
        n = n.parentNode;
    n.parentNode.innerHTML =
732 733
        "<textarea rows=8 class='setting-input' name='"+field.name+"'>"+value+"</textarea>";
}
734 735 736 737 738


// refresh a part of the HTML specified by the given ID,
// by using the contents fetched from the given URL.
function refreshPart(id,url) {
739
    var f = function() {
740
        new Ajax.Request(url, {
741
            method: "post",
742
            onSuccess: function(rsp) {
743 744 745 746 747 748 749 750
                var hist = $(id);
                var p = hist.parentNode;
                var next = hist.nextSibling;
                p.removeChild(hist);

                var div = document.createElement('div');
                div.innerHTML = rsp.responseText;

751 752
                var node = div.firstChild;
                p.insertBefore(node, next);
K
kohsuke 已提交
753

754
                Behaviour.applySubtree(node);
K
kohsuke 已提交
755

756
                if(isRunAsTest) return;
K
kohsuke 已提交
757
                refreshPart(id,url);
758 759
            }
        });
760 761 762 763 764
    };
    // if run as test, just do it once and do it now to make sure it's working,
    // but don't repeat.
    if(isRunAsTest) f();
    else    window.setTimeout(f, 5000);
K
kohsuke 已提交
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
}


/*
    Perform URL encode.
    Taken from http://www.cresc.co.jp/tech/java/URLencoding/JavaScript_URLEncoding.htm
*/
function encode(str){
    var s, u;
    var s0 = "";                // encoded str

    for (var i = 0; i < str.length; i++){   // scan the source
        s = str.charAt(i);
        u = str.charCodeAt(i);          // get unicode of the char

        if (s == " "){s0 += "+";}       // SP should be converted to "+"
        else {
            if ( u == 0x2a || u == 0x2d || u == 0x2e || u == 0x5f || ((u >= 0x30) && (u <= 0x39)) || ((u >= 0x41) && (u <= 0x5a)) || ((u >= 0x61) && (u <= 0x7a))){     // check for escape
                s0 = s0 + s;           // don't escape
            } else {                      // escape
                if ((u >= 0x0) && (u <= 0x7f)){     // single byte format
                    s = "0"+u.toString(16);
                    s0 += "%"+ s.substr(s.length-2);
                } else
                if (u > 0x1fffff){     // quaternary byte format (extended)
                    s0 += "%" + (0xF0 + ((u & 0x1c0000) >> 18)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0x3f000) >> 12)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                } else
                if (u > 0x7ff){        // triple byte format
                    s0 += "%" + (0xe0 + ((u & 0xf000) >> 12)).toString(16);
                    s0 += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                } else {                      // double byte format
                    s0 += "%" + (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
                    s0 += "%" + (0x80 + (u & 0x3f)).toString(16);
                }
            }
        }
    }
    return s0;
807 808
}

K
kohsuke 已提交
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
// when there are multiple form elements of the same name,
// this method returns the input field of the given name that pairs up
// with the specified 'base' input element.
Form.findMatchingInput = function(base, name) {
    // find the FORM element that owns us
    var f = base;
    while (f.tagName != "FORM")
        f = f.parentNode;

    var bases = Form.getInputs(f, null, base.name);
    var targets = Form.getInputs(f, null, name);

    for (var i=0; i<bases.length; i++) {
        if (bases[i] == base)
            return targets[i];
    }

    return null;        // not found
}

829 830
// used witih <dropdownList> and <dropdownListBlock> to control visibility
function updateDropDownList(sel) {
831
    for (var i = 0; i < sel.subForms.length; i++) {
832
        var show = sel.selectedIndex == i;
833
        var f = sel.subForms[i];
834 835 836
        var td = f.start;
        while (true) {
            td.style.display = (show ? "" : "none");
837
            if(show)
838
                td.removeAttribute("field-disabled");
839
            else    // buildFormData uses this attribute and ignores the contents
840
                td.setAttribute("field-disabled","true");
841 842 843 844
            if (td == f.end) break;
            td = td.nextSibling;
        }
    }
845 846 847 848
}


// code for supporting repeatable.jelly
K
kohsuke 已提交
849
var repeatableSupport = {
850 851 852 853 854 855 856 857 858
    // set by the inherited instance to the insertion point DIV
    insertionPoint: null,

    // HTML text of the repeated chunk
    blockHTML: null,

    // containing <div>.
    container: null,

859 860 861
    // block name for structured HTML
    name : null,

862 863 864 865 866 867 868 869
    // do the initialization
    init : function(container,master,insertionPoint) {
        this.container = $(container);
        this.container.tag = this;
        master = $(master);
        this.blockHTML = master.innerHTML;
        master.parentNode.removeChild(master);
        this.insertionPoint = $(insertionPoint);
870
        this.name = master.getAttribute("name");
871 872 873 874 875 876 877 878 879
        this.update();
    },

    // insert one more block at the insertion position
    expand : function() {
        // importNode isn't supported in IE.
        // nc = document.importNode(node,true);
        var nc = document.createElement("div");
        nc.className = "repeated-chunk";
K
bug fix  
kohsuke 已提交
880
        nc.setAttribute("name",this.name);
881 882 883 884 885 886 887 888 889 890 891 892 893 894
        nc.innerHTML = this.blockHTML;
        this.insertionPoint.parentNode.insertBefore(nc, this.insertionPoint);

        Behaviour.applySubtree(nc);
        this.update();
    },

    // update CSS classes associated with repeated items.
    update : function() {
        var children = [];
        for( var n=this.container.firstChild; n!=null; n=n.nextSibling )
            if(Element.hasClassName(n,"repeated-chunk"))
                children.push(n);

K
kohsuke 已提交
895 896 897
        if(children.length==0) {
            // noop
        } else
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
        if(children.length==1) {
            children[0].className = "repeated-chunk first last only";
        } else {
            children[0].className = "repeated-chunk first";
            for(var i=1; i<children.length-1; i++)
                children[i].className = "repeated-chunk middle";
            children[children.length-1].className = "repeated-chunk last";
        }
    },

    // these are static methods that don't rely on 'this'

    // called when 'delete' button is clicked
    onDelete : function(n) {
        while (!Element.hasClassName(n,"repeated-chunk"))
            n = n.parentNode;

        var p = n.parentNode;
        p.removeChild(n);
        p.tag.update();
    },

    // called when 'add' button is clicked
    onAdd : function(n) {
        while(n.tag==null)
            n = n.parentNode;
        n.tag.expand();
    }
926 927
};

K
kohsuke 已提交
928 929 930 931 932
// Used by radioBlock.jelly to wire up expandable radio block
function addRadioBlock(id) {
    // prototype object to be duplicated for each radio button group
    var radioBlockSupport = {
        buttons : null,
933

K
kohsuke 已提交
934 935 936 937
        updateButtons : function() {
            for( var i=0; i<this.buttons.length; i++ )
                this.buttons[i]();
        },
938

K
kohsuke 已提交
939
        // update one block based on the status of the given radio button
940
        updateSingleButton : function(radio, blockStart, blockEnd) {
K
kohsuke 已提交
941 942 943 944
            var tbl = blockStart.parentNode;
            var i = false;
            var o = false;
            var show = radio.checked;
945

946 947
            for (var j = 0; tbl.rows[j]; j++) {
                var n = tbl.rows[j];
948

949 950
                if (n == blockEnd)
                    o = true;
951

952 953 954 955 956 957
                if (i && !o) {
                    if (show)
                        n.style.display = "";
                    else
                        n.style.display = "none";
                }
958

959
                if (n == blockStart) {
960
                    i = true;
961 962 963
                    if (n.getAttribute('hasHelp') == 'true')
                        j++;
                }
K
kohsuke 已提交
964
            }
965
        }
K
kohsuke 已提交
966
    };
967

K
kohsuke 已提交
968 969 970
    // when one radio button is clicked, we need to update foldable block for
    // other radio buttons with the same name. To do this, group all the
    // radio buttons with the same name together and hang it under the form object
971 972 973 974 975 976 977 978 979 980 981 982
    var r = document.getElementById('Rb' + id);
    var f = r.form;
    var radios = f.radios;
    if (radios == null)
        f.radios = radios = {};

    var g = radios[r.name];
    if (g == null) {
        radios[r.name] = g = object(radioBlockSupport);
        g.buttons = [];
    }

983 984 985
    var s = document.getElementById("rb_s"+id);
    var e = document.getElementById("rb_e"+id);

986
    var u = function() {
987
        g.updateSingleButton(r,s,e);
988
    };
989
    applyNameRef(s,e,'Rb'+id);
990 991 992 993 994 995 996 997 998 999
    g.buttons.push(u);

    // apply the initial visibility
    u();

    // install event handlers to update visibility.
    // needs to use onclick and onchange for Safari compatibility
    r.onclick = r.onchange = function() { g.updateButtons(); };
}

1000

K
kohsuke 已提交
1001
function updateBuildHistory(ajaxUrl,nBuild) {
1002
    if(isRunAsTest) return;
1003 1004 1005 1006
    $('buildHistory').headers = ["n",nBuild];

    function updateBuilds() {
        var bh = $('buildHistory');
K
kohsuke 已提交
1007
        new Ajax.Request(ajaxUrl, {
1008
            requestHeaders: bh.headers,
1009
            onSuccess: function(rsp) {
1010 1011 1012 1013 1014 1015 1016 1017 1018
                var rows = bh.rows;

                //delete rows with transitive data
                while (rows.length > 2 && Element.hasClassName(rows[1], "transitive"))
                    Element.remove(rows[1]);

                // insert new rows
                var div = document.createElement('div');
                div.innerHTML = rsp.responseText;
K
kohsuke 已提交
1019
                Behaviour.applySubtree(div);
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

                var pivot = rows[0];
                var newRows = div.firstChild.rows;
                for (var i = newRows.length - 1; i >= 0; i--) {
                    pivot.parentNode.insertBefore(newRows[i], pivot.nextSibling);
                }

                // next update
                bh.headers = ["n",rsp.getResponseHeader("n")];
                window.setTimeout(updateBuilds, 5000);
            }
        });
    }
    window.setTimeout(updateBuilds, 5000);
}
1035 1036 1037 1038 1039 1040

// send async request to the given URL (which will send back serialized ListBoxModel object),
// then use the result to fill the list box.
function updateListBox(listBox,url) {
    new Ajax.Request(url, {
        method: "post",
1041
        onSuccess: function(rsp) {
1042 1043 1044 1045 1046 1047 1048 1049 1050
            var l = $(listBox);
            while(l.length>0)   l.options[0] = null;

            var opts = eval('('+rsp.responseText+')').values;
            for( var i=0; i<opts.length; i++ ) {
                l.options[i] = new Option(opts[i].name,opts[i].value);
                if(opts[i].selected)
                    l.selectedIndex = i;
            }
1051 1052 1053 1054
        },
        onFailure: function(rsp) {
            var l = $(listBox);
            l.options[0] = null;
1055 1056
        }
    });
1057 1058
}

1059 1060 1061 1062 1063
// get the cascaded computed style value. 'a' is the style name like 'backgroundColor'
function getStyle(e,a){
  if(document.defaultView && document.defaultView.getComputedStyle)
    return document.defaultView.getComputedStyle(e,null).getPropertyValue(a.replace(/([A-Z])/g, "-$1"));
  if(e.currentStyle)
K
kohsuke 已提交
1064 1065
    return e.currentStyle[a];
  return null;
1066 1067 1068
};

// set up logic behind the search box
1069 1070 1071 1072 1073
function createSearchBox(searchURL) {
    var ds = new YAHOO.widget.DS_XHR(searchURL+"suggest",["suggestions","name"]);
    ds.queryMatchCase = false;
    var ac = new YAHOO.widget.AutoComplete("search-box","search-box-completion",ds);
    ac.typeAhead = false;
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110

    var box   = $("search-box");
    var sizer = $("search-box-sizer");
    var comp  = $("search-box-completion");
    var minW  = $("search-box-minWidth");

    Behaviour.addLoadEvent(function(){
        // make sure all three components have the same font settings
        function copyFontStyle(s,d) {
            var ds = d.style;
            ds.fontFamily = getStyle(s,"fontFamily");
            ds.fontSize = getStyle(s,"fontSize");
            ds.fontStyle = getStyle(s,"fontStyle");
            ds.fontWeight = getStyle(s,"fontWeight");
        }

        copyFontStyle(box,sizer);
        copyFontStyle(box,minW);
    });

    // update positions and sizes of the components relevant to search
    function updatePos() {
        function max(a,b) { if(a>b) return a; else return b; }

        sizer.innerHTML = box.value;
        var w = max(sizer.offsetWidth,minW.offsetWidth);
        box.style.width =
        comp.style.width = 
        comp.firstChild.style.width = (w+60)+"px";

        var pos = YAHOO.util.Dom.getXY(box);
        pos[1] += YAHOO.util.Dom.get(box).offsetHeight + 2;
        YAHOO.util.Dom.setXY(comp, pos);
    }

    updatePos();
    box.onkeyup = updatePos;
1111 1112 1113 1114 1115 1116 1117
}


//
// structured form submission handling
//   see http://hudson.gotdns.com/wiki/display/HUDSON/Structured+Form+Submission
function buildFormTree(form) {
K
kohsuke 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126
    try {
        // I initially tried to use an associative array with DOM elemnets as keys
        // but that doesn't seem to work neither on IE nor Firefox.
        // so I switch back to adding a dynamic property on DOM.
        form.formDom = {}; // root object

        var doms = []; // DOMs that we added 'formDom' for.
        doms.push(form);

1127
        function shortenName(name) {
1128 1129 1130 1131 1132
            // [abc.def.ghi] -> abc.def.ghi
            if(name.startsWith('['))
                return name.substring(1,name.length-1);

            // abc.def.ghi -> ghi
K
kohsuke 已提交
1133 1134
            var idx = name.lastIndexOf('.');
            if(idx>=0)  name = name.substring(idx+1);
1135 1136
            return name;
        }
K
kohsuke 已提交
1137

1138 1139
        function addProperty(parent,name,value) {
            name = shortenName(name);
K
kohsuke 已提交
1140 1141 1142 1143 1144 1145 1146
            if(parent[name]!=null) {
                if(parent[name].push==null) // is this array?
                    parent[name] = [ parent[name] ];
                parent[name].push(value);
            } else {
                parent[name] = value;
            }
1147 1148
        }

K
kohsuke 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
        // find the grouping parent node, which will have @name.
        // then return the corresponding object in the map
        function findParent(e) {
            while(e!=form) {
                e = e.parentNode;

                // this is used to create a group where no single containing parent node exists,
                // like <optionalBlock>
                var nameRef = e.getAttribute("nameRef");
                if(nameRef!=null)
                    e = $(nameRef);

1161
                if(e.getAttribute("field-disabled")!=null)
1162 1163
                    return {};  // this field shouldn't contribute to the final result

K
kohsuke 已提交
1164 1165
                var name = e.getAttribute("name");
                if(name!=null) {
K
kohsuke 已提交
1166
                    if(e.tagName=="INPUT" && !xor(e.checked,Element.hasClassName(e,"negative")))
K
kohsuke 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
                        return {};  // field is not active

                    var m = e.formDom;
                    if(m==null) {
                        // this is a new grouping node
                        doms.push(e);
                        e.formDom = m = {};
                        addProperty(findParent(e), name, m);
                    }
                    return m;
1177 1178 1179
                }
            }

K
kohsuke 已提交
1180 1181
            return form.formDom; // guaranteed non-null
        }
1182

K
kohsuke 已提交
1183
        var jsonElement = null;
1184

K
kohsuke 已提交
1185 1186 1187 1188 1189
        for( var i=0; i<form.elements.length; i++ ) {
            var e = form.elements[i];
            if(e.name=="json") {
                jsonElement = e;
                continue;
1190
            }
1191
            if(e.tagName=="FIELDSET")
K
kohsuke 已提交
1192
                continue;
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
            if(e.tagName=="SELECT" && e.multiple) {
                var values = [];
                for( var o=0; o<e.options.length; o++ ) {
                    var opt = e.options.item(o);
                    if(opt.selected)
                        values.push(opt.value);
                }
                addProperty(findParent(e),e.name,values);
                continue;
            }
                
K
kohsuke 已提交
1204 1205 1206 1207 1208 1209 1210 1211
            var p;
            var type = e.getAttribute("type");
            if(type==null)  type="";
            switch(type.toLowerCase()) {
            case "button":
            case "submit":
                break;
            case "checkbox":
1212
                p = findParent(e);
K
kohsuke 已提交
1213
                var checked = xor(e.checked,Element.hasClassName(e,"negative"));
K
kohsuke 已提交
1214
                if(!e.groupingNode)
K
kohsuke 已提交
1215
                    addProperty(p, e.name, checked);
K
kohsuke 已提交
1216
                else {
K
kohsuke 已提交
1217
                    if(checked)
K
kohsuke 已提交
1218 1219
                        addProperty(p, e.name, e.formDom = {});
                }
1220
                break;
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
            case "file":
                // to support structured form submission with file uploads,
                // rename form field names to unique ones, and leave this name mapping information
                // in JSON. this behavior is backward incompatible, so only do
                // this when
                p = findParent(e);
                if(e.getAttribute("jsonAware")!=null) {
                    var on = e.getAttribute("originalName");
                    if(on!=null) {
                        addProperty(p,on,e.name);
                    } else {
                        var uniqName = "file"+(iota++);
                        addProperty(p,e.name,uniqName);
                        e.setAttribute("originalName",e.name);
                        e.name = uniqName;
                    }
                }
                // switch to multipart/form-data to support file submission
K
See...  
kohsuke 已提交
1239 1240
                // @enctype is the standard, but IE needs @encoding.
                form.enctype = form.encoding = "multipart/form-data";
1241
                break;
K
kohsuke 已提交
1242 1243 1244 1245 1246 1247 1248
            case "radio":
                if(!e.checked)  break;
                if(e.groupingNode) {
                    p = findParent(e);
                    addProperty(p, e.name, e.formDom = { value: e.value });
                    break;
                }
1249

K
kohsuke 已提交
1250 1251 1252 1253 1254 1255
                // otherwise fall through
            default:
                p = findParent(e);
                addProperty(p, e.name, e.value);
                break;
            }
1256 1257
        }

K
kohsuke 已提交
1258
        jsonElement.value = Object.toJSON(form.formDom);
1259

K
kohsuke 已提交
1260 1261 1262
        // clean up
        for( i=0; i<doms.length; i++ )
            doms[i].formDom = null;
1263

K
kohsuke 已提交
1264 1265 1266 1267 1268

        return jsonElement.value;
    } catch(e) {
        alert(e);
    }
K
kohsuke 已提交
1269 1270 1271 1272
}

// this used to be in prototype.js but it must have been removed somewhere between 1.4.0 to 1.5.1
String.prototype.trim = function() {
K
kohsuke 已提交
1273 1274 1275 1276 1277 1278 1279 1280
    var temp = this;
    var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
    if (obj.test(temp))
        temp = temp.replace(obj, '$2');
    obj = /  /g;
    while (temp.match(obj))
        temp = temp.replace(obj, " ");
    return temp;
K
kohsuke 已提交
1281
}
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329



var hoverNotification = (function() {
    var msgBox;
    var body;

    // animation effect that automatically hide the message box
    var effect = function(overlay, dur) {
        var o = YAHOO.widget.ContainerEffect.FADE(overlay, dur);
        o.animateInCompleteEvent.subscribe(function() {
            window.setTimeout(function() {
                msgBox.hide()
            }, 1500);
        });
        return o;
    }

    function init() {
        if(msgBox!=null)  return;   // already initialized

        var div = document.createElement("DIV");
        document.body.appendChild(div);
        div.innerHTML = "<div id=hoverNotification><div class=bd></div></div>";
        body = $('hoverNotification');
        
        msgBox = new YAHOO.widget.Overlay(body, {
          visible:false,
          width:"10em",
          zIndex:1000,
          effect:{
            effect:effect,
            duration:0.25
          }
        });
        msgBox.render();
    }

    return function(title,anchor) {
        init();
        body.innerHTML = title;
        var xy = YAHOO.util.Dom.getXY(anchor);
        xy[0] += 48;
        xy[1] += anchor.offsetHeight;
        msgBox.cfg.setProperty("xy",xy);
        msgBox.show();
    };
})();
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

/*
    D&D implementation for heterogeneous list.
 */
var DragDrop = function(id, sGroup, config) {
    DragDrop.superclass.constructor.apply(this, arguments);
};

(function() {
    var Dom = YAHOO.util.Dom;
    var Event = YAHOO.util.Event;
    var DDM = YAHOO.util.DragDropMgr;

    YAHOO.extend(DragDrop, YAHOO.util.DDProxy, {
        startDrag: function(x, y) {
            var el = this.getEl();

            this.resetConstraints();
            this.setXConstraint(0,0);    // D&D is for Y-axis only

            // set Y constraint to be within the container
            var totalHeight = el.parentNode.offsetHeight;
            var blockHeight = el.offsetHeight;
            this.setYConstraint(el.offsetTop, totalHeight-blockHeight-el.offsetTop);

            el.style.visibility = "hidden";

            this.goingUp = false;
            this.lastY = 0;
        },

        endDrag: function(e) {
            var srcEl = this.getEl();
            var proxy = this.getDragEl();

            // Show the proxy element and animate it to the src element's location
            Dom.setStyle(proxy, "visibility", "");
            var a = new YAHOO.util.Motion(
                proxy, {
                    points: {
                        to: Dom.getXY(srcEl)
                    }
                },
                0.2,
                YAHOO.util.Easing.easeOut
            )
            var proxyid = proxy.id;
            var thisid = this.id;

            // Hide the proxy and show the source element when finished with the animation
            a.onComplete.subscribe(function() {
                    Dom.setStyle(proxyid, "visibility", "hidden");
                    Dom.setStyle(thisid, "visibility", "");
                });
            a.animate();
        },

        onDrag: function(e) {

            // Keep track of the direction of the drag for use during onDragOver
            var y = Event.getPageY(e);

            if (y < this.lastY) {
                this.goingUp = true;
            } else if (y > this.lastY) {
                this.goingUp = false;
            }

            this.lastY = y;
        },

        onDragOver: function(e, id) {
            var srcEl = this.getEl();
            var destEl = Dom.get(id);

            // We are only concerned with list items, we ignore the dragover
            // notifications for the list.
            if (destEl.nodeName == "DIV" && Dom.hasClass(destEl,"repeated-chunk")) {
                var p = destEl.parentNode;

                // if going up, insert above the target element
                p.insertBefore(srcEl, this.goingUp?destEl:destEl.nextSibling);

                DDM.refreshCache();
            }
        }
    });
1417 1418
})();

1419 1420 1421 1422 1423 1424
function loadScript(href) {
    var s = document.createElement("script");
    s.setAttribute("src",href);
    document.getElementsByTagName("HEAD")[0].appendChild(s);
}

1425 1426
var updateCenter = {
    postBackURL : null,
1427
    info: {},
1428
    completionHandler: null,
1429
    url: "https://hudson.dev.java.net/",
1430 1431

    checkUpdates : function() {
1432
        loadScript(updateCenter.url+"update-center.json?"+Hash.toQueryString(updateCenter.info));
1433 1434 1435 1436 1437
    },

    post : function(data) {
        new Ajax.Request(updateCenter.postBackURL, {
            method:"post",
1438 1439 1440 1441 1442
            parameters:{json:Object.toJSON(data)},
            onSuccess: function() {
                if(updateCenter.completionHandler!=null)
                    updateCenter.completionHandler();
            }
1443 1444
        });
    }
1445
};
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479

/*
redirects to a page once the page is ready.

    @param url
        Specifies the URL to redirect the user.
*/
function applySafeRedirector(url) {
    var i=0;
    new PeriodicalExecuter(function() {
      i = (i+1)%4;
      var s = "";
      for( var j=0; j<i; j++ )
        s+='.';
      $('progress').innerHTML = s;
    },1);

    window.setTimeout(function() {
      var statusChecker = arguments.callee;
        new Ajax.Request(url, {
            method: "get",
            onFailure: function(rsp) {
                if(rsp.status==503) {
                  // redirect as long as we are still loading
                  window.setTimeout(statusChecker,5000);
                } else {
                  window.location.replace(url);
                }
            },
            onSuccess: function(rsp) {
                window.location.replace(url);
            }
        });
    }, 5000);
1480
}
K
kohsuke 已提交
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506

// logic behind <f:validateButton />
function validateButton(checkUrl,paramList,button) {
  button = button._button;

  var parameters = {};

  paramList.split(',').each(function(name) {
      var p = findPreviousFormItem(button,name);
      if(p!=null)
        parameters[name] = p.value;
  });

  var spinner = Element.up(button,"DIV").nextSibling;
  var target = spinner.nextSibling;
  spinner.style.display="block";

  new Ajax.Request(checkUrl, {
      method: "post",
      parameters: parameters,
      onComplete: function(rsp) {
          spinner.style.display="none";
          target.innerHTML = rsp.responseText;
      }
  });
}
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534

// create a combobox.
// @param id
//      ID of the <input type=text> element that becomes a combobox.
// @param valueFunction
//      Function that returns all the candidates as an array
function createComboBox(id,valueFunction) {
    var candidates = valueFunction();

    Behaviour.addLoadEvent(function() {
        var callback = function(value /*, comboBox*/) {
          var items = new Array();
          if (value.length > 0) { // if no value, we'll not provide anything
            value = value.toLowerCase();
            for (var i = 0; i<candidates.length; i++) {
              if (candidates[i].toLowerCase().indexOf(value) >= 0) {
                items.push(candidates[i]);
                if(items.length>20)
                  break; // 20 items in the list should be enough
              }
            }
          }
          return items; // equiv to: comboBox.setItems(items);
        };

        new ComboBox(id,callback);
    });
}