Commit 3c816d66 authored by katja heuer's avatar katja heuer Committed by GitHub
Browse files

Merge pull request #166 from koddsson/refactor-jquery-promises-to-native

[WIP] chore: replace jquery promises with native ones
parents b6c4e14c 9f1cf1ad
This diff is collapsed.
......@@ -189,49 +189,48 @@ var AtlasMakerWidget = {
me.progress=$("a.download_MRI");
// Init the toolbar: load template, wire actions
var def=$.Deferred();
$.get("/templates/tools.html",function from_initAtlasMaker(html) {
me.container.append(html);
// intercept keyboard events
$(document).keydown(function(e){me.keyDown(e)});
// configure annotation tools
$("#tools-minimized").click(function(){me.changeToolbarDisplay("maximize")});
me.push($(".push#display-minimize"),function(){me.changeToolbarDisplay("minimize")});
me.push($(".push#display-left"),function(){me.changeToolbarDisplay("left")});
me.push($(".push#display-right"),function(){me.changeToolbarDisplay("right")});
me.slider($(".slider#slice"),function(x){me.changeSlice(Math.round(x))});
me.chose($(".chose#plane"),me.changeView);
me.chose($(".chose#paintTool"),me.changeTool);
me.chose($(".chose#penSize"),me.changePenSize);
me.toggle($(".toggle#precise"),me.togglePreciseCursor);
me.toggle($(".toggle#fill"),me.toggleFill);
me.toggle($(".toggle#fullscreen"),me.toggleFullscreen);
me.toggle($(".toggle#bubble"),me.toggleChat);
me.push($(".push#3drender"),me.render3D);
me.push($(".push#link"),me.link);
me.push($(".push#upload"),me.upload);
me.push($(".push#download"),me.download);
me.push($(".push#color"),me.color);
me.push($(".push#undo"),me.sendUndoMessage);
me.push($(".push#save"),me.sendSaveMessage);
me.push($(".push#prev"),me.prevSlice);
me.push($(".push#next"),me.nextSlice);
// connect chat message input
$("#msg").keypress(function keypress_fromInitAtlasMaker(e) {me.onkey(e)});
$("#tools-minimized").hide();
})
.then(function from_initAtlasMaker() {
// Init web socket connection
return me.initSocketConnection();
}).then(function() {
def.resolve()
return new Promise(function(resolve, reject) {
$.get("/templates/tools.html",function from_initAtlasMaker(html) {
me.container.append(html);
// intercept keyboard events
$(document).keydown(function(e){me.keyDown(e)});
// configure annotation tools
$("#tools-minimized").click(function(){me.changeToolbarDisplay("maximize")});
me.push($(".push#display-minimize"),function(){me.changeToolbarDisplay("minimize")});
me.push($(".push#display-left"),function(){me.changeToolbarDisplay("left")});
me.push($(".push#display-right"),function(){me.changeToolbarDisplay("right")});
me.slider($(".slider#slice"),function(x){me.changeSlice(Math.round(x))});
me.chose($(".chose#plane"),me.changeView);
me.chose($(".chose#paintTool"),me.changeTool);
me.chose($(".chose#penSize"),me.changePenSize);
me.toggle($(".toggle#precise"),me.togglePreciseCursor);
me.toggle($(".toggle#fill"),me.toggleFill);
me.toggle($(".toggle#fullscreen"),me.toggleFullscreen);
me.toggle($(".toggle#bubble"),me.toggleChat);
me.push($(".push#3drender"),me.render3D);
me.push($(".push#link"),me.link);
me.push($(".push#upload"),me.upload);
me.push($(".push#download"),me.download);
me.push($(".push#color"),me.color);
me.push($(".push#undo"),me.sendUndoMessage);
me.push($(".push#save"),me.sendSaveMessage);
me.push($(".push#prev"),me.prevSlice);
me.push($(".push#next"),me.nextSlice);
// connect chat message input
$("#msg").keypress(function keypress_fromInitAtlasMaker(e) {me.onkey(e)});
$("#tools-minimized").hide();
})
.then(function from_initAtlasMaker() {
// Init web socket connection
return me.initSocketConnection();
}).then(function() {
resolve()
});
});
return def.promise();
},
/**
* @function configureAtlasMaker
......@@ -297,25 +296,23 @@ var AtlasMakerWidget = {
var me=AtlasMakerWidget;
var l=me.traceLog(requestMRIInfo,0,"#bbd");if(l)console.log.apply(undefined,l);
if(!def) {
var def=$.Deferred();
}
$.post("/mri/json",{url:source}, function(info) {
if(info.success == true) {
def.resolve(info);
return Promise.resolve(info);
} else if(info.success == 'downloading') {
if(me.User.source != source)
return;
setTimeout(function(){me.requestMRIInfo(source,def)},2000);
return;
$("#loadingIndicator p").text("Loading... "+parseInt(info.cur/info.len*100,10)+"%");
return new Promise(function(resolve, reject) {
setTimeout(function(){
resolve(me.requestMRIInfo(source))
}, 2000);
})
} else {
console.log("ERROR: requestMRIInfo",info);
def.reject();
console.log("ERROR: requestMRIInfo",info);
return Promise.reject();
}
});
return def.promise();
},
/**
* @function configureMRI
......@@ -324,67 +321,64 @@ var AtlasMakerWidget = {
var me=AtlasMakerWidget;
var l=me.traceLog(configureMRI,0,"#bbd");if(l)console.log.apply(undefined,l);
var def=$.Deferred();
me.User.source=info.source;
me.requestMRIInfo(info.source)
.then(function(info2) {
if(!info.dim) {
// the mri object used to call this function does not have a 'dim'
// property, indicating that it had not been downloaded at the time of the
// call. Here we merge the fields from info2 that are initialised upon
// download of the mri server-side. The mri field in the original 'info',
// which contains the newly created text 'annotations', is conserved
$.extend(true, info, info2);
}
info2=info;
// Get data from AtlasMaker object
me.name=info2.name||"Untitled";
me.url=info2.url;
me.atlasFilename=info2.mri.atlas[index].filename;
me.atlasName=info2.mri.atlas[index].name;
// get local file path from url
me.User.dirname=me.url; // TEMPORARY
me.User.mri=info2.mri.brain;
me.User.specimenName=me.name;
me.User.atlasFilename=info2.mri.atlas[index].filename;
me.User.isMRILoaded=false;
// TODO: it's silly to have to put vol dim twice...
// (first here, once again further down)
me.User.dim=info2.dim;
me.User.pixdim=info2.pixdim;
// compute space transformations
me.User.v2w=info2.voxel2world;
me.User.wori=info2.worldOrigin;
me.computeS2VTransformation();
//me.testS2VTransformation();
me.flagLoadingImg={loading:false};
me.brain_img.img=null;
// get volume dimensions
me.brain_dim=info2.dim;
if(info2.pixdim)
me.brain_pixdim=info2.pixdim;
else
me.brain_pixdim=[1,1,1];
def.resolve(info2);
})
.catch(function(err) {
console.log("ERROR: DOWNLOAD FAILED", err);
def.reject(err);
});
return new Promise(function(resolve, reject) {
me.User.source=info.source;
me.requestMRIInfo(info.source)
.then( function(info2) {
if(!info.dim) {
// the mri object used to call this function does not have a 'dim'
// property, indicating that it had not been downloaded at the time of the
// call. Here we merge the fields from info2 that are initialised upon
// download of the mri server-side. The mri field in the original 'info',
// which contains the newly created text 'annotations', is conserved
$.extend(true, info, info2);
}
info2=info;
// Get data from AtlasMaker object
me.name=info2.name||"Untitled";
me.url=info2.url;
me.atlasFilename=info2.mri.atlas[index].filename;
me.atlasName=info2.mri.atlas[index].name;
// get local file path from url
me.User.dirname=me.url; // TEMPORARY
me.User.mri=info2.mri.brain;
me.User.specimenName=me.name;
me.User.atlasFilename=info2.mri.atlas[index].filename;
me.User.isMRILoaded=false;
// TODO: it's silly to have to put vol dim twice...
// (first here, once again further down)
me.User.dim=info2.dim;
me.User.pixdim=info2.pixdim;
return def.promise();
// compute space transformations
me.User.v2w=info2.voxel2world;
me.User.wori=info2.worldOrigin;
me.computeS2VTransformation();
//me.testS2VTransformation();
me.flagLoadingImg={loading:false};
me.brain_img.img=null;
// get volume dimensions
me.brain_dim=info2.dim;
if(info2.pixdim)
me.brain_pixdim=info2.pixdim;
else
me.brain_pixdim=[1,1,1];
resolve(info2);
})
.catch(function(err) {
console.log("ERROR: DOWNLOAD FAILED", err);
reject(err);
});
});
}
};
/*
......
......@@ -61,150 +61,146 @@ var BrainBox={
* If undefined, the script will be loaded.
*/
loadScript: function loadScript(path, testScriptPresent) {
var def = new $.Deferred();
if(testScriptPresent && testScriptPresent()) {
console.log("[loadScript] Script",path,"already present, not loading it again");
return def.resolve().promise();
}
var s = document.createElement("script");
s.src = path;
s.onload=function () {
console.log("Loaded",path);
def.resolve();
};
document.body.appendChild(s);
return def.promise();
return new Promise(function(resolve, reject) {
if(testScriptPresent && testScriptPresent()) {
console.log("[loadScript] Script",path,"already present, not loading it again");
return resolve();
}
var s = document.createElement("script");
s.src = path;
s.onload=function () {
console.log("Loaded",path);
resolve();
};
document.body.appendChild(s);
});
},
/**
* @function initBrainBox
*/
initBrainBox: function initBrainBox() {
var l=BrainBox.traceLog(initBrainBox);if(l)console.log(l);
var def=$.Deferred();
// Add AtlasMaker and friends
$("#stereotaxic").html('<div id="atlasMaker"></div>');
$("#atlasMaker").addClass('edit-mode');
BrainBox.loadScript('/lib/jquery-ui.min.js', function(){return window.jQuery.ui != undefined})
.then(function(){return BrainBox.loadScript('/lib/pako/pako.min.js', function(){return window.pako != undefined})})
.then(function(){return BrainBox.loadScript('/lib/purify.min.js', function(){return window.DOMPurify != undefined})})
.then(function(){return BrainBox.loadScript('/lib/json-patch-duplex.min.js', function(){return window.jsonpatch != undefined})})
.then(function(){return BrainBox.loadScript('/lib/npm-bundle.js')})
.then(function(){return BrainBox.loadScript('/js/twoWayBinding.js')})
.then(function(){
$.when(
BrainBox.loadScript('/js/atlasMaker-draw.js'),
BrainBox.loadScript('/js/atlasMaker-interaction.js'),
BrainBox.loadScript('/js/atlasMaker-io.js'),
BrainBox.loadScript('/js/atlasMaker-paint.js'),
BrainBox.loadScript('/js/atlasMaker-ui.js'),
BrainBox.loadScript('/js/atlasMaker-ws.js'),
BrainBox.loadScript('/js/atlasMaker.js')
).then(function () {
$.extend(AtlasMakerWidget,AtlasMakerDraw);
$.extend(AtlasMakerWidget,AtlasMakerInteraction);
$.extend(AtlasMakerWidget,AtlasMakerIO);
$.extend(AtlasMakerWidget,AtlasMakerPaint);
$.extend(AtlasMakerWidget,AtlasMakerUI);
$.extend(AtlasMakerWidget,AtlasMakerWS);
AtlasMakerWidget.initAtlasMaker($("#atlasMaker"))
.then(function() {
def.resolve();
});
})
return new Promise(function(resolve, reject) {
// Add AtlasMaker and friends
$("#stereotaxic").html('<div id="atlasMaker"></div>');
$("#atlasMaker").addClass('edit-mode');
BrainBox.loadScript('/lib/jquery-ui.min.js', function(){return window.jQuery.ui != undefined})
.then(function(){return BrainBox.loadScript('/lib/pako/pako.min.js', function(){return window.pako != undefined})})
.then(function(){return BrainBox.loadScript('/lib/purify.min.js', function(){return window.DOMPurify != undefined})})
.then(function(){return BrainBox.loadScript('/lib/json-patch-duplex.min.js', function(){return window.jsonpatch != undefined})})
.then(function(){return BrainBox.loadScript('/lib/npm-bundle.js')})
.then(function(){return BrainBox.loadScript('/js/twoWayBinding.js')})
.then(function(){
$.when(
BrainBox.loadScript('/js/atlasMaker-draw.js'),
BrainBox.loadScript('/js/atlasMaker-interaction.js'),
BrainBox.loadScript('/js/atlasMaker-io.js'),
BrainBox.loadScript('/js/atlasMaker-paint.js'),
BrainBox.loadScript('/js/atlasMaker-ui.js'),
BrainBox.loadScript('/js/atlasMaker-ws.js'),
BrainBox.loadScript('/js/atlasMaker.js')
).then(function () {
$.extend(AtlasMakerWidget,AtlasMakerDraw);
$.extend(AtlasMakerWidget,AtlasMakerInteraction);
$.extend(AtlasMakerWidget,AtlasMakerIO);
$.extend(AtlasMakerWidget,AtlasMakerPaint);
$.extend(AtlasMakerWidget,AtlasMakerUI);
$.extend(AtlasMakerWidget,AtlasMakerWS);
AtlasMakerWidget.initAtlasMaker($("#atlasMaker"))
.then(function() {
resolve();
});
})
});
// store state on exit
$(window).on('unload',BrainBox.unload);
});
// store state on exit
$(window).on('unload',BrainBox.unload);
return def.promise();
},
/**
* @function configureBrainBox
*/
configureBrainBox: function configureBrainBox(param) {
var l=BrainBox.traceLog(configureBrainBox);if(l)console.log(l);
var def=$.Deferred();
var date=new Date();
var index=param.annotationItemIndex||0;
// Copy MRI from source
$("#msgLog").html("<p>Downloading from source to server...");
// Configure MRI into atlasMaker
if(param.info.success===false) {
date=new Date();
$("#msgLog").append("<p>ERROR: "+param.info.message+".");
console.log("<p>ERROR: "+param.info.message+".");
return def.promise().reject();
}
BrainBox.info=param.info;
var def=new Promise(function(resolve, reject) {
var date=new Date();
var index=param.annotationItemIndex||0;
var arr=param.url.split("/");
var name=arr[arr.length-1];
date=new Date();
$("#msgLog").append("<p>Downloading from server...");
// Copy MRI from source
$("#msgLog").html("<p>Downloading from source to server...");
/**
* @todo Check it these two lines are of any use...
*/
param.dim=BrainBox.info.dim; // this allows to keep dim and pixdim through annotation changes
param.pixdim=BrainBox.info.pixdim;
// Configure MRI into atlasMaker
if(param.info.success===false) {
date=new Date();
$("#msgLog").append("<p>ERROR: "+param.info.message+".");
console.log("<p>ERROR: "+param.info.message+".");
return reject();
}
BrainBox.info=param.info;
// re-instance stored configuration
var stored=localStorage.AtlasMaker;
if(stored) {
var stored=JSON.parse(stored);
if(stored.version && stored.version==BrainBox.version) {
for(var i=0;i<stored.history.length;i++) {
if(stored.history[i].url==param.url) {
AtlasMakerWidget.User.view=stored.history[i].view;
AtlasMakerWidget.User.slice=stored.history[i].slice;
break;
}
}
}
}
var arr=param.url.split("/");
var name=arr[arr.length-1];
date=new Date();
$("#msgLog").append("<p>Downloading from server...");
// enact configuration in param, eventually overriding the stored one
if(param.view) {
AtlasMakerWidget.User.view=param.view;
AtlasMakerWidget.User.slice=null; // this will set the slider to the middle slice in case no slice were specified
}
if(param.slice)
AtlasMakerWidget.User.slice=param.slice;
/**
* @todo Check it these two lines are of any use...
*/
param.dim=BrainBox.info.dim; // this allows to keep dim and pixdim through annotation changes
param.pixdim=BrainBox.info.pixdim;
if(param.fullscreen)
AtlasMakerWidget.fullscreen=param.fullscreen;
else
AtlasMakerWidget.fullscreen=false;
AtlasMakerWidget.configureAtlasMaker(BrainBox.info,index)
.then(function(info2) {
BrainBox.info = info2;
// check 'edit' access
var accessStr = BrainBox.info.mri.atlas[index].access;
var accessLvl = BrainBox.accessLevels.indexOf(accessStr);
if(accessLvl<0 || accessLvl>BrainBox.accessLevels.length-1)
accessLvl = 0;
if(accessLvl>=2)
AtlasMakerWidget.editMode = 1;
else
AtlasMakerWidget.editMode = 0;
def.resolve();
})
.catch(function(err) {
console.log("ERROR:",err);
def.reject();
// re-instance stored configuration
var stored=localStorage.AtlasMaker;
if(stored) {
var stored=JSON.parse(stored);
if(stored.version && stored.version==BrainBox.version) {
for(var i=0;i<stored.history.length;i++) {
if(stored.history[i].url==param.url) {
AtlasMakerWidget.User.view=stored.history[i].view;
AtlasMakerWidget.User.slice=stored.history[i].slice;
break;
}
}
}
}
// enact configuration in param, eventually overriding the stored one
if(param.view) {
AtlasMakerWidget.User.view=param.view;
AtlasMakerWidget.User.slice=null; // this will set the slider to the middle slice in case no slice were specified
}
if(param.slice)
AtlasMakerWidget.User.slice=param.slice;
if(param.fullscreen)
AtlasMakerWidget.fullscreen=param.fullscreen;
else
AtlasMakerWidget.fullscreen=false;
AtlasMakerWidget.configureAtlasMaker(BrainBox.info,index)
.then(function(info2) {
BrainBox.info = info2;
// check 'edit' access
var accessStr = BrainBox.info.mri.atlas[index].access;
var accessLvl = BrainBox.accessLevels.indexOf(accessStr);
if(accessLvl<0 || accessLvl>BrainBox.accessLevels.length-1)
accessLvl = 0;
if(accessLvl>=2)
AtlasMakerWidget.editMode = 1;
else
AtlasMakerWidget.editMode = 0;
resolve();
})
.catch(function(err) {
console.log("ERROR:",err);
reject();
});
});
return def.promise();
},
/**
* @function convertImgObjectURLToDataURL
......@@ -212,18 +208,18 @@ var BrainBox={
* suitable to be stored as a string in localStorage
*/
convertImgObjectURLToDataURL: function convertImgObjectURLToDataURL(objURL) {
var def = $.Deferred();
var x = new XMLHttpRequest(), f = new FileReader();
x.open('GET',objURL,true);
x.responseType = 'blob';
x.onload = function (e) {
f.onload = function (evt) {
def.resolve(evt.target.result);
return new Promise(function(resolve, reject) {
var x = new XMLHttpRequest(), f = new FileReader();
x.open('GET',objURL,true);
x.responseType = 'blob';
x.onload = function (e) {
f.onload = function (evt) {
resolve(evt.target.result);
};
f.readAsDataURL(x.response);
};
f.readAsDataURL(x.response);
};
x.send();
return def;
x.send();
})
},
/**
* @function addCurrentMRIToHistory
......
......@@ -90,20 +90,20 @@ loadScript("/lib/three.min.js")
} else {
console.log("with segmentation from server");
worker.postMessage({cmd:"start",path:path,level:level});
}
}
});
// "wait" animation
var dot=0;setInterval(function(){if($("#dot"))$("#dot").css({marginLeft:50*(1+Math.sin(dot))+"%"});dot+=0.1},33);
function loadScript(script) {
var def=new $.Deferred();
var s = document.createElement("script");
s.src = script;
s.onload=function(){console.log("loaded",script,new Date());def.resolve();}
s.onerror=function(e){console.log("unable to load",script);def.reject();}
document.body.appendChild(s);
return def.promise();
return new Promise(function(resolve, reject) {
var s = document.createElement("script");
s.src = script;
s.onload=function(){console.log("loaded",script,new Date());resolve();}
s.onerror=function(e){console.log("unable to load",script);reject();}
document.body.appendChild(s);
});
}
function deparam() {
......
......@@ -221,25 +221,25 @@ function goToURL(e) {
* @function testWebSockets
*/
function testWebSockets() {
var def =