Debian Codegraph @

gavo/resources/web/js/gavo.js

raw
1 // javascript support code for the GAVO data center
2
3
4 ////////////////////////////// possibly generic functions
5
6 function decodeGetPars(queryString) {
7 // an incredibly crappy approach to getting whatever was in the query string
8 // into javascript.
9 var pars = new Object();
10 var pairs = queryString.slice(1).split("&");
11 for (var ind in pairs) {
12 var pair = pairs[ind].split("=");
13 var key = 'arg'+unescape(pair[0]).replace("+", " ");
14 var value = unescape(pair[1]).replace("+", " ");
15 if (pars[key]==undefined) {
16 pars[key] = new Array();
17 }
18 pars[key].push(value);
19 }
20 return pars;
21 }
22
23
24 function isIn(item, arr) {
25 // does a linear search through arr to see if item is in there
26 // (can't we use assoc. arrs for that?)
27 for (var ind in arr) {
28 if (arr[ind]==item) {
29 return true;
30 }
31 }
32 return false;
33 }
34
35
36 function getJD(date) {
37 return date/86400000+2440587.5;
38 }
39
40
41 function getJYear(date) {
42 return (getJD(date)-2451545)/365.25+2000;
43 }
44
45
46 ///////////// Micro templating. See develNotes
47 function htmlEscape(str) {
48 return String(str).replace(/&/g, '&').replace(/"/g, '"')
49 .replace(/'/g, '&apos;').replace(/</g, '&lt;')
50 .replace(/>/g, '&gt;');
51 }
52
53
54 function jqueryOrRaw(arg) {
55 return arg.html ? arg.html() : arg;
56 }
57
58
59 (function () {
60 var _tmplCache = {};
61 this.renderTemplate = function (templateId, data) {
62 var err = "";
63 var func = _tmplCache[templateId];
64 if (!func) {
65 str = document.getElementById(templateId).innerHTML;
66 var strFunc =
67 "var p=[],print=function(){p.push.apply(p,arguments);};"
68 + "with(obj){p.push('"
69 + str.replace(/[\r\t\n]/g, " ")
70 .split("'").join("\\'")
71 .split("\t").join("'")
72 .replace(/\$([a-zA-Z_]+)/g, "',htmlEscape($1),'")
73 .replace(/\$!([a-zA-Z_]+)/g, "',jqueryOrRaw($1),'")
74 + "');}return $.trim(p.join(''));";
75 func = new Function("obj", strFunc);
76 _tmplCache[str] = func;
77 }
78 return func(data);
79 }
80 })()
81
82
83
84
85 ///////////// Code for generating GET-URLs for forms
86
87 function getEnclosingForm(element) {
88 // returns the form element immediately enclosing element.
89 if (element.nodeName=="FORM") {
90 return element;
91 }
92 return getEnclosingForm(element.parentNode);
93 }
94
95 function getSelectedEntries(selectElement) {
96 // returns an array of all selected entries from a select element
97 // in url encoded form
98 var result = new Array();
99 var i;
100
101 for (i=0; i<selectElement.length; i++) {
102 if (selectElement.options[i].selected) {
103 result.push(selectElement.name+"="+encodeURIComponent(
104 selectElement.options[i].value))
105 }
106 }
107 return result;
108 }
109
110 function makeQueryItem(element, keepEmpties) {
111 // returns an url-encoded query tag item out of a form element
112 var val=null;
113
114 switch (element.nodeName.toUpperCase()) {
115 case "INPUT":
116 case "TEXTAREA":
117 if (element.type=="radio" || element.type=="checkbox") {
118 if (element.checked) {
119 val = element.name+"="+encodeURIComponent(element.value);
120 }
121 } else if (element.name) {
122 if (element.value || keepEmpties) {
123 val = element.name+"="+encodeURIComponent(element.value);
124 }
125 }
126 break;
127 case "SELECT":
128 return getSelectedEntries(element).join("&");
129 break;
130 case "BUTTON": // no state here
131 break;
132 default:
133 alert("No handler for "+element.nodeName);
134 }
135 if (val) {
136 return val;
137 } else {
138 return element.NodeName;
139 }
140 }
141
142
143 function completeURL(uriOrPath) {
144 // guesses whether uriOrPath has a host part and adds the
145 // current one if necessary.
146 // This for now does not support relative paths.
147 if (uriOrPath[0]=="/") {
148 return window.location.protocol+"//"+window.location.host+uriOrPath;
149 }
150 return uriOrPath;
151 }
152
153 function getFormQuery(form, ignoreNames, keepEmpties) {
154 // returns a link to the result sending the HTML form form would
155 // yield.
156 var fragments = new Array();
157 var i;
158
159 items = form.elements;
160 for (i=0; i<items.length; i++) {
161 var fragment = makeQueryItem(items[i], keepEmpties);
162 if (fragment && ignoreNames[items[i].name]==undefined) {
163 fragments.push(fragment);
164 }
165 }
166 return completeURL(form.getAttribute("action")+"?"+fragments.join("&"));
167 }
168
169
170 function makeResultLink(form) {
171 return getFormQuery(form, []);
172 }
173
174
175 function makeBookmarkLink(form) {
176 return getFormQuery(form, {'__nevow_form__': 1});
177 }
178
179
180 ///////////// Functions for the sidebar
181
182 function followEmbeddedLink(parent) {
183 // forwards the browser to the href of the first child that has one.
184 // this is for the button-type decoration around links.
185 for (index in parent.childNodes) {
186 child = parent.childNodes[index];
187 if (child.href) {
188 window.location = child.href;
189 break;
190 }
191 }
192 }
193
194 ///////////// letting people bookmark anchors
195
196 function _add_anchor(ev) {
197 var anchor = document.createElement("a");
198 anchor.setAttribute("class", "linkAnchor");
199 anchor.innerHTML = "¶";
200 anchor.href = "#"+this.id;
201 this.appendChild(anchor);
202 }
203
204
205 function _remove_anchor(ev) {
206 var parent = this;
207 parent.querySelectorAll(".linkAnchor").forEach(
208 function(c) {
209 parent.removeChild(c);
210 });
211 }
212
213
214 function _add_anchor_shower(el) {
215 if (el.id) {
216 el.addEventListener("mouseenter", _add_anchor);
217 el.addEventListener("mouseleave", _remove_anchor);
218 }
219 }
220
221 function add_anchors_to_heads() {
222 // adds linkable anchors to all h? elements with ids.
223 // this is supposed to be run from a document.ready callback.
224 document.querySelectorAll("h1,h2,h3,h4,h5"
225 ).forEach(_add_anchor_shower);
226 }
227
228
229 ///////////// Functions dealing with the output format widget
230 // This incredibly verbose crap hides and shows widgets selecting aspects
231 // of the output format. Basically, you have widgets in output_bussedElements
232 // that get notified when the output format changes and then (un)attach
233 // themselves to a container.
234 //
235 // To use this, you need:
236 // * a block element with id "genForm-_OUTPUT" in which the subwidgets are
237 // displayed
238 // * a form element calling output_broadcast(this.value) on a change
239 //
240 // In the DC, the static QueryMeta method getOutputWidget worries about this.
241
242
243 function output_BussedElement(domNode, id, visibleFor) {
244 // An element that can be passed to output_broadcast and does something
245 // in response.
246 domNode.id = id;
247 for (var ind in visibleFor) {
248 domNode["visibleFor_"+visibleFor[ind]] = true;
249 }
250 return domNode;
251 }
252
253
254 function output_verbSelector(pars) {
255 // returns a BussedElement for the selector for output verbosity
256 var verbosities = new Array("H", "1", "2", "3");
257 var root = document.createElement("span")
258 var sel = document.createElement("select");
259 var curSetting;
260
261 root["class"] = "op_widget";
262 root.appendChild(document.createTextNode(" output verbosity "));
263 sel.name = "_VERB";
264 if (pars['arg'+sel.name]!=undefined) {
265 curSetting = pars['arg'+sel.name][0];
266 } else {
267 curSetting = "H";
268 }
269 for (verbInd in verbosities) {
270 var el = sel.appendChild(document.createElement("option"));
271 var verb = verbosities[verbInd];
272 el.appendChild(document.createTextNode(verb));
273 if (verb==curSetting) {
274 el.selected = "selected";
275 }
276 }
277 root.appendChild(sel);
278 return output_BussedElement(root, "op_verb", ["VOTable", "FITS",
279 "CSV", "TSV", "JSON"]);
280 }
281
282
283 function output_tdEncSelector(pars) {
284 // returns a BussedElement to select VOTable encoding
285 var root = document.createElement("span");
286 var box = document.createElement("input");
287 var curSetting;
288
289 root["class"] = "op_widget";
290 box.name = "_TDENC";
291 if (pars['arg'+box.name]!=undefined) {
292 curSetting = pars['arg'+box.name][0];
293 } else {
294 curSetting = "false";
295 }
296 box.type = "checkbox";
297 box.style.width = "auto";
298 root.appendChild(box);
299 root.appendChild(document.createTextNode(" human-readable "));
300 if (curSetting=="true") {
301 box.checked = "checked";
302 }
303 return output_BussedElement(root, "op_tdenc", ["VOTable"]);
304 }
305
306
307 function output_setFormat(format) {
308 var opts=document.getElementById("genForm-_FORMAT").options;
309 for (var optInd=0; optInd<opts.length; optInd++) {
310 if (opts[optInd].value==format) {
311 opts[optInd].selected = true;
312 } else {
313 opts[optInd].selected = false;
314 }
315 }
316 }
317
318 var output_bussedElements = new Array();
319
320
321 function output_init() {
322 var pars = decodeGetPars(location.search);
323 var format = pars["arg_FORMAT"];
324
325 if (!document.getElementById("genForm-_OUTPUT")) { // no form on page
326 return;
327 }
328 output_bussedElements.push(output_verbSelector(pars));
329 output_bussedElements.push(output_tdEncSelector(pars));
330
331 let itemSelector = output_itemSelector(pars);
332 if (itemSelector) {
333 output_bussedElements.push(itemSelector);
334 }
335 if (format==undefined) {
336 format = "HTML";
337 }
338 output_broadcast(format);
339 outputInited = true;
340 }
341
342 function output_broadcast(newFormat) {
343 var visibleForThis = "visibleFor_"+newFormat;
344
345 output_setFormat(newFormat);
346 for (var ind in output_bussedElements) {
347 var el=output_bussedElements[ind];
348 if (el[visibleForThis]) {
349 output_show(el);
350 } else {
351 output_hide(el);
352 }
353 }
354 }
355
356 function init_preview_observer() {
357 // create an observer for lazy image loading (so far used for
358 // previews only.
359 if (IntersectionObserver) {
360 var previewObserver = new IntersectionObserver(
361 function(entries, obs) {
362 entries.forEach(function(item) {
363 if (item.isIntersecting) {
364 insertPreview(item.target);
365 obs.unobserve(item.target);
366 }
367 },
368 {'threshold': 2});
369 });
370
371 document.querySelectorAll(".productlink").forEach(
372 function(node) {previewObserver.observe(node)});
373 }
374 }
375
376
377 ///////////////// UI extensions
378
379 function enableMLMenu(menuRoot, selectHandler) {
380 // makes a hierarchical popup menu from a nested ul/li structure.
381 // menuRoot is a piece of DOM with the ul/li-s.
382 // Furnish clickable li-s with a data-value attribute.
383 // The selectHandler receives that value if one has been clicked
384 // (plus the underlying event for special effects).
385 // menuRoot is hidden anyway.
386 // The function returns a function that pops up the menu and arranges
387 // for it to be popped down again (and of course to call selectHandler
388 // as appropriate).
389 // There's example code for this in wirr.
390
391 // make ul-s that are children of li-s to pop out things
392 for (const node of menuRoot.querySelectorAll("li")) {
393 if (node.querySelector("ul")) {
394 // there's a submenu here, amend the last text node if necessary
395 let textNode = null;
396 for (child of node.childNodes) {
397 if (child.nodeType === Node.TEXT_NODE) {
398 textNode = child;
399 }
400 }
401 if (textNode && !textNode.textContent.endsWith("➤")) {
402 textNode.textContent = textNode.textContent+" ➤";
403 }
404 }
405 }
406
407 let popDown = (ev) => {
408 try {
409 let selected = ev.target.closest("li[data-value]");
410 if (selected) {
411 selectHandler(selected.dataset.value, ev);
412 }
413 } finally {
414 menuRoot.style.display = 'none';
415 }
416
417 }
418
419 return () => {
420 menuRoot.style.display = 'block';
421 document.addEventListener("click",
422 popDown,
423 {capture: true, once: true});
424 }
425 }
426
427
428 ///////////////// jquery-dependent code
429
430
431 $(document).ready(
432 function() {
433 output_init();
434 init_preview_observer();
435 add_anchors_to_heads();
436 });
437
438
439 function makeTabCallback(handlers) {
440 // see develNotes
441 return function (ev) {
442 $("#tabset_tabs > li").removeClass("selected");
443 var curTab = $(ev.currentTarget);
444 curTab.addClass("selected");
445 var mainId = curTab.find("a").attr("name");
446 handlers[mainId]($('#mainbox'));
447 }
448 }
449
450 function popupInnerWindow(content, parent, onClose) {
451 // puts content into a thing that looks like a window and can be
452 // dragged and resized. Parent is the element the container
453 // gets added to within the tree.
454 // The function returns a closer function destroying the subwindow.
455 // This is only used in output_popupAddSel, and it shouldn't be
456 // used any more. Let's use some more modern thing (e.g., what's used
457 // in flotplot) in the future and port output_popupAddSel to that.
458 var prevParent = content.parent()
459 prevParent.css({"position": "relative"});
460
461 var container = $("<div class='innerWin'/>");
462 var titlebar = $(
463 "<p class='innerTitle'><span class='closer'>x&nbsp;</span></p>");
464 container.append(titlebar);
465 container.append(content);
466 content.addClass("innerBody");
467 content.show();
468
469 container.draggable({cancel: ".innerBody"});
470 parent.append(container);
471 // XXX TODO: Why doesn't container expand to content size in the first place?
472 container.css({"width": content.width(),
473 "height": content.height()+titlebar.height(),
474 "position": "relative"});
475
476 closer = function(ignored) {
477 container.hide();
478 container.detach();
479 content.hide();
480 onClose();
481 }
482
483 container.find(".closer").bind("click", closer);
484 return closer;
485 }
486
487
488 function output_popupAddSel(additemsSelection) {
489 // pops up the dialog with the additional output items. The popup
490 // receives a cleanup function.
491 // The trick here is that the selector (that has display:none outside
492 // or the popup) needs to be added back to the form so it gets evaluated;
493 // but it needs to be detached while shown in the window.
494 var govButton = output_bussedElements[2];
495 additemsSelection.detach();
496
497 var closer = popupInnerWindow(
498 additemsSelection,
499 $("#genForm-_OUTPUT"),
500 function() {
501 govButton.unbind("click");
502 govButton.bind("click", function() {
503 output_popupAddSel(additemsSelection)});
504 govButton.empty().append("More output fields");
505 govButton.parent().append(additemsSelection);
506 });
507 govButton.unbind("click");
508 govButton.bind("click", closer);
509 govButton.empty().append("Pop down field selector");
510 return false;
511 }
512
513
514 function output_itemSelector(pars) {
515 // returns a Bussedelement to pop up the element Selector if
516 // there are items to select.
517 var itemSelector = $("#genForm-_ADDITEMS");
518 if (! itemSelector) {
519 return null;
520 }
521 itemSelector.detach();
522
523 var opener = $(`<button type="button" id="op_additem" class="popButton"
524 >More output fields</button>`);
525 opener.bind("click", () => output_popupAddSel(itemSelector));
526 res = output_BussedElement(opener, "op_additem", ["HTML"]);
527 return res;
528 }
529
530
531 function output_show(el) {
532 if (!document.getElementById(el.id)) {
533 var dest = $("#genForm-_OUTPUT");
534 dest.append(document.createTextNode(" "));
535 dest.append(el);
536 }
537 }
538
539 function output_hide(el) {
540 if (document.getElementById(el.id)) {
541 $(el).detach();
542 }
543 }
544
545
546 function openFlotPlot(tableElement, options) {
547 // loads the flot plotting code; this stub will be overrwritten as
548 // flotplot.js is loaded.
549 $.getScript("/static/js/flotplot.js",
550 function() {openFlotPlot(tableElement, options)}
551 ).fail(function() {
552 alert("Loading the plotting code failed; please complain to the operators")});
553 }
554
555
556 function insertPreview(node, width) {
557 // replaces the text content of node with a DC-generated preview
558 // image. node has to have a href attribute pointing to a DC
559 // FITS product for this to work (width is ignored these days).
560 if (!node.getAttribute("href")) {
561 return;
562 }
563
564 if (width==undefined) {
565 width = 200;
566 }
567
568 var oldHref = node.getAttribute("href");
569 var newPars = "preview=True&width="+width;
570 var joiner = "?";
571 // TODO: do actual URL parsing here
572 if (oldHref.indexOf("?")!=-1) { // assume we have a query
573 joiner = "&";
574 }
575
576 // IE9 workaround: defuse onmouseover before removing it.
577 node.setAttribute("onmouseover", "");
578 node.removeAttribute("onmouseover");
579 var jqNode = $(node);
580 jqNode.addClass("busy");
581
582 var previewURL = oldHref+joiner+newPars;
583 var img = $("<img class='preview'/>").attr("src", previewURL
584 ).attr("alt", "[preview image]");
585
586 img.bind("load", function() {
587 jqNode.prepend($("<br/>"));
588 jqNode.prepend(img[0], node.firstChild);
589 jqNode.removeClass("busy");
590 });
591 // TODO: use "complete" here when we've updated jquery
592 img.bind("error", function() {
593 jqNode.removeClass("busy");
594 });
595 }
596
597