code stringlengths 2 1.05M |
|---|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({colorRamps:{none:"Nenhum",blackToWhite_predefined:"De Negro a Branco",yellowToRed_predefined:"De Amarelo a Vermelho",slope_predefined:"Inclina\u00e7\u00e3o",aspect_predefined:"Aspeto",errors_predefined:"Erros",heatmap1_predefined:"Mapa de Calor #1",elevation1_predefined:"Eleva\u00e7\u00e3o #1",elevation2_predefined:"Eleva\u00e7\u00e3o #2",blueBright_predefined:"Azul Vivo",blueLightToDark_predefined:"Azul de Claro a Escuro",blueGreenBright_predefined:"Azul-Verde Vivo",blueGreenLightToDark_predefined:"Azul-Verde de Claro a Escuro",
brownLightToDark_predefined:"Castanho de Claro a Escuro",brownToBlueGreenDivergingBright_predefined:"De Castanho a Azul Verde Divergente, Vivo",brownToBlueGreenDivergingDark_predefined:"De Castanho a Azul Verde Divergente, Escuro",coefficientBias_predefined:"Tend\u00eancia de Coeficiente",coldToHotDiverging_predefined:"A Divergir entre Frio e Quente",conditionNumber_predefined:"N\u00famero de Condi\u00e7\u00e3o",cyanToPurple_predefined:"De Ciano a P\u00farpura",cyanLightToBlueDark_predefined:"De Ciano-Claro a Azul-Escuro",
distance_predefined:"Dist\u00e2ncia",grayLightToDark_predefined:"Cinza de Claro a Escuro",greenBright_predefined:"Verde Vivo",greenLightToDark_predefined:"Verde de Claro a Escuro",greenToBlue_predefined:"De Verde a Azul",orangeBright_predefined:"Laranja Vivo",orangeLightToDark_predefined:"Laranja de Claro a Escuro",partialSpectrum_predefined:"Espectro Parcial",partialSpectrum1Diverging_predefined:"Espectro Parcial 1 Divergente",partialSpectrum2Diverging_predefined:"Espectro Parcial 2 Divergente",
pinkToYellowGreenDivergingBright_predefined:"De Rosa a AmareloVerde Divergente, Vivo",pinkToYellowGreenDivergingDark_predefined:"De Rosa a AmareloVerde Divergente, Escuro",precipitation_predefined:"Precipita\u00e7\u00e3o",prediction_predefined:"Previs\u00e3o",purpleBright_predefined:"P\u00farpura Vivo",purpleToGreenDivergingBright_predefined:"De P\u00farpura a Verde Divergente, Vivo",purpleToGreenDivergingDark_predefined:"De P\u00farpura a Verde Divergente, Escuro",purpleBlueBright_predefined:"P\u00farpura-Azul Vivo",
purpleBlueLightToDark_predefined:"P\u00farpura-Azul de Claro a Escuro",purpleRedBright_predefined:"P\u00farpura-Vermelho Vivo",purpleRedLightToDark_predefined:"P\u00farpura-Vermelho de Claro a Escuro",redBright_predefined:"Vermelho Vivo",redLightToDark_predefined:"Vermelho de Claro a Escuro",redToBlueDivergingBright_predefined:"De Vermelho a Azul Divergente, Vivo",redToBlueDivergingDark_predefined:"De Vermelho a Azul Divergente, Escuro",redToGreen_predefined:"Vermelho para Verde",redToGreenDivergingBright_predefined:"De Vermelho a Verde Divergente, Vivo",
redToGreenDivergingDark_predefined:"De Vermelho a Verde Divergente, Escuro",spectrumFullBright_predefined:"Espectro-Totalmente Vivo",spectrumFullDark_predefined:"Espectro-Totalmente Escuro",spectrumFullLight_predefined:"Espectro-Totalmente Claro",surface_predefined:"Superf\u00edcie",temperature_predefined:"Temperatura",whiteToBlack_predefined:"De Branco a Negro",yellowToDarkRed_predefined:"De Amarelo a Vermelho Escuro",yellowToGreenToDarkBlue_predefined:"De Amarelo a Verde a Azul Escuro",yellowGreenBright_predefined:"Amarelo-Verde Vivo",
yellowGreenLightToDark_predefined:"Amarelo-Verde de Claro a Escuro"}}); |
requirejs.config({
baseUrl: '/js',
paths: {
'jquery': 'jquery/jquery'
},
shim: {
tinyMCE: {
exports: 'tinyMCE',
init: function () {
'use strict';
this.tinyMCE.DOM.events.domLoaded = true;
return this.tinyMCE;
}
}
}
});
require(['Foo/Page'], function (page) {
page.init();
});
/* ID: Page.main.js */
|
import { moduleForModel, test } from 'ember-qunit';
moduleForModel('account-guarantor', 'Unit | Model | Account_Guarantor', {
needs: [
'model:meta',
'model:narrative',
'model:resource',
'model:extension',
'model:reference',
'model:period'
]
});
test('it exists', function(assert) {
const model = this.subject();
assert.ok(!!model);
}); |
/**
* Created by Julius Höfler on 30.03.15.
*/
var global_currentInputUnitName = "";
var list_units = [];
var counter_multiSelectionContextInfos = 0;
var array_multiSelectionContextInfos = [];
var array_multiSelectionMetaData = [];
var counter_multiSelectionMetaData = 0;
var bool_unitClicked = false;
// Jobs: - make details in tab "Kontextinformation" visible,
// - hide main part
// - get information into the selections and input fields
/**
* Function gets information into the selection bar and input fields.
* Furthermore hide main part in tab and show details of context information.
* */
function showDetailContextInfo() {
// show detail, hide main
$("#detailContextInfo").slideDown();
$("#mainContextInfo").slideUp();
/* add context information in selection bar */
// clean selections
cleanSection("#selectContextInfos");
cleanSection("#selectOperator");
cleanSection("#selectPossibleValues");
cleanSection("#selectParameter");
cleanSection("#selectParameter2");
// clean input fields
$("#formContextInformation")[0].reset();
// make objects invisible
$("#inputContextValue").css("display", "none");
$("#selectPossibleValues").css("display", "none");
$("#s2id_selectPossibleValues").css("display", "none");
$("#divContextParameter").css("display", "none");
// fill selection "Kontextinformation"
fillSelectionContextInformation();
}
// if home button is clicked change view
/**
* Function changes view of context information tab from detail view to main view.
* */
function showMainContextInfo() {
// show main, hide detail
$("#mainContextInfo").slideDown();
$("#detailContextInfo").slideUp();
}
// bind unit with properties (tabs)
/**
* Function add event listeners after learning unit creation.
* @param {Object} newState Contains new created learning unit.
* */
function activateFunctionalities(newState) {
// get id from new state (unit)
var id = newState[0].getAttribute("id");
var unit = document.getElementById(id);
var name = "";
// creates variable which decides whether all or one context information have to be satisfied
// default is all have to be satisfied
var unitSatisfiesAllContextInfos = true;
// get newState id in unit list
list_units.push(unit);
var current_unit;
// triggered if learning unit is clicked
$(unit).click(function(event) {
// clear marking from all units
for (var l=0; l<list_units.length; l++) {
$(list_units[l]).css("background", "");
$(list_units[l]).css("color", "");
}
// unit is marked --> change color
$(unit).css("background", "#16a085");
$(unit).css("color", "white");
bool_unitClicked = true;
// show tab content of the current active tab
var activeTab = $(".tab-Container > ul > li").children("a.active").attr("href");
$(activeTab).fadeIn();
$(".tab-Container").show();
// hide tab from unit label connection
$("#tabUnitLabel").hide();
// clear marking from label connections
$(".aLabel").css("background-color", "");
$(".aLabel").css("color", "");
/* input field in tab "Eigenschaften"*/
// get name of the unit
if ($(unit).children("div").hasClass("title")) {
name = (this).innerText.replace(/(\r\n|\n|\r)/gm,"");
}
// put name into the input field
//var formObject = document.forms["formProperties"];
$("#inputUnitName")[0].value = name;
global_currentInputUnitName = name;
// get current unit dictionary
for (var p=0; p<myAuthorSystem.length; p++) {
if (myAuthorSystem[p]["name"] == $("#lname")[0].innerText) {
for (var q=0; q<myAuthorSystem[p]["units"].length; q++) {
if (myAuthorSystem[p]["units"][q]["name"] == name) {
current_unit = myAuthorSystem[p]["units"][q];
}
}
}
}
// get current unit dictionary if scenario was loaded
if (loadedData) {
for (var q=0; q<loadedData["units"].length; q++) {
if (loadedData["units"][q]["name"] == name) {
current_unit = loadedData["units"][q];
}
}
}
// set description field
$("#inputUnitDescription")[0].value = current_unit["description"];
/* tab "Kontextinformation" */
// check how much context information are needed to reach SAT
var ciSAT = $(unit).children("div.unit-icons")[0].getAttribute("ci");
if (ciSAT == "all") {
$("#s2id_selectNumberContextInfos").children("a").children("span.select2-chosen").html("Alle");
} else if (ciSAT == "one") {
$("#s2id_selectNumberContextInfos").children("a").children("span.select2-chosen").html("Eine");
}
// clear multi selection in context info tab
$("#selectMultiContextInfos").empty();
$("#selectMultiContextInfos").select2("data", null);
array_multiSelectionContextInfos = [];
// change format: add icons to text
$("#selectMultiContextInfos").select2({
formatSelection: formatMultiContextInfos,
formatResult: formatMultiContextInfos,
escapeMarkup: function(m) {return m;}
});
// get data back in multi selection bar from a past edited learning unit
var array_unitIcons = $(unit).find(".unit-icon");
for (var n=0; n<array_unitIcons.length; n++) {
array_multiSelectionContextInfos.push({
"id":$(array_unitIcons[n]).children("img")[0].getAttribute("ccID"),
"text":$(array_unitIcons[n]).children("img")[0].title
});
}
// get data in multi selection bar
$("#selectMultiContextInfos").select2("data", array_multiSelectionContextInfos);
// check if multi selection bar is empty
if ( jQuery.isEmptyObject($("#selectMultiContextInfos").select2("data")) ) {
$("#mainContextInfoSAT").hide();
$("#mainContextInfoSelection").hide();
} else {
$("#mainContextInfoSAT").show();
$("#mainContextInfoSelection").show();
}
// needed too re-color the selections
changeColorMultiContextInfos();
/* multi selection bar in tab "Metadaten" */
// clear multi selection in meta data tab
$("#selectMultiMetaData").empty();
$("#selectMultiMetaData").select2("data", null);
array_multiSelectionMetaData = [];
// get data back in multi selection bar from a past edited learning unit
var array_icons = $(unit).find(".unit-meta-icons");
for (var j=0; j<array_icons.length; j++) {
array_multiSelectionMetaData.push({"id":j, "text":$(array_icons[j])[0].title});
}
// change format: add icons to text
$("#selectMultiMetaData").select2({
formatSelection: formatMultiMetaData,
escapeMarkup: function(m) {return m;}
});
// get data in multi selection bar
$("#selectMultiMetaData").select2("data", array_multiSelectionMetaData);
// prevents that underlying container is also clicked (needed for unit marking)
event.stopPropagation();
//console.log(myAuthorSystem);
console.log(JSON.stringify(myAuthorSystem));
});
// triggered if one option was selected ("Eine" or "Alle")
$("#selectNumberContextInfos").select2().on("select2-selecting", function(e) {
// only for the selected unit
if (name == global_currentInputUnitName) {
// decides that one of the group of selected context information has to be satisfied (1 == "Eine")
if (e.val == 1) {
// if a border already exists and is unequal to 1 --> change design
if (unitSatisfiesAllContextInfos) {
// check if icons exist
if ($(unit).children("div.unit-icons").children("div.unit-icon").length != 0) {
$(unit).children("div.unit-icons").css("border", "2px dotted #adadad");
// check if ci attribute exists and change attribute ci
if ($(unit).children("div.unit-icons")[0].hasAttribute("ci")) {
$(unit).children("div.unit-icons").attr("ci", "one");
}
}
}
// false == one has to be satisfied
unitSatisfiesAllContextInfos = false;
// change sat information in current unit
current_unit["sat"] = "one";
}
// decides that all of the group of selected context information has to be satisfied (0 == "Alle")
if (e.val == 0) {
// if a border already exists and is unequal to 0 --> change design
if (!unitSatisfiesAllContextInfos) {
if ($(unit).children("div.unit-icons").children("div.unit-icon").length != 0) {
$(unit).children("div.unit-icons").css("border", "2px solid #adadad");
// check if ci attribute exists and change attribute ci
if ($(unit).children("div.unit-icons")[0].hasAttribute("ci")) {
$(unit).children("div.unit-icons").attr("ci", "all");
}
}
}
// true == all have to be satisfied
unitSatisfiesAllContextInfos = true;
// change sat information in current unit
current_unit["sat"] = "all";
}
}
});
// triggered if string is changed in input field in tab "Eigenschaften"
$("#inputUnitName").bind("input", function() {
// get current input field value
var val = $(this).val();
// only for the selected unit
if (name == global_currentInputUnitName) {
// store old name
var old_name = name;
// change unit name if his corresponding input field is changing
$(unit).children("div.title")[0].innerText = val;
//name = $(unit).children("div.title")[0].innerText;
name = val;
global_currentInputUnitName = val;
// find right scenario in menu bar
var scenarioName = $("#lname")[0].innerText;
var findScenario = $("span.title").filter(":contains('" + scenarioName + "')");
findScenario = findScenario.parent("a").parent("li");
// change name in menu bar
if (findScenario.length != 0) {
var findUnit = findScenario.children("ul").children("li").children("a")
.children("span").filter(":contains('" + old_name + "')");
findUnit[0].innerHTML = val;
}
// update JSON structure
current_unit["name"] = name;
// necessary to redraw endpoints
inst.repaintEverything();
}
});
// triggered if string is changed in description field in tab "Eigenschaften"
$("#inputUnitDescription").bind("input", function() {
// get current input field value
var val = $(this).val();
// only for the selected unit
if (name == global_currentInputUnitName) {
// update JSON structure
current_unit["description"] = val;
}
});
// triggered if an operator was selected in tab "Kontextinformation"
$("#selectOperator").select2().on("select2-selecting", function(e) {
// check string of the operator value
if (e.choice.text == "Hat keinen Wert") {
// disable input field if operator needs no value
if ($("#inputContextValue").css("display") == "block") {
$("#inputContextValue").attr("disabled", true);
}
// disable selection bar if operator needs no value
if ($("#selectPossibleValues").css("display") == "block") {
$("#selectPossibleValues").attr("disabled", true);
}
// in both cases enable input/selection if operator needs a value
} else {
if ($("#inputContextValue").css("display") == "block") {
$("#inputContextValue").attr("disabled", false);
}
if ($("#selectPossibleValues").css("display") == "block") {
$("#selectPossibleValues").attr("disabled", false);
}
}
});
// triggered if one option in multi selection bar in tab "Kontextinformation" was removed
$("#selectMultiContextInfos").select2().on("select2-removed", function(e) {
// only for the selected unit
if (name == global_currentInputUnitName) {
// remove this option from array
for (var m=0; m<array_multiSelectionContextInfos.length; m++) {
if (array_multiSelectionContextInfos[m]["text"] == e.choice.text) {
array_multiSelectionContextInfos.splice(m, 1);
break;
}
}
// remove icon from learning unit
$(unit).children("div.unit-icons").children("div.unit-icon").each(function() {
var iconName = $(this).children("img")[0].title;
if (iconName == e.choice.text) {
$(this).remove();
}
});
// remove border if unit has no icons anymore
if ($(unit).children("div.unit-icons").children("div.unit-icon").length == 0) {
$(unit).children(".unit-icons").css("border", "");
$(unit).children(".unit-icons").css("height", "");
$(unit).children(".unit-icons").css("display", "");
$(unit).css("padding-top", "");
}
// update JSON structure
for (var i=0; i<current_unit["contextInformations"].length; i++) {
if (current_unit["contextInformations"][i].name == e.choice.text) {
current_unit["contextInformations"].splice(i, 1);
break;
}
}
// set endpoints on the right place
inst.repaintEverything();
}
});
// button "Bestätigen" in tab "Kontextinformation" was clicked
// Jobs: - evaluate the selections and inputs
// - put context information in multi selection bar
// - add icons in current unit
$("#btnConfirmContextInfo, #btnConfirmContextInfoSmall").on("click", function() {
// only for the selected unit
if (name == global_currentInputUnitName) {
// check if all needed fields were filled with information
var missing_content = "";
var returnArray = [];
returnArray = checkInformation(missing_content, current_unit);
missing_content = returnArray[0];
var selectedInfos = returnArray[1];
// if content is missing do not except adding of the context information
if (missing_content == "Error999") {
return false;
} else {
// if something needed is missing
if (!!missing_content) {
alert("[Fehler] Bitte setzen Sie Werte in den folgenden Feldern:\n" + missing_content);
return false;
} else {
// push all new information about the context unit in current scenario
current_unit["contextInformations"].push(selectedInfos);
// get selected context information
var contentContextInfo = $("#selectContextInfos").select2("data");
var selecElem = contentContextInfo.element[0];
// get corresponding context class
var optgroup = $(selecElem).parent()[0].label;
// get corresponding context class id
var ccID = contentContextInfo.element[0].value;
// create icon DOM
var divContextIcon = $("<div>").addClass("unit-icon").attr("id", ccID + "icon");
//var icon = $("<img>").attr("src", "img/context-classes/" + optgroup + ".png");
//icon.attr("width", "15").attr("height", "15").attr("title", e.choice.text).attr("ccID", ccID);
// get right format for icon visualisation in learning unit
// case 1: context specific icon
// case 2: context class icon (upper class icon, only color)
var icon = formatUnitIcons(contentContextInfo, optgroup, ccID);
// get icon information in JSON structure
for (var j = 0; j < current_unit["contextInformations"].length; j++) {
if (current_unit["contextInformations"][j].name == $("#selectContextInfos").select2("data")["text"]) {
current_unit["contextInformations"][j].icon = icon;
}
}
// add icon and div to unit
divContextIcon.append(icon);
$(unit).children("div.unit-icons").append(divContextIcon);
/* design reasons */
// all SAT needs solid border
if (unitSatisfiesAllContextInfos) {
$(unit).children("div.unit-icons").css("border", "2px solid #adadad");
$(unit).children("div.unit-icons").attr("ci", "all"); // ci all = all context informations
// one SAT needs dotted border
} else {
$(unit).children("div.unit-icons").css("border", "2px dotted #adadad");
$(unit).children("div.unit-icons").attr("ci", "one"); // ci one = one context information
}
$(unit).children("div.unit-icons").css("border-radius", "4px");
$(unit).css("padding-top", "10px");
$(unit).children("div.unit-icons").css("height", "23px");
$(unit).children("div.unit-icons").css("display", "inline-block");
// set endpoints on the right place
inst.repaintEverything();
/* get selected context information name into multi selection bar */
var id = $("#selectContextInfos").select2("data").id;
// get name
var contextInfoName = $("#selectContextInfos").select2("data").text;
var option = $("<option>").attr("value", id.toString()).attr("selected", "selected");
option.html(contextInfoName);
// change format: add icons to text
$("#selectMultiContextInfos").select2({
formatSelection: formatMultiContextInfos,
formatResult: formatMultiContextInfos,
escapeMarkup: function (m) {
return m;
}
});
// get name into multi selection
//$("#selectMultiContextInfos").append(option);
array_multiSelectionContextInfos.push({id: id, text: contextInfoName});
$("#selectMultiContextInfos").select2("data", array_multiSelectionContextInfos);
// change color per option in multi selection bar
changeColorMultiContextInfos();
// increase counter --> needed for continuous ids
counter_multiSelectionContextInfos++;
// show main, hide detail
$("#mainContextInfo").slideDown();
$("#detailContextInfo").slideUp();
// show SAT and multi selection bar
$("#mainContextInfoSAT").show();
$("#mainContextInfoSelection").show();
//console.log(myAuthorSystem);
//console.log(JSON.stringify(myAuthorSystem));
}
}
}
});
// triggered if an option in selection "Metadaten" was selected
$("#selectMetaData").select2().on("select2-selecting", function(e) {
// only for the selected unit
if (name == global_currentInputUnitName) {
// no two same meta data symbols allowed
for (var i = 0; i < array_multiSelectionMetaData.length; i++) {
if (array_multiSelectionMetaData[i]["text"] == e.choice.text) {
return true;
}
}
// create meta data DOM
var divMetaIcon = $("<div>").addClass("unit-meta-icons").attr("id", counter_multiSelectionMetaData + "metaIcon");
// choose icon symbol and add it to meta data DOM
var metaIcon;
switch (e.choice.text) {
case "Bild":
metaIcon = "fui-photo";
divMetaIcon.attr("title", e.choice.text);
break;
case "Film":
metaIcon = "fui-video";
divMetaIcon.attr("title", e.choice.text);
break;
case "Text":
metaIcon = "fui-document";
divMetaIcon.attr("title", e.choice.text);
break;
case "Navigation":
metaIcon = "fui-location";
divMetaIcon.attr("title", e.choice.text);
break;
case "Test":
metaIcon = "fui-radio-unchecked";
divMetaIcon.attr("title", e.choice.text);
break;
case "Audio":
metaIcon = "fui-volume";
divMetaIcon.attr("title", e.choice.text);
break;
case "3D Umgebung":
metaIcon = "fui-windows";
divMetaIcon.attr("title", e.choice.text);
break;
}
// add DOM for meta data icon (glyph)
var bMetaIcon = $("<b>").addClass(metaIcon);
// get icon into learning unit
divMetaIcon.append(bMetaIcon);
$(unit).append(divMetaIcon);
// change size of learning unit
$(unit).css("padding-bottom", "5px");
// clear multi selection bar
$("#selectMultiMetaData").empty();
$("#selectMultiMetaData").select2("data", null);
// get meta data in multi selection bar
array_multiSelectionMetaData.push({"id": counter_multiSelectionMetaData, "text": e.choice.text});
$("#selectMultiMetaData").select2({
formatSelection: formatMultiMetaData,
escapeMarkup: function(m) {return m;}
});
$("#selectMultiMetaData").select2("data", array_multiSelectionMetaData);
counter_multiSelectionMetaData ++;
// update JSON structure
var currentMetaData = {};
currentMetaData.name = e.choice.text;
currentMetaData.icon = metaIcon;
current_unit["metaData"].push(currentMetaData);
// set endpoints on the right place
inst.repaintEverything();
}
});
// remove option from multi selection bar in tab "Metadaten"
$("#selectMultiMetaData").select2().on("select2-removed", function(e) {
// only for the selected unit
if (name == global_currentInputUnitName) {
// find the right meta icon
$(unit).find("div.unit-meta-icons").each(function() {
// get icon title name
var icon = $(this)[0].title;
// remove the right icon from unit
if (icon == e.choice.text) {
this.remove();
// update the array of the multi selection meta data
for (var k=0; k<array_multiSelectionMetaData.length; k++) {
if (array_multiSelectionMetaData[k]["text"] == e.choice.text) {
array_multiSelectionMetaData.splice(k, 1);
}
}
// if no more meta icons in unit go back to old unit design
if (array_multiSelectionMetaData.length == 0) {
$(unit).css("padding-bottom", "");
}
}
});
// update JSON structure
for (var j=0; j<current_unit["metaData"].length; j++) {
if (current_unit["metaData"][j].name == e.choice.text) {
current_unit["metaData"].splice(j, 1);
}
}
// set endpoints on the right place
inst.repaintEverything();
}
});
// re-sets the glyphs in selection bar
$("#selectMetaData").select2({
formatSelection: formatMetaData,
formatResult: formatMetaData,
escapeMarkup: function(m) {return m;}
});
// triggered if unit was dragged
$(unit).on("dragstop", function() {
// get new positions (absolute)
var top = $(unit)[0].offsetTop;
var left = $(unit)[0].offsetLeft;
// only set if current unit object exists
if (current_unit) {
current_unit.posX = left;
current_unit.posY = top;
}
});
// clear marking from existing learning units
for (var l=0; l<list_units.length; l++) {
$(list_units[l]).css("background", "");
$(list_units[l]).css("color", "");
}
// clear multi selection bar
$("#selectMultiContextInfos").empty();
$("#selectMultiContextInfos").select2("data", null);
array_multiSelectionContextInfos = [];
}
// change shown format in multi selection bar in tab "Metadaten"
/**
* Function
* @param {Object} item Contains the selected option from meta data selection bar.
* @return {String} Returns DOM string which contains a meta data specific glyph.
* */
function formatMultiMetaData(item) {
switch (item.text) {
case "Bild":
return '<b class="fui-photo"></b>';
case "Film":
return '<b class="fui-video"></b>';
case "Text":
return '<b class="fui-document"></b>';
case "Navigation":
return '<b class="fui-location"></b>';
case "Test":
return '<b class="fui-radio-unchecked"></b>';
case "Audio":
return '<b class="fui-volume"></b>';
case "3D Umgebung":
return '<b class="fui-windows"></b>';
}
}
// change shown format in selection bar in tab "Metadaten"
/**
* Function
* @param {Object} item Contains the selected option from meta data selection bar.
* @return {String} Returns DOM string which contains a meta data specific glyph and the corresponding text.
* */
function formatMetaData(item) {
switch (item.text) {
case "Bild":
return '<b class="fui-photo"> </b>' + item.text;
case "Film":
return '<b class="fui-video"> </b> ' + item.text;
case "Text":
return '<b class="fui-document"> </b>' + item.text;
case "Navigation":
return '<b class="fui-location"> </b> ' + item.text;
case "Test":
return '<b class="fui-radio-unchecked"> </b> ' + item.text;
case "Audio":
return '<b class="fui-volume"> </b>' + item.text;
case "3D Umgebung":
return '<b class="fui-windows"> </b>' + item.text;
}
}
// fill selection bars in tab "Kontextinformation"
/**
* Function sets a event listener for selection bar context information after parsing is finished.
* In this listener all selections and input fields were filled.
* Furthermore the meta data selection bar is also filled with information.
* */
function parsingFinished() {
/* tab "Kontextinformation" */
// triggered if a context information was selected
$("#selectContextInfos").select2().on("select2-selecting", function(e) {
// get index (value) of the selected option
var j = e.val;
// get the corresponding operators to the selected context information
var operators = array_ContextInformations[j][2][1];
// clear selection bar
$("#selectOperator").empty();
$("#selectPossibleValues").empty();
// set empty field in selected start field
$("#selectOperator").select2("data", {id:"\r",text:"\r"});
$("#selectPossibleValues").select2("data", {id:"\r",text:"\r"});
// fill selection bar "Operator"
for (var i=0; i<operators.length; i++) {
var option = $("<option>").attr("value", i.toString());
option.html(operators[i]);
$("#selectOperator").append(option);
}
// fill input field
fillInputField(array_ContextInformations[j][2]);
// fill parameter selection bar
fillParameterSelection(array_ContextInformations[j][3]);
});
/* tab "Metadaten" */
// set all needed meta data
var array_SelectionMetaData = ["Bild", "Film", "Text", "Navigation", "Test", "Audio", "3D Umgebung"];
// get meta data options in selection bar
for (var i=0; i<array_SelectionMetaData.length; i++) {
var option = $("<option>").attr("value", i.toString());
option.html(array_SelectionMetaData[i]);
$("#selectMetaData").append(option);
}
// change format: add glyphs per option
$("#selectMetaData").select2({
formatSelection: formatMetaData,
formatResult: formatMetaData,
escapeMarkup: function(m) {return m;}
});
}
// fill selection bar "Kontextinformation"
/**
* Function adds all context information and context classes into the selection bar context information.
* */
function fillSelectionContextInformation() {
// create array for all context classes
var array_optgroups = [];
// iterate through all context classes
for (var j=0; j<array_ContextClasses.length; j++) {
var classname = array_ContextClasses[j];
var optgroup = $("<optgroup>").attr("label", classname);
array_optgroups.push(optgroup);
}
// iterate through all context information
for (var i=0; i<array_ContextInformations.length; i++) {
// create option DOM and add the context information
var option = $("<option>").attr("value", i.toString());
option.attr("origin", array_ContextInformations[i][4]); // save origin name
option.html(array_ContextInformations[i][0]);
// find right context class and put it in this optgroup
for (var k=0; k<array_ContextClasses.length; k++) {
if (array_ContextInformations[i][1][0] == array_ContextClasses[k]) {
array_optgroups[k].append(option);
break;
}
}
}
// change color of all context classes if selection bar "Kontextinformation" is opening
$("#selectContextInfos").select2().on("select2-open", function() {
$(".select2-results").children("li").children("div.select2-result-label").each(function() {
// for all context classes set a specific color
if ( $(this)[0].textContent == "Lernszenario" ) {
$(this).css("background-color", "#3287C8");
$(this).css("color", "white");
} else if ( $(this)[0].textContent == "Persönlich" ) {
$(this).css("background-color", "#AF46C8");
$(this).css("color", "white");
} else if ( $(this)[0].textContent == "Situationsbezogen" ) {
$(this).css("background-color", "#91F52D");
$(this).css("color", "#555555");
} else if ( $(this)[0].textContent == "Infrastruktur" ) {
$(this).css("background-color", "#969696");
$(this).css("color", "white");
} else if ( $(this)[0].textContent == "Umwelt" ) {
$(this).css("background-color", "#FADC3C");
$(this).css("color", "#555555");
} else if ( $(this)[0].textContent == "Ortung" ) {
$(this).css("background-color", "#F03C32");
$(this).css("color", "white");
}
});
});
// change format: add glyphs per option
$("#selectContextInfos").select2({
formatSelection: formatContextInfos,
formatResult: formatContextInfos,
escapeMarkup: function(m) {return m;}
});
// append optgroups (context classes) and their included options in selection bar "Kontextinformation"
for (var l=0; l<array_optgroups.length; l++) {
$("#selectContextInfos").append(array_optgroups[l]);
}
}
// fill input field (value in tab Kontexinformation)
/**
* Function gets the seletect context information and decides which input field has to be set on GUI.
* @param {Object} ci Contains current context information.
* */
function fillInputField(ci) {
// clear input field caused by removing input field and re-building
$("#inputContextValue").remove();
var inputField = $("<input>").addClass("form-control").attr("id", "inputContextValue")
.attr("onkeyup", "getInputContextValue(this)");
$("#divContextValue").append(inputField);
// get type of the context information
var type = ci[0][0]["type"]; // float, integer, string, enum, boolean
// decide which type of input field is needed
switch (type) {
case "FLOAT":
configureInputContextValueForFloatInt(ci[0]);
break;
case "INTEGER":
configureInputContextValueForFloatInt(ci[0]);
break;
case "STRING":
$("#inputContextValue").attr("disabled", false); // activate input field
$("#inputContextValue").attr("type", "text"); // set type to text
$("#inputContextValue").css("display", "block"); // make input field visible
$("#selectPossibleValues").css("display", "none"); // and selection bar invisible
$("#s2id_selectPossibleValues").css("display", "none");
$("#inputContextValue").attr("maxlength", 40); // set max length to 40
break;
case "ENUM":
$("#inputContextValue").css("display", "none"); // make input field invisible
$("#selectPossibleValues").css("display", "block"); // and selection bar visible
$("#s2id_selectPossibleValues").css("display", "block");
// clear selection
$("#selectPossibleValues").empty();
$("#selectPossibleValues").select2("data", {id:"\r",text:"\r"});
// fill selection bar
for (var i=0; i<ci[2].length; i++) {
var option = $("<option>").attr("value", i.toString());
option.html(ci[2][i]);
$("#selectPossibleValues").append(option);
}
break;
case "BOOLEAN":
$("#selectPossibleValues").css("display", "block"); // make selection bar visible
$("#s2id_selectPossibleValues").css("display", "block");
$("#inputContextValue").css("display", "none"); // and input field invisible
// get the two possible values true and false in selection bar
var option0 = $("<option>").attr("value", 0);
var option1 = $("<option>").attr("value", 1);
option0.html("falsch");
option1.html("wahr");
$("#selectPossibleValues").append(option1);
$("#selectPossibleValues").append(option0);
break;
}
}
// set the need functionalities into the input field for float and integer values
/**
* Function shows an input field an set minimum, maximum and default values if needed.
* @param {Object} ci Contains current context information.
* */
function configureInputContextValueForFloatInt(ci) {
var min, max, def = null;
// activate and show input field and hide selection bar
$("#inputContextValue").attr("disabled", false);
$("#inputContextValue").attr("type", "number");
$("#inputContextValue").css("display", "block");
$("#selectPossibleValues").css("display", "none");
$("#s2id_selectPossibleValues").css("display", "none");
for (var i=1; i<ci.length; i++) {
// find minimum if given
if (ci[i]["min"]) {
min = ci[i]["min"];
}
// find maximum if given
if (ci[i]["max"]) {
max = ci[i]["max"];
}
// find default value if given
if (ci[i]["default"]) {
def = ci[i]["default"];
// set default value in input field
$("#inputContextValue").attr("value", def);
}
}
// set minimum and maximum in input field
if (min && max) {
$("#inputContextValue").attr("min", min).attr("max", max);
}
// set minimum only
if (min && !max) {
$("#inputContextValue").attr("min", min);
}
// set maximum only
if (!min && max) {
$("#inputContextValue").attr("max", max);
}
}
// get current value from input field
/**
* Function evaluate the input value and sets too big values to maximum and too small values to minimum.
* @param {Object} val Contains the current value of the context value input field.
* */
function getInputContextValue(val) {
// reduce to big values to maximum
if ( $("#inputContextValue")[0].hasAttribute("max") ) {
// get max attribute value
var max = $("#inputContextValue")[0].getAttribute("max");
max = parseInt(max);
if (val.value > max) {
val.value = max;
}
}
// increase to little values to minimum
if ( $("#inputContextValue")[0].hasAttribute("min") ) {
// get min attribute value
var min = $("#inputContextValue")[0].getAttribute("min");
min = parseInt(min);
if (val.value < min) {
val.value = min;
}
}
// do not allow no numbers
/*if (val.value.length == 0) {
var regex = /[0-9]/;
if( !regex.test(val.value) ) {
val.value = 0;
}
}*/
}
// get the current needed input fields and selection bars (tab Kontextinformation)
/**
* Function show all needed input fields and selection bar for the selected context information.
* @param {Object} cp Contains all existing context parameter.
* */
function fillParameterSelection(cp) {
// clear selection bar
$("#selectParameter").empty();
$("#selectParameter2").empty();
// set empty field in selected start field
$("#selectParameter").select2("data", {id:"\r",text:"\r"});
$("#selectParameter2").select2("data", {id:"\r",text:"\r"});
// clear input fields caused by removing input fields and re-building
$("#inputContextParameter1").remove();
$("#inputContextParameter2").remove();
$("#inputParameterString").remove();
var inputField = $("<input>").addClass("form-control").attr("id", "inputContextParameter1")
.attr("type", "number").attr("onkeyup", "getParameterInput(this,1)");
var inputField2 = $("<input>").addClass("form-control").attr("id", "inputContextParameter2")
.attr("type", "number").attr("onkeyup", "getParameterInput(this,2)");
var inputField3 = $("<input>").addClass("form-control").attr("id", "inputParameterString");
$("#divParameterInput1").append(inputField);
$("#divParameterInput2").append(inputField2);
$("#divParameterString").append(inputField3);
// set all parameter fields invisible
$("#divContextParameter > div").css("display", "none");
// cp[i][0] = parameter name
// cp[i][1] = type (enum, string, float, integer)
// cp[i][2] = possible values
// iterate through all parameters
for (var i=0; i<cp.length; i++) {
// get the current type
var type = cp[i][1];
switch (type) {
// type enum needs a drop down selection for only possible values
case "ENUM":
// get all possible values
for (var j=0; j<cp[i][2].length; j++) {
var option = $("<option>").attr("value", j.toString());
option.html(cp[i][2][j]);
// needed if first selection is already existing
if ( $("#divParameterSelection1").css("display") == "block" ) {
// append possible values
$("#selectParameter2").append(option);
// add specific label to selection
$("#divParameterSelection2").children("label").html(cp[i][0]);
// make selection visible
$("#divParameterSelection2").css("display", "block");
} else {
// append possible values
$("#selectParameter").append(option);
// add specific label to selection
$("#divParameterSelection1").children("label").html(cp[i][0]);
}
}
// make selection visible
$("#divParameterSelection1").css("display", "block");
break;
// type float needs one/two input fields and a specific label
case "FLOAT":
if ( $("#divParameterInput1").css("display") == "table-cell" ) {
$("#divParameterInput2").css("display", "table-cell");
$("#divParameterInput2").children("label").html(cp[i][0]);
setMinMax(cp[i][2], $("#inputContextParameter2"));
// display google maps
$("#divMaps").css("display", "block");
resizeMap();
} else {
$("#divParameterInput1").css("display", "table-cell");
$("#divParameterInput1").children("label").html(cp[i][0]);
setMinMax(cp[i][2], $("#inputContextParameter1"));
}
break;
// type integer needs one/two input fields and a specific label
case "INTEGER":
if ( $("#divParameterInput1").css("display") == "table-cell" ) {
$("#divParameterInput2").css("display", "table-cell");
$("#divParameterInput2").children("label").html(cp[i][0]);
} else {
$("#divParameterInput1").css("display", "table-cell");
$("#divParameterInput1").children("label").html(cp[i][0]);
}
break;
// type string needs an input field and a specific label
case "STRING":
$("#divParameterString").css("display", "block");
$("#divParameterString").children("label").html(cp[i][0]);
break;
}
// show context parameter section
$("#divContextParameter").css("display", "block");
}
}
// set minima and maxima if needed in input fields in tab "Kontextinformation"
/**
* Function set minimum and maximum values for an input field.
* @param {Array} values Contains minimum and maximum values.
* @param {Object} inputField Contains an input field.
* */
function setMinMax(values, inputField) {
var min, max = null;
for (var i=0; i<values.length; i++) {
// find minimum if given
if (values[i]["min"]) {
min = values[i]["min"];
}
// find maximum if given
if (values[i]["max"]) {
max = values[i]["max"];
}
}
// set minimum and maximum in input field
if (min && max) {
inputField.attr("min", min).attr("max", max);
}
// set minimum only
if (min && !max) {
inputField.attr("min", min);
}
// set maximum only
if (!min && max) {
inputField.attr("max", max);
}
}
// get current value from input field
/**
* Function evaluate the input value of the context parameter.
* Resets values if they are too high (maximum) or too small (minimum).
* Set marker on Google Maps if two input fields and the map are available.
* @param {Object} val Contains current input field content.
* @param {int} num Contains the specific input id number.
* */
function getParameterInput(val, num) {
// reduce to big values to maximum
if ( $("#inputContextParameter" + num)[0].hasAttribute("max") ) {
// get max attribute value
var max = $("#inputContextParameter" + num)[0].getAttribute("max");
max = parseInt(max);
if (val.value > max) {
val.value = max;
}
}
// increase to little values to minimum
if ( $("#inputContextParameter" + num)[0].hasAttribute("min") ) {
// get min attribute value
var min = $("#inputContextParameter" + num)[0].getAttribute("min");
min = parseInt(min);
if (val.value < min) {
val.value = min;
}
}
/* get values from inputs and set the marker on this point in google maps */
var lat, long;
// check if latitude is not empty
if ($("#inputContextParameter1").val()) {
lat = $("#inputContextParameter1").val();
}
// check if longitude is not empty
if ($("#inputContextParameter2").val()) {
long = $("#inputContextParameter2").val();
}
// only if both inputs have a value set marker
if ($("#inputContextParameter1").val() && $("#inputContextParameter2").val()) {
var new_LatLong = new google.maps.LatLng(lat, long);
// replace old marker and set the new one
replaceMarker2(new_LatLong);
// conter the map and set zoom factor
map.setCenter(new_LatLong);
map.setOptions({zoom: 15});
}
}
// check if all needed fields were filled with information
/**
* Function checks whether all visible selections and input fields are not empty
* @param {String} missing_content Contains an empty string.
* @param {Object} current_unit Contains the current selected unit.
* @return {Array} Returns and array which includes the string with the missing content and which an object with selected infos.
* */
function checkInformation(missing_content, current_unit) {
var selectedInfos = {};
// check selection bar "Kontextinformationen"
if ( $("#selectContextInfos").select2("data") == null ) {
// if selection bar context information is empty, concatenate it in missing_content string
missing_content += " - Kontextinformation\n";
} else {
// update JSON structure
selectedInfos.name = $("#selectContextInfos").select2("data")["text"];
selectedInfos.id = $("#selectContextInfos").select2("data").element[0].getAttribute("origin");
}
// only addable if context info doesn't exist already
for (var h=0; h<current_unit["contextInformations"].length; h++) {
if ($("#selectContextInfos").select2("data")["text"] == current_unit["contextInformations"][h]["name"]) {
alert($("#selectContextInfos").select2("data")["text"] + " existiert bereits!");
// if already exist return with error code
return ["Error999", {}];
}
}
// check selection bar "Operator"
if ( $("#selectOperator").select2("data")["text"] == "\r" ) {
// if selection bar operator is empty, concatenate it in missing_content string
missing_content += " - Operator\n";
} else {
// update JSON structure
selectedInfos.operator = $("#selectOperator").select2("data")["text"];
}
// check input "Wert" is visible AND filled with information
if ( $("#inputContextValue")[0].style.display == "block" &&
$("#inputContextValue")[0].disabled == false ) {
// if input field context value is empty, concatenate it in missing_content string
if ( $("#inputContextValue")[0].value == "" ) {
missing_content += " - Wert\n";
$("#inputContextValue").parent().addClass("has-error");
} else if ($("#inputContextValue").parent().hasClass("has-error")) {
$("#inputContextValue").parent().removeClass("has-error");
}
// update JSON structure
selectedInfos.value = $("#inputContextValue")[0].value;
// check if selection bar "Wert" is visible AND filled with information
} else if ( $("#selectPossibleValues")[0].style.display == "block" &&
$("#selectPossibleValues")[0].disabled != true ) {
// if selection bar context value is empty, concatenate it in missing_content string
if ( $("#selectPossibleValues").select2("data")["text"] == "\r" ) {
missing_content += " - Wert\n";
}
// update JSON structure
selectedInfos.value = $("#selectPossibleValues").select2("data")["text"];
}
// check selection bar "Parameter" is visible
if ( $("#divParameterSelection1")[0].style.display == "block") {
// if selection bar parameter is empty, concatenate it in missing_content string
if ($("#selectParameter").select2("data")["text"] == "\r") {
missing_content += " - " + $("#selectParameter")[0].labels[0].innerHTML + "\n";
}
// update JSON structure
selectedInfos.parameter1 = $("#selectParameter").select2("data")["text"];
}
// check selection bar "Parameter" is visible
if ( $("#divParameterSelection2")[0].style.display == "block") {
// if selection bar parameter is empty, concatenate it in missing_content string
if ($("#selectParameter2").select2("data")["text"] == "\r") {
missing_content += " - " + $("#selectParameter2")[0].labels[0].innerHTML + "\n";
}
// update JSON structure
selectedInfos.parameter2 = $("#selectParameter2").select2("data")["text"];
}
// check input context parameter 1 is visible
if ( $("#divParameterInput1")[0].style.display == "table-cell" ) {
// if input field context parameter is empty, concatenate it in missing_content string
if ($("#inputContextParameter1")[0].value == "") {
missing_content += " - " + $("#inputContextParameter1")[0].labels[0].innerHTML + "\n";
$("#inputContextParameter1").parent().addClass("has-error");
} else if ($("#inputContextParameter1").parent().hasClass("has-error")) {
$("#inputContextParameter1").parent().removeClass("has-error");
}
// update JSON structure
selectedInfos.input1 = $("#inputContextParameter1")[0].value;
}
// check input context parameter 2 is visible
if ( $("#divParameterInput2")[0].style.display == "table-cell" ) {
// if input field context parameter is empty, concatenate it in missing_content string
if ($("#inputContextParameter2")[0].value == "") {
missing_content += " - " + $("#inputContextParameter2")[0].labels[0].innerHTML + "\n";
$("#inputContextParameter2").parent().addClass("has-error");
} else if ($("#inputContextParameter2").parent().hasClass("has-error")) {
$("#inputContextParameter2").parent().removeClass("has-error");
}
// update JSON structure
selectedInfos.input2 = $("#inputContextParameter2")[0].value;
}
// check input context parameter 2 is visible
if ( $("#divParameterString")[0].style.display == "block" ) {
// if input field context parameter is empty, concatenate it in missing_content string
if ($("#inputParameterString")[0].value == "") {
missing_content += " - " + $("#inputParameterString")[0].labels[0].innerHTML + "\n";
$("#inputParameterString").parent().addClass("has-error");
} else if ($("#inputParameterString").parent().hasClass("has-error")) {
$("#inputParameterString").parent().removeClass("has-error");
}
// update JSON structure
selectedInfos.inputString = $("#inputParameterString")[0].value;
}
// create return array
var returnArray = [missing_content, selectedInfos];
return returnArray;
}
// change all colors in multi selection in tab "Kontextinformation"
/**
* Function changes colors of all selected options in multi selection bar context information.
* */
function changeColorMultiContextInfos() {
// get all names from selected options
var name = $("#s2id_selectMultiContextInfos > .select2-choices > .select2-search-choice > div");
$(name).each(function() {
// iterate over all multi selections
for (var i=0; i<array_multiSelectionContextInfos.length; i++) {
// get id
var thisID = array_multiSelectionContextInfos[i]["id"];
// needed to prevent failure, if no img exist
var title;
if ($(this).children("img").length != 0) {
// get context information title
title = $(this).children("img")[0].title;
}
/* new */
// add edit icon
var edit = $("<a>").attr("href", "#").addClass("select2-search-choice-edit").attr("tabindex", -1).attr("title", "Bearbeiten");
//var icon = $("<b>").addClass("fui-new edit-ci").attr("style", "padding-right: 10px;");
//edit.append(icon);
$(this).parent().append(edit);
$(this).parent().hover(
function() { $(this).css("width", "85px"); },
function() { var obj = $(this);
setTimeout(function() { obj.css("width", ""); }, 200);
}
);
// add event listeners
$(".select2-search-choice-edit").on("click", function(e) {
console.log("edit");
var nameContextInfo = $(this).parent()[0].title;
var operator, value, parameter1, parameter2, input1, input2, inputString;
for (var i=0; i<myAuthorSystem.length; i++) {
if ( myAuthorSystem[i].name == $("#lname")[0].innerText ) {
for (var j=0; j<myAuthorSystem[i]["units"].length; j++) {
if ( myAuthorSystem[i]["units"][j].name == global_currentInputUnitName ) {
for (var k=0; k<myAuthorSystem[i]["units"][j]["contextInformations"].length; k++) {
if ( myAuthorSystem[i]["units"][j]["contextInformations"][k].name == nameContextInfo ) {
operator = myAuthorSystem[i]["units"][j]["contextInformations"][k].operator;
if (myAuthorSystem[i]["units"][j]["contextInformations"][k].value) {
value = myAuthorSystem[i]["units"][j]["contextInformations"][k].value }
if (myAuthorSystem[i]["units"][j]["contextInformations"][k].parameter1) {
parameter1 = myAuthorSystem[i]["units"][j]["contextInformations"][k].parameter1 }
if (myAuthorSystem[i]["units"][j]["contextInformations"][k].parameter2) {
parameter2 = myAuthorSystem[i]["units"][j]["contextInformations"][k].parameter2 }
if (myAuthorSystem[i]["units"][j]["contextInformations"][k].input1) {
input1 = myAuthorSystem[i]["units"][j]["contextInformations"][k].input1 }
if (myAuthorSystem[i]["units"][j]["contextInformations"][k].input2) {
input2 = myAuthorSystem[i]["units"][j]["contextInformations"][k].input2 }
if (myAuthorSystem[i]["units"][j]["contextInformations"][k].inputString) {
inputString = myAuthorSystem[i]["units"][j]["contextInformations"][k].inputString }
break;
}
}
}
}
}
}
for (var l= 0; l<$("#selectContextInfos")[0].length; l++) {
if ( $("#selectContextInfos")[0][l].text == nameContextInfo ) {
$("#selectContextInfos").select2("data", {id:$("#selectContextInfos")[0][l].id, text:$("#selectContextInfos")[0][l].text});
}
}
$("#mainContextInfo").hide();
$("#detailContextInfo").show();
e.stopPropagation();
});
$(".select2-search-choice-close").on("click", function(e) {
console.log("delete");
e.stopPropagation();
});
$(".select2-search-choice-close").hover(
function() {$(this).attr("title", "Löschen")}
);
/* end new */
// find right one
if (array_multiSelectionContextInfos[i]["text"] == this.innerHTML || // text
array_multiSelectionContextInfos[i]["text"] == title) { // icon
// get first context class
var contextClass = array_ContextInformations[thisID][1][0];
// get specific context class color
var color = getColor(contextClass);
$(this).parent().css("background-color", color);
// set title --> tooltip if the mouse is on the icon
$(this).parent().attr("title", title);
break;
}
}
});
}
// get the specific color for each context class
/**
* Function finds specific color of a context class.
* @param {String} cc Contains a context class.
* @return {String} Returns the specific color.
* */
function getColor(cc) {
var color;
switch (cc) {
case "Lernszenario":
color = "#3287C8";
break;
case "Persönlich":
color = "#AF46C8";
break;
case "Situationsbezogen":
color = "#91F52D";
break;
case "Infrastruktur":
color = "#969696";
break;
case "Umwelt":
color = "#FADC3C";
break;
case "Ortung":
color = "#F03C32";
break;
}
return color;
}
// cleans selection bars
/**
* Function cleans a selection bar.
* @param {String} s Contains a selection bar id.
* */
function cleanSection(s) {
$(s).empty();
$(s).select2("data", {id:"\r",text:"\r"});
}
// google maps
var map;
var image;
var shadow;
var marker;
var markers = [];
$(function(){
var currentLat, currentLng;
// central point of the map
var latlng = new google.maps.LatLng('52.3877833', '13.0831297');
// creates the map
/**
* Function visualize Google Maps and marker on it.
* */
function showMap() {
markers = [];
var myOptions = {
zoom: 15, // set zoom factor
center: latlng, // center map at set coordinates
mapTypeId: 'roadmap', // set map type
mapTypeControl: true, // activate map control elements
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, // set drop down menu for control element
position: google.maps.ControlPosition.LEFT_BOTTOM // set position of control element
}
};
// flat ui style
var style = [/*{
"stylers": [{
"visibility": "off"
}]
},*/ {
"featureType": "road", // streets are white
"stylers": [{
"visibility": "on"
}, {
"color": "#ffffff"
}]
}, {
"featureType": "road.arterial", // main streets are yellow
"stylers": [{
"visibility": "on"
}, {
"color": "#fee379"
}]
}, {
"featureType": "road.highway", // highways are yellow
"stylers": [{
"visibility": "on"
}, {
"color": "#fee379"
}]
}, {
"featureType": "landscape", // landscape is grey
"stylers": [{
"visibility": "on"
}, {
"color": "#f3f4f4"
}]
}, {
"featureType": "water", // water is blue
"stylers": [{
"visibility": "on"
}, {
"color": "#7fc8ed"
}]
}, {
"featureType": "road", // road labels are grey
"elementType": "labels.text",
"stylers": [{
"visibility": "on"
}, {
"weight": 1
}, {
"color": "#7A7A7A"
}]
}, {
"featureType": "road.arterial", // road labels are light grey
"elementType": "labels.text",
"stylers": [{
"visibility": "on"
}, {
"color": "#545454"
}]
}, {
"featureType": "road.highway", // road labels are light grey
"elementType": "labels.text",
"stylers": [{
"visibility": "on"
}, {
"color": "#545454"
}]
}, {
"featureType": "poi.park", // parks are light green
"elementType": "geometry.fill",
"stylers": [{
"visibility": "on"
}, {
"color": "#83cead"
}]
}, {
"featureType": "water",
"elementType": "labels.text", // water labels are white
"stylers": [{
"visibility": "on"
}, {
"color": "#eeeeee"
}, {
"weight": 1
}]
}, /*{
"featureType": "transit",
"elementType": "labels.text", // transit labels are grey
"stylers": [{
"visibility": "on"
}, {
"color": "#B8B8B8"
}, {
"weight": 1
}]
},*/ /*{
"featureType": "poi",
"elementType": "labels.text", // poi labels are grey
"stylers": [{
"visibility": "on"
}, {
"color": "#B8B8B8"
}, {
"weight": 1
}]
},*/ /*{
"featureType": "landscape",
"elementType": "labels.text", // landscape labels are grey
"stylers": [{
"visibility": "on"
}, {
"color": "#B8B8B8"
}, {
"weight": 1
}]
},*/ /*{
"featureType": "administrative",
"elementType": "labels.text", // administrative labels are grey
"stylers": [{
"visibility": "on"
}, {
"color": "#333333"
}, {
"weight": 1
}]
},*/ {
"featureType": "landscape.man_made",
"elementType": "geometry",
"stylers": [{
"weight": 0.9
}, {
"visibility": "off"
}]
}]
// create new map object
map = new google.maps.Map($('#maps')[0], myOptions);
map.setOptions({
styles: style,
linksControl: false,
panControl: false,
mapTypeControl: true,
streetViewControl: false
});
// get flat marker image
image = {
url: 'https://dl.dropboxusercontent.com/u/814783/fiddle/marker.png',
scaledSize: new google.maps.Size(20, 40),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(10, 45)
};
// get flat marker shadow image
shadow = {
url: 'https://dl.dropboxusercontent.com/u/814783/fiddle/shadow.png',
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(-2, 36)
};
// create marker
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image,
shadow: shadow
});
// marker not set on map per default
marker.setMap(null);
// set new marker if user clicked into the map
google.maps.event.addListener(map, "click", function(e) {
replaceMarker(e.latLng);
currentLat = e.latLng.lat();
$("#inputContextParameter1")[0].value = currentLat;
currentLng = e.latLng.lng();
$("#inputContextParameter2")[0].value = currentLng;
});
// delete old and set new marker
/**
* Function deletes old and set new google maps marker.
* @param {Object} location Contains location of a google maps marker.
* */
function replaceMarker(location) {
// deletion
marker.setMap(null);
for (var i = 0, mark; mark = markers[i]; i++) {
mark.setMap(null);
}
markers = [];
// set new marker
marker = new google.maps.Marker({
position: location,
map: map,
icon: image,
shadow: shadow
});
}
/* add search box */
// Create the search box and link it to the UI element.
var input = /** @type {HTMLInputElement} */(
document.getElementById('pac-input')
);
// add input to map
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** @type {HTMLInputElement} */(input)
);
//var autocomplete = new google.maps.places.Autocomplete(input);
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, mark; mark = markers[i]; i++) {
mark.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
// add marker
markers.push(marker);
bounds.extend(place.geometry.location);
// set input fields with coordinates
$("#inputContextParameter1")[0].value = place.geometry.location["k"];
$("#inputContextParameter2")[0].value = place.geometry.location["D"];
}
map.fitBounds(bounds);
map.setOptions({zoom: 15});
});
// [END region_getplaces]
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
/* end search box */
}
// resize map due to map opening
/*function resizeMap() {
if (typeof map == "undefined") return;
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
}*/
// add event listeners showMap and resizeMap
google.maps.event.addDomListener(window, 'load', showMap);
google.maps.event.addDomListener(window, "resize", resizeMap());
});
// resize map due to map opening
/**
* Function resize map if it becomes visible.
* */
function resizeMap() {
if (typeof map == "undefined") return;
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
map.setOptions({mapTypeControl: true});
}
// delete old and set new marker
/**
* Function deletes old and set new google maps marker.
* @param {Object} location Contains location of a google maps marker.
* */
function replaceMarker2(location) {
// clean map and delete marker
marker.setMap(null);
for (var i = 0, mark; mark = markers[i]; i++) {
mark.setMap(null);
}
// set new marker
markers = [];
marker = new google.maps.Marker({
position: location,
map: map,
icon: image,
shadow: shadow
});
} |
/*global module, define */
( function( root, factory ) {
if ( typeof module === "object" && module.exports ) {
// Node, or CommonJS-Like environments
module.exports = factory( require( "react" ), require( "postal" ) );
} else if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "react", "postal" ], factory );
} else {
// Browser globals
root.React.postal = factory( root.React, root.postal );
}
}( this, function( React, postal ) {
return {
publish: function( topic, data ) {
postal.publish( {
channel: this.props.channel,
topic: topic,
data: data
} );
},
subscribe: function( topic, callback ) {
if ( !this.hasOwnProperty( "subscriptions" ) ) {
this.subscriptions = {};
}
if ( !this.subscriptions.hasOwnProperty( topic ) ) {
this.subscriptions[ topic ] = postal.subscribe( {
channel: this.props.channel,
topic: topic,
callback: callback
} ).withContext( this );
}
},
disposeSubscriptions: function() {
var key;
for ( key in this.subscriptions ) {
if ( this.subscriptions.hasOwnProperty( key ) ) {
this.subscriptions[ key ].unsubscribe();
}
}
this.subscriptions = {};
}
};
} ) ); |
/**
* @file Registration of all WebUI core services
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
angular.module('pipCore', [
'pipUtils',
'pipErrors',
'pipTransactions',
'pipTranslate',
'pipState',
'pipTimer',
'pipAssert',
'pipDebug',
'pipDateFormat',
'pipDateTimeFilters',
'pipTranslateFilters',
'pipClearErrors',
'pipTheme',
'pipFocused',
'pipSelected',
'pipInfiniteScroll',
'pipDraggable',
'pipUnsavedChanges',
'pipFabTooltipVisibility',
]);
})();
/**
* @file Special error handling for forms
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module('pipClearErrors', []);
thisModule.directive('pipClearErrors', function () {
return {
restrict: 'A',
require: ['ngModel', '^?form'],
link: function ($scope, $element, $attrs, $ctrls) {
var
fieldController = $ctrls[0],
formController = $ctrls[1];
$scope.$watch($attrs.ngModel, function (newValue) {
clearFieldErrors();
clearFormErrors();
});
//-------------------
function clearFieldErrors() {
var errors = fieldController.$error;
for (var prop in errors) {
if (errors.hasOwnProperty(prop) && prop.substring(0, 6) == 'ERROR_') {
fieldController.$setValidity(prop, true);
}
};
}
function clearFormErrors() {
formController.$serverError = {};
};
}
};
});
})();
/**
* @file Drag & drop attachable behavior
* @description
* Based on https://github.com/fatlinesofcode/pipDraggable
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module("pipDraggable", ['pipUtils']);
thisModule.service('pipDraggable', function () {
var scope = this;
scope.inputEvent = function (event) {
if (angular.isDefined(event.touches)) {
return event.touches[0];
}
//Checking both is not redundent. If only check if touches isDefined, angularjs isDefnied will return error and stop the remaining scripty if event.originalEvent is not defined.
else if (angular.isDefined(event.originalEvent) && angular.isDefined(event.originalEvent.touches)) {
return event.originalEvent.touches[0];
}
return event;
};
});
thisModule.directive('pipDrag', ['$rootScope', '$parse', '$document', '$window', 'pipDraggable', 'pipUtils', function ($rootScope, $parse, $document, $window, pipDraggable, pipUtils) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.value = attrs.ngDrag;
var offset, _centerAnchor = false, _mx, _my, _tx, _ty, _mrx, _mry;
var _hasTouch = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
var _pressEvents = 'touchstart mousedown';
var _moveEvents = 'touchmove mousemove';
var _releaseEvents = 'touchend mouseup';
var _dragHandle;
// to identify the element in order to prevent getting superflous events when a single element has both drag and drop directives on it.
var _myid = scope.$id;
var _data = null;
var _dragOffset = null;
var _dragEnabled = false;
var _pressTimer = null;
var onDragStartCallback = $parse(attrs.pipDragStart) || null;
var onDragStopCallback = $parse(attrs.pipDragStop) || null;
var onDragSuccessCallback = $parse(attrs.pipDragSuccess) || null;
var allowTransform = angular.isDefined(attrs.allowTransform) ? scope.$eval(attrs.allowTransform) : false;
var getDragData = $parse(attrs.pipDragData);
var
verticalScroll = pipUtils.toBoolean(attrs.pipVerticalScroll) || true,
horizontalScroll = pipUtils.toBoolean(attrs.pipHorizontalScroll) || true,
activationDistance = parseFloat(attrs.pipActivationDistance) || 75,
scrollDistance = parseFloat(attrs.pipScrollDistance) || 50,
scrollParent = false,
scrollContainer = angular.element(window),
scrollContainerGetter = $parse(attrs.pipScrollContainer);
// deregistration function for mouse move events in $rootScope triggered by jqLite trigger handler
var _deregisterRootMoveListener = angular.noop;
var initialize = function () {
element.attr('pip-draggable', 'false'); // prevent native drag
// check to see if drag handle(s) was specified
// if querySelectorAll is available, we use this instead of find
// as JQLite find is limited to tagnames
if (element[0].querySelectorAll) {
var dragHandles = angular.element(element[0].querySelectorAll('[pip-drag-handle]'));
} else {
var dragHandles = element.find('[pip-drag-handle]');
}
if (dragHandles.length) {
_dragHandle = dragHandles;
}
toggleListeners(true);
// Initialize scroll container
if (scrollParent) {
scrollContainer = angular.element($element.parent());
} else if (attrs.pipScrollContainer) {
scrollContainer = angular.element(scrollContainerGetter(scope));
} else {
scrollContainer = angular.element(window);
}
};
var toggleListeners = function (enable) {
if (!enable)return;
// add listeners.
scope.$on('$destroy', onDestroy);
scope.$watch(attrs.pipDrag, onEnableChange);
scope.$watch(attrs.pipCenterAnchor, onCenterAnchor);
// wire up touch events
if (_dragHandle) {
// handle(s) specified, use those to initiate drag
_dragHandle.on(_pressEvents, onpress);
} else {
// no handle(s) specified, use the element as the handle
element.on(_pressEvents, onpress);
}
if (!_hasTouch && element[0].nodeName.toLowerCase() == "img") {
element.on('mousedown', function () {
return false;
}); // prevent native drag for images
}
};
var onDestroy = function (enable) {
toggleListeners(false);
};
var onEnableChange = function (newVal, oldVal) {
_dragEnabled = (newVal);
};
var onCenterAnchor = function (newVal, oldVal) {
if (angular.isDefined(newVal))
_centerAnchor = (newVal || 'true');
};
var isClickableElement = function (evt) {
return (
angular.isDefined(angular.element(evt.target).attr("pip-cancel-drag"))
);
};
/*
* When the element is clicked start the drag behaviour
* On touch devices as a small delay so as not to prevent native window scrolling
*/
var onpress = function (evt) {
if (!_dragEnabled)return;
if (isClickableElement(evt)) {
return;
}
if (evt.type == "mousedown" && evt.button != 0) {
// Do not start dragging on right-click
return;
}
if (_hasTouch) {
cancelPress();
_pressTimer = setTimeout(function () {
cancelPress();
onlongpress(evt);
}, 100);
$document.on(_moveEvents, cancelPress);
$document.on(_releaseEvents, cancelPress);
} else {
onlongpress(evt);
}
};
var cancelPress = function () {
clearTimeout(_pressTimer);
$document.off(_moveEvents, cancelPress);
$document.off(_releaseEvents, cancelPress);
};
var onlongpress = function (evt) {
if (!_dragEnabled)return;
evt.preventDefault();
offset = element[0].getBoundingClientRect();
if (allowTransform)
_dragOffset = offset;
else {
_dragOffset = {left: document.body.scrollLeft, top: document.body.scrollTop};
}
element.centerX = element[0].offsetWidth / 2;
element.centerY = element[0].offsetHeight / 2;
_mx = pipDraggable.inputEvent(evt).pageX;
_my = pipDraggable.inputEvent(evt).pageY;
_mrx = _mx - offset.left;
_mry = _my - offset.top;
if (_centerAnchor) {
_tx = _mx - element.centerX - $window.pageXOffset;
_ty = _my - element.centerY - $window.pageYOffset;
} else {
_tx = _mx - _mrx - $window.pageXOffset;
_ty = _my - _mry - $window.pageYOffset;
}
$document.on(_moveEvents, onmove);
$document.on(_releaseEvents, onrelease);
// This event is used to receive manually triggered mouse move events
// jqLite unfortunately only supports triggerHandler(...)
// See http://api.jquery.com/triggerHandler/
// _deregisterRootMoveListener = $rootScope.$on('draggable:_triggerHandlerMove', onmove);
_deregisterRootMoveListener = $rootScope.$on('draggable:_triggerHandlerMove', function (event, origEvent) {
onmove(origEvent);
});
};
var onmove = function (evt) {
if (!_dragEnabled)return;
evt.preventDefault();
if (!element.hasClass('pip-dragging')) {
_data = getDragData(scope);
element.addClass('pip-dragging');
$rootScope.$broadcast('draggable:start', {
x: _mx,
y: _my,
tx: _tx,
ty: _ty,
event: evt,
element: element,
data: _data
});
if (onDragStartCallback) {
scope.$apply(function () {
onDragStartCallback(scope, {$data: _data, $event: evt});
});
}
}
_mx = pipDraggable.inputEvent(evt).pageX;
_my = pipDraggable.inputEvent(evt).pageY;
if (horizontalScroll || verticalScroll) {
dragToScroll();
}
if (_centerAnchor) {
_tx = _mx - element.centerX - _dragOffset.left;
_ty = _my - element.centerY - _dragOffset.top;
} else {
_tx = _mx - _mrx - _dragOffset.left;
_ty = _my - _mry - _dragOffset.top;
}
moveElement(_tx, _ty);
$rootScope.$broadcast('draggable:move', {
x: _mx,
y: _my,
tx: _tx,
ty: _ty,
event: evt,
element: element,
data: _data,
uid: _myid,
dragOffset: _dragOffset
});
};
var onrelease = function (evt) {
if (!_dragEnabled)
return;
evt.preventDefault();
$rootScope.$broadcast('draggable:end', {
x: _mx,
y: _my,
tx: _tx,
ty: _ty,
event: evt,
element: element,
data: _data,
callback: onDragComplete,
uid: _myid
});
element.removeClass('pip-dragging');
element.parent().find('.pip-drag-enter').removeClass('pip-drag-enter');
reset();
$document.off(_moveEvents, onmove);
$document.off(_releaseEvents, onrelease);
if (onDragStopCallback) {
scope.$apply(function () {
onDragStopCallback(scope, {$data: _data, $event: evt});
});
}
_deregisterRootMoveListener();
};
var onDragComplete = function (evt) {
if (!onDragSuccessCallback)return;
scope.$apply(function () {
onDragSuccessCallback(scope, {$data: _data, $event: evt});
});
};
var reset = function () {
if (allowTransform)
element.css({transform: '', 'z-index': '', '-webkit-transform': '', '-ms-transform': ''});
else
element.css({'position': '', top: '', left: '', 'z-index': '', width: ''});
};
var moveElement = function (x, y) {
var eWidth = element.css('width');
if (allowTransform) {
element.css({
transform: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ' + x + ', ' + y + ', 0, 1)',
'z-index': 99999,
'-webkit-transform': 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ' + x + ', ' + y + ', 0, 1)',
'-ms-transform': 'matrix(1, 0, 0, 1, ' + x + ', ' + y + ')'
});
} else {
element.css({
'left': x + 'px',
'top': y + 'px',
'position': 'fixed',
'z-index': 100,
width: eWidth
});
}
};
var dragToScroll = function () {
var scrollX = 0, scrollY = 0,
offset = function (element) {
return element.offset() || {left: 0, top: 0};
};
if (horizontalScroll) {
var
containerLeft = offset(scrollContainer).left,
containerWidth = scrollContainer.innerWidth(),
containerRight = containerLeft + containerWidth;
if ((_mx - containerLeft) < activationDistance) {
scrollX = -scrollDistance;
}
else if ((containerRight - _mx) < activationDistance) {
scrollX = scrollDistance;
}
}
if (verticalScroll) {
var
containerTop = offset(scrollContainer).top,
containerHeight = scrollContainer.innerHeight(),
containerBottom = containerTop + containerHeight;
if ((_my - containerTop) < activationDistance) {
scrollY = -scrollDistance + 30;
}
else if ((containerBottom - _my) < activationDistance) {
scrollY = scrollDistance - 30;
}
}
if (scrollX !== 0 || scrollY !== 0) {
var
containerScrollLeft = scrollContainer.scrollLeft(),
containerScrollTop = scrollContainer.scrollTop();
scrollContainer.scrollLeft(containerScrollLeft + scrollX);
scrollContainer.scrollTop(containerScrollTop + scrollY);
}
};
initialize();
}
};
}]);
thisModule.directive('pipDrop', ['$parse', '$timeout', '$window', '$document', 'pipDraggable', function ($parse, $timeout, $window, $document, pipDraggable) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.value = attrs.pipDrop;
scope.isTouching = false;
var _lastDropTouch = null;
var _myid = scope.$id;
var _dropEnabled = false;
var onDropCallback = $parse(attrs.pipDropSuccess);// || function(){};
var onDragStartCallback = $parse(attrs.pipDragStart);
var onDragStopCallback = $parse(attrs.pipDragStop);
var onDragMoveCallback = $parse(attrs.pipDragMove);
var initialize = function () {
toggleListeners(true);
};
var toggleListeners = function (enable) {
// remove listeners
if (!enable)return;
// add listeners.
scope.$watch(attrs.pipDrop, onEnableChange);
scope.$on('$destroy', onDestroy);
scope.$on('draggable:start', onDragStart);
scope.$on('draggable:move', onDragMove);
scope.$on('draggable:end', onDragEnd);
};
var onDestroy = function (enable) {
toggleListeners(false);
};
var onEnableChange = function (newVal, oldVal) {
_dropEnabled = newVal;
};
var onDragStart = function (evt, obj) {
if (!_dropEnabled)return;
isTouching(obj.x, obj.y, obj.element);
if (attrs.pipDragStart) {
$timeout(function () {
onDragStartCallback(scope, {$data: obj.data, $event: obj});
});
}
};
var onDragMove = function (evt, obj) {
if (!_dropEnabled)return;
isTouching(obj.x, obj.y, obj.element);
if (attrs.pipDragMove) {
$timeout(function () {
onDragMoveCallback(scope, {$data: obj.data, $event: obj});
});
}
};
var onDragEnd = function (evt, obj) {
// don't listen to drop events if this is the element being dragged
// only update the styles and return
if (!_dropEnabled || _myid === obj.uid) {
updateDragStyles(false, obj.element);
return;
}
if (isTouching(obj.x, obj.y, obj.element)) {
// call the pipDraggable pipDragSuccess element callback
if (obj.callback) {
obj.callback(obj);
}
if (attrs.pipDropSuccess) {
$timeout(function () {
onDropCallback(scope, {
$data: obj.data,
$event: obj,
$target: scope.$eval(scope.value)
});
});
}
}
if (attrs.pipDragStop) {
$timeout(function () {
onDragStopCallback(scope, {$data: obj.data, $event: obj});
});
}
updateDragStyles(false, obj.element);
};
var isTouching = function (mouseX, mouseY, dragElement) {
var touching = hitTest(mouseX, mouseY);
scope.isTouching = touching;
if (touching) {
_lastDropTouch = element;
}
updateDragStyles(touching, dragElement);
return touching;
};
var updateDragStyles = function (touching, dragElement) {
if (touching) {
element.addClass('pip-drag-enter');
dragElement.addClass('pip-drag-over');
} else if (_lastDropTouch == element) {
_lastDropTouch = null;
element.removeClass('pip-drag-enter');
dragElement.removeClass('pip-drag-over');
}
};
var hitTest = function (x, y) {
var bounds = element[0].getBoundingClientRect();
x -= $document[0].body.scrollLeft + $document[0].documentElement.scrollLeft;
y -= $document[0].body.scrollTop + $document[0].documentElement.scrollTop;
return x >= bounds.left
&& x <= bounds.right
&& y <= bounds.bottom
&& y >= bounds.top;
};
initialize();
}
};
}]);
//thisModule.directive('pipDragClone', ['$parse', '$timeout', 'pipDraggable', function ($parse, $timeout, pipDraggable) {
// return {
// restrict: 'A',
// link: function (scope, element, attrs) {
// var img, _allowClone = true;
// var _dragOffset = null;
// scope.clonedData = {};
// var initialize = function () {
//
// img = element.find('img');
// element.attr('pip-draggable', 'false');
// img.attr('draggable', 'false');
// reset();
// toggleListeners(true);
// };
//
//
// var toggleListeners = function (enable) {
// // remove listeners
//
// if (!enable)return;
// // add listeners.
// scope.$on('draggable:start', onDragStart);
// scope.$on('draggable:move', onDragMove);
// scope.$on('draggable:end', onDragEnd);
// preventContextMenu();
//
// };
// var preventContextMenu = function () {
// // element.off('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
// img.off('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
// // element.on('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
// img.on('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
// };
// var onDragStart = function (evt, obj, elm) {
// _allowClone = true;
// if (angular.isDefined(obj.data.allowClone)) {
// _allowClone = obj.data.allowClone;
// }
// if (_allowClone) {
// scope.$apply(function () {
// scope.clonedData = obj.data;
// });
// element.css('width', obj.element[0].offsetWidth);
// element.css('height', obj.element[0].offsetHeight);
//
// moveElement(obj.tx, obj.ty);
// }
//
// };
// var onDragMove = function (evt, obj) {
// if (_allowClone) {
//
// _tx = obj.tx + obj.dragOffset.left;
// _ty = obj.ty + obj.dragOffset.top;
//
// moveElement(_tx, _ty);
// }
// };
// var onDragEnd = function (evt, obj) {
// //moveElement(obj.tx,obj.ty);
// if (_allowClone) {
// reset();
// }
// };
//
// var reset = function () {
// element.css({left: 0, top: 0, position: 'fixed', 'z-index': -1, visibility: 'hidden'});
// };
// var moveElement = function (x, y) {
// element.css({
// transform: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ' + x + ', ' + y + ', 0, 1)',
// 'z-index': 99999,
// 'visibility': 'visible',
// '-webkit-transform': 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ' + x + ', ' + y + ', 0, 1)',
// '-ms-transform': 'matrix(1, 0, 0, 1, ' + x + ', ' + y + ')'
// //,margin: '0' don't monkey with the margin,
// });
// };
//
// var absorbEvent_ = function (event) {
// var e = event;//.originalEvent;
// e.preventDefault && e.preventDefault();
// e.stopPropagation && e.stopPropagation();
// e.cancelBubble = true;
// e.returnValue = false;
// return false;
// };
//
// initialize();
// }
// };
//}]);
thisModule.directive('pipPreventDrag', ['$parse', '$timeout', function ($parse, $timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var initialize = function () {
element.attr('pip-draggable', 'false');
toggleListeners(true);
};
var toggleListeners = function (enable) {
// remove listeners
if (!enable)return;
// add listeners.
element.on('mousedown touchstart touchmove touchend touchcancel', absorbEvent_);
};
var absorbEvent_ = function (event) {
var e = event.originalEvent;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
};
initialize();
}
};
}]);
thisModule.directive('pipCancelDrag', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.find('*').attr('pip-cancel-drag', 'pip-cancel-drag');
}
};
});
})();
/**
* @file Directive to show confirmation dialog when user tries to leave page with unsaved changes.
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function(){
'use strict';
var thisModule = angular.module("pipFabTooltipVisibility", []);
thisModule.directive("pipFabTooltipVisibility", ['$parse', '$timeout', function ($parse, $timeout) {
return {
restrict: 'A',
scope: false,
controller: ['$scope', '$attrs', function($scope, $attrs) {
var trigGetter = $parse($attrs.pipFabTooltipVisibility),
showGetter = $parse($attrs.pipFabShowTooltip),
showSetter = showGetter.assign;
$scope.$watch(trigGetter, function(isOpen) {
if (isOpen) {
$timeout(function() {
showSetter($scope, isOpen);
}, 600);
} else {
showSetter($scope, isOpen);
}
});
}]
};
}]);
})();
/**
* @file Keyboard navigation over few focusable controls
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module("pipFocused", []);
thisModule.directive('pipFocused', ['$timeout', '$mdConstant', function($timeout, $mdConstant) {
return {
require: "?ngModel",
link: function ($scope, $element, $attrs) {
var controls, controlsLength,
withHidden = $attrs.pipWithHidden;
$timeout(init);
$element.on('keydown', keydownListener);
$scope.$watch($attrs.ngModel, function () {
$timeout(init);
}, true);
function init() {
var selector = withHidden ? '.pip-focusable' : '.pip-focusable:visible';
controls = $element.find(selector);
controlsLength = controls.length;
// add needed event listeners
controls.on('focus', function () {
$element.addClass('pip-focused-container');
$(this).addClass('md-focused');
}).on('focusout', function () {
$element.removeClass('pip-focused-container');
});
}
function keydownListener(e) {
var keyCode = e.which || e.keyCode;
// Check control keyCode
if (keyCode == $mdConstant.KEY_CODE.LEFT_ARROW ||
keyCode == $mdConstant.KEY_CODE.UP_ARROW ||
keyCode == $mdConstant.KEY_CODE.RIGHT_ARROW ||
keyCode == $mdConstant.KEY_CODE.DOWN_ARROW) {
e.preventDefault();
var
increment = (keyCode == $mdConstant.KEY_CODE.RIGHT_ARROW || keyCode == $mdConstant.KEY_CODE.DOWN_ARROW) ? 1 : -1,
moveToControl = controls.index(controls.filter(".md-focused")) + increment;
// Move focus to next control
if (moveToControl >= 0 && moveToControl < controlsLength) {
controls[moveToControl].focus();
}
}
}
}
};
}]);
})();
/**
* @file Infinite scrolling behavior
* @description
* Modified from https://github.com/sroze/ngInfiniteScroll
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module("pipInfiniteScroll", []);
thisModule.directive('pipInfiniteScroll',
['$rootScope', '$window', '$interval', '$parse', function($rootScope, $window, $interval, $parse) {
var THROTTLE_MILLISECONDS = 500;
return {
scope: {
pipInfiniteScroll: '&',
pipScrollContainer: '=',
pipScrollDistance: '=',
pipScrollDisabled: '=',
pipScrollUseDocumentBottom: '=',
pipScrollListenForEvent: '@'
},
link: function($scope, $element, $attrs) {
var
checkWhenEnabled = null,
scrollContainer,
immediateCheck = true,
scrollDistance = null,
scrollEnabled = null,
unregisterEventListener = null,
useDocumentBottom = false,
windowElement = angular.element($window);
function height(element) {
element = element[0] || element;
if (isNaN(element.offsetHeight)) {
return element.document.documentElement.clientHeight;
} else {
return element.offsetHeight;
}
};
function offsetTop(element) {
if (!element[0].getBoundingClientRect || element.css('none')) {
return;
}
return element[0].getBoundingClientRect().top + pageYOffset(element);
};
function pageYOffset(element) {
element = element[0] || element;
if (isNaN(window.pageYOffset)) {
return element.document.documentElement.scrollTop;
} else {
return element.ownerDocument.defaultView.pageYOffset;
}
};
var onContainerScroll = function() {
var
containerBottom,
containerTopOffset,
elementBottom,
remaining,
shouldScroll;
if (scrollContainer === windowElement) {
containerBottom = height(scrollContainer) + pageYOffset(scrollContainer[0].document.documentElement);
elementBottom = offsetTop($element) + height($element);
} else {
containerBottom = height(scrollContainer);
containerTopOffset = 0;
if (offsetTop(scrollContainer) !== void 0) {
containerTopOffset = offsetTop(scrollContainer);
}
elementBottom = offsetTop($element) - containerTopOffset + height($element);
}
if (useDocumentBottom) {
elementBottom = height(($element[0].ownerDocument || $element[0].document).documentElement);
}
remaining = elementBottom - containerBottom;
shouldScroll = remaining <= height(scrollContainer) * scrollDistance + 1;
if (shouldScroll) {
checkWhenEnabled = true;
if (scrollEnabled) {
if ($scope.$$phase || $rootScope.$$phase) {
return $scope.pipInfiniteScroll();
} else {
return $scope.$apply($scope.pipInfiniteScroll);
}
}
} else {
return checkWhenEnabled = false;
}
};
if (THROTTLE_MILLISECONDS != null) {
onContainerScroll = _.throttle(onContainerScroll, THROTTLE_MILLISECONDS);
}
$scope.$on('$destroy', function() {
scrollContainer.unbind('scroll', onContainerScroll);
if (unregisterEventListener != null) {
unregisterEventListener();
return unregisterEventListener = null;
}
});
function handleScrollDistance(v) {
return scrollDistance = parseFloat(v) || 0;
};
$scope.$watch('pipScrollDistance', handleScrollDistance);
handleScrollDistance($scope.pipScrollDistance);
function handleScrollDisabled(v) {
scrollEnabled = !v;
if (scrollEnabled && checkWhenEnabled) {
checkWhenEnabled = false;
return onContainerScroll();
}
};
$scope.$watch('pipScrollDisabled', handleScrollDisabled);
handleScrollDisabled($scope.pipScrollDisabled);
function handleScrollUseDocumentBottom(v) {
return useDocumentBottom = v;
};
$scope.$watch('pipScrollUseDocumentBottom', handleScrollUseDocumentBottom);
handleScrollUseDocumentBottom($scope.pipScrollUseDocumentBottom);
function changeContainer(newContainer) {
if (scrollContainer != null) {
scrollContainer.unbind('scroll', onContainerScroll);
}
scrollContainer = newContainer;
if (newContainer != null) {
return scrollContainer.bind('scroll', onContainerScroll);
}
};
changeContainer(windowElement);
if ($scope.pipScrollListenForEvent) {
unregisterEventListener = $rootScope.$on($scope.pipScrollListenForEvent, onContainerScroll);
}
function handleScrollContainer(newContainer) {
if ((newContainer == null) || newContainer.length === 0) {
return;
}
if (newContainer instanceof HTMLElement) {
newContainer = angular.element(newContainer);
} else if (typeof newContainer.append === 'function') {
newContainer = angular.element(newContainer[newContainer.length - 1]);
} else if (typeof newContainer === 'string') {
newContainer = $element.parents().find(newContainer);
}
if (newContainer != null && (!Array.isArray(newContainer) ||
(Array.isArray(newContainer) && newContainer.length > 0))) {
return changeContainer(newContainer);
} else {
throw new Error("Invalid pip-scroll-container attribute.");
}
};
$scope.$watch('pipScrollContainer', function (newContainer) {
if (newContainer !== scrollContainer)
handleScrollContainer(newContainer);
});
handleScrollContainer($scope.pipScrollContainer || []);
if ($attrs.pipScrollParent != null) {
changeContainer(angular.element($element.parent()));
}
if ($attrs.pipScrolImmediateCheck != null) {
immediateCheck = $scope.$eval($attrs.pipScrolImmediateCheck);
}
return $interval((function() {
if (immediateCheck) {
return onContainerScroll();
}
}), 0, 1);
}
}
}]
);
})();
/**
* @file Keyboard navigation with scrolling over non-focusable controls
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module("pipSelected", ['pipUtils']);
thisModule.directive('pipSelected',['$parse', 'pipUtils', '$mdConstant', '$timeout', function ($parse, pipUtils, $mdConstant, $timeout) {
return {
restrict: 'A',
scope: false,
link: function ($scope, $element, $attrs) {
var
indexGetter = $attrs.pipSelected ? $parse($attrs.pipSelected) : null,
indexSetter = indexGetter ? indexGetter.assign : null,
idGetter = $attrs.pipSelectedId ? $parse($attrs.pipSelectedId) : null,
idSetter = idGetter ? idGetter.assign : null,
changeGetter = $attrs.pipSelect ? $parse($attrs.pipSelect) : null,
enterSpaceGetter = $attrs.pipEnterSpacePress ? $parse($attrs.pipEnterSpacePress) : null,
noScroll = pipUtils.toBoolean($attrs.pipNoScroll),
modifier = pipUtils.toBoolean($attrs.pipSkipHidden) ? ':visible' : '',
className = pipUtils.toBoolean($attrs.pipTreeList) ? '.pip-selectable-tree' : '.pip-selectable',
selectedIndex = indexGetter($scope),
currentElementTabinex = $element.attr('tabindex'),
pipSelectedWatch = $attrs.pipSelectedWatch;
// Set tabindex if it's not set yet
$element.attr('tabindex', currentElementTabinex || 0);
// Watch selected item index
if (!pipUtils.toBoolean($attrs.pipTreeList)) {
$scope.$watch(indexGetter, function(newSelectedIndex) {
selectItem({itemIndex: newSelectedIndex});
});
} else {
$scope.$watch(idGetter, function(newSelectedId) {
setTimeout(function () {
selectItem({itemId: newSelectedId, raiseEvent: true});
}, 0);
});
}
// Watch resync selection
if (pipSelectedWatch) {
$scope.$watch(pipSelectedWatch, function() {
// Delay update to allow ng-repeat to update DOM
setTimeout(function() {
selectedIndex = indexGetter($scope);
selectItem({itemIndex: selectedIndex});
}, 100);
});
}
// Select item defined by index
selectItem({itemIndex: selectedIndex, items: $element.find(className)});
// Functions and listeners
function selectItem(itemParams) {
var itemIndex = itemParams.itemIndex,
itemId = itemParams.itemId,
items = itemParams.items || $element.find(className + modifier),
itemsLength = items.length,
item = (function () {
if (itemParams.item) return itemParams.item;
if (itemIndex === undefined && itemIndex === -1) {
itemIndex = items.index(items.filter('[pip-id=' + itemId + ']'));
}
if (itemIndex >= 0 && itemIndex < itemsLength) {
return items[itemIndex]
}
}()),
raiseEvent = itemParams.raiseEvent;
if (item) {
$element.find(className).removeClass('selected md-focused');
item = angular.element(item)
.addClass('selected md-focused')
.focus(); // todo сдвигает список тут, на первом проходе
if (!noScroll) scrollToItem(item);
if (raiseEvent) defineSelectedIndex(items);
}
};
function defineSelectedIndex(items) {
var oldSelectedIndex = selectedIndex;
selectedIndex = -1;
for (var index = 0; index < items.length; index++) {
if ($(items[index]).hasClass('selected')) {
selectedIndex = index;
break;
}
}
// Execute callback to notify about item select
if (oldSelectedIndex != selectedIndex && selectedIndex !== -1) {
$scope.$apply(updateIndex);
}
function updateIndex() {
var selectedItem = angular.element(items[selectedIndex]),
selectedId = selectedItem.attr('pip-id');
if (indexSetter) indexSetter($scope, selectedIndex);
if (idSetter) idSetter($scope, selectedId);
if (changeGetter) {
changeGetter($scope, {
$event: {
target: $element,
item: selectedItem,
index: selectedIndex,
id: selectedId,
newIndex: selectedIndex,
oldIndex: oldSelectedIndex
}
});
}
};
};
function scrollToItem($item) {
if (noScroll) return;
var
containerTop = $element.offset().top,
containerHeight = $element.height(),
containerBottom = containerTop + containerHeight,
itemTop = $item.offset().top,
itemHeight = $item.outerHeight(true),
itemBottom = itemTop + itemHeight,
containerScrollTop = $element.scrollTop();
if (containerTop > itemTop) {
$element.scrollTop(containerScrollTop + itemTop - containerTop);
}
else if (containerBottom < itemBottom) {
$element.scrollTop(containerScrollTop + itemBottom - containerBottom);
}
};
$element.on('click touchstart', className, function (event) {
selectItem({item: event.currentTarget, raiseEvent: true});
});
$element.on('keydown', function (e) {
var keyCode = e.which || e.keyCode;
// Check control keyCode
if (keyCode == $mdConstant.KEY_CODE.ENTER || keyCode == $mdConstant.KEY_CODE.SPACE) {
e.preventDefault();
e.stopPropagation();
if (enterSpaceGetter) {
enterSpaceGetter($scope, {
$event: {
target: $element,
index: selectedIndex,
item: $element.find('.selected')
}
});
}
} else
if (keyCode == $mdConstant.KEY_CODE.LEFT_ARROW || keyCode == $mdConstant.KEY_CODE.RIGHT_ARROW ||
keyCode == $mdConstant.KEY_CODE.UP_ARROW || keyCode == $mdConstant.KEY_CODE.DOWN_ARROW) {
e.preventDefault();
e.stopPropagation();
// Get next selectable control index
var items = $element.find(className + modifier),
inc = (keyCode == $mdConstant.KEY_CODE.RIGHT_ARROW || keyCode == $mdConstant.KEY_CODE.DOWN_ARROW) ? 1 : -1,
newSelectedIndex = selectedIndex + inc;
// Set next control as selected
selectItem({itemIndex: newSelectedIndex, items: items, raiseEvent: true});
}
});
$element.on('focusin', function (event) {
// Choose selected element
var items,
selectedItem = $element.find(className + '.selected');
selectedItem.addClass('md-focused');
// If there are not selected elements then pick the first one
if (selectedItem.length === 0) {
selectedIndex = indexGetter($scope);
items = $element.find(className + modifier);
selectItem({itemIndex: selectedIndex || 0, items: items, raiseEvent: true});
}
});
$element.on('focusout', function (event) {
$element.find(className + '.md-focused' + modifier).removeClass('md-focused');
});
}
};
}]);
})();
/**
* @file Directive to show confirmation dialog when user tries to leave page with unsaved changes.
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function(){
'use strict';
var thisModule = angular.module("pipUnsavedChanges", []);
thisModule.directive("pipUnsavedChanges", ['$window', '$rootScope', function ($window, $rootScope) {
return {
restrict: 'AE',
scope: {
unsavedChangesAvailable: '&pipUnsavedChangesAvailable',
unsavedChangesMessage: '@pipUnsavedChangesMessage',
afterLeave: '&pipUnsavedChangesAfterLeave'
},
link: function($scope) {
$window.onbeforeunload = function() {
if ($scope.unsavedChangesAvailable()) {
$rootScope.$routing = false;
return $scope.unsavedChangesMessage;
}
};
var unbindFunc = $scope.$on('$stateChangeStart', function(event) {
if ($scope.unsavedChangesAvailable() && !$window.confirm($scope.unsavedChangesMessage)) {
$rootScope.$routing = false;
event.preventDefault();
} else {
_.isFunction($scope.afterLeave) && $scope.afterLeave();
}
});
$scope.$on('$destroy', function() {
$window.onbeforeunload = null;
unbindFunc();
});
}
};
}]);
})();
/**
* @file Date formatting service
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipDateFormat', ['pipUtils', 'pipTranslate']);
thisModule.config(['pipTranslateProvider', function(pipTranslateProvider) {
pipTranslateProvider.translations('en', {
// Months - 'MONTH_' + monthIndex
// start at 0 to match JS date format
'MONTH_1': 'January',
'MONTH_2': 'February',
'MONTH_3': 'March',
'MONTH_4': 'April',
'MONTH_5': 'May',
'MONTH_6': 'June',
'MONTH_7': 'July',
'MONTH_8': 'August',
'MONTH_9': 'September',
'MONTH_10': 'October',
'MONTH_11': 'November',
'MONTH_12': 'December',
'MONTH_LONG_1': 'January',
'MONTH_LONG_2': 'February',
'MONTH_LONG_3': 'March',
'MONTH_LONG_4': 'April',
'MONTH_LONG_5': 'May',
'MONTH_LONG_6': 'June',
'MONTH_LONG_7': 'July',
'MONTH_LONG_8': 'August',
'MONTH_LONG_9': 'September',
'MONTH_LONG_10': 'October',
'MONTH_LONG_11': 'November',
'MONTH_LONG_12': 'December',
'MONTH_SHORT_1': 'Jan',
'MONTH_SHORT_2': 'Feb',
'MONTH_SHORT_3': 'Mar',
'MONTH_SHORT_4': 'Apr',
'MONTH_SHORT_5': 'May',
'MONTH_SHORT_6': 'Jun',
'MONTH_SHORT_7': 'Jul',
'MONTH_SHORT_8': 'Aug',
'MONTH_SHORT_9': 'Sep',
'MONTH_SHORT_10': 'Oct',
'MONTH_SHORT_11': 'Nov',
'MONTH_SHORT_12': 'Dec',
// Days of the week - 'DAY_' + dayIndex
// start at 1 to match JS date format
'DAY_1': 'Monday',
'DAY_2': 'Tuesday',
'DAY_3': 'Wednesday',
'DAY_4': 'Thursday',
'DAY_5': 'Friday',
'DAY_6': 'Saturday',
'DAY_7': 'Sunday',
'ELAPSED_TODAY': 'Today',
'ELAPSED_YESTERDAY': 'Yesterday',
'ELAPSED_YEARS': 'y',
'ELAPSED_MONTHS': 'mth',
'ELAPSED_WEEKS': 'w',
'ELAPSED_DAYS': 'd',
'ELAPSED_HOURS': 'h',
'ELAPSED_MINUTES': 'm',
'ELAPSED_SECONDS': 's',
'ELAPSED_AT': 'at',
'ELAPSED_AGO': 'ago',
'ELAPSED_JUST_NOW': 'Just now',
'ELAPSED_FEW_MIN_AGO': 'Few min ago',
'ELAPSED_MIN_AGO': 'min ago',
'ELAPSED_HOUR_AGO': 'hour ago',
'ELAPSED_HOURS_AGO': 'hours ago',
'ELAPSED_HOURS_AGO_MORE_THAN_FIVE': 'hours ago'
});
pipTranslateProvider.translations('ru', {
// Months - 'MONTH_' + monthIndex
// start at 0 to match JS date format
'MONTH_1': 'январь',
'MONTH_2': 'февраль',
'MONTH_3': 'март',
'MONTH_4': 'апрель',
'MONTH_5': 'май',
'MONTH_6': 'июнь',
'MONTH_7': 'июль',
'MONTH_8': 'август',
'MONTH_9': 'сентябрь',
'MONTH_10': 'октябрь',
'MONTH_11': 'ноябрь',
'MONTH_12': 'декабрь',
'MONTH_LONG_1': 'января',
'MONTH_LONG_2': 'февраля',
'MONTH_LONG_3': 'марта',
'MONTH_LONG_4': 'апреля',
'MONTH_LONG_5': 'мая',
'MONTH_LONG_6': 'июня',
'MONTH_LONG_7': 'июля',
'MONTH_LONG_8': 'августа',
'MONTH_LONG_9': 'сентября',
'MONTH_LONG_10': 'октября',
'MONTH_LONG_11': 'ноября',
'MONTH_LONG_12': 'декабря',
'MONTH_SHORT_1': 'янв',
'MONTH_SHORT_2': 'фев',
'MONTH_SHORT_3': 'мар',
'MONTH_SHORT_4': 'апр',
'MONTH_SHORT_5': 'май',
'MONTH_SHORT_6': 'июн',
'MONTH_SHORT_7': 'июл',
'MONTH_SHORT_8': 'авг',
'MONTH_SHORT_9': 'сен',
'MONTH_SHORT_10': 'окт',
'MONTH_SHORT_11': 'ноя',
'MONTH_SHORT_12': 'дек',
// Days of the week - 'DAY_' + dayIndex
// start at 1 to match JS date format
'DAY_1': 'понедельник',
'DAY_2': 'вторник',
'DAY_3': 'среда',
'DAY_4': 'четверг',
'DAY_5': 'пятница',
'DAY_6': 'суббота',
'DAY_7': 'воскресенье',
'ELAPSED_TODAY': 'Сегодня',
'ELAPSED_YESTERDAY': 'Вчера',
'ELAPSED_YEARS': 'г',
'ELAPSED_MONTHS': 'мц',
'ELAPSED_WEEKS': 'н',
'ELAPSED_DAYS': 'д',
'ELAPSED_HOURS': 'ч',
'ELAPSED_MINUTES': 'м',
'ELAPSED_SECONDS': 'с',
'ELAPSED_AT': 'в',
'ELAPSED_AGO': 'тн',
'ELAPSED_JUST_NOW': 'Только что',
'ELAPSED_FEW_MIN_AGO': 'Несколько мин тн',
'ELAPSED_MIN_AGO': 'мин тн',
'ELAPSED_HOUR_AGO': 'час тн',
'ELAPSED_HOURS_AGO': 'часа тн',
'ELAPSED_HOURS_AGO_MORE_THAN_FIVE': 'часов тн'
});
}]);
thisModule.factory('pipDateFormat',
['pipDates', 'pipTranslate', '$rootScope', function (pipDates, pipTranslate, $rootScope) {
return {
formatDate: formatDate,
formatLongDate: formatLongDate,
formatShortDate: formatShortDate,
formatShortDateWithYear: formatShortDateWithYear,
formatLongDateWithYear: formatLongDateWithYear,
formatLongMonth: formatLongMonth,
formatMonth: formatMonth,
formatYear: formatYear,
formatShortWeek: formatShortWeek,
formatShortDayAndMonth: formatShortDayAndMonth,
formatLongDayAndMonth: formatLongDayAndMonth,
formatDateRange: formatDateRange,
formatDateTimeRange: formatDateTimeRange,
formatTime: formatTime,
formatLongTime: formatLongTime,
formatShortTime: formatShortTime,
formatLongDateTime: formatLongDateTime,
formatShortDateTime: formatShortDateTime,
formatElapsedTime: formatElapsedTime,
formatElapsedInterval: formatElapsedInterval,
formatMillisecondsToSeconds: formatMillisecondsToSeconds
};
function twoDigits(value) {
return value < 10 ? '0' + value : value;
};
function formatDate(value, format, str) {
if (value == null) return '';
var
strict = str || false,
value = _.isDate(value) ? value : new Date(value),
thisYear = new Date().getUTCFullYear(),
year = value.getUTCFullYear(),
month = value.getUTCMonth(),
longMonthName = pipTranslate.translate('MONTH_LONG_' + (month + 1)),
shortMonthName = pipTranslate.translate('MONTH_SHORT_' + (month + 1)),
monthName = pipTranslate.translate('MONTH_' + (month + 1)),
day = value.getUTCDate(),
startWeek = pipDates.toStartWeek(value),
endWeek = pipDates.toEndWeek(value, -1);
if (strict == false && format == 'd MMMM yyyy' && thisYear === year) {
format = 'MMMM d';
}
if (strict == false && format == 'd MMM yyyy' && thisYear === year) {
format = 'MMM d';
}
if ((format == 'MMM d') && $rootScope.$language == 'ru') {
format = 'd MMM';
}
if ((format == 'MMMM d') && $rootScope.$language == 'ru') {
format = 'd MMMM';
}
if (format == 'd MMMM yyyy')
return '' + day + ' ' + longMonthName + ' ' + year
else if (format == 'MMMM d, yyyy')
return '' + monthName + ' ' + day + ', ' + year
if (format == 'd MMM yyyy')
return '' + day + ' ' + shortMonthName + ' ' + year
else if (format == 'MMM d, yyyy')
return '' + shortMonthName + ' ' + day + ', ' + year
else if (format == 'd MMMM')
return '' + day + ' ' + longMonthName
else if (format == 'd MMM')
return '' + day + ' ' + shortMonthName
else if (format == 'MMM d')
return '' + shortMonthName + ' ' + day;
else if (format == 'MMMM d')
return '' + longMonthName + ' ' + day;
else if (format == 'yyyy/M/d')
return '' + year + '/' + month + '/' + day;
else if (format == 'yyy-M-d')
return '' + year + '-' + month + '-' + day;
else if (format == 'MMMM')
return '' + longMonthName + ' ' + year;
else if (format == 'yyyy')
return '' + year;
else if (format == 'ww')
return '' + startWeek.getUTCDate() + ' - ' + endWeek.getUTCDate() + ' ' + monthName + ' ' + year;
return '' + day + ' ' + monthName + ' ' + year
}
function formatLongDate(value) {
return formatDate(value, 'd MMMM yyyy');
}
function formatShortDateWithYear(value) {
return formatDate(value, 'd MMM yyyy', true);
}
function formatLongDateWithYear(value) {
return formatDate(value, 'd MMMM yyyy', true);
}
function formatShortDate(value) {
return formatDate(value, 'd MMM yyyy');
}
function formatLongMonth(value) {
return formatDate(value, 'MMMM');
}
function formatYear(value) {
return formatDate(value, 'yyyy');
}
function formatShortWeek(value) {
return formatDate(value, 'ww');
}
function formatShortDayAndMonth(value) {
return formatDate(value, 'd MMM');
}
function formatLongDayAndMonth(value) {
if ($rootScope.$language == 'ru')
return formatDate(value, 'd MMMM');
else
return formatDate(value, 'MMMM d');
}
function formatDateRange(value1, value2) {
value1 = value1 ? (_.isDate(value1) ? value1 : new Date(value1)) : null;
value2 = value2 ? (_.isDate(value2) ? value2 : new Date(value2)) : null;
if (value1 == null) {
if ($rootScope.$language == 'ru')
return formatDate(value2, 'd MMM yyyy', true);
else
return formatDate(value2, 'MMM d, yyyy', true);
}
if (value2 == null || value1 == value2) {
if ($rootScope.$language == 'ru')
return formatDate(value1, 'd MMM yyyy', true);
else
return formatDate(value1, 'MMM d, yyyy', true);
}
if (value1.getUTCFullYear() !== value2.getUTCFullYear()) {
if ($rootScope.$language == 'ru')
return formatDate(value1, 'd MMM yyyy', true) + '-' + formatDate(value2, 'd MMM yyyy', true);
else
return formatDate(value1, 'MMM d, yyyy', true) + '-' + formatDate(value2, 'MMM d, yyyy', true);
} else {
return formatDate(value1, 'd MMM') + ' - ' + formatDate(value2, 'd MMM')
+ ((new Date().getUTCFullYear() !== value1.getUTCFullYear()) ? ' ' + formatDate(value1, 'yyyy') : '');
}
}
function formatDateTimeRange(value1, value2) {
value1 = value1 ? (_.isDate(value1) ? value1 : new Date(value1)) : null;
value2 = value2 ? (_.isDate(value2) ? value2 : new Date(value2)) : null;
if (value1 == null && value2 == null) return '';
if (value1 == null) {
return formatShortDateTime(value2);
}
if (value2 == null || value1 == value2) {
return formatShortDateTime(value1);
}
var dayStart, monthStart, yearStart,
dayEnd, monthEnd, yearEnd;
dayStart = value1.getUTCDate();
monthStart = value1.getUTCMonth();
yearStart = value1.getUTCFullYear();
dayEnd = value2.getUTCDate();
monthEnd = value2.getUTCMonth();
yearEnd = value2.getUTCFullYear();
if (yearStart !== yearEnd) {
return formatDate(value1, 'd MMM') + ', ' + yearStart + ' ' + formatTime(value1, 'hh:mm') +
' - ' + formatDate(value2, 'd MMM') + ', ' + yearEnd + ' ' + formatTime(value2, 'hh:mm');
} else {
if (monthStart != monthEnd && !dayStart != dayEnd)
return formatDate(value1, 'd MMM') + ', ' + formatTime(value1, 'hh:mm') +
' - ' + formatDate(value2, 'd MMM') + ', ' + formatTime(value2, 'hh:mm');
else
return formatTime(value1, 'hh:mm') + ' - ' + formatTime(value2, 'hh:mm')
}
}
function formatTime(value, format) {
if (value == null) return '';
value = _.isDate(value) ? value : new Date(value);
var
hours = value.getHours(),
mins = value.getMinutes(),
secs = value.getSeconds(),
ampm = '';
if (pipTranslate.use() == 'en') {
ampm = hours >= 12 ? ' PM' : ' AM';
hours = hours % 12;
if (hours == 0) hours = 12;
}
if (format == 'hh:mm:ss')
return '' + twoDigits(hours) + ':' + twoDigits(mins) + ':' + twoDigits(secs) + ampm;
else if (format == 'hh:mm')
return '' + twoDigits(hours) + ':' + twoDigits(mins) + ampm;
return '' + twoDigits(hours) + ':' + twoDigits(mins) + ':' + twoDigits(secs) + ampm;
}
function formatMonth(value, short) {
if (value == null) return '';
return short ? pipTranslate.translate('MONTH_SHORT_' + value) : pipTranslate.translate('MONTH_' + value);
}
function formatLongTime(value) {
return formatTime(value, 'hh:mm:ss');
}
function formatShortTime(value) {
return formatTime(value, 'hh:mm');
}
function formatLongDateTime(value) {
if (value == null) return '';
value = _.isDate(value) ? value : new Date(value);
return formatLongDate(value) + ' ' + formatLongTime(value);
}
function formatShortDateTime(value) {
if (value == null) return '';
value = _.isDate(value) ? value : new Date(value);
return formatShortDate(value) + ' ' + formatShortTime(value);
}
function formatElapsedTime(value, format) {
if (value == null) return '';
value = _.isDate(value) ? value : new Date(value);
var
current = new Date(),
diff = Math.floor(((current.getTime() + current.getTimezoneOffset()) - (value.getTime() + value.getTimezoneOffset())) / 1000);
if (diff < 1) return pipTranslate.translate('ELAPSED_JUST_NOW');
var years, months, weeks, days, hours, mins, secs;
secs = diff % 60;
diff = Math.floor(diff / 60);
mins = diff % 60;
diff = Math.floor(diff / 60);
hours = diff % 24;
diff = diff / 24;
years = Math.floor(diff / 365),
diff = diff - years * 365;
months = Math.floor(diff / 30),
days = Math.floor(diff - months * 30);
if (days % 7 == 0) {
weeks = Math.floor(days / 7);
days = 0;
} else {
weeks = 0;
}
if (format == 'interval') {
var result = '';
if (years) {
result += ' ' + years + pipTranslate.translate('ELAPSED_YEARS');
weeks = days = hours = mins = secs = null;
}
if (months) {
result += ' ' + months + pipTranslate.translate('ELAPSED_MONTHS');
days = hours = mins = secs = null;
}
if (weeks) {
result += ' ' + weeks + pipTranslate.translate('ELAPSED_WEEKS');
hours = mins = secs = null;
}
if (days) {
result += ' ' + days + pipTranslate.translate('ELAPSED_DAYS');
mins = secs = null;
}
if (hours) {
result += ' ' + hours + pipTranslate.translate('ELAPSED_HOURS');
secs = null;
}
if (mins) result += ' ' + mins + pipTranslate.translate('ELAPSED_MINUTES');
if (secs) result += ' ' + secs + pipTranslate.translate('ELAPSED_SECONDS');
return result != '' ? result + ' ' + pipTranslate.translate('ELAPSED_AGO')
: pipTranslate.translate('ELAPSED_JUST_NOW');
}
// Default time format = 'default'
if (years > 0) {
return formatDate(value, 'd MMM yyyy');
}
if (months > 0 || weeks > 0 || days > 1) {
return formatDate(value, 'MMM d')
+ ', ' + formatTime(value, 'hh:mm');
}
if (days == 1) {
return pipTranslate.translate('ELAPSED_YESTERDAY')
+ ', ' + formatTime(value, 'hh:mm');
}
if (hours > 10) {
return pipTranslate.translate('ELAPSED_TODAY')
+ ', ' + formatTime(value, 'hh:mm');
}
if (hours > 0) {
return '' + hours + ' ' + (hours < 2 ? pipTranslate.translate('ELAPSED_HOUR_AGO') :
hours < 5 ? pipTranslate.translate('ELAPSED_HOURS_AGO') : pipTranslate.translate('ELAPSED_HOURS_AGO_MORE_THAN_FIVE'));
}
if (mins > 10) {
return '' + mins + ' ' + pipTranslate.translate('ELAPSED_MIN_AGO');
}
if (mins > 0) {
return pipTranslate.translate('ELAPSED_FEW_MIN_AGO');
}
return pipTranslate.translate('ELAPSED_JUST_NOW');
}
function formatElapsedInterval(value) {
return formatElapsedTime(value, 'interval');
}
function formatMillisecondsToSeconds(value) {
return Math.floor(value / 1000)
}
}]
);
})();
/**
* @file Filter to format date and time
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module('pipDateTimeFilters', ['pipDateFormat']);
thisModule.filter('formatDate',
['pipDateFormat', function (pipDateFormat) {
return function(value, format) {
return pipDateFormat.formatDate(value, format);
};
}]
);
thisModule.filter('formatLongDate',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatLongDate(value);
};
}]
);
thisModule.filter('formatLongDateWithYear',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatLongDateWithYear(value);
};
}]
);
thisModule.filter('formatMonth',
['pipDateFormat', function (pipDateFormat) {
return function(value, format) {
return pipDateFormat.formatMonth(value, format);
};
}]
);
thisModule.filter('formatShortDate',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatShortDate(value);
};
}]
);
thisModule.filter('formatShortDateWithYear',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatShortDateWithYear(value);
};
}]
);
thisModule.filter('formatLongMonth',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatLongMonth(value);
};
}]
);
thisModule.filter('formatYear',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatYear(value);
};
}]
);
thisModule.filter('formatShortWeek',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatShortWeek(value);
};
}]
);
thisModule.filter('formatTime',
['pipDateFormat', function (pipDateFormat) {
return function(value, format) {
return pipDateFormat.formatTime(value, format);
};
}]
);
thisModule.filter('formatLongTime',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatLongTime(value);
};
}]
);
thisModule.filter('formatShortTime',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatShortTime(value);
};
}]
);
thisModule.filter('formatLongDateTime',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatLongDateTime(value);
};
}]
);
thisModule.filter('formatShortDateTime',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatShortDateTime(value);
};
}]
);
thisModule.filter('formatElapsedInterval',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatElapsedInterval(value);
};
}]
);
thisModule.filter('formatElapsedTime',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatElapsedTime(value);
};
}]
);
thisModule.filter('formatMillisecondsToSeconds',
['pipDateFormat', function (pipDateFormat) {
return function(value) {
return pipDateFormat.formatMillisecondsToSeconds(value);
};
}]
);
thisModule.filter('formatDateRange',
['pipDateFormat', function (pipDateFormat) {
return function(value1, value2) {
return pipDateFormat.formatDateRange(value1, value2);
};
}]
);
thisModule.filter('formatDateTimeRange',
['pipDateFormat', function (pipDateFormat) {
return function(value1, value2) {
return pipDateFormat.formatDateTimeRange(value1, value2);
};
}]
);
})();
/**
* @file Filter to translate string resources
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module('pipTranslateFilters', ['pipTranslate']);
thisModule.filter('translate', ['pipTranslate', function (pipTranslate) {
return function (key) {
return pipTranslate.translate(key) || key;
}
}]);
})();
/**
* @file Assertion utilities
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipAssert', ['pipDebug']);
thisModule.provider('pipAssert', ['pipDebugProvider', function (pipDebugProvider) {
return {
isEmpty: pipDebugProvider.enabled() ? isEmpty : noop,
isObjectId: pipDebugProvider.enabled() ? isObjectId : noop,
isDefined: pipDebugProvider.enabled() ? isDefined : noop,
isDef: pipDebugProvider.enabled() ? isDefined : noop,
contains: pipDebugProvider.enabled() ? contains : noop,
equal: pipDebugProvider.enabled() ? equal : noop,
notEqual: pipDebugProvider.enabled() ? notEqual : noop,
strictEqual: pipDebugProvider.enabled() ? strictEqual : noop,
notStrictEqual: pipDebugProvider.enabled() ? notStrictEqual : noop,
isArray: pipDebugProvider.enabled() ? isArray : noop,
isBoolean: pipDebugProvider.enabled() ? isBoolean : noop,
isNumber: pipDebugProvider.enabled() ? isNumber : noop,
isString: pipDebugProvider.enabled() ? isString : noop,
isObject: pipDebugProvider.enabled() ? isObject : noop,
isDate: pipDebugProvider.enabled() ? isDate : noop,
isError: pipDebugProvider.enabled() ? isError : noop,
isFunction: pipDebugProvider.enabled() ? isFunction : noop,
isNotNull: pipDebugProvider.enabled() ? isNotNull : noop,
$get: ['pipDebug', function(pipDebug) {
return {
isEmpty: pipDebug.enabled() ? isEmpty : noop,
isObjectId: pipDebug.enabled() ? isObjectId : noop,
isDefined: pipDebug.enabled() ? isDefined : noop,
isDef: pipDebug.enabled() ? isDefined : noop,
contains: pipDebug.enabled() ? contains : noop,
equal: pipDebug.enabled() ? equal : noop,
notEqual: pipDebug.enabled() ? notEqual : noop,
strictEqual: pipDebug.enabled() ? strictEqual : noop,
notStrictEqual: pipDebug.enabled() ? notStrictEqual : noop,
isArray: pipDebug.enabled() ? isArray : noop,
isBoolean: pipDebug.enabled() ? isBoolean : noop,
isNumber: pipDebug.enabled() ? isNumber : noop,
isString: pipDebug.enabled() ? isString : noop,
isObject: pipDebug.enabled() ? isObject : noop,
isDate: pipDebug.enabled() ? isDate : noop,
isError: pipDebug.enabled() ? isError : noop,
isFunction: pipDebug.enabled() ? isFunction : noop,
isNotNull: pipDebug.enabled() ? isNotNull : noop
}
}]
};
function noop() {}
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function isArray(arg, message) {
if (!Array.isArray(arg)) {
throw new Error(message || arg + ' should be array');
}
}
function isBoolean(arg, message) {
if (typeof arg !== 'boolean') {
throw new Error(message || arg + ' should be boolean');
}
}
function isNotNull(arg, message) {
if (arg === null) {
throw new Error(message || arg + ' should be not null');
}
}
function isNumber(arg, message) {
if (typeof arg !== 'number') {
throw new Error(message || arg + ' should be number');
}
}
function isString(arg, message) {
if (typeof arg !== 'string') {
throw new Error(message || arg + ' should be string');
}
}
function isObject(arg, message) {
if (typeof arg !== 'object') {
throw new Error(message || arg + ' should be an object');
}
}
function isDate(d, message) {
if (typeof d === 'object' && objectToString(d) !== '[object Date]') {
throw new Error(message || d + ' should be a date');
}
}
function isError(e, message) {
if (typeof e === 'object' && (objectToString(e) !== '[object Error]' || e instanceof Error)) {
throw new Error(message || e + ' should be an error');
}
}
function isFunction(arg, message) {
if (typeof arg !== 'function') {
throw new Error(message || arg + ' should be a function');
}
}
function isDefined(arg, message) {
if (typeof arg === "undefined") {
throw new Error(message || arg + ' should be defined');
}
}
function isEmpty(arg, message) {
if (arg === null || arg === undefined || arg === false) {
throw new Error(message || arg + ' should be not null or undefined or false');
}
}
function contains(obj, prop, message) {
if (typeof obj !== 'object') {
throw new Error(obj + ' should be an object');
}
if (obj[prop] === null || obj[prop] === undefined) {
throw new Error(message || prop + ' should be in object ' + obj);
}
}
// Compares args with ==
function equal(actual, expected, message) {
if (actual != expected) {
throw new Error(message || actual + ' should be not equal ' + expected);
}
}
// Compares args with !=
function notEqual(actual, expected, message) {
if (actual == expected) {
throw new Error(message || actual + ' should be equal ' + expected);
}
}
// Compares args with ===
function strictEqual(actual, expected, message) {
if (actual !== expected) {
throw new Error(message || actual + ' should not be strict equal ' + expected);
}
}
// Compares args with !==
function notStrictEqual(actual, expected, message) {
if (actual === expected) {
throw new Error(message || actual + ' should not strict equal ' + expected);
}
}
// Checks if value is a valid ObjectId
function isObjectId(value, message) {
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if (!checkForHexRegExp.test(value)) {
throw new Error(message || value + ' should be an object id');
}
}
}]);
})();
/**
* @file Debugging service
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipDebug', []);
thisModule.provider('pipDebug', ['$logProvider', function ($logProvider) {
this.enabled = true;
return {
enable: enable,
disable: disable,
enabled: enabled,
$get: ['$log', function($log) {
return {
enabled: enabled,
log: $log.log,
info: $log.info,
warn: $log.warn,
error: $log.error,
debug: $log.debug
}
}]
};
function enabled() {
return this.enabled;
}
function enable() {
this.enabled = true;
$logProvider.debugEnabled(true);
}
function disable() {
this.enabled = false;
$logProvider.debugEnabled(false);
}
}]);
})();
/**
* @file Error context
* @description
* Error context decouples business components that throw errors
* and visualization components that show them to users
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module('pipErrors', ['pipUtils', 'pipAssert']);
/*
* Error is designed to assist with error handling
* within different application scopes & controllers without overlap.
*
* A unique identification of the scope/controller is passed to the service
* when it is initialized to identify the error for that scope.
* */
thisModule.factory('pipError',
['$rootScope', 'pipAssert', function ($rootScope, pipAssert) {
// Initialize error scope
$rootScope.errors = {};
return createError;
//----------------------------
function initError(scope) {
$rootScope.errors[scope] = {
message: undefined,
code: undefined,
details: undefined
};
};
function errorMessage(error) {
if (_.isNull(error)) {
return null;
}
// Process regular messages
if (error.message) {
return error.message;
}
// Process server application errors
if (error.data) {
if (error.data.code) {
// process server error codes here
return 'ERROR_' + error.data.code;
}
if (error.data.message) {
return error.data.message;
}
}
// Process standard HTTP errors
if (error.statusText) {
return error.statusText;
}
if (error.status) {
return 'ERROR_' + error.status;
}
return error.data ? error.data : error;
};
function errorCode(error) {
if (_.isNull(error)) {
return null;
}
if (error.data && error.data.code) {
return error.data.code;
}
if (error.status) {
return error.status;
}
return null;
};
function errorDetails(error) {
return error && error.data ? error.data : error;
};
function createError(scope, scopeObject) {
scope = scope || 'global';
var error = {
reset: function () {
initError(scope);
},
empty: function() {
var error = $rootScope.errors[scope];
return _.isNull(error) || (_.isNull(error.message) && _.isNull(error.code));
},
get: function () {
if ($rootScope.errors[scope]) {
return $rootScope.errors[scope];
}
return '';
},
message: function () {
if ($rootScope.errors[scope]) {
return $rootScope.errors[scope].message;
}
return null;
},
code: function () {
if ($rootScope.errors[scope]) {
return $rootScope.errors[scope].code;
}
return null;
},
details: function () {
if ($rootScope.errors[scope]) {
return $rootScope.errors[scope].details;
}
return null;
},
set: function (error) {
if (error) {
pipAssert.isObject(error, "Setting error: error should be an object");
$rootScope.errors[scope] = {
message: errorMessage(error),
code: errorCode(error),
details: errorDetails(error)
};
console.error($rootScope.errors[scope]);
} else {
initError(scope);
}
}
};
// Assign error into scope
if (_.isObject(scopeObject)) scopeObject.error = error;
return error;
};
}]
);
})();
/**
* @file Application router extended from ui.router
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module('pipState', ['ui.router', 'pipTranslate', 'pipAssert']);
thisModule.config(
['$locationProvider', '$httpProvider', 'pipTranslateProvider', function($locationProvider, $httpProvider, pipTranslateProvider) {
// Switch to HTML5 routing mode
//$locationProvider.html5Mode(true);
pipTranslateProvider.translations('en', {
'ERROR_SWITCHING': 'Error while switching route. Try again.'
});
pipTranslateProvider.translations('ru', {
'ERROR_SWITCHING': 'Ошибка при переходе. Попробуйте ещё раз.'
});
}]
);
thisModule.run(
['$rootScope', 'pipTranslate', '$state', function($rootScope, pipTranslate, $state) {
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
if ($rootScope.$user && $rootScope.$user.id && toState.params && toState.params.access) {
if (toParams && toParams.party_id) {
var party = _.find($rootScope.$user.party_access, {party_id: toParams.party_id});
if (party) {
if (toState.params.access == 'manager' && !party.manager ||
toState.params.access == 'contributor' && !party.contributor) {
if (toState.params.toState) {
event.preventDefault();
$state.go(toState.params.toState, toParams);
return;
}
}
} else {
if (toParams.party_id != $rootScope.$user.id && toState.params.toState) {
event.preventDefault();
$state.go(toState.params.toState, toParams);
return;
}
}
}
}
// Unset routing variable to disable page transition
$rootScope.$routing = false;
// Record current and previous state
$rootScope.$state = {name: toState.name, url: toState.url, params: toParams};
$rootScope.$prevState = {name: fromState.name, url: fromState.url, params: fromParams};
}
);
// Intercept route error
$rootScope.$on('$stateChangeError',
function(event, toState, toParams, fromState, fromParams, error) {
// Unset routing variable to disable page transition
$rootScope.$routing = false;
console.error('Error while switching route to ' + toState.name);
console.error(error);
}
);
// Intercept route error
$rootScope.$on('$stateNotFound',
function(event, unfoundState, fromState, fromParams) {
event.preventDefault();
// todo make configured error state name
$state.go('errors_missing_route', {
unfoundState: unfoundState,
fromState : {
to: fromState ? fromState.name : '',
fromParams: fromParams
}
}
);
$rootScope.$routing = false;
}
);
}]
);
thisModule.provider('pipState', ['$stateProvider', 'pipAssertProvider', function($stateProvider, pipAssertProvider) {
// Configuration of redirected states
var redirectedStates = {};
this.redirect = setRedirect;
this.state = $stateProvider.state;
this.$get = ['$state', '$timeout', 'pipAssert', function ($state, $timeout, pipAssert) {
$state.redirect = redirect;
return $state;
//------------------------
function redirect(event, state, params, $rootScope) {
pipAssert.contains(state, 'name', "$state.redirect: state should contains name prop");
pipAssert.isObject(params, "$state.redirect: params should be an object");
var toState;
$rootScope.$routing = true;
toState = redirectedStates[state.name];
if (_.isFunction(toState)) {
toState = toState(state.name, params, $rootScope);
if (_.isNull(toState)) {
$rootScope.$routing = false;
throw new Error('Redirected toState cannot be null');
}
}
if (!!toState) {
$timeout(function() {
event.preventDefault();
$state.transitionTo(toState, params, {location: 'replace'});
});
return true;
}
return false;
}
}];
return;
//------------------
// Specify automatic redirect from one state to another
function setRedirect(fromState, toState) {
pipAssertProvider.isNotNull(fromState, "pipState.redirect: fromState cannot be null");
pipAssertProvider.isNotNull(toState, "pipState.redirect: toState cannot be null");
redirectedStates[fromState] = toState;
return this;
};
}]);
})();
(function () {
'use strict';
config.$inject = ['$mdThemingProvider', 'pipTranslateProvider'];
run.$inject = ['localStorageService', 'pipTheme', '$rootScope'];
ThemeFactory.$inject = ['localStorageService', '$mdTheming', '$rootScope', '$timeout', '$state', '$stateParams'];
angular
.module('pipTheme', ['ngMaterial'])
.config(config)
.run(run)
.factory('pipTheme', ThemeFactory);
function config($mdThemingProvider, pipTranslateProvider) {
pipTranslateProvider.translations('en', {
THEME: 'Theme',
blue: 'Blue',
pink: 'Pink',
amber: 'Amber',
orange: 'Orange',
green: 'Green',
navy: 'Navy',
grey: 'Grey'
});
pipTranslateProvider.translations('ru', {
THEME: 'Тема',
blue: 'Голубая',
pink: 'Розовая',
amber: 'Янтарная',
orange: 'Оранжевая',
green: 'Зеленая',
navy: 'Сине-серая',
grey: 'Серая'
});
registerBlueTheme('default');
registerBlueTheme('blue');
registerPinkTheme('pink');
registerAmberTheme('amber');
registerOrangeTheme('orange');
registerGreenTheme('green');
registerNavyTheme('navy');
registerGreyTheme('grey');
// registerDarkTheme('dark');
// registerBlackTheme('black');
$mdThemingProvider.setDefaultTheme('default');
$mdThemingProvider.alwaysWatchTheme(true);
function registerBlueTheme(themeName) {
var bluePrimaryPalette = $mdThemingProvider.extendPalette('blue', {
'contrastDefaultColor': 'light',
'contrastDarkColors': undefined
});
$mdThemingProvider.definePalette('blue-primary', bluePrimaryPalette);
var blueBackgroundPalette = $mdThemingProvider.extendPalette('grey', {
'A100': 'rgba(231, 231, 231, 1)',
'A200': 'rgba(33, 150, 243, 1)'
});
$mdThemingProvider.definePalette('blue-background', blueBackgroundPalette);
var blueAccentPalette = $mdThemingProvider.extendPalette('green', {
'600': 'rgba(0, 200, 83, 1)'
});
$mdThemingProvider.definePalette('blue-accent', blueAccentPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('blue-primary', {
'default': '500',
'hue-1': '300'
})
.backgroundPalette('blue-background', {
'default': '50', // background
'hue-1': 'A200', // tiles dialog
'hue-2': 'A700' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('blue-accent', {
'default': '600'
});
}
function registerPinkTheme(themeName) {
var PinkBackgroundPalette = $mdThemingProvider.extendPalette('grey', {
'A100': 'rgba(231, 231, 231, 1)',
'A200': 'rgba(188, 86, 121, 1)',
'contrastDefaultColor': 'dark',
'contrastLightColors': ['A200', 'A700']
});
$mdThemingProvider.definePalette('pink-background', PinkBackgroundPalette);
var PinkPrimaryPalette = $mdThemingProvider.extendPalette('pink', {
'600': 'rgba(255, 128, 171, 1)',
'700': 'rgba(188, 86, 121, .54)',
'900': 'rgba(188, 86, 121, 1)',
'contrastDefaultColor': 'light'
});
$mdThemingProvider.definePalette('pink-primary', PinkPrimaryPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('pink-primary', {
'default': '900',
'hue-1': '700'
})
.backgroundPalette('pink-background', {
'default': '50', // background
'hue-1': 'A200', // tiles dialog
'hue-2': 'A700' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('pink-primary', {
'default': '600'
});
}
function registerAmberTheme(themeName) {
var orangeBackgroundPalette = $mdThemingProvider.extendPalette('grey', {
'A100': 'rgba(231, 231, 231, 1)',
'A200': 'rgba(255, 152, 0, 1)'
});
$mdThemingProvider.definePalette('orange-background', orangeBackgroundPalette);
var orangePrimaryPalette = $mdThemingProvider.extendPalette('orange', {
'800': 'rgba(255, 152, 0, 1)',
'900': 'rgba(255, 152, 0, .54);'
});
$mdThemingProvider.definePalette('orange-primary', orangePrimaryPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('orange-primary', {
'default': '800',
'hue-1': '900'
})
.backgroundPalette('orange-background', {
'default': '50', // background
'hue-1': 'A200', // tiles dialog
'hue-2': 'A700' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('orange', {
'default': '900'
});
}
function registerOrangeTheme(themeName) {
var RedBackgroundPalette = $mdThemingProvider.extendPalette('grey', {
'A100': 'rgba(231, 231, 231, 1)',
'A200': 'rgba(255, 112, 67, 1)',
'contrastLightColors': ['600', '700', '800', '900', 'A200']
});
$mdThemingProvider.definePalette('red-background', RedBackgroundPalette);
var RedPrimaryPalette = $mdThemingProvider.extendPalette('orange', {
'800': 'rgba(255, 112, 67, 1)',
'900': 'rgba(255, 152, 67, .54)',
'A100': 'rgba(255, 171, 64, 1)',
'contrastLightColors': ['800', '900', 'A100']
});
$mdThemingProvider.definePalette('red-primary', RedPrimaryPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('red-primary', {
'default': '800',
'hue-1': '900'
})
.backgroundPalette('red-background', {
'default': '50', // background
'hue-1': 'A200', // tiles dialog
'hue-2': 'A700' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('red-primary', {
'default': 'A100'
});
}
function registerGreenTheme(themeName) {
var greenBackgroundPalette = $mdThemingProvider.extendPalette('grey', {
'A100': 'rgba(231, 231, 231, 1)',
'A200': 'rgba(76, 175, 80, 1)'
});
$mdThemingProvider.definePalette('green-background', greenBackgroundPalette);
var greenPrimaryPalette = $mdThemingProvider.extendPalette('green', {
'300':'#9ed4a1',
'contrastLightColors': ['500', '300']
});
$mdThemingProvider.definePalette('green-primary', greenPrimaryPalette);
var greenAccentPalette = $mdThemingProvider.extendPalette('amber', {
'contrastLightColors': ['A700']
});
$mdThemingProvider.definePalette('green-accent', greenAccentPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('green-primary', {
'default': '500',
'hue-1': '300'
})
.backgroundPalette('green-background', {
'default': '50', // background
'hue-1': 'A200', // tiles dialog
'hue-2': 'A700' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('green-accent', {
'default': 'A700'
});
}
function registerNavyTheme(themeName) {
var greyPalette = $mdThemingProvider.extendPalette('grey', {
'700': 'rgba(86, 97, 125, 1)',
'800': 'rgba(86, 97, 125, .54)',
'A100': 'rgba(231, 231, 231, 1)'
});
$mdThemingProvider.definePalette('grey', greyPalette);
var tealPalette = $mdThemingProvider.extendPalette('teal', {
'contrastLightColors': [ '500', '600', '700', '800', '900', 'A700']
});
$mdThemingProvider.definePalette('teal', tealPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('grey', {
'default': '700',
'hue-1': '800'
})
.backgroundPalette('grey', {
'default': '50', // background
'hue-1': '700', // tiles dialog
'hue-2': 'A700' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('teal', {
'default': 'A700'
});
}
function registerGreyTheme(themeName) {
var thirdPartyPalette = $mdThemingProvider.extendPalette('grey', {
'A100': 'rgba(231, 231, 231, 1)',
'A200': 'rgba(255, 152, 0, 1)',
'A400': '#a9b9c0',
'500': '#607D8B',
'A700': '#90A4AE',
//'800': '',
'contrastDefaultColor': 'dark',
'contrastLightColors': [ '300', '400', '500', '600', '700', '800', '900', 'A700']
});
$mdThemingProvider.definePalette('third-party', thirdPartyPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('third-party', {
'default': '500',
'hue-1': 'A400'
})
.backgroundPalette('third-party', {
'default': '50', // background
'hue-1': '500', // tiles dialog
'hue-2': 'A700' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('third-party', {
'default': 'A700'
});
}
function registerDarkTheme(themeName) {
var darkBackgroundPalette = $mdThemingProvider.extendPalette('grey', {
'600': 'rgba(48, 48, 48, 1)',
'700': 'rgba(255, 255, 255, 0.54)',
'800': 'rgba(66, 66, 66, 1)'
});
$mdThemingProvider.definePalette('dark-background', darkBackgroundPalette);
var darkAccentPalette = $mdThemingProvider.extendPalette('green', {
'600': 'rgba(0, 200, 83, 1)'
});
$mdThemingProvider.definePalette('dark-accent', darkAccentPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('dark-background', {
'default': '900',
'hue-1': '700'
})
.backgroundPalette('dark-background', {
'default': '800', // background
'hue-1': '900', // tiles dialog
'hue-2': 'A700' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('dark-accent', {
'default': '600'
});
}
function registerBlackTheme(themeName) {
var blackBackgroundPalette = $mdThemingProvider.extendPalette('grey', {
'600': 'rgba(48, 48, 48, 1)',
'700': 'rgba(255, 255, 255, 0.54)',
'800': 'rgba(66, 66, 66, 1)',
'500': 'rgba(38, 50, 56, 1)'
});
$mdThemingProvider.definePalette('black-background', blackBackgroundPalette);
var blackAccentPalette = $mdThemingProvider.extendPalette('blue-grey', {
'700': 'rgba(255, 255, 255, 0.54)'
});
$mdThemingProvider.definePalette('black-accent', blackAccentPalette);
$mdThemingProvider.theme(themeName)
.primaryPalette('black-accent', {
'default': '900',
'hue-1': '700'
})
.backgroundPalette('black-background', {
'default': '800', // background
'hue-1': '500', // tiles dialog
'hue-2': '800' // app bar
})
.warnPalette('red', {
'default': 'A200'
})
.accentPalette('black-accent', {
'default': '600'
});
}
}
function run(localStorageService, pipTheme, $rootScope) {
try {
var currentTheme = ($rootScope.$user && $rootScope.$user.theme) ?
$rootScope.$user.theme : localStorageService.get('theme');
pipTheme.initializeTheme(currentTheme);
} catch (ex) {
pipTheme.initializeTheme('blue');
}
}
/**
* @ngdoc factory
* @name pipTheme
*/
function ThemeFactory(localStorageService, $mdTheming, $rootScope, $timeout, $state, $stateParams) {
return {
/**
* Set current theme
* @param {String} theme - theme name
* @param {String}
* @throws {Error} 'Theme is not specified' in case if theme is not defined
* @throws {Error} 'Theme XXX is not registered. Please, register it first with $mdThemingProvider' if theme is not registered
*/
setCurrentTheme: function (theme) {
if (theme == null || theme === '') {
throw new Error('Theme is not specified');
}
if (localStorageService.get('theme') == theme && $rootScope.$theme == theme) {
return;
}
if (!(theme in $mdTheming.THEMES)) {
throw new Error('Theme ' + theme + ' is not registered. Please, register it first with $mdThemingProvider');
}
localStorageService.set('theme', theme);
$rootScope.$theme = theme;
},
/** Add attribute 'md-theme' with value current theme
* Add current theme class
*/
initializeTheme: function (theme) {
if (theme == null || theme === '') {
throw new Error('Theme is not specified');
}
if (!(theme in $mdTheming.THEMES)) {
throw new Error('Theme ' + theme + ' is not registered. Please, register it first with $mdThemingProvider');
}
$rootScope.$theme = theme;
$('body').attr('md-theme', '{{ $theme }}').addClass('{{ $theme }}');
}
};
}
})();
/**
* @file Global application timer service
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module('pipTimer', []);
thisModule.service('pipTimer',
['$interval', '$rootScope', function ($interval, $rootScope) {
var
AUTO_PULL_CHANGES_TIMEOUT = 60000,
AUTO_UPDATE_PAGE_TIMEOUT = 15000,
started = false,
autoPullChangesInterval,
autoUpdatePageInterval;
return {
isStarted: isStarted,
start: start,
stop: stop
};
//------------------------
function isStarted() {
return started;
};
function start() {
if (started) return;
autoPullChangesInterval = $interval(function () {
$rootScope.$broadcast('pipAutoPullChanges');
}, AUTO_PULL_CHANGES_TIMEOUT);
autoUpdatePageInterval = $interval(function () {
$rootScope.$broadcast('pipAutoUpdatePage');
}, AUTO_UPDATE_PAGE_TIMEOUT);
started = true;
};
function stop() {
if (autoPullChangesInterval)
$interval.cancel(autoPullChangesInterval);
if (autoUpdatePageInterval)
$interval.cancel(autoUpdatePageInterval);
started = false;
};
}]
);
})();
/**
* @file Transaction context
* @description
* Transaction context helps to wrap multiple server requests
* into one logical transaction. It decouples transaction
* management and progress visualization to the user
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module('pipTransactions', ['pipTranslate', 'pipErrors']);
thisModule.config(['pipTranslateProvider', function(pipTranslateProvider) {
pipTranslateProvider.translations('en', {
'ENTERING': 'Entering...',
'PROCESSING': 'Processing...',
'LOADING': 'Loading...',
'SAVING': 'Saving...'
});
pipTranslateProvider.translations('ru', {
'ENTERING': 'Вход в систему...',
'PROCESSING': 'Обрабатывается...',
'LOADING': 'Загружается...',
'SAVING': 'Сохраняется...'
});
}]);
/*
* Transaction is designed to assist with transaction processing
* within different application scopes & controllers without overlap.
*
* A unique identification of the scope/controller is passed to the service
* when it is initialized to identify the error for that scope.
*
* Transaction is also integrated with Error service. So you don't need to double it
* */
thisModule.factory('pipTransaction',
['$rootScope', 'pipError', function ($rootScope, pipError) {
// Initialize transaction scope
$rootScope.transactions = {};
return createTransaction;
//---------------------------------
function initTransaction(scope) {
$rootScope.transactions[scope] = {
id: undefined,
operation: undefined
};
}
function createTransaction(scope, scopeObject) {
scope = scope || 'global';
var error = pipError(scope);
var transaction = {
error: error,
reset: function () {
initTransaction();
error.reset();
},
busy: function() {
var transaction = $rootScope.transactions[scope];
return transaction != null && transaction.id;
},
failed: function() {
return !error.empty();
},
aborted: function(id) {
var transaction = $rootScope.transactions[scope];
return _.isNull(transaction) || transaction.id != id;
},
get: function () {
if (_.isNull($rootScope.transactions[scope])) {
initTransaction(scope);
}
return $rootScope.transactions[scope];
},
id: function () {
var transaction = $rootScope.transactions[scope];
return transaction ? transaction.id : null;
},
operation: function () {
var transaction = $rootScope.transactions[scope];
return transaction ? transaction.operation : null;
},
errorMessage: function () {
return error.message();
},
begin: function (operation) {
var transaction = $rootScope.transactions[scope];
// Transaction already in progress
if (transaction != null && transaction.id) {
return null;
}
transaction = $rootScope.transactions[scope] = {
id: new Date().getTime(),
operation: operation || 'PROCESSING'
};
error.reset();
return transaction.id;
},
abort: function() {
var transaction = $rootScope.transactions[scope];
if (transaction) {
transaction.id = null;
}
error.reset();
},
end: function (err) {
if (err) error.set(err);
else error.reset();
var transaction = $rootScope.transactions[scope];
if (transaction != null) {
transaction.id = null;
}
}
};
if (_.isObject(scopeObject)) {
scopeObject.error = error;
scopeObject.transaction = transaction;
}
return transaction;
}
}]
);
})();
/**
* @file Translatation service
* @copyright Digital Living Software Corp. 2014-2016
* @todo:
* - Move directives to more appropriate places
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipTranslate', ['LocalStorageModule', 'pipAssert']);
thisModule.provider('pipTranslate', ['pipAssertProvider', function(pipAssertProvider) {
var
language = 'en',
persist = true,
setRoot = true,
translationMap = {
en: {
'en': 'English',
'ru': 'Russian',
'es': 'Spanish',
'pt': 'Portuguese',
'de': 'German',
'fr': 'French'
},
ru: {
'en': 'Английский',
'ru': 'Русский',
'es': 'Испанский',
'pt': 'Португальский',
'de': 'Немецкий',
'fr': 'Французский'
}
};
this.translations = setTranslations;
this.language = initLanguage;
this.use = initLanguage;
this.persist = initPersist;
this.setRoot = initSetRoot;
this.$get = ['$rootScope', '$timeout', 'localStorageService', 'pipAssert', function ($rootScope, $timeout, localStorageService, pipAssert) {
// Read language from persistent storage
if (persist)
language = localStorageService.get('language') || language;
// Set root variable
if (setRoot)
$rootScope.$language = language;
// Resetting root scope to force update language on the screen
function reset(fullReset, partialReset) {
fullReset = fullReset !== undefined ? !!fullReset : true;
partialReset = partialReset !== undefined ? !!partialReset : true;
$rootScope.$reset = fullReset;
$rootScope.$partialReset = partialReset;
$timeout(function() {
$rootScope.$reset = false;
$rootScope.$partialReset = false;
}, 0);
}
return {
use: function (newLanguage, fullReset, partialReset) {
pipAssert.isString(newLanguage || '', "pipTranslate.use: argument should be a string");
if (newLanguage != null && newLanguage != language) {
language = newLanguage;
if (persist)
localStorageService.set('language', language);
if (setRoot)
$rootScope.$language = language;
reset(fullReset, partialReset);
}
return language;
},
translations: setTranslations,
translate: translate,
translateArray: translateArray,
translateSet: translateSet,
translateObjects: translateObjects,
translateById: translateById,
translateSetById: translateSetById,
translateStringsSet: translateStringsSet
}
}];
// Initialize language selection
function initLanguage(newLanguage) {
pipAssertProvider.isString(newLanguage || '', "pipTranslateProvider.use or pipTranslateProvider.language: argument should be a string");
if (newLanguage != null) {
language = newLanguage;
}
return language;
}
// Initialize persistence flag
function initPersist(newPersist) {
if (newPersist != null) {
pipAssertProvider.isBoolean(newPersist || '', "pipTranslateProvider.persist: argument should be a boolean");
persist = newPersist;
}
return persist;
}
// Initialize set root flag
function initSetRoot(newSetRoot) {
if (newSetRoot != null) {
pipAssertProvider.isBoolean(newSetRoot || '', "pipTranslateProvider.setRoot: argument should be a boolean");
setRoot = newSetRoot;
}
return setRoot;
}
// Set translation strings for specific language
function setTranslations(language, languageMap) {
pipAssertProvider.isString(language, "pipTranslate.setTranslations or pipTranslateProvider.translations: first argument should be a string");
pipAssertProvider.isObject(languageMap, "pipTranslate.setTranslations or pipTranslateProvider.translations: second argument should be an object");
var map = translationMap[language] || {};
translationMap[language] = _.extend(map, languageMap);
}
// Translate a string by key using set language
function translate(key) {
if (_.isNull(key) || _.isUndefined(key)) return '';
var map = translationMap[language] || {};
return map[key] || key;
}
// Translate an array of strings
function translateArray(keys) {
if (_.isNull(keys) || keys.length == 0) return [];
pipAssertProvider.isArray(keys, "pipTranslate.translateArray: argument should be an array");
var values = [];
var map = translationMap[language] || {};
_.each(keys, function (k) {
var key = k || '';
values.push(map[key] || key);
});
return values;
}
// Translate an array of strings into array of objects (set)
function translateSet(keys, key, value) {
if (_.isNull(keys) || keys.length == 0) return [];
pipAssertProvider.isArray(keys, "pipTranslate.translateSet: first argument should be an array");
pipAssertProvider.isString(key || '', "pipTranslate.translateSet: second argument should be a string");
pipAssertProvider.isString(value || '', "pipTranslate.translateSet: third argument should be a string");
key = key || 'id';
value = value || 'name';
var values = [];
var map = translationMap[language] || {};
_.each(keys, function (k) {
var obj = {}, mapKey = k || '';
obj[key] = mapKey;
obj[value] = map[mapKey] || mapKey;
values.push(obj);
});
return values;
}
// Translate a collection of objects
function translateObjects(items, key, value) {
if (_.isNull(items) || items.length == 0) return [];
pipAssertProvider.isArray(items, "pipTranslate.translateObjects: first argument should be an array");
pipAssertProvider.isString(key || '', "pipTranslate.translateObjects: second argument should be a string");
pipAssertProvider.isString(value || '', "pipTranslate.translateObjects: third argument should be a string");
key = key || 'name';
value = value || 'nameLocal';
var map = translationMap[language] || {};
_.each(items, function (i) {
var item = i, mapKey = item[key] || '';
item[value] = map[mapKey] || mapKey;
});
return items;
}
// Translate a string by key with prefix using set language todo
function translateById(prefix, key) {
pipAssertProvider.isString(key || '', "pipTranslate.translateById: second argument should be a string");
pipAssertProvider.isString(prefix || '', "pipTranslate.translateById: first argument should be a string");
prefix = prefix ? prefix + '_' : '';
key = (prefix + key).replace(/ /g, '_').toUpperCase();
if (key == null) return '';
var map = translationMap[language] || {};
return map[key] || key;
};
function translateSetById(keys, prefix, key, value) {
if (_.isNull(keys) || keys.length == 0) return [];
pipAssertProvider.isArray(keys, "pipTranslate.translateSetById: first argument should be an array");
pipAssertProvider.isString(prefix || '', "pipTranslate.translateSetById: second argument should be a string");
pipAssertProvider.isString(key || '', "pipTranslate.translateSetById: third argument should be a string");
pipAssertProvider.isString(value || '', "pipTranslate.translateSetById: forth argument should be a string");
prefix = prefix ? prefix.replace(/ /g, '_').toUpperCase() : '';
key = key || 'id';
value = value || 'name';
var values = [];
var map = translationMap[language] || {};
_.each(keys, function (k) {
var obj = {}, mapKey = k || '';
obj[key] = mapKey;
obj[value] = map[prefix + '_' + mapKey] || mapKey;
values.push(obj);
});
return values;
}
// Translate an array of strings, apply uppercase and replace ' ' => '_'
function translateStringsSet(keys, prefix, key, value) {
if (_.isNull(keys) || keys.length == 0) return [];
pipAssertProvider.isArray(keys, "pipTranslate.translateStringsSet: first argument should be an array");
pipAssertProvider.isString(prefix || '', "pipTranslate.translateStringsSet: second argument should be a string");
pipAssertProvider.isString(key || '', "pipTranslate.translateStringsSet: third argument should be a string");
pipAssertProvider.isString(value || '', "pipTranslate.translateStringsSet: forth argument should be a string");
key = key || 'id';
value = value || 'name';
prefix = prefix ? prefix.replace(/ /g, '_').toUpperCase() + '_': '';
var values = [];
var map = translationMap[language] || {};
_.each(keys, function (k) {
var obj = {}, mapKey = k || '';
obj[key] = mapKey;
obj[value] = map[prefix + mapKey.replace(/ /g, '_').toUpperCase()]
|| (prefix + mapKey.replace(/ /g, '_').toUpperCase());
values.push(obj);
});
return values;
}
}]);
thisModule.directive('pipTranslate', ['pipTranslate', function(pipTranslate) {
return {
restrict: 'EA',
scope: {
key1: '@pipTranslate',
key2: '@key'
},
link: function (scope, element, attrs) {
var key = scope.key1 || scope.key2;
var value = pipTranslate.translate(key);
element.text(value);
}
};
}]);
thisModule.directive('pipTranslateHtml', ['pipTranslate', function(pipTranslate) {
return {
restrict: 'EA',
scope: {
key1: '@pipTranslateHtml',
key2: '@key'
},
link: function (scope, element, attrs) {
var key = scope.key1 || scope.key2;
var value = pipTranslate.translate(key);
element.html(value);
}
};
}]);
})();
/**
* @file Collection utilities
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipUtils.Collections', []);
thisModule.factory('pipCollections', function () {
var collections = {};
// Index of element in array by key
collections.indexBy = function (items, key, value) {
if (!items || !items.length)
return null;
for (var i = 0; i < items.length; i++) {
if (items[i][key] == value) {
return i;
}
}
return null;
};
// Find element in array by key
collections.findBy = function (items, key, value) {
if (!items || !items.length)
return null;
for (var i = 0; i < items.length; i++) {
if (items[i][key] == value) {
return items[i];
}
}
return null;
};
// Remove element from array by value
collections.remove = function (items, item) {
if (!items || !items.length)
return null;
for (var i = 0; i < items.length; i++) {
if (items[i] == item) {
items.splice(i, 1);
i--;
}
}
};
// Removes element from array by key
collections.removeBy = function (items, key, value) {
if (!items || !items.length)
return null;
for (var i = 0; i < items.length; i++) {
if (items[i][key] == value) {
items.splice(i, 1);
i--;
}
}
};
// Replaced element by key
collections.replaceBy = function (items, key, value, data) {
if (!items || !items.length)
return null;
for (var i = 0; i < items.length; i++) {
if (items[i][key] == value) {
items[i] = data;
return;
}
}
};
// Calculate difference between two collections
collections.difference = function (a1, a2, comparator) {
var result = [];
_.each(a1, function (e1) {
var e2 = _.find(a2, function (e) {
return comparator(e1, e);
});
if (e2 == null) {
result.push(e1);
}
})
return result;
};
return collections;
});
})();
/**
* @file Date utilities
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipUtils.Dates', []);
thisModule.factory('pipDates', function () {
var dates = {};
dates.addHours = function (date, hours) {
date = _.isDate(date) ? date : new Date(date);
var time = date.getTime() + hours * 3600000;
return new Date(time);
};
dates.toStartDay = function (date) {
date = _.isDate(date) ? date : new Date(date);
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
};
dates.toEndDay = function (date, offset) {
date = _.isDate(date) ? date : new Date(date);
offset = offset != null ? offset : 0;
var start = new Date(date.getFullYear(), date.getMonth(), date.getDate());
return new Date(start.getTime() + 24 * 3600000 + offset);
};
dates.toStartWeek = function (date) {
date = _.isDate(date) ? date : new Date(date);
var dayOfWeek = date.getDay() ? date.getDay() : 7;
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
return new Date(date.getTime() - (dayOfWeek - 1) * 24 * 3600000); // dayOfWeek = 0 для воскресенья
};
dates.toEndWeek = function (date, offset) {
date = _.isDate(date) ? date : new Date(date);
offset = offset != null ? offset : 0;
var dayOfWeek = date.getDay() ? date.getDay() : 7;
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
return new Date(date.getTime() + (8 - dayOfWeek) * 24 * 3600000 + offset);
};
dates.toStartMonth = function (date) {
date = _.isDate(date) ? date : new Date(date);
return new Date(date.getFullYear(), date.getMonth(), 1);
};
dates.toEndMonth = function (date, offset) {
date = _.isDate(date) ? date : new Date(date);
var
month = date.getMonth() + 1,
year = date.getFullYear();
if (month > 11) {
year++;
month = 0;
}
date = new Date(year, month, 1);
if (offset != null) {
date = new Date(date.getTime() + offset);
}
return date;
};
dates.toStartYear = function (date) {
date = _.isDate(date) ? date : new Date(date);
return new Date(date.getFullYear(), 0, 1);
};
dates.toEndYear = function (date, offset) {
date = _.isDate(date) ? date : new Date(date);
date = new Date(date.getFullYear() + 1, 0, 1);
if (offset != null) {
date = new Date(date.getTime() + offset);
}
return date;
};
/** UTC functions - **/
dates.toUTCDate = function (year, month, day) {
return new Date(Date.UTC(year, month, day));
};
dates.toUTCDate = function (date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
};
dates.fromUTCDate = function (date) {
if (date == null) date = new Date();
return new Date(
date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
};
dates.toUTCStartWeek = function (date) {
if(!_.isDate(date)) {
date = new Date(date);
date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}
var dayOfWeek = date.getDay() ? date.getDay() : 7;
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
date = dayOfWeek != 1 ? new Date(date.getTime() - (dayOfWeek - 1) * 24 * 3600000) : date;
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
};
dates.toUTCEndWeek = function (date, offset) {
if(!_.isDate(date)) {
date = new Date(date);
date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}
offset = offset != null ? offset : 0;
var dayOfWeek = date.getDay() ? date.getDay() : 7;
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
date = new Date(date.getTime() + (8 - dayOfWeek) * 24 * 3600000 + offset);
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
};
return dates;
});
})();
/**
* @file Form error utilities
* @copyright Digital Living Software Corp. 2014-2016
*
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipUtils.FormErrors', []);
thisModule.factory('pipFormErrors', ['$rootScope', function ($rootScope) {
return {
errorsWithHint: errorsWithHint,
//submittedErrors: submittedErrors,
//submittedErrorsWithHint: submittedErrorsWithHint,
//dirtyErrors: dirtyErrors,
//dirtyErrorsWithHint: dirtyErrorsWithHint,
//touchedErrors: touchedErrors,
touchedErrorsWithHint: touchedErrorsWithHint,
resetFormErrors: resetFormErrors,
setFormError: setFormError,
resetFieldsErrors: resetFieldsErrors
};
//-------------------
function errorsWithHint(field) {
if (field == null) return;
return _.isEmpty(field.$error) ? { hint: true } : field.$error;
};
// function submittedErrors(form, field) {
// if (form == null) throw new Error('Form is not set');
// if (field == null) throw new Error('Field is not set');
//
// if (form.$submitted)
// return field.$error;
// return {};
// };
//
// function submittedErrorsWithHint(form, field) {
// if (form == null) throw new Error('Form is not set');
// if (field == null) throw new Error('Field is not set');
//
// if (form.$submitted) {
// return _.isEmpty(field.$error) ? { hint: true} : field.$error;
// }
// return { hint: true };
// };
//
// function dirtyErrors(form, field) {
// if (form == null) throw new Error('Form is not set');
// if (field == null) throw new Error('Field is not set');
//
// if (field.$dirty || form.$dirty)
// return field.$error;
// return {};
// };
//
// function dirtyErrorsWithHint(form, field) {
// if (form == null) throw new Error('Form is not set');
// if (field == null) throw new Error('Field is not set');
//
// if (field.$dirty || form.$dirty) {
// return _.isEmpty(field.$error) ? { hint: true} : field.$error;
// }
// return { hint: true };
// };
//
// function touchedErrors(form, field) {
// if (form == null) throw new Error('Form is not set');
// if (field == null) throw new Error('Field is not set');
//
// if (field.$touched || form.$dirty)
// return field.$error;
// return {};
// };
function touchedErrorsWithHint(form, field) {
if (form == null) return;
if (field == null) return;
if (form.$submitted && (field.$touched || form.$dirty) || !form.$submitted && (field.$touched || field.$dirty)) {
var result = _.isEmpty(field.$error) ? { hint: true} : field.$error;
return result;
}
return { hint: true };
};
function resetFormErrors(form, errors) {
form.$setPristine();
form.$setUntouched();
if (errors) {
form.$setDirty();
form.$setSubmitted();
}
form.$serverError = {};
};
function resetFieldsErrors(form, field) {
if (!form) return;
if (field && form[field] && form[field].$error) {
form[field].$error = {};
} else {
for (var prop in form) {
if (form[prop] && form[prop].$error) {
form[prop].$error = {};
};
}
if (form && form.$error) form.$error = {};
}
};
function setFormError(form, error, errorFieldMap) {
if (error == null) return;
// Prepare form server errors
form.$serverError = form.$serverError || {};
// Prepare error code
var code = error.code || (error.data || {}).code || null;
if (!code && error.status) code = error.status;
if (code) {
var
errorName = 'ERROR_' + code,
field = errorFieldMap ? errorFieldMap[code] : null;
// Set server error to fields
if (field && form[field] && form[field].$setValidity) {
form[field].$setValidity(errorName, false);
return;
}
// Set server error to form
if (field == 'form') {
form.$serverError[errorName] = true;
return;
}
}
// if undefined error for this form or code === undefined/null, go to unhandled error page
if (error.data && error.data.message) {
form.$serverError['ERROR_UNKNOWN'] = error.data.message;
goToUnhandledErrorPage(error);
return;
}
// Set as undefined error
if (error.message) {
form.$serverError['ERROR_UNKNOWN'] = error.message;
goToUnhandledErrorPage(error);
return;
}
if (error.name) {
form.$serverError['ERROR_UNKNOWN'] = error.name;
goToUnhandledErrorPage(error);
return;
}
form.$serverError['ERROR_UNKNOWN'] = error;
goToUnhandledErrorPage(error);
};
function goToUnhandledErrorPage(error) {
$rootScope.$emit('pipUnhandledInternalError', {
error: error
});
};
}]);
})();
/**
* @file General purpose utilities
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global _, $, angular */
(function () {
'use strict';
var thisModule = angular.module('pipUtils.General', ['pipState', 'pipAssert']);
thisModule.factory('pipUtils', ['$rootScope', '$window', '$state', 'pipAssert', function ($rootScope, $window, $state, pipAssert) {
function strRepeat(str, qty) {
if (qty < 1) return '';
var result = '';
while (qty > 0) {
if (qty & 1) result += str;
qty >>= 1, str += str;
}
return result;
}
var toString = Object.prototype.toString;
var sprintf = (function sprintf() {
function get_type(variable) {
return toString.call(variable).slice(8, -1).toLowerCase();
}
var str_repeat = strRepeat;
var str_format = function() {
if (!str_format.cache.hasOwnProperty(arguments[0])) {
str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
}
return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
};
str_format.format = function(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
for (i = 0; i < tree_length; i++) {
node_type = get_type(parse_tree[i]);
if (node_type === 'string') {
output.push(parse_tree[i]);
}
else if (node_type === 'array') {
match = parse_tree[i]; // convenience purposes only
if (match[2]) { // keyword argument
arg = argv[cursor];
for (k = 0; k < match[2].length; k++) {
if (!arg.hasOwnProperty(match[2][k])) {
throw new Error(sprintf('[_.sprintf] property "%s" does not exist', match[2][k]));
}
arg = arg[match[2][k]];
}
} else if (match[1]) { // positional argument (explicit)
arg = argv[match[1]];
}
else { // positional argument (implicit)
arg = argv[cursor++];
}
if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
throw new Error(sprintf('[_.sprintf] expecting number but found %s', get_type(arg)));
}
switch (match[8]) {
case 'b': arg = arg.toString(2); break;
case 'c': arg = String.fromCharCode(arg); break;
case 'd': arg = parseInt(arg, 10); break;
case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
case 'o': arg = arg.toString(8); break;
case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
case 'u': arg = Math.abs(arg); break;
case 'x': arg = arg.toString(16); break;
case 'X': arg = arg.toString(16).toUpperCase(); break;
}
arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
pad_length = match[6] - String(arg).length;
pad = match[6] ? str_repeat(pad_character, pad_length) : '';
output.push(match[5] ? arg + pad : pad + arg);
}
}
return output.join('');
};
str_format.cache = {};
str_format.parse = function(fmt) {
var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
while (_fmt) {
if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
parse_tree.push(match[0]);
}
else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
parse_tree.push('%');
}
else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1;
var field_list = [], replacement_field = match[2], field_match = [];
if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
field_list.push(field_match[1]);
}
else {
throw new Error('[_.sprintf] huh?');
}
}
}
else {
throw new Error('[_.sprintf] huh?');
}
match[2] = field_list;
}
else {
arg_names |= 2;
}
if (arg_names === 3) {
throw new Error('[_.sprintf] mixing positional and named placeholders is not (yet) supported');
}
parse_tree.push(match);
}
else {
throw new Error('[_.sprintf] huh?');
}
_fmt = _fmt.substring(match[0].length);
}
return parse_tree;
};
return str_format;
})();
return {
copyProperty: copyProperty,
copy: copyProperty,
swapProperties: swapProperties,
swap: swapProperties,
convertToBoolean: convertToBoolean,
toBoolean: convertToBoolean,
toBool: convertToBoolean,
convertObjectIdsToString: convertObjectIdsToString,
OidToString: convertObjectIdsToString,
generateVerificationCode: generateVerificationCode,
vercode: generateVerificationCode,
goBack: goBack,
goBackAndSelect: goBackAndSelect,
scrollTo: scrollTo,
equalObjectIds: equalObjectIds,
eqOid: equalObjectIds,
notEqualObjectIds: notEqualObjectIds,
neqOid: notEqualObjectIds,
containsObjectId: containsObjectId,
hasOid: containsObjectId,
isObjectId: isObjectId,
// Strings functions. No analogues in lodash.strings
sampleLine: sampleLine,
hashCode: hashCode,
makeString: makeString,
getBrowser: getBrowser,
checkSupported: checkSupported,
sprintf: sprintf,
// Collection function. No analogues in lodash. It may be in lodash later. Look gitHub/lodash issue #1022
replaceBy: replaceBy
};
//--------------------
function replaceBy(items, key, value, data) {
if (!items || !items.length)
return null;
for (var i = 0; i < items.length; i++) {
if (items[i][key] == value) {
items[i] = data;
return;
}
}
};
// Creates a sample line from a text
function sampleLine(value, maxLength) {
if (!value || value == '') return '';
var length = value.indexOf('\n');
length = length >= 0 ? length : value.length;
length = length < maxLength ? value.length : maxLength;
return value.substring(0, length);
};
// Simple version of string hashcode
function hashCode(value) {
if (value == null) return 0;
var result = 0;
for (var i = 0; i < value.length; i++) {
result += value.charCodeAt(i);
}
return result;
};
// Ensure some object is a coerced to a string
function makeString(object) {
if (object == null) return '';
return '' + object;
};
function isObjectId(value) {
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
return checkForHexRegExp.test(value);
}
// Compares two ObjectIds (they are not equal by '==')
function equalObjectIds(value1, value2) {
if (value1 == null && value2 == null)
return true;
if (value1 == null || value2 == null)
return false;
return value1.toString() == value2.toString();
};
// Compares two ObjectIds (they are always not equal by '!=')
function notEqualObjectIds(value1, value2) {
if (value1 == null && value2 == null)
return false;
if (value1 == null || value2 == null)
return true;
return value1.toString() != value2.toString();
};
// Checks if array contains concrete objectId
function containsObjectId(values, value) {
return _.some(values, function (value1) {
return equalObjectIds(value1, value);
});
};
// Copy property from one object to another if it exists (not null)
function copyProperty(dest, destProperty, orig, origProperty) {
// Shift if only 3 arguments set
if (_.isObject(destProperty)
&& typeof (origProperty) == 'undefined') {
origProperty = orig;
orig = destProperty;
destProperty = origProperty;
}
if (orig[origProperty] || (typeof (orig[origProperty]) === 'number' && orig[origProperty] % 1 == 0)) {
dest[destProperty] = orig[origProperty];
return true;
}
return false;
};
// Swaps values of two properties
function swapProperties(obj, prop1, prop2) {
var
temp1 = obj[prop1],
temp2 = obj[prop2];
if (temp1) {
obj[prop2] = temp1;
}
else {
delete obj[prop2];
}
if (temp2) {
obj[prop1] = temp2;
}
else {
delete obj[prop1];
}
};
// Converts value into boolean
function convertToBoolean(value) {
if (value == null) return false;
if (!value) return false;
value = value.toString().toLowerCase();
return value == '1' || value == 'true';
};
// Converts array of object ids to strings (for comparison)
function convertObjectIdsToString(values) {
return _.map(values, function (value) {
return value ? value.toString() : 0;
});
};
// Generates random big number for verification codes
function generateVerificationCode() {
return Math.random().toString(36).substr(2, 10).toUpperCase(); // remove `0.`
};
// Navigation
//-------------
function goBack() {
$window.history.back()
};
function goBackAndSelect(object, idParamName, objParamName) {
pipAssert.isDef(object, 'pipUtils.goBack: first argument should be defined');
pipAssert.isDef(idParamName, 'pipUtils.goBack: second argument should be defined');
pipAssert.isDef(objParamName, 'pipUtils.goBack: third argument should be defined');
pipAssert.isObject(object, 'pipUtils.goBack: first argument should be an object');
pipAssert.isString(idParamName, 'pipUtils.goBack: second argument should a string');
pipAssert.isString(objParamName, 'pipUtils.goBack: third argument should a string');
if ($rootScope.$prevState && $rootScope.$prevState.name) {
var state = _.cloneDeep($rootScope.$prevState);
state.params[idParamName] = object.id;
state.params[objParamName] = object;
$state.go(state.name, state.params);
} else {
$window.history.back();
}
};
// Scrolling
//--------------
function scrollTo(parentElement, childElement, animationDuration) {
if(!parentElement || !childElement) return;
if (animationDuration == undefined) animationDuration = 300;
setTimeout(function () {
if (!$(childElement).position()) return;
var modDiff= Math.abs($(parentElement).scrollTop() - $(childElement).position().top);
if (modDiff < 20) return;
var scrollTo = $(parentElement).scrollTop() + ($(childElement).position().top - 20);
if (animationDuration > 0)
$(parentElement).animate({
scrollTop: scrollTo + 'px'
}, animationDuration);
}, 100);
};
// todo add support for iPhone
function getBrowser() {
var ua = $window.navigator.userAgent;
var bName = function () {
if (ua.search(/Edge/) > -1) return "edge";
if (ua.search(/MSIE/) > -1) return "ie";
if (ua.search(/Trident/) > -1) return "ie11";
if (ua.search(/Firefox/) > -1) return "firefox";
if (ua.search(/Opera/) > -1) return "opera";
if (ua.search(/OPR/) > -1) return "operaWebkit";
if (ua.search(/YaBrowser/) > -1) return "yabrowser";
if (ua.search(/Chrome/) > -1) return "chrome";
if (ua.search(/Safari/) > -1) return "safari";
if (ua.search(/Maxthon/) > -1) return "maxthon";
}();
var version;
switch (bName) {
case "edge":
version = (ua.split("Edge")[1]).split("/")[1];
break;
case "ie":
version = (ua.split("MSIE ")[1]).split(";")[0];
break;
case "ie11":
bName = "ie";
version = (ua.split("; rv:")[1]).split(")")[0];
break;
case "firefox":
version = ua.split("Firefox/")[1];
break;
case "opera":
version = ua.split("Version/")[1];
break;
case "operaWebkit":
bName = "opera";
version = ua.split("OPR/")[1];
break;
case "yabrowser":
version = (ua.split("YaBrowser/")[1]).split(" ")[0];
break;
case "chrome":
version = (ua.split("Chrome/")[1]).split(" ")[0];
break;
case "safari":
version = (ua.split("Version/")[1]).split(" ")[0];
break;
case "maxthon":
version = ua.split("Maxthon/")[1];
break;
}
var platform = 'desktop';
if (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(ua.toLowerCase())) platform = 'mobile';
var os;
try {
var osAll = (/(windows|mac|android|linux|blackberry|sunos|solaris|iphone)/.exec(ua.toLowerCase()) || [u])[0].replace('sunos', 'solaris'),
osAndroid = (/(android)/.exec(ua.toLowerCase()) || '');
os = osAndroid && (osAndroid == 'android' || (osAndroid[0] == 'android')) ? 'android' : osAll;
} catch (err) {
os = 'unknown'
}
var browsrObj;
try {
browsrObj = {
platform: platform,
browser: bName,
versionFull: version,
versionShort: version.split(".")[0],
os: os
};
} catch (err) {
browsrObj = {
platform: platform,
browser: 'unknown',
versionFull: 'unknown',
versionShort: 'unknown',
os: 'unknown'
};
}
return browsrObj;
}
// todo нужны каке нибудь настройки?
function checkSupported(supported) {
if (!supported) supported = {
edge: 11,
ie: 11,
firefox: 43, //4, for testing
opera: 35,
chrome: 47
};
var systemInfo = getBrowser();
if (systemInfo && systemInfo.browser && supported[systemInfo.browser]){
if (systemInfo.versionShort >= supported[systemInfo.browser]) return true;
}
return true;
};
}]);
})();
/**
* @file String utilities
* @copyright Digital Living Software Corp. 2014-2016
* @todo
* - Move functions to general utilities
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipUtils.Strings', []);
thisModule.factory('pipStrings', function () {
var strings = {};
// Creates a sample line from a text
strings.sampleLine = function (value, maxLength) {
if (!value || value == '') return '';
var length = value.indexOf('\n');
length = length >= 0 ? length : value.length;
length = length < maxLength ? value.length : maxLength;
return value.substring(0, length);
};
// Simple version of string hashcode
strings.hashCode = function (value) {
if (value == null) return 0;
var result = 0;
for (var i = 0; i < value.length; i++) {
result += value.charCodeAt(i);
}
return result;
};
return strings;
});
})();
/**
* @file Search tag utilities
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global _, angular */
(function () {
'use strict';
var thisModule = angular.module('pipUtils.Tags', []);
thisModule.factory('pipTags', function () {
var tags = {};
var HASHTAG_REGEX = /#\w+/g;
var normalizeTag = function (tag) {
return tag
? _.trim(tag.replace(/(_|#)+/g, ' '))
: null;
};
tags.normalizeTag = normalizeTag;
var compressTag = function (tag) {
return tag
? tag.replace(/( |_|#)/g, '').toLowerCase()
: null;
};
tags.compressTag = compressTag;
var equalTags = function (tag1, tag2) {
if (tag1 == null && tag2 == null)
return true;
if (tag1 == null || tag2 == null)
return false;
return compressTag(tag1) == compressTag(tag2);
};
tags.equalTags = equalTags;
var normalizeTags = function (tags) {
if (_.isString(tags)) {
tags = tags.split(/( |,|;)+/);
}
tags = _.map(tags, function (tag) {
return normalizeTag(tag);
});
return tags;
};
tags.normalizeTags = normalizeTags;
var compressTags = function (tags) {
if (_.isString(tags)) {
tags = tags.split(/( |,|;)+/);
}
tags = _.map(tags, function (tag) {
return compressTag(tag);
});
return tags;
};
tags.compressTags = compressTags;
var extractTags = function (entity, searchFields) {
var tags = normalizeTags(entity.tags);
_.each(searchFields, function (field) {
var text = entity[field] || '';
if (text != '') {
var hashTags = text.match(HASHTAG_REGEX);
tags = tags.concat(normalizeTags(hashTags));
}
});
return _.uniq(tags);
};
tags.extractTags = extractTags;
return tags;
});
})();
/**
* @file Collection of utilities
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
angular.module('pipUtils',
['pipUtils.General', 'pipUtils.Strings', 'pipUtils.Dates', 'pipUtils.Tags', 'pipUtils.Collections', 'pipUtils.FormErrors']);
})();
//# sourceMappingURL=pip-webui-core.js.map
|
var prompter = require('./src/keypress-prompt');
prompter
.prompt('Are you crazy', ['y', 'n'])
.then(function(choice) {
console.log('choice', choice);
process.exit(0);
});
|
import { DESCRIPTORS } from '../helpers/constants';
import getOwnPropertyDescriptor from 'core-js-pure/es/object/get-own-property-descriptor';
QUnit.test('Object.getOwnPropertyDescriptor', assert => {
assert.isFunction(getOwnPropertyDescriptor);
assert.arity(getOwnPropertyDescriptor, 2);
assert.deepEqual(getOwnPropertyDescriptor({ q: 42 }, 'q'), {
writable: true,
enumerable: true,
configurable: true,
value: 42,
});
assert.same(getOwnPropertyDescriptor({}, 'toString'), undefined);
const primitives = [42, 'foo', false];
for (const value of primitives) {
assert.notThrows(() => getOwnPropertyDescriptor(value) || true, `accept ${ typeof value }`);
}
assert.throws(() => getOwnPropertyDescriptor(null), TypeError, 'throws on null');
assert.throws(() => getOwnPropertyDescriptor(undefined), TypeError, 'throws on undefined');
});
QUnit.test('Object.getOwnPropertyDescriptor.sham flag', assert => {
assert.same(getOwnPropertyDescriptor.sham, DESCRIPTORS ? undefined : true);
});
|
function solve(args) {
var input = (args + '').split('\n').map(Number),
find, len, i, j, left, right, found;
input.splice(0, 1);
len = input.length;
find = input.splice(len - 1, 1);
len -= 1;
input.sort(function (a, b) {
if (+a < +b) {
return -1;
} else if (+a > +b) {
return 1;
} else {
return 0;
}
});
left = 0;
right = len - 1;
function BinarySearch(leftarg, rightarg) {
var leftIndex = +leftarg;
var rightIndex = +rightarg;
var mid = ((rightIndex - leftIndex) / 2 + leftIndex) | 0;
if (leftIndex === rightIndex) {
found = -1;
return;
}
if (+find === input[mid]) {
found = mid;
return;
} else if (+find < input[mid]) {
BinarySearch(leftIndex, mid);
} else {
BinarySearch(mid + 1, rightIndex);
}
}
BinarySearch(left, right);
console.log(found);
}
// solve(['10\n1\n2\n4\n8\n16\n31\n32\n64\n77\n99\n32']); |
define([
"dojo/_base/declare", "dojo/_base/lang",
"./TabViewerBase",
"../AntibioticOverview", "../AMRPanelGridContainer", "../FeatureGridContainer", "../SpecialtyGeneGridContainer",
"../../util/QueryToEnglish"
], function(declare, lang,
TabViewerBase,
AntibioticOverview, AMRPanelGridContainer, FeatureGridContainer, SpecialtyGeneGridContainer,
QueryToEnglish){
return declare([TabViewerBase], {
perspectiveLabel: "Antibiotic View",
perspectiveIconClass: "icon-selection-Antibiotic",
onSetState: function(attr, oldVal, state){
if(!state){
return;
}
if(!state.search){
this.queryNode.innerHTML = "Error";
this.totalCountNode.innerHTML = "";
}
// bypass setting attribute and invoke tabs with state
this.buildHeaderContent(state.search);
if(state.hashParams && state.hashParams.view_tab){
if(this[state.hashParams.view_tab]){
var vt = this[state.hashParams.view_tab];
vt.set("visible", true);
this.viewer.selectChild(vt);
}else{
// console.log("No view-tab supplied in State Object");
}
}
this.setActivePanelState();
},
setActivePanelState: function(){
var activeQueryState;
var active = (this.state && this.state.hashParams && this.state.hashParams.view_tab) ? this.state.hashParams.view_tab : "overview";
var activeTab = this[active];
var antibioticName = this.state.search.split(",")[1].split(")")[0];
switch(active){
case "overview":
activeTab.set("state", lang.mixin({}, this.state));
break;
case "amr":
activeTab.set("state", lang.mixin({}, this.state, {
search: "eq(antibiotic," + antibioticName + ")"
}));
break;
case "amrGenes":
activeTab.set("state", lang.mixin({}, this.state, {
search: "keyword(" + antibioticName + ")&eq(property,%22Antibiotic%20Resistance%22)"
}));
break;
case "amrRegions":
activeTab.set("state", lang.mixin({}, this.state, {
search: "keyword(" + antibioticName + ")&eq(feature_type,classifier_predicted_region)"
}));
break;
default:
if(activeQueryState){
activeTab.set("state", activeQueryState);
}else{
console.error("Missing Active Query State for: ", active);
}
break;
}
},
buildHeaderContent: function(search){
this.queryNode.innerHTML = QueryToEnglish(search);
this.totalCountNode.innerHTML = "";
},
postCreate: function(){
if(!this.state){
this.state = {}
}
this.inherited(arguments); // creates this.viewer
this.overview = new AntibioticOverview({
title: "Overview",
id: this.viewer.id + "_" + "overview"
});
this.amr = new AMRPanelGridContainer({
title: "AMR Phenotypes",
id: this.viewer.id + "_" + "amr"
});
this.amrGenes = new SpecialtyGeneGridContainer({
title: "AMR Genes",
facetFields: ["source", "evidence", "classification", "antibiotics_class", "antibiotics"],
id: this.viewer.id + "_" + "amrGenes"
});
this.amrRegions = new FeatureGridContainer({
title: "AMR Regions",
id: this.viewer.id + "_" + "amrRegions",
defaultFilter: ""
});
this.viewer.addChild(this.overview);
this.viewer.addChild(this.amr);
this.viewer.addChild(this.amrGenes);
this.viewer.addChild(this.amrRegions);
}
})
});
|
'use strict';
$.fn.quail = function (options) {
if (!this.length) {
return this;
}
quail.options = options;
quail.html = this;
quail.run(options);
return this;
};
$.expr[':'].quailCss = function (obj, index, meta) {
var args = meta[3].split(/\s*=\s*/);
return $(obj).css(args[0]).search(args[1]) > -1;
}; |
require('./assets/styles/style.css');
$(window).load(function (){
var webcom_url=__WEBCOM_SERVER__+"/base/"+__NAMESPACE__;
var bricks={};
var preview_bricks={};
var last_move="";
var color="white";
var mode="draw";
var noAuth=true;
var authData;
// Ici commence le code du "backend"
var legobase = new Webcom(webcom_url);
var domain="brick";
if (m=window.location.href.match(/#(.*)$/)) {
if (m && m[1].match(/^[A-Za-z0-9_\-]+$/)) {
domain=m[1];
}
}
// Méthode appelée pour créer/modifier/supprimer une brique à la position x,y
function updatePos(x, y) {
if (!authData)
return;
console.log(x+"-"+y);
// On "instancie" une nouvelle brique avec comme id "x-y" (c'est plus lisible coté forge)
var brick=legobase.child(domain+"/"+x+"-"+y);
// On regarde si on a déjà une valeur pour cette position
brick.once("value", function(currentData) {
if (currentData.val() === null) {
// il n'y avait pas encore de brique on l'ajoute avec la couleur actuellement sélectionné
if (mode=="draw")
brick.set({color: color, x: x, y: y, uid: authData.uid});
} else {
// il y a déjà une brique à cet emplacement.
// En mode "erase" on supprime le bloc
if (mode=="erase")
brick.set(null);
// En mode "draw" si la couleur de la brique est modifiée on averti le backend
if (mode=="draw") // && currentData.color != color)
brick.set({color: color, x: x, y: y, uid: authData.uid});
}
});
// Utilisation de la méthode transaction() qui permet de vérifier si une brique était déjà positionnée (élément existant)
/*
brick.transaction(function(currentData) {
if (currentData === null) {
// il n'y avait pas encore de brique on l'ajoute avec la couleur actuellement sélectionnée
if (mode=="draw")
return {color: color, x: x, y: y, uid: authData.uid};
} else {
// il y a déjà une brique à cet emplacement.
// En mode "erase" on supprime le bloc
if (mode=="erase")
brick.remove();
// En mode "draw" si la couleur de la brique est modifiée on averti le backend
if (mode=="draw") // && currentData.color != color)
return {color: color, x: x, y: y, uid: authData.uid};
}
});
*/
}
// Callback sur changement d'une brique. Dans notre cas c'est juste la couleur qui change
legobase.child(domain).on('child_changed', function(snapshot) {
var brick=snapshot.val();
bricks[brick.x+"-"+brick.y].removeClass().addClass("brick "+brick.color+" "+brick.uid.replace(":", "_"));
preview_bricks[brick.x+"-"+brick.y].removeClass().addClass("preview_brick "+brick.color);
if (authData && brick.uid && brick.uid == authData.uid && $("#view_my_bricks").is(":checked")) {
bricks[brick.x+"-"+brick.y].addClass("view_owner");
}
});
// Callback sur l'ajout d'une nouvelle brick
legobase.child(domain).on('child_added', function(snapshot) {
var brick=snapshot.val();
var brick_div=$('<div>', {class: "brick "+brick.color}).css('top', (20*brick.y)+"px").css('left', (20*brick.x)+"px");
if (brick.uid) {
brick_div.addClass(brick.uid.replace(":", "_"));
}
bricks[brick.x+"-"+brick.y]=brick_div;
if (authData && brick.uid && brick.uid == authData.uid && $("#view_my_bricks").is(":checked")) {
bricks[brick.x+"-"+brick.y].addClass("view_owner");
}
$("body").append(brick_div);
var brick_preview=$('<div>', {class: "preview_brick "+brick.color}).css('top', (brick.y)+"px").css('left', (brick.x)+"px");
preview_bricks[brick.x+"-"+brick.y]=brick_preview;
$("#preview_div").append(brick_preview);
$("#bricks_count").html(Object.keys(bricks).length);
});
// Callback sur la suppression d'une brique
legobase.child(domain).on('child_removed', function(snapshot) {
var brick=snapshot.val();
bricks[brick.x+"-"+brick.y].remove();
preview_bricks[brick.x+"-"+brick.y].remove();
delete bricks[brick.x+"-"+brick.y];
delete preview_bricks[brick.x+"-"+brick.y];
$("#bricks_count").html(Object.keys(bricks).length);
});
// Gestion de l'authentification
if (noAuth) {
$("#connect").hide();
$("#disconnect").hide();
authData={uid: "anonymous", provider: "none", none: {displayName: "anonymous"}};
} else {
legobase.resume(checkAuth);
}
$("#register").click(function(){
$("#simple_register").show();
});
$(".cancel").click(function(){
$(this).parent().hide();
});
$("#register_submit").click(function(){
var user_id=$("#register_user_id").val();
var password1=$("#register_password1").val();
var password2=$("#register_password2").val();
if (user_id!=null && user_id.match(/\@/)) {
if (password1!= null && password1!="" && password1.length>6) {
if (password1==password2) {
legobase.createUser(user_id, password1, checkAuth );
} else {
$("#register_error").html("Les mots de passe ne correspondent pas");
}
} else {
$("#register_error").html("Mot de passe invalide (>=6 caractères)");
}
} else {
$("#register_error").html("Adresse e-mail invalide");
}
});
function checkAuth(error, user) {
if (error) {
$("#login_error").html(error);
authData=null;
console.log("auth error: " + error);
} else {
if (user) {
console.log("auth OK: " + JSON.stringify(user));
$("#simple_login").hide();
authData={uid: user.uid, provider: "local", local: {displayName: user.email}};
legobase.child("users").child(authData.uid).set(authData);
$("#user_name").html(authData[authData.provider].displayName.replace(/@/, "<br/>@"));
$("#connect").hide();
$("#disconnect").show();
$("#erase").show();
$("#draw").show();
$(".colors").show();
} else {
console.log("not authenticated");
authData=null;
$(".owner").removeClass("view_owner");
$("#connect").show();
$("#disconnect").hide();
$("#erase").hide();
$("#draw").hide();
$(".colors").hide();
}
}
}
$("#login_submit").click(function(){
var user_id=$("#user_id").val();
var password=$("#password").val();
if (user_id!=null && user_id.match(/\@/)) {
if (password!= null && password!="") {
legobase.authWithPassword({
email : user_id,
password : password,
rememberMe : true
}, checkAuth);
} else {
$(".login_error").html("Veuillez renseigner votre mot de passe");
}
} else {
$("#login_error").html("Adresse e-mail invalide");
}
});
$(".login").click(function(){
var provider=$(this).attr("provider");
if (provider=="simple") {
$(".simple_login").show();
} else {
//TODO
}
});
$("#logout").click(function(){
legobase.logout();
});
// Ici se termine le code du "backend".
//Le reste sert à (mal) géré les évèvements souris/écran tactile
$("#view_my_bricks").change(function() {
if ($(this).is(":checked") && authData && authData.uid) {
$("."+authData.uid.replace(":", "_")).addClass("view_owner");
} else {
$("."+authData.uid.replace(":", "_")).removeClass("view_owner");
}
});
$(".close").click(function() {toggle_opt($(this).parent().attr("opt"))});
$(".colors .brick").click(function(e) {
$(".colors .brick").removeClass("active");
$(this).addClass("active");
color=$(this).attr('class').replace(/\s*(brick|active)\s*/g, '');
});
$(".little_button").click(function(e){
var opt=$(this).attr("id");
toggle_opt(opt);
});
function toggle_opt(opt_name) {
var sub_button=$("#"+opt_name+" :nth-child(1)");
if (sub_button.hasClass("fa-square-o")) {
$("#"+opt_name+" :nth-child(1)").removeClass("fa-square-o").addClass("fa-square");
$("#"+opt_name+" :nth-child(2)").removeClass("fa-inverse").addClass("fa-inverse");
$("."+opt_name+"_box").show();
} else {
$("#"+opt_name+" :nth-child(1)").removeClass("fa-square").addClass("fa-square-o");
$("#"+opt_name+" :nth-child(2)").removeClass("fa-inverse");
$("."+opt_name+"_box").hide();
}
}
$(".button").click(function(e){
change_mode($(this).attr("id"))
});
function change_mode(new_mode) {
mode=new_mode;
if (mode=="draw")
$(".colors").show();
else
$(".colors").hide();
["draw", "erase"].forEach(function(action){
if (action == mode) {
$("#"+action+" :nth-child(1)").removeClass("fa-square-o").addClass("fa-square");
$("#"+action+" :nth-child(2)").removeClass("fa-inverse").addClass("fa-inverse");
} else{
$("#"+action+" :nth-child(1)").removeClass("fa-square").addClass("fa-square-o");
$("#"+action+" :nth-child(2)").removeClass("fa-inverse");
}
});
}
if (! /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
toggle_opt("preview");
$("body").on('mousedown', function(e){
e.preventDefault();
var target = $( e.target );
var options_div=target.closest(".options");
var position = options_div.offset() || target.offset();
var initialized = {
x : position.left - e.pageX,
y : position.top - e.pageY
};
var handlers = {
mousemove : function(e){
e.preventDefault();
if (options_div.length==0) {
var x=parseInt(e.pageX / 20);
var y=parseInt(e.pageY / 20);
var new_move=x+"-"+y;
if (new_move!=last_move) {
updatePos(x,y);
}
last_move=new_move;
} else {
options_div.css({
left : ( initialized.x + e.pageX - $(document).scrollLeft() ) + 'px',
top : ( initialized.y + e.pageY - $(document).scrollTop() ) + 'px',
bottom: 'inherit',
right: 'inherit',
});
}
},
mouseup : function(e){
$(this).off(handlers);
}
};
$(document).on(handlers);
});
}
$("body").bind("click", function(e){
var target = $( e.target );
if (target.closest(".options").length==0) {
var x=parseInt(e.pageX / 20);
var y=parseInt(e.pageY / 20);
updatePos(x,y);
}
});
$(document).keypress(function(e) {
if (e.which==101 || e.which==69) {
change_mode("erase");
}else if (e.which==100 || e.which==68) {
change_mode("draw");
}
});
}); |
'use strict'
var nets = require('nets')
var _ = require('lodash')
var Aerials = function () {
this.videos_url = 'http://a1.phobos.apple.com/us/r1000/000/Features/atv/AutumnResources/videos/entries.json'
}
Aerials.prototype.get = function (opts, cb) {
var self = this
if (typeof opts === 'string') opts = { id: opts }
if (typeof opts === 'function') {
cb = opts
opts = {}
}
self._fetch(function (err, videos) {
if (err) return cb(err)
cb(null, self._findWithOptions(opts))
})
}
Aerials.prototype._fetch = function (cb) {
var self = this
nets({ url: self.videos_url, json: true }, function (err, resp, body) {
if (err) return cb(err)
self.videos = mapVideos(body)
return cb(null, self.videos)
})
}
Aerials.prototype._findWithOptions = function (opts) {
var self = this
if (!self.videos) throw new Error('no videos found')
var results = self.videos
var filters = _.pick(opts, ['city', 'timeOfDay', 'id'])
results = filters ? _.filter(results, filters) : results
return _.sample(results)
}
function mapVideos (data) {
return _(data)
.map('assets')
.flatten()
.map(function (video) {
video.city = video.accessibilityLabel
delete video.accessibilityLabel
return video
})
.value()
}
var aerials = new Aerials()
module.exports = aerials
|
// Test automatically retrieved. Do not edit manually
const { render, json } = require('server/reply');
const { get, post } = require('server/router');
const { modern } = require('server').utils;
const run = require('server/test/run');
const fs = require('mz/fs');
const path = require('path');
describe('Automatic test from content 7', () => {
it('works', async () => {
// START
// Simple visit counter for the main page
const counter = get('/', ctx => {
ctx.session.views = (ctx.session.views || 0) + 1;
return { views: ctx.session.views };
});
/* test */
await run(counter).alive(async api => {
let res = await api.get('/');
expect(res.body.views).toBe(1);
res = await api.get('/');
expect(res.body.views).toBe(2);
res = await api.get('/');
expect(res.body.views).toBe(3);
});
// END
});
});
|
sap.ui.define([
"md/flp/unit/line/line/unit/model/models",
"sap/ui/thirdparty/sinon",
"sap/ui/thirdparty/sinon-qunit"
], function (models) {
"use strict";
QUnit.module("createDeviceModel", {
afterEach : function () {
this.oDeviceModel.destroy();
}
});
function isPhoneTestCase(assert, bIsPhone) {
// Arrange
this.stub(sap.ui.Device, "system", { phone : bIsPhone });
// System under test
this.oDeviceModel = models.createDeviceModel();
// Assert
assert.strictEqual(this.oDeviceModel.getData().system.phone, bIsPhone, "IsPhone property is correct");
}
QUnit.test("Should initialize a device model for desktop", function (assert) {
isPhoneTestCase.call(this, assert, false);
});
QUnit.test("Should initialize a device model for phone", function (assert) {
isPhoneTestCase.call(this, assert, true);
});
function isTouchTestCase(assert, bIsTouch) {
// Arrange
this.stub(sap.ui.Device, "support", { touch : bIsTouch });
// System under test
this.oDeviceModel = models.createDeviceModel();
// Assert
assert.strictEqual(this.oDeviceModel.getData().support.touch, bIsTouch, "IsTouch property is correct");
}
QUnit.test("Should initialize a device model for non touch devices", function (assert) {
isTouchTestCase.call(this, assert, false);
});
QUnit.test("Should initialize a device model for touch devices", function (assert) {
isTouchTestCase.call(this, assert, true);
});
QUnit.test("The binding mode of the device model should be one way", function (assert) {
// System under test
this.oDeviceModel = models.createDeviceModel();
// Assert
assert.strictEqual(this.oDeviceModel.getDefaultBindingMode(), "OneWay", "Binding mode is correct");
});
}
); |
// what params from the proxy do we want to handle?
// const parseParams = [
// 'httpMethod',
// 'path',
// 'resource',
// 'queryStringParameters',
// 'pathParameters',
// 'stageVariables',
// 'headers',
// 'requestContext',
// 'isBase64Encoded',
// ];
// rawParams will be added to config.request - otherwise they will
// be formatted and added in a cleaner way
// const rawParams = ['headers', 'requestContext', 'isBase64Encoded'];
const handleHeader = {
'User-Agent': (value, config) => {
config.client.agent = value;
},
'X-Forwarded-For': (value, config) => {
config.client.forwardedFor = value.split(',');
},
'X-Forwarded-Port': (value, config) => {
config.client.forwardedPort = Number(value);
},
'CloudFront-Viewer-Country': (value, config) => {
config.client.country = value;
},
};
// If we want to handle the given parameter in some special way we add
// a function for it here.
const handleParam = {
httpMethod: (value, config) => {
config.method = value;
if (Array.isArray(config.methods) && !config.methods.includes(value)) {
throw new Error(`Invalid HTTP Method: ${value}`);
}
return true;
},
path: (value, config) => {
config.path = value;
return true;
},
resource: (value, config) => {
config.resource = value;
return true;
},
queryStringParameters: (value, config) => {
config.queries = value && Object.assign({}, value);
return true;
},
pathParameters: (value, config) => {
config.params = value && Object.assign({}, value);
return true;
},
stageVariables: (value, config) => {
config.stage = Object.assign({}, value);
return true;
},
requestContext: (value, config) => {
if (value && value.identity && value.identity.sourceIp) {
config.client.sourceIP = value.identity.sourceIp;
}
config.request.requestContext = value;
},
// If none are provided, we will assign to config.request[key] by default
DEFAULT: (key, value, config) => {
config.request[key] = value;
},
// headers will be read and further parsed to capture useful information
headers: (value, config) => {
config.request.headers = value;
const handledHeaders = Object.keys(handleHeader);
const receivedHeaders = Object.keys(value);
const callHandler = hdr => {
if (value[hdr] === undefined) {
return;
}
if (typeof handleHeader[hdr] === 'function') {
handleHeader[hdr](value[hdr], config);
}
};
if (handledHeaders.length >= receivedHeaders.length) {
receivedHeaders.forEach(callHandler);
} else {
handledHeaders.forEach(callHandler);
}
},
};
export default function (e, config) {
// We will take values from e and format them into our configuration
if (typeof e !== 'object') {
return;
}
// Indicate that we have a proxy
config.isProxy = true;
if (!config.request) {
config.request = {};
}
// iterate thorugh our parameters and call the handler for each.
for (const param in e) {
if (handleParam[param] === undefined) {
handleParam.DEFAULT(param, e[param], config);
} else {
const remove = handleParam[param](e[param], config);
if (remove === true) {
delete e[param];
}
}
}
}
|
define("ace/mode/sql_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var SqlHighlightRules = function() {
var keywords = (
"select|insert|update|delete|from|where|and|or|group|by|order|limit|offset|having|as|case|" +
"when|else|end|type|left|right|join|on|outer|desc|asc|union|create|table|primary|key|if|" +
"foreign|not|references|default|null|inner|cross|natural|database|drop|grant"
);
var builtinConstants = (
"true|false"
);
var builtinFunctions = (
"avg|count|first|last|max|min|sum|ucase|lcase|mid|len|round|rank|now|format|" +
"coalesce|ifnull|isnull|nv|"
);
var dataTypes = (
"int|numeric|decimal|date|varchar|char|bigint|float|double|bit|binary|text|set|timestamp|" +
"money|real|number|integer"
);
var keywordMapper = this.createKeywordMapper({
"support.function": builtinFunctions,
"keyword": keywords,
"constant.language": builtinConstants,
"storage.type": dataTypes
}, "identifier", true);
this.$rules = {
"start" : [ {
token : "comment",
regex : "--.*$"
}, {
token : "comment",
start : "/\\*",
end : "\\*/"
}, {
token : "string", // " string
regex : '".*?"'
}, {
token : "string", // ' string
regex : "'.*?'"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : keywordMapper,
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="
}, {
token : "paren.lparen",
regex : "[\\(]"
}, {
token : "paren.rparen",
regex : "[\\)]"
}, {
token : "text",
regex : "\\s+"
} ]
};
this.normalizeRules();
};
oop.inherits(SqlHighlightRules, TextHighlightRules);
exports.SqlHighlightRules = SqlHighlightRules;
});
define("ace/mode/sql",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/sql_highlight_rules","ace/range"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var SqlHighlightRules = require("./sql_highlight_rules").SqlHighlightRules;
var Range = require("../range").Range;
var Mode = function() {
this.HighlightRules = SqlHighlightRules;
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "--";
this.$id = "ace/mode/sql";
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
import React from 'react';
import { mount } from 'enzyme';
import chai, { expect } from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import { createStore } from 'redux';
import rootReducer from '../reducers/rootReducer';
import { Provider } from 'react-redux';
import Navbar from './Navbar'; // eslint-disable-line import/no-named-as-default
chai.use(sinonChai);
const ExampleToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwidXNlcm5hbWUiOiJKb2huIERvZSIsImFkbWluIjp0cnVlfQ.Y0M_wkxFaw2R8ZQUT1-nAd_2zKtzBs2almfUwZposoM";
describe('<Navbar />', () => {
describe('when user is logged out', () => {
let store;
beforeEach(() => {
store = createStore(rootReducer, {
auth: {
token: '',
username: 'user',
roles: ['user'],
isFetching: false
}
});
});
it('should render Login component', () => {
const props = {
login: sinon.spy(),
logout: sinon.spy()
};
const wrapper = mount(
<Provider store={store}>
<Navbar {...props} />
</Provider>
);
const loginComponent = wrapper.find('Login');
expect(loginComponent.length).to.equal(1);
});
});
describe('when user is logged in', () => {
let store;
beforeEach(() => {
store = createStore(rootReducer, {
auth: {
token: ExampleToken,
username: 'user',
roles: ['user'],
isFetching: false
}
});
});
it('should render Logout', () => {
const props = {
login: sinon.spy(),
logout: sinon.spy()
};
const wrapper = mount(
<Provider store={store}>
<Navbar {...props} />
</Provider>
);
const logoutButton = wrapper.find('Logout');
expect(logoutButton.length).to.equal(1);
});
});
});
|
import agent from 'superagent'
import {apiBaseUrl} from '../config'
import identity from 'lodash/identity'
const apply = ({method, dispatch, actionId, path, requestBody, transform = identity}) => {
dispatch({type: actionId, status: 'start'})
return agent[method](`${apiBaseUrl}/${path}`, requestBody)
.then(({body}) => {
dispatch({type: actionId, status: 'done', result: transform(body)})
})
.catch(error => dispatch({type: actionId, status: 'error', error}))
}
export default {
get (dispatch, actionId, path, transform) {
return apply({method: 'get', dispatch, actionId, path, transform})
},
put (dispatch, actionId, path, requestBody) {
return apply({method: 'put', dispatch, actionId, path, requestBody})
},
del (dispatch, actionId, path, id) {
dispatch({type: actionId, status: 'start'})
return agent['delete'](`${apiBaseUrl}/${path}`)
.then(({body}) => {
dispatch({type: actionId, status: 'done', id})
})
.catch(error => dispatch({type: actionId, status: 'error', error}))
}
}
|
// Libs
import PropTypes from 'prop-types';
import React from 'react';
import isObject from 'lodash/lang/isObject';
import filterProps from '../../utils/filter-html-attributes';
// Stores
import applicationStore from 'focus-core/application/built-in-store';
// Components
import Button from '../../components/button';
import Dropdown from '../../components/icon-dropdown';
import storeConnect from '../../behaviours/store/connect';
/** Connector for HeaderActions. */
const connector = storeConnect([{
store: applicationStore,
properties: ['actions']
}], () => ({
actions: applicationStore.getActions() || { primary: [], secondary: [] }
}));
/** Sub-action type. */
const subActionType = PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.string.isRequired,
action: PropTypes.func.isRequired
}));
/** Action type. */
const actionType = PropTypes.oneOfType([
PropTypes.shape({ // Icon action
label: PropTypes.string.isRequired,
action: PropTypes.func.isRequired,
icon: PropTypes.string.isRequired,
iconLibrary: PropTypes.string,
className: PropTypes.string
}),
PropTypes.shape({ // Dropdown action
icon: PropTypes.string,
iconLibrary: PropTypes.string,
action: subActionType.isRequired
})
]);
/** Proptypes validation for HeaderActions. */
const propTypes = {
actions: PropTypes.shape({
primary: PropTypes.arrayOf(actionType),
secondary: PropTypes.oneOfType([
subActionType,
actionType
])
}).isRequired
};
/**
* Render a list fab component.
* @param {object} fab Fab.
* @param {number} idx Index.
* @returns {JSXElement} Component.
*/
function renderFabListAction(fab, idx) {
if (Array.isArray(fab.action) && fab.action.length > 0) {
const { icon, iconLibrary, action, ...otherProps } = fab;
return (
<Dropdown
key={`header-action-${idx}`}
iconProps={{ name: icon, iconLibrary }}
operationList={action}
shape='fab'
{...otherProps}
/>
);
}
}
/**
* Render a fab component.
* @param {object} fab Fab.
* @returns {JSXElement} Component.
*/
function renderFabAction(fab) {
const { action, className, icon, iconLibrary, label, ...otherProps } = fab;
return (
<Button
key={`header-action-${label}`}
className={className}
handleOnClick={action}
icon={icon}
iconLibrary={iconLibrary}
label={label}
shape='fab'
type='button'
{...otherProps}
/>
);
}
/**
* HeaderActions component.
* @returns {JSXElement} Component.
*/
const HeaderActions = ({ actions: { primary, secondary }, ...otherProps }) => {
return (
<div data-focus='header-actions' {...filterProps(otherProps)}>
{primary.map((action, idx) => {
return action && Array.isArray(action.action) ? renderFabListAction(action, idx) : renderFabAction(action)
})}
{Array.isArray(secondary) && renderFabListAction({ action: secondary }, 0)}
{isObject(secondary) && renderFabListAction(secondary, 0)}
</div>
);
};
HeaderActions.displayName = 'HeaderActions';
HeaderActions.propTypes = propTypes;
export default connector(HeaderActions); |
'use strict';
var getReturnValue = require('../getReturnValue'),
throwOnUnknownProperties = require('../throwOnUnknownProperties');
var validator = function validator(options) {
options = options || {};
options.minLength = options.minLength || 0;
options.maxLength = options.maxLength || Number.MAX_VALUE;
throwOnUnknownProperties(options, ['minLength', 'maxLength', 'default']);
return function (value) {
var returnValue = getReturnValue(value, options);
if (typeof value !== 'string') {
return returnValue.false;
}
if (value.length < options.minLength) {
return returnValue.false;
}
if (value.length > options.maxLength) {
return returnValue.false;
}
if (!/^[a-zA-Z0-9]*$/.test(value)) {
return returnValue.false;
}
return returnValue.true;
};
};
module.exports = validator; |
function ContidioWidget() {
var defaultOptions = {
container: ".contidio-widget",
itemClass: "contidio-item",
translations: {
detailLink: "more",
licenseButton: "License on Contidio",
endOfExcerpt: "(The preview of the story ends here. Please license this asset to download the full story)",
fetchError: "An error occurred while trying to fetch the required data.",
noContainerError: "The container defined for the contidio widget was not found",
noRendererError: "No ContidioRenderer found"
},
hideDetailButton: false,
onListClick: null,
onListClickTarget: "_blank",
beforeRender: null,
afterRender: null,
url: "https://mdidx.contidio.com/api/v1/searchEntities/anonymous/?flags=145340470544642&startIndex=0&count=48&orderBy=2&orderDirection=2&recursive=1&types=1,2,3"
};
var Promise = require('promise-polyfill');
require('whatwg-fetch');
if (!window.Promise) {
window.Promise = Promise;
}
var $ = (typeof jQuery === 'undefined') ? require('domtastic') : jQuery;
this.items = [];
this.stringNullOrEmpty = function (str) {
return (!str || /^\s*$/.test(str));
};
this.mergeOptions = function (obj1, obj2) {
var obj3 = {};
for (var attrname in obj1) {
obj3[attrname] = obj1[attrname];
}
for (var attrname in obj2) {
obj3[attrname] = obj2[attrname];
}
return obj3;
};
this.init = function () {
this.options = this.mergeOptions(defaultOptions, contidioOptions || {});
this.options.translations = this.mergeOptions(defaultOptions.translations, contidioOptions ? contidioOptions.translations : {});
if (typeof ContidioRenderer === 'undefined') {
return this.throwError(this.options.translations.noRendererError);
}else{
this.renderer = new ContidioRenderer(this, $);
}
if ($(this.options.container).length === 0) {
return this.throwError(this.options.translations.noContainerError);
}
if (!this.stringNullOrEmpty(this.options.url)) {
this.fetchUrl(this.options.url);
}
};
this.throwError = function (message) {
console.error(message);
if(this.renderer && this.options.container){
$(options.container)[0].innerHTML = "";
$(options.container).append(renderer.renderError(error));
}
};
this.fetchUrl = function (url) {
this.items = [];
var options = this.options;
var renderer = this.renderer;
var that = this;
if(renderer.renderLoader){
$(options.container).append(renderer.renderLoader());
}
fetch(url, {
headers: {
'x-contidio-sdk': '1.0-JS-W'
}
}).then(function (response) {
return response.json();
}).then(function (json) {
that.extractItems(json);
if (typeof options.beforeRender === "function") {
options.beforeRender(that.items);
}
$(options.container)[0].innerHTML = "";
if (json.entity) {
$(options.container).append(renderer.renderListView(that.items));
} else {
$(options.container).append(renderer.renderDetailView(that.items[0]));
}
if (typeof options.afterRender === "function") {
options.afterRender(that.items);
}
if (renderer.resize) {
renderer.resize();
that.addEvent(window, "resize", function () {
renderer.resize();
});
}
}).catch(function (error) {
that.throwError(error);
});
};
this.extractItems = function (json) {
var that = this;
if (json.entity) {
json.entity.forEach(function (entity) {
that.items.push(that.getItemData(entity, false));
});
} else {
that.items.push(that.getItemData(json, true));
}
};
this.escapeHtml = function (text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
if (text)
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
return text;
};
this.getItemData = function (entity, isDetail) {
var item = {
uuid: entity.uuid,
name: entity.name ? this.escapeHtml(entity.name) : entity.uuid,
description: this.escapeHtml(entity.description) || false,
editorial: this.escapeHtml(entity.editorial) || false,
type: this.getType(entity.type),
url: "https://www.contidio.com/" + this.getType(entity.type) + "/" + entity.uuid
};
if (typeof entity.isUnlocked !== "undefined" && entity.isUnlocked === false) {
item.restricted = true;
}
if (entity.workingSetBinaryType) {
item.binaryType = this.getBinaryType(entity.workingSetBinaryType);
}
if (entity.resolvedInheritedData && entity.resolvedInheritedData.tags && entity.resolvedInheritedData.tags.tag && entity.resolvedInheritedData.tags.tag.length) {
for (var tag in entity.resolvedInheritedData.tags.tag) {
if (tag.text) {
tag.text = this.escapeHtml(tag.text);
}
}
item.tags = entity.resolvedInheritedData.tags.tag;
}
if (entity.previewBinarySet && entity.previewBinarySet[0].author) {
item.author = this.escapeHtml(entity.previewBinarySet[0].author);
}
var timeStampForLastUpdate = entity.lastUpdatedTimestamp || entity.publicationTimestamp;
var timeStampForPublicationDate = entity.publicationTimestamp || false;
var publicationDate = new Date(timeStampForPublicationDate);
var lastUpdate = new Date(timeStampForLastUpdate);
var dateToString = function(date){
return (date.getDate() < 10 ? "0" : "") + date.getDate() + "." + (date.getMonth() < 9 ? "0" : "") + (date.getMonth() + 1) + "." + date.getFullYear()
};
if(timeStampForPublicationDate){
item.publicationDate = dateToString(publicationDate);
}
item.lastUpdate = dateToString(lastUpdate);
var width = isDetail ? 875 : 350;
var previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.ASSET_LIST_PREVIEW;
if (isDetail) {
previewBinaryPurpose = item.type === "folder" ? this.CONSTANTS.BinaryPurpose.FOLDER_LIST_PREVIEW : this.CONSTANTS.BinaryPurpose.ASSET_PREVIEW;
if (item.binaryType) {
switch (item.binaryType) {
case "image":
previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.ASSET_PREVIEW;
break;
case "audio":
previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.ASSET_COVER;
item.audioSrc = this.getBinarySrc(entity, this.CONSTANTS.BinaryPurpose.ASSET_ADVANCED_PREVIEW, -1);
break;
case "video":
previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.ASSET_ADVANCED_PREVIEW_IMAGE;
item.videoSrc = this.getBinarySrc(entity, this.CONSTANTS.BinaryPurpose.ASSET_ADVANCED_PREVIEW, width);
break;
case "document":
//check if document is richtext story
if (entity.asset && entity.asset.type && entity.asset.type === 2) {
item.isStory = true;
item.coverImage = this.getBinarySrc(entity, this.CONSTANTS.BinaryPurpose.ASSET_BACKGROUND, 1920);
if (item.coverImage.indexOf("placeholder") > -1) {
item.coverImage = false;
}
var htmlSrc = this.getBinarySrc(entity, this.CONSTANTS.BinaryPurpose.ASSET_BASE, -2);
previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.ASSET_HEADER;
width = 875;
item.html = fetch(htmlSrc, {
headers: {
'x-contidio-sdk': '1.0-JS-W'
}
}).then(function (response) {
return response.text();
}).then(function (text) {
return text;
});
} else {
item.isStory = false;
previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.ASSET_ADVANCED_LIST_PREVIEW_IMAGE;
item.pdfSrc = this.getBinarySrc(entity, this.CONSTANTS.BinaryPurpose.ASSET_BASE, -2);
width = 700;
}
break;
}
}
} else {
previewBinaryPurpose = item.type === "folder" ? this.CONSTANTS.BinaryPurpose.FOLDER_LIST_PREVIEW : this.CONSTANTS.BinaryPurpose.ASSET_LIST_PREVIEW;
switch (item.type) {
case "brand":
previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.BRAND_LOGO;
break;
case "folder":
previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.FOLDER_LIST_PREVIEW;
break;
}
if (item.binaryType) {
switch (item.binaryType) {
case "video":
previewBinaryPurpose = this.CONSTANTS.BinaryPurpose.ASSET_ADVANCED_LIST_PREVIEW_IMAGE;
break;
case "document":
item.isStory = entity.asset && entity.asset.type && entity.asset.type === 2;
previewBinaryPurpose = (entity.asset && entity.asset.type === 2) ? this.CONSTANTS.BinaryPurpose.ASSET_LIST_PREVIEW : this.CONSTANTS.BinaryPurpose.ASSET_ADVANCED_LIST_PREVIEW_IMAGE;
break;
}
}
}
item.previewImage = this.getBinarySrc(entity, previewBinaryPurpose, width);
return item;
};
this.getType = function (type) {
/* TODO: switch to constants */
switch (type) {
case 0:
return "brand";
case 1:
return "folder";
case 2:
return "asset";
default:
return false;
}
};
this.getBinaryType = function (binaryType) {
/* TODO: switch to constants */
switch (binaryType) {
case 1:
return "image";
case 2:
return "audio";
case 3:
return "video";
case 4:
return "document";
default:
return "undefined";
}
};
this.getBinarySrc = function (entity, binaryPurpose, width) {
var indexToUse = -1;
if (!entity.previewBinarySet || entity.previewBinarySet.length === 0) {
return this.getPlaceholderSrc(entity);
}
var bP = binaryPurpose ? binaryPurpose : this.CONSTANTS.BinaryPurpose.ASSET_LIST_PREVIEW;
var w = width ? width : 560;
for (var i = 0; i < entity.previewBinarySet[0].calculatedBinary.length; i++) {
if (entity.previewBinarySet[0].calculatedBinary[i].binaryPurpose === bP &&
entity.previewBinarySet[0].calculatedBinary[i].outputId >= w
) {
indexToUse = i;
}
}
if (indexToUse > -1) {
return entity.previewBinarySet[0].calculatedBinary[indexToUse].downloadLink;
} else {
return this.getPlaceholderSrc(entity);
}
};
this.getPlaceholderSrc = function (entity) {
var type = this.getType(entity.type);
var binaryType = this.getBinaryType(entity.workingSetBinaryType);
if (type === "folder") {
return "https://www.contidio.com/assets/placeholders/folder_gray.png";
}
if (binaryType === "document") {
return "https://www.contidio.com/assets/placeholders/document_landscape.png";
}
return "https://www.contidio.com/assets/placeholders/" + binaryType + "_gray.png";
};
this.addEvent = function (object, type, callback) {
if (object === null || typeof(object) === 'undefined') return;
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on" + type] = callback;
}
};
this.CONSTANTS = {
EXCERPT_END_IDENTIFIER: "--SNIP--",
BinaryPurpose: {
BRAND_LOGO: 100,
BRAND_ASSET: 150,
BRAND_BACKGROUND: 200,
BRAND_BACKGROUND_TALL: 250,
BRAND_WATERMARK: 300,
FOLDER_ASSET: 1000,
FOLDER_BACKGROUND: 1100,
FOLDER_BACKGROUND_TALL: 1150,
FOLDER_LIST_PREVIEW: 1200,
JOBS_ASSET: 1500,
JOBS_BACKGROUND: 1600,
JOBS_BACKGROUND_TALL: 1650,
JOBS_LIST_PREVIEW: 1700,
JOB_ASSET: 2000,
JOB_BACKGROUND: 2100,
JOB_BACKGROUND_TALL: 2150,
JOB_LIST_PREVIEW: 2200,
PROJECT_ASSET: 3000,
PROJECT_BACKGROUND: 3100,
PROJECT_BACKGROUND_TALL: 3150,
PROJECT_LIST_PREVIEW: 3200,
ASSET_ASSET: 10000,
ASSET_BASE: 10001,
ASSET_LIST_PREVIEW: 19000,
ASSET_PREVIEW: 19001,
ASSET_ADVANCED_LIST_PREVIEW_IMAGE: 19002,
ASSET_ADVANCED_LIST_PREVIEW: 19003,
ASSET_ADVANCED_PREVIEW_IMAGE: 19004,
ASSET_ADVANCED_PREVIEW: 19005,
ASSET_COVER: 19006,
ASSET_BACKGROUND_ASSET: 19007,
ASSET_BACKGROUND: 19008,
ASSET_BACKGROUND_TALL: 19009,
ASSET_HEADER: 19010,
ASSET_SPLITVIEW_LIST_PREVIEW: 19011
}
};
}
var cw = new ContidioWidget();
cw.init();
|
version https://git-lfs.github.com/spec/v1
oid sha256:a5f2ca3e6a95a130baa25500975fed8cc95ea10ef5ce9ec0ea791ac52dc240e5
size 14919
|
$(document).ready(function(){
$("button").click(function(){
window.location = $(this).attr("url");
});
}); |
import React from 'react'; const Vessel = (props) => <svg {...props} viewBox="0 0 183 183"><g><g><g transform="translate(1, 10)"><path d="M181.19188,49.2488043 L168.050293,49.2488043 L164.604163,22.8884783 L140.815576,22.8884783 L135.492076,0 L130.168576,22.8884783 L117.528478,22.8884783 L117.528478,49.2488043 L0,49.2488043 L19.9566957,87.117663 C21.3711522,89.8179891 24.1743478,91.515337 27.2218587,91.515337 L174.466783,91.515337 C178.182946,91.515337 181.19188,88.4935435 181.19188,84.7773804 L181.19188,49.2488043 Z" transform="translate(0,30)"/></g></g></g></svg>; export default Vessel;
|
define([], function () {
return {
collation: '1700170117021703170417051706170717081709170A170B170C170E170F17101711171217131714',
compare: 'single'
};
}); |
module.exports = {
memory: require('./memory'),
// For example purposes
redis: require('./redis')
}; |
describe('pages.LiveStatistics', () => {
let $output, statistic,
LiveStatistics = window.c.root.LiveStatistics;
describe('view', () => {
beforeAll(() => {
statistic = StatisticMockery()[0];
let component = m.component(LiveStatistics);
$output = mq(component.view(component.controller(), {}));
});
it('should render statistics', () => {
expect($output.contains(window.c.h.formatNumber(statistic.total_contributed, 2, 3))).toEqual(true);
expect($output.contains(statistic.total_contributors)).toEqual(true);
});
});
});
|
/**
* Copyright (C) 2020 tt.bot dev team
*
* This file is part of tt.bot.
*
* tt.bot 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, either version 3 of the License, or
* (at your option) any later version.
*
* tt.bot 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 tt.bot. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const { Event } = require("sosamba");
const { serverLogChannel } = require("../config");
const dm = require("../lib/util/sendReplyToDMs");
const UserProfile = require("../lib/Structures/UserProfile");
class GuildJoinEvent extends Event {
constructor(...args) {
super(...args, {
name: "guildCreate"
});
}
async run(guild) {
const blacklist = await this.sosamba.db.getBlacklistedGuilds();
// blacklisting bot collection servers with intents is too expensive
if (/*this.sosamba.botCollectionServers.includes(guild)
|| */blacklist.find(entry => entry.id === guild.id || entry.ownerID === guild.ownerID)) {
guild.__automaticallyLeft = true;
await guild.leave();
return;
}
try {
await dm(guild.members.get(guild.ownerID), await this.getWelcomeMessage(guild.ownerID));
} catch { }
await this.sosamba.createMessage(serverLogChannel, {
embed: {
author: {
name: `I was added into ${guild.name} (${guild.id})`,
icon_url: guild.iconURL
},
color: 0x008800
}
});
}
async getWelcomeMessage(owner) {
const profileEntry = await this.sosamba.db.getUserProfile(owner);
let lang = "en";
if (profileEntry) {
const profile = new UserProfile(profileEntry);
lang = profile.locale || "en";
}
return {
embed: {
title: await this.sosamba.i18n.getTranslation("HI_I_AM_BOT", lang),
description: await this.sosamba.i18n.getTranslation("SOME_THINGS_SAID", lang),
fields: [{
name: await this.sosamba.i18n.getTranslation("GETTING_STARTED", lang),
value: await this.sosamba.i18n.getTranslation("GETTING_STARTED_DESCRIPTION", lang)
}, {
name: await this.sosamba.i18n.getTranslation("EVERYTHING_ELSE", lang),
value: await this.sosamba.i18n.getTranslation("EVERYTHING_ELSE_DESCRIPTION", lang)
}, {
name: await this.sosamba.i18n.getTranslation("FREE_SOFTWARE", lang),
value: await this.sosamba.i18n.getTranslation("FREE_SOFTWARE_DESCRIPTION", lang)
},
{
name: ":newspaper: Updates",
value: "You can opt into receiving updates about tt.bot by typing `tt.botupdates` into a channel where you want to receive them. This requires the bot to have the Manage Webhooks permission."
},
{
name: await this.sosamba.i18n.getTranslation("THANKS_FOR_CHOOSING", lang),
value: await this.sosamba.i18n.getTranslation("WISHING_GOOD_LUCK", lang)
}],
color: 0x008800
}
};
}
}
module.exports = GuildJoinEvent;
|
import React from 'react';
import UICard from './UICard';
const Misc = () => (
<div>
<UICard />
<UICard rank="5" suit="spade" selected />
<UICard rank="K" suit="heart" />
<UICard rank="K" suit="diamond" disabled />
<UICard rank="A" suit="diamond" selected />
<UICard rank="A" suit="heart" selected />
<UICard rank="A" suit="club" selected />
<UICard rank="A" suit="club" />
</div>
);
export default Misc;
|
'use strict';
const winston = require('winston');
const webpack = require('webpack');
const express = require('express');
const path = require('path');
function createRouter(options) {
const router = new express.Router();
const distPath = options.distPath || 'dist';
const indexFileName = options.indexFileName || 'indexPath';
const webpackConfig = options.webpackConfig;
if (!webpackConfig) {
throw new Error('options.webpackConfig is required');
}
if (process.env.NODE_ENV === 'production') {
// In production, assets are bundled at build time and served statically from
// the 'dist' folder. This is more efficient.
winston.info('Prod mode: serving client static assets.');
router.use(express.static(distPath));
router.get('*', (req, res) => res.sendFile(path.join(distPath, indexFileName)));
} else {
// In development, assets are bundled and hot-loaded on the fly. This is
// resource intensive, but allows auto-rebuilding of client and server code
// for developer convenience.
winston.info('Dev mode: serving client from webpack... Please wait.');
const compiler = webpack(webpackConfig);
const devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true
}
});
router.use(devMiddleware);
router.use(require('webpack-hot-middleware')(compiler));
router.get('*', (req, res) => res.end(
devMiddleware.fileSystem.readFileSync(
path.join(webpackConfig.output.path, indexFileName))));
}
return router;
}
module.exports = createRouter;
|
var test = require("test");
var d = require('./d');
test.assert(d.name == 'D', 'Module D is invalid');
exports.name = 'C'; |
/* global window, document */
'use strict';
var _ = require('underscore');
var constants = require('../../constants');
var keys = {
LEFT : 37,
RIGHT : 39,
SPACE : 32
};
var validKeys = [37, 39, 32];
module.exports = {
componentWillMount : function()
{
document.onkeydown = this.onKeyDown;
document.onkeyup = this.onKeyUp;
},
componentWillUnmount : function()
{
document.onkeydown = undefined;
document.onkeyup = undefined;
},
onKeyDown : function(e)
{
var game = this.getFlux().actions.game;
e = e || window.event;
if (this.ignoreKeyDown(e.keyCode)) {
return;
}
if (e.keyCode === keys.SPACE && this.state.playing === false) {
game.start();
} else if (e.keyCode === keys.SPACE && this.state.playing === true) {
game.togglePause();
} else if (this.state.playing === false) {
return;
}
this.handleArrowKeysDown(e.keyCode);
},
onKeyUp : function(e)
{
var game = this.getFlux().actions.game;
e = e || window.event;
if (! _.contains(validKeys, e.keyCode)) {
return;
}
if (e.keyCode === keys.LEFT && this.state.direction === constants.LEFT) {
game.setDirection(null);
} else if (e.keyCode === keys.RIGHT && this.state.direction === constants.RIGHT) {
game.setDirection(null);
}
},
/**
* Whether to ignore a keydown action, based on whether it contains information
* that we care about
*
* @return {Boolean}
*/
ignoreKeyDown : function(keyCode)
{
var direction = this.state.direction;
if (! _.contains(validKeys, keyCode)) {
return true;
}
if (keyCode === keys.RIGHT && direction === constants.RIGHT) {
return true;
}
if (keyCode === keys.LEFT && direction === constants.LEFT) {
return true;
}
return false;
},
handleArrowKeysDown : function(keyCode)
{
var game = this.getFlux().actions.game;
if (keyCode === keys.LEFT) {
game.setDirection(constants.LEFT);
} else if (keyCode === keys.RIGHT) {
game.setDirection(constants.RIGHT);
}
}
};
|
/* global describe, it */
import * as getFromCSV from '../src/scripts/scriptUtils/getFromCSV'
import assert from 'assert'
let input = {
surveyname: 'LFS Instructor/Course Evaluation 2016W2',
datestart: '03/24/2017',
dateclose: '04/09/2017',
crsnum: 'LFS 200 001',
crsname: 'Introduction to LFS',
crsyear: 2,
xlist: '',
deptname: 'LFS',
crs_dir: 'Justin Lee',
resp_fac: 'Justin Lee',
eval_id: 12345677,
eval_uname: 'ABCDEFGHIKL',
eval_email: 'justin@justin.com',
tsubmit: '04/09/2017 01:01:47 PM',
mobile: 0,
gradyear: 2014,
gender: 'Female',
research1: '',
research2: '',
research3: '',
'The instructor made it clear what students were expected to learn.': 3,
'The instructor communicated the subject matter effectively.': 2,
'The instructor helped inspire interest in learning the subject matter.': 1,
'Overall evaluation of student learning (through exams essays presentations etc.) was fair.': 3,
'The instructor showed concern for student learning.': 4,
'Overall the instructor was an effective teacher.': 5
}
describe('getYear', () => {
it('takes as input an object and returns the year from that object', () => {
assert.deepEqual(getFromCSV.getYear(input), 2016)
})
it('can also handle when the year is written differently', () => {
let input = {
surveyname: 'LFS Instructor/Course Evaluations - 2016W1',
datestart: '03/24/2017',
dateclose: '04/09/2017',
crsnum: 'LFS 200 001',
crsname: 'Introduction to LFS',
crsyear: 2,
xlist: '',
deptname: 'LFS',
crs_dir: 'Justin Lee',
resp_fac: 'Justin Lee',
eval_id: 12345677,
eval_uname: 'ABCDEFGHIKL',
eval_email: 'justin@justin.com',
tsubmit: '04/09/2017 01:01:47 PM',
mobile: 0,
gradyear: 2014,
gender: 'Female',
research1: '',
research2: '',
research3: '',
'The instructor made it clear what students were expected to learn.': 3,
'The instructor communicated the subject matter effectively.': 2,
'The instructor helped inspire interest in learning the subject matter.': 1,
'Overall evaluation of student learning (through exams essays presentations etc.) was fair.': 3,
'The instructor showed concern for student learning.': 4,
'Overall the instructor was an effective teacher.': 5
}
assert.deepEqual(getFromCSV.getYear(input), 2016)
})
})
describe('getTerm', () => {
it('takes as input an object and returns the term from that object', () => {
assert.deepEqual(getFromCSV.getTerm(input), 'W2')
})
it('can also handle when the year is written differently', () => {
let input = {
surveyname: 'LFS Instructor/Course Evaluations - 2016W1',
datestart: '03/24/2017',
dateclose: '04/09/2017',
crsnum: 'LFS 200 001',
crsname: 'Introduction to LFS',
crsyear: 2,
xlist: '',
deptname: 'LFS',
crs_dir: 'Justin Lee',
resp_fac: 'Justin Lee',
eval_id: 12345677,
eval_uname: 'ABCDEFGHIKL',
eval_email: 'justin@justin.com',
tsubmit: '04/09/2017 01:01:47 PM',
mobile: 0,
gradyear: 2014,
gender: 'Female',
research1: '',
research2: '',
research3: '',
'The instructor made it clear what students were expected to learn.': 3,
'The instructor communicated the subject matter effectively.': 2,
'The instructor helped inspire interest in learning the subject matter.': 1,
'Overall evaluation of student learning (through exams essays presentations etc.) was fair.': 3,
'The instructor showed concern for student learning.': 4,
'Overall the instructor was an effective teacher.': 5
}
assert.deepEqual(getFromCSV.getTerm(input), 'W1')
})
})
describe('getCourse', () => {
it('takes as input an object and returns the course without the section number', () => {
let input = {
crsnum: 'FRE 385/FRE 585 001'
}
assert.deepEqual(getFromCSV.getCourse(input), 'FRE 385/FRE 585')
})
})
describe('getDeptFromCourseNum', () => {
it('takes as input an object and returns the depts without the section number', () => {
let input = {
crsnum: 'FRE 385/FRE 585 001'
}
assert.deepEqual(getFromCSV.getDeptFromCourseNum(input), ['FRE', 'FRE'])
input = {
crsnum: 'LFS 200 001'
}
assert.deepEqual(getFromCSV.getDeptFromCourseNum(input), ['LFS'])
})
})
describe('getSection', () => {
it('takes as input an object and returns the section number of the course', () => {
assert.deepEqual(getFromCSV.getSection(input), '001')
input = {
surveyname: 'LFS Instructor/Course Evaluation 2016W2',
datestart: '03/24/2017',
dateclose: '04/09/2017',
crsnum: 'FRE 385/FRE 585 001',
crsname: 'Introduction to LFS',
crsyear: 2,
xlist: '',
deptname: 'LFS',
crs_dir: 'Justin Lee',
resp_fac: 'Justin Lee',
eval_id: 12345677,
eval_uname: 'ABCDEFGHIKL',
eval_email: 'justin@justin.com',
tsubmit: '04/09/2017 01:01:47 PM',
mobile: 0,
gradyear: 2014,
gender: 'Female',
research1: '',
research2: '',
research3: '',
'The instructor made it clear what students were expected to learn.': 3,
'The instructor communicated the subject matter effectively.': 2,
'The instructor helped inspire interest in learning the subject matter.': 1,
'Overall evaluation of student learning (through exams essays presentations etc.) was fair.': 3,
'The instructor showed concern for student learning.': 4,
'Overall the instructor was an effective teacher.': 5
}
assert.deepEqual(getFromCSV.getSection(input), '001')
})
})
describe('getDept', () => {
it('takes an object and returns the dept', () => {
assert.deepEqual(getFromCSV.getDept(input), 'LFS')
})
})
describe('getInstructorName', () => {
it('takes an object and returns the instructor name', () => {
assert.deepEqual(getFromCSV.getInstructorName(input), 'Justin Lee')
})
})
describe('UMIGets', () => {
it('gets the value of the UMIs', () => {
assert.deepEqual(getFromCSV.getUMI1(input), 3)
assert.deepEqual(getFromCSV.getUMI2(input), 2)
assert.deepEqual(getFromCSV.getUMI3(input), 1)
assert.deepEqual(getFromCSV.getUMI4(input), 3)
assert.deepEqual(getFromCSV.getUMI5(input), 4)
assert.deepEqual(getFromCSV.getUMI6(input), 5)
})
})
describe('getEnrolmentCourseNumber', () => {
it('takes a crsnum and returns the portion before the "." because some crsnums for some reason have sections attached', () => {
let input = 'AGRO 260.001'
let output = 'AGRO 260'
assert.deepEqual(getFromCSV.getEnrolmentCourseNumber(input), output)
})
it('can handle if an input with no period is entered', () => {
let input = 'AGRO 260'
let output = 'AGRO 260'
assert.deepEqual(getFromCSV.getEnrolmentCourseNumber(input), output)
})
})
describe('getEnrolmentSection', () => {
it('takes a section and returns the section with trailing 0s if necessary, can take a number as input and returns a string', () => {
let input = 1
let output = '001'
assert.deepEqual(getFromCSV.getEnrolmentSection(input), output)
})
it('can handle a correct input as well', () => {
let input = '001'
let output = '001'
assert.deepEqual(getFromCSV.getEnrolmentSection(input), output)
input = '99A'
output = '99A'
assert.deepEqual(getFromCSV.getEnrolmentSection(input), output)
})
})
describe('getEnrolmentYear', () => {
it('takes a period and returns the year', () => {
let input = '2016W1'
let output = 2016
assert.deepEqual(getFromCSV.getEnrolmentYear(input), output)
})
})
describe('getEnrolmentTerm', () => {
it('takes a period and returns the term', () => {
let input = '2016W1'
let output = 'W1'
assert.deepEqual(getFromCSV.getEnrolmentTerm(input), output)
})
})
describe('getUniqYears', () => {
it('takes an array and returns only the uniq years', () => {
let input = [
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2014W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2017W2'}
]
let output = [2016, 2014, 2017]
assert.deepEqual(getFromCSV.getUniqYears(input), output)
})
})
describe('getUniqTerms', () => {
it('takes an array and returns only the uniq years', () => {
let input = [
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2014W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2016W2'},
{surveyname: 'LFS Instructor/Course Evaluation 2016S'},
{surveyname: 'LFS Instructor/Course Evaluation 2017W1'}
]
let output = ['W2', 'S', 'W1']
assert.deepEqual(getFromCSV.getUniqTerms(input), output)
})
})
describe('getUniqDepts', () => {
it('takes an array and returns only the uniq dept', () => {
let input = [
{deptname: 'LFS'},
{deptname: 'APBI'},
{deptname: 'CPSC'},
{deptname: 'CPSC'},
{deptname: 'LFS'}
]
let output = ['LFS', 'APBI', 'CPSC']
assert.deepEqual(getFromCSV.getUniqDepts(input), output)
})
})
|
/* eslint no-underscore-dangle: "off" */
import componentsRouter from './components-router';
import f7, { f7Instance } from './f7';
function f7ready(callback) {
f7.ready(callback);
}
const f7Theme = {};
const Plugin = {
name: 'phenomePlugin',
installed: false,
install(params = {}) {
if (Plugin.installed) return;
Plugin.installed = true;
const Framework7 = this;
f7.Framework7 = Framework7;
f7.events = new Framework7.Events();
// eslint-disable-next-line
const { theme } = params;
if (theme === 'md') f7Theme.md = true;
if (theme === 'ios') f7Theme.ios = true;
if (theme === 'aurora') f7Theme.aurora = true;
if (!theme || theme === 'auto') {
f7Theme.ios = !!Framework7.device.ios;
f7Theme.aurora = Framework7.device.desktop && Framework7.device.electron;
f7Theme.md = !f7Theme.ios && !f7Theme.aurora;
}
f7.ready(() => {
f7Theme.ios = f7.instance.theme === 'ios';
f7Theme.md = f7.instance.theme === 'md';
f7Theme.aurora = f7.instance.theme === 'aurora';
});
// Extend F7 Router
Framework7.Router.use(componentsRouter);
},
};
export { f7ready, f7Instance as f7, f7Theme as theme };
export default Plugin;
|
var async = require('async');
var mongoose = require('mongoose');
require(process.cwd() + '/lib/connection');
var Employee = mongoose.model('Employee');
var Team = mongoose.model('Team');
var data = {
employees: [
{
id: '1000003',
name: {
first: 'Colin',
last: 'Ihrig'
},
image: 'images/employees/1000003.png',
address: {
lines: ['11 Wall Street'],
city: 'New York',
state: 'NY',
zip: 10118
}
},
{
id: '1000021',
name: {
first: 'Adam',
last: 'Bretz'
},
address: {
lines: ['46 18th St','St. 210'],
city: 'Pittsburgh',
state: 'PA',
zip: 15222
}
},
{
id: '1000022',
name: {
first: 'Matt',
last: 'Liegey'
},
address: {
lines: ['2 S Market Square','(Market Square)'],
city: 'Pittsburgh',
state: 'PA',
zip: 15222
}
},
{
id: '1000025',
name: {
first: 'Aleksey',
last: 'Smolenchuk'
},
image: 'images/employees/1000025.png' /* invalid image */,
address: {
lines: ['3803 Forbes Ave'],
city: 'Pittsburgh',
state: 'PA',
zip: 15213
}
},
{
id: '1000030',
name: {
first: 'Sarah',
last: 'Gay'
},
address: {
lines: ['8651 University Blvd'],
city: 'Pittsburgh',
state: 'PA',
zip: 15108
}
},
{
id: '1000031',
name: {
first: 'Dave',
last: 'Beshero'
},
address: {
lines: ['1539 Washington Rd'],
city: 'Mt Lebanon',
state: 'PA',
zip: 15228
}
}
],
teams: [
{
name: 'Software and Services Group'
},
{
name: 'Project Development'
}
]
};
var deleteEmployees = function(callback) {
console.info('Deleting employees');
Employee.remove({}, function(error, response) {
if (error) {
console.error('Error deleting employees: ' + error);
}
console.info('Done deleting employees');
callback();
});
};
var addEmployees = function(callback) {
console.info('Adding employees');
Employee.create(data.employees, function (error) {
if (error) {
console.error('Error: ' + error);
}
console.info('Done adding employees');
callback();
});
};
var deleteTeams = function(callback) {
console.info('Deleting teams');
Team.remove({}, function(error, response) {
if (error) {
console.error('Error deleting teams: ' + error);
}
console.info('Done deleting teams');
callback();
});
};
var addTeams = function(callback) {
console.info('Adding teams');
Team.create(data.teams, function (error, team1) {
if (error) {
console.error('Error: ' + error);
} else {
data.team_id = team1._id;
}
console.info('Done adding teams');
callback();
});
};
var updateEmployeeTeams = function (callback) {
console.info('Updating employee teams');
var team = data.teams[0];
// Set everyone to be on the same team to start
Employee.update({}, {
team: data.team_id
}, {
multi: true
}, function (error, numberAffected, response) {
if (error) {
console.error('Error updating employe team: ' + error);
}
console.info('Done updating employee teams');
callback();
});
};
async.series([
deleteEmployees,
deleteTeams,
addEmployees,
addTeams,
updateEmployeeTeams
], function(error, results) {
if (error) {
console.error('Error: ' + error);
}
mongoose.connection.close();
console.log('Done!');
});
|
/**
* @fileoverview Responsible for loading ignore config files and managing ignore patterns
* @author Jonathan Rajavuori
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var fs = require("fs"),
path = require("path"),
debug = require("debug"),
ignore = require("ignore"),
assign = require("object-assign"),
FileFinder = require("./file-finder");
debug = debug("eslint:ignored-paths");
//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
var ESLINT_IGNORE_FILENAME = ".eslintignore";
var DEFAULT_IGNORE_PATTERNS = [
"/node_modules/",
"/bower_components/"
];
var DEFAULT_OPTIONS = {
dotfiles: false,
cwd: process.cwd()
};
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
var ignoreFileFinder;
/**
* Find an ignore file in the current directory or a parent directory.
* @param {stirng} cwd Current working directory
* @returns {string} Path of ignore file or an empty string.
*/
function findIgnoreFile(cwd) {
cwd = cwd || DEFAULT_OPTIONS.cwd;
if (!ignoreFileFinder) {
ignoreFileFinder = new FileFinder(ESLINT_IGNORE_FILENAME, cwd);
}
return ignoreFileFinder.findInDirectoryOrParents(cwd);
}
/**
* Replace Windows with Unix style paths and remove ./ prefix
* @param {string} filepath Path to normalize
* @returns {string} Normalized filepath
*/
function normalizeFilepath(filepath) {
filepath = filepath.replace("\\", "/");
filepath = filepath.replace(/^\.\//, "");
return filepath;
}
/**
* Remove a prefix from a filepath
* @param {string} filepath Path to remove the prefix from
* @param {string} prefix Prefix to remove from filepath
* @returns {string} Normalized filepath
*/
function removePrefixFromFilepath(filepath, prefix) {
prefix += "/";
if (filepath.indexOf(prefix) === 0) {
filepath = filepath.substr(prefix.length);
}
return filepath;
}
/**
* Resolves a filepath
* @param {string} filepath Path resolve
* @param {string} baseDir Base directory to resolve the filepath from
* @returns {string} Resolved filepath
*/
function resolveFilepath(filepath, baseDir) {
if (baseDir) {
var base = path.resolve(baseDir);
filepath = removePrefixFromFilepath(filepath, base);
filepath = removePrefixFromFilepath(filepath, fs.realpathSync(base));
}
filepath.replace(/^\//, "");
return filepath;
}
/**
* Normalize and resolve a filepath relative to a given base directory
* @param {string} filepath Path resolve
* @param {string} baseDir Base directory to resolve the filepath from
* @returns {string} Normalized and resolved filepath
*/
function normalizeAndResolveFilepath(filepath, baseDir) {
filepath = normalizeFilepath(filepath);
return resolveFilepath(filepath, baseDir);
}
/**
* Merge options with defaults
* @param {object} options Options to merge with DEFAULT_OPTIONS constant
* @returns {object} Merged options
*/
function mergeDefaultOptions(options) {
options = (options || {});
return assign({}, DEFAULT_OPTIONS, options);
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* IgnoredPaths
* @constructor
* @class IgnoredPaths
* @param {Object} options object containing 'ignore', 'ignorePath' and 'patterns' properties
*/
function IgnoredPaths(options) {
options = mergeDefaultOptions(options);
/**
* add pattern to node-ignore instance
* @param {object} ig, instance of node-ignore
* @param {string} pattern, pattern do add to ig
* @returns {array} raw ignore rules
*/
function addPattern(ig, pattern) {
return ig.addPattern(pattern);
}
/**
* add ignore file to node-ignore instance
* @param {object} ig, instance of node-ignore
* @param {string} filepath, file to add to ig
* @returns {array} raw ignore rules
*/
function addIgnoreFile(ig, filepath) {
var fileContent = fs.readFileSync(filepath, "utf8");
fileContent = fileContent.replace(/\*\*/g, "*");
return ig.addIgnoreFile(filepath);
}
this.defaultPatterns = DEFAULT_IGNORE_PATTERNS.concat(options.patterns || []);
this.baseDir = ".";
this.ig = {
custom: new ignore.Ignore({
twoGlobstars: true,
ignore: []
}),
default: new ignore.Ignore({
twoGlobstars: true,
ignore: []
})
};
if (options.dotfiles !== true) {
addPattern(this.ig.default, ".*");
}
if (options.ignore !== false) {
addPattern(this.ig.default, this.defaultPatterns);
var ignorePath;
if (options.ignorePattern) {
addPattern(this.ig.custom, options.ignorePattern);
}
if (options.ignorePath) {
try {
fs.statSync(options.ignorePath);
ignorePath = options.ignorePath;
} catch (e) {
e.message = "Cannot read ignore file: " + options.ignorePath + "\nError: " + e.message;
throw e;
}
} else {
ignorePath = findIgnoreFile(options.cwd);
try {
fs.statSync(ignorePath);
} catch (e) {
this.options = options;
}
}
if (ignorePath) {
this.baseDir = path.dirname(ignorePath);
addIgnoreFile(this.ig.custom, ignorePath);
}
}
this.options = options;
return this;
}
/**
* Determine whether a file path is included in the default or custom ignore patterns
* @param {string} filepath Path to check
* @param {string} [category=null] check 'default', 'custom' or both (null)
* @returns {boolean} true if the file path matches one or more patterns, false otherwise
*/
IgnoredPaths.prototype.contains = function(filepath, category) {
var result = false;
filepath = normalizeAndResolveFilepath(filepath, this.baseDir);
if ((typeof category === "undefined") || (category === "default")) {
result = result || (this.ig.default.filter([filepath]).length === 0);
}
if ((typeof category === "undefined") || (category === "custom")) {
result = result || (this.ig.custom.filter([filepath]).length === 0);
}
return result;
};
module.exports = IgnoredPaths;
|
'use strict';
module.exports = {
domain: 'www.abc.com', // domain of you web app (Important!)
portIndex: 9527, // port that socket.io will listen to
logRootFolder: '/path/to/your/log/folder/', // folder path of your log files
servers: ['127.0.0.1'], // ip of your servers
logs: ['a.log', 'b.log'], // log file name
};
|
var util = require("util");
var _ = require("lodash");
var Resource = require("./resource");
var camelKeys = require('camelcase-keys');
function ThreadItem(session, params) {
Resource.apply(this, arguments);
}
util.inherits(ThreadItem, Resource);
module.exports = ThreadItem;
var Account = require('./account');
var Media = require('./media');
var Location = require('./location');
var Link = require('./link');
var Placeholder = require('./placeholder');
var Hashtag = require('./hashtag');
ThreadItem.prototype.parseParams = function (json) {
var hash = camelKeys(json);
hash.id = json.item_id || json.id;
hash.type = json.item_type;
if(hash.type === "link"){
hash.link = 'link';
this.link = new Link(this.session, json.link)
}
if(hash.type === "placeholder"){
hash.placeholder = 'placeholder';
this.placeholder = new Placeholder(this.session, json.placeholder)
}
if (hash.type === "text") {
hash.text = json.text;
}
if (hash.type === "media") {
hash.media = json.media.image_versions2.candidates;
if (json.reactions) {
hash.reactions = json.reactions;
}
}
if (hash.type === "media_share") {
hash.type = 'mediaShare';
this.mediaShare = new Media(this.session, json.media_share)
}
if (hash.type === "action_log") {
hash.type = 'actionLog';
hash.actionLog = json.action_log;
}
if (hash.type === "profile") {
this.profile = new Account(this.session, json.profile);
hash.profileMediaPreview = _.map(json.preview_medias || [], function (medium) {
return {
id: medium.id.toString(),
images: medium.image_versions2.candidates
}
})
}
// @Todo media preview just like profile for location and hashtag
if (hash.type === "location") {
var location = json.location;
location.location = Object.create(json.location);
location.title = location.name;
location.subtitle = null;
this.location = new Location(this.session, location);
}
if (hash.type === "hashtag") {
this.hashtag = new Hashtag(this.session, json.hashtag);
}
hash.accountId = json.user_id;
hash.created = parseInt(json.timestamp / 1000);
return hash;
};
ThreadItem.prototype.getParams = function() {
var params = _.clone(this._params);
if(params.type == 'link')
params.link = this.link.params;
if(params.type == 'placeholder')
params.placeholder = this.placeholder.params;
if(params.type == 'mediaShare')
params.mediaShare = this.mediaShare.params;
if(params.type == 'profile')
params.profile = this.profile.params;
if(params.type == 'location')
params.location = this.location.params;
if(params.type == 'hashtag')
params.hashtag = this.hashtag.params;
return params;
}
|
/*********************
* UserList Controller
**********************/
(function () {
'use strict';
angular.module('app.controllers')
.controller('UserListCtrl', UserListCtrl);
UserListCtrl.$inject = ['userData', 'logger'];
function UserListCtrl(userData, logger) {
var vm = this;
vm.getAllUsers = getAllUsers;
getAllUsers();
function getAllUsers() {
userData.getAllUsers()
.then(onGetUsersSuccess, onGetUsersFailed);
}
// PRIVATE FUNCTIONS
function onGetUsersSuccess(response) {
vm.users = response;
logger.log(response);
}
function onGetUsersFailed(error) {
logger.error(error);
}
}
}());
|
/* eslint-disable no-unused-expressions */
import React from 'react';
import { mount, shallow } from 'enzyme';
import sinon from 'sinon';
import { ipcRenderer } from 'electron';
import { expect } from 'chai';
import Settings from './settings';
const defaultProps = {
config: {},
changePage: () => {},
update: () => {},
updateShortCut: () => {}
};
const settingsFactory = (props, render = mount) => render(<Settings {...defaultProps} {...props} />);
describe('<Settings />', () => {
it('renders', () => {
expect(settingsFactory()).to.have.length(1);
});
describe('on mount', () => {
before(() => {
sinon.spy(ipcRenderer, 'send');
});
after(() => {
ipcRenderer.send.restore();
});
it('calls `ipcRenderer` `newHeight` on mount', () => {
settingsFactory();
expect(ipcRenderer.send.calledWith('newHeight')).to.be.true;
});
});
describe('on unmount', () => {
before(() => {
sinon.spy(ipcRenderer, 'send');
});
after(() => {
ipcRenderer.send.restore();
});
it('calls `ipcRenderer` `resetHeight` on unmount', () => {
const cmp = settingsFactory();
cmp.unmount();
expect(ipcRenderer.send.calledWith('resetHeight')).to.be.true;
});
});
describe('navigate home', () => {
it('renders a close button', () => {
expect(settingsFactory().find('.qa-home')).to.have.length(1);
});
it('fires `changePage` with `home` when the close button is clicked', (done) => {
const btn = settingsFactory({
changePage: (page) => {
expect(page).to.eql('home');
done();
}
}).find('.qa-home');
btn.simulate('click');
});
});
describe('copy options', () => {
it('renders a copy options Select', () => {
expect(settingsFactory().find('.qa-cp')).to.have.length(1);
});
it('sets the correct copy option based on the `copy` config', () => {
const copy = 'url';
const sel = settingsFactory({
config: { copy }
}, shallow).find('.qa-cp');
expect(sel.prop('value')).to.eql(copy);
});
it('calls update when the copy select is changed', (done) => {
const copy = 'url';
const value = 'newSetting';
const sel = settingsFactory({
update: (k, v) => {
expect(k).to.eql('copy');
expect(v).to.eql(value);
done();
},
config: { copy }
}, shallow).find('.qa-cp');
sel.prop('onChange')({
target: {
value
}
});
});
});
describe('preview options', () => {
it('renders preview options buttons', () => {
const bg = settingsFactory({}, shallow).find('.qa-prev');
bg.children().forEach(b => expect(b.name()).to.eql('Button'));
});
it('sets the correct preview option based on the `preview` config', () => {
const bg = settingsFactory({
config: {
preview: 'gif'
}
}, shallow).find('.qa-prev');
expect(bg.childAt(0).prop('isActive')).to.be.true;
});
it('calls update when the preview is changed', (done) => {
const value = 'gif';
const bg = settingsFactory({
config: {
preview: 'mp4'
},
update: (k, v) => {
expect(k).to.eql('preview');
expect(v).to.eql(value);
done();
}
}, shallow).find('.qa-prev');
bg.childAt(0).prop('onClick')({
target: {
value
}
});
});
});
describe('on start options', () => {
it('renders on start options buttons', () => {
const bg = settingsFactory({}, shallow).find('.qa-str');
bg.children().forEach(b => expect(b.name()).to.eql('Button'));
});
it('sets the correct on start option based on the `login` config', () => {
const bg = settingsFactory({
config: {
login: false
}
}, shallow).find('.qa-str');
expect(bg.childAt(0).prop('isActive')).to.be.true;
});
it('calls update when the on start is changed', (done) => {
const bg = settingsFactory({
config: {
login: false
},
update: (k, v) => {
expect(k).to.eql('login');
expect(v).to.be.true;
done();
}
}, shallow).find('.qa-str');
bg.childAt(1).prop('onClick')(true);
});
});
describe('global shortcut', () => {
const props = {
config: {
shortcut: 'ctrl+0'
}
};
const sc = settingsFactory(props).find('Shortcut');
it('renders', () => {
expect(sc).to.have.length(1);
});
it('passes the current shortcut config down to <Shortcut />', () => {
expect(sc.prop('currentShortcut')).to.eql(props.config.shortcut);
});
it('passes `updateShortCut` down to <Shortcut />', () => {
expect(sc.prop('updateShortCut')).to.eql(defaultProps.updateShortCut);
});
});
});
|
/* eslint-env mocha */
import { assert } from 'chai';
import { create as createJss } from 'jss';
import DomRenderer from 'jss/lib/backends/DomRenderer';
import preset from 'jss-preset-default';
import { createStyleManager, createStyleSheet } from 'src';
describe('basic usage', () => {
let themeObj;
let styleManager;
let styleSheet;
let classes;
before(() => {
themeObj = {
fontFamily: 'Roboto',
fontSize: 12,
color: 'red',
};
styleManager = createStyleManager({
jss: createJss(preset()),
theme: themeObj,
});
styleSheet = createStyleSheet('button', (theme) => ({
root: {
color: theme.color,
fontSize: theme.fontSize,
fontFamily: theme.fontFamily,
},
}), { Renderer: DomRenderer });
});
afterEach(() => {
styleManager.reset();
});
it('should start with no stylesheets in the DOM', () => {
const styleElements = document.querySelectorAll('style');
assert.strictEqual(styleElements.length, 0, 'should have no style tags');
});
describe('rendering to the DOM', () => {
let styleElement;
before(() => {
classes = styleManager.render(styleSheet);
});
it('should render the stylesheet to the DOM', () => {
const styleElements = document.querySelectorAll('style');
assert.strictEqual(styleElements.length, 1, 'should have 1 style tag');
styleElement = styleElements[0];
assert.strictEqual(
styleElement.getAttribute('data-meta'),
`button-${themeObj.id}`,
'should have the stylesheet name as the data-meta attribute',
);
const { style } = styleElement.sheet.cssRules[0];
assert.strictEqual(style.color, themeObj.color);
assert.strictEqual(style['font-size'], `${themeObj.fontSize}px`);
assert.strictEqual(style['font-family'], themeObj.fontFamily);
});
it('should return the classNames', () => {
const { selectorText } = styleElement.sheet.cssRules[0];
assert.strictEqual(
typeof classes.root,
'string',
'should return a className on the root key',
);
assert.strictEqual(
classes.root.indexOf('button-'),
0,
'should prefix the selector with the sheet name',
);
assert.strictEqual(
`.${classes.root}`,
selectorText,
'should match the selectorText',
);
});
});
});
|
/*!
* mobserver.js - A UX Tracking Infromation Generator
*
* Copyright (c) 2014 Barış Güler
* http://hwclass.github.io
*
* Licensed under MIT
* http://www.opensource.org/licenses/mit-license.php
*
* github.com/hwclass/mobserver/README.md
* Script Guideline
*
* Launch : September 2014
* Version : 0.1.0
* Released: September xxx, 2014
*
*
* tracks user interactions over a page in order to supply informations for user experience statistics
*/
var mobserver = (function(w, undefined) {
var inputs = document.getElementsByTagName('input');
window.onmousemove = handleMouseMove;
function handleMouseMove(event) {
event = event || window.event;
log('X: ' + event.clientX + ' Y: ' + event.clientY);
};
var log = function (message) {
console.log(message);
};
var logInputs = function() {
for (var countForInputs = 0, len = inputs.length; countForInputs < len; countForInputs++) {
log('input name: ' + inputs[countForInputs].name + (inputs[countForInputs].type === 'button' ? '' : ', ' + 'value: ' + inputs[countForInputs].value) );
}
};
return {
logInputs : logInputs
}
})(window); |
import { deprecate } from 'ember-metal/debug';
import calculateLocationDisplay from '../system/calculate-location-display';
/**
@module ember
@submodule ember-htmlbars
*/
/**
An HTMLBars AST transformation that replaces all instances of
```handlebars
{{input on="enter" action="doStuff"}}
{{input on="key-press" action="doStuff"}}
```
with
```handlebars
{{input enter="doStuff"}}
{{input key-press="doStuff"}}
```
@private
@class TransformInputOnToOnEvent
*/
export default function TransformInputOnToOnEvent(options = {}) {
// set later within HTMLBars to the syntax package
this.syntax = null;
this.options = options;
}
/**
@private
@method transform
@param {AST} ast The AST to be transformed.
*/
TransformInputOnToOnEvent.prototype.transform = function TransformInputOnToOnEvent_transform(ast) {
let pluginContext = this;
let b = pluginContext.syntax.builders;
let walker = new pluginContext.syntax.Walker();
let moduleName = pluginContext.options.moduleName;
walker.visit(ast, function(node) {
if (pluginContext.validate(node)) {
let action = hashPairForKey(node.hash, 'action');
let on = hashPairForKey(node.hash, 'on');
let onEvent = hashPairForKey(node.hash, 'onEvent');
let normalizedOn = on || onEvent;
let moduleInfo = calculateLocationDisplay(moduleName, node.loc);
if (normalizedOn && normalizedOn.value.type !== 'StringLiteral') {
deprecate(
`Using a dynamic value for '#{normalizedOn.key}=' with the '{{input}}' helper ${moduleInfo}is deprecated.`,
false,
{ id: 'ember-template-compiler.transform-input-on-to-onEvent.dynamic-value', until: '3.0.0' }
);
normalizedOn.key = 'onEvent';
return; // exit early, as we cannot transform further
}
removeFromHash(node.hash, normalizedOn);
removeFromHash(node.hash, action);
if (!action) {
deprecate(
`Using '{{input ${normalizedOn.key}="${normalizedOn.value.value}" ...}}' without specifying an action ${moduleInfo}will do nothing.`,
false,
{ id: 'ember-template-compiler.transform-input-on-to-onEvent.no-action', until: '3.0.0' }
);
return; // exit early, if no action was available there is nothing to do
}
let specifiedOn = normalizedOn ? `${normalizedOn.key}="${normalizedOn.value.value}" ` : '';
if (normalizedOn && normalizedOn.value.value === 'keyPress') {
// using `keyPress` in the root of the component will
// clobber the keyPress event handler
normalizedOn.value.value = 'key-press';
}
let expected = `${normalizedOn ? normalizedOn.value.value : 'enter'}="${action.value.original}"`;
deprecate(
`Using '{{input ${specifiedOn}action="${action.value.original}"}}' ${moduleInfo}is deprecated. Please use '{{input ${expected}}}' instead.`,
false,
{ id: 'ember-template-compiler.transform-input-on-to-onEvent.normalized-on', until: '3.0.0' }
);
if (!normalizedOn) {
normalizedOn = b.pair('onEvent', b.string('enter'));
}
node.hash.pairs.push(b.pair(
normalizedOn.value.value,
action.value
));
}
});
return ast;
};
TransformInputOnToOnEvent.prototype.validate = function TransformWithAsToHash_validate(node) {
return node.type === 'MustacheStatement' &&
node.path.original === 'input' &&
(
hashPairForKey(node.hash, 'action') ||
hashPairForKey(node.hash, 'on') ||
hashPairForKey(node.hash, 'onEvent')
);
};
function hashPairForKey(hash, key) {
for (let i = 0; i < hash.pairs.length; i++) {
let pair = hash.pairs[i];
if (pair.key === key) {
return pair;
}
}
return false;
}
function removeFromHash(hash, pairToRemove) {
let newPairs = [];
for (let i = 0; i < hash.pairs.length; i++) {
let pair = hash.pairs[i];
if (pair !== pairToRemove) {
newPairs.push(pair);
}
}
hash.pairs = newPairs;
}
|
function swap(input, index_A, index_B) {
var temp = input[index_A];
input[index_A] = input[index_B];
input[index_B] = temp;
}
app.controller('angelCafeSpecialtyListCtrl', function($scope, Specialty, toastr){
var vm = this;
vm.specialtyList = []
Specialty.all().then(function(d){
console.log(d.data)
if (d.data.length > 0) {
vm.specialtyList = d.data[0].specialties
}
})
vm.add = function(newItem) {
// alert('aaa')
vm.specialtyList.push(newItem)
vm.newItem = ''
Specialty.update({specialties: vm.specialtyList}).then(function(d){
})
}
vm.delete = function(index) {
vm.specialtyList.splice(index, 1)
Specialty.update({specialties: vm.specialtyList}).then(function(d){
})
}
vm.changed = function(index, item) {
if (vm.specialtyList[index] !== item) {
console.log('changed ', item)
vm.specialtyList[index] = item
Specialty.update({specialties: vm.specialtyList}).then(function(d){
toastr.success('데이터 저장 완료')
})
}
}
vm.swapDown = function(index) {
swap(vm.specialtyList,index,index+1)
Specialty.update({specialties: vm.specialtyList}).then(function(d){
})
}
vm.swapUp = function(index) {
swap(vm.specialtyList,index,index-1)
Specialty.update({specialties: vm.specialtyList}).then(function(d){
})
}
}) |
$(function(){
$("#accordion").accordion({
collapsible: true,
heightStyle: "content",
animate: 120,
icons: {"header": "accIcon","activeHeader": "accIcon"}
});
});
|
describe('convolutional layer: ZeroPadding3D', function() {
const assert = chai.assert
const styles = testGlobals.styles
const logTime = testGlobals.logTime
const stringifyCondensed = testGlobals.stringifyCondensed
const approxEquals = KerasJS.testUtils.approxEquals
const layers = KerasJS.layers
const testParams = [
{ inputShape: [3, 5, 2, 2], attrs: { padding: [1, 1, 1], data_format: 'channels_last' } },
{ inputShape: [3, 5, 2, 2], attrs: { padding: [1, 1, 1], data_format: 'channels_first' } },
{ inputShape: [3, 2, 1, 4], attrs: { padding: [3, 2, 2], data_format: 'channels_last' } },
{ inputShape: [3, 2, 1, 4], attrs: { padding: [3, 2, 2], data_format: 'channels_first' } },
{ inputShape: [3, 2, 1, 4], attrs: { padding: [[1, 2], [3, 4], [3, 1]], data_format: 'channels_last' } },
{ inputShape: [3, 2, 1, 4], attrs: { padding: 2, data_format: 'channels_last' } }
]
before(function() {
console.log('\n%cconvolutional layer: ZeroPadding3D', styles.h1)
})
/*********************************************************
* CPU
*********************************************************/
describe('CPU', function() {
before(function() {
console.log('\n%cCPU', styles.h2)
})
testParams.forEach(({ inputShape, attrs }, i) => {
const key = `convolutional.ZeroPadding3D.${i}`
const title = `[${key}] [CPU] padding ${JSON.stringify(attrs.padding)} on ${JSON.stringify(
inputShape
)} input, data_format='${attrs.data_format}'`
it(title, function() {
console.log(`\n%c${title}`, styles.h3)
let testLayer = new layers.ZeroPadding3D(attrs)
let t = new KerasJS.Tensor(TEST_DATA[key].input.data, TEST_DATA[key].input.shape)
console.log('%cin', styles.h4, stringifyCondensed(t.tensor))
const startTime = performance.now()
t = testLayer.call(t)
const endTime = performance.now()
console.log('%cout', styles.h4, stringifyCondensed(t.tensor))
logTime(startTime, endTime)
const dataExpected = new Float32Array(TEST_DATA[key].expected.data)
const shapeExpected = TEST_DATA[key].expected.shape
assert.deepEqual(t.tensor.shape, shapeExpected)
assert.isTrue(approxEquals(t.tensor, dataExpected))
})
})
})
/*********************************************************
* GPU
*********************************************************/
describe('GPU', function() {
before(function() {
console.log('\n%cGPU', styles.h2)
})
testParams.forEach(({ inputShape, attrs }, i) => {
const key = `convolutional.ZeroPadding3D.${i}`
const title = `[${key}] [GPU] padding ${JSON.stringify(attrs.padding)} on ${JSON.stringify(
inputShape
)} input, data_format='${attrs.data_format}'`
it(title, function() {
console.log(`\n%c${title}`, styles.h3)
let testLayer = new layers.ZeroPadding3D(Object.assign(attrs, { gpu: true }))
let t = new KerasJS.Tensor(TEST_DATA[key].input.data, TEST_DATA[key].input.shape)
console.log('%cin', styles.h4, stringifyCondensed(t.tensor))
const startTime = performance.now()
t = testLayer.call(t)
const endTime = performance.now()
console.log('%cout', styles.h4, stringifyCondensed(t.tensor))
logTime(startTime, endTime)
const dataExpected = new Float32Array(TEST_DATA[key].expected.data)
const shapeExpected = TEST_DATA[key].expected.shape
assert.deepEqual(t.tensor.shape, shapeExpected)
assert.isTrue(approxEquals(t.tensor, dataExpected))
})
})
})
})
|
var Waterline = require('waterline');
var randomstring = require('randomstring');
var Bugs = Waterline.Collection.extend({
identity: 'bugs',
connection: 'save',
autoUpdatedAt: false,
autoPK: false,
attributes: {
id: {
type: 'string',
primaryKey: true,
defaultsTo: function () {
return randomstring.generate(11);
}
},
description: {
type: 'string',
required: true
},
project: {
model: 'projects'
},
path: {
type: 'string'
},
mimetype: {
type: 'string'
},
email: {
type: 'string',
email: true
},
}
});
module.exports = Bugs;
|
import colors from './chartColors';
export const getBgColorByIndex = (index) => {
let colorLength = colors.length;
let colorIndex = index % colorLength;
return colors[colorIndex];
};
|
/*
* Copyright (c) 2017. MIT-license for Jari Van Melckebeke
* Note that there was a lot of educational work in this project,
* this project was (or is) used for an assignment from Realdolmen in Belgium.
* Please just don't abuse my work
*/
define(function (require) {
return function (ecModel) {
ecModel.eachSeriesByType('map', function (seriesModel) {
var colorList = seriesModel.get('color');
var itemStyleModel = seriesModel.getModel('itemStyle.normal');
var areaColor = itemStyleModel.get('areaColor');
var color = itemStyleModel.get('color')
|| colorList[seriesModel.seriesIndex % colorList.length];
seriesModel.getData().setVisual({
'areaColor': areaColor,
'color': color
});
});
};
});
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
// TODO 判断当前页面是否支持 FocusReading,支持时才显示图标
chrome.pageAction.show(tabId)
})
chrome.pageAction.onClicked.addListener(function (tab) {
chrome.tabs.sendRequest(tab.id, {}, function (response) {
// 暂时不做任何处理,只是通过触发请求来尝试使页面进入专注阅读模式
// 注意:第二个参数需要保留(即便为空对象),使用 null 时无法触发请求
})
})
// TODO 打开 link-tip 请求的新页面
//chrome.extension.onRequest(function () {
// TODO chrome.windows.create
//})
},{}]},{},[1]);
|
YUI.add('general-tests', function(Y) {
var Assert = Y.Assert,
suite = new Y.Test.Suite('General Tests');
var simpleReport = {
passed: 2,
failed: 2,
ignored: 1,
total: 5,
type: "report",
name: "YUI Test Results",
duration: 500,
"Some Suite":{
passed: 2,
failed: 2,
ignored: 1,
total: 5,
type: "testsuite",
name: "Some Suite",
duration: 356,
"Some Tests": {
passed: 2,
failed: 2,
ignored: 1,
total: 5,
type: "testcase",
name: "Some Tests",
duration: 250,
test1:{
result: "pass",
message: "Test passed.",
type: "test",
name: "test1",
duration: 25
},
test2:{
result: "pass",
message: "Test passed.",
type: "test",
name: "test2",
duration: 30
},
test3:{
result: "ignore",
message: "Test ignored.",
type: "test",
name: "test3",
duration: 35
},
test4:{
result: "fail",
message: "Test failed.",
type: "test",
name: "test4",
duration: 45
},
test5:{
result: "fail",
message: "Test failed.",
type: "test",
name: "test5",
duration: 50
}
}
}
};
suite.add(new Y.Test.Case({
name: 'Wait/Resume',
'test: resume without wait': function() {
this.resume(function() {
//Nothing
});
},
'test: wait without function': function() {
this.wait(100);
},
'test: next() resumes the test': function () {
var self = this;
function async(callback) {
setTimeout(callback, 0);
}
async(self.next( function () {} ));
self.wait();
},
'test: next() passes parameters to the callback': function () {
var self = this;
function async(callback) {
setTimeout(function () {
callback('hello world');
}, 0);
}
async(self.next(function (message) {
self.assert(message === 'hello world');
}));
self.wait();
},
'test: next() bounds the function to given context': function () {
var self = this, async;
async = {
i_am_async: true,
execute: function (callback) {
setTimeout(callback, 0);
}
};
async.execute(self.next(function () {
self.assert(this.i_am_async === true);
}, async));
self.wait();
},
'test: next() preserves the original context of a function': function () {
var self = this,
foo,
bar = { hello: 'world' };
function Foo() {}
Y.augment(Foo, Y.EventTarget);
foo = new Foo();
foo.on('something', this.next(function () {
self.assert(this === bar);
}), bar);
setTimeout(function () {
foo.fire('something');
}, 0);
self.wait();
},
'test: next() bounds the function to Y.config.global if no context is given': function () {
var self = this;
function async(callback) {
setTimeout(callback, 0);
}
async(self.next(function () {
self.assert(this === Y.config.global);
}));
self.wait();
},
_should: {
error: {
'test: resume without wait': true
},
fail: {
'test: wait without function': true
}
}
}));
suite.add(new Y.Test.Case({
name: 'waitFor',
_should: {
fail: {
'waitFor() without params should fail': true,
'waitFor(nonFn, fn) should fail': true,
'waitFor(fn, nonFn) should fail': true,
'waitFor(falseFn, fn) should fail': true,
'waitFor(trueFn, failFn) should fail': true,
'waitFor(falseFn, yfn, smallTimeout) should fail before default wait time': true
}
},
'waitFor() without params should fail': function () {
this.waitFor();
},
'waitFor(nonFn, fn) should fail': function () {
this.waitFor('boom', function () {});
},
'waitFor(fn, nonFn) should fail': function () {
this.waitFor(function () {}, 'boom');
},
'`this` in waitFor(HERE, fn) should be the TestCase': function () {
var self = this,
conditionThis;
self.waitFor(function () {
conditionThis = this;
return true;
}, function () {
self.assert(self === conditionThis);
});
},
'`this` in waitFor(fn, HERE) should be the TestCase': function () {
var self = this;
self.waitFor(function () { return true; }, function () {
self.assert(self === this);
});
},
'waitFor(falseFn, fn) should fail': function () {
this.waitFor(function () { return false; }, function () {
this.assert(true);
});
},
'waitFor(trueFn, failFn) should fail': function () {
this.waitFor(function () { return true; }, function () {
this.fail('failure === success!');
});
},
'waitFor(xfn, yfn) should call xfn multiple times until it returns true': function () {
var remaining = 3;
this.waitFor(function () {
return !(--remaining);
}, function () {
this.assert(remaining === 0, 'waitFor() conditional function called ' + remaining + ' fewer times than expected');
});
},
// FIXME: This is an unreliable test because if the process is so busy
// that it can't free up a tick to call teh condition before the
// default 10s is up, the test will fail, which is an indicator of
// success. So, false positive. I can't think of a better way to test
// this, though, and it seems pretty unlikely to end up "failing" in
// that way, so here it is.
'waitFor(falseFn, yfn, smallTimeout) should fail before default wait time': function () {
var tooLate = (+new Date()) + 2000,
called;
this.waitFor(function () {
if (called && (+new Date()) > tooLate) {
// Pass === fail
this.assert('condition called well past specified timeout');
}
// Hack to avoid race condition with busy event loop not
// freeing up a tick before the full 10s wait timeout. The
// hope is that if the process isn't so bogged down that it
// can call the condition once, it can call it multiple times.
called = true;
return false;
}, function () {
// Pass === fail
this.assert('segment should not have been called');
}, 300);
},
// FIXME: This is a textbook race condition. It may fail due to process
// load interfering with event loop fidelity. If you can think of a
// better way to test it, please do so. Otherwise, if you think this
// shouldn't even be here, please comment it out so there's a history
// of the issue being avoided.
'waitFor(xfn, fn, null, smallIncrement) should call xfn more frequently than default increment': function () {
var firstPass = 0,
secondPass = 0,
milestoneReached;
setTimeout(function () {
milestoneReached = true;
}, 1000);
this.waitFor(function () {
firstPass++;
return milestoneReached;
}, function () {
milestoneReached = false;
setTimeout(function () {
milestoneReached = true;
}, 1000);
this.waitFor(function () {
secondPass++;
return milestoneReached;
}, function () {
// TODO: can this be refined in a reasonable way? This is
// pretty arbitrary
this.assert(firstPass > (secondPass * 1.5));
}, null, 200);
}, null, 20);
}
}));
suite.add(new Y.Test.Case({
name: 'Suite/Case Tests',
'test: suite with no name': function() {
var s = new Y.Test.Suite();
Assert.isTrue((s.name.indexOf('testSuite') === 0));
},
'test: case with no name': function() {
var s = new Y.Test.Case();
Assert.isTrue((s.name.indexOf('testCase') === 0));
},
'test: callback': function() {
var fn = this.callback();
},
'test: assert': function() {
this.assert(true, 'Assert');
},
'test: assert no condition': function() {
this.assert();
},
'test: assert.fail': function() {
this.fail('Failed');
},
_should: {
fail: {
'test: assert.fail': true,
'test: assert no condition': true
}
}
}));
suite.add(new Y.Test.Case({
name: 'EventTarget',
'test: attach': function() {
var tcase = Y.Test.Runner;
var noop = function() {};
var count = Y.Object.keys(tcase._handlers).length;
tcase.subscribe('foobar', noop);
var count2 = Y.Object.keys(tcase._handlers).length;
Assert.areEqual(count + 1, count2);
tcase.unsubscribe('foobar', noop);
var count3 = tcase._handlers.foobar.length;
Assert.areEqual(0, count3);
}
}));
suite.add(new Y.Test.Case({
name: 'General Asserts',
'test: asserts': function() {
Assert.areNotEqual(true, false);
Assert.areNotSame(1, '1');
Assert.isFalse(false);
Assert.isTrue(true);
Assert.isNaN(parseInt('foobar'));
Assert.isNotNaN(parseInt(100));
Assert.isNull(null);
Assert.isNotNull(true);
Assert.isUndefined(undefined);
Assert.isNotUndefined('foo');
Assert.isArray([]);
Assert.isInstanceOf(Y.Test.Case, this);
Assert.isTypeOf(typeof 'foo', 'FooBar');
Y.assert(true);
},
'test: asserts fail areNotEqual': function() {
Assert.areNotEqual(true, true);
},
'test: asserts fail areNotSame': function() {
Assert.areNotSame(1, 1);
},
'test: asserts fail isFalse': function() {
Assert.isFalse(true);
},
'test: asserts fail isTrue': function() {
Assert.isTrue(false);
},
'test: asserts fail isNaN': function() {
Assert.isNaN(parseInt(100));
},
'test: asserts fail isNotNaN': function() {
Assert.isNotNaN(parseInt('Foobar'));
},
'test: asserts fail isNull': function() {
Assert.isNull(false);
},
'test: asserts fail isNotNull': function() {
Assert.isNotNull(null);
},
'test: asserts fail isUndefined': function() {
Assert.isUndefined(false);
},
'test: asserts fail isNotUndefined': function() {
Assert.isNotUndefined(undefined);
},
'test: asserts fail isArray': function() {
Assert.isArray({});
Assert.isArray('asdf');
Assert.isArray(function() {});
Assert.isArray(arguments);
},
'test: asserts fail isInstanceOf': function() {
Assert.isInstanceOf(Y.Test.Suite, this);
},
'test: asserts fail isTypeOf': function() {
Assert.isTypeOf(typeof 'string', {});
},
'test: Y.assert fail': function() {
Y.assert(false);
},
_should: {
fail: {
'test: asserts fail areNotEqual': true,
'test: asserts fail areNotSame': true,
'test: asserts fail isFalse': true,
'test: asserts fail isTrue': true,
'test: asserts fail isNaN': true,
'test: asserts fail isNotNaN': true,
'test: asserts fail isNull': true,
'test: asserts fail isNotNull': true,
'test: asserts fail isUndefined': true,
'test: asserts fail isNotUndefined': true,
'test: asserts fail isArray': true,
'test: asserts fail isInstanceOf': true,
'test: asserts fail isTypeOf': true,
'test: Y.assert fail': true
}
}
}));
var DateAssert = Y.DateAssert;
suite.add(new Y.Test.Case({
name: 'Date Tests',
'test: datesAreEqual()': function() {
var date1 = date2 = new Date();
DateAssert.datesAreEqual(date1, date2);
},
'test: datesAreEqual() fail': function() {
var date1 = new Date();
DateAssert.datesAreEqual(date1, new Date('01/01/1999'));
},
'test: timesAreEqual()': function() {
var date1 = date2 = new Date();
DateAssert.datesAreEqual(date1, date2);
},
'test: timesAreEqual() fail': function() {
var date1 = new Date('01/01/1999 16:16:16');
DateAssert.timesAreEqual(date1, new Date('01/01/1999 12:12:12'));
},
'test: should error for not passing dates': function() {
DateAssert.datesAreEqual(null, null);
},
'test: should error for not passing times': function() {
DateAssert.timesAreEqual(null, null);
},
_should: {
fail: {
'test: datesAreEqual() fail': true,
'test: timesAreEqual() fail': true
},
error: {
'test: should error for not passing dates': true,
'test: should error for not passing times': true
}
}
}));
suite.add(new Y.Test.Case({
name: 'Runner Tests',
'test: set name': function() {
var setName = 'YUITest Test Suite',
name = Y.Test.Runner.getName();
Y.Test.Runner.setName(setName);
name = Y.Test.Runner.getName();
Assert.areSame(setName, name);
},
'test: ignore': function() {
Assert.isTrue(false);
},
'test: running/waiting': function() {
Assert.isTrue(Y.Test.Runner.isRunning(), 'Running');
Assert.isFalse(Y.Test.Runner.isWaiting(), 'Waiting');
},
'test: getResults': function() {
var results = Y.Test.Runner.getResults();
Assert.isNull(results);
},
'test: clear': function() {
var suite = Y.Test.Runner.masterSuite;
Y.Test.Runner.clear();
Assert.isTrue((Y.Test.Runner.masterSuite.name.indexOf('testSuite_') === 0));
Y.Test.Runner.masterSuite = suite;
},
'test: _getCount and reset': function() {
var asserts = Assert._asserts;
Assert.areEqual(asserts, Assert._getCount());
Assert._reset();
Assert.areEqual(0, Assert._getCount());
Assert._asserts = asserts;
},
_should: {
ignore: {
'test: ignore': true
}
}
}));
suite.add(new Y.Test.Case({
name: 'Error Tests',
'test: Assert.Error': function() {
var e = new Y.Assert.Error('Assertion Error');
Assert.areEqual('Assert Error', e.name);
Assert.areEqual('Assert Error: Assertion Error', e.toString());
Assert.areEqual('Assert Error: Assertion Error', e.valueOf());
Assert.areEqual('Assertion Error', e.message);
},
'test: Assert.ComparisonFailure': function() {
var e = new Y.Assert.ComparisonFailure('ComparisonFailure Error', false, true);
Assert.areEqual('ComparisonFailure', e.name);
Assert.areEqual('ComparisonFailure: ComparisonFailure Error\nExpected: false (boolean)\nActual: true (boolean)', e.toString());
Assert.areEqual('ComparisonFailure: ComparisonFailure Error\nExpected: false (boolean)\nActual: true (boolean)', e.valueOf());
Assert.areEqual('ComparisonFailure Error', e.message);
},
'test: Assert.UnexpectedValue': function() {
var e = new Y.Assert.UnexpectedValue('UnexpectedValueError', false);
Assert.areEqual('UnexpectedValue', e.name);
Assert.areEqual('UnexpectedValue: UnexpectedValueError\nUnexpected: false (boolean) ', e.toString());
Assert.areEqual('UnexpectedValue: UnexpectedValueError\nUnexpected: false (boolean) ', e.valueOf());
Assert.areEqual('UnexpectedValueError', e.message);
}
}));
suite.add(new Y.Test.Case({
name: 'Reporter',
'test: report': function() {
var url = "http://foobar.com/",
reporter = new Y.Test.Reporter(url, Y.Test.Format.JSON),
form,
foo,
results,
json;
reporter.addField('foo', 'bar');
json = Y.Test.Format.JSON(simpleReport);
reporter.report(simpleReport, false);
Assert.isNotNull(reporter._form);
Assert.areEqual(url, reporter.url);
form = Y.one(reporter._form);
foo = form.one('input[name=foo]');
results = form.one('input[name=results]');
Assert.areEqual("bar", foo.get('value'));
Assert.areEqual(json, results.get('value'));
reporter.clearFields();
reporter.destroy();
Assert.isNull(reporter._form);
}
}));
Y.Test.Runner.add(suite);
});
|
var axios = require('axios');
import { CheckReponse } from './responses';
import { AGO_URL, AGO_RIVER_BASINS, AGO_CATALOGING_UNITS, AGO_HUCS } from '../constants/actionConstants';
//set base URL for axios
axios.defaults.baseURL = AGO_URL;
const CHART_DATA_OUT_FIELDS = 'geography_level%2Cgeography_label';
const CHART_DATA_ORDER_BY_FIELDS = 'geography_level';
function get_Basins(){
return axios.get(AGO_RIVER_BASINS)
}
function get_CatalogingUnits(){
return axios.get(AGO_CATALOGING_UNITS)
}
function get_HUCS(){
return axios.get(AGO_HUCS)
}
function buildNameList(name){
return {
name,
lists:[]
}
}
//builds a menu list
function buildMenuList (name, menuList, geoJSON){
var ml = [];
var nameList = buildNameList(name);
ml.push( nameList );
//map the menu list
ml.map(function(menu){
//check if name matches the passed name
if(menu.name === name){
//map geojson features and add the properties (attributes) to the list
// this will populate the menu items
geoJSON.features.map(function(features) {
menu.lists.push(features.properties)
})
}
})
//return new menu list
return ml[0]
}
export function get_MenuList(){
return (dispatch, getState) => {
//start fetching state (set to true)
dispatch(fetching_start())
const state = getState()
axios.all([get_Basins(), get_CatalogingUnits(),get_HUCS()])
.then(axios.spread(function (basins, catalogingUnits, HUCS) {
//check repsonses for errors
let theBasins = CheckReponse(basins,'AGO_API_ERROR');
let theCatalogingUnits = CheckReponse(catalogingUnits,'AGO_API_ERROR');
let theHUCS = CheckReponse(HUCS,'AGO_API_ERROR');
//restructure data for menu lists
let basinList = buildMenuList( 'River Basins', [] , theBasins)
let catalogingUnitList = buildMenuList( 'Cataloging Units', [] , theCatalogingUnits)
let HUCList = buildMenuList( 'HUC12', [], theHUCS)
//combine the lists into one
let allList = [ {...basinList}, {...catalogingUnitList}, {...HUCList} ]
//send the lists on
dispatch(MenuList(allList))
//start fetching state (set to true)
dispatch(fetching_end())
})
)
// .catch(error => {
// //end fetching set fetching state to false
// dispatch(fetching_end())
// console.log('request failed', error);
// });
}
}
function fetching_start(){
return {type: "FETCHING_MENUS", fetching: true}
}
function fetching_end(){
return {type: "FETCHING_MENUS", fetching: false}
}
//new menu list object to pass to reducer
function MenuList(json) {
return {
type: 'GET_MENU_LIST',
lists: json,
receivedAt: Date.now()
}
}
|
(function(){
'use strict';
var ctrl = angular.module('colorWell.controllers', []);
ctrl.controller('ColorWellController', ['_', 'LoaderService', colorWell]);
function colorWell(_, LoaderService){
var vm = this;
vm.title = "Color Well";
vm.colors = null;
vm.r = 255;
vm.g = 255;
vm.b = 255;
vm.a = 1;
vm.newColor = {};
vm.submitNewColor = function(inputColors){
// read out the current values from the slider controls
vm.newColor.r = inputColors[0];
vm.newColor.g = inputColors[1];
vm.newColor.b = inputColors[2];
// push the new color onto the vm.colors array
vm.colors.push(vm.newColor);
// set vm.newColor to empty object, will wipe the form as well
vm.newColor = {};
console.log("New Color", vm.newColor);
};
vm.userTypes = [
'user',
'admin'
];
vm.userSelected = {
userTypes: []
};
vm.colorTypes = [
'primary',
'secondary',
'other'
];
vm.colorSelected = {
colorTypes: []
};
LoaderService.load('data/colors.json').then(
function(data){
vm.colors = data;
//filter out colors different color types using Lodash
var primaryColors = _(data).filter({type:"primary"}).value();
var secondaryColors = _(data).filter({type:"secondary"}).value();
var otherColors = _(data).filter({type:"other"}).value();
console.log("Primary Colors", primaryColors);
console.log("Secondary Colors", secondaryColors);
console.log("Other Colors", otherColors);
},
function(errorMessage){
console.log(errorMessage);
}
);
vm.setColor = function(color){
console.log("setColor() called");
console.log("Color", color);
vm.r = color.r;
vm.g = color.g;
vm.b = color.b;
};
vm.executeCon = function(){
alert("You have been conned!!! :))")
};
vm.checkType = function(inputArray, inputType){
return !(inputArray.indexOf(inputType) < 0);
};
}
}()); |
describe("Module.Manager", function() {
var factory, manager, element;
beforeEach(function() {
factory = {
getInstance: function() {}
};
spyOn(factory, "getInstance");
element = document.createElement("div");
manager = new Module.Manager();
manager.provider = new Module.Provider();
manager.provider.factory = factory;
spyOn(manager.provider, "destructor");
});
describe("init", function() {
describe("to support Dependency Injection and Inversion of Control", function() {
it("does not instantiate a module factory if one already exists", function() {
manager.init();
expect(manager.provider.factory).toBe(factory);
});
it("does not instantiate a registry if one already exists", function() {
var registry = {};
manager.registry = registry;
manager.init();
expect(manager.registry).toBe(registry);
});
it("does not instantiate a module groups object if one already exists", function() {
var groups = {};
manager.groups = groups;
manager.init();
expect(manager.groups).toBe(groups);
});
it("sets Module.manager", function() {
manager.init();
expect(Module.manager).toBe(manager);
});
});
});
describe("destructor", function() {
var module1, module2;
function TestModule(guid) {
this.guid = guid;
spyOn(this, "destructor");
}
TestModule.prototype = {
guid: null,
constructor: TestModule,
destructor: function() {}
};
beforeEach(function() {
module1 = new TestModule(0);
module2 = new TestModule(1);
manager.init();
manager.registerModule("a", module1);
manager.registerModule("b", module2);
})
it("nullifies references to Module.manager, groups, provider and registry", function() {
expect(Module.manager).toBe(manager);
manager.destructor();
expect(Module.manager).toBe(null);
expect(manager.groups).toBe(null);
expect(manager.registry).toBe(null);
expect(manager.provider).toBe(null);
expect(module1.destructor).not.toHaveBeenCalled();
expect(module2.destructor).not.toHaveBeenCalled();
});
it("destroys the module provider and all registered modules", function() {
expect(Module.manager).toBe(manager);
manager.destructor(true);
expect(Module.manager).toBe(null);
expect(manager.groups).toBe(null);
expect(manager.registry).toBe(null);
expect(manager.provider).toBe(null);
expect(module1.destructor).toHaveBeenCalledWith(true);
expect(module2.destructor).toHaveBeenCalledWith(true);
});
});
describe("eagerLoadModules", function() {
it("calls createModules() for each child element with a data-modules attribute", function() {
spyOn(manager, "createModules");
element.innerHTML = [
'<ol>',
'<li data-modules="Foo Bar"></li>',
'<li data-modules="Baz"></li>',
'</ol>',
'<div data-modules="Bazzing"></div>'
].join("");
manager.init();
var returnValue = manager.eagerLoadModules(element);
expect(returnValue).toBe(manager);
expect(manager.createModules).toHaveBeenCalledWith(element.firstChild.childNodes[0]);
expect(manager.createModules).toHaveBeenCalledWith(element.firstChild.childNodes[1]);
expect(manager.createModules).toHaveBeenCalledWith(element.childNodes[1]);
expect(manager.createModules).not.toHaveBeenCalledWith(element.firstChild);
});
it("does not call createModules() on elements with a data-module-lazyload attribute", function() {
spyOn(manager.provider, "createModules");
element.innerHTML = [
'<ol>',
'<li></li>',
'<li></li>',
'</ol>',
'<div data-modules="Bazzing" data-module-lazyload="mouseover"></div>'
].join("");
manager.init();
manager.eagerLoadModules(element);
expect(manager.provider.createModules).not.toHaveBeenCalled();
});
});
describe("lazyLoadModules", function() {
xit("should be tested");
});
describe("registerModule", function() {
var _guid = 0, module;
beforeEach(function() {
module = {
guid: _guid++
};
manager.init();
});
it("registers a new module and adds it to a module group", function() {
manager.registerModule("testing", module);
expect(manager.registry[module.guid]).toEqual({module: module, type: "testing"});
expect(manager.groups.testing instanceof Array).toEqual(true);
expect(manager.groups.testing.length).toEqual(1);
expect(manager.groups.testing[0]).toBe(module);
});
it("throws an error if the module has a null guid", function() {
module.guid = null;
expect(function() {
manager.registerModule("testing", module);
}).toThrow(new Error("Cannot register module testing without a guid property"));
});
it("throws an error if the module has an undefined guid", function() {
module.guid = undefined;
expect(function() {
manager.registerModule("testing", module);
}).toThrow(new Error("Cannot register module testing without a guid property"));
});
it("throws an error if the module has already been registered", function() {
manager.registerModule("testing", module);
expect(function() {
manager.registerModule("testing", module);
}).toThrow(new Error("Module " + module.guid + " has already been registered"));
});
});
describe("unregisterModule", function() {
var _guid = 0, module;
beforeEach(function() {
module = {
guid: _guid++
};
manager.init();
});
it("returns false for modules without a guid", function() {
module.guid = null;
manager.unregisterModule(module);
module.guid = undefined;
expect(manager.unregisterModule(module)).toBe(false);
});
it("returns false if the module has already been unregistered", function() {
manager.registerModule("testing", module);
manager.unregisterModule(module);
expect(manager.unregisterModule(module)).toBe(false);
});
it("removes a module from the registry and its associated group, and returns true", function() {
manager.registerModule("testing", module);
expect(manager.unregisterModule(module)).toBe(true);
expect(manager.registry[module.guid]).toBe(undefined);
expect(manager.groups.testing.length).toEqual(0);
});
});
describe("createModules", function() {
beforeEach(function() {
element = document.createElement("div");
manager.init();
});
it("throws an error if the data-modules attribute is missing", function() {
element.id = "testing";
element.className = "module";
expect(function() {
manager.createModules(element);
}).toThrow(new Error("Missing required attribute data-modules on DIV.module#testing"));
});
describe("when data-modules contains one module type", function() {
var _guid = 0, module;
beforeEach(function() {
module = {
guid: _guid++,
init: function() {},
setElement: function(element) { this.element = element; },
setOptions: function(options) { this.options = options; }
};
element = document.createElement("div");
element.setAttribute("data-modules", "SpecFixtures.Modules.TestModule");
factory = {
getInstance: function() {}
};
manager.provider.factory = factory;
spyOn(factory, "getInstance").and.returnValue(module);
spyOn(manager, "registerModule");
spyOn(manager.provider, "createModule").and.callThrough();
spyOn(element, "getAttribute").and.callThrough();
spyOn(element, "setAttribute").and.callThrough();
spyOn(element, "removeAttribute").and.callThrough();
});
it("creates and registers a module", function() {
manager.createModules(element);
expect(element.getAttribute("data-module-options")).toBe(null);
expect(manager.provider.createModule)
.toHaveBeenCalledWith(element, "SpecFixtures.Modules.TestModule", {});
expect(factory.getInstance)
.toHaveBeenCalledWith("SpecFixtures.Modules.TestModule");
expect(manager.registerModule)
.toHaveBeenCalledWith("SpecFixtures.Modules.TestModule", module);
expect(element.getAttribute)
.toHaveBeenCalledWith("data-modules");
expect(element.getAttribute)
.toHaveBeenCalledWith("data-module-options");
expect(element.removeAttribute)
.toHaveBeenCalledWith("data-modules");
expect(element.setAttribute)
.toHaveBeenCalledWith("data-modules-created", "SpecFixtures.Modules.TestModule");
expect(element.getAttribute("data-modules")).toBe(null);
expect(element.getAttribute("data-modules-created")).toEqual("SpecFixtures.Modules.TestModule");
});
it("creates and registers a module with options", function() {
element.setAttribute("data-module-options", '{"foo":"bar"}');
manager.createModules(element);
expect(factory.getInstance)
.toHaveBeenCalledWith("SpecFixtures.Modules.TestModule");
expect(manager.provider.createModule)
.toHaveBeenCalledWith(element, "SpecFixtures.Modules.TestModule", { foo: "bar" });
expect(manager.registerModule)
.toHaveBeenCalledWith("SpecFixtures.Modules.TestModule", module);
expect(element.getAttribute)
.toHaveBeenCalledWith("data-modules");
expect(element.getAttribute)
.toHaveBeenCalledWith("data-module-options");
expect(element.removeAttribute)
.toHaveBeenCalledWith("data-modules");
expect(element.setAttribute)
.toHaveBeenCalledWith("data-modules-created", "SpecFixtures.Modules.TestModule");
expect(element.getAttribute("data-modules")).toBe(null);
expect(element.getAttribute("data-modules-created")).toEqual("SpecFixtures.Modules.TestModule");
});
});
describe("when data-modules contains a space separated list of module types", function() {
var _guid = 0, module;
beforeEach(function() {
module = {
guid: _guid++,
init: function() {},
setElement: function(element) { this.element = element; },
setOptions: function(options) { this.options = options; }
};
element = document.createElement("div");
element.setAttribute("data-modules", "SpecFixtures.Modules.FooModule SpecFixtures.Modules.BarModule");
factory = {
getInstance: function() {}
};
manager.provider.factory = factory;
spyOn(factory, "getInstance").and.returnValue(module);
spyOn(manager, "registerModule");
spyOn(manager.provider, "createModule").and.callThrough();
spyOn(element, "getAttribute").and.callThrough();
spyOn(element, "setAttribute").and.callThrough();
spyOn(element, "removeAttribute").and.callThrough();
});
it("creates and registers multiple modules", function() {
manager.createModules(element);
expect(element.getAttribute("data-module-options")).toBe(null);
expect(manager.provider.createModule)
.toHaveBeenCalledWith(element, "SpecFixtures.Modules.FooModule", {});
expect(manager.provider.createModule)
.toHaveBeenCalledWith(element, "SpecFixtures.Modules.BarModule", {});
expect(manager.registerModule)
.toHaveBeenCalledWith("SpecFixtures.Modules.FooModule", module);
expect(manager.registerModule)
.toHaveBeenCalledWith("SpecFixtures.Modules.BarModule", module);
expect(element.getAttribute)
.toHaveBeenCalledWith("data-modules");
expect(element.getAttribute)
.toHaveBeenCalledWith("data-module-options");
expect(element.removeAttribute)
.toHaveBeenCalledWith("data-modules");
expect(element.setAttribute)
.toHaveBeenCalledWith("data-modules-created", "SpecFixtures.Modules.FooModule SpecFixtures.Modules.BarModule");
expect(element.getAttribute("data-modules")).toBe(null);
expect(element.getAttribute("data-modules-created"))
.toEqual("SpecFixtures.Modules.FooModule SpecFixtures.Modules.BarModule");
});
it("creates and registers multiple modules with options namespaced to the module type", function() {
var options = {
"SpecFixtures.Modules.FooModule": {
foo: "foo"
}
};
var json = JSON.stringify(options);
element.setAttribute("data-module-options", json);
manager.createModules(element);
expect(element.getAttribute("data-module-options")).toBe(json);
expect(manager.provider.createModule)
.toHaveBeenCalledWith(element, "SpecFixtures.Modules.FooModule", options["SpecFixtures.Modules.FooModule"]);
expect(manager.provider.createModule)
.toHaveBeenCalledWith(element, "SpecFixtures.Modules.BarModule", {});
expect(manager.registerModule)
.toHaveBeenCalledWith("SpecFixtures.Modules.FooModule", module);
expect(manager.registerModule)
.toHaveBeenCalledWith("SpecFixtures.Modules.BarModule", module);
expect(element.getAttribute)
.toHaveBeenCalledWith("data-modules");
expect(element.getAttribute)
.toHaveBeenCalledWith("data-module-options");
expect(element.removeAttribute)
.toHaveBeenCalledWith("data-modules");
expect(element.setAttribute)
.toHaveBeenCalledWith("data-modules-created", "SpecFixtures.Modules.FooModule SpecFixtures.Modules.BarModule");
expect(element.getAttribute("data-modules")).toBe(null);
expect(element.getAttribute("data-modules-created"))
.toEqual("SpecFixtures.Modules.FooModule SpecFixtures.Modules.BarModule");
});
});
});
});
|
// --------------------------------
// Gulp Plugins
// --------------------------------
// Gulp - Duh
var gulp = require('gulp');
// CSS Related
var sass = require('gulp-sass');
var bulkSass = require('gulp-sass-glob-import');
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('autoprefixer');
// JavaScript Related
var uglify = require('gulp-uglify');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
// Tasks
var clean = require('gulp-clean');
var plumber = require('gulp-plumber');
var notify = require('gulp-notify');
var browserSync = require('browser-sync').create();
var fs = require('fs');
var svgo = require('gulp-svgo');
var inlineSvg = require('gulp-inline-svg');
var svgmin = require('gulp-svgmin');
var svgstore = require('gulp-svgstore');
var cheerio = require('gulp-cheerio'); // lets us use a lean library of core jQuery to modify files. https://cheerio.js.org/
// New Sync/Copy task dependencies
var path = require('path');
// --------------------------------
// Globals
// --------------------------------
/**
* Let's us access the contents of package.json as an object.
* @type {Object}
*/
var packagejson = JSON.parse(fs.readFileSync('./package.json'));
/**
* The host you'd like to use while working locally.
* @type {String}
*/
var host = "mashkey.com";
// Root Paths
var src = {
root: "./src/",
theme: {}
};
src.theme.root = src.root + "theme/";
src.theme.sass = src.theme.root + "sass/";
src.theme.sassVarsDir = src.theme.sass + "00-utilities/vars/";
src.theme.js = src.theme.root + "js/";
src.theme.fonts = src.theme.root + "fonts/";
src.theme.svgs = src.theme.root + "svgs/";
src.theme.icons = src.theme.svgs + "icons/";
src.theme.images = src.theme.root + "images/";
// WordPress Paths
var wp = {
root: "./",
theme: {}
};
wp.content = "./wp-content/";
wp.themes = wp.content + "themes/";
wp.theme.root = wp.themes + packagejson.name + "/";
wp.theme.core = wp.theme.root + "core/";
wp.theme.css = wp.theme.root + "css/";
wp.theme.maps = wp.theme.root + "maps/";
wp.theme.js = wp.theme.root + "js/";
wp.theme.fonts = wp.theme.root + "fonts/";
wp.theme.svgs = wp.theme.root + "svgs/";
wp.theme.icons = wp.theme.root + "acf-em-icon-picker/";
wp.theme.images = wp.theme.root + "images/";
wp.theme.acf = wp.theme.root + "acf-json/";
/**
* All theme files excepty js and sass
*/
var themeFiles = [
src.theme.root + '**/*',
'!' + src.theme.root + 'sass{,/**}',
'!' + src.theme.root + 'js{,/**}'
];
/**
* Gulp Error Handling
*/
var plumberErrorHandler = {
errorHandler: notify.onError({
title: 'Gulp - Error',
message: 'Error: <%= error.message %>'
})
};
/**
* Clean out the theme directory in wp-content/themes/{packagejson.name}
*/
gulp.task("clean", function() {
return gulp.src([wp.theme.root], {read: false})
.pipe(clean());
});
/**
* Copy everything but source sass and javascript files over to wp-content/themes/{packagejson.name}
*/
gulp.task("copy", function() {
return gulp.src(themeFiles, { dot: true })
.pipe(plumber(plumberErrorHandler))
.pipe(gulp.dest(wp.theme.root));
});
/**
* Process CSS
*
* Compile SASS, while adding sourcemaps and browser prefixes.
*/
gulp.task('css', function() {
// Post CSS Processors
var processors = [
autoprefixer({
browsers: ['last 4 versions', 'ie >= 9', 'iOS >= 7']
})
];
return gulp.src([src.theme.sass + '**/*.scss'])
.pipe(plumber(plumberErrorHandler))
.pipe(sourcemaps.init())
.pipe(bulkSass())
.pipe(sass({
outputStyle: 'compressed'
})
.on('error', sass.logError))
.pipe(postcss(processors))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest(wp.theme.css))
.pipe(browserSync.stream({match: '**/*.css'}));
});
/**
* Javascript
*
* Module support (Browserify), ES2015 support (Babel), minification, and sourcemaps.
*
* @link http://browserify.org/
* @link https://babeljs.io/
*
* @param {String} entry Path to JS entry point.
* @param {String} filename Name of file, with extension, for compiled JS to be saved to.
*/
function bundleScripts(entry, filename) {
return browserify({
entries: entry,
debug: true
})
.transform(babelify, {
presets: ["es2015"]
})
.bundle()
.on('error', function(err) {
console.error(err);
this.emit('end');
})
.pipe(source(filename))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest(wp.theme.js));
}
gulp.task('js:head', function() {
return bundleScripts(src.theme.js + 'theme/head.js', 'head.js');
});
gulp.task('js:main', function() {
return bundleScripts(src.theme.js + 'theme/main.js', 'main.js');
});
gulp.task('js:admin', function() {
return bundleScripts(src.theme.js + 'admin/admin.js', 'admin.js');
});
gulp.task('js', gulp.series('js:head', 'js:main', 'js:admin'));
/**
* SVG Tasks
*
* Takes all files from a directory ending in ".svg", and creates a dynamically generated
* sass partial that converts all sources into optimized Data URIs. This sass partial is then
* distributed into our theme's sass directory. It also includes mixins for using each
* icon as a background-image.
*
* @ref: https://www.npmjs.com/package/gulp-svgo
* @ref: https://www.npmjs.com/package/gulp-inline-svg
*/
gulp.task('svg:sass-partial', function() {
return gulp
.src([src.theme.svgs + '**/*.svg'])
.pipe(svgo())
.pipe(inlineSvg())
.pipe(gulp.dest(src.theme.sassVarsDir));
});
//---
// SVG SPRITE TASK
//---
gulp.task('svg:sprite', function () {
return gulp.src([src.theme.icons + '**/*.svg', '!' + src.theme.icons + '**/*-white.svg'])
.pipe(cheerio({
run: function ($) {
$('[stroke]').each(function(){
$this = $(this);
if ( $this.attr('stroke') === 'none' ) {
} else {
$this.attr('stroke', 'currentColor');
}
});
$('[fill]').each(function(){
$this = $(this);
if ( $this.attr('fill') === 'none' ) {
} else {
$this.attr('fill', 'currentColor');
}
});
},
parserOptions: { xmlMode: true }
}))
.pipe(svgmin(function (file) {
var prefix = path.basename(file.relative, path.extname(file.relative));
return {
plugins: [{
cleanupIDs: {
prefix: prefix + '-',
minify: false,
remove: false
}
}]
};
}))
.pipe(svgstore())
.pipe(gulp.dest(wp.theme.icons))
});
gulp.task('svg', gulp.series('svg:sass-partial', 'svg:sprite'));
gulp.task("build", gulp.series(
'clean',
'svg',
'css',
'js',
'copy',
function(done) {
done();
}
));
// --------------------------------
// Server Tasks
// --------------------------------
/**
* Serves up the site using a proxy server which you need to provide
*/
gulp.task('serve', function(done) {
browserSync.init({
proxy: host, // Rename this to your desired host name
port: 3333
},
function(){
console.log('SITE WATCHING FOR CHANGES');
done();
});
});
// --------------------------------
// Watch Tasks
// --------------------------------
gulp.task('watch', function(done) {
// Theme Watcher
gulp.watch(themeFiles, gulp.series(['copy']));
// Sass Watcher
gulp.watch(src.theme.sass + '**/*.scss', gulp.series('css'));
// SVG Watcher
gulp.watch(src.theme.svgs + '**/*.svg', gulp.series(['svg:sass-partial', 'svg:sprite']));
// Scripts Watcher
gulp.watch(src.theme.js + '**/*.js', gulp.series('js'));
done();
});
// --------------------------------
// Default Task
// --------------------------------
gulp.task('default', gulp.series(
'build',
'serve',
'watch',
function(done) {
done();
}
));
|
'use strict'
const joi = require('joi')
// const Schemas = require('./schemas')
module.exports = [
{
method: ['GET'],
path: '/generalStats',
handler: 'ProxyCartController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.object()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/gateways',
handler: 'GatewayController.gateways',
config: {
validate: {
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetGatewaysRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['GET'],
path: '/countries',
handler: 'CountryController.countries',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCountriesRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['GET'],
path: '/provinces',
handler: 'CountryController.provinces',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProvincesRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['GET'],
path: '/counties',
handler: 'CountryController.counties',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCountiesRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['GET'],
path: '/cities',
handler: 'CountryController.cities',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCitiesRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST'],
path: '/country',
handler: 'CountryController.createCountry',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCountryRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/country/:id',
handler: 'CountryController.country',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCountryIdRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['GET'],
path: '/country/:id/provinces',
handler: 'CountryController.countryProvinces',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCountryIdProvincesRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/country/:id',
handler: 'CountryController.updateCountry',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCountryIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/country/:id',
handler: 'CountryController.destroyCountry',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCountryIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/country/:id/addProvince/:province',
handler: 'CountryController.addProvince',
config: {
validate: {
params: {
id: joi.number(),
province: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCountryIdAddProvinceProvinceRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/country/:id/removeProvince/:province',
handler: 'CountryController.removeProvince',
config: {
validate: {
params: {
id: joi.number(),
province: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCountryIdRemoveProvinceProvinceRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/province',
handler: 'CountryController.createProvince',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostProvinceRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/province/:id',
handler: 'CountryController.province',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProvinceIdRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/province/:id',
handler: 'CountryController.updateProvince',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostProvinceIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/province/:id',
handler: 'CountryController.destroyProvince',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteProvinceIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/county',
handler: 'CountryController.createCounty',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCountyRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/county/:id',
handler: 'CountryController.county',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCountyIdRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/county/:id',
handler: 'CountryController.updateCounty',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCountyIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/county/:id',
handler: 'CountryController.destroyCounty',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCountyIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/city',
handler: 'CountryController.createCity',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCityRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/city/:id',
handler: 'CountryController.city',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCityIdRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/city/:id',
handler: 'CountryController.updateCity',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCityIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/city/:id',
handler: 'CountryController.destroyCity',
config: {
validate: {
params: {
id: joi.number()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCityIdRoute',
roles: ['admin']
}
}
}
},
// Cart
{
method: ['GET'],
path: '/carts',
handler: 'CartController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCartsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/cart',
handler: 'CartController.create',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCartRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/cart',
handler: 'CartController.session',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCartRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST'],
path: '/cart/draft',
handler: 'CartController.draft',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCartDraftRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/cart/:id',
handler: 'CartController.resolve',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCartIdRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['PUT'],
path: '/cart',
handler: 'CartController.update',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPutCartRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id',
handler: 'CartController.update',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCartIdRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/addShipping',
handler: 'CartController.addShipping',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdAddShippingRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/removeShipping',
handler: 'CartController.removeShipping',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdRemoveShippingRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/addTaxes',
handler: 'CartController.addTaxes',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdAddTaxesRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/removeTaxes',
handler: 'CartController.removeTaxes',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdRemoveTaxesRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/cart/generalStats',
handler: 'CartController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCartGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/cart/count',
handler: 'CartController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCartCountRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET','POST'],
path: '/cart/init',
handler: 'CartController.init',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCartInitRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['GET'],
path: '/cart/session',
handler: 'CartController.session',
config: {
app: {
proxyRouter: {
ignore: true
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/logout',
handler: 'CartController.logout',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCartLogoutRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/checkout',
handler: 'CartController.checkout',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCartCheckoutRoute',
roles: ['public','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/addItems',
handler: 'CartController.addItems',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCartAddItemsRoute',
roles: ['public','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/removeItems',
handler: 'CartController.removeItems',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCartRemoveItemsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/cart/clear',
handler: 'CartController.clear',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCartClearRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/cart/login',
handler: 'CartController.login',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCartLoginRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/cart/:id/login',
handler: 'CartController.login',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdLoginRoute',
roles: ['public','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/checkout',
handler: 'CartController.checkout',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdCheckoutRoute',
roles: ['public','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/checkout/:customer',
handler: 'CartController.checkout',
config: {
validate: {
params: {
id: joi.number().required(),
customer: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdCheckoutCustomerRoute',
roles: ['public','registered']
}
}
}
},
{
method: ['GET'],
path: '/cart/:id/customer',
handler: 'CartController.customer',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetCartIdCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/cart/:id/switch',
handler: 'CartController.switchCart',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdSwitchRoute',
roles: ['public','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/addItems',
handler: 'CartController.addItems',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdAddItemsRoute',
roles: ['public','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/removeItems',
handler: 'CartController.removeItems',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdRemoveItemsRoute',
roles: ['public','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/pricingOverrides',
handler: 'CartController.pricingOverrides',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdPricingOverridesRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/cart/:id/clear',
handler: 'CartController.clear',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCartIdClearRoute',
roles: ['public','registered']
}
}
}
},
// Collections
{
method: ['GET'],
path: '/collections',
handler: 'CollectionController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/collection',
handler: 'CollectionController.create',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id',
handler: 'CollectionController.update',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/collection/:id',
handler: 'CollectionController.findById',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/collection/:collection',
handler: 'CollectionController.addCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/collection/:id/addCollection/:collection',
handler: 'CollectionController.addCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdAddCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/collections',
handler: 'CollectionController.addCollections',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdCollectionsRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/collection/:id/collection/:collection',
handler: 'CollectionController.removeCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCollectionIdCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/collection/:id/removeCollection/:collection',
handler: 'CollectionController.removeCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCollectionIdRemoveCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/collection/:id/collections',
handler: 'CollectionController.collections',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionIdCollectionsRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/addProduct/:product',
handler: 'CollectionController.addProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdAddProductProductRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/product/:product',
handler: 'CollectionController.addProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdProductProductRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/collection/:id/removeProduct/:product',
handler: 'CollectionController.removeProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdRemoveProductProductRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/products',
handler: 'CollectionController.addProducts',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/collection/:id/product/:product',
handler: 'CollectionController.removeProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCollectionIdProductProductRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/collection/:id/products',
handler: 'CollectionController.products',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionIdProductsRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['GET'],
path: '/collection/:id/discounts',
handler: 'CollectionController.discounts',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionIdDiscountsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/addTag/:tag',
handler: 'CollectionController.addTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdAddTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/tag/:tag',
handler: 'CollectionController.addTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/removeTag/:tag',
handler: 'CollectionController.removeTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdRemoveTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/collection/:id/tag/:tag',
handler: 'CollectionController.removeTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCollectionIdTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/collection/:id/tags',
handler: 'CollectionController.tags',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionIdTagsRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/addCustomer/:customer',
handler: 'CollectionController.addCustomer',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
customer: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdAddCustomerCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/customer/:customer',
handler: 'CollectionController.addCustomer',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
customer: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdCustomerCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/collection/:id/customers',
handler: 'CollectionController.addCustomers',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdCustomersRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/collection/:id/removeCustomer/:customer',
handler: 'CollectionController.removeCustomer',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
customer: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCollectionIdRemoveCustomerCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/collection/:id/customer/:customer',
handler: 'CollectionController.removeCustomer',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
customer: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCollectionIdCustomerCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/collection/:id/customers',
handler: 'CollectionController.customers',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionIdCustomersRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/collection/handle/:handle',
handler: 'CollectionController.findByHandle',
config: {
validate: {
params: {
handle: joi.string().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionHandleRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/collection/count',
handler: 'CollectionController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionCountRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/collection/generalStats',
handler: 'CollectionController.generalStats',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/collections/search',
handler: 'CollectionController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any().optional(),
term: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCollectionsSearchRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/collection/uploadCSV',
handler: 'CollectionController.uploadCSV',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCollectionUploadCsvRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/collection/processUpload/:id',
handler: 'CollectionController.processUpload',
config: {
validate: {
params: {
// This is a only ever a String
id: joi.string().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCollectionProcessUploadRoute',
roles: ['admin']
}
}
}
},
// Customer
{
method: ['GET'],
path: '/customers',
handler: 'CustomerController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomersRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/customer',
handler: 'CustomerController.createAndLogin',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['PUT'],
path: '/customer',
handler: 'CustomerController.update',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPutCustomerRoute',
roles: ['registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/customer/create',
handler: 'CustomerController.create',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerCreateRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/customer/processUpload/:id',
handler: 'CustomerController.processUpload',
config: {
validate: {
params: {
// This is a only ever a String
id: joi.string().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerProcessUploadRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id',
handler: 'CustomerController.findById',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/token/:token',
handler: 'CustomerController.findByToken',
config: {
validate: {
params: {
token: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerTokenTokenRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/discounts',
handler: 'CustomerController.discounts',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdDiscountsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/reviews',
handler: 'CustomerController.reviews',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdReviewsRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['GET'],
path: '/customer/generalStats',
handler: 'CustomerController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/count',
handler: 'CustomerController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerCountRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/customer/export',
handler: 'CustomerController.exportCustomers',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerExportRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customers/search',
handler: 'CustomerController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any().optional(),
term: joi.string().required(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomersSearchRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id',
handler: 'CustomerController.update',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST', 'PUT'],
path: '/customer/:id/accountBalance',
handler: 'CustomerController.accountBalance',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdAccountBalanceRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/customer/:id/enable',
handler: 'CustomerController.enable',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutCustomerIdEnableRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/customer/:id/disable',
handler: 'CustomerController.disable',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutCustomerIdDisableRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id/addTag/:tag',
handler: 'CustomerController.addTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdAddTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id/tag/:tag',
handler: 'CustomerController.addTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdPostTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT','DELETE'],
path: '/customer/:id/removeTag/:tag',
handler: 'CustomerController.removeTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdRemoveTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/customer/:id/tag/:tag',
handler: 'CustomerController.removeTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdDeleteTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id/addCollection/:collection',
handler: 'CustomerController.addCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdAddCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id/collections',
handler: 'CustomerController.addCollections',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdCollectionsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id/collection/:collection',
handler: 'CustomerController.addCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdPostCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id/removeCollection/:collection',
handler: 'CustomerController.removeCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdRemoveCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/customer/:id/collection/:collection',
handler: 'CustomerController.removeCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteCustomerIdDeleteCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/customer/:id/login',
handler: 'CustomerController.login',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdLoginRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/customer/:id/source',
handler: 'CustomerController.addSource',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdSourceRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id/source/:source',
handler: 'CustomerController.updateSource',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
source: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdSourceIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/customer/:id/source/:source',
handler: 'CustomerController.destroySource',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
source: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteCustomerIdSourceSourceRoute',
roles: ['admin']
}
}
}
},
// Customer Address
{
method: ['POST'],
path: '/customer/:id/address',
handler: 'CustomerController.addAddress',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdAddressRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/:id/address/:address',
handler: 'CustomerController.updateAddress',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
address: joi.any().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdAddressAddressRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/customer/:id/address/:address',
handler: 'CustomerController.destroyAddress',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
address: joi.any().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteCustomerIdAddressAddressRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/customer/:id/event/:event',
handler: 'CustomerController.destroyEvent',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteCustomerIdEventEventRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/accounts',
handler: 'CustomerController.accounts',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdAccountsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/account/:account',
handler: 'CustomerController.customerAccount',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
account: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdAccountAccountRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/account/:account/sources',
handler: 'CustomerController.customerAccountSources',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
account: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdAccountAccountSourcesRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/account/:account/transactions',
handler: 'CustomerController.customerAccountTransactions',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
account: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
retransaction_name: 'apiGetCustomerIdAccountAccountTransactionsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/addresses',
handler: 'CustomerController.addresses',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdAddressesRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/collections',
handler: 'CustomerController.collections',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdCollectionsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/tags',
handler: 'CustomerController.tags',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdTagsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/users',
handler: 'CustomerController.users',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdUsersRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/user/:user',
handler: 'CustomerController.user',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
user: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdUserUserRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT','POST'],
path: '/customer/:id/user/:user',
handler: 'CustomerController.addUser',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
user: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCustomerIdUserUserRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT','POST'],
path: '/customer/:id/addUsers',
handler: 'CustomerController.addUsers',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCustomerIdAddUsersRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT','POST'],
path: '/customer/:id/users',
handler: 'CustomerController.addUsers',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCustomerIdUsersRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/customer/:id/user/:user',
handler: 'CustomerController.removeUser',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
user: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCustomerIdUserUserRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/orders',
handler: 'CustomerController.orders',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdOrdersRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/events',
handler: 'CustomerController.events',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdEventsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/sources',
handler: 'CustomerController.sources',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdSourcesRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:id/subscriptions',
handler: 'CustomerController.subscriptions',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIdSubscriptionsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/account/:account',
handler: 'CustomerController.account',
config: {
validate: {
params: {
account: joi.any().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerAccountAccountRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/user/:user',
handler: 'CustomerController.user',
config: {
validate: {
params: {
user: joi.any().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerUserUserRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/order/:order',
handler: 'CustomerController.order',
config: {
validate: {
params: {
order: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerOrderOrderRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/isSubscribed/:product',
handler: 'CustomerController.isSubscribedToProduct',
config: {
validate: {
params: {
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerIsSubscribedProductRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/hasPurchased/:product',
handler: 'CustomerController.hasPurchasedProduct',
config: {
validate: {
params: {
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerHasPurchasedProductRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST'],
path: '/customer/source',
handler: 'CustomerController.addSource',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCustomerSourceRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/source/:source',
handler: 'CustomerController.source',
config: {
validate: {
params: {
source: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerSourceSourceRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST'],
path: '/customer/source/:source',
handler: 'CustomerController.updateSource',
config: {
validate: {
params: {
source: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCustomerSourceSourceRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['DELETE'],
path: '/customer/source/:source',
handler: 'CustomerController.destroySource',
config: {
validate: {
params: {
source: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCustomerSourceSourceRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/tag/:tag',
handler: 'CustomerController.findByTag',
config: {
validate: {
params: {
tag: joi.string().required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerTagTagRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/collection/:handle',
handler: 'CustomerController.findByCollection',
config: {
validate: {
params: {
handle: joi.string().required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerCollectionHandleRoute',
roles: ['public','registered','admin']
}
}
}
},
// Customer Addresses
{
method: ['POST'],
path: '/customer/address',
handler: 'CustomerController.addAddress',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCustomerAddressRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/address/:address',
handler: 'CustomerController.address',
config: {
validate: {
params: {
address: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerAddressAddressRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/address/:address',
handler: 'CustomerController.updateAddress',
config: {
validate: {
params: {
address: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCustomerAddressAddressRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['DELETE'],
path: '/customer/address/:address',
handler: 'CustomerController.destroyAddress',
config: {
validate: {
params: {
address: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiDeleteCustomerAddressAddressRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST'],
path: '/customer/login',
handler: 'CustomerController.login',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerLoginRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/customer/logout',
handler: 'CustomerController.logout',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerLogoutRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/accounts',
handler: 'CustomerController.accounts',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerAccountsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/addresses',
handler: 'CustomerController.addresses',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerAddressesRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/collections',
handler: 'CustomerController.collections',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerCollectionsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/events',
handler: 'CustomerController.events',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerEventsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/orders',
handler: 'CustomerController.orders',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerOrdersRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/tags',
handler: 'CustomerController.tags',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerTagsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/sources',
handler: 'CustomerController.sources',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerSourcesRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer/subscription/:subscription',
handler: 'CustomerController.subscription',
config: {
validate: {
params: {
subscription: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerSubscriptionSubscriptionRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/subscription/:subscription',
handler: 'CustomerController.subscriptionUpdate',
config: {
validate: {
params: {
subscription: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiPostCustomerSubscriptionSubscriptionRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/subscription/:subscription/activate',
handler: 'CustomerController.subscriptionActivate',
config: {
validate: {
params: {
subscription: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerSubscriptionSubscriptionActivateRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/subscription/:subscription/deactivate',
handler: 'CustomerController.subscriptionDeactivate',
config: {
validate: {
params: {
subscription: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerSubscriptionSubscriptionDeactivateRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/customer/subscription/:subscription/renew',
handler: 'SubscriptionController.renew',
config: {
validate: {
params: {
subscription: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerSubscriptionSubscriptionRenewRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST'],
path: '/customer/subscription/:subscription/addItems',
handler: 'CustomerController.subscriptionAddItems',
config: {
validate: {
params: {
subscription: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerSubscriptionSubscriptionAddItemsRoute',
roles: ['admin', 'registered']
}
}
}
},
{
method: ['POST'],
path: '/customer/subscription/:subscription/cancel',
handler: 'CustomerController.subscriptionCancel',
config: {
validate: {
params: {
subscription: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerSubscriptionSubscriptionCancelRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST'],
path: '/customer/subscription/:subscription/removeItems',
handler: 'CustomerController.subscriptionRemoveItems',
config: {
validate: {
params: {
subscription: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerSubscriptionSubscriptionRemoveItemsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/subscriptions',
handler: 'CustomerController.subscriptions',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerSubscriptionsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/customer',
handler: 'CustomerController.session',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/session',
handler: 'CustomerController.session',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerSessionRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:product/isSubscribedToProduct',
handler: 'CustomerController.isSubscribedToProduct',
config: {
validate: {
params: {
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerProductIsSubscribedToProductRoute',
roles: ['registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/:product/hasPurchasedProduct',
handler: 'CustomerController.hasPurchasedProduct',
config: {
validate: {
params: {
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerProductHasPurchasedProductRoute',
roles: ['registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/customer/users',
handler: 'CustomerController.users',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetCustomerUsersRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST'],
path: '/customer/uploadCSV',
handler: 'CustomerController.uploadCSV',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerUploadCsvRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/customer/:id/switch',
handler: 'CustomerController.switchCustomer',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostCustomerIdSwitchRoute',
roles: ['public','registered']
}
}
}
},
// Discount
{
method: ['GET'],
path: '/discount/generalStats',
handler: 'DiscountController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetDiscountGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discounts',
handler: 'DiscountController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetDiscountsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discounts/search',
handler: 'DiscountController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
term: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetDiscountsSearchRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discount/:id',
handler: 'DiscountController.findById',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetDiscountIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discount/handle/:handle',
handler: 'DiscountController.findByHandle',
config: {
validate: {
params: {
handle: joi.string().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetDiscountHandleHandleRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST'],
path: '/discount',
handler: 'DiscountController.create',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/discount/:id',
handler: 'DiscountController.update',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/discount/:id',
handler: 'DiscountController.destroy',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteDiscountIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/discount/:id/product/:product',
handler: 'DiscountController.addProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountIdProductProductRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discount/:id/events',
handler: 'DiscountController.events',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetDiscountIdEventsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/discount/:id/products',
handler: 'DiscountController.addProducts',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountIdProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/discount/:id/product/:product',
handler: 'DiscountController.removeProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
product: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteDiscountIdProductProductRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discount/:id/products',
handler: 'DiscountController.products',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetDiscountIdProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/discount/:id/customer/:customer',
handler: 'DiscountController.addCustomer',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
customer: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountIdCustomerCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/discount/:id/customers',
handler: 'DiscountController.addCustomers',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountIdCustomersRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/discount/:id/customer/:customer',
handler: 'DiscountController.removeCustomer',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
customer: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteDiscountIdCustomerCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discount/:id/customers',
handler: 'DiscountController.customers',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetDiscountIdCustomersRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/discount/:id/cart/:cart',
handler: 'DiscountController.addCart',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
cart: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountIdCartCartRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/discount/:id/cart/:cart',
handler: 'DiscountController.removeCart',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
cart: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteDiscountIdCartCartRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discount/:id/carts',
handler: 'DiscountController.carts',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetDiscountIdCartsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/discount/:id/collection/:collection',
handler: 'DiscountController.addCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountIdCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/discount/:id/collections',
handler: 'DiscountController.addCollections',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostDiscountIdCollectionsRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/discount/:id/collection/:collection',
handler: 'DiscountController.removeCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteDiscountIdCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/discount/:id/collections',
handler: 'DiscountController.collections',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetDiscountIdCollectionsRoute',
roles: ['admin']
}
}
}
},
// Fulfillment
{
method: ['GET'],
path: '/fulfillments',
handler: 'FulfillmentController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetFulfillmentsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/fulfillment',
handler: 'FulfillmentController.create',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostFulfillmentRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/fulfillment/generalStats',
handler: 'FulfillmentController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetFulfillmentGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST', 'PUT'],
path: '/fulfillment/:id',
handler: 'FulfillmentController.update',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostFulfillmentIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/fulfillment/:id',
handler: 'FulfillmentController.destroy',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteFulfillmentIdRoute',
roles: ['admin']
}
}
}
},
// Products
{
method: ['GET'],
path: '/products',
handler: 'ProductController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductsRoute',
roles: ['public','registered','admin']
}
}
}
},
// TODO make this resolve instead of by Id only
{
method: ['GET'],
path: '/product/:id',
handler: 'ProductController.findById',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/products/search',
handler: 'ProductController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any().optional(),
term: joi.string().required(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductsSearchRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/tag/:tag',
handler: 'ProductController.findByTag',
config: {
validate: {
params: {
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductTagTagRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/handle/:handle',
handler: 'ProductController.findByHandle',
config: {
validate: {
params: {
handle: joi.string().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductHandleHandleRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/collection/:handle',
handler: 'ProductController.findByCollection',
config: {
validate: {
params: {
handle: joi.string().required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductCollectionHandleRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/collection/:handle/search',
handler: 'ProductController.searchByCollection',
config: {
validate: {
params: {
handle: joi.string().required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
term: joi.string(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductCollectionHandleSearchRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/generalStats',
handler: 'ProductController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/product/count',
handler: 'ProductController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductCountRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product',
handler: 'ProductController.addProduct',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/add',
handler: 'ProductController.addProduct',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductAddRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/products',
handler: 'ProductController.addProducts',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/addProducts',
handler: 'ProductController.addProducts',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductAddProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/update',
handler: 'ProductController.updateProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdUpdateRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/product/:id',
handler: 'ProductController.updateProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutProductIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/addTag/:tag',
handler: 'ProductController.addTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdAddTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/tag/:tag',
handler: 'ProductController.addTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/removeTag/:tag',
handler: 'ProductController.removeTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdRemoveTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id/tag/:tag',
handler: 'ProductController.removeTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/addCollection/:collection',
handler: 'ProductController.addCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdAddCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/collection/:collection',
handler: 'ProductController.addCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutProductIdCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/removeCollection/:collection',
handler: 'ProductController.removeCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdRemoveCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id/collection/:collection',
handler: 'ProductController.removeCollection',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
collection: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdCollectionCollectionRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/addAssociation/:association',
handler: 'ProductController.addAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdAddAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/association/:association',
handler: 'ProductController.addAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/removeAssociation/:association',
handler: 'ProductController.removeAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdRemoveAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id/association/:association',
handler: 'ProductController.removeAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/variant/:id/addAssociation/:association',
handler: 'ProductController.addVariantAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductVariantIdAddAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/variant/:id/removeAssociation/:association',
handler: 'ProductController.removeVariantAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductVariantIdRemoveAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/variant/:variant/addAssociation/:association',
handler: 'ProductController.addVariantAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdVariantVariantAddAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/variant/:variant/association/:association',
handler: 'ProductController.addVariantAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutProductIdVariantVariantAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/variant/:variant/removeAssociation/:association',
handler: 'ProductController.removeVariantAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdVariantVariantRemoveAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id/variant/:variant/association/:association',
handler: 'ProductController.removeVariantAssociation',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
association: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdVariantVariantAssociationAssociationRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/variant/:variant/associations',
handler: 'ProductController.variantAssociations',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetProductIdVariantVariantAssociationsRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/addShop/:shop',
handler: 'ProductController.addShop',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
shop: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdAddShopShopRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/shop/:shop',
handler: 'ProductController.addShop',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
shop: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdShopShopRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/removeShop/:shop',
handler: 'ProductController.removeShop',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
shop: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdRemoveShopShopRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id/shop/:shop',
handler: 'ProductController.removeShop',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
shop: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdShopShopRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/collections',
handler: 'ProductController.collections',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetProductIdCollectionsRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/addVendor/:vendor',
handler: 'ProductController.addVendor',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
vendor: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdAddVendorVendorRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/vendor/:vendor',
handler: 'ProductController.addVendor',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
vendor: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutProductIdVendorVendorRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/:id/removeVendor/:vendor',
handler: 'ProductController.removeVendor',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
vendor: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdRemoveVendorVendorRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id/vendor/:vendor',
handler: 'ProductController.removeVendor',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
vendor: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdVendorVendorRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/vendors',
handler: 'ProductController.vendors',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetProductIdVendorsRoute',
roles: ['admin','registered','public']
}
}
}
},
{
method: ['PUT'],
path: '/products',
handler: 'ProductController.updateProducts',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPutProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/product/updateProducts',
handler: 'ProductController.updateProducts',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductUpdateProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/:id/remove',
handler: 'ProductController.removeProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdRemoveRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id',
handler: 'ProductController.removeProduct',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE','POST'],
path: '/product/removeProducts',
handler: 'ProductController.removeProducts',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductRemoveProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/:id/variant',
handler: 'ProductController.createVariant',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdVariantRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/:id/variant/:variant/remove',
handler: 'ProductController.removeVariant',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdVariantVariantRemoveRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/:id/variant/:variant',
handler: 'ProductController.updateVariant',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdVariantVariantRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id/variant/:variant',
handler: 'ProductController.removeVariant',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdVariantVariantRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE','POST'],
path: '/product/removeVariants',
handler: 'ProductController.removeVariants',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductRemoveVariantsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/:id/image/create',
handler: 'ProductController.createImage',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdImageCreateRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/:id/variant/:variant/image/create',
handler: 'ProductController.createImage',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
variant: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdVariantVariantImageCreateRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/:id/image/:image/add',
handler: 'ProductController.addImage',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
image: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdImageImageAddRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/:id/image/:image/remove',
handler: 'ProductController.removeImage',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
image: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdImageImageRemoveRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/product/:id/image/:image',
handler: 'ProductController.removeImage',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
image: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteProductIdImageImageRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/associations',
handler: 'ProductController.associations',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdAssociationsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/variant/:id/associations',
handler: 'ProductController.variantAssociations',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdVariantAssociationsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/relations',
handler: 'ProductController.relations',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdRelationsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/suggestions',
handler: 'ProductController.suggestions',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdSuggestionsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/reviews',
handler: 'ProductController.reviews',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdReviewsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/variants',
handler: 'ProductController.variants',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdVariantsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/variants/search',
handler: 'ProductController.variantsSearch',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
term: joi.string().required(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdVariantsSearchRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/images',
handler: 'ProductController.images',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdImagesRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/product/:id/shops',
handler: 'ProductController.shops',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetProductIdShopsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['DELETE','POST'],
path: '/product/:id/removeImages',
handler: 'ProductController.removeImages',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductIdRemoveImagesRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/uploadCSV',
handler: 'ProductController.uploadCSV',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductUploadCsvRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/processUpload/:id',
handler: 'ProductController.processUpload',
config: {
validate: {
params: {
// This will only ever be a string
id: joi.string().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductProcessUploadRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/export',
handler: 'ProductController.exportProducts',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductExportRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/uploadMetaCSV',
handler: 'ProductController.uploadMetaCSV',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductUploadMetaCsvRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/processMetaUpload/:id',
handler: 'ProductController.processMetaUpload',
config: {
validate: {
params: {
// this will only ever be a string
id: joi.string().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductProcessMetaUploadRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/uploadReviewCSV',
handler: 'ProductController.uploadReviewCSV',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostProductUploadReviewCsvRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/product/processReviewUpload/:id',
handler: 'ProductController.processReviewUpload',
config: {
validate: {
params: {
// this will only ever be a string
id: joi.string().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostProductProcessReviewUploadRoute',
roles: ['admin']
}
}
}
},
// Orders
{
method: ['GET'],
path: '/orders',
handler: 'OrderController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.object(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetOrdersRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/order',
handler: 'OrderController.create',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostOrderRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/order/:id/events/:event',
handler: 'OrderController.event',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
event: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdEventsEventRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/order/:id',
handler: 'OrderController.findById',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetOrderIdRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/order/token/:token',
handler: 'OrderController.findByToken',
config: {
validate: {
params: {
token: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetOrderTokenTokenRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/order/:id/customer',
handler: 'OrderController.customer',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetOrderIdCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST', 'PUT'],
path: '/order/:id',
handler: 'OrderController.update',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/pricingOverrides',
handler: 'OrderController.pricingOverrides',
config: {
validate: {
params: {
id: joi.number().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdPricingOverridesRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/addItem',
handler: 'OrderController.addItem',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdAddItemRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/addItems',
handler: 'OrderController.addItems',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdAddItemsRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/updateItem',
handler: 'OrderController.updateItem',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdUpdateItemRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/removeItem',
handler: 'OrderController.removeItem',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdRemoveItemRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/addShipping',
handler: 'OrderController.addShipping',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdAddShippingRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/removeShipping',
handler: 'OrderController.removeShipping',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdRemoveShippingRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/addTaxes',
handler: 'OrderController.addTaxes',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdAddTaxesRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/removeTaxes',
handler: 'OrderController.removeTaxes',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdRemoveTaxesRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/fulfill',
handler: 'OrderController.fulfill',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdFulfillRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/pay',
handler: 'OrderController.pay',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdPayRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/order/:id/events',
handler: 'OrderController.events',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdEventsRoute',
roles: ['admin']
},
proxyRouter: {
ignore: true
}
}
}
},
{
method: ['GET'],
path: '/order/:id/refunds',
handler: 'OrderController.refunds',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdRefundsRoute',
roles: ['admin']
},
proxyRouter: {
ignore: true
},
}
}
},
{
method: ['GET'],
path: '/order/:id/transactions',
handler: 'OrderController.transactions',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdTransactionsRoute',
roles: ['admin']
},
proxyRouter: {
ignore: true
},
}
}
},
{
method: ['PUT'],
path: '/order/:id/transaction/:transaction/pay',
handler: 'OrderController.payTransaction',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
transaction: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdTransactionTransactionPayRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/order/:id/transaction/:transaction/authorize',
handler: 'OrderController.authorizeTransaction',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
transaction: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdTransactionTransactionAuthorizeRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/order/:id/transaction/:transaction/capture',
handler: 'OrderController.captureTransaction',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
transaction: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdTransactionTransactionCaptureRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/order/:id/transaction/:transaction/void',
handler: 'OrderController.voidTransaction',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
transaction: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdTransactionTransactionVoidRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/order/:id/transaction/:transaction/refund',
handler: 'OrderController.refundTransaction',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
transaction: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdTransactionTransactionRefundRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/order/:id/transaction/:transaction/retry',
handler: 'OrderController.retryTransaction',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
transaction: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdTransactionTransactionRetryRoute',
roles: ['admin']
}
}
}
},
{
method: ['PUT'],
path: '/order/:id/transaction/:transaction/cancel',
handler: 'OrderController.cancelTransaction',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
transaction: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdTransactionTransactionCancelRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/order/:id/fulfillments',
handler: 'OrderController.fulfillments',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdFulfillmentsRoute',
roles: ['admin']
},
proxyRouter: {
ignore: true
}
}
}
},
{
method: ['PUT'],
path: '/order/:id/fulfillment/:fulfillment',
handler: 'OrderController.updateFulfillment',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
fulfillment: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdFulfillmentFulfillmentRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/addTag/:tag',
handler: 'OrderController.addTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdAddTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/removeTag/:tag',
handler: 'OrderController.removeTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdRemoveTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/tag/:tag',
handler: 'OrderController.addTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPutOrderIdTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/order/:id/tag/:tag',
handler: 'OrderController.removeTag',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required(),
tag: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteOrderTagTagRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/cancel',
handler: 'OrderController.cancel',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdCancelRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/authorize',
handler: 'OrderController.authorize',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdAuthorizeRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/capture',
handler: 'OrderController.capture',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdCaptureRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/void',
handler: 'OrderController.void',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdVoidRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/refund',
handler: 'OrderController.refund',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdRefundRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/retry',
handler: 'OrderController.retry',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdRetryRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/order/:id/send',
handler: 'OrderController.send',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderIdSendRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/order/generalStats',
handler: 'OrderController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetOrderGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/order/count',
handler: 'OrderController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetOrderCountRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/order/search',
handler: 'OrderController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
term: joi.string().required(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetOrderSearchRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/order/export',
handler: 'OrderController.exportOrders',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostOrderExportRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/order/uploadCSV',
handler: 'OrderController.uploadCSV',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostOrderUploadCsvRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/order/processUpload/:id',
handler: 'OrderController.processUpload',
config: {
validate: {
params: {
// this will only ever be a string
id: joi.string().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostOrderProcessUploadRoute',
roles: ['admin']
}
}
}
},
// Reviews
{
method: ['POST'],
path: '/review',
handler: 'ReviewController.create',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostReviewRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/reviews',
handler: 'ReviewController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetReviewsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/review/:id',
handler: 'ReviewController.findById',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetReviewIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/review/:id',
handler: 'ReviewController.update',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostReviewIdRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/review/generalStats',
handler: 'ReviewController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetReviewGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/review/count',
handler: 'ReviewController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetReviewCountRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/reviews/search',
handler: 'ReviewController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any().optional(),
term: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetReviewsSearchRoute',
roles: ['public','registered','admin']
}
}
}
},
// Shop
{
method: ['GET'],
path: '/shops',
handler: 'ShopController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetShopsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/shop/generalStats',
handler: 'ShopController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetShopGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/shop/count',
handler: 'ShopController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetShopCountRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/shop',
handler: 'ShopController.create',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostShopRoute',
roles: ['admin']
}
}
}
},
// Subscription
{
method: ['GET'],
path: '/subscriptions',
handler: 'SubscriptionController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetSubscriptionsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/subscriptions/search',
handler: 'SubscriptionController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any().optional(),
term: joi.string().required(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetSubscriptionsSearchRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['POST'],
path: '/subscription/:id',
handler: 'SubscriptionController.update',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/subscription/:id',
handler: 'SubscriptionController.findById',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetSubscriptionIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/subscription/token/:token',
handler: 'SubscriptionController.findByToken',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetSubscriptionTokenTokenRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/subscription/:id/customer',
handler: 'SubscriptionController.customer',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetSubscriptionIdCustomerRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/subscription/:id/activate',
handler: 'SubscriptionController.activate',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionIdActivateRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/subscription/:id/deactivate',
handler: 'SubscriptionController.deactivate',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionIdDeactivateRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/subscription/:id/renew',
handler: 'SubscriptionController.renew',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionIdRenewRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/subscription/:id/addItems',
handler: 'SubscriptionController.addItems',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionIdAddItemsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/subscription/:id/cancel',
handler: 'SubscriptionController.cancel',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionIdCancelRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/subscription/:id/removeItems',
handler: 'SubscriptionController.removeItems',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionIdRemoveItemsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/subscription/:id/events',
handler: 'SubscriptionController.events',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetSubscriptionIdEventsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/subscription/:id/update',
handler: 'SubscriptionController.update',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionIdUpdateRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/subscription/generalStats',
handler: 'SubscriptionController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetSubscriptionGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/subscription/count',
handler: 'SubscriptionController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetSubscriptionCountRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/subscription/uploadCSV',
handler: 'SubscriptionController.uploadCSV',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionUploadCsvRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/subscription/processUpload/:id',
handler: 'SubscriptionController.processUpload',
config: {
validate: {
params: {
// this will only ever be a string
id: joi.string().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostSubscriptionProcessUploadRoute',
roles: ['admin']
}
}
}
},
// Tag
{
method: ['GET'],
path: '/tags',
handler: 'TagController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetTagsRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/tag/:id',
handler: 'TagController.findById',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetTagIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/tag/name/:name',
handler: 'TagController.findByName',
config: {
validate: {
params: {
// this will only ever be a string
name: joi.string().required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetTagNameRoute',
roles: ['public','registered','admin']
}
}
}
},
{
method: ['GET'],
path: '/tag/count',
handler: 'TagController.count',
config: {
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetTagCountRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/tag/search',
handler: 'TagController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any().optional(),
term: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetTagSearchRoute',
roles: ['public','registered','admin']
}
}
}
},
// Transaction
{
method: ['POST'],
path: '/transaction',
handler: 'TransactionController.create',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/transaction/generalStats',
handler: 'TransactionController.generalStats',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetTransactionGeneralStatsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/transactions',
handler: 'TransactionController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetTransactionsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/transaction/:id',
handler: 'TransactionController.findById',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiGetTransactionIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/transaction/:id',
handler: 'TransactionController.update',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['DELETE'],
path: '/transaction/:id',
handler: 'TransactionController.destroy',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiDeleteTransactionIdRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/transaction/:id/authorize',
handler: 'TransactionController.authorize',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionAuthorizeRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/transaction/:id/capture',
handler: 'TransactionController.capture',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionIdCaptureRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/transaction/:id/retry',
handler: 'TransactionController.retry',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionIdRetryRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/transaction/:id/sale',
handler: 'TransactionController.sale',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionIdSaleRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/transaction/:id/void',
handler: 'TransactionController.void',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionIdVoidRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/transaction/:id/refund',
handler: 'TransactionController.refund',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionIdRefundRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST','PUT'],
path: '/transaction/:id/cancel',
handler: 'TransactionController.cancel',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostTransactionIdCancelRoute',
roles: ['admin']
}
}
}
},
// User
{
method: ['GET'],
path: '/user/:id/customers',
handler: 'UserController.customers',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetUserIdCustomersRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/user/customers',
handler: 'UserController.customers',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetUserCustomersRoute',
roles: ['admin','registered']
}
}
}
},
{
method: ['GET'],
path: '/user/:id/passports',
handler: 'UserController.passports',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
},
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetUserIdPassportsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/user/reviews',
handler: 'UserController.reviews',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetUserReviewsRoute',
roles: ['admin','registered']
}
}
}
},
// Vendor
{
method: ['GET'],
path: '/vendors',
handler: 'VendorController.findAll',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetVendorsRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/vendors/search',
handler: 'VendorController.search',
config: {
validate: {
query: {
offset: joi.number(),
limit: joi.number(),
sort: joi.array().items(joi.array()),
where: joi.any(),
term: joi.any(),
include: joi.array().items(joi.string())
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetVendorsSearchRoute',
roles: ['admin']
}
}
}
},
{
method: ['GET'],
path: '/vendor/:id/products',
handler: 'VendorController.products',
config: {
validate: {
params: {
id: joi.alternatives().try(
joi.number(),
joi.string()
).required()
}
},
app: {
proxyRouter: {
ignore: true
},
proxyPermissions: {
resource_name: 'apiGetVendorIdProductsRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/vendor/uploadCSV',
handler: 'VendorController.uploadCSV',
config: {
app: {
proxyPermissions: {
resource_name: 'apiPostVendorUploadCsvRoute',
roles: ['admin']
}
}
}
},
{
method: ['POST'],
path: '/vendor/processUpload/:id',
handler: 'VendorController.processUpload',
config: {
validate: {
params: {
// This will only ever be a sting
id: joi.string().required()
}
},
app: {
proxyPermissions: {
resource_name: 'apiPostVendorProcessUploadRoute',
roles: ['admin']
}
}
}
}
]
|
export default function (sequelize, DataTypes) {
const Province = sequelize.define('province', {
province: {
type: DataTypes.STRING,
}
}, {
classMethods: {
associate: models => {
Province.belongsTo(models.country);
Province.belongsToMany(models.city, {
through: 'provinceCity'
});
}
},
freezeTableName: true // Model tableName will be the same as the model name
});
return Province;
}
|
function pad(number, size) {
var zeroesToAdd = 7 - size
var newNumber = number
for (var x = zeroesToAdd - 1; x >= 0; x--) {
newNumber = "0" + newNumber
};
return newNumber
}
var app = angular.module('scoresApp',[])
function ScoreController($scope, $http){
$http({method: 'GET', url: '/games/1/scores'}).success(function(data, status, headers, config) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
var counter = 1;
for (var items in data.scores) {
data.scores[items].id = counter
counter = counter + 1
$scope.data.push(data.scores[items])
var val = $scope.data[items].value
var valLen = val.toString().length
$scope.data[items].value = pad(val,valLen)
}
})
}
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
if (input != undefined){
return input.slice(start);
}
}
}); |
var data = {names: ['aaa', 'bbb', 'ccc']}; |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Sale Schema
*/
var SaleSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Client name',
trim: true
},
cnpj: {
type: String,
default: '',
required: 'Please fill CNPJ'
},
address: {
type: String,
default: '',
required: 'Please fill ADDRESS'
},
products: {
type: Array,
required: 'Please fill Products'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Sale', SaleSchema);
|
'use strict';
import React from 'react';
import DocumentLink from 'fw/DocumentLink';
import LessonTitle from 'fw/LessonTitle';
import LessonHelper from 'fw/LessonHelper';
import Preview from 'fw/Preview';
import InputBar from './InputBar';
import TextList from './TextList';
class Lesson3 extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<LessonTitle text='add input text into below list' />
<LessonHelper>
<DocumentLink link='http://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute' text='Read reference' />
<DocumentLink link='http://facebook.github.io/react/docs/multiple-components.html#dynamic-children' text='Read dynamic-children' />
<DocumentLink link='http://facebook.github.io/react/docs/reusable-components.html#es6-classes' text='Read reusable-components' />
</LessonHelper>
<Preview>
<InputBar/>
<TextList />
</Preview>
</div>
);
}
}
module.exports = Lesson3;
|
import React from "react"
import { Link } from "gatsby"
import { rhythm, scale } from "../utils/typography"
import Cube from "../components/cube"
class IndexLayout extends React.Component {
render() {
const { location, title, children } = this.props
const rootPath = `${__PATH_PREFIX__}/blog`
let header
if (location.pathname === rootPath) {
header = (
<h1
style={{
...scale(1.2),
marginBottom: rhythm(1.5),
marginTop: 0,
}}
>
<Link
style={{
boxShadow: `none`,
textDecoration: `none`,
color: `inherit`,
}}
to={`/blog`}
>
{title}
</Link>
</h1>
)
} else {
header = (
<>
<Link
to="/blog"
style={{ boxShadow: "none", marginRight: 20, height: 80 }}
>
<Cube />
</Link>
<h3
style={{
fontFamily: `Montserrat, system-ui, sans-serif`,
marginTop: 33,
}}
>
<Link
style={{
boxShadow: `none`,
textDecoration: `none`,
color: `inherit`,
}}
to={`/blog`}
>
{title}
</Link>
</h3>
</>
)
}
return (
<div
style={{
marginLeft: `auto`,
marginRight: `auto`,
maxWidth: rhythm(24),
padding: `${rhythm(1)} ${rhythm(3 / 4)}`,
}}
>
<header
style={{
display: "flex",
alignItems: "center",
height: `auto`,
}}
>
{header}
</header>
<main>{children}</main>
</div>
)
}
}
export default IndexLayout
|
const App = require('ghost-app');
const BASE_URL = process.env.BASE_TOMMY_URL || 'http://tommy-web.ertrzyiks.me/'
function renderTommyIframe(slug) {
return `
<div class="post-iframe_placeholder--tommy">
<div class="post-iframe_wrapper--tommy">
<button class="post-iframe_button--tommy is-hidden" style="display: none;" data-role="load-exercise">Load exercise</button>
<iframe class="post-iframe--tommy" data-src="${BASE_URL}${slug}" style="width: 100%; height: 600px; border: none;"></iframe>
</div>
</div>
`
}
function replaceWithTommyIframe(html) {
return html.replace(/<!--TOMMY (.+?) YMMOT-->/g, function (match, slug) {
return renderTommyIframe(slug)
})
}
const cssUrl = '/assets/my-ghost-tommy/css/tommy.css?v=1'
const jsUrl = '/assets/my-ghost-tommy/js/tommy.js?v=1'
var MyApp = App.extend({
filters: {
prePostsRender: 'handlePrePostRender',
ghost_head: 'handleGhostHead',
ghost_foot: 'handleGhostFoot',
},
handlePrePostRender: function (post) {
if (post.html) {
post.html = replaceWithTommyIframe(post.html)
}
return post;
},
handleGhostHead: function (head) {
head.push(`<link rel="preload" href="${cssUrl}" as="style">`)
return head;
},
handleGhostFoot: function (foot) {
foot.push(`<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '${cssUrl}';
link.type = 'text/css';
var ref = document.getElementsByTagName('link')[0];
ref.parentNode.insertBefore(link, ref);
</script>`)
foot.push(`<script async defer src="${jsUrl}"></script>\n`)
return foot
}
});
module.exports = MyApp
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.redListVersion = exports.setRedListToken = exports.redListToken = undefined;
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _util = require('./util');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var redListToken = process.env.RED_LIST_TOKEN;
var setRedListToken = function setRedListToken(token) {
exports.redListToken = redListToken = token;
return null;
};
var redListVersion = function redListVersion() {
return new _promise2.default(function (resolve, reject) {
return (0, _util.sendRequest)('/version', resolve, reject, _util.handleResult);
});
};
exports.redListToken = redListToken;
exports.setRedListToken = setRedListToken;
exports.redListVersion = redListVersion; |
Pizzicato.Events = {
/**
* Adds an event handler that will be treated upon
* the triggering of that event.
*/
on: function(name, callback, context) {
if (!name || !callback)
return;
this._events = this._events || {};
var _event = this._events[name] || (this._events[name] = []);
_event.push({
callback: callback,
context: context || this,
handler: this
});
},
/**
* Triggers a particular event. If a handler
* is linked to that event, the handler will be
* executed.
*/
trigger: function(name) {
if (!name)
return;
var _event, length, args, i;
this._events = this._events || {};
_event = this._events[name] || (this._events[name] = []);
if (!_event)
return;
length = Math.max(0, arguments.length - 1);
args = [];
for (i = 0; i < length; i++)
args[i] = arguments[i + 1];
for (i = 0; i < _event.length; i++)
_event[i].callback.apply(_event[i].context, args);
},
/**
* Removes an event handler. If no name is provided,
* all handlers for this object will be removed.
*/
off: function(name) {
if (name)
this._events[name] = undefined;
else
this._events = {};
}
}; |
import Vue from 'vue'
import VueRouter from 'vue-router' // eslint-disable-line import/no-extraneous-dependencies
import VueI18n from 'vue-i18n'
import VueLazyload from 'vue-lazyload'
import PhotoCard from './PhotoCard.vue'
describe('Component | PhotoCard.vue', () => {
let wrapper
let photo
let localVue
beforeEach(() => {
photo = {
imgLink: 'webf',
dropboxId: '45',
}
console.warn = jest.fn()
localVue = createLocalVue()
localVue.use(VueI18n)
localVue.use(VueRouter)
localVue.use(VueLazyload)
const propsData = { photo }
wrapper = shallowMount(PhotoCard, { localVue, propsData })
})
describe('template', () => {
it('should match snapshot', () => {
expect(wrapper).toMatchSnapshot()
})
})
describe('render', () => {
it('should render photo image', () => Vue.nextTick().then(() => {
const photoLink = wrapper.find('img')
expect(photoLink.attributes().src).toEqual('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
expect(photoLink.attributes().lazy).toEqual('loading')
}))
// // Comment tester le lazy load ?
// it.skip('should render photo image', () => Vue.nextTick().then(() => {
// const photoLink = wrapper.find('img')
//
// // return Vue.nextTick().then(() => {
// // console.log(photoLink);
// expect(photoLink.getAttribute('lazy')).toEqual('loaded')
// expect(photoLink.getAttribute('src')).toContain('webf')
// // });
// }))
})
describe('computed property #imgLink', () => {
it('should return imgLink when defined', () => {
photo.imgLink = 'dropbox.com/img0.jpg'
const propsData = { photo }
wrapper = shallowMount(PhotoCard, { localVue, propsData })
expect(wrapper.vm.imgLink).toEqual('dropbox.com/img0.jpg')
})
it('should return false when api status is undefined', () => {
photo.imgLink = ''
const propsData = { photo }
wrapper = shallowMount(PhotoCard, { localVue, propsData })
expect(wrapper.vm.imgLink).toEqual(false)
})
})
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:205f7d5f24d70eb38bbde6852bde49be8838590352bf82dd062237ab6069e1a7
size 5329
|
import category from './category';
export default {
category
};
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* <p>
* The current version of Cocos2d-html5 being used.<br/>
* Please DO NOT remove this String, it is an important flag for bug tracking.<br/>
* If you post a bug to forum, please attach this flag.
* </p>
* @constant
* @type String
*/
cc.ENGINE_VERSION = "Cocos2d-html5-v2.1.4";
/**
* <p>
* If enabled, the texture coordinates will be calculated by using this formula: <br/>
* - texCoord.left = (rect.origin.x*2+1) / (texture.wide*2); <br/>
* - texCoord.right = texCoord.left + (rect.size.width*2-2)/(texture.wide*2); <br/>
* <br/>
* The same for bottom and top. <br/>
* <br/>
* This formula prevents artifacts by using 99% of the texture. <br/>
* The "correct" way to prevent artifacts is by using the spritesheet-artifact-fixer.py or a similar tool.<br/>
* <br/>
* Affected nodes: <br/>
* - cc.Sprite / cc.SpriteBatchNode and subclasses: cc.LabelBMFont, cc.TMXTiledMap <br/>
* - cc.LabelAtlas <br/>
* - cc.QuadParticleSystem <br/>
* - cc.TileMap <br/>
* <br/>
* To enabled set it to 1. Disabled by default.
* </p>
* @constant
* @type Number
*/
cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0;
/**
* Position of the FPS (Default: 0,0 (bottom-left corner))
* @constant
* @type cc.Point
*/
cc.DIRECTOR_STATS_POSITION = cc.p(0, 0);
/**
* <p>
* Senconds between FPS updates.<br/>
* 0.5 seconds, means that the FPS number will be updated every 0.5 seconds.<br/>
* Having a bigger number means a more reliable FPS<br/>
* <br/>
* Default value: 0.1f<br/>
* </p>
* @constant
* @type Number
*/
cc.DIRECTOR_FPS_INTERVAL = 0.5;
/**
* <p>
* If enabled, the cc.Node objects (cc.Sprite, cc.Label,etc) will be able to render in subpixels.<br/>
* If disabled, integer pixels will be used.<br/>
* <br/>
* To enable set it to 1. Enabled by default.
* </p>
* @constant
* @type Number
*/
cc.COCOSNODE_RENDER_SUBPIXEL = 1;
/**
* <p>
* If enabled, the cc.Sprite objects rendered with cc.SpriteBatchNode will be able to render in subpixels.<br/>
* If disabled, integer pixels will be used.<br/>
* <br/>
* To enable set it to 1. Enabled by default.
* </p>
* @constant
* @type Number
*/
cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 1;
/**
* <p>
* If most of your imamges have pre-multiplied alpha, set it to 1 (if you are going to use .PNG/.JPG file images).<br/>
* Only set to 0 if ALL your images by-pass Apple UIImage loading system (eg: if you use libpng or PVR images)<br/>
* <br/>
* To enable set it to a value different than 0. Enabled by default.
* </p>
* @constant
* @type Number
*/
cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = 1;
/**
* <p>
* Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture atlas.<br/>
* It seems it is the recommend way, but it is much slower, so, enable it at your own risk<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default.
* </p>
* @constant
* @type Number
*/
cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0;
/**
* <p>
* By default, cc.TextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects).<br/>
* Apple recommends its usage but they might consume a lot of memory, specially if you use many of them.<br/>
* So for certain cases, where you might need hundreds of VAO objects, it might be a good idea to disable it.<br/>
* <br/>
* To disable it set it to 0. disable by default.(Not Supported on WebGL)<br/>
* </p>
* @constant
* @type Number
*/
cc.TEXTURE_ATLAS_USE_VAO = 0;
/**
* <p>
* If enabled, NPOT textures will be used where available. Only 3rd gen (and newer) devices support NPOT textures.<br/>
* NPOT textures have the following limitations:<br/>
* - They can't have mipmaps<br/>
* - They only accept GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default. <br/>
* <br/>
* This value governs only the PNG, GIF, BMP, images.<br/>
* This value DOES NOT govern the PVR (PVR.GZ, PVR.CCZ) files. If NPOT PVR is loaded, then it will create an NPOT texture ignoring this value.
* </p>
* @constant
* @type Number
* @deprecated This value will be removed in 1.1 and NPOT textures will be loaded by default if the device supports it.
*/
cc.TEXTURE_NPOT_SUPPORT = 0;
/**
* <p>
* If enabled, cocos2d supports retina display.<br/>
* For performance reasons, it's recommended disable it in games without retina display support, like iPad only games.<br/>
* <br/>
* To enable set it to 1. Use 0 to disable it. Enabled by default.<br/>
* <br/>
* This value governs only the PNG, GIF, BMP, images.<br/>
* This value DOES NOT govern the PVR (PVR.GZ, PVR.CCZ) files. If NPOT PVR is loaded, then it will create an NPOT texture ignoring this value.
* </p>
* @constant
* @type Number
* @deprecated This value will be removed in 1.1 and NPOT textures will be loaded by default if the device supports it.
*/
cc.RETINA_DISPLAY_SUPPORT = 1;
/**
* <p>
* It's the suffix that will be appended to the files in order to load "retina display" images.<br/>
* <br/>
* On an iPhone4 with Retina Display support enabled, the file @"sprite-hd.png" will be loaded instead of @"sprite.png".<br/>
* If the file doesn't exist it will use the non-retina display image.<br/>
* <br/>
* Platforms: Only used on Retina Display devices like iPhone 4.
* </p>
* @constant
* @type String
*/
cc.RETINA_DISPLAY_FILENAME_SUFFIX = "-hd";
/**
* <p>
* If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for CCLabelTTF objects. <br/>
* If it is disabled, it will use A8 (Alpha 8-bit textures). <br/>
* LA88 textures are 6% faster than A8 textures, but they will consume 2x memory. <br/>
* <br/>
* This feature is enabled by default.
* </p>
* @constant
* @type Number
*/
cc.USE_LA88_LABELS = 1;
/**
* <p>
* If enabled, all subclasses of cc.Sprite will draw a bounding box<br/>
* Useful for debugging purposes only. It is recommened to leave it disabled.<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default:<br/>
* 0 -- disabled<br/>
* 1 -- draw bounding box<br/>
* 2 -- draw texture box
* </p>
* @constant
* @type Number
*/
cc.SPRITE_DEBUG_DRAW = 0;
/**
* <p>
* If enabled, all subclasses of cc.Sprite that are rendered using an cc.SpriteBatchNode draw a bounding box.<br/>
* Useful for debugging purposes only. It is recommened to leave it disabled.<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default.
* </p>
* @constant
* @type Number
*/
cc.SPRITEBATCHNODE_DEBUG_DRAW = 0;
/**
* <p>
* If enabled, all subclasses of cc.LabelBMFont will draw a bounding box <br/>
* Useful for debugging purposes only. It is recommened to leave it disabled.<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default.<br/>
* </p>
* @constant
* @type Number
*/
cc.LABELBMFONT_DEBUG_DRAW = 0;
/**
* <p>
* If enabled, all subclasses of cc.LabeltAtlas will draw a bounding box<br/>
* Useful for debugging purposes only. It is recommened to leave it disabled.<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default.
* </p>
* @constant
* @type Number
*/
cc.LABELATLAS_DEBUG_DRAW = 0;
/**
* whether or not support retina display
* @constant
* @type Number
*/
cc.IS_RETINA_DISPLAY_SUPPORTED = 1;
/**
* default engine
* @constant
* @type String
*/
cc.DEFAULT_ENGINE = cc.ENGINE_VERSION + "-canvas";
/**
* Runtime information
* @deprecated Use "sys" instead.
*/
cc.config = {
'platform' : sys.platform
};
/**
* dump config info, but only in debug mode
*/
cc.dumpConfig = function() {
for(var i in sys )
cc.log( i + " = " + sys[i] );
};
/** @def CC_ENABLE_GL_STATE_CACHE
If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches.
In order to use them, you have to use the following functions, insead of the the GL ones:
- ccGLUseProgram() instead of glUseProgram()
- ccGLDeleteProgram() instead of glDeleteProgram()
- ccGLBlendFunc() instead of glBlendFunc()
If this functionality is disabled, then ccGLUseProgram(), ccGLDeleteProgram(), ccGLBlendFunc() will call the GL ones, without using the cache.
It is recommened to enable whenever possible to improve speed.
If you are migrating your code from GL ES 1.1, then keep it disabled. Once all your code works as expected, turn it on.
@since v2.0.0
*/
cc.ENABLE_GL_STATE_CACHE = 1; |
import throttle from 'lodash/throttle'
import createReducer from '@zap/utils/createReducer'
import { CoinBig } from '@zap/utils/coin'
import { getIntl } from '@zap/i18n'
import { requestSuggestedNodes } from '@zap/utils/api'
import { grpc } from 'workers'
import { fetchPeers } from 'reducers/peers'
import { fetchBalance } from 'reducers/balance'
import { updateNotification, showWarning, showError } from 'reducers/notification'
import { walletSelectors } from 'reducers/wallet'
import { updateNodeData } from 'reducers/network'
import { putConfig, settingsSelectors } from 'reducers/settings'
import messages from './messages'
import * as constants from './constants'
import channelsSelectors from './selectors'
const {
DEFAULT_FILTER,
SET_CHANNEL_VIEW_MODE,
SET_SELECTED_CHANNEL,
CHANGE_CHANNEL_FILTER,
CHANGE_CHANNEL_SORT,
CHANGE_CHANNEL_SORT_ORDER,
UPDATE_SEARCH_QUERY,
GET_CHANNELS,
RECEIVE_CHANNELS,
ADD_LOADING_PUBKEY,
REMOVE_LOADING_PUBKEY,
ADD_CLOSING_CHAN_ID,
REMOVE_CLOSING_CHAN_ID,
GET_SUGGESTED_NODES,
RECEIVE_SUGGESTED_NODES_ERROR,
RECEIVE_SUGGESTED_NODES,
OPEN_CHANNEL,
OPEN_CHANNEL_SUCCESS,
OPEN_CHANNEL_FAILURE,
} = constants
const CHANNEL_REFRESH_THROTTLE = 1000 * 60
// ------------------------------------
// Initial State
// ------------------------------------
const initialState = {
channelsLoading: false,
loadingChannels: [],
channels: [],
pendingChannels: {
totalLimboBalance: '0',
pendingOpenChannels: [],
pendingClosingChannels: [],
pendingForceClosingChannels: [],
waitingCloseChannels: [],
},
closedChannels: [],
closingChannelIds: [],
searchQuery: null,
filter: new Set([...DEFAULT_FILTER]),
filters: [
{ key: 'ACTIVE_CHANNELS', value: 'Online' },
{ key: 'NON_ACTIVE_CHANNELS', value: 'Offline' },
{ key: 'OPEN_PENDING_CHANNELS', value: 'Pending' },
{ key: 'CLOSING_PENDING_CHANNELS', value: 'Closing' },
],
sortOrder: 'asc',
sort: 'CHANNELS_SORT_OPEN_DATE',
sorters: [
{ key: 'CHANNELS_SORT_OPEN_DATE', value: 'Open date' },
{ key: 'CHANNELS_SORT_REMOTE_BALANCE', value: 'Remote balance' },
{ key: 'CHANNELS_SORT_LOCAL_BALANCE', value: 'Local balance' },
{ key: 'CHANNELS_SORT_ACTIVITY', value: 'Activity' },
{ key: 'CHANNELS_SORT_NAME', value: 'Name' },
{ key: 'CHANNELS_SORT_CAPACITY', value: 'Capacity' },
],
selectedChannelId: null,
suggestedNodes: {
mainnet: [],
testnet: [],
},
suggestedNodesLoading: false,
suggestedNodesError: null,
}
// ------------------------------------
// Actions
// ------------------------------------
/**
* setChannelViewMode - Set the current channels list view mode.
*
* @param {('list'|'card')} viewMode View mode
* @returns {(dispatch:Function) => void} Thunk
*/
export const setChannelViewMode = viewMode => dispatch => {
dispatch({ type: SET_CHANNEL_VIEW_MODE, viewMode })
dispatch(putConfig('channels.viewMode', viewMode))
}
/**
* initChannels - Initialise channels.
*
* @returns {(dispatch:Function, getState:Function) => Promise<void>} Thunk
*/
export const initChannels = () => async (dispatch, getState) => {
const state = getState()
const currentConfig = settingsSelectors.currentConfig(state)
const currentViewMode = channelsSelectors.viewMode(state)
if (currentConfig.channels.viewMode !== currentViewMode) {
dispatch(setChannelViewMode(currentConfig.channels.viewMode))
}
}
/**
* changeFilter - Set the current channels list filter.
*
* @param {string} filter Filter Id
* @returns {object} Action
*/
export function changeFilter(filter) {
return {
type: CHANGE_CHANNEL_FILTER,
filter,
}
}
/**
* changeSort - Set the current channels list sort.
*
* @param {string} sort Sort Id
* @returns {object} Action
*/
export function changeSort(sort) {
return {
type: CHANGE_CHANNEL_SORT,
sort,
}
}
/**
* changeSortOrder - Set the current channels list sort order.
*
* @param {('asc'|'desc')} sortOrder Sort order
* @returns {object} Action
*/
export function changeSortOrder(sortOrder) {
return {
type: CHANGE_CHANNEL_SORT_ORDER,
sortOrder,
}
}
/**
* switchSortOrder - Switches between sort modes (asc<->desc).
*
* @returns {Function} Thunk
*/
export function switchSortOrder() {
return (dispatch, getState) => {
const sortOrder = channelsSelectors.channelSortOrder(getState())
return dispatch(changeSortOrder(sortOrder === 'asc' ? 'desc' : 'asc'))
}
}
/**
* getChannels - Initialte fetch of channel data.
*
* @returns {object} Action
*/
export function getChannels() {
return {
type: GET_CHANNELS,
}
}
/**
* updateChannelSearchQuery - Set the current channel serach string.
*
* @param {string} searchQuery Search query
* @returns {object} Action
*/
export function updateChannelSearchQuery(searchQuery) {
return {
type: UPDATE_SEARCH_QUERY,
searchQuery,
}
}
/**
* addLoadingChannel - Add a channel to the list of currently loading channels.
*
* @param {object} data Channel loading object
* @returns {object} Action
*/
export function addLoadingChannel(data) {
return {
type: ADD_LOADING_PUBKEY,
data,
}
}
/**
* removeLoadingChannel - Remove an item from list of currently loading channels.
*
* @param {string} pubkey Channel Pubkey
* @returns {object} Action
*/
export function removeLoadingChannel(pubkey) {
return {
type: REMOVE_LOADING_PUBKEY,
pubkey,
}
}
/**
* addClosingChanId - Add a channel id to to the list of currently closing channels.
*
* @param {string} chanId Channel Id
* @returns {object} Action
*/
export function addClosingChanId(chanId) {
return {
type: ADD_CLOSING_CHAN_ID,
chanId,
}
}
/**
* removeClosingChanId - Remove an item from list of currently closing channels.
*
* @param {string} chanId Channel Id
* @returns {object} Action
*/
export function removeClosingChanId(chanId) {
return {
type: REMOVE_CLOSING_CHAN_ID,
chanId,
}
}
/**
* setSelectedChannel - Set the currently selected channel.
*
* @param {string} selectedChannelId Channel Id
* @returns {object} Action
*/
export function setSelectedChannel(selectedChannelId) {
return {
type: SET_SELECTED_CHANNEL,
selectedChannelId,
}
}
/**
* getSuggestedNodes - Initiate fetch of the suggested nodes list.
*
* @returns {object} Action
*/
export function getSuggestedNodes() {
return {
type: GET_SUGGESTED_NODES,
}
}
/**
* receiveSuggestedNodesError - Error handler for issues fetching the suggested nodes list.
*
* @param {string} error Error message
* @returns {object} Action
*/
export function receiveSuggestedNodesError(error) {
return {
type: RECEIVE_SUGGESTED_NODES_ERROR,
error,
}
}
/**
* receiveSuggestedNodes - Success handler for fetching the suggested nodes list.
*
* @param {object[]} suggestedNodes List of suggested nodes
* @returns {object} Action
*/
export function receiveSuggestedNodes(suggestedNodes) {
return {
type: RECEIVE_SUGGESTED_NODES,
suggestedNodes,
}
}
/**
* fetchSuggestedNodes - Fetch suggested node list.
*
* @returns {(dispatch:Function) => Promise<void>} Thunk
*/
export const fetchSuggestedNodes = () => async dispatch => {
dispatch(getSuggestedNodes())
try {
const suggestedNodes = await requestSuggestedNodes()
dispatch(receiveSuggestedNodes(suggestedNodes))
} catch (error) {
dispatch(receiveSuggestedNodesError(error.message))
}
}
/**
* receiveChannels - Receive channels data from lnd.
*
* @param {object} data Details of all current channels
* @param {object} data.channels Channel data
* @param {object[]} data.channels.channels Channel data
* @param {object[]} data.pendingChannels Pending channels
* @param {object} data.closedChannels Closed channels
* @param {object[]} data.closedChannels.channels Closed channels
* @returns {(dispatch:Function) => void} Thunk
*/
export const receiveChannels = ({
channels: { channels },
pendingChannels,
closedChannels: { channels: closedChannels },
}) => dispatch => {
dispatch({ type: RECEIVE_CHANNELS, channels, pendingChannels, closedChannels })
}
/**
* fetchChannels - Fetch channel data from lnd.
*
* @returns {(dispatch:Function) => Promise<void>} Thunk
*/
export const fetchChannels = () => async dispatch => {
dispatch(getChannels())
const channels = await grpc.services.Lightning.getChannels()
await dispatch(receiveChannels(channels))
}
/**
* refreshChannels - Refresh channel data from lnd.
*
* @returns {(dispatch:Function) => Promise<void>} Thunk
*/
export const refreshChannels = () => async dispatch => {
await Promise.all([dispatch(fetchChannels()), dispatch(fetchPeers())])
}
/**
* pushchannelupdated - Receive a channel update notification from lnd.
*
* @param {object} data Channel update notification
* @param {string} data.nodePubkey Node pubkey
* @param {string} data.chanId Channel Id
* @param {object} data.data Channel update data
* @returns {(dispatch:Function) => void} Thunk
*/
export const pushchannelupdated = ({ nodePubkey, chanId, data }) => dispatch => {
dispatch(fetchChannels())
dispatch(fetchBalance())
if (data.update === 'chanPending') {
if (nodePubkey) {
dispatch(removeLoadingChannel(nodePubkey))
} else if (chanId) {
dispatch(removeClosingChanId(chanId))
}
dispatch(
updateNotification(
{ payload: { pubkey: nodePubkey, chanId } },
{
variant: 'success',
message: 'Channel successfully created',
isProcessing: false,
}
)
)
}
}
/**
* pushchannelerror - Receive a channel error notification from lnd.
*
* @param {object} data Channel error notification
* @param {string} [data.nodePubkey] Node pubkey
* @param {string} [data.chanId] Channel id
* @param {string} data.error Error
* @returns {(dispatch:Function) => void} Thunk
*/
export const pushchannelerror = ({ nodePubkey, chanId, error }) => dispatch => {
if (nodePubkey) {
dispatch(removeLoadingChannel(nodePubkey))
} else if (chanId) {
dispatch(removeClosingChanId(chanId))
}
dispatch(
updateNotification(
{ payload: { pubkey: nodePubkey, chanId } },
{
variant: 'error',
message: error,
isProcessing: false,
}
)
)
}
/**
* pushclosechannelupdated - Receive a channel cloase update notification from lnd.
*
* @param {object} data Channel close update notification
* @param {string} data.chanId Channel Id
* @returns {(dispatch:Function) => void} Thunk
*/
export const pushclosechannelupdated = ({ chanId }) => dispatch => {
dispatch(fetchChannels())
dispatch(fetchBalance())
dispatch(removeClosingChanId(chanId))
}
/**
* openChannel - Send open channel request to lnd.
*
* @param {object} data New channel config
* @returns {(dispatch:Function, getState:Function) => Promise<void>} Thunk
*/
export const openChannel = data => async (dispatch, getState) => {
const {
pubkey,
host,
localamt,
satPerByte,
isPrivate,
remoteCsvDelay,
spendUnconfirmed = true,
} = data
dispatch({ type: OPEN_CHANNEL, data })
// Grab the activeWallet type from our local store. If the active connection type is local (light clients using
// neutrino) we will flag manually created channels as private. Other connections like remote node and BTCPay Server
// we will announce to the network as these users are using Zap to drive nodes that are online 24/7
const state = getState()
const activeWalletSettings = walletSelectors.activeWalletSettings(state)
const channelIsPrivate = isPrivate || activeWalletSettings.type === 'local'
// Add channel loading state.
const loadingChannel = {
nodePubkey: pubkey,
localBalance: CoinBig(localamt || 0).toString(),
remoteBalance: '0',
private: channelIsPrivate,
}
dispatch(addLoadingChannel(loadingChannel))
// Show notification.
dispatch(
showWarning(getIntl().formatMessage(messages.channels_open_warning), {
timeout: 3000,
isProcessing: true,
payload: { pubkey },
})
)
// Attempt to open the channel.
try {
const channelData = await grpc.services.Lightning.connectAndOpen({
pubkey,
host,
localamt,
private: channelIsPrivate,
satPerByte,
remoteCsvDelay,
spendUnconfirmed,
})
dispatch(pushchannelupdated(channelData))
dispatch({ type: OPEN_CHANNEL_SUCCESS })
} catch (e) {
dispatch(
pushchannelerror({
error: `Unable to open channel: ${e.message}`,
nodePubkey: pubkey,
})
)
dispatch({ type: OPEN_CHANNEL_FAILURE })
}
}
/**
* closeChannel - Close the currently selected channel.
*
* @param {object} data Channel error notification
* @param {string|number} [data.targetConf] The target number of blocks the closure transaction should be confirmed by.
* @returns {(dispatch:Function, getState:Function) => Promise<void>} Thunk
*/
export const closeChannel = ({ targetConf }) => async (dispatch, getState) => {
const selectedChannel = channelsSelectors.selectedChannel(getState())
if (selectedChannel) {
const { channelPoint, chanId, active } = selectedChannel
dispatch(addClosingChanId(chanId))
const [fundingTxid, outputIndex] = channelPoint.split(':')
// Attempt to close the channel.
try {
const data = await grpc.services.Lightning.closeChannel({
channelPoint: {
fundingTxid,
outputIndex,
},
chanId,
force: !active,
targetConf,
})
dispatch(pushclosechannelupdated(data))
} catch (e) {
dispatch(
pushchannelerror({
error: `Unable to close channel: ${e.message}`,
chanId: e.payload.chanId,
})
)
}
}
}
/**
* pushclosechannelerror - Receive a channel cloase error notification from lnd.
*
* @param {object} data Channel close error notification
* @param {string} data.error Error
* @param {string} data.chanId Channel Id
* @returns {(dispatch:Function) => void} Thunk
*/
export const pushclosechannelerror = ({ error, chanId }) => dispatch => {
dispatch(showError(error))
dispatch(removeClosingChanId(chanId))
}
/**
* throttledFetchChannels - Throttled dispatch to fetchChannels (calls fetchChannels no more than once per second).
*/
const throttledFetchChannels = throttle(
dispatch => {
dispatch(fetchChannels())
dispatch(fetchBalance())
},
CHANNEL_REFRESH_THROTTLE,
{
leading: true,
trailing: true,
}
)
/**
* receiveChannelGraphData - Receive channel graph data from lnd.
*
* @param {object} data Channel grph subscription updates.
* @param {object} data.channelUpdates New channels being advertised, updates in channel routing policy etc
* @param {object} data.nodeUpdates New nodes coming online, nodes updating their authenticated attributes
* @returns {(dispatch:Function, getState:Function) => void} Thunk
*/
export const receiveChannelGraphData = ({ channelUpdates, nodeUpdates }) => (
dispatch,
getState
) => {
const { info, channels } = getState()
// Process node updates.
if (nodeUpdates.length) {
dispatch(updateNodeData(nodeUpdates))
}
// if there are any new channel updates
let hasUpdates = false
if (channelUpdates.length) {
// loop through the channel updates
for (let i = 0; i < channelUpdates.length; i += 1) {
const channelUpdate = channelUpdates[i]
const { advertisingNode, connectingNode } = channelUpdate
// Determine whether this update affected our node or any of our channels.
if (
info.data.identityPubkey === advertisingNode ||
info.data.identityPubkey === connectingNode ||
channels.channels.find(channel => {
return [advertisingNode, connectingNode].includes(channel.remotePubkey)
})
) {
hasUpdates = true
}
}
}
// if our node or any of our channels were involved in this update, fetch an updated channel list.
if (hasUpdates) {
// We can receive a lot of channel updates from channel graph subscription in a short space of time. If these
// involve our our channels we make a call to fetchChannels and then fetchBalances in order to refresh our channel
// and balance data. Throttle these calls so that we don't attempt to fetch channels to often.
throttledFetchChannels(dispatch)
}
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[SET_CHANNEL_VIEW_MODE]: (state, { viewMode }) => {
state.viewMode = viewMode
},
[GET_CHANNELS]: state => {
state.channelsLoading = true
},
[RECEIVE_CHANNELS]: (state, { channels, pendingChannels, closedChannels }) => {
state.channelsLoading = false
state.channels = channels
state.pendingChannels = pendingChannels
state.closedChannels = closedChannels
},
[UPDATE_SEARCH_QUERY]: (state, { searchQuery }) => {
state.searchQuery = searchQuery
},
[CHANGE_CHANNEL_FILTER]: (state, { filter }) => {
const { filter: allFilters } = state
// if `filter` action param is not set - reset to default
if (!filter) {
state.filter = new Set([...DEFAULT_FILTER])
} else if (allFilters.has(filter)) {
allFilters.delete(filter)
} else {
allFilters.add(filter)
}
},
[CHANGE_CHANNEL_SORT]: (state, { sort }) => {
state.sort = sort
},
[CHANGE_CHANNEL_SORT_ORDER]: (state, { sortOrder }) => {
state.sortOrder = sortOrder
},
[ADD_LOADING_PUBKEY]: (state, { data }) => {
state.loadingChannels.unshift(data)
},
[REMOVE_LOADING_PUBKEY]: (state, { pubkey }) => {
state.loadingChannels = state.loadingChannels.filter(data => data.nodePubkey !== pubkey)
},
[ADD_CLOSING_CHAN_ID]: (state, { chanId }) => {
state.closingChannelIds.unshift(chanId)
},
[REMOVE_CLOSING_CHAN_ID]: (state, { chanId }) => {
state.closingChannelIds = state.closingChannelIds.filter(
closingChanId => closingChanId !== chanId
)
},
[SET_SELECTED_CHANNEL]: (state, { selectedChannelId }) => {
state.selectedChannelId = selectedChannelId
},
[GET_SUGGESTED_NODES]: state => {
state.suggestedNodesLoading = true
state.suggestedNodesError = null
},
[RECEIVE_SUGGESTED_NODES]: (state, { suggestedNodes }) => {
state.suggestedNodesLoading = false
state.suggestedNodesError = null
state.suggestedNodes = suggestedNodes
},
[RECEIVE_SUGGESTED_NODES_ERROR]: (state, { error }) => {
state.suggestedNodesLoading = false
state.suggestedNodesError = error
state.suggestedNodes = {
mainnet: [],
testnet: [],
}
},
}
export default createReducer(initialState, ACTION_HANDLERS)
|
var appRoute = new Route('data-page');
/*!
*
* Interaction Process
* Version: 1.0.4
* Original author: TN devs
* Support && crowsource: @tndevs
* Extend: View Pattern
*
*/
$(function(){
var index = 0;
/* Configuration Process */
/*--------------------------------*/
var now = new Date()
,local = new Local()
,social = new Social()
,auth = new Auth()
,konami = new KonamiCode()
,commentApp = new CommentApp()
,geolocation = new GeolocationApp()
,header = new HeaderApp()
,sticky = new StickyDOM()
,scroll = new ScrollDOM()
,poll = new PollDOM()
,ref = new Ref()
,nav = new Nav()
,everScripts = new EverScripts()
,all = {
tn:'tn',
tp:'tp',
tnm:'tnm',
tnf:'tnf',
tnl:'tnl',
cl:'clima'
};
/*--------------------------------*/
/* Conditional Process */
appRoute.action(appRoute.get(), function(pos){
/*****************************************************/
appRoute.condition('ever',function(){
/*****************************************************/
EverScripts();
Helpers._wizard(everScripts,[ 'eplanning', 'login', 'newsletter', 'lostPassword', 'menuStatic' ]);
header.process();
social.publish();
Nav();
nav.swipe();
if ( $('html').hasClass('touch') ){
$('.shares').on('touchstart', function(){
$(this).find('.share').fadeToggle();
});
}
new TN.app().syncscript('facebook-jssdk',true,'//connect.facebook.net/es_LA/all.js',function(){
auth.tracking('pop-action-auth');
});
geolocation.getCurrentLocation('/services/geolocalization.json',function(o){
if(o == 'Buenos Aires') $("#traffic-item").show().css('visibility','visible');
geolocation.getWeather(o);
});
Helpers._wizard(geolocation,[ 'changeAction' ]);
$.Smartbox('open');
$("#weather-pop, .other-location").open('ajax',{
url: config.ajax + 'weather-pop' + '.html'
},function(){
geolocation.changeLocation(function(){
geolocation.autocomplete();
});
});
});
/*****************************************************/
appRoute.condition({ tnylg: 'user-tnylg' },function(){
/*****************************************************/
Helpers.storage._lastConnection(now);
$(".bubble-info").tipTip({ maxWidth: "auto", edgeOffset: 10 });
local.ranking('ranking-populares');
sticky.note();
scroll.home();
Helpers.home.sidebar(true,120);
});
/*****************************************************/
appRoute.condition({ tn:'tn', tp:'tp' },function(){
/*****************************************************/
MamScripts();
});
/*****************************************************/
appRoute.condition({ tn:'tn' }, function(){
/*****************************************************/
if($('#scrollbar-big-header').length == 1){
Helpers.twitter.scroll(true);
$(window).on('resize', function(){Helpers.twitter.scroll()});
}
Helpers.videos.scroll(true);
$(window).on('resize', function(){Helpers.videos.scroll()});
if(store.get('ciudades')){
geolocation.weatherpage();
}else{
$("#weather-search").click(function(){
geolocation.changeLocation(function(){
geolocation.weatherpage();
});
});
}
$('.weather .weather-now').click(function(){
if(window.innerWidth <= 768){
window.location.href = 'http://www.tn.com.ar/clima'
}
});
});
/*****************************************************/
appRoute.condition({ extraview:'extraview-tn' }, function(){
/*****************************************************/
sticky.customeview("#last-news","#menu-sections","#footer");
Helpers.home.sidebar(true,120);
});
/*****************************************************/
appRoute.condition({ extraview:'video-tn' }, function(){
/*****************************************************/
sticky.customeview(".wrapper-sticky","#menu-sections","#footer");
Helpers.home.sidebar(true,120);
});
/*****************************************************/
appRoute.condition(all,function(){
/*****************************************************/
if(TN.UA.desktop){
Helpers.home.stickyHeightEvilFixed();
}
sticky.home();
if ($('#last-news').length == 1){
Helpers.home.sidebar(true);
$(window).on('resize', function(){
setTimeout(Helpers.home.sidebar, 100);
});
}
if ($('#poll-big-header').length == 1) {
$('#poll-big-header').poll_widget({animation:'none'});
}
scroll.home();
poll.home();
new Local().ranking('ranking-ml');
new Local().ranking('ranking-populares');
});
/*****************************************************/
appRoute.when('billboard-tn',{
/*****************************************************/
/*-----------------------*/
onRoute: function(){
/*-----------------------*/
sticky.customeview("#last-news","#menu-sections","#footer");
Helpers.home.sidebar(true,120);
setTimeout(function(){
commentApp.pagination(commentApp.total());
new CommentApp([
'reply',
'report',
'keyboard',
'pagination',
'arrows'
]);
commentApp.disconnectTest();
},50);
},
/*-----------------------*/
onComplete: function(){
/*-----------------------*/
$(".home-flow, .wrapper-sticky").css('height','auto');
}
});
/*****************************************************/
appRoute.when('news-tn',{
/*****************************************************/
/*-----------------------*/
onRoute: function(){
/*-----------------------*/
poll.note();
everScripts.flyout();
Helpers.storage._lastConnection(now);
//Helpers.rules.sidebarDOM();
Reactions();
local.socialcore();
Gajax();
setTimeout(function(){
commentApp.pagination(commentApp.total());
new CommentApp([
'reply',
'report',
'keyboard',
'pagination',
'arrows'
]);
commentApp.disconnectTest();
},50);
},
/*-----------------------*/
onComplete: function(e){
/*-----------------------*/
setTimeout(function(){
sticky.note();
scroll.note();
Helpers.home.sidebar(true,120);
},4000);
},
/*-----------------------*/
onError: function(e){
/*-----------------------*/
}
});
/*****************************************************/
appRoute.when('news-tn-complete',{
/*****************************************************/
onRoute: function(){
setTimeout(function(){
new CommentApp([
'reply',
'report',
'keyboard'
]);
commentApp.disconnectTest();
},50);
}
});
});
});
|
// generated by Neptune Namespaces v4.x.x
// file: Art/Engine/Elements/Widgets/namespace.js
module.exports = require('../namespace').addNamespace(
'Widgets',
class Widgets extends Neptune.PackageNamespace {}
);
|
version https://git-lfs.github.com/spec/v1
oid sha256:ac96bdb00d96d899156d8e178e441f587ecf6638ba7ef9ed9bf169390a35bee9
size 2974
|
version https://git-lfs.github.com/spec/v1
oid sha256:8e8bf5b450bbc30977448594bc1eb35d681c5ff63000c623b1ecdf019e015518
size 528
|
/**
* HandsontableManualRowResize
*
* Has 2 UI components:
* - handle - the draggable element that sets the desired height of the row
* - guide - the helper guide that shows the desired height as a horizontal guide
*
* Warning! Whenever you make a change in this file, make an analogous change in manualRowResize.js
* @constructor
*/
(function (Handsontable) {
function HandsontableManualRowResize () {
var currentTH
, currentRow
, currentHeight
, instance
, newSize
, startY
, startHeight
, startOffset
, handle = document.createElement('DIV')
, guide = document.createElement('DIV')
, eventManager = Handsontable.eventManager(this);
handle.className = 'manualRowResizer';
guide.className = 'manualRowResizerGuide';
var saveManualRowHeights = function () {
var instance = this;
Handsontable.hooks.run(instance, 'persistentStateSave', 'manualRowHeights', instance.manualRowHeights);
};
var loadManualRowHeights = function () {
var instance = this
, storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualRowHeights', storedState);
return storedState.value;
};
function setupHandlePosition(TH) {
instance = this;
currentTH = TH;
var row = this.view.wt.wtTable.getCoords(TH).row; //getCoords returns WalkontableCellCoords
if (row >= 0) { //if not col header
currentRow = row;
var box = currentTH.getBoundingClientRect();
startOffset = box.top - 6;
startHeight = parseInt(box.height, 10);
handle.style.left = box.left + 'px';
handle.style.top = startOffset + startHeight + 'px';
instance.rootElement.appendChild(handle);
}
}
function refreshHandlePosition() {
handle.style.top = startOffset + currentHeight + 'px';
}
function setupGuidePosition() {
var instance = this;
Handsontable.Dom.addClass(handle, 'active');
Handsontable.Dom.addClass(guide, 'active');
guide.style.top = handle.style.top;
guide.style.left = handle.style.left;
guide.style.width = instance.view.maximumVisibleElementWidth(0) + 'px';
instance.rootElement.appendChild(guide);
}
function refreshGuidePosition() {
guide.style.top = handle.style.top;
}
function hideHandleAndGuide() {
Handsontable.Dom.removeClass(handle, 'active');
Handsontable.Dom.removeClass(guide, 'active');
}
var checkRowHeader = function (element) {
if (element.tagName != 'BODY') {
if (element.parentNode.tagName == 'TBODY') {
return true;
} else {
element = element.parentNode;
return checkRowHeader(element);
}
}
return false;
};
var getTHFromTargetElement = function (element) {
if (element.tagName != 'TABLE') {
if (element.tagName == 'TH') {
return element;
} else {
return getTHFromTargetElement(element.parentNode);
}
}
return null;
};
var bindEvents = function () {
var instance = this;
var pressed;
var dblclick = 0;
var autoresizeTimeout = null;
eventManager.addEventListener(instance.rootElement,'mouseover', function (e){
if(checkRowHeader(e.target)) {
var th = getTHFromTargetElement(e.target)
if (th) {
if (!pressed) {
setupHandlePosition.call(instance, th);
}
}
}
});
eventManager.addEventListener(instance.rootElement,'mousedown', function (e) {
if (Handsontable.Dom.hasClass(e.target, 'manualRowResizer')) {
setupGuidePosition.call(instance);
pressed = instance;
if (autoresizeTimeout == null) {
autoresizeTimeout = setTimeout(function () {
if (dblclick >= 2) {
setManualSize(currentRow, null); //double click sets auto row size
instance.forceFullRender = true;
instance.view.render(); //updates all
Handsontable.hooks.run(instance, 'afterRowResize', currentRow, newSize);
}
dblclick = 0;
autoresizeTimeout = null;
}, 500);
instance._registerTimeout(autoresizeTimeout);
}
dblclick++;
startY = Handsontable.helper.pageY(e);
newSize = startHeight;
}
});
eventManager.addEventListener(window,'mousemove',function (e) {
if (pressed) {
currentHeight = startHeight + (Handsontable.helper.pageY(e) - startY);
newSize = setManualSize(currentRow, currentHeight);
refreshHandlePosition();
refreshGuidePosition();
}
});
eventManager.addEventListener(window,'mouseup',function (e) {
if (pressed) {
hideHandleAndGuide();
pressed = false;
if(newSize != startHeight){
instance.forceFullRender = true;
instance.view.render(); //updates all
saveManualRowHeights.call(instance);
Handsontable.hooks.run(instance, 'afterRowResize', currentRow, newSize);
}
setupHandlePosition.call(instance, currentTH);
}
});
instance.addHook('afterDestroy', unbindEvents);
};
var unbindEvents = function(){
eventManager.clear();
};
this.beforeInit = function () {
this.manualRowHeights = [];
};
this.init = function (source) {
var instance = this;
var manualColumnHeightEnabled = !!(this.getSettings().manualRowResize);
if (manualColumnHeightEnabled) {
var initialRowHeights = this.getSettings().manualRowResize;
var loadedManualRowHeights = loadManualRowHeights.call(instance);
if (typeof loadedManualRowHeights != 'undefined') {
this.manualRowHeights = loadedManualRowHeights;
} else if (initialRowHeights instanceof Array) {
this.manualRowHeights = initialRowHeights;
} else {
this.manualRowHeights = [];
}
if (source === 'afterInit') {
bindEvents.call(this);
if (this.manualRowHeights.length > 0) {
this.forceFullRender = true;
this.render();
}
}
else {
this.forceFullRender = true;
this.render();
}
}
else {
unbindEvents.call(this);
this.manualRowHeights = [];
}
};
var setManualSize = function (row, height) {
row = Handsontable.hooks.execute(instance, 'modifyRow', row);
instance.manualRowHeights[row] = height;
return height;
};
this.modifyRowHeight = function (height, row) {
if (this.getSettings().manualRowResize) {
row = this.runHooksAndReturn('modifyRow', row);
if (this.manualRowHeights[row] !== void 0) {
return this.manualRowHeights[row];
}
}
return height;
};
}
var htManualRowResize = new HandsontableManualRowResize();
Handsontable.hooks.add('beforeInit', htManualRowResize.beforeInit);
Handsontable.hooks.add('afterInit', function () {
htManualRowResize.init.call(this, 'afterInit');
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htManualRowResize.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('modifyRowHeight', htManualRowResize.modifyRowHeight);
Handsontable.hooks.register('afterRowResize');
})(Handsontable);
|
var searchData=
[
['geodb',['GeoDB',['../classrocksdb_1_1GeoDB.html',1,'rocksdb']]],
['geodboptions',['GeoDBOptions',['../structrocksdb_1_1GeoDBOptions.html',1,'rocksdb']]],
['geoiterator',['GeoIterator',['../classrocksdb_1_1GeoIterator.html',1,'rocksdb']]],
['geoobject',['GeoObject',['../classrocksdb_1_1GeoObject.html',1,'rocksdb']]],
['geoposition',['GeoPosition',['../classrocksdb_1_1GeoPosition.html',1,'rocksdb']]],
['get',['get',['../classJson_1_1Value.html#a034eb7bf85a44fa759bdaa232788ca66',1,'Json::Value::get(ArrayIndex index, const Value &defaultValue) const'],['../classJson_1_1Value.html#a57de86629ed23246f14014fb6c44fa67',1,'Json::Value::get(const char *key, const Value &defaultValue) const'],['../classJson_1_1Value.html#aa59ed050e87e1d58d93671a38687f36c',1,'Json::Value::get(const char *begin, const char *end, const Value &defaultValue) const'],['../classJson_1_1Value.html#a7406e6af727c288bf8ab59945ece686a',1,'Json::Value::get(const JSONCPP_STRING &key, const Value &defaultValue) const']]],
['getcomment',['getComment',['../classJson_1_1Value.html#a82817229a986f0b254e31d5c83066ffe',1,'Json::Value']]],
['getformatederrormessages',['getFormatedErrorMessages',['../classJson_1_1Reader.html#a791cbc5afd1bef1631e07239dc452c79',1,'Json::Reader']]],
['getformattederrormessages',['getFormattedErrorMessages',['../classJson_1_1Reader.html#ae638a7b1f36f7ccf99ba89fa36ccf222',1,'Json::Reader']]],
['getmembernames',['getMemberNames',['../classJson_1_1Value.html#a79d7725dce6260317333e69022367ac9',1,'Json::Value']]],
['getstring',['getString',['../classJson_1_1Value.html#a2e1b7be6bde2fe23f15290d9ddbbdf8a',1,'Json::Value']]],
['getstructurederrors',['getStructuredErrors',['../classJson_1_1Reader.html#ae3d714e95bd98b27e296c607e408189b',1,'Json::Reader']]],
['good',['good',['../classJson_1_1Reader.html#a86cbb42b3e6d4a4d6416473b1a8f6ae7',1,'Json::Reader']]]
];
|
"use strict";
var schema = require('../../');
module.exports = function*() {
var self = this;
this.s = schema({
first: {
type: {
name: {
type: Date
},
}
}
});
var neutralTestCases = [
{
first: {}
},
{
first: {
name: null
}
},
{
first: {
name: undefined
}
},
{
first: {
name: ['bla']
}
},
{
first: {
name: {
a: 123
}
}
},
{
first: {
name: function() {}
}
},
{
first: {
name: 'blabla'
}
},
{
first: {
name: 2323
}
},
];
var dateTestCases = [
{
first: {
name: new Date(2014,0,2)
}
},
{
first: {
name: new Date(2014,0,2).toString()
}
},
{
first: {
name: '2014-01-02 00:00:00'
}
},
]
neutralTestCases.forEach(function(c) {
self.s.typeify(c).should.eql(c);
});
dateTestCases.forEach(function(c) {
var ret = self.s.typeify(c);
ret.first.name.getTime().should.eql(new Date(2014,0,2).getTime());
});
};
|
/// <reference path="typings/jquery.d.ts" />
/// <reference path="typings/jqueryui.d.ts" />
var Orchard;
(function (Orchard) {
(function (Azure) {
(function (MediaServices) {
(function (CloudVideoEdit) {
function hasCorsSupport() {
return 'withCredentials' in new XMLHttpRequest();
}
$(function () {
var corsSupported = hasCorsSupport();
if (corsSupported) {
CloudVideoEdit.initializeUploadDirect();
} else {
CloudVideoEdit.initializeUploadProxied();
}
var localStorage = window["localStorage"];
var isCreating = $("#tabs").data("cloudvideo-iscreating");
$("#tabs").tabs({
activate: function () {
if (localStorage && localStorage.setItem)
localStorage.setItem("selectedCloudVideoTab", $("#tabs").tabs("option", "active"));
},
active: !isCreating && localStorage && localStorage.getItem ? localStorage.getItem("selectedCloudVideoTab") : null
}).show();
});
})(MediaServices.CloudVideoEdit || (MediaServices.CloudVideoEdit = {}));
var CloudVideoEdit = MediaServices.CloudVideoEdit;
})(Azure.MediaServices || (Azure.MediaServices = {}));
var MediaServices = Azure.MediaServices;
})(Orchard.Azure || (Orchard.Azure = {}));
var Azure = Orchard.Azure;
})(Orchard || (Orchard = {}));
|
const React = require('react');
const isEmail = require('../../../utils/is-email');
const Api = require('../../../api');
const errorsFrom = function (data) {
let errors = {};
if (!isEmail(data.email)) {
errors.email = "This email address does not appear valid"
}
if (data.name.length < 3) {
errors.name = "This name is very short, it looks invalid"
}
if (data.message.length < 4) {
errors.message = "If you want to talk to use we need more than that!"
}
return errors;
};
const hasErrors = function (errors) {
return (errors) ? (Object.keys(errors).length > 0) : false;
};
const dataFrom = function (state) {
const _state = (state) ? state : {};
return {
name: _state.name || "",
email: _state.email || "",
message: _state.message || ""
};
};
const submit = function (api) {
return function (data) {
return api.post(data, api.routes.postContactFormData);
};
};
function Form() {
const api = Api();
return {
isEmail: isEmail,
errorsFrom: errorsFrom,
hasErrors: hasErrors,
dataFrom: dataFrom,
submit: submit(api)
};
}
module.exports = Form; |
module.exports = {
drink: {
model: {
name: {
type: 'string',
length: 45
},
description: {
type: 'string',
length: null
},
treatment: {
type: 'string',
length: null
}
}
},
ingredient: {
model: {
name: {
type: 'string',
length: 45
},
description: {
type: 'string',
length: 45
},
alcohol_in_it: {
type: 'float'
},
flavour: {
type: 'string',
length: 60
}
}
},
drink_has_ingredient: {
model: {
drink_id: {
type: 'int'
},
ingredient_id: {
type: 'int'
},
quantity: {
type: 'float'
},
percentage: {
type: 'float'
},
slices: {
type: 'float'
}
}
},
verifyModel: function (model, schema) {
var schemamodel = this[schema].model;
if (this.verifyKeys(Object.keys(model), Object.keys(schemamodel))) {
return this.verifyDataTypes(model, schemamodel);
}
return false;
},
verifyKeys: function (datakeys, schemakeys) {
schemakeys.forEach(function (key) {
if (datakeys.indexOf(key) === -1) {
return false;
}
});
return true;
},
verifyDataTypes: function (datamodel, schemamodel) {
var inmatch = true;
for (var prop in schemamodel) {
var datamodelvalue = datamodel[prop];
var schemamodelvalue = schemamodel[prop];
var type = schemamodelvalue.type;
switch (type) {
case 'string':
inmatch = !(typeof datamodelvalue !== 'string');
break;
case 'int':
inmatch = !(typeof datamodelvalue !== 'number' || isNaN(Number(datamodelvalue)));
break;
case 'float':
inmatch = !(typeof datamodelvalue !== 'number' || isNaN(Number(datamodelvalue)));
break;
}
if (!inmatch) {
break;
}
}
return inmatch;
}
}
|
// Initializing the smart device
var name = "Boolean Example Thing";
var description = "A smart device that is being tested.";
var app = require("./../index.js")(name, description);
function SimpleProperty(){
// Declaring a propery for the smart device
var state = false;
this.get = function(callback){
callback(state);
};
this.set = function(value, callback){
console.log("Value set to "+ value);
state = value;
callback();
};
}
var state = app.addProperty("state", "boolean", "Volume of computer", new SimpleProperty());
function displayProperty(properties, k){
properties[k].get(function(value){
console.log(" "+ k+" = "+ value);
});
}
state.get(function(val){
console.log("My Value: "+ val);
state.set(true, function(){
console.log("Value set.");
state.get(function(val){
console.log("My Value: "+ val);
});
});
});
/*
setInterval(function(){
state.get(function(val){
state.set(!val);
});
}, 2000);
*/
// Adding listeners
app.on("new peer", function(peer){
peer.getDetails(function(data){
console.log("New peer: " + data['name']);
peer.getProperties(function(properties){
if(properties["state"]){
properties["state"].set(true, function(){
console.log("Changed state on "+data['name']+" to true.");
});
}
});
peer.on("disconnect", function(){
console.log(data['name']+ " disconnected.");
});
});
});
|
(function () {
"use strict";
window.APP = window.APP || {Routers: {}, Collections: {}, Models: {}, Views: {}};
APP.Routers.GowithRouter = Backbone.Router.extend({
routes: {
"gowith/new": "create",
"gowiths/index": "index",
"gowith/:id/edit": "edit",
"gowith/:id/detail": "detail"
},
initialize: function (options) {
this.Gowiths = options.Gowiths;
// this is debug only to demonstrate how the backbone collection / models work
this.Gowiths.bind('reset', this.updateDebug, this);
this.Gowiths.bind('add', this.updateDebug, this);
this.Gowiths.bind('remove', this.updateDebug, this);
this.index();
},
updateDebug: function () {
$('#output').text(JSON.stringify(this.Gowiths.toJSON(), null, 4));
},
create: function () {
this.currentView = new APP.Views.GowithNewView({Gowiths: this.Gowiths, Gowith: new APP.Models.GowithModel()});
this.setHeader({title:"发起结伴",showRightBtn:false});
$('#dynamic_content').html(this.currentView.render().el);
},
edit: function (id) {
var gowith = this.Gowiths.get(id);
this.currentView = new APP.Views.gowithEditView({gowith: gowith});
$('#dynamic_content').html(this.currentView.render().el);
},
detail: function (id) {
this.setHeader({title:"结伴详情",showRightBtn:true});
var gowith = this.Gowiths.get(id);
this.currentView = new APP.Views.GowithDetailView({gowith: gowith});
$('#dynamic_content').html(this.currentView.render().el);
},
setHeader:function(headerset){
var hs = headerset || {title:"结伴",showRightBtn:true}
if(hs){
$(".head-title").html(hs.title);
if(hs.showRightBtn){
$(".p_nav .nav").show();
}
else{
$(".p_nav .nav").hide();
}
}
},
index: function () {
this.currentView = new APP.Views.GowithIndexView({Gowiths: this.Gowiths});
$('#dynamic_content').html(this.currentView.render().el);
this.setHeader();
}
});
}());
|
/**
* 分类下拉选择组件.
*
* @author lvshuang1201@gmail.com
*/
define(function(require, exports, module) {
var Class = require('arale.class');
var Select = Class.extend({
container: '',
loadUrl: '',
tmp_v2: '<div id="category-select" class="category-select" style="display: inline-block;">',
tmp: '<div class="category-select" style="display: inline-block;">\n\
<select class="form-control col-sm-3" data-level=1></select>\n\
<select class="form-control col-sm-3" data-level=2></select>\n\
</div>',
totalLeve: '', // 默认3级分类
currentLevel: 1, // 当前分类等级
initialize: function (options) {
if (!options.container) {
throw '请设置容器参数';
}
if (!options.level) {
throw '请设置要展示的分类等级';
}
this.container = $(options.container);
this.totalLeve = options.level;
if (options.url) {
this.loadUrl = options.url;
}
var appendHtml = this.tmp_v2;
for (var i = 1; i<= this.totalLeve; i++) {
appendHtml += '<select class="form-control col-sm-3" data-level=' + i + '></select>';
}
appendHtml += '</div>';
$(appendHtml).prependTo(this.container);
this._initEvents();
this._loadParent();
},
setOnSelect: function (callback) {
if (typeof(callback) === 'function') {
this.onSelect = callback;
}
},
setLoadChirdUrl: function(url) {
this.loadUrl = url;
},
setTemplete: function(templete) {
this.templete = templete;
},
_loadParent: function() {
var self = this;
if (!this.loadUrl) {
throw 'load url not set';
}
$.get(this.loadUrl, {}, function(response){
self._render(response, 1);
}, 'json');
},
_initEvents: function() {
var self = this;
$('#category-select').on('change', 'select', function() {
var currentLevel = $(this).data('level');
var level = currentLevel + 1;
$(this).find('option:selected').each(function() {
self._clear(level);
var parendId = $(this).val();
if (self.onSelect) {
self.onSelect(parendId, currentLevel);
}
self._loadChild(parendId, level);
});
});
},
// 预加载已选择的分类
_preload: function(preloadUrl) {
$.get(preloadUrl, function(response) {
} , 'json');
},
_loadChild: function(id, level) {
if (level > this.totalLeve) {
return ;
}
var url = this.loadUrl;
var self = this;
$.get(url, {parent_id: id}, function(response) {
self._render(response, level);
}, 'json');
},
_render: function(categorys, level) {
var html = '<option value="0">---请选择---</option>';
$.each(categorys, function(index, category) {
html += '<option value=' + category.id + '>' + category.name + '</option>';
});
$(html).appendTo('select[data-level=' + level + ']');
},
_clear: function(level) {
$('select[data-level=' + level + ']').html('');
},
});
module.exports = Select;
}); |
/*
{
artistName: "The Weeknd"
artworkUrl100: "http://is3.mzstatic.com/image/thumb/Music1/v4/a4/b8/10/a4b8104b-c210-b7e8-d89d-84a418638b83/UMG_cvrart_00602547490759_01_RGB72_1800x1800_15UMGIM36513.jpg/100x100bb-85.jpg"
collectionId: "1017804831"
collectionName: "Beauty Behind the Madness"
firstPlay: "1440864001"
lastPlay: "1441164842"
numberOfTracks: "8"
primaryGenreName: "R&B/Soul"
releaseDate: "1440709200"
totalPlays: "97"
}
*/
var svg = svg || {};
function processAlbum(response){
if(response.resultCount == 1){
var album = response.results[0];
if(album.country !== "USA"){
var url = album.collectionViewUrl;
var uniqueId = (album.collectionName + " " + album.artistName).toLowerCase().replace(/[^a-z0-9\s]/gi, '').replace(/\s+/gi,'-');
// console.log(uniqueId);
try{
localStorage.setItem(uniqueId+"-"+global.country, url);
}catch(e){
console.error("Localstorage error: " + e);
localStorage.clear();
}
if(dom.title.firstChild && dom.title.firstChild.textContent.substr(0,3) === album.collectionName.substr(0,3)){
dom.title.firstChild.href = url;
}
}
}
}
svg.setAlbumTitle = function(d){
dom.title.innerHTML = "<a target='_blank' href='"+d["trackViewUrl"]+"' title='Open in Apple Music'>"+d["collectionName"]+ " — " + d["artistName"] + "</a>";
if(!global.country || global.country === "us" || typeof(Storage) === "undefined") return;
var uniqueId = (d["collectionName"] + " " + d["artistName"]).toLowerCase().replace(/[^a-z0-9\s]/gi, '').replace(/\s+/gi,'-');
if(url = localStorage.getItem(uniqueId+"-"+global.country)){
dom.title.firstChild.href= url;
}else{
var term = encodeURIComponent(d["collectionName"]+ " " + d["artistName"]);
global.loadScript('http://itunes.apple.com/search?term='+ term +'&media=music&entity=album&limit=1&callback=processAlbum&country='+ global.country);
}
};
svg.click = function(d){
d3.event.stopPropagation();
if(svg.active.node() === this) return svg.reset();
svg.reset();
svg.setAlbumTitle(d);
//dom.title.textContent = d["collectionName"] + ' — ' + d["artistName"];
svg.active = d3.select(this).classed("active", true);
if(svg.active.attr("data-zoomed") == 0){
svg.active.attr("data-zoomed", 1);
var img = d3.select("pattern#artwork-"+svg.active.attr("data-id") + " image");
img.attr('xlink:href', d["artworkUrl100"].replace("100x100", svg.bigImageSize+"x"+svg.bigImageSize))
}
svg.active.moveToFront()
.transition()
.duration(500)
.style("stroke-width", svg.pad)
.attr("r", Math.floor(Math.min(svg.w, svg.h)/2) - svg.pad*2)
.attr("cy", Math.floor(svg.h/2))
.attr("cx", Math.floor(svg.w/2));
ga('send', 'event', 'Track', 'Zoom');
};
svg.filter = function(d){
d3.event.stopPropagation();
if(svg.genre.node() === this) return svg.clearFilters();
svg.genre.classed("active", false);
svg.genre = d3.select(this).classed("active", true);
svg.curGenre = svg.genre.attr("data-id");
svg.setGenreTitle(svg.curGenre);
for (var i = 0; i < svg.dataByGenre.length; i++) {
if(svg.dataByGenre[i].key === svg.curGenre){
svg.data =svg.dataByGenre[i].values;
break;
}
};
history.pushState({}, '', "#" +svg.genreShortName(svg.curGenre));
svg.drawD3();
ga('send', 'event', 'Interface', 'Filter');
};
svg.clearFilters = function(){
if(svg.genre.empty()) return;
svg.genre.classed("active", false);
svg.genre = d3.select(null);
svg.data = topAlbums;
svg.setGenreTitle();
svg.curGenre = null;
history.pushState({}, '', "#");
svg.drawD3();
}
svg.reset = function(){
if(svg.active.empty()) return;
svg.active.transition()
.duration(500)
.attr("cx", function (d) { return svg.x(+d[svg.xKey]); })
.attr("cy", function (d) { return svg.y(+d[svg.yKey]); })
.style("stroke-width", Math.floor(svg.radius/10))
.attr("r", function (d) { return svg.r(+d[svg.rKey]); });
svg.active.classed("active", false);
svg.active = d3.select(null);
svg.setGenreTitle(svg.curGenre);
};
svg.hover = function(d){
if(svg.active.node() === this) return;
d3.select(this).moveToFront()
.transition()
.duration(500)
.style("stroke-width", Math.floor(svg.radius/10))
.attr("cx", svg.x(+d[svg.xKey]))
.attr("cy", svg.y(+d[svg.yKey]))
.attr("r", svg.radius);
};
svg.hoverOut = function(d){
if(svg.active.node() === this) return;
var cur = d3.select(this);
cur.transition()
.duration(250)
.style("stroke-width", Math.floor(svg.radius/10))
.attr("cx", svg.x(+d[svg.xKey]))
.attr("cy", svg.y(+d[svg.yKey]))
.attr("r", svg.r(+d[svg.rKey]));
setTimeout(function(){cur.moveToBack();}, 251);
};
svg.genreShortName = function(str){
return str.toLowerCase().replace(/[^a-z]/g,'');
};
svg.setGenreTitle = function(str){
if(str){
var titles = dom.title.getAttribute("data-text").split("100 ");
dom.title.textContent = titles[0] + " " + str + " " +titles[1];
}else{
dom.title.textContent = dom.title.getAttribute("data-text");
}
};
svg.drawD3 = function(){
//console.log("Drawing up D3");
// console.log(svg.data);
svg.pad = dom.links[0].offsetLeft
svg.w = dom.graph.offsetWidth - (svg.pad*2);
svg.h = dom.graph.offsetHeight - dom.footer.offsetHeight - dom.title.offsetHeight;
svg.bigImageSize = global.getImageWidth(Math.min(svg.w, svg.h) - svg.pad*2);
//console.log(svg.bigImageSize);
svg.radius = Math.max(Math.min(Math.min(svg.w, svg.h)/10, 50), 25);
//console.log(svg.radius);
svg.xDomain = d3.extent(svg.data, function(d) { return +d[svg.xKey]; });
svg.yDomain = d3.extent(svg.data, function(d) { return +d[svg.yKey]; });
svg.rDomain = d3.extent(svg.data, function(d) { return +d[svg.rKey]; });
svg.x = d3.scale.linear().domain(svg.xDomain).range([svg.radius+svg.pad*2, svg.w-svg.radius]),
svg.y = d3.scale.linear().domain(svg.yDomain).range([ svg.h-svg.radius-svg.pad*2,svg.radius]),
svg.xA = d3.scale.linear().domain([0,100]).range([0, svg.w]),
svg.yA = d3.scale.linear().domain([0,100]).range([svg.h, 0 ]),
svg.r = d3.scale.linear().domain(svg.rDomain).range([ svg.radius/3,svg.radius]);
svg.tDomain = d3.extent(svg.data, function(d) { return +d[svg.tKey]; });
svg.t = d3.scale.linear().domain(svg.tDomain).range([ 500, 0]);
svg.xAxis.scale(svg.xA);
svg.yAxis.scale(svg.yA);
svg.canvas.attr("width", svg.w).attr("height", svg.h);
svg.xAxisGroup.attr("transform", "translate(5, "+(svg.h -5)+")").call(svg.xAxis);
svg.yAxisGroup.call(svg.yAxis);
svg.legend.attr("transform", function(d, i) { return "translate(0," + i * svg.pad*1.5 + ")"; });
svg.legend.selectAll("text").attr("x", svg.w - svg.pad*1.5).attr("y",svg.pad/2);
svg.legend.selectAll("circle").attr("cx", svg.w - svg.pad/2).attr("cy", svg.pad/2).attr("r", svg.pad/2);
svg.radiusLegend.attr("transform", function(d, i) { return "translate(0," + (((svg.cDomain.domain().length+0.5) * svg.pad*1.5) + (svg.pad*3)) + ")"; });
svg.radiusLegend.selectAll("text").attr("x", svg.w - svg.pad*3.5);
svg.radiusLegend.selectAll("circle").attr("cx", svg.w).attr("r", svg.pad*3);
svg.xLabel.attr("x", svg.w ).attr("y", svg.h - svg.pad*1.2);
svg.yLabel.attr("y", svg.pad);
svg.circles = svg.canvas.selectAll(".circle").data(svg.data, function(d) { return d["collectionId"]; });
var newCircles = svg.circles.enter()// new
.append("circle")
// .on("mouseover", svg.hover)
// .on("mouseout",svg.hoverOut)
// .on("click",svg.click)
.attr("class", "circle")
.style("fill", function(d) { return "url(#artwork-" + d["collectionId"] + ")";})
.style("stroke", function(d) { return svg.color(svg.cValue(d));})
.attr("data-id",function(d) { return d["collectionId"];})
.attr("data-album",function(d) { return d["collectionName"];})
.attr("data-artist",function(d) { return d["artistName"];})
.attr("data-link",function(d) { return d["trackViewUrl"];})
.attr("data-zoomed",0)
.style("stroke-width", Math.floor(svg.radius/10))
.attr("cx", function (d) { return svg.x(+d[svg.xKey]); })
.attr("cy", function (d) { return svg.y(+d[svg.yKey]); })
.attr("r", 5)
.style("fill-opacity", 1e-6)
.style("stroke-opacity", 1e-6)
;
newCircles.on("mouseover", svg.hover);
newCircles.on("mouseout",svg.hoverOut);
newCircles.on("click",svg.click);
newCircles.append("svg:title")
.text(function(d) { return d["collectionName"] + ' — ' + d["artistName"]; });
svg.circles.transition()// update
.duration(500)
.delay(function (d) { return svg.t(+d[svg.tKey]); })
.attr("cx", function (d) { return svg.x(+d[svg.xKey]); })
.attr("cy", function (d) { return svg.y(+d[svg.yKey]); })
.attr("r", function (d) { return svg.r(+d[svg.rKey]); })
.style("stroke-width", Math.floor(svg.radius/10))
.style("fill-opacity", 1)
.style("stroke-opacity", 1);
svg.circles.exit() // old
.transition()
.duration(500)
.delay(function (d) { return svg.t(+d[svg.tKey]); })
.attr("r", 5)
.style("fill-opacity", 1e-6)
.style("stroke-opacity", 1e-6)
.remove();
};
////////////////////////////////////////////////////////////////////////////////////
svg.setupD3 = function(container){
d3.selection.prototype.moveToFront = function() {
//console.log("front");
return this.each(function(){
this.parentNode.appendChild(this);
});
};
d3.selection.prototype.moveToBack = function() {
// console.log("back");
return this.each(function() {
var firstChild = this.parentNode.firstChild;
if (firstChild) {
this.parentNode.insertBefore(this, firstChild);
}
});
};
// console.log("Setting up D3");
svg.yKey = "totalPlays";
svg.xKey = "firstPlay";
svg.rKey = "numberOfTracks";
svg.cKey = "primaryGenreName";
svg.tKey = "lastPlay";
svg.data = topAlbums || [];
svg.dataByGenre = d3.nest()
.key(function(d) { return d[svg.cKey]; })
.entries(svg.data);
svg.cDomain = d3.scale.ordinal()
.domain(svg.data.map( function (d) { return d[svg.cKey]; }));
// setup fill color
svg.cValue = function(d) { return d[svg.cKey];},
svg.color = d3.scale.category20().domain(svg.cDomain.domain());
svg.canvas = d3.select("#graph").append("svg");
svg.canvas.on("click",svg.reset);
svg.xAxisGroup = svg.canvas.append("g")
.attr("class", "axis");
svg.yAxisGroup = svg.canvas.append("g")
.attr("class", "axis")
.attr("transform", "translate(5, -5)");
svg.xAxis = d3.svg.axis().orient("bottom").tickFormat(function (d) { return ''; });
svg.yAxis = d3.svg.axis().orient("left").tickFormat(function (d) { return ''; });
svg.canvas.append("defs").selectAll("pattern").data(svg.data)
.enter()
.append('pattern')
.attr('id', function(d) { return "artwork-"+d["collectionId"];})
.attr('x', 0)
.attr('y', 0)
.attr('width', "100%")
.attr('height', "100%")
.attr('viewBox', "0 0 100 100")
.append('image')
.attr('xlink:href', function(d) { return d["artworkUrl100"];})
.attr('x', 0)
.attr('y', 0)
.attr('width', 100)
.attr('height', 100);
svg.legend = svg.canvas.selectAll(".legend")
.data(svg.color.domain())
.enter().append("g")
.attr("class", function(d) {
if(window.location.hash.length < 2) return "legend";
return (svg.genreShortName(d) === window.location.hash.substring(1))?"legend active":"legend";
})
.attr("data-id", function(d) { return d;});
svg.legend.on("click",svg.filter);
// draw legend colored rectangles
svg.legend.append("circle")
.style("fill", svg.color);
// draw legend text
svg.legend.append("text")
.attr("dy", "0.35em")
.style("text-anchor", "end")
.text(function(d) { return d;});
svg.legend.append("svg:title")
.text(function(d) { return "Filter by " + d + " genre" });
svg.radiusLegend = svg.canvas.append("g")
.attr("class", "radius-legend");
svg.radiusLegend.append("text")
.attr("dy", "0.35em")
.style("text-anchor", "end")
.text("no. of tracks in an album");
svg.radiusLegend.append("circle")
.style("fill-opacity", 0)
.attr("y",0)
.attr("stroke", "#888");
svg.radiusLegend.append("svg:title")
.text("Radius of circles corelates to a number of popular songs in a particular album");
svg.xLabel = svg.canvas.append("g")
.attr("class", "label")
.append("text")
.attr("dy", ".35em")
.style("text-anchor", "end")
.text("release date");
svg.yLabel = svg.canvas.append("g")
.attr("class", "label")
.append("text")
.attr("transform", "rotate(-90)")
.attr("dy", ".35em")
.attr("x", 0)
.style("text-anchor", "end")
.text("amount of plays");
svg.active = d3.select(null);
svg.genre = d3.select(".legend.active");
if(window.location.hash.length > 2){
var hash = window.location.hash.substring(1);
for (var i = 0; i < svg.dataByGenre.length; i++) {
if(svg.genreShortName(svg.dataByGenre[i].key) === hash){
svg.data = svg.dataByGenre[i].values;
var titles = dom.title.getAttribute("data-text").split("100 ");
dom.title.textContent = titles[0] + "100 " + svg.dataByGenre[i].key + " " +titles[1];
break;
}
};
}
svg.drawD3();
window.addEventListener("resize", svg.drawD3);
}; |
/// <reference path="../require.d.ts" />
define(["require", "exports"], function (require, exports) {
var Common = (function () {
function Common(message) {
this.greeting = message;
}
Common.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Common;
}());
return Common;
});
//# sourceMappingURL=main.js.map |
'use strict';
exports.__esModule = true;
exports['default'] = combineReducers;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _createStore = require('../createStore');
var _utilsIsPlainObject = require('../utils/isPlainObject');
var _utilsIsPlainObject2 = _interopRequireDefault(_utilsIsPlainObject);
var _utilsMapValues = require('../utils/mapValues');
var _utilsMapValues2 = _interopRequireDefault(_utilsMapValues);
var _utilsPick = require('../utils/pick');
var _utilsPick2 = _interopRequireDefault(_utilsPick);
/* eslint-disable no-console */
function getUndefinedStateErrorMessage(key, action) {
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Reducer "' + key + '" returned undefined handling ' + actionName + '. ' + 'To ignore an action, you must explicitly return the previous state.';
}
function getUnexpectedStateKeyWarningMessage(inputState, outputState, action) {
var reducerKeys = Object.keys(outputState);
var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!_utilsIsPlainObject2['default'](inputState)) {
return 'The ' + argumentName + ' has unexpected type of "' + ({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return reducerKeys.indexOf(key) < 0;
});
if (unexpectedKeys.length > 0) {
return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
}
}
function assertReducerSanity(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var finalReducers = _utilsPick2['default'](reducers, function (val) {
return typeof val === 'function';
});
var sanityError;
try {
assertReducerSanity(finalReducers);
} catch (e) {
sanityError = e;
}
var defaultState = _utilsMapValues2['default'](finalReducers, function () {
return undefined;
});
return function combination(state, action) {
if (state === undefined) state = defaultState;
if (sanityError) {
throw sanityError;
}
var finalState = _utilsMapValues2['default'](finalReducers, function (reducer, key) {
var newState = reducer(state[key], action);
if (typeof newState === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action);
throw new Error(errorMessage);
}
return newState;
});
if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateKeyWarningMessage(state, finalState, action);
if (warningMessage) {
console.error(warningMessage);
}
}
return finalState;
};
}
module.exports = exports['default']; |
/* ************************************************************************
Copyright: Hericus Software, LLC
License: The MIT License (MIT)
Authors: Steven M. Cherry
************************************************************************ */
qx.Class.define("admin.OldLayoutEngine", {
type : "static",
statics : {
/** This function makes it easy to create your widget layout by describing
* the contents of your layout using an XML document. This allows you to
* be more compact in your layout description, while still taking full advantage
* of the qooxdoo widget system.
*
* @param theThis {Object} This is the object that we will attach any variables to.
* @param layoutDoc {Object} This is an XML string that we will parse to read your layout.
* @param parent {Object} This is the widget parent that the new layout will be added to.
*/
renderLayout : function ( theThis, layoutDoc, parent ) {
var xmlDoc = null;
var elem = null;
if(typeof(layoutDoc) === "string" || layoutDoc instanceof String){
xmlDoc = admin.Statics.xmlStringToDoc( layoutDoc );
} else {
xmlDoc = layoutDoc;
}
if(xmlDoc === null){
theThis.error( "Invalid XML Document passed to renderLayout" );
return null;
}
elem = xmlDoc.documentElement;
// Start at the root and work our way down
if(elem.nodeName === "parsererror"){
theThis.error("Invalid XML Document passed to renderLayout" );
theThis.error( admin.Statics.xmlDocToString( xmlDoc ) );
return null;
}
var obj = admin.LayoutEngine.createElementAndChildren( theThis, elem, parent );
if((parent) && (obj) && (parent !== obj)){
var flex = admin.LayoutEngine.getFlexAttr(elem);
if(flex){
parent.add(obj, {flex: flex});
} else {
parent.add(obj);
}
}
return obj;
},
/** This method combines the loadxml call with the call to renderLayout
* as a convienence.
*/
loadRenderLayout : function ( theThis, docURL, parent, callback ){
admin.Api.LoadXMLDoc( docURL,
function(response){
var obj = admin.LayoutEngine.renderLayout( theThis, response, parent);
callback.call(theThis, response.ownerDocument, obj);
}, theThis );
},
/** This method will create the object that represents the current node and
* then recursively call ourselves for all child nodes found.
*/
createElementAndChildren : function (theThis, elem, parent) {
if(elem.nodeName === "VerticalBoxLayout"){
return admin.LayoutEngine.createVBox( theThis, elem, parent );
} else if(elem.nodeName === "HorizontalBoxLayout"){
return admin.LayoutEngine.createHBox( theThis, elem, parent );
} else if(elem.nodeName === "VerticalSplitPane") {
return admin.LayoutEngine.createVerticalSplitPane( theThis, elem, parent );
} else if(elem.nodeName === "GroupBox") {
return admin.LayoutEngine.createGroupBox( theThis, elem, parent );
} else if(elem.nodeName === "Tree" ) {
return admin.LayoutEngine.createTree( theThis, elem, parent );
} else if(elem.nodeName === "TreeVirtual" ) {
return admin.LayoutEngine.createTreeVirtual( theThis, elem, parent );
} else if(elem.nodeName === "RecursiveCheckBoxTree" ) {
return admin.LayoutEngine.createRecursiveCheckBoxTree( theThis, elem, parent );
} else if(elem.nodeName === "HorizontalSplitPane") {
return admin.LayoutEngine.createHorizontalSplitPane( theThis, elem, parent );
} else if(elem.nodeName === "TextArea") {
return admin.LayoutEngine.createTextArea( theThis, elem, parent );
} else if(elem.nodeName === "HtmlEmbed") {
return admin.LayoutEngine.createHtmlEmbed( theThis, elem, parent );
} else if(elem.nodeName === "IFrame") {
return admin.LayoutEngine.createIFrame( theThis, elem, parent );
} else if(elem.nodeName === "StandardTable") {
return admin.LayoutEngine.createStandardTable( theThis, elem, parent );
} else if(elem.nodeName === "StandardTreeVirtual") {
return admin.LayoutEngine.createStandardTreeVirtual( theThis, elem, parent );
} else if(elem.nodeName === "FieldArea") {
return admin.LayoutEngine.createFieldArea( theThis, elem, parent );
} else if(elem.nodeName === "Label") {
return admin.LayoutEngine.createLabel( theThis, elem, parent );
} else if(elem.nodeName === "Spacer") {
return admin.LayoutEngine.createSpacer( theThis, elem, parent );
} else if(elem.nodeName === "List") {
return admin.LayoutEngine.createList( theThis, elem, parent );
} else if(elem.nodeName === "Button") {
return admin.LayoutEngine.createButton( theThis, elem, parent );
} else if(elem.nodeName === "LayoutEngine") {
admin.LayoutEngine.processChildren( theThis, elem, parent);
return null;
} else {
return null;
}
},
createVBox : function ( theThis, elem, parent ) {
var obj = new qx.ui.container.Composite(new qx.ui.layout.VBox);
admin.LayoutEngine.processAttributes( theThis, elem, obj );
admin.LayoutEngine.processChildren( theThis, elem, obj );
return obj;
},
createHBox : function ( theThis, elem, parent ) {
var obj = new qx.ui.container.Composite(new qx.ui.layout.HBox);
admin.LayoutEngine.processAttributes( theThis, elem, obj );
admin.LayoutEngine.processChildren( theThis, elem, obj );
return obj;
},
createGroupBox : function ( theThis, elem, parent ) {
if(elem.getAttribute( "isCheck") && elem.getAttribute("isCheck") === "true"){
var obj = new qx.ui.groupbox.CheckGroupBox();
} else if(elem.getAttribute( "isRadio") && elem.getAttribute("isRadio") === "true"){
var obj = new qx.ui.groupbox.RadioGroupBox();
} else {
var obj = new qx.ui.groupbox.GroupBox();
}
obj.setLayout(new qx.ui.layout.VBox);
admin.LayoutEngine.processAttributes( theThis, elem, obj );
admin.LayoutEngine.processChildren( theThis, elem, obj );
return obj;
},
createLabel : function ( theThis, elem, parent ) {
var obj = new qx.ui.basic.Label;
admin.Statics.trackExtraObj( theThis, obj);
admin.LayoutEngine.processAttributes( theThis, elem, obj );
return obj;
},
createSpacer : function ( theThis, elem, parent ) {
var obj = new qx.ui.core.Spacer;
admin.LayoutEngine.processAttributes( theThis, elem, obj );
return obj;
},
createList : function ( theThis, elem, parent ) {
var obj = new qx.ui.form.List;
admin.LayoutEngine.processAttributes( theThis, elem, obj );
return obj;
},
createButton : function ( theThis, elem, parent ) {
var obj = new qx.ui.form.Button();
admin.LayoutEngine.processAttributes( theThis, elem, obj );
return obj;
},
createSplitPane : function ( theThis, elem, parent, orientation ) {
var flex1 = Number( elem.getAttribute( "leftsize") );
var flex2 = Number( elem.getAttribute("rightsize") );
var obj = new qx.ui.splitpane.Pane(orientation);
// The standard splitpane has a decorator that adds a border around
// the whole widget. We don't want that, so use the Background decorator
// instead to get a 0 border.
obj.set({decorator : new qx.ui.decoration.Decorator});
// remove leftsize and rightsize before processing attrs:
elem.removeAttribute("leftsize");
elem.removeAttribute("rightsize");
admin.LayoutEngine.processAttributes( theThis, elem, obj );
// A split-pane has only 2 children. Process them by hand:
if(orientation === "vertical"){
var firstHalf = admin.Statics.xmlFindChild(elem, "VerticalSplitPaneTop" );
} else {
var firstHalf = admin.Statics.xmlFindChild(elem, "HorizontalSplitPaneLeft");
}
// find the first real child of VerticalSplitPaneTop
for(var i = 0, l = firstHalf.childNodes.length; i < l; i++){
var node = firstHalf.childNodes[i];
var child = admin.LayoutEngine.createElementAndChildren( theThis, node, obj );
if(child){
obj.add(child, flex1);
break;
}
}
if(orientation === "vertical"){
var secondHalf = admin.Statics.xmlFindChild(elem, "VerticalSplitPaneBottom" );
} else {
var secondHalf = admin.Statics.xmlFindChild(elem, "HorizontalSplitPaneRight" );
}
// find the first real child of VerticalSplitPaneBottom
for(var i = 0, l = secondHalf.childNodes.length; i < l; i++){
var node = secondHalf.childNodes[i];
var child = admin.LayoutEngine.createElementAndChildren( theThis, node, obj );
if(child){
obj.add(child, flex2);
break;
}
}
return obj;
},
createVerticalSplitPane : function ( theThis, elem, parent ) {
return admin.LayoutEngine.createSplitPane( theThis, elem, parent, "vertical" );
},
createHorizontalSplitPane : function ( theThis, elem, parent ) {
return admin.LayoutEngine.createSplitPane( theThis, elem, parent, "horizontal" );
},
createTreeVirtual : function ( theThis, elem, parent ) {
// first pull out the column list:
var columns = elem.getElementsByTagName( "Column" );
var titles = [];
for(var i = 0, l = columns.length; i < l; i++){
titles.push( columns[i].getAttribute("title") );
}
var obj = admin.Statics.createStandardTreeVirtual( titles );
admin.LayoutEngine.processAttributes( theThis, elem, obj );
// Adjust column sizes if given:
var sizing = obj.getTableColumnModel().getBehavior();
for(var i = 0, l = columns.length; i < l; i++){
var hash = {};
if(columns[i].getAttribute("width")){
hash.width = columns[i].getAttribute("width");
}
if(columns[i].getAttribute("minWidth")){
hash.minWidth = Number(columns[i].getAttribute("minWidth"));
}
if(columns[i].getAttribute("maxWidth")){
hash.maxWidth = Number(columns[i].getAttribute("maxWidth"));
}
sizing.set( i, hash );
}
// A tree has no children.
return obj;
},
createTree : function ( theThis, elem, parent ) {
var obj = new qx.ui.tree.Tree();
admin.LayoutEngine.processAttributes( theThis, elem, obj );
// A tree has no children.
return obj;
},
createRecursiveCheckBoxTree : function ( theThis, elem, parent ) {
// first pull out the column list:
// A tree has no children.
return null;
},
createTextArea : function ( theThis, elem, parent ) {
var obj = new qx.ui.form.TextArea;
obj.setNativeContextMenu( true );
admin.LayoutEngine.processAttributes( theThis, elem, obj );
// a text area has no children.
return obj;
},
createHtmlEmbed : function ( theThis, elem, parent ){
var obj = new qx.ui.embed.Html;
admin.LayoutEngine.processAttributes( theThis, elem, obj );
obj.setOverflow("auto", "auto");
// an html embed has no children.
return obj;
},
createIFrame : function ( theThis, elem, parent ){
var obj = new qx.ui.embed.Iframe().set({decorator: null});
admin.LayoutEngine.processAttributes( theThis, elem, obj );
// an iframe embed has no children.
return obj;
},
createStandardTable : function ( theThis, elem, parent ) {
// first pull out the column list:
var columns = elem.getElementsByTagName( "Column" );
var titles = [];
for(var i = 0, l = columns.length; i < l; i++){
titles.push( columns[i].getAttribute("title") );
}
var filtered = "false";
if(elem.getAttribute( "filtered" )){
filtered = elem.getAttribute("filtered");
}
var obj = admin.Statics.createStandardTable( titles, filtered );
admin.LayoutEngine.processAttributes( theThis, elem, obj );
// Adjust column sizes if given:
var sizing = obj.getTableColumnModel().getBehavior();
for(var i = 0, l = columns.length; i < l; i++){
var hash = {};
if(columns[i].getAttribute("width")){
hash.width = columns[i].getAttribute("width");
}
if(columns[i].getAttribute("minWidth")){
hash.minWidth = Number(columns[i].getAttribute("minWidth"));
}
if(columns[i].getAttribute("maxWidth")){
hash.maxWidth = Number(columns[i].getAttribute("maxWidth"));
}
sizing.set( i, hash );
}
// A table has no children.
return obj;
},
createStandardTreeVirtual: function ( theThis, elem, parent ) {
// first pull out the column list:
var columns = elem.getElementsByTagName( "Column" );
var titles = [];
for(var i = 0, l = columns.length; i < l; i++){
titles.push( columns[i].getAttribute("title") );
}
var obj = admin.Statics.createStandardTreeVirtual( titles );
admin.LayoutEngine.processAttributes( theThis, elem, obj );
// Adjust column sizes if given:
var sizing = obj.getTableColumnModel().getBehavior();
for(var i = 0, l = columns.length; i < l; i++){
var hash = {};
if(columns[i].getAttribute("width")){
hash.width = columns[i].getAttribute("width");
}
if(columns[i].getAttribute("minWidth")){
hash.minWidth = Number(columns[i].getAttribute("minWidth"));
}
if(columns[i].getAttribute("maxWidth")){
hash.maxWidth = Number(columns[i].getAttribute("maxWidth"));
}
sizing.set( i, hash );
}
// A table has no children.
return obj;
},
addToolTip : function (theThis, node, tipAttr, varAttr) {
var tipText = node.getAttribute(tipAttr);
if(tipText){
var obj = theThis[ node.getAttribute(varAttr) ];
if(tipText.indexOf("<br") != -1 ||
tipText.indexOf("<p>") != -1
){
// Tip contains some html markup. Use a rich tip.
var tip = new qx.ui.tooltip.ToolTip(tipText);
tip.setRich(true);
obj.setToolTip( tip );
} else {
// Tip is simple text:
obj.setToolTipText( tipText );
}
}
},
setReadOnly : function (theThis, node, roAttr, varAttr) {
var roText = node.getAttribute(roAttr);
if(roText){
var obj = theThis[ node.getAttribute(varAttr) ];
obj.setReadOnly( roText == "true" ? true : false );
}
},
checkFieldVerification : function(theThis, node) {
var verify1 = node.getAttribute("verify1");
if(verify1 && verify1 === "true"){
if(theThis.fieldVerificationList === undefined){
theThis.fieldVerificationList = [];
}
theThis.fieldVerificationList.push( {
varName: node.getAttribute("varName1"),
label: node.getAttribute("label1"),
type: node.getAttribute("verify1type"),
min: node.getAttribute("verify1min"),
max: node.getAttribute("verify1max"),
upper: node.getAttribute("upper1"),
required: node.getAttribute("required1")
} );
}
var verify2 = node.getAttribute("verify2");
if(verify2 && verify2 === "true"){
if(theThis.fieldVerificationList === undefined){
theThis.fieldVerificationList = [];
}
theThis.fieldVerificationList.push( {
varName: node.getAttribute("varName2"),
label: node.getAttribute("label2"),
type: node.getAttribute("verify2type"),
min: node.getAttribute("verify2min"),
max: node.getAttribute("verify2max"),
upper: node.getAttribute("upper2"),
required: node.getAttribute("required2")
} );
}
var verify3 = node.getAttribute("verify3");
if(verify3 && verify3 === "true"){
if(theThis.fieldVerificationList === undefined){
theThis.fieldVerificationList = [];
}
theThis.fieldVerificationList.push( {
varName: node.getAttribute("varName3"),
label: node.getAttribute("label3"),
type: node.getAttribute("verify3type"),
min: node.getAttribute("verify3min"),
max: node.getAttribute("verify3max"),
upper: node.getAttribute("upper3"),
required: node.getAttribute("required3")
} );
}
var verify4 = node.getAttribute("verify4");
if(verify4 && verify4 === "true"){
if(theThis.fieldVerificationList === undefined){
theThis.fieldVerificationList = [];
}
theThis.fieldVerificationList.push( {
varName: node.getAttribute("varName4"),
label: node.getAttribute("label4"),
type: node.getAttribute("verify4type"),
min: node.getAttribute("verify4min"),
max: node.getAttribute("verify4max"),
upper: node.getAttribute("upper4"),
required: node.getAttribute("required4")
} );
}
},
createFieldArea : function ( theThis, elem, parent ) {
//var cols = Number( elem.getAttribute("columns") );
var first = Number( elem.getAttribute("first") );
var second = Number( elem.getAttribute("second") );
// Get the list of children:
for(var i = 0, l = elem.childNodes.length; i < l; i ++){
var node = elem.childNodes[i];
if (node.nodeName === "QuadField") {
admin.Statics.addFieldsToForm(theThis, parent,
node.getAttribute("label1"), first,
node.getAttribute("varName1"),
node.getAttribute("type1"),
node.getAttribute("label2"), second,
node.getAttribute("varName2"),
node.getAttribute("type2"),
node.getAttribute("label3"), first,
node.getAttribute("varName3"),
node.getAttribute("type3"),
node.getAttribute("label4"), second,
node.getAttribute("varName4"),
node.getAttribute("type4"));
// Check for tooltips:
admin.LayoutEngine.addToolTip(theThis, node, "tooltip1", "varName1");
admin.LayoutEngine.addToolTip(theThis, node, "tooltip2", "varName2");
admin.LayoutEngine.addToolTip(theThis, node, "tooltip3", "varName3");
admin.LayoutEngine.addToolTip(theThis, node, "tooltip4", "varName4");
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly3", "varName3");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly4", "varName4");
// Check for field verification
admin.LayoutEngine.checkFieldVerification(theThis, node);
} else if (node.nodeName === "TripleField") {
admin.Statics.addFieldsToForm(theThis, parent,
node.getAttribute("label1"), first,
node.getAttribute("varName1"),
node.getAttribute("type1"),
node.getAttribute("label2"), second,
node.getAttribute("varName2"),
node.getAttribute("type2"),
node.getAttribute("label3"), first,
node.getAttribute("varName3"),
node.getAttribute("type3"));
// Check for tooltips:
admin.LayoutEngine.addToolTip(theThis, node, "tooltip1", "varName1");
admin.LayoutEngine.addToolTip(theThis, node, "tooltip2", "varName2");
admin.LayoutEngine.addToolTip(theThis, node, "tooltip3", "varName3");
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly3", "varName3");
// Check for field verification
admin.LayoutEngine.checkFieldVerification(theThis, node);
} else if (node.nodeName === "DoubleField") {
admin.Statics.addFieldsToForm(theThis, parent,
node.getAttribute("label1"), first,
node.getAttribute("varName1"),
node.getAttribute("type1"),
node.getAttribute("label2"), second,
node.getAttribute("varName2"),
node.getAttribute("type2") );
// Check for tooltips:
admin.LayoutEngine.addToolTip(theThis, node, "tooltip1", "varName1");
admin.LayoutEngine.addToolTip(theThis, node, "tooltip2", "varName2");
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
// Check for field verification
admin.LayoutEngine.checkFieldVerification(theThis, node);
} else if(node.nodeName === "SpanField"){
admin.Statics.addFieldsToForm(theThis, parent,
node.getAttribute("label1"), first,
node.getAttribute("varName1"),
node.getAttribute("type1") );
// Check for tooltips:
admin.LayoutEngine.addToolTip(theThis, node, "tooltip1", "varName1");
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
if(node.getAttribute("type1") === "TextArea" && node.getAttribute("height1")){
theThis[node.getAttribute("varName1")].setMaxHeight(
Number( node.getAttribute("height1") )
);
theThis[node.getAttribute("varName1")].setHeight(
Number( node.getAttribute("height1") )
);
}
// Check for field verification
admin.LayoutEngine.checkFieldVerification(theThis, node);
} else if(node.nodeName === "DoubleCheck"){
admin.Statics.addCheckboxes(theThis, parent, first,
node.getAttribute("varName1"),
node.getAttribute("label1"),
node.getAttribute("varName2"),
node.getAttribute("label2") );
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
} else if(node.nodeName === "DoubleCheck2"){
admin.Statics.addCheckboxes2(theThis, parent, first,
Number( node.getAttribute("width1")),
Number( node.getAttribute("width2")),
0,
0,
node.getAttribute("varName1"),
node.getAttribute("label1"),
node.getAttribute("varName2"),
node.getAttribute("label2") );
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
} else if(node.nodeName === "QuadCheck"){
admin.Statics.addCheckboxes2(theThis, parent, first,
Number( node.getAttribute("width1")),
Number( node.getAttribute("width2")),
Number( node.getAttribute("width3")),
Number( node.getAttribute("width4")),
node.getAttribute("varName1"),
node.getAttribute("label1"),
node.getAttribute("varName2"),
node.getAttribute("label2"),
node.getAttribute("varName3"),
node.getAttribute("label3"),
node.getAttribute("varName4"),
node.getAttribute("label4")
);
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly3", "varName3");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly4", "varName4");
} else if(node.nodeName === "SingleCheck"){
admin.Statics.addCheckboxes(theThis, parent, first,
node.getAttribute("varName1"),
node.getAttribute("label1") );
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
} else if(node.nodeName === "RadioGroup2"){
var rg = admin.Statics.addRadioGroupVertical(theThis, parent, first,
node.getAttribute("varName1"),
node.getAttribute("label1") ,
node.getAttribute("varName2"),
node.getAttribute("label2")
);
theThis[ node.getAttribute("groupName") ] = rg;
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
} else if(node.nodeName === "RadioGroup3"){
var rg = admin.Statics.addRadioGroupVertical(theThis, parent, first,
node.getAttribute("varName1"),
node.getAttribute("label1") ,
node.getAttribute("varName2"),
node.getAttribute("label2"),
node.getAttribute("varName3"),
node.getAttribute("label3")
);
theThis[ node.getAttribute("groupName") ] = rg;
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly3", "varName3");
} else if(node.nodeName === "RadioGroup4"){
var rg = admin.Statics.addRadioGroupVertical(theThis, parent, first,
node.getAttribute("varName1"),
node.getAttribute("label1") ,
node.getAttribute("varName2"),
node.getAttribute("label2"),
node.getAttribute("varName3"),
node.getAttribute("label3") ,
node.getAttribute("varName4"),
node.getAttribute("label4")
);
theThis[ node.getAttribute("groupName") ] = rg;
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly3", "varName3");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly4", "varName4");
} else if(node.nodeName === "RadioGroup5"){
var rg = admin.Statics.addRadioGroupHorizontal(theThis, parent, first,
null, // groupName is not used
node.getAttribute("labelPrefix"),
node.getAttribute("varName1"), node.getAttribute("label1") ,
node.getAttribute("varName2"), node.getAttribute("label2"),
node.getAttribute("varName3"), node.getAttribute("label3") ,
node.getAttribute("varName4"), node.getAttribute("label4")
);
theThis[ node.getAttribute("groupName") ] = rg;
// Set read only state:
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly1", "varName1");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly2", "varName2");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly3", "varName3");
admin.LayoutEngine.setReadOnly(theThis, node, "readOnly4", "varName4");
} else if(node.nodeName === "LongLabel"){
admin.Statics.addLongLabel(parent,
node.getAttribute("label"),
node.getAttribute("varName"),
theThis);
} else if(node.nodeName === "LongLabelRich"){
admin.Statics.addLongLabelRich(parent,
node.getAttribute("label"),
node.getAttribute("varName"),
theThis);
}
}
// A field area creates multiple children. return null
return null;
},
processAttributes : function ( theThis, elem, obj ){
var attrMap = elem.attributes;
if(attrMap === null){
return;
}
for(var i = 0, l = attrMap.length; i < l; i++){
var node = attrMap.item( i );
var name = node.nodeName;
var val = node.nodeValue;
if(name === "varName"){
theThis[ val ] = obj;
admin.Statics.trackNamedAttr( theThis, val );
} else if(name === "label" ){
obj.setLabel( val );
} else if(name === "legend" ){
obj.setLegend( val );
} else if(name === "icon" ){
obj.setIcon( val );
} else if(name === "text" ){
obj.setValue( val );
} else if(name === "flex" ){
// skip this attribute.
} else if(name === "isCheck" ){
// skip this attribute.
} else if(name === "isRadio" ){
// skip this attribute.
} else if(name === "alignY" ){
obj._getLayout().setAlignY( val );
} else if(name === "alignX" ){
obj._getLayout().setAlignX( val );
} else if(name === "spacing" ){
obj._getLayout().setSpacing( Number(val) );
} else if(name === "separator" ){
// skip this attribute.
} else if(name === "reversed" ){
if(val === "true"){
obj._getLayout().setReversed( true );
} else {
obj._getLayout().setReversed( false );
}
} else if(name === "minWidth" ){
obj.setMinWidth( Number(val) );
} else if(name === "width" ){
obj.setWidth( Number(val) );
} else if(name === "maxWidth" ){
obj.setMaxWidth( Number(val) );
} else if(name === "minHeight" ){
obj.setMinHeight( Number(val) );
} else if(name === "height" ){
obj.setHeight( Number(val) );
} else if(name === "maxHeight" ){
obj.setMaxHeight( Number(val) );
} else if(name === "allowGrowX" ){
if(val === "true"){
obj.setAllowGrowX( true );
} else {
obj.setAllowGrowY( false );
}
} else if(name === "allowShrinkX" ){
if(val === "true"){
obj.setAllowShrinkX( true );
} else {
obj.setAllowShrinkX( false );
}
} else if(name === "allowGrowY" ){
if(val === "true"){
obj.setAllowGrowY( true );
} else {
obj.setAllowGrowY( false );
}
} else if(name === "allowShrinkY" ){
if(val === "true"){
obj.setAllowShrinkY( true );
} else {
obj.setAllowShrinkY( false );
}
} else if(name === "allowStretchX" ){
if(val === "true"){
obj.setAllowStretchX( true );
} else {
obj.setAllowStretchX( false );
}
} else if(name === "allowStretchY" ){
if(val === "true"){
obj.setAllowStretchY( true );
} else {
obj.setAllowStretchY( false );
}
} else if(name === "nativeContextMenu" ){
if(val === "true"){
obj.setNativeContextMenu( true );
} else {
obj.setNativeContextMenu( false );
}
} else if(name === "marginTop" ){
obj.setMarginTop( Number(val) );
} else if(name === "marginRight" ){
obj.setMarginRight( Number(val) );
} else if(name === "marginBottom" ){
obj.setMarginBottom( Number(val) );
} else if(name === "marginLeft" ){
obj.setMarginLeft( Number(val) );
} else if(name === "margin" ){
obj.setMargin( Number(val) );
} else if(name === "paddingTop" ){
obj.setPaddingTop( Number(val) );
} else if(name === "paddingRight" ){
obj.setPaddingRight( Number(val) );
} else if(name === "paddingBottom" ){
obj.setPaddingBottom( Number(val) );
} else if(name === "paddingLeft" ){
obj.setPaddingLeft( Number(val) );
} else if(name === "padding" ){
obj.setPadding( Number(val) );
} else if(name === "appearance" ){
obj.setAppearance( val );
} else if(name === "overflow" ){
obj.set({overflow:val});
} else if(name === "wrap" ){
if(val === "true"){
obj.setWrap( true );
} else {
obj.setWrap( false );
}
} else if(name === "readOnly" ){
if(val === "true"){
obj.setReadOnly( true );
} else {
obj.setReadOnly( false );
}
} else if(name === "filename" ){
// Ignore this one.
} else if(name === "filtered" ){
// Ignore this one.
} else {
theThis.error("Unknown attribute (" + name + ") in layout element (" + elem.nodeName + ")" );
}
}
},
getFlexAttr : function (elem){
var attrMap = elem.attributes;
if(attrMap === null){
return null;
}
for(var i = 0, l = attrMap.length; i < l; i++){
var node = attrMap.item( i );
var name = node.nodeName;
var val = node.nodeValue;
if(name === "flex"){
return Number(val);
}
}
// didn't find it.
return null;
},
processChildren : function ( theThis, elem, obj ){
for(var i = 0, l = elem.childNodes.length; i < l; i++){
var node = elem.childNodes[i];
var child = admin.LayoutEngine.createElementAndChildren( theThis, node, obj );
if(child){
var flex_num = admin.LayoutEngine.getFlexAttr(node);
if(flex_num){
obj.add(child, {flex: flex_num});
} else {
obj.add(child);
}
}
}
}
}
});
|
var Todo = require('./models/todo');
var Users = require('./models/users');
function getTodos(res){
Todo.find(function(err, todos) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(todos); // return all todos in JSON format
});
};
module.exports = function(app) {
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// api ---------------------------------------------------------------------
// get all todos
app.get('/api/todos', function(req, res) {
// use mongoose to get all todos in the database
getTodos(res);
});
app.get('/api/users', function(req, res) {
// use mongoose to get all todos in the database
res.json(Users());
});
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
getTodos(res);
});
});
// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
Todo.remove({
_id : req.params.todo_id
}, function(err, todo) {
if (err)
res.send(err);
getTodos(res);
});
});
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
}; |
export { default as Home } from './home';
export { default as Post } from './post';
export { default as Search } from './search';
export { default as About } from './about';
export { default as Author } from './author';
export { default as PostComment } from './postComment';
export { default as Setting } from './setting';
export { default as Offline } from './offline';
export { default as OfflinePost } from './offlinePost';
export { default as Login } from './login';
export { default as Startup } from './startup';
export { default as Blink } from './blink';
export { default as Question } from './question';
export { default as CommentAdd } from './commentAdd';
export { default as BlinkAdd } from './blinkAdd';
export { default as QuestionAdd } from './questionAdd';
export { default as User } from './user';
export { default as Favorite } from './favorite';
export { default as UserAsset } from './userAsset';
export { default as SearchDetail } from './searchDetail';
export { default as Feedback } from './feedback';
export { default as Update } from './update';
export { default as TailSetting } from './tailSetting';
export { default as Web } from './web';
export { default as QuestionAnswerComment } from './questionAnswerComment'; |
import React from 'react';
import './index.css';
/* Icon masks from https://github.com/markhuge/svg-social-icons */
const socialIcons = {
email: {
href: 'mailto:wenger.jacob@gmail.com',
mask:
'M41.1,25H22.9l9.1,7.1L41.1,25z M44,26.6l-12,9.3l-12-9.3V39h24V26.6z M0,0v64h64V0H0z M47,42H17V22h30V42z',
ariaLabel: 'Send Jacob an email',
},
github: {
href: 'https://github.com/jwngr',
mask:
'M0,0v64h64V0H0z M37.1,47.2c-0.8,0.2-1.1-0.3-1.1-0.8c0-0.5,0-2.3,0-4.4c0-1.5-0.5-2.5-1.1-3 c3.6-0.4,7.3-1.7,7.3-7.9c0-1.7-0.6-3.2-1.6-4.3c0.2-0.4,0.7-2-0.2-4.2c0,0-1.3-0.4-4.4,1.6c-1.3-0.4-2.6-0.5-4-0.5 c-1.4,0-2.7,0.2-4,0.5c-3.1-2.1-4.4-1.6-4.4-1.6c-0.9,2.2-0.3,3.8-0.2,4.2c-1,1.1-1.6,2.5-1.6,4.3c0,6.1,3.7,7.5,7.3,7.9 c-0.5,0.4-0.9,1.1-1,2.1c-0.9,0.4-3.2,1.1-4.7-1.3c0,0-0.8-1.5-2.5-1.6c0,0-1.6,0-0.1,1c0,0,1,0.5,1.8,2.3c0,0,0.9,3.1,5.4,2.1 c0,1.3,0,2.3,0,2.7c0,0.4-0.3,0.9-1.1,0.8C20.6,45.1,16,39.1,16,32c0-8.8,7.2-16,16-16c8.8,0,16,7.2,16,16 C48,39.1,43.4,45.1,37.1,47.2z',
ariaLabel: `View Jacob's GitHub profile`,
},
linkedin: {
href: 'https://www.linkedin.com/in/jwngr/',
mask:
'M0,0v64h64V0H0z M25.8,44h-5.4V26.6h5.4V44z M23.1,24.3c-1.7,0-3.1-1.4-3.1-3.1c0-1.7,1.4-3.1,3.1-3.1 c1.7,0,3.1,1.4,3.1,3.1C26.2,22.9,24.8,24.3,23.1,24.3z M46,44h-5.4v-8.4c0-2,0-4.6-2.8-4.6c-2.8,0-3.2,2.2-3.2,4.5V44h-5.4V26.6 h5.2V29h0.1c0.7-1.4,2.5-2.8,5.1-2.8c5.5,0,6.5,3.6,6.5,8.3V44z',
ariaLabel: `View Jacob's LinkedIn profile`,
},
twitter: {
href: 'https://twitter.com/_jwngr',
mask:
'M0,0v64h64V0H0z M44.7,25.5c0,0.3,0,0.6,0,0.8C44.7,35,38.1,45,26.1,45c-3.7,0-7.2-1.1-10.1-2.9 c0.5,0.1,1,0.1,1.6,0.1c3.1,0,5.9-1,8.2-2.8c-2.9-0.1-5.3-2-6.1-4.6c0.4,0.1,0.8,0.1,1.2,0.1c0.6,0,1.2-0.1,1.7-0.2 c-3-0.6-5.3-3.3-5.3-6.4c0,0,0-0.1,0-0.1c0.9,0.5,1.9,0.8,3,0.8c-1.8-1.2-2.9-3.2-2.9-5.5c0-1.2,0.3-2.3,0.9-3.3 c3.2,4,8.1,6.6,13.5,6.9c-0.1-0.5-0.2-1-0.2-1.5c0-3.6,2.9-6.6,6.6-6.6c1.9,0,3.6,0.8,4.8,2.1c1.5-0.3,2.9-0.8,4.2-1.6 c-0.5,1.5-1.5,2.8-2.9,3.6c1.3-0.2,2.6-0.5,3.8-1C47.1,23.4,46,24.5,44.7,25.5z',
ariaLabel: `View Jacob's Twitter profile`,
},
};
const SocialIcon = ({type}) => {
const {href, mask, ariaLabel} = socialIcons[type];
return (
<a className="social-icon" aria-label={ariaLabel} href={href}>
<svg viewBox="0 0 64 64">
<path d={mask} />
</svg>
</a>
);
};
const SocialIcons = () => (
<div className="social-icons">
<SocialIcon type="email" />
<SocialIcon type="github" />
<SocialIcon type="twitter" />
<SocialIcon type="linkedin" />
</div>
);
export default SocialIcons;
|
'use strict';
var _ = require('lodash');
var dictionaries = require('../dictionaries');
var tokenizers = require('../tokenizers');
var candidateMatchers = _.reduce(dictionaries.candidates, function(matchers, name) {
var n = name.split(' ');
matchers[name] = new RegExp([ n[0], '? (?=', n[1], ')' ].join(''), 'ig');
return matchers;
}, {});
module.exports = function callouts(lines) {
var matches;
return _.reduce(lines, function(callouts, line) {
_.each(tokenizers.sentence(line), function(sentence) {
_.each(candidateMatchers, function(matcher, name) {
if(matcher.test(sentence)) {
if(!callouts[name]) callouts[name] = [];
callouts[name].push(sentence);
}
});
});
return callouts;
}, {});
}; |
import './HomePage.less';
import React, { PropTypes } from 'react';
class HomePage {
static propTypes = {
};
render() {
return (
<div>
<h1>Home page component</h1>
<p>This component is used to test the routing</p>
</div>
);
}
}
export default HomePage;
|
/**
* Created by Standard on 9/28/2014.
*/
var test = (function(){
function superFunc() {
}
return {
fim: superFunc
}
})(); |
var ASSERT = require("assert");
var GEOM = require("geoscript/geom");
var PROJ = require("geoscript/proj");
var WKT = require("geoscript/io/wkt");
exports["test: constructor"] = function() {
var checkPoint = function(pt, x, y) {
ASSERT.ok(pt instanceof GEOM.Point, "point is a point");
ASSERT.strictEqual(pt.x, x, "point x is " + x);
ASSERT.strictEqual(pt.y, y, "point y is " + y);
};
var cc = new GEOM.CompoundCurve([
new GEOM.CircularString([[10.0, 10.0], [0.0, 20.0], [-10.0, 10.0]]),
new GEOM.LineString([[-10.0, 10.0], [-10.0, 0.0], [10.0, 0.0], [5.0, 5.0]])
]);
ASSERT.ok(cc instanceof GEOM.Geometry, "cc is a geometry");
ASSERT.ok(cc instanceof GEOM.CompoundCurve, "cc is a compoundcurve");
ASSERT.strictEqual(cc.components.length, 2, "cc has two components");
ASSERT.ok(cc.components[0] instanceof GEOM.CircularString, "cc component 1 is a circularstring");
ASSERT.ok(cc.components[1] instanceof GEOM.LineString, "cc component 2 is a linestring");
var cs = cc.components[0];
checkPoint(cs.controlPoints[0], 10.0, 10.0);
checkPoint(cs.controlPoints[1], 0.0, 20.0);
checkPoint(cs.controlPoints[2], -10.0, 10.0);
var ls = cc.components[1];
ASSERT.strictEqual(ls.coordinates.length, 4, "line has four coordinates");
ASSERT.deepEqual([[-10.0, 10.0], [-10.0, 0.0], [10.0, 0.0], [5.0, 5.0]], ls.coordinates, "line coordinates match");
ASSERT.ok(cc.linear instanceof GEOM.LineString,"cc linear is a linestring");
ASSERT.strictEqual("COMPOUNDCURVE (CIRCULARSTRING (10.0 10.0, 0.0 20.0, -10.0 10.0), (-10.0 10.0, -10.0 0.0, 10.0 0.0, 5.0 5.0))", cc.curvedWkt, "cs curved wkt");
var ccFromWkt = WKT.read("COMPOUNDCURVE (CIRCULARSTRING (10.0 10.0, 0.0 20.0, -10.0 10.0), (-10.0 10.0, -10.0 0.0, 10.0 0.0, 5.0 5.0))");
ASSERT.deepEqual(cc, ccFromWkt);
cc = new GEOM.CompoundCurve({
geometries: [
new GEOM.CircularString([[10.0, 10.0], [0.0, 20.0], [-10.0, 10.0]]),
new GEOM.LineString([[-10.0, 10.0], [-10.0, 0.0], [10.0, 0.0], [5.0, 5.0]])
],
tolerance: 25
});
ASSERT.ok(cc instanceof GEOM.Geometry, "cc is a geometry");
ASSERT.ok(cc instanceof GEOM.CompoundCurve, "cc is a compoundcurve");
ASSERT.strictEqual(cc.components.length, 2, "cc has two components");
ASSERT.ok(cc.components[0] instanceof GEOM.CircularString, "cc component 1 is a circularstring");
ASSERT.ok(cc.components[1] instanceof GEOM.LineString, "cc component 2 is a linestring");
var cs = cc.components[0];
checkPoint(cs.controlPoints[0], 10.0, 10.0);
checkPoint(cs.controlPoints[1], 0.0, 20.0);
checkPoint(cs.controlPoints[2], -10.0, 10.0);
var ls = cc.components[1];
ASSERT.strictEqual(ls.coordinates.length, 4, "line has four coordinates");
ASSERT.deepEqual([[-10.0, 10.0], [-10.0, 0.0], [10.0, 0.0], [5.0, 5.0]], ls.coordinates, "line coordinates match");
ASSERT.ok(cc.linear instanceof GEOM.LineString,"cc linear is a linestring");
ASSERT.strictEqual("COMPOUNDCURVE (CIRCULARSTRING (10.0 10.0, 0.0 20.0, -10.0 10.0), (-10.0 10.0, -10.0 0.0, 10.0 0.0, 5.0 5.0))", cc.curvedWkt, "cs curved wkt");
}; |
/*globals describe, before, beforeEach, afterEach, after, it */
var testUtils = require('../utils/index'),
should = require('should'),
sinon = require('sinon'),
Promise = require('bluebird'),
moment = require('moment'),
assert = require('assert'),
_ = require('lodash'),
validator = require('validator'),
// Stuff we are testing
db = require('../../server/data/db'),
versioning = require('../../server/data/schema').versioning,
exporter = require('../../server/data/export'),
importer = require('../../server/data/import'),
DataImporter = require('../../server/data/import/data-importer'),
DEF_DB_VERSION = versioning.getDefaultDatabaseVersion(),
knex = db.knex,
sandbox = sinon.sandbox.create();
// Tests in here do an import for each test
describe('Import', function () {
before(testUtils.teardown);
afterEach(testUtils.teardown);
afterEach(function () {
sandbox.restore();
});
should.exist(exporter);
should.exist(importer);
describe('Resolves', function () {
beforeEach(testUtils.setup());
it('resolves DataImporter', function (done) {
var importStub = sandbox.stub(DataImporter, 'importData', function () {
return Promise.resolve();
}),
fakeData = {test: true};
importer.doImport(fakeData).then(function () {
importStub.calledWith(fakeData).should.equal(true);
importStub.restore();
done();
}).catch(done);
});
});
describe('Sanitizes', function () {
beforeEach(testUtils.setup('roles', 'owner', 'settings'));
it('import results have data and problems', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003').then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function (importResult) {
should.exist(importResult);
should.exist(importResult.data);
should.exist(importResult.problems);
done();
}).catch(done);
});
it('removes duplicate posts', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003-duplicate-posts').then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function (importResult) {
should.exist(importResult.data.data.posts);
importResult.data.data.posts.length.should.equal(1);
importResult.problems.posts.length.should.equal(1);
done();
}).catch(done);
});
it('removes duplicate tags and updates associations', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003-duplicate-tags').then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function (importResult) {
should.exist(importResult.data.data.tags);
should.exist(importResult.data.data.posts_tags);
importResult.data.data.tags.length.should.equal(1);
// Check we imported all posts_tags associations
importResult.data.data.posts_tags.length.should.equal(2);
// Check the post_tag.tag_id was updated when we removed duplicate tag
_.all(importResult.data.data.posts_tags, function (postTag) {
return postTag.tag_id !== 2;
});
importResult.problems.tags.length.should.equal(1);
done();
}).catch(done);
});
});
describe('DataImporter', function () {
beforeEach(testUtils.setup('roles', 'owner', 'settings'));
should.exist(DataImporter);
it('imports data from 000', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-000').then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
// Grab the data from tables
return Promise.all([
knex('users').select(),
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
]);
}).then(function (importedData) {
should.exist(importedData);
importedData.length.should.equal(4, 'Did not get data successfully');
var users = importedData[0],
posts = importedData[1],
settings = importedData[2],
tags = importedData[3];
// we always have 1 user, the owner user we added
users.length.should.equal(1, 'There should only be one user');
// import no longer requires all data to be dropped, and adds posts
posts.length.should.equal(exportData.data.posts.length, 'Wrong number of posts');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
// test tags
tags.length.should.equal(exportData.data.tags.length, 'no new tags');
done();
}).catch(done);
});
it('safely imports data, from 001', function (done) {
var exportData,
timestamp = moment().startOf('day').valueOf(); // no ms
testUtils.fixtures.loadExportFixture('export-001').then(function (exported) {
exportData = exported;
// Modify timestamp data for testing
exportData.data.posts[0].created_at = timestamp;
exportData.data.posts[0].updated_at = timestamp;
exportData.data.posts[0].published_at = timestamp;
return importer.doImport(exportData);
}).then(function () {
// Grab the data from tables
return Promise.all([
knex('users').select(),
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
]);
}).then(function (importedData) {
should.exist(importedData);
importedData.length.should.equal(4, 'Did not get data successfully');
var users = importedData[0],
posts = importedData[1],
settings = importedData[2],
tags = importedData[3];
// we always have 1 user, the default user we added
users.length.should.equal(1, 'There should only be one user');
// user should still have the credentials from the original insert, not the import
users[0].email.should.equal(testUtils.DataGenerator.Content.users[0].email);
users[0].password.should.equal(testUtils.DataGenerator.Content.users[0].password);
// but the name, slug, and bio should have been overridden
users[0].name.should.equal(exportData.data.users[0].name);
users[0].slug.should.equal(exportData.data.users[0].slug);
should.not.exist(users[0].bio, 'bio is not imported');
// import no longer requires all data to be dropped, and adds posts
posts.length.should.equal(exportData.data.posts.length, 'Wrong number of posts');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
// activeTheme should NOT have been overridden
_.findWhere(settings, {key: 'activeTheme'}).value.should.equal('casper', 'Wrong theme');
// test tags
tags.length.should.equal(exportData.data.tags.length, 'no new tags');
// Ensure imported post retains set timestamp
// When in sqlite we are returned a unix timestamp number,
// in MySQL we're returned a date object.
// We pass the returned post always through the date object
// to ensure the return is consistent for all DBs.
assert.equal(moment(posts[0].created_at).valueOf(), timestamp);
assert.equal(moment(posts[0].updated_at).valueOf(), timestamp);
assert.equal(moment(posts[0].published_at).valueOf(), timestamp);
done();
}).catch(done);
});
it('doesn\'t import invalid post data from 001', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-001').then(function (exported) {
exportData = exported;
// change title to 151 characters
exportData.data.posts[0].title = new Array(152).join('a');
exportData.data.posts[0].tags = 'Tag';
return importer.doImport(exportData);
}).then(function () {
(1).should.eql(0, 'Data import should not resolve promise.');
}, function (error) {
error[0].message.should.eql('Value in [posts.title] exceeds maximum length of 150 characters.');
error[0].errorType.should.eql('ValidationError');
Promise.all([
knex('users').select(),
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
]).then(function (importedData) {
should.exist(importedData);
importedData.length.should.equal(4, 'Did not get data successfully');
var users = importedData[0],
posts = importedData[1],
settings = importedData[2],
tags = importedData[3];
// we always have 1 user, the default user we added
users.length.should.equal(1, 'There should only be one user');
// Nothing should have been imported
posts.length.should.equal(0, 'Wrong number of posts');
tags.length.should.equal(0, 'no new tags');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
done();
});
}).catch(done);
});
it('doesn\'t import invalid settings data from 001', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-001').then(function (exported) {
exportData = exported;
// change to blank settings key
exportData.data.settings[3].key = null;
return importer.doImport(exportData);
}).then(function () {
(1).should.eql(0, 'Data import should not resolve promise.');
}, function (error) {
error[0].message.should.eql('Value in [settings.key] cannot be blank.');
error[0].errorType.should.eql('ValidationError');
Promise.all([
knex('users').select(),
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
]).then(function (importedData) {
should.exist(importedData);
importedData.length.should.equal(4, 'Did not get data successfully');
var users = importedData[0],
posts = importedData[1],
settings = importedData[2],
tags = importedData[3];
// we always have 1 user, the default user we added
users.length.should.equal(1, 'There should only be one user');
// Nothing should have been imported
posts.length.should.equal(0, 'Wrong number of posts');
tags.length.should.equal(0, 'no new tags');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
done();
});
}).catch(done);
});
});
describe('002', function () {
beforeEach(testUtils.setup('roles', 'owner', 'settings'));
it('safely imports data from 002', function (done) {
var exportData,
timestamp = moment().startOf('day').valueOf(); // no ms
testUtils.fixtures.loadExportFixture('export-002').then(function (exported) {
exportData = exported;
// Modify timestamp data for testing
exportData.data.posts[0].created_at = timestamp;
exportData.data.posts[0].updated_at = timestamp;
exportData.data.posts[0].published_at = timestamp;
return importer.doImport(exportData);
}).then(function () {
// Grab the data from tables
return Promise.all([
knex('users').select(),
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
]);
}).then(function (importedData) {
should.exist(importedData);
importedData.length.should.equal(4, 'Did not get data successfully');
var users = importedData[0],
posts = importedData[1],
settings = importedData[2],
tags = importedData[3];
// we always have 1 user, the owner user we added
users.length.should.equal(1, 'There should only be one user');
// user should still have the credentials from the original insert, not the import
users[0].email.should.equal(testUtils.DataGenerator.Content.users[0].email);
users[0].password.should.equal(testUtils.DataGenerator.Content.users[0].password);
// but the name, slug, and bio should have been overridden
users[0].name.should.equal(exportData.data.users[0].name);
users[0].slug.should.equal(exportData.data.users[0].slug);
should.not.exist(users[0].bio, 'bio is not imported');
// import no longer requires all data to be dropped, and adds posts
posts.length.should.equal(exportData.data.posts.length, 'Wrong number of posts');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
// activeTheme should NOT have been overridden
_.findWhere(settings, {key: 'activeTheme'}).value.should.equal('casper', 'Wrong theme');
// test tags
tags.length.should.equal(exportData.data.tags.length, 'no new tags');
// Ensure imported post retains set timestamp
// When in sqlite we are returned a unix timestamp number,
// in MySQL we're returned a date object.
// We pass the returned post always through the date object
// to ensure the return is consistant for all DBs.
assert.equal(moment(posts[0].created_at).valueOf(), timestamp);
assert.equal(moment(posts[0].updated_at).valueOf(), timestamp);
assert.equal(moment(posts[0].published_at).valueOf(), timestamp);
done();
}).catch(done);
});
it('doesn\'t import invalid post data from 002', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-002').then(function (exported) {
exportData = exported;
// change title to 151 characters
exportData.data.posts[0].title = new Array(152).join('a');
exportData.data.posts[0].tags = 'Tag';
return importer.doImport(exportData);
}).then(function () {
(1).should.eql(0, 'Data import should not resolve promise.');
}, function (error) {
error[0].message.should.eql('Value in [posts.title] exceeds maximum length of 150 characters.');
error[0].errorType.should.eql('ValidationError');
Promise.all([
knex('users').select(),
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
]).then(function (importedData) {
should.exist(importedData);
importedData.length.should.equal(4, 'Did not get data successfully');
var users = importedData[0],
posts = importedData[1],
settings = importedData[2],
tags = importedData[3];
// we always have 1 user, the owner user we added
users.length.should.equal(1, 'There should only be one user');
// Nothing should have been imported
posts.length.should.equal(0, 'Wrong number of posts');
tags.length.should.equal(0, 'no new tags');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
done();
});
}).catch(done);
});
it('doesn\'t import invalid settings data from 002', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-002').then(function (exported) {
exportData = exported;
// change to blank settings key
exportData.data.settings[3].key = null;
return importer.doImport(exportData);
}).then(function () {
(1).should.eql(0, 'Data import should not resolve promise.');
}, function (error) {
error[0].message.should.eql('Value in [settings.key] cannot be blank.');
error[0].errorType.should.eql('ValidationError');
Promise.all([
knex('users').select(),
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
]).then(function (importedData) {
should.exist(importedData);
importedData.length.should.equal(4, 'Did not get data successfully');
var users = importedData[0],
posts = importedData[1],
settings = importedData[2],
tags = importedData[3];
// we always have 1 user, the owner user we added
users.length.should.equal(1, 'There should only be one user');
// Nothing should have been imported
posts.length.should.equal(0, 'Wrong number of posts');
tags.length.should.equal(0, 'no new tags');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
done();
});
}).catch(done);
});
});
describe('003', function () {
beforeEach(testUtils.setup('roles', 'owner', 'settings'));
it('safely imports data from 003 (single user)', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003').then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
// Grab the data from tables
return Promise.all([
knex('users').select(),
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
]);
}).then(function (importedData) {
should.exist(importedData);
importedData.length.should.equal(4, 'Did not get data successfully');
var users = importedData[0],
posts = importedData[1],
settings = importedData[2],
tags = importedData[3];
// user should still have the credentials from the original insert, not the import
users[0].email.should.equal(testUtils.DataGenerator.Content.users[0].email);
users[0].password.should.equal(testUtils.DataGenerator.Content.users[0].password);
// but the name, slug, and bio should have been overridden
users[0].name.should.equal(exportData.data.users[0].name);
users[0].slug.should.equal(exportData.data.users[0].slug);
should.not.exist(users[0].bio, 'bio is not imported');
// test posts
posts.length.should.equal(1, 'Wrong number of posts');
// test tags
tags.length.should.equal(1, 'no new tags');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
done();
}).catch(done);
});
it('handles validation errors nicely', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003-badValidation').then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
done(new Error('Allowed import of duplicate data'));
}).catch(function (response) {
response.length.should.equal(5);
response[0].errorType.should.equal('ValidationError');
response[0].message.should.eql('Value in [posts.title] cannot be blank.');
response[1].errorType.should.equal('ValidationError');
response[1].message.should.eql('Value in [posts.slug] cannot be blank.');
response[2].errorType.should.equal('ValidationError');
response[2].message.should.eql('Value in [settings.key] cannot be blank.');
response[3].errorType.should.equal('ValidationError');
response[3].message.should.eql('Value in [tags.slug] cannot be blank.');
response[4].errorType.should.equal('ValidationError');
response[4].message.should.eql('Value in [tags.name] cannot be blank.');
done();
}).catch(done);
});
it('handles database errors nicely', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003-dbErrors').then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
done(new Error('Allowed import of duplicate data'));
}).catch(function (response) {
response.length.should.be.above(0);
response[0].errorType.should.equal('DataImportError');
done();
}).catch(done);
});
it('doesn\'t import posts with an invalid author', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003-mu-unknownAuthor').then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
done(new Error('Allowed import of unknown author'));
}).catch(function (response) {
response.length.should.equal(1);
response[0].message.should.eql('Attempting to import data linked to unknown user id 2');
response[0].errorType.should.equal('DataImportError');
done();
}).catch(done);
});
it('doesn\'t import invalid tags data from 003', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003-nullTags').then(function (exported) {
exportData = exported;
exportData.data.tags.length.should.be.above(1);
exportData.data.posts_tags.length.should.be.above(1);
return importer.doImport(exportData);
}).then(function () {
done(new Error('Allowed import of invalid tags data'));
}).catch(function (response) {
response.length.should.equal(2);
response[0].errorType.should.equal('ValidationError');
response[0].message.should.eql('Value in [tags.name] cannot be blank.');
response[1].errorType.should.equal('ValidationError');
response[1].message.should.eql('Value in [tags.slug] cannot be blank.');
done();
}).catch(done);
});
it('doesn\'t import invalid posts data from 003', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003-nullPosts').then(function (exported) {
exportData = exported;
exportData.data.posts.length.should.be.above(1);
return importer.doImport(exportData);
}).then(function () {
done(new Error('Allowed import of invalid tags data'));
}).catch(function (response) {
response.length.should.equal(5, response);
done();
}).catch(done);
});
it('correctly sanitizes incorrect UUIDs', function (done) {
var exportData;
testUtils.fixtures.loadExportFixture('export-003-wrongUUID').then(function (exported) {
exportData = exported;
exportData.data.posts.length.should.be.above(0);
return importer.doImport(exportData);
}).then(function () {
// Grab the data from tables
return knex('posts').select();
}).then(function (importedData) {
should.exist(importedData);
assert.equal(validator.isUUID(importedData[0].uuid), true, 'Old Ghost UUID NOT fixed');
assert.equal(validator.isUUID(importedData[1].uuid), true, 'Empty UUID NOT fixed');
assert.equal(validator.isUUID(importedData[2].uuid), true, 'Missing UUID NOT fixed');
assert.equal(validator.isUUID(importedData[3].uuid), true, 'Malformed UUID NOT fixed');
done();
}).catch(done);
});
});
});
// Tests in here do an import-per-describe, and then have several tests to check various bits of data
describe('Import (new test structure)', function () {
before(testUtils.teardown);
describe('imports multi user data onto blank ghost install', function () {
var exportData;
before(function doImport(done) {
testUtils.initFixtures('roles', 'owner', 'settings').then(function () {
return testUtils.fixtures.loadExportFixture('export-003-mu');
}).then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
done();
}).catch(done);
});
after(testUtils.teardown);
it('gets the right data', function (done) {
var fetchImported = Promise.join(
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
);
fetchImported.then(function (importedData) {
var posts,
settings,
tags,
post1,
post2,
post3;
// General data checks
should.exist(importedData);
importedData.length.should.equal(3, 'Did not get data successfully');
// Test posts, settings and tags
posts = importedData[0];
settings = importedData[1];
tags = importedData[2];
post1 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[0].slug;
});
post2 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[1].slug;
});
post3 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[2].slug;
});
// test posts
posts.length.should.equal(3, 'Wrong number of posts');
post1.title.should.equal(exportData.data.posts[0].title);
post2.title.should.equal(exportData.data.posts[1].title);
post3.title.should.equal(exportData.data.posts[2].title);
// test tags
tags.length.should.equal(3, 'should be 3 tags');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
done();
}).catch(done);
});
it('imports users with correct roles and status', function (done) {
var fetchImported = Promise.join(
knex('users').select(),
knex('roles_users').select()
);
fetchImported.then(function (importedData) {
var user1,
user2,
user3,
users,
rolesUsers;
// General data checks
should.exist(importedData);
importedData.length.should.equal(2, 'Did not get data successfully');
// Test the users and roles
users = importedData[0];
rolesUsers = importedData[1];
// we imported 3 users
// the original user should be untouched
// the two news users should have been created
users.length.should.equal(3, 'There should only be three users');
// the owner user is first
user1 = users[0];
// the other two users should have the imported data, but they get inserted in different orders
user2 = _.find(users, function (user) {
return user.name === exportData.data.users[1].name;
});
user3 = _.find(users, function (user) {
return user.name === exportData.data.users[2].name;
});
user1.email.should.equal(testUtils.DataGenerator.Content.users[0].email);
user1.password.should.equal(testUtils.DataGenerator.Content.users[0].password);
user1.status.should.equal('active');
user2.email.should.equal(exportData.data.users[1].email);
user3.email.should.equal(exportData.data.users[2].email);
// Newly created users should have a status of locked
user2.status.should.equal('locked');
user3.status.should.equal('locked');
// Newly created users should have created_at/_by and updated_at/_by set to when they were imported
user2.created_by.should.equal(user1.id);
user2.created_at.should.not.equal(exportData.data.users[1].created_at);
user2.updated_by.should.equal(user1.id);
user2.updated_at.should.not.equal(exportData.data.users[1].updated_at);
user3.created_by.should.equal(user1.id);
user3.created_at.should.not.equal(exportData.data.users[2].created_at);
user3.updated_by.should.equal(user1.id);
user3.updated_at.should.not.equal(exportData.data.users[2].updated_at);
rolesUsers.length.should.equal(3, 'There should be 3 role relations');
_.each(rolesUsers, function (roleUser) {
if (roleUser.user_id === user1.id) {
roleUser.role_id.should.equal(4, 'Original user should be an owner');
}
if (roleUser.user_id === user2.id) {
roleUser.role_id.should.equal(1, 'Josephine should be an admin');
}
if (roleUser.user_id === user3.id) {
roleUser.role_id.should.equal(3, 'Smith should be an author by default');
}
});
done();
}).catch(done);
});
it('imports posts & tags with correct authors, owners etc', function (done) {
var fetchImported = Promise.join(
knex('users').select(),
knex('posts').select(),
knex('tags').select()
);
fetchImported.then(function (importedData) {
var users, user1, user2, user3,
posts, post1, post2, post3,
tags, tag1, tag2, tag3;
// General data checks
should.exist(importedData);
importedData.length.should.equal(3, 'Did not get data successfully');
// Test the users and roles
users = importedData[0];
posts = importedData[1];
tags = importedData[2];
// Grab the users
// the owner user is first
user1 = users[0];
// the other two users should have the imported data, but they get inserted in different orders
user2 = _.find(users, function (user) {
return user.name === exportData.data.users[1].name;
});
user3 = _.find(users, function (user) {
return user.name === exportData.data.users[2].name;
});
post1 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[0].slug;
});
post2 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[1].slug;
});
post3 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[2].slug;
});
tag1 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[0].slug;
});
tag2 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[1].slug;
});
tag3 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[2].slug;
});
// Check the authors are correct
post1.author_id.should.equal(user2.id);
post2.author_id.should.equal(user3.id);
post3.author_id.should.equal(user1.id);
// Created by should be what was in the import file
post1.created_by.should.equal(user1.id);
post2.created_by.should.equal(user3.id);
post3.created_by.should.equal(user1.id);
// Updated by gets set to the current user
post1.updated_by.should.equal(user1.id);
post2.updated_by.should.equal(user1.id);
post3.updated_by.should.equal(user1.id);
// Published by should be what was in the import file
post1.published_by.should.equal(user2.id);
post2.published_by.should.equal(user3.id);
post3.published_by.should.equal(user1.id);
// Created by should be what was in the import file
tag1.created_by.should.equal(user1.id);
tag2.created_by.should.equal(user2.id);
tag3.created_by.should.equal(user3.id);
// Updated by gets set to the current user
tag1.updated_by.should.equal(user1.id);
tag2.updated_by.should.equal(user1.id);
tag3.updated_by.should.equal(user1.id);
done();
}).catch(done);
});
});
describe('imports multi user data with no owner onto blank ghost install', function () {
var exportData;
before(function doImport(done) {
testUtils.initFixtures('roles', 'owner', 'settings').then(function () {
return testUtils.fixtures.loadExportFixture('export-003-mu-noOwner');
}).then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
done();
}).catch(done);
});
after(testUtils.teardown);
it('gets the right data', function (done) {
var fetchImported = Promise.join(
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
);
fetchImported.then(function (importedData) {
var posts,
settings,
tags,
post1,
post2,
post3;
// General data checks
should.exist(importedData);
importedData.length.should.equal(3, 'Did not get data successfully');
// Test posts, settings and tags
posts = importedData[0];
settings = importedData[1];
tags = importedData[2];
post1 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[0].slug;
});
post2 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[1].slug;
});
post3 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[2].slug;
});
// test posts
posts.length.should.equal(3, 'Wrong number of posts');
post1.title.should.equal(exportData.data.posts[0].title);
post2.title.should.equal(exportData.data.posts[1].title);
post3.title.should.equal(exportData.data.posts[2].title);
// test tags
tags.length.should.equal(3, 'should be 3 tags');
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
done();
}).catch(done);
});
it('imports users with correct roles and status', function (done) {
var fetchImported = Promise.join(
knex('users').select(),
knex('roles_users').select()
);
fetchImported.then(function (importedData) {
var user1,
user2,
user3,
users,
rolesUsers;
// General data checks
should.exist(importedData);
importedData.length.should.equal(2, 'Did not get data successfully');
// Test the users and roles
users = importedData[0];
rolesUsers = importedData[1];
// we imported 3 users
// the original user should be untouched
// the two news users should have been created
users.length.should.equal(3, 'There should only be three users');
// the owner user is first
user1 = users[0];
// the other two users should have the imported data, but they get inserted in different orders
user2 = _.find(users, function (user) {
return user.name === exportData.data.users[0].name;
});
user3 = _.find(users, function (user) {
return user.name === exportData.data.users[1].name;
});
user1.email.should.equal(testUtils.DataGenerator.Content.users[0].email);
user1.password.should.equal(testUtils.DataGenerator.Content.users[0].password);
user1.status.should.equal('active');
user2.email.should.equal(exportData.data.users[0].email);
user3.email.should.equal(exportData.data.users[1].email);
// Newly created users should have a status of locked
user2.status.should.equal('locked');
user3.status.should.equal('locked');
// Newly created users should have created_at/_by and updated_at/_by set to when they were imported
user2.created_by.should.equal(user1.id);
user2.created_at.should.not.equal(exportData.data.users[0].created_at);
user2.updated_by.should.equal(user1.id);
user2.updated_at.should.not.equal(exportData.data.users[0].updated_at);
user3.created_by.should.equal(user1.id);
user3.created_at.should.not.equal(exportData.data.users[1].created_at);
user3.updated_by.should.equal(user1.id);
user3.updated_at.should.not.equal(exportData.data.users[1].updated_at);
rolesUsers.length.should.equal(3, 'There should be 3 role relations');
_.each(rolesUsers, function (roleUser) {
if (roleUser.user_id === user1.id) {
roleUser.role_id.should.equal(4, 'Original user should be an owner');
}
if (roleUser.user_id === user2.id) {
roleUser.role_id.should.equal(1, 'Josephine should be an admin');
}
if (roleUser.user_id === user3.id) {
roleUser.role_id.should.equal(3, 'Smith should be an author by default');
}
});
done();
}).catch(done);
});
it('imports posts & tags with correct authors, owners etc', function (done) {
var fetchImported = Promise.join(
knex('users').select(),
knex('posts').select(),
knex('tags').select()
);
fetchImported.then(function (importedData) {
var users, user1, user2, user3,
posts, post1, post2, post3,
tags, tag1, tag2, tag3;
// General data checks
should.exist(importedData);
importedData.length.should.equal(3, 'Did not get data successfully');
// Test the users and roles
users = importedData[0];
posts = importedData[1];
tags = importedData[2];
// Grab the users
// the owner user is first
user1 = users[0];
// the other two users should have the imported data, but they get inserted in different orders
user2 = _.find(users, function (user) {
return user.name === exportData.data.users[0].name;
});
user3 = _.find(users, function (user) {
return user.name === exportData.data.users[1].name;
});
post1 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[0].slug;
});
post2 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[1].slug;
});
post3 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[2].slug;
});
tag1 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[0].slug;
});
tag2 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[1].slug;
});
tag3 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[2].slug;
});
// Check the authors are correct
post1.author_id.should.equal(user2.id);
post2.author_id.should.equal(user3.id);
post3.author_id.should.equal(user1.id);
// Created by should be what was in the import file
post1.created_by.should.equal(user1.id);
post2.created_by.should.equal(user3.id);
post3.created_by.should.equal(user1.id);
// Updated by gets set to the current user
post1.updated_by.should.equal(user1.id);
post2.updated_by.should.equal(user1.id);
post3.updated_by.should.equal(user1.id);
// Published by should be what was in the import file
post1.published_by.should.equal(user2.id);
post2.published_by.should.equal(user3.id);
post3.published_by.should.equal(user1.id);
// Created by should be what was in the import file
tag1.created_by.should.equal(user1.id);
tag2.created_by.should.equal(user2.id);
tag3.created_by.should.equal(user3.id);
// Updated by gets set to the current user
tag1.updated_by.should.equal(user1.id);
tag2.updated_by.should.equal(user1.id);
tag3.updated_by.should.equal(user1.id);
done();
}).catch(done);
});
});
describe('imports multi user data onto existing data', function () {
var exportData;
before(function doImport(done) {
// initialise the blog with some data
testUtils.initFixtures('users:roles', 'posts', 'settings').then(function () {
return testUtils.fixtures.loadExportFixture('export-003-mu');
}).then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
done();
}).catch(done);
});
after(testUtils.teardown);
it('gets the right data', function (done) {
var fetchImported = Promise.join(
knex('posts').select(),
knex('settings').select(),
knex('tags').select()
);
fetchImported.then(function (importedData) {
var posts,
settings,
tags,
post1,
post2,
post3;
// General data checks
should.exist(importedData);
importedData.length.should.equal(3, 'Did not get data successfully');
// Test posts, settings and tags
posts = importedData[0];
settings = importedData[1];
tags = importedData[2];
post1 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[0].slug;
});
post2 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[1].slug;
});
post3 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[2].slug;
});
// test posts
posts.length.should.equal(
(exportData.data.posts.length + testUtils.DataGenerator.Content.posts.length),
'Wrong number of posts'
);
posts[0].title.should.equal(testUtils.DataGenerator.Content.posts[0].title);
post1.title.should.equal(exportData.data.posts[0].title);
post2.title.should.equal(exportData.data.posts[1].title);
post3.title.should.equal(exportData.data.posts[2].title);
// test tags
tags.length.should.equal(
(exportData.data.tags.length + testUtils.DataGenerator.Content.tags.length),
'Wrong number of tags'
);
tags[0].name.should.equal(testUtils.DataGenerator.Content.tags[0].name);
// test settings
settings.length.should.be.above(0, 'Wrong number of settings');
_.findWhere(settings, {key: 'databaseVersion'}).value.should.equal(DEF_DB_VERSION, 'Wrong database version');
done();
}).catch(done);
});
it('imports users with correct roles and status', function (done) {
var fetchImported = Promise.join(
knex('users').select(),
knex('roles_users').select()
);
fetchImported.then(function (importedData) {
var ownerUser,
newUser,
existingUser,
users,
rolesUsers;
// General data checks
should.exist(importedData);
importedData.length.should.equal(2, 'Did not get data successfully');
// Test the users and roles
users = importedData[0];
rolesUsers = importedData[1];
// we imported 3 users, there were already 4 users, only one of the imported users is new
users.length.should.equal(5, 'There should only be three users');
// the owner user is first
ownerUser = users[0];
// the other two users should have the imported data, but they get inserted in different orders
newUser = _.find(users, function (user) {
return user.name === exportData.data.users[1].name;
});
existingUser = _.find(users, function (user) {
return user.name === exportData.data.users[2].name;
});
ownerUser.email.should.equal(testUtils.DataGenerator.Content.users[0].email);
ownerUser.password.should.equal(testUtils.DataGenerator.Content.users[0].password);
ownerUser.status.should.equal('active');
newUser.email.should.equal(exportData.data.users[1].email);
existingUser.email.should.equal(exportData.data.users[2].email);
// Newly created users should have a status of locked
newUser.status.should.equal('locked');
// The already existing user should still have a status of active
existingUser.status.should.equal('active');
// Newly created users should have created_at/_by and updated_at/_by set to when they were imported
newUser.created_by.should.equal(ownerUser.id);
newUser.created_at.should.not.equal(exportData.data.users[1].created_at);
newUser.updated_by.should.equal(ownerUser.id);
newUser.updated_at.should.not.equal(exportData.data.users[1].updated_at);
rolesUsers.length.should.equal(5, 'There should be 5 role relations');
_.each(rolesUsers, function (roleUser) {
if (roleUser.user_id === ownerUser.id) {
roleUser.role_id.should.equal(4, 'Original user should be an owner');
}
if (roleUser.user_id === newUser.id) {
roleUser.role_id.should.equal(1, 'New user should be an admin');
}
if (roleUser.user_id === existingUser.id) {
roleUser.role_id.should.equal(1, 'Existing user was an admin');
}
});
done();
}).catch(done);
});
it('imports posts & tags with correct authors, owners etc', function (done) {
var fetchImported = Promise.join(
knex('users').select(),
knex('posts').select(),
knex('tags').select()
);
fetchImported.then(function (importedData) {
var users, ownerUser, newUser, existingUser,
posts, post1, post2, post3,
tags, tag1, tag2, tag3;
// General data checks
should.exist(importedData);
importedData.length.should.equal(3, 'Did not get data successfully');
// Test the users and roles
users = importedData[0];
posts = importedData[1];
tags = importedData[2];
// Grab the users
// the owner user is first
ownerUser = users[0];
// the other two users should have the imported data, but they get inserted in different orders
newUser = _.find(users, function (user) {
return user.name === exportData.data.users[1].name;
});
existingUser = _.find(users, function (user) {
return user.name === exportData.data.users[2].name;
});
post1 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[0].slug;
});
post2 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[1].slug;
});
post3 = _.find(posts, function (post) {
return post.slug === exportData.data.posts[2].slug;
});
tag1 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[0].slug;
});
tag2 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[1].slug;
});
tag3 = _.find(tags, function (tag) {
return tag.slug === exportData.data.tags[2].slug;
});
// Check the authors are correct
post1.author_id.should.equal(newUser.id);
post2.author_id.should.equal(existingUser.id);
post3.author_id.should.equal(ownerUser.id);
// Created by should be what was in the import file
post1.created_by.should.equal(ownerUser.id);
post2.created_by.should.equal(existingUser.id);
post3.created_by.should.equal(ownerUser.id);
// Updated by gets set to the current user
post1.updated_by.should.equal(ownerUser.id);
post2.updated_by.should.equal(ownerUser.id);
post3.updated_by.should.equal(ownerUser.id);
// Published by should be what was in the import file
post1.published_by.should.equal(newUser.id);
post2.published_by.should.equal(existingUser.id);
post3.published_by.should.equal(ownerUser.id);
// Created by should be what was in the import file
tag1.created_by.should.equal(ownerUser.id);
tag2.created_by.should.equal(newUser.id);
tag3.created_by.should.equal(existingUser.id);
// Updated by gets set to the current user
tag1.updated_by.should.equal(ownerUser.id);
tag2.updated_by.should.equal(ownerUser.id);
tag3.updated_by.should.equal(ownerUser.id);
done();
}).catch(done);
});
});
describe('imports multi user data onto existing data without duplicate owners', function () {
var exportData;
before(function doImport(done) {
// initialise the blog with some data
testUtils.initFixtures('users:roles', 'posts', 'settings').then(function () {
return testUtils.fixtures.loadExportFixture('export-003-mu-multipleOwner');
}).then(function (exported) {
exportData = exported;
return importer.doImport(exportData);
}).then(function () {
done();
}).catch(done);
});
after(testUtils.teardown);
it('imports users with correct roles and status', function (done) {
var fetchImported = Promise.join(
knex('users').select(),
knex('roles_users').select()
);
fetchImported.then(function (importedData) {
var ownerUser,
newUser,
existingUser,
users,
rolesUsers;
// General data checks
should.exist(importedData);
importedData.length.should.equal(2, 'Did not get data successfully');
// Test the users and roles
users = importedData[0];
rolesUsers = importedData[1];
// the owner user is first
ownerUser = users[0];
// the other two users should have the imported data, but they get inserted in different orders
newUser = _.find(users, function (user) {
return user.name === exportData.data.users[1].name;
});
existingUser = _.find(users, function (user) {
return user.name === exportData.data.users[2].name;
});
// we imported 3 users, there were already 4 users, only one of the imported users is new
users.length.should.equal(5, 'There should only be three users');
rolesUsers.length.should.equal(5, 'There should be 5 role relations');
_.each(rolesUsers, function (roleUser) {
if (roleUser.user_id === ownerUser.id) {
roleUser.role_id.should.equal(4, 'Original user should be an owner');
}
if (roleUser.user_id === newUser.id) {
roleUser.role_id.should.equal(1, 'New user should be downgraded from owner to admin');
}
if (roleUser.user_id === existingUser.id) {
roleUser.role_id.should.equal(1, 'Existing user was an admin');
}
});
done();
}).catch(done);
});
});
});
|
// Author : Prathap Reddy SV
var LStorage = (function () {
function LStorage() {
this.init = function(){
if(!this.localStorage) {
this.localStorage = JSON.parse(JSON.stringify(localStorage));
// or new Function("return JSON.parse('" + JSON.stringify(localStorage) + "')")();
}
}
}
var prototype = {
constructor: LStorage
};
prototype.setItem = function (key, val) {
this.init();
if(this.localStorage[key] == val) return;
this.localStorage[key] = val;
localStorage.setItem(key, val);
};
prototype.getItem = function (key, undef) {
this.init();
var val = this.localStorage[key];
return val;
};
prototype.removeItem = function (key) {
this.init();
delete this.localStorage[key];
localStorage.removeItem(key);
return true;
};
LStorage.prototype = prototype;
return LStorage;
})();
|
// Une application minimaliste pour découvrir Node.js
// Pour la faire fonctionner, il faut d'abord avoir installé Express
// La commande node chapitre3-premier-pas permet de la démarrer
// Chargement du module Express
var express = require("express");
// Création d'un objet qui représente notre application
var app = express();
// Démarrage du serveur à l'adresse http://localhost:8080
app.listen(8080);
// On affiche un message pour indiquer que tout s'est bien passé
console.log("Serveur en marche"); |
'use strict';
var React = require('react');
var mui = require('material-ui');
var SvgIcon = mui.SvgIcon;
var createClass = require('create-react-class');
var ContentClear = createClass({
displayName: 'ContentClear',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z' })
);
}
});
module.exports = ContentClear; |
const test = require('ava')
const { translate, create, clone } = require('./index')
const { compareVectors } = require('../../../test/helpers/index')
test('mat4: translate() called with two paramerters should return a mat4 with correct values', (t) => {
const identityMatrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
]
const obs1 = translate([0, 0, 0], identityMatrix)
t.true(compareVectors(obs1, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]))
const obs2 = translate([2, 3, 6], identityMatrix)
t.true(compareVectors(obs2, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 3, 6, 1]))
const x = 1
const y = 5
const z = 7
const translationMatrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
x, y, z, 1
]
const obs3 = translate([-2, -3, -6], translationMatrix)
t.true(compareVectors(obs3, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -1, 2, 1, 1]))
const w = 1
const h = 3
const d = 5
const scaleMatrix = [
w, 0, 0, 0,
0, h, 0, 0,
0, 0, d, 0,
0, 0, 0, 1
]
const obs4 = translate([2, 3, 6], scaleMatrix)
t.true(compareVectors(obs4, [1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 2, 9, 30, 1]))
const r = (90 * 0.017453292519943295)
const rotateZMatrix = [
Math.cos(r), -Math.sin(r), 0, 0,
Math.sin(r), Math.cos(r), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
]
const obs5 = translate([6, 4, 2], rotateZMatrix)
// t.true(compareVectors(obs5, [0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 4, -6, 2, 1])) // close to zero
})
test('mat4: translate() called with three paramerters should update a mat4 with correct values', (t) => {
const identityMatrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
]
const obs1 = create()
const ret1 = translate(obs1, [0, 0, 0], identityMatrix)
t.true(compareVectors(obs1, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]))
t.true(compareVectors(ret1, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]))
const obs2 = create(0, 0, 0, 0)
const ret2 = translate(obs2, [2, 3, 6], identityMatrix)
t.true(compareVectors(obs2, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 3, 6, 1]))
t.true(compareVectors(ret2, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 3, 6, 1]))
const x = 1
const y = 5
const z = 7
const translationMatrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
x, y, z, 1
]
const obs3 = create()
const ret3 = translate(obs3, [-2, -3, -6], translationMatrix)
t.true(compareVectors(obs3, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -1, 2, 1, 1]))
t.true(compareVectors(ret3, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -1, 2, 1, 1]))
const w = 1
const h = 3
const d = 5
const scaleMatrix = [
w, 0, 0, 0,
0, h, 0, 0,
0, 0, d, 0,
0, 0, 0, 1
]
const obs4 = create()
const ret4 = translate(obs4, [2, 3, 6], scaleMatrix)
t.true(compareVectors(obs4, [1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 2, 9, 30, 1]))
t.true(compareVectors(ret4, [1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 2, 9, 30, 1]))
const r = (90 * 0.017453292519943295)
const rotateZMatrix = [
Math.cos(r), -Math.sin(r), 0, 0,
Math.sin(r), Math.cos(r), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
]
const obs5 = create()
const ret5 = translate(obs5, [6, 4, 2], rotateZMatrix)
// t.true(compareVectors(obs5, [0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 4, -6, 2, 1])) // close to zero
// t.true(compareVectors(ret5, [0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 4, -6, 2, 1])) // close to zero
// special case where in and out are the same
const obs6 = clone(rotateZMatrix)
const ret6 = translate(obs6, [6, 4, 2], obs6)
// t.true(compareVectors(obs6, [0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 4, -6, 2, 1])) // close to zero
// t.true(compareVectors(ret6, [0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 4, -6, 2, 1])) // close to zero
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.