File: hoogle.js

package info (click to toggle)
haskell-hoogle 5.0.1%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 504 kB
  • ctags: 37
  • sloc: haskell: 2,762; ansic: 110; sh: 33; xml: 20; makefile: 3
file content (414 lines) | stat: -rw-r--r-- 12,958 bytes parent folder | download
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

// PERHAPS I SHOULD BE USING Bootstrap with:
// http://silviomoreto.github.io/bootstrap-select/


var embed = false; // are we running as an embedded search box
var instant = true; // should we search on key presses
var query = parseQuery(); // what is the current query string

var $hoogle; // $("#hoogle") after load


/////////////////////////////////////////////////////////////////////
// SEARCHING

function on_arrow_press(ev) {
    var offset = 0;
    if (ev.keyCode == Key.Up) {
        offset = -1;
    } else if (ev.keyCode == Key.Down) {
        offset = +1;
    } else if (ev.keyCode != Key.Return) {
        return;
    }

    // Figure out where we are
    var results = $("div#body .result");
    var activeResults = $("div#body .result.active");
    var activeRow = -1;
    if (activeResults.length == 1) {
        activeRow = results.index(activeResults[0]);
    }

    if (ev.keyCode == Key.Return) {
        if (activeRow >= 0)
            document.location.href = $("a", activeResults).attr("href");
    } else {
        var newRow = activeRow + offset;
        var $activeRow = $(results[activeRow]);
        if (newRow < 0) {
            $activeRow.removeClass("active");
            $hoogle.focus();
        } else if (newRow < results.length) {
            var $newRow = $(results[newRow]);
            if (activeRow >= 0)
                $activeRow.removeClass("active");
            $newRow.addClass("active");
            $hoogle.blur();
        }
    }
}

$(function() {
    $(document).keyup(on_arrow_press);
});

$(function(){
    $hoogle = $("#hoogle");
    var $form = $hoogle.parents("form:first");
    var $scope = $form.find("[name=scope]");
    embed = !$hoogle.hasClass("HOOGLE_REAL");
    if (!embed) $scope.chosen({"search_contains":true});

    var self = embed ? newEmbed() : newReal();

    var ajaxUrl = !embed ? "?" : $form.attr("action") + "?";
    var ajaxMode = embed ? 'embed' : 'body';

    var active = $hoogle.val() + " " + $scope.val(); // What is currently being searched for (may not yet be displayed)
    var past = cache(100); // Cache of previous searches
    var watch = watchdog(500, function(){self.showWaiting();}); // Timeout of the "Waiting..." callback

    function hit(){
        if (!instant) return;
        function getScope(){return $scope && $scope.val() !== "set:stackage" ? $scope.val() : "";}

        var nowHoogle = $hoogle.val();
        var nowScope = getScope();
        var now = nowHoogle + " " + nowScope;
        if (now == active) return;
        active = now;

        var title = now + (now == " " ? "" : " - ") + "Hoogle";
        query["hoogle"] = nowHoogle;
        query["scope"] = nowScope;
        if (!embed){
            if (window.history)
                window.history.replaceState(null, title, renderQuery(query));
            $("title").text(title);
        }

        var old = past.ask(now);
        if (old != undefined){self.showResult(old); return;}

        watch.stop();
        if (embed && now == ""){self.hide(); return;}
        watch.start();

        var data = {hoogle:nowHoogle, scope:nowScope, mode:ajaxMode};
        function complete(e)
        {
            watch.stop();
            var current = $hoogle.val() + " " + getScope() == now;
            if (e.status == 200)
            {
                past.add(now,e.responseText);
                if (current)
                    self.showResult(e.responseText);
            }
            else if (current)
                self.showError(e.status, e.responseText);
        }

        var args = {url:ajaxUrl, data:data, complete:complete, dataType:"html"}
        try {
            $.ajax(args);
        } catch (err) {
            try {
                if (!embed) throw err;
                $.ajaxCrossDomain(args);
            } catch (err) {
                // Probably a permissions error from cross domain scripting...
                watch.stop();
            }
        }
    };
    $hoogle.keyup(hit);
    $scope.change(hit);
})

function newReal()
{
    $hoogle.focus();
    $hoogle.select();
    var $body = $("#body");

    return {
        showWaiting: function(){$("h1").text("Still working...");},
        showError: function(status,text){$body.html("<h1><b>Error:</b> status " + status + "</h1><p>" + text + "</p>")},
        showResult: function(text){$body.html(text); newDocs();}
    }
}

function newEmbed()
{
    $hoogle.attr("autocomplete","off");
    // IE note: unless the div in the iframe contain any border it doesn't calculate the correct outerHeight()
    //          therefore we put 3 borders on the iframe, and leave one for the bottom div
    var $iframe = $("<iframe id='hoogle-output' scrolling='no' "+
                    "style='position:absolute;border:1px solid rgb(127,157,185);border-bottom:0px;display:none;' />");
    var $body;
    $iframe.load(function(){
        var $contents = $iframe.contents();
        $contents.find("head").html(
            "<style type='text/css'>" +
            "html {border: 0px;}" +
            "body {font-family: sans-serif; font-size: 13px; background-color: white; padding: 0px; margin: 0px;}" +
            "a, i {display: block; color: black; padding: 1px 3px; text-decoration: none; white-space: nowrap; overflow: hidden; cursor: default;}" +
            "a.sel {background-color: rgb(10,36,106); color: white;}" +
            "div {border-bottom:1px solid rgb(127,157,185);}" +
            "</style>");
        $body = $("<div>").appendTo($contents.find("body"));
    });
    $iframe.insertBefore($hoogle);

    var finishOnBlur = true; // Should a blur hide the box

    function show(x){
        if (x == undefined)
            $iframe.css("display","none");
        else {
            $body.html(x).find("a").attr("target","_parent")
                .mousedown(function(){finishOnBlur = false;})
                .mouseup(function(){finishOnBlur = true;})
                .mouseenter(function(){
                    $body.find(".sel").removeClass("sel");
                    $(this).addClass("sel");
                });

            var pos = $hoogle.position();
            // need to display before using $body.outerHeight() on Firefox
            $iframe.css("display","").css(
                {top:px(pos.top + $hoogle.outerHeight() + unpx($hoogle.css("margin-top")))
                ,left:px(pos.left + unpx($hoogle.css("margin-left")))
                ,width:px($hoogle.outerWidth() - 2 /* iframe border */)
                ,height:$body.outerHeight()
                });
        }
    }

    $hoogle.blur(function(){if (finishOnBlur) show();});

    $hoogle.keydown(function(event){
        switch(event.which)
        {
        case Key.Return:
            var sel = $body.find(".sel:first");
            if (sel.size() == 0) return;
            event.preventDefault();
            document.location.href = sel.attr("href");
            break;

        case Key.Escape:
            $body.find(".sel").removeClass("sel");
            show();
            break;

        case Key.Down: case Key.Up:
            var i = event.which == Key.Down ? 1 : -1;
            var all = $body.find("a");
            var sel = all.filter(".sel");
            var now = all.index(sel);
            if (now == -1)
                all.filter(i == 1 ? ":first" : ":last").addClass("sel");
            else {
                sel.removeClass("sel");
                // IE treats :eq(-1) as :eq(0), so filter specifically
                if (now+i >= 0) all.filter(":eq(" + (now+i) + ")").addClass("sel");
            }
            event.preventDefault();
            break;
        }
    });

    return {
        showWaiting: function(){show("<i>Still working...</i>");},
        showError: function(status,text){show("<i>Error: status " + status + "</i>");},
        showResult: function(text){show(text);},
        hide: function(){show();}
    }
}


/////////////////////////////////////////////////////////////////////
// SEARCH PLUGIN

var prefixUrl = document.location.protocol + "//" + document.location.hostname + document.location.pathname;

$(function(){
    if (embed) return;
    if (prefixUrl != "http://hoogle.haskell.org/")
    {
        $("link[rel=search]").attr("href", function(){
            return this.href + "?domain=" + escape(prefixUrl);
        });
    }
    if (window.external && ("AddSearchProvider" in window.external))
        $("#plugin").css("display","");
});

function searchPlugin()
{
    var url = $("link[rel=search]").attr("href");
    if (url.substring(0, prefixUrl.length) != prefixUrl)
        url = prefixUrl + url;
    window.external.AddSearchProvider(url);
}


/////////////////////////////////////////////////////////////////////
// DOCUMENTATION

$(function(){
    if (embed) return;
    $(window).resize(resizeDocs);
    newDocs();
});

function resizeDocs()
{
    $("#body .doc").each(function(){
        // If a segment is open, it should remain open forever
        var $this = $(this);
        var toosmall = ($.support.preWrap && $this.hasClass("newline")) ||
                       ($this.height() < $this.children().height());
        if (toosmall && !$this.hasClass("open"))
            $this.addClass("shut");
        else if (!toosmall && $this.hasClass("shut"))
            $this.removeClass("shut");
    });
}

function newDocs()
{
    resizeDocs();
    $("#body .doc").click(function(){
        var $this = $(this);
        if ($this.hasClass("open") || $this.hasClass("shut"))
            $this.toggleClass("open").toggleClass("shut");
    });
}


/////////////////////////////////////////////////////////////////////
// iOS TWEAKS

$(function(){
    if ($.support.inputSearch)
        $("#hoogle")[0].type = "search";

    var qphone = query["phone"];
    phone =
        qphone == "0" ? false :
        qphone == "1" ? true :
        $.support.phone;

    if (!phone) return;
    $("body").addClass("phone");
    $("head").append("<meta name='viewport' content='width=device-width' />");
});


/////////////////////////////////////////////////////////////////////
// LIBRARY BITS

function parseQuery() // :: IO (Dict String String)
{
    // From http://stackoverflow.com/questions/901115/get-querystring-values-with-jquery/3867610#3867610
    var params = {},
        e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
        params[d(e[1])] = d(e[2]);

    return params;
}

function renderQuery(query) // Dict String String -> IO String
{
    var s = "";
    for (var i in query)
    {
        if (query[i] != "")
            s += (s == "" ? "?" : "&") + i + "=" + encodeURIComponent(query[i]);
    }
    return window.location.href.substring(0, window.location.href.length - window.location.search.length) + s;
}


// Supports white-space: pre-wrap;
$.support.preWrap = true;

$.support.iOS =
    (navigator.userAgent.indexOf("iPhone") != -1) ||
    (navigator.userAgent.indexOf("iPod") != -1) ||
    (navigator.userAgent.indexOf("iPad") != -1);

$.support.phone =
    (navigator.userAgent.indexOf("iPhone") != -1) ||
    (navigator.userAgent.indexOf("iPod") != -1) ||
    (navigator.userAgent.indexOf("Android") != -1);

// Supports <input type=search />
$.support.inputSearch = $.support.iOS;

var Key = {
    Up: 38,
    Down: 40,
    Return: 13,
    Escape: 27
};

function unpx(x){var r = 1 * x.replace("px",""); return isNaN(r) ? 0 : r;}
function px(x){return x + "px";}

function cache(maxElems)
{
    // FIXME: Currently does not evict things
    var contents = {}; // what we have in the cache, with # prepended
    // note that contents[toString] != undefined, since it's a default method
    // hence the leading #

    return {
        add: function(key,val)
        {
            contents["#" + key] = val;
        },
        
        ask: function(key)
        {
            return contents["#" + key];
        }
    };
}

function watchdog(time, fun)
{
    var id = undefined;
    function stop(){if (id == undefined) return; window.clearTimeout(id); id = undefined;}
    function start(){stop(); id = window.setTimeout(function(){id = undefined; fun();}, time);}
    return {start:start, stop:stop}
}

$.ajaxCrossDomain = function(args)
{
    if (!window.XDomainRequest) throw new Error("the XDomainRequest object is not supported in this browser");

    var xdr = new XDomainRequest();
    xdr.onload = function(){args.complete({status:200, responseText:xdr.responseText});};
    xdr.onerror = function(){args.complete({status:0, responseText:""});};

    var url = "";
    for (var i in args.data)
    {
        if (args.data[i] == undefined) continue;
        url += (url == "" ? "" : "&") + encodeURIComponent(i) + "=" + encodeURIComponent(args.data[i]);
    }
    xdr.open("get", args.url + url);
    xdr.send();
}