<commit_before>var config = require('../../config.js');

module.exports = function(){

    function isAscii(input){
       return config.regex.ascii.test(input);
    }

    function getEquation(input){
        if(isAscii(input))
            return input.replace(config.regex.filter,"");

        return false
    }

    return {
        isAscii: isAscii,
        getEquation : getEquation
    };
}();<commit_msg>added infix to postfix<commit_after>var config = require('../../config.js');

module.exports = function(){

    function isAscii(input){
        return config.regex.ascii.test(input);
    }

    function getEquation(input){
        if(isAscii(input))
            return input.replace(config.regex.filter, "");

        return false
    }

    function infixToPostfix(input){
        var pemdas = config.math.pemdas;
        var operators = config.regex.operators;
        var stack = [];
        input = input.replace(operators,",$1,")
        input = input.split(",");

        input = input.filter(function(result){
                return result.trim() != '';
        });

        var result = "";

        input.forEach(function(value, key, array){
            if(!(value in pemdas)){
                result = result.concat(value + " ");
            }else{
                if(stack.length == 0){
                    stack.push(value);
                }else if(pemdas[value] == pemdas[stack[stack.length - 1]] ||
                    pemdas[value] > pemdas[stack[stack.length - 1]]){
                    var temp = stack.pop();

                    if(temp != '('){
                        stack.push(temp);
                        result = result.concat(stack.pop() + " ");
                    }else{
                        stack.push(temp);
                    }
                    stack.push(value);
                }else if(value == ')'){
                    result = result.concat(stack.pop() + " ");
                    stack.pop();
                }else{
                    stack.push(value);
                }
            }

            if(key === array.length - 1){
                for(i = 0; i <= stack.length; i++){
                    result = result.concat(stack.pop() + " ");
                }
            }
        });

        return result.trim();
    }

    return{
        isAscii        : isAscii,
        getEquation    : getEquation,
        infixToPostfix : infixToPostfix
    };
}();<|endoftext|>


<commit_before>'use strict';

var readJson = require('./readJson')
var Promise = require('bluebird')
var _ = require('lodash')
var add = require('./add')
var db = require('./db')
var buildDeptNum = require('./deptNum').buildDeptNum
var deptNumToCrsidCache = require('./getCourses').deptNumToCrsidCache

var logDataLoading = false

function storeCourses(item) {
	return new Promise(function(resolve, reject) {
		console.log(item.meta.path, 'called storeCourses')

		var courses = _.map(item.data.courses, function(course) {
			course.sourcePath = item.meta.path
			course.deptnum = buildDeptNum(course)
			deptNumToCrsidCache[course.deptnum] = course.crsid
			return course
		})

		db.store('courses').batch(courses)
			.then(function(results) {
				resolve(item)
			}).catch(function (records, err) {
				reject(err)
			})
	})
}

function storeArea(item) {
	return new Promise(function(resolve, reject) {
		console.log(item.meta.path, 'called storeArea')

		var area = item.data.info
		area.sourcePath = item.meta.path

		db.store('areas').put(area)
			.then(function(results) {
				resolve(item)
			}).catch(function(records, err) {
				reject(err)
			})
	})
}

function storeItem(item) {
	if (item.type === 'courses') {
		return storeCourses(item)
	} else if (item.type === 'areas') {
		return storeArea(item)
	}
}

function cleanPriorData(item) {
	return new Promise(function (resolve, reject) {
		var path = item.meta.path
		console.info('deleting ' + item.type + ' from ' + path)

		var deleteItemsPromise = db.store(item.type).del(path)

		deleteItemsPromise
			.then(function() {
				localStorage.removeItem(path)
				resolve(item)
			}).catch(function(err) {
				reject(err)
			})
	})
}

function cacheItemHash(item) {
	return new Promise(function(resolve, reject) {
		console.info(item.meta.path + ' called cacheItemHash')
		localStorage.setItem(item.meta.path, item.meta.hash)
		resolve(item)
	})
}

var lookup = {
	'courses': 'courses',
	'areas': 'info'
}

function updateDatabase(itemType, infoFromServer) {
	infoFromServer.path = '/data/' + itemType + '/' + infoFromServer.path
	var oldHash = localStorage.getItem(infoFromServer.path)
	var newHash = infoFromServer.hash
	var itemPath = infoFromServer.path

	if (newHash === oldHash) {
		if (logDataLoading) {
			console.log('skipped ' + itemPath)
		}
		return Promise.resolve(false)
	}

	if (logDataLoading) {
		console.log('need to add ' + itemPath)
	}

	return readJson(itemPath)
		.then(function(data) {
			return {
				data: data,
				meta: infoFromServer,
				type: itemType,
				count: _.size(data[lookup[itemType]]) || 1,
			}
		})
		.then(cleanPriorData)
		.then(storeItem)
		.then(cacheItemHash)
		.catch(function(err) {
			return Promise.reject(err.stack)
		})
		.done(function(item) {
			if (logDataLoading) {
				console.log('added '+item.meta.path+' ('+item.count+' '+item.type+')')
			}
			return Promise.resolve(true)
		})
}

function loadDataFiles(infoFile) {
	console.log('load data files', infoFile)

	return Promise.all(_.map(infoFile.info, function(files) {
		return Promise.all(_.map(files, function(file) {
			return updateDatabase(infoFile.type, file)
		}))
	}))
}

/*
function loadDataFiles(infoFile) {
	console.log('load data files', infoFile)

	var progress = 0;
	var notification = new Cortex({
		message: 'Updating ' + infoFile.type,
		hasProgress: true,
		progressValue: progress,
		maxProgressValue: _.chain(infoFile.info).mapValues(_.size).reduce(add).value(),
		ident: infoFile.type
	})
	window.notifications.push(notification.val())

	return Promise.all(_.map(infoFile.info, function(files) {
		var allFilesLoadedPromise = Promise.all(_.map(files, function(file) {
			var dbUpdatedPromise = updateDatabase(infoFile.type, file)
			dbUpdatedPromise.then(function() {
				notification.progressValue.set(progress += 1)
			})
			return dbUpdatedPromise
		}))

		allFilesLoadedPromise.then(function() {
			setTimeout(notification.remove, 200)
		})

		return allFilesLoadedPromise
	}))
}
*/

function loadInfoFile(url) {
	console.log('loading', url)
	return readJson(url).then(loadDataFiles)
}

function loadData() {
	var infoFiles = [
		'/data/areas/info.json',
		'/data/courses/info.json',
	]
	return Promise.all(_.map(infoFiles, loadInfoFile))
}

module.exports = window.loadData = loadData
<commit_msg>Update a style issue<commit_after>'use strict';

var readJson = require('./readJson')
var Promise = require('bluebird')
var _ = require('lodash')
var add = require('./add')
var db = require('./db')
var buildDeptNum = require('./deptNum').buildDeptNum
var deptNumToCrsidCache = require('./getCourses').deptNumToCrsidCache

var logDataLoading = false

function storeCourses(item) {
	return new Promise(function(resolve, reject) {
		console.log(item.meta.path, 'called storeCourses')

		var courses = _.map(item.data.courses, function(course) {
			course.sourcePath = item.meta.path
			course.deptnum = buildDeptNum(course)
			deptNumToCrsidCache[course.deptnum] = course.crsid
			return course
		})

		db.store('courses').batch(courses)
			.then(function(results) {
				resolve(item)
			}).catch(function (records, err) {
				reject(err)
			})
	})
}

function storeArea(item) {
	return new Promise(function(resolve, reject) {
		console.log(item.meta.path, 'called storeArea')

		var area = item.data.info
		area.sourcePath = item.meta.path

		db.store('areas').put(area)
			.then(function(results) {
				resolve(item)
			})
			.catch(function(records, err) {
				reject(err)
			})
	})
}

function storeItem(item) {
	if (item.type === 'courses') {
		return storeCourses(item)
	} else if (item.type === 'areas') {
		return storeArea(item)
	}
}

function cleanPriorData(item) {
	return new Promise(function (resolve, reject) {
		var path = item.meta.path
		console.info('deleting ' + item.type + ' from ' + path)

		var deleteItemsPromise = db.store(item.type).del(path)

		deleteItemsPromise
			.then(function() {
				localStorage.removeItem(path)
				resolve(item)
			})
			.catch(function(err) {
				reject(err)
			})
	})
}

function cacheItemHash(item) {
	return new Promise(function(resolve, reject) {
		console.info(item.meta.path + ' called cacheItemHash')
		localStorage.setItem(item.meta.path, item.meta.hash)
		resolve(item)
	})
}

var lookup = {
	'courses': 'courses',
	'areas': 'info'
}

function updateDatabase(itemType, infoFromServer) {
	infoFromServer.path = '/data/' + itemType + '/' + infoFromServer.path
	var oldHash = localStorage.getItem(infoFromServer.path)
	var newHash = infoFromServer.hash
	var itemPath = infoFromServer.path

	if (newHash === oldHash) {
		if (logDataLoading) {
			console.log('skipped ' + itemPath)
		}
		return Promise.resolve(false)
	}

	if (logDataLoading) {
		console.log('need to add ' + itemPath)
	}

	return readJson(itemPath)
		.then(function(data) {
			return {
				data: data,
				meta: infoFromServer,
				type: itemType,
				count: _.size(data[lookup[itemType]]) || 1,
			}
		})
		.then(cleanPriorData)
		.then(storeItem)
		.then(cacheItemHash)
		.catch(function(err) {
			return Promise.reject(err.stack)
		})
		.done(function(item) {
			if (logDataLoading) {
				console.log('added '+item.meta.path+' ('+item.count+' '+item.type+')')
			}
			return Promise.resolve(true)
		})
}

function loadDataFiles(infoFile) {
	console.log('load data files', infoFile)

	return Promise.all(_.map(infoFile.info, function(files) {
		return Promise.all(_.map(files, function(file) {
			return updateDatabase(infoFile.type, file)
		}))
	}))
}

/*
function loadDataFiles(infoFile) {
	console.log('load data files', infoFile)

	var progress = 0;
	var notification = new Cortex({
		message: 'Updating ' + infoFile.type,
		hasProgress: true,
		progressValue: progress,
		maxProgressValue: _.chain(infoFile.info).mapValues(_.size).reduce(add).value(),
		ident: infoFile.type
	})
	window.notifications.push(notification.val())

	return Promise.all(_.map(infoFile.info, function(files) {
		var allFilesLoadedPromise = Promise.all(_.map(files, function(file) {
			var dbUpdatedPromise = updateDatabase(infoFile.type, file)
			dbUpdatedPromise.then(function() {
				notification.progressValue.set(progress += 1)
			})
			return dbUpdatedPromise
		}))

		allFilesLoadedPromise.then(function() {
			setTimeout(notification.remove, 200)
		})

		return allFilesLoadedPromise
	}))
}
*/

function loadInfoFile(url) {
	console.log('loading', url)
	return readJson(url).then(loadDataFiles)
}

function loadData() {
	var infoFiles = [
		'/data/areas/info.json',
		'/data/courses/info.json',
	]
	return Promise.all(_.map(infoFiles, loadInfoFile))
}

module.exports = window.loadData = loadData
<|endoftext|>


<commit_before>
var NotesPopupPlugin = function(app) {

	var notesPopup = new InfoWindow('NotesPopup');

	notesPopup.body.on('click', '.bibleref', function(e) {

		sofia.globals.handleBibleRefClick.call(this, e);

		notesPopup.hide();

	});

	if (!Detection.hasTouch) {
		notesPopup.body.on('mouseover', '.bibleref', function(e) {
			sofia.globals.handleBibleRefMouseover.call(this, e, $(notesPopup.currentWord).closest('.section').attr('data-textid') );
		});

		notesPopup.body.on('mouseout', '.bibleref', function(e) {
			sofia.globals.handleBibleRefMouseout.call(this, e);
		});
	}

	$('.windows-main').on('click','.note .key, .cf .key', function(e) {

		console.log('notes');

		var key = $(this);

		// hide if second click
		if (notesPopup.container.is(':visible') && notesPopup.currentWord == this) {
			notesPopup.hide();
			notesPopup.currentWord == null;
			return;
		}
		notesPopup.currentWord = this;

		// clone and attach content
		var content = key.parent().find('.text').clone();

		notesPopup.body
					.html('')
					.append(content);

		// show popup
		notesPopup.show();
		notesPopup.position(key);

		return false;
	});

	var ext = {
		getData: function() {
			return null;
		}
	};
	ext = $.extend(true, ext, EventEmitter);

	return ext;
};

sofia.plugins.push('NotesPopupPlugin');
<commit_msg>new notes system<commit_after>
var NotesPopupPlugin = function(app) {

	var notesPopup = new InfoWindow('NotesPopup');

	notesPopup.body.on('click', '.bibleref', function(e) {

		sofia.globals.handleBibleRefClick.call(this, e);

		notesPopup.hide();

	});

	if (!Detection.hasTouch) {
		notesPopup.body.on('mouseover', '.bibleref', function(e) {
			sofia.globals.handleBibleRefMouseover.call(this, e, $(notesPopup.currentWord).closest('.section').attr('data-textid') );
		});

		notesPopup.body.on('mouseout', '.bibleref', function(e) {
			sofia.globals.handleBibleRefMouseout.call(this, e);
		});
	}

	$('.windows-main').on('click','.note .key, .cf .key', function(e) {

		e.preventDefault();

		console.log('notes');

		var key = $(this);

		// hide if second click
		if (notesPopup.container.is(':visible') && notesPopup.currentWord == this) {
			notesPopup.hide();
			notesPopup.currentWord == null;
			return;
		}
		notesPopup.currentWord = this;

		// clone and attach content
		var content = key.parent().find('.text').clone();

		notesPopup.body
					.html('')
					.append(content);

		// show popup
		notesPopup.show();
		notesPopup.position(key);

		return false;
	});

	var ext = {
		getData: function() {
			return null;
		}
	};
	ext = $.extend(true, ext, EventEmitter);

	return ext;
};

sofia.plugins.push('NotesPopupPlugin');
<|endoftext|>


<commit_before>import * as activityFns from './activityfns.js';
import { getActivityList } from './activitylist.js';
import { get24hTime } from '../Utils/time.js';

const ten = new Date(Date.UTC(2020, 4, 2, 10,  0));          // May 2, 2020 10:00
const eleven = new Date(Date.UTC(2020, 4, 2, 11, 0));        // May 2, 2020 11:00
const elevenThirty = new Date(Date.UTC(2020, 4, 2, 11, 30)); // May 2, 2020 11:30
const twelve = new Date(Date.UTC(2020, 4, 2, 12, 0));        // May 2, 2020 12:00
const one = new Date(Date.UTC(2020, 4, 2, 13, 0));           // May 2, 2020 13:00
const may102pm = new Date(Date.UTC(2020, 4, 10, 14, 0)); // May 10, 2020 14:00
const may014pm = new Date(Date.UTC(2020, 4, 1, 16, 0));   // May 1, 2020 16:00
const may153am = new Date(Date.UTC(2020, 4, 15, 3, 0));   // May 15, 2020 3:00

function createActivity(startTime, endTime){
  return {'start_time': startTime, 'end_time': endTime};
}

describe('Same day activity compareActivities', () => {
  const tenToTwelve = createActivity(ten, twelve);
  const elevenToOne = createActivity(eleven, one);
  const elevenToElevenThirty = createActivity(eleven, elevenThirty);
  const tenToEleven = createActivity(ten, eleven);
  const elevenToTwelve = createActivity(eleven, twelve);

  test('Overlapping activities', () => {
    expect(activityFns.compareActivities(elevenToOne, tenToTwelve)).toBe(1);
  })

  test('One activity completely during another', () => {
    expect(activityFns.compareActivities(tenToTwelve, elevenToElevenThirty)).toBe(-1);
  })

  test('Activities with same start time', () => {
    expect(activityFns.compareActivities(tenToEleven, tenToTwelve)).toBe(-1);
  })

  test('Sequential activities', () => {
    expect(activityFns.compareActivities(tenToEleven, elevenToTwelve)).toBe(-1);
  })

  test('Activities with same end time', () => {
    expect(activityFns.compareActivities(elevenToTwelve, tenToTwelve)).toBe(1);
  })
})

test('compareActivities on different days', () => {
  const may10 = createActivity(may102pm, may102pm);
  const may15 = createActivity(may153am, may153am);
  const may01 = createActivity(may014pm, may014pm);
  expect(activityFns.compareActivities(may10, may01)).toBe(1);
  expect(activityFns.compareActivities(may15, may01)).toBe(1);
})

describe('sortByDate tests', () => {
  const act1 = createActivity(ten, eleven);
  const act2 = createActivity(elevenThirty, twelve);
  const act3 = createActivity(twelve, one);
  const act4 = createActivity(may102pm, may102pm);
  const act5 = createActivity(may153am, may153am);

  test('sortByDate all same date', () => {
    const tripActivities = [act1, act2, act3];

    let expected = new Map();
    expected.set(ten.toLocaleDateString(), new Set([act1, act2, act3]));
    expected = Array.from(expected);

    expect(activityFns.sortByDate(tripActivities)).toEqual(expected);
  })

  test('sortByDate all differentDates', () =>   {
    const tripActivities = [act3, act4, act5];

    let expected = new Map();
    expected.set(ten.toLocaleDateString(), new Set([act3]));
    expected.set(may102pm.toLocaleDateString(), new Set([act4]));
    expected.set(may153am.toLocaleDateString(), new Set([act5]));
    expected = Array.from(expected);

    expect(activityFns.sortByDate(tripActivities)).toEqual(expected);
  })

  test('sortByDate mixed dates', () => {
    const tripActivities = [act3, act4, act1, act5, act2];

    let expected = new Map();
    expected.set(ten.toLocaleDateString(), new Set([act3, act1, act2]));
    expected.set(may102pm.toLocaleDateString(), new Set([act4]));
    expected.set(may153am.toLocaleDateString(), new Set([act5]));
    expected = Array.from(expected);

    expect(activityFns.sortByDate(tripActivities)).toEqual(expected);
  })
})

test('getField', () => {
  const activity = {field1: 'yes'};
  expect(activityFns.getField(activity, 'field1', 'nooo')).toBe('yes');
  expect(activityFns.getField(activity, 'field2', 4)).toBe(4);
  expect(activityFns.getField(activity, 'field1', 'nooo', 'aww ')).toBe('aww yes');
  expect(activityFns.getField(activity, 'field2', 4, ' and')).toBe(4);
  expect(activityFns.getField(activity, 'field2')).toBeNull();
})

test('getRefValue', () => {
  const fakeRef = {current: {value: 'parasailing!'}};
  expect(activityFns.getRefValue(fakeRef, 'parasailing!')).toBeNull();
  expect(activityFns.getRefValue(fakeRef, 'parasailing!', 'swimming.')).toBe('swimming.');
  expect(activityFns.getRefValue(fakeRef, 'swimming')).toBe('parasailing!');
  expect(activityFns.getRefValue(fakeRef, 'swimming', 'jumping')).toBe('parasailing!');
});<commit_msg>remove unused imports<commit_after>import * as activityFns from './activityfns.js';

const ten = new Date(Date.UTC(2020, 4, 2, 10,  0));          // May 2, 2020 10:00
const eleven = new Date(Date.UTC(2020, 4, 2, 11, 0));        // May 2, 2020 11:00
const elevenThirty = new Date(Date.UTC(2020, 4, 2, 11, 30)); // May 2, 2020 11:30
const twelve = new Date(Date.UTC(2020, 4, 2, 12, 0));        // May 2, 2020 12:00
const one = new Date(Date.UTC(2020, 4, 2, 13, 0));           // May 2, 2020 13:00
const may102pm = new Date(Date.UTC(2020, 4, 10, 14, 0)); // May 10, 2020 14:00
const may014pm = new Date(Date.UTC(2020, 4, 1, 16, 0));   // May 1, 2020 16:00
const may153am = new Date(Date.UTC(2020, 4, 15, 3, 0));   // May 15, 2020 3:00

function createActivity(startTime, endTime){
  return {'start_time': startTime, 'end_time': endTime};
}

describe('Same day activity compareActivities', () => {
  const tenToTwelve = createActivity(ten, twelve);
  const elevenToOne = createActivity(eleven, one);
  const elevenToElevenThirty = createActivity(eleven, elevenThirty);
  const tenToEleven = createActivity(ten, eleven);
  const elevenToTwelve = createActivity(eleven, twelve);

  test('Overlapping activities', () => {
    expect(activityFns.compareActivities(elevenToOne, tenToTwelve)).toBe(1);
  })

  test('One activity completely during another', () => {
    expect(activityFns.compareActivities(tenToTwelve, elevenToElevenThirty)).toBe(-1);
  })

  test('Activities with same start time', () => {
    expect(activityFns.compareActivities(tenToEleven, tenToTwelve)).toBe(-1);
  })

  test('Sequential activities', () => {
    expect(activityFns.compareActivities(tenToEleven, elevenToTwelve)).toBe(-1);
  })

  test('Activities with same end time', () => {
    expect(activityFns.compareActivities(elevenToTwelve, tenToTwelve)).toBe(1);
  })
})

test('compareActivities on different days', () => {
  const may10 = createActivity(may102pm, may102pm);
  const may15 = createActivity(may153am, may153am);
  const may01 = createActivity(may014pm, may014pm);
  expect(activityFns.compareActivities(may10, may01)).toBe(1);
  expect(activityFns.compareActivities(may15, may01)).toBe(1);
})

describe('sortByDate tests', () => {
  const act1 = createActivity(ten, eleven);
  const act2 = createActivity(elevenThirty, twelve);
  const act3 = createActivity(twelve, one);
  const act4 = createActivity(may102pm, may102pm);
  const act5 = createActivity(may153am, may153am);

  test('sortByDate all same date', () => {
    const tripActivities = [act1, act2, act3];

    let expected = new Map();
    expected.set(ten.toLocaleDateString(), new Set([act1, act2, act3]));
    expected = Array.from(expected);

    expect(activityFns.sortByDate(tripActivities)).toEqual(expected);
  })

  test('sortByDate all differentDates', () =>   {
    const tripActivities = [act3, act4, act5];

    let expected = new Map();
    expected.set(ten.toLocaleDateString(), new Set([act3]));
    expected.set(may102pm.toLocaleDateString(), new Set([act4]));
    expected.set(may153am.toLocaleDateString(), new Set([act5]));
    expected = Array.from(expected);

    expect(activityFns.sortByDate(tripActivities)).toEqual(expected);
  })

  test('sortByDate mixed dates', () => {
    const tripActivities = [act3, act4, act1, act5, act2];

    let expected = new Map();
    expected.set(ten.toLocaleDateString(), new Set([act3, act1, act2]));
    expected.set(may102pm.toLocaleDateString(), new Set([act4]));
    expected.set(may153am.toLocaleDateString(), new Set([act5]));
    expected = Array.from(expected);

    expect(activityFns.sortByDate(tripActivities)).toEqual(expected);
  })
})

test('getField', () => {
  const activity = {field1: 'yes'};
  expect(activityFns.getField(activity, 'field1', 'nooo')).toBe('yes');
  expect(activityFns.getField(activity, 'field2', 4)).toBe(4);
  expect(activityFns.getField(activity, 'field1', 'nooo', 'aww ')).toBe('aww yes');
  expect(activityFns.getField(activity, 'field2', 4, ' and')).toBe(4);
  expect(activityFns.getField(activity, 'field2')).toBeNull();
})

test('getRefValue', () => {
  const fakeRef = {current: {value: 'parasailing!'}};
  expect(activityFns.getRefValue(fakeRef, 'parasailing!')).toBeNull();
  expect(activityFns.getRefValue(fakeRef, 'parasailing!', 'swimming.')).toBe('swimming.');
  expect(activityFns.getRefValue(fakeRef, 'swimming')).toBe('parasailing!');
  expect(activityFns.getRefValue(fakeRef, 'swimming', 'jumping')).toBe('parasailing!');
});<|endoftext|>


<commit_before>angular
    .module('alesmith')
    .controller('AppController', AppController);

AppController.$inject = ['$scope', '$location', '$http', '$rootScope', '$window'];

/* @ngInject */
function AppController($scope, $location, $http, $rootScope, $window) {
    /* jshint validthis: true */
    var vm = this;
    vm.title = 'AppController';
    $scope.tabSelected = -1;
    ////////////////
    $http.get('/v1/user/current').success(function (user) {
        $rootScope.user = user;
    }).error(function () {
        $window.location = "/login";
    });
    $scope.logout = function () {
        $http.get('/v1/user/logout').success(function () {
            $window.location = "/login";
        })
    };
    $scope.getClass = function (path) {
        return $location.path().substr(0, path.length) == path;
    };
    $scope.menu = [];
    $scope.menu.push({
        title: "TENTAMEN",
        prefix: "exam",
        links: [
            {link: '/exam/all', text: ''}
        ]
    });
    $scope.menu.push({
        title: "MEDDELANDEN",
        prefix: "chat",
        links: [{link: '/chat/chat#bottom', text: ''}]
    });
    $scope.menu.push({
        title: "INFORMATION",
        prefix: "information",
        links: [
            {
                link: '/information/tentamenregistration', text: "Information om tentamina"
            },
            {
                link: '/information/reexam', text: "Omprövning"
            },
            {
                link: '/information/rules', text: 'Regler för tentamensskrivning'
            },
            {
                link: '/information/faq', text: 'Vanliga frågor (FAQ)'
            }

        ]
    });
    $scope.menu.push({
        title: "SUPPORT",
        prefix: "support",
        links: [
            {
                link: '/information/contact', text: 'Kontaktinformation'
            },
            {
                link: '/support/help', text: 'Hjälp'
            }
        ]
    });

    $scope.menu.push({
        title: "INSTÄLLNINGAR",
        prefix: "notifications",
        links: [
            {link: '/notifications/settings', text: ''}
        ]
    });

    $scope.tabClick = function (index) {
        $scope.tabSelected = index;

        $location.url($scope.menu[index].links[0].link);
    };
    $scope.activeTab = function (index) {
        if ($scope.tabSelected != -1) return index == $scope.tabSelected;
        console.log($location.path().substr(0, $location.path().length));
        if ($location.path().substr(0, $location.path().length).split("/")[1] === $scope.menu[index].prefix) {
            $scope.tabSelected = index;
            return true;
        }
        return false;
    };
    $scope.getActive = function (path) {
        return $location.path().substr(0, path.length) == path;
    };
}

<commit_msg>Changed in menu<commit_after>angular
    .module('alesmith')
    .controller('AppController', AppController);

AppController.$inject = ['$scope', '$location', '$http', '$rootScope', '$window'];

/* @ngInject */
function AppController($scope, $location, $http, $rootScope, $window) {
    /* jshint validthis: true */
    var vm = this;
    vm.title = 'AppController';
    $scope.tabSelected = -1;
    ////////////////
    $http.get('/v1/user/current').success(function (user) {
        $rootScope.user = user;
    }).error(function () {
        $window.location = "/login";
    });
    $scope.logout = function () {
        $http.get('/v1/user/logout').success(function () {
            $window.location = "/login";
        })
    };
    $scope.getClass = function (path) {
        return $location.path().substr(0, path.length) == path;
    };
    $scope.menu = [];
    $scope.menu.push({
        title: "TENTAMEN",
        prefix: "exam",
        links: [
            {link: '/exam/all', text: ''}
        ]
    });
    $scope.menu.push({
        title: "MEDDELANDEN",
        prefix: "chat",
        links: [{link: '/chat/chat#bottom', text: ''}]
    });
    $scope.menu.push({
        title: "INFORMATION",
        prefix: "information",
        links: [
            {
                link: '/information/tentamenregistration', text: "Information om tentamina"
            },
            {
                link: '/information/reexam', text: "Omprövning"
            },
            {
                link: '/information/rules', text: 'Regler för tentamensskrivning'
            },
            {
                link: '/information/faq', text: 'Vanliga frågor (FAQ)'
            },
            {
                link: '/information/contact', text: 'Kontaktinformation'
            }

        ]
    });
    $scope.menu.push({
        title: "HJÄLP",
        prefix: "support",
        links: [
            {
                link: '/support/help', text: ''
            }
        ]
    });

    $scope.menu.push({
        title: "INSTÄLLNINGAR",
        prefix: "notifications",
        links: [
            {link: '/notifications/settings', text: ''}
        ]
    });

    $scope.tabClick = function (index) {
        $scope.tabSelected = index;

        $location.url($scope.menu[index].links[0].link);
    };
    $scope.activeTab = function (index) {
        if ($scope.tabSelected != -1) return index == $scope.tabSelected;
        console.log($location.path().substr(0, $location.path().length));
        if ($location.path().substr(0, $location.path().length).split("/")[1] === $scope.menu[index].prefix) {
            $scope.tabSelected = index;
            return true;
        }
        return false;
    };
    $scope.getActive = function (path) {
        return $location.path().substr(0, path.length) == path;
    };
}

<|endoftext|>


<commit_before>import {DOM_CHANGED_EVENT} from '../classes/fef-dom-observer';
import {FefResponsiveHelper} from '../classes/fef-responsive-helper';

const ANIMATION_SPEED = 200;
const KEYCODES = {
    'enter': 13,
    'tab': 9,
    'escape': 27
};

let existingModals = {};
let scrollbarWidth = 0;

$(window).on(DOM_CHANGED_EVENT, (e) => {
    scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
    $('[data-modal-id]').each((index, element) => {

        $(element).on('click', () => {
            let $caller = $(element);
            let modalId = $caller.attr('data-modal-id');
            let $modalElement = $(`[data-id=${modalId}]`);

            if (existingModals[modalId]) {
                existingModals[modalId].show();
            } else if ($modalElement.length > 0) {
                existingModals[modalId] = new FefModal($modalElement, $caller);
            }
        });
    });
});

/**
 * Handles showing and hiding a modal element
 */
export class FefModal {

    /**
     * @param $element jQuery element
     * @param $caller jQuery element
     */
    constructor($element, $caller) {
        this.$element = $element;
        this.$caller = $caller;
        this.$focusTarget = this.$element.find('.js-focus-target').first();
        this.$mainWrapper = this.$element.find('.js-modal-main-wrapper');
        this.$mainContent = this.$element.find('.js-modal-main-content');
        this.animation = this.$element.attr('data-animation');
        this.previousScrollPosition = null;

        this.bindEvents();

        if (this.$element.hasClass('js-min-height-of-masthead')) {
            this.$mainContent.css('min-height', $('.js-masthead').outerHeight());
        }

        this.show();
    }

    /**
     * Binds the relevant events for this modal:
     * - Click on a close-button or the overlay
     * - Pressing Escape
     */
    bindEvents() {
        this.$element.find('.js-close-modal, .js-modal-overlay').on('click', () => {
            this.close();
        });

        this.$element.on('keydown', (e) => {
            if (e.keyCode === KEYCODES.escape) {
                this.close();
            }
        });
    }

    /**
     * Show the modal, depending on the provided animation.
     */
    show() {
        switch (this.animation) {
            case 'scale-from-origin':
                this.scaleFromOrigin(() => this.preventScrolling());
                break;
            case 'fade-in-out':
                this.$element.stop(true, true).fadeIn(ANIMATION_SPEED, () => this.preventScrolling());
                break;
            default:
                this.$element.show(() => this.preventScrolling());
                break;
        }

        if (this.$focusTarget.length === 1) {
            this.setFocus(this.$focusTarget);
        }
    }

    /**
     * Hide the modal, depending on the provided animation.
     */
    close() {
        this.scrollToPreviousPosition();

        switch (this.animation) {
            case 'fade-in-out':
                this.$element.stop(true, true).fadeOut(ANIMATION_SPEED);
                break;
            default:
                this.$element.hide();
                break;
        }

        this.setFocus(this.$caller);
    }

    /**
     * Simply using .focus() doesn't suffice.
     *
     * @param $element jQuery.Element
     */
    setFocus($element) {
        $element.attr('tabindex', -1).on('blur focusout', () => {
            $element.removeAttr('tabindex');
        }).focus();
    }

    /**
     * Fancy menu opening animation:
     * - fades the modal in
     * - 'opens' it from the originating element
     * - fades in the content (otherwise it'll be resized)
     * - calls an optional callback
     *
     * For aesthetical reasons we have to animate to the previous height and not 100% max-height directly.
     */
    scaleFromOrigin(callBack) {
        this.$mainContent.css('opacity', 0);
        this.$element.show();

        let originalHeight = this.$mainWrapper.height();
        let box = this.$caller[0].getBoundingClientRect();
        this.$mainWrapper.css({
            'left': box.left,
            'width': box.width,
            'max-height': box.height,
            'top': box.top,
            'opacity': 0
        }).animate({
            'left': 0,
            'width': '100%',
            'max-height': originalHeight,
            'top': 0,
            'opacity': 1
        }, ANIMATION_SPEED, 'easeInOutSine', () => {
            // remove the scrollbars
            this.$mainWrapper.css({
                'max-height': '100%',
                'width': `calc(100% + ${scrollbarWidth}px)`,
                'margin-right': scrollbarWidth
            });
            this.$mainContent.animate({
                'opacity': 1
            }, ANIMATION_SPEED, callBack);
        });
    }

    /**
     * Prevent scrollable page when the modal is open.
     * We achieve this by setting the body to overflow: hidden and setting the height to 100%, thus
     * effectively cutting the rest of the page off. This scrolls to the top of the page, so we
     * also have to save the previous scroll state.
     *
     * We only do this if the modal covers the whole page and on mobile/tablet.
     */
    preventScrolling() {
        if (this.$mainContent.outerHeight() >= $(window).outerHeight() && (FefResponsiveHelper.isTablet() || FefResponsiveHelper.isSmartphone())) {
            this.previousScrollPosition = $(window).scrollTop();
            $('html').addClass('h-prevent-scrolling');
        }
    }

    /**
     * If, upon opening the modal, the ability to scroll was removed, we give it back now. This means:
     * - removing the class that prevents the scrolling
     * - scrolling back to the previously saved scroll position
     *
     * This makes it appear as if we never even scrolled away.
     */
    scrollToPreviousPosition() {
        if (this.previousScrollPosition !== null) {
            $('html').removeClass('h-prevent-scrolling');
            $(window).scrollTop(this.previousScrollPosition);
            this.previousScrollPosition = null;
        }
    }
}
<commit_msg>Adds Breakpoint to Focus-Target-Modal-JS<commit_after>import {DOM_CHANGED_EVENT} from '../classes/fef-dom-observer';
import {FefResponsiveHelper} from '../classes/fef-responsive-helper';

const ANIMATION_SPEED = 200;
const KEYCODES = {
    'enter': 13,
    'tab': 9,
    'escape': 27
};

let existingModals = {};
let scrollbarWidth = 0;

$(window).on(DOM_CHANGED_EVENT, (e) => {
    scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
    $('[data-modal-id]').each((index, element) => {

        $(element).on('click', () => {
            let $caller = $(element);
            let modalId = $caller.attr('data-modal-id');
            let $modalElement = $(`[data-id=${modalId}]`);

            if (existingModals[modalId]) {
                existingModals[modalId].show();
            } else if ($modalElement.length > 0) {
                existingModals[modalId] = new FefModal($modalElement, $caller);
            }
        });
    });
});

/**
 * Handles showing and hiding a modal element
 */
export class FefModal {

    /**
     * @param $element jQuery element
     * @param $caller jQuery element
     */
    constructor($element, $caller) {
        this.$element = $element;
        this.$caller = $caller;
        this.$focusTarget = this.$element.find('.js-focus-target').first();
        this.$mainWrapper = this.$element.find('.js-modal-main-wrapper');
        this.$mainContent = this.$element.find('.js-modal-main-content');
        this.animation = this.$element.attr('data-animation');
        this.previousScrollPosition = null;

        this.bindEvents();

        if (this.$element.hasClass('js-min-height-of-masthead')) {
            this.$mainContent.css('min-height', $('.js-masthead').outerHeight());
        }

        this.show();
    }

    /**
     * Binds the relevant events for this modal:
     * - Click on a close-button or the overlay
     * - Pressing Escape
     */
    bindEvents() {
        this.$element.find('.js-close-modal, .js-modal-overlay').on('click', () => {
            this.close();
        });

        this.$element.on('keydown', (e) => {
            if (e.keyCode === KEYCODES.escape) {
                this.close();
            }
        });
    }

    /**
     * Show the modal, depending on the provided animation.
     */
    show() {
        switch (this.animation) {
            case 'scale-from-origin':
                this.scaleFromOrigin(() => this.preventScrolling());
                break;
            case 'fade-in-out':
                this.$element.stop(true, true).fadeIn(ANIMATION_SPEED, () => this.preventScrolling());
                break;
            default:
                this.$element.show(() => this.preventScrolling());
                break;
        }

        if (this.$focusTarget.length === 1 && (FefResponsiveHelper.isDesktop() || FefResponsiveHelper.isDesktopWide()) ) {
            this.setFocus(this.$focusTarget);
        }
    }

    /**
     * Hide the modal, depending on the provided animation.
     */
    close() {
        this.scrollToPreviousPosition();

        switch (this.animation) {
            case 'fade-in-out':
                this.$element.stop(true, true).fadeOut(ANIMATION_SPEED);
                break;
            default:
                this.$element.hide();
                break;
        }

        this.setFocus(this.$caller);
    }

    /**
     * Simply using .focus() doesn't suffice.
     *
     * @param $element jQuery.Element
     */
    setFocus($element) {
        $element.attr('tabindex', -1).on('blur focusout', () => {
            $element.removeAttr('tabindex');
        }).focus();
    }

    /**
     * Fancy menu opening animation:
     * - fades the modal in
     * - 'opens' it from the originating element
     * - fades in the content (otherwise it'll be resized)
     * - calls an optional callback
     *
     * For aesthetical reasons we have to animate to the previous height and not 100% max-height directly.
     */
    scaleFromOrigin(callBack) {
        this.$mainContent.css('opacity', 0);
        this.$element.show();

        let originalHeight = this.$mainWrapper.height();
        let box = this.$caller[0].getBoundingClientRect();
        this.$mainWrapper.css({
            'left': box.left,
            'width': box.width,
            'max-height': box.height,
            'top': box.top,
            'opacity': 0
        }).animate({
            'left': 0,
            'width': '100%',
            'max-height': originalHeight,
            'top': 0,
            'opacity': 1
        }, ANIMATION_SPEED, 'easeInOutSine', () => {
            // remove the scrollbars
            this.$mainWrapper.css({
                'max-height': '100%',
                'width': `calc(100% + ${scrollbarWidth}px)`,
                'margin-right': scrollbarWidth
            });
            this.$mainContent.animate({
                'opacity': 1
            }, ANIMATION_SPEED, callBack);
        });
    }

    /**
     * Prevent scrollable page when the modal is open.
     * We achieve this by setting the body to overflow: hidden and setting the height to 100%, thus
     * effectively cutting the rest of the page off. This scrolls to the top of the page, so we
     * also have to save the previous scroll state.
     *
     * We only do this if the modal covers the whole page and on mobile/tablet.
     */
    preventScrolling() {
        if (this.$mainContent.outerHeight() >= $(window).outerHeight() && (FefResponsiveHelper.isTablet() || FefResponsiveHelper.isSmartphone())) {
            this.previousScrollPosition = $(window).scrollTop();
            $('html').addClass('h-prevent-scrolling');
        }
    }

    /**
     * If, upon opening the modal, the ability to scroll was removed, we give it back now. This means:
     * - removing the class that prevents the scrolling
     * - scrolling back to the previously saved scroll position
     *
     * This makes it appear as if we never even scrolled away.
     */
    scrollToPreviousPosition() {
        if (this.previousScrollPosition !== null) {
            $('html').removeClass('h-prevent-scrolling');
            $(window).scrollTop(this.previousScrollPosition);
            this.previousScrollPosition = null;
        }
    }
}
<|endoftext|>


<commit_before>
/*
 * Copyright (c) Burak Arslan (burak.arslan-qx@arskom.com.tr).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Arskom Consultancy Ltd. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

qx.Class.define("soap.test.SoaplibInterop", { extend : qx.dev.unit.TestCase,
    construct : function() {
        this.c = new soap.Client('http://'+document.location.host+'/app/');
        try {
            this.c.easy("!_name_!");
        }
        catch(e) {

        }
        this.ns = "soaplib.test.interop.server._service";
        qx.log.Logger.debug("hey.");
    }

    ,members : {
          c : null
         ,ns: null

        // helper functions

        ,__test_echo: function(service_name, val, cb) {
            var ctx = this;

            ctx.c.easy(service_name
                ,val
                ,function(r) {
                    ctx.resume(function() {
                        if (cb) {
                            cb(r,val)
                        }
                        else {
                            ctx.assertEquals(r, val);
                        }
                    });
                });
            ctx.wait();
        }

        ,__test_echo_array: function(service_name, val, cb) {
            var ctx = this;

            ctx.__test_echo(service_name, val, function(r,v) {
                for (var i=0,l=r.length; i<l; ++i) {
                    if (cb) {
                        cb(r,v,i);
                    }
                    else {
                        ctx.assertEquals(r[i], val[i]);
                    }
                }
            });
        }

        // primitive tests

        ,test_echo_string : function() {
            var service_name = "echo_string";

            var val = "punk üğışçöÜĞİŞÇÖ";

            this.__test_echo(service_name, val);
        }

        ,test_echo_integer : function() {
            var service_name = "echo_integer";

            var val = 10;

            this.__test_echo(service_name, val);
        }

        ,test_echo_float : function() {
            var service_name = "echo_float";

            var val = 10.1;

            this.__test_echo(service_name, val);
        }

        ,test_echo_double : function() {
            var service_name = "echo_double";

            var val = 123132123.124;

            this.__test_echo(service_name, val);
        }

        ,test_echo_boolean : function() {
            var service_name = "echo_boolean";

            var val = true;

            this.__test_echo(service_name, val);
        }

        ,test_echo_datetime : function() {
            var service_name = "echo_datetime";

            var ctx = this;
            var val = new Date();

            this.__test_echo(service_name, val, function(r,v) {
                ctx.assertEquals(r.getTime(), v.getTime());
            });
        }

        // array tests

        ,test_echo_integer_array : function() {
            var service_name = "echo_integer_array";

            var val = [1,3,5,7,11];

            this.__test_echo_array(service_name, val);
        }

        ,test_echo_string_array : function() {
            var service_name = "echo_string_array";

            var val = ["hobaaa", "bir", "punk", "üğışçöÜĞİŞÇÖ"];

            this.__test_echo_array(service_name, val);
        }

        ,test_echo_float_array : function() {
            var service_name = "echo_float_array";

            var val = [1.1, 3.3, 5.5, 7.7, 11.11];

            this.__test_echo_array(service_name, val);
        }

        ,test_echo_double_array : function() {
            var service_name = "echo_double_array";

            var val = [1123123123.12, 12.34];

            this.__test_echo_array(service_name, val);
        }

        ,test_echo_boolean_array : function() {
            var service_name = "echo_boolean_array";

            var val = [true,false,true];

            this.__test_echo_array(service_name, val);
        }

        // complex object tests

        ,__test_simple_class : function(r,v) {
            this.assertEquals(r.get_i(), v.get_i());
            this.assertEquals(r.get_s(), v.get_s());
        }

        ,__test_nested_class : function(r,v) {
            this.assertEquals(r.get_i(), v.get_i());
            this.assertEquals(r.get_s(), v.get_s());
            this.assertEquals(r.get_f(), v.get_f());

            for (var i=0; i<r.get_simple().length; ++i) {
                this.__test_simple_class(r.get_simple()[i], v.get_simple()[i]);
            }

            this.__test_other_class(r.get_other(), v.get_other());
        }

        ,__test_other_class : function(r,v) {
            this.assertEquals(r.get_dt().getTime(), v.get_dt().getTime());
            this.assertEquals(r.get_d(), v.get_d());
            this.assertEquals(r.get_b(), v.get_b());
        }

        ,__test_non_nillable_class : function(r,v) {
            this.assertEquals(r.get_dt().getTime(), v.get_dt().getTime());
            this.assertEquals(r.get_i(), v.get_i());
            this.assertEquals(r.get_s(), v.get_s());
        }

        ,__test_extended_class : function(r,v) {
            this.assertEquals(r.get_i(), v.get_i());
            this.assertEquals(r.get_s(), v.get_s());
            this.assertEquals(r.get_f(), v.get_f());

            for (var i=0; i<r.get_simple().length; ++i) {
                this.__test_simple_class(r.get_simple()[i], v.get_simple()[i]);
            }

            this.__test_other_class(r.get_other(), v.get_other());
            this.__test_non_nillable_class(r.get_p(), v.get_p());
            this.assertEquals(r.get_l().getTime(), v.get_l().getTime());
            this.assertEquals(r.get_q(), v.get_q());
        }

        ,test_echo_simple_class : function() {
            var service_name = "echo_simple_class";
            var ctx = this;

            var val = this.c.get_object(ctx.ns,"SimpleClass");
            val.set_i(45);
            val.set_s("asd");

            this.__test_echo(service_name, val, function(r,v) {
                ctx.__test_simple_class(r,v);
            });
        }

        ,test_echo_simple_class_array : function() {
            var service_name = "echo_simple_class_array";
            var ctx = this;
            var val = []

            val.push(this.c.get_object(ctx.ns,"SimpleClass"));
            val.push(this.c.get_object(ctx.ns,"SimpleClass"));

            val[0].set_i(45);
            val[0].set_s("asd");

            val[1].set_i(12);
            val[1].set_s("qwe");

            this.__test_echo_array(service_name, val, function(r,v,i) {
                ctx.__test_simple_class(r[i],v[i]);
            });
        }

        ,test_echo_nested_class : function() {
            var service_name = "echo_nested_class";
            var ctx = this;
            var val = this.c.get_object(ctx.ns,"NestedClass");

            val.set_i(45);
            val.set_s("asd");
            val.set_f(12.34);

            val.set_simple([]);
            val.get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));
            val.get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));

            val.get_simple()[0].set_i(45);
            val.get_simple()[0].set_s("asd");
            val.get_simple()[1].set_i(12);
            val.get_simple()[1].set_s("qwe");

            val.set_other(this.c.get_object(ctx.ns,"OtherClass"));
            val.get_other().set_dt(new Date(2010,05,02));
            val.get_other().set_d(123.456);
            val.get_other().set_b(true);

            this.__test_echo(service_name, val, function(r,v) {
                ctx.__test_nested_class(r,v);
            });
        }

        ,test_echo_nested_class_array : function() {
            var service_name = "echo_nested_class_array";
            var ctx = this;
            var val = []

            val.push(this.c.get_object(ctx.ns,"NestedClass"));
            val.push(this.c.get_object(ctx.ns,"NestedClass"));

            for (var i=0; i< val.length; ++i) {
                val[i].set_i(45 + i);
                val[i].set_s("asd" + i);
                val[i].set_f(12.34 + i);

                val[i].set_simple([]);
                val[i].get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));
                val[i].get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));

                val[i].get_simple()[0].set_i(45 + i);
                val[i].get_simple()[0].set_s("asd"  + i);
                val[i].get_simple()[1].set_i(12 + i);
                val[i].get_simple()[1].set_s("qwe" + i);

                val[i].set_other(this.c.get_object(ctx.ns,"OtherClass"));
                val[i].get_other().set_dt(new Date(new Date().getTime() + i));
                val[i].get_other().set_d(123.456 + i);
                val[i].get_other().set_b(true);
            }

            this.__test_echo_array(service_name, val, function(r,v,i) {
                ctx.__test_nested_class(r[i],v[i]);
            });
        }

        ,test_echo_extension_class : function() {
            var service_name = "echo_extension_class";
            var ctx = this;
            var val = this.c.get_object(ctx.ns,"ExtensionClass");

            val.set_i(45);
            val.set_s("asd");
            val.set_f(12.34);

            val.set_simple([]);
            val.get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));
            val.get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));

            val.get_simple()[0].set_i(45);
            val.get_simple()[0].set_s("asd");
            val.get_simple()[1].set_i(12);
            val.get_simple()[1].set_s("qwe");

            val.set_other(this.c.get_object(ctx.ns,"OtherClass"));
            val.get_other().set_dt(new Date(2010,05,02));
            val.get_other().set_d(123.456);
            val.get_other().set_b(true);

            val.set_p(this.c.get_object(ctx.ns,"NonNillableClass"));
            val.get_p().set_dt(new Date(2010,06,02));
            val.get_p().set_i(123);
            val.get_p().set_s("punk");

            val.set_l(new Date(2010,07,02));
            val.set_q(5);

            this.__test_echo(service_name, val, function(r,v) {
                ctx.__test_extended_class(r,v);
            });
        }

        // misc tests
        ,test_empty: function() {
            var ctx=this;
            var service_name = "test_empty";

            ctx.c.easy(service_name
                ,function(r) {
                    ctx.resume(function() {

                    });
                });
            ctx.wait();
        }

        ,test_multi_param: function() {
            var service_name = "multi_param";
            var ctx=this;
            ctx.c.easy(service_name
                ,"string"
                ,123
                ,new Date()
                ,function(r) {
                    ctx.resume(function() {

                    });
                });
            ctx.wait();
        }

        ,test_return_only: function() {
            var service_name = "return_only";
            var ctx=this;
            ctx.c.easy(service_name
                ,function(r) {
                    ctx.resume(function() {
                        ctx.assertEquals(r, 'howdy');
                    });
                });
            ctx.wait();
        }

        ,test_alternate_name: function() {
            var service_name = "do_something";
            var ctx=this;
            var val = 'punk';

            ctx.c.easy(service_name
                ,'punk'
                ,function(r) {
                    ctx.resume(function() {
                        ctx.assertEquals(r, val);
                    });
                });
            ctx.wait();
        }
    }
});
<commit_msg>added echo_any and echo_any_as_dict tests<commit_after>
/*
 * Copyright (c) Burak Arslan (burak.arslan-qx@arskom.com.tr).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Arskom Consultancy Ltd. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

qx.Class.define("soap.test.SoaplibInterop", { extend : qx.dev.unit.TestCase,
    construct : function() {
        this.c = new soap.Client('http://'+document.location.host+'/app/');
        try {
            this.c.easy("!_name_!");
        }
        catch(e) {

        }
        this.ns = "soaplib.test.interop.server._service";
        qx.log.Logger.debug("hey.");
    }

    ,members : {
          c : null
         ,ns: null

        // helper functions

        ,__test_echo: function(service_name, val, cb) {
            var ctx = this;

            ctx.c.easy(service_name
                ,val
                ,function(r) {
                    ctx.resume(function() {
                        if (cb) {
                            cb(r,val)
                        }
                        else {
                            ctx.assertEquals(r, val);
                        }
                    });
                });
            ctx.wait();
        }

        ,__test_echo_array: function(service_name, val, cb) {
            var ctx = this;

            ctx.__test_echo(service_name, val, function(r,v) {
                for (var i=0,l=r.length; i<l; ++i) {
                    if (cb) {
                        cb(r,v,i);
                    }
                    else {
                        ctx.assertEquals(r[i], val[i]);
                    }
                }
            });
        }

        // primitive tests

        ,test_echo_string : function() {
            var service_name = "echo_string";

            var val = "punk üğışçöÜĞİŞÇÖ";

            this.__test_echo(service_name, val);
        }

        ,__get_xml_test_val : function() {
            var doc = qx.xml.Document.create();
            var sub=soap.Client.createSubElementNS(doc, doc, "test_sub", "test_ns");
            var subsub1=soap.Client.createSubElementNS(doc, sub, "test_subsub1", "test_ns");
            var subsubsub1=soap.Client.createSubElementNS(doc, subsub1, "test_subsubsub1", "test_ns");
            var subsub2=soap.Client.createSubElementNS(doc, sub, "test_subsubsub1", "test_ns");
            var subsub3=soap.Client.createSubElementNS(doc, sub, "test_subsubsub1", "test_ns");

            subsub2.nodeValue = "subsub2 value";
            subsub3.nodeValue = "subsub3 value";
            subsubsub1.nodeValue = "subsubsub1 value";

            return doc;
        }

        ,test_echo_any : function() {
            var service_name = "echo_any";

            var val = this.__get_xml_test_val();

            this.__test_echo(service_name, val);
        }

        ,test_echo_any_as_dict : function() {
            var service_name = "echo_any_as_dict";

            var val = this.__get_xml_test_val();

            this.__test_echo(service_name, val);
        }

        ,test_echo_integer : function() {
            var service_name = "echo_integer";

            var val = 10;

            this.__test_echo(service_name, val);
        }

        ,test_echo_float : function() {
            var service_name = "echo_float";

            var val = 10.1;

            this.__test_echo(service_name, val);
        }

        ,test_echo_double : function() {
            var service_name = "echo_double";

            var val = 123132123.124;

            this.__test_echo(service_name, val);
        }

        ,test_echo_boolean : function() {
            var service_name = "echo_boolean";

            var val = true;

            this.__test_echo(service_name, val);
        }

        ,test_echo_datetime : function() {
            var service_name = "echo_datetime";

            var ctx = this;
            var val = new Date();

            this.__test_echo(service_name, val, function(r,v) {
                ctx.assertEquals(r.getTime(), v.getTime());
            });
        }

        // array tests

        ,test_echo_integer_array : function() {
            var service_name = "echo_integer_array";

            var val = [1,3,5,7,11];

            this.__test_echo_array(service_name, val);
        }

        ,test_echo_string_array : function() {
            var service_name = "echo_string_array";

            var val = ["hobaaa", "bir", "punk", "üğışçöÜĞİŞÇÖ"];

            this.__test_echo_array(service_name, val);
        }

        ,test_echo_float_array : function() {
            var service_name = "echo_float_array";

            var val = [1.1, 3.3, 5.5, 7.7, 11.11];

            this.__test_echo_array(service_name, val);
        }

        ,test_echo_double_array : function() {
            var service_name = "echo_double_array";

            var val = [1123123123.12, 12.34];

            this.__test_echo_array(service_name, val);
        }

        ,test_echo_boolean_array : function() {
            var service_name = "echo_boolean_array";

            var val = [true,false,true];

            this.__test_echo_array(service_name, val);
        }

        // complex object tests

        ,__test_simple_class : function(r,v) {
            this.assertEquals(r.get_i(), v.get_i());
            this.assertEquals(r.get_s(), v.get_s());
        }

        ,__test_nested_class : function(r,v) {
            this.assertEquals(r.get_i(), v.get_i());
            this.assertEquals(r.get_s(), v.get_s());
            this.assertEquals(r.get_f(), v.get_f());

            for (var i=0; i<r.get_simple().length; ++i) {
                this.__test_simple_class(r.get_simple()[i], v.get_simple()[i]);
            }

            this.__test_other_class(r.get_other(), v.get_other());
        }

        ,__test_other_class : function(r,v) {
            this.assertEquals(r.get_dt().getTime(), v.get_dt().getTime());
            this.assertEquals(r.get_d(), v.get_d());
            this.assertEquals(r.get_b(), v.get_b());
        }

        ,__test_non_nillable_class : function(r,v) {
            this.assertEquals(r.get_dt().getTime(), v.get_dt().getTime());
            this.assertEquals(r.get_i(), v.get_i());
            this.assertEquals(r.get_s(), v.get_s());
        }

        ,__test_extended_class : function(r,v) {
            this.assertEquals(r.get_i(), v.get_i());
            this.assertEquals(r.get_s(), v.get_s());
            this.assertEquals(r.get_f(), v.get_f());

            for (var i=0; i<r.get_simple().length; ++i) {
                this.__test_simple_class(r.get_simple()[i], v.get_simple()[i]);
            }

            this.__test_other_class(r.get_other(), v.get_other());
            this.__test_non_nillable_class(r.get_p(), v.get_p());
            this.assertEquals(r.get_l().getTime(), v.get_l().getTime());
            this.assertEquals(r.get_q(), v.get_q());
        }

        ,test_echo_simple_class : function() {
            var service_name = "echo_simple_class";
            var ctx = this;

            var val = this.c.get_object(ctx.ns,"SimpleClass");
            val.set_i(45);
            val.set_s("asd");

            this.__test_echo(service_name, val, function(r,v) {
                ctx.__test_simple_class(r,v);
            });
        }

        ,test_echo_simple_class_array : function() {
            var service_name = "echo_simple_class_array";
            var ctx = this;
            var val = []

            val.push(this.c.get_object(ctx.ns,"SimpleClass"));
            val.push(this.c.get_object(ctx.ns,"SimpleClass"));

            val[0].set_i(45);
            val[0].set_s("asd");

            val[1].set_i(12);
            val[1].set_s("qwe");

            this.__test_echo_array(service_name, val, function(r,v,i) {
                ctx.__test_simple_class(r[i],v[i]);
            });
        }

        ,test_echo_nested_class : function() {
            var service_name = "echo_nested_class";
            var ctx = this;
            var val = this.c.get_object(ctx.ns,"NestedClass");

            val.set_i(45);
            val.set_s("asd");
            val.set_f(12.34);

            val.set_simple([]);
            val.get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));
            val.get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));

            val.get_simple()[0].set_i(45);
            val.get_simple()[0].set_s("asd");
            val.get_simple()[1].set_i(12);
            val.get_simple()[1].set_s("qwe");

            val.set_other(this.c.get_object(ctx.ns,"OtherClass"));
            val.get_other().set_dt(new Date(2010,05,02));
            val.get_other().set_d(123.456);
            val.get_other().set_b(true);

            this.__test_echo(service_name, val, function(r,v) {
                ctx.__test_nested_class(r,v);
            });
        }

        ,test_echo_nested_class_array : function() {
            var service_name = "echo_nested_class_array";
            var ctx = this;
            var val = []

            val.push(this.c.get_object(ctx.ns,"NestedClass"));
            val.push(this.c.get_object(ctx.ns,"NestedClass"));

            for (var i=0; i< val.length; ++i) {
                val[i].set_i(45 + i);
                val[i].set_s("asd" + i);
                val[i].set_f(12.34 + i);

                val[i].set_simple([]);
                val[i].get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));
                val[i].get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));

                val[i].get_simple()[0].set_i(45 + i);
                val[i].get_simple()[0].set_s("asd"  + i);
                val[i].get_simple()[1].set_i(12 + i);
                val[i].get_simple()[1].set_s("qwe" + i);

                val[i].set_other(this.c.get_object(ctx.ns,"OtherClass"));
                val[i].get_other().set_dt(new Date(new Date().getTime() + i));
                val[i].get_other().set_d(123.456 + i);
                val[i].get_other().set_b(true);
            }

            this.__test_echo_array(service_name, val, function(r,v,i) {
                ctx.__test_nested_class(r[i],v[i]);
            });
        }

        ,test_echo_extension_class : function() {
            var service_name = "echo_extension_class";
            var ctx = this;
            var val = this.c.get_object(ctx.ns,"ExtensionClass");

            val.set_i(45);
            val.set_s("asd");
            val.set_f(12.34);

            val.set_simple([]);
            val.get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));
            val.get_simple().push(this.c.get_object(ctx.ns,"SimpleClass"));

            val.get_simple()[0].set_i(45);
            val.get_simple()[0].set_s("asd");
            val.get_simple()[1].set_i(12);
            val.get_simple()[1].set_s("qwe");

            val.set_other(this.c.get_object(ctx.ns,"OtherClass"));
            val.get_other().set_dt(new Date(2010,05,02));
            val.get_other().set_d(123.456);
            val.get_other().set_b(true);

            val.set_p(this.c.get_object(ctx.ns,"NonNillableClass"));
            val.get_p().set_dt(new Date(2010,06,02));
            val.get_p().set_i(123);
            val.get_p().set_s("punk");

            val.set_l(new Date(2010,07,02));
            val.set_q(5);

            this.__test_echo(service_name, val, function(r,v) {
                ctx.__test_extended_class(r,v);
            });
        }

        // misc tests
        ,test_empty: function() {
            var ctx=this;
            var service_name = "test_empty";

            ctx.c.easy(service_name
                ,function(r) {
                    ctx.resume(function() {

                    });
                });
            ctx.wait();
        }

        ,test_multi_param: function() {
            var service_name = "multi_param";
            var ctx=this;
            ctx.c.easy(service_name
                ,"string"
                ,123
                ,new Date()
                ,function(r) {
                    ctx.resume(function() {

                    });
                });
            ctx.wait();
        }

        ,test_return_only: function() {
            var service_name = "return_only";
            var ctx=this;
            ctx.c.easy(service_name
                ,function(r) {
                    ctx.resume(function() {
                        ctx.assertEquals(r, 'howdy');
                    });
                });
            ctx.wait();
        }

        ,test_alternate_name: function() {
            var service_name = "do_something";
            var ctx=this;
            var val = 'punk';

            ctx.c.easy(service_name
                ,'punk'
                ,function(r) {
                    ctx.resume(function() {
                        ctx.assertEquals(r, val);
                    });
                });
            ctx.wait();
        }
    }
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import canvasBaseTheme from '@instructure/canvas-theme'
import canvasHighContrastTheme from '@instructure/canvas-high-contrast-theme'
import moment from 'moment'
import tz from 'timezone_core'
import './fakeRequireJSFallback'

// we already put a <script> tag for the locale corresponding ENV.MOMENT_LOCALE
// on the page from rails, so this should not cause a new network request.
moment().locale(ENV.MOMENT_LOCALE)

// These timezones and locales should already be put on the page as <script>
// tags from rails. this block should not create any network requests.
if (typeof ENV !== 'undefined') {
  if (ENV.TIMEZONE) tz.changeZone(ENV.TIMEZONE)
  if (ENV.CONTEXT_TIMEZONE) tz.preload(ENV.CONTEXT_TIMEZONE)
  if (ENV.BIGEASY_LOCALE) tz.changeLocale(ENV.BIGEASY_LOCALE, ENV.MOMENT_LOCALE)
}

// This will inject and set up sentry for deprecation reporting.  It should be
// stripped out and be a no-op in production.
if (process.env.NODE_ENV !== 'production' && process.env.DEPRECATION_SENTRY_DSN) {
  const Raven = require('raven-js')
  Raven.config(process.env.DEPRECATION_SENTRY_DSN, {
    ignoreErrors: ['renderIntoDiv', 'renderSidebarIntoDiv'], // silence the `Cannot read property 'renderIntoDiv' of null` errors we get from the pre- rce_enhancements old rce code
    release: process.env.GIT_COMMIT
  }).install()

  const setupRavenConsoleLoggingPlugin = require('../jsx/shared/helpers/setupRavenConsoleLoggingPlugin')
    .default
  setupRavenConsoleLoggingPlugin(Raven, {loggerName: 'console'})
}

if (process.env.NODE_ENV !== 'production') {
  const {
    filterUselessConsoleMessages
  } = require('@instructure/js-utils/lib/filterUselessConsoleMessages')
  filterUselessConsoleMessages(console)
}

// setup the inst-ui default theme
if (ENV.use_high_contrast) {
  canvasHighContrastTheme.use()
} else {
  const brandvars = window.CANVAS_ACTIVE_BRAND_VARIABLES || {}

  // Set CSS transitions to 0ms in Selenium and JS tests
  let transitionOverride = {}
  if (process.env.NODE_ENV === 'test' || window.INST.environment === 'test') {
    transitionOverride = {
      transitions: {
        duration: '0ms'
      }
    }
  }

  canvasBaseTheme.use({
    overrides: {...transitionOverride, ...brandvars}
  })
}

/* #__PURE__ */ if (process.env.NODE_ENV === 'test' || window.INST.environment === 'test') {
  // This is for the `wait_for_ajax_requests` method in selenium
  window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__ = 0
  const send = XMLHttpRequest.prototype.send
  XMLHttpRequest.prototype.send = function() {
    window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__++
    // 'loadend' gets fired after both successful and errored requests
    this.addEventListener('loadend', () => {
      window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__--
      window.dispatchEvent(new CustomEvent('canvasXHRComplete'))
    })
    return send.apply(this, arguments)
  }

  // and this so it also tracks `fetch` requests
  const fetch = window.fetch
  window.fetch = function() {
    window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__++
    const promise = fetch.apply(this, arguments)
    promise.finally(() => window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__--)
    return promise
  }
}
<commit_msg>treesame commit of origin/stable/2020-11-18<commit_after>/*
 * Copyright (C) 2016 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import canvasBaseTheme from '@instructure/canvas-theme'
import canvasHighContrastTheme from '@instructure/canvas-high-contrast-theme'
import moment from 'moment'
import tz from 'timezone_core'
import './fakeRequireJSFallback'

// we already put a <script> tag for the locale corresponding ENV.MOMENT_LOCALE
// on the page from rails, so this should not cause a new network request.
moment().locale(ENV.MOMENT_LOCALE)

// These timezones and locales should already be put on the page as <script>
// tags from rails. this block should not create any network requests.
if (typeof ENV !== 'undefined') {
  if (ENV.TIMEZONE) tz.changeZone(ENV.TIMEZONE)
  if (ENV.CONTEXT_TIMEZONE) tz.preload(ENV.CONTEXT_TIMEZONE)
  if (ENV.BIGEASY_LOCALE) tz.changeLocale(ENV.BIGEASY_LOCALE, ENV.MOMENT_LOCALE)
}

// This will inject and set up sentry for deprecation reporting.  It should be
// stripped out and be a no-op in production.
if (process.env.NODE_ENV !== 'production' && process.env.DEPRECATION_SENTRY_DSN) {
  const Raven = require('raven-js')
  Raven.config(process.env.DEPRECATION_SENTRY_DSN, {
    ignoreErrors: ['renderIntoDiv', 'renderSidebarIntoDiv'], // silence the `Cannot read property 'renderIntoDiv' of null` errors we get from the pre- rce_enhancements old rce code
    release: process.env.GIT_COMMIT
  }).install()

  const setupRavenConsoleLoggingPlugin = require('../jsx/shared/helpers/setupRavenConsoleLoggingPlugin')
    .default
  setupRavenConsoleLoggingPlugin(Raven, {loggerName: 'console'})
}

if (process.env.NODE_ENV !== 'production') {
  const {
    filterUselessConsoleMessages
  } = require('@instructure/js-utils/lib/filterUselessConsoleMessages')
  filterUselessConsoleMessages(console)
}

// setup the inst-ui default theme
// override the fontFamily to include "Lato Extended", which we prefer
// to load over plain Lato (see LS-1559)
if (ENV.use_high_contrast) {
  canvasHighContrastTheme.use({
    overrides: {
      typography: {
        fontFamily: 'LatoWeb, "Lato Extended", Lato, "Helvetica Neue", Helvetica, Arial, sans-serif'
      }
    }
  })
} else {
  const brandvars = window.CANVAS_ACTIVE_BRAND_VARIABLES || {}

  // Set CSS transitions to 0ms in Selenium and JS tests
  let transitionOverride = {}
  if (process.env.NODE_ENV === 'test' || window.INST.environment === 'test') {
    transitionOverride = {
      transitions: {
        duration: '0ms'
      }
    }
  }

  canvasBaseTheme.use({
    overrides: {
      ...transitionOverride,
      ...brandvars,
      typography: {
        fontFamily: 'LatoWeb, "Lato Extended", Lato, "Helvetica Neue", Helvetica, Arial, sans-serif'
      }
    }
  })
}

/* #__PURE__ */ if (process.env.NODE_ENV === 'test' || window.INST.environment === 'test') {
  // This is for the `wait_for_ajax_requests` method in selenium
  window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__ = 0
  const send = XMLHttpRequest.prototype.send
  XMLHttpRequest.prototype.send = function() {
    window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__++
    // 'loadend' gets fired after both successful and errored requests
    this.addEventListener('loadend', () => {
      window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__--
      window.dispatchEvent(new CustomEvent('canvasXHRComplete'))
    })
    return send.apply(this, arguments)
  }

  // and this so it also tracks `fetch` requests
  const fetch = window.fetch
  window.fetch = function() {
    window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__++
    const promise = fetch.apply(this, arguments)
    promise.finally(() => window.__CANVAS_IN_FLIGHT_XHR_REQUESTS__--)
    return promise
  }
}
<|endoftext|>


<commit_before>var _ = require('footwork-lodash');
var fw = require('knockout/build/output/knockout-latest');

var isEntity = require('../entity-tools').isEntity;

var routerTools = require('./router-tools');
var getNamedRoute = routerTools.getNamedRoute;
var getMatchedRoute = routerTools.getMatchedRoute;

var util = require('../../misc/util');
var propertyDispose = util.propertyDispose;
var privateDataSymbol = util.getSymbol('footwork');
var resultBound = util.resultBound;

var viewModelMethodDispose = require('../viewModel/viewModel-methods').dispose;
var clearSequenceQueue = require('../../binding/animation-sequencing').clearSequenceQueue;
var noComponentSelected = require('./router-config').noComponentSelected;

var activeOutlets = fw.observableArray();

module.exports = {
  outlet: function (outletName, options) {
    if (!_.isObject(options)) {
      options = { display: arguments.length > 1 ? options || noComponentSelected : undefined };
    }

    var router = this;
    var outlets = router[privateDataSymbol].outlets;
    var outletProperties = outlets[outletName] || {};
    var outlet = outletProperties.routeObservable;
    var outletViewModel = outletProperties.outletViewModel;
    var routerOutletOptions = router[privateDataSymbol].configParams.outlet || {};

    if (!fw.isObservable(outlet)) {
      // router outlet observable not found, we must create a new one
      outlet = fw.observable({
        name: noComponentSelected,
        params: {},
        getOnCompleteCallback: function () { return _.noop; }
      });

      // register the new outlet under its outletName
      outlets[outletName] = {
        outletViewModel: outletProperties.outletViewModel || null,
        routeObservable: outlet
      };
    }

    if (options.display) {
      // user specified a new display, lets find out how long the transition should take and cache that on the outlet display for lookup later
      outlet().transition = options.transition || resultBound(routerOutletOptions, 'transition', router, [outletName, options.display]) || 0;
    }

    if (outletViewModel) {
      // grab and set the loading display if needed
      if (arguments.length > 1) {
        // user requested change, lets find out and inject what we need to display during load
        outletViewModel.loading(options.loading || resultBound(routerOutletOptions, 'loading', router, [outletName, options.display]) || outletViewModel[privateDataSymbol].originalDisplay);
      } else {
        // bootup process, just show original contents during startup
        outletViewModel.loading(outletViewModel[privateDataSymbol].originalDisplay);
      }
    }

    var outletHasMutated = false;
    if (!_.isUndefined(options.display)) {
      var currentOutletDef = outlet();

      if (currentOutletDef.name !== options.display) {
        currentOutletDef.name = options.display;
        outletHasMutated = true;
      }
      if (_.isObject(options.params)) {
        currentOutletDef.params = options.params;
        outletHasMutated = true;
      }

      if (outletHasMutated) {
        clearSequenceQueue();

        if (outletViewModel) {
          outletViewModel[privateDataSymbol].loadingChildren.removeAll();
          outletViewModel[privateDataSymbol].outletIsChanging(true);
        }

        currentOutletDef.getOnCompleteCallback = function (element) {
          var outletElement = element.parentNode;

          activeOutlets.remove(outlet);
          outletElement.setAttribute('data-rendered', currentOutletDef.name);

          return function addBindingOnComplete () {
            var outletViewModel = outlets[outletName].outletViewModel;
            outletViewModel[privateDataSymbol].outletOnComplete = function () {
              router[privateDataSymbol].scrollToFragment();
              [routerOutletOptions.onComplete, options.onComplete].forEach(function callOnCompleteFunctions (onComplete) {
                (onComplete || _.noop).call(router, outletElement);
              });
            };
            outletViewModel[privateDataSymbol].outletIsChanging(false);
          };
        };

        if (activeOutlets().indexOf(outlet) === -1) {
          activeOutlets.push(outlet);
        }

        outlet.valueHasMutated();
      }
    }

    return outlet;
  },
  getRouteForState: function (currentState) {
    var route;

    if (_.isObject(currentState)) {
      route = getNamedRoute(this, currentState);
    } else {
      route = getMatchedRoute(this, currentState);
    }

    if (!route && (route = _.find(this.routes(), { unknown: true }))) {
      route = {
        controller: route.controller,
        title: route.title,
        url: _.isString(currentState) ? currentState : null
      };
    }

    return route;
  },
  replaceState: function (newState) {
    if (this.activated()) {
      this[privateDataSymbol].alterStateMethod = history.replaceState;
      this.currentState(newState);
    }

    return this;
  },
  pushState: function (newState) {
    if (this.activated()) {
      this[privateDataSymbol].alterStateMethod = history.pushState;
      this.currentState(newState);
    }

    return this;
  },
  dispose: function () {
    if (!this[privateDataSymbol].isDisposed) {
      // first run all of the standard viewModel disposal logic
      viewModelMethodDispose.call(this);

      // deactivate the router (unbinds the history event listener)
      this.activated(false);

      // dispose of all privately stored properties
      _.each(this[privateDataSymbol], propertyDispose);

      return this;
    }
  }
};

<commit_msg>removed dead code<commit_after>var _ = require('footwork-lodash');
var fw = require('knockout/build/output/knockout-latest');

var isEntity = require('../entity-tools').isEntity;

var routerTools = require('./router-tools');
var getNamedRoute = routerTools.getNamedRoute;
var getMatchedRoute = routerTools.getMatchedRoute;

var util = require('../../misc/util');
var propertyDispose = util.propertyDispose;
var privateDataSymbol = util.getSymbol('footwork');
var resultBound = util.resultBound;

var viewModelMethodDispose = require('../viewModel/viewModel-methods').dispose;
var clearSequenceQueue = require('../../binding/animation-sequencing').clearSequenceQueue;
var noComponentSelected = require('./router-config').noComponentSelected;

module.exports = {
  outlet: function (outletName, options) {
    if (!_.isObject(options)) {
      options = { display: arguments.length > 1 ? options || noComponentSelected : undefined };
    }

    var router = this;
    var outlets = router[privateDataSymbol].outlets;
    var outletProperties = outlets[outletName] || {};
    var outlet = outletProperties.routeObservable;
    var outletViewModel = outletProperties.outletViewModel;
    var routerOutletOptions = router[privateDataSymbol].configParams.outlet || {};

    if (!fw.isObservable(outlet)) {
      // router outlet observable not found, we must create a new one
      outlet = fw.observable({
        name: noComponentSelected,
        params: {},
        getOnCompleteCallback: function () { return _.noop; }
      });

      // register the new outlet under its outletName
      outlets[outletName] = {
        outletViewModel: outletProperties.outletViewModel || null,
        routeObservable: outlet
      };
    }

    if (options.display) {
      // user specified a new display, lets find out how long the transition should take and cache that on the outlet display for lookup later
      outlet().transition = options.transition || resultBound(routerOutletOptions, 'transition', router, [outletName, options.display]) || 0;
    }

    if (outletViewModel) {
      // grab and set the loading display if needed
      if (arguments.length > 1) {
        // user requested change, lets find out and inject what we need to display during load
        outletViewModel.loading(options.loading || resultBound(routerOutletOptions, 'loading', router, [outletName, options.display]) || outletViewModel[privateDataSymbol].originalDisplay);
      } else {
        // bootup process, just show original contents during startup
        outletViewModel.loading(outletViewModel[privateDataSymbol].originalDisplay);
      }
    }

    var outletHasMutated = false;
    if (!_.isUndefined(options.display)) {
      var currentOutletDef = outlet();

      if (currentOutletDef.name !== options.display) {
        currentOutletDef.name = options.display;
        outletHasMutated = true;
      }
      if (_.isObject(options.params)) {
        currentOutletDef.params = options.params;
        outletHasMutated = true;
      }

      if (outletHasMutated) {
        clearSequenceQueue();

        if (outletViewModel) {
          outletViewModel[privateDataSymbol].loadingChildren.removeAll();
          outletViewModel[privateDataSymbol].outletIsChanging(true);
        }

        currentOutletDef.getOnCompleteCallback = function (element) {
          var outletElement = element.parentNode;
          outletElement.setAttribute('data-rendered', currentOutletDef.name);

          return function addBindingOnComplete () {
            var outletViewModel = outlets[outletName].outletViewModel;
            outletViewModel[privateDataSymbol].outletOnComplete = function () {
              router[privateDataSymbol].scrollToFragment();
              [routerOutletOptions.onComplete, options.onComplete].forEach(function callOnCompleteFunctions (onComplete) {
                (onComplete || _.noop).call(router, outletElement);
              });
            };
            outletViewModel[privateDataSymbol].outletIsChanging(false);
          };
        };

        outlet.valueHasMutated();
      }
    }

    return outlet;
  },
  getRouteForState: function (currentState) {
    var route;

    if (_.isObject(currentState)) {
      route = getNamedRoute(this, currentState);
    } else {
      route = getMatchedRoute(this, currentState);
    }

    if (!route && (route = _.find(this.routes(), { unknown: true }))) {
      route = {
        controller: route.controller,
        title: route.title,
        url: _.isString(currentState) ? currentState : null
      };
    }

    return route;
  },
  replaceState: function (newState) {
    if (this.activated()) {
      this[privateDataSymbol].alterStateMethod = history.replaceState;
      this.currentState(newState);
    }

    return this;
  },
  pushState: function (newState) {
    if (this.activated()) {
      this[privateDataSymbol].alterStateMethod = history.pushState;
      this.currentState(newState);
    }

    return this;
  },
  dispose: function () {
    if (!this[privateDataSymbol].isDisposed) {
      // first run all of the standard viewModel disposal logic
      viewModelMethodDispose.call(this);

      // deactivate the router (unbinds the history event listener)
      this.activated(false);

      // dispose of all privately stored properties
      _.each(this[privateDataSymbol], propertyDispose);

      return this;
    }
  }
};

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import $ from 'jquery'
import _ from 'underscore'
import preventDefault from 'compiled/fn/preventDefault'
import ReactModal from 'react-modal'
import ModalContent from './modal-content'
import ModalButtons from './modal-buttons'

  const modalOverrides = {
    overlay : {
      backgroundColor: 'rgba(0,0,0,0.5)'
    },
    content : {
      position: 'static',
      top: '0',
      left: '0',
      right: 'auto',
      bottom: 'auto',
      borderRadius: '0',
      border: 'none',
      padding: '0'
    }
  };

  const Modal = React.createClass({

    getInitialState() {
      return {
        modalIsOpen: this.props.isOpen
      }
    },
    getDefaultProps(){
      return {
        className: "ReactModal__Content--canvas", // Override with "ReactModal__Content--canvas ReactModal__Content--mini-modal" for a mini modal
        style: {},
      };
    },
    componentWillReceiveProps(props){
      let callback
      if (this.props.isOpen && !props.isOpen) callback = this.cleanupAfterClose
      this.setState({modalIsOpen: props.isOpen}, callback);
    },

    openModal() {
      this.setState({modalIsOpen: true});
    },

    cleanupAfterClose () {
      if (this.props.onRequestClose) this.props.onRequestClose();
      $(this.getAppElement()).removeAttr('aria-hidden');
    },

    closeModal() {
      this.setState({modalIsOpen: false}, this.cleanupAfterClose);
    },

    closeWithX() {
      if(_.isFunction(this.props.closeWithX))
        this.props.closeWithX()
      this.closeModal();
    },
    onSubmit(){
      const promise = this.props.onSubmit();
      $(this.modal).disableWhileLoading(promise);
    },
    getAppElement () {
      // Need to wait for the dom to load before we can get the default #application dom element
      return this.props.appElement || document.getElementById('application');
    },
    processMultipleChildren(props){
      let content = null;
      let buttons = null;

      React.Children.forEach(props.children, function(child){
        if(child.type == ModalContent){
          content = child;
        }
        if(child.type == ModalButtons){
          buttons = child;
        }
      });

      // Warning if you don't include a component of the right type
      if(content == null){
        console.warn('You should wrap your content in the modal-content component');
      }
      if(buttons == null){
        console.warn('You should wrap your buttons in the modal-buttons component');
      }

      if(this.props.onSubmit){
        return (
          <form className="ModalForm" onSubmit={preventDefault(this.onSubmit)}>
            { [content, buttons] }
          </form>
        )
      }
      else
      {
        return [content, buttons]; // This order needs to be maintained
      }
    },
    render() {
      return (

          <ReactModal
            ariaHideApp={!!this.state.modalIsOpen}
            isOpen={!!this.state.modalIsOpen}
            onRequestClose={this.closeModal}
            className={this.props.className}
            style={modalOverrides}
            overlayClassName={this.props.overlayClassName}
            contentLabel={this.props.contentLabel}
            appElement={this.getAppElement()}>

 { this.modal = c }}
              className="ReactModal__Layout"
              style={this.props.style}
            >

{this.props.title}

                  <button ref={(c) => { this.closeBtn = c }} className="Button Button--icon-action" type="button" onClick={this.closeWithX}>

                    Close
                  </button>

              {this.processMultipleChildren(this.props)}

          </ReactModal>

      );
    }

  });

export default Modal
<commit_msg>focus on close button of modal when opened<commit_after>/*
 * Copyright (C) 2015 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import $ from 'jquery'
import _ from 'underscore'
import preventDefault from 'compiled/fn/preventDefault'
import ReactModal from 'react-modal'
import ModalContent from './modal-content'
import ModalButtons from './modal-buttons'

  const modalOverrides = {
    overlay : {
      backgroundColor: 'rgba(0,0,0,0.5)'
    },
    content : {
      position: 'static',
      top: '0',
      left: '0',
      right: 'auto',
      bottom: 'auto',
      borderRadius: '0',
      border: 'none',
      padding: '0'
    }
  };

  const Modal = React.createClass({

    getDefaultProps(){
      return {
        className: "ReactModal__Content--canvas", // Override with "ReactModal__Content--canvas ReactModal__Content--mini-modal" for a mini modal
        style: {},
      };
    },
    getInitialState() {
      return {
        modalIsOpen: this.props.isOpen
      }
    },
    componentWillReceiveProps(props){
      let callback
      if (this.props.isOpen && !props.isOpen) callback = this.cleanupAfterClose
      this.setState({modalIsOpen: props.isOpen}, callback);
    },

    openModal() {
      this.setState({modalIsOpen: true});
    },

    cleanupAfterClose () {
      if (this.props.onRequestClose) this.props.onRequestClose();
      $(this.getAppElement()).removeAttr('aria-hidden');
    },

    closeModal() {
      this.setState({modalIsOpen: false}, this.cleanupAfterClose);
    },

    closeWithX() {
      if(_.isFunction(this.props.closeWithX))
        this.props.closeWithX()
      this.closeModal();
    },
    onSubmit(){
      const promise = this.props.onSubmit();
      $(this.modal).disableWhileLoading(promise);
    },
    onAfterOpen() {
      this.closeBtn.focus()
    },
    getAppElement () {
      // Need to wait for the dom to load before we can get the default #application dom element
      return this.props.appElement || document.getElementById('application');
    },
    processMultipleChildren(props){
      let content = null;
      let buttons = null;

      React.Children.forEach(props.children, function(child){
        if(child.type == ModalContent){
          content = child;
        }
        if(child.type == ModalButtons){
          buttons = child;
        }
      });

      // Warning if you don't include a component of the right type
      if(content == null){
        console.warn('You should wrap your content in the modal-content component');
      }
      if(buttons == null){
        console.warn('You should wrap your buttons in the modal-buttons component');
      }

      if(this.props.onSubmit){
        return (
          <form className="ModalForm" onSubmit={preventDefault(this.onSubmit)}>
            { [content, buttons] }
          </form>
        )
      }
      else
      {
        return [content, buttons]; // This order needs to be maintained
      }
    },
    render() {
      return (

          <ReactModal
            ariaHideApp={!!this.state.modalIsOpen}
            isOpen={!!this.state.modalIsOpen}
            onRequestClose={this.closeModal}
            className={this.props.className}
            style={modalOverrides}
            onAfterOpen={this.onAfterOpen}
            overlayClassName={this.props.overlayClassName}
            contentLabel={this.props.contentLabel}
            appElement={this.getAppElement()}>

 { this.modal = c }}
              className="ReactModal__Layout"
              style={this.props.style}
            >

{this.props.title}

                  <button ref={(c) => { this.closeBtn = c }} className="Button Button--icon-action" type="button" onClick={this.closeWithX}>

                    Close
                  </button>

              {this.processMultipleChildren(this.props)}

          </ReactModal>

      );
    }

  });

export default Modal
<|endoftext|>