<commit_before>define([
        "dojo/_base/declare",
        "dojo/_base/lang",
        "dojo/date/stamp",
        "dojo/date/locale",
        "dojo/topic",
        "dojo/dom-class"
        ],function(declare,lang,stamp,locale,topic,domClass){

	var busyInd = null;

	return declare([],{

		// view: dojox/app/View
		//		Pointer to view.  You can use this.view.loadedModels etc.
		view : null,

		constructor : function(args){
			lang.mixin(this,args);
		},

		init : function(){
			// summary:
			//		Called when the view is first initialized
		},

		beforeActivate : function(previousView, data){
			// summary:
			//		Called before this view transitions off
			// previousView: dojox/app/View
			//		The previous view
			// data: Object
			//		The transition data.  The data received is the data passed in the data attribute of the transition options of the transition that led to that view.
		},

		afterActivate : function(previousView, data){
			// summary:
			//		Called after this view transitions off
			// previousView: dojox/app/View
			//		The previous view
			// data: Object
			//		The transition data.  The data received is the data passed in the data attribute of the transition options of the transition that led to that view.

		},

		beforeDeactivate : function(nextView, data){
			// summary:
			//		Called before this view transitions off
			// nextView: dojox/app/View
			//		The next view
			// data: Object
			//		The transition data.  The data received is the data passed in the data attribute of the transition options of the transition that led to that view.
        },

        afterDeactivate : function(nextView, data){
			// summary:
			//		Called after this view transitions off
			// nextView: dojox/app/View
			//		The next view
			// data: Object
			//		The transition data.  The data received is the data passed in the data attribute of the transition options of the transition that led to that view.
        },

        destroy : function(){
        	// summary:
        	//		Called when the view is being destroyed
        },

        showLoading : function(){

        	if(!busyInd){
        		busyInd = new WL.BusyIndicator('content', {text : 'Loading...'});
        	}//end if
        	busyInd.show();
        },

        hideLoading : function(){
        	if(!busyInd){
        		busyInd = new WL.BusyIndicator('content', {text : 'Loading...'});
        	}//end if
        	busyInd.hide();
        },

        formatDate : function(isoString,includeTime){
        	// summary:
        	//		This function is used to provide a standard date format function for the application.
        	// isoString: String
        	//		The ISO date string to format
        	// includeTime: boolean
        	//		Whether to include the time in the result string
        	// returns:
        	//		Formatted date string

        	var d = stamp.fromISOString(isoString);

        	if(!includeTime){
        		return locale.format(d,{selector: "date",datePattern: this.getDatePattern()});
        	}else{
        		return locale.format(d,{datePattern: this.getDatePattern(),timePattern: this.getTimePattern()});
        	}//end if
        },

        formatTime : function(isoString){
        	// summary:
        	//		This function is used to provide a standard date format function for the application.
        	// isoString: String
        	//		The ISO date string to format
        	// returns:
        	//		Formatted date string

        	var d = stamp.fromISOString(isoString);
        	return locale.format(d,{selector: "time",timePattern: this.getTimePattern()});

        },

        getDate : function(isoString){
        	// summary:
        	//		This method returns the date given the iso string
        	// isoString: String
        	//		The iso string

        	return stamp.fromISOString(isoString);
        },

        getDatePattern : function(){
        	return "yyyy-MM-dd";
        },

        getTimePattern : function(){
        	return "hh:mm a";
        },

		setHeadingLabel : function(label){
	        this.view.parent.dapHeading.set("label",label);
	    },

	    showBack : function(show){
	    	 if(!show){
	    		 domClass.add(this.view.parent.dapBackButton.domNode,"hide");
	    	 }else{
	    		 domClass.remove(this.view.parent.dapBackButton.domNode,"hide");
	    	 }//end if
	    },

	    setBackLabel : function(label){
	    	this.view.parent.dapBackButton.set("label",label);
	    },

	    setBackTarget : function(target){
	    	if(target){
	    		this.view.parent.dapBackButton.set("back",false);
		    	this.view.parent.dapBackButton.set("transitionOptions",{target : target, url: "#" + target});
	    	}else{
	    		this.view.parent.dapBackButton.set("back",true);
	    	}//end if
	    },

        _createWidgets : function(){
        	// summary:
        	//		This is a private method that should be implemented by the child class if there are programatic widgets
        	//		to be created
        	// tags:
        	//		protected
        },

 		_connectActionHandlers : function(){
 			// summary:
 			//		This is a private method that should be implemented by the child class if there are action handlers
 			//		to connect to inputs in the view
 			// tags:
 			//		protected
 		},

 		_onEnterForeground : function(){
 			// summary:
 			//		This action handler is called when this is the active view, and the app enters the foreground. iOS only
 			// tags:
 			//		protected
 		},

 		_onEnterBackground : function(){
 			// summary:
 			//		This action handler is called when this is the active view, and the app enters the background. iOS only
 			// tags:
 			//		protected
 		},

		controller : function(){
			var _this = this;
			var onForegroundHandle = null;
			var onBackgroundHandle = null;
			return {
				 init: function(){
					 	_this.view = this;
					 	_this.init();
					 	_this._createWidgets();
					 	_this._connectActionHandlers();
				 },

		         beforeActivate: function(previousView, data){
		        	 onForegroundHandle = topic.subscribe("app/enterforeground",_this._onEnterForeground);
		        	 onBackgroundHandle = topic.subscribe("app/enterbackground",_this._onEnterBackground);

		        	 _this.beforeActivate(previousView, data);
		         },

		         afterActivate: lang.hitch(this,this.afterActivate),

		         beforeDeactivate: function(nextView, data){
		        	 if(onForegroundHandle){onForegroundHandle.remove();}
		        	 if(onBackgroundHandle){onBackgroundHandle.remove();}

		        	 _this.beforeDeactivate(nextView, data);
		         },

		         afterDeactivate: lang.hitch(this,this.afterDeactivate),

		         destroy: function(){
		                 // _WidgetBase.on listener is automatically destroyed when the Widget itself is.
		                 this.inherited(arguments);
		                 _this.destroy();
		         }
			 };
		}

	});
});<commit_msg>Adding some additional common logic to BaseViewController<commit_after>define([
        "dojo/_base/declare",
        "dojo/_base/lang",
        "dojo/date/stamp",
        "dojo/date/locale",
        "dojo/topic",
        "dojo/dom-class"
        ],function(declare,lang,stamp,locale,topic,domClass){

	var busyInd = null;

	return declare([],{

		// view: dojox/app/View
		//		Pointer to view.  You can use this.view.loadedModels etc.
		view : null,

		constructor : function(args){
			lang.mixin(this,args);
		},

		init : function(){
			// summary:
			//		Called when the view is first initialized
		},

		beforeActivate : function(previousView, data){
			// summary:
			//		Called before this view transitions off
			// previousView: dojox/app/View
			//		The previous view
			// data: Object
			//		The transition data.  The data received is the data passed in the data attribute of the transition options of the transition that led to that view.
		},

		afterActivate : function(previousView, data){
			// summary:
			//		Called after this view transitions off
			// previousView: dojox/app/View
			//		The previous view
			// data: Object
			//		The transition data.  The data received is the data passed in the data attribute of the transition options of the transition that led to that view.

		},

		beforeDeactivate : function(nextView, data){
			// summary:
			//		Called before this view transitions off
			// nextView: dojox/app/View
			//		The next view
			// data: Object
			//		The transition data.  The data received is the data passed in the data attribute of the transition options of the transition that led to that view.
        },

        afterDeactivate : function(nextView, data){
			// summary:
			//		Called after this view transitions off
			// nextView: dojox/app/View
			//		The next view
			// data: Object
			//		The transition data.  The data received is the data passed in the data attribute of the transition options of the transition that led to that view.
        },

        destroy : function(){
        	// summary:
        	//		Called when the view is being destroyed
        },

        showLoading : function(){

        	if(!busyInd){
        		busyInd = new WL.BusyIndicator('content', {text : 'Loading...'});
        	}//end if
        	busyInd.show();
        },

        hideLoading : function(){
        	if(!busyInd){
        		busyInd = new WL.BusyIndicator('content', {text : 'Loading...'});
        	}//end if
        	busyInd.hide();
        },

        formatDate : function(isoString,includeTime){
        	// summary:
        	//		This function is used to provide a standard date format function for the application.
        	// isoString: String
        	//		The ISO date string to format
        	// includeTime: boolean
        	//		Whether to include the time in the result string
        	// returns:
        	//		Formatted date string

        	var d = stamp.fromISOString(isoString);

        	if(!includeTime){
        		return locale.format(d,{selector: "date",datePattern: this.getDatePattern()});
        	}else{
        		return locale.format(d,{datePattern: this.getDatePattern(),timePattern: this.getTimePattern()});
        	}//end if
        },

        formatTime : function(isoString){
        	// summary:
        	//		This function is used to provide a standard date format function for the application.
        	// isoString: String
        	//		The ISO date string to format
        	// returns:
        	//		Formatted date string

        	var d = stamp.fromISOString(isoString);
        	return locale.format(d,{selector: "time",timePattern: this.getTimePattern()});

        },

        getDate : function(isoString){
        	// summary:
        	//		This method returns the date given the iso string
        	// isoString: String
        	//		The iso string

        	return stamp.fromISOString(isoString);
        },

        getDatePattern : function(){
        	return "yyyy-MM-dd";
        },

        getTimePattern : function(){
        	return "hh:mm a";
        },

		setHeadingLabel : function(label){
	        this.view.parent.dapHeading.set("label",label);
	        // The CSS class androidOnly used for this header should have taken care of this, will have to investigate
	        // This is a temporary workaround
	        if (window.device && (WL.Client.getEnvironment() == WL.Environment.ANDROID)) {
	        	this.view.parent.dapAndroidHeading.set("label",label);
	        } else {
	        	 domClass.add(this.view.parent.dapAndroidHeading.domNode, "hide");
	        	 // a part of the same temporary fix, no need to call it every time, could be in app.js
	        	 // but a temp code anyway, so not polluting other files with this, so it will called many time unnecessarily
	        	 domClass.add(this.view.parent.dapAndroidMenuButton.domNode, "hide");
	        }
	    },

	    showBack : function(show){
	    	 if(!show){
	    		 domClass.add(this.view.parent.dapHeading.backButton.domNode, "hide");
//	    		 domClass.add(this.view.parent.dapBackButton.domNode,"hide");
	    	 }else{
	    		 domClass.remove(this.view.parent.dapHeading.backButton.domNode, "hide");
//	    		 domClass.remove(this.view.parent.dapBackButton.domNode,"hide");
	    	 }//end if
	    },

	    setBackLabel : function(label){
   		 	this.view.parent.dapHeading.backButton.set("label",label);
//	    	this.view.parent.dapBackButton.set("label",label);
	    },

	    setBackTarget : function(target){
	    	if(target){
	    		this.view.parent.dapBackButton.set("back",false);
		    	this.view.parent.dapBackButton.set("transitionOptions",{target : target, url: "#" + target});
	    	}else{
	    		this.view.parent.dapBackButton.set("back",true);
	    	}//end if
	    },

        _createWidgets : function(){
        	// summary:
        	//		This is a private method that should be implemented by the child class if there are programatic widgets
        	//		to be created
        	// tags:
        	//		protected
        },

 		_connectActionHandlers : function(){
 			// summary:
 			//		This is a private method that should be implemented by the child class if there are action handlers
 			//		to connect to inputs in the view
 			// tags:
 			//		protected
 		},

 		_onEnterForeground : function(){
 			// summary:
 			//		This action handler is called when this is the active view, and the app enters the foreground
 			// tags:
 			//		protected
 		},

 		_onEnterBackground : function(){
 			// summary:
 			//		This action handler is called when this is the active view, and the app enters the background
 			// tags:
 			//		protected
 		},

		controller : function(){
			var _this = this;
			var onForegroundHandle = null;
			var onBackgroundHandle = null;
			return {
				 init: function(){
					 	_this.view = this;
					 	_this.init();
					 	_this._createWidgets();
					 	_this._connectActionHandlers();
				 },

		         beforeActivate: function(previousView, data){
		        	 onForegroundHandle = topic.subscribe("app/enterforeground",_this._onEnterForeground);
		        	 onBackgroundHandle = topic.subscribe("app/enterbackground",_this._onEnterBackground);

		        	 _this.beforeActivate(previousView, data);
		         },

		         afterActivate: lang.hitch(this,this.afterActivate),

		         beforeDeactivate: function(nextView, data){
		        	 if(onForegroundHandle){onForegroundHandle.remove();}
		        	 if(onBackgroundHandle){onBackgroundHandle.remove();}

		        	 _this.beforeDeactivate(nextView, data);
		         },

		         afterDeactivate: lang.hitch(this,this.afterDeactivate),

		         destroy: function(){
		                 // _WidgetBase.on listener is automatically destroyed when the Widget itself is.
		                 this.inherited(arguments);
		                 _this.destroy();
		         }
			 };
		}

	});
});<|endoftext|>


<commit_before>var isAbsolute = true;

var colorScale = (function() {
	var twoColors = [d3.rgb("#00a700"), d3.rgb('#a90000')];
	// default color settings
	var color = d3.scale.linear().domain([0, 100]).interpolate(d3.interpolateHcl).range(twoColors);

	/*
	 *
	 * Calculates the worst case of #warnings/loc
	 *
	 */
	function getRelativeWarnings() {
		var worstRatio = 0;
		for(var p =0; p < inputData.length; p++){
			var package = inputData[p];
			var classesArray = package.classes;
			for (i = 0; i < classesArray.length; i++) {
				classObjectJson = classesArray[i];
				var numberOfWarnings = 0;
				for (j = 0; j < classObjectJson.warningList.length; j++) {
					numberOfWarnings++;
		  		}
		  		var curRatio = numberOfWarnings / classObjectJson.loc;
		  		if(curRatio > worstRatio) {
		  			worstRatio = curRatio;
		  		}
			}
		}
		return (worstRatio * 100);
	}

    return {

        getColor: function() {
            return color;
        },
		getColor: function(ratio) {
			if(isAbsolute) {
				return (ratio > 100) ? color(100) : color(ratio);
			} else {
				console.log(ratio);
				return color(ratio);
			}
        },
		colorsRelative: function() {
			color = d3.scale.linear().domain([0, getRelativeWarnings()]).interpolate(d3.interpolateHcl).range(twoColors);
		},
		colorsAbsolute: function() {
			color = d3.scale.linear().domain([0, 100]).interpolate(d3.interpolateHcl).range(twoColors);
		}

    };

}());
        <commit_msg>the removded color file<commit_after><|endoftext|>


<commit_before>import { app, BrowserWindow, nativeTheme } from 'electron'

try {
  if (process.platform === 'win32' && nativeTheme.shouldUseDarkColors === true) {
    require('fs').unlinkSync(require('path').join(app.getPath('userData'), 'DevTools Extensions'))
  }
} catch (_) { }

/**
 * Set `__statics` path to static files in production;
 * The reason we are setting it here is that the path needs to be evaluated at runtime
 */
if (process.env.PROD) {
  global.__statics = require('path').join(__dirname, 'statics').replace(/\\/g, '\\\\')
}

let mainWindow

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 600,
    useContentSize: true,
    webPreferences: {
      // Change from /quasar.conf.js > electron > nodeIntegration;
      // More info: https://quasar.dev/quasar-cli/developing-electron-apps/node-integration
      nodeIntegration: QUASAR_NODE_INTEGRATION,

      // More info: /quasar-cli/developing-electron-apps/electron-preload-script
      // preload: path.resolve(__dirname, 'electron-preload.js')
    }
  })

  mainWindow.loadURL(process.env.APP_URL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
<commit_msg>feat(app): include nodeIntegrationInWorker for Electron in template<commit_after>import { app, BrowserWindow, nativeTheme } from 'electron'

try {
  if (process.platform === 'win32' && nativeTheme.shouldUseDarkColors === true) {
    require('fs').unlinkSync(require('path').join(app.getPath('userData'), 'DevTools Extensions'))
  }
} catch (_) { }

/**
 * Set `__statics` path to static files in production;
 * The reason we are setting it here is that the path needs to be evaluated at runtime
 */
if (process.env.PROD) {
  global.__statics = require('path').join(__dirname, 'statics').replace(/\\/g, '\\\\')
}

let mainWindow

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 600,
    useContentSize: true,
    webPreferences: {
      // Change from /quasar.conf.js > electron > nodeIntegration;
      // More info: https://quasar.dev/quasar-cli/developing-electron-apps/node-integration
      nodeIntegration: QUASAR_NODE_INTEGRATION,
      nodeIntegrationInWorker: QUASAR_NODE_INTEGRATION,

      // More info: /quasar-cli/developing-electron-apps/electron-preload-script
      // preload: path.resolve(__dirname, 'electron-preload.js')
    }
  })

  mainWindow.loadURL(process.env.APP_URL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
<|endoftext|>


<commit_before>import React from 'react';
import {Button, ButtonToolbar, Grid, Row, Col} from 'react-bootstrap';
import 'whatwg-fetch';
import AnswerButton from './answerbutton';

export default class GuessPlayPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {question: '',
            correctAlt: '',
            randomOrderAlt: ['', '', '', ''],
            buttonStyles: ['default', 'default', 'default', 'default'],
            buttonDisabled: false,
            lesson: [],
            currentQuestion: ''
        };
        this.setQuestion = this.setQuestion.bind(this);
        this.getNextQuestion = this.getNextQuestion.bind(this);
        this.checkAnswer = this.checkAnswer.bind(this);
        this.getSuccessRate = this.getSuccessRate.bind(this);
        this.onKeys = this.onKeys.bind(this);

        sessionStorage.setItem('correctAttempts', 0);
        sessionStorage.totalAttempts = 0;
        sessionStorage.currentQuestionIndex = 0;

    }
    componentDidMount() {
        window.addEventListener("keydown", this.onKeys);
        this.setState({
            lessonLength: JSON.parse(sessionStorage.lesson).length
        });
        this.setQuestion(0);
    }
    componentWillUnmount() {
        window.clearInterval(this.countDownVisible);
        window.removeEventListener("keydown", this.onKeys);
        sessionStorage.removeItem('currentQuestionIndex');

    }
    setQuestion(questionIndex) {
        this.setState({
            question: JSON.parse(sessionStorage.lesson)[questionIndex].question,
            correctAlt: JSON.parse(sessionStorage.lesson)[questionIndex].correctAlternative,
            randomOrderAlt: this.randomizeOrder([
                JSON.parse(sessionStorage.lesson)[questionIndex].alternative1,
                JSON.parse(sessionStorage.lesson)[questionIndex].alternative2,
                JSON.parse(sessionStorage.lesson)[questionIndex].alternative3,
                JSON.parse(sessionStorage.lesson)[questionIndex].correctAlternative]),
            buttonStyles: ['default', 'default', 'default', 'default'],
            buttonDisabled: false
        });
    }
    getNextQuestion(){
        if(Number(sessionStorage.currentQuestionIndex) + 1 < this.state.lessonLength){
            sessionStorage.currentQuestionIndex = Number(sessionStorage.currentQuestionIndex) + 1;
            this.setQuestion(Number(sessionStorage.currentQuestionIndex));
        } else {
            this.setState({
                buttonDisabled: true
            });
        }
    }
    randomizeOrder(array) {
        let i = array.length - 1;
        for (; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            const temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        };
        return array;
    }
    checkAnswer(answer) {
        var newButtonStyles = [];
        if (answer === this.state.correctAlt) {
            newButtonStyles = this.state.randomOrderAlt.map( (word) => (word === answer) ?
            'success' : 'default');
            sessionStorage.correctAttempts = Number(sessionStorage.correctAttempts) + 1;
        } else {
            newButtonStyles = this.state.randomOrderAlt.map( (word) => {
                if (word === answer) {
                    return 'danger';
                } else if(word === this.state.correctAlt) {
                    return 'success';
                } else {
                    return 'default';
                }
            });
        }
        sessionStorage.totalAttempts = Number(sessionStorage.totalAttempts) + 1;
        this.setState({
            buttonDisabled: true,
            buttonStyles: newButtonStyles
        });

        if(Number(sessionStorage.currentQuestionIndex) < this.state.lessonLength - 1){
            setTimeout(() => {
                this.getNextQuestion();
            }, 1000);
        } else {
            setTimeout(() => this.props.switchPage('EndScreenPage'), 1000);
        }
    }
    getSuccessRate(){
        var successRate = 0;
        var successRateMessage = '';
        if (Number(sessionStorage.totalAttempts) > 0) {
            successRate = Number(sessionStorage.correctAttempts)
                / Number(sessionStorage.totalAttempts) * 100;
            successRateMessage = successRate.toFixed(0) + '%';
            if(successRate >= 80){
                return ', ' + successRateMessage + ' :D';
            } else if(successRate < 80 && successRate >= 60){
                return ', ' + successRateMessage + ' :)';
            } else if(successRate < 60 && successRate >= 40){
                return ', ' + successRateMessage + ' :/';
            } else if(successRate < 40 && successRate >= 20){
                return ', ' + successRateMessage + ' :(';
            } else if(successRate < 20){
                return ', ' + successRateMessage + ' :((';
            }
        } else {
              return successRateMessage;
        }
    }
    onKeys(event){
        var keyDown = event.key;
        if(!this.state.buttonDisabled){
            if (keyDown === '1') {
                this.checkAnswer(this.state.randomOrderAlt[0]);
            } else if (keyDown === '2') {
                this.checkAnswer(this.state.randomOrderAlt[1]);
            } else if (keyDown === '3') {
                this.checkAnswer(this.state.randomOrderAlt[2]);
            } else if (keyDown === '4') {
                this.checkAnswer(this.state.randomOrderAlt[3]);
            }
        }

    }
    render() {
        return (

                <Grid>
                    <Row>
{this.state.question}
</Row>

                    <Row>
                        <ButtonToolbar>
                            <Col xs={6} sm={4} smOffset={2} md={3} mdOffset={3}>
                                <AnswerButton label = {this.state.randomOrderAlt[0]}
                                    onAnswerClick={this.checkAnswer}
                                    buttonStyle = {this.state.buttonStyles[0]}
                                    disableButton = {this.state.buttonDisabled} />
                            </Col>
                            <Col xs={6} sm={4} md={3}>
                                <AnswerButton label = {this.state.randomOrderAlt[1]}
                                    onAnswerClick={this.checkAnswer}
                                    buttonStyle = {this.state.buttonStyles[1]}
                                    disableButton = {this.state.buttonDisabled} />
                            </Col>
                        </ButtonToolbar>
                    </Row>

                    <Row>
                        <ButtonToolbar>
                            <Col xs={6} sm={4} smOffset={2} md={3} mdOffset={3}>
                                <AnswerButton label = {this.state.randomOrderAlt[2]}
                                    onAnswerClick={this.checkAnswer}
                                    buttonStyle = {this.state.buttonStyles[2]}
                                    disableButton = {this.state.buttonDisabled} />
                            </Col>
                            <Col xs={6} sm={4} md={3}>
                                <AnswerButton label = {this.state.randomOrderAlt[3]}
                                    onAnswerClick = {this.checkAnswer}
                                    buttonStyle = {this.state.buttonStyles[3]}
                                    disableButton = {this.state.buttonDisabled} />
                            </Col>
                        </ButtonToolbar>
                    </Row>

                    <Row>

                            Fråga: {(Number(sessionStorage.currentQuestionIndex) + 1) + ' / '
                            + this.state.lessonLength}

                            {sessionStorage.correctAttempts + ' rätt' + this.getSuccessRate()}

                    </Row>
                    <Row>

                            <Button bsStyle="info" onClick={() =>
                            this.props.switchPage('GuessPlayPageSelection')}>
                                Ny spelomgång
                            </Button>

                    </Row>

                </Grid>

        );
    }
}<commit_msg>Switch ascii smileys to emoji in gameplay feedback<commit_after>import React from 'react';
import {Button, ButtonToolbar, Grid, Row, Col} from 'react-bootstrap';
import 'whatwg-fetch';
import AnswerButton from './answerbutton';

export default class GuessPlayPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {question: '',
            correctAlt: '',
            randomOrderAlt: ['', '', '', ''],
            buttonStyles: ['default', 'default', 'default', 'default'],
            buttonDisabled: false,
            lesson: [],
            currentQuestion: ''
        };
        this.setQuestion = this.setQuestion.bind(this);
        this.getNextQuestion = this.getNextQuestion.bind(this);
        this.checkAnswer = this.checkAnswer.bind(this);
        this.getSuccessRate = this.getSuccessRate.bind(this);
        this.onKeys = this.onKeys.bind(this);

        sessionStorage.setItem('correctAttempts', 0);
        sessionStorage.totalAttempts = 0;
        sessionStorage.currentQuestionIndex = 0;

    }
    componentDidMount() {
        window.addEventListener("keydown", this.onKeys);
        this.setState({
            lessonLength: JSON.parse(sessionStorage.lesson).length
        });
        this.setQuestion(0);
    }
    componentWillUnmount() {
        window.clearInterval(this.countDownVisible);
        window.removeEventListener("keydown", this.onKeys);
        sessionStorage.removeItem('currentQuestionIndex');

    }
    setQuestion(questionIndex) {
        this.setState({
            question: JSON.parse(sessionStorage.lesson)[questionIndex].question,
            correctAlt: JSON.parse(sessionStorage.lesson)[questionIndex].correctAlternative,
            randomOrderAlt: this.randomizeOrder([
                JSON.parse(sessionStorage.lesson)[questionIndex].alternative1,
                JSON.parse(sessionStorage.lesson)[questionIndex].alternative2,
                JSON.parse(sessionStorage.lesson)[questionIndex].alternative3,
                JSON.parse(sessionStorage.lesson)[questionIndex].correctAlternative]),
            buttonStyles: ['default', 'default', 'default', 'default'],
            buttonDisabled: false
        });
    }
    getNextQuestion(){
        if(Number(sessionStorage.currentQuestionIndex) + 1 < this.state.lessonLength){
            sessionStorage.currentQuestionIndex = Number(sessionStorage.currentQuestionIndex) + 1;
            this.setQuestion(Number(sessionStorage.currentQuestionIndex));
        } else {
            this.setState({
                buttonDisabled: true
            });
        }
    }
    randomizeOrder(array) {
        let i = array.length - 1;
        for (; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            const temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        };
        return array;
    }
    checkAnswer(answer) {
        let newButtonStyles = [];
        if (answer === this.state.correctAlt) {
            newButtonStyles = this.state.randomOrderAlt.map( (word) => (word === answer) ?
            'success' : 'default');
            sessionStorage.correctAttempts = Number(sessionStorage.correctAttempts) + 1;
        } else {
            newButtonStyles = this.state.randomOrderAlt.map( (word) => {
                if (word === answer) {
                    return 'danger';
                } else if(word === this.state.correctAlt) {
                    return 'success';
                } else {
                    return 'default';
                }
            });
        }
        sessionStorage.totalAttempts = Number(sessionStorage.totalAttempts) + 1;
        this.setState({
            buttonDisabled: true,
            buttonStyles: newButtonStyles
        });

        if(Number(sessionStorage.currentQuestionIndex) < this.state.lessonLength - 1){
            setTimeout(() => {
                this.getNextQuestion();
            }, 1000);
        } else {
            setTimeout(() => this.props.switchPage('EndScreenPage'), 1000);
        }
    }
    getSuccessRate(){
        let successRate = 0;
        let successRateMessage = '';
        const emojiFeedback = {
            veryBad : String.fromCodePoint(0x1F61E),
            bad : String.fromCodePoint(0x1F615),
            average : String.fromCodePoint(0x1F610),
            good : String.fromCodePoint(0x1F642),
            veryGood : String.fromCodePoint(0x1F600)
        };
        if (Number(sessionStorage.totalAttempts) > 0) {
            successRate = Number(sessionStorage.correctAttempts)
                / Number(sessionStorage.totalAttempts) * 100;
            successRateMessage = `${successRate.toFixed(0)} %`;
            if(successRate >= 80){
                return `, ${successRateMessage} ${emojiFeedback['veryGood']}`;
            } else if(successRate < 80 && successRate >= 60){
                return `, ${successRateMessage} ${emojiFeedback['good']}`;
            } else if(successRate < 60 && successRate >= 40){
                return `, ${successRateMessage} ${emojiFeedback['average']}`;
            } else if(successRate < 40 && successRate >= 20){
                return `, ${successRateMessage} ${emojiFeedback['bad']}`;
            } else if(successRate < 20){
                return `, ${successRateMessage} ${emojiFeedback['veryBad']}`;
            }
        } else {
              return successRateMessage;
        }
    }
    onKeys(event){
        let keyDown = event.key;
        if(!this.state.buttonDisabled){
            if (keyDown === '1') {
                this.checkAnswer(this.state.randomOrderAlt[0]);
            } else if (keyDown === '2') {
                this.checkAnswer(this.state.randomOrderAlt[1]);
            } else if (keyDown === '3') {
                this.checkAnswer(this.state.randomOrderAlt[2]);
            } else if (keyDown === '4') {
                this.checkAnswer(this.state.randomOrderAlt[3]);
            }
        }

    }
    render() {
        return (

                <Grid>
                    <Row>
{this.state.question}
</Row>

                    <Row>
                        <ButtonToolbar>
                            <Col xs={6} sm={4} smOffset={2} md={3} mdOffset={3}>
                                <AnswerButton label = {this.state.randomOrderAlt[0]}
                                    onAnswerClick={this.checkAnswer}
                                    buttonStyle = {this.state.buttonStyles[0]}
                                    disableButton = {this.state.buttonDisabled} />
                            </Col>
                            <Col xs={6} sm={4} md={3}>
                                <AnswerButton label = {this.state.randomOrderAlt[1]}
                                    onAnswerClick={this.checkAnswer}
                                    buttonStyle = {this.state.buttonStyles[1]}
                                    disableButton = {this.state.buttonDisabled} />
                            </Col>
                        </ButtonToolbar>
                    </Row>

                    <Row>
                        <ButtonToolbar>
                            <Col xs={6} sm={4} smOffset={2} md={3} mdOffset={3}>
                                <AnswerButton label = {this.state.randomOrderAlt[2]}
                                    onAnswerClick={this.checkAnswer}
                                    buttonStyle = {this.state.buttonStyles[2]}
                                    disableButton = {this.state.buttonDisabled} />
                            </Col>
                            <Col xs={6} sm={4} md={3}>
                                <AnswerButton label = {this.state.randomOrderAlt[3]}
                                    onAnswerClick = {this.checkAnswer}
                                    buttonStyle = {this.state.buttonStyles[3]}
                                    disableButton = {this.state.buttonDisabled} />
                            </Col>
                        </ButtonToolbar>
                    </Row>

                    <Row>

                            Fråga: {(Number(sessionStorage.currentQuestionIndex) + 1) + ' / '
                            + this.state.lessonLength}

                            {sessionStorage.correctAttempts + ' rätt' + this.getSuccessRate()}

                    </Row>
                    <Row>

                            <Button bsStyle="info" onClick={() =>
                            this.props.switchPage('GuessPlayPageSelection')}>
                                Ny spelomgång
                            </Button>

                    </Row>

                </Grid>

        );
    }
}<|endoftext|>


<commit_before>//viewmodel for the assess page
function pageViewModel(gvm) {
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableCoursesRapport = ko.observableArray([]);
    gvm.availableModules = ko.observableArray([]);
    gvm.availableSubmodules = ko.observableArray([]);
    gvm.availableGoals = ko.observableArray([]);

    gvm.currentCourseRapportId = null;
    gvm.currentModuleid = null;
    gvm.currentSubmoduleId = null;
    gvm.currentGoalId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownrapporten/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-courseRapport span:first").text(item.course);
                    $(".btn-module span:first").text(item.module);
                    $(".btn-submodule span:first").text(item.submodule);
                    $(".btn-goal span:first").text(item.goal);
                    gvm.currentCourseRapportId = item.courseid;
                    gvm.currentModuleid = item.moduleid;
                    gvm.currentSubmoduleId = item.submoduleid;
                    gvm.currentGoalId = item.goalid;
                    gvm.updateCourseRapport();
                    gvm.updateModules(item.moduleid);
                    gvm.updateSubmodules(item.submoduleid);
                    gvm.updateGoals(item.goalid);
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateCourseRapport();
            }
        });
    }

    //Houdt bij wat geselecteerd wordt
    //Wordt opgeroepen bij iedere wijziging (niet ingevulde velden = NULL)
    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["course"] = $(".btn-courseRapport span:first").text();
        data["courseid"] = gvm.currentCourseRapportId;
        data["module"] = $(".btn-module span:first").text();
        data["moduleid"] = gvm.currentModuleid;
        data["submodule"] = $(".btn-submodule span:first").text();
        data["submoduleid"] = gvm.currentSubmoduleId;
        data["goal"] = $(".btn-goal span:first").text();
        data["goalid"] = gvm.currentGoalId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdownsRapport",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateCourseRapport = function() {
        $.getJSON('/api/courserapportdrop', function(data) {
            gvm.availableCoursesRapport.removeAll();
            $.each(data, function(i, item) {
                //  Put item in list
                gvm.availableCoursesRapport.push(item);

                // Add listener to listitem
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentCourseRapportId = item.id;
                    gvm.currentModuleid = null;
                    gvm.currentSubmoduleId = null;
                    gvm.currentGoalId = null;
                    gvm.updateModules(item.id);
                    gvm.updateSubmodules(null);
                    gvm.updateGoals(null);
                    $(".btn-courseRapport span:first").text($(this).text());
                    $(".btn-module span:first").text("Module");
                    $(".btn-submodule span:first").text("Sub-module");
                    $(".btn-goal span:first").text("Goal");
                    gvm.saveLastSelectedDropdowns();
                    //method to get all students who follow this course
                });
            });
        });
    };

    /*
     * Update the module data
     */
    gvm.updateModules = function(id) {
        $.getJSON('/api/coursesrapport/' + id, function(data) {
            gvm.availableModules.removeAll();
            $.each(data, function(i, item) {
                gvm.availableModules.push(item);

                /* Add listener to listitem */
                $("#modulebtn-" + item.id).click(function(){
                    gvm.currentModuleid = item.id;
                    gvm.currentSubmoduleId = null;
                    gvm.currentGoalId = null;
                    gvm.updateSubmodules(item.id);
                    gvm.updateGoals(null);
                    $(".btn-module span:first").text($(this).text());
                    $(".btn-submodule span:first").text("Sub-module");
                    $(".btn-goal span:first").text("Goal");
                    gvm.saveLastSelectedDropdowns();
                    //method to get all students who follow this module
                });
            });
        });
    }

    /*
     * Update sub-module
     */
    gvm.updateSubmodules = function(id) {
        $.getJSON('/api/submodulerapport/' + id, function(data) {
            gvm.availableSubmodules.removeAll();
            $.each(data, function(i, item) {
                gvm.availableSubmodules.push(item);

                /* Add listener to listitem */
                $("#submodulebtn-" + item.id).click(function(){
                    $(".btn-submodule span:first").text($(this).text());
                    gvm.currentSubmoduleId = item.id;
                    gvm.currentGoalId = null;
                    gvm.updateGoals(item.id);
                    loadTablePage(item.id, 1);
                    $(".btn-goal span:first").text("Goal");
                    gvm.saveLastSelectedDropdowns();
                    //method to get all students who follow this submodule
                });
            });
        });
    }

    /*
     * Update goals
     */
    gvm.updateGoals = function(id) {
        $.getJSON('/api/goalrapport/' + id, function(data) {
            gvm.availableGoals.removeAll();
            $.each(data, function(i, item) {
                gvm.availableGoals.push(item);

                /* Add listener to listitem */
                $("#goalbtn-" + item.id).click(function(){
                    $(".btn-goal span:first").text($(this).text());
                    gvm.currentGoalId = item.id;
                    loadTablePage(item.id, 1);
                    gvm.saveLastSelectedDropdowns();
                    //method to get all students who follow this goal
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        //viewModel.updateDropdowns();
        viewModel.updateDropdowns();
    });
}
<commit_msg>undo test<commit_after>//viewmodel for the assess page
function pageViewModel(gvm) {
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableCoursesRapport = ko.observableArray([]);
    gvm.availableModules = ko.observableArray([]);
    gvm.availableSubmodules = ko.observableArray([]);
    gvm.availableGoals = ko.observableArray([]);

    gvm.currentCourseRapportId = null;
    gvm.currentModuleid = null;
    gvm.currentSubmoduleId = null;
    gvm.currentGoalId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownrapporten/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-courseRapport span:first").text(item.course);
                    $(".btn-module span:first").text(item.module);
                    $(".btn-submodule span:first").text(item.submodule);
                    $(".btn-goal span:first").text(item.goal);
                    gvm.currentCourseRapportId = item.courseid;
                    gvm.currentModuleid = item.moduleid;
                    gvm.currentSubmoduleId = item.submoduleid;
                    gvm.currentGoalId = item.goalid;
                    gvm.updateCourseRapport();
                    gvm.updateModules(item.moduleid);
                    gvm.updateSubmodules(item.submoduleid);
                    gvm.updateGoals(item.goalid);
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateCourseRapport();
            }
        });
    }

    //Houdt bij wat geselecteerd wordt
    //Wordt opgeroepen bij iedere wijziging (niet ingevulde velden = NULL)
    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["course"] = $(".btn-courseRapport span:first").text();
        data["courseid"] = gvm.currentCourseRapportId;
        data["module"] = $(".btn-module span:first").text();
        data["moduleid"] = gvm.currentModuleid;
        data["submodule"] = $(".btn-submodule span:first").text();
        data["submoduleid"] = gvm.currentSubmoduleId;
        data["goal"] = $(".btn-goal span:first").text();
        data["goalid"] = gvm.currentGoalId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdownsRapport",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateCourseRapport = function() {
        $.getJSON('/api/courserapportdrop', function(data) {
            gvm.availableCoursesRapport.removeAll();
            $.each(data, function(i, item) {
                //  Put item in list
                gvm.availableCoursesRapport.push(item);

                // Add listener to listitem
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentCourseRapportId = item.id;
                    gvm.currentModuleid = null;
                    gvm.currentSubmoduleId = null;
                    gvm.currentGoalId = null;
                    gvm.updateModules(item.id);
                    gvm.updateSubmodules(null);
                    gvm.updateGoals(null);
                    $(".btn-courseRapport span:first").text($(this).text());
                    $(".btn-module span:first").text("Module");
                    $(".btn-submodule span:first").text("Sub-module");
                    $(".btn-goal span:first").text("Goal");
                    gvm.saveLastSelectedDropdowns();
                    //method to get all students who follow this course
                });
            });
        });
    };

    /*
     * Update the module data
     */
    gvm.updateModules = function(id) {
        $.getJSON('/api/coursesrapport/' + id, function(data) {
            gvm.availableModules.removeAll();
            $.each(data, function(i, item) {
                gvm.availableModules.push(item);

                /* Add listener to listitem */
                $("#modulebtn-" + item.id).click(function(){
                    gvm.currentModuleid = item.id;
                    gvm.currentSubmoduleId = null;
                    gvm.currentGoalId = null;
                    gvm.updateSubmodules(item.id);
                    gvm.updateGoals(null);
                    $(".btn-module span:first").text($(this).text());
                    $(".btn-submodule span:first").text("Sub-module");
                    $(".btn-goal span:first").text("Goal");
                    gvm.saveLastSelectedDropdowns();
                    //method to get all students who follow this module
                });
            });
        });
    }

    /*
     * Update sub-module
     */
    gvm.updateSubmodules = function(id) {
        $.getJSON('/api/submodulerapport/' + id, function(data) {
            gvm.availableSubmodules.removeAll();
            $.each(data, function(i, item) {
                gvm.availableSubmodules.push(item);

                /* Add listener to listitem */
                $("#submodulebtn-" + item.id).click(function(){
                    $(".btn-submodule span:first").text($(this).text());
                    gvm.currentSubmoduleId = item.id;
                    gvm.currentGoalId = null;
                    gvm.updateGoals(item.id);
                    loadTablePage(item.id, 1);
                    $(".btn-goal span:first").text("Goal");
                    gvm.saveLastSelectedDropdowns();
                    //method to get all students who follow this submodule
                });
            });
        });
    }

    /*
     * Update goals
     */
    gvm.updateGoals = function(id) {
        $.getJSON('/api/goalrapport/' + id, function(data) {
            gvm.availableGoals.removeAll();
            $.each(data, function(i, item) {
                gvm.availableGoals.push(item);

                /* Add listener to listitem */
                $("#goalbtn-" + item.id).click(function(){
                    $(".btn-goal span:first").text($(this).text());
                    gvm.currentGoalId = item.id;
                    loadTablePage(item.id, 1);
                    gvm.saveLastSelectedDropdowns();
                    //method to get all students who follow this goal
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        //viewModel.updateDropdowns();
        viewModel.updateDropdowns();
    });
}
<|endoftext|>


<commit_before>//viewmodel for the assess page
function pageViewModel(gvm) {
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableSubmodules = ko.observableArray([]);
    gvm.availableGoals = ko.observableArray([]);

    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;
    gvm.currentSubmoduleId = null;
    gvm.currentCourseId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-submodule span:first").text(item.course);
                    $(".btn-goal span:first").text(item.goal);
                    gvm.currentLocationId = item.locationid;
                    gvm.currentTrainingid = item.trainingid;
                    gvm.currentCourseId = item.courseid;
                    gvm.currentGoalId = item.goalid;
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid);
                    gvm.updateSubmodules(item.trainingid);
                    gvm.updateGoals(item.courseid);
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["submodule"] = $(".btn-submodule span:first").text();
        data["submoduleid"] = gvm.currentCourseId;
        data["goal"] = $(".btn-goal span:first").text();
        data["goalid"] = gvm.currentGoalId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateLocations = function() {
        $.getJSON('/api/courserapportdrop', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
              //  Put item in list
                gvm.availableLocations.push(item);

                // Add listener to listitem
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentCourseId = null;
                    gvm.currentGoalId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                    $(".btn-training span:first").text("module");
                    $(".btn-submodule span:first").text("sub-module");
                    $(".btn-goal span:first").text("goal");
                });
            });
        });
    };

    /*
     * Update the course data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/coursesrapport/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = item.id;
                    gvm.currentCourseId = null;
                    gvm.updateSubmodules(item.id);
                    $(".btn-training span:first").text($(this).text());
                    $(".btn-submodule span:first").text("course");
                });
            });
        });
    }

    /*
     * Update sub-module
     */
    gvm.updateSubmodules = function(id) {
        $.getJSON('/api/submodulerapport/' + id, function(data) {
            gvm.availableSubmodules.removeAll();
            $.each(data, function(i, item) {
                gvm.availableSubmodules.push(item);

                /* Add listener to listitem */
                $("#submodulebtn-" + item.id).click(function(){
                    $(".btn-submodule span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    /*
     * Update goals
     */
    gvm.updateGoals = function(id) {
        $.getJSON('/api/goalrapport/' + id, function(data) {
            gvm.availableGoals.removeAll();
            $.each(data, function(i, item) {
                gvm.availableGoals.push(item);

                /* Add listener to listitem */
                $("#goalbtn-" + item.id).click(function(){
                    $(".btn-goal span:first").text($(this).text());
                    gvm.currentGoalId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<commit_msg>courseid --> submoduleid<commit_after>//viewmodel for the assess page
function pageViewModel(gvm) {
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableSubmodules = ko.observableArray([]);
    gvm.availableGoals = ko.observableArray([]);

    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;
    gvm.currentSubmoduleId = null;
    gvm.currentCourseId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-submodule span:first").text(item.course);
                    $(".btn-goal span:first").text(item.goal);
                    gvm.currentLocationId = item.locationid;
                    gvm.currentTrainingid = item.trainingid;
                    gvm.currentCourseId = item.submoduleid;
                    gvm.currentGoalId = item.goalid;
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid);
                    gvm.updateSubmodules(item.trainingid);
                    gvm.updateGoals(item.submoduleid);
                    loadTablePage(item.submoduleid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-submodule span:first").text();
        data["submoduleid"] = gvm.currentCourseId;
        data["goal"] = $(".btn-goal span:first").text();
        data["goalid"] = gvm.currentGoalId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateLocations = function() {
        $.getJSON('/api/courserapportdrop', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
              //  Put item in list
                gvm.availableLocations.push(item);

                // Add listener to listitem
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentCourseId = null;
                    gvm.currentGoalId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                    $(".btn-training span:first").text("module");
                    $(".btn-submodule span:first").text("sub-module");
                    $(".btn-goal span:first").text("goal");
                });
            });
        });
    };

    /*
     * Update the course data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/coursesrapport/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = item.id;
                    gvm.currentCourseId = null;
                    gvm.updateSubmodules(item.id);
                    $(".btn-training span:first").text($(this).text());
                    $(".btn-submodule span:first").text("course");
                });
            });
        });
    }

    /*
     * Update sub-module
     */
    gvm.updateSubmodules = function(id) {
        $.getJSON('/api/submodulerapport/' + id, function(data) {
            gvm.availableSubmodules.removeAll();
            $.each(data, function(i, item) {
                gvm.availableSubmodules.push(item);

                /* Add listener to listitem */
                $("#submodulebtn-" + item.id).click(function(){
                    $(".btn-submodule span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    /*
     * Update goals
     */
    gvm.updateGoals = function(id) {
        $.getJSON('/api/goalrapport/' + id, function(data) {
            gvm.availableGoals.removeAll();
            $.each(data, function(i, item) {
                gvm.availableGoals.push(item);

                /* Add listener to listitem */
                $("#goalbtn-" + item.id).click(function(){
                    $(".btn-goal span:first").text($(this).text());
                    gvm.currentGoalId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(submoduleid, pagenr)
{
    $.getJSON('/api/projects/' + submoduleid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(submoduleid, thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<|endoftext|>


<commit_before>import { vec3, mat4 } from 'gl-matrix';
import macro from 'vtk.js/Sources/macros';
import vtkCompositeCameraManipulator from 'vtk.js/Sources/Interaction/Manipulators/CompositeCameraManipulator';
import vtkCompositeMouseManipulator from 'vtk.js/Sources/Interaction/Manipulators/CompositeMouseManipulator';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';

// ----------------------------------------------------------------------------
// vtkMouseCameraTrackballRotateManipulator methods
// ----------------------------------------------------------------------------

function vtkMouseCameraTrackballRotateManipulator(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkMouseCameraTrackballRotateManipulator');

  const newCamPos = new Float64Array(3);
  const newFp = new Float64Array(3);
  const newViewUp = new Float64Array(3);
  const trans = new Float64Array(16);
  const v2 = new Float64Array(3);
  const centerNeg = new Float64Array(3);
  const direction = new Float64Array(3);

  publicAPI.onButtonDown = (interactor, renderer, position) => {
    model.previousPosition = position;
  };

  publicAPI.onMouseMove = (interactor, renderer, position) => {
    if (!position) {
      return;
    }

    const camera = renderer.getActiveCamera();
    const cameraPos = camera.getPosition();
    const cameraFp = camera.getFocalPoint();

    mat4.identity(trans);

    const { center, rotationFactor } = model;

    if (model.useFocalPointAsCenterOfRotation) {
      center[0] = cameraFp[0];
      center[1] = cameraFp[1];
      center[2] = cameraFp[2];
    }

    const dx = model.previousPosition.x - position.x;
    const dy = model.previousPosition.y - position.y;

    const size = interactor.getView().getSize();

    // Azimuth
    const viewUp = camera.getViewUp();
    if (model.useWorldUpVec) {
      const centerOfRotation = new Float64Array(3);
      vec3.copy(centerOfRotation, model.worldUpVec);

      // Compute projection of cameraPos onto worldUpVec
      vtkMath.multiplyScalar(
        centerOfRotation,
        vtkMath.dot(cameraPos, model.worldUpVec) /
          vtkMath.dot(model.worldUpVec, model.worldUpVec)
      );

      if (model.useFocalPointAsCenterOfRotation) {
        vtkMath.add(center, centerOfRotation, centerOfRotation);
      }

      mat4.translate(trans, trans, centerOfRotation);
      mat4.rotate(
        trans,
        trans,
        vtkMath.radiansFromDegrees(((360.0 * dx) / size[0]) * rotationFactor),
        model.worldUpVec
      );

      // Translate back
      if (model.useFocalPointAsCenterOfRotation) {
        centerOfRotation[0] = -centerOfRotation[0];
        centerOfRotation[1] = -centerOfRotation[1];
        centerOfRotation[2] = -centerOfRotation[2];
        mat4.translate(trans, trans, centerOfRotation);
        mat4.translate(trans, trans, center);
      } else {
        mat4.translate(
          trans,
          trans,
          vtkMath.subtract(center, centerOfRotation, centerOfRotation)
        );
      }
    } else {
      mat4.translate(trans, trans, center);
      mat4.rotate(
        trans,
        trans,
        vtkMath.radiansFromDegrees(((360.0 * dx) / size[0]) * rotationFactor),
        viewUp
      );
    }

    // Elevation
    vtkMath.cross(camera.getDirectionOfProjection(), viewUp, v2);
    mat4.rotate(
      trans,
      trans,
      vtkMath.radiansFromDegrees(((-360.0 * dy) / size[1]) * rotationFactor),
      v2
    );

    // Translate back
    centerNeg[0] = -center[0];
    centerNeg[1] = -center[1];
    centerNeg[2] = -center[2];
    mat4.translate(trans, trans, centerNeg);

    // Apply transformation to camera position, focal point, and view up
    vec3.transformMat4(newCamPos, cameraPos, trans);
    vec3.transformMat4(newFp, cameraFp, trans);
    direction[0] = viewUp[0] + cameraPos[0];
    direction[1] = viewUp[1] + cameraPos[1];
    direction[2] = viewUp[2] + cameraPos[2];
    vec3.transformMat4(newViewUp, direction, trans);

    camera.setPosition(newCamPos[0], newCamPos[1], newCamPos[2]);
    camera.setFocalPoint(newFp[0], newFp[1], newFp[2]);
    camera.setViewUp(
      newViewUp[0] - newCamPos[0],
      newViewUp[1] - newCamPos[1],
      newViewUp[2] - newCamPos[2]
    );
    camera.orthogonalizeViewUp();

    renderer.resetCameraClippingRange();

    if (interactor.getLightFollowCamera()) {
      renderer.updateLightsGeometryToFollowCamera();
    }

    model.previousPosition = position;
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  useWorldUpVec: false,
  // set WorldUpVector to be y-axis by default
  worldUpVec: [0, 1, 0],
  useFocalPointAsCenterOfRotation: false,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Inheritance
  macro.obj(publicAPI, model);
  vtkCompositeMouseManipulator.extend(publicAPI, model, initialValues);
  vtkCompositeCameraManipulator.extend(publicAPI, model, initialValues);

  // Create get-set macro
  macro.setGet(publicAPI, model, ['useWorldUpVec']);
  macro.setGetArray(publicAPI, model, ['worldUpVec'], 3);
  macro.setGet(publicAPI, model, ['useFocalPointAsCenterOfRotation']);

  // Object specific methods
  vtkMouseCameraTrackballRotateManipulator(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(
  extend,
  'vtkMouseCameraTrackballRotateManipulator'
);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(View): Fix center of rotation when used with world up vector setting<commit_after>import { vec3, mat4 } from 'gl-matrix';
import macro from 'vtk.js/Sources/macros';
import vtkCompositeCameraManipulator from 'vtk.js/Sources/Interaction/Manipulators/CompositeCameraManipulator';
import vtkCompositeMouseManipulator from 'vtk.js/Sources/Interaction/Manipulators/CompositeMouseManipulator';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';

// ----------------------------------------------------------------------------
// vtkMouseCameraTrackballRotateManipulator methods
// ----------------------------------------------------------------------------

function vtkMouseCameraTrackballRotateManipulator(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkMouseCameraTrackballRotateManipulator');

  const newCamPos = new Float64Array(3);
  const newFp = new Float64Array(3);
  const newViewUp = new Float64Array(3);
  const trans = new Float64Array(16);
  const v2 = new Float64Array(3);
  const centerNeg = new Float64Array(3);
  const direction = new Float64Array(3);

  publicAPI.onButtonDown = (interactor, renderer, position) => {
    model.previousPosition = position;
  };

  publicAPI.onMouseMove = (interactor, renderer, position) => {
    if (!position) {
      return;
    }

    const camera = renderer.getActiveCamera();
    const cameraPos = camera.getPosition();
    const cameraFp = camera.getFocalPoint();

    mat4.identity(trans);

    const { center, rotationFactor } = model;

    if (model.useFocalPointAsCenterOfRotation) {
      center[0] = cameraFp[0];
      center[1] = cameraFp[1];
      center[2] = cameraFp[2];
    }

    const dx = model.previousPosition.x - position.x;
    const dy = model.previousPosition.y - position.y;

    const size = interactor.getView().getSize();

    // Azimuth
    const viewUp = camera.getViewUp();
    if (model.useWorldUpVec) {
      const centerOfRotation = new Float64Array(3);
      vec3.copy(centerOfRotation, model.worldUpVec);

      // Compute projection of cameraPos onto worldUpVec
      vtkMath.multiplyScalar(
        centerOfRotation,
        vtkMath.dot(cameraPos, model.worldUpVec) /
          vtkMath.dot(model.worldUpVec, model.worldUpVec)
      );

      vtkMath.add(center, centerOfRotation, centerOfRotation);

      mat4.translate(trans, trans, centerOfRotation);
      mat4.rotate(
        trans,
        trans,
        vtkMath.radiansFromDegrees(((360.0 * dx) / size[0]) * rotationFactor),
        model.worldUpVec
      );

      // Translate back
      centerOfRotation[0] = -centerOfRotation[0];
      centerOfRotation[1] = -centerOfRotation[1];
      centerOfRotation[2] = -centerOfRotation[2];
      mat4.translate(trans, trans, centerOfRotation);
      mat4.translate(trans, trans, center);
    } else {
      mat4.translate(trans, trans, center);
      mat4.rotate(
        trans,
        trans,
        vtkMath.radiansFromDegrees(((360.0 * dx) / size[0]) * rotationFactor),
        viewUp
      );
    }

    // Elevation
    vtkMath.cross(camera.getDirectionOfProjection(), viewUp, v2);
    mat4.rotate(
      trans,
      trans,
      vtkMath.radiansFromDegrees(((-360.0 * dy) / size[1]) * rotationFactor),
      v2
    );

    // Translate back
    centerNeg[0] = -center[0];
    centerNeg[1] = -center[1];
    centerNeg[2] = -center[2];
    mat4.translate(trans, trans, centerNeg);

    // Apply transformation to camera position, focal point, and view up
    vec3.transformMat4(newCamPos, cameraPos, trans);
    vec3.transformMat4(newFp, cameraFp, trans);
    direction[0] = viewUp[0] + cameraPos[0];
    direction[1] = viewUp[1] + cameraPos[1];
    direction[2] = viewUp[2] + cameraPos[2];
    vec3.transformMat4(newViewUp, direction, trans);

    camera.setPosition(newCamPos[0], newCamPos[1], newCamPos[2]);
    camera.setFocalPoint(newFp[0], newFp[1], newFp[2]);
    camera.setViewUp(
      newViewUp[0] - newCamPos[0],
      newViewUp[1] - newCamPos[1],
      newViewUp[2] - newCamPos[2]
    );
    camera.orthogonalizeViewUp();

    renderer.resetCameraClippingRange();

    if (interactor.getLightFollowCamera()) {
      renderer.updateLightsGeometryToFollowCamera();
    }

    model.previousPosition = position;
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  useWorldUpVec: false,
  // set WorldUpVector to be y-axis by default
  worldUpVec: [0, 1, 0],
  useFocalPointAsCenterOfRotation: false,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Inheritance
  macro.obj(publicAPI, model);
  vtkCompositeMouseManipulator.extend(publicAPI, model, initialValues);
  vtkCompositeCameraManipulator.extend(publicAPI, model, initialValues);

  // Create get-set macro
  macro.setGet(publicAPI, model, ['useWorldUpVec']);
  macro.setGetArray(publicAPI, model, ['worldUpVec'], 3);
  macro.setGet(publicAPI, model, ['useFocalPointAsCenterOfRotation']);

  // Object specific methods
  vtkMouseCameraTrackballRotateManipulator(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(
  extend,
  'vtkMouseCameraTrackballRotateManipulator'
);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>function User(userID, login, fullName, firstName, lastName, color)
{
	if (userID !== undefined && login === undefined && fullName === undefined && firstName === undefined &&
		lastName === undefined && color === undefined)
	{
		// Just look up an existing user
		return User.prototype.users[userID];
	}
	else
	{
		// Create a new instance.
		this.id = userID;
		this.login = login;
		this.fullName = fullName;
		this.firstName = firstName;
		this.lastName = lastName;
		this.color = color;

		// Cache the instance for later lookups.
 		User.prototype.users[userID] = this;
	}

	return this;
};

User.prototype.users = {};

User.all = function()
{
	return User.prototype.users;
};

/**
 * Gets the user object belonging the passed ID and calls the passed function
 * with this as parameter. If the user object is not available, an update of
 * the user cache is scheduled before.
 */
User.auto_update_call = function(user_id, fn)
{
  if (user_id in User.prototype.users) {
    fn(User.prototype.users[user_id]);
  } else {
    User.getUsers(function() {
      // Expect it to be there after the update
      fn(User.prototype.users[user_id]);
    });
  }
};

User.getUsers = function(completionCallback)
{
	// Asynchronously request the list of users from the server.
	requestQueue.register(django_url + 'user-list',
							'GET',
							undefined,
							function (status, text, xml) {
								User.prototype.handleGetUsers(status, text, xml);
								if (completionCallback !== undefined) {
									completionCallback();
								}
							});
};

User.prototype.handleGetUsers = function(status, text, xml)
{
	if (status == 200 && text)
	{
		var jsonData = $.parseJSON(text);
		for (var i = 0; i < jsonData.length; i++)
		{
			var userData = jsonData[i];
			new User(userData.id, userData.login, userData.full_name, userData.first_name, userData.last_name,
			         new THREE.Color().setRGB(userData.color[0], userData.color[1], userData.color[2]));
		}
	}
	else
	{
		new ErrorDialog("The list of users could not be retrieved.",
			text + "\n\n(Status: " + status + ")").show();
	}
};
<commit_msg>Add standard formatting header to user front-end file and reformat it<commit_after>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

function User(userID, login, fullName, firstName, lastName, color)
{
  if (userID !== undefined && login === undefined && fullName === undefined &&
      firstName === undefined && lastName === undefined && color === undefined)
  {
    // Just look up an existing user
    return User.prototype.users[userID];
  }
  else
  {
    // Create a new instance.
    this.id = userID;
    this.login = login;
    this.fullName = fullName;
    this.firstName = firstName;
    this.lastName = lastName;
    this.color = color;

    // Cache the instance for later lookups.
    User.prototype.users[userID] = this;
  }

  return this;
};

User.prototype.users = {};

User.all = function()
{
  return User.prototype.users;
};

/**
 * Gets the user object belonging the passed ID and calls the passed function
 * with this as parameter. If the user object is not available, an update of
 * the user cache is scheduled before.
 */
User.auto_update_call = function(user_id, fn)
{
  if (user_id in User.prototype.users) {
    fn(User.prototype.users[user_id]);
  } else {
    User.getUsers(function() {
      // Expect it to be there after the update
      fn(User.prototype.users[user_id]);
    });
  }
};

User.getUsers = function(completionCallback)
{
  // Asynchronously request the list of users from the server.
  requestQueue.register(django_url + 'user-list',
      'GET',
      undefined,
      function (status, text, xml) {
        User.prototype.handleGetUsers(status, text, xml);
        if (completionCallback !== undefined) {
          completionCallback();
        }
      });
};

User.prototype.handleGetUsers = function(status, text, xml)
{
  if (status == 200 && text)
  {
    var jsonData = $.parseJSON(text);
    for (var i = 0; i < jsonData.length; i++)
    {
      var userData = jsonData[i];
      new User(userData.id, userData.login, userData.full_name,
          userData.first_name, userData.last_name, new THREE.Color().setRGB(
              userData.color[0], userData.color[1], userData.color[2]));
    }
  }
  else
  {
    new ErrorDialog("The list of users could not be retrieved.",
      text + "\n\n(Status: " + status + ")").show();
  }
};
<|endoftext|>


<commit_before>var cdb = require('cartodb.js');
var _ = require('underscore');
var $ = require('jquery');
var BaseDialog = require('../../views/base_dialog/view.js');
var randomQuote = require('../../view_helpers/random_quote.js');
var ViewFactory = require('../../view_factory.js');
var ViewModel = require('./add_custom_basemap_model.js');
var TabsView = require('./tabs_view.js');

/**
 * Dialog to add ¯custom basemap to current map.
 */
module.exports = BaseDialog.extend({

  className: 'Dialog is-opening CustomBasemap',

  // TODO: Remove once all tabs are implemented
  events: function() {
    return _.extend({}, BaseDialog.prototype.events, {
      'click .js-open-old-dialog': '_openOldDialog'
    });
  },

  initialize: function() {
    this.elder('initialize');
    this.model = new ViewModel({
      map: this.options.map,
      baseLayers: this.options.baseLayers
    });
    this._initViews();
    this._initBinds();
  },

  /**
   * @override cdb.ui.common.Dialog.prototype.render
   */
  render: function() {
    BaseDialog.prototype.render.apply(this, arguments);
    this.$('.content').addClass('Dialog-contentWrapper');
    return this;
  },

  /**
   * @implements cdb.ui.common.Dialog.prototype.render_content
   */
  render_content: function() {
    var contentView = this._panes.active(this.model.get('currentView')).render();
    contentView.$el.addClass('Dialog-body Dialog-body--expanded CreateDialog-body');
    contentView.delegateEvents(); // enable events after being added to $el
    var $el = $(
      cdb.templates.getTemplate('common/dialogs/add_custom_basemap/add_custom_basemap')({
        model: this.model
      })
    );
    $el.append(contentView.el);
    return $el;
  },

  ok: function() {
    if (this.model.canSaveBasemap()) {
      this.model.saveBasemap();
    }
  },

  _initViews: function() {
    this._panes = new cdb.ui.common.TabPane({
      el: this.el
    });
    this.addView(this._panes);
    this._panes.addTab('tabs',
      new TabsView({
        model: this.model,
        openOldDialog: this.options.openOldDialog
      })
    );
    this._panes.addTab('saving',
      ViewFactory.createByTemplate('common/templates/loading', {
        title: 'Setting basemap…',
        quote: randomQuote()
      }).render()
    );
    this._panes.addTab('saveFail',
      ViewFactory.createByTemplate('common/templates/fail', {
        msg: ''
      }).render()
    );
    this._panes.active(this.model.get('currentView'));
  },

  _initBinds: function() {
    this.model.bind('change:currentView', this._onCurrentViewChange, this);
  },

  // TODO: Remove once all tabs are implemented
  _openOldDialog: function(ev) {
    this.killEvent(ev);
    this.options.openOldDialog();
    this.hide();
  },

  _onCurrentViewChange: function() {
    if (this.model.get('currentView') === 'saveDone') {
      this.close();
    } else {
      this.render();
    }
  }

});
<commit_msg>Removed unnecessary className for add_custom_basemap dialog<commit_after>var cdb = require('cartodb.js');
var _ = require('underscore');
var $ = require('jquery');
var BaseDialog = require('../../views/base_dialog/view.js');
var randomQuote = require('../../view_helpers/random_quote.js');
var ViewFactory = require('../../view_factory.js');
var ViewModel = require('./add_custom_basemap_model.js');
var TabsView = require('./tabs_view.js');

/**
 * Dialog to add ¯custom basemap to current map.
 */
module.exports = BaseDialog.extend({

  // TODO: Remove once all tabs are implemented
  events: function() {
    return _.extend({}, BaseDialog.prototype.events, {
      'click .js-open-old-dialog': '_openOldDialog'
    });
  },

  initialize: function() {
    this.elder('initialize');
    this.model = new ViewModel({
      map: this.options.map,
      baseLayers: this.options.baseLayers
    });
    this._initViews();
    this._initBinds();
  },

  /**
   * @override cdb.ui.common.Dialog.prototype.render
   */
  render: function() {
    BaseDialog.prototype.render.apply(this, arguments);
    this.$('.content').addClass('Dialog-contentWrapper');
    return this;
  },

  /**
   * @implements cdb.ui.common.Dialog.prototype.render_content
   */
  render_content: function() {
    var contentView = this._panes.active(this.model.get('currentView')).render();
    contentView.$el.addClass('Dialog-body Dialog-body--expanded CreateDialog-body');
    contentView.delegateEvents(); // enable events after being added to $el
    var $el = $(
      cdb.templates.getTemplate('common/dialogs/add_custom_basemap/add_custom_basemap')({
        model: this.model
      })
    );
    $el.append(contentView.el);
    return $el;
  },

  ok: function() {
    if (this.model.canSaveBasemap()) {
      this.model.saveBasemap();
    }
  },

  _initViews: function() {
    this._panes = new cdb.ui.common.TabPane({
      el: this.el
    });
    this.addView(this._panes);
    this._panes.addTab('tabs',
      new TabsView({
        model: this.model,
        openOldDialog: this.options.openOldDialog
      })
    );
    this._panes.addTab('saving',
      ViewFactory.createByTemplate('common/templates/loading', {
        title: 'Setting basemap…',
        quote: randomQuote()
      }).render()
    );
    this._panes.addTab('saveFail',
      ViewFactory.createByTemplate('common/templates/fail', {
        msg: ''
      }).render()
    );
    this._panes.active(this.model.get('currentView'));
  },

  _initBinds: function() {
    this.model.bind('change:currentView', this._onCurrentViewChange, this);
  },

  // TODO: Remove once all tabs are implemented
  _openOldDialog: function(ev) {
    this.killEvent(ev);
    this.options.openOldDialog();
    this.hide();
  },

  _onCurrentViewChange: function() {
    if (this.model.get('currentView') === 'saveDone') {
      this.close();
    } else {
      this.render();
    }
  }

});
<|endoftext|>