<commit_before>var UsersTable = function () {
    this.tableId = '#users-table';

    this.table = $('#users-table').DataTable( {
                "sAjaxSource": "/users/all",
                "sAjaxDataProp": "users",
                "order": [],
                "columns": [
                    null,
                    {data: 0},
                    {data: 1},
                    {data: 2},
                    {data: 3}
                ],
                "columnDefs": [
                    {
                        "targets": 0,
                        "orderable": false,
                        "className": "column-checkbox",
                        "render": function (data, type, users, meta){
                            var checkbox = '
' +
                                           '    <input name="selected-item" id="item'+users[0]+'" value="'+users[0]+'" type="checkbox">' +
                                           '    '
                                           '
';

                        return checkbox;
                    }
                    },
                    {
                        'className' : 'body-checkbox',
                        'targets':  4,
                        'render': function(data, type, users, meta){
                            return '<input type="checkbox" name="active" id="active'+users[0]+
                                    '" value="'+users[0]+ (data ? '" checked>' : '" >');
                    },
                } ],
               "paging": true,
               "bFilter": false,
               "info": false, //number of rows in footer table
               "initComplete": function(settings, json) {
                    $( 'input[name="active"]' ).each(function() {
                        var switchery = new Switchery(this, {
                            size: 'small',
                            color: '#5A9DC4'
                        });

                        $(this).next().click(function() {
                            var checkbox = $(this).siblings().get(0);

                            var ids = [checkbox.value],
                                status = $(checkbox).attr('name'),
                                status_value = checkbox.checked;

                            changeStatus(ids, status, status_value);
                        });
                    });

                    $('input[name="selected-item"]').change(function() {
                        checkManySelected();
                    });
                }
            });

    $('#users-table thead tr th').first().addClass('check-all')

    $('#users-table .check-all').click(function() {
        var checked = $('#users-table .check-all input:checkbox').get(0).checked;
        $('input[name="selected-item"]').each(function() {
            $(this).prop('checked', checked);
        });
        checkManySelected();
    })
};

UsersTable.prototype.getCheckedIds = function(first_argument) {
    var checkedIds = [];
    $('#users-table input[name="selected-item"]').each(function() {
        if (this.checked) {
            checkedIds.push(this.value);
        }
    });
    return checkedIds;
};

var usersTable = new UsersTable();

var changeStatus = function(ids, status, status_value){
    if (ids.length) {
        $.ajax({
            method: "POST",
            url: "/"+lang+"/users/admin/users/"+status+"/"+status_value,
            data: {ids:ids},
            statusCode: {
                500: function () {
                    showMessage('Não foi possível alterar o(s) usuário(s) selecionada(s) devido a um erro no servidor.', 'danger', 8000);
                },
                404: function () {
                    showMessage('Um ou mais usuários selecionados não puderam ser encontrados, a lista de usuários será atualizada.', 'info', 8000);
                    usersTable.table.fnReloadAjax();
                }
            },
            success: function (message) {
                for (item in ids) {
                    if ($('#'+status+ids[item])[0].checked !== status_value) {
                        $('#'+status+ids[item]).click();
                    }
                }

                showMessage(message, 'success', 8000);
            }
        });
    } else {
        showMessage('Por favor selecione algum usuário para alterar.', 'warning', 8000);
    }
}

var destroy = function(ids){
    if (ids.length) {
        $.ajax({
            method: "POST",
            url: "/"+lang+"/users/admin/delete",
            data: {ids:ids},
            statusCode: {
                500: function () {
                    showMessage('Não foi possível alterar o(s) usuário(s) selecionado(s) devido a um erro no servidor.', 'danger', 8000);
                },
                404: function () {
                    showMessage('Um ou mais usuários selecionados não puderam ser encontradas, a lista de notícias será atualizada.', 'info', 8000);
                    usersTable.table.fnReloadAjax();
                }
            },
            success: function (message) {
                for (item in ids) {
                    itemId = '#item'+ids[item];
                    usersTable.table.row($(itemId).parents('tr')).remove().draw();
                }

                showMessage(message, 'success', 8000);
            }
        });
    } else {
        showMessage('Por favor selecione para excluir.', 'warning', 8000);
    }
}

var edit = function(ids){
    if (ids.length) {
        window.location = '/'+lang+'/users/admin/users/'+ids[0]+'/edit';
    } else {
        showMessage('Por favor selecione para editar.', 'warning', 8000);
    }
}

var checkManySelected = function() {
    if (usersTable.getCheckedIds().length > 1) {
        $('#admin-edit').prop('disabled', true);
    } else {
        $('#admin-edit').prop('disabled', false);
    }
}

$(document).ready(function(){
    $('#admin-delete').click(function() {
        destroy(usersTable.getCheckedIds());
    });
    $('#admin-edit').click(function() {
        edit(usersTable.getCheckedIds());
    });
    $('#admin-activate').click(function() {
        changeStatus(usersTable.getCheckedIds(), 'active', true);
    });
    $('#admin-deactivate').click(function() {
        changeStatus(usersTable.getCheckedIds(), 'active', false);
    });

    setAlertTimeOut(8000);
});
<commit_msg>Add infinite vertical scrolling in users dataTable.<commit_after>var UsersTable = function () {
    this.tableId = '#users-table';

    this.table = $('#users-table').DataTable( {
                "sAjaxSource": "/users/all",
                "sAjaxDataProp": "users",
                "order": [],
                "columns": [
                    null,
                    {data: 0},
                    {data: 1},
                    {data: 2},
                    {data: 3}
                ],
                "columnDefs": [
                    {
                        "targets": 0,
                        "orderable": false,
                        "className": "column-checkbox",
                        "render": function (data, type, users, meta){
                            var checkbox = '
' +
                                           '    <input name="selected-item" id="item'+users[0]+'" value="'+users[0]+'" type="checkbox">' +
                                           '    '
                                           '
';

                        return checkbox;
                    }
                    },
                    {
                        'className' : 'body-checkbox',
                        'targets':  4,
                        'render': function(data, type, users, meta){
                            return '<input type="checkbox" name="active" id="active'+users[0]+
                                    '" value="'+users[0]+ (data ? '" checked>' : '" >');
                    },
                } ],
                "paging": false,
                "deferRender": true,
                "scrollY": 500,
                "scrollX": true,
                "scrollCollapse": true,
                "info": false, //number of rows in footer table
                "initComplete": function(settings, json) {
                    $( 'input[name="active"]' ).each(function() {
                        var switchery = new Switchery(this, {
                            size: 'small',
                            color: '#5A9DC4'
                        });

                        $(this).next().click(function() {
                            var checkbox = $(this).siblings().get(0);

                            var ids = [checkbox.value],
                                status = $(checkbox).attr('name'),
                                status_value = checkbox.checked;

                            changeStatus(ids, status, status_value);
                        });
                    });

                    $('input[name="selected-item"]').change(function() {
                        checkManySelected();
                    });
                }
            });

    $('#users-table thead tr th').first().addClass('check-all')

    $('#users-table .check-all').click(function() {
        var checked = $('#users-table .check-all input:checkbox').get(0).checked;
        $('input[name="selected-item"]').each(function() {
            $(this).prop('checked', checked);
        });
        checkManySelected();
    })
};

UsersTable.prototype.getCheckedIds = function(first_argument) {
    var checkedIds = [];
    $('#users-table input[name="selected-item"]').each(function() {
        if (this.checked) {
            checkedIds.push(this.value);
        }
    });
    return checkedIds;
};

var usersTable = new UsersTable();

var changeStatus = function(ids, status, status_value){
    if (ids.length) {
        $.ajax({
            method: "POST",
            url: "/"+lang+"/users/admin/users/"+status+"/"+status_value,
            data: {ids:ids},
            statusCode: {
                500: function () {
                    showMessage('Não foi possível alterar o(s) usuário(s) selecionada(s) devido a um erro no servidor.', 'danger', 8000);
                },
                404: function () {
                    showMessage('Um ou mais usuários selecionados não puderam ser encontrados, a lista de usuários será atualizada.', 'info', 8000);
                    usersTable.table.fnReloadAjax();
                }
            },
            success: function (message) {
                for (item in ids) {
                    if ($('#'+status+ids[item])[0].checked !== status_value) {
                        $('#'+status+ids[item]).click();
                    }
                }

                showMessage(message, 'success', 8000);
            }
        });
    } else {
        showMessage('Por favor selecione algum usuário para alterar.', 'warning', 8000);
    }
}

var destroy = function(ids){
    if (ids.length) {
        $.ajax({
            method: "POST",
            url: "/"+lang+"/users/admin/delete",
            data: {ids:ids},
            statusCode: {
                500: function () {
                    showMessage('Não foi possível alterar o(s) usuário(s) selecionado(s) devido a um erro no servidor.', 'danger', 8000);
                },
                404: function () {
                    showMessage('Um ou mais usuários selecionados não puderam ser encontradas, a lista de notícias será atualizada.', 'info', 8000);
                    usersTable.table.fnReloadAjax();
                }
            },
            success: function (message) {
                for (item in ids) {
                    itemId = '#item'+ids[item];
                    usersTable.table.row($(itemId).parents('tr')).remove().draw();
                }

                showMessage(message, 'success', 8000);
            }
        });
    } else {
        showMessage('Por favor selecione para excluir.', 'warning', 8000);
    }
}

var edit = function(ids){
    if (ids.length) {
        window.location = '/'+lang+'/users/admin/users/'+ids[0]+'/edit';
    } else {
        showMessage('Por favor selecione para editar.', 'warning', 8000);
    }
}

var checkManySelected = function() {
    if (usersTable.getCheckedIds().length > 1) {
        $('#admin-edit').prop('disabled', true);
    } else {
        $('#admin-edit').prop('disabled', false);
    }
}

$(document).ready(function(){
    $('#admin-delete').click(function() {
        destroy(usersTable.getCheckedIds());
    });
    $('#admin-edit').click(function() {
        edit(usersTable.getCheckedIds());
    });
    $('#admin-activate').click(function() {
        changeStatus(usersTable.getCheckedIds(), 'active', true);
    });
    $('#admin-deactivate').click(function() {
        changeStatus(usersTable.getCheckedIds(), 'active', false);
    });

    setAlertTimeOut(8000);
});
<|endoftext|>


<commit_before>var server  = require("./server");
var path = require('path');

var domains = require("../config/domains");
var domain_validator = require(path.join(__dirname, "lib", "domain-restrictor"))(domains);
server.use(domain_validator);

require('./lib/distributor')(server);

server.listen(Number(process.argv[2]) || 3000);
<commit_msg>rformat frontend<commit_after>var server = require("./server");
var path   = require('path');

var domains = require("../config/domains");
var domain_validator = require(path.join(__dirname, "lib", "domain-restrictor"))(domains);

server.use(domain_validator);
require('./lib/distributor')(server);

server.listen(Number(process.argv[2]) || 3000);
<|endoftext|>


<commit_before>var db = Ti.Database.open('userDatabase');
db.file.setRemoteBackup(false);
db.execute('CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT, user TEXT, pass TEXT, userid INTEGER);');

//Text Field and Label
	//Main site field

var headerLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Log in!",
	font: {fontSize: 25},
	color: "#E47100",
	top: 45,
	left: margin*2.5
});

var userLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Username Here",
	font: {fontSize: 15, fontWeight: "bold"},
	color: "#CC6500",
	top: 90,
	left: margin*3
});

var userField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 120,
	width: 250,
	height: 30,
	hintText: "Username",
	value: ""
});

var passLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Password (6 character minimum)",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 160,
	color: "#CC6500",
	left: margin*3
});

var passField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	bordercolor: "#000",
	color: '#336699',
	top: 190,
	width: 250,
	height: 30,
	passwordMask: true,
	hintText: "Password (Six character minimum)"
});

	//Main Site Field end

	//Sign Up Field

var emailField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 40,
	width: 250,
	height: 30,
	hintText: "E-mail Address",
	value: "",
	returnKeyType: Ti.UI.RETURNKEY_NEXT
});

var emailLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Email Address",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 10,
	color: "#CC6500",
	left: margin*3
});

var userSignupField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 110,
	width: 250,
	height: 30,
	hintText: "Username",
	value: "",
	returnKeyType: Ti.UI.RETURNKEY_NEXT
});

var userSignupLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Username",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 80,
	color: "#CC6500",
	left: margin*3
});

var passSignupField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 185,
	width: 250,
	height: 30,
	hintText: "Password",
	passwordMask: true,
	returnKeyType: Ti.UI.RETURNKEY_NEXT
});

var passSignupLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Password (6 Characters!)",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 155,
	color: "#CC6500",
	left: margin*3
});

var passVerifyField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 260,
	width: 250,
	height: 30,
	hintText: "Verify Password",
	passwordMask: true,
	returnKeyType: Ti.UI.RETURNKEY_NEXT
});

var verifyLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Verify Password",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 230,
	color: "#CC6500",
	left: margin*3
});

var userIDField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 335,
	width: 250,
	height: 30,
	hintText: "User ID",
	value: "",
	focusable: true
});

var userIDLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "User ID - Provided by Admin",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 305,
	color: "#CC6500",
	left: margin*3
});

	//Signup Field end
//End Text Fields and Labels

var loginButton = Ti.UI.createLabel({
	borderRadius: 50,
	borderColor: "#000",
	text: "Sign In",
	backgroundColor: "#E47100",
	height: 50,
	width: "80%",
	top: 255,
	textAlign: "center"
});

var createButton = Ti.UI.createLabel({
	borderColor: "#000",
	borderRadius: 10,
	text: "Sign Up!",
	backgroundColor: "#CC6500",
	height: 50,
	width: "80%",
	top: 340,
	textAlign: "center"
});

var signupButton = Ti.UI.createLabel({
	borderColor: "#000",
	borderRadius: 10,
	text: "Confirm",
	backgroundColor: "#CC6500",
	height: 50,
	width: "80%",
	top: 410,
	textAlign: "center"
});

emailField.addEventListener('return', function() {
    userSignupField.focus();
});

userSignupField.addEventListener('return', function() {
    passSignupField.focus();
});

passSignupField.addEventListener('return', function() {
	passVerifyField.focus();
});

passVerifyField.addEventListener('return', function() {
    userIDField.focus();
});

//functions - main screen

var userCheck = function(){
	if(userField.value === ""){
		alert("No username entered!");
		return false;
	}else{
		passCheck();
		return true;
		passCheck();
	};
};

var passCheck = function (){
	if(passField.value.length < 6){
		alert("Password must be 6 characters long.");
	}else if (passField.value.length >= 6){
		countOpen();
		alert("Successful login!");

	};
};

//functions - main screen end
//functions - signup screen

var emailCheck = function(){
	var checkValue = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if (checkValue.test(emailField.value)){
		userSignupCheck();
	}else{
		alert("Email incorrect! Remember to use xxxx@xxx.com format");
	};
};

var userSignupCheck = function(){
	if(userSignupField.value === ""){
		alert("Username not entered!");
	}else{
		passSignupCheck();
		return true;
	};
};

var passSignupCheck = function(){
	if(passSignupField.value.length < 6){
		alert("Password must be 6 characters or over.");
	}else if (passSignupField.value.length >= 6){
		passVerifyCheck();
	};
};

var passVerifyCheck = function(){
	if(passSignupField.value != passVerifyField.value){
		alert("Passwords do not match!");
	}else if (passSignupField.value === passVerifyField.value){
		alert("Successful signup!");
		var addRows = db.execute('INSERT INTO users (email,user,pass,userid) VALUES ("'+emailField.value+'","'+userSignupField.value+'", "'+passSignupField.value+'", "'+userIDField.value+'")');
		addRows;
	};
};

var signupOpen = function(){
	navWindow.openWindow(newWindow);
};

var countOpen = function(){
	navWindow.openWindow(countWindow);
};

loginButton.addEventListener("click", userCheck);
createButton.addEventListener("click", signupOpen);
signupButton.addEventListener("click", emailCheck);

newView.add(emailLabel, emailField, userSignupLabel, userSignupField, passSignupLabel, passSignupField, verifyLabel, passVerifyField, userIDField, userIDLabel, signupButton);
mainView.add(headerLabel, userLabel, userField, passLabel, passField, loginButton, createButton);
mainWindow.add(border, mainView);<commit_msg>function move, label change<commit_after>

//Text Field and Label
	//Main site field

var headerLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Log in!",
	font: {fontSize: 25},
	color: "#E47100",
	top: 45,
	left: margin*2.5
});

var userLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Username Here",
	font: {fontSize: 15, fontWeight: "bold"},
	color: "#CC6500",
	top: 90,
	left: margin*3
});

var userField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 120,
	width: 250,
	height: 30,
	hintText: "Username",
	value: ""
});

var passLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Password (6 character minimum)",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 160,
	color: "#CC6500",
	left: margin*3
});

var passField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	bordercolor: "#000",
	color: '#336699',
	top: 190,
	width: 250,
	height: 30,
	passwordMask: true,
	hintText: "Password (Six character minimum)"
});

	//Main Site Field end

	//Sign Up Field

var emailField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 40,
	width: 250,
	height: 30,
	hintText: "E-mail Address",
	value: "",
	returnKeyType: Ti.UI.RETURNKEY_NEXT
});

var emailLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Email Address",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 10,
	color: "#CC6500",
	left: margin*3
});

var userSignupField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 110,
	width: 250,
	height: 30,
	hintText: "Username",
	value: "",
	returnKeyType: Ti.UI.RETURNKEY_NEXT
});

var userSignupLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Username",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 80,
	color: "#CC6500",
	left: margin*3
});

var passSignupField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 185,
	width: 250,
	height: 30,
	hintText: "Password",
	passwordMask: true,
	returnKeyType: Ti.UI.RETURNKEY_NEXT
});

var passSignupLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Enter Password (6 Characters!)",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 155,
	color: "#CC6500",
	left: margin*3
});

var passVerifyField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 260,
	width: 250,
	height: 30,
	hintText: "Verify Password",
	passwordMask: true,
	returnKeyType: Ti.UI.RETURNKEY_NEXT
});

var verifyLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "Verify Password",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 230,
	color: "#CC6500",
	left: margin*3
});

var userIDField = Ti.UI.createTextField({
	borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
	borderColor: "#000",
	color: '#336699',
	top: 335,
	width: 250,
	height: 30,
	hintText: "User ID",
	value: "",
	focusable: true
});

var userIDLabel = Ti.UI.createLabel({
	shadowColor: "#000",
	text: "User ID - Provided by Admin",
	font: {fontSize: 15, fontWeight: "bold"},
	top: 305,
	color: "#CC6500",
	left: margin*3
});

	//Signup Field end
//End Text Fields and Labels

var loginButton = Ti.UI.createLabel({
	borderRadius: 50,
	borderColor: "#000",
	text: "Sign In",
	backgroundColor: "#E47100",
	height: 50,
	width: "80%",
	top: 255,
	textAlign: "center"
});

var createButton = Ti.UI.createLabel({
	borderColor: "#000",
	borderRadius: 10,
	text: "Sign Up!",
	backgroundColor: "#CC6500",
	height: 50,
	width: "80%",
	top: 340,
	textAlign: "center"
});

var signupButton = Ti.UI.createLabel({
	borderColor: "#000",
	borderRadius: 10,
	text: "Confirm",
	backgroundColor: "#CC6500",
	height: 50,
	width: "80%",
	top: 410,
	textAlign: "center"
});

emailField.addEventListener('return', function() {
    userSignupField.focus();
});

userSignupField.addEventListener('return', function() {
    passSignupField.focus();
});

passSignupField.addEventListener('return', function() {
	passVerifyField.focus();
});

passVerifyField.addEventListener('return', function() {
    userIDField.focus();
});

//functions - main screen

var userCheck = function(){
	if(userField.value === ""){
		alert("No username entered!");
		return false;
	}else{
		passCheck();
		return true;
		passCheck();
	};
};

var passCheck = function (){
	if(passField.value.length < 6){
		alert("Password must be 6 characters long.");
	}else if (passField.value.length >= 6){
		countOpen();
		alert("Successful login!");

	};
};

//functions - main screen end
//functions - signup screen

var emailCheck = function(){
	var checkValue = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if (checkValue.test(emailField.value)){
		userSignupCheck();
	}else{
		alert("Email incorrect! Remember to use xxxx@xxx.com format");
	};
};

var userSignupCheck = function(){
	if(userSignupField.value === ""){
		alert("Username not entered!");
	}else{
		passSignupCheck();
		return true;
	};
};

var passSignupCheck = function(){
	if(passSignupField.value.length < 6){
		alert("Password must be 6 characters or over.");
	}else if (passSignupField.value.length >= 6){
		passVerifyCheck();
	};
};

var passVerifyCheck = function(){
	if(passSignupField.value != passVerifyField.value){
		alert("Passwords do not match!");
	}else if (passSignupField.value === passVerifyField.value){
		alert("Successful signup!");
		var db = Ti.Database.open('userDatabase');
		db.file.setRemoteBackup(false);
		db.execute('CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT, user TEXT, pass TEXT, userid INTEGER);');

		var addRows = db.execute('INSERT INTO users (email,user,pass,userid) VALUES ("?,?,?,?", emailField.value, userSignupField.value, passVerifyField.value,userIDField.value)');
		addRows;
	};
};

var signupOpen = function(){
	navWindow.openWindow(newWindow);
};

var countOpen = function(){
	navWindow.openWindow(countWindow);
};

loginButton.addEventListener("click", userCheck);
createButton.addEventListener("click", signupOpen);
signupButton.addEventListener("click", emailCheck);

newView.add(emailLabel, emailField, userSignupLabel, userSignupField, passSignupLabel, passSignupField, verifyLabel, passVerifyField, userIDField, userIDLabel, signupButton);
mainView.add(headerLabel, userLabel, userField, passLabel, passField, loginButton, createButton);
mainWindow.add(border, mainView);
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import { _t } from '../../../languageHandler';
const MatrixClientPeg = require("../../../MatrixClientPeg");
const sdk = require('../../../index');
const GeminiScrollbar = require('react-gemini-scrollbar');
const rate_limited_func = require('../../../ratelimitedfunc');
const CallHandler = require("../../../CallHandler");

const INITIAL_LOAD_NUM_MEMBERS = 30;
const INITIAL_LOAD_NUM_INVITED = 5;
const SHOW_MORE_INCREMENT = 100;

module.exports = React.createClass({
    displayName: 'MemberList',

    getInitialState: function() {
        this.memberDict = this.getMemberDict();
        const members = this.roomMembers();

        return {
            members: members,
            filteredJoinedMembers: this._filterMembers(members, 'join'),
            filteredInvitedMembers: this._filterMembers(members, 'invite'),

            // ideally we'd size this to the page height, but
            // in practice I find that a little constraining
            truncateAtJoined: INITIAL_LOAD_NUM_MEMBERS,
            truncateAtInvited: INITIAL_LOAD_NUM_INVITED,
            searchQuery: "",
        };
    },

    componentWillMount: function() {
        const cli = MatrixClientPeg.get();
        cli.on("RoomState.members", this.onRoomStateMember);
        cli.on("RoomMember.name", this.onRoomMemberName);
        cli.on("RoomState.events", this.onRoomStateEvent);
        cli.on("Room", this.onRoom); // invites
        // We listen for changes to the lastPresenceTs which is essentially
        // listening for all presence events (we display most of not all of
        // the information contained in presence events).
        cli.on("User.lastPresenceTs", this.onUserLastPresenceTs);
        // cli.on("Room.timeline", this.onRoomTimeline);
    },

    componentWillUnmount: function() {
        const cli = MatrixClientPeg.get();
        if (cli) {
            cli.removeListener("RoomState.members", this.onRoomStateMember);
            cli.removeListener("RoomMember.name", this.onRoomMemberName);
            cli.removeListener("RoomState.events", this.onRoomStateEvent);
            cli.removeListener("Room", this.onRoom);
            cli.removeListener("User.lastPresenceTs", this.onUserLastPresenceTs);
            // cli.removeListener("Room.timeline", this.onRoomTimeline);
        }

        // cancel any pending calls to the rate_limited_funcs
        this._updateList.cancelPendingCall();
    },

/*
    onRoomTimeline: function(ev, room, toStartOfTimeline, removed, data) {
        // ignore anything but real-time updates at the end of the room:
        // updates from pagination will happen when the paginate completes.
        if (toStartOfTimeline || !data || !data.liveEvent) return;

        // treat any activity from a user as implicit presence to update the
        // ordering of the list whenever someone says something.
        // Except right now we're not tiebreaking "active now" users in this way
        // so don't bother for now.
        if (ev.getSender()) {
            // console.log("implicit presence from " + ev.getSender());

            var tile = this.refs[ev.getSender()];
            if (tile) {
                // work around a race where you might have a room member object
                // before the user object exists.  XXX: why does this ever happen?
                var all_members = room.currentState.members;
                var userId = ev.getSender();
                if (all_members[userId].user === null) {
                    all_members[userId].user = MatrixClientPeg.get().getUser(userId);
                }
                this._updateList(); // reorder the membership list
            }
        }
    },
*/

    onUserLastPresenceTs(event, user) {
        // Attach a SINGLE listener for global presence changes then locate the
        // member tile and re-render it. This is more efficient than every tile
        // evar attaching their own listener.
        // console.log("explicit presence from " + user.userId);
        const tile = this.refs[user.userId];
        if (tile) {
            this._updateList(); // reorder the membership list
        }
    },

    onRoom: function(room) {
        if (room.roomId !== this.props.roomId) {
            return;
        }
        // We listen for room events because when we accept an invite
        // we need to wait till the room is fully populated with state
        // before refreshing the member list else we get a stale list.
        this._updateList();
    },

    onRoomStateMember: function(ev, state, member) {
        this._updateList();
    },

    onRoomMemberName: function(ev, member) {
        this._updateList();
    },

    onRoomStateEvent: function(event, state) {
        if (event.getType() === "m.room.third_party_invite") {
            this._updateList();
        }
    },

    _updateList: new rate_limited_func(function() {
        // console.log("Updating memberlist");
        this.memberDict = this.getMemberDict();

        const newState = {
            members: this.roomMembers(),
        };
        newState.filteredJoinedMembers = this._filterMembers(newState.members, 'join');
        newState.filteredInvitedMembers = this._filterMembers(newState.members, 'invite');
        this.setState(newState);
    }, 500),

    getMemberDict: function() {
        if (!this.props.roomId) return {};
        const cli = MatrixClientPeg.get();
        const room = cli.getRoom(this.props.roomId);
        if (!room) return {};

        const all_members = room.currentState.members;

        Object.keys(all_members).map(function(userId) {
            // work around a race where you might have a room member object
            // before the user object exists.  This may or may not cause
            // https://github.com/vector-im/vector-web/issues/186
            if (all_members[userId].user === null) {
                all_members[userId].user = MatrixClientPeg.get().getUser(userId);
            }

            // XXX: this user may have no lastPresenceTs value!
            // the right solution here is to fix the race rather than leave it as 0
        });

        return all_members;
    },

    roomMembers: function() {
        const all_members = this.memberDict || {};
        const all_user_ids = Object.keys(all_members);
        const ConferenceHandler = CallHandler.getConferenceHandler();

        all_user_ids.sort(this.memberSort);

        const to_display = [];
        let count = 0;
        for (let i = 0; i < all_user_ids.length; ++i) {
            const user_id = all_user_ids[i];
            const m = all_members[user_id];

            if (m.membership == 'join' || m.membership == 'invite') {
                if ((ConferenceHandler && !ConferenceHandler.isConferenceUser(user_id)) || !ConferenceHandler) {
                    to_display.push(user_id);
                    ++count;
                }
            }
        }
        return to_display;
    },

    _createOverflowTileJoined: function(overflowCount, totalCount) {
        return this._createOverflowTile(overflowCount, totalCount, this._showMoreJoinedMemberList);
    },

    _createOverflowTileInvited: function(overflowCount, totalCount) {
        return this._createOverflowTile(overflowCount, totalCount, this._showMoreInvitedMemberList);
    },

    _createOverflowTile: function(overflowCount, totalCount, onClick) {
        // For now we'll pretend this is any entity. It should probably be a separate tile.
        const EntityTile = sdk.getComponent("rooms.EntityTile");
        const BaseAvatar = sdk.getComponent("avatars.BaseAvatar");
        const text = _t("and %(count)s others...", { count: overflowCount });
        return (
            <EntityTile className="mx_EntityTile_ellipsis" avatarJsx={
                <BaseAvatar url="img/ellipsis.svg" name="..." width={36} height={36} />
            } name={text} presenceState="online" suppressOnHover={true}
            onClick={onClick} />
        );
    },

    _showMoreJoinedMemberList: function() {
        this.setState({
            truncateAtJoined: this.state.truncateAtJoined + SHOW_MORE_INCREMENT,
        });
    },

    _showMoreInvitedMemberList: function() {
        this.setState({
            truncateAtInvited: this.state.truncateAtInvited + SHOW_MORE_INCREMENT,
        });
    },

    memberString: function(member) {
        if (!member) {
            return "(null)";
        } else {
            return "(" + member.name + ", " + member.powerLevel + ", " + member.user.lastActiveAgo + ", " + member.user.currentlyActive + ")";
        }
    },

    // returns negative if a comes before b,
    // returns 0 if a and b are equivalent in ordering
    // returns positive if a comes after b.
    memberSort: function(userIdA, userIdB) {
            // order by last active, with "active now" first.
            // ...and then by power
            // ...and then alphabetically.
            // We could tiebreak instead by "last recently spoken in this room" if we wanted to.

            const memberA = this.memberDict[userIdA];
            const memberB = this.memberDict[userIdB];
            const userA = memberA.user;
            const userB = memberB.user;

            // if (!userA || !userB) {
            //     console.log("comparing " + memberA.name + " user=" + memberA.user + " with " + memberB.name + " user=" + memberB.user);
            // }

            if (!userA && !userB) return 0;
            if (userA && !userB) return -1;
            if (!userA && userB) return 1;

            // console.log("comparing " + this.memberString(memberA) + " and " + this.memberString(memberB));

            if (userA.currentlyActive && userB.currentlyActive) {
                // console.log(memberA.name + " and " + memberB.name + " are both active");
                if (memberA.powerLevel === memberB.powerLevel) {
                    // console.log(memberA + " and " + memberB + " have same power level");
                    if (memberA.name && memberB.name) {
                        // console.log("comparing names: " + memberA.name + " and " + memberB.name);
                        const nameA = memberA.name[0] === '@' ? memberA.name.substr(1) : memberA.name;
                        const nameB = memberB.name[0] === '@' ? memberB.name.substr(1) : memberB.name;
                        return nameA.localeCompare(nameB);
                    } else {
                        return 0;
                    }
                } else {
                    // console.log("comparing power: " + memberA.powerLevel + " and " + memberB.powerLevel);
                    return memberB.powerLevel - memberA.powerLevel;
                }
            }

            if (userA.currentlyActive && !userB.currentlyActive) return -1;
            if (!userA.currentlyActive && userB.currentlyActive) return 1;

            // For now, let's just order things by timestamp. It's really annoying
            // that a user disappears from sight just because they temporarily go offline
            return userB.getLastActiveTs() - userA.getLastActiveTs();
    },

    onSearchQueryChanged: function(ev) {
        const q = ev.target.value;
        this.setState({
            searchQuery: q,
            filteredJoinedMembers: this._filterMembers(this.state.members, 'join', q),
            filteredInvitedMembers: this._filterMembers(this.state.members, 'invite', q),
        });
    },

    _filterMembers: function(members, membership, query) {
        return members.filter((userId) => {
            const m = this.memberDict[userId];

            if (query) {
                const matchesName = m.name.toLowerCase().indexOf(query) !== -1;
                const matchesId = m.userId.toLowerCase().indexOf(query) !== -1;

                if (!matchesName && !matchesId) {
                    return false;
                }
            }

            return m.membership == membership;
        });
    },

    _makeMemberTiles: function(members, membership) {
        const MemberTile = sdk.getComponent("rooms.MemberTile");

        const memberList = members.map((userId) => {
            const m = this.memberDict[userId];
            return (
                <MemberTile key={userId} member={m} ref={userId} />
            );
        });

        // XXX: surely this is not the right home for this logic.
        // Double XXX: Now it's really, really not the right home for this logic:
        // we shouldn't even be passing in the 'membership' param to this function.
        // Ew, ew, and ew.
        if (membership === "invite") {
            // include 3pid invites (m.room.third_party_invite) state events.
            // The HS may have already converted these into m.room.member invites so
            // we shouldn't add them if the 3pid invite state key (token) is in the
            // member invite (content.third_party_invite.signed.token)
            const room = MatrixClientPeg.get().getRoom(this.props.roomId);
            const EntityTile = sdk.getComponent("rooms.EntityTile");
            if (room) {
                room.currentState.getStateEvents("m.room.third_party_invite").forEach(
                function(e) {
                    // any events without these keys are not valid 3pid invites, so we ignore them
                    const required_keys = ['key_validity_url', 'public_key', 'display_name'];
                    for (let i = 0; i < required_keys.length; ++i) {
                        if (e.getContent()[required_keys[i]] === undefined) return;
                    }

                    // discard all invites which have a m.room.member event since we've
                    // already added them.
                    const memberEvent = room.currentState.getInviteForThreePidToken(e.getStateKey());
                    if (memberEvent) {
                        return;
                    }
                    memberList.push(
                        <EntityTile key={e.getStateKey()} name={e.getContent().display_name} suppressOnHover={true} />,
                    );
                });
            }
        }

        return memberList;
    },

    _getChildrenJoined: function(start, end) {
        return this._makeMemberTiles(this.state.filteredJoinedMembers.slice(start, end));
    },

    _getChildCountJoined: function() {
        return this.state.filteredJoinedMembers.length;
    },

    _getChildrenInvited: function(start, end) {
        return this._makeMemberTiles(this.state.filteredInvitedMembers.slice(start, end), 'invite');
    },

    _getChildCountInvited: function() {
        return this.state.filteredInvitedMembers.length;
    },

    render: function() {
        const TruncatedList = sdk.getComponent("elements.TruncatedList");

        let invitedSection = null;
        if (this._getChildCountInvited() > 0) {
            invitedSection = (

{ _t("Invited") }

                        <TruncatedList className="mx_MemberList_wrapper" truncateAt={this.state.truncateAtInvited}
                                createOverflowElement={this._createOverflowTileInvited}
                                getChildren={this._getChildrenInvited}
                                getChildCount={this._getChildCountInvited}
                        />

            );
        }

        const inputBox = (
            <form autoComplete="off">
                <input className="mx_MemberList_query" id="mx_MemberList_query" type="text"
                        onChange={this.onSearchQueryChanged} value={this.state.searchQuery}
                        placeholder={_t('Filter room members')} />
            </form>
        );

        return (

                { inputBox }
                <GeminiScrollbar autoshow={true} className="mx_MemberList_joined mx_MemberList_outerWrapper">
                    <TruncatedList className="mx_MemberList_wrapper" truncateAt={this.state.truncateAtJoined}
                            createOverflowElement={this._createOverflowTileJoined}
                            getChildren={this._getChildrenJoined}
                            getChildCount={this._getChildCountJoined}
                    />
                    { invitedSection }
                </GeminiScrollbar>

        );
    },
});
<commit_msg>pass search query to filter fn in _updateList<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import { _t } from '../../../languageHandler';
const MatrixClientPeg = require("../../../MatrixClientPeg");
const sdk = require('../../../index');
const GeminiScrollbar = require('react-gemini-scrollbar');
const rate_limited_func = require('../../../ratelimitedfunc');
const CallHandler = require("../../../CallHandler");

const INITIAL_LOAD_NUM_MEMBERS = 30;
const INITIAL_LOAD_NUM_INVITED = 5;
const SHOW_MORE_INCREMENT = 100;

module.exports = React.createClass({
    displayName: 'MemberList',

    getInitialState: function() {
        this.memberDict = this.getMemberDict();
        const members = this.roomMembers();

        return {
            members: members,
            filteredJoinedMembers: this._filterMembers(members, 'join'),
            filteredInvitedMembers: this._filterMembers(members, 'invite'),

            // ideally we'd size this to the page height, but
            // in practice I find that a little constraining
            truncateAtJoined: INITIAL_LOAD_NUM_MEMBERS,
            truncateAtInvited: INITIAL_LOAD_NUM_INVITED,
            searchQuery: "",
        };
    },

    componentWillMount: function() {
        const cli = MatrixClientPeg.get();
        cli.on("RoomState.members", this.onRoomStateMember);
        cli.on("RoomMember.name", this.onRoomMemberName);
        cli.on("RoomState.events", this.onRoomStateEvent);
        cli.on("Room", this.onRoom); // invites
        // We listen for changes to the lastPresenceTs which is essentially
        // listening for all presence events (we display most of not all of
        // the information contained in presence events).
        cli.on("User.lastPresenceTs", this.onUserLastPresenceTs);
        // cli.on("Room.timeline", this.onRoomTimeline);
    },

    componentWillUnmount: function() {
        const cli = MatrixClientPeg.get();
        if (cli) {
            cli.removeListener("RoomState.members", this.onRoomStateMember);
            cli.removeListener("RoomMember.name", this.onRoomMemberName);
            cli.removeListener("RoomState.events", this.onRoomStateEvent);
            cli.removeListener("Room", this.onRoom);
            cli.removeListener("User.lastPresenceTs", this.onUserLastPresenceTs);
            // cli.removeListener("Room.timeline", this.onRoomTimeline);
        }

        // cancel any pending calls to the rate_limited_funcs
        this._updateList.cancelPendingCall();
    },

/*
    onRoomTimeline: function(ev, room, toStartOfTimeline, removed, data) {
        // ignore anything but real-time updates at the end of the room:
        // updates from pagination will happen when the paginate completes.
        if (toStartOfTimeline || !data || !data.liveEvent) return;

        // treat any activity from a user as implicit presence to update the
        // ordering of the list whenever someone says something.
        // Except right now we're not tiebreaking "active now" users in this way
        // so don't bother for now.
        if (ev.getSender()) {
            // console.log("implicit presence from " + ev.getSender());

            var tile = this.refs[ev.getSender()];
            if (tile) {
                // work around a race where you might have a room member object
                // before the user object exists.  XXX: why does this ever happen?
                var all_members = room.currentState.members;
                var userId = ev.getSender();
                if (all_members[userId].user === null) {
                    all_members[userId].user = MatrixClientPeg.get().getUser(userId);
                }
                this._updateList(); // reorder the membership list
            }
        }
    },
*/

    onUserLastPresenceTs(event, user) {
        // Attach a SINGLE listener for global presence changes then locate the
        // member tile and re-render it. This is more efficient than every tile
        // evar attaching their own listener.
        // console.log("explicit presence from " + user.userId);
        const tile = this.refs[user.userId];
        if (tile) {
            this._updateList(); // reorder the membership list
        }
    },

    onRoom: function(room) {
        if (room.roomId !== this.props.roomId) {
            return;
        }
        // We listen for room events because when we accept an invite
        // we need to wait till the room is fully populated with state
        // before refreshing the member list else we get a stale list.
        this._updateList();
    },

    onRoomStateMember: function(ev, state, member) {
        this._updateList();
    },

    onRoomMemberName: function(ev, member) {
        this._updateList();
    },

    onRoomStateEvent: function(event, state) {
        if (event.getType() === "m.room.third_party_invite") {
            this._updateList();
        }
    },

    _updateList: new rate_limited_func(function() {
        // console.log("Updating memberlist");
        this.memberDict = this.getMemberDict();

        const newState = {
            members: this.roomMembers(),
        };
        newState.filteredJoinedMembers = this._filterMembers(newState.members, 'join', this.state.searchQuery);
        newState.filteredInvitedMembers = this._filterMembers(newState.members, 'invite', this.state.searchQuery);
        this.setState(newState);
    }, 500),

    getMemberDict: function() {
        if (!this.props.roomId) return {};
        const cli = MatrixClientPeg.get();
        const room = cli.getRoom(this.props.roomId);
        if (!room) return {};

        const all_members = room.currentState.members;

        Object.keys(all_members).map(function(userId) {
            // work around a race where you might have a room member object
            // before the user object exists.  This may or may not cause
            // https://github.com/vector-im/vector-web/issues/186
            if (all_members[userId].user === null) {
                all_members[userId].user = MatrixClientPeg.get().getUser(userId);
            }

            // XXX: this user may have no lastPresenceTs value!
            // the right solution here is to fix the race rather than leave it as 0
        });

        return all_members;
    },

    roomMembers: function() {
        const all_members = this.memberDict || {};
        const all_user_ids = Object.keys(all_members);
        const ConferenceHandler = CallHandler.getConferenceHandler();

        all_user_ids.sort(this.memberSort);

        const to_display = [];
        let count = 0;
        for (let i = 0; i < all_user_ids.length; ++i) {
            const user_id = all_user_ids[i];
            const m = all_members[user_id];

            if (m.membership == 'join' || m.membership == 'invite') {
                if ((ConferenceHandler && !ConferenceHandler.isConferenceUser(user_id)) || !ConferenceHandler) {
                    to_display.push(user_id);
                    ++count;
                }
            }
        }
        return to_display;
    },

    _createOverflowTileJoined: function(overflowCount, totalCount) {
        return this._createOverflowTile(overflowCount, totalCount, this._showMoreJoinedMemberList);
    },

    _createOverflowTileInvited: function(overflowCount, totalCount) {
        return this._createOverflowTile(overflowCount, totalCount, this._showMoreInvitedMemberList);
    },

    _createOverflowTile: function(overflowCount, totalCount, onClick) {
        // For now we'll pretend this is any entity. It should probably be a separate tile.
        const EntityTile = sdk.getComponent("rooms.EntityTile");
        const BaseAvatar = sdk.getComponent("avatars.BaseAvatar");
        const text = _t("and %(count)s others...", { count: overflowCount });
        return (
            <EntityTile className="mx_EntityTile_ellipsis" avatarJsx={
                <BaseAvatar url="img/ellipsis.svg" name="..." width={36} height={36} />
            } name={text} presenceState="online" suppressOnHover={true}
            onClick={onClick} />
        );
    },

    _showMoreJoinedMemberList: function() {
        this.setState({
            truncateAtJoined: this.state.truncateAtJoined + SHOW_MORE_INCREMENT,
        });
    },

    _showMoreInvitedMemberList: function() {
        this.setState({
            truncateAtInvited: this.state.truncateAtInvited + SHOW_MORE_INCREMENT,
        });
    },

    memberString: function(member) {
        if (!member) {
            return "(null)";
        } else {
            return "(" + member.name + ", " + member.powerLevel + ", " + member.user.lastActiveAgo + ", " + member.user.currentlyActive + ")";
        }
    },

    // returns negative if a comes before b,
    // returns 0 if a and b are equivalent in ordering
    // returns positive if a comes after b.
    memberSort: function(userIdA, userIdB) {
            // order by last active, with "active now" first.
            // ...and then by power
            // ...and then alphabetically.
            // We could tiebreak instead by "last recently spoken in this room" if we wanted to.

            const memberA = this.memberDict[userIdA];
            const memberB = this.memberDict[userIdB];
            const userA = memberA.user;
            const userB = memberB.user;

            // if (!userA || !userB) {
            //     console.log("comparing " + memberA.name + " user=" + memberA.user + " with " + memberB.name + " user=" + memberB.user);
            // }

            if (!userA && !userB) return 0;
            if (userA && !userB) return -1;
            if (!userA && userB) return 1;

            // console.log("comparing " + this.memberString(memberA) + " and " + this.memberString(memberB));

            if (userA.currentlyActive && userB.currentlyActive) {
                // console.log(memberA.name + " and " + memberB.name + " are both active");
                if (memberA.powerLevel === memberB.powerLevel) {
                    // console.log(memberA + " and " + memberB + " have same power level");
                    if (memberA.name && memberB.name) {
                        // console.log("comparing names: " + memberA.name + " and " + memberB.name);
                        const nameA = memberA.name[0] === '@' ? memberA.name.substr(1) : memberA.name;
                        const nameB = memberB.name[0] === '@' ? memberB.name.substr(1) : memberB.name;
                        return nameA.localeCompare(nameB);
                    } else {
                        return 0;
                    }
                } else {
                    // console.log("comparing power: " + memberA.powerLevel + " and " + memberB.powerLevel);
                    return memberB.powerLevel - memberA.powerLevel;
                }
            }

            if (userA.currentlyActive && !userB.currentlyActive) return -1;
            if (!userA.currentlyActive && userB.currentlyActive) return 1;

            // For now, let's just order things by timestamp. It's really annoying
            // that a user disappears from sight just because they temporarily go offline
            return userB.getLastActiveTs() - userA.getLastActiveTs();
    },

    onSearchQueryChanged: function(ev) {
        const q = ev.target.value;
        this.setState({
            searchQuery: q,
            filteredJoinedMembers: this._filterMembers(this.state.members, 'join', q),
            filteredInvitedMembers: this._filterMembers(this.state.members, 'invite', q),
        });
    },

    _filterMembers: function(members, membership, query) {
        return members.filter((userId) => {
            const m = this.memberDict[userId];

            if (query) {
                const matchesName = m.name.toLowerCase().indexOf(query) !== -1;
                const matchesId = m.userId.toLowerCase().indexOf(query) !== -1;

                if (!matchesName && !matchesId) {
                    return false;
                }
            }

            return m.membership == membership;
        });
    },

    _makeMemberTiles: function(members, membership) {
        const MemberTile = sdk.getComponent("rooms.MemberTile");

        const memberList = members.map((userId) => {
            const m = this.memberDict[userId];
            return (
                <MemberTile key={userId} member={m} ref={userId} />
            );
        });

        // XXX: surely this is not the right home for this logic.
        // Double XXX: Now it's really, really not the right home for this logic:
        // we shouldn't even be passing in the 'membership' param to this function.
        // Ew, ew, and ew.
        if (membership === "invite") {
            // include 3pid invites (m.room.third_party_invite) state events.
            // The HS may have already converted these into m.room.member invites so
            // we shouldn't add them if the 3pid invite state key (token) is in the
            // member invite (content.third_party_invite.signed.token)
            const room = MatrixClientPeg.get().getRoom(this.props.roomId);
            const EntityTile = sdk.getComponent("rooms.EntityTile");
            if (room) {
                room.currentState.getStateEvents("m.room.third_party_invite").forEach(
                function(e) {
                    // any events without these keys are not valid 3pid invites, so we ignore them
                    const required_keys = ['key_validity_url', 'public_key', 'display_name'];
                    for (let i = 0; i < required_keys.length; ++i) {
                        if (e.getContent()[required_keys[i]] === undefined) return;
                    }

                    // discard all invites which have a m.room.member event since we've
                    // already added them.
                    const memberEvent = room.currentState.getInviteForThreePidToken(e.getStateKey());
                    if (memberEvent) {
                        return;
                    }
                    memberList.push(
                        <EntityTile key={e.getStateKey()} name={e.getContent().display_name} suppressOnHover={true} />,
                    );
                });
            }
        }

        return memberList;
    },

    _getChildrenJoined: function(start, end) {
        return this._makeMemberTiles(this.state.filteredJoinedMembers.slice(start, end));
    },

    _getChildCountJoined: function() {
        return this.state.filteredJoinedMembers.length;
    },

    _getChildrenInvited: function(start, end) {
        return this._makeMemberTiles(this.state.filteredInvitedMembers.slice(start, end), 'invite');
    },

    _getChildCountInvited: function() {
        return this.state.filteredInvitedMembers.length;
    },

    render: function() {
        const TruncatedList = sdk.getComponent("elements.TruncatedList");

        let invitedSection = null;
        if (this._getChildCountInvited() > 0) {
            invitedSection = (

{ _t("Invited") }

                        <TruncatedList className="mx_MemberList_wrapper" truncateAt={this.state.truncateAtInvited}
                                createOverflowElement={this._createOverflowTileInvited}
                                getChildren={this._getChildrenInvited}
                                getChildCount={this._getChildCountInvited}
                        />

            );
        }

        const inputBox = (
            <form autoComplete="off">
                <input className="mx_MemberList_query" id="mx_MemberList_query" type="text"
                        onChange={this.onSearchQueryChanged} value={this.state.searchQuery}
                        placeholder={_t('Filter room members')} />
            </form>
        );

        return (

                { inputBox }
                <GeminiScrollbar autoshow={true} className="mx_MemberList_joined mx_MemberList_outerWrapper">
                    <TruncatedList className="mx_MemberList_wrapper" truncateAt={this.state.truncateAtJoined}
                            createOverflowElement={this._createOverflowTileJoined}
                            getChildren={this._getChildrenJoined}
                            getChildCount={this._getChildCountJoined}
                    />
                    { invitedSection }
                </GeminiScrollbar>

        );
    },
});
<|endoftext|>


<commit_before>import Vue from "vue";
import VueRouter from "vue-router";
import App from "./components/app";
import Cards from "./components/cards";
import Card from "./components/card";
import {CardsResource} from "./services/resources";

// register plugins
Vue.use(VueRouter);

// create & configure router
var router = new VueRouter();

router.map({
    '/cards': {
        name: 'cards',
        component: Cards,
        subRoutes: {
            '/': {
                component: {
                    init: function() {
                        // redirect to first card
                        CardsResource.query().then(response => {
                            this.$route.router.go({ name: 'card', params: { id: response.data[0].id } });
                        });
                    }
                }
            },
            '/:id': {
                name: 'card',
                component: Card
            }
        }
    }
});

// start app
router.start(App, '#app');

<commit_msg>added default redirect to `/cards`<commit_after>import Vue from "vue";
import VueRouter from "vue-router";
import App from "./components/app";
import Cards from "./components/cards";
import Card from "./components/card";
import {CardsResource} from "./services/resources";

// register plugins
Vue.use(VueRouter);

// create & configure router
var router = new VueRouter();

router.map({
    '/cards': {
        name: 'cards',
        component: Cards,
        subRoutes: {
            '/': {
                component: {
                    init: function() {
                        // redirect to first card
                        CardsResource.query().then(response => {
                            this.$route.router.go({ name: 'card', params: { id: response.data[0].id } });
                        });
                    }
                }
            },
            '/:id': {
                name: 'card',
                component: Card
            }
        }
    }
});

// default redirect to `/cards`
router.redirect({
    '/': '/cards'
});

// start app
router.start(App, '#app');

<|endoftext|>


<commit_before>import { OHIF } from 'meteor/ohif:core';
import { _ } from 'meteor/underscore';

OHIF.cornerstone = {};

OHIF.cornerstone.pixelToPage = (element, position) => {
    const enabledElement = cornerstone.getEnabledElement(element);
    const result = {
        x: 0,
        y: 0
    };

    // Stop here if the cornerstone element is not enabled or position is not an object
    if (!enabledElement || typeof position !== 'object') {
        return result;
    }

    const canvas = enabledElement.canvas;

    const canvasOffset = $(canvas).offset();
    result.x += canvasOffset.left;
    result.y += canvasOffset.top;

    const canvasPosition = cornerstone.pixelToCanvas(element, position);
    result.x += canvasPosition.x;
    result.y += canvasPosition.y;

    return result;
};

OHIF.cornerstone.repositionTextBoxWhileDragging = (eventData, measurementData) => {
    const element = eventData.element;
    const enabledElement = cornerstone.getEnabledElement(element);
    const $element = $(element);
    const image = enabledElement.image;

    const getAvailableBlankAreas = (enabledElement, labelWidth, labelHeight) => {
        const { element, canvas, image } = enabledElement;

        const topLeft = cornerstone.pixelToCanvas(element, {
            x: 0,
            y: 0
        });

        const bottomRight = cornerstone.pixelToCanvas(element, {
            x: image.width,
            y: image.height
        });

        const $canvas = $(canvas);
        const canvasWidth = $canvas.outerWidth();
        const canvasHeight = $canvas.outerHeight();

        const result = {};
        result['x-1'] = topLeft.x > labelWidth;
        result['y-1'] = topLeft.y > labelHeight;
        result.x1 = canvasWidth - bottomRight.x > labelWidth;
        result.y1 = canvasHeight - bottomRight.y > labelHeight;

        return result;
    };

    const modifiedCallback = () => {
        const handles = measurementData.handles;
        const textBox = handles.textBox;

        const bounds = {};
        bounds.x = textBox.boundingBox.width;
        bounds.y = textBox.boundingBox.height;

        const getHandlePosition = key => _.pick(handles[key], ['x', 'y']);
        const start = getHandlePosition('start');
        const end = getHandlePosition('end');

        const calculateAxisCenter = axis => {
            const a = start[axis];
            const b = end[axis];
            const lowest = Math.min(a, b);
            const highest = Math.max(a, b);
            return lowest + ((highest - lowest) / 2);
        };

        const tool = {};
        tool.x = calculateAxisCenter('x');
        tool.y = calculateAxisCenter('y');

        const mid = {};
        mid.x = image.width / 2;
        mid.y = image.height / 2;

        const directions = {};
        directions.x = tool.x < mid.x ? -1 : 1;
        directions.y = tool.y < mid.y ? -1 : 1;

        const points = {};
        points.x = directions.x < 0 ? 0 : image.width;
        points.y = directions.y < 0 ? 0 : image.height;

        const diffX = directions.x < 0 ? tool.x : image.width - tool.x;
        const diffY = directions.y < 0 ? tool.y : image.height - tool.y;

        let cornerAxis = diffY < diffX ? 'y' : 'x';
        let toolAxis = diffY < diffX ? 'x' : 'y';

        textBox[cornerAxis] = points[cornerAxis];
        textBox[toolAxis] = tool[toolAxis];

        if (directions[cornerAxis] < 0) {
            const topLeft = cornerstone.pageToPixel(element, 0, 0);
            const bottomRight = cornerstone.pageToPixel(element, bounds.x, bounds.y);
            const boxSize = bottomRight[cornerAxis] - topLeft[cornerAxis];
            textBox[cornerAxis] -= boxSize;
        }
    };

    const mouseUpCallback = () => {
        $element.off('CornerstoneToolsMeasurementModified', modifiedCallback);
    };

    $element.one('CornerstoneToolsMouseDrag', () => {
        $element.on('CornerstoneToolsMeasurementModified', modifiedCallback);
    });

    // Using mouseup because sometimes the CornerstoneToolsMouseUp event is not triggered
    $element.one('mouseup', mouseUpCallback);
};
<commit_msg>LT-40: Placing the text call-outs inside nearest available blank space in viewport<commit_after>import { OHIF } from 'meteor/ohif:core';
import { _ } from 'meteor/underscore';

OHIF.cornerstone = {};

OHIF.cornerstone.pixelToPage = (element, position) => {
    const enabledElement = cornerstone.getEnabledElement(element);
    const result = {
        x: 0,
        y: 0
    };

    // Stop here if the cornerstone element is not enabled or position is not an object
    if (!enabledElement || typeof position !== 'object') {
        return result;
    }

    const canvas = enabledElement.canvas;

    const canvasOffset = $(canvas).offset();
    result.x += canvasOffset.left;
    result.y += canvasOffset.top;

    const canvasPosition = cornerstone.pixelToCanvas(element, position);
    result.x += canvasPosition.x;
    result.y += canvasPosition.y;

    return result;
};

OHIF.cornerstone.repositionTextBoxWhileDragging = (eventData, measurementData) => {
    const element = eventData.element;
    const enabledElement = cornerstone.getEnabledElement(element);
    const $element = $(element);
    const image = enabledElement.image;

    const getAvailableBlankAreas = (enabledElement, labelWidth, labelHeight) => {
        const { element, canvas, image } = enabledElement;

        const topLeft = cornerstone.pixelToCanvas(element, {
            x: 0,
            y: 0
        });

        const bottomRight = cornerstone.pixelToCanvas(element, {
            x: image.width,
            y: image.height
        });

        const $canvas = $(canvas);
        const canvasWidth = $canvas.outerWidth();
        const canvasHeight = $canvas.outerHeight();

        const result = {};
        result['x-1'] = topLeft.x > labelWidth;
        result['y-1'] = topLeft.y > labelHeight;
        result.x1 = canvasWidth - bottomRight.x > labelWidth;
        result.y1 = canvasHeight - bottomRight.y > labelHeight;

        return result;
    };

    const modifiedCallback = () => {
        const handles = measurementData.handles;
        const textBox = handles.textBox;

        const bounds = {};
        bounds.x = textBox.boundingBox.width;
        bounds.y = textBox.boundingBox.height;

        const getHandlePosition = key => _.pick(handles[key], ['x', 'y']);
        const start = getHandlePosition('start');
        const end = getHandlePosition('end');

        const calculateAxisCenter = axis => {
            const a = start[axis];
            const b = end[axis];
            const lowest = Math.min(a, b);
            const highest = Math.max(a, b);
            return lowest + ((highest - lowest) / 2);
        };

        const tool = {};
        tool.x = calculateAxisCenter('x');
        tool.y = calculateAxisCenter('y');

        const mid = {};
        mid.x = image.width / 2;
        mid.y = image.height / 2;

        const directions = {};
        directions.x = tool.x < mid.x ? -1 : 1;
        directions.y = tool.y < mid.y ? -1 : 1;

        const points = {};
        points.x = directions.x < 0 ? 0 : image.width;
        points.y = directions.y < 0 ? 0 : image.height;

        const diffX = directions.x < 0 ? tool.x : image.width - tool.x;
        const diffY = directions.y < 0 ? tool.y : image.height - tool.y;

        let cornerAxis = diffY < diffX ? 'y' : 'x';

        const availableAreas = getAvailableBlankAreas(enabledElement, bounds.x, bounds.y);
        const tempDirections = _.clone(directions);
        let tempCornerAxis = cornerAxis;
        let foundPlace = false;
        let current = 0;
        while (current < 4) {
            if (availableAreas[tempCornerAxis + tempDirections[tempCornerAxis]]) {
                foundPlace = true;
                break;
            }

            // Invert the direction for the next iteration
            tempDirections[tempCornerAxis] *= -1;

            // Invert the tempCornerAxis
            tempCornerAxis = tempCornerAxis === 'x' ? 'y' : 'x';

            current++;
        }

        if (foundPlace) {
            _.extend(directions, tempDirections);
            cornerAxis = tempCornerAxis;
        }

        const toolAxis = cornerAxis === 'x' ? 'y' : 'x';

        textBox[cornerAxis] = points[cornerAxis];
        textBox[toolAxis] = tool[toolAxis];

        if (directions[cornerAxis] < 0) {
            const topLeft = cornerstone.pageToPixel(element, 0, 0);
            const bottomRight = cornerstone.pageToPixel(element, bounds.x, bounds.y);
            const boxSize = bottomRight[cornerAxis] - topLeft[cornerAxis];
            textBox[cornerAxis] -= boxSize;
        }
    };

    const mouseUpCallback = () => {
        $element.off('CornerstoneToolsMeasurementModified', modifiedCallback);
    };

    $element.one('CornerstoneToolsMouseDrag', () => {
        $element.on('CornerstoneToolsMeasurementModified', modifiedCallback);
    });

    // Using mouseup because sometimes the CornerstoneToolsMouseUp event is not triggered
    $element.one('mouseup', mouseUpCallback);
};
<|endoftext|>


<commit_before>import Morph from 'src/components/widgets/lively-morph.js';
import ohm from "https://unpkg.com/ohm-js@15.2.1/dist/ohm.js";

var g = ohm.grammar(
  `Academic {
    Exp =
      AcademicQuery

    AcademicQuery = Attribute Comparator Value -- simple
      | ("And" | "Or") "(" AcademicQuery "," AcademicQuery ")" -- complex
      | "Composite(" CompositeQuery ")" -- composite
    CompositeQuery = Attribute "." Attribute Comparator Value -- simple
      | ("And" | "Or") "(" CompositeQuery "," CompositeQuery ")" -- complex

    Comparator =
      PartialComparator "="?
    PartialComparator =
      "=" | "<" | ">"

    Attribute (an attribute) =
      letter letter? letter?

    Value (a value) =
      "\'" alnum* "\'" -- string
      | Number
      | Date
      | ( "[" | "(" ) Number "," Number ( "]" | ")" ) -- numberRange
      | ( "[" | "(" ) Date "," Date ( "]" | ")" ) -- dateRange

    Number =
      digit+
      Date =
      "\'" Number "-" Number "-" Number "\'"
  }`
);

var s = g.createSemantics();

s.addOperation(
  'interpret', {
    Exp: function(e) {
      return e.interpret();
    },

    AcademicQuery_simple: function(attribute, comparator, value) {
      return {
        "attribute" : attribute.interpret(),
        "comparator" : comparator.interpret(),
        "value" : value.interpret(),
        "type" : "simple"
      }
    },
    AcademicQuery_complex: function(conjunction, _1, left, _2, right, _3) {
      return {
        "conjunction" : conjunction.sourceString,
        "left" : left.interpret(),
        "right" : right.interpret(),
        "type" : "conjunction"
       }
    },
    AcademicQuery_composite: function(_1, query, _2) {
      return query.interpret();
    },

    CompositeQuery_simple: function(mainAttribute, _, secondaryAttribute, comparator, value) {
      // would it make sense to split main and secondary attribute?
      var main = mainAttribute.interpret();
      var secondary = secondaryAttribute.interpret();
      return {
        "attribute" : main + "." + secondary,
        "comparator" : comparator.interpret(),
        "value" : value.interpret(),
        "type" : "composite"
      }
    },
    CompositeQuery_complex: function(conjunction, _1, left, _2, right, _3) {
      return {
        "conjunction" : conjunction.sourceString,
        "left" : left.interpret(),
        "right" : right.interpret(),
        "type" : "conjunction"
      }
    },

    Comparator: function(main, secondary) {
      return [main.interpret(), secondary.sourceString].join('');
    },
    PartialComparator: function(comparator) {
      return comparator.sourceString;
    },

    Attribute: function(a, b, c) {
      return [a.interpret(), b.interpret(), c.interpret()].join('');
    },

    Value: function(value) {
      return value.interpret();
    },
    Value_string: function(_1, string, _2) {
      return string.sourceString;
    },
    Value_numberRange: function(leftBracket, nLeft, _, nRight, rightBracket) {
      return "TODO";//arguments.map(a => {a.sourceString}).join('');
    },
    Value_dateRange: function(leftBracket, dLeft, _, dRight, rightBracket) {
      return "TODO";//arguments.map(a => {a.sourceString}).join('');
    },

    Number: function(n) {
      return parseFloat(n.sourceString);
    },
    Date: function(_1, year, _2, month, _3, day, _4) {
      return new Date(year.interpret(),
                      month.interpret(),
                      day.interpret())
    },

    letter: function(a) {
      return a.sourceString;
    }
  }
)

export default class AcademicQuery extends Morph {
  async initialize() {
    this.updateView()
  }

  setQuery(q) {
    var match = g.match(q);

    this.textContent = q;
    var queryObject = s(match).interpret();

    this.ui = this.queryToView(queryObject);

    this.updateView()
  }

  updateView() {
    var pane = this.get("#pane")
    pane.innerHTML = ""

    if(this.ui) {
      pane.appendChild(this.ui)
    }
      //Query:{this.textContent})
  }

  viewToQuery() {
    var pane = this.get("#pane")

    var s = "... parsed from ui"

    return s
  }

  queryToView(object) {
      var subDiv =

;

    switch(object.type) {
      case "simple":
        [object.attribute, object.comparator, object.value].forEach(value => {
          var input = <input value={value}></input>;
          subDiv.appendChild(input)
        });
        break;
      case "conjunction":
        var input = <input value={object.conjunction}></input>;
        var left = this.queryToView(object.left);
        var right = this.queryToView(object.right);
        [input, left, right].forEach(element => {
          subDiv.appendChild(element);
        });
        break;
      case "composite":
        [object.attribute, object.comparator, object.value].forEach(value => {
          var input = <input value={value}></input>;
          subDiv.appendChild(input)
        });
    }
    return subDiv;
  }

  async livelyExample() {
    this.setQuery("And(Or(Y='1985', Y='2008'), Ti='disordered electronic systems')")
  }

}<commit_msg>[academic_query] add new ui for widget<commit_after>import Morph from 'src/components/widgets/lively-morph.js';
import ohm from "https://unpkg.com/ohm-js@15.2.1/dist/ohm.js";

var g = ohm.grammar(
  `Academic {
    Exp =
      AcademicQuery

    AcademicQuery = Attribute Comparator Value -- simple
      | ("And" | "Or") "(" AcademicQuery "," AcademicQuery ")" -- complex
      | "Composite(" CompositeQuery ")" -- composite
    CompositeQuery = Attribute "." Attribute Comparator Value -- simple
      | ("And" | "Or") "(" CompositeQuery "," CompositeQuery ")" -- complex

    Comparator =
      PartialComparator "="?
    PartialComparator =
      "=" | "<" | ">"

    Attribute (an attribute) =
      letter letter? letter?

    Value (a value) =
      "\'" alnum* "\'" -- string
      | Number
      | Date
      | ( "[" | "(" ) Number "," Number ( "]" | ")" ) -- numberRange
      | ( "[" | "(" ) Date "," Date ( "]" | ")" ) -- dateRange

    Number =
      digit+
      Date =
      "\'" Number "-" Number "-" Number "\'"
  }`
);

var s = g.createSemantics();

s.addOperation(
  'interpret', {
    Exp: function(e) {
      return e.interpret();
    },

    AcademicQuery_simple: function(attribute, comparator, value) {
      return {
        "attribute" : attribute.interpret(),
        "comparator" : comparator.interpret(),
        "value" : value.interpret(),
        "type" : "simple"
      }
    },
    AcademicQuery_complex: function(conjunction, _1, left, _2, right, _3) {
      return {
        "conjunction" : conjunction.sourceString,
        "left" : left.interpret(),
        "right" : right.interpret(),
        "type" : "conjunction"
       }
    },
    AcademicQuery_composite: function(_1, query, _2) {
      return query.interpret();
    },

    CompositeQuery_simple: function(mainAttribute, _, secondaryAttribute, comparator, value) {
      // would it make sense to split main and secondary attribute?
      var main = mainAttribute.interpret();
      var secondary = secondaryAttribute.interpret();
      return {
        "attribute" : main + "." + secondary,
        "comparator" : comparator.interpret(),
        "value" : value.interpret(),
        "type" : "composite"
      }
    },
    CompositeQuery_complex: function(conjunction, _1, left, _2, right, _3) {
      return {
        "conjunction" : conjunction.sourceString,
        "left" : left.interpret(),
        "right" : right.interpret(),
        "type" : "conjunction"
      }
    },

    Comparator: function(main, secondary) {
      return [main.interpret(), secondary.sourceString].join('');
    },
    PartialComparator: function(comparator) {
      return comparator.sourceString;
    },

    Attribute: function(a, b, c) {
      return [a.interpret(), b.interpret(), c.interpret()].join('');
    },

    Value: function(value) {
      return value.interpret();
    },
    Value_string: function(_1, string, _2) {
      return string.sourceString;
    },
    Value_numberRange: function(leftBracket, nLeft, _, nRight, rightBracket) {
      return "TODO";//arguments.map(a => {a.sourceString}).join('');
    },
    Value_dateRange: function(leftBracket, dLeft, _, dRight, rightBracket) {
      return "TODO";//arguments.map(a => {a.sourceString}).join('');
    },

    Number: function(n) {
      return parseFloat(n.sourceString);
    },
    Date: function(_1, year, _2, month, _3, day, _4) {
      return new Date(year.interpret(),
                      month.interpret(),
                      day.interpret())
    },

    letter: function(a) {
      return a.sourceString;
    }
  }
)

export default class AcademicQuery extends Morph {
  constructor() {
    super()
    //this.setQuery('T=1')
  }

  async initialize() {
    this.updateView()
  }

  async setQuery(q) {
    lively.notify("query", q)
    var match = g.match(q);

    this.textContent = q;
    var queryObject = s(match).interpret();

    this.ui = await this.queryToView(queryObject);

    this.updateView()
  }

  async setQueryObject(o) {
    this.ui = await this.queryToView(o);

    lively.notify("Object", o)

    this.updateView()
  }

  async updateView() {
    // Ansatz: Ein academic query widget ist nur für eine Query oder eine conjunction
    // eine conjunction enthält dann aber zwei weitere query widgets
    var pane = this.get("#pane")
    lively.notify("pane", pane)
    pane.innerHTML = ""

    if(this.ui) {
      pane.appendChild(this.ui)
    }
      //Query:{this.textContent})
  }

  viewToQuery() {
    var pane = this.get("#pane")

    var s = "... parsed from ui"

    return s
  }

  async queryToView(object) {
      //var subDiv =

;
      var span =

    switch(object.type) {
      case "simple":
        // [object.attribute, object.comparator, object.value].forEach(value => {
        //   var input = <input value={value}></input>;
        //   subDiv.appendChild(input)
        // });
        [object.attribute, object.comparator, object.value].forEach(value => {
          var subSpan = {value} ;
          span.appendChild(subSpan)
        });
        break;
      case "conjunction":
        // var input = <input value={object.conjunction}></input>;
        // var left = this.queryToView(object.left);
        // var right = this.queryToView(object.right);
        // [input, left, right].forEach(element => {
        //   subDiv.appendChild(element);
        // });
        var subSpan = {object.conjunction};
        var left = await (<academic-query style="font-size: smaller;"></academic-query>);
        left.setQueryObject(object.left);
        var right = await (<academic-query style="font-size: smaller;"></academic-query>);
        right.setQueryObject(object.right);
        span.appendChild(

              {subSpan}

{left}

{right}

        )
        break;
      case "composite":
        // [object.attribute, object.comparator, object.value].forEach(value => {
        //   var input = <input value={value}></input>;
        //   subDiv.appendChild(input)
        // });
        [object.attribute, object.comparator, object.value].forEach(value => {
          var subSpan = {value} ;
          span.appendChild(subSpan)
        });
    }
    var queryElement = {span}
    return queryElement;
  }

  async livelyExample() {
    this.setQuery("And(Or(Y='1985', Y='2008'), Ti='disordered electronic systems')")
    //this.setQuery("And(O='abc', Y='1000')")
  }

}<|endoftext|>


<commit_before>const express = require('express');
const bodyParser = require('body-parser');
const webpush = require('web-push');
const gcloud = require('google-cloud');
const model = require('../model');
const path = require ('path');

// Project variables
const project_id = 'web-push-rocks';
const app = express();
const pubsub = gcloud.pubsub({
  projectId: project_id
});
const subscribeTopicId = `projects/${project_id}/topics/subscribe`;
const sendTopicId = `projects/${project_id}/topics/send`;
const jsonParser = bodyParser.json();

let subscribeTopic;
let sendTopic;
let sendRawTopic;
let instanceVAPIDKey;

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.render('index', {
    publicKey: instanceVAPIDKey.publicKey,
    messages: [{}]
  });
});

app.post('/subscribe', jsonParser, (req, res) => {
  const subscription = req.body;
  console.log(subscription);

  subscription.privateKey = instanceVAPIDKey.privateKey;

  subscribeTopic.publish({
    subscription: subscription
  });
  res.send('ok');
});

app.post('/send', jsonParser, (req, res) => {
  const message = req.body;
  const id = req.query.id;

  console.log(message)

  sendTopic.publish({
    id: id,
    message: message
  });

  res.send('ok');
});

app.post('/send-raw', jsonParser, (req, res) => {
  const message = req.body;
  const id = req.query.id;
  const processor = req.query.processor;

  const sendRawTopicId = `projects/${project_id}/topics/send-${processor}`;

  pubsub.createTopic(sendRawTopicId)
        .then(data => rawTopic = data[0])
        .catch(data => rawTopic = pubsub.topic(sendRawTopicId))
        .then(() => {
            rawTopic.publish({
              id: id,
              processor: processor,
              message: message
            });
        });

  res.send('ok');
});

app.listen(3000, () => {
  app.set('views', path.join(__dirname , 'views'));
  app.set('view engine', 'ejs');

  const vapidKeys = webpush.generateVAPIDKeys();

  // Before the server starts, let's get VAPID persisted
  instanceVAPIDKey = new model.ApplicationKey(vapidKeys.publicKey, vapidKeys.privateKey);
  instanceVAPIDKey.put();

  // Create the topic
  pubsub.createTopic(subscribeTopicId)
        .then(data => subscribeTopic = data[0])
        .catch(data => subscribeTopic = pubsub.topic(subscribeTopicId));

  // Create the topic that will be used to send the broadcasts.
  pubsub.createTopic(sendTopicId)
        .then(data => sendTopic = data[0])
        .catch(data => sendTopic = pubsub.topic(sendTopicId));

  console.log('Front-end is listenting on port 3000');
});<commit_msg>Topic must exist.<commit_after>const express = require('express');
const bodyParser = require('body-parser');
const webpush = require('web-push');
const gcloud = require('google-cloud');
const model = require('../model');
const path = require ('path');

// Project variables
const project_id = 'web-push-rocks';
const app = express();
const pubsub = gcloud.pubsub({
  projectId: project_id
});
const subscribeTopicId = `projects/${project_id}/topics/subscribe`;
const sendTopicId = `projects/${project_id}/topics/send`;
const jsonParser = bodyParser.json();

let subscribeTopic;
let sendTopic;
let sendRawTopic;
let instanceVAPIDKey;

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.render('index', {
    publicKey: instanceVAPIDKey.publicKey,
    messages: [{}]
  });
});

app.post('/subscribe', jsonParser, (req, res) => {
  const subscription = req.body;
  console.log(subscription);

  subscription.privateKey = instanceVAPIDKey.privateKey;

  subscribeTopic.publish({
    subscription: subscription
  });
  res.send('ok');
});

app.post('/send', jsonParser, (req, res) => {
  const message = req.body;
  const id = req.query.id;

  console.log(message)

  sendTopic.publish({
    id: id,
    message: message
  });

  res.send('ok');
});

app.post('/send-raw', jsonParser, (req, res) => {
  const message = req.body;
  const id = req.query.id;
  const processor = req.query.processor;

  // topic must exist
  const rawTopic = pubsub.topic(`projects/${project_id}/topics/send-${processor}`);
  rawTopic.publish({
      id: id,
      processor: processor,
      message: message
    });

  res.send('ok');
});

app.listen(3000, () => {
  app.set('views', path.join(__dirname , 'views'));
  app.set('view engine', 'ejs');

  const vapidKeys = webpush.generateVAPIDKeys();

  // Before the server starts, let's get VAPID persisted
  instanceVAPIDKey = new model.ApplicationKey(vapidKeys.publicKey, vapidKeys.privateKey);
  instanceVAPIDKey.put();

  // Create the topic
  pubsub.createTopic(subscribeTopicId)
        .then(data => subscribeTopic = data[0])
        .catch(data => subscribeTopic = pubsub.topic(subscribeTopicId));

  // Create the topic that will be used to send the broadcasts.
  pubsub.createTopic(sendTopicId)
        .then(data => sendTopic = data[0])
        .catch(data => sendTopic = pubsub.topic(sendTopicId));

  console.log('Front-end is listenting on port 3000');
});<|endoftext|>