code
stringlengths 2
1.05M
|
---|
const fs = require('fs');
module.exports = function insertSiteSettings(htmlPath, settings) {
const origHtml = fs.readFileSync(htmlPath, { encoding: 'utf8' });
const html = replaceTitle(origHtml, settings);
const scriptIndex = html.indexOf('<script');
const analyticsCode = settings.trackingId ? getAnalyticsCode(settings.trackingId) : '';
const siteCode = getSiteCode(settings);
return `${html.substring(0, scriptIndex)}${analyticsCode}${siteCode}${html.substring(scriptIndex)}`;
}
function getAnalyticsCode(trackingId) {
if (trackingId == 'TEST') {
const logger = 'console.log(`ga(${params.join(",")})`)'
return `<script>
ga = (...params) => ${logger};
ga.trackingId = 'TEST';
ga('create', '${trackingId}', 'auto');
</script>`;
} else {
return `<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga.trackingId = '${trackingId}'
ga('create', '${trackingId}', 'auto');
ga('send', 'pageview');
</script>`;
}
}
function getSiteCode(settings) {
return `<script>
window.__zwiftGPS = ${JSON.stringify(settings)}
</script>`;
}
function replaceTitle(html, settings) {
if (settings.title) {
const start = html.indexOf('<title>'),
end = html.indexOf('</title>')
if (start !== -1 && end !== -1) {
return `${html.substring(0, start)}<title>${settings.title}</title>${html.substring(end + 8)}`;
}
}
return html;
}
|
//========================================================================
// not necessary to include just to check wether the prefixes work or not
//========================================================================
// In the following line, you should include the prefixes of implementations you want to test.
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// DON'T use "var indexedDB = ..." if you're not in a function.
// Moreover, you may need references to some window.IDB* objects:
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"}; // This line should only be needed if it is needed to support the object's constants for older browsers
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
//========================================================================
// to check wether indexeddb works on your browser or not
//========================================================================
if (!window.indexedDB)
{
window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
}
//========================================================================
// open a database
//========================================================================
var request = window.indexedDB.open("DB_NAME", "DB_VERSION");
// "MyTestDatabase" is DB_NAME
// 3 is the DB_VERSION
//========================================================================
// Creating or updating the version of the database
//========================================================================
request.onupgradeneeded = function(event)
{
var db = event.target.result;
// Create an objectStore for this database
var objectStore = db.createObjectStore("DB_STORE_NAME", { keyPath: "u_id", autoIncrement: true });
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = function(event)
{
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
for (var i in customerData)
{
customerObjectStore.add(customerData[i]);
};
}
}
//========================================================================
// ADD DATA
//========================================================================
var transaction = db.transaction(["param 1"], "param 2");
// param1 list of object storesthat transactions will span
// param2 always use "readwrite" over " " or "read"
// Do something when all the data is added to the database.
transaction.oncomplete = function(event)
{
alert("All done!");
};
transaction.onerror = function(event)
{
// Don't forget to handle errors!
};
var objectStore = transaction.objectStore("customers");
for (var i in customerData)
{
var request = objectStore.add(customerData[i]);
request.onsuccess = function(event)
{
// event.target.result == customerData[i].ssn;
};
}
//========================================================================
// REMOVE DATA
//========================================================================
var request = db.transaction(["customers"], "readwrite")
.objectStore("customers")
.delete("444-44-4444");
request.onsuccess = function(event)
{
// It's gone!
};
//========================================================================
// GETTING DATA
//========================================================================
// PART 1 LONG METHOD WITH HANGLING ALL ERRORS
var transaction = db.transaction(["customers"]);
var objectStore = transaction.objectStore("customers");
var request = objectStore.get("444-44-4444");
request.onerror = function(event) {
// Handle errors!
};
request.onsuccess = function(event) {
// Do something with the request.result!
alert("Name for SSN 444-44-4444 is " + request.result.name);
};
// PART 2 IF ALL REQUESTS ARE HANDLED AT DATABASE LEVEL
db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event)
{
alert("Name for SSN 444-44-4444 is " + event.target.result.name);
};
//========================================================================
// UPDATING DATA
//========================================================================
var objectStore = db.transaction(["customers"], "readwrite").objectStore("customers");
var request = objectStore.get("444-44-4444");
request.onerror = function(event) {
// Handle errors!
};
request.onsuccess = function(event) {
// Get the old value that we want to update
var data = event.target.result;
// update the value(s) in the object that you want to change
data.age = 42;
// Put this updated object back into the database.
var requestUpdate = objectStore.put(data);
requestUpdate.onerror = function(event) {
// Do something with the error
};
requestUpdate.onsuccess = function(event) {
// Success - the data is updated!
};
};
//========================================================================
// USING CURSOR
//========================================================================
// PART 1
var objectStore = db.transaction("customers").objectStore("customers");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for SSN " + cursor.key + " is " + cursor.value.name);
cursor.continue();
}
else {
alert("No more entries!");
}
};
// PART 2
var customers = [];
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
customers.push(cursor.value);
cursor.continue();
}
else {
alert("Got all customers: " + customers);
}
};
|
import AbstractEnum from './AbstractEnum';
/**
* Keys of contract fields.
*/
export default class ContractAttributeEnum extends AbstractEnum {
static getNiceLabel(key) {
return super.getNiceLabel(`core:enums.ContractAttributeEnum.${key}`);
}
static getHelpBlockLabel(key) {
return super.getNiceLabel(`core:enums.ContractAttributeEnum.helpBlock.${key}`);
}
static findKeyBySymbol(sym) {
return super.findKeyBySymbol(this, sym);
}
static findSymbolByKey(key) {
return super.findSymbolByKey(this, key);
}
static getField(key) {
if (!key) {
return null;
}
const sym = super.findSymbolByKey(this, key);
switch (sym) {
case this.IDENTITY: {
return 'identity';
}
case this.VALID_FROM: {
return 'validFrom';
}
case this.VALID_TILL: {
return 'validTill';
}
case this.WORK_POSITION: {
return 'workPosition';
}
case this.POSITION: {
return 'position';
}
case this.EXTERNE: {
return 'externe';
}
case this.MAIN: {
return 'main';
}
case this.DESCRIPTION: {
return 'description';
}
case this.GUARANTEES: {
return 'guarantees';
}
case this.POSITIONS: {
return 'positions';
}
case this.STATE: {
return 'state';
}
default: {
return null;
}
}
}
static getEnum(field) {
if (!field) {
return null;
}
switch (field) {
case 'identity': {
return this.IDENTITY;
}
case 'validFrom': {
return this.VALID_FROM;
}
case 'validTill': {
return this.VALID_TILL;
}
case 'workPosition': {
return this.WORK_POSITION;
}
case 'position': {
return this.POSITION;
}
case 'externe': {
return this.EXTERNE;
}
case 'main': {
return this.MAIN;
}
case 'description': {
return this.DESCRIPTION;
}
case 'disabled': {
return this.DISABLED;
}
case 'guarantees': {
return this.GUARANTEES;
}
case 'positions': {
return this.POSITIONS;
}
case 'state': {
return this.STATE;
}
default: {
return null;
}
}
}
static getLevel(key) {
if (!key) {
return null;
}
const sym = super.findSymbolByKey(this, key);
switch (sym) {
default: {
return 'default';
}
}
}
}
ContractAttributeEnum.IDENTITY = Symbol('IDENTITY');
ContractAttributeEnum.MAIN = Symbol('MAIN');
ContractAttributeEnum.STATE = Symbol('STATE');
ContractAttributeEnum.POSITION = Symbol('POSITION');
ContractAttributeEnum.WORK_POSITION = Symbol('WORK_POSITION');
ContractAttributeEnum.VALID_FROM = Symbol('VALID_FROM');
ContractAttributeEnum.VALID_TILL = Symbol('VALID_TILL');
ContractAttributeEnum.EXTERNE = Symbol('EXTERNE');
ContractAttributeEnum.DESCRIPTION = Symbol('DESCRIPTION');
ContractAttributeEnum.GUARANTEES = Symbol('GUARANTEES');
ContractAttributeEnum.POSITIONS = Symbol('POSITIONS');
|
import { postReviews, parseErrors } from '../adapters/creameryApi'
export const ADD_REVIEW = 'ADD_REVIEW'
export const ADD_REVIEW_SUCCESS = 'ADD_REVIEW_SUCCESS'
export const ADD_REVIEW_ERROR = 'ADD_REVIEW_ERROR'
function initiateAddReview() {
return {
type: ADD_REVIEW
}
}
function addReviewSuccess(response) {
return {
type: ADD_REVIEW_SUCCESS,
data: response.data
}
}
function addReviewError(error) {
return {
type: ADD_REVIEW_ERROR,
errors: parseErrors(error)
}
}
export function addReview(review) {
return function(dispatch) {
dispatch(initiateAddReview())
return postReviews(review)
.then((response) => {
dispatch(addReviewSuccess(response))
})
.catch((error) => {
dispatch(addReviewError(error))
}
)
}
}
|
// AFRIKADIAL
var baseUrl = 'http://jalapenodigital.co.za/images/Africa-flags/';
var dialObj = {
//CENTRAL AFRICA
AO: {flag: baseUrl + 'ao.png',name: 'Angola',area_code: '+244'},
CM: {flag: baseUrl + 'cm.png',name: 'Cameroon',area_code: '+237'},
CF: {flag: baseUrl + 'cf.png',name: 'Central African Republic',area_code: '+236'},
TD: {flag: baseUrl + 'td.png',name: 'Chad',area_code: '+235'},
CD: {flag: baseUrl + 'cd.png',name: 'Democratic Rebublic of the Congo',area_code: '+243'},
CG: {flag: baseUrl + 'cg.png',name: 'Republic of the Congo',area_code: '+242'},
GQ: {flag: baseUrl + 'gq.png',name: 'Equatorial Guinea',area_code: '+240'},
GA: {flag: baseUrl + 'ga.png',name: 'Gabon',area_code: '+241'},
ST: {flag: baseUrl + 'st.png',name: 'São Tomé and Príncipe',area_code: '+239'},
//EAST AFRICA
BI: {flag: baseUrl + 'bi.png',name: 'Burundi',area_code: '+257'},
KM: {flag: baseUrl + 'km.png',name: 'Comoros',area_code: '+269'},
KE: {flag: baseUrl + 'ke.png',name: 'Kenya',area_code: '+254'},
MG: {flag: baseUrl + 'mg.png',name: 'Madagascar',area_code: '+261'},
MW: {flag: baseUrl + 'mw.png',name: 'Malawi',area_code: '+265'},
MU: {flag: baseUrl + 'mu.png',name: 'Mauritius',area_code: '+230'},
YT: {flag: baseUrl + 'yt.png',name: 'Mayotte (France)',area_code: '+262'},
MZ: {flag: baseUrl + 'mz.png',name: 'Mozambique',area_code: '+258'},
RE: {flag: baseUrl + 're.png',name: 'Réunion (France)',area_code: '+262'},
RW: {flag: baseUrl + 'rw.png',name: 'Rwanda',area_code: '+250'},
SC: {flag: baseUrl + 'sc.png',name: 'Seychelles',area_code: '+248'},
TZ: {flag: baseUrl + 'tz.png',name: 'Tanzania',area_code: '+255'},
UG: {flag: baseUrl + 'ug.png',name: 'Uganda',area_code: '+256'},
//HORN
DJ: {flag: baseUrl + 'dj.png',name: 'Djibouti',area_code: '+253'},
ER: {flag: baseUrl + 'er.png',name: 'Eritrea',area_code: '+291'},
ET: {flag: baseUrl + 'et.png',name: 'Ethiopia',area_code: '+251'},
SO: {flag: baseUrl + 'so.png',name: 'Somalia',area_code: '+252'},
//NORTH AFRICA
DZ: {flag: baseUrl + 'dz.png',name: 'Algeria',area_code: '+213'},
EG: {flag: baseUrl + 'eg.png',name: 'Egypt',area_code: '+20'},
LY: {flag: baseUrl + 'ly.png',name: 'Libya',area_code: '+218'},
MA: {flag: baseUrl + 'ma.png',name: 'Morocco',area_code: '+212'},
SS: {flag: baseUrl + 'ss.png',name: 'South Sudan',area_code: '+211'},
SD: {flag: baseUrl + 'sd.png',name: 'Sudan',area_code: '+249'},
TN: {flag: baseUrl + 'tn.png',name: 'Tunisia',area_code: '+216'},
//SOUTHERN AFRICA
BW: {flag: baseUrl + 'bw.png',name: 'Botswana',area_code: '+267'},
LS: {flag: baseUrl + 'ls.png',name: 'Lesotho',area_code: '+266'},
NA: {flag: baseUrl + 'na.png',name: 'Namibia',area_code: '+264'},
ZA: {flag: baseUrl + 'za.png',name: 'South Africa',area_code: '+27'},
SZ: {flag: baseUrl + 'sz.png',name: 'Swaziland',area_code: '+268'},
ZM: {flag: baseUrl + 'zm.png',name: 'Zambia',area_code: '+260'},
ZW: {flag: baseUrl + 'zw.png',name: 'Zimbabwe',area_code: '+263'},
//WEST AFRICA
SH: {flag: baseUrl + 'sh.png',name: 'Ascension Island (UK)',area_code: '+247'},
BJ: {flag: baseUrl + 'bj.png',name: 'Benin',area_code: '+229'},
BF: {flag: baseUrl + 'bf.png',name: 'Burkina Faso',area_code: '+226'},
CV: {flag: baseUrl + 'cv.png',name: 'Cape Verde',area_code: '+238'},
CI: {flag: baseUrl + 'ci.png',name: 'Ivory Coast',area_code: '+225'},
GM: {flag: baseUrl + 'gm.png',name: 'Gambia',area_code: '+220'},
GH: {flag: baseUrl + 'gh.png',name: 'Ghana',area_code: '+233'},
GN: {flag: baseUrl + 'gn.png',name: 'Guinea',area_code: '+224'},
GW: {flag: baseUrl + 'gw.png',name: 'Guinea-Bissau',area_code: '+245'},
LR: {flag: baseUrl + 'lr.png',name: 'Liberia',area_code: '+231'},
ML: {flag: baseUrl + 'ml.png',name: 'Mali',area_code: '+223'},
MR: {flag: baseUrl + 'mr.png',name: 'Mauritania',area_code: '+222'},
NE: {flag: baseUrl + 'ne.png',name: 'Niger',area_code: '+227'},
NG: {flag: baseUrl + 'ng.png',name: 'Nigeria',area_code: '+234'},
SH: {flag: baseUrl + 'sh.png',name: 'Saint Helena (UK)',area_code: '+290'},
SN: {flag: baseUrl + 'sn.png',name: 'Senegal',area_code: '+221'},
SL: {flag: baseUrl + 'sl.png',name: 'Sierra Leone',area_code: '+232'},
TG: {flag: baseUrl + 'tg.png',name: 'Togo',area_code: '+228'},
}
$(function () {
$(document).delegate('#cc,#cc-flag','click',function() {
$('.afrika-container').css('transition','all 0s')
.css('opacity','0')
.css('display','block');
setTimeout(function () {
$('.afrika-container').css('transition','all 0.5s')
.css('opacity','1')
},10);
});
$(document).delegate('.afrika-item-container','click', function() {
$('#cc').val($(this).attr('data-code'));
$('.afrika-container').css('display','none');
$('#cc-flag').css('background-image',$(this).children().first().css('background-image'));
});
})
function afrikalist($elem) {
var $li, $css, $container;
$('body').prepend('<div class="afrika-container"></div>');
$($elem).css('position','relative');
$($elem).append('<input class="area-code" id="cc"name="area-code" type="text" required placeholder="+27">\
<div id="cc-flag"> </div>\
</input>');
for (var key in dialObj) {
if (dialObj.hasOwnProperty(key)) {
$item = '<div class="afrika-item-container" data-code='+dialObj[key].area_code+'> \
<div class="afrika-flag" style="background-image: url('+dialObj[key].flag+')"> </div>\
<div class="afrika-text">'+dialObj[key].name+'</div>\
</div>'
$('.afrika-container').append($item);
}
}
}
$(document).ready(function () {
$css = '<link href="http://jalapenodigital.co.za/images/Africa-flags/afrikadial.css" rel="stylesheet" type="text/css">';
$('head').prepend($css);
});
|
var gulp = require('gulp')
var webserver = require('gulp-webserver');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var cleanCSS = require('gulp-clean-css');
var plumber = require('gulp-plumber');
var metagenerator = require('./app/metagenerator.js');
var paths = {
scripts: ['src/*.js'],
public : ['public/'],
style: ['public/css/style.sass']
};
gulp.task('compile', function() {
// Minify and copy all JavaScript (except vendor scripts)
return gulp.src(paths.scripts)
.pipe(plumber())
.pipe(concat('main.min.js'))
//.pipe(uglify())
.pipe(gulp.dest(paths.public + 'js/'));
});
gulp.task('lint', function() {
return gulp.src(paths.scripts)
.pipe(plumber())
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('style', function() {
return gulp.src(paths.style)
.pipe(sass().on('error', sass.logError))
.pipe(cleanCSS())
.pipe(gulp.dest('public/css'));
});
gulp.task('webserver', function() {
gulp.src('.')
.pipe(webserver());
});
// Rerun the task when a file changes
gulp.task('watch', function() {
gulp.watch(paths.scripts, [ 'lint','compile']);
gulp.watch(paths.style, [ 'style' ]);
});
gulp.task('generate', function(cb){
metagenerator(cb);
});
gulp.task('default', [ 'lint', 'compile', 'style', 'webserver', 'watch' ]);
|
(function() {
'use strict';
module.exports = function() {
var service = global.io.rootPath + 'back-end/routes/restApi/apImpl/services/';
var config = {
settings : require(service + 'settings'),
user : require(service + 'user'),
upload : require(service + 'upload')
};
return config;
};
}());
|
'use strict'
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const config = require('config.json')('./config.json');
module.exports = class RolesCommand extends Command {
constructor(client) {
super(client, {
name: 'roles',
group: 'info',
memberName: 'roles',
description: 'Get a list of all roles on the server.',
guildOnly: true,
examples: ['roles']
});
};
run(msg) {
let roles = msg.guild.roles.array().sort((a, b) => {
return 0 - (a.rawPosition - b.rawPosition);
});
return msg.channel.send(new MessageEmbed()
.setColor(config.embedColor)
.setDescription(roles.map(e => e.name))
.setTitle('Roles on this server'));
}
};
|
datab = [{},{"IE":{"colspan":"1","rowspan":"1","text":"Image"},"Module":{"colspan":"1","rowspan":"1","text":"XA/XRF Acquisition"},"PS3.3 Reference":{"colspan":"1","rowspan":"1","text":""},"Usage":{"colspan":"1","rowspan":"1","text":"Specifies the type of detector."}},{"IE":{"colspan":"1","rowspan":"1","text":""},"Module":{"colspan":"1","rowspan":"1","text":"X-Ray Image Intensifier"},"PS3.3 Reference":{"colspan":"1","rowspan":"1","text":""},"Usage":{"colspan":"1","rowspan":"1","text":"Conditional to type of detector. Applicable in case of IMG_INTENSIFIER."}},{"IE":{"colspan":"1","rowspan":"1","text":""},"Module":{"colspan":"1","rowspan":"1","text":"X-Ray Detector"},"PS3.3 Reference":{"colspan":"1","rowspan":"1","text":""},"Usage":{"colspan":"1","rowspan":"1","text":"Conditional to type of detector. Applicable in case of DIGITAL_DETECTOR."}}];
|
from collections import OrderedDict as od
def first_non_repeated(s):
d=od()
for c in s:
try: d[c]+=1
except:d[c]=1
for key,val in d.items():
if val==1: return key
|
import _ from "lodash";
import fetch from "cross-fetch";
import moment from "moment-timezone";
export const ACCEPTED_FILE_TYPES = [
"image/*",
"audio/x-wav",
"audio/wav",
"audio/wave",
"audio/mp3",
"audio/mpeg",
"audio/x-mp3",
"audio/mp4",
"audio/x-m4a",
"audio/amr"
].join( ", " );
export const MAX_FILE_SIZE = 20971520; // 20 MB in bytes
export const DATETIME_WITH_TIMEZONE = "YYYY/MM/DD h:mm A z";
export const DATETIME_WITH_TIMEZONE_OFFSET = "YYYY/MM/DD h:mm A ZZ";
const util = class util {
static isOnline( callback ) {
// temporary until we have a ping API
fetch( "/pages/about", {
method: "head",
mode: "no-cors",
cache: "no-store"
} )
.then( ( ) => callback( true ) )
.catch( ( ) => callback( false ) );
}
// returns a Promise
static reverseGeocode( lat, lng ) {
if ( typeof ( google ) === "undefined" ) return new Promise( );
const geocoder = new google.maps.Geocoder( );
return new Promise( resolve => {
geocoder.geocode( { location: { lat, lng } }, ( results, status ) => {
let locationName;
if ( status === google.maps.GeocoderStatus.OK ) {
if ( results[0] ) {
results.reverse( );
const neighborhood = _.find( results, r => _.includes( r.types, "neighborhood" ) );
const locality = _.find( results, r => _.includes( r.types, "locality" ) );
const sublocality = _.find( results, r => _.includes( r.types, "sublocality" ) );
const level2 = _.find( results,
r => _.includes( r.types, "administrative_area_level_2" ) );
const level1 = _.find( results,
r => _.includes( r.types, "administrative_area_level_1" ) );
if ( neighborhood ) {
locationName = neighborhood.formatted_address;
} else if ( sublocality ) {
locationName = sublocality.formatted_address;
} else if ( locality ) {
locationName = locality.formatted_address;
} else if ( level2 ) {
locationName = level2.formatted_address;
} else if ( level1 ) {
locationName = level1.formatted_address;
}
}
}
resolve( locationName );
} );
} );
}
static gpsCoordConvert( c ) {
return ( c[0][0] / c[0][1] )
+ ( ( c[1][0] / c[1][1] ) / 60 )
+ ( ( c[2][0] / c[2][1] ) / 3600 );
}
static countPending( files ) {
return _.size( _.pickBy( files,
f => f.uploadState === "pending" || f.uploadState === "uploading" ) );
}
static dateInvalid( dateString ) {
let invalidDate = false;
if ( dateString ) {
const now = moment( );
// valid dates must at least have year/month/day
const onlyDate = moment( dateString.split( " " )[0], "YYYY/MM/DD", true );
if ( !onlyDate.isValid( ) ) {
invalidDate = true;
} else if ( onlyDate.isAfter( now ) && !onlyDate.isSame( now, "day" ) ) {
// dates in the future are also invalid
invalidDate = true;
}
}
return invalidDate;
}
static errorJSON( text ) {
try {
const json = JSON.parse( text );
return json;
} catch ( e ) {
return null;
}
}
};
export default util;
|
'use strict';
angular.module('grubUpClientApp')
.config(function ($routeProvider) {
$routeProvider
.when('/menu', {
templateUrl: 'app/menu/menu.html',
controller: 'MenuCtrl'
});
});
|
var structspp___1_1_combiner_3_01_t_00_014_01_4 =
[
[ "operator()", "structspp___1_1_combiner_3_01_t_00_014_01_4.html#aeacf87124749fd2f7269e8e04dcb410a", null ]
];
|
'use strict';
describe('Controller: PlanningSprintCtrl', function () {
// load the controller's module
beforeEach(module('globalgamejam2015App'));
var PlanningSprintCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
PlanningSprintCtrl = $controller('PlanningSprintCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
/*! JSON Editor v0.7.28 - JSON Schema -> HTML Editor
* By Jeremy Dorn - https://github.com/jdorn/json-editor/
* Released under the MIT license
*
* Date: 2016-08-07
*/
/**
* See README.md for requirements and usage info
*/
(function() {
/*jshint loopfunc: true */
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
var Class;
(function(){
var initializing = false, fnTest = /xyz/.test(function(){window.postMessage("xyz");}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function extend(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = extend;
return Class;
};
return Class;
})();
// CustomEvent constructor polyfill
// From MDN
(function () {
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] ||
window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
// Array.isArray polyfill
// From MDN
(function() {
if(!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
}());
/**
* Taken from jQuery 2.1.3
*
* @param obj
* @returns {boolean}
*/
var $isplainobject = function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if (typeof obj !== "object" || obj.nodeType || (obj !== null && obj === obj.window)) {
return false;
}
if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
};
var $extend = function(destination) {
var source, i,property;
for(i=1; i<arguments.length; i++) {
source = arguments[i];
for (property in source) {
if(!source.hasOwnProperty(property)) continue;
if(source[property] && $isplainobject(source[property])) {
if(!destination.hasOwnProperty(property)) destination[property] = {};
$extend(destination[property], source[property]);
}
else {
destination[property] = source[property];
}
}
}
return destination;
};
var $each = function(obj,callback) {
if(!obj || typeof obj !== "object") return;
var i;
if(Array.isArray(obj) || (typeof obj.length === 'number' && obj.length > 0 && (obj.length - 1) in obj)) {
for(i=0; i<obj.length; i++) {
if(callback(i,obj[i])===false) return;
}
}
else {
if (Object.keys) {
var keys = Object.keys(obj);
for(i=0; i<keys.length; i++) {
if(callback(keys[i],obj[keys[i]])===false) return;
}
}
else {
for(i in obj) {
if(!obj.hasOwnProperty(i)) continue;
if(callback(i,obj[i])===false) return;
}
}
}
};
var $trigger = function(el,event) {
var e = document.createEvent('HTMLEvents');
e.initEvent(event, true, true);
el.dispatchEvent(e);
};
var $triggerc = function(el,event) {
var e = new CustomEvent(event,{
bubbles: true,
cancelable: true
});
el.dispatchEvent(e);
};
var JSONEditor = function(element,options) {
if (!(element instanceof Element)) {
throw new Error('element should be an instance of Element');
}
options = $extend({},JSONEditor.defaults.options,options||{});
this.element = element;
this.options = options;
this.init();
};
JSONEditor.prototype = {
// necessary since we remove the ctor property by doing a literal assignment. Without this
// the $isplainobject function will think that this is a plain object.
constructor: JSONEditor,
init: function() {
var self = this;
this.ready = false;
var theme_class = JSONEditor.defaults.themes[this.options.theme || JSONEditor.defaults.theme];
if(!theme_class) throw "Unknown theme " + (this.options.theme || JSONEditor.defaults.theme);
this.schema = this.options.schema;
this.theme = new theme_class();
this.template = this.options.template;
this.refs = this.options.refs || {};
this.uuid = 0;
this.__data = {};
var icon_class = JSONEditor.defaults.iconlibs[this.options.iconlib || JSONEditor.defaults.iconlib];
if(icon_class) this.iconlib = new icon_class();
this.root_container = this.theme.getContainer();
this.element.appendChild(this.root_container);
// Fetch all external refs via ajax
this._loadExternalRefs(this.schema, function() {
self._getDefinitions(self.schema);
// Validator options
var validator_options = {};
if(self.options.custom_validators) {
validator_options.custom_validators = self.options.custom_validators;
}
self.validator = new JSONEditor.Validator(self,null,validator_options);
// Create the root editor
var editor_class = self.getEditorClass(self.schema);
self.root = self.createEditor(editor_class, {
jsoneditor: self,
schema: self.schema,
required: true,
container: self.root_container
});
self.root.preBuild();
self.root.build();
self.root.postBuild();
// Starting data
if(self.options.startval) self.root.setValue(self.options.startval);
self.validation_results = self.validator.validate(self.root.getValue());
self.root.showValidationErrors(self.validation_results);
self.ready = true;
// Fire ready event asynchronously
window.requestAnimationFrame(function() {
if(!self.ready) return;
self.validation_results = self.validator.validate(self.root.getValue());
self.root.showValidationErrors(self.validation_results);
self.trigger('ready');
self.trigger('change');
});
});
},
getValue: function() {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before getting the value";
return this.root.getValue();
},
setValue: function(value) {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before setting the value";
this.root.setValue(value);
return this;
},
validate: function(value) {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before validating";
// Custom value
if(arguments.length === 1) {
return this.validator.validate(value);
}
// Current value (use cached result)
else {
return this.validation_results;
}
},
destroy: function() {
if(this.destroyed) return;
if(!this.ready) return;
this.schema = null;
this.options = null;
this.root.destroy();
this.root = null;
this.root_container = null;
this.validator = null;
this.validation_results = null;
this.theme = null;
this.iconlib = null;
this.template = null;
this.__data = null;
this.ready = false;
this.element.innerHTML = '';
this.destroyed = true;
},
on: function(event, callback) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = this.callbacks[event] || [];
this.callbacks[event].push(callback);
return this;
},
off: function(event, callback) {
// Specific callback
if(event && callback) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = this.callbacks[event] || [];
var newcallbacks = [];
for(var i=0; i<this.callbacks[event].length; i++) {
if(this.callbacks[event][i]===callback) continue;
newcallbacks.push(this.callbacks[event][i]);
}
this.callbacks[event] = newcallbacks;
}
// All callbacks for a specific event
else if(event) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = [];
}
// All callbacks for all events
else {
this.callbacks = {};
}
return this;
},
trigger: function(event) {
if(this.callbacks && this.callbacks[event] && this.callbacks[event].length) {
for(var i=0; i<this.callbacks[event].length; i++) {
this.callbacks[event][i]();
}
}
return this;
},
setOption: function(option, value) {
if(option === "show_errors") {
this.options.show_errors = value;
this.onChange();
}
// Only the `show_errors` option is supported for now
else {
throw "Option "+option+" must be set during instantiation and cannot be changed later";
}
return this;
},
getEditorClass: function(schema) {
var classname;
schema = this.expandSchema(schema);
$each(JSONEditor.defaults.resolvers,function(i,resolver) {
var tmp = resolver(schema);
if(tmp) {
if(JSONEditor.defaults.editors[tmp]) {
classname = tmp;
return false;
}
}
});
if(!classname) throw "Unknown editor for schema "+JSON.stringify(schema);
if(!JSONEditor.defaults.editors[classname]) throw "Unknown editor "+classname;
return JSONEditor.defaults.editors[classname];
},
createEditor: function(editor_class, options) {
options = $extend({},editor_class.options||{},options);
return new editor_class(options);
},
onChange: function() {
if(!this.ready) return;
if(this.firing_change) return;
this.firing_change = true;
var self = this;
window.requestAnimationFrame(function() {
self.firing_change = false;
if(!self.ready) return;
// Validate and cache results
self.validation_results = self.validator.validate(self.root.getValue());
if(self.options.show_errors !== "never") {
self.root.showValidationErrors(self.validation_results);
}
else {
self.root.showValidationErrors([]);
}
// Fire change event
self.trigger('change');
});
return this;
},
compileTemplate: function(template, name) {
name = name || JSONEditor.defaults.template;
var engine;
// Specifying a preset engine
if(typeof name === 'string') {
if(!JSONEditor.defaults.templates[name]) throw "Unknown template engine "+name;
engine = JSONEditor.defaults.templates[name]();
if(!engine) throw "Template engine "+name+" missing required library.";
}
// Specifying a custom engine
else {
engine = name;
}
if(!engine) throw "No template engine set";
if(!engine.compile) throw "Invalid template engine set";
return engine.compile(template);
},
_data: function(el,key,value) {
// Setting data
if(arguments.length === 3) {
var uuid;
if(el.hasAttribute('data-jsoneditor-'+key)) {
uuid = el.getAttribute('data-jsoneditor-'+key);
}
else {
uuid = this.uuid++;
el.setAttribute('data-jsoneditor-'+key,uuid);
}
this.__data[uuid] = value;
}
// Getting data
else {
// No data stored
if(!el.hasAttribute('data-jsoneditor-'+key)) return null;
return this.__data[el.getAttribute('data-jsoneditor-'+key)];
}
},
registerEditor: function(editor) {
this.editors = this.editors || {};
this.editors[editor.path] = editor;
return this;
},
unregisterEditor: function(editor) {
this.editors = this.editors || {};
this.editors[editor.path] = null;
return this;
},
getEditor: function(path) {
if(!this.editors) return;
return this.editors[path];
},
watch: function(path,callback) {
this.watchlist = this.watchlist || {};
this.watchlist[path] = this.watchlist[path] || [];
this.watchlist[path].push(callback);
return this;
},
unwatch: function(path,callback) {
if(!this.watchlist || !this.watchlist[path]) return this;
// If removing all callbacks for a path
if(!callback) {
this.watchlist[path] = null;
return this;
}
var newlist = [];
for(var i=0; i<this.watchlist[path].length; i++) {
if(this.watchlist[path][i] === callback) continue;
else newlist.push(this.watchlist[path][i]);
}
this.watchlist[path] = newlist.length? newlist : null;
return this;
},
notifyWatchers: function(path) {
if(!this.watchlist || !this.watchlist[path]) return this;
for(var i=0; i<this.watchlist[path].length; i++) {
this.watchlist[path][i]();
}
},
isEnabled: function() {
return !this.root || this.root.isEnabled();
},
enable: function() {
this.root.enable();
},
disable: function() {
this.root.disable();
},
_getDefinitions: function(schema,path) {
path = path || '#/definitions/';
if(schema.definitions) {
for(var i in schema.definitions) {
if(!schema.definitions.hasOwnProperty(i)) continue;
this.refs[path+i] = schema.definitions[i];
if(schema.definitions[i].definitions) {
this._getDefinitions(schema.definitions[i],path+i+'/definitions/');
}
}
}
},
_getExternalRefs: function(schema) {
var refs = {};
var merge_refs = function(newrefs) {
for(var i in newrefs) {
if(newrefs.hasOwnProperty(i)) {
refs[i] = true;
}
}
};
if(schema.$ref && typeof schema.$ref !== "object" && schema.$ref.substr(0,1) !== "#" && !this.refs[schema.$ref]) {
refs[schema.$ref] = true;
}
for(var i in schema) {
if(!schema.hasOwnProperty(i)) continue;
if(schema[i] && typeof schema[i] === "object" && Array.isArray(schema[i])) {
for(var j=0; j<schema[i].length; j++) {
if(typeof schema[i][j]==="object") {
merge_refs(this._getExternalRefs(schema[i][j]));
}
}
}
else if(schema[i] && typeof schema[i] === "object") {
merge_refs(this._getExternalRefs(schema[i]));
}
}
return refs;
},
_loadExternalRefs: function(schema, callback) {
var self = this;
var refs = this._getExternalRefs(schema);
var done = 0, waiting = 0, callback_fired = false;
$each(refs,function(url) {
if(self.refs[url]) return;
if(!self.options.ajax) throw "Must set ajax option to true to load external ref "+url;
self.refs[url] = 'loading';
waiting++;
var r = new XMLHttpRequest();
r.open("GET", url, true);
r.onreadystatechange = function () {
if (r.readyState != 4) return;
// Request succeeded
if(r.status === 200) {
var response;
try {
response = JSON.parse(r.responseText);
}
catch(e) {
window.console.log(e);
throw "Failed to parse external ref "+url;
}
if(!response || typeof response !== "object") throw "External ref does not contain a valid schema - "+url;
self.refs[url] = response;
self._loadExternalRefs(response,function() {
done++;
if(done >= waiting && !callback_fired) {
callback_fired = true;
callback();
}
});
}
// Request failed
else {
window.console.log(r);
throw "Failed to fetch ref via ajax- "+url;
}
};
r.send();
});
if(!waiting) {
callback();
}
},
expandRefs: function(schema) {
schema = $extend({},schema);
while (schema.$ref) {
var ref = schema.$ref;
delete schema.$ref;
if(!this.refs[ref]) ref = decodeURIComponent(ref);
schema = this.extendSchemas(schema,this.refs[ref]);
}
return schema;
},
expandSchema: function(schema) {
var self = this;
var extended = $extend({},schema);
var i;
// Version 3 `type`
if(typeof schema.type === 'object') {
// Array of types
if(Array.isArray(schema.type)) {
$each(schema.type, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.type[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.type = self.expandSchema(schema.type);
}
}
// Version 3 `disallow`
if(typeof schema.disallow === 'object') {
// Array of types
if(Array.isArray(schema.disallow)) {
$each(schema.disallow, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.disallow[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.disallow = self.expandSchema(schema.disallow);
}
}
// Version 4 `anyOf`
if(schema.anyOf) {
$each(schema.anyOf, function(key,value) {
schema.anyOf[key] = self.expandSchema(value);
});
}
// Version 4 `dependencies` (schema dependencies)
if(schema.dependencies) {
$each(schema.dependencies,function(key,value) {
if(typeof value === "object" && !(Array.isArray(value))) {
schema.dependencies[key] = self.expandSchema(value);
}
});
}
// Version 4 `not`
if(schema.not) {
schema.not = this.expandSchema(schema.not);
}
// allOf schemas should be merged into the parent
if(schema.allOf) {
for(i=0; i<schema.allOf.length; i++) {
extended = this.extendSchemas(extended,this.expandSchema(schema.allOf[i]));
}
delete extended.allOf;
}
// extends schemas should be merged into parent
if(schema["extends"]) {
// If extends is a schema
if(!(Array.isArray(schema["extends"]))) {
extended = this.extendSchemas(extended,this.expandSchema(schema["extends"]));
}
// If extends is an array of schemas
else {
for(i=0; i<schema["extends"].length; i++) {
extended = this.extendSchemas(extended,this.expandSchema(schema["extends"][i]));
}
}
delete extended["extends"];
}
// parent should be merged into oneOf schemas
if(schema.oneOf) {
var tmp = $extend({},extended);
delete tmp.oneOf;
for(i=0; i<schema.oneOf.length; i++) {
extended.oneOf[i] = this.extendSchemas(this.expandSchema(schema.oneOf[i]),tmp);
}
}
return this.expandRefs(extended);
},
extendSchemas: function(obj1, obj2) {
obj1 = $extend({},obj1);
obj2 = $extend({},obj2);
var self = this;
var extended = {};
$each(obj1, function(prop,val) {
// If this key is also defined in obj2, merge them
if(typeof obj2[prop] !== "undefined") {
// Required and defaultProperties arrays should be unioned together
if((prop === 'required'||prop === 'defaultProperties') && typeof val === "object" && Array.isArray(val)) {
// Union arrays and unique
extended[prop] = val.concat(obj2[prop]).reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
}
// Type should be intersected and is either an array or string
else if(prop === 'type' && (typeof val === "string" || Array.isArray(val))) {
// Make sure we're dealing with arrays
if(typeof val === "string") val = [val];
if(typeof obj2.type === "string") obj2.type = [obj2.type];
// If type is only defined in the first schema, keep it
if(!obj2.type || !obj2.type.length) {
extended.type = val;
}
// If type is defined in both schemas, do an intersect
else {
extended.type = val.filter(function(n) {
return obj2.type.indexOf(n) !== -1;
});
}
// If there's only 1 type and it's a primitive, use a string instead of array
if(extended.type.length === 1 && typeof extended.type[0] === "string") {
extended.type = extended.type[0];
}
// Remove the type property if it's empty
else if(extended.type.length === 0) {
delete extended.type;
}
}
// All other arrays should be intersected (enum, etc.)
else if(typeof val === "object" && Array.isArray(val)){
extended[prop] = val.filter(function(n) {
return obj2[prop].indexOf(n) !== -1;
});
}
// Objects should be recursively merged
else if(typeof val === "object" && val !== null) {
extended[prop] = self.extendSchemas(val,obj2[prop]);
}
// Otherwise, use the first value
else {
extended[prop] = val;
}
}
// Otherwise, just use the one in obj1
else {
extended[prop] = val;
}
});
// Properties in obj2 that aren't in obj1
$each(obj2, function(prop,val) {
if(typeof obj1[prop] === "undefined") {
extended[prop] = val;
}
});
return extended;
}
};
JSONEditor.defaults = {
themes: {},
templates: {},
iconlibs: {},
editors: {},
languages: {},
resolvers: [],
custom_validators: []
};
JSONEditor.Validator = Class.extend({
init: function(jsoneditor,schema,options) {
this.jsoneditor = jsoneditor;
this.schema = schema || this.jsoneditor.schema;
this.options = options || {};
this.translate = this.jsoneditor.translate || JSONEditor.defaults.translate;
},
validate: function(value) {
return this._validateSchema(this.schema, value);
},
_validateSchema: function(schema,value,path) {
var self = this;
var errors = [];
var valid, i, j;
var stringified = JSON.stringify(value);
path = path || 'root';
// Work on a copy of the schema
schema = $extend({},this.jsoneditor.expandRefs(schema));
/*
* Type Agnostic Validation
*/
// Version 3 `required`
if(schema.required && schema.required === true) {
if(typeof value === "undefined") {
errors.push({
path: path,
property: 'required',
message: this.translate("edt_msg_error_notset")
});
// Can't do any more validation at this point
return errors;
}
}
// Value not defined
else if(typeof value === "undefined") {
// If required_by_default is set, all fields are required
if(this.jsoneditor.options.required_by_default) {
errors.push({
path: path,
property: 'required',
message: this.translate("edt_msg_error_notset")
});
}
// Not required, no further validation needed
else {
return errors;
}
}
// `enum`
if(schema["enum"]) {
valid = false;
for(i=0; i<schema["enum"].length; i++) {
if(stringified === JSON.stringify(schema["enum"][i])) valid = true;
}
if(!valid) {
errors.push({
path: path,
property: 'enum',
message: this.translate("edt_msg_error_enum")
});
}
}
// `extends` (version 3)
if(schema["extends"]) {
for(i=0; i<schema["extends"].length; i++) {
errors = errors.concat(this._validateSchema(schema["extends"][i],value,path));
}
}
// `allOf`
if(schema.allOf) {
for(i=0; i<schema.allOf.length; i++) {
errors = errors.concat(this._validateSchema(schema.allOf[i],value,path));
}
}
// `anyOf`
if(schema.anyOf) {
valid = false;
for(i=0; i<schema.anyOf.length; i++) {
if(!this._validateSchema(schema.anyOf[i],value,path).length) {
valid = true;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'anyOf',
message: this.translate('edt_msg_error_anyOf')
});
}
}
// `oneOf`
if(schema.oneOf) {
valid = 0;
var oneof_errors = [];
for(i=0; i<schema.oneOf.length; i++) {
// Set the error paths to be path.oneOf[i].rest.of.path
var tmp = this._validateSchema(schema.oneOf[i],value,path);
if(!tmp.length) {
valid++;
}
for(j=0; j<tmp.length; j++) {
tmp[j].path = path+'.oneOf['+i+']'+tmp[j].path.substr(path.length);
}
oneof_errors = oneof_errors.concat(tmp);
}
if(valid !== 1) {
errors.push({
path: path,
property: 'oneOf',
message: this.translate('edt_msg_error_oneOf', [valid])
});
errors = errors.concat(oneof_errors);
}
}
// `not`
if(schema.not) {
if(!this._validateSchema(schema.not,value,path).length) {
errors.push({
path: path,
property: 'not',
message: this.translate('edt_msg_error_not')
});
}
}
// `type` (both Version 3 and Version 4 support)
if(schema.type) {
// Union type
if(Array.isArray(schema.type)) {
valid = false;
for(i=0;i<schema.type.length;i++) {
if(this._checkType(schema.type[i], value)) {
valid = true;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'type',
message: this.translate('edt_msg_error_type_union')
});
}
}
// Simple type
else {
if(!this._checkType(schema.type, value)) {
errors.push({
path: path,
property: 'type',
message: this.translate('edt_msg_error_type', [schema.type])
});
}
}
}
// `disallow` (version 3)
if(schema.disallow) {
// Union type
if(Array.isArray(schema.disallow)) {
valid = true;
for(i=0;i<schema.disallow.length;i++) {
if(this._checkType(schema.disallow[i], value)) {
valid = false;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'disallow',
message: this.translate('edt_msg_error_disallow_union')
});
}
}
// Simple type
else {
if(this._checkType(schema.disallow, value)) {
errors.push({
path: path,
property: 'disallow',
message: this.translate('edt_msg_error_disallow', [schema.disallow])
});
}
}
}
/*
* Type Specific Validation
*/
// Number Specific Validation
if(typeof value === "number") {
// `multipleOf` and `divisibleBy`
if(schema.multipleOf || schema.divisibleBy) {
var divisor = schema.multipleOf || schema.divisibleBy;
// Vanilla JS, prone to floating point rounding errors (e.g. 1.14 / .01 == 113.99999)
valid = (value/divisor === Math.floor(value/divisor));
// Use math.js is available
if(window.math) {
valid = window.math.mod(window.math.bignumber(value), window.math.bignumber(divisor)).equals(0);
}
// Use decimal.js is available
else if(window.Decimal) {
valid = (new window.Decimal(value)).mod(new window.Decimal(divisor)).equals(0);
}
if(!valid) {
errors.push({
path: path,
property: schema.multipleOf? 'multipleOf' : 'divisibleBy',
message: this.translate('edt_msg_error_multipleOf', [divisor])
});
}
}
// `maximum`
if(schema.hasOwnProperty('maximum')) {
// Vanilla JS, prone to floating point rounding errors (e.g. .999999999999999 == 1)
valid = schema.exclusiveMaximum? (value < schema.maximum) : (value <= schema.maximum);
// Use math.js is available
if(window.math) {
valid = window.math[schema.exclusiveMaximum?'smaller':'smallerEq'](
window.math.bignumber(value),
window.math.bignumber(schema.maximum)
);
}
// Use Decimal.js if available
else if(window.Decimal) {
valid = (new window.Decimal(value))[schema.exclusiveMaximum?'lt':'lte'](new window.Decimal(schema.maximum));
}
if(!valid) {
errors.push({
path: path,
property: 'maximum',
message: this.translate(
(schema.exclusiveMaximum?'edt_msg_error_maximum_excl':'edt_msg_error_maximum_incl'),
[schema.maximum]
)
});
}
}
// `minimum`
if(schema.hasOwnProperty('minimum')) {
// Vanilla JS, prone to floating point rounding errors (e.g. .999999999999999 == 1)
valid = schema.exclusiveMinimum? (value > schema.minimum) : (value >= schema.minimum);
// Use math.js is available
if(window.math) {
valid = window.math[schema.exclusiveMinimum?'larger':'largerEq'](
window.math.bignumber(value),
window.math.bignumber(schema.minimum)
);
}
// Use Decimal.js if available
else if(window.Decimal) {
valid = (new window.Decimal(value))[schema.exclusiveMinimum?'gt':'gte'](new window.Decimal(schema.minimum));
}
if(!valid) {
errors.push({
path: path,
property: 'minimum',
message: this.translate(
(schema.exclusiveMinimum?'edt_msg_error_minimum_excl':'edt_msg_error_minimum_incl'),
[schema.minimum]
)
});
}
}
}
// String specific validation
else if(typeof value === "string") {
// `maxLength`
if(schema.maxLength) {
if((value+"").length > schema.maxLength) {
errors.push({
path: path,
property: 'maxLength',
message: this.translate('edt_msg_error_maxLength', [schema.maxLength])
});
}
}
// `minLength`
if(schema.minLength) {
if((value+"").length < schema.minLength) {
errors.push({
path: path,
property: 'minLength',
message: this.translate((schema.minLength===1?'edt_msg_error_notempty':'edt_msg_error_minLength'), [schema.minLength])
});
}
}
// `pattern`
if(schema.pattern) {
if(!(new RegExp(schema.pattern)).test(value)) {
errors.push({
path: path,
property: 'pattern',
message: this.translate('edt_msg_error_pattern', [schema.pattern])
});
}
}
}
// Array specific validation
else if(typeof value === "object" && value !== null && Array.isArray(value)) {
// `items` and `additionalItems`
if(schema.items) {
// `items` is an array
if(Array.isArray(schema.items)) {
for(i=0; i<value.length; i++) {
// If this item has a specific schema tied to it
// Validate against it
if(schema.items[i]) {
errors = errors.concat(this._validateSchema(schema.items[i],value[i],path+'.'+i));
}
// If all additional items are allowed
else if(schema.additionalItems === true) {
break;
}
// If additional items is a schema
// TODO: Incompatibility between version 3 and 4 of the spec
else if(schema.additionalItems) {
errors = errors.concat(this._validateSchema(schema.additionalItems,value[i],path+'.'+i));
}
// If no additional items are allowed
else if(schema.additionalItems === false) {
errors.push({
path: path,
property: 'additionalItems',
message: this.translate('edt_msg_error_additionalItems')
});
break;
}
// Default for `additionalItems` is an empty schema
else {
break;
}
}
}
// `items` is a schema
else {
// Each item in the array must validate against the schema
for(i=0; i<value.length; i++) {
errors = errors.concat(this._validateSchema(schema.items,value[i],path+'.'+i));
}
}
}
// `maxItems`
if(schema.maxItems) {
if(value.length > schema.maxItems) {
errors.push({
path: path,
property: 'maxItems',
message: this.translate('edt_msg_error_maxItems', [schema.maxItems])
});
}
}
// `minItems`
if(schema.minItems) {
if(value.length < schema.minItems) {
errors.push({
path: path,
property: 'minItems',
message: this.translate('edt_msg_error_minItems', [schema.minItems])
});
}
}
// `uniqueItems`
if(schema.uniqueItems) {
var seen = {};
for(i=0; i<value.length; i++) {
valid = JSON.stringify(value[i]);
if(seen[valid]) {
errors.push({
path: path,
property: 'uniqueItems',
message: this.translate('edt_msg_error_uniqueItems')
});
break;
}
seen[valid] = true;
}
}
}
// Object specific validation
else if(typeof value === "object" && value !== null) {
// `maxProperties`
if(schema.maxProperties) {
valid = 0;
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
valid++;
}
if(valid > schema.maxProperties) {
errors.push({
path: path,
property: 'maxProperties',
message: this.translate('edt_msg_error_maxProperties', [schema.maxProperties])
});
}
}
// `minProperties`
if(schema.minProperties) {
valid = 0;
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
valid++;
}
if(valid < schema.minProperties) {
errors.push({
path: path,
property: 'minProperties',
message: this.translate('edt_msg_error_minProperties', [schema.minProperties])
});
}
}
// Version 4 `required`
if(schema.required && Array.isArray(schema.required)) {
for(i=0; i<schema.required.length; i++) {
if(typeof value[schema.required[i]] === "undefined") {
errors.push({
path: path,
property: 'required',
message: this.translate('edt_msg_error_required', [schema.required[i]])
});
}
}
}
// `properties`
var validated_properties = {};
if(schema.properties) {
for(i in schema.properties) {
if(!schema.properties.hasOwnProperty(i)) continue;
validated_properties[i] = true;
errors = errors.concat(this._validateSchema(schema.properties[i],value[i],path+'.'+i));
}
}
// `patternProperties`
if(schema.patternProperties) {
for(i in schema.patternProperties) {
if(!schema.patternProperties.hasOwnProperty(i)) continue;
var regex = new RegExp(i);
// Check which properties match
for(j in value) {
if(!value.hasOwnProperty(j)) continue;
if(regex.test(j)) {
validated_properties[j] = true;
errors = errors.concat(this._validateSchema(schema.patternProperties[i],value[j],path+'.'+j));
}
}
}
}
// The no_additional_properties option currently doesn't work with extended schemas that use oneOf or anyOf
if(typeof schema.additionalProperties === "undefined" && this.jsoneditor.options.no_additional_properties && !schema.oneOf && !schema.anyOf) {
schema.additionalProperties = false;
}
// `additionalProperties`
if(typeof schema.additionalProperties !== "undefined") {
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
if(!validated_properties[i]) {
// No extra properties allowed
if(!schema.additionalProperties) {
errors.push({
path: path,
property: 'additionalProperties',
message: this.translate('edt_msg_error_additional_properties', [i])
});
break;
}
// Allowed
else if(schema.additionalProperties === true) {
break;
}
// Must match schema
// TODO: incompatibility between version 3 and 4 of the spec
else {
errors = errors.concat(this._validateSchema(schema.additionalProperties,value[i],path+'.'+i));
}
}
}
}
// `dependencies`
if(schema.dependencies) {
for(i in schema.dependencies) {
if(!schema.dependencies.hasOwnProperty(i)) continue;
// Doesn't need to meet the dependency
if(typeof value[i] === "undefined") continue;
// Property dependency
if(Array.isArray(schema.dependencies[i])) {
for(j=0; j<schema.dependencies[i].length; j++) {
if(typeof value[schema.dependencies[i][j]] === "undefined") {
errors.push({
path: path,
property: 'dependencies',
message: this.translate('edt_msg_error_dependency', [schema.dependencies[i][j]])
});
}
}
}
// Schema dependency
else {
errors = errors.concat(this._validateSchema(schema.dependencies[i],value,path));
}
}
}
}
// Custom type validation (global)
$each(JSONEditor.defaults.custom_validators,function(i,validator) {
errors = errors.concat(validator.call(self,schema,value,path));
});
// Custom type validation (instance specific)
if(this.options.custom_validators) {
$each(this.options.custom_validators,function(i,validator) {
errors = errors.concat(validator.call(self,schema,value,path));
});
}
return errors;
},
_checkType: function(type, value) {
// Simple types
if(typeof type === "string") {
if(type==="string") return typeof value === "string";
else if(type==="number") return typeof value === "number";
else if(type==="integer") return typeof value === "number" && value === Math.floor(value);
else if(type==="boolean") return typeof value === "boolean";
else if(type==="array") return Array.isArray(value);
else if(type === "object") return value !== null && !(Array.isArray(value)) && typeof value === "object";
else if(type === "null") return value === null;
else return true;
}
// Schema
else {
return !this._validateSchema(type,value).length;
}
}
});
/**
* All editors should extend from this class
*/
JSONEditor.AbstractEditor = Class.extend({
onChildEditorChange: function(editor) {
this.onChange(true);
},
notify: function() {
this.jsoneditor.notifyWatchers(this.path);
},
change: function() {
if(this.parent) this.parent.onChildEditorChange(this);
else this.jsoneditor.onChange();
},
onChange: function(bubble) {
this.notify();
if(this.watch_listener) this.watch_listener();
if(bubble) this.change();
},
register: function() {
this.jsoneditor.registerEditor(this);
this.onChange();
},
unregister: function() {
if(!this.jsoneditor) return;
this.jsoneditor.unregisterEditor(this);
},
getNumColumns: function() {
return 12;
},
init: function(options) {
this.jsoneditor = options.jsoneditor;
this.theme = this.jsoneditor.theme;
this.template_engine = this.jsoneditor.template;
this.iconlib = this.jsoneditor.iconlib;
this.translate = this.jsoneditor.translate || JSONEditor.defaults.translate;
this.original_schema = options.schema;
this.schema = this.jsoneditor.expandSchema(this.original_schema);
this.options = $extend({}, (this.options || {}), (options.schema.options || {}), options);
if(!options.path && !this.schema.id) this.schema.id = 'root';
this.path = options.path || 'root';
this.formname = options.formname || this.path.replace(/\.([^.]+)/g,'_$1');
if(this.jsoneditor.options.form_name_root) this.formname = this.formname.replace(/^root\[/,this.jsoneditor.options.form_name_root+'[');
this.key = this.path.split('.').pop();
this.parent = options.parent;
this.link_watchers = [];
if(options.container) this.setContainer(options.container);
},
setContainer: function(container) {
this.container = container;
if(this.schema.id) this.container.setAttribute('data-schemaid',this.schema.id);
if(this.schema.type && typeof this.schema.type === "string") this.container.setAttribute('data-schematype',this.schema.type);
this.container.setAttribute('data-schemapath',this.path);
},
preBuild: function() {
},
build: function() {
},
postBuild: function() {
this.setupWatchListeners();
this.addLinks();
this.setValue(this.getDefault(), true);
this.updateHeaderText();
this.register();
this.onWatchedFieldChange();
//hide input field, if it didn't match the current access level
var storedAccess = localStorage.getItem("accesslevel");
if(this.schema.access){
if(this.schema.access == 'system')
this.container.style.display = "none";
if(this.schema.access == 'expert' && storedAccess != 'expert'){
this.container.style.display = "none";
//this.disable();
}
}
},
setupWatchListeners: function() {
var self = this;
// Watched fields
this.watched = {};
if(this.schema.vars) this.schema.watch = this.schema.vars;
this.watched_values = {};
this.watch_listener = function() {
if(self.refreshWatchedFieldValues()) {
self.onWatchedFieldChange();
}
};
this.register();
if(this.schema.hasOwnProperty('watch')) {
var path,path_parts,first,root,adjusted_path;
for(var name in this.schema.watch) {
if(!this.schema.watch.hasOwnProperty(name)) continue;
path = this.schema.watch[name];
if(Array.isArray(path)) {
if(path.length<2) continue;
path_parts = [path[0]].concat(path[1].split('.'));
}
else {
path_parts = path.split('.');
if(!self.theme.closest(self.container,'[data-schemaid="'+path_parts[0]+'"]')) path_parts.unshift('#');
}
first = path_parts.shift();
if(first === '#') first = self.jsoneditor.schema.id || 'root';
// Find the root node for this template variable
root = self.theme.closest(self.container,'[data-schemaid="'+first+'"]');
if(!root) throw "Could not find ancestor node with id "+first;
// Keep track of the root node and path for use when rendering the template
adjusted_path = root.getAttribute('data-schemapath') + '.' + path_parts.join('.');
self.jsoneditor.watch(adjusted_path,self.watch_listener);
self.watched[name] = adjusted_path;
}
}
// Dynamic header
if(this.schema.headerTemplate) {
this.header_template = this.jsoneditor.compileTemplate(this.schema.headerTemplate, this.template_engine);
}
},
addLinks: function() {
// Add links
if(!this.no_link_holder) {
this.link_holder = this.theme.getLinksHolder();
this.container.appendChild(this.link_holder);
if(this.schema.links) {
for(var i=0; i<this.schema.links.length; i++) {
this.addLink(this.getLink(this.schema.links[i]));
}
}
}
},
getButton: function(text, icon, title) {
var btnClass = 'json-editor-btn-'+icon;
if(!this.iconlib) icon = null;
else icon = this.iconlib.getIcon(icon);
if(!icon && title) {
text = title;
title = null;
}
var btn = this.theme.getButton(text, icon, title);
btn.className += ' ' + btnClass + ' ';
return btn;
},
setButtonText: function(button, text, icon, title) {
if(!this.iconlib) icon = null;
else icon = this.iconlib.getIcon(icon);
if(!icon && title) {
text = title;
title = null;
}
return this.theme.setButtonText(button, text, icon, title);
},
addLink: function(link) {
if(this.link_holder) this.link_holder.appendChild(link);
},
getLink: function(data) {
var holder, link;
// Get mime type of the link
var mime = data.mediaType || 'application/javascript';
var type = mime.split('/')[0];
// Template to generate the link href
var href = this.jsoneditor.compileTemplate(data.href,this.template_engine);
// Template to generate the link's download attribute
var download = null;
if(data.download) download = data.download;
if(download && download !== true) {
download = this.jsoneditor.compileTemplate(download, this.template_engine);
}
// Image links
if(type === 'image') {
holder = this.theme.getBlockLinkHolder();
link = document.createElement('a');
link.setAttribute('target','_blank');
var image = document.createElement('img');
this.theme.createImageLink(holder,link,image);
// When a watched field changes, update the url
this.link_watchers.push(function(vars) {
var url = href(vars);
link.setAttribute('href',url);
link.setAttribute('title',data.rel || url);
image.setAttribute('src',url);
});
}
// Audio/Video links
else if(['audio','video'].indexOf(type) >=0) {
holder = this.theme.getBlockLinkHolder();
link = this.theme.getBlockLink();
link.setAttribute('target','_blank');
var media = document.createElement(type);
media.setAttribute('controls','controls');
this.theme.createMediaLink(holder,link,media);
// When a watched field changes, update the url
this.link_watchers.push(function(vars) {
var url = href(vars);
link.setAttribute('href',url);
link.textContent = data.rel || url;
media.setAttribute('src',url);
});
}
// Text links
else {
link = holder = this.theme.getBlockLink();
holder.setAttribute('target','_blank');
holder.textContent = data.rel;
// When a watched field changes, update the url
this.link_watchers.push(function(vars) {
var url = href(vars);
holder.setAttribute('href',url);
holder.textContent = data.rel || url;
});
}
if(download && link) {
if(download === true) {
link.setAttribute('download','');
}
else {
this.link_watchers.push(function(vars) {
link.setAttribute('download',download(vars));
});
}
}
if(data.class) link.className = link.className + ' ' + data.class;
return holder;
},
refreshWatchedFieldValues: function() {
if(!this.watched_values) return;
var watched = {};
var changed = false;
var self = this;
if(this.watched) {
var val,editor;
for(var name in this.watched) {
if(!this.watched.hasOwnProperty(name)) continue;
editor = self.jsoneditor.getEditor(this.watched[name]);
val = editor? editor.getValue() : null;
if(self.watched_values[name] !== val) changed = true;
watched[name] = val;
}
}
watched.self = this.getValue();
if(this.watched_values.self !== watched.self) changed = true;
this.watched_values = watched;
return changed;
},
getWatchedFieldValues: function() {
return this.watched_values;
},
updateHeaderText: function() {
if(this.header) {
// If the header has children, only update the text node's value
if(this.header.children.length) {
for(var i=0; i<this.header.childNodes.length; i++) {
if(this.header.childNodes[i].nodeType===3) {
this.header.childNodes[i].nodeValue = this.getHeaderText();
break;
}
}
}
// Otherwise, just update the entire node
else {
this.header.textContent = this.getHeaderText();
}
}
},
getHeaderText: function(title_only) {
if(this.header_text) return this.header_text;
else if(title_only) return this.schema.title;
else return this.getTitle();
},
onWatchedFieldChange: function() {
var vars;
if(this.header_template) {
vars = $extend(this.getWatchedFieldValues(),{
key: this.key,
i: this.key,
i0: (this.key*1),
i1: (this.key*1+1),
title: this.getTitle()
});
var header_text = this.header_template(vars);
if(header_text !== this.header_text) {
this.header_text = header_text;
this.updateHeaderText();
this.notify();
//this.fireChangeHeaderEvent();
}
}
if(this.link_watchers.length) {
vars = this.getWatchedFieldValues();
for(var i=0; i<this.link_watchers.length; i++) {
this.link_watchers[i](vars);
}
}
},
setValue: function(value) {
this.value = value;
},
getValue: function() {
return this.value;
},
refreshValue: function() {
},
getChildEditors: function() {
return false;
},
destroy: function() {
var self = this;
this.unregister(this);
$each(this.watched,function(name,adjusted_path) {
self.jsoneditor.unwatch(adjusted_path,self.watch_listener);
});
this.watched = null;
this.watched_values = null;
this.watch_listener = null;
this.header_text = null;
this.header_template = null;
this.value = null;
if(this.container && this.container.parentNode) this.container.parentNode.removeChild(this.container);
this.container = null;
this.jsoneditor = null;
this.schema = null;
this.path = null;
this.key = null;
this.parent = null;
},
getDefault: function() {
if(this.schema["default"]) return this.schema["default"];
if(this.schema["enum"]) return this.schema["enum"][0];
var type = this.schema.type || this.schema.oneOf;
if(type && Array.isArray(type)) type = type[0];
if(type && typeof type === "object") type = type.type;
if(type && Array.isArray(type)) type = type[0];
if(typeof type === "string") {
if(type === "number") return 0.0;
if(type === "boolean") return false;
if(type === "integer") return 0;
if(type === "string") return "";
if(type === "object") return {};
if(type === "array") return [];
}
return null;
},
getTitle: function() {
if (this.schema.title == null)
return this.key;
else
return $.i18n(this.schema.title);
},
getAppend: function() {
return $.i18n(this.schema.append);
},
enable: function() {
this.disabled = false;
},
disable: function() {
this.disabled = true;
},
isEnabled: function() {
return !this.disabled;
},
isRequired: function() {
if(typeof this.schema.required === "boolean") return this.schema.required;
else if(this.parent && this.parent.schema && Array.isArray(this.parent.schema.required)) return this.parent.schema.required.indexOf(this.key) > -1;
else if(this.jsoneditor.options.required_by_default) return true;
else return true;
},
getDisplayText: function(arr) {
var disp = [];
var used = {};
// Determine how many times each attribute name is used.
// This helps us pick the most distinct display text for the schemas.
$each(arr,function(i,el) {
if(el.title) {
used[el.title] = used[el.title] || 0;
used[el.title]++;
}
if(el.description) {
used[el.description] = used[el.description] || 0;
used[el.description]++;
}
if(el.format) {
used[el.format] = used[el.format] || 0;
used[el.format]++;
}
if(el.type) {
used[el.type] = used[el.type] || 0;
used[el.type]++;
}
});
// Determine display text for each element of the array
$each(arr,function(i,el) {
var name;
// If it's a simple string
if(typeof el === "string") name = el;
// Object
else if(el.title && used[el.title]<=1) name = el.title;
else if(el.format && used[el.format]<=1) name = el.format;
else if(el.type && used[el.type]<=1) name = el.type;
else if(el.description && used[el.description]<=1) name = el.descripton;
else if(el.title) name = el.title;
else if(el.format) name = el.format;
else if(el.type) name = el.type;
else if(el.description) name = el.description;
else if(JSON.stringify(el).length < 50) name = JSON.stringify(el);
else name = "type";
disp.push(name);
});
// Replace identical display text with "text 1", "text 2", etc.
var inc = {};
$each(disp,function(i,name) {
inc[name] = inc[name] || 0;
inc[name]++;
if(used[name] > 1) disp[i] = name + " " + inc[name];
});
return disp;
},
getOption: function(key) {
try {
throw "getOption is deprecated";
}
catch(e) {
window.console.error(e);
}
return this.options[key];
},
showValidationErrors: function(errors) {
}
});
JSONEditor.defaults.editors["null"] = JSONEditor.AbstractEditor.extend({
getValue: function() {
return null;
},
setValue: function() {
this.onChange();
},
getNumColumns: function() {
return 2;
}
});
JSONEditor.defaults.editors.string = JSONEditor.AbstractEditor.extend({
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('id',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('id');
},
setValue: function(value,initial,from_template) {
var self = this;
if(this.template && !from_template) {
return;
}
if(value === null || typeof value === 'undefined') value = "";
else if(typeof value === "object") value = JSON.stringify(value);
else if(typeof value !== "string") value = ""+value;
if(value === this.serialized) return;
// Sanitize value before setting it
var sanitized = this.sanitize(value);
if(this.input.value === sanitized) {
return;
}
this.input.value = sanitized;
// If using SCEditor, update the WYSIWYG
if(this.sceditor_instance) {
this.sceditor_instance.val(sanitized);
}
else if(this.epiceditor) {
this.epiceditor.importFile(null,sanitized);
}
else if(this.ace_editor) {
this.ace_editor.setValue(sanitized);
}
var changed = from_template || this.getValue() !== value;
this.refreshValue();
if(initial) this.is_dirty = false;
else if(this.jsoneditor.options.show_errors === "change") this.is_dirty = true;
if(this.adjust_height) this.adjust_height(this.input);
// Bubble this setValue to parents if the value changed
this.onChange(changed);
},
getNumColumns: function() {
var min = Math.ceil(Math.max(this.getTitle().length,this.schema.maxLength||0,this.schema.minLength||0)/5);
var num;
if(this.input_type === 'textarea') num = 6;
else if(['text','email'].indexOf(this.input_type) >= 0) num = 4;
else num = 2;
return Math.min(12,Math.max(min,num));
},
build: function() {
var self = this, i;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.schema.append) this.append = this.theme.getFormInputAppend(this.getAppend());
this.placeholder = this.schema.default;
this.format = this.schema.format;
if(!this.format && this.schema.media && this.schema.media.type) {
this.format = this.schema.media.type.replace(/(^(application|text)\/(x-)?(script\.)?)|(-source$)/g,'');
}
if(!this.format && this.options.default_format) {
this.format = this.options.default_format;
}
if(this.options.format) {
this.format = this.options.format;
}
// Specific format
if(this.format) {
// Text Area
if(this.format === 'textarea') {
this.input_type = 'textarea';
this.input = this.theme.getTextareaInput();
}
// Range Input
else if(this.format === 'range') {
this.input_type = 'range';
var min = this.schema.minimum || 0;
var max = this.schema.maximum || Math.max(100,min+1);
var step = 1;
if(this.schema.multipleOf) {
if(min%this.schema.multipleOf) min = Math.ceil(min/this.schema.multipleOf)*this.schema.multipleOf;
if(max%this.schema.multipleOf) max = Math.floor(max/this.schema.multipleOf)*this.schema.multipleOf;
step = this.schema.multipleOf;
}
this.input = this.theme.getRangeInput(min,max,step);
}
// Source Code
else if([
'actionscript',
'batchfile',
'bbcode',
'c',
'c++',
'cpp',
'coffee',
'csharp',
'css',
'dart',
'django',
'ejs',
'erlang',
'golang',
'groovy',
'handlebars',
'haskell',
'haxe',
'html',
'ini',
'jade',
'java',
'javascript',
'json',
'less',
'lisp',
'lua',
'makefile',
'markdown',
'matlab',
'mysql',
'objectivec',
'pascal',
'perl',
'pgsql',
'php',
'python',
'r',
'ruby',
'sass',
'scala',
'scss',
'smarty',
'sql',
'stylus',
'svg',
'twig',
'vbscript',
'xml',
'yaml'
].indexOf(this.format) >= 0
) {
this.input_type = this.format;
this.source_code = true;
this.input = this.theme.getTextareaInput();
}
// HTML5 Input type
else {
this.input_type = this.format;
this.input = this.theme.getFormInputField(this.input_type);
}
}
// Number or integer adds html5 tag 'number'
else if (this.schema.type == "number" || this.schema.type == "integer"){
var min = this.schema.minimum
var max = this.schema.maximum
var step = this.schema.step
this.input = this.theme.getRangeInput(min,max,step);
}
// Normal text input
else {
this.input_type = 'text';
this.input = this.theme.getFormInputField(this.input_type);
}
// minLength, maxLength, and pattern
if(typeof this.schema.maxLength !== "undefined") this.input.setAttribute('maxlength',this.schema.maxLength);
if(typeof this.schema.pattern !== "undefined") this.input.setAttribute('pattern',this.schema.pattern);
else if(typeof this.schema.minLength !== "undefined") this.input.setAttribute('pattern','.{'+this.schema.minLength+',}');
if(this.options.compact) {
this.container.className += ' compact';
}
else {
if(this.options.input_width) this.input.style.width = this.options.input_width;
}
if(this.schema.readOnly || this.schema.readonly || this.schema.template) {
this.always_disabled = true;
this.input.disabled = true;
}
this.input
.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
// Don't allow changing if this field is a template
if(self.schema.template) {
this.value = self.value;
return;
}
var val = this.value;
// sanitize value
var sanitized = self.sanitize(val);
if(val !== sanitized) {
this.value = sanitized;
}
self.is_dirty = true;
self.refreshValue();
self.onChange(true);
});
if(this.options.input_height) this.input.style.height = this.options.input_height;
if(this.options.expand_height) {
this.adjust_height = function(el) {
if(!el) return;
var i, ch=el.offsetHeight;
// Input too short
if(el.offsetHeight < el.scrollHeight) {
i=0;
while(el.offsetHeight < el.scrollHeight+3) {
if(i>100) break;
i++;
ch++;
el.style.height = ch+'px';
}
}
else {
i=0;
while(el.offsetHeight >= el.scrollHeight+3) {
if(i>100) break;
i++;
ch--;
el.style.height = ch+'px';
}
el.style.height = (ch+1)+'px';
}
};
this.input.addEventListener('keyup',function(e) {
self.adjust_height(this);
});
this.input.addEventListener('change',function(e) {
self.adjust_height(this);
});
this.adjust_height();
}
if(this.format) this.input.setAttribute('data-schemaformat',this.format);
if(this.defaultValue) this.input.setAttribute('data-schemaformat',this.format);
if(this.formname)this.label.setAttribute('for',this.formname);
this.control = this.theme.getFormControl(this.label, this.input, this.description, this.append, this.placeholder);
this.container.appendChild(this.control);
// Any special formatting that needs to happen after the input is added to the dom
window.requestAnimationFrame(function() {
// Skip in case the input is only a temporary editor,
// otherwise, in the case of an ace_editor creation,
// it will generate an error trying to append it to the missing parentNode
if(self.input.parentNode) self.afterInputReady();
if(self.adjust_height) self.adjust_height(self.input);
});
// Compile and store the template
if(this.schema.template) {
this.template = this.jsoneditor.compileTemplate(this.schema.template, this.template_engine);
this.refreshValue();
}
else {
this.refreshValue();
}
},
enable: function() {
if(!this.always_disabled) {
this.input.disabled = false;
// TODO: WYSIWYG and Markdown editors
}
this._super();
},
disable: function() {
this.input.disabled = true;
// TODO: WYSIWYG and Markdown editors
this._super();
},
afterInputReady: function() {
var self = this, options;
// Code editor
if(this.source_code) {
// WYSIWYG html and bbcode editor
if(this.options.wysiwyg &&
['html','bbcode'].indexOf(this.input_type) >= 0 &&
window.jQuery && window.jQuery.fn && window.jQuery.fn.sceditor
) {
options = $extend({},{
plugins: self.input_type==='html'? 'xhtml' : 'bbcode',
emoticonsEnabled: false,
width: '100%',
height: 300
},JSONEditor.plugins.sceditor,self.options.sceditor_options||{});
window.jQuery(self.input).sceditor(options);
self.sceditor_instance = window.jQuery(self.input).sceditor('instance');
self.sceditor_instance.blur(function() {
// Get editor's value
var val = window.jQuery("<div>"+self.sceditor_instance.val()+"</div>");
// Remove sceditor spans/divs
window.jQuery('#sceditor-start-marker,#sceditor-end-marker,.sceditor-nlf',val).remove();
// Set the value and update
self.input.value = val.html();
self.value = self.input.value;
self.is_dirty = true;
self.onChange(true);
});
}
// EpicEditor for markdown (if it's loaded)
else if (this.input_type === 'markdown' && window.EpicEditor) {
this.epiceditor_container = document.createElement('div');
this.input.parentNode.insertBefore(this.epiceditor_container,this.input);
this.input.style.display = 'none';
options = $extend({},JSONEditor.plugins.epiceditor,{
container: this.epiceditor_container,
clientSideStorage: false
});
this.epiceditor = new window.EpicEditor(options).load();
this.epiceditor.importFile(null,this.getValue());
this.epiceditor.on('update',function() {
var val = self.epiceditor.exportFile();
self.input.value = val;
self.value = val;
self.is_dirty = true;
self.onChange(true);
});
}
// ACE editor for everything else
else if(window.ace) {
var mode = this.input_type;
// aliases for c/cpp
if(mode === 'cpp' || mode === 'c++' || mode === 'c') {
mode = 'c_cpp';
}
this.ace_container = document.createElement('div');
this.ace_container.style.width = '100%';
this.ace_container.style.position = 'relative';
this.ace_container.style.height = '400px';
this.input.parentNode.insertBefore(this.ace_container,this.input);
this.input.style.display = 'none';
this.ace_editor = window.ace.edit(this.ace_container);
this.ace_editor.setValue(this.getValue());
// The theme
if(JSONEditor.plugins.ace.theme) this.ace_editor.setTheme('ace/theme/'+JSONEditor.plugins.ace.theme);
// The mode
mode = window.ace.require("ace/mode/"+mode);
if(mode) this.ace_editor.getSession().setMode(new mode.Mode());
// Listen for changes
this.ace_editor.on('change',function() {
var val = self.ace_editor.getValue();
self.input.value = val;
self.refreshValue();
self.is_dirty = true;
self.onChange(true);
});
}
}
self.theme.afterInputReady(self.input);
},
refreshValue: function() {
this.value = this.input.value;
if(typeof this.value !== "string") this.value = '';
this.serialized = this.value;
},
destroy: function() {
// If using SCEditor, destroy the editor instance
if(this.sceditor_instance) {
this.sceditor_instance.destroy();
}
else if(this.epiceditor) {
this.epiceditor.unload();
}
else if(this.ace_editor) {
this.ace_editor.destroy();
}
this.template = null;
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
this._super();
},
/**
* This is overridden in derivative editors
*/
sanitize: function(value) {
return value;
},
/**
* Re-calculates the value if needed
*/
onWatchedFieldChange: function() {
var self = this, vars, j;
// If this editor needs to be rendered by a macro template
if(this.template) {
vars = this.getWatchedFieldValues();
this.setValue(this.template(vars),false,true);
}
this._super();
},
showValidationErrors: function(errors) {
var self = this;
if(this.jsoneditor.options.show_errors === "always") {}
else if(!this.is_dirty && this.previous_error_setting===this.jsoneditor.options.show_errors) return;
this.previous_error_setting = this.jsoneditor.options.show_errors;
var messages = [];
$each(errors,function(i,error) {
if(error.path === self.path) {
messages.push(error.message);
}
});
if(messages.length) {
this.theme.addInputError(this.input, messages.join('. ')+'.');
}
else {
this.theme.removeInputError(this.input);
}
}
});
JSONEditor.defaults.editors.number = JSONEditor.defaults.editors.string.extend({
sanitize: function(value) {
return (value+"").replace(/[^0-9\.\-eE]/g,'');
},
getNumColumns: function() {
return 2;
},
getValue: function() {
return this.value*1;
}
});
JSONEditor.defaults.editors.integer = JSONEditor.defaults.editors.number.extend({
sanitize: function(value) {
value = value + "";
return value.replace(/[^0-9\-]/g,'');
},
getNumColumns: function() {
return 2;
}
});
JSONEditor.defaults.editors.object = JSONEditor.AbstractEditor.extend({
getDefault: function() {
return $extend({},this.schema["default"] || {});
},
getChildEditors: function() {
return this.editors;
},
register: function() {
this._super();
if(this.editors) {
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.editors[i].register();
}
}
},
unregister: function() {
this._super();
if(this.editors) {
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.editors[i].unregister();
}
}
},
getNumColumns: function() {
return Math.max(Math.min(12,this.maxwidth),3);
},
enable: function() {
if(this.editjson_button) this.editjson_button.disabled = false;
if(this.addproperty_button) this.addproperty_button.disabled = false;
this._super();
if(this.editors) {
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.editors[i].enable();
}
}
},
disable: function() {
if(this.editjson_button) this.editjson_button.disabled = true;
if(this.addproperty_button) this.addproperty_button.disabled = true;
this.hideEditJSON();
this._super();
if(this.editors) {
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.editors[i].disable();
}
}
},
layoutEditors: function() {
var self = this, i, j;
if(!this.row_container) return;
// Sort editors by propertyOrder
this.property_order = Object.keys(this.editors);
this.property_order = this.property_order.sort(function(a,b) {
var ordera = self.editors[a].schema.propertyOrder;
var orderb = self.editors[b].schema.propertyOrder;
if(typeof ordera !== "number") ordera = 1000;
if(typeof orderb !== "number") orderb = 1000;
return ordera - orderb;
});
var container;
if(this.format === 'grid') {
var rows = [];
$each(this.property_order, function(j,key) {
var editor = self.editors[key];
if(editor.property_removed) return;
var found = false;
var width = editor.options.hidden? 0 : (editor.options.grid_columns || editor.getNumColumns());
var height = editor.options.hidden? 0 : editor.container.offsetHeight;
// See if the editor will fit in any of the existing rows first
for(var i=0; i<rows.length; i++) {
// If the editor will fit in the row horizontally
if(rows[i].width + width <= 12) {
// If the editor is close to the other elements in height
// i.e. Don't put a really tall editor in an otherwise short row or vice versa
if(!height || (rows[i].minh*0.5 < height && rows[i].maxh*2 > height)) {
found = i;
}
}
}
// If there isn't a spot in any of the existing rows, start a new row
if(found === false) {
rows.push({
width: 0,
minh: 999999,
maxh: 0,
editors: []
});
found = rows.length-1;
}
rows[found].editors.push({
key: key,
//editor: editor,
width: width,
height: height
});
rows[found].width += width;
rows[found].minh = Math.min(rows[found].minh,height);
rows[found].maxh = Math.max(rows[found].maxh,height);
});
// Make almost full rows width 12
// Do this by increasing all editors' sizes proprotionately
// Any left over space goes to the biggest editor
// Don't touch rows with a width of 6 or less
for(i=0; i<rows.length; i++) {
if(rows[i].width < 12) {
var biggest = false;
var new_width = 0;
for(j=0; j<rows[i].editors.length; j++) {
if(biggest === false) biggest = j;
else if(rows[i].editors[j].width > rows[i].editors[biggest].width) biggest = j;
rows[i].editors[j].width *= 12/rows[i].width;
rows[i].editors[j].width = Math.floor(rows[i].editors[j].width);
new_width += rows[i].editors[j].width;
}
if(new_width < 12) rows[i].editors[biggest].width += 12-new_width;
rows[i].width = 12;
}
}
// layout hasn't changed
if(this.layout === JSON.stringify(rows)) return false;
this.layout = JSON.stringify(rows);
// Layout the form
container = document.createElement('div');
for(i=0; i<rows.length; i++) {
var row = this.theme.getGridRow();
container.appendChild(row);
for(j=0; j<rows[i].editors.length; j++) {
var key = rows[i].editors[j].key;
var editor = this.editors[key];
if(editor.options.hidden) editor.container.style.display = 'none';
else this.theme.setGridColumnSize(editor.container,rows[i].editors[j].width);
row.appendChild(editor.container);
}
}
}
// Normal layout
else {
container = document.createElement('div');
$each(this.property_order, function(i,key) {
var editor = self.editors[key];
if(editor.property_removed) return;
var row = self.theme.getGridRow();
container.appendChild(row);
if(editor.options.hidden) editor.container.style.display = 'none';
else self.theme.setGridColumnSize(editor.container,12);
row.appendChild(editor.container);
});
}
this.row_container.innerHTML = '';
this.row_container.appendChild(container);
},
getPropertySchema: function(key) {
// Schema declared directly in properties
var schema = this.schema.properties[key] || {};
schema = $extend({},schema);
var matched = this.schema.properties[key]? true : false;
// Any matching patternProperties should be merged in
if(this.schema.patternProperties) {
for(var i in this.schema.patternProperties) {
if(!this.schema.patternProperties.hasOwnProperty(i)) continue;
var regex = new RegExp(i);
if(regex.test(key)) {
schema.allOf = schema.allOf || [];
schema.allOf.push(this.schema.patternProperties[i]);
matched = true;
}
}
}
// Hasn't matched other rules, use additionalProperties schema
if(!matched && this.schema.additionalProperties && typeof this.schema.additionalProperties === "object") {
schema = $extend({},this.schema.additionalProperties);
}
return schema;
},
preBuild: function() {
this._super();
this.editors = {};
this.cached_editors = {};
var self = this;
this.format = this.options.layout || this.options.object_layout || this.schema.format || this.jsoneditor.options.object_layout || 'normal';
this.schema.properties = this.schema.properties || {};
this.minwidth = 0;
this.maxwidth = 0;
// If the object should be rendered as a table row
if(this.options.table_row) {
$each(this.schema.properties, function(key,schema) {
var editor = self.jsoneditor.getEditorClass(schema);
self.editors[key] = self.jsoneditor.createEditor(editor,{
jsoneditor: self.jsoneditor,
schema: schema,
path: self.path+'.'+key,
parent: self,
compact: true,
required: true
});
self.editors[key].preBuild();
var width = self.editors[key].options.hidden? 0 : (self.editors[key].options.grid_columns || self.editors[key].getNumColumns());
self.minwidth += width;
self.maxwidth += width;
});
this.no_link_holder = true;
}
// If the object should be rendered as a table
else if(this.options.table) {
// TODO: table display format
throw "Not supported yet";
}
// If the object should be rendered as a div
else {
if(!this.schema.defaultProperties) {
if(this.jsoneditor.options.display_required_only || this.options.display_required_only) {
this.schema.defaultProperties = [];
$each(this.schema.properties, function(k,s) {
if(self.isRequired({key: k, schema: s})) {
self.schema.defaultProperties.push(k);
}
});
}
else {
self.schema.defaultProperties = Object.keys(self.schema.properties);
}
}
// Increase the grid width to account for padding
self.maxwidth += 1;
$each(this.schema.defaultProperties, function(i,key) {
self.addObjectProperty(key, true);
if(self.editors[key]) {
self.minwidth = Math.max(self.minwidth,(self.editors[key].options.grid_columns || self.editors[key].getNumColumns()));
self.maxwidth += (self.editors[key].options.grid_columns || self.editors[key].getNumColumns());
}
});
}
// Sort editors by propertyOrder
this.property_order = Object.keys(this.editors);
this.property_order = this.property_order.sort(function(a,b) {
var ordera = self.editors[a].schema.propertyOrder;
var orderb = self.editors[b].schema.propertyOrder;
if(typeof ordera !== "number") ordera = 1000;
if(typeof orderb !== "number") orderb = 1000;
return ordera - orderb;
});
},
build: function() {
var self = this;
// If the object should be rendered as a table row
if(this.options.table_row) {
this.editor_holder = this.container;
$each(this.editors, function(key,editor) {
var holder = self.theme.getTableCell();
self.editor_holder.appendChild(holder);
editor.setContainer(holder);
editor.build();
editor.postBuild();
if(self.editors[key].options.hidden) {
holder.style.display = 'none';
}
if(self.editors[key].options.input_width) {
holder.style.width = self.editors[key].options.input_width;
}
});
}
// If the object should be rendered as a table
else if(this.options.table) {
// TODO: table display format
throw "Not supported yet";
}
// If the object should be rendered as a div
else {
this.header = document.createElement('span');
this.header.textContent = this.getTitle();
this.title = this.theme.getHeader(this.header);
this.container.appendChild(this.title);
this.container.style.position = 'relative';
// Edit JSON modal
this.editjson_holder = this.theme.getModal();
this.editjson_textarea = this.theme.getTextareaInput();
this.editjson_textarea.style.height = '170px';
this.editjson_textarea.style.width = '300px';
this.editjson_textarea.style.display = 'block';
this.editjson_save = this.getButton('Save','save','Save');
this.editjson_save.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.saveJSON();
});
this.editjson_cancel = this.getButton('Cancel','cancel','Cancel');
this.editjson_cancel.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.hideEditJSON();
});
this.editjson_holder.appendChild(this.editjson_textarea);
this.editjson_holder.appendChild(this.editjson_save);
this.editjson_holder.appendChild(this.editjson_cancel);
// Manage Properties modal
this.addproperty_holder = this.theme.getModal();
this.addproperty_list = document.createElement('div');
this.addproperty_list.style.width = '295px';
this.addproperty_list.style.maxHeight = '160px';
this.addproperty_list.style.padding = '5px 0';
this.addproperty_list.style.overflowY = 'auto';
this.addproperty_list.style.overflowX = 'hidden';
this.addproperty_list.style.paddingLeft = '5px';
this.addproperty_list.setAttribute('class', 'property-selector');
this.addproperty_add = this.getButton('add','add','add');
this.addproperty_input = this.theme.getFormInputField('text');
this.addproperty_input.setAttribute('placeholder','Property name...');
this.addproperty_input.style.width = '220px';
this.addproperty_input.style.marginBottom = '0';
this.addproperty_input.style.display = 'inline-block';
this.addproperty_add.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
if(self.addproperty_input.value) {
if(self.editors[self.addproperty_input.value]) {
window.alert('there is already a property with that name');
return;
}
self.addObjectProperty(self.addproperty_input.value);
if(self.editors[self.addproperty_input.value]) {
self.editors[self.addproperty_input.value].disable();
}
self.onChange(true);
}
});
this.addproperty_holder.appendChild(this.addproperty_list);
this.addproperty_holder.appendChild(this.addproperty_input);
this.addproperty_holder.appendChild(this.addproperty_add);
var spacer = document.createElement('div');
spacer.style.clear = 'both';
this.addproperty_holder.appendChild(spacer);
// Description
if(this.schema.description) {
this.description = this.theme.getDescription(this.schema.description);
this.container.appendChild(this.description);
}
// Validation error placeholder area
this.error_holder = document.createElement('div');
this.container.appendChild(this.error_holder);
// Container for child editor area
this.editor_holder = this.theme.getIndentedPanel();
this.container.appendChild(this.editor_holder);
// Container for rows of child editors
this.row_container = this.theme.getGridContainer();
this.editor_holder.appendChild(this.row_container);
$each(this.editors, function(key,editor) {
var holder = self.theme.getGridColumn();
self.row_container.appendChild(holder);
editor.setContainer(holder);
editor.build();
editor.postBuild();
});
// Control buttons
this.title_controls = this.theme.getHeaderButtonHolder();
this.editjson_controls = this.theme.getHeaderButtonHolder();
this.addproperty_controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.title_controls);
this.title.appendChild(this.editjson_controls);
this.title.appendChild(this.addproperty_controls);
// Show/Hide button
this.collapsed = false;
this.toggle_button = this.getButton('','collapse',this.translate('edt_msg_button_collapse'));
this.title_controls.appendChild(this.toggle_button);
this.toggle_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
if(self.collapsed) {
self.editor_holder.style.display = '';
self.collapsed = false;
self.setButtonText(self.toggle_button,'','collapse',self.translate('edt_msg_button_collapse'));
}
else {
self.editor_holder.style.display = 'none';
self.collapsed = true;
self.setButtonText(self.toggle_button,'','expand',self.translate('edt_msg_button_expand'));
}
});
// If it should start collapsed
if(this.options.collapsed) {
$trigger(this.toggle_button,'click');
}
// Collapse button disabled
if(this.schema.options && typeof this.schema.options.disable_collapse !== "undefined") {
if(this.schema.options.disable_collapse) this.toggle_button.style.display = 'none';
}
else if(this.jsoneditor.options.disable_collapse) {
this.toggle_button.style.display = 'none';
}
// Edit JSON Button
this.editjson_button = this.getButton('JSON','edit','Edit JSON');
this.editjson_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.toggleEditJSON();
});
this.editjson_controls.appendChild(this.editjson_button);
this.editjson_controls.appendChild(this.editjson_holder);
// Edit JSON Buttton disabled
if(this.schema.options && typeof this.schema.options.disable_edit_json !== "undefined") {
if(this.schema.options.disable_edit_json) this.editjson_button.style.display = 'none';
}
else if(this.jsoneditor.options.disable_edit_json) {
this.editjson_button.style.display = 'none';
}
// Object Properties Button
this.addproperty_button = this.getButton('Properties','edit','Object Properties');
this.addproperty_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.toggleAddProperty();
});
this.addproperty_controls.appendChild(this.addproperty_button);
this.addproperty_controls.appendChild(this.addproperty_holder);
this.refreshAddProperties();
}
// Fix table cell ordering
if(this.options.table_row) {
this.editor_holder = this.container;
$each(this.property_order,function(i,key) {
self.editor_holder.appendChild(self.editors[key].container);
});
}
// Layout object editors in grid if needed
else {
// Initial layout
this.layoutEditors();
// Do it again now that we know the approximate heights of elements
this.layoutEditors();
}
},
showEditJSON: function() {
if(!this.editjson_holder) return;
this.hideAddProperty();
// Position the form directly beneath the button
// TODO: edge detection
this.editjson_holder.style.left = this.editjson_button.offsetLeft+"px";
this.editjson_holder.style.top = this.editjson_button.offsetTop + this.editjson_button.offsetHeight+"px";
// Start the textarea with the current value
this.editjson_textarea.value = JSON.stringify(this.getValue(),null,2);
// Disable the rest of the form while editing JSON
this.disable();
this.editjson_holder.style.display = '';
this.editjson_button.disabled = false;
this.editing_json = true;
},
hideEditJSON: function() {
if(!this.editjson_holder) return;
if(!this.editing_json) return;
this.editjson_holder.style.display = 'none';
this.enable();
this.editing_json = false;
},
saveJSON: function() {
if(!this.editjson_holder) return;
try {
var json = JSON.parse(this.editjson_textarea.value);
this.setValue(json);
this.hideEditJSON();
}
catch(e) {
window.alert('invalid JSON');
throw e;
}
},
toggleEditJSON: function() {
if(this.editing_json) this.hideEditJSON();
else this.showEditJSON();
},
insertPropertyControlUsingPropertyOrder: function (property, control, container) {
var propertyOrder;
if (this.schema.properties[property])
propertyOrder = this.schema.properties[property].propertyOrder;
if (typeof propertyOrder !== "number") propertyOrder = 1000;
control.propertyOrder = propertyOrder;
for (var i = 0; i < container.childNodes.length; i++) {
var child = container.childNodes[i];
if (control.propertyOrder < child.propertyOrder) {
this.addproperty_list.insertBefore(control, child);
control = null;
break;
}
}
if (control) {
this.addproperty_list.appendChild(control);
}
},
addPropertyCheckbox: function(key) {
var self = this;
var checkbox, label, labelText, control;
checkbox = self.theme.getCheckbox();
checkbox.style.width = 'auto';
if (this.schema.properties[key] && this.schema.properties[key].title)
labelText = this.schema.properties[key].title;
else
labelText = key;
label = self.theme.getCheckboxLabel(labelText);
control = self.theme.getFormControl(label,checkbox);
control.style.paddingBottom = control.style.marginBottom = control.style.paddingTop = control.style.marginTop = 0;
control.style.height = 'auto';
//control.style.overflowY = 'hidden';
this.insertPropertyControlUsingPropertyOrder(key, control, this.addproperty_list);
checkbox.checked = key in this.editors;
checkbox.addEventListener('change',function() {
if(checkbox.checked) {
self.addObjectProperty(key);
}
else {
self.removeObjectProperty(key);
}
self.onChange(true);
});
self.addproperty_checkboxes[key] = checkbox;
return checkbox;
},
showAddProperty: function() {
if(!this.addproperty_holder) return;
this.hideEditJSON();
// Position the form directly beneath the button
// TODO: edge detection
this.addproperty_holder.style.left = this.addproperty_button.offsetLeft+"px";
this.addproperty_holder.style.top = this.addproperty_button.offsetTop + this.addproperty_button.offsetHeight+"px";
// Disable the rest of the form while editing JSON
this.disable();
this.adding_property = true;
this.addproperty_button.disabled = false;
this.addproperty_holder.style.display = '';
this.refreshAddProperties();
},
hideAddProperty: function() {
if(!this.addproperty_holder) return;
if(!this.adding_property) return;
this.addproperty_holder.style.display = 'none';
this.enable();
this.adding_property = false;
},
toggleAddProperty: function() {
if(this.adding_property) this.hideAddProperty();
else this.showAddProperty();
},
removeObjectProperty: function(property) {
if(this.editors[property]) {
this.editors[property].unregister();
delete this.editors[property];
this.refreshValue();
this.layoutEditors();
}
},
addObjectProperty: function(name, prebuild_only) {
var self = this;
// Property is already added
if(this.editors[name]) return;
// Property was added before and is cached
if(this.cached_editors[name]) {
this.editors[name] = this.cached_editors[name];
if(prebuild_only) return;
this.editors[name].register();
}
// New property
else {
if(!this.canHaveAdditionalProperties() && (!this.schema.properties || !this.schema.properties[name])) {
return;
}
var schema = self.getPropertySchema(name);
// Add the property
var editor = self.jsoneditor.getEditorClass(schema);
self.editors[name] = self.jsoneditor.createEditor(editor,{
jsoneditor: self.jsoneditor,
schema: schema,
path: self.path+'.'+name,
parent: self
});
self.editors[name].preBuild();
if(!prebuild_only) {
var holder = self.theme.getChildEditorHolder();
self.editor_holder.appendChild(holder);
self.editors[name].setContainer(holder);
self.editors[name].build();
self.editors[name].postBuild();
}
self.cached_editors[name] = self.editors[name];
}
// If we're only prebuilding the editors, don't refresh values
if(!prebuild_only) {
self.refreshValue();
self.layoutEditors();
}
},
onChildEditorChange: function(editor) {
this.refreshValue();
this._super(editor);
},
canHaveAdditionalProperties: function() {
if (typeof this.schema.additionalProperties === "boolean") {
return this.schema.additionalProperties;
}
return !this.jsoneditor.options.no_additional_properties;
},
destroy: function() {
$each(this.cached_editors, function(i,el) {
el.destroy();
});
if(this.editor_holder) this.editor_holder.innerHTML = '';
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.error_holder && this.error_holder.parentNode) this.error_holder.parentNode.removeChild(this.error_holder);
this.editors = null;
this.cached_editors = null;
if(this.editor_holder && this.editor_holder.parentNode) this.editor_holder.parentNode.removeChild(this.editor_holder);
this.editor_holder = null;
this._super();
},
getValue: function() {
var result = this._super();
if(this.jsoneditor.options.remove_empty_properties || this.options.remove_empty_properties) {
for(var i in result) {
if(result.hasOwnProperty(i)) {
if(!result[i]) delete result[i];
}
}
}
return result;
},
refreshValue: function() {
this.value = {};
var self = this;
for(var i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
this.value[i] = this.editors[i].getValue();
}
if(this.adding_property) this.refreshAddProperties();
},
refreshAddProperties: function() {
if(this.options.disable_properties || (this.options.disable_properties !== false && this.jsoneditor.options.disable_properties)) {
this.addproperty_controls.style.display = 'none';
return;
}
var can_add = false, can_remove = false, num_props = 0, i, show_modal = false;
// Get number of editors
for(i in this.editors) {
if(!this.editors.hasOwnProperty(i)) continue;
num_props++;
}
// Determine if we can add back removed properties
can_add = this.canHaveAdditionalProperties() && !(typeof this.schema.maxProperties !== "undefined" && num_props >= this.schema.maxProperties);
if(this.addproperty_checkboxes) {
this.addproperty_list.innerHTML = '';
}
this.addproperty_checkboxes = {};
// Check for which editors can't be removed or added back
for(i in this.cached_editors) {
if(!this.cached_editors.hasOwnProperty(i)) continue;
this.addPropertyCheckbox(i);
if(this.isRequired(this.cached_editors[i]) && i in this.editors) {
this.addproperty_checkboxes[i].disabled = true;
}
if(typeof this.schema.minProperties !== "undefined" && num_props <= this.schema.minProperties) {
this.addproperty_checkboxes[i].disabled = this.addproperty_checkboxes[i].checked;
if(!this.addproperty_checkboxes[i].checked) show_modal = true;
}
else if(!(i in this.editors)) {
if(!can_add && !this.schema.properties.hasOwnProperty(i)) {
this.addproperty_checkboxes[i].disabled = true;
}
else {
this.addproperty_checkboxes[i].disabled = false;
show_modal = true;
}
}
else {
show_modal = true;
can_remove = true;
}
}
if(this.canHaveAdditionalProperties()) {
show_modal = true;
}
// Additional addproperty checkboxes not tied to a current editor
for(i in this.schema.properties) {
if(!this.schema.properties.hasOwnProperty(i)) continue;
if(this.cached_editors[i]) continue;
show_modal = true;
this.addPropertyCheckbox(i);
}
// If no editors can be added or removed, hide the modal button
if(!show_modal) {
this.hideAddProperty();
this.addproperty_controls.style.display = 'none';
}
// If additional properties are disabled
else if(!this.canHaveAdditionalProperties()) {
this.addproperty_add.style.display = 'none';
this.addproperty_input.style.display = 'none';
}
// If no new properties can be added
else if(!can_add) {
this.addproperty_add.disabled = true;
}
// If new properties can be added
else {
this.addproperty_add.disabled = false;
}
},
isRequired: function(editor) {
if(typeof editor.schema.required === "boolean") return editor.schema.required;
else if(Array.isArray(this.schema.required)) return this.schema.required.indexOf(editor.key) > -1;
else if(this.jsoneditor.options.required_by_default) return true;
else return false;
},
setValue: function(value, initial) {
var self = this;
value = value || {};
if(typeof value !== "object" || Array.isArray(value)) value = {};
// First, set the values for all of the defined properties
$each(this.cached_editors, function(i,editor) {
// Value explicitly set
if(typeof value[i] !== "undefined") {
self.addObjectProperty(i);
editor.setValue(value[i],initial);
}
// Otherwise, remove value unless this is the initial set or it's required
else if(!initial && !self.isRequired(editor)) {
self.removeObjectProperty(i);
}
// Otherwise, set the value to the default
else {
editor.setValue(editor.getDefault(),initial);
}
});
$each(value, function(i,val) {
if(!self.cached_editors[i]) {
self.addObjectProperty(i);
if(self.editors[i]) self.editors[i].setValue(val,initial);
}
});
this.refreshValue();
this.layoutEditors();
this.onChange();
},
showValidationErrors: function(errors) {
var self = this;
// Get all the errors that pertain to this editor
var my_errors = [];
var other_errors = [];
$each(errors, function(i,error) {
if(error.path === self.path) {
my_errors.push(error);
}
else {
other_errors.push(error);
}
});
// Show errors for this editor
if(this.error_holder) {
if(my_errors.length) {
var message = [];
this.error_holder.innerHTML = '';
this.error_holder.style.display = '';
$each(my_errors, function(i,error) {
self.error_holder.appendChild(self.theme.getErrorMessage(error.message));
});
}
// Hide error area
else {
this.error_holder.style.display = 'none';
}
}
// Show error for the table row if this is inside a table
if(this.options.table_row) {
if(my_errors.length) {
this.theme.addTableRowError(this.container);
}
else {
this.theme.removeTableRowError(this.container);
}
}
// Show errors for child editors
$each(this.editors, function(i,editor) {
editor.showValidationErrors(other_errors);
});
}
});
JSONEditor.defaults.editors.array = JSONEditor.AbstractEditor.extend({
getDefault: function() {
return this.schema["default"] || [];
},
register: function() {
this._super();
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].register();
}
}
},
unregister: function() {
this._super();
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].unregister();
}
}
},
getNumColumns: function() {
var info = this.getItemInfo(0);
// Tabs require extra horizontal space
if(this.tabs_holder) {
return Math.max(Math.min(12,info.width+2),4);
}
else {
return info.width;
}
},
enable: function() {
if(this.add_row_button) this.add_row_button.disabled = false;
if(this.remove_all_rows_button) this.remove_all_rows_button.disabled = false;
if(this.delete_last_row_button) this.delete_last_row_button.disabled = false;
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].enable();
if(this.rows[i].moveup_button) this.rows[i].moveup_button.disabled = false;
if(this.rows[i].movedown_button) this.rows[i].movedown_button.disabled = false;
if(this.rows[i].delete_button) this.rows[i].delete_button.disabled = false;
}
}
this._super();
},
disable: function() {
if(this.add_row_button) this.add_row_button.disabled = true;
if(this.remove_all_rows_button) this.remove_all_rows_button.disabled = true;
if(this.delete_last_row_button) this.delete_last_row_button.disabled = true;
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].disable();
if(this.rows[i].moveup_button) this.rows[i].moveup_button.disabled = true;
if(this.rows[i].movedown_button) this.rows[i].movedown_button.disabled = true;
if(this.rows[i].delete_button) this.rows[i].delete_button.disabled = true;
}
}
this._super();
},
preBuild: function() {
this._super();
this.rows = [];
this.row_cache = [];
this.hide_delete_buttons = this.options.disable_array_delete || this.jsoneditor.options.disable_array_delete;
this.hide_delete_all_rows_buttons = this.hide_delete_buttons || this.options.disable_array_delete_all_rows || this.jsoneditor.options.disable_array_delete_all_rows;
this.hide_delete_last_row_buttons = this.hide_delete_buttons || this.options.disable_array_delete_last_row || this.jsoneditor.options.disable_array_delete_last_row;
this.hide_move_buttons = this.options.disable_array_reorder || this.jsoneditor.options.disable_array_reorder;
this.hide_add_button = this.options.disable_array_add || this.jsoneditor.options.disable_array_add;
},
build: function() {
var self = this;
if(!this.options.compact) {
this.header = document.createElement('span');
this.header.textContent = this.getTitle();
this.title = this.theme.getHeader(this.header);
this.container.appendChild(this.title);
this.title_controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.title_controls);
if(this.schema.description) {
this.description = this.theme.getDescription(this.schema.description);
this.container.appendChild(this.description);
}
if(this.schema.append) {
this.append = this.theme.getAppend(this.schema.append);
this.container.appendChild(this.append);
}
this.error_holder = document.createElement('div');
this.container.appendChild(this.error_holder);
if(this.schema.format === 'tabs') {
this.controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.controls);
this.tabs_holder = this.theme.getTabHolder();
this.container.appendChild(this.tabs_holder);
this.row_holder = this.theme.getTabContentHolder(this.tabs_holder);
this.active_tab = null;
}
else {
this.panel = this.theme.getIndentedPanel();
this.container.appendChild(this.panel);
this.row_holder = document.createElement('div');
this.panel.appendChild(this.row_holder);
this.controls = this.theme.getButtonHolder();
this.panel.appendChild(this.controls);
}
}
else {
this.panel = this.theme.getIndentedPanel();
this.container.appendChild(this.panel);
this.controls = this.theme.getButtonHolder();
this.panel.appendChild(this.controls);
this.row_holder = document.createElement('div');
this.panel.appendChild(this.row_holder);
}
// Add controls
this.addControls();
},
onChildEditorChange: function(editor) {
this.refreshValue();
this.refreshTabs(true);
this._super(editor);
},
getItemTitle: function() {
if(!this.item_title) {
if(this.schema.items && !Array.isArray(this.schema.items)) {
var tmp = this.jsoneditor.expandRefs(this.schema.items);
if (typeof tmp.title == 'undefined')
this.item_title = 'item';
else
this.item_title = $.i18n(tmp.title);
}
else {
this.item_title = 'item';
}
}
return this.item_title;
},
getItemSchema: function(i) {
if(Array.isArray(this.schema.items)) {
if(i >= this.schema.items.length) {
if(this.schema.additionalItems===true) {
return {};
}
else if(this.schema.additionalItems) {
return $extend({},this.schema.additionalItems);
}
}
else {
return $extend({},this.schema.items[i]);
}
}
else if(this.schema.items) {
return $extend({},this.schema.items);
}
else {
return {};
}
},
getItemInfo: function(i) {
var schema = this.getItemSchema(i);
// Check if it's cached
this.item_info = this.item_info || {};
var stringified = JSON.stringify(schema);
if(typeof this.item_info[stringified] !== "undefined") return this.item_info[stringified];
// Get the schema for this item
schema = this.jsoneditor.expandRefs(schema);
this.item_info[stringified] = {
title: schema.title || "item",
'default': schema["default"],
width: 12,
child_editors: schema.properties || schema.items
};
return this.item_info[stringified];
},
getElementEditor: function(i) {
var item_info = this.getItemInfo(i);
var schema = this.getItemSchema(i);
schema = this.jsoneditor.expandRefs(schema);
schema.title = $.i18n(item_info.title)+' '+(i+1);
var editor = this.jsoneditor.getEditorClass(schema);
var holder;
if(this.tabs_holder) {
holder = this.theme.getTabContent();
}
else if(item_info.child_editors) {
holder = this.theme.getChildEditorHolder();
}
else {
holder = this.theme.getIndentedPanel();
}
this.row_holder.appendChild(holder);
var ret = this.jsoneditor.createEditor(editor,{
jsoneditor: this.jsoneditor,
schema: schema,
container: holder,
path: this.path+'.'+i,
parent: this,
required: true
});
ret.preBuild();
ret.build();
ret.postBuild();
if(!ret.title_controls) {
ret.array_controls = this.theme.getButtonHolder();
holder.appendChild(ret.array_controls);
}
return ret;
},
destroy: function() {
this.empty(true);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.row_holder && this.row_holder.parentNode) this.row_holder.parentNode.removeChild(this.row_holder);
if(this.controls && this.controls.parentNode) this.controls.parentNode.removeChild(this.controls);
if(this.panel && this.panel.parentNode) this.panel.parentNode.removeChild(this.panel);
this.rows = this.row_cache = this.title = this.description = this.row_holder = this.panel = this.controls = null;
this._super();
},
empty: function(hard) {
if(!this.rows) return;
var self = this;
$each(this.rows,function(i,row) {
if(hard) {
if(row.tab && row.tab.parentNode) row.tab.parentNode.removeChild(row.tab);
self.destroyRow(row,true);
self.row_cache[i] = null;
}
self.rows[i] = null;
});
self.rows = [];
if(hard) self.row_cache = [];
},
destroyRow: function(row,hard) {
var holder = row.container;
if(hard) {
row.destroy();
if(holder.parentNode) holder.parentNode.removeChild(holder);
if(row.tab && row.tab.parentNode) row.tab.parentNode.removeChild(row.tab);
}
else {
if(row.tab) row.tab.style.display = 'none';
holder.style.display = 'none';
row.unregister();
}
},
getMax: function() {
if((Array.isArray(this.schema.items)) && this.schema.additionalItems === false) {
return Math.min(this.schema.items.length,this.schema.maxItems || Infinity);
}
else {
return this.schema.maxItems || Infinity;
}
},
refreshTabs: function(refresh_headers) {
var self = this;
$each(this.rows, function(i,row) {
if(!row.tab) return;
if(refresh_headers) {
row.tab_text.textContent = row.getHeaderText();
}
else {
if(row.tab === self.active_tab) {
self.theme.markTabActive(row.tab);
row.container.style.display = '';
}
else {
self.theme.markTabInactive(row.tab);
row.container.style.display = 'none';
}
}
});
},
setValue: function(value, initial) {
// Update the array's value, adding/removing rows when necessary
value = value || [];
if(!(Array.isArray(value))) value = [value];
var serialized = JSON.stringify(value);
if(serialized === this.serialized) return;
// Make sure value has between minItems and maxItems items in it
if(this.schema.minItems) {
while(value.length < this.schema.minItems) {
value.push(this.getItemInfo(value.length)["default"]);
}
}
if(this.getMax() && value.length > this.getMax()) {
value = value.slice(0,this.getMax());
}
var self = this;
$each(value,function(i,val) {
if(self.rows[i]) {
// TODO: don't set the row's value if it hasn't changed
self.rows[i].setValue(val,initial);
}
else if(self.row_cache[i]) {
self.rows[i] = self.row_cache[i];
self.rows[i].setValue(val,initial);
self.rows[i].container.style.display = '';
if(self.rows[i].tab) self.rows[i].tab.style.display = '';
self.rows[i].register();
}
else {
self.addRow(val,initial);
}
});
for(var j=value.length; j<self.rows.length; j++) {
self.destroyRow(self.rows[j]);
self.rows[j] = null;
}
self.rows = self.rows.slice(0,value.length);
// Set the active tab
var new_active_tab = null;
$each(self.rows, function(i,row) {
if(row.tab === self.active_tab) {
new_active_tab = row.tab;
return false;
}
});
if(!new_active_tab && self.rows.length) new_active_tab = self.rows[0].tab;
self.active_tab = new_active_tab;
self.refreshValue(initial);
self.refreshTabs(true);
self.refreshTabs();
self.onChange();
// TODO: sortable
},
refreshValue: function(force) {
var self = this;
var oldi = this.value? this.value.length : 0;
this.value = [];
$each(this.rows,function(i,editor) {
// Get the value for this editor
self.value[i] = editor.getValue();
});
if(oldi !== this.value.length || force) {
// If we currently have minItems items in the array
var minItems = this.schema.minItems && this.schema.minItems >= this.rows.length;
$each(this.rows,function(i,editor) {
// Hide the move down button for the last row
if(editor.movedown_button) {
if(i === self.rows.length - 1) {
editor.movedown_button.style.display = 'none';
}
else {
editor.movedown_button.style.display = '';
}
}
// Hide the delete button if we have minItems items
if(editor.delete_button) {
if(minItems) {
editor.delete_button.style.display = 'none';
}
else {
editor.delete_button.style.display = '';
}
}
// Get the value for this editor
self.value[i] = editor.getValue();
});
var controls_needed = false;
if(!this.value.length) {
this.delete_last_row_button.style.display = 'none';
this.remove_all_rows_button.style.display = 'none';
}
else if(this.value.length === 1) {
this.remove_all_rows_button.style.display = 'none';
// If there are minItems items in the array, or configured to hide the delete_last_row button, hide the delete button beneath the rows
if(minItems || this.hide_delete_last_row_buttons) {
this.delete_last_row_button.style.display = 'none';
}
else {
this.delete_last_row_button.style.display = '';
controls_needed = true;
}
}
else {
if(minItems || this.hide_delete_last_row_buttons) {
this.delete_last_row_button.style.display = 'none';
}
else {
this.delete_last_row_button.style.display = '';
controls_needed = true;
}
if(minItems || this.hide_delete_all_rows_buttons) {
this.remove_all_rows_button.style.display = 'none';
}
else {
this.remove_all_rows_button.style.display = '';
controls_needed = true;
}
}
// If there are maxItems in the array, hide the add button beneath the rows
if((this.getMax() && this.getMax() <= this.rows.length) || this.hide_add_button){
this.add_row_button.style.display = 'none';
}
else {
this.add_row_button.style.display = '';
controls_needed = true;
}
if(!this.collapsed && controls_needed) {
this.controls.style.display = 'inline-block';
}
else {
this.controls.style.display = 'none';
}
}
},
addRow: function(value, initial) {
var self = this;
var i = this.rows.length;
self.rows[i] = this.getElementEditor(i);
self.row_cache[i] = self.rows[i];
if(self.tabs_holder) {
self.rows[i].tab_text = document.createElement('span');
self.rows[i].tab_text.textContent = self.rows[i].getHeaderText();
self.rows[i].tab = self.theme.getTab(self.rows[i].tab_text);
self.rows[i].tab.addEventListener('click', function(e) {
self.active_tab = self.rows[i].tab;
self.refreshTabs();
e.preventDefault();
e.stopPropagation();
});
self.theme.addTab(self.tabs_holder, self.rows[i].tab);
}
var controls_holder = self.rows[i].title_controls || self.rows[i].array_controls;
// Buttons to delete row, move row up, and move row down
if(!self.hide_delete_buttons) {
self.rows[i].delete_button = this.getButton(self.getItemTitle(),'delete',this.translate('edt_msg_button_delete_row_title',[self.getItemTitle()]));
self.rows[i].delete_button.className += ' delete';
self.rows[i].delete_button.setAttribute('data-i',i);
self.rows[i].delete_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
var value = self.getValue();
var newval = [];
var new_active_tab = null;
$each(value,function(j,row) {
if(j===i) {
// If the one we're deleting is the active tab
if(self.rows[j].tab === self.active_tab) {
// Make the next tab active if there is one
// Note: the next tab is going to be the current tab after deletion
if(self.rows[j+1]) new_active_tab = self.rows[j].tab;
// Otherwise, make the previous tab active if there is one
else if(j) new_active_tab = self.rows[j-1].tab;
}
return; // If this is the one we're deleting
}
newval.push(row);
});
self.setValue(newval);
if(new_active_tab) {
self.active_tab = new_active_tab;
self.refreshTabs();
}
self.onChange(true);
});
if(controls_holder) {
controls_holder.appendChild(self.rows[i].delete_button);
}
}
if(i && !self.hide_move_buttons) {
self.rows[i].moveup_button = this.getButton('','moveup',this.translate('edt_msg_button_move_up_title'));
self.rows[i].moveup_button.className += ' moveup';
self.rows[i].moveup_button.setAttribute('data-i',i);
self.rows[i].moveup_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
if(i<=0) return;
var rows = self.getValue();
var tmp = rows[i-1];
rows[i-1] = rows[i];
rows[i] = tmp;
self.setValue(rows);
self.active_tab = self.rows[i-1].tab;
self.refreshTabs();
self.onChange(true);
});
if(controls_holder) {
controls_holder.appendChild(self.rows[i].moveup_button);
}
}
if(!self.hide_move_buttons) {
self.rows[i].movedown_button = this.getButton('','movedown',this.translate('edt_msg_button_move_down_title'));
self.rows[i].movedown_button.className += ' movedown';
self.rows[i].movedown_button.setAttribute('data-i',i);
self.rows[i].movedown_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
var rows = self.getValue();
if(i>=rows.length-1) return;
var tmp = rows[i+1];
rows[i+1] = rows[i];
rows[i] = tmp;
self.setValue(rows);
self.active_tab = self.rows[i+1].tab;
self.refreshTabs();
self.onChange(true);
});
if(controls_holder) {
controls_holder.appendChild(self.rows[i].movedown_button);
}
}
if(value) self.rows[i].setValue(value, initial);
self.refreshTabs();
},
addControls: function() {
var self = this;
this.collapsed = false;
this.toggle_button = this.getButton('','collapse',this.translate('edt_msg_button_collapse'));
this.title_controls.appendChild(this.toggle_button);
var row_holder_display = self.row_holder.style.display;
var controls_display = self.controls.style.display;
this.toggle_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
if(self.collapsed) {
self.collapsed = false;
if(self.panel) self.panel.style.display = '';
self.row_holder.style.display = row_holder_display;
if(self.tabs_holder) self.tabs_holder.style.display = '';
self.controls.style.display = controls_display;
self.setButtonText(this,'','collapse',self.translate('edt_msg_button_collapse'));
}
else {
self.collapsed = true;
self.row_holder.style.display = 'none';
if(self.tabs_holder) self.tabs_holder.style.display = 'none';
self.controls.style.display = 'none';
if(self.panel) self.panel.style.display = 'none';
self.setButtonText(this,'','expand',self.translate('edt_msg_button_expand'));
}
});
// If it should start collapsed
if(this.options.collapsed) {
$trigger(this.toggle_button,'click');
}
// Collapse button disabled
if(this.schema.options && typeof this.schema.options.disable_collapse !== "undefined") {
if(this.schema.options.disable_collapse) this.toggle_button.style.display = 'none';
}
else if(this.jsoneditor.options.disable_collapse) {
this.toggle_button.style.display = 'none';
}
// Add "new row" and "delete last" buttons below editor
this.add_row_button = this.getButton(this.getItemTitle(),'add',this.translate('edt_msg_button_add_row_title',[this.getItemTitle()]));
this.add_row_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = self.rows.length;
if(self.row_cache[i]) {
self.rows[i] = self.row_cache[i];
self.rows[i].setValue(self.rows[i].getDefault(), true);
self.rows[i].container.style.display = '';
if(self.rows[i].tab) self.rows[i].tab.style.display = '';
self.rows[i].register();
}
else {
self.addRow();
}
self.active_tab = self.rows[i].tab;
self.refreshTabs();
self.refreshValue();
self.onChange(true);
});
self.controls.appendChild(this.add_row_button);
this.delete_last_row_button = this.getButton(this.translate('edt_msg_button_delete_last',[this.getItemTitle()]),'delete',this.translate('edt_msg_button_delete_last_title',[this.getItemTitle()]));
this.delete_last_row_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var rows = self.getValue();
var new_active_tab = null;
if(self.rows.length > 1 && self.rows[self.rows.length-1].tab === self.active_tab) new_active_tab = self.rows[self.rows.length-2].tab;
rows.pop();
self.setValue(rows);
if(new_active_tab) {
self.active_tab = new_active_tab;
self.refreshTabs();
}
self.onChange(true);
});
self.controls.appendChild(this.delete_last_row_button);
this.remove_all_rows_button = this.getButton(this.translate('edt_msg_button_delete_all'),'delete',this.translate('edt_msg_button_delete_all_title'));
this.remove_all_rows_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.setValue([]);
self.onChange(true);
});
self.controls.appendChild(this.remove_all_rows_button);
if(self.tabs) {
this.add_row_button.style.width = '100%';
this.add_row_button.style.textAlign = 'left';
this.add_row_button.style.marginBottom = '3px';
this.delete_last_row_button.style.width = '100%';
this.delete_last_row_button.style.textAlign = 'left';
this.delete_last_row_button.style.marginBottom = '3px';
this.remove_all_rows_button.style.width = '100%';
this.remove_all_rows_button.style.textAlign = 'left';
this.remove_all_rows_button.style.marginBottom = '3px';
}
},
showValidationErrors: function(errors) {
var self = this;
// Get all the errors that pertain to this editor
var my_errors = [];
var other_errors = [];
$each(errors, function(i,error) {
if(error.path === self.path) {
my_errors.push(error);
}
else {
other_errors.push(error);
}
});
// Show errors for this editor
if(this.error_holder) {
if(my_errors.length) {
var message = [];
this.error_holder.innerHTML = '';
this.error_holder.style.display = '';
$each(my_errors, function(i,error) {
self.error_holder.appendChild(self.theme.getErrorMessage(error.message));
});
}
// Hide error area
else {
this.error_holder.style.display = 'none';
}
}
// Show errors for child editors
$each(this.rows, function(i,row) {
row.showValidationErrors(other_errors);
});
}
});
JSONEditor.defaults.editors.table = JSONEditor.defaults.editors.array.extend({
register: function() {
this._super();
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].register();
}
}
},
unregister: function() {
this._super();
if(this.rows) {
for(var i=0; i<this.rows.length; i++) {
this.rows[i].unregister();
}
}
},
getNumColumns: function() {
return Math.max(Math.min(12,this.width),3);
},
preBuild: function() {
var item_schema = this.jsoneditor.expandRefs(this.schema.items || {});
this.item_title = item_schema.title || 'row';
this.item_default = item_schema["default"] || null;
this.item_has_child_editors = item_schema.properties || item_schema.items;
this.width = 12;
this._super();
},
build: function() {
var self = this;
this.table = this.theme.getTable();
this.container.appendChild(this.table);
this.thead = this.theme.getTableHead();
this.table.appendChild(this.thead);
this.header_row = this.theme.getTableRow();
this.thead.appendChild(this.header_row);
this.row_holder = this.theme.getTableBody();
this.table.appendChild(this.row_holder);
// Determine the default value of array element
var tmp = this.getElementEditor(0,true);
this.item_default = tmp.getDefault();
this.width = tmp.getNumColumns() + 2;
if(!this.options.compact) {
this.title = this.theme.getHeader(this.getTitle());
this.container.appendChild(this.title);
this.title_controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.title_controls);
if(this.schema.description) {
this.description = this.theme.getDescription(this.schema.description);
this.container.appendChild(this.description);
}
if(this.schema.append) {
this.append = this.theme.getAppend(this.getAppend());
this.container.appendChild(this.append);
}
this.panel = this.theme.getIndentedPanel();
this.container.appendChild(this.panel);
this.error_holder = document.createElement('div');
this.panel.appendChild(this.error_holder);
}
else {
this.panel = document.createElement('div');
this.container.appendChild(this.panel);
}
this.panel.appendChild(this.table);
this.controls = this.theme.getButtonHolder();
this.panel.appendChild(this.controls);
if(this.item_has_child_editors) {
var ce = tmp.getChildEditors();
var order = tmp.property_order || Object.keys(ce);
for(var i=0; i<order.length; i++) {
var th = self.theme.getTableHeaderCell(ce[order[i]].getTitle());
if(ce[order[i]].options.hidden) th.style.display = 'none';
self.header_row.appendChild(th);
}
}
else {
self.header_row.appendChild(self.theme.getTableHeaderCell(this.item_title));
}
tmp.destroy();
this.row_holder.innerHTML = '';
// Row Controls column
this.controls_header_cell = self.theme.getTableHeaderCell(" ");
self.header_row.appendChild(this.controls_header_cell);
// Add controls
this.addControls();
},
onChildEditorChange: function(editor) {
this.refreshValue();
this._super();
},
getItemDefault: function() {
return $extend({},{"default":this.item_default})["default"];
},
getItemTitle: function() {
return this.item_title;
},
getElementEditor: function(i,ignore) {
var schema_copy = $extend({},this.schema.items);
var editor = this.jsoneditor.getEditorClass(schema_copy, this.jsoneditor);
var row = this.row_holder.appendChild(this.theme.getTableRow());
var holder = row;
if(!this.item_has_child_editors) {
holder = this.theme.getTableCell();
row.appendChild(holder);
}
var ret = this.jsoneditor.createEditor(editor,{
jsoneditor: this.jsoneditor,
schema: schema_copy,
container: holder,
path: this.path+'.'+i,
parent: this,
compact: true,
table_row: true
});
ret.preBuild();
if(!ignore) {
ret.build();
ret.postBuild();
ret.controls_cell = row.appendChild(this.theme.getTableCell());
ret.row = row;
ret.table_controls = this.theme.getButtonHolder();
ret.controls_cell.appendChild(ret.table_controls);
ret.table_controls.style.margin = 0;
ret.table_controls.style.padding = 0;
}
return ret;
},
destroy: function() {
this.innerHTML = '';
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.row_holder && this.row_holder.parentNode) this.row_holder.parentNode.removeChild(this.row_holder);
if(this.table && this.table.parentNode) this.table.parentNode.removeChild(this.table);
if(this.panel && this.panel.parentNode) this.panel.parentNode.removeChild(this.panel);
this.rows = this.title = this.description = this.row_holder = this.table = this.panel = null;
this._super();
},
setValue: function(value, initial) {
// Update the array's value, adding/removing rows when necessary
value = value || [];
// Make sure value has between minItems and maxItems items in it
if(this.schema.minItems) {
while(value.length < this.schema.minItems) {
value.push(this.getItemDefault());
}
}
if(this.schema.maxItems && value.length > this.schema.maxItems) {
value = value.slice(0,this.schema.maxItems);
}
var serialized = JSON.stringify(value);
if(serialized === this.serialized) return;
var numrows_changed = false;
var self = this;
$each(value,function(i,val) {
if(self.rows[i]) {
// TODO: don't set the row's value if it hasn't changed
self.rows[i].setValue(val);
}
else {
self.addRow(val);
numrows_changed = true;
}
});
for(var j=value.length; j<self.rows.length; j++) {
var holder = self.rows[j].container;
if(!self.item_has_child_editors) {
self.rows[j].row.parentNode.removeChild(self.rows[j].row);
}
self.rows[j].destroy();
if(holder.parentNode) holder.parentNode.removeChild(holder);
self.rows[j] = null;
numrows_changed = true;
}
self.rows = self.rows.slice(0,value.length);
self.refreshValue();
if(numrows_changed || initial) self.refreshRowButtons();
self.onChange();
// TODO: sortable
},
refreshRowButtons: function() {
var self = this;
// If we currently have minItems items in the array
var minItems = this.schema.minItems && this.schema.minItems >= this.rows.length;
var need_row_buttons = false;
$each(this.rows,function(i,editor) {
// Hide the move down button for the last row
if(editor.movedown_button) {
if(i === self.rows.length - 1) {
editor.movedown_button.style.display = 'none';
}
else {
need_row_buttons = true;
editor.movedown_button.style.display = '';
}
}
// Hide the delete button if we have minItems items
if(editor.delete_button) {
if(minItems) {
editor.delete_button.style.display = 'none';
}
else {
need_row_buttons = true;
editor.delete_button.style.display = '';
}
}
if(editor.moveup_button) {
need_row_buttons = true;
}
});
// Show/hide controls column in table
$each(this.rows,function(i,editor) {
if(need_row_buttons) {
editor.controls_cell.style.display = '';
}
else {
editor.controls_cell.style.display = 'none';
}
});
if(need_row_buttons) {
this.controls_header_cell.style.display = '';
}
else {
this.controls_header_cell.style.display = 'none';
}
var controls_needed = false;
if(!this.value.length) {
this.delete_last_row_button.style.display = 'none';
this.remove_all_rows_button.style.display = 'none';
this.table.style.display = 'none';
}
else if(this.value.length === 1) {
this.table.style.display = '';
this.remove_all_rows_button.style.display = 'none';
// If there are minItems items in the array, or configured to hide the delete_last_row button, hide the delete button beneath the rows
if(minItems || this.hide_delete_last_row_buttons) {
this.delete_last_row_button.style.display = 'none';
}
else {
this.delete_last_row_button.style.display = '';
controls_needed = true;
}
}
else {
this.table.style.display = '';
if(minItems || this.hide_delete_last_row_buttons) {
this.delete_last_row_button.style.display = 'none';
}
else {
this.delete_last_row_button.style.display = '';
controls_needed = true;
}
if(minItems || this.hide_delete_all_rows_buttons) {
this.remove_all_rows_button.style.display = 'none';
}
else {
this.remove_all_rows_button.style.display = '';
controls_needed = true;
}
}
// If there are maxItems in the array, hide the add button beneath the rows
if((this.schema.maxItems && this.schema.maxItems <= this.rows.length) || this.hide_add_button) {
this.add_row_button.style.display = 'none';
}
else {
this.add_row_button.style.display = '';
controls_needed = true;
}
if(!controls_needed) {
this.controls.style.display = 'none';
}
else {
this.controls.style.display = '';
}
},
refreshValue: function() {
var self = this;
this.value = [];
$each(this.rows,function(i,editor) {
// Get the value for this editor
self.value[i] = editor.getValue();
});
this.serialized = JSON.stringify(this.value);
},
addRow: function(value) {
var self = this;
var i = this.rows.length;
self.rows[i] = this.getElementEditor(i);
var controls_holder = self.rows[i].table_controls;
// Buttons to delete row, move row up, and move row down
if(!this.hide_delete_buttons) {
self.rows[i].delete_button = this.getButton('','delete',this.translate('edt_msg_button_delete_row_title_short'));
self.rows[i].delete_button.className += ' delete';
self.rows[i].delete_button.setAttribute('data-i',i);
self.rows[i].delete_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
var value = self.getValue();
var newval = [];
$each(value,function(j,row) {
if(j===i) return; // If this is the one we're deleting
newval.push(row);
});
self.setValue(newval);
self.onChange(true);
});
controls_holder.appendChild(self.rows[i].delete_button);
}
if(i && !this.hide_move_buttons) {
self.rows[i].moveup_button = this.getButton('','moveup',this.translate('edt_msg_button_move_up_title'));
self.rows[i].moveup_button.className += ' moveup';
self.rows[i].moveup_button.setAttribute('data-i',i);
self.rows[i].moveup_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
if(i<=0) return;
var rows = self.getValue();
var tmp = rows[i-1];
rows[i-1] = rows[i];
rows[i] = tmp;
self.setValue(rows);
self.onChange(true);
});
controls_holder.appendChild(self.rows[i].moveup_button);
}
if(!this.hide_move_buttons) {
self.rows[i].movedown_button = this.getButton('','movedown',this.translate('edt_msg_button_move_down_title'));
self.rows[i].movedown_button.className += ' movedown';
self.rows[i].movedown_button.setAttribute('data-i',i);
self.rows[i].movedown_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var i = this.getAttribute('data-i')*1;
var rows = self.getValue();
if(i>=rows.length-1) return;
var tmp = rows[i+1];
rows[i+1] = rows[i];
rows[i] = tmp;
self.setValue(rows);
self.onChange(true);
});
controls_holder.appendChild(self.rows[i].movedown_button);
}
if(value) self.rows[i].setValue(value);
},
addControls: function() {
var self = this;
this.collapsed = false;
this.toggle_button = this.getButton('','collapse',this.translate('edt_msg_button_collapse'));
if(this.title_controls) {
this.title_controls.appendChild(this.toggle_button);
this.toggle_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
if(self.collapsed) {
self.collapsed = false;
self.panel.style.display = '';
self.setButtonText(this,'','collapse',self.translate('edt_msg_button_collapse'));
}
else {
self.collapsed = true;
self.panel.style.display = 'none';
self.setButtonText(this,'','expand',self.translate('edt_msg_button_expand'));
}
});
// If it should start collapsed
if(this.options.collapsed) {
$trigger(this.toggle_button,'click');
}
// Collapse button disabled
if(this.schema.options && typeof this.schema.options.disable_collapse !== "undefined") {
if(this.schema.options.disable_collapse) this.toggle_button.style.display = 'none';
}
else if(this.jsoneditor.options.disable_collapse) {
this.toggle_button.style.display = 'none';
}
}
// Add "new row" and "delete last" buttons below editor
this.add_row_button = this.getButton(this.getItemTitle(),'add',this.translate('edt_msg_button_add_row_title',[this.getItemTitle()]));
this.add_row_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.addRow();
self.refreshValue();
self.refreshRowButtons();
self.onChange(true);
});
self.controls.appendChild(this.add_row_button);
this.delete_last_row_button = this.getButton(this.translate('edt_msg_button_delete_last',[this.getItemTitle()]),'delete',this.translate('edt_msg_button_delete_last_title',[this.getItemTitle()]));
this.delete_last_row_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
var rows = self.getValue();
rows.pop();
self.setValue(rows);
self.onChange(true);
});
self.controls.appendChild(this.delete_last_row_button);
this.remove_all_rows_button = this.getButton(this.translate('edt_msg_button_delete_all'),'delete',this.translate('edt_msg_button_delete_all_title'));
this.remove_all_rows_button.addEventListener('click',function(e) {
e.preventDefault();
e.stopPropagation();
self.setValue([]);
self.onChange(true);
});
self.controls.appendChild(this.remove_all_rows_button);
}
});
// Multiple Editor (for when `type` is an array)
JSONEditor.defaults.editors.multiple = JSONEditor.AbstractEditor.extend({
register: function() {
if(this.editors) {
for(var i=0; i<this.editors.length; i++) {
if(!this.editors[i]) continue;
this.editors[i].unregister();
}
if(this.editors[this.type]) this.editors[this.type].register();
}
this._super();
},
unregister: function() {
this._super();
if(this.editors) {
for(var i=0; i<this.editors.length; i++) {
if(!this.editors[i]) continue;
this.editors[i].unregister();
}
}
},
getNumColumns: function() {
if(!this.editors[this.type]) return 4;
return Math.max(this.editors[this.type].getNumColumns(),4);
},
enable: function() {
if(this.editors) {
for(var i=0; i<this.editors.length; i++) {
if(!this.editors[i]) continue;
this.editors[i].enable();
}
}
this.switcher.disabled = false;
this._super();
},
disable: function() {
if(this.editors) {
for(var i=0; i<this.editors.length; i++) {
if(!this.editors[i]) continue;
this.editors[i].disable();
}
}
this.switcher.disabled = true;
this._super();
},
switchEditor: function(i) {
var self = this;
if(!this.editors[i]) {
this.buildChildEditor(i);
}
var current_value = self.getValue();
self.type = i;
self.register();
$each(self.editors,function(type,editor) {
if(!editor) return;
if(self.type === type) {
if(self.keep_values) editor.setValue(current_value,true);
editor.container.style.display = '';
}
else editor.container.style.display = 'none';
});
self.refreshValue();
self.refreshHeaderText();
},
buildChildEditor: function(i) {
var self = this;
var type = this.types[i];
var holder = self.theme.getChildEditorHolder();
self.editor_holder.appendChild(holder);
var schema;
if(typeof type === "string") {
schema = $extend({},self.schema);
schema.type = type;
}
else {
schema = $extend({},self.schema,type);
schema = self.jsoneditor.expandRefs(schema);
// If we need to merge `required` arrays
if(type.required && Array.isArray(type.required) && self.schema.required && Array.isArray(self.schema.required)) {
schema.required = self.schema.required.concat(type.required);
}
}
var editor = self.jsoneditor.getEditorClass(schema);
self.editors[i] = self.jsoneditor.createEditor(editor,{
jsoneditor: self.jsoneditor,
schema: schema,
container: holder,
path: self.path,
parent: self,
required: true
});
self.editors[i].preBuild();
self.editors[i].build();
self.editors[i].postBuild();
if(self.editors[i].header) self.editors[i].header.style.display = 'none';
self.editors[i].option = self.switcher_options[i];
holder.addEventListener('change_header_text',function() {
self.refreshHeaderText();
});
if(i !== self.type) holder.style.display = 'none';
},
preBuild: function() {
var self = this;
this.types = [];
this.type = 0;
this.editors = [];
this.validators = [];
this.keep_values = true;
if(typeof this.jsoneditor.options.keep_oneof_values !== "undefined") this.keep_values = this.jsoneditor.options.keep_oneof_values;
if(typeof this.options.keep_oneof_values !== "undefined") this.keep_values = this.options.keep_oneof_values;
if(this.schema.oneOf) {
this.oneOf = true;
this.types = this.schema.oneOf;
delete this.schema.oneOf;
}
else if(this.schema.anyOf) {
this.anyOf = true;
this.types = this.schema.anyOf;
delete this.schema.anyOf;
}
else {
if(!this.schema.type || this.schema.type === "any") {
this.types = ['string','number','integer','boolean','object','array','null'];
// If any of these primitive types are disallowed
if(this.schema.disallow) {
var disallow = this.schema.disallow;
if(typeof disallow !== 'object' || !(Array.isArray(disallow))) {
disallow = [disallow];
}
var allowed_types = [];
$each(this.types,function(i,type) {
if(disallow.indexOf(type) === -1) allowed_types.push(type);
});
this.types = allowed_types;
}
}
else if(Array.isArray(this.schema.type)) {
this.types = this.schema.type;
}
else {
this.types = [this.schema.type];
}
delete this.schema.type;
}
this.display_text = this.getDisplayText(this.types);
},
build: function() {
var self = this;
var container = this.container;
this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
this.container.appendChild(this.header);
this.switcher = this.theme.getSwitcher(this.display_text);
container.appendChild(this.switcher);
this.switcher.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.switchEditor(self.display_text.indexOf(this.value));
self.onChange(true);
});
this.editor_holder = document.createElement('div');
container.appendChild(this.editor_holder);
var validator_options = {};
if(self.jsoneditor.options.custom_validators) {
validator_options.custom_validators = self.jsoneditor.options.custom_validators;
}
this.switcher_options = this.theme.getSwitcherOptions(this.switcher);
$each(this.types,function(i,type) {
self.editors[i] = false;
var schema;
if(typeof type === "string") {
schema = $extend({},self.schema);
schema.type = type;
}
else {
schema = $extend({},self.schema,type);
// If we need to merge `required` arrays
if(type.required && Array.isArray(type.required) && self.schema.required && Array.isArray(self.schema.required)) {
schema.required = self.schema.required.concat(type.required);
}
}
self.validators[i] = new JSONEditor.Validator(self.jsoneditor,schema,validator_options);
});
this.switchEditor(0);
},
onChildEditorChange: function(editor) {
if(this.editors[this.type]) {
this.refreshValue();
this.refreshHeaderText();
}
this._super();
},
refreshHeaderText: function() {
var display_text = this.getDisplayText(this.types);
$each(this.switcher_options, function(i,option) {
option.textContent = display_text[i];
});
},
refreshValue: function() {
this.value = this.editors[this.type].getValue();
},
setValue: function(val,initial) {
// Determine type by getting the first one that validates
var self = this;
$each(this.validators, function(i,validator) {
if(!validator.validate(val).length) {
self.type = i;
self.switcher.value = self.display_text[i];
return false;
}
});
this.switchEditor(this.type);
this.editors[this.type].setValue(val,initial);
this.refreshValue();
self.onChange();
},
destroy: function() {
$each(this.editors, function(type,editor) {
if(editor) editor.destroy();
});
if(this.editor_holder && this.editor_holder.parentNode) this.editor_holder.parentNode.removeChild(this.editor_holder);
if(this.switcher && this.switcher.parentNode) this.switcher.parentNode.removeChild(this.switcher);
this._super();
},
showValidationErrors: function(errors) {
var self = this;
// oneOf and anyOf error paths need to remove the oneOf[i] part before passing to child editors
if(this.oneOf || this.anyOf) {
var check_part = this.oneOf? 'oneOf' : 'anyOf';
$each(this.editors,function(i,editor) {
if(!editor) return;
var check = self.path+'.'+check_part+'['+i+']';
var new_errors = [];
$each(errors, function(j,error) {
if(error.path.substr(0,check.length)===check) {
var new_error = $extend({},error);
new_error.path = self.path+new_error.path.substr(check.length);
new_errors.push(new_error);
}
});
editor.showValidationErrors(new_errors);
});
}
else {
$each(this.editors,function(type,editor) {
if(!editor) return;
editor.showValidationErrors(errors);
});
}
}
});
// Enum Editor (used for objects and arrays with enumerated values)
JSONEditor.defaults.editors["enum"] = JSONEditor.AbstractEditor.extend({
getNumColumns: function() {
return 4;
},
build: function() {
var container = this.container;
this.title = this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
this.container.appendChild(this.title);
this.options.enum_titles = this.options.enum_titles || [];
this["enum"] = this.schema["enum"];
this.selected = 0;
this.select_options = [];
this.html_values = [];
var self = this;
for(var i=0; i<this["enum"].length; i++) {
this.select_options[i] = this.options.enum_titles[i] || "Value "+(i+1);
this.html_values[i] = this.getHTML(this["enum"][i]);
}
// Switcher
this.switcher = this.theme.getSwitcher(this.select_options);
this.container.appendChild(this.switcher);
// Display area
this.display_area = this.theme.getIndentedPanel();
this.container.appendChild(this.display_area);
if(this.options.hide_display) this.display_area.style.display = "none";
this.switcher.addEventListener('change',function() {
self.selected = self.select_options.indexOf(this.value);
self.value = self["enum"][self.selected];
self.refreshValue();
self.onChange(true);
});
this.value = this["enum"][0];
this.refreshValue();
if(this["enum"].length === 1) this.switcher.style.display = 'none';
},
refreshValue: function() {
var self = this;
self.selected = -1;
var stringified = JSON.stringify(this.value);
$each(this["enum"], function(i, el) {
if(stringified === JSON.stringify(el)) {
self.selected = i;
return false;
}
});
if(self.selected<0) {
self.setValue(self["enum"][0]);
return;
}
this.switcher.value = this.select_options[this.selected];
this.display_area.innerHTML = this.html_values[this.selected];
},
enable: function() {
if(!this.always_disabled) this.switcher.disabled = false;
this._super();
},
disable: function() {
this.switcher.disabled = true;
this._super();
},
getHTML: function(el) {
var self = this;
if(el === null) {
return '<em>null</em>';
}
// Array or Object
else if(typeof el === "object") {
// TODO: use theme
var ret = '';
$each(el,function(i,child) {
var html = self.getHTML(child);
// Add the keys to object children
if(!(Array.isArray(el))) {
// TODO: use theme
html = '<div><em>'+i+'</em>: '+html+'</div>';
}
// TODO: use theme
ret += '<li>'+html+'</li>';
});
if(Array.isArray(el)) ret = '<ol>'+ret+'</ol>';
else ret = "<ul style='margin-top:0;margin-bottom:0;padding-top:0;padding-bottom:0;'>"+ret+'</ul>';
return ret;
}
// Boolean
else if(typeof el === "boolean") {
return el? 'true' : 'false';
}
// String
else if(typeof el === "string") {
return el.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
// Number
else {
return el;
}
},
setValue: function(val) {
if(this.value !== val) {
this.value = val;
this.refreshValue();
this.onChange();
}
},
destroy: function() {
if(this.display_area && this.display_area.parentNode) this.display_area.parentNode.removeChild(this.display_area);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.switcher && this.switcher.parentNode) this.switcher.parentNode.removeChild(this.switcher);
this._super();
}
});
JSONEditor.defaults.editors.select = JSONEditor.AbstractEditor.extend({
setValue: function(value,initial) {
value = this.typecast(value||'');
// Sanitize value before setting it
var sanitized = value;
if(this.enum_values.indexOf(sanitized) < 0) {
sanitized = this.enum_values[0];
}
if(this.value === sanitized) {
return;
}
this.input.value = this.enum_options[this.enum_values.indexOf(sanitized)];
if(this.select2) this.select2.select2('val',this.input.value);
this.value = sanitized;
this.onChange();
},
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('id',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('id');
},
getNumColumns: function() {
if(!this.enum_options) return 3;
var longest_text = this.getTitle().length;
for(var i=0; i<this.enum_options.length; i++) {
longest_text = Math.max(longest_text,this.enum_options[i].length+4);
}
return Math.min(12,Math.max(longest_text/7,2));
},
typecast: function(value) {
if(this.schema.type === "boolean") {
return !!value;
}
else if(this.schema.type === "number") {
return 1*value;
}
else if(this.schema.type === "integer") {
return Math.floor(value*1);
}
else {
return ""+value;
}
},
getValue: function() {
return this.value;
},
preBuild: function() {
var self = this;
this.input_type = 'select';
this.enum_options = [];
this.enum_values = [];
this.enum_display = [];
var i;
// Enum options enumerated
if(this.schema["enum"]) {
var display = this.schema.options && this.schema.options.enum_titles || [];
$each(this.schema["enum"],function(i,option) {
self.enum_options[i] = ""+option;
self.enum_display[i] = ""+(display[i] || option);
self.enum_values[i] = self.typecast(option);
});
if(!this.isRequired()){
self.enum_display.unshift(' ');
self.enum_options.unshift('undefined');
self.enum_values.unshift(undefined);
}
}
// Boolean
else if(this.schema.type === "boolean") {
self.enum_display = this.schema.options && this.schema.options.enum_titles || ['true','false'];
self.enum_options = ['1',''];
self.enum_values = [true,false];
if(!this.isRequired()){
self.enum_display.unshift(' ');
self.enum_options.unshift('undefined');
self.enum_values.unshift(undefined);
}
}
// Dynamic Enum
else if(this.schema.enumSource) {
this.enumSource = [];
this.enum_display = [];
this.enum_options = [];
this.enum_values = [];
// Shortcut declaration for using a single array
if(!(Array.isArray(this.schema.enumSource))) {
if(this.schema.enumValue) {
this.enumSource = [
{
source: this.schema.enumSource,
value: this.schema.enumValue
}
];
}
else {
this.enumSource = [
{
source: this.schema.enumSource
}
];
}
}
else {
for(i=0; i<this.schema.enumSource.length; i++) {
// Shorthand for watched variable
if(typeof this.schema.enumSource[i] === "string") {
this.enumSource[i] = {
source: this.schema.enumSource[i]
};
}
// Make a copy of the schema
else if(!(Array.isArray(this.schema.enumSource[i]))) {
this.enumSource[i] = $extend({},this.schema.enumSource[i]);
}
else {
this.enumSource[i] = this.schema.enumSource[i];
}
}
}
// Now, enumSource is an array of sources
// Walk through this array and fix up the values
for(i=0; i<this.enumSource.length; i++) {
if(this.enumSource[i].value) {
this.enumSource[i].value = this.jsoneditor.compileTemplate(this.enumSource[i].value, this.template_engine);
}
if(this.enumSource[i].title) {
this.enumSource[i].title = this.jsoneditor.compileTemplate(this.enumSource[i].title, this.template_engine);
}
if(this.enumSource[i].filter) {
this.enumSource[i].filter = this.jsoneditor.compileTemplate(this.enumSource[i].filter, this.template_engine);
}
}
}
// Other, not supported
else {
throw "'select' editor requires the enum property to be set.";
}
},
build: function() {
var self = this;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.schema.append) this.append = this.theme.getFormInputAppend(this.getAppend());
if(this.options.compact) this.container.className += ' compact';
this.input = this.theme.getSelectInput(this.enum_options);
this.theme.setSelectOptions(this.input,this.enum_options,this.enum_display);
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
this.input.disabled = true;
}
this.input.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.onInputChange();
});
if(this.formname)this.label.setAttribute('for',this.formname);
this.control = this.theme.getFormControl(this.label, this.input, this.description);
this.container.appendChild(this.control);
this.value = this.enum_values[0];
},
onInputChange: function() {
var val = this.input.value;
var new_val;
// Invalid option, use first option instead
if(this.enum_options.indexOf(val) === -1) {
new_val = this.enum_values[0];
}
else {
new_val = this.enum_values[this.enum_options.indexOf(val)];
}
// If valid hasn't changed
if(new_val === this.value) return;
// Store new value and propogate change event
this.value = new_val;
this.onChange(true);
},
setupSelect2: function() {
// If the Select2 library is loaded use it when we have lots of items
if(window.jQuery && window.jQuery.fn && window.jQuery.fn.select2 && (this.enum_options.length > 2 || (this.enum_options.length && this.enumSource))) {
var options = $extend({},JSONEditor.plugins.select2);
if(this.schema.options && this.schema.options.select2_options) options = $extend(options,this.schema.options.select2_options);
this.select2 = window.jQuery(this.input).select2(options);
var self = this;
this.select2.on('select2-blur',function() {
self.input.value = self.select2.select2('val');
self.onInputChange();
});
this.select2.on('change',function() {
self.input.value = self.select2.select2('val');
self.onInputChange();
});
}
else {
this.select2 = null;
}
},
postBuild: function() {
this._super();
this.theme.afterInputReady(this.input);
this.setupSelect2();
},
onWatchedFieldChange: function() {
var self = this, vars, j;
// If this editor uses a dynamic select box
if(this.enumSource) {
vars = this.getWatchedFieldValues();
var select_options = [];
var select_titles = [];
for(var i=0; i<this.enumSource.length; i++) {
// Constant values
if(Array.isArray(this.enumSource[i])) {
select_options = select_options.concat(this.enumSource[i]);
select_titles = select_titles.concat(this.enumSource[i]);
}
else {
var items = [];
// Static list of items
if(Array.isArray(this.enumSource[i].source)) {
items = this.enumSource[i].source;
// A watched field
} else {
items = vars[this.enumSource[i].source];
}
if(items) {
// Only use a predefined part of the array
if(this.enumSource[i].slice) {
items = Array.prototype.slice.apply(items,this.enumSource[i].slice);
}
// Filter the items
if(this.enumSource[i].filter) {
var new_items = [];
for(j=0; j<items.length; j++) {
if(this.enumSource[i].filter({i:j,item:items[j],watched:vars})) new_items.push(items[j]);
}
items = new_items;
}
var item_titles = [];
var item_values = [];
for(j=0; j<items.length; j++) {
var item = items[j];
// Rendered value
if(this.enumSource[i].value) {
item_values[j] = this.enumSource[i].value({
i: j,
item: item
});
}
// Use value directly
else {
item_values[j] = items[j];
}
// Rendered title
if(this.enumSource[i].title) {
item_titles[j] = this.enumSource[i].title({
i: j,
item: item
});
}
// Use value as the title also
else {
item_titles[j] = item_values[j];
}
}
// TODO: sort
select_options = select_options.concat(item_values);
select_titles = select_titles.concat(item_titles);
}
}
}
var prev_value = this.value;
this.theme.setSelectOptions(this.input, select_options, select_titles);
this.enum_options = select_options;
this.enum_display = select_titles;
this.enum_values = select_options;
if(this.select2) {
this.select2.select2('destroy');
}
// If the previous value is still in the new select options, stick with it
if(select_options.indexOf(prev_value) !== -1) {
this.input.value = prev_value;
this.value = prev_value;
}
// Otherwise, set the value to the first select option
else {
this.input.value = select_options[0];
this.value = select_options[0] || "";
if(this.parent) this.parent.onChildEditorChange(this);
else this.jsoneditor.onChange();
this.jsoneditor.notifyWatchers(this.path);
}
this.setupSelect2();
}
this._super();
},
enable: function() {
if(!this.always_disabled) {
this.input.disabled = false;
if(this.select2) this.select2.select2("enable",true);
}
this._super();
},
disable: function() {
this.input.disabled = true;
if(this.select2) this.select2.select2("enable",false);
this._super();
},
destroy: function() {
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.select2) {
this.select2.select2('destroy');
this.select2 = null;
}
this._super();
}
});
JSONEditor.defaults.editors.selectize = JSONEditor.AbstractEditor.extend({
setValue: function(value,initial) {
value = this.typecast(value||'');
// Sanitize value before setting it
var sanitized = value;
if(this.enum_values.indexOf(sanitized) < 0) {
sanitized = this.enum_values[0];
}
if(this.value === sanitized) {
return;
}
this.input.value = this.enum_options[this.enum_values.indexOf(sanitized)];
if(this.selectize) {
this.selectize[0].selectize.addItem(sanitized);
}
this.value = sanitized;
this.onChange();
},
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('name',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('name');
},
getNumColumns: function() {
if(!this.enum_options) return 3;
var longest_text = this.getTitle().length;
for(var i=0; i<this.enum_options.length; i++) {
longest_text = Math.max(longest_text,this.enum_options[i].length+4);
}
return Math.min(12,Math.max(longest_text/7,2));
},
typecast: function(value) {
if(this.schema.type === "boolean") {
return !!value;
}
else if(this.schema.type === "number") {
return 1*value;
}
else if(this.schema.type === "integer") {
return Math.floor(value*1);
}
else {
return ""+value;
}
},
getValue: function() {
return this.value;
},
preBuild: function() {
var self = this;
this.input_type = 'select';
this.enum_options = [];
this.enum_values = [];
this.enum_display = [];
var i;
// Enum options enumerated
if(this.schema.enum) {
var display = this.schema.options && this.schema.options.enum_titles || [];
$each(this.schema.enum,function(i,option) {
self.enum_options[i] = ""+option;
self.enum_display[i] = ""+(display[i] || option);
self.enum_values[i] = self.typecast(option);
});
}
// Boolean
else if(this.schema.type === "boolean") {
self.enum_display = this.schema.options && this.schema.options.enum_titles || ['true','false'];
self.enum_options = ['1','0'];
self.enum_values = [true,false];
}
// Dynamic Enum
else if(this.schema.enumSource) {
this.enumSource = [];
this.enum_display = [];
this.enum_options = [];
this.enum_values = [];
// Shortcut declaration for using a single array
if(!(Array.isArray(this.schema.enumSource))) {
if(this.schema.enumValue) {
this.enumSource = [
{
source: this.schema.enumSource,
value: this.schema.enumValue
}
];
}
else {
this.enumSource = [
{
source: this.schema.enumSource
}
];
}
}
else {
for(i=0; i<this.schema.enumSource.length; i++) {
// Shorthand for watched variable
if(typeof this.schema.enumSource[i] === "string") {
this.enumSource[i] = {
source: this.schema.enumSource[i]
};
}
// Make a copy of the schema
else if(!(Array.isArray(this.schema.enumSource[i]))) {
this.enumSource[i] = $extend({},this.schema.enumSource[i]);
}
else {
this.enumSource[i] = this.schema.enumSource[i];
}
}
}
// Now, enumSource is an array of sources
// Walk through this array and fix up the values
for(i=0; i<this.enumSource.length; i++) {
if(this.enumSource[i].value) {
this.enumSource[i].value = this.jsoneditor.compileTemplate(this.enumSource[i].value, this.template_engine);
}
if(this.enumSource[i].title) {
this.enumSource[i].title = this.jsoneditor.compileTemplate(this.enumSource[i].title, this.template_engine);
}
if(this.enumSource[i].filter) {
this.enumSource[i].filter = this.jsoneditor.compileTemplate(this.enumSource[i].filter, this.template_engine);
}
}
}
// Other, not supported
else {
throw "'select' editor requires the enum property to be set.";
}
},
build: function() {
var self = this;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.schema.append) this.append = this.theme.getFormInputAppend(this.getAppend());
if(this.options.compact) this.container.className += ' compact';
this.input = this.theme.getSelectInput(this.enum_options);
this.theme.setSelectOptions(this.input,this.enum_options,this.enum_display);
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
this.input.disabled = true;
}
this.input.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.onInputChange();
});
this.control = this.theme.getFormControl(this.label, this.input, this.description);
this.container.appendChild(this.control);
this.value = this.enum_values[0];
},
onInputChange: function() {
var val = this.input.value;
var sanitized = val;
if(this.enum_options.indexOf(val) === -1) {
sanitized = this.enum_options[0];
}
this.value = this.enum_values[this.enum_options.indexOf(val)];
this.onChange(true);
},
setupSelectize: function() {
// If the Selectize library is loaded use it when we have lots of items
var self = this;
if(window.jQuery && window.jQuery.fn && window.jQuery.fn.selectize && (this.enum_options.length >= 2 || (this.enum_options.length && this.enumSource))) {
var options = $extend({},JSONEditor.plugins.selectize);
if(this.schema.options && this.schema.options.selectize_options) options = $extend(options,this.schema.options.selectize_options);
this.selectize = window.jQuery(this.input).selectize($extend(options,
{
create: true,
onChange : function() {
self.onInputChange();
}
}));
}
else {
this.selectize = null;
}
},
postBuild: function() {
this._super();
this.theme.afterInputReady(this.input);
this.setupSelectize();
},
onWatchedFieldChange: function() {
var self = this, vars, j;
// If this editor uses a dynamic select box
if(this.enumSource) {
vars = this.getWatchedFieldValues();
var select_options = [];
var select_titles = [];
for(var i=0; i<this.enumSource.length; i++) {
// Constant values
if(Array.isArray(this.enumSource[i])) {
select_options = select_options.concat(this.enumSource[i]);
select_titles = select_titles.concat(this.enumSource[i]);
}
// A watched field
else if(vars[this.enumSource[i].source]) {
var items = vars[this.enumSource[i].source];
// Only use a predefined part of the array
if(this.enumSource[i].slice) {
items = Array.prototype.slice.apply(items,this.enumSource[i].slice);
}
// Filter the items
if(this.enumSource[i].filter) {
var new_items = [];
for(j=0; j<items.length; j++) {
if(this.enumSource[i].filter({i:j,item:items[j]})) new_items.push(items[j]);
}
items = new_items;
}
var item_titles = [];
var item_values = [];
for(j=0; j<items.length; j++) {
var item = items[j];
// Rendered value
if(this.enumSource[i].value) {
item_values[j] = this.enumSource[i].value({
i: j,
item: item
});
}
// Use value directly
else {
item_values[j] = items[j];
}
// Rendered title
if(this.enumSource[i].title) {
item_titles[j] = this.enumSource[i].title({
i: j,
item: item
});
}
// Use value as the title also
else {
item_titles[j] = item_values[j];
}
}
// TODO: sort
select_options = select_options.concat(item_values);
select_titles = select_titles.concat(item_titles);
}
}
var prev_value = this.value;
this.theme.setSelectOptions(this.input, select_options, select_titles);
this.enum_options = select_options;
this.enum_display = select_titles;
this.enum_values = select_options;
// If the previous value is still in the new select options, stick with it
if(select_options.indexOf(prev_value) !== -1) {
this.input.value = prev_value;
this.value = prev_value;
}
// Otherwise, set the value to the first select option
else {
this.input.value = select_options[0];
this.value = select_options[0] || "";
if(this.parent) this.parent.onChildEditorChange(this);
else this.jsoneditor.onChange();
this.jsoneditor.notifyWatchers(this.path);
}
if(this.selectize) {
// Update the Selectize options
this.updateSelectizeOptions(select_options);
}
else {
this.setupSelectize();
}
this._super();
}
},
updateSelectizeOptions: function(select_options) {
var selectized = this.selectize[0].selectize,
self = this;
selectized.off();
selectized.clearOptions();
for(var n in select_options) {
selectized.addOption({value:select_options[n],text:select_options[n]});
}
selectized.addItem(this.value);
selectized.on('change',function() {
self.onInputChange();
});
},
enable: function() {
if(!this.always_disabled) {
this.input.disabled = false;
if(this.selectize) {
this.selectize[0].selectize.unlock();
}
}
this._super();
},
disable: function() {
this.input.disabled = true;
if(this.selectize) {
this.selectize[0].selectize.lock();
}
this._super();
},
destroy: function() {
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.selectize) {
this.selectize[0].selectize.destroy();
this.selectize = null;
}
this._super();
}
});
JSONEditor.defaults.editors.multiselect = JSONEditor.AbstractEditor.extend({
preBuild: function() {
this._super();
var i;
this.select_options = {};
this.select_values = {};
var items_schema = this.jsoneditor.expandRefs(this.schema.items || {});
var e = items_schema["enum"] || [];
var t = items_schema.options? items_schema.options.enum_titles || [] : [];
this.option_keys = [];
this.option_titles = [];
for(i=0; i<e.length; i++) {
// If the sanitized value is different from the enum value, don't include it
if(this.sanitize(e[i]) !== e[i]) continue;
this.option_keys.push(e[i]+"");
this.option_titles.push((t[i]||e[i])+"");
this.select_values[e[i]+""] = e[i];
}
},
build: function() {
var self = this, i;
if(!this.options.compact) this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.schema.append) this.append = this.theme.getFormInputAppend(this.getAppend());
if((!this.schema.format && this.option_keys.length < 8) || this.schema.format === "checkbox") {
this.input_type = 'checkboxes';
this.inputs = {};
this.controls = {};
for(i=0; i<this.option_keys.length; i++) {
this.inputs[this.option_keys[i]] = this.theme.getCheckbox();
this.select_options[this.option_keys[i]] = this.inputs[this.option_keys[i]];
var label = this.theme.getCheckboxLabel(this.option_titles[i]);
this.controls[this.option_keys[i]] = this.theme.getFormControl(label, this.inputs[this.option_keys[i]]);
}
this.control = this.theme.getMultiCheckboxHolder(this.controls,this.label,this.description);
}
else {
this.input_type = 'select';
this.input = this.theme.getSelectInput(this.option_keys);
this.theme.setSelectOptions(this.input,this.option_keys,this.option_titles);
this.input.multiple = true;
this.input.size = Math.min(10,this.option_keys.length);
for(i=0; i<this.option_keys.length; i++) {
this.select_options[this.option_keys[i]] = this.input.children[i];
}
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
this.input.disabled = true;
}
this.control = this.theme.getFormControl(this.label, this.input, this.description);
}
this.container.appendChild(this.control);
this.control.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
var new_value = [];
for(i = 0; i<self.option_keys.length; i++) {
if(self.select_options[self.option_keys[i]].selected || self.select_options[self.option_keys[i]].checked) new_value.push(self.select_values[self.option_keys[i]]);
}
self.updateValue(new_value);
self.onChange(true);
});
},
setValue: function(value, initial) {
var i;
value = value || [];
if(typeof value !== "object") value = [value];
else if(!(Array.isArray(value))) value = [];
// Make sure we are dealing with an array of strings so we can check for strict equality
for(i=0; i<value.length; i++) {
if(typeof value[i] !== "string") value[i] += "";
}
// Update selected status of options
for(i in this.select_options) {
if(!this.select_options.hasOwnProperty(i)) continue;
this.select_options[i][this.input_type === "select"? "selected" : "checked"] = (value.indexOf(i) !== -1);
}
this.updateValue(value);
this.onChange();
},
setupSelect2: function() {
if(window.jQuery && window.jQuery.fn && window.jQuery.fn.select2) {
var options = window.jQuery.extend({},JSONEditor.plugins.select2);
if(this.schema.options && this.schema.options.select2_options) options = $extend(options,this.schema.options.select2_options);
this.select2 = window.jQuery(this.input).select2(options);
var self = this;
this.select2.on('select2-blur',function() {
var val =self.select2.select2('val');
self.value = val;
self.onChange(true);
});
}
else {
this.select2 = null;
}
},
onInputChange: function() {
this.value = this.input.value;
this.onChange(true);
},
postBuild: function() {
this._super();
this.setupSelect2();
},
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('name',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('name');
},
getNumColumns: function() {
var longest_text = this.getTitle().length;
for(var i in this.select_values) {
if(!this.select_values.hasOwnProperty(i)) continue;
longest_text = Math.max(longest_text,(this.select_values[i]+"").length+4);
}
return Math.min(12,Math.max(longest_text/7,2));
},
updateValue: function(value) {
var changed = false;
var new_value = [];
for(var i=0; i<value.length; i++) {
if(!this.select_options[value[i]+""]) {
changed = true;
continue;
}
var sanitized = this.sanitize(this.select_values[value[i]]);
new_value.push(sanitized);
if(sanitized !== value[i]) changed = true;
}
this.value = new_value;
if(this.select2) this.select2.select2('val',this.value);
return changed;
},
sanitize: function(value) {
if(this.schema.items.type === "number") {
return 1*value;
}
else if(this.schema.items.type === "integer") {
return Math.floor(value*1);
}
else {
return ""+value;
}
},
enable: function() {
if(!this.always_disabled) {
if(this.input) {
this.input.disabled = false;
}
else if(this.inputs) {
for(var i in this.inputs) {
if(!this.inputs.hasOwnProperty(i)) continue;
this.inputs[i].disabled = false;
}
}
if(this.select2) this.select2.select2("enable",true);
}
this._super();
},
disable: function() {
if(this.input) {
this.input.disabled = true;
}
else if(this.inputs) {
for(var i in this.inputs) {
if(!this.inputs.hasOwnProperty(i)) continue;
this.inputs[i].disabled = true;
}
}
if(this.select2) this.select2.select2("enable",false);
this._super();
},
destroy: function() {
if(this.select2) {
this.select2.select2('destroy');
this.select2 = null;
}
this._super();
}
});
JSONEditor.defaults.editors.base64 = JSONEditor.AbstractEditor.extend({
getNumColumns: function() {
return 4;
},
build: function() {
var self = this;
this.title = this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
// Input that holds the base64 string
this.input = this.theme.getFormInputField('hidden');
this.container.appendChild(this.input);
// Don't show uploader if this is readonly
if(!this.schema.readOnly && !this.schema.readonly) {
if(!window.FileReader) throw "FileReader required for base64 editor";
// File uploader
this.uploader = this.theme.getFormInputField('file');
this.uploader.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
if(this.files && this.files.length) {
var fr = new FileReader();
fr.onload = function(evt) {
self.value = evt.target.result;
self.refreshPreview();
self.onChange(true);
fr = null;
};
fr.readAsDataURL(this.files[0]);
}
});
}
this.preview = this.theme.getFormInputDescription(this.schema.description);
this.container.appendChild(this.preview);
this.control = this.theme.getFormControl(this.label, this.uploader||this.input, this.preview);
this.container.appendChild(this.control);
},
refreshPreview: function() {
if(this.last_preview === this.value) return;
this.last_preview = this.value;
this.preview.innerHTML = '';
if(!this.value) return;
var mime = this.value.match(/^data:([^;,]+)[;,]/);
if(mime) mime = mime[1];
if(!mime) {
this.preview.innerHTML = '<em>Invalid data URI</em>';
}
else {
this.preview.innerHTML = '<strong>Type:</strong> '+mime+', <strong>Size:</strong> '+Math.floor((this.value.length-this.value.split(',')[0].length-1)/1.33333)+' bytes';
if(mime.substr(0,5)==="image") {
this.preview.innerHTML += '<br>';
var img = document.createElement('img');
img.style.maxWidth = '100%';
img.style.maxHeight = '100px';
img.src = this.value;
this.preview.appendChild(img);
}
}
},
enable: function() {
if(this.uploader) this.uploader.disabled = false;
this._super();
},
disable: function() {
if(this.uploader) this.uploader.disabled = true;
this._super();
},
setValue: function(val) {
if(this.value !== val) {
this.value = val;
this.input.value = this.value;
this.refreshPreview();
this.onChange();
}
},
destroy: function() {
if(this.preview && this.preview.parentNode) this.preview.parentNode.removeChild(this.preview);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.uploader && this.uploader.parentNode) this.uploader.parentNode.removeChild(this.uploader);
this._super();
}
});
JSONEditor.defaults.editors.upload = JSONEditor.AbstractEditor.extend({
getNumColumns: function() {
return 4;
},
build: function() {
var self = this;
this.title = this.header = this.label = this.theme.getFormInputLabel(this.getTitle());
// Input that holds the base64 string
this.input = this.theme.getFormInputField('hidden');
this.container.appendChild(this.input);
// Don't show uploader if this is readonly
if(!this.schema.readOnly && !this.schema.readonly) {
if(!this.jsoneditor.options.upload) throw "Upload handler required for upload editor";
// File uploader
this.uploader = this.theme.getFormInputField('file');
this.uploader.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
if(this.files && this.files.length) {
var fr = new FileReader();
fr.onload = function(evt) {
self.preview_value = evt.target.result;
self.refreshPreview();
self.onChange(true);
fr = null;
};
fr.readAsDataURL(this.files[0]);
}
});
}
var description = this.schema.description;
if (!description) description = '';
this.preview = this.theme.getFormInputDescription(description);
this.container.appendChild(this.preview);
this.control = this.theme.getFormControl(this.label, this.uploader||this.input, this.preview);
this.container.appendChild(this.control);
},
refreshPreview: function() {
if(this.last_preview === this.preview_value) return;
this.last_preview = this.preview_value;
this.preview.innerHTML = '';
if(!this.preview_value) return;
var self = this;
var mime = this.preview_value.match(/^data:([^;,]+)[;,]/);
if(mime) mime = mime[1];
if(!mime) mime = 'unknown';
var file = this.uploader.files[0];
this.preview.innerHTML = '<strong>Type:</strong> '+mime+', <strong>Size:</strong> '+file.size+' bytes';
if(mime.substr(0,5)==="image") {
this.preview.innerHTML += '<br>';
var img = document.createElement('img');
img.style.maxWidth = '100%';
img.style.maxHeight = '100px';
img.src = this.preview_value;
this.preview.appendChild(img);
}
this.preview.innerHTML += '<br>';
var uploadButton = this.getButton('Upload', 'upload', 'Upload');
this.preview.appendChild(uploadButton);
uploadButton.addEventListener('click',function(event) {
event.preventDefault();
uploadButton.setAttribute("disabled", "disabled");
self.theme.removeInputError(self.uploader);
if (self.theme.getProgressBar) {
self.progressBar = self.theme.getProgressBar();
self.preview.appendChild(self.progressBar);
}
self.jsoneditor.options.upload(self.path, file, {
success: function(url) {
self.setValue(url);
if(self.parent) self.parent.onChildEditorChange(self);
else self.jsoneditor.onChange();
if (self.progressBar) self.preview.removeChild(self.progressBar);
uploadButton.removeAttribute("disabled");
},
failure: function(error) {
self.theme.addInputError(self.uploader, error);
if (self.progressBar) self.preview.removeChild(self.progressBar);
uploadButton.removeAttribute("disabled");
},
updateProgress: function(progress) {
if (self.progressBar) {
if (progress) self.theme.updateProgressBar(self.progressBar, progress);
else self.theme.updateProgressBarUnknown(self.progressBar);
}
}
});
});
},
enable: function() {
if(this.uploader) this.uploader.disabled = false;
this._super();
},
disable: function() {
if(this.uploader) this.uploader.disabled = true;
this._super();
},
setValue: function(val) {
if(this.value !== val) {
this.value = val;
this.input.value = this.value;
this.onChange();
}
},
destroy: function() {
if(this.preview && this.preview.parentNode) this.preview.parentNode.removeChild(this.preview);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
if(this.uploader && this.uploader.parentNode) this.uploader.parentNode.removeChild(this.uploader);
this._super();
}
});
JSONEditor.defaults.editors.checkbox = JSONEditor.AbstractEditor.extend({
setValue: function(value,initial) {
this.value = !!value;
this.input.checked = this.value;
this.onChange();
},
register: function() {
this._super();
if(!this.input) return;
this.input.setAttribute('name',this.formname);
},
unregister: function() {
this._super();
if(!this.input) return;
this.input.removeAttribute('name');
},
getNumColumns: function() {
return Math.min(12,Math.max(this.getTitle().length/7,2));
},
build: function() {
var self = this;
if(!this.options.compact) {
this.label = this.header = this.theme.getCheckboxLabel(this.getTitle());
}
if(this.schema.description) this.description = this.theme.getFormInputDescription(this.schema.description);
if(this.options.compact) this.container.className += ' compact';
this.input = this.theme.getCheckbox();
if(this.formname)this.label.setAttribute('for',this.formname);
if(this.formname)this.input.setAttribute('id',this.formname);
this.control = this.theme.getFormControl(this.label, this.input, this.description);
if(this.schema.readOnly || this.schema.readonly) {
this.always_disabled = true;
this.input.disabled = true;
}
this.input.addEventListener('change',function(e) {
e.preventDefault();
e.stopPropagation();
self.value = this.checked;
self.onChange(true);
});
this.container.appendChild(this.control);
if (this.input.id.endsWith('_enable'))
this.container.appendChild(document.createElement('hr'));
},
enable: function() {
if(!this.always_disabled) {
this.input.disabled = false;
}
this._super();
},
disable: function() {
this.input.disabled = true;
this._super();
},
destroy: function() {
if(this.label && this.label.parentNode) this.label.parentNode.removeChild(this.label);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
this._super();
}
});
JSONEditor.defaults.editors.arraySelectize = JSONEditor.AbstractEditor.extend({
build: function() {
this.title = this.theme.getFormInputLabel(this.getTitle());
this.title_controls = this.theme.getHeaderButtonHolder();
this.title.appendChild(this.title_controls);
this.error_holder = document.createElement('div');
if(this.schema.description) {
this.description = this.theme.getDescription(this.schema.description);
}
if(this.schema.append) {
this.append = this.theme.getAppend(this.getAppend());
}
this.input = document.createElement('select');
this.input.setAttribute('multiple', 'multiple');
var group = this.theme.getFormControl(this.title, this.input, this.description);
this.container.appendChild(group);
this.container.appendChild(this.error_holder);
window.jQuery(this.input).selectize({
delimiter: false,
createOnBlur: true,
create: true
});
},
postBuild: function() {
var self = this;
this.input.selectize.on('change', function(event) {
self.refreshValue();
self.onChange(true);
});
},
destroy: function() {
this.empty(true);
if(this.title && this.title.parentNode) this.title.parentNode.removeChild(this.title);
if(this.description && this.description.parentNode) this.description.parentNode.removeChild(this.description);
if(this.input && this.input.parentNode) this.input.parentNode.removeChild(this.input);
this._super();
},
empty: function(hard) {},
setValue: function(value, initial) {
var self = this;
// Update the array's value, adding/removing rows when necessary
value = value || [];
if(!(Array.isArray(value))) value = [value];
this.input.selectize.clearOptions();
this.input.selectize.clear(true);
value.forEach(function(item) {
self.input.selectize.addOption({text: item, value: item});
});
this.input.selectize.setValue(value);
this.refreshValue(initial);
},
refreshValue: function(force) {
this.value = this.input.selectize.getValue();
},
showValidationErrors: function(errors) {
var self = this;
// Get all the errors that pertain to this editor
var my_errors = [];
var other_errors = [];
$each(errors, function(i,error) {
if(error.path === self.path) {
my_errors.push(error);
}
else {
other_errors.push(error);
}
});
// Show errors for this editor
if(this.error_holder) {
if(my_errors.length) {
var message = [];
this.error_holder.innerHTML = '';
this.error_holder.style.display = '';
$each(my_errors, function(i,error) {
self.error_holder.appendChild(self.theme.getErrorMessage(error.message));
});
}
// Hide error area
else {
this.error_holder.style.display = 'none';
}
}
}
});
// colorpicker creation and handling, build on top of strings editor
JSONEditor.defaults.editors.colorPicker = JSONEditor.defaults.editors.string.extend({
getValue: function() {
if ($(this.input).data("colorpicker") !== undefined) {
var color = $(this.input).data('colorpicker').color.toRGB();
return [color.r,color.g, color.b];
}
else {
return [0,0,0];
}
},
setValue: function(val) {
function rgb2hex(rgb)
{
return "#" +
("0" + parseInt(rgb[0],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2);
}
$(this.input).colorpicker('updateInput', 'rgb('+val+')');
$(this.input).colorpicker('updateData', val);
$(this.input).colorpicker('updatePicker', rgb2hex(val));
$(this.input).colorpicker('updateComponent', 'rgb('+val+')');
},
build: function() {
this._super();
var myinput = this;
$(myinput.input).parent().attr("class", $(myinput.input).parent().attr('class') + " colorpicker-element input-group");
$(myinput.input).append("<span class='input-group-addon' id='event_catcher'><i></i></span>");
$(myinput.input).colorpicker({
format: 'rgb',
customClass: 'colorpicker-2x',
sliders: {
saturation: {
maxLeft: 200,
maxTop: 200
},
hue: {
maxTop: 200
},
},
})
$("#event_catcher").detach().insertAfter(myinput.input);
$("#event_catcher").attr("id", "selector");
$(this.input).colorpicker().on('changeColor', function(e) {
$(myinput).val(e.color.toRGB()).change();
});
}
});
var matchKey = (function () {
var elem = document.documentElement;
if (elem.matches) return 'matches';
else if (elem.webkitMatchesSelector) return 'webkitMatchesSelector';
else if (elem.mozMatchesSelector) return 'mozMatchesSelector';
else if (elem.msMatchesSelector) return 'msMatchesSelector';
else if (elem.oMatchesSelector) return 'oMatchesSelector';
})();
JSONEditor.AbstractTheme = Class.extend({
getContainer: function() {
return document.createElement('div');
},
getFloatRightLinkHolder: function() {
var el = document.createElement('div');
el.style = el.style || {};
el.style.cssFloat = 'right';
el.style.marginLeft = '10px';
return el;
},
getModal: function() {
var el = document.createElement('div');
el.style.backgroundColor = 'white';
el.style.border = '1px solid black';
el.style.boxShadow = '3px 3px black';
el.style.position = 'absolute';
el.style.zIndex = '10';
el.style.display = 'none';
return el;
},
getGridContainer: function() {
var el = document.createElement('div');
return el;
},
getGridRow: function() {
var el = document.createElement('div');
el.className = 'row';
return el;
},
getGridColumn: function() {
var el = document.createElement('div');
return el;
},
setGridColumnSize: function(el,size) {
},
getLink: function(text) {
var el = document.createElement('a');
el.setAttribute('href','#');
el.appendChild(document.createTextNode(text));
return el;
},
disableHeader: function(header) {
header.style.color = '#ccc';
},
disableLabel: function(label) {
label.style.color = '#ccc';
},
enableHeader: function(header) {
header.style.color = '';
},
enableLabel: function(label) {
label.style.color = '';
},
getFormInputLabel: function(text) {
var el = document.createElement('label');
el.appendChild(document.createTextNode(text));
return el;
},
getCheckboxLabel: function(text) {
var el = this.getFormInputLabel(text);
el.style.fontWeight = 'bold';
return el;
},
getHeader: function(text) {
var el = document.createElement('h3');
if(text.innerHTML == ''){
text.style.display = 'none';
return text;
}
else if(typeof text === "string") {
el.textContent = text;
}
else {
el.appendChild(text);
}
return el;
},
getCheckbox: function() {
var el = this.getFormInputField('checkbox');
el.style.display = 'inline-block';
el.style.width = 'auto';
return el;
},
getMultiCheckboxHolder: function(controls,label,description) {
var el = document.createElement('div');
if(label) {
label.style.display = 'block';
el.appendChild(label);
}
for(var i in controls) {
if(!controls.hasOwnProperty(i)) continue;
controls[i].style.display = 'inline-block';
controls[i].style.marginRight = '20px';
el.appendChild(controls[i]);
}
if(description) el.appendChild(description);
return el;
},
getSelectInput: function(options) {
var select = document.createElement('select');
if(options) this.setSelectOptions(select, options);
return select;
},
getSwitcher: function(options) {
var switcher = this.getSelectInput(options);
switcher.style.backgroundColor = 'transparent';
switcher.style.display = 'inline-block';
switcher.style.fontStyle = 'italic';
switcher.style.fontWeight = 'normal';
switcher.style.height = 'auto';
switcher.style.marginBottom = 0;
switcher.style.marginLeft = '5px';
switcher.style.padding = '0 0 0 3px';
switcher.style.width = 'auto';
return switcher;
},
getSwitcherOptions: function(switcher) {
return switcher.getElementsByTagName('option');
},
setSwitcherOptions: function(switcher, options, titles) {
this.setSelectOptions(switcher, options, titles);
},
setSelectOptions: function(select, options, titles) {
titles = titles || [];
select.innerHTML = '';
for(var i=0; i<options.length; i++) {
var option = document.createElement('option');
option.setAttribute('value',options[i]);
option.textContent = titles[i] || options[i];
select.appendChild(option);
}
},
getTextareaInput: function() {
var el = document.createElement('textarea');
el.style = el.style || {};
el.style.width = '100%';
el.style.height = '300px';
el.style.boxSizing = 'border-box';
return el;
},
getRangeInput: function(min,max,step) {
if (typeof step == "undefined") step = 1;
var el = this.getFormInputField('number');
if (typeof min != "undefined") el.setAttribute('min',min);
if (typeof max != "undefined") el.setAttribute('max',max);
el.setAttribute('step',step);
return el;
},
getFormInputField: function(type) {
var el = document.createElement('input');
el.setAttribute('type',type);
return el;
},
afterInputReady: function(input) {
},
getFormControl: function(label, input, description) {
var el = document.createElement('div');
el.className = 'form-control';
if(label) el.appendChild(label);
if(input.type === 'checkbox') {
label.insertBefore(input,label.firstChild);
}
else {
el.appendChild(input);
}
if(description) el.appendChild(description);
return el;
},
getIndentedPanel: function() {
var el = document.createElement('div');
el.style = el.style || {};
el.style.paddingLeft = '10px';
el.style.marginLeft = '10px';
el.style.borderLeft = '1px solid #ccc';
return el;
},
getChildEditorHolder: function() {
return document.createElement('div');
},
getDescription: function(text) {
var el = document.createElement('p');
el.innerHTML = text;
return el;
},
getAppend: function(text) {
var el = document.createElement('p');
el.innerHTML = text;
return el;
},
getCheckboxDescription: function(text) {
return this.getDescription(text);
},
getFormInputDescription: function(text) {
return this.getDescription(text);
},
getHeaderButtonHolder: function() {
return this.getButtonHolder();
},
getButtonHolder: function() {
return document.createElement('div');
},
getButton: function(text, icon, title) {
var el = document.createElement('button');
el.type = 'button';
this.setButtonText(el,text,icon,title);
return el;
},
setButtonText: function(button, text, icon, title) {
button.innerHTML = '';
if(icon) {
button.appendChild(icon);
button.innerHTML += ' ';
}
button.appendChild(document.createTextNode(text));
if(title) button.setAttribute('title',title);
},
getTable: function() {
return document.createElement('table');
},
getTableRow: function() {
return document.createElement('tr');
},
getTableHead: function() {
return document.createElement('thead');
},
getTableBody: function() {
return document.createElement('tbody');
},
getTableHeaderCell: function(text) {
var el = document.createElement('th');
el.textContent = text;
return el;
},
getTableCell: function() {
var el = document.createElement('td');
return el;
},
getErrorMessage: function(text) {
var el = document.createElement('p');
el.style = el.style || {};
el.style.color = 'red';
el.appendChild(document.createTextNode(text));
return el;
},
addInputError: function(input, text) {
},
removeInputError: function(input) {
},
addTableRowError: function(row) {
},
removeTableRowError: function(row) {
},
getTabHolder: function() {
var el = document.createElement('div');
el.innerHTML = "<div style='float: left; width: 130px;' class='tabs'></div><div class='content' style='margin-left: 130px;'></div><div style='clear:both;'></div>";
return el;
},
applyStyles: function(el,styles) {
el.style = el.style || {};
for(var i in styles) {
if(!styles.hasOwnProperty(i)) continue;
el.style[i] = styles[i];
}
},
closest: function(elem, selector) {
while (elem && elem !== document) {
if (elem[matchKey]) {
if (elem[matchKey](selector)) {
return elem;
} else {
elem = elem.parentNode;
}
}
else {
return false;
}
}
return false;
},
getTab: function(span) {
var el = document.createElement('div');
el.appendChild(span);
el.style = el.style || {};
this.applyStyles(el,{
border: '1px solid #ccc',
borderWidth: '1px 0 1px 1px',
textAlign: 'center',
lineHeight: '30px',
borderRadius: '5px',
borderBottomRightRadius: 0,
borderTopRightRadius: 0,
fontWeight: 'bold',
cursor: 'pointer'
});
return el;
},
getTabContentHolder: function(tab_holder) {
return tab_holder.children[1];
},
getTabContent: function() {
return this.getIndentedPanel();
},
markTabActive: function(tab) {
this.applyStyles(tab,{
opacity: 1,
background: 'white'
});
},
markTabInactive: function(tab) {
this.applyStyles(tab,{
opacity:0.5,
background: ''
});
},
addTab: function(holder, tab) {
holder.children[0].appendChild(tab);
},
getBlockLink: function() {
var link = document.createElement('a');
link.style.display = 'block';
return link;
},
getBlockLinkHolder: function() {
var el = document.createElement('div');
return el;
},
getLinksHolder: function() {
var el = document.createElement('div');
return el;
},
createMediaLink: function(holder,link,media) {
holder.appendChild(link);
media.style.width='100%';
holder.appendChild(media);
},
createImageLink: function(holder,link,image) {
holder.appendChild(link);
link.appendChild(image);
}
});
JSONEditor.defaults.themes.bootstrap3 = JSONEditor.AbstractTheme.extend({
getSelectInput: function(options) {
var el = this._super(options);
el.className += 'form-control';
//el.style.width = 'auto';
return el;
},
setGridColumnSize: function(el,size) {
el.className = 'col-md-'+size;
},
afterInputReady: function(input) {
if(input.controlgroup) return;
input.controlgroup = this.closest(input,'.form-group');
if(this.closest(input,'.compact')) {
input.controlgroup.style.marginBottom = 0;
}
// TODO: use bootstrap slider
},
getTextareaInput: function() {
var el = document.createElement('textarea');
el.className = 'form-control';
return el;
},
getRangeInput: function(min, max, step) {
// TODO: use better slider
return this._super(min, max, step);
},
getFormInputField: function(type) {
var el = this._super(type);
if(type !== 'checkbox') {
el.className += 'form-control';
}
return el;
},
getFormControl: function(label, input, description, append, placeholder) {
var group = document.createElement('div');
var subgroup = document.createElement('div');
if(placeholder)
input.setAttribute('placeholder',placeholder);
if (input.type === 'checkbox'){
var helplabel = document.createElement("label")
group.className += ' form-group';
group.style.minHeight = "30px";
label.className += ' col-form-label col-sm-5 col-md-3 col-lg-5 col-xxl-4';
label.style.fontWeight = "bold";
group.appendChild(label);
group.appendChild(subgroup);
subgroup.className += 'checkbox col-sm-7 col-md-9 col-lg-7 col-xxl-8';
subgroup.style.marginTop = "0px";
subgroup.appendChild(input);
subgroup.appendChild(helplabel);
if (input.id.endsWith('_enable'))
subgroup.className += ' checkbox-success';
}
else if (append){
group.className += ' form-group';
if(label) {
label.className += ' col-form-label col-sm-5 col-md-3 col-lg-5 col-xxl-4';
group.appendChild(label);
}
group.appendChild(subgroup);
subgroup.className += ' col-sm-7 col-md-9 col-lg-7 input-group col-xxl-8';
subgroup.appendChild(input);
subgroup.appendChild(append);
}
else {
group.className += ' form-group';
if(label) {
label.className += ' col-form-label col-sm-5 col-md-3 col-lg-5 col-xxl-4';
group.appendChild(label);
}
group.appendChild(subgroup);
subgroup.className += ' input-group col-sm-7 col-md-9 col-lg-7 col-xxl-8';
subgroup.appendChild(input);
}
if(description) group.appendChild(description);
return group;
},
getIndentedPanel: function() {
var el = document.createElement('div');
el.className = 'well well-sm';
el.style.paddingBottom = 0;
return el;
},
getFormInputDescription: function(text) {
var el = document.createElement('p');
el.className = 'help-block';
el.innerHTML = text;
return el;
},
getFormInputAppend: function(text) {
var el = document.createElement('div');
el.className = 'input-group-addon';
el.textContent = text;
return el;
},
getHeaderButtonHolder: function() {
var el = this.getButtonHolder();
el.style.marginLeft = '10px';
return el;
},
getButtonHolder: function() {
var el = document.createElement('div');
el.className = 'btn-group';
return el;
},
getButton: function(text, icon, title) {
var el = this._super(text, icon, title);
el.className += 'btn btn-sm btn-primary';
return el;
},
getTable: function() {
var el = document.createElement('table');
el.className = 'table table-bordered';
el.style.width = 'auto';
el.style.maxWidth = 'none';
return el;
},
addInputError: function(input,text) {
if(!input.controlgroup) return;
input.controlgroup.className += ' has-error';
if(!input.errmsg) {
input.errmsg = document.createElement('p');
input.errmsg.className = 'help-block errormsg';
input.controlgroup.appendChild(input.errmsg);
}
else {
input.errmsg.style.display = '';
}
input.errmsg.textContent = text;
},
removeInputError: function(input) {
if(!input.errmsg) return;
input.errmsg.style.display = 'none';
input.controlgroup.className = input.controlgroup.className.replace(/\s?has-error/g,'');
},
getTabHolder: function() {
var el = document.createElement('div');
el.innerHTML = "<div class='tabs list-group col-md-2'></div><div class='col-md-10'></div>";
el.className = 'rows';
return el;
},
getTab: function(text) {
var el = document.createElement('a');
el.className = 'list-group-item';
el.setAttribute('href','#');
el.appendChild(text);
return el;
},
markTabActive: function(tab) {
tab.className += ' active';
},
markTabInactive: function(tab) {
tab.className = tab.className.replace(/\s?active/g,'');
},
getProgressBar: function() {
var min = 0, max = 100, start = 0;
var container = document.createElement('div');
container.className = 'progress';
var bar = document.createElement('div');
bar.className = 'progress-bar';
bar.setAttribute('role', 'progressbar');
bar.setAttribute('aria-valuenow', start);
bar.setAttribute('aria-valuemin', min);
bar.setAttribute('aria-valuenax', max);
bar.innerHTML = start + "%";
container.appendChild(bar);
return container;
},
updateProgressBar: function(progressBar, progress) {
if (!progressBar) return;
var bar = progressBar.firstChild;
var percentage = progress + "%";
bar.setAttribute('aria-valuenow', progress);
bar.style.width = percentage;
bar.innerHTML = percentage;
},
updateProgressBarUnknown: function(progressBar) {
if (!progressBar) return;
var bar = progressBar.firstChild;
progressBar.className = 'progress progress-striped active';
bar.removeAttribute('aria-valuenow');
bar.style.width = '100%';
bar.innerHTML = '';
}
});
JSONEditor.AbstractIconLib = Class.extend({
mapping: {
collapse: '',
expand: '',
"delete": '',
edit: '',
add: '',
cancel: '',
save: '',
moveup: '',
movedown: ''
},
icon_prefix: '',
getIconClass: function(key) {
if(this.mapping[key]) return this.icon_prefix+this.mapping[key];
else return null;
},
getIcon: function(key) {
var iconclass = this.getIconClass(key);
if(!iconclass) return null;
var i = document.createElement('i');
i.className = iconclass;
return i;
}
});
JSONEditor.defaults.iconlibs.fontawesome4 = JSONEditor.AbstractIconLib.extend({
mapping: {
collapse: 'caret-square-o-down',
expand: 'caret-square-o-right',
"delete": 'times',
edit: 'pencil',
add: 'plus',
cancel: 'ban',
save: 'save',
moveup: 'arrow-up',
movedown: 'arrow-down'
},
icon_prefix: 'fa fa-'
});
JSONEditor.defaults.templates["default"] = function() {
return {
compile: function(template) {
var matches = template.match(/{{\s*([a-zA-Z0-9\-_ \.]+)\s*}}/g);
var l = matches && matches.length;
// Shortcut if the template contains no variables
if(!l) return function() { return template; };
// Pre-compute the search/replace functions
// This drastically speeds up template execution
var replacements = [];
var get_replacement = function(i) {
var p = matches[i].replace(/[{}]+/g,'').trim().split('.');
var n = p.length;
var func;
if(n > 1) {
var cur;
func = function(vars) {
cur = vars;
for(i=0; i<n; i++) {
cur = cur[p[i]];
if(!cur) break;
}
return cur;
};
}
else {
p = p[0];
func = function(vars) {
return vars[p];
};
}
replacements.push({
s: matches[i],
r: func
});
};
for(var i=0; i<l; i++) {
get_replacement(i);
}
// The compiled function
return function(vars) {
var ret = template+"";
var r;
for(i=0; i<l; i++) {
r = replacements[i];
ret = ret.replace(r.s, r.r(vars));
}
return ret;
};
}
};
};
JSONEditor.defaults.templates.ejs = function() {
if(!window.EJS) return false;
return {
compile: function(template) {
var compiled = new window.EJS({
text: template
});
return function(context) {
return compiled.render(context);
};
}
};
};
JSONEditor.defaults.templates.handlebars = function() {
return window.Handlebars;
};
JSONEditor.defaults.templates.hogan = function() {
if(!window.Hogan) return false;
return {
compile: function(template) {
var compiled = window.Hogan.compile(template);
return function(context) {
return compiled.render(context);
};
}
};
};
JSONEditor.defaults.templates.markup = function() {
if(!window.Mark || !window.Mark.up) return false;
return {
compile: function(template) {
return function(context) {
return window.Mark.up(template,context);
};
}
};
};
JSONEditor.defaults.templates.mustache = function() {
if(!window.Mustache) return false;
return {
compile: function(template) {
return function(view) {
return window.Mustache.render(template, view);
};
}
};
};
JSONEditor.defaults.templates.swig = function() {
return window.swig;
};
JSONEditor.defaults.templates.underscore = function() {
if(!window._) return false;
return {
compile: function(template) {
return function(context) {
return window._.template(template, context);
};
}
};
};
// Set the default theme
JSONEditor.defaults.theme = 'html';
// Set the default template engine
JSONEditor.defaults.template = 'default';
// Default options when initializing JSON Editor
JSONEditor.defaults.options = {};
// String translate function
JSONEditor.defaults.translate = function(key, variables) {
return $.i18n(key, variables);
};
// Miscellaneous Plugin Settings
JSONEditor.plugins = {
ace: {
theme: ''
},
epiceditor: {
},
sceditor: {
},
select2: {
},
selectize: {
}
};
// Default per-editor options
$each(JSONEditor.defaults.editors, function(i,editor) {
JSONEditor.defaults.editors[i].options = editor.options || {};
});
// Set the default resolvers
// Use "multiple" as a fall back for everything
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(typeof schema.type !== "string") return "multiple";
});
// If the type is not set but properties are defined, we can infer the type is actually object
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If the schema is a simple type
if(!schema.type && schema.properties ) return "object";
});
// If the type is set and it's a basic type, use the primitive editor
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If the schema is a simple type
if(typeof schema.type === "string") return schema.type;
});
// Boolean editors
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.type === 'boolean') {
// convert all boolean to checkbox
return "checkbox";
}
});
// Use the multiple editor for schemas where the `type` is set to "any"
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If the schema can be of any type
if(schema.type === "any") return "multiple";
});
// Editor for base64 encoded files
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If the schema can be of any type
if(schema.type === "string" && schema.media && schema.media.binaryEncoding==="base64") {
return "base64";
}
});
// Editor for uploading files
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.type === "string" && schema.format === "url" && schema.options && schema.options.upload === true) {
if(window.FileReader) return "upload";
}
});
// Use the table editor for arrays with the format set to `table`
JSONEditor.defaults.resolvers.unshift(function(schema) {
// Type `array` with format set to `table`
if(schema.type == "array" && schema.format == "table") {
return "table";
}
});
// Use the `select` editor for dynamic enumSource enums
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.enumSource) return (JSONEditor.plugins.selectize.enable) ? 'selectize' : 'select';
});
// Use the `enum` or `select` editors for schemas with enumerated properties
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema["enum"]) {
if(schema.type === "array" || schema.type === "object") {
return "enum";
}
else if(schema.type === "number" || schema.type === "integer" || schema.type === "string") {
return (JSONEditor.plugins.selectize.enable) ? 'selectize' : 'select';
}
}
});
// Specialized editors for arrays of strings
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.type === "array" && schema.items && !(Array.isArray(schema.items)) && schema.uniqueItems && ['string','number','integer'].indexOf(schema.items.type) >= 0) {
// For enumerated strings, number, or integers
if(schema.items.enum) {
return 'multiselect';
}
// For non-enumerated strings (tag editor)
else if(JSONEditor.plugins.selectize.enable && schema.items.type === "string") {
return 'arraySelectize';
}
}
});
// Use the multiple editor for schemas with `oneOf` set
JSONEditor.defaults.resolvers.unshift(function(schema) {
// If this schema uses `oneOf` or `anyOf`
if(schema.oneOf || schema.anyOf) return "multiple";
});
// colorpicker extend for strings
JSONEditor.defaults.resolvers.unshift(function(schema) {
if(schema.type === "array" && schema.format === "colorpicker") {
return "colorPicker";
}
});
/**
* This is a small wrapper for using JSON Editor like a typical jQuery plugin.
*/
(function() {
if(window.jQuery || window.Zepto) {
var $ = window.jQuery || window.Zepto;
$.jsoneditor = JSONEditor.defaults;
$.fn.jsoneditor = function(options) {
var self = this;
var editor = this.data('jsoneditor');
if(options === 'value') {
if(!editor) throw "Must initialize jsoneditor before getting/setting the value";
// Set value
if(arguments.length > 1) {
editor.setValue(arguments[1]);
}
// Get value
else {
return editor.getValue();
}
}
else if(options === 'validate') {
if(!editor) throw "Must initialize jsoneditor before validating";
// Validate a specific value
if(arguments.length > 1) {
return editor.validate(arguments[1]);
}
// Validate current value
else {
return editor.validate();
}
}
else if(options === 'destroy') {
if(editor) {
editor.destroy();
this.data('jsoneditor',null);
}
}
else {
// Destroy first
if(editor) {
editor.destroy();
}
// Create editor
editor = new JSONEditor(this.get(0),options);
this.data('jsoneditor',editor);
// Setup event listeners
editor.on('change',function() {
self.trigger('change');
});
editor.on('ready',function() {
self.trigger('ready');
});
}
return this;
};
}
})();
window.JSONEditor = JSONEditor;
})();
//# sourceMappingURL=jsoneditor.js.map
|
/**
* Created by Jan on 1/6/16.
*/
$(document).ready(function(){
$('#regCaptcha').keyup(function(){
if($('#regCaptcha').val() == $('#captchaImg').data('code')){
$('#regBtn').removeAttr('disabled');
$('#errorSpan').empty();
$('#successSpan').empty().append('<i class="fa fa-check"></i> Captcha code correct.');
}else{
$('#regBtn').prop('disabled', 'true');
$('#successSpan').empty();
$('#errorSpan').empty().append('<i class="fa fa-warning"></i> Captcha code incorrect! try again.');
}
});
});
$(function() {
$( "#regBdate" ).datepicker({
changeMonth: true,
changeYear: true
});
$( "#editBdate" ).datepicker({
changeMonth: true,
changeYear: true
});
});
|
/**
* Created by Kirsten on 2/11/2015. Adds input functionality to the game.
*
*/
window.uwetech.Input = (function () {
var keys = {};
window.addEventListener('keydown', function (e) {
keys[e.keyCode] = true;
});
window.addEventListener('keyup', function (e) {
delete keys[e.keyCode];
});
return {
keys : keys
};
}());
var mouse_canvas = document.getElementById('mouselayer');
//mouse_ctx = mouse_canvas.getContext('2d');
window.uwetech.Input.getMousePos = function(evt) {
var mouse_rect = mouse_canvas.getBoundingClientRect();
var transX = mouse_canvas.width / mouse_rect.width;
var transY = mouse_canvas.height / mouse_rect.height;
return {
// client position is in actual pixels on the client
// canvas may be stretched.
// need to convert coordinates to canvas dimensions
x: Math.floor((evt.clientX - mouse_rect.left) * transX),
y: Math.floor((evt.clientY - mouse_rect.top) * transY)
};
};
mouse_canvas.addEventListener('mousedown', function(evt) {
//console.log("mouse down!");
g.handleMouseDown(window.uwetech.Input.getMousePos(evt));
});
|
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.xnt=t():e.xnt=t()}(this,function(){return function(e){function t(n){if(o[n])return o[n].exports;var r=o[n]={exports:{},id:n,loaded:!1};return e[n].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var o={};return t.m=e,t.c=o,t.p="",t(0)}([function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o={"00":"[xnt-empty]","01":"[xnt-half-left]",10:"[xnt-half-right]",11:"[xnt-full]"},n=function(e){return o[e]},r={all:o,binaryToHex:n};t["default"]=r,e.exports=r}])});
//# sourceMappingURL=xnt.umd.min.js.map
|
import adapter from '@sveltejs/adapter-static';
export default {
kit: {
adapter: adapter({
// default options are shown
pages: 'build',
assets: 'build',
fallback: null
})
}
};
|
'use strict';
var _templateObject = _taggedTemplateLiteral(['this is string ', ''], ['this is string ', '']);
function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
var Tool = require('../tool');
// notes: define back-tick as bt prefix
Tool.log('module', 'ES6 template literal string');
// ============== back-triks =====================
Tool.log('unit', 'Back-tick Basic');
var btTestContext = 'back-tick';
Tool.log('\nCONTEXT: \nvar btTestContext = \'back-tick\';\nthis is a test for ${btTestContext}\n\nRESULT:\nthis is a test for ' + btTestContext + '\n');
// ============== expression ======================
Tool.log('unit', 'Expression');
var btA = 12,
btB = 12;
Tool.log('\nCONTEXT:\nvar btA = 12, btB = 12;\nbtA + btB is equal to ${btA} + ${btB} = ${btA + btB};\n\nRESULT:\nbtA + btB is equal to ' + btA + ' + ' + btB + ' = ' + (btA + btB) + ';\n');
// ================== use function ======================
Tool.log('unit', 'use function');
var negativeNum = -12;
Tool.log('\nCONTEXT:\nvar negativeNum = -12;\nuse Math.abs fn ${Math.abs(negativeNum)}\n\nRESULT:\nuse Math.abs fn ' + Math.abs(negativeNum) + '\n');
// ============== tagged string ===================
Tool.log('unit', 'Tagged string');
var tag = function tag(strings) {
for (var _len = arguments.length, values = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
values[_key - 1] = arguments[_key];
}
var strings = strings.join('\n');
var values = values.join('\n');
// just todo something
return '\nRESULT:\nstrings:\n' + strings + 'values:\n' + values + '\n';
};
var tagVarA = 12;
Tool.log('\nCONTEXT:\nvar tag = function(strings, ...values){\n var strings = strings.join(\'\\n\');\n var values = values.join(\'\\n\');\n\n // just todo something\n\n return \'\\nRESULT:\\nstrings:\\n\' + strings + \'values:\\n\' + values + \'\\n\';\n};\nvar tagVarA = 12;\n\nUSAGE:\ntag`this is string ${tagVarA}`\n');
Tool.log(tag(_templateObject, tagVarA));
// =================== raw string => strings.raw[0] ====================
Tool.log('unit', 'raw string => strings.raw[0]');
var rawStr = function rawStr(strings) {
return '\nRESULT:\n' + strings.raw[0] + '\n';
};
var rawVar = 12;
Tool.log('\nCONTEXT:\nvar rawStr = function(strings, ...values){\n return \'\\nRESULT:\\n\' + strings.raw[0] + \'\\n\'\n};\nvar rawVar = 12;\n\nUSAGE:\nrawStr`this is string ${rawVar}`\n\nNOTES:\nthe rawVar variable is not show!\n');
Tool.log(rawStr(_templateObject, rawVar));
// =================== raw string => Strings.raw`string` ====================
Tool.log('unit', 'raw string => String.raw');
var rawVar2 = 12;
Tool.log('\nCONTEXT:\nvar rawVar2 = 12;\n\nUSAGE:\nString.raw`this is string ${rawVar2}`\n\nNOTES:\nNot supported by node 0.12.7, String has not the raw method\nTested it in chrome45 is ok!\n');
// Tool.log(String.raw`this is string ${rawVar2}`);
|
import React from 'react';
import {
Text,
View,
TouchableOpacity,
Dimensions,
Image
} from 'react-native';
import styles from '../../themes/styles';
import mystyles from './styles';
import{
Container,
Header,
Title,
Button
} from 'native-base';
import {
Actions
} from 'react-native-router-flux';
import { Row, Grid } from "react-native-easy-grid";
const deviceWidth = Dimensions.get('window').width;
class RouteDirection extends React.Component {
constructor(props){
super(props)
}
HandleButton(id, direction, name){
this.props.navigator.push({
name: 'routePlate',
passProps:{
rutaId: id,
routeDirection: direction,
routeName:name,
}
});
}
render(){
return (
<Container>
<Header style={styles.navBar}>
<Button transparent onPress={() => this.props.reset(this.props.navigation.key)}>
<Text style={{fontWeight:'800', color:'#FFF'}}>{'Salir'}</Text>
</Button>
<Title style={styles.navBarTitle}>{'Dirección'}</Title>
</Header>
<View style={[{alignItems:'center'},mystyles.container]}>
<Grid>
<Row style={mystyles.rowBuses}>
<TouchableOpacity style={{width: deviceWidth}} onPress={this.HandleButton.bind(this, this.props.rutaId, "entrada",this.props.routeName )}>
<Image source={require('../../imgs/bus_entrance.png')} style={mystyles.myBusEntrance}></Image>
<Text style={mystyles.text}>
Entrada
</Text>
</TouchableOpacity>
</Row>
<Row style={mystyles.rowBuses}>
<TouchableOpacity style={{width: deviceWidth}} onPress={this.HandleButton.bind(this, this.props.rutaId, "salida", this.props.routeName)}>
<Image source={require('../../imgs/bus_exit2.png')} style={mystyles.myBusEntrance}></Image>
<Text style={mystyles.text}>
Salida
</Text>
</TouchableOpacity>
</Row>
</Grid>
</View>
</Container>
);
}
}
export default RouteDirection;
|
import React, { Component } from 'react';
import { Table, Header, Image, Button } from 'semantic-ui-react';
import axios from 'axios';
export default class AdministratorTableStudents extends Component {
constructor () {
super();
this.state = {
students: []
}
}
componentWillMount () {
const tick = this;
// Get Events Data to render
axios.get('/api/admin/student/all')
.then(function (response) {
console.log(response);
tick.setState({students: response.data.students})
})
.catch(function (error) {
console.log(error);
});
}
renderRows () {
return this.state.students.map((student) => {
const { account_id, user_id, first_name, last_name, hometown, college, major, gender, bio, birthdate, email, date_created, image_path } = student;
return (
<Table.Row key={account_id}>
<Table.Cell>{user_id}</Table.Cell>
<Table.Cell>
<Image src={image_path} shape='rounded' size='mini' />
</Table.Cell>
<Table.Cell>
<Header as='h4'>{first_name + ' ' + last_name}</Header>
</Table.Cell>
<Table.Cell>{email}</Table.Cell>
<Table.Cell>{birthdate}</Table.Cell>
<Table.Cell>{gender}</Table.Cell>
<Table.Cell>{hometown}</Table.Cell>
<Table.Cell>{college}</Table.Cell>
<Table.Cell>{major}</Table.Cell>
<Table.Cell>{date_created}</Table.Cell>
<Table.Cell><Button>Edit</Button></Table.Cell>
</Table.Row>
);
});
}
render() {
return (
<div>
<Header as='h2'>Manage Associations Accounts</Header>
<Table celled structured>
<Table.Header>
<Table.Row>
<Table.HeaderCell>ID</Table.HeaderCell>
<Table.HeaderCell>Image</Table.HeaderCell>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>E-mail</Table.HeaderCell>
<Table.HeaderCell>Birthdate</Table.HeaderCell>
<Table.HeaderCell>Gender</Table.HeaderCell>
<Table.HeaderCell>Hometown</Table.HeaderCell>
<Table.HeaderCell>College</Table.HeaderCell>
<Table.HeaderCell>Major</Table.HeaderCell>
<Table.HeaderCell>Account Created</Table.HeaderCell>
<Table.HeaderCell>Edit</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{this.renderRows()}
</Table.Body>
</Table>
</div>
);
}
}
|
//
// Wraps a Joi type in a magical Proxy API so that we can extend Joi to do
// CRUD validations, e.g.
//
// ```
// {
// _id: id()
// .on('update').required()
// .on('create').forbidden()
// }
// ````
//
const joi = require('joi')
const mongo = require('promised-mongo')
const { each } = require('lodash')
const idType = joi.extend({
base: joi.string(),
name: 'string',
pre: (val, state, options) => {
if (options.convert) return mongo.ObjectId(val)
else return val
}
}).string
module.exports = (type) => {
return (...typeArgs) => {
const schema = () =>
type === 'id'
? idType(...typeArgs)
: joi[type](...typeArgs)
let schemas = {
all: schema(),
create: schema(),
read: schema(),
update: schema(),
delete: schema(),
list: schema()
}
let curSchemas = ['all']
const proxy = new Proxy({}, {
get: (_, key) => {
return (...args) => {
if (key === 'on') {
curSchemas = args[0].split(' ')
} else if (key === 'schema') {
return schemas[args[0]]
} else if (key === 'describe') {
return schemas.all.describe(...args)
} else {
curSchemas.forEach((k) => {
const convertedArgs = args.map((arg) => {
if (arg.schema) return arg.schema('all')
else return arg
})
if (k === 'all') {
each(schemas, (v, k) => {
schemas[k] = schemas[k][key](...convertedArgs)
})
} else schemas[k] = schemas[k][key](...convertedArgs)
})
}
return proxy
}
}
})
return proxy
}
}
|
'use strict';
adsApp.controller('HomeCtrl', ['$scope', 'adsData', 'authService', 'notificationService', 'pageSize',
function($scope, adsData, authService, notificationService, pageSize) {
$scope.pageTitle = 'Home';
$scope.isLoggedIn = authService.isLoggedIn();
$scope.adsParams = {
'startPage' : 1,
'pageSize' : pageSize
};
$scope.authService = authService;
$scope.logout = function() {
authService.logout();
}
}
]);
|
import { Modal, message } from 'antd'
import React from 'react'
import ReactDOM from 'react-dom'
import classnames from 'classnames'
import styles from './layer.less'
const { info, success, error, warning, confirm } = Modal
const layer = {
prefixCls: 'ant-layer',
index: 1,
info,
success,
error,
warning,
confirm,
}
/**
* 对弹层监听鼠标移动事件
* @param clickEl
* @param moveEl
*/
function listenerMoveEvent (clickEl, moveEl) {
clickEl.style.cursor = 'move'
var disX = 0;
var disY = 0;
clickEl.onmousedown = function (ev) { //鼠标按下
clearEvent(clickEl)
var oEvent = ev || event; //判断浏览器兼容
disX = oEvent.clientX - moveEl.offsetLeft; //鼠标横坐标点到 moveEl 的offsetLeft距离
disY = oEvent.clientY - moveEl.offsetTop; //鼠标纵坐标点到 moveEl 的offsetTop距离
clickEl.onmousemove = function (ev) { //鼠标移动
var oEvent = ev || event;
var l = oEvent.clientX - disX; //获取 moveEl 左边的距离
var t = oEvent.clientY - disY; //获取 moveEl 上边的距离
if (l < 0) { //判断 moveEl 的可视区,为避免DIV失去鼠标点
l = 0;
} else if (l > document.body.clientWidth - moveEl.offsetWidth) {
l = document.body.clientWidth - moveEl.offsetWidth;
}
if (t < 0) {
t = 0;
} else if (t > document.body.clientHeight - moveEl.offsetHeight) {
t = document.body.clientHeight - moveEl.offsetHeight;
}
if (moveEl.style.position != 'absolute') {
moveEl.style.position = 'absolute'
}
moveEl.style.left = l + 'px'; //确定 moveEl 的左边位置
moveEl.style.top = t + 'px'; //确定 moveEl 的上边位置
}
clickEl.onmouseup = function () { //当鼠标松开后关闭移动事件和自身事件
clearEvent(clickEl)
}
return false;
}
clickEl.onmouseup = function () { //当鼠标松开后关闭移动事件和自身事件
clearEvent(clickEl)
}
function clearEvent (clickEl) {
// 关闭移动事件和自身事件
clickEl.onmousemove = null;
clickEl.onmouseup = null;
}
}
layer.close = (index) => new Promise((resolve, reject) => {
const { prefixCls } = layer
let div = document.getElementById(`${prefixCls}-reference-${index}`)
if (index === undefined) {
const references = document.querySelectorAll(`.${prefixCls}-reference`)
div = references[references.length - 1]
}
if (!div) {
message.error('关闭失败,未找到Dom')
return
}
const unmountResult = ReactDOM.unmountComponentAtNode(div)
if (unmountResult && div.parentNode) {
div.parentNode.removeChild(div)
resolve(index)
} else {
reject(index)
}
})
layer.closeAll = () => {
const { prefixCls } = layer
const references = document.querySelectorAll(`.${prefixCls}-reference`)
let i = 0
while (i < references.length) {
layer.close()
i++
}
}
layer.open = (config) => {
const props = Object.assign({}, config)
const { content, isMove = true, ...modalProps } = props
const { className, wrapClassName = '', verticalCenter = true } = modalProps
const { prefixCls } = layer
const index = layer.index++
let div = document.createElement('div')
div.id = `${prefixCls}-reference-${index}`
div.className = `${prefixCls}-reference`
document.body.appendChild(div)
ReactDOM.render(
<Modal
visible
title="Title"
transitionName="zoom"
maskTransitionName="fade"
onCancel={() => {
layer.close(index)
}}
onOk={() => {
layer.close(index)
}}
{...modalProps}
wrapClassName={classnames({ [styles.verticalCenter]: verticalCenter, [wrapClassName]: true })}
className={classnames(prefixCls, className, [`${prefixCls}-${index}`])}
>
<div className={`${prefixCls}-body-wrapper`} style={{ maxHeight: document.body.clientHeight - 256 }}>
{content}
</div>
</Modal>, div)
if (isMove) {
let moveEl = document.getElementsByClassName(`${prefixCls}-${index}`)[0] // ant-modal
let clickEl = moveEl.children[0].children[1] // 'ant-modal-header
listenerMoveEvent(clickEl, moveEl)
}
return index
}
export default layer
|
'use strict';
var bygglib = require('../lib');
var mime = require('mime');
var path = require('path');
var vfs = require('vinyl-fs');
module.exports = function (options) {
options = (typeof options === 'string') ? { src: options } : options;
var src = (typeof options.src === 'string') ? [options.src] : options.src;
var base = options.base !== undefined ? path.resolve(options.base) : process.cwd();
var watcher = bygglib.watcher();
var signal = bygglib.signal();
var nodeFromVinyl = function (file) {
return {
name: path.relative(base, file.path),
base: base,
data: file.contents,
stat: file.stat,
metadata: {
mime: mime.lookup(file.path)
},
siblings: []
};
};
var pushNext = function () {
var stream = vfs.src(src, { cwd: base });
var files = [];
stream.on('data', function (file) {
if (!file.isNull()) {
files.push(file);
}
});
stream.on('end', function () {
watcher.watch(files.map(function (file) { return file.path; }));
signal.push(bygglib.tree(files.map(nodeFromVinyl)));
});
};
watcher.listen(pushNext);
pushNext();
return signal;
};
|
(function(root, models, depHandler) {
var viewModel = function() {
var self = this;
// må pushe objecter med minimum en prop kalt name i programs og
// programStages
// Kan være lurt å ha en model som ser slik ut kanskje: {name: "Navnet",
// id: "idsomething"}s
self.programs = ko.observableArray();
self.selectedProgram = ko.observable();
self.programStages = ko.observableArray();
self.selectedProgramStage = ko.observable();
self.dataElements = ko.observableArray();
self.circular = ko.observable(false);
self.previewToggled = ko.observable(false);
self.activeElement = ko.observable({
type : "None"
});
self.selectedProgram.subscribe(function() {
survey.utils.log("Getting program stages for selected program");
self.programStages().length = 0;
survey.data.getProgramStageIdsFromSelectedProgram();
});
self.selectedProgramStage.subscribe(function() {
self.downloadedAndOrderedDataElements().length = 0;
self.selectedProgramStagesOptionSets().length = 0;
self.downloadedDataElements().length = 0;
self.dataElements().length = 0;
if (self.selectedProgramStage()) {
if (self.selectedProgramStage().programStageDataElements) {
survey.data.getAllDataElementsForSelectedProgramStage();
self.orgUnitOpts().length = 0;
survey.data.getOrgUnits(self.selectedProgram().id);
}
}
});
self.selectedProgramStagesOptionSets = ko.observableArray();
self.dataElementCreator = function(dataElement) {
return new models.DataElement(dataElement);
};
self.downloadedDataElements = ko.observableArray();
self.downloadedAndOrderedDataElements = ko.observableArray();
self.getDataElementByID = function(id) {
var elements = root.viewModel.dataElements();
for (var i in elements) {
var elem = elements[i];
if (elem.id === id) {
return elem;
}
}
return null;
};
self.dependenciesHold = function(elem) {
function getTriggersForDependency(dep) {
var triggers = '';
var dependencies = elem.dependencies;
for (var i in dependencies) {
var dep_descriptor = dependencies[i];
if (dep_descriptor.id === dep.id) {
triggers = dep_descriptor.triggers;
break;
}
}
return triggers;
}
function triggerIsFulfilled(type, triggers, value) {
var fulfills = false;
if (triggers[0].from !== undefined) {
var range = triggers[0];
var from = range.from;
var to = range.to;
// ranges
if (type === 'int') {
fulfills = value >= from && value <= to;
} else if (type === 'date') {
var t0 = new Date(from);
var t1 = new Date(to);
var tc = new Date(value);
var inv = 'Invalid Date';
if (t0 !== inv && t1 !== inv && tc !== inv) {
var val = tc.getTime();
fulfills = val >= t0.getTime() && val <= t1.getTime();
}
}
} else {
// points
for (var i in triggers) {
if (triggers[i] == value) {
fulfills = true;
break;
}
}
}
return fulfills;
}
var dependents = elem.dependents;
var dependencies = elem.dependencies;
for (var i in dependencies) {
var dep_descriptor = dependencies[i];
var dependency = self.getDataElementByID(dep_descriptor.id);
if (!dependency) {
return false;
}
if (!self.dependenciesHold(dependency)) {
return false;
}
var triggers = getTriggersForDependency(dependency);
var dep_val = survey.utils.translateElementValue(dependency);
if (!triggerIsFulfilled(dependency.type, triggers, dep_val)) {
return false;
}
}
return true;
};
self.addSkipLogic = function(dataelement) {
dataelement.addingSkipLogic(true);
self.activeElement(dataelement);
$.each(self.dataElements(), function(index, element) {
if (element != dataelement) {
element.isInSkipLogic(true);
element.isDependent(depHandler.hasDependency(element,
dataelement));
element.setSkipLogicUIElements(dataelement);
}
});
};
self.saveSkipLogic = function(dataelement) {
$.each(root.viewModel.dataElements(), function(index, element) {
if (element != dataelement) {
if (element.isDependent()) {
depHandler.addDependency(dataelement, element).done(
function() {
element.resetSkipLogicUI();
survey.utils.log("legger til avhengighet",
element);
}).fail(function(status) {
element.resetSkipLogicUI();
survey.utils.log(status);
});
} else {
depHandler.removeDependency(dataelement, element);
element.resetSkipLogicUI();
}
} else {
element.resetSkipLogicUI();
}
});
dataelement.addingSkipLogic(false);
self.detectCircularDependencies();
};
self.detectCircularDependencies = function() {
var unordered = root.viewModel.dataElements();
survey.rearrange.withDeps(unordered, function(arranged) {
self.circular(unordered.length != arranged.length);
});
}
/*Nav elements*/
self.isAdmin = ko.observable(true);
self.showLockedElements = ko.observable(self.isAdmin());
self.previewButtonText = ko.computed(function() {
return (self.previewToggled()? 'Hide':'Show') + ' Preview';
});
self.activeMenuItem = ko.observable("Admin");
self.adminClick = function() {
self.isAdmin(true);
self.showLockedElements(true);
self.activeMenuItem("Admin");
};
self.userClick = function() {
// Trigger a program stage refresh
var scratch = self.selectedProgramStage();
self.selectedProgramStage(undefined);
self.selectedProgramStage(scratch);
self.isAdmin(false);
self.showLockedElements(false);
self.activeMenuItem("Data entry");
};
self.logoutClick = function() {
survey.data.logout();
// window.location.reload(true);
window.location.replace(survey.utils.url);
};
//SAVE DATA ENTRY
self.entryDate = ko.observable();
self.orgUnit = "";
self.orgUnitOpts = ko.observableArray();
self.programIsChosen = ko.computed(function () {
return self.selectedProgramStage() != undefined;
})
self.saveDataEntry = function() {
if (!self.areThereAnyUnfilledRequiredDataElements()) {
return;
}
if(self.orgUnit == undefined || self.entryDate() == undefined) {
survey.utils.alert("Required fields", "Report date and orgUnit must be specified!", "info");
return;
}
var getDataValues = function() {
dataelements = [];
$.each(self.dataElements(), function(index, element) {
var entryValue = element.value();
if(element.type === 'trueOnly' && entryValue === false) {
entryValue = undefined;
}
if(entryValue != undefined) {
if(element.type === 'bool') {
if(entryValue === 'Yes')
entryValue = true;
if(entryValue === 'No')
entryValue = false;
}
dataelements.push({dataElement: element.id, value: entryValue});
}
});
return dataelements;
}
var dataentry = {
program : self.selectedProgram().id,
orgUnit: self.orgUnit.orgUnit,
eventDate: self.entryDate(),
dataValues: getDataValues()
}
survey.data.saveDataEntry(dataentry);
}
self.clearAllSkipLogic = function() {
survey.utils.alert("Clear all?", "Are you sure? The changes will not be saved before you choose save changes",
"warning", "Yes", "No", function() {
$.each(root.viewModel.dataElements(), function(index, element) {
element.dependencies = [];
});
});
};
self.togglePreview = function() {
var preview = !self.previewToggled();
var fun = function(elements) {
self.dataElements(elements);
self.showLockedElements(!preview);
self.previewToggled(preview);
}
survey.rearrange.withDeps(self.dataElements(), fun);
}
self.uploadSkipLogic = function() {
var sps = self.selectedProgramStage();
if (!sps) return;
if (self.circular()) {
survey.error.displayErrorMessage("Your questions contain circular dependencie(s). Please resolve them.");
return;
}
//var surveyId = sps.id;
//var surveyId = 12;
var id = sps.id;
var success = function() {
survey.utils.alert("Skip logic saved", "Skip logic saved successfully with id "+id, "success");
self.uploadingSkipLogic = false;
};
var error = function(req, stat, err) {
survey.utils.log('Error while posting skip logic, with status "'+stat+'":\n'+
err+'\n'+'Request was:');
survey.utils.log(req);
survey.error.displayErrorMessage('Failed to save your changes.\n(Read more about it in your console)');
self.uploadingSkipLogic = false;
};
//self.post_dependencies = function(surveyId, elements, success, error) {
survey.data.post_dependencies(sps.id, self.dataElements(), success, error);
self.uploadingSkipLogic = true;
}
self.uploadingSkipLogic = false;
self.areThereAnyUnfilledRequiredDataElements = function() {
var unfilledElements = [];
for (var i = 0; i < self.dataElements().length; i++) {
if (self.dataElements()[i].isRequired() && !self.dataElements()[i].value()) {
unfilledElements.push(self.dataElements()[i]);
}
}
return self.alertIfUncheckedRequiredDataElements(unfilledElements);
}
self.alertIfUncheckedRequiredDataElements = function(unfilledElements) {
if (unfilledElements.length > 0) {
var alertMsg = "";
if (unfilledElements.length === 1) {
alertMsg = "These elements are required and not filled out: ";
} else {
alertMsg = "This element is required and not filled out: ";
}
for (var i = 0; i < unfilledElements.length; i++) {
alertMsg += unfilledElements[i].name;
if (i !== unfilledElements.length-1) {
alertMsg += ", ";
}
}
survey.utils.alert("Required fields", alertMsg, "info");
return false;
}
return true;
};
};
root.viewModel = new viewModel();
})(survey, survey.models, survey.dependencyHandler);
|
define([
'sandbox',
'aura_perms',
'./collectionView',
'./collection'
], function(sandbox, permissions, AppView, payments) {
return function(options) {
var element = sandbox.dom.find(options.element);
new AppView({ collection: sandbox.collection, el: element });
};
});
|
/* */
"format cjs";
import warning from 'warning';
const dayAbbreviation = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
const dayList = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const monthList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
const monthLongList = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
function DateTimeFormat(locale, options) {
warning(locale === 'en-US',
'Wrong usage of DateTimeFormat. The ' + locale + ' locale is not supported.');
this.format = function(date) {
let output;
if (options.month === 'short' &&
options.weekday === 'short' &&
options.day === '2-digit') {
output = dayList[date.getDay()] + ', ';
output += monthList[date.getMonth()] + ' ';
output += date.getDate();
} else if (options.month === 'long' && options.year === 'numeric') {
output = monthLongList[date.getMonth()];
output += ' ' + date.getFullYear();
} else if (options.weekday === 'narrow') {
output = dayAbbreviation[date.getDay()];
} else {
warning(false, 'Wrong usage of DateTimeFormat');
}
return output;
};
}
export default {
DateTimeFormat: DateTimeFormat,
addDays(d, days) {
const newDate = this.clone(d);
newDate.setDate(d.getDate() + days);
return newDate;
},
addMonths(d, months) {
const newDate = this.clone(d);
newDate.setMonth(d.getMonth() + months);
return newDate;
},
addYears(d, years) {
const newDate = this.clone(d);
newDate.setFullYear(d.getFullYear() + years);
return newDate;
},
clone(d) {
return new Date(d.getTime());
},
cloneAsDate(d) {
const clonedDate = this.clone(d);
clonedDate.setHours(0, 0, 0, 0);
return clonedDate;
},
getDaysInMonth(d) {
let resultDate = this.getFirstDayOfMonth(d);
resultDate.setMonth(resultDate.getMonth() + 1);
resultDate.setDate(resultDate.getDate() - 1);
return resultDate.getDate();
},
getFirstDayOfMonth(d) {
return new Date(d.getFullYear(), d.getMonth(), 1);
},
getFirstDayOfWeek() {
const now = new Date();
return new Date(now.setDate(now.getDate() - now.getDay()));
},
getWeekArray(d, firstDayOfWeek) {
let dayArray = [];
let daysInMonth = this.getDaysInMonth(d);
let weekArray = [];
let week = [];
for (let i = 1; i <= daysInMonth; i++) {
dayArray.push(new Date(d.getFullYear(), d.getMonth(), i));
}
const addWeek = week => {
const emptyDays = 7 - week.length;
for (let i = 0; i < emptyDays; ++i) {
week[weekArray.length ? 'push' : 'unshift'](null);
}
weekArray.push(week);
};
dayArray.forEach(day => {
if (week.length > 0 && day.getDay() === firstDayOfWeek) {
addWeek(week);
week = [];
}
week.push(day);
if (dayArray.indexOf(day) === dayArray.length - 1) {
addWeek(week);
}
});
return weekArray;
},
localizedWeekday(DateTimeFormat, locale, day, firstDayOfWeek) {
const weekdayFormatter = new DateTimeFormat(locale, {weekday: 'narrow'});
const firstDayDate = this.getFirstDayOfWeek();
return weekdayFormatter.format(this.addDays(firstDayDate, day + firstDayOfWeek));
},
format(date) {
const m = date.getMonth() + 1;
const d = date.getDate();
const y = date.getFullYear();
return m + '/' + d + '/' + y;
},
isEqualDate(d1, d2) {
return d1 && d2 &&
(d1.getFullYear() === d2.getFullYear()) &&
(d1.getMonth() === d2.getMonth()) &&
(d1.getDate() === d2.getDate());
},
isBeforeDate(d1, d2) {
const date1 = this.cloneAsDate(d1);
const date2 = this.cloneAsDate(d2);
return (date1.getTime() < date2.getTime());
},
isAfterDate(d1, d2) {
const date1 = this.cloneAsDate(d1);
const date2 = this.cloneAsDate(d2);
return (date1.getTime() > date2.getTime());
},
isBetweenDates(dateToCheck, startDate, endDate) {
return (!(this.isBeforeDate(dateToCheck, startDate)) &&
!(this.isAfterDate(dateToCheck, endDate)));
},
isDateObject(d) {
return d instanceof Date;
},
monthDiff(d1, d2) {
let m;
m = (d1.getFullYear() - d2.getFullYear()) * 12;
m += d1.getMonth();
m -= d2.getMonth();
return m;
},
yearDiff(d1, d2) {
return ~~(this.monthDiff(d1, d2) / 12);
},
};
|
/**************************************************************************************
Aria Leave action
Take a call out of a queue.
NOT YET IMPLEMENTED
**************************************************************************************/
twimlActions.Leave = function(command, callback) {
var call = command.call;
var channel = call.channel;
var client = call.client;
var playback = null;
console.log("Channel " + channel.id + " - Leave: NOT YET IMPLEMENTED");
// terminate the call on the next tick
setTimeout(function() {
return callback();
}, 0);
};
|
function Coin(parValue, count) {
this.ParValue = ko.observable(parValue);
this.Count = ko.observable(count);
}
function CoinDto(parValue, count) {
this.ParValue = parValue;
this.Count = count;
}
|
/*
* Fuel UX Spinner
* https://github.com/ExactTarget/fuelux
*
* Copyright (c) 2012 ExactTarget
* Licensed under the MIT license.
*/
!function (e) {
var t = function (t, i) {
this.$element = e(t), this.options = e.extend({}, e.fn.spinner.defaults, i), this.$input = this.$element.find(".spinner-input"), this.$element.on("keyup", this.$input, e.proxy(this.change, this)), this.options.hold ? (this.$element.on("mousedown", ".spinner-up", e.proxy(function () {
this.startSpin(!0)
}, this)), this.$element.on("mouseup", ".spinner-up, .spinner-down", e.proxy(this.stopSpin, this)), this.$element.on("mouseout", ".spinner-up, .spinner-down", e.proxy(this.stopSpin, this)), this.$element.on("mousedown", ".spinner-down", e.proxy(function () {
this.startSpin(!1)
}, this))) : (this.$element.on("click", ".spinner-up", e.proxy(function () {
this.step(!0)
}, this)), this.$element.on("click", ".spinner-down", e.proxy(function () {
this.step(!1)
}, this))), this.switches = {count: 1, enabled: !0}, this.switches.speed = "medium" === this.options.speed ? 300 : "fast" === this.options.speed ? 100 : 500, this.lastValue = null, this.render(), this.options.disabled && this.disable()
};
t.prototype = {constructor: t, render: function () {
var e = this.$input.val();
e ? this.value(e) : this.$input.val(this.options.value), this.$input.attr("maxlength", (this.options.max + "").split("").length)
}, change: function () {
var e = this.$input.val();
e / 1 ? this.options.value = e / 1 : (e = e.replace(/[^0-9]/g, ""), this.$input.val(e), this.options.value = e / 1), this.triggerChangedEvent()
}, stopSpin: function () {
clearTimeout(this.switches.timeout), this.switches.count = 1, this.triggerChangedEvent()
}, triggerChangedEvent: function () {
var e = this.value();
e !== this.lastValue && (this.lastValue = e, this.$element.trigger("changed", e), this.$element.trigger("change"))
}, startSpin: function (t) {
if (!this.options.disabled) {
var i = this.switches.count;
1 === i ? (this.step(t), i = 1) : i = 3 > i ? 1.5 : 8 > i ? 2.5 : 4, this.switches.timeout = setTimeout(e.proxy(function () {
this.iterator(t)
}, this), this.switches.speed / i), this.switches.count++
}
}, iterator: function (e) {
this.step(e), this.startSpin(e)
}, step: function (e) {
var t = this.options.value, i = e ? this.options.max : this.options.min;
if (e ? i > t : t > i) {
var s = t + (e ? 1 : -1) * this.options.step;
(e ? s > i : i > s) ? this.value(i) : this.value(s)
} else if (this.options.cycle) {
var n = e ? this.options.min : this.options.max;
this.value(n)
}
}, value: function (e) {
return!isNaN(parseFloat(e)) && isFinite(e) ? (e = parseFloat(e), this.options.value = e, this.$input.val(e), this) : this.options.value
}, disable: function () {
this.options.disabled = !0, this.$input.attr("disabled", ""), this.$element.find("button").addClass("disabled")
}, enable: function () {
this.options.disabled = !1, this.$input.removeAttr("disabled"), this.$element.find("button").removeClass("disabled")
}}, e.fn.spinner = function (i, s) {
var n, a = this.each(function () {
var a = e(this), o = a.data("spinner"), r = "object" == typeof i && i;
o || a.data("spinner", o = new t(this, r)), "string" == typeof i && (n = o[i](s))
});
return void 0 === n ? a : n
}, e.fn.spinner.defaults = {value: 1, min: 1, max: 999, step: 1, hold: !0, speed: "medium", disabled: !1}, e.fn.spinner.Constructor = t, e(function () {
e("body").on("mousedown.spinner.data-api", ".spinner", function () {
var t = e(this);
t.data("spinner") || t.spinner(t.data())
})
})
}(window.jQuery);
|
// Generated by CoffeeScript 1.4.0
(function() {
define("personBio", function() {
var bio, display, formatBio, get;
bio = null;
get = function(personName, callBack) {
var settings;
settings = {
url: "http://en.wikipedia.org/w/api.php?action=parse&page=" + personName + "§ion=0&format=json",
dataType: "jsonp",
success: function(data) {
bio = formatBio(data.parse.text["*"]);
return callBack();
},
error: function(error) {
return console.log("Error Getting Bio: ", error);
}
};
return $.ajax(settings);
};
display = function(desiredTag) {
$("#bioText").remove();
return $(desiredTag).append("<div id='bioText'> " + bio + " </div>");
};
formatBio = function(bio) {
bio = bio.slice(bio.indexOf("<p>"), bio.indexOf("<strong"));
while (bio.indexOf("href=\"/wiki") !== -1) {
bio = bio.replace("href=\"/wiki", "href=\"http://en.wikipedia.org/wiki");
}
return bio;
};
return {
get: get,
display: display,
bio: bio
};
});
}).call(this);
|
/**
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author bhouston / http://exocortex.com
*/
THREE.Quaternion = function ( x, y, z, w ) {
this._x = x || 0;
this._y = y || 0;
this._z = z || 0;
this._w = ( w !== undefined ) ? w : 1;
};
THREE.Quaternion.prototype = {
constructor: THREE.Quaternion,
_x: 0,_y: 0, _z: 0, _w: 0,
get x () {
return this._x;
},
set x ( value ) {
this._x = value;
this.onChangeCallback();
},
get y () {
return this._y;
},
set y ( value ) {
this._y = value;
this.onChangeCallback();
},
get z () {
return this._z;
},
set z ( value ) {
this._z = value;
this.onChangeCallback();
},
get w () {
return this._w;
},
set w ( value ) {
this._w = value;
this.onChangeCallback();
},
set: function ( x, y, z, w ) {
this._x = x;
this._y = y;
this._z = z;
this._w = w;
this.onChangeCallback();
return this;
},
copy: function ( quaternion ) {
this._x = quaternion.x;
this._y = quaternion.y;
this._z = quaternion.z;
this._w = quaternion.w;
this.onChangeCallback();
return this;
},
setFromEuler: function ( euler, update ) {
if ( euler instanceof THREE.Euler === false ) {
throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
}
// http://www.mathworks.com/matlabcentral/fileexchange/
// 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
// content/SpinCalc.m
var c1 = Math.cos( euler._x / 2 );
var c2 = Math.cos( euler._y / 2 );
var c3 = Math.cos( euler._z / 2 );
var s1 = Math.sin( euler._x / 2 );
var s2 = Math.sin( euler._y / 2 );
var s3 = Math.sin( euler._z / 2 );
if ( euler.order === 'XYZ' ) {
this._x = s1 * c2 * c3 + c1 * s2 * s3;
this._y = c1 * s2 * c3 - s1 * c2 * s3;
this._z = c1 * c2 * s3 + s1 * s2 * c3;
this._w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( euler.order === 'YXZ' ) {
this._x = s1 * c2 * c3 + c1 * s2 * s3;
this._y = c1 * s2 * c3 - s1 * c2 * s3;
this._z = c1 * c2 * s3 - s1 * s2 * c3;
this._w = c1 * c2 * c3 + s1 * s2 * s3;
} else if ( euler.order === 'ZXY' ) {
this._x = s1 * c2 * c3 - c1 * s2 * s3;
this._y = c1 * s2 * c3 + s1 * c2 * s3;
this._z = c1 * c2 * s3 + s1 * s2 * c3;
this._w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( euler.order === 'ZYX' ) {
this._x = s1 * c2 * c3 - c1 * s2 * s3;
this._y = c1 * s2 * c3 + s1 * c2 * s3;
this._z = c1 * c2 * s3 - s1 * s2 * c3;
this._w = c1 * c2 * c3 + s1 * s2 * s3;
} else if ( euler.order === 'YZX' ) {
this._x = s1 * c2 * c3 + c1 * s2 * s3;
this._y = c1 * s2 * c3 + s1 * c2 * s3;
this._z = c1 * c2 * s3 - s1 * s2 * c3;
this._w = c1 * c2 * c3 - s1 * s2 * s3;
} else if ( euler.order === 'XZY' ) {
this._x = s1 * c2 * c3 - c1 * s2 * s3;
this._y = c1 * s2 * c3 - s1 * c2 * s3;
this._z = c1 * c2 * s3 + s1 * s2 * c3;
this._w = c1 * c2 * c3 + s1 * s2 * s3;
}
if ( update !== false ) this.onChangeCallback();
return this;
},
setFromAxisAngle: function ( axis, angle ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
// assumes axis is normalized
var halfAngle = angle / 2, s = Math.sin( halfAngle );
this._x = axis.x * s;
this._y = axis.y * s;
this._z = axis.z * s;
this._w = Math.cos( halfAngle );
this.onChangeCallback();
return this;
},
setFromRotationMatrix: function ( m ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var te = m.elements,
m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
trace = m11 + m22 + m33,
s;
if ( trace > 0 ) {
s = 0.5 / Math.sqrt( trace + 1.0 );
this._w = 0.25 / s;
this._x = ( m32 - m23 ) * s;
this._y = ( m13 - m31 ) * s;
this._z = ( m21 - m12 ) * s;
} else if ( m11 > m22 && m11 > m33 ) {
s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
this._w = ( m32 - m23 ) / s;
this._x = 0.25 * s;
this._y = ( m12 + m21 ) / s;
this._z = ( m13 + m31 ) / s;
} else if ( m22 > m33 ) {
s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
this._w = ( m13 - m31 ) / s;
this._x = ( m12 + m21 ) / s;
this._y = 0.25 * s;
this._z = ( m23 + m32 ) / s;
} else {
s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
this._w = ( m21 - m12 ) / s;
this._x = ( m13 + m31 ) / s;
this._y = ( m23 + m32 ) / s;
this._z = 0.25 * s;
}
this.onChangeCallback();
return this;
},
setFromUnitVectors: function () {
// http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
// assumes direction vectors vFrom and vTo are normalized
var v1, r;
var EPS = 0.000001;
return function ( vFrom, vTo ) {
if ( v1 === undefined ) v1 = new THREE.Vector3();
r = vFrom.dot( vTo ) + 1;
if ( r < EPS ) {
r = 0;
if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
v1.set( - vFrom.y, vFrom.x, 0 );
} else {
v1.set( 0, - vFrom.z, vFrom.y );
}
} else {
v1.crossVectors( vFrom, vTo );
}
this._x = v1.x;
this._y = v1.y;
this._z = v1.z;
this._w = r;
this.normalize();
return this;
}
}(),
inverse: function () {
this.conjugate().normalize();
return this;
},
conjugate: function () {
this._x *= - 1;
this._y *= - 1;
this._z *= - 1;
this.onChangeCallback();
return this;
},
dot: function ( v ) {
return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
},
lengthSq: function () {
return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
},
length: function () {
return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
},
normalize: function () {
var l = this.length();
if ( l === 0 ) {
this._x = 0;
this._y = 0;
this._z = 0;
this._w = 1;
} else {
l = 1 / l;
this._x = this._x * l;
this._y = this._y * l;
this._z = this._z * l;
this._w = this._w * l;
}
this.onChangeCallback();
return this;
},
multiply: function ( q, p ) {
if ( p !== undefined ) {
console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
return this.multiplyQuaternions( q, p );
}
return this.multiplyQuaternions( this, q );
},
multiplyQuaternions: function ( a, b ) {
// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
this.onChangeCallback();
return this;
},
multiplyVector3: function ( vector ) {
console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
return vector.applyQuaternion( this );
},
slerp: function ( qb, t ) {
if ( t === 0 ) return this;
if ( t === 1 ) return this.copy( qb );
var x = this._x, y = this._y, z = this._z, w = this._w;
// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
if ( cosHalfTheta < 0 ) {
this._w = - qb._w;
this._x = - qb._x;
this._y = - qb._y;
this._z = - qb._z;
cosHalfTheta = - cosHalfTheta;
} else {
this.copy( qb );
}
if ( cosHalfTheta >= 1.0 ) {
this._w = w;
this._x = x;
this._y = y;
this._z = z;
return this;
}
var halfTheta = Math.acos( cosHalfTheta );
var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
if ( Math.abs( sinHalfTheta ) < 0.001 ) {
this._w = 0.5 * ( w + this._w );
this._x = 0.5 * ( x + this._x );
this._y = 0.5 * ( y + this._y );
this._z = 0.5 * ( z + this._z );
return this;
}
var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
this._w = ( w * ratioA + this._w * ratioB );
this._x = ( x * ratioA + this._x * ratioB );
this._y = ( y * ratioA + this._y * ratioB );
this._z = ( z * ratioA + this._z * ratioB );
this.onChangeCallback();
return this;
},
equals: function ( quaternion ) {
return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this._x = array[ offset ];
this._y = array[ offset + 1 ];
this._z = array[ offset + 2 ];
this._w = array[ offset + 3 ];
this.onChangeCallback();
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this._x;
array[ offset + 1 ] = this._y;
array[ offset + 2 ] = this._z;
array[ offset + 3 ] = this._w;
return array;
},
onChange: function ( callback ) {
this.onChangeCallback = callback;
return this;
},
onChangeCallback: function () {},
clone: function () {
return new THREE.Quaternion( this._x, this._y, this._z, this._w );
}
};
THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
return qm.copy( qa ).slerp( qb, t );
};
|
const mongoose = require('mongoose') //.set('debug', true)
const bcrypt = require('bcryptjs')
const ip = require('ip')
const fs = require('fs')
const os = require('os')
const splitca = require('split-ca')
const logger = require('../modules/logger')
const config = require('../config/config')
const encrypt = require('../modules/encryption')
const mqttc = require('../modules/mqttc')
const findisy = require('../modules/findisy')
const isy = require('../modules/isy')
// Node Schema
const SettingsSchema = mongoose.Schema({
name: {
type: String,
default: 'polyglot'
},
'isyUsername': {
type: String,
default: process.env.ISY_USERNAME || 'admin'
},
'isyPassword': {
type: String,
default: encrypt.encryptText('admin')
},
'isyPort': {
type: Number,
default: process.env.ISY_PORT || 80
},
'isyHost': {
type: String,
default: process.env.ISY_HOST || '192.168.1.10'
},
'isyHttps': {
type: Boolean,
default: process.env.ISY_HTTPS || false
},
'isyVersion': {
type: String,
default: '0.0.0'
},
'pgVersion': {
type: String,
default: '0.0.0'
},
'mqttHost': {
type: String,
default: process.env.MQTT_HOST || 'localhost'
},
'mqttPort': {
type: Number,
default: process.env.MQTT_PORT || 1883
},
'secret': {
type: String,
default: process.env.SECRET || encrypt.randomString(25)
},
'ipAddress': {
type: String,
default: process.env.HOST_IP || ip.address()
},
'isyConnected': {
type: Boolean,
default: false
},
'isyFound': {
type: Boolean,
default: false
},
'listenPort': {
type: Number,
default: process.env.HOST_PORT || 3000
},
'useHttps': {
type: Boolean,
default: process.env.USEHTTPS || true
},
'sslData': {
type: Object,
default: {}
},
'customSSL': {
type: Boolean,
default: false
},
'customSSLData': {
type: Object,
default: {}
}
}, { usePushEach: true })
SettingsSchema.statics = {
sendUpdate () {
cleanSettings = SettingsModel.cleanSettings()
mqttc.publish('udi/polyglot/frontend/settings', {node: 'polyglot', settings: cleanSettings}, {retain: true})
},
async updateSettings (newSettings, callback) {
if (newSettings.hasOwnProperty('updateprofile')) {
const options = { new: true, upsert: true }
const query = {_id: new mongoose.Types.ObjectId(newSettings.updateprofile._id)}
delete newSettings.updateprofile._id
if (newSettings.updateprofile.hasOwnProperty('password')) {
var newPass
bcrypt.genSalt(2, (err, salt) => {
bcrypt.hash(newSettings.updateprofile.password, salt, (err, hash) => {
if(err) throw err
newSettings.updateprofile.password = hash
UserModel.findOneAndUpdate(query, newSettings.updateprofile, options, (err, doc) => {
if (err) { return logger.error('Failed to update profile: ' + err)}
logger.info('Successfully updated profile for User: ' + doc.username)
})
})
})
} else {
UserModel.findByIdAndUpdate(new mongoose.Types.ObjectId(newSettings.updateprofile._id), newSettings.updateprofile, options, (err, doc) => {
logger.info('Successfully updated profile for User: ' + doc.username)
})
}
} else {
settings = JSON.parse(JSON.stringify(newSettings.updatesettings))
if (settings.name) { delete settings.name }
if (settings._id) { delete settings._id }
if (settings.isyPassword) {
settings.isyPassword = encrypt.encryptText(settings.isyPassword)
}
const query = { name: 'polyglot' }
const options = { new: true, upsert: true }
SettingsModel.findOneAndUpdate(query, settings, options, async (err, doc) => {
logger.info('Settings Saved Successfully.')
config.settings = doc
if (newSettings.hasOwnProperty('seq')) {
let response = {
node: 'polyglot',
seq: newSettings.seq,
response: {
success: err ? false : true,
msg: err ? err : ''
}
}
mqttc.publish('udi/polyglot/frontend/settings', response)
await isy.getVersion()
this.sendUpdate()
NodeServerModel.verifyNonManagedNodeServers()
}
if (callback) callback(err, doc)
})
}
},
async resetToDefault () {
const newSettings = new SettingsModel()
let settings = config.dotenv.parsed || {}
if (settings.hasOwnProperty('ISY_HOST')) {
newSettings.isyHost = settings.ISY_HOST
if (settings.hasOwnProperty('ISY_PORT')) { newSettings.isyPort = settings.ISY_PORT }
if (settings.hasOwnProperty('ISY_HTTPS')) { newSettings.isyHttps = settings.ISY_HTTPS }
logger.info(`ISY Host Override found. Skipping auto-discovery. ${newSettings.isyHttps ? 'https://' : 'http://'}${newSettings.isyHost}:${newSettings.isyPort}`)
const query = { name: 'polyglot' }
const options = { overwrite: true, new: true, upsert: true }
var upsertData = newSettings.toObject()
delete upsertData._id
await SettingsModel.findOneAndUpdate(query, upsertData, options)
await SettingsModel.loadSettings()
} else {
logger.info(`Auto Discovering ISY on local network.....`)
try {
[isyFound, isyAddress, isyPort] = await findisy.find()
newSettings.isyHost = isyAddress
newSettings.isyPort = isyPort
newSettings.isyFound = true
logger.info(`${(isyFound ? 'ISY discovered at address' : 'No ISY responded on local network. Using default config of')}: ${isyAddress}:${isyPort}`)
} catch (err) {
logger.error(err)
}
const query = { name: 'polyglot' }
const options = { overwrite: true, new: true, upsert: true }
var upsertData = newSettings.toObject()
delete upsertData._id
await SettingsModel.findOneAndUpdate(query, upsertData, options)
await SettingsModel.loadSettings()
}
},
async loadSettings() {
let dbsettings = await SettingsModel.findOne({name: 'polyglot'})
if (dbsettings) {
config.settings = dbsettings
config.settings.pgVersion = require('../../package.json').version
logger.info('Settings: Polyglot Version ' + config.settings.pgVersion)
logger.info('Settings: Retrieved config from database')
await SettingsModel.parseEnvUpdate()
if (config.settings.useHttps === true) {
try {
await this.getSSLData()
} catch (e) {
logger.error('Failed to get SSL Key or Cert. Falling back to HTTP')
config.settings.useHttps = false
}
}
await config.settings.save()
} else {
logger.info('Settings: No config found in database, creating settings entries.')
await SettingsModel.resetToDefault()
}
},
async getSSLData() {
const sslDir = os.homedir() + '/.polyglot/ssl/'
process.umask(0o177)
if (Object.keys(config.settings.sslData).length !== 0 && config.settings.sslData.constructor === Object) {
logger.debug('TLS: Found Keys and Certificate data in database. Exporting to ' + sslDir.toString())
fs.writeFileSync(sslDir + 'polyglot_private.key', config.settings.sslData.private)
fs.writeFileSync(sslDir + 'polyglot_public.key', config.settings.sslData.public)
fs.writeFileSync(sslDir + 'polyglot.crt', config.settings.sslData.cert)
fs.writeFileSync(sslDir + 'client_private.key', config.settings.sslData.clientprivate)
fs.writeFileSync(sslDir + 'client_public.key', config.settings.sslData.clientpublic)
fs.writeFileSync(sslDir + 'client.crt', config.settings.sslData.clientcert)
} else {
logger.info('SSL: No HTTPS Certificate or Key found. Generating...')
var selfsigned = require('selfsigned')
var attrs = [
{ name: 'commonName', value: os.hostname()},
{ name: 'countryName', value: 'US'},
{ shortName: 'ST', value: 'California'},
{ name: 'localityName', value: 'Los Angeles'},
{ name: 'organizationName', value: 'Universal Devices'},
{ shortName: 'OU', value: 'polyglot'}
]
var opts = {
keySize: 2048,
algorithm: 'sha256',
days: 365 * 10,
clientCertificate: true,
clientCertificateCN: 'polyglot_client'
}
opts.extensions = [{
name: 'subjectAltName',
altNames: [{
type: 2,
value: os.hostname()
}, {
type: 2,
value: 'polyglot.local'
}, {
type: 2,
value: 'raspberrypi.local'
}, {
type: 2,
value: 'polyglot'
}, {
type: 2,
value: 'localhost'
} , {
type: 7,
ip: config.settings.ipAddress
}, {
type: 7,
ip: '127.0.0.1'
} ]
}]
var pems = await selfsigned.generate(attrs, opts)
config.settings.sslData = pems
fs.writeFileSync(sslDir + 'polyglot_private.key', pems.private)
fs.writeFileSync(sslDir + 'polyglot_public.key', pems.public)
fs.writeFileSync(sslDir + 'polyglot.crt', pems.cert)
fs.writeFileSync(sslDir + 'client_private.key', pems.clientprivate)
fs.writeFileSync(sslDir + 'client_public.key', pems.clientpublic)
fs.writeFileSync(sslDir + 'client.crt', pems.clientcert)
logger.info('SSL: Certificate Generation completed successfully.')
}
process.umask(0o022)
if (config.settings.customSSL) {
await this.readCustomSSL(sslDir)
}
},
async readCustomSSL(sslDir) {
let customSSLData = JSON.parse(JSON.stringify(config.settings.customSSLData))
if (Object.keys(customSSLData).length === 0) {
customSSLData = {key: '', cert: '', ca: []}
}
try {
customSSLData.key = encrypt.encryptText(fs.readFileSync(sslDir + 'custom/custom.key', 'utf8'))
logger.debug(`Custom SSL Key file found. Importing to database and encrypting.`)
} catch (e) {
if (customSSLData.key === '') {
logger.error(`Custom SSL Key file could not be read and doesn't exist in the database. Falling back to self-signed.`)
config.settings.customSSL = false
} else {
logger.debug(`Custom SSL Key file could not be read but data exists in database. Using.`)
}
}
if (config.settings.customSSL) {
try {
customSSLData.cert = fs.readFileSync(sslDir + 'custom/custom.crt', 'utf8')
logger.debug(`Custom SSL Cert file found. Importing to database.`)
} catch (e) {
if (customSSLData.cert === '') {
logger.error(`Custom SSL Cert file could not be read and doesn't exist in the database. Falling back to self-signed.`)
config.settings.customSSL = false
} else {
logger.debug(`Custom SSL Cert file could not be read but data exists in database. Using.`)
}
}
}
if (config.settings.customSSL) {
try {
customSSLData.ca = splitca(sslDir + 'custom/custom.ca', '\n', 'utf8')
logger.debug(`Custom SSL CA Chain file found. Importing to database.`)
} catch (e) {
if (customSSLData.ca.length === 0) {
logger.error(`Custom SSL CA file could not be read and doesn't exist in the database. Falling back to self-signed.`)
config.settings.customSSL = false
} else {
logger.debug(`Custom SSL CA file could not be read but data exists in database. Using.`)
}
}
}
config.settings.customSSLData = customSSLData
if (config.settings.customSSL) {
logger.debug(`Custom SSL Certificates enabled`)
}
},
cleanSettings() {
// hack to deepcopy in node
let cleanSettings = JSON.parse(JSON.stringify(config.settings))
delete cleanSettings.isyPassword
delete cleanSettings._id
delete cleanSettings.name
delete cleanSettings.sslData
delete cleanSettings.customSSLData
delete cleanSettings.customSSL
return cleanSettings
},
async parseEnvUpdate() {
try {
let settings = config.dotenv.parsed || {}
config.settings.customSSL = false
if (settings.hasOwnProperty('HOST_IP')) { config.settings.ipAddress = settings.HOST_IP } else { config.settings.ipAddress = ip.address() }
if (settings.hasOwnProperty('HOST_PORT')) { config.settings.listenPort = settings.HOST_PORT }
if (settings.hasOwnProperty('ISY_USERNAME')) { config.settings.isyUsername = settings.ISY_USERNAME }
if (settings.hasOwnProperty('ISY_PASSWORD')) { config.settings.isyPassword = encrypt.encryptText(settings.ISY_PASSWORD) }
if (settings.hasOwnProperty('ISY_HOST')) { config.settings.isyHost = settings.ISY_HOST }
if (settings.hasOwnProperty('ISY_PORT')) { config.settings.isyPort = settings.ISY_PORT }
if (settings.hasOwnProperty('ISY_HTTPS')) { config.settings.isyHttps = settings.ISY_HTTPS }
if (settings.hasOwnProperty('MQTT_HOST')) { config.settings.mqttHost = settings.MQTT_HOST }
if (settings.hasOwnProperty('MQTT_PORT')) { config.settings.mqttPort = settings.MQTT_PORT }
if (settings.hasOwnProperty('CUSTOM_SSL')) { config.settings.customSSL = settings.CUSTOM_SSL }
if (settings.USEHTTPS) { config.settings.useHttps = settings.USEHTTPS }
logger.info('Settings: Retrieved config overrides from .env and updated database')
} catch (e) {
logger.error('Settings: ParseEnv Error ' + e)
}
},
}
SettingsModel = mongoose.model('Setting', SettingsSchema)
module.exports = SettingsModel
|
'use strict';
/**
* Removes server error when user updates input
*/
angular.module('flickrScannerApp')
.directive('mongooseError', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
element.on('keydown', () => ngModel.$setValidity('mongoose', true));
}
};
});
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define(["require","exports"],function(k,e){Object.defineProperty(e,"__esModule",{value:!0});e.applyToModelMatrix=function(b,a){var c=-b[0],d=-b[1];b=-b[2];var e=a[3],f=a[7],g=a[11],h=a[15];a[0]+=e*c;a[1]+=e*d;a[2]+=e*b;a[4]+=f*c;a[5]+=f*d;a[6]+=f*b;a[8]+=g*c;a[9]+=g*d;a[10]+=g*b;a[12]+=h*c;a[13]+=h*d;a[14]+=h*b};e.applyToViewMatrix=function(b,a){var c=b[0],d=b[1];b=b[2];a[12]+=c*a[0]+d*a[4]+b*a[8];a[13]+=c*a[1]+d*a[5]+b*a[9];a[14]+=c*a[2]+d*a[6]+b*a[10];a[14]+=c*a[3]+d*a[7]+b*a[11]}});
|
import hasTransitions from 'ember-modal-service/utils/css-transitions/has-transitions';
import { module, test } from 'qunit';
import { createElement, clearScenario } from './helpers';
module('Unit | Util | css-transitions | has-transitions', (hooks) => {
hooks.afterEach(() => {
clearScenario();
});
test('it returns true when element has any transition', (assert) => {
const element = createElement();
element.style.transition = 'all .5s linear 0s';
assert.ok(hasTransitions(element), 'element has transitions');
});
test('it returns true when element has a transition', (assert) => {
const element = createElement();
element.style.transition = 'opacity .5s linear 0s';
assert.ok(hasTransitions(element), 'element has transitions');
});
test('it returns true when element has several transitions', (assert) => {
const element = createElement();
element.style.transition = 'opacity .5s linear 0s, background-color 1s linear 0s';
assert.ok(hasTransitions(element), 'element has transitions');
});
test('it returns false when element has no transitions', (assert) => {
const element = createElement();
assert.notOk(hasTransitions(element), 'element has no transitions');
});
test('it returns false when element has no durations', (assert) => {
const element = createElement();
element.style.transition = 'transform 0s linear 0s, -webkit-transform 0s linear 0s';
assert.notOk(hasTransitions(element), 'element has no transitions');
});
});
|
// // randomColor by David Merfield under the MIT license
// // https://github.com/davidmerfield/randomColor/
// ;(function(root, factory) {
// // Support AMD
// if (typeof define === 'function' && define.amd) {
// define([], factory);
// // Support CommonJS
// } else if (typeof exports === 'object') {
// var randomColor = factory();
// // Support NodeJS & Component, which allow module.exports to be a function
// if (typeof module === 'object' && module && module.exports) {
// exports = module.exports = randomColor;
// }
// // Support CommonJS 1.1.1 spec
// exports.randomColor = randomColor;
// // Support vanilla script loading
// } else {
// root.randomColor = factory();
// };
// }(this, function() {
// Seed to get repeatable colors
var seed = null;
// Shared color dictionary
var colorDictionary = {};
// Populate the color dictionary
loadColorBounds();
var randomColor = function(options) {
options = options || {};
if (options.seed && !seed) seed = options.seed;
var H,S,B;
// Check if we need to generate multiple colors
if (options.count != null) {
var totalColors = options.count,
colors = [];
options.count = null;
while (totalColors > colors.length) {
colors.push(randomColor(options));
}
options.count = totalColors;
//Keep the seed constant between runs.
if (options.seed) seed = options.seed;
return colors;
}
// First we pick a hue (H)
H = pickHue(options);
// Then use H to determine saturation (S)
S = pickSaturation(H, options);
// Then use S and H to determine brightness (B).
B = pickBrightness(H, S, options);
// Then we return the HSB color in the desired format
return setFormat([H,S,B], options);
};
function pickHue (options) {
var hueRange = getHueRange(options.hue),
hue = randomWithin(hueRange);
// Instead of storing red as two seperate ranges,
// we group them, using negative numbers
if (hue < 0) {hue = 360 + hue}
return hue;
}
function pickSaturation (hue, options) {
if (options.luminosity === 'random') {
return randomWithin([0,100]);
}
if (options.hue === 'monochrome') {
return 0;
}
var saturationRange = getSaturationRange(hue);
var sMin = saturationRange[0],
sMax = saturationRange[1];
switch (options.luminosity) {
case 'bright':
sMin = 55;
break;
case 'dark':
sMin = sMax - 10;
break;
case 'light':
sMax = 55;
break;
}
return randomWithin([sMin, sMax]);
}
function pickBrightness (H, S, options) {
var brightness,
bMin = getMinimumBrightness(H, S),
bMax = 100;
switch (options.luminosity) {
case 'dark':
bMax = bMin + 20;
break;
case 'light':
bMin = (bMax + bMin)/2;
break;
case 'random':
bMin = 0;
bMax = 100;
break;
}
return randomWithin([bMin, bMax]);
}
function setFormat (hsv, options) {
switch (options.format) {
case 'hsvArray':
return hsv;
case 'hslArray':
return HSVtoHSL(hsv);
case 'hsl':
var hsl = HSVtoHSL(hsv);
return 'hsl('+hsl[0]+', '+hsl[1]+'%, '+hsl[2]+'%)';
case 'hsla':
var hslColor = HSVtoHSL(hsv);
return 'hsla('+hslColor[0]+', '+hslColor[1]+'%, '+hslColor[2]+'%, ' + Math.random() + ')';
case 'rgbArray':
return HSVtoRGB(hsv);
case 'rgb':
var rgb = HSVtoRGB(hsv);
return 'rgb(' + rgb.join(', ') + ')';
case 'rgba':
var rgbColor = HSVtoRGB(hsv);
return 'rgba(' + rgbColor.join(', ') + ', ' + Math.random() + ')';
default:
return HSVtoHex(hsv);
}
}
function getMinimumBrightness(H, S) {
var lowerBounds = getColorInfo(H).lowerBounds;
for (var i = 0; i < lowerBounds.length - 1; i++) {
var s1 = lowerBounds[i][0],
v1 = lowerBounds[i][1];
var s2 = lowerBounds[i+1][0],
v2 = lowerBounds[i+1][1];
if (S >= s1 && S <= s2) {
var m = (v2 - v1)/(s2 - s1),
b = v1 - m*s1;
return m*S + b;
}
}
return 0;
}
function getHueRange (colorInput) {
if (typeof parseInt(colorInput) === 'number') {
var number = parseInt(colorInput);
if (number < 360 && number > 0) {
return [number, number];
}
}
if (typeof colorInput === 'string') {
if (colorDictionary[colorInput]) {
var color = colorDictionary[colorInput];
if (color.hueRange) {return color.hueRange}
}
}
return [0,360];
}
function getSaturationRange (hue) {
return getColorInfo(hue).saturationRange;
}
function getColorInfo (hue) {
// Maps red colors to make picking hue easier
if (hue >= 334 && hue <= 360) {
hue-= 360;
}
for (var colorName in colorDictionary) {
var color = colorDictionary[colorName];
if (color.hueRange &&
hue >= color.hueRange[0] &&
hue <= color.hueRange[1]) {
return colorDictionary[colorName];
}
} return 'Color not found';
}
function randomWithin (range) {
if (seed == null) {
return Math.floor(range[0] + Math.random()*(range[1] + 1 - range[0]));
} else {
//Seeded random algorithm from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
var max = range[1] || 1;
var min = range[0] || 0;
seed = (seed * 9301 + 49297) % 233280;
var rnd = seed / 233280.0;
return Math.floor(min + rnd * (max - min));
}
}
function HSVtoHex (hsv){
var rgb = HSVtoRGB(hsv);
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
var hex = "#" + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]);
return hex;
}
function defineColor (name, hueRange, lowerBounds) {
var sMin = lowerBounds[0][0],
sMax = lowerBounds[lowerBounds.length - 1][0],
bMin = lowerBounds[lowerBounds.length - 1][1],
bMax = lowerBounds[0][1];
colorDictionary[name] = {
hueRange: hueRange,
lowerBounds: lowerBounds,
saturationRange: [sMin, sMax],
brightnessRange: [bMin, bMax]
};
}
function loadColorBounds () {
defineColor(
'monochrome',
null,
[[0,0],[100,0]]
);
defineColor(
'red',
[-26,18],
[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]
);
defineColor(
'orange',
[19,46],
[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]
);
defineColor(
'yellow',
[47,62],
[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]
);
defineColor(
'green',
[63,178],
[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]
);
defineColor(
'blue',
[179, 257],
[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]
);
defineColor(
'purple',
[258, 282],
[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]
);
defineColor(
'pink',
[283, 334],
[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]]
);
}
function HSVtoRGB (hsv) {
// this doesn't work for the values of 0 and 360
// here's the hacky fix
var h = hsv[0];
if (h === 0) {h = 1}
if (h === 360) {h = 359}
// Rebase the h,s,v values
h = h/360;
var s = hsv[1]/100,
v = hsv[2]/100;
var h_i = Math.floor(h*6),
f = h * 6 - h_i,
p = v * (1 - s),
q = v * (1 - f*s),
t = v * (1 - (1 - f)*s),
r = 256,
g = 256,
b = 256;
switch(h_i) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
var result = [Math.floor(r*255), Math.floor(g*255), Math.floor(b*255)];
return result;
}
function HSVtoHSL (hsv) {
var h = hsv[0],
s = hsv[1]/100,
v = hsv[2]/100,
k = (2-s)*v;
return [
h,
Math.round(s*v / (k<1 ? k : 2-k) * 10000) / 100,
k/2 * 100
];
}
// return randomColor;
// }));
|
/*
Dice rolls, coin flips, 8balls, syncwatch, banners, JS injections, missle
launchers - amusement.
*/
const common = require('../common/index'),
config = require('../config'),
db = require('../db'),
fs = require('fs'),
hooks = require('../util/hooks'),
state = require('./state'),
push = require('./websockets').push,
radio = config.RADIO && require('./radio')
// Insert #hash commands as tuples into the text body array
function roll_dice(frag, parsed) {
if (!frag.length)
return false
let info
const types = common.tupleTypes
switch (frag) {
case '#flip':
info = [types.flip, Math.random() > 0.5]
break
case '#8ball':
info = [types.dice, roll(state.hot.EIGHT_BALL.length)]
break
case '#q':
info = radio && [types.radioQueue, radio.queue]
break
default:
info = parseRegularDice(frag) || parseSyncwatch(frag)
}
return info && parsed.push(info)
}
exports.roll_dice = roll_dice
function roll(faces) {
return Math.floor(Math.random() * faces)
}
function parseRegularDice(frag) {
const m = frag.match(/^#(\d*)d(\d+)([+-]\d+)?$/i)
if (!m)
return false
const n = parseInt(m[1], 10) || 1,
faces = parseInt(m[2], 10),
bias = parseInt(m[3] || 10) || 0
if (n < 1 || n > 10 || faces < 2 || faces > 100)
return false
const die = [common.tupleTypes.dice, n, faces, bias]
for (let i = 0; i < n; i++) {
info.push(roll(faces) + 1)
}
return die
}
function parseSyncwatch(frag) {
// First capture group may or may not be present
const sw = frag.match(/^#sw(\d+:)?(\d+):(\d+)([+-]\d+)?$/i)
if (!sw)
return false
const hour = parseInt(sw[1], 10) || 0,
min = parseInt(sw[2], 10),
sec = parseInt(sw[3], 10)
let start = common.serverTime()
// Offset the start. If the start is in the future, a countdown will be
// displayed.
if (sw[4]) {
const symbol = sw[4].slice(0, 1),
offset = sw[4].slice(1) * 1000
start = symbol == '+' ? start + offset : start - offset
}
const end = ((hour * 60 + min) * 60 + sec) * 1000 + start
return [common.tupleTypes.syncwatch, sec, min, hour, start, end]
}
// Information banner
hooks.hook('clientSynced', function (info, cb) {
const {client} = info;
client.db.get_banner(function (err, msg) {
if (err)
return cb(err);
if (msg)
client.send([0, common.UPDATE_BANNER, msg]);
cb();
});
});
// Inject JS on client synchronisation
hooks.hook('clientSynced', (info, cb) => {
readJS(js => {
if (!js)
return cb();
info.client.send([0, common.EXECUTE_JS, js]);
cb();
});
});
function readJS(cb) {
const {inject_js} = state.hot
if (!inject_js)
return cb()
fs.readFile(inject_js, {encoding: 'utf8'}, (err, js) => {
if (err) {
winston.error('Failed ro read JS injection:', err)
return cb()
}
cb(js)
});
}
// Push injection to all clients on hot reload
function pushJS() {
readJS(js => js && push([0, common.EXECUTE_JS, js]));
}
exports.pushJS = pushJS;
// Regex replacement filter
function hot_filter(frag) {
let filter = state.hot.FILTER
if (!filter)
return frag
for (let f of filter) {
const m = frag.match(f.p)
if (m) {
// Case sensitivity
if (m[0].length > 2) {
if (/[A-Z]/.test(m[0].charAt(1)))
f.r = f.r.toUpperCase()
else if (/[A-Z]/.test(m[0].charAt(0)))
f.r = f.r.charAt(0).toUpperCase() + f.r.slice(1)
}
return frag.replace(f.p, f.r)
}
}
return frag
}
exports.hot_filter = hot_filter
|
var path = require("path"),
app = require(path.join(__dirname, "../server")),
request = require("supertest"),
assert = require("chai").assert,
helper = require(__dirname + "/helper")
async = require("async");
describe("Postcodes routes", function () {
var testPostcode;
before(function (done) {
this.timeout(0);
helper.clearPostcodeDb(function (error, result) {
if (error) return done(error);
helper.seedPostcodeDb(function (error, result) {
if (error) return done(error);
done();
});
});
});
beforeEach(function (done) {
helper.lookupRandomPostcode(function (result) {
testPostcode = result.postcode;
testOutcode = result.outcode;
done();
});
});
after(function (done) {
helper.clearPostcodeDb(done);
});
describe("GET /postcodes", function () {
var uri, limit;
it ("should return a list of matching postcode objects", function (done) {
uri = encodeURI("/postcodes?q=" + testPostcode.replace(" ", "").slice(0, 2));
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 10);
response.body.result.forEach(function (postcode) {
helper.isPostcodeObject(postcode);
});
done();
});
});
it ("should be insensitive to case", function (done) {
uri = encodeURI("/postcodes?q=" + testPostcode.slice(0, 2).toLowerCase());
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 10);
response.body.result.forEach(function (postcode) {
helper.isPostcodeObject(postcode);
});
done();
});
});
it ("should be insensitive to space", function (done) {
uri = encodeURI("/postcodes?q=" + testPostcode.slice(0, 2).split("").join(" "));
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 10);
response.body.result.forEach(function (postcode) {
helper.isPostcodeObject(postcode);
});
done();
});
});
it ("should be sensitive to limit", function (done) {
limit = 11;
uri = encodeURI("/postcodes?q=" + testPostcode.slice(0, 2).split("").join(" ") + "&limit=" + limit);
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 11);
response.body.result.forEach(function (postcode) {
helper.isPostcodeObject(postcode);
});
done();
});
});
it ("should max out limit at 100", function (done) {
limit = 101;
uri = encodeURI("/postcodes?q=" + testPostcode.slice(0, 2).split("").join(" ") + "&limit=" + limit);
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 100);
response.body.result.forEach(function (postcode) {
helper.isPostcodeObject(postcode);
});
done();
});
});
it ("should set limit to 10 if invalid", function (done) {
limit = "BOGUS";
uri = encodeURI("/postcodes?q=" + testPostcode.slice(0, 2).split("").join(" ") + "&limit=" + limit);
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 10);
response.body.result.forEach(function (postcode) {
helper.isPostcodeObject(postcode);
});
done();
});
});
it ("should return 400 if no postcode submitted", function (done) {
uri = encodeURI("/postcodes?q=");
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(400)
.end(function (error, response) {
if (error) return done(error);
assert.equal(response.body.status, 400);
done();
});
});
it ("should respond to options", function (done) {
request(app)
.options("/postcodes")
.expect(204)
.end(function (error, response) {
if (error) done(error);
helper.validCorsOptions(response);
done();
});
});
});
describe("GET /postcodes/:postcode", function () {
it ("should return 200 if postcode found", function (done) {
var path = ["/postcodes/", encodeURI(testPostcode)].join("");
request(app)
.get(path)
.expect('Content-Type', /json/)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.equal(response.body.status, 200);
assert.equal(response.body.result.postcode, testPostcode);
helper.isPostcodeObject(response.body.result);
done();
});
});
it ("should return 404 if not found", function (done) {
testPostcode = "ID11QE";
var path = ["/postcodes/", encodeURI(testPostcode)].join("");
request(app)
.get(path)
.expect('Content-Type', /json/)
.expect(404)
.end(function (error, response) {
if (error) return done(error);
assert.equal(response.body.status, 404);
assert.match(response.body.error, /postcode not found/i);
done();
});
});
it ("returns invalid postcode if postcode doesn't match format", function (done) {
testPostcode = "FOO";
var path = ["/postcodes/", encodeURI(testPostcode)].join("");
request(app)
.get(path)
.expect('Content-Type', /json/)
.expect(404)
.end(function (error, response) {
if (error) return done(error);
assert.equal(response.body.status, 404);
assert.match(response.body.error, /invalid postcode/i);
done();
});
});
it ("should respond to options", function (done) {
var path = ["/postcodes/", encodeURI(testPostcode)].join("");
request(app)
.options(path)
.expect(204)
.end(function (error, response) {
if (error) done(error);
helper.validCorsOptions(response);
done();
});
});
});
describe("GET /postcodes/:postcode/validate", function () {
it ("should return true if postcode found", function (done) {
var path = ["/postcodes/", encodeURI(testPostcode), "/validate"].join("");
request(app)
.get(path)
.expect('Content-Type', /json/)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.equal(response.body.status, 200);
assert.isTrue(response.body.result);
done();
});
});
it ("should return false if postcode not found", function (done) {
testPostcode = "ID11QE";
var path = ["/postcodes/", encodeURI(testPostcode), "/validate"].join("");
request(app)
.get(path)
.expect('Content-Type', /json/)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.equal(response.body.status, 200);
assert.isFalse(response.body.result);
done();
});
});
it ("should respond to options", function (done) {
var path = ["/postcodes/", encodeURI(testPostcode), "/validate"].join("");
request(app)
.options(path)
.expect(204)
.end(function (error, response) {
if (error) done(error);
helper.validCorsOptions(response);
done();
});
});
});
describe("GET /random/postcode", function () {
it ("should return a random postcode", function (done) {
var path = "/random/postcodes";
request(app)
.get(path)
.expect('Content-Type', /json/)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.property(response.body.result, "postcode");
helper.isPostcodeObject(response.body.result);
done();
});
});
it ("should respond to options", function (done) {
var path = "/random/postcodes";
request(app)
.options(path)
.expect(204)
.end(function (error, response) {
if (error) done(error);
helper.validCorsOptions(response);
done();
});
});
describe("filtered by outcode", function () {
it ("returns a random postcode within an outcode", function (done) {
var path = "/random/postcodes";
var outcode = "AB10";
request(app)
.get(path)
.query({ outcode: outcode })
.expect('Content-Type', /json/)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.property(response.body.result, "postcode");
helper.isPostcodeObject(response.body.result);
assert.equal(response.body.result.outcode, outcode);
done();
});
});
it ("returns a null for invalid outcode", function (done) {
var path = "/random/postcodes";
var outcode = "BOGUS";
request(app)
.get(path)
.query({ outcode: outcode })
.expect('Content-Type', /json/)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isNull(response.body.result);
done();
});
});
});
});
describe("GET /postcodes/:postcode/autocomplete", function () {
var uri, limit;
let testPostcode = "AB101AL";
it ("should return a list of matching postcodes only", function (done) {
uri = encodeURI("/postcodes/" + testPostcode.slice(0, 2) + "/autocomplete");
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 10);
response.body.result.forEach(function (postcode) {
assert.isString(postcode);
});
done();
});
});
it ("should be insensitive to case", function (done) {
uri = encodeURI("/postcodes/" + testPostcode.slice(0, 2).toLowerCase() + "/autocomplete");
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 10);
response.body.result.forEach(function (postcode) {
assert.isString(postcode);
});
done();
});
});
it ("should be insensitive to space", function (done) {
uri = encodeURI("/postcodes/" + testPostcode.slice(0, 2).split("").join(" ") + "/autocomplete");
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 10);
response.body.result.forEach(function (postcode) {
assert.isString(postcode);
});
done();
});
});
it("should be sensitive to limit", function (done) {
limit = 11;
uri = encodeURI("/postcodes/" + testPostcode.slice(0, 2).split("").join(" ") + "/autocomplete" + "?limit=" + limit);
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, limit);
response.body.result.forEach(function (postcode) {
assert.isString(postcode);
});
done();
});
});
it("should max limit out at 100", function (done) {
limit = 101;
uri = encodeURI("/postcodes/" + testPostcode.slice(0, 2).split("").join(" ") + "/autocomplete" + "?limit=" + limit);
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 100);
response.body.result.forEach(function (postcode) {
assert.isString(postcode);
});
done();
});
});
it("should set limit to 10 if invalid", function (done) {
limit = "BOGUS";
uri = encodeURI("/postcodes/" + testPostcode.slice(0, 2).split("").join(" ") + "/autocomplete" + "?limit=" + limit);
request(app)
.get(uri)
.expect("Content-Type", /json/)
.expect(helper.allowsCORS)
.expect(200)
.end(function (error, response) {
if (error) return done(error);
assert.isArray(response.body.result);
assert.equal(response.body.result.length, 10);
response.body.result.forEach(function (postcode) {
assert.isString(postcode);
});
done();
});
});
it ("should respond to options", function (done) {
uri = encodeURI("/postcodes/" + testPostcode.slice(0, 2) + "/autocomplete");
request(app)
.options(uri)
.expect(204)
.end(function (error, response) {
if (error) done(error);
helper.validCorsOptions(response);
done();
});
});
});
});
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {
var margin = {
left: 75,
right: 75,
top: 75,
bottom: 75
};
var chartWidth = 1500 - margin.left - margin.right;
var chartHeight = 700 - margin.top - margin.bottom;
d3.select('.chart')
.attr('width', (chartWidth + margin.left + margin.right) + "px")
.attr('height', (chartHeight + margin.top + margin.bottom) + "px");
// We also need a legend
var legendWidth = 200, legendHeight = 100;
var legend = d3.select('.chart')
.append('g')
.classed('legend', true)
.attr('transform', 'translate(' + (margin.left + (chartWidth - legendWidth)) + ', ' + (margin.top) + ')');
legend.append('rect')
.attr('width', legendWidth)
.attr('height', legendHeight);
legend.append('circle')
.attr('r', 5)
.attr('fill', 'purple')
.attr('transform', 'translate(' + (legendWidth / 5) + ', ' + (legendHeight / 3) + ')');
legend.append('text')
.text('Female Respondents')
.attr('transform', 'translate(' + ((legendWidth / 5) + 10) + ', ' + ((legendHeight / 3) + 5) + ')');
legend.append('circle')
.attr('r', 5)
.attr('fill', 'blue')
.attr('transform', 'translate(' + (legendWidth / 5) + ', ' + ((legendHeight / 3) * 2) + ')');
legend.append('text')
.text('Male Respondents')
.attr('transform', 'translate(' + ((legendWidth / 5) + 10) + ', ' + (((legendHeight / 3) * 2) + 5) + ')');
d3.json('https://assets.zackward.net/timeuse4.json', function (error, data) {
if (error !== null) {
console.log("Error: " + error);
}
// First let's build our scales and axes
var x = d3.scaleLinear()
.domain(d3.extent(data.data, function (d) { return d.age; }))
.range([0, chartWidth]);
var xAxis = d3.axisBottom(x);
d3.select('.chart')
.append('g')
.call(xAxis)
.classed('axis', true)
.attr('transform', 'translate(' + margin.left + ', ' + (margin.top + chartHeight) + ')');
d3.select('.chart')
.append('g')
.classed('axis', true)
.append('text')
.text('Age')
.attr('fill', '#000')
.attr('text-anchor', 'middle')
.attr('transform', 'translate(' + (margin.left + (chartWidth / 2)) + ', ' + (margin.top + chartHeight + margin.bottom - 20) + ')');
var minEarning = d3.min(data.data, function (d) { return d.avgWeeklyEarnings; });
var maxEarning = d3.max(data.data, function (d) { return d.avgWeeklyEarnings; });
var y = d3.scaleLinear()
.domain([maxEarning, minEarning])
.range([0, chartHeight]);
var yAxis = d3.axisLeft(y);
d3.select('.chart')
.append('g')
.call(yAxis)
.classed('axis', true)
.attr('transform', 'translate(' + (margin.left) + ', ' + margin.top + ')');
d3.select('.chart')
.append('g')
.classed('axis', true)
.append('text')
.text('Average Weekly Earnings in USD')
.attr('fill', '#000')
.attr('text-anchor', 'middle')
.attr('transform', 'translate(' + (margin.left / 5) + ', ' + (margin.top + (chartHeight / 2)) + ') rotate(-90)');
var r = d3.scaleLinear()
.domain(d3.extent(data.data, function (d) { return d.minutes; }))
.range([5, 25]);
// Now add our data
var update = d3.select('.chart')
.selectAll('.data-point')
.data(data.data);
update.enter()
.append('g')
.attr('class', 'data-point')
.append('circle')
.attr('cx', function (d) { return margin.left + x(d.age); })
.attr('cy', function (d) { return margin.top + y(d.avgWeeklyEarnings); })
.attr('r', '5')
.attr('class', function (d) { return d.sex == 'M' ? 'male' : 'female'; })
.on('mouseenter', function (d) {
d3.select(this)
.attr('stroke', 'black')
.attr('stroke-width', '2');
d3.select('.scatterplot-tooltip')
.html("<p>In " + d.year + ", " + d.age + " year old " + (d.sex == "M" ? "males" : "females") + " earned an average of $" + d.avgWeeklyEarnings + " per week.</p>")
.style('display', 'block')
.style('left', (d3.event.pageX - 75) + "px")
.style('top', (d3.event.pageY + 20) + "px");
})
.on('mouseout', function (d) {
d3.select(this)
.attr('stroke', null)
.attr('stroke-width', null);
d3.select('.scatterplot-tooltip')
.style('display', 'none');
});
});
/***/ }
/******/ ]);
|
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=Base64._utf8_encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+ this._keyStr.charAt(enc1)+ this._keyStr.charAt(enc2)+ this._keyStr.charAt(enc3)+ this._keyStr.charAt(enc4);}
return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+ String.fromCharCode(chr1);if(enc3!=64){output=output+ String.fromCharCode(chr2);}
if(enc4!=64){output=output+ String.fromCharCode(chr3);}}
output=Base64._utf8_decode(output);return output;},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}
else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}
else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}
else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+ 1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}
else{c2=utftext.charCodeAt(i+ 1);c3=utftext.charCodeAt(i+ 2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return string;}}
var encode=document.getElementById('encode'),decode=document.getElementById('decode'),output=document.getElementById('output'),input=document.getElementById('input');var User_ID="";var protected_links="";var a_to_va=0;var a_to_vb=0;var a_to_vc="";function auto_safelink(){auto_safeconvert();}
function auto_safeconvert(){var a_to_vd=window.location.hostname;if(protected_links!=""&&!protected_links.match(a_to_vd)){protected_links+=", "+ a_to_vd;}else if(protected_links=="")
{protected_links=a_to_vd;}
var a_to_ve="";var a_to_vf=new Array();var a_to_vg=0;a_to_ve=document.getElementsByTagName("a");a_to_va=a_to_ve.length;a_to_vf=a_to_fa();a_to_vg=a_to_vf.length;var a_to_vh=false;var j=0;var a_to_vi="";for(var i=0;i<a_to_va;i++)
{a_to_vh=false;j=0;while(a_to_vh==false&&j<a_to_vg)
{a_to_vi=a_to_ve[i].href;if(a_to_vi.match(a_to_vf[j])||!a_to_vi||!a_to_vi.match("http"))
{a_to_vh=true;}
j++;}
if(a_to_vh==false)
{var encryptedUrl=Base64.encode(a_to_vi);a_to_ve[i].href="https://urlminify.com/2017/08/chained?url="+ encryptedUrl;a_to_ve[i].rel="nofollow";a_to_vb++;a_to_vc+=i+":::"+ a_to_ve[i].href+"\n";}}
var a_to_vj=document.getElementById("anonyminized");var a_to_vk=document.getElementById("found_links");if(a_to_vj)
{a_to_vj.innerHTML+=a_to_vb;}
if(a_to_vk)
{a_to_vk.innerHTML+=a_to_va;}}
function a_to_fa()
{var a_to_vf=new Array();protected_links=protected_links.replace(" ","");a_to_vf=protected_links.split(",");return a_to_vf;}
|
(function () {
'use strict';
angular.module('cd.app.platform')
.factory('PlatformService', PlatformService);
PlatformService.$inject = ['$http'];
function PlatformService ($http) {
var service = {
getPlatforms: getPlatforms
};
return service;
function getPlatforms () {
return $http.get('http://private-59658d-celulardireto2017.apiary-mock.com/plataformas')
.then(_onSuccess)
.catch(_onError);
function _onSuccess (response) {
return response.data.plataformas;
};
function _onError (error) {
return error;
};
};
};
})();
|
module.exports = {
BOARD_URL: 'https://www.reddit.com/api/place/board-bitmap',
BOARD_FILE: __dirname + '/tmp/board.bmp',
REMOTE_TARGET_URL: 'https://raw.githubusercontent.com/Zequez/reddit-placebot/master/images/target.png',
REMOTE_TARGET_FILE: __dirname + '/tmp/remote_target',
LOCAL_TARGET_FILE: __dirname + '/images/target.png',
DRAW_URL: 'https://www.reddit.com/api/place/draw.json',
// Use the REMOTE_TARGET_URL file as target, otherwise it's gonna just
// try to read from target.bmp
useRemoteTarget: false,
// Wait until these amount of accounts are available
// and paint pixels at the same time
bundleAccounts: 10,
// The PLACEBOT mark in the world <3
targetStartX: 981,
targetStartY: 784,
drawMode: 'RANDOM', // LEFTTOP | RANDOM
// Testing configuration things
// This is used for testing
useExistingBoardCache: false,
// Do not send the painting to the server so you don't waste your pixels
// while testing something else
mockPainting: false
}
|
'use strict';
/*jshint asi: true */
var test = require('tape')
var chunkRate = require('../')
, numbers = require('../test/fixtures/number-readable');
test('given a stream that emits numbers every 100 ms - total of 6, measuring rate per 200ms', function (t) {
var numbersStream = numbers({ to: 5, throttle: 100 })
var rates = chunkRate(numbersStream, { interval: 200 })
// throttle causes numbersStream to not emit anything for first 100ms
var expectedRates = [ 1, 2, 2, 1, 0 ].map(function (n) { return '' + n })
rates.on('data', check)
function check (rate) {
t.equal(rate.toString(), expectedRates.shift(), 'rate ' + rate)
if (!expectedRates.length) {
rates.removeAllListeners()
rates.endSoon()
t.end()
}
}
})
|
describe('boilerplateConstants factory', function () {
var service;
beforeEach(function () {
angular.mock.module('boilerplate');
inject(function ($injector) {
service = $injector.get('boilerplateConstants');
});
});
it('Should check the constant values to be defined', function () {
expect(service.jokesApi).toBeDefined();
expect(service.jokesCategoriesApi).toBeDefined();
expect(service.loginJokesApp).toBeDefined();
expect(service.none).toBeDefined();
});
});
|
var class_yeah_1_1_fw_1_1_http_1_1_exception_1_1_unsupported_media_type_http_exception =
[
[ "__construct", "class_yeah_1_1_fw_1_1_http_1_1_exception_1_1_unsupported_media_type_http_exception.html#a7d2fe9612ef241479a4c10151d580249", null ]
];
|
import { A } from '@ember/array';
import Route from '@ember/routing/route';
export default Route.extend({
model() {
return A(Array.from({ length: 10 }).map((_, index) => `Section ${index}`));
}
});
|
#!/bin/sh
':' //; exec "$(command -v nodejs || command -v node)" "$0" "$@"
var inject = function(callback) {
// Just make each a 1 property object for demonstration
var services = {
$timeout: {name: 'timeout'},
$window: {name: 'window'}
};
// Find the service names to inject
var functionString = callback + '';// Same as .toString()
functionString = functionString.replace(/ /g, '');
var lastPart = functionString.split('function(').slice(-1)[0];
var args = lastPart.split('){')[0].split(',');
// Send the right services in
var toSend = [];
args.forEach(function(serviceName) {
toSend.push(services[serviceName]);
});
callback.apply(this, toSend);
};
inject(function($timeout, $window) {
console.log($timeout.name);// 'timeout'
console.log($window.name);// 'window'
});
|
#!/bin/sh
':' //; exec "$(command -v nodejs || command -v node)" "$0" "$@"
// The data
var vehicles = [
{name: 'mx-5', type: 'car', parts: ['engine', '4wheels']},
{name: 'ninja', type: 'motorcyle', parts: ['engine', '2wheels']},
{name: 'enzo', type: 'car', parts: ['engine', '4wheels']}
];
// The where function
// Only need to check if the second appears in the first. This assumes
var equalOr2In1 = function(item1, item2) {
if (item1 === item2) {
return true;
} else if (typeof item1 === 'object' && typeof item2 === 'object') {
var allEqual = true;
for (var name in item2) {
allEqual = equalOr2In1(item1[name], item2[name]);
}
return allEqual;
}
return false;
}
var where = function(array, checkObj) {
var results = [];
array.forEach(function(obj) {
// No external libraries so no equals function
for (var name in checkObj) {
if (equalOr2In1(obj[name], checkObj[name])) {
results.push(obj);
}
}
});
return results;
};
// Various tests of it
console.log(where(vehicles, {type: 'other'}));
// []
console.log(where(vehicles, {type: 'car'}));
// [{name: 'enzo', type: 'car', ...}, {name: 'mx-5', type: 'car', ...}]
console.log(where(vehicles, {parts: ['engine', '2wheels']}));
// [{name: 'ninja', type: 'motorcycle', ...}];
console.log(where(vehicles, {parts: ['engine']}));
// [<all of the results>];
vehicles[2].type = {
property: 'value1'
}
console.log(where(vehicles, {type: {
property: 'value1'
}}));
// [{ name: 'enzo', ...}];
|
var webpack = require('webpack'),
config = require('./webpack.config.js');
config.plugins.concat([
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
]);
module.exports = config;
|
/* @requires
mapshaper-common
mapshaper-geojson
mapshaper-topojson
mapshaper-shapefile
mapshaper-json-table
*/
// Parse content of one or more input files and return a dataset
// @obj: file data, indexed by file type
// File data objects have two properties:
// content: Buffer, ArrayBuffer, String or Object
// filename: String or null
//
MapShaper.importContent = function(obj, opts) {
var dataset, content, fileFmt, data;
opts = opts || {};
if (obj.json) {
data = obj.json;
content = data.content;
if (utils.isString(content)) {
content = JSON.parse(content);
}
if (content.type == 'Topology') {
fileFmt = 'topojson';
dataset = MapShaper.importTopoJSON(content, opts);
} else if (content.type) {
fileFmt = 'geojson';
dataset = MapShaper.importGeoJSON(content, opts);
} else if (utils.isArray(content)) {
fileFmt = 'json';
dataset = MapShaper.importJSONTable(content, opts);
}
} else if (obj.text) {
fileFmt = 'dsv';
data = obj.text;
dataset = MapShaper.importDelim(data.content, opts);
} else if (obj.shp) {
fileFmt = 'shapefile';
data = obj.shp;
dataset = MapShaper.importShapefile(obj, opts);
} else if (obj.dbf) {
fileFmt = 'dbf';
data = obj.dbf;
dataset = MapShaper.importDbf(obj, opts);
}
if (!dataset) {
stop("Missing an expected input type");
}
// Convert to topological format, if needed
if (dataset.arcs && !opts.no_topology && fileFmt != 'topojson') {
T.start();
api.buildTopology(dataset);
T.stop("Process topology");
}
// Use file basename for layer name, except TopoJSON, which uses object names
if (fileFmt != 'topojson') {
MapShaper.setLayerName(dataset.layers[0], MapShaper.filenameToLayerName(data.filename || ''));
}
// Add input filename and format to the dataset's 'info' object
// (this is useful when exporting if format or name has not been specified.)
if (data.filename) {
dataset.info.input_files = [data.filename];
}
dataset.info.input_format = fileFmt;
return dataset;
};
// Deprecated (included for compatibility with older tests)
MapShaper.importFileContent = function(content, filename, opts) {
var type = MapShaper.guessInputType(filename, content),
input = {};
input[type] = {filename: filename, content: content};
return MapShaper.importContent(input, opts);
};
MapShaper.importShapefile = function(obj, opts) {
var shpSrc = obj.shp.content || obj.shp.filename, // content may be missing
dataset = MapShaper.importShp(shpSrc, opts),
lyr = dataset.layers[0],
dbf;
if (obj.dbf) {
dbf = MapShaper.importDbf(obj, opts);
utils.extend(dataset.info, dbf.info);
lyr.data = dbf.layers[0].data;
if (lyr.data.size() != lyr.shapes.length) {
message("[shp] Mismatched .dbf and .shp record count -- possible data loss.");
}
}
if (obj.prj) {
dataset.info.input_prj = obj.prj.content;
}
return dataset;
};
MapShaper.importDbf = function(input, opts) {
var table;
opts = utils.extend({}, opts);
if (input.cpg && !opts.encoding) {
opts.encoding = input.cpg.content;
}
table = MapShaper.importDbfTable(input.dbf.content, opts);
return {
info: {},
layers: [{data: table}]
};
};
MapShaper.filenameToLayerName = function(path) {
var name = 'layer1';
var obj = utils.parseLocalPath(path);
if (obj.basename && obj.extension) { // exclude paths like '/dev/stdin'
name = obj.basename;
}
return name;
};
// initialize layer name using filename
MapShaper.setLayerName = function(lyr, path) {
if (!lyr.name) {
lyr.name = utils.getFileBase(path);
}
};
|
import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
const styles = theme => ({
root: {
display: "flex",
width: "100%",
},
});
class Container extends Component {
render() {
const { children, classes, ...props } = this.props;
return (
<div className={classes.root} {...props}>
{children}
</div>
);
}
}
Container = withStyles(styles)(Container);
export { Container };
|
// This loads the environment variables from the .env file
require('dotenv-extended').load();
var restify = require('restify');
var builder = require('botbuilder');
var locationDialog = require('botbuilder-location');
var strava = require('strava-v3');
var bingAPI = require('./Common/bingAPI.js');
var polyline = require( 'google-polyline' );
var cardlib = require('microsoft-adaptivecards');
var adaptivecard = require('./Common/adaptivecards.js');
var GeoPoint = require('geopoint');
var recognizer = new builder.LuisRecognizer(process.env.LUIS_MODEL);
//var intents = new builder.IntentDialog({ recognizers: [recognizer]});
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
server.get(/\/public\/?.*/, restify.serveStatic({
'directory': __dirname,
'default': 'api_logo_pwrdBy_strava_horiz_light.png'
}));
// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
var bot = new builder.UniversalBot(connector);
bot.recognizer(recognizer);
var place;
// Listen for messages from users
server.post('/api/messages', connector.listen());
bot.library(locationDialog.createLibrary(process.env.BING_MAPS_API_KEY));
bot.dialog('/findroute', [
function (session, args, next) {
var minDistance, minDistance, maxDistance, activityType, activityCategory, difficulty, distance;
minDistance = builder.EntityRecognizer.findEntity(args.intent.entities, 'Distance.MinDistance'); // min max
maxDistance = builder.EntityRecognizer.findEntity(args.intent.entities, 'Distance.MaxDistance'); // min max
distance = builder.EntityRecognizer.findEntity(args.intent.entities, 'builtin.dimension'); // min max
activityType = builder.EntityRecognizer.findEntity(args.intent.entities, 'ActvityType'); // Run or Bike
difficulty = builder.EntityRecognizer.findEntity(args.intent.entities, 'ActivityCategory'); // Hills or Flat
//difficulty = builder.EntityRecognizer.findEntity(args.intent.entities, 'Difficulty');
var unit = null;
if (minDistance == undefined | !minDistance) {
minDistance = 0 // KM
} else {
minDistance = minDistance.entity;
}
if (maxDistance == undefined | !maxDistance) {
if (distance == undefined | !distance) {
maxDistance = 10 // KM
} else {
maxDistance = distance.resolution.value;
unit = distance.resolution.unit;
}
} else {
maxDistance = maxDistance.entity;
}
if (activityType == undefined | !activityType)
{
activityType = 'running';
} else {
switch (activityType.entity) {
case 'run':
activityType = 'running';
break;
case 'ride':
activityType = 'riding';
break;
default:
activityType = 'running';
}
}
if (difficulty == undefined | !difficulty)
{
difficulty = 'flat';
} else {
difficulty = difficulty.entity;
}
// Calc difficulty
var minCategoryClimb, maxCategoryClimb;
switch (difficulty) {
case 'flat':
minCategoryClimb = '1';
maxCategoryClimb = '2';
break;
case 'hilly':
minCategoryClimb = '3';
maxCategoryClimb = '5';
break;
default:
minCategoryClimb = '1';
maxCategoryClimb = '5';
}
var query = session.dialogData.query = {
'minDistance': minDistance,
'maxDistance': maxDistance,
'activityType': activityType,
'activityCategory': activityCategory,
'difficulty': difficulty,
'minCategoryClimb': minCategoryClimb,
'maxCategoryClimb': maxCategoryClimb,
'unit': unit
}
session.send(`Just a sec. I'll look for a ${activityType} based on your critieria`);
var place = session.userData.place;
if (!place)
{
session.beginDialog('/getlocation');
} else
{
next();
}
},
function (session, results) {
var place = session.userData.place;
if (!place) {
place = results.response;
session.userData.place = place;
};
let activityType = session.dialogData.query.activityType;
let maxDistance = session.dialogData.query.maxDistance;
let minCategoryClimb = session.dialogData.query.minCategoryClimb;
let maxCategoryClimb = session.dialogData.query.maxCategoryClimb;
// Calc bounding box
let center = new GeoPoint(parseFloat(place.geo.latitude), parseFloat(place.geo.longitude), false);
let boundingBox = center.boundingCoordinates(parseFloat(maxDistance), null, false);
let boxSize = 0.1;
var boundsStr = boundingBox[0]._degLat + ','
+ boundingBox[0]._degLon + ','
+ boundingBox[1]._degLat + ','
+ boundingBox[1]._degLon;
//var boundsStr = (parseFloat(place.geo.latitude)-boxSize)+','+(parseFloat(place.geo.longitude)-boxSize)+','+(parseFloat(place.geo.latitude)+boxSize)+','+(parseFloat(place.geo.longitude)+boxSize);
strava.segments.explore({'bounds':boundsStr, 'activity_type':activityType, 'min_cat':minCategoryClimb, 'max_cat':maxCategoryClimb},function(err,payload,limits) {
if(!err) {
console.log(payload);
handleSuccessResponse(session, payload);
session.endDialog();
}
else {
handleErrorResponse(session, err);
session.endDialog();
}
});
var formattedAddress =
session.send(`Ok I will look for these types of segments: \n${activityType}\nMinimum Category:${minCategoryClimb}\nMaximum Category:${maxCategoryClimb}`);
}
]).triggerAction({
matches: 'Route.Find',
intentThreshold: 0.8
});
bot.dialog("/newlocation", [
function (session,args) {
session.replaceDialog('/getlocation');
}
]).triggerAction({
matches: "Location"
});
bot.dialog("/", [
function (session) {
session.endDialog("I don't understand that. Can you ask again?");
}
]).triggerAction({
matches: 'None'
});
bot.dialog("/getlocation", [
function (session) {
var options = {
prompt: "I need to know where you are first.",
useNativeControl: true,
reverseGeocode: true,
skipFavorites: false,
skipConfirmationAsk: true
// requiredFields:
// locationDialog.LocationRequiredFields.streetAddress |
// locationDialog.LocationRequiredFields.locality |
// locationDialog.LocationRequiredFields.region |
// locationDialog.LocationRequiredFields.postalCode |
// locationDialog.LocationRequiredFields.country
};
locationDialog.getLocation(session, options);
},
function (session, results) {
if (results.response) {
session.userData.place = results.response;
}
session.endDialogWithResult(results.response);
}
]);
function getFormattedAddressFromPlace(place, separator) {
var addressParts = [place.streetAddress, place.locality, place.region, place.postalCode, place.country];
return addressParts.filter(i => i).join(separator);
}
//=========================================================
// Response Handling
//=========================================================
function handleSuccessResponse(session, payload) {
if ((payload)&&(payload.segments)&&(payload.segments.length>0)) {
console.log(payload);
//session.send('you are at '+place.geo.latitude+','+place.geo.longitude);
//session.send(payload.segments[0].name+' start location: '+payload.segments[0].start_latlng[0]+','+payload.segments[0].start_latlng[1]);
var place = session.userData.place;
var startpoint = [place.geo.latitude,place.geo.longitude];
var cards = [];
// only get 1 for now
var showlimit = payload.segments.length<=3 ? payload.segments.length : 3;
adaptivecard.clearSegments();
for (var i=0; i < showlimit; i++) {
var points = polyline.decode(payload.segments[i].points);
var waypoints = [];
waypoints.push(payload.segments[i].start_latlng);
var step = Math.floor(points.length / 10);
for (var j=0; j < points.length; j += step) {
waypoints.push(points[j]);
}
waypoints.push(payload.segments[i].end_latlng);
var locationUrl = bingAPI.getRouteImage(startpoint, startpoint, waypoints);
var bingUrl = bingAPI.getBingSiteRouteUrl(startpoint, startpoint, waypoints);
adaptivecard.addSegment(locationUrl, bingUrl, (i+1) + ". " + payload.segments[i].name);
}
var cardtemplate = adaptivecard.get();
var msg = new builder.Message(session);
msg.addAttachment({
'contentType': 'application/vnd.microsoft.card.adaptive',
'content': cardtemplate
});
session.send(msg);
}
else {
session.send('Couldn\'t find any segments near here');
}
}
function handleErrorResponse(session, error) {
session.send('Oops! Something went wrong. Try again later.');
console.error(error);
}
|
require("./100.js");
require("./201.js");
require("./403.js");
require("./806.js");
module.exports = 807;
|
'use strict';
define(function(require) {
var angular = require('angular');
var template = require('text!./selectUsers.tpl.html');
var SelectUsers = function(userService) {
return {
template: template,
restrict: 'E',
scope: {
selectedUsers: '=',
teacher: '=',
multiple: '=?',
onFinished: '&?',
onCanceled: '&?',
},
link: function(scope, element, attrs, controller) {
scope.showBack = attrs.onCanceled !== undefined;
scope.showNext = attrs.onFinished !== undefined;
},
controller: function($scope) {
$scope.newUser = {
name: 'New User'
};
$scope.users = userService.getUsers();
if ($scope.multiple === undefined) {
$scope.multiple = true;
}
$scope.$watch('selectedUsers', function(users) {
if (users !== $scope.selected) {
$scope.selected = users;
}
});
$scope.back = function() {
$scope.onCanceled();
};
$scope.next = function() {
$scope.selectedUsers = $scope.selected;
$scope.onFinished();
};
$scope.selectUser = function(user) {
if (!$scope.selected) {
$scope.selected = [];
}
if ($scope.multiple) {
for (var i = 0; i < $scope.selected.length; i++) {
if ($scope.selected[i] == user) {
$scope.selected.splice(i, 1);
return;
}
}
$scope.selected.push(user);
} else {
$scope.selected = [user];
}
};
$scope.isSelected = function(user) {
if ($scope.selected) {
for (var i = 0; i < $scope.selected.length; i++) {
if ($scope.selected[i] == user) {
return true;
}
}
}
return false;
};
$scope.addUser = function() {
userService.addUser(null, $scope.users);
};
}
};
};
return ['userService', SelectUsers];
});
|
var Cube = {
initPoly: function () {
Poly.vertices = [
[[0], [0], [0]], [[0], [0], [100]], [[0], [100], [0]], [[0], [100], [100]],
[[100], [0], [0]], [[100], [0], [100]], [[100], [100], [0]], [[100], [100], [100]] //cube
];
Poly.lines = [
[0, 1], [0, 2], [0, 4], [1, 3], [1, 5], [2, 3],
[3, 7], [4, 5], [4, 6], [5, 7], [6, 7], [6, 2] //cube
];
},
initCamera: function () {
Camera.location = [[-50], [-150], [500]];
},
screen: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0.0015, 0]],
particles: [],
projection: function () {
Projection.vertices = [];
for (var i = 0; i < Poly.vertices.length; i++) {
var transpose = Matrix.add(Poly.vertices[i], Camera.location);
transpose = Matrix.multiply(this.YrotationMatrix(), transpose);
transpose.push([1]);
transpose = Matrix.multiply(this.screen, transpose);
Projection.vertices.push([transpose[0][0] / transpose[3][0], transpose[1][0] / transpose[3][0]]);
}
},
YrotationMatrix: function () {
var theta = Math.PI - Camera.theta;
return [[Math.cos(theta), 0, Math.sin(theta)],
[0, 1, 0],
[-Math.sin(theta), 0, Math.cos(theta)]];
},
centerX: 0,
centerY: 0,
canvas: null,
ctx: null,
speed: 3,
initCanvas: function () {
this.ctx.fillStyle = "black";
this.ctx.fillRect(0, 0, canvas.width, canvas.height);
},
init: function () {
this.canvas = document.getElementById("canvas");
this.ctx = canvas.getContext("2d");
this.ctx.canvas.width = document.body.clientWidth;
this.ctx.canvas.height = document.body.clientHeight;
this.centerX = canvas.width / 2 - 200;
this.centerY = canvas.height / 2 - 100;
this.initCanvas();
this.initCamera();
this.initPoly();
},
drawLines: function () {
for (var i = 0; i < Poly.lines.length; i++) {
var p1 = Projection.vertices[Poly.lines[i][0]];
var p2 = Projection.vertices[Poly.lines[i][1]];
this.ctx.beginPath();
this.ctx.moveTo(p1[0] + this.centerX, p1[1] + this.centerY);
this.ctx.lineTo(p2[0] + this.centerX, p2[1] + this.centerY);
this.ctx.lineWidth = 3;
this.ctx.strokeStyle = "white";
//this.ctx.stroke();
}
for (var i = 0; i < Projection.vertices.length; i++) {
var p = {
x: Projection.vertices[i][0],
y: Projection.vertices[i][1],
age: 1
};
this.particles.push(p);
}
for (var i = 0; i < this.particles.length; i++) {
this.ctx.beginPath();
this.ctx.rect(this.particles[i].x + this.centerX, this.particles[i].y + this.centerY, 1, 1);
this.ctx.fillStyle = 'white';
this.ctx.fill();
this.particles[i].age += 1;
if (this.particles[i].age > 800) {
this.particles.splice(i, 1);
}
}
},
draw: function () {
Camera.location[1][0] += this.speed * Camera.direction;
if (Camera.location[1][0] > 150 || Camera.location[1][0] < -200) {
Camera.direction = Camera.direction * -1;
}
Camera.location[2][0] = 50 + 500 * Math.cos(Camera.theta);
Camera.location[0][0] = 50 + 500 * Math.sin(Camera.theta);
Camera.theta = (Camera.theta + 0.05) % (Math.PI * 2);
// if(Math.random() > 0.8) {
// //MUTATE!
// var index1 = Math.floor(Math.random()*(Poly.vertices.length));
// var index2 = Math.floor(Math.random()*3);
// Poly.vertices[index1][index2][0] += Math.random()*10;
// }
this.initCanvas();
this.projection();
this.drawLines();
}
}
Cube.init();
Animation.animate(Cube, Cube.canvas, Cube.ctx);
|
$(document).ready(function(){
$('#showPedirProd').click(function () {
$('#modal-peticiones').modal('show');
});
$('#newProd').click(function () {
agregarNuevoProd ();
});
$("#solicitar").click(function () {
solicitar($(this).data('usu'),$(this).data('url'));
});
$('.list-group-item').click(function (e) {
prod=$(this).data('idprod');
nombre=$(this).data('nombre');
unid=$(this).data('unid');
$('#formtag_cantidad').val('');
$('#formtag_unid').html(unid);
$('#formtag_nombre').html(nombre);
$('#formtag_nombre').data('idprod',prod);
return false;
});
// $('#prueba').click(function (e) {
// alert('borrar');
// // borrarProducto ($(this).data('id'));
// });
//------------------------------------//
// $('#contAddProd').hover(function () {
alertasPop (
'contAddProd',
"Haga click en el producto deseado para añadirlo.",
'right','hover','info large'
);
// });
//----------------------------------------------------//
});
//--------------FUNCIONES ------------//
var Tag = function (id_pro,nombre,cantidad,unidad) {
this.id_pro = id_pro;
this.nombre = nombre;
this.cantidad = cantidad;
this.unidad = unidad;
}
function agregarNuevoProd () {
id_pro=$('#formtag_nombre').data('idprod');
nombre=$('#formtag_nombre').html();
cantidad=$('#formtag_cantidad').val();
unidad=$('#formtag_unid').html();
if (nombre != undefined && nombre != "") {
if (cantidad!="" && id_pro!=undefined) {
if (!isNaN(cantidad)) {
cantidad=parseFloat(cantidad);
addTag(new Tag(id_pro,nombre,cantidad,unidad),'#tags');
$('#formtag_unid').html("");
$('#formtag_nombre').html("");
$('#formtag_cantidad').val('');
alertasPop ('formtag_cantidad',false,'bottom',false,'danger' );
} else{
alertasPop ('formtag_cantidad',"El valor introducido no es un número",'top',false,'danger' );
};
} else{
alertasPop ('formtag_cantidad',"Rellene este campo.",'top',false,'danger' );
};
}else{
alertasPop ('formtag_cantidad',"Haga click en un ingrediente del bloque derecho.",'top',false,'danger' );
}
}
function addTag (tag,id_tag) {
alertasPop ('solicitudes',false,'bottom',false,'danger' );
if(ifexistTag(tag.id_pro)){
$('.tag_cnt').each(function(key, element){
id_pro=$(this).data('idprod');
cant_prod=$(this).children('.cantidad').html();
if(tag.id_pro==id_pro){
cantidad=parseFloat(cant_prod) + parseFloat(tag.cantidad);
cantidad=Math.round(cantidad * 100) / 100;
// alert($(this).html()+" - Actual: " +cant_prod+" + "+tag.cantidad+" = "+cantidad);
$(this).data('cant',cantidad);
$('#tag_cnt_'+id_pro).html("<span class='cantidad'>"+cantidad+" </span>"+tag.unidad);
}
});
}else{
generateTag (tag,id_tag);
}
}
function ifexistTag (id) {
if ($('#tag_'+id).length) {
return true;
}else{
return false;
}
}
function generateTag (tag,id_tag) {
salida="<tr id='cnt_tag_"+tag.id_pro+"' class='content_tag'>";
salida+="<td id='tag_"+tag.id_pro+"' class='tag col-md-5' data-idprod='"+tag.id_pro+"' data-idunid='"+tag.unidad+"' data-cant='"+tag.cantidad+"'>"+tag.nombre+"</td>";
salida+="<td id='tag_cnt_"+tag.id_pro+"' class='tag_cnt col-md-3' data-idprod='"+tag.id_pro+"' > <span class='cantidad'> "+tag.cantidad+"</span> "+ tag.unidad+"</td>";
salida+="<td class='col-md-3'><div class='btn-group btn-group-sm'>";
salida+="<button id='btneditar_"+tag.id_pro+"' data-id='"+tag.id_pro+"' data-editable=false type='button' class='btn btn-primary complement-1-b' onclick='editarProducto ("+tag.id_pro+")'>";
salida+="<span class='glyphicon glyphicon-edit'></span></button>";
salida+="<button id='' type='button' class='btn btn-danger' onclick='borrarProducto ("+tag.id_pro+")'>";
salida+="<span class='glyphicon glyphicon-trash'></span></button>";
salida+="</div></td>";
salida+="</tr>";
$(id_tag).html($(id_tag).html()+salida);
}
function borrarProducto (id_pro) {
$('#cnt_tag_'+id_pro).remove();
}
function editarProducto (id_pro) {
button=$('#btneditar_'+id_pro);
if (button.data('editable')) {
// alert('editable');
nombre=$("#tag_"+id_pro).html();
unid=$("#tag_"+id_pro).data('idunid');
cant=$('.cantidad input').val();
if (cant !="" && !isNaN(cant)) {
$("#tag_cnt_"+id_pro).children(".cantidad").html(cant);
$("#tag_"+id_pro).data('cant',cant);
}else{
$("#tag_cnt_"+id_pro).children(".cantidad").html($("#tag_"+id_pro).data('cant'));
}
button.html("<span class='glyphicon glyphicon-edit'></span>");
button.removeClass('btn-success');
button.addClass('btn-primary complement-1-b');
button.data('editable',false);
}else{
// alert('no editable');
nombre=$("#tag_"+id_pro).html();
unid=$("#tag_"+id_pro).data('idunid');
cant=$("#tag_"+id_pro).data('cant');
$("#tag_cnt_"+id_pro).children(".cantidad").html("<input type='text' value='"+cant+"' class='col-md-2 editinput'>");
button.html("<span class='glyphicon glyphicon-ok'></span>");
button.removeClass('btn-primary complement-1-b');
button.addClass('btn-success');
button.data('editable',true);
}
}
function solicitar (id_usu,url) {
// alert(url);
solicitudes={};
if ($('.tag_cnt').length) {
$('.tag_cnt').each(function(key, element){
prod=$(this).data('idprod');
cantidad=$(this).children('.cantidad').text();
solicitudes[prod]=cantidad;
});
// for (prod in solicitudes) {
// alert(prod+" - "+solicitudes[prod]);
// };
$.ajax({
url: url,
type: 'POST',
async: true,
data: {'id_usuario':id_usu, 'ingr':solicitudes},
success: function (response) {
// alert(response);
location.reload();
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
// $('#response').html(jqXHR.responseText);
alert(jqXHR.responseText);
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
}else{
alertasPop ('solicitudes',"No ha introducido ningún ingrediente.",'bottom',false,'danger' );
}
}
function delSolc(id,element) {
url=element.data('url');
$.ajax({
url: url,
type: 'POST',
async: true,
data: {'idsolic':id,},
success: function (response) {
// alert(true);
if (response='true') {
location.reload();
};
}
});
}
function verProdSolc(id,element) {
url=element.data('url');
$.ajax({
url: url,
type: 'POST',
async: true,
data: {'idsolic':id,},
success: function (response) {
separadores=["||","&","="];
respProc=procResponse(response,separadores);
// alert(print_r(respProc,true));
for (var i = 0; i < respProc[0].length; i++) {
// alert(respProc[0][i][0]);
key=respProc[0][i][0];
value=respProc[0][i][1];
if(key!="foto"){
$("#info_prod ."+key).html(value);
}else{
img='<img class="img-rounded img-xs" src="/Gestor_de_cocina/web/'+value+'">';
$("#info_prod ."+key).html(img);
}
};
// $("#info_prod").show();
}
});
}
|
export const LABELS = {
kind: 'Kind',
interaction: 'Interaction',
serviceDelivery: 'Service delivery',
advisers: 'Adviser',
myInteractions: 'My interactions',
dateAfter: 'From',
dateBefore: 'To',
service: 'Service',
teams: 'Teams',
sector: 'Sector',
businessIntelligence: 'Business intelligence',
policyAreas: 'Policy area(s)',
policyIssueType: 'Policy issue type',
companyOneListGroupTier: 'Company One List Group Tier',
}
|
import { Redirect } from 'content/types'
export let mount = (field, onDone) => {
onDone(new Redirect({
url: 'https://github.com/jessepollak/command/wiki/Getting-started',
target: '_blank'
}))
}
export let match = "help"
export let icon = require("./Help.png")
|
// process.env.NODE_ENV = false;
const path = require('path');
const fs = require('grunt').file;
const chokidar = require('chokidar');
const _ = require('lodash');
const Stylus = require('stylus');
const CSSO = require('csso')
const chalk = require('chalk')
let DIST_DIR = path.join(process.cwd(), 'dist');
let STYL_DIR = path.join(process.cwd(), 'styl');
let CSS_DIR = path.join(DIST_DIR, 'css');
compileStyles('get-this-party-started.styl');
let files = [
path.join(STYL_DIR, '/**/*.styl')
];
chokidar
.watch(files, {ignored: /(^|[\/\\])\../})
.on('change', (filepath, filemeta) => {
compileStyles(filepath);
})
;
process.env.FILE_SERVER_PATH = './';
process.env.FILE_SERVER_PORT = 8080;
console.log(`Starting node fileserver at http://localhost:${process.env.FILE_SERVER_PORT}`);
require('node-file-server');
function compileStyles(filepath) {
// skip no stylus files
if (!filepath.match && !filepath.match(/\.styl$/)) { return; }
let styles = fs.expand({ filter: 'isFile' }, [
path.join(STYL_DIR, '**/*')
, "!"+path.join(STYL_DIR, '**/_*')
]);
_.each(styles, function(style) {
let filename = path.basename(style)
.replace(/\s+/, '-')
.toLowerCase()
;
let newStyle = path.join(DIST_DIR, filename.replace(/\.[\w\d]+/, ''));
let content = fs.read(style);
Stylus(content)
.set('filename', style)
.set('paths', [ STYL_DIR ])
// .set('linenos', process.env.NODE_ENV ? false : true)
// .set('compress', process.env.NODE_ENV ? true : false)
.render(function(err, css) {
if (err) {
console.error(chalk.red(err));
return;
}
// POST PROCESS CSS A BIT
css = css
.replace(/#__ROOT__/gi, ':root')
.replace(/PP__/gi, '--')
;
// Write unminified styles to disk
fs.write(`${newStyle}.css`, css);
let csso_opts = {
debug: process.env.NODE_ENV ? false : true
// , c: process.env.NODE_ENV ? true : false
};
css = CSSO.minify(css, csso_opts).css;
// console.log(css);
fs.write(`${newStyle}.min.css`, css);
console.log(chalk.green(`> Compiled ${style}`));
})
;
});
}
|
if (this.importScripts) {
importScripts('../../../resources/js-test.js');
importScripts('shared.js');
}
description("Test that a database is recreated correctly when an open-with-version call is queued behind both a deleteDatabase and an open-with-version call");
indexedDBTest(prepareDatabase, connection1Success);
function prepareDatabase(evt)
{
preamble(evt);
evalAndLog("db = event.target.result");
}
function connection1Success(evt)
{
preamble(evt);
evalAndLog("connection1 = event.target.result");
shouldBe("db", "connection1");
evalAndLog("connection1.onversionchange = connection1VersionChangeCallback");
evalAndLog("request = indexedDB.open(dbname, 2)");
evalAndLog("request.onsuccess = connection2Success");
evalAndLog("request.onupgradeneeded = connection2UpgradeNeeded");
evalAndLog("request.onblocked = connection2Blocked");
request.onerror = unexpectedErrorCallback;
}
function connection1VersionChangeCallback(evt)
{
preamble(evt);
shouldBeEqualToString("event.type", "versionchange");
shouldBe("event.oldVersion", "1");
shouldBe("event.newVersion", "2");
}
function connection2Blocked(evt)
{
preamble(evt);
evalAndLog("request = indexedDB.deleteDatabase(dbname)");
evalAndLog("request.onblocked = deleteDatabaseBlockedCallback");
evalAndLog("request.onsuccess = deleteDatabaseSuccessCallback");
request.onerror = unexpectedErrorCallback;
evalAndLog("request = indexedDB.open(dbname, 3)");
evalAndLog("request.onupgradeneeded = connection3UpgradeNeeded");
evalAndLog("request.onsuccess = connection3Success");
request.onerror = unexpectedErrorCallback;
evalAndLog("connection1.close()");
}
function deleteDatabaseBlockedCallback(evt)
{
preamble(evt);
shouldBe("event.oldVersion", "1");
shouldBeNull("event.newVersion");
}
function deleteDatabaseSuccessCallback(evt)
{
preamble(evt);
shouldBeUndefined("event.target.result");
shouldBeEqualToString("event.type", "success");
}
function connection2UpgradeNeeded(evt)
{
preamble(evt);
shouldBe("event.oldVersion", "1");
shouldBe("event.newVersion", "2");
evalAndLog("db = event.target.result");
shouldBe("db.objectStoreNames.length", "0");
evalAndLog("db.createObjectStore('some object store')");
evalAndLog("transaction = event.target.transaction");
evalAndLog("transaction.oncomplete = connection2TransactionComplete");
}
function connection2Success(evt)
{
preamble(evt);
evalAndLog("connection2 = event.target.result");
connection2.onversionchange = unexpectedVersionChangeCallback;
evalAndLog("connection2.close()");
}
function connection2TransactionComplete(evt)
{
preamble(evt);
shouldBe("db.version", "2");
}
var gotUpgradeNeededEvent = false;
function connection3UpgradeNeeded(evt)
{
preamble(evt);
evalAndLog("gotUpgradeNeededEvent = true");
shouldBe("event.newVersion", "3");
shouldBe("event.oldVersion", "0");
}
function connection3Success(evt)
{
preamble(evt);
shouldBeTrue("gotUpgradeNeededEvent");
shouldBe("event.target.result.objectStoreNames.length", "0");
finishJSTest();
}
|
var path = require('path');
var webpack = require('webpack');
var banner = require('./webpack.banner');
var TARGET = process.env.TARGET || null;
var externals = {
'react': {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom'
}
};
var config = {
entry: {
index: './src/react-aria.js'
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: 'dist/',
filename: 'react-aria.js',
sourceMapFilename: 'react-aria.sourcemap.js',
library: 'ReactARIA',
libraryTarget: 'umd'
},
module: {
loaders: [
{ test: /\.(js|jsx)/, loader: 'babel-loader' },
]
},
plugins: [
new webpack.BannerPlugin(banner)
],
resolve: {
extensions: ['', '.js', '.jsx']
},
externals: externals
};
if (TARGET === 'minify') {
config.output.filename = 'react-aria.min.js';
config.output.sourceMapFilename = 'react-aria.min.js';
config.plugins.push(new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
mangle: {
except: ['React', 'ReactARIA']
}
}));
}
module.exports = config;
|
export default function validatePassword(password) {
if (!password) {
return {
isValid: false,
error: "Passwords must contain four words and be at least 15 characters",
};
}
if (!password.match(/.+\s.+\s.+\s.+/)) {
return {
isValid: false,
error: "Passwords must contain four words, separated by spaces",
};
}
if (password.length <= 15) {
return {
isValid: false,
error: "Passwords must contain at least 15 characters",
};
}
return {
isValid: true,
error: "",
};
}
|
import React, { PropTypes } from 'react';
import '../styles/core.scss';
const propTypes = {
children: PropTypes.element,
};
function SimpleContainer(props) {
return (
<div>{props.children}</div>
);
}
SimpleContainer.propTypes = propTypes;
export default SimpleContainer;
|
var Log = require('./../../utils/Log.js');
var util = require('util');
var QueueProcessor = require('./../QueueProcessor');
var OAuth= require('oauth').OAuth;
var https = require('https');
/**
* InsufficientMetadataRemovalController
* @constructor
*/
function InsufficientMetadataRemovalController() {
var self = this;
/** refined asset list */
this._assets = [];
/**
* process
*/
this.process = function (data, callback) {
self.callback = callback;
self.config = data;
Log.prototype.log(InsufficientMetadataRemovalController.prototype.className, InsufficientMetadataRemovalController.prototype.classDescription + " Process");
this.queueProcessor = new QueueProcessor(this.onComplete, this.onProcessItem );
this.queueProcessor.process(data.assetslist);
}
/**
* on queue complete
*/
this.onComplete = function() {
Log.prototype.log(InsufficientMetadataRemovalController.prototype.className, InsufficientMetadataRemovalController.prototype.classDescription + " Complete");
self.callback.apply(self, [ [
{file: self.config.output, data: JSON.stringify(self._assets, null, '\t')},
{file: self.config.removalListFile, data: JSON.stringify(self.config.removalList, null, '\t')}] ]);
}
/**
* on process item
*/
this.onProcessItem = function(item) {
var hasGoodMetadata = true;
if (item.artist == undefined || item.artist == null) {
hasGoodMetadata = false;
}
if (item.title == undefined || item.title == null) {
hasGoodMetadata = false;
}
if (hasGoodMetadata) {
self._assets.push(item);
} else {
self.config.removalList.push({ media: item.media, reason: "insufficient metadata"});
Log.prototype.log(InsufficientMetadataRemovalController.prototype.className, InsufficientMetadataRemovalController.prototype.classDescription + "Remove asset: " + item.label + " with artist: " + item.artist + " and title: " + item.title );
}
self.queueProcessor.next();
}
}
InsufficientMetadataRemovalController.prototype.className = "InsufficientMetadataRemovalController";
InsufficientMetadataRemovalController.prototype.classDescription = "Insufficient Metadata Asset Removal Complete";
exports = module.exports = InsufficientMetadataRemovalController;
|
module.exports = function(models, bot) {
return {
getJSON: function(req, res) {
res.json(Object.keys(bot.getPlugins()));
}
}
};
|
var sqleye = require ('./sqleye')
// *************** Our Parent & Child Bullseye object *************//
var beye = new sqleye( {pname: 'text', ppin: 'integer', pcode: 'text', pfname: 'text', pemail: 'text'},
[ 'pname', 'ppin' ],
'sqllite', 'client' )
var ceye = new sqleye( {cname: 'text', istatus: 'integer'},
[ 'cname' ],
'sqllite', 'test')
function test_register(obj) {
if (beye.search('pname', obj.pname)) {
console.log ('parent registration failed: Duplicate')
} else {
switch (beye.insert(obj)) {
case 1: console.log ('test_register: success'); break;
case -2: console.log('parent registartion failed: Key field is not present'); break;
}
}
}
var obj = { pname:'tnoel', ppin:1234, pcode:'system1000', pfname:'Timothy Noel', pemail:'tnoelhere@gmail.com' }
test_register(obj)
test_register(obj)
var obj = { pname:'tl', ppin:1234, pcode:'system1000', pfname:'Timothy Noel', pemail:'tnoelhere@gmail.com' }
test_register(obj)
var d = beye.query (['tnoel', 1234])
if (d) { console.log ("Found query result for tnoel 1234 ") }
|
var should = require('should');
var getAnalysis= require('../src/interfaceToBunte').getAnalysis;
describe('Bunte API', function () {
it('should return data from Bunte', function (next) {
getAnalysis(function(error, response) {
next();
return; // requires Bunte Api to be up and running
JSON.stringify(response).should.containEql("articleArray");
next()
}) ;
});
});
|
import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: ['overflowHidden:overflow-hidden'],
classNames: ['skills'],
tagName: 'ul',
sortByTitle: ['title:asc'],
userSkillsService: Ember.inject.service('user-skills'),
alphaSkills: Ember.computed.sort('skills', 'sortByTitle'),
skillsNotInCommon: Ember.computed.setDiff('skillsToFilter', 'skillsInCommon'),
sortedSkills: Ember.computed.union('skillsInCommon', 'skillsNotInCommon'),
userSkills: Ember.computed.alias('userSkillsService.userSkills'),
skillsInCommon: Ember.computed.filter('skillsToFilter', function(skill) {
let userSkillsService = Ember.get(this, 'userSkillsService');
if (userSkillsService) {
let hasSkill = userSkillsService.hasSkill(skill);
if (hasSkill) { return skill; }
}
}),
skillsToFilter: Ember.computed('alphaSkills', 'userSkills', function() {
return Ember.get(this, 'alphaSkills');
}),
actions: {
skillItemHidden() {
this.sendAction('skillItemHidden');
},
}
});
|
/**
* Created by Wayne on 15/7/9.
*/
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
timestamps = require('mongoose-timestamp');
module.exports = function (appDb) {
var OrderOptionSchema = new Schema({
//强制进场
must_entrance: {
type: Boolean,
default: false
},
//强制进场拍照
must_entrance_photo: {
type: Boolean,
default: false
},
//进场拍照要求
entrance_photos: {
type: [Schema.Types.Mixed]
},
//操作必须拍照
must_take_photo: {
type: Boolean,
default: false
},
//拍照要求
take_photos: {
type: [Schema.Types.Mixed]
},
//强制货物明细确认
must_confirm_detail: {
type: Boolean,
default: false
}
});
OrderOptionSchema.plugin(timestamps, {
createdAt: 'created',
updatedAt: 'updated'
});
appDb.model('OrderOption', OrderOptionSchema);
var PushOptionSchema = new Schema({
abnormal_push: {
type: Boolean,
default: false
},
pickup_push: {
type: Boolean,
default: false
},
delivery_push: {
type: Boolean,
default: false
},
//提货迟到时长,超过次时长会推送异常
pickup_deferred_duration: {
type: Number
},
//交货提前推送时长,提前多长时间会推送给收货人
delivery_early_duration: {
type: Number
}
});
PushOptionSchema.plugin(timestamps, {
createdAt: 'created',
updatedAt: 'updated'
});
appDb.model('PushOption', PushOptionSchema);
// 后台管理员对公司的配置
var AdminOptionSchema = new Schema({
send_salesman_sms: { // 是否给公司的运单关注人发送短信通知
type: Boolean,
default: false
}
});
AdminOptionSchema.plugin(timestamps, {
createdAt: 'created',
updatedAt: 'updated'
});
appDb.model('AdminOption', AdminOptionSchema);
//与公司相关的配置
var CompanyConfigurationSchema = new Schema({
object: {
type: String,
default: 'CompanyConfiguration'
},
company: {
type: Schema.Types.ObjectId,
ref: 'Company',
required: true
},
update_id: {
type: Schema.Types.ObjectId
},
pickup_option: {
type: Schema.Types.Mixed
},
delivery_option: {
type: Schema.Types.Mixed
},
push_option: {
type: Schema.Types.Mixed
},
admin_option: {
type: Schema.Types.Mixed
}
});
CompanyConfigurationSchema.plugin(timestamps, {
createdAt: 'created',
updatedAt: 'updated'
});
appDb.model('CompanyConfiguration', CompanyConfigurationSchema);
};
|
exports.padLeft = function () {
return function (input, length, using, options) {
options = arguments[arguments.length - 1];
switch (arguments.length) {
case 1:
if (!options.fn) {
throw new Error('Handlebars Helper "padLeft" needs 2 parameters minimum');
} else {
input = options.fn(this);
length = options.hash && options.hash.size || 0;
using = options.hash && options.hash.using || ' ';
}
break;
case 2:
length = options.hash && options.hash.size || 0;
using = options.hash && options.hash.using || ' ';
break;
case 3:
using = options.hash && options.hash.using || ' ';
break;
}
//make sure we've got a string
input = ''+input;
if (length < input.length) {
return input;
}
return input + new Array(length - input.length + 1).join(using);
};
};
|
{
"metadata" :
{
"formatVersion" : 3,
"generatedBy" : "Blender 2.60 Exporter",
"vertices" : 20,
"faces" : 18,
"normals" : 14,
"colors" : 0,
"uvs" : 0,
"materials" : 1,
"morphTargets" : 0
},
"scale" : 1.000000,
"materials": [ {
"DbgColor" : 15658734,
"DbgIndex" : 0,
"DbgName" : "default",
"vertexColors" : false
}],
"vertices": [1.000000,-1.000000,-2.000000,1.000000,-1.000000,2.000000,-1.000000,-1.000000,2.000000,-1.000000,-1.000000,-2.000000,1.000000,1.000000,-2.000000,0.999999,1.000000,2.000000,-1.000000,1.000000,2.000000,-1.000000,1.000000,-2.000000,1.000000,3.000000,-2.000000,-1.000000,3.000000,-2.000000,-1.000000,3.000000,2.000000,0.999999,3.000000,2.000000,-1.000000,-3.000000,2.000000,-1.000000,-3.000000,-2.000000,1.000000,-3.000000,-2.000000,1.000000,-3.000000,2.000000,-1.000001,-1.000000,4.000000,-1.000001,1.000000,4.000000,0.999999,-1.000000,4.000000,0.999999,1.000000,4.000000],
"morphTargets": [],
"normals": [0.707083,0.000000,-0.707083,0.904508,0.301492,0.301492,0.904508,-0.301492,0.301492,-0.904508,-0.301492,0.301492,-0.904508,0.301492,0.301492,-0.707083,0.000000,-0.707083,-0.577349,0.577349,-0.577349,0.577349,0.577349,-0.577349,-0.577349,0.577349,0.577349,0.577349,0.577349,0.577349,-0.577349,-0.577349,-0.577349,-0.577349,-0.577349,0.577349,0.577349,-0.577349,-0.577349,0.577349,-0.577349,0.577349],
"colors": [],
"uvs": [[]],
"faces": [35,0,4,5,1,0,0,0,1,2,35,2,6,7,3,0,3,4,5,5,35,4,0,3,7,0,0,0,5,5,35,4,7,9,8,0,0,5,6,7,35,7,6,10,9,0,5,4,8,6,35,6,5,11,10,0,4,1,9,8,35,5,4,8,11,0,1,0,7,9,35,8,9,10,11,0,7,6,8,9,35,2,3,13,12,0,3,5,10,11,35,3,0,14,13,0,5,0,12,10,35,0,1,15,14,0,0,2,13,12,35,1,2,12,15,0,2,3,11,13,35,14,15,12,13,0,12,13,11,10,35,6,2,16,17,0,4,3,11,8,35,1,5,19,18,0,2,1,9,13,35,5,6,17,19,0,1,4,8,9,35,2,1,18,16,0,3,2,13,11,35,18,19,17,16,0,13,9,8,11]
}
|
var test = require('tape')
var cg = require('../')()
test('hex/rbg linear end-to-end', function (t) {
t.plan(2)
var ops = {
"nshades": 3
}
var hex = cg.colorgrad('#0000FF', '#FFFFFF', ops)
var rgb = cg.colorgrad([60,60,60], [120,120,120], ops)
var expectedhex = [ '#0000ff', '#8080ff', '#ffffff' ]
var expectedrgb = [ [ 60, 60, 60 ], [ 90, 90, 90 ], [ 120, 120, 120 ] ]
t.same(hex, expectedhex, "hex point-to-point")
t.same(rgb, expectedrgb, "rgb point-to-point")
t.end()
})
test('hex/rgb linear end-to-lum', function (t) {
t.plan(2)
var ops = {
"lum": -2
, "nshades": 4
}
var hex = cg.colorgrad("#808080", ops)
var expectedhex = [ '#808080', '#2b2b2b', '#000000', '#000000' ]
ops = {
"lum": 2
, "nshades": 4
}
var rgb = cg.colorgrad([128, 128, 128], ops)
var expectedrgb = [ [ 128, 128, 128 ],
[ 213, 213, 213 ],
[ 255, 255, 255 ],
[ 255, 255, 255 ] ]
t.same(hex, expectedhex, "hex point-to-lum increase")
t.same(rgb, expectedrgb, "rgb point-to-lum increase")
t.end()
})
|
import React from 'react';
import AppManagementPanel from './AppManagementPanel';
import Panel from '../Panel';
import { mount, shallow } from 'enzyme';
describe('(Component) AppManagementPanel', () => {
it('Shallow renders a Panel', () => {
const _component = shallow(<AppManagementPanel />);
expect(_component.type()).to.equal(Panel);
});
it('Renders an AppManagementPanel', () => {
const _component = mount(<AppManagementPanel />);
expect(_component.type()).to.equal(AppManagementPanel);
});
});
|
import enumerate from './generators/enumerate';
/**
* Returns the first value in a collection matched by the match function.
*
* @param collection - The collection to search through.
* @param match - The match function.
* @param from - Key to start searching.
* @param to - Key (exclusive) to stop searching.
*
* @returns The found value or undefined otherwise.
*/
export default function find(collection, match, from, to) {
for (const [key, value] of enumerate(collection, from, to)) {
if (match(value, key, collection)) {
return value;
}
}
}
//# sourceMappingURL=find.js.map
|
MSG.title = "Webduino Blockly Chapter 1-1 : Lighting up an LED";
MSG.subTitle = "Chapter 1-1 : Lighting up an LED";
MSG.demoDescription = "Set up the stack to light up an LED and the bulb in image.";
|
'use strict';
const Immutable = require('immutable');
const validateValuesMap = (valuesMap) => {
const filteredValues = valuesMap.filter((value) => typeof value !== 'undefined');
const net = filteredValues.get('net');
const gross = filteredValues.get('gross');
const vat = filteredValues.get('vat');
const vatPercentage = filteredValues.get('vatPercentage');
const tolerance = 0.01;
switch (filteredValues.size) {
case 3:
return (Math.abs(net - (gross - vat)) < tolerance) || (Math.abs(vat - (gross - gross * (1 - vatPercentage))) < tolerance);
case 4:
return (Math.abs(net - (gross - vat)) < tolerance) && (Math.abs(vat - (gross - gross * (1 - vatPercentage))) < tolerance);
default:
// if size <= 2
return true;
}
};
const validators = Immutable.fromJS([
{
condition: (line, validateValuesMap) => (line.has('amount') ? validateValuesMap(line.get('amount')) : true),
msg: 'amount is inconsistent'
},
{
condition: (line, validateValuesMap) => {
if (!line.has('expectedAmount')) {
return true;
}
const expectedAmount = line.get('expectedAmount');
const net = expectedAmount.get('net');
const gross = expectedAmount.get('gross');
const vat = expectedAmount.get('vat');
const vatPercentage = expectedAmount.get('vatPercentage');
return [0, 1].every((index) => {
const columnValues = Immutable.Map(
{
net: Immutable.List.isList(net) ? net.get(index) : net,
gross: Immutable.List.isList(gross) ? gross.get(index) : gross,
vat: Immutable.List.isList(vat) ? vat.get(index) : vat,
vatPercentage: Immutable.List.isList(vatPercentage) ? vatPercentage.get(index) : vatPercentage
}
);
return validateValuesMap(columnValues);
});
},
msg: 'expectedAmount is inconsistent'
}
]);
const validateLine = (line, validators, validateValuesMap) => {
return validators.reduce((errors, validator) => {
const error = Immutable.Map(
{
lineId: line.get('id') || 'UNKNOWN_LINE_ID',
mergedFrom: line.get('mergedFrom'),
msg: validator.get('msg')
}
);
return !validator.get('condition')(line, validateValuesMap) ? errors.push(error) : errors;
},
Immutable.List()
);
};
const validateLines = (cff, validateLine, validators, validateValuesMap) => {
const errors = cff.get('lines').reduce(
(errors, line) => errors.concat(validateLine(line, validators, validateValuesMap)),
Immutable.List()
);
return errors.size > 0 ? Immutable.Map({errors: errors}) : Immutable.Map();
};
const validateCFFConsistency = (cff) => validateLines(cff, validateLine, validators, validateValuesMap);
module.exports = validateCFFConsistency;
|
import React from 'react';
import { bindActionCreators } from 'redux';
import { Counter } from 'routes/Counter/components/Counter';
import { shallow } from 'enzyme';
describe('(Component) Counter', () => {
let _props, _spies, _wrapper;
beforeEach(() => {
_spies = {};
_props = {
counter : 5,
...bindActionCreators({
doubleAsync : (_spies.doubleAsync = sinon.spy()),
increment : (_spies.increment = sinon.spy())
}, _spies.dispatch = sinon.spy())
};
_wrapper = shallow(<Counter {..._props} />);
});
it('Should render as a <div>.', () => {
expect(_wrapper.is('div')).to.equal(true);
});
it('Should render with an <h2> that includes Sample Counter text.', () => {
expect(_wrapper.find('h2').text()).to.match(/Counter:/);
});
it('Should render props.counter at the end of the sample counter <h2>.', () => {
expect(_wrapper.find('h2').text()).to.match(/5$/);
_wrapper.setProps({ counter: 8 });
expect(_wrapper.find('h2').text()).to.match(/8$/);
});
it('Should render exactly two buttons.', () => {
expect(_wrapper.find('button')).to.have.length(2);
});
describe('An increment button...', () => {
let _button;
beforeEach(() => {
_button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment');
});
it('has bootstrap classes', () => {
expect(_button.hasClass('btn btn-default')).to.be.true;
});
it('Should dispatch a `increment` action when clicked', () => {
_spies.dispatch.should.have.not.been.called;
_button.simulate('click');
_spies.dispatch.should.have.been.called;
_spies.increment.should.have.been.called;
});
});
describe('A Double (Async) button...', () => {
let _button;
beforeEach(() => {
_button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)');
});
it('has bootstrap classes', () => {
expect(_button.hasClass('btn btn-default')).to.be.true;
});
it('Should dispatch a `doubleAsync` action when clicked', () => {
_spies.dispatch.should.have.not.been.called;
_button.simulate('click');
_spies.dispatch.should.have.been.called;
_spies.doubleAsync.should.have.been.called;
});
});
});
|
{
if (e && typeof e.stack === "string") {
e.stack = e.stack
.split("\n")
.map(function(line) {
return rewriteTraceLine(line, mapConsumers);
})
.join("\n");
}
}
|
Oskari.registerLocalization({
"lang": "fi",
"key": "GenericAdmin",
"value": {
"title": "Ylläpito",
"desc": "",
"tile": {
"title": "Ylläpito"
},
"flyout": {
"title": "Ylläpito",
"defaultviews" : {
"title" : "Oletusnäkymät",
"desc" : "Valitse haluamasi karttatasot, kartan sijainti ja mittakaavataso. Tallenna oletusnäkymä klikkaamalla 'Aseta'",
"headerName" : "Oletusnäkymä",
"globalViewTitle" : '*Järjestelmän oletusnäkymä*',
"setButton" : "Aseta",
"forceButton" : "Päivitä silti",
"notifications" : {
"errorTitle" : "Virhe",
"warningTitle" : "Varoitus",
"successTitle" : "Tallennettu",
"errorLoadingFailed" : "Oletusnäkymien lataaminen epäonnistui",
"errorUpdating" : "Oletusnäkymän (id=${id}) päivittäminen epäonnistui.",
"listTitle" : "Guest-käyttäjällä ei ole oikeuksia näihin tasoihin:",
"viewUpdated" : "Oletusnäkymä (id=${id}) päivitetty"
}
}
}
}
});
|
import {expect} from 'chai'
import path from 'path'
import fse from 'fs-extra'
import _ from 'lodash'
import * as utils from '../../dist/generators/utils'
describe('removeWholeLine', function () {
it('removes the whole line on which the given string appears', function () {
let line = '{\n User,\n Posts,\n Comments}'
let result = utils.removeWholeLine(line, 'User')
expect(result).to.equal('{\n Posts,\n Comments}')
})
it('removes the whole line on which the given regex matches', function () {
let line = '{\n User,\n Posts,\n Comments}'
let result = utils.removeWholeLine(line, /[a-zA-Z]{5}/g)
expect(result).to.equal('{\n User,\n Comments}')
})
})
describe('removeFromIndexFile', function () {
let dummyPath = path.resolve(__dirname, '../../tmp/removeFromIndexFile.js')
afterEach(function () {
// Cleanup
fse.removeSync(dummyPath)
})
it('removes import/export lines - capitalizeVarName', function () {
// Setup
fse.outputFileSync(
dummyPath,
`
import Comments from './comments';
import Users from './users';
import Posts from './posts';
export {
Commnets,
Users,
Posts
};
`
)
utils.removeFromIndexFile(dummyPath, 'users', {capitalizeVarName: true})
let result = fse.readFileSync(dummyPath, {encoding: 'utf-8'})
expect(result).to.equal(`
import Comments from './comments';
import Posts from './posts';
export {
Commnets,
Posts
};
`)
})
it('removes import/export lines', function () {
// Setup
fse.outputFileSync(
dummyPath,
`
import comments from './comments';
import users from './users';
export default function () {
comments();
users();
}
`
)
utils.removeFromIndexFile(dummyPath, 'users', {capitalizeVarName: false})
let result = fse.readFileSync(dummyPath, {encoding: 'utf-8'})
expect(result).to.equal(`
import comments from './comments';
export default function () {
comments();
}
`)
})
})
describe('getOutputPath', function () {
const customConfig = {}
it('returns a correct output path for container', function () {
let result = utils.getOutputPath(
customConfig,
'container',
'user_list',
'core'
)
expect(result).to.equal('./client/modules/core/containers/user_list.js')
})
it('returns a correct output path for component', function () {
let result = utils.getOutputPath(
customConfig,
'component',
'user_list',
'core'
)
expect(result).to.equal('./client/modules/core/components/user_list.jsx')
})
it('returns a correct output path for a storybook', function () {
let result = utils.getOutputPath(
customConfig,
'storybook',
'user_list',
'core'
)
expect(result).to.equal(
'./client/modules/core/components/.stories/user_list.js'
)
})
describe('with custom modules path', function () {
const customConfig = {modulesPath: 'foo/bar/mantra/modules'}
it('returns a correct output path for container', function () {
let result = utils.getOutputPath(
customConfig,
'container',
'user_list',
'core'
)
expect(result).to.equal(
'./foo/bar/mantra/modules/core/containers/user_list.js'
)
})
it('returns a correct output path for component', function () {
let result = utils.getOutputPath(
customConfig,
'component',
'user_list',
'core'
)
expect(result).to.equal(
'./foo/bar/mantra/modules/core/components/user_list.jsx'
)
})
it('returns a correct output path for a storybook', function () {
let result = utils.getOutputPath(
customConfig,
'storybook',
'user_list',
'core'
)
expect(result).to.equal(
'./foo/bar/mantra/modules/core/components/.stories/user_list.js'
)
})
})
})
describe('getTemplateVariables', function () {
describe('for components', function () {
let expected = {
componentName: 'UserList',
moduleName: 'core'
}
it('gets template variables - variation 1', function () {
let result = utils.getTemplateVariables('component', 'core', 'userList')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets template variables - variation 2', function () {
let result = utils.getTemplateVariables('component', 'core', 'user_list')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets template variables - variation 3', function () {
let result = utils.getTemplateVariables('component', 'core', 'UserList')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
})
describe('for storybook', function () {
let expected = {
moduleName: 'core',
componentName: 'UserList',
componentFileName: 'user_list'
}
it('gets template variables - variation 1', function () {
let result = utils.getTemplateVariables('storybook', 'core', 'userList')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets template variables - variation 2', function () {
let result = utils.getTemplateVariables('storybook', 'core', 'user_list')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets template variables - variation 3', function () {
let result = utils.getTemplateVariables('storybook', 'core', 'UserList')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
})
describe('for containers', function () {
let expected = {
componentName: 'UserList',
componentFileName: 'user_list',
moduleName: 'core'
}
it('gets template variables - variation 1', function () {
let result = utils.getTemplateVariables('container', 'core', 'userList')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets template variables - variation 2', function () {
let result = utils.getTemplateVariables('container', 'core', 'user_list')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets template variables - variation 3', function () {
let result = utils.getTemplateVariables('container', 'core', 'UserList')
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
})
describe('for collections', function () {
let expected = {
collectionName: 'PullRequests',
collectionFileName: 'pull_requests'
}
it('gets template variables - variation 1', function () {
let result = utils.getTemplateVariables(
'collection',
null,
'pullRequests'
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets template variables - variation 2', function () {
let result = utils.getTemplateVariables(
'collection',
null,
'pull_requests'
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets template variables - variation 3', function () {
let result = utils.getTemplateVariables(
'collection',
null,
'PullRequests'
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets templates variables with collection2 option', function () {
let result = utils.getTemplateVariables(
'collection',
null,
'PullRequests',
{schema: 'collection2'}
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('gets templates variables with astronomy option', function () {
let result = utils.getTemplateVariables(
'collection',
null,
'PullRequests',
{schema: 'astronomy'}
)
let matched = _.isEqual(result, {
collectionName: 'PullRequests',
collectionFileName: 'pull_requests',
className: 'PullRequest'
})
expect(matched).to.equal(true)
})
})
})
describe('checkForModuleName', function () {
it('returns true if module name is provided', function () {
let result = utils.checkForModuleName('core:user_list')
expect(result).to.equal(true)
})
it('returns false if module name is provided', function () {
let result = utils.checkForModuleName('user_list')
expect(result).to.equal(false)
})
})
describe('getTestTemplateVariables', function () {
describe('for components', function () {
let expected = {
componentName: 'HeaderMenu',
componentFileName: 'header_menu',
moduleName: 'user_management'
}
it('getes templates varaibles - variation 1', function () {
let result = utils.getTestTemplateVariables(
'component',
'user_management',
'headerMenu'
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('getes templates varaibles - variation 2', function () {
let result = utils.getTestTemplateVariables(
'component',
'userManagement',
'headerMenu'
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('getes templates varaibles - variation 3', function () {
let result = utils.getTestTemplateVariables(
'component',
'UserManagement',
'header_menu'
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
})
describe('for containers', function () {
let expected = {
containerFileName: 'comment_lists',
moduleName: 'core'
}
it('getes templates varaibles - variation 1', function () {
let result = utils.getTestTemplateVariables(
'container',
'core',
'comment_lists'
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
it('getes templates varaibles - variation 2', function () {
let result = utils.getTestTemplateVariables(
'container',
'core',
'comment_lists'
)
let matched = _.isEqual(result, expected)
expect(matched).to.equal(true)
})
})
})
describe('getTemplatePath', function () {
it('gets template path for collection - collection2', function () {
let result = utils.getTemplatePath('collection', {schema: 'collection2'})
expect(result).to.match(/generic_collection2.tt/)
})
})
describe('compileTemplate', function () {
it('applies tabSize', function () {
let content = `function() {
if (true) {
console.log('hello world');
}
}
`
let result = utils.compileTemplate(content, {}, {tabSize: 4})
expect(result).to.equal(`function() {
if (true) {
console.log('hello world');
}
}
`)
})
})
describe('readTemplateContent', function () {
it('returns the custom content if config is provided', function () {
let options = {}
let customContent = 'hello world'
let configs = {templates: [{name: 'action', text: customContent}]}
let result = utils.readTemplateContent('action', options, configs)
expect(result).to.equal(customContent)
})
})
|
let data = {
'http://swapi.co/api/people/1': {
name: 'Luke Skywalker'
},
'http://swapi.co/api/films/1': {
title: 'A New Hope'
},
'http://swapi.co/api/starships/9': {
name: 'Death Star'
},
'http://swapi.co/api/vehicles/4': {
name: 'Sand Crawler'
},
'http://swapi.co/api/species/3': {
name: 'Wookiee'
},
'http://swapi.co/api/planets/1': {
name: 'Tatooine'
}
};
export default data;
|
var path = require('path');
var webpack = require('webpack');
// extract-text is used to extract CSS definitions into separate CSS file
var ExtractTextPlugin = require('extract-text-webpack-plugin');
// indexhtml is used to enable index.html as an entry point
var IndexHtmlPlugin = require('indexhtml-webpack-plugin');
// setup css target file name
var cssExtractPlugin = new ExtractTextPlugin('css/bundle-[contenthash:16].css');
module.exports = {
// root folder for all reference paths
context: path.join(__dirname, 'src'),
// entry points for webpack to analyse
entry: {
'index.html': './index.html',
'js/app.js': './js/app.js'
},
// loaders to use to process files
module:{
// lint all js files before compilation process starts
// jshint config bellow will stop webpack if there is
// any js problems
preLoaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['jshint']
},
],
loaders: [
// css -> style -> text-extract all CSS files;
// css loads css file contents and identifies dependencies;
// style will link the CSS generated bundle into the html file;
// cssExtractPlugin will generate a CSS bundle file;
// publicPath option is needed because we are putting the CSS file
// into a 'css' subfolder.
{
test: /\.css$/,
loader: cssExtractPlugin.extract('style', 'css', { publicPath: '../' })
},
// use url loader for font files
// url will inline font file contents if size is less than 'limit' value
{
test: /\.(woff|woff2|eot|ttf|svg)(\?v=.*)?$/i,
loaders: [ 'url?name=font/[name]-[hash].[ext]&limit=10000' ]
},
// use html loader to load index.html and include dependencies
// from 'link' and 'img' tags
{
test: /index\.html$/,
loader: 'html?attrs=link:href img:src'
},
// expose jquery module as 'jQuery' global variable
// because bootstrap needs it to work
{
test: require.resolve('jquery'),
loader: 'expose?$!expose?jQuery'
}
]
},
// register plug-ins
plugins: [
cssExtractPlugin,
new IndexHtmlPlugin('index.html', 'index.html')
],
// set output folder and filename
output: {
path: './dist',
filename: '[name]'
},
jshint: {
// set jshint to interrupt the compilation
// if any file errors
failOnHint: true
}
};
|
var mongoose = require('mongoose')
var WorkSchema = require('../schemas/work')
var Work = mongoose.model('Work', WorkSchema)
module.exports = Work
|
var products = [
"Brooklyn T-Shirt White",
"Brooklyn T-Shirt Black",
"Apple Watch",
"Android Phone"
];
var prices = [10, 10, 199, 159]
var productsText = "";
var productsElement = document.getElementById("product-list");
productsText += "<li class='list-group-item'><span class='badge'>$" + prices[0] + "</span>" + products[0] + "</li>";
productsText += "<li class='list-group-item'><span class='badge'>$" + prices[1] + "</span>" + products[1] + "</li>";
productsText += "<li class='list-group-item'><span class='badge'>$" + prices[2] + "</span>" + products[2] + "</li>";
productsText += "<li class='list-group-item'><span class='badge'>$" + prices[3] + "</span>" + products[3] + "</li>";
productsElement.innerHTML = productsText;
var customerName = "Angelina"
var price = 10;
var quantity = 2;
var total = prices[0] + prices[1] + prices[2] + prices[3];
var totalPrice = total * 0.75;
var totalPriceElement = document.getElementById("total-price")
totalPriceElement.textContent = totalPrice;
var customerElement = document.getElementById("customer-name");
customerElement.textContent = customerName;
var time = new Date().getHours();
var greeting;
if (time < 12) {
greeting = "Good morning";
} else if (time < 18) {
greeting = "Good afternoon"
} else {
greeting = "Good evening";
}
var greetingElement = document.getElementById("hello-word")
greetingElement.textContent = greeting;
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M15.5 10.5h2v1h-2z" /><path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-10 6.5H6.5v.75H9c.55 0 1 .45 1 1V14c0 .55-.45 1-1 1H5v-1.5h3.5v-.75H6c-.55 0-1-.45-1-1V10c0-.55.45-1 1-1h4v1.5zm3 4.5h-2V9h2v6zm6-3c0 .55-.45 1-1 1h-2.5v2H14V9h4c.55 0 1 .45 1 1v2z" /></React.Fragment>
, 'Sip');
|
function Draw(n) {
for (var i = 0; i < n; i++) {
var str = "";
for (var k = 0; k < i; k++) {
str += "**";
}
str = str.substring(0, str.length - 1);
console.log(str);
}
}
Draw(8);
|
var Acceptance = (function() {
//================================================================
// DSL function and public methods
//================================================================
var environment = function(rules) {
rules.apply(Root);
};
environment.reattach = function() {
var n = 0;
for (var key in forms) {
if (forms[key]._attach()) ++n;
}
return n;
};
//================================================================
// Storage of all registered sets of form rules
//================================================================
var forms = {};
var getForm = function(id) {
return forms[id] || (forms[id] = new FormDescription(id));
};
//================================================================
// Constants
//================================================================
var NUMBER_FORMAT = /^\-?(0|[1-9]\d*)(\.\d+)?(e[\+\-]?\d+)?$/i;
var EMAIL_FORMAT = /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b$/i;
//================================================================
// Private utility methods
//================================================================
var isBlank = function(value) {
return value ? false : (String(value).strip() == '');
};
var isNumeric = function(value) {
return NUMBER_FORMAT.test(String(value));
};
var isPresent = function(value) {
return !isBlank(value) || ['must not be blank'];
};
var getLabel = function(input) {
input = $(input);
if (!input) return null;
var label = input.ancestors().find(function(tag) { return tag.match('label') });
if (label) return label;
var id = input.id;
if (!id) return null;
return $$('label[for=' + id + ']')[0] || null;
};
var getData = function(form) {
var data = $(form).serialize(true);
for (var key in data) {
if (data[key] instanceof Array) data[key] = data[key][0];
}
return data;
};
var setValue = function(elements, value) {
var selected, options, element = elements[0];
switch (true) {
case elements.all(function(e) { return e.match('[type=radio]') }) :
selected = elements.find(function(e) { return e.value == value });
if (!selected) return;
elements.each(function(e) { e.checked = false });
selected.checked = true;
break;
case element.match('[type=checkbox]') :
element.checked = !!(value === true || value == element.value);
break;
case element.match('select') :
options = $A(element.options);
selected = options.find(function(o) { return o.value == value });
if (!selected) return;
options.each(function(o) { o.selected = false });
selected.selected = true;
break;
case element.match('input') :
case element.match('[type=hidden]') :
case element.match('textarea') :
element.value = String(value);
break;
}
};
//================================================================
// DSL root object with top-level functions
//================================================================
var Root = {
form: function(id) {
return getForm(id)._dsl || null;
},
when: function(id) {
return getForm(id)._when || null;
},
before: function(id) {
return getForm(id)._before || null;
},
displayErrorsIn: function(element) {
return function(errors) {
if (typeof element == 'string') element = $$(element)[0];
if (!element) return;
var n = errors.length;
if (n == 0) return element.update('');
var were = (n == 1) ? 'was' : 'were', s = (n == 1) ? '' : 's';
var content = '<div class="error-explanation">';
content += '<p>There ' + were + ' ' + n + ' error' + s + ' with the form:</p>';
content += '<ul>';
errors.each(function(error) { content += '<li>' + error.message + '</li>' });
content += '</ul>';
content += '</div>';
element.update(content);
};
},
displayResponseIn: function(element) {
return function(response) {
if (typeof element == 'string') element = $$(element)[0];
if (!element) return;
element.update(response.responseText);
};
},
EMAIL_FORMAT: EMAIL_FORMAT
};
//================================================================
// Class: FormDSL
//================================================================
var FormDSL = Class.create({
initialize: function(form) {
this._form = form;
},
requires: function(name, displayed) {
var requirement = this._form._getRequirement(name);
if (displayed) this._form._displayNames[name] = displayed;
return requirement._dsl;
},
validates: function(block) {
this._form._validators.push(block);
return this;
},
submitsUsingAjax: function() {
this._form._ajax = true;
return this;
}
});
FormDSL.prototype.expects = FormDSL.prototype.requires;
FormDSLMethods = ['requires', 'expects', 'validates', 'submitsUsingAjax'];
//================================================================
// Class: RequirementDSL
//================================================================
var RequirementDSL = Class.create({
initialize: function(requirement) {
this._requirement = requirement;
},
toBeChecked: function(message) {
var requirement = this._requirement;
this._requirement._add(function(value) {
var element = requirement._elements[0];
return (value == element.value && element.checked) || [message || 'must be checked'];
});
return this;
},
toBeNumeric: function(message) {
this._requirement._add(function(value) {
return isNumeric(value) || [message || 'must be a number'];
});
return this;
},
toBeOneOf: function(list, message) {
this._requirement._add(function(value) {
return list.include(value) || [message || 'is not valid'];
});
return this;
},
toBeNoneOf: function(list, message) {
this._requirement._add(function(value) {
return !list.include(value) || [message || 'is not valid'];
});
return this;
},
toBePresent: function(message) {
this._requirement._add(function(value) {
return !isBlank(value) || [message || 'must not be blank'];
});
return this;
},
toConfirm: function(field, message) {
this._requirement._add(function(value, data) {
return value == data.get(field) || [message || 'must be confirmed', field];
});
return this;
},
toHaveLength: function(options, message) {
var min = options.minimum, max = options.maximum;
this._requirement._add(function(value) {
return (typeof options == 'number' && value.length != options &&
[message || 'must contain exactly ' + options + ' characters']) ||
(min !== undefined && value.length < min &&
[message || 'must contain at least ' + min + ' characters']) ||
(max !== undefined && value.length > max &&
[message || 'must contain no more than ' + max + ' characters']) ||
true;
});
return this;
},
toHaveValue: function(options, message) {
var min = options.minimum, max = options.maximum;
this._requirement._add(function(value) {
if (!isNumeric(value)) return [message || 'must be a number'];
value = Number(value);
return (min !== undefined && value < min &&
[message || 'must be at least ' + min]) ||
(max !== undefined && value > max &&
[message || 'must not be greater than ' + max]) ||
true;
});
return this;
},
toMatch: function(format, message) {
this._requirement._add(function(value) {
return format.test(value) || [message || 'is not valid'];
});
return this;
}
});
FormDSLMethods.each(function(method) {
RequirementDSL.prototype[method] = function() {
var base = this._requirement._form._dsl;
return base[method].apply(base, arguments);
};
});
//================================================================
// Class: WhenDSL
//================================================================
var WhenDSL = Class.create({
initialize: function(form) {
this._form = form;
},
isValidated: function(block, context) {
this._form.subscribe(function(form) {
block.call(context || null, form._errors._messages());
});
},
responseArrives: function(block, context) {
if (context) block = block.bind(context);
this._form._ajaxResponders.push(block);
}
});
//================================================================
// Class: BeforeDSL
//================================================================
var BeforeDSL = Class.create({
initialize: function(form) {
this._form = form;
},
isValidated: function(block) {
this._form._dataFilters.push(block);
}
});
//================================================================
// Class: FormDescription
//================================================================
var FormDescription = Class.create({
initialize: function(id) {
this._observers = [];
this._handleSubmission = this._handleSubmission.bindAsEventListener(this);
this._formID = id;
this._displayNames = {};
this._attach();
this._requirements = {};
this._validators = [];
this._dataFilters = [];
this._ajaxResponders = [];
this._dsl = new FormDSL(this);
this._when = new WhenDSL(this);
this._before = new BeforeDSL(this);
},
subscribe: function(block, context) {
this._observers.push({_blk: block, _ctx: context || null});
},
notifyObservers: function() {
var args = $A(arguments);
this._observers.each(function(observer) {
observer._blk.apply(observer._ctx, args);
});
},
_attach: function() {
if (this._hasForm()) return false;
this._inputs = {};
this._labels = {};
this._names = {};
this._form = $(this._formID);
if (!this._hasForm()) return false;
this._form.observe('submit', this._handleSubmission);
for (var field in this._requirements) this._requirements[field]._attach();
return true;
},
_hasForm: function() {
return this._form && this._form.match('body form');
},
_getRequirement: function(name) {
return this._requirements[name] || (this._requirements[name] = new FormRequirement(this, name));
},
_handleSubmission: function(evnt) {
var valid = this._isValid();
if (this._ajax || !valid) Event.stop(evnt);
if (!this._ajax || !valid) return;
var form = this._form;
new Ajax.Request(form.action, {
method: form.method || 'post',
parameters: this._data,
onSuccess: function(response) {
this._ajaxResponders.each(function(block) { block(response) });
}.bind(this)
});
},
_getInputs: function(name) {
if (this._inputs[name]) return this._inputs[name];
if (!this._form) return [];
return this._inputs[name] = this._form.descendants().findAll(function(tag) {
var isInput = tag.match('input, textarea, select');
return isInput && (name ? (tag.name == name) : true);
});
},
_getLabel: function(name) {
if (name.name) name = name.name;
return this._labels[name] || ( this._labels[name] = getLabel(this._getInputs(name)[0]) );
},
_getName: function(field) {
if (this._names[field]) return this._names[field];
if (this._displayNames[field]) return this._names[field] = this._displayNames[field];
var label = this._getLabel(field);
var name = ((label||{}).innerHTML || field).stripTags().strip();
name = name.replace(/(\w)[_-](\w)/g, '$1 $2')
.replace(/([a-z])([A-Z])/g, function(match, a, b) {
return a + ' ' + b.toLowerCase();
});
return this._names[field] = name.charAt(0).toUpperCase() + name.substring(1);
},
_getData: function() {
return this._data = getData(this._form);
},
_validate: function() {
this._errors = new FormErrors(this);
var data = this._getData(), key, input;
this._dataFilters.each(function(filter) { filter(data); });
for (key in data) setValue(this._getInputs(key), data[key]);
data = new FormData(data);
for (key in this._requirements)
this._requirements[key]._test(data.get(key), data);
this._validators.each(function(validate) { validate(data, this._errors); }, this);
var fields = this._errors._fields();
for (key in this._inputs)
[this._getInputs(key), [this._getLabel(key)]].invoke('each', function(element) {
if (!element) return;
element[fields.include(key) ? 'addClassName' : 'removeClassName']('invalid');
});
this.notifyObservers(this);
},
_isValid: function() {
this._validate();
return this._errors._count() == 0;
}
});
//================================================================
// Class: FormRequirement
//================================================================
var FormRequirement = Class.create({
initialize: function(form, field) {
this._form = form;
this._field = field;
this._tests = [];
this._dsl = new RequirementDSL(this);
this._attach();
},
_attach: function() {
this._elements = this._form._getInputs(this._field);
},
_add: function(block) {
this._tests.push(block);
},
_test: function(value, data) {
var errors = [], tests = this._tests.length ? this._tests : [isPresent], value = value || '';
tests.each(function(block) {
var result = block(value, data), message, field;
if (result !== true) {
message = result[0]; field = result[1] || this._field;
this._form._errors.register(this._field);
this._form._errors.add(field, message);
}
}, this);
return errors.length ? errors : true;
}
});
//================================================================
// Class: FormData
//================================================================
var FormData = Class.create({
initialize: function(data) {
this.get = function(field) {
return data[field] === undefined ? null : data[field];
};
}
});
//================================================================
// Class: FormErrors
//================================================================
var FormErrors = Class.create({
initialize: function(form) {
var errors = {}, base = [];
Object.extend(this, {
register: function(field) {
errors[field] = errors[field] || [];
},
add: function(field, message) {
this.register(field);
if (!errors[field].include(message)) errors[field].push(message);
},
addToBase: function(message) {
base.push(message);
},
_count: function() {
var n = base.length;
for (var field in errors) n += errors[field].length;
return n;
},
_messages: function() {
var name, messages = base.map(function(message) {
return {field: null, message: message};
});
for (var field in errors) {
name = form._getName(field);
errors[field].each(function(message) {
messages.push({field: field, message: name + ' ' + message});
});
}
return messages;
},
_fields: function() {
var fields = [];
for (var field in errors) fields.push(field);
return fields;
}
});
}
});
return environment;
})();
|
// Manipulating JavaScript Objects
// I worked on this challenge: [by myself, with: ]
// There is a section below where you will write your code.
// DO NOT ALTER THIS OBJECT BY ADDING ANYTHING WITHIN THE CURLY BRACES!
var terah = {
name: "Terah",
age: 32,
height: 66,
weight: 130,
hairColor: "brown",
eyeColor: "brown"
}
// __________________________________________
// Write your code below.
var adam = {};
adam.name = 'Adam';
terah.spouse = adam;
terah.weight = 125;
delete terah.eyeColor;
adam.spouse = terah;
terah.children = {};
terah.children.carson = {};
terah.children.carson.name = 'Carson';
terah.children.carter = {};
terah.children.carter.name = 'Carter';
terah.children.colton = {};
terah.children.colton.name = 'Colton';
adam.children = terah.children;
// __________________________________________
// Reflection: Use the reflection guidelines
// What tests did you have trouble passing? What did you do to make it pass? Why did that work?
// I did not have trouble making any of the tests pass once I reviewed the syntax for modifying objects in the text - i.e. do not go back and reopen the object, instead edit the object's properties using the = operator.
// How difficult was it to add and delete properties outside of the object itself?
// It's easy once you get the hang of the syntax and understand the structure of the object.
// What did you learn about manipulating objects in this challenge?
// Manipulating objects in JS does not require complex syntax; it is very similar syntactically to calling methods on an object in Ruby.
//
//
//
//
// __________________________________________
// Driver Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(adam instanceof Object),
"The value of adam should be an Object.",
"1. "
)
assert(
(adam.name === "Adam"),
"The value of the adam name property should be 'Adam'.",
"2. "
)
assert(
terah.spouse === adam,
"terah should have a spouse property with the value of the object adam.",
"3. "
)
assert(
terah.weight === 125,
"The terah weight property should be 125.",
"4. "
)
assert(
terah.eyeColor === undefined || null,
"The terah eyeColor property should be deleted.",
"5. "
)
assert(
terah.spouse.spouse === terah,
"Terah's spouse's spouse property should refer back to the terah object.",
"6. "
)
assert(
(terah.children instanceof Object),
"The value of the terah children property should be defined as an Object.",
"7. "
)
assert(
(terah.children.carson instanceof Object),
"carson should be defined as an object and assigned as a child of Terah",
"8. "
)
assert(
terah.children.carson.name === "Carson",
"Terah's children should include an object called carson which has a name property equal to 'Carson'.",
"9. "
)
assert(
(terah.children.carter instanceof Object),
"carter should be defined as an object and assigned as a child of Terah",
"10. "
)
assert(
terah.children.carter.name === "Carter",
"Terah's children should include an object called carter which has a name property equal to 'Carter'.",
"11. "
)
assert(
(terah.children.colton instanceof Object),
"colton should be defined as an object and assigned as a child of Terah",
"12. "
)
assert(
terah.children.colton.name === "Colton",
"Terah's children should include an object called colton which has a name property equal to 'Colton'.",
"13. "
)
assert(
adam.children === terah.children,
"The value of the adam children property should be equal to the value of the terah children property",
"14. "
)
console.log("\nHere is your final terah object:")
console.log(terah)
|
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var Holodeck = require('../../../holodeck'); /* jshint ignore:line */
var Request = require(
'../../../../../lib/http/request'); /* jshint ignore:line */
var Response = require(
'../../../../../lib/http/response'); /* jshint ignore:line */
var RestException = require(
'../../../../../lib/base/RestException'); /* jshint ignore:line */
var Twilio = require('../../../../../lib'); /* jshint ignore:line */
var client;
var holodeck;
describe('CompositionHook', function() {
beforeEach(function() {
holodeck = new Holodeck();
client = new Twilio('ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AUTHTOKEN', {
httpClient: holodeck
});
});
it('should generate valid fetch request',
function(done) {
holodeck.mock(new Response(500, {}));
var promise = client.video.v1.compositionHooks('HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var sid = 'HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://video.twilio.com/v1/CompositionHooks/${sid}`;
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid fetch response',
function(done) {
var body = {
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': 'My composition hook',
'enabled': true,
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:01:33Z',
'sid': 'HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'audio_sources': [
'user*'
],
'audio_sources_excluded': [
'moderator*'
],
'video_layout': {
'grid': {
'video_sources': [
'*'
],
'video_sources_excluded': [
'moderator*'
],
'reuse': 'show_oldest',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
},
'pip': {
'video_sources': [
'student*'
],
'video_sources_excluded': [],
'reuse': 'none',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
}
},
'resolution': '1280x720',
'format': 'webm',
'trim': true,
'status_callback': 'http://www.example.com',
'status_callback_method': 'POST',
'url': 'https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
holodeck.mock(new Response(200, body));
var promise = client.video.v1.compositionHooks('HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should treat the first each arg as a callback',
function(done) {
var body = {
'composition_hooks': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': 'My Special Hook1',
'enabled': true,
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:01:33Z',
'sid': 'HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'audio_sources': [
'*'
],
'audio_sources_excluded': [],
'video_layout': {
'grid': {
'video_sources': [
'*'
],
'video_sources_excluded': [
'moderator*'
],
'reuse': 'show_oldest',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
},
'pip': {
'video_sources': [
'student*'
],
'video_sources_excluded': [],
'reuse': 'none',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
}
},
'resolution': '1280x720',
'format': 'webm',
'trim': true,
'status_callback': 'http://www.example.com',
'status_callback_method': 'POST',
'url': 'https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'meta': {
'page': 0,
'page_size': 50,
'first_page_url': 'https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0',
'previous_page_url': null,
'url': 'https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0',
'next_page_url': null,
'key': 'composition_hooks'
}
};
holodeck.mock(new Response(200, body));
client.video.v1.compositionHooks.each(() => done());
}
);
it('should treat the second arg as a callback',
function(done) {
var body = {
'composition_hooks': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': 'My Special Hook1',
'enabled': true,
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:01:33Z',
'sid': 'HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'audio_sources': [
'*'
],
'audio_sources_excluded': [],
'video_layout': {
'grid': {
'video_sources': [
'*'
],
'video_sources_excluded': [
'moderator*'
],
'reuse': 'show_oldest',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
},
'pip': {
'video_sources': [
'student*'
],
'video_sources_excluded': [],
'reuse': 'none',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
}
},
'resolution': '1280x720',
'format': 'webm',
'trim': true,
'status_callback': 'http://www.example.com',
'status_callback_method': 'POST',
'url': 'https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'meta': {
'page': 0,
'page_size': 50,
'first_page_url': 'https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0',
'previous_page_url': null,
'url': 'https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0',
'next_page_url': null,
'key': 'composition_hooks'
}
};
holodeck.mock(new Response(200, body));
client.video.v1.compositionHooks.each({pageSize: 20}, () => done());
holodeck.assertHasRequest(new Request({
method: 'GET',
url: 'https://video.twilio.com/v1/CompositionHooks',
params: {PageSize: 20},
}));
}
);
it('should find the callback in the opts object',
function(done) {
var body = {
'composition_hooks': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': 'My Special Hook1',
'enabled': true,
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:01:33Z',
'sid': 'HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'audio_sources': [
'*'
],
'audio_sources_excluded': [],
'video_layout': {
'grid': {
'video_sources': [
'*'
],
'video_sources_excluded': [
'moderator*'
],
'reuse': 'show_oldest',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
},
'pip': {
'video_sources': [
'student*'
],
'video_sources_excluded': [],
'reuse': 'none',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
}
},
'resolution': '1280x720',
'format': 'webm',
'trim': true,
'status_callback': 'http://www.example.com',
'status_callback_method': 'POST',
'url': 'https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'meta': {
'page': 0,
'page_size': 50,
'first_page_url': 'https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0',
'previous_page_url': null,
'url': 'https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0',
'next_page_url': null,
'key': 'composition_hooks'
}
};
holodeck.mock(new Response(200, body));
client.video.v1.compositionHooks.each({callback: () => done()}, () => fail('wrong callback!'));
}
);
it('should generate valid list request',
function(done) {
holodeck.mock(new Response(500, {}));
var promise = client.video.v1.compositionHooks.list();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var url = 'https://video.twilio.com/v1/CompositionHooks';
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid read_empty response',
function(done) {
var body = {
'composition_hooks': [],
'meta': {
'page': 0,
'page_size': 50,
'first_page_url': 'https://video.twilio.com/v1/CompositionHooks?Enabled=True&PageSize=50&Page=0',
'previous_page_url': null,
'url': 'https://video.twilio.com/v1/CompositionHooks?Enabled=True&PageSize=50&Page=0',
'next_page_url': null,
'key': 'composition_hooks'
}
};
holodeck.mock(new Response(200, body));
var promise = client.video.v1.compositionHooks.list();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid read_results response',
function(done) {
var body = {
'composition_hooks': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'friendly_name': 'My Special Hook1',
'enabled': true,
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:01:33Z',
'sid': 'HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'audio_sources': [
'*'
],
'audio_sources_excluded': [],
'video_layout': {
'grid': {
'video_sources': [
'*'
],
'video_sources_excluded': [
'moderator*'
],
'reuse': 'show_oldest',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
},
'pip': {
'video_sources': [
'student*'
],
'video_sources_excluded': [],
'reuse': 'none',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 0,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': []
}
},
'resolution': '1280x720',
'format': 'webm',
'trim': true,
'status_callback': 'http://www.example.com',
'status_callback_method': 'POST',
'url': 'https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
],
'meta': {
'page': 0,
'page_size': 50,
'first_page_url': 'https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0',
'previous_page_url': null,
'url': 'https://video.twilio.com/v1/CompositionHooks?FriendlyName=%2AHook%2A&DateCreatedBefore=2017-12-31T23%3A59%3A59Z&DateCreatedAfter=2017-01-01T00%3A00%3A01Z&Enabled=True&PageSize=50&Page=0',
'next_page_url': null,
'key': 'composition_hooks'
}
};
holodeck.mock(new Response(200, body));
var promise = client.video.v1.compositionHooks.list();
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid remove request',
function(done) {
holodeck.mock(new Response(500, {}));
var promise = client.video.v1.compositionHooks('HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove();
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var sid = 'HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://video.twilio.com/v1/CompositionHooks/${sid}`;
holodeck.assertHasRequest(new Request({
method: 'DELETE',
url: url
}));
}
);
it('should generate valid delete response',
function(done) {
var body = null;
holodeck.mock(new Response(204, body));
var promise = client.video.v1.compositionHooks('HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').remove();
promise.then(function(response) {
expect(response).toBe(true);
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid create request',
function(done) {
holodeck.mock(new Response(500, {}));
var opts = {'friendlyName': 'friendly_name'};
var promise = client.video.v1.compositionHooks.create(opts);
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var url = 'https://video.twilio.com/v1/CompositionHooks';
var values = {'FriendlyName': 'friendly_name', };
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url,
data: values
}));
}
);
it('should generate valid create response',
function(done) {
var body = {
'friendly_name': 'My composition hook',
'enabled': false,
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T20:00:00Z',
'date_updated': null,
'sid': 'HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'audio_sources': [
'user*',
'moderator'
],
'audio_sources_excluded': [
'admin'
],
'video_layout': {
'custom': {
'video_sources': [
'user*'
],
'video_sources_excluded': [
'moderator'
],
'reuse': 'show_oldest',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 800,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': [
2,
3
]
}
},
'trim': true,
'format': 'mp4',
'resolution': '1280x720',
'status_callback': 'http://www.example.com',
'status_callback_method': 'POST',
'url': 'https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
holodeck.mock(new Response(201, body));
var opts = {'friendlyName': 'friendly_name'};
var promise = client.video.v1.compositionHooks.create(opts);
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid update request',
function(done) {
holodeck.mock(new Response(500, {}));
var opts = {'friendlyName': 'friendly_name'};
var promise = client.video.v1.compositionHooks('HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(opts);
promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
done();
}).done();
var sid = 'HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var url = `https://video.twilio.com/v1/CompositionHooks/${sid}`;
var values = {'FriendlyName': 'friendly_name', };
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url,
data: values
}));
}
);
it('should generate valid update_all_fields response',
function(done) {
var body = {
'friendly_name': 'My composition hook',
'enabled': true,
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'sid': 'HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'audio_sources': [
'user*',
'moderator'
],
'audio_sources_excluded': [
'admin'
],
'video_layout': {
'custom': {
'video_sources': [
'user*'
],
'video_sources_excluded': [
'moderator'
],
'reuse': 'show_oldest',
'x_pos': 100,
'y_pos': 600,
'z_pos': 10,
'width': 800,
'height': 0,
'max_columns': 0,
'max_rows': 0,
'cells_excluded': [
2,
3
]
}
},
'trim': true,
'format': 'mp4',
'resolution': '1280x720',
'status_callback': 'http://www.example.com',
'status_callback_method': 'POST',
'url': 'https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
holodeck.mock(new Response(200, body));
var opts = {'friendlyName': 'friendly_name'};
var promise = client.video.v1.compositionHooks('HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(opts);
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
it('should generate valid update_with_defaults response',
function(done) {
var body = {
'friendly_name': 'My composition hook',
'enabled': true,
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'sid': 'HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'audio_sources': [
'user*',
'moderator'
],
'audio_sources_excluded': [
'admin'
],
'video_layout': {},
'trim': true,
'format': 'mp4',
'resolution': '1280x720',
'status_callback': null,
'status_callback_method': 'POST',
'url': 'https://video.twilio.com/v1/CompositionHooks/HKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
holodeck.mock(new Response(200, body));
var opts = {'friendlyName': 'friendly_name'};
var promise = client.video.v1.compositionHooks('HKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').update(opts);
promise.then(function(response) {
expect(response).toBeDefined();
done();
}, function() {
throw new Error('failed');
}).done();
}
);
});
|
var request = require('request');
request.post({
url: 'http://localhost:3000/endpoint/00000/emit/login/testmember',
json: true,
body: {
payload: 'Hello'
}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
|
var TIME_DOT = 0.1;
var TIME_DASH = 3 * TIME_DOT;
var TIME_BETWEEN_SYMBOLS = TIME_DOT;
var TIME_BETWEEN_LETTERS = TIME_DASH;
var TIME_BLANK = 7 * TIME_DOT;
var DOT = '.';
var DASH = '-';
var BLANK = ' ';
var ALPHABET = {
'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..',
'e': '.', 'f': '..-.', 'g': '--.', 'h': '....',
'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..',
'm': '--', 'n': '-.', 'o': '---', 'p': '.--.',
'q': '--.-', 'r': '.-.', 's': '...', 't': '-',
'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-',
'y': '-.--', 'z': '--..',
'1': '.----', '2': '..---', '3': '...--', '4': '....-',
'5': '.....', '6': '-....', '7': '--...', '8': '---..',
'9': '----.', '0': '-----',
}
function toMorse(string) {
// https://stackoverflow.com/questions/26059170/using-javascript-to-encode-morsecode
return string.split('') // Transform the string into an array: ['T', 'h', 'i', 's'...
.map(function(e){ // Replace each character with a morse "letter"
return ALPHABET[e.toLowerCase()] || ''; // Lowercase only, ignore unknown characters.
})
.join(' ') // Convert the array back to a string.
.replace(/ +/g, ' '); // Replace double spaces that may occur when unknow characters were in the source string.
}
function removeDiacritics(string) {
//https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
return string.normalize('NFD').replace(/[\u0300-\u036f]/g, "")
}
function sleep(s) {
// https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
return new Promise(resolve => setTimeout(resolve, s * 1000));
}
function play(time) {
envelope.setADSR(0.001, time, 1, 0.001);
envelope.play(osc);
}
async function playString(string) {
var raw = removeDiacritics(string);
var morseString = toMorse(raw);
for(var i = 0; i < raw.length; i++) {
await playChar(raw[i]);
}
}
async function playChar(c) {
// string example: -.-.
var morseString = toMorse(c);
for(var i = 0; i < morseString.length; i++) {
c = morseString[i];
switch (c) {
case DOT:
balls.push(new Ball(DOT));
play(TIME_DOT);
await sleep(TIME_DOT + TIME_BETWEEN_SYMBOLS);
break;
case DASH:
balls.push(new Ball(DASH));
play(TIME_DASH);
await sleep(TIME_DASH + TIME_BETWEEN_SYMBOLS);
break;
case BLANK:
await sleep(TIME_BLANK);
break;
default:
break;
}
}
await sleep(TIME_BETWEEN_LETTERS);
}
|
'use strict';
angular.module('com.module.tickets')
.config(function ($stateProvider) {
$stateProvider
.state('app.tickets', {
abstract: true,
url: '/tickets',
templateUrl: 'modules/tickets/views/main.html'
})
.state('app.tickets.list', {
url: '',
templateUrl: 'modules/tickets/views/list.html',
controller: 'ticketsCtrl',
resolve:{
tickets: function(SER_mcglobalRequests){
return SER_mcglobalRequests.find().$promise;
}
}
})
.state('app.tickets.view', {
url: '/:id',
templateUrl: 'modules/tickets/views/view.html',
controller: 'ticketDetailCtrl',
resolve:{
ticket: function(SER_mcglobalRequests, $stateParams){
console.log('are we running this resolve');
console.log($stateParams.id);
return SER_mcglobalRequests.find({"filter":{"where":{"id":$stateParams.id}}}).$promise;
},
comments: function(CommentService, $stateParams){
console.log('are we running this second resolve');
return CommentService.getComments($stateParams.id);
}
}
})
});
|
'use strict';
const extractText = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = env => {
const config = {
entry: './src/js/app.js',
module: {
rules: [
{
include: path.resolve(__dirname, 'src/js'),
loader: 'babel-loader',
options: {
compact: true,
plugins: ['inferno'],
presets: ['es2015'],
},
test: /\.js?$/,
},
{
include: path.resolve(__dirname, 'src/scss'),
loader: extractText.extract({
fallbackLoader: 'style-loader',
loader: [
{
loader: 'css-loader',
query: {
autoprefixer: {
add: true,
browsers: ['> 0.05%'],
},
},
},
{
loader: 'sass-loader',
},
],
}),
test: /\.scss$/,
},
],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new extractText('../dist/bundle.css'),
],
};
if (env && env.production) {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
})
);
} else {
config.performance = {
hints: false,
};
config.watch = true;
}
return config;
}
|
export default {
comments: [],
create(comment) {
this.comments.push(comment);
},
};
export const ioc = { };
|
require.config({
baseUrl: '/Scripts',
paths: {
"jquery": "jquery-2.0.3.min",
"bootstrap": "bootstrap.min",
"ko": "knockout-3.0.0",
"signalr": "jquery.signalR-1.2.0.min",
"signalr-hubs": "/signalr/hubs?_",
"json": "json2.min",
"underscore": "underscore-extensions"
},
shim: {
"jquery": { exports: '$' },
"bootstrap": ["jquery"],
"ko": { exports: "ko", deps: ["jquery", "underscore"] },
"clipboard": ["jquery"],
"signalr": ["jquery"],
"signalr-hubs": ["signalr"],
"json": { exports: "JSON" },
"underscore": { exports: "_" },
}
});
define("config", function () {
return globalConfig;
});
require(["ko", "signalr-hubs", "bootstrap", "app/validation-summary"], function (ko) {
$(document).ready(function () {
var viewModels = $("[data-view-model]");
var loadCounter = 0;
$(viewModels).each(function () {
var filename = $(this).text();
require(["app" + filename], function (viewModel) {
if (viewModel.target) {
ko.applyBindings(viewModel, $(viewModel.target)[0]);
} else {
ko.applyBindings(viewModel);
}
loadCounter++;
if (loadCounter == viewModels.length) {
$(document).trigger("viewModelsReady");
}
});
});
});
});
|
var initSidebar = function () {
var getHierarchy = function (coursepath) {
var xmlDom = loadXmlFile(coursepath + "course.xml");
xmlDom = xmlDom.getElementsByTagName("course")[0];
var url_name = xmlDom.getAttribute("url_name");
xmlDom = loadXmlFile(coursepath + "course/" + url_name + ".xml");
xmlDom = xmlDom.getElementsByTagName("course")[0];
var chapterSet = xmlDom.getElementsByTagName("chapter");
var hierarchy = [];
for (var chapterIndex = 0; chapterIndex < chapterSet.length; chapterIndex++) {
var chapter = chapterSet[chapterIndex];
url_name = chapter.getAttribute("url_name");
hierarchy.push(loadChapter(coursepath, url_name));
}
return hierarchy;
}
var loadChapter = function (coursepath, url_name) { //Week or Section
var xmlDom = loadXmlFile(coursepath + "chapter/" + url_name + ".xml");
xmlDom = xmlDom.getElementsByTagName("chapter")[0];
var chapter = {};
chapter["url_name"] = url_name;
/* possible attributes:
* display_name
* graceperiod
* start
* xqa_key
*/
for (var attrIdx = 0; attrIdx < xmlDom.attributes.length; attrIdx++) {
var attribute = xmlDom.attributes.item(attrIdx);
chapter[attribute.nodeName] = attribute.nodeValue;
}
chapter["sequentials"] = [];
var sequentialSet = xmlDom.getElementsByTagName("sequential");
for (var sequentialIndex = 0; sequentialIndex < sequentialSet.length; sequentialIndex++) {
var sequential = sequentialSet[sequentialIndex];
url_name = sequential.getAttribute("url_name");
chapter["sequentials"].push(loadSequential(coursepath, url_name));
}
return chapter;
}
var loadSequential = function (coursepath, url_name) { //Subsection
var xmlDom = loadXmlFile(coursepath + "sequential/" + url_name + ".xml");
xmlDom = xmlDom.getElementsByTagName("sequential")[0];
var sequential = {};
sequential["url_name"] = url_name;
/* possible attributes:
* display_name
* graceperiod
* start
* xqa_key
* due
* format
* graded
* rerandomize
* showanswer
*/
for (var attrIdx = 0; attrIdx < xmlDom.attributes.length; attrIdx++) {
var attribute = xmlDom.attributes.item(attrIdx);
sequential[attribute.nodeName] = attribute.nodeValue;
}
sequential["verticals"] = [];
var verticalSet = xmlDom.getElementsByTagName("vertical");
for (var verticalIndex = 0; verticalIndex < verticalSet.length; verticalIndex++) {
var vertical = verticalSet[verticalIndex];
url_name = vertical.getAttribute("url_name");
sequential["verticals"].push(loadVertical(coursepath, url_name));
}
return sequential;
}
var loadVertical = function (coursepath, url_name) { //Unit
var xmlDom = loadXmlFile(coursepath + "vertical/" + url_name + ".xml");
xmlDom = xmlDom.getElementsByTagName("vertical")[0];
var vertical = {};
vertical["url_name"] = url_name;
/* possible attributes:
* attempts
* display_name
* start
* due
* format
* graded
* rerandomize
* showanswer
*/
for (var attrIdx = 0; attrIdx < xmlDom.attributes.length; attrIdx++) {
var attribute = xmlDom.attributes.item(attrIdx);
vertical[attribute.nodeName] = attribute.nodeValue;
}
vertical["components"] = [];
for (var childIdx = 0; childIdx < xmlDom.childNodes.length; childIdx++) {
var child = xmlDom.childNodes.item(childIdx);
if (child.nodeName != "#text") {
vertical["components"].push({
"type": child.nodeName,
"url_name": child.getAttribute("url_name")
});
}
}
return vertical;
}
return getHierarchy('../../../data/2013_Spring_Tsinghua/');
}
var obj = initSidebar();
//alert(obj);
|
jQuery.fn.customList = function (defaults) {
var element = this;
var options = {
elements: {
methodModels: '.c-list-method',
reqUrl: '.c-list-url',
nextAction: '.c-list-next',
contentContainer: '.c-list-content',
contentItem: '.c-list-c-item',
displayToggle: '.c-list-display-tg',
searchAction: '.c-list-sr-btn'
},
listEndedCls: 'c-list-ended',
processNewCls: 'c-list-in-sr',
processNextCls: 'c-list-in-next',
filters: '.c-list-filter',
orders: '.c-list-order'
};
var methods = {
Init: function (element) {
for (var k in options.defaults) {
element.data(options.defaults[k], element.data(options.defaults[k]) || options.defaults[k]);
}
methods.InitEvents(element);
if(methods.GetOffset(element) == element.data('quantity')){
element.addClass(options.listEndedCls);
}
},
GetReqUrl: function (element) {
var url = null,
urls = element.find(options.elements.reqUrl);
if (urls.length == 1) {
url = element.find(options.elements.reqUrl).data('url');
} else if (urls.length == 0) {
url = element.data('url');
}
return url;
},
ResetListInfo: function (element) {
methods.SetOffset(element, 0);
element.data('quantity', 0);
},
RequestItems: function (element, data) {
data = data || {};
var filters = methods.CreateFilters(element),
orderBy = methods.CreateOrders(element),
url = methods.GetReqUrl(element);
var onSuccess = function (response) {
var result = {};
if (!response.error) {
result = response.result;
element.trigger('onSuccess.erlCustomList', result);
element.data('quantity', result.quantity);
if ('list' in result) {
var offset = methods.GetOffset(element);
if (!offset) {
methods.FillList(element, {list: result.list});
} else {
methods.AppendList(element, {list: result.list});
}
offset = methods.SetOffset(element, offset + methods.GetItemsPerPage(element));
if (result.quantity <= offset) {
element.addClass(options.listEndedCls);
}
else {
element.removeClass(options.listEndedCls);
}
}
if (result.count > 0) {
}
}
};
var params = {
filters: filters,
order_by: orderBy
};
if (data.addParams) {
jQuery.extend(true, params, data.addParams);
}
jQuery
.post(url, {params: JSON.stringify(params)})
.done(onSuccess);
},
makeSearch: function (element, data) {
methods.ResetListInfo(element, null);
data = jQuery.extend(true, data, {
addParams: {
offset: methods.GetOffset(element, null),
per_page: methods.GetItemsPerPage(element, null)}
});
methods.RequestItems(element, data);
},
InitEvents: function (element) {
var onClick = function (event, data) {
methods.makeSearch(element, data);
};
element.on('click', options.elements.searchAction, onClick);
element.bind('makeOrder.erlCustomList', onClick);
element.bind('makeSearch.erlCustomList', onClick);
var onNextClick = function (event, data) {
if (!element.hasClass(options.listEndedCls)) {
methods.GetNext(element, {});
}
};
element.on('click', options.elements.nextAction, onNextClick);
element.bind('getNext.erlCustomList', onNextClick);
},
MakeFilter: function (data) {
var item = data.item,
localFilter = {},
filterName, val,
type = item.data('type');
switch (type) {
case 'select':
if (item.prop('type') == 'select-one') {
val = item.find('option').filter(':selected').val();
filterName = item.attr('name');
if (val) {
localFilter[filterName] = val;
}
}
break;
case 'select-data':
if (item.prop('type') == 'select-one') {
val = item.find('option').filter(':selected').val();
filterName = item.data('name');
if (val) {
localFilter[filterName] = val;
}
}
break;
case 'input':
filterName = item.attr('name');
val = item.val();
if (val) {
localFilter[filterName] = val;
}
break;
case 'data':
filterName = item.data('name');
val = item.data('value');
if (val) {
localFilter[filterName] = val;
}
break;
case 'data-text':
filterName = item.data('name');
val = item.text();
if (val) {
localFilter[filterName] = val;
}
break;
case 'checkboxes':
filterName = item.data('name');
var arr = [];
item.find(':checkbox:checked').each(function(){
arr.push(this.value);
});
if (arr.length){
localFilter[filterName] = arr;
}
}
return {filter: localFilter, name: filterName};
},
CreateFilters: function (element) {
var filter = {};
var onEach = function (index, item) {
jQuery.extend(true, filter, (methods.MakeFilter({item: jQuery(item)})).filter);
};
element.find(options.filters).filter('.activeEl').each(onEach);
return filter;
},
MakeOrder: function (data) {
var item = data.item,
localOrder = '',
type = item.data('type'),
dir = '?';
if (type == 'select') {
} else if (type == 'select-data') {
} else if (type == 'input') {
} else if (type == 'data') {
localOrder = item.data('name');
}
if (localOrder) {
if (item.hasClass('sortAsc')) {
dir = ''
} else if (item.hasClass('sortDesc')) {
dir = '-'
}
if (dir == '?') {
localOrder = dir;
} else {
localOrder = dir + localOrder;
}
}
return localOrder;
},
CreateOrders: function (element) {
var order = [];
var onEach = function (index, item) {
var localOrder = methods.MakeOrder({item: jQuery(item)});
if (localOrder) {
order.push(localOrder);
}
};
element.find(options.orders).filter('.activeEl').each(onEach);
return order;
},
GetNext: function (element, data) {
var itemsPerPage = methods.GetItemsPerPage(element, null),
offset = methods.GetOffset(element);
methods.RequestItems(element, {addParams: {offset: offset, per_page: itemsPerPage}}); //limit - items per page
},
GetItemsPerPage: function (element) {
return element.data('per-page');
},
GetOffset: function (element) {
return element.data('offset');
},
SetOffset: function (element, offset) {
element.data('offset', offset);
return offset;
},
FillList: function (element, data) {
var list = jQuery(data.list).hide();
element.find(options.elements.contentContainer).html(list);
list.fadeIn();
},
AppendList: function (element, data) {
var list = jQuery(data.list).hide();
element.find(options.elements.contentContainer).append(list);
list.fadeIn();
}
};
defaults = defaults || {};
methods.Init(element);
return element;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.