libtoaster.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. "use strict";
  2. /* All shared functionality to go in libtoaster object.
  3. * This object really just helps readability since we can then have
  4. * a traceable namespace.
  5. */
  6. var libtoaster = (function () {
  7. // prevent conflicts with Bootstrap 2's typeahead (required during
  8. // transition from v2 to v3)
  9. var typeahead = jQuery.fn.typeahead.noConflict();
  10. jQuery.fn._typeahead = typeahead;
  11. /* Make a typeahead from an input element
  12. *
  13. * _makeTypeahead parameters
  14. * jQElement: input element as selected by $('selector')
  15. * xhrUrl: the url to get the JSON from; this URL should return JSON in the
  16. * format:
  17. * { "results": [ { "name": "test", "detail" : "a test thing" }, ... ] }
  18. * xhrParams: the data/parameters to pass to the getJSON url e.g.
  19. * { 'type' : 'projects' }; the text typed will be passed as 'search'.
  20. * selectedCB: function to call once an item has been selected; has
  21. * signature selectedCB(item), where item is an item in the format shown
  22. * in the JSON list above, i.e.
  23. * { "name": "name", "detail": "detail" }.
  24. */
  25. function _makeTypeahead(jQElement, xhrUrl, xhrParams, selectedCB) {
  26. if (!xhrUrl || xhrUrl.length === 0) {
  27. throw("No url supplied for typeahead");
  28. }
  29. var xhrReq;
  30. jQElement._typeahead(
  31. {
  32. highlight: true,
  33. classNames: {
  34. open: "dropdown-menu",
  35. cursor: "active"
  36. }
  37. },
  38. {
  39. source: function (query, syncResults, asyncResults) {
  40. xhrParams.search = query;
  41. // if we have a request in progress, cancel it and start another
  42. if (xhrReq) {
  43. xhrReq.abort();
  44. }
  45. xhrReq = $.getJSON(xhrUrl, xhrParams, function (data) {
  46. if (data.error !== "ok") {
  47. console.error("Error getting data from server: " + data.error);
  48. return;
  49. }
  50. xhrReq = null;
  51. asyncResults(data.results);
  52. });
  53. },
  54. // how the selected item is shown in the input
  55. display: function (item) {
  56. return item.name;
  57. },
  58. templates: {
  59. // how the item is displayed in the dropdown
  60. suggestion: function (item) {
  61. var elt = document.createElement("div");
  62. elt.innerHTML = item.name + " " + item.detail;
  63. return elt;
  64. }
  65. }
  66. }
  67. );
  68. // when an item is selected using the typeahead, invoke the callback
  69. jQElement.on("typeahead:select", function (event, item) {
  70. selectedCB(item);
  71. });
  72. }
  73. /* startABuild:
  74. * url: xhr_buildrequest or null for current project
  75. * targets: an array or space separated list of targets to build
  76. * onsuccess: callback for successful execution
  77. * onfail: callback for failed execution
  78. */
  79. function _startABuild (url, targets, onsuccess, onfail) {
  80. if (!url)
  81. url = libtoaster.ctx.xhrBuildRequestUrl;
  82. /* Flatten the array of targets into a space spearated list */
  83. if (targets instanceof Array){
  84. targets = targets.reduce(function(prevV, nextV){
  85. return prev + ' ' + next;
  86. });
  87. }
  88. $.ajax( {
  89. type: "POST",
  90. url: url,
  91. data: { 'targets' : targets },
  92. headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
  93. success: function (_data) {
  94. if (_data.error !== "ok") {
  95. console.warn(_data.error);
  96. } else {
  97. if (onsuccess !== undefined) onsuccess(_data);
  98. }
  99. },
  100. error: function (_data) {
  101. console.warn("Call failed");
  102. console.warn(_data);
  103. if (onfail) onfail(data);
  104. } });
  105. }
  106. /* cancelABuild:
  107. * url: xhr_buildrequest url or null for current project
  108. * buildRequestIds: space separated list of build request ids
  109. * onsuccess: callback for successful execution
  110. * onfail: callback for failed execution
  111. */
  112. function _cancelABuild(url, buildRequestIds, onsuccess, onfail){
  113. if (!url)
  114. url = libtoaster.ctx.xhrBuildRequestUrl;
  115. $.ajax( {
  116. type: "POST",
  117. url: url,
  118. data: { 'buildCancel': buildRequestIds },
  119. headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
  120. success: function (_data) {
  121. if (_data.error !== "ok") {
  122. console.warn(_data.error);
  123. } else {
  124. if (onsuccess) onsuccess(_data);
  125. }
  126. },
  127. error: function (_data) {
  128. console.warn("Call failed");
  129. console.warn(_data);
  130. if (onfail) onfail(_data);
  131. }
  132. });
  133. }
  134. function _getMostRecentBuilds(url, onsuccess, onfail) {
  135. $.ajax({
  136. url: url,
  137. type: 'GET',
  138. data : {format: 'json'},
  139. headers: {'X-CSRFToken': $.cookie('csrftoken')},
  140. success: function (data) {
  141. onsuccess ? onsuccess(data) : console.log(data);
  142. },
  143. error: function (data) {
  144. onfail ? onfail(data) : console.error(data);
  145. }
  146. });
  147. }
  148. /* Get a project's configuration info */
  149. function _getProjectInfo(url, onsuccess, onfail){
  150. $.ajax({
  151. type: "GET",
  152. data : { format: "json" },
  153. url: url,
  154. headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
  155. success: function (_data) {
  156. if (_data.error !== "ok") {
  157. console.warn(_data.error);
  158. } else {
  159. if (onsuccess !== undefined) onsuccess(_data);
  160. }
  161. },
  162. error: function (_data) {
  163. console.warn(_data);
  164. if (onfail) onfail(_data);
  165. }
  166. });
  167. }
  168. /* Properties for data can be:
  169. * layerDel (csv)
  170. * layerAdd (csv)
  171. * projectName
  172. * projectVersion
  173. * machineName
  174. */
  175. function _editCurrentProject(data, onSuccess, onFail){
  176. $.ajax({
  177. type: "POST",
  178. url: libtoaster.ctx.projectPageUrl + "?format=json",
  179. data: data,
  180. headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
  181. success: function (data) {
  182. if (data.error != "ok") {
  183. console.log(data.error);
  184. if (onFail !== undefined)
  185. onFail(data);
  186. } else {
  187. if (onSuccess !== undefined)
  188. onSuccess(data);
  189. }
  190. },
  191. error: function (data) {
  192. console.log("Call failed");
  193. console.log(data);
  194. }
  195. });
  196. }
  197. function _getLayerDepsForProject(url, onSuccess, onFail){
  198. /* Check for dependencies not in the current project */
  199. $.getJSON(url,
  200. { format: 'json' },
  201. function(data) {
  202. if (data.error != "ok") {
  203. console.log(data.error);
  204. if (onFail !== undefined)
  205. onFail(data);
  206. } else {
  207. var deps = {};
  208. /* Filter out layer dep ids which are in the
  209. * project already.
  210. */
  211. deps.list = data.layerdeps.list.filter(function(layerObj){
  212. return (data.projectlayers.lastIndexOf(layerObj.id) < 0);
  213. });
  214. onSuccess(deps);
  215. }
  216. }, function() {
  217. console.log("E: Failed to make request");
  218. });
  219. }
  220. /* parses the query string of the current window.location to an object */
  221. function _parseUrlParams() {
  222. var string = window.location.search;
  223. string = string.substr(1);
  224. var stringArray = string.split ("&");
  225. var obj = {};
  226. for (var i in stringArray) {
  227. var keyVal = stringArray[i].split ("=");
  228. obj[keyVal[0]] = keyVal[1];
  229. }
  230. return obj;
  231. }
  232. /* takes a flat object and outputs it as a query string
  233. * e.g. the output of dumpsUrlParams
  234. */
  235. function _dumpsUrlParams(obj) {
  236. var str = "?";
  237. for (var key in obj){
  238. if (!obj[key])
  239. continue;
  240. str += key+ "="+obj[key].toString();
  241. str += "&";
  242. }
  243. /* Maintain the current hash */
  244. str += window.location.hash;
  245. return str;
  246. }
  247. function _addRmLayer(layerObj, add, doneCb){
  248. if (add === true) {
  249. /* If adding get the deps for this layer */
  250. libtoaster.getLayerDepsForProject(layerObj.layerdetailurl,
  251. function (layers) {
  252. /* got result for dependencies */
  253. if (layers.list.length === 0){
  254. var editData = { layerAdd : layerObj.id };
  255. libtoaster.editCurrentProject(editData, function() {
  256. doneCb([]);
  257. });
  258. return;
  259. } else {
  260. try {
  261. showLayerDepsModal(layerObj, layers.list, null, null, true, doneCb);
  262. } catch (e) {
  263. $.getScript(libtoaster.ctx.jsUrl + "layerDepsModal.js", function(){
  264. showLayerDepsModal(layerObj, layers.list, null, null, true, doneCb);
  265. }, function(){
  266. console.warn("Failed to load layerDepsModal");
  267. });
  268. }
  269. }
  270. }, null);
  271. } else if (add === false) {
  272. var editData = { layerDel : layerObj.id };
  273. libtoaster.editCurrentProject(editData, function () {
  274. doneCb([]);
  275. }, function () {
  276. console.warn ("Removing layer from project failed");
  277. doneCb(null);
  278. });
  279. }
  280. }
  281. function _makeLayerAddRmAlertMsg(layer, layerDepsList, add) {
  282. var alertMsg;
  283. if (layerDepsList.length > 0 && add === true) {
  284. alertMsg = $("<span>You have added <strong>"+(layerDepsList.length+1)+"</strong> layers to your project: <a class=\"alert-link\" id=\"layer-affected-name\"></a> and its dependencies </span>");
  285. /* Build the layer deps list */
  286. layerDepsList.map(function(layer, i){
  287. var link = $("<a class=\"alert-link\"></a>");
  288. link.attr("href", layer.layerdetailurl);
  289. link.text(layer.name);
  290. link.tooltip({title: layer.tooltip});
  291. if (i !== 0)
  292. alertMsg.append(", ");
  293. alertMsg.append(link);
  294. });
  295. } else if (layerDepsList.length === 0 && add === true) {
  296. alertMsg = $("<span>You have added <strong>1</strong> layer to your project: <a class=\"alert-link\" id=\"layer-affected-name\"></a></span></span>");
  297. } else if (add === false) {
  298. alertMsg = $("<span>You have removed <strong>1</strong> layer from your project: <a class=\"alert-link\" id=\"layer-affected-name\"></a></span>");
  299. }
  300. alertMsg.children("#layer-affected-name").text(layer.name);
  301. alertMsg.children("#layer-affected-name").attr("href", layer.layerdetailurl);
  302. return alertMsg.html();
  303. }
  304. function _showChangeNotification(message){
  305. var alertMsg = $("#change-notification-msg");
  306. alertMsg.html(message);
  307. $("#change-notification, #change-notification *").fadeIn();
  308. }
  309. function _createCustomRecipe(name, baseRecipeId, doneCb){
  310. var data = {
  311. 'name' : name,
  312. 'project' : libtoaster.ctx.projectId,
  313. 'base' : baseRecipeId,
  314. };
  315. $.ajax({
  316. type: "POST",
  317. url: libtoaster.ctx.xhrCustomRecipeUrl,
  318. data: data,
  319. headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
  320. success: function (ret) {
  321. if (doneCb){
  322. doneCb(ret);
  323. } else if (ret.error !== "ok") {
  324. console.warn(ret.error);
  325. }
  326. },
  327. error: function (ret) {
  328. console.warn("Call failed");
  329. console.warn(ret);
  330. }
  331. });
  332. }
  333. /* Validate project names. Use unique project names
  334. All arguments accepted by this function are JQeury objects.
  335. For example if the HTML element has "hint-error-project-name", then
  336. it is passed to this function as $("#hint-error-project-name").
  337. Arg1 - projectName : This is a string object. In the HTML, project name will be entered here.
  338. Arg2 - hintEerror : This is a jquery object which will accept span which throws error for
  339. duplicate project
  340. Arg3 - ctrlGrpValidateProjectName : This object holds the div with class "control-group"
  341. Arg4 - enableOrDisableBtn : This object will help the API to enable or disable the form.
  342. For example in the new project the create project button will be hidden if the
  343. duplicate project exist. Similarly in the projecttopbar the save button will be
  344. disabled if the project name already exist.
  345. Return - This function doesn't return anything. It sets/unsets the behavior of the elements.
  346. */
  347. function _makeProjectNameValidation(projectName, hintError,
  348. ctrlGrpValidateProjectName, enableOrDisableBtn ) {
  349. function checkProjectName(projectName){
  350. $.ajax({
  351. type: "GET",
  352. url: libtoaster.ctx.projectsTypeAheadUrl,
  353. data: { 'search' : projectName },
  354. headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
  355. success: function(data){
  356. if (data.results.length > 0 &&
  357. data.results[0].name === projectName) {
  358. // This project name exists hence show the error and disable
  359. // the save button
  360. ctrlGrpValidateProjectName.addClass('has-error');
  361. hintError.show();
  362. enableOrDisableBtn.attr('disabled', 'disabled');
  363. } else {
  364. ctrlGrpValidateProjectName.removeClass('has-error');
  365. hintError.hide();
  366. enableOrDisableBtn.removeAttr('disabled');
  367. }
  368. },
  369. error: function (data) {
  370. console.log(data);
  371. },
  372. });
  373. }
  374. /* The moment user types project name remove the error */
  375. projectName.on("input", function() {
  376. var projectName = $(this).val();
  377. checkProjectName(projectName)
  378. });
  379. /* Validate new project name */
  380. projectName.on("blur", function(){
  381. var projectName = $(this).val();
  382. checkProjectName(projectName)
  383. });
  384. }
  385. return {
  386. reload_params : reload_params,
  387. startABuild : _startABuild,
  388. cancelABuild : _cancelABuild,
  389. getMostRecentBuilds: _getMostRecentBuilds,
  390. makeTypeahead : _makeTypeahead,
  391. getProjectInfo: _getProjectInfo,
  392. getLayerDepsForProject : _getLayerDepsForProject,
  393. editCurrentProject : _editCurrentProject,
  394. debug: false,
  395. parseUrlParams : _parseUrlParams,
  396. dumpsUrlParams : _dumpsUrlParams,
  397. addRmLayer : _addRmLayer,
  398. makeLayerAddRmAlertMsg : _makeLayerAddRmAlertMsg,
  399. showChangeNotification : _showChangeNotification,
  400. createCustomRecipe: _createCustomRecipe,
  401. makeProjectNameValidation: _makeProjectNameValidation,
  402. };
  403. })();
  404. /* keep this in the global scope for compatability */
  405. function reload_params(params) {
  406. var uri = window.location.href;
  407. var splitlist = uri.split("?");
  408. var url = splitlist[0];
  409. var parameters = splitlist[1];
  410. // deserialize the call parameters
  411. var cparams = [];
  412. if(parameters)
  413. cparams = parameters.split("&");
  414. var nparams = {};
  415. for (var i = 0; i < cparams.length; i++) {
  416. var temp = cparams[i].split("=");
  417. nparams[temp[0]] = temp[1];
  418. }
  419. // update parameter values
  420. for (i in params) {
  421. nparams[encodeURIComponent(i)] = encodeURIComponent(params[i]);
  422. }
  423. // serialize the structure
  424. var callparams = [];
  425. for (i in nparams) {
  426. callparams.push(i+"="+nparams[i]);
  427. }
  428. window.location.href = url+"?"+callparams.join('&');
  429. }
  430. /* Things that happen for all pages */
  431. $(document).ready(function() {
  432. var ajaxLoadingTimer;
  433. /* If we don't have a console object which might be the case in some
  434. * browsers, no-op it to avoid undefined errors.
  435. */
  436. if (!window.console) {
  437. window.console = {};
  438. window.console.warn = function() {};
  439. window.console.error = function() {};
  440. }
  441. /*
  442. * PrettyPrint plugin.
  443. *
  444. */
  445. // Init
  446. prettyPrint();
  447. // Prevent invalid links from jumping page scroll
  448. $('a[href=#]').click(function() {
  449. return false;
  450. });
  451. /* START TODO Delete this section now redundant */
  452. /* Belen's additions */
  453. // turn Edit columns dropdown into a multiselect menu
  454. $('.dropdown-menu input, .dropdown-menu label').click(function(e) {
  455. e.stopPropagation();
  456. });
  457. // enable popovers in any table cells that contain an anchor with the
  458. // .btn class applied, and make sure popovers work on click, are mutually
  459. // exclusive and they close when your click outside their area
  460. $('html').click(function(){
  461. $('td > a.btn').popover('hide');
  462. });
  463. $('td > a.btn').popover({
  464. html:true,
  465. placement:'left',
  466. container:'body',
  467. trigger:'manual'
  468. }).click(function(e){
  469. $('td > a.btn').not(this).popover('hide');
  470. // ideally we would use 'toggle' here
  471. // but it seems buggy in our Bootstrap version
  472. $(this).popover('show');
  473. e.stopPropagation();
  474. });
  475. // enable tooltips for applied filters
  476. $('th a.btn-primary').tooltip({container:'body', html:true, placement:'bottom', delay:{hide:1500}});
  477. // hide applied filter tooltip when you click on the filter button
  478. $('th a.btn-primary').click(function () {
  479. $('.tooltip').hide();
  480. });
  481. /* Initialise bootstrap tooltips */
  482. $(".get-help, [data-toggle=tooltip]").tooltip({
  483. container : 'body',
  484. html : true,
  485. delay: { show : 300 }
  486. });
  487. // show help bubble on hover inside tables
  488. $("table").on("mouseover", "th, td", function () {
  489. $(this).find(".hover-help").css("visibility","visible");
  490. });
  491. $("table").on("mouseleave", "th, td", function () {
  492. $(this).find(".hover-help").css("visibility","hidden");
  493. });
  494. /* END TODO Delete this section now redundant */
  495. // show task type and outcome in task details pages
  496. $(".task-info").tooltip({ container: 'body', html: true, delay: {show: 200}, placement: 'right' });
  497. // initialise the tooltips for the edit icons
  498. $(".glyphicon-edit").tooltip({ container: 'body', html: true, delay: {show: 400}, title: "Change" });
  499. // initialise the tooltips for the download icons
  500. $(".icon-download-alt").tooltip({ container: 'body', html: true, delay: { show: 200 } });
  501. // initialise popover for debug information
  502. $(".glyphicon-info-sign").popover( { placement: 'bottom', html: true, container: 'body' });
  503. // linking directly to tabs
  504. $(function(){
  505. var hash = window.location.hash;
  506. $('ul.nav a[href="' + hash + '"]').tab('show');
  507. $('.nav-tabs a').click(function () {
  508. $(this).tab('show');
  509. $('body').scrollTop();
  510. });
  511. });
  512. // toggle for long content (variables, python stack trace, etc)
  513. $('.full, .full-hide').hide();
  514. $('.full-show').click(function(){
  515. $('.full').slideDown(function(){
  516. $('.full-hide').show();
  517. });
  518. $(this).hide();
  519. });
  520. $('.full-hide').click(function(){
  521. $(this).hide();
  522. $('.full').slideUp(function(){
  523. $('.full-show').show();
  524. });
  525. });
  526. //toggle the errors and warnings sections
  527. $('.show-errors').click(function() {
  528. $('#collapse-errors').addClass('in');
  529. });
  530. $('.toggle-errors').click(function() {
  531. $('#collapse-errors').toggleClass('in');
  532. });
  533. $('.show-warnings').click(function() {
  534. $('#collapse-warnings').addClass('in');
  535. });
  536. $('.toggle-warnings').click(function() {
  537. $('#collapse-warnings').toggleClass('in');
  538. });
  539. $('.show-exceptions').click(function() {
  540. $('#collapse-exceptions').addClass('in');
  541. });
  542. $('.toggle-exceptions').click(function() {
  543. $('#collapse-exceptions').toggleClass('in');
  544. });
  545. $("#hide-alert").click(function(){
  546. $(this).parent().fadeOut();
  547. });
  548. //show warnings section when requested from the previous page
  549. if (location.href.search('#warnings') > -1) {
  550. $('#collapse-warnings').addClass('in');
  551. }
  552. /* Show the loading notification if nothing has happend after 1.5
  553. * seconds
  554. */
  555. $(document).bind("ajaxStart", function(){
  556. if (ajaxLoadingTimer)
  557. window.clearTimeout(ajaxLoadingTimer);
  558. ajaxLoadingTimer = window.setTimeout(function() {
  559. $("#loading-notification").fadeIn();
  560. }, 1200);
  561. });
  562. $(document).bind("ajaxStop", function(){
  563. if (ajaxLoadingTimer)
  564. window.clearTimeout(ajaxLoadingTimer);
  565. $("#loading-notification").fadeOut();
  566. });
  567. $(document).ajaxError(function(event, jqxhr, settings, errMsg){
  568. if (errMsg === 'abort')
  569. return;
  570. console.warn("Problem with xhr call");
  571. console.warn(errMsg);
  572. console.warn(jqxhr.responseText);
  573. });
  574. function check_for_duplicate_ids () {
  575. /* warn about duplicate element ids */
  576. var ids = {};
  577. $("[id]").each(function() {
  578. if (this.id && ids[this.id]) {
  579. console.warn('Duplicate element id #'+this.id);
  580. }
  581. ids[this.id] = true;
  582. });
  583. }
  584. if (libtoaster.debug) {
  585. check_for_duplicate_ids();
  586. } else {
  587. /* Debug is false so supress warnings by overriding the functions */
  588. window.console.warn = function () {};
  589. window.console.error = function () {};
  590. }
  591. });