~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to www/media/common/util.js

  • Committer: mattgiuca
  • Date: 2008-03-01 01:59:10 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:630
subjects: Added subjects/subjects.css to correctly style the iframe.
    Added "sample" subject home page with minimal instructions on how to make
    a subject home page.
    Link to subjects.css.
Set svn:ignore on apps/subjects and apps/home (*.pyc).

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
 * Defines some generic JavaScript utility functions.
23
23
 */
24
24
 
 
25
/* Expects the following variables to have been declared by JavaScript in
 
26
 * the HTML generated by the server:
 
27
 * - root_dir
 
28
 * - username
 
29
 */
 
30
 
25
31
/** Removes all children of a given DOM element
26
32
 * \param elem A DOM Element. Will be modified.
27
33
 */
34
40
/** Creates a DOM element with simple text inside it.
35
41
 * \param tagname String. Name of the element's tag (eg. "p").
36
42
 * \param text String. Text to be placed inside the element.
 
43
 * \param title String, optional. Tooltip for the text.
 
44
 *  (Note, title creates a span element around the text).
37
45
 * \return DOM Element object.
38
46
 */
39
 
function dom_make_text_elem(tagname, text)
 
47
function dom_make_text_elem(tagname, text, title)
40
48
{
41
49
    if (text == null) text = "";
42
50
    var elem = document.createElement(tagname);
43
 
    elem.appendChild(document.createTextNode(text));
 
51
    var textnode;
 
52
    if (title == null)
 
53
        textnode = document.createTextNode(text);
 
54
    else
 
55
    {
 
56
        textnode = document.createElement("span");
 
57
        textnode.setAttribute("title", title);
 
58
        textnode.appendChild(document.createTextNode(text));
 
59
    }
 
60
    elem.appendChild(textnode);
44
61
    return elem;
45
62
}
46
63
 
47
64
/** Creates a DOM element with hyperlinked text inside it.
48
65
 * \param tagname String. Name of the element's tag (eg. "p").
49
66
 * \param text String. Text to be placed inside the element.
 
67
 * \param title String, optional. Sets a tooltip for the link.
50
68
 * \param href String. URL the text will link to. This is a raw string,
51
69
 *  it will automatically be URL-encoded.
52
70
 * \param onclick Optional string. Will be set as the "onclick" attribute
53
71
 *  of the "a" element.
 
72
 * \param dontencode Optional boolean. If true, will not encode the href.
 
73
 *  if including query strings, you must set this to true and use build_url
 
74
 *  to escape the URI correctly.
54
75
 * \return DOM Element object.
55
76
 */
56
 
function dom_make_link_elem(tagname, text, href, onclick)
 
77
function dom_make_link_elem(tagname, text, title, href, onclick, dontencode)
57
78
{
58
79
    if (text == null) text = "";
59
80
    if (href == null) href = "";
60
81
    var elem = document.createElement(tagname);
61
82
    var link = document.createElement("a");
62
 
    link.setAttribute("href", encodeURI(href));
 
83
    if (dontencode != true)
 
84
        href = urlencode_path(href);
 
85
    link.setAttribute("href", href);
 
86
    if (title != null)
 
87
        link.setAttribute("title", title);
63
88
    if (onclick != null)
64
89
        link.setAttribute("onclick", onclick);
65
90
    link.appendChild(document.createTextNode(text));
73
98
function dom_make_img(src, width, height, title, alt)
74
99
{
75
100
    var img = document.createElement("img");
76
 
    img.setAttribute("src", src);
 
101
    img.setAttribute("src", urlencode_path(src));
77
102
    if (width != null)
78
103
        img.setAttribute("width", width);
79
104
    if (height != null)
129
154
 * args is never null, though it may be empty.
130
155
 *
131
156
 * All strings are decoded/unescaped. Reserved characters
132
 
 * (; , / ? : @ & = + * $) are not decoded except in args.
 
157
 * (; , / ? : @ & = + * $) are not decoded except in args and path.
133
158
 *
134
159
 * \param url String. A URL. To read from the current browser window, use
135
160
 *  window.location.href.
142
167
    var serverpart;
143
168
    var args;
144
169
 
145
 
    url = decodeURI(url);
146
 
 
147
170
    /* Split scheme from rest */
148
171
    index = url.indexOf("://");
149
172
    if (index < 0)
200
223
            obj.query_string = url.substr(index+1);
201
224
        }
202
225
    }
 
226
    obj.path = decodeURIComponent(obj.path);
203
227
 
204
228
    /* Split query string into arguments */
205
229
    args = {};
254
278
            query_string += "&" + encodeURIComponent(arg_key) + "=" +
255
279
                encodeURIComponent(arg_val);
256
280
    }
257
 
    if (query_string == "")
258
 
        query_string = null;
259
 
    else
 
281
    if (query_string != "")
260
282
        /* Drop the first "&" */
261
283
        query_string = query_string.substr(1);
262
284
 
287
309
        url += ":" + obj.server_port.toString();
288
310
    if (("path" in obj) && obj.path != null)
289
311
    {
290
 
        var path = obj.path.toString();
 
312
        var path = urlencode_path(obj.path.toString());
291
313
        if (url.length > 0 && path.length > 0 && path[0] != "/")
292
314
            path = "/" + path;
293
315
        url += path;
294
316
    }
295
317
    if (("query_string" in obj) && obj.query_string != null)
296
 
        query_string = obj.query_string.toString();
 
318
        query_string = encodeURI(obj.query_string.toString());
297
319
    else if (("args" in obj) && obj.args != null)
298
320
        query_string = make_query_string(obj.args);
299
321
 
300
 
    if (query_string != null)
 
322
    if (query_string != "" && query_string != null)
301
323
        url += "?" + query_string;
302
324
 
303
 
    return encodeURI(url);
 
325
    return url;
 
326
}
 
327
 
 
328
/** URL-encodes a path. This is a special case of URL encoding as all
 
329
 * characters *except* the slash must be encoded.
 
330
 */
 
331
function urlencode_path(path)
 
332
{
 
333
    /* Split up the path, URLEncode each segment with encodeURIComponent,
 
334
     * and rejoin.
 
335
     */
 
336
    var split = path.split('/');
 
337
    for (var i=0; i<split.length; i++)
 
338
        split[i] = encodeURIComponent(split[i]);
 
339
    path = path_join.apply(null, split);
 
340
    if (split[0] == "" && split.length > 1) path = "/" + path;
 
341
    return path;
304
342
}
305
343
 
306
344
/** Given an argument map, as output in the args parameter of the return of
348
386
function path_join(path1 /*, path2, ... */)
349
387
{
350
388
    var arg;
351
 
    path = path1;
352
 
    for (var i=1; i<arguments.length; i++)
 
389
    var path = "";
 
390
    for (var i=0; i<arguments.length; i++)
353
391
    {
354
392
        arg = arguments[i];
355
393
        if (arg.length == 0) continue;
357
395
            path = arg;
358
396
        else
359
397
        {
360
 
            if (path[path.length-1] != '/')
 
398
            if (path.length > 0 && path[path.length-1] != '/')
361
399
                path += '/';
362
400
            path += arg;
363
401
        }
388
426
    {
389
427
        /* FIXME: Encoding not supported here (should not matter if we
390
428
         * only use ASCII names */
391
 
        data += "--" + boundary + "\n"
 
429
        data += "--" + boundary + "\r\n"
392
430
            + "Content-Disposition: form-data; name=\"" + arg_key
393
 
            + "\"\n\n"
394
 
            + arg_val + "\n";
 
431
            + "\"\r\n\r\n"
 
432
            + arg_val + "\r\n";
395
433
    }
396
434
 
397
435
    for (var arg_key in args)
406
444
            extend_data(arg_key, arg_val);
407
445
    }
408
446
    /* End boundary */
409
 
    data += "--" + boundary + "--\n";
 
447
    data += "--" + boundary + "--\r\n";
410
448
 
411
449
    return data;
412
450
}
431
469
    return path_join(root_dir, path);
432
470
}
433
471
 
434
 
/** Makes an XMLHttpRequest call to the server. Waits (synchronously) for a
435
 
 * response, and returns an XMLHttpRequest object containing the completed
436
 
 * response.
 
472
/** Shorthand for make_path(path_join(app, ...))
 
473
 * Creates an absolute path for a given path within a given app.
 
474
 */
 
475
function app_path(app /*,...*/)
 
476
{
 
477
    return make_path(path_join.apply(null, arguments));
 
478
}
 
479
 
 
480
/** Given a path, gets the "basename" (the last path segment).
 
481
 */
 
482
function path_basename(path)
 
483
{
 
484
    segments = path.split("/");
 
485
    if (segments[segments.length-1].length == 0)
 
486
        return segments[segments.length-2];
 
487
    else
 
488
        return segments[segments.length-1];
 
489
}
 
490
 
 
491
/** Given a string str, determines whether it ends with substr */
 
492
function endswith(str, substring)
 
493
{
 
494
    if (str.length < substring.length) return false;
 
495
    return str.substr(str.length - substring.length) == substring;
 
496
}
 
497
 
 
498
/** Equivalent to Python's repr.
 
499
 * Gets the JavaScript string representation.
 
500
 * Actually just calls JSON.stringify.
 
501
 */
 
502
function repr(str)
 
503
{
 
504
    return JSON.stringify(str);
 
505
}
 
506
 
 
507
/** Removes all occurences of a value from an array.
 
508
 */
 
509
Array.prototype.removeall = function(val)
 
510
{
 
511
    var i, j;
 
512
    var arr = this;
 
513
    j = 0;
 
514
    for (i=0; i<arr.length; i++)
 
515
    {
 
516
        arr[j] = arr[i];
 
517
        if (arr[i] != val) j++;
 
518
    }
 
519
    arr.splice(j, i-j);
 
520
}
 
521
 
 
522
/** Shallow-clones an object */
 
523
function shallow_clone_object(obj)
 
524
{
 
525
    o = {};
 
526
    for (k in obj)
 
527
        o[k] = obj[k];
 
528
    return o;
 
529
}
 
530
 
 
531
/** Returns a new XMLHttpRequest object, in a somewhat browser-agnostic
 
532
 * fashion.
 
533
 */
 
534
function new_xmlhttprequest()
 
535
{
 
536
    try
 
537
    {
 
538
        /* Real Browsers */
 
539
        return new XMLHttpRequest();
 
540
    }
 
541
    catch (e)
 
542
    {
 
543
        /* Internet Explorer */
 
544
        try
 
545
        {
 
546
            return new ActiveXObject("Msxml2.XMLHTTP");
 
547
        }
 
548
        catch (e)
 
549
        {
 
550
            try
 
551
            {
 
552
                return new ActiveXObject("Microsoft.XMLHTTP");
 
553
            }
 
554
            catch (e)
 
555
            {
 
556
                throw("Your browser does not support AJAX. "
 
557
                    + "IVLE requires a modern browser.");
 
558
            }
 
559
        }
 
560
    }
 
561
}
 
562
 
 
563
/** Makes an asynchronous XMLHttpRequest call to the server.
 
564
 * Sends the XMLHttpRequest object containing the completed response to a
 
565
 * specified callback function.
437
566
 *
 
567
 * \param callback A callback function. Will be called when the response is
 
568
 *      complete. Passed 1 parameter, an XMLHttpRequest object containing the
 
569
 *      completed response.
438
570
 * \param app IVLE app to call (such as "fileservice").
439
571
 * \param path URL path to make the request to, within the application.
440
572
 * \param args Argument object, as described in parse_url and friends.
442
574
 * \param content_type String, optional. Only applies if method is "POST".
443
575
 *      May be "application/x-www-form-urlencoded" or "multipart/form-data".
444
576
 *      Defaults to "application/x-www-form-urlencoded".
445
 
 * \return An XMLHttpRequest object containing the completed response.
446
577
 */
447
 
function ajax_call(app, path, args, method, content_type)
 
578
function ajax_call(callback, app, path, args, method, content_type)
448
579
{
449
580
    if (content_type != "multipart/form-data")
450
581
        content_type = "application/x-www-form-urlencoded";
451
 
    path = make_path(path_join(app, path));
 
582
    path = app_path(app, path);
452
583
    var url;
453
584
    /* A random string, for multipart/form-data
454
585
     * (This is not checked against anywhere else, it is solely defined and
455
586
     * used within this function) */
456
587
    var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
457
 
    var xhr = new XMLHttpRequest();
 
588
    var xhr = new_xmlhttprequest();
 
589
    xhr.onreadystatechange = function()
 
590
        {
 
591
            if (xhr.readyState == 4)
 
592
            {
 
593
                callback(xhr);
 
594
            }
 
595
        }
458
596
    if (method == "GET")
459
597
    {
460
598
        /* GET sends the args in the URL */
461
599
        url = build_url({"path": path, "args": args});
462
 
        /* open's 3rd argument = false -> SYNCHRONOUS (wait for response)
463
 
         * (No need for a callback function) */
464
 
        xhr.open(method, url, false);
 
600
        /* open's 3rd argument = true -> asynchronous */
 
601
        xhr.open(method, url, true);
465
602
        xhr.send(null);
466
603
    }
467
604
    else
468
605
    {
469
606
        /* POST sends the args in application/x-www-form-urlencoded */
470
607
        url = encodeURI(path);
471
 
        xhr.open(method, url, false);
 
608
        xhr.open(method, url, true);
472
609
        var message;
473
610
        if (content_type == "multipart/form-data")
474
611
        {
481
618
            xhr.setRequestHeader("Content-Type", content_type);
482
619
            message = make_query_string(args);
483
620
        }
 
621
        xhr.setRequestHeader("Content-Length", message.length);
484
622
        xhr.send(message);
485
623
    }
486
 
    return xhr;
487
624
}
488
625